{
  "canonical_name": "BrettNye/stoa",
  "compilation_id": "pack_1c2bca0fb8474ab3b065a4c1c1f75c0c",
  "created_at": "2026-05-19T06:28:35.761118+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 `npm i -g @stoa-mcp/cli` 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": "npm i -g @stoa-mcp/cli",
      "sandbox_container_image": "node:22-slim",
      "sandbox_execution_backend": "docker",
      "sandbox_planner_decision": "deterministic_isolated_install",
      "sandbox_validation_id": "sbx_9df9c94e383d498885b8f47aad4919c9"
    },
    "feedback_event_type": "project_pack_compilation_feedback",
    "learning_candidate_reasons": [],
    "template_gaps": []
  },
  "identity": {
    "canonical_id": "project_c7c903fcacde9176328e27721533e764",
    "canonical_name": "BrettNye/stoa",
    "homepage_url": null,
    "license": "unknown",
    "repo_url": "https://github.com/BrettNye/stoa",
    "slug": "stoa",
    "source_packet_id": "phit_654a6c2a8b454d8aac3cf50908f376cb",
    "source_validation_id": "dval_413b9b2eea374cd085b8ac7ceb0dd907"
  },
  "merchandising": {
    "best_for": "需要软件开发与交付能力，并使用 mcp_host的用户",
    "github_forks": 0,
    "github_stars": 0,
    "one_liner_en": "Persistent shared memory for AI coding agents (MCP server + CLI)",
    "one_liner_zh": "Persistent shared memory for AI coding agents (MCP server + CLI)",
    "primary_category": {
      "category_id": "software-development",
      "confidence": "high",
      "name_en": "Software Development",
      "name_zh": "软件开发与交付",
      "reason": "matched_keywords:code, coding, git"
    },
    "target_user": "使用 mcp_host, claude, claude_code 等宿主 AI 的用户",
    "title_en": "stoa",
    "title_zh": "stoa 能力包",
    "visible_tags": [
      {
        "label_en": "Browser Agents",
        "label_zh": "浏览器 Agent",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "product_domain-browser-agents",
        "type": "product_domain"
      },
      {
        "label_en": "Web Task Automation",
        "label_zh": "网页任务自动化",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "user_job-web-task-automation",
        "type": "user_job"
      },
      {
        "label_en": "Structured Data Extraction",
        "label_zh": "结构化数据提取",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "core_capability-structured-data-extraction",
        "type": "core_capability"
      },
      {
        "label_en": "Page Observation and Action Planning",
        "label_zh": "页面观察与动作规划",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "workflow_pattern-page-observation-and-action-planning",
        "type": "workflow_pattern"
      },
      {
        "label_en": "Open Source Tool",
        "label_zh": "开源工具",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "selection_signal-open-source-tool",
        "type": "selection_signal"
      }
    ]
  },
  "packet_id": "phit_654a6c2a8b454d8aac3cf50908f376cb",
  "page_model": {
    "artifacts": {
      "artifact_slug": "stoa",
      "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": "npm i -g @stoa-mcp/cli",
          "label": "Node.js / npm · 官方安装入口",
          "source": "https://github.com/BrettNye/stoa#readme",
          "verified": true
        }
      ],
      "display_tags": [
        "浏览器 Agent",
        "网页任务自动化",
        "结构化数据提取",
        "页面观察与动作规划",
        "开源工具"
      ],
      "eyebrow": "软件开发与交付",
      "glance": [
        {
          "body": "判断自己是不是目标用户。",
          "label": "最适合谁",
          "value": "需要软件开发与交付能力，并使用 mcp_host的用户"
        },
        {
          "body": "先理解能力边界，再决定是否继续。",
          "label": "核心价值",
          "value": "Persistent shared memory for AI coding agents (MCP server + CLI)"
        },
        {
          "body": "未完成验证前保持审慎。",
          "label": "继续前",
          "value": "publish to Doramagic.ai project surfaces"
        }
      ],
      "guardrail_source": "Boundary & Risk Card",
      "guardrails": [
        {
          "body": "Prompt Preview 只展示流程，不证明项目已安装或运行。",
          "label": "Check 1",
          "value": "不要把试用当真实运行"
        },
        {
          "body": "mcp_host, claude, claude_code",
          "label": "Check 2",
          "value": "确认宿主兼容"
        },
        {
          "body": "publish to Doramagic.ai project surfaces",
          "label": "Check 3",
          "value": "先隔离验证"
        }
      ],
      "mode": "mcp_config, recipe, host_instruction, eval, preflight",
      "pitfall_log": {
        "items": [
          {
            "body": "项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。",
            "category": "配置坑",
            "evidence": [
              "capability.host_targets | github_repo:1229401738 | https://github.com/BrettNye/stoa | host_targets=mcp_host, claude, claude_code"
            ],
            "severity": "medium",
            "suggested_check": "列出会写入的配置文件、目录和卸载/回滚步骤。",
            "title": "可能修改宿主 AI 配置",
            "user_impact": "安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。"
          },
          {
            "body": "README/documentation is current enough for a first validation pass.",
            "category": "能力坑",
            "evidence": [
              "capability.assumptions | github_repo:1229401738 | https://github.com/BrettNye/stoa | README/documentation is current enough for a first validation pass."
            ],
            "severity": "medium",
            "suggested_check": "将假设转成下游验证清单。",
            "title": "能力判断依赖假设",
            "user_impact": "假设不成立时，用户拿不到承诺的能力。"
          },
          {
            "body": "未记录 last_activity_observed。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:1229401738 | https://github.com/BrettNye/stoa | 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:1229401738 | https://github.com/BrettNye/stoa | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "进入安全/权限治理复核队列。",
            "title": "下游验证发现风险项",
            "user_impact": "下游已经要求复核，不能在页面中弱化。"
          },
          {
            "body": "no_demo",
            "category": "安全/权限坑",
            "evidence": [
              "risks.scoring_risks | github_repo:1229401738 | https://github.com/BrettNye/stoa | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "把风险写入边界卡，并确认是否需要人工复核。",
            "title": "存在评分风险",
            "user_impact": "风险会影响是否适合普通用户安装。"
          },
          {
            "body": "issue_or_pr_quality=unknown。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:1229401738 | https://github.com/BrettNye/stoa | 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:1229401738 | https://github.com/BrettNye/stoa | release_recency=unknown"
            ],
            "severity": "low",
            "suggested_check": "确认最近 release/tag 和 README 安装命令是否一致。",
            "title": "发布节奏不明确",
            "user_impact": "安装命令和文档可能落后于代码，用户踩坑概率升高。"
          }
        ],
        "source": "ProjectPitfallLog + ProjectHitPacket + validation + community signals",
        "summary": "发现 7 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：配置坑 - 可能修改宿主 AI 配置。",
        "title": "踩坑日志"
      },
      "snapshot": {
        "contributors": 1,
        "forks": 0,
        "license": "unknown",
        "note": "站点快照，非实时质量证明；用于开工前背景判断。",
        "stars": 0
      },
      "source_url": "https://github.com/BrettNye/stoa",
      "steps": [
        {
          "body": "不安装项目，先体验能力节奏。",
          "code": "preview",
          "title": "先试 Prompt"
        },
        {
          "body": "理解输入、输出、失败模式和边界。",
          "code": "manual",
          "title": "读说明书"
        },
        {
          "body": "把上下文交给宿主 AI 继续工作。",
          "code": "context",
          "title": "带给 AI"
        },
        {
          "body": "进入主力环境前先完成安装入口与风险边界验证。",
          "code": "verify",
          "title": "沙箱验证"
        }
      ],
      "subtitle": "Persistent shared memory for AI coding agents (MCP server + CLI)",
      "title": "stoa 能力包",
      "trial_prompt": "# stoa - 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 BrettNye/stoa.\n\nProject:\n- Name: stoa\n- Repository: https://github.com/BrettNye/stoa\n- Summary: Persistent shared memory for AI coding agents (MCP server + CLI)\n- Host target: mcp_host, claude, claude_code\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: Persistent shared memory for AI coding agents (MCP server + CLI)\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: Persistent shared memory for AI coding agents (MCP server + CLI)\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 Stoa. Produce one small intermediate artifact and wait for confirmation.\n2. concepts-vocabulary: Core Concepts and Vocabulary. Produce one small intermediate artifact and wait for confirmation.\n3. architecture-design: Architecture and Design. Produce one small intermediate artifact and wait for confirmation.\n4. profiles-evolution: Agent Profiles and Evolution. Produce one small intermediate artifact and wait for confirmation.\n5. task-workflow: Task Workflow System. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/BrettNye/stoa\n- https://github.com/BrettNye/stoa#readme\n- README.md\n- src/core/profiles.ts\n- src/core/pokemon.ts\n- src/core/tasks.ts\n- src/core/channel.ts\n- src/tools/index.ts\n- src/cli/index.ts\n- src/core/index.ts\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": "当前没有项目级社区来源；不会把未抓取讨论包装成社会证明。",
          "items": [],
          "status": "待发现 Agent 补证",
          "title": "社区讨论"
        }
      ]
    },
    "homepage_card": {
      "category": "软件开发与交付",
      "desc": "Persistent shared memory for AI coding agents (MCP server + CLI)",
      "effort": "安装已验证",
      "forks": 0,
      "icon": "code",
      "name": "stoa 能力包",
      "risk": "需复核",
      "slug": "stoa",
      "stars": 0,
      "tags": [
        "浏览器 Agent",
        "网页任务自动化",
        "结构化数据提取",
        "页面观察与动作规划",
        "开源工具"
      ],
      "thumb": "gray",
      "type": "MCP 配置"
    },
    "manual": {
      "markdown": "# https://github.com/BrettNye/stoa 项目说明书\n\n生成时间：2026-05-16 00:38:52 UTC\n\n## 目录\n\n- [Introduction to Stoa](#introduction)\n- [Core Concepts and Vocabulary](#concepts-vocabulary)\n- [Architecture and Design](#architecture-design)\n- [Event Bus System](#event-bus-system)\n- [Agent Profiles and Evolution](#profiles-evolution)\n- [Task Workflow System](#task-workflow)\n- [Channels and Claims](#channels-claims)\n- [Runtime Adapters](#runtime-adapters)\n- [Sync Agents and Skills](#sync-agents-skills)\n- [Tool Categories Reference](#tool-categories)\n\n<a id='introduction'></a>\n\n## Introduction to Stoa\n\n### 相关页面\n\n相关主题：[Core Concepts and Vocabulary](#concepts-vocabulary), [Architecture and Design](#architecture-design)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/BrettNye/stoa/blob/main/README.md)\n- [src/core/profiles.ts](https://github.com/BrettNye/stoa/blob/main/src/core/profiles.ts)\n- [src/core/pokemon.ts](https://github.com/BrettNye/stoa/blob/main/src/core/pokemon.ts)\n- [src/core/synthesize.ts](https://github.com/BrettNye/stoa/blob/main/src/core/synthesize.ts)\n- [src/core/index.ts](https://github.com/BrettNye/stoa/blob/main/src/core/index.ts)\n- [src/core/wikilinks.ts](https://github.com/BrettNye/stoa/blob/main/src/core/wikilinks.ts)\n- [src/core/pages.ts](https://github.com/BrettNye/stoa/blob/main/src/core/pages.ts)\n- [src/core/pokeapi.ts](https://github.com/BrettNye/stoa/blob/main/src/core/pokeapi.ts)\n</details>\n\n# Introduction to Stoa\n\nStoa is a vault-based knowledge management system powered by MCP (Model Context Protocol). It provides a structured wiki infrastructure for organizing, synthesizing, and retrieving information across multiple knowledge domains. The system combines a file-based vault architecture with intelligent tooling for content discovery, cross-referencing, and collaborative agent workflows.\n\n## Overview\n\nStoa operates as an MCP server that manages a hierarchical vault of wiki pages. The vault structure organizes content into wikis, each containing typed pages (concepts, guides, decisions, journals, etc.) with frontmatter metadata and markdown body content.\n\nThe system provides:\n\n- **File-based storage**: All content stored as markdown files with YAML frontmatter\n- **MCP tooling**: Standardized tools for read, write, search, and coordination operations\n- **Multi-wiki support**: Independent wiki spaces with cross-wiki linking via wikilinks\n- **Agent profiles**: Named agent identities with associated skills and capabilities\n- **Synthesis engine**: Automated compilation of related pages into synthesized summaries\n\n## Architecture\n\n### Core Components\n\n```mermaid\ngraph TD\n    subgraph \"Transport Layer\"\n        STDIO[Stdio Transport]\n        HTTP[HTTP Transport]\n    end\n    \n    subgraph \"Core Engine\"\n        IDX[Index Engine]\n        SYN[Synthesis Engine]\n        WL[Wikilink Parser]\n        FM[Frontmatter Handler]\n    end\n    \n    subgraph \"Tools\"\n        RECALL[Recall - Search]\n        INBOX[Inbox - Capture]\n        NEW[New - Create]\n        SYNTH[Synthesize]\n        CLAIM[Claims]\n        TASKS[Tasks]\n    end\n    \n    subgraph \"Platform Integration\"\n        POKEAPI[PokeAPI Client]\n        STADIUM[Stadium Platform]\n        SKILLS[Skills Platform]\n    end\n    \n    STDIO --> SERVER[MCP Server]\n    HTTP --> SERVER\n    SERVER --> TOOLS[Tools Registry]\n    TOOLS --> CORE[Core Engine]\n    CORE --> IDX\n    CORE --> SYN\n    CORE --> WL\n    CORE --> FM\n    TOOLS --> PLATFORM[Platform APIs]\n```\n\n### Page Types\n\nThe system supports multiple page types with distinct conventions:\n\n| Type | Filename Pattern | Description |\n|------|------------------|-------------|\n| `concept` | `concept-<slug>.md` | Knowledge concepts and definitions |\n| `guide` | `guide-<slug>.md` | Procedural how-to documentation |\n| `decision` | `decision-YYYY-MM-DD-<slug>.md` | Decision records with date prefix |\n| `journal` | `journal-YYYY-MM-DD-HHMM-<slug>.md` | Time-stamped reflection entries |\n| `move` | `move-<slug>/SKILL.md` | Directory-based skill/move definitions |\n| `map` | `map.md` | Fixed filename for wiki maps |\n| `profile` | `profile-<slug>.md` | Agent profiles |\n| `synthesis` | `synthesis-<slug>.md` | Compiled summaries of related pages |\n\n资料来源：[src/core/ids.ts:25-35]()\n\n### Vault Structure\n\n```mermaid\ngraph TD\n    VAULT[Vault Root]\n    WIKIS[wikis/]\n    META[_meta/]\n    INDEX[_index/]\n    AGENTS[wikis/_agents/]\n    \n    VAULT --> WIKIS\n    VAULT --> META\n    VAULT --> INDEX\n    VAULT --> AGENTS\n    \n    WIKIS --> WIKI1[alpha/]\n    WIKIS --> WIKI2[beta/]\n    \n    WIKI1 --> TYPES1[concepts/ guides/ decisions/]\n    WIKI2 --> TYPES2[concepts/ guides/ synthesis/]\n    \n    AGENTS --> PROFILES[profiles/]\n    AGENTS --> MOVES[moves/]\n    AGENTS --> JOURNALS[journal/]\n```\n\n## Key Features\n\n### Recall (Search)\n\nThe `vault.recall` tool provides full-text search across the vault using an inverted token index. Search results are filtered by topic, wiki, layer (knowledge vs execution), and other metadata criteria.\n\nThe indexing process:\n1. Tokenizes page content using a Porter stemmer\n2. Filters stop words (the, and, of, a, an, in, to, is, etc.)\n3. Builds inverted index mapping tokens to page IDs\n4. Supports frontmatter fields in search scope\n\n```typescript\n// Tokenization logic from index.ts\nconst UPSERT_STOP_WORDS = new Set([\n  \"the\",\"and\",\"of\",\"a\",\"an\",\"in\",\"to\",\"is\",\"for\",\"on\",\"with\",\"as\",\"at\",\"by\",\"or\",\"be\",\n  \"this\",\"that\",\"it\",\"from\",\"are\",\"was\",\"were\",\"not\",\"but\",\"if\"\n]);\n\nfunction upsertTokenize(text: string): string[] {\n  return text.toLowerCase()\n    .replace(/[^a-z0-9\\s]/g, \" \")\n    .split(/\\s+/)\n    .filter(t => t.length > 1 && !UPSERT_STOP_WORDS.has(t))\n    .map(t => upsertStemmer.stem(t));\n}\n```\n\n资料来源：[src/core/index.ts:45-52]()\n\n### Synthesis Engine\n\nThe synthesis feature compiles related pages into structured summaries. The engine:\n\n1. Discovers input pages by topic recall or explicit agent memory\n2. Generates frontmatter with metadata, sources, and tags\n3. Creates marker-bounded content regions for idempotent re-rendering\n4. Supports per-agent memory synthesis scoped to `wikis/_agents`\n\n```mermaid\ngraph LR\n    INPUT[Input Pages] --> RECALL[Recall Query]\n    RECALL --> FILTER[Filter by Topic/Wiki/Agent]\n    FILTER --> BUILD[Build Synthesis Frontmatter]\n    BUILD --> RENDER[Render Marker-Bounded Content]\n    RENDER --> OUTPUT[Synthesis Page]\n```\n\nThe synthesis frontmatter includes:\n\n| Field | Description |\n|-------|-------------|\n| `id` | Unique synthesis identifier |\n| `title` | Synthesis title with topic/agent context |\n| `type` | Always \"synthesis\" |\n| `wiki` | Target wiki namespace |\n| `status` | Draft status |\n| `sources` | Array of wikilinks to contributing pages |\n| `last_compiled` | ISO date of last synthesis refresh |\n\n资料来源：[src/core/synthesize.ts:1-85]()\n\n### Wikilink System\n\nStoa uses vault-root absolute wikilinks for cross-page references:\n\n```\n[[wikis/<wiki>/<type>/<id>(|alias)]]\n```\n\nThe wikilink parser:\n- Extracts links from page bodies and frontmatter `related:` arrays\n- Skips links inside fenced code blocks\n- Silently skips malformed links\n- Preserves inline code spans\n\n```typescript\nexport interface WikilinkRef {\n  raw: string;\n  wiki: string;\n  type: string;\n  id: string;\n  alias?: string;\n  source: \"body\" | \"frontmatter\";\n}\n```\n\n资料来源：[src/core/wikilinks.ts:1-30]()\n\n### Profile System\n\nAgent profiles define identities within the system. Each profile:\n\n- Has a unique `profile-<slug>` ID\n- Stores species/pokemon data via frontmatter\n- Links to skills/moves in `wikis/_agents/moves/`\n- Can be registered with the Stadium platform\n\n```mermaid\ngraph TD\n    PROFILE[Profile Page] --> FRONTMATTER[Frontmatter]\n    PROFILE --> BODY[Body Content]\n    \n    FRONTMATTER --> SPECIES[pokemon: species_name]\n    FRONTMATTER --> TYPE[pokemon_type: type]\n    FRONTMATTER --> SPECIALTY[dev_specialty: specialty]\n    FRONTMATTER --> STAGE[evolution_stage: basic|stage1|stage2]\n    \n    PROFILE --> REGISTER[Profile Register Tool]\n    REGISTER --> STADIUM[Stadium Platform API]\n```\n\n资料来源：[src/core/profiles.ts:1-30]()\n\n### PokeAPI Integration\n\nThe system integrates with the PokeAPI to enrich agent profiles with game-related data:\n\n| Function | Purpose |\n|----------|---------|\n| `fetchSpecies()` | Get legendary/mythical/baby flags and evolution data |\n| `fetchPokemonSpecies()` | Full species data with evolution chain |\n| `filterByEvolutionStage()` | Filter candidates by basic/stage1/stage2 |\n\nData is cached locally to minimize API calls.\n\n资料来源：[src/core/pokeapi.ts:1-80]()\n\n### Page Operations\n\n```mermaid\ngraph TD\n    READ[readPage] --> PARSE[Parse Frontmatter + Body]\n    READ --> VALIDATE[Validate Page Type]\n    \n    WRITE[writePage] --> PATH[Resolve Path for Type]\n    WRITE --> MERGE[Merge Frontmatter]\n    WRITE --> SERIALIZE[Serialize to Markdown]\n    \n    UPSERT[upsertPage] --> CONDITIONAL[Read then Write]\n    UPSERT --> REINDEX[Update Token Index]\n```\n\nThe `WritePageInput` interface:\n\n```typescript\nexport interface WritePageInput {\n  id: string;\n  type: NoteType;\n  wiki: string;\n  frontmatter: Record<string, any>;\n  body: string;\n  expectedUpdated?: string;  // Optimistic locking\n}\n```\n\n资料来源：[src/core/pages.ts:40-70]()\n\n## Tools Reference\n\n### Read Tools\n\n| Tool | Description |\n|------|-------------|\n| `vault.recall` | Full-text search across vault |\n| `vault.inbox-list` | List captured thoughts |\n| `vault.page-read` | Read specific page by ID |\n| `vault.channel-tail` | Pull recent channel entries |\n\n### Write Tools\n\n| Tool | Description |\n|------|-------------|\n| `vault.inbox` | Capture fleeting thoughts |\n| `vault.new` | Create typed page from template |\n| `vault.new-wiki` | Scaffold new wiki space |\n| `vault.synthesize` | Compile synthesis from matching pages |\n| `vault.set-active` | Set ambient active wiki |\n| `vault.agent-journal` | Append agent reflection |\n| `vault.reindex` | Regenerate index files |\n\n### Coordination Tools\n\n| Tool | Description |\n|------|-------------|\n| `vault.channel-post` | Post to coordination channel |\n| `vault.task-*` | Task lifecycle (create, list, claim, update) |\n| `vault.claims-*` | Claims management (submit, list, retract, reject) |\n\n### Platform Tools\n\n| Tool | Description |\n|------|-------------|\n| `vault.profile-register` | Register profile with Stadium platform |\n| `vault.sync-skills` | Deploy agent moveset as local skills |\n| `vault.bootstrap-repo` | Wire consuming repo with MCP config |\n\n### Wait Primitives\n\n| Tool | Description |\n|------|-------------|\n| `vault.wait-for` | Block until matching event |\n| `vault.wait-for-any` | Wake on first match (race) |\n| `vault.wait-for-all` | Wake when all filters matched |\n| `vault.wait-for-many` | Bounded batch over window |\n\n资料来源：[README.md:1-60]()\n\n## CLI Usage\n\n```bash\n# Set vault path environment variable\nexport STOA_VAULT_PATH=/path/to/vault\n\n# Recall search\nstoa recall \"topic query\"\n\n# Capture a thought\nstoa inbox \"thought to capture\"\n\n# List wikis\nstoa list-wikis\n\n# With explicit vault path\nstoa --vault=/path/to/vault recall \"search terms\"\n```\n\n## Configuration\n\n### Wiki Parameter Resolution\n\nThe `wiki:` parameter resolves in this order:\n\n1. Explicit `wiki:` argument on tool call\n2. `--default-wiki=<name>` server flag\n3. `.active-wiki` file at vault root\n4. Error if none found\n\n### Server Configuration\n\n```bash\nstoa --vault=/path/to/vault \\\n     --default-wiki=alpha \\\n     --default-family=my-family\n```\n\n## Related Documentation\n\n- [Installation Guide](docs/installation.md) — Full setup and configuration walkthrough\n- [Manual Smoke Test](docs/manual-smoke-test.md) — Verify your installation\n- [Wait-For Primitives](docs/wait-for.md) — Push primitives documentation\n\n## License\n\nFSL-1 (Functional Source License)\n\n---\n\n<a id='concepts-vocabulary'></a>\n\n## Core Concepts and Vocabulary\n\n### 相关页面\n\n相关主题：[Introduction to Stoa](#introduction), [Agent Profiles and Evolution](#profiles-evolution)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/core/index.ts](https://github.com/BrettNye/stoa/blob/main/src/core/index.ts)\n- [src/core/wikilinks.ts](https://github.com/BrettNye/stoa/blob/main/src/core/wikilinks.ts)\n- [src/core/pages.ts](https://github.com/BrettNye/stoa/blob/main/src/core/pages.ts)\n- [src/core/ids.ts](https://github.com/BrettNye/stoa/blob/main/src/core/ids.ts)\n- [src/core/synthesize.ts](https://github.com/BrettNye/stoa/blob/main/src/core/synthesize.ts)\n- [src/core/syntheses.ts](https://github.com/BrettNye/stoa/blob/main/src/core/syntheses.ts)\n- [src/core/family.ts](https://github.com/BrettNye/stoa/blob/main/src/core/family.ts)\n- [src/core/eventbus/state-cache.ts](https://github.com/BrettNye/stoa/blob/main/src/core/eventbus/state-cache.ts)\n</details>\n\n# Core Concepts and Vocabulary\n\nThis document provides a comprehensive reference for the fundamental concepts, data structures, and terminology used throughout the stoa vault management system. Understanding these core concepts is essential for working effectively with the vault infrastructure, creating and managing pages, and integrating with the MCP (Model Context Protocol) server.\n\n## Vault Structure\n\nThe stoa system operates on a directory-based vault architecture where all content is organized within a hierarchical folder structure. The vault serves as the single source of truth for all wiki pages, profiles, agents, and metadata.\n\n### Vault Root Organization\n\n```\n<vault-path>/\n├── wikis/\n│   ├── <wiki-name>/\n│   │   ├── index.md\n│   │   ├── map.md\n│   │   ├── <type>-<slug>.md\n│   │   ├── profiles/\n│   │   ├── synthesis/\n│   │   └── ...\n│   └── _agents/\n│       ├── synthesis/\n│       └── journal/\n├── _index/\n│   ├── pages.json\n│   ├── tokens.json\n│   ├── links.json\n│   ├── wikis.json\n│   └── profiles.json\n├── .active-wiki\n└── .active-family\n```\n\n资料来源：[src/core/index.ts:1-50]()\n\n### Wiki Hierarchy\n\nWikis are the primary organizational unit within the vault. Each wiki contains typed pages organized by content type. The system supports multiple wikis per vault, with each wiki potentially belonging to a family for grouped operations.\n\n```mermaid\ngraph TD\n    A[Vault Root] --> B[wikis/]\n    B --> C[<wiki-name>]\n    B --> D[_agents]\n    B --> E[_meta]\n    C --> F[concepts/]\n    C --> G[decisions/]\n    C --> H[guides/]\n    C --> I[profiles/]\n    C --> J[synthesis/]\n    C --> K[inbox/]\n```\n\n资料来源：[src/core/family.ts:1-30]()\n\n## Page System\n\n### Page Types\n\nPages in stoa are distinguished by their `type` field in frontmatter. The type determines the file naming convention, storage location, and how the page is processed by various tools.\n\n| Type | Filename Pattern | Description |\n|------|------------------|-------------|\n| `concept` | `concept-<slug>.md` | Knowledge concepts and definitions |\n| `decision` | `decision-YYYY-MM-DD-<slug>.md` | Decision records with date prefix |\n| `guide` | `guide-<slug>.md` | Procedural guides |\n| `source` | `source-<slug>.md` | External citations and references |\n| `idea` | `idea-<slug>.md` | Ideas and brainstorms |\n| `question` | `question-<slug>.md` | Questions for investigation |\n| `profile` | `profile-<slug>.md` | Agent or entity profiles |\n| `synthesis` | `synthesis-<slug>.md` | Compiled synthesis pages |\n| `journal` | `journal-YYYY-MM-DD-HHMM-<slug>.md` | Agent journal entries |\n| `move` | `move-<slug>/SKILL.md` | Skills/moves (directory layout) |\n| `map` | `map.md` | Wiki map page (fixed filename) |\n\n资料来源：[src/core/ids.ts:1-50]()\n\n### Page Data Model\n\nEvery page in the vault has a consistent structure combining YAML frontmatter with markdown body content.\n\n```typescript\ninterface IndexedPage {\n  id: string;           // Unique page identifier\n  path: string;         // Relative path from vault root\n  wiki: string;         // Wiki name containing this page\n  type: NoteType;       // Page type discriminator\n  title?: string;       // Human-readable title\n  tags?: string[];      // Categorization tags\n  status?: string;      // Lifecycle status (draft, published, etc.)\n  created?: string;     // ISO 8601 creation date\n  updated?: string;     // ISO 8601 last modified date\n  summary?: string;     // Brief description\n  layer?: string;       // knowledge | execution classification\n  sources?: string[];   // Referenced wikilinks\n}\n```\n\n资料来源：[src/core/pages.ts:1-40]()\n\n### Wikilink Format\n\nThe system uses a structured wikilink syntax for cross-referencing pages within the vault.\n\n```markdown\n[[wikis/<wiki>/<type>/<id>(|alias)]]\n```\n\n**Components:**\n- `wikis/` — Literal prefix indicating a vault-root absolute link\n- `<wiki>` — Target wiki name (e.g., `alpha`, `_agents`)\n- `<type>` — Page type folder (e.g., `concept`, `decision`, `profile`)\n- `<id>` — Page identifier\n- `|alias` — Optional display alias\n\n**Examples:**\n```markdown\n[[wikis/alpha/concept/trust-gradient-axes]]\n[[wikis/_agents/profile/pikachu-agent|My Agent]]\n```\n\n资料来源：[src/core/wikilinks.ts:1-60]()\n\n## Indexing System\n\n### Token-Based Search\n\nThe index system uses a custom tokenization pipeline for full-text search across all vault pages.\n\n```typescript\nfunction upsertTokenize(text: string): string[] {\n  return text.toLowerCase()\n    .replace(/[^a-z0-9\\s]/g, \" \")\n    .split(/\\s+/)\n    .filter(t => t.length > 1 && !UPSERT_STOP_WORDS.has(t))\n    .map(t => upsertStemmer.stem(t));  // Porter stemming\n}\n```\n\n**Tokenization Pipeline:**\n1. Lowercase normalization\n2. Strip non-alphanumeric characters\n3. Split on whitespace\n4. Filter stop words and single characters\n5. Apply Porter stemmer\n\n**Stop Words:** `the`, `and`, `of`, `a`, `an`, `in`, `to`, `is`, `for`, `on`, `with`, `as`, `at`, `by`, `or`, `be`, `this`, `that`, `it`, `from`, `are`, `was`, `were`, `not`, `but`, `if`\n\n资料来源：[src/core/index.ts:40-55]()\n\n### Index Files\n\nThe `_index/` directory contains aggregated metadata for efficient querying:\n\n| File | Purpose |\n|------|---------|\n| `pages.json` | Full page metadata with frontmatter |\n| `tokens.json` | Search tokens mapped to page IDs |\n| `links.json` | Inter-page references (wikilinks) |\n| `wikis.json` | Wiki registry and metadata |\n| `profiles.json` | Profile-specific metadata |\n\n资料来源：[src/core/index.ts:55-70]()\n\n### Layer Classification\n\nPages are classified into layers for filtering and organization:\n\n```typescript\nconst KNOWLEDGE_TYPES = [\"concept\", \"decision\", \"spec\", \"source\"];\nconst EXECUTION_TYPES = [\"guide\", \"idea\", \"question\"];\n```\n\n- **Knowledge Layer** — Factual, distillable content (concepts, decisions, specs, sources)\n- **Execution Layer** — Procedural and exploratory content (guides, ideas, questions)\n\n资料来源：[src/core/index.ts:20-30]()\n\n## Synthesis System\n\n### Synthesis Pages\n\nSynthesis pages compile multiple related pages into a cohesive document. They serve as \"second-order\" content that distills information from source pages.\n\n```typescript\ninterface SynthesisPage extends IndexedPage {\n  type: \"synthesis\";\n  topic: string;           // Synthesis subject\n  sources: string[];       // Wikilinks to contributing pages\n  last_compiled: string;   // ISO date of last regeneration\n  scope?: \"memory\";        // Agent memory synthesis flag\n  by_agent?: string;       // Agent identifier for memory syntheses\n}\n```\n\n资料来源：[src/core/synthesize.ts:1-50]()\n\n### Synthesis Generation\n\n```mermaid\ngraph TD\n    A[Synthesize Request] --> B{scope?}\n    B -->|memory| C[Collect Agent Pages]\n    B -->|topic| D[Recall Matching Pages]\n    C --> E[Filter by Author]\n    D --> E\n    E --> F[Build Frontmatter]\n    F --> G[Generate Synthesis File]\n    G --> H[Upsert to Index]\n```\n\n资料来源：[src/core/synthesize.ts:50-120]()\n\n### Synthesis Debt Detection\n\nThe lint system identifies clusters of related hard-knowledge pages that lack corresponding synthesis pages.\n\n**Debt Rule:**\n- Clusters pages by shared tags\n- Flags clusters with ≥3 pages that have no synthesis\n- Suggests `vault.synthesize` command with derived title\n\n**Hard-Knowledge Types:** `concept`, `decision`, `spec`\n\n资料来源：[src/core/lint-checks/synthesis-debt.ts:1-50]()\n\n### Synthesis Staleness\n\nThe system tracks how long synthesis pages have gone without recompilation:\n\n```typescript\ninterface SynthesisStaleness {\n  id: string;\n  lag_days: number | null;  // null if never compiled\n  last_compiled: string | null;\n  topic: string;\n}\n```\n\n资料来源：[src/core/syntheses.ts:1-50]()\n\n## Wiki Resolution\n\n### Family Resolution Order\n\nWhen determining the active family context, the system follows this precedence:\n\n1. `familyArg` — Explicit parameter passed to the function\n2. `defaultFamily` — Configured default (via `--default-family` CLI arg)\n3. `.active-family` file at vault root\n4. `null` — Falls through to single-wiki resolution\n\n资料来源：[src/core/family.ts:15-40]()\n\n### Wiki Resolution Order\n\nWiki parameter resolution follows this order:\n\n1. Explicit `wiki:` argument on tool call\n2. `--default-wiki=<name>` flag on server invocation\n3. `.active-wiki` file at vault root\n4. Error if no wiki can be determined\n\n资料来源：[README.md:1-30]()\n\n### Family-Wiki Validation\n\nWhen both `familyArg` and `wikiArg` are provided with `knownWikis`, the system validates consistency:\n\n```typescript\nif (knownWikis[wikiArg].family !== familyArg) {\n  throw new FamilyMismatchError(...);\n}\n```\n\n资料来源：[src/core/family.ts:25-35]()\n\n## Event Bus and State Cache\n\n### StateCache\n\nThe StateCache provides an in-memory cache for tracking page states across event sources.\n\n```typescript\nclass StateCache {\n  private states = new Map<string, unknown>();\n  \n  private key(source: string, wiki: string, id: string): string {\n    return `${source}:${wiki}:${id}`;\n  }\n  \n  get<T>(source: string, wiki: string, id: string): T | undefined;\n  set<T>(source: string, wiki: string, id: string, state: T): void;\n  has(source: string, wiki: string, id: string): boolean;\n  size(): number;\n}\n```\n\n**Key Format:** `source:wiki:id`\n\n资料来源：[src/core/eventbus/state-cache.ts:1-35]()\n\n### Cache Initialization\n\nThe system pre-warms the cache by walking the `wikis/` directory before accepting live events, ensuring the first change event has valid prior state for diffing.\n\n```typescript\nfunction walkInitablePaths(vaultPath: string): string[] {\n  // Recursively find all .md files in wikis/\n  // Returns paths where 'init' is defined for state tracking\n}\n```\n\n资料来源：[src/transport/stdio.ts:40-70]()\n\n## Frontmatter Schema\n\n### Standard Frontmatter Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `id` | string | Unique page identifier |\n| `title` | string | Display title |\n| `type` | string | Page type |\n| `wiki` | string | Wiki name |\n| `status` | string | Lifecycle status |\n| `created` | string | ISO 8601 creation date |\n| `updated` | string | ISO 8601 modification date |\n| `summary` | string | Brief description |\n| `tags` | string[] | Categorization tags |\n| `layer` | string | knowledge or execution |\n| `sources` | string[] | Wikilinks to source pages |\n\n### Profile-Specific Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `pokemon` | string | Species name |\n| `evolution_stage` | string | basic, stage1, stage2 |\n| `pokemon_type` | string | Pokémon type (if applicable) |\n| `dev_specialty` | string | Developer specialty |\n| `rarity` | string | common, baby, legendary, mythical |\n| `platform_profile_id` | string | Stadium platform ID |\n| `platform_stats` | object | Persisted platform statistics |\n\n资料来源：[src/transport/ui/routes-write.ts:1-40]()\n\n## Marker Rendering\n\nThe marker system enables tools to maintain managed regions within human-editable files.\n\n### Marker Contract\n\n- **Start Marker:** `<!-- <name>:start (rendered: <date>, half-life: <N>d) -->`\n- **End Marker:** `<!-- <name>:end -->`\n- **Idempotent:** Same inputs produce byte-identical output\n- **Independent:** Different marker names don't interfere\n\n```typescript\ninterface MarkerOptions {\n  renderedDate?: string;   // ISO date YYYY-MM-DD\n  halfLifeDays?: number;   // Half-life in days\n}\n```\n\n**Applications:**\n- `synthesize` — Claims rollup\n- `sync-skills` — Moveset synchronization\n- `bootstrap-repo` — Agent documentation patches\n\n资料来源：[src/core/marker-render.ts:1-50]()\n\n## Tool Categories\n\n### Read Primitives\n\n| Tool | Purpose |\n|------|---------|\n| `vault.recall` | Full-text search with filters |\n| `vault.page-read` | Read single page by ID |\n| `vault.channel-tail` | Pull coordination channel entries |\n| `vault.synthesis-staleness` | Check synthesis freshness |\n\n### Wait (Push Primitives)\n\n| Tool | Purpose |\n|------|---------|\n| `vault.wait-for` | Block until matching event |\n| `vault.wait-for-any` | Wake on first match across N filters |\n| `vault.wait-for-all` | Wake when all N filters matched |\n| `vault.wait-for-many` | Bounded batch over window |\n\n### Write — Content\n\n| Tool | Purpose |\n|------|---------|\n| `vault.inbox` | Capture fleeting thoughts |\n| `vault.new` | Create typed page from template |\n| `vault.new-wiki` | Scaffold new wiki structure |\n| `vault.set-active` | Set ambient active wiki |\n| `vault.synthesize` | Compile synthesis page |\n| `vault.agent-journal` | Append agent reflection |\n\n### Write — System\n\n| Tool | Purpose |\n|------|---------|\n| `vault.reindex` | Regenerate `_index/` files |\n\n### Coordination\n\n| Tool | Purpose |\n|------|---------|\n| `vault.channel-post` | Post to coordination channel |\n| `vault.task-claim` | Atomically claim pending task |\n| `vault.task-create` | Create new task |\n| `vault.task-list` | List tasks |\n| `vault.task-update` | Update task state |\n| `vault.bootstrap-repo` | Wire consuming repo with MCP config |\n| `vault.sync-skills` | Deploy agent moveset as local skills |\n\n资料来源：[README.md:30-80]()\n\n## Configuration Files\n\n### Server Configuration\n\n| Config Method | Description |\n|---------------|-------------|\n| `--vault=<path>` | Vault root directory |\n| `--default-wiki=<name>` | Default wiki for operations |\n| `--default-family=<name>` | Default family for multi-wiki ops |\n| `STOA_VAULT_PATH` | Environment variable alternative |\n\n### Active Context Files\n\n| File | Purpose |\n|------|---------|\n| `.active-wiki` | Current active wiki name |\n| `.active-family` | Current active family name |\n\n## Common Patterns\n\n### Idempotent Page Creation\n\nPages use upsert semantics — creating a page with an existing ID updates rather than duplicates:\n\n```typescript\nfunction writePage(vaultPath: string, input: WritePageInput): WritePageResult {\n  const path = pathForPage(vaultPath, input.id, input.type, input.wiki);\n  // Uses expectedUpdated for optimistic concurrency control\n}\n```\n\n资料来源：[src/core/pages.ts:40-80]()\n\n### Three-Step Alias Resolution\n\nProfile and agent references resolve through multiple resolution steps:\n\n```typescript\nfunction normalizeProfileId(vaultPath: string, raw: string): string {\n  const r1 = resolveCurrent(vaultPath, raw);\n  if (r1 !== raw) return r1;\n  const candidate = raw.startsWith(\"profile-\") ? raw : `profile-${raw}`;\n  return resolveCurrent(vaultPath, candidate);\n}\n```\n\n资料来源：[src/tools/sync-agents.ts:1-40]()\n\n### Lint Rule Pattern\n\nNew lint rules follow a consistent structure:\n\n```typescript\nexport const LINT_RULE = {\n  ruleId: \"rule-name\",\n  severity: \"warn\" | \"error\",\n  message: \"Human-readable description\",\n};\n```\n\n资料来源：[src/core/lint-checks/claim-with-no-scope.ts:1-30]()\n\n## Terminology Summary\n\n| Term | Definition |\n|------|------------|\n| **Vault** | Root directory containing all wikis and metadata |\n| **Wiki** | Organizational unit containing typed pages |\n| **Family** | Grouping of related wikis |\n| **Page** | Single markdown document with frontmatter |\n| **Type** | Page classification determining storage and behavior |\n| **Wikilink** | Cross-reference syntax `[[wikis/...]]` |\n| **Synthesis** | Compiled page aggregating multiple sources |\n| **Layer** | Knowledge vs execution classification |\n| **Marker** | HTML comment bounding managed file regions |\n| **Index** | Aggregated metadata for efficient querying |\n| **Debt** | Gap between source pages and their synthesis |\n\n---\n\n<a id='architecture-design'></a>\n\n## Architecture and Design\n\n### 相关页面\n\n相关主题：[Introduction to Stoa](#introduction), [Event Bus System](#event-bus-system)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/core/index.ts](https://github.com/BrettNye/stoa/blob/main/src/core/index.ts)\n- [src/transport/stdio.ts](https://github.com/BrettNye/stoa/blob/main/src/transport/stdio.ts)\n- [src/core/family.ts](https://github.com/BrettNye/stoa/blob/main/src/core/family.ts)\n- [src/core/skills-platform.ts](https://github.com/BrettNye/stoa/blob/main/src/core/skills-platform.ts)\n- [src/core/pages.ts](https://github.com/BrettNye/stoa/blob/main/src/core/pages.ts)\n- [src/core/frontmatter.ts](https://github.com/BrettNye/stoa/blob/main/src/core/frontmatter.ts)\n- [src/core/synthesize.ts](https://github.com/BrettNye/stoa/blob/main/src/core/synthesize.ts)\n- [src/core/wikilinks.ts](https://github.com/BrettNye/stoa/blob/main/src/core/wikilinks.ts)\n- [src/core/lint-checks/synthesis-debt.ts](https://github.com/BrettNye/stoa/blob/main/src/core/lint-checks/synthesis-debt.ts)\n- [src/core/channel.ts](https://github.com/BrettNye/stoa/blob/main/src/core/channel.ts)\n</details>\n\n# Architecture and Design\n\n## Overview\n\nStoa is an MCP (Model Context Protocol) server that provides structured access to a flat-file knowledge vault. It bridges AI agents with a wiki-based knowledge management system, enabling semantic search, cross-wiki linking, task management, and skill deployment. The architecture follows a layered design with clear separation between transport mechanisms, core domain logic, and tool interfaces.\n\n**Purpose and Scope:**\n- Expose vault operations via MCP protocol (STDIO or HTTP transports)\n- Maintain a search index for full-text and structured queries\n- Enforce wiki semantics and validation rules through lint checks\n- Support multi-wiki, multi-family deployments\n- Enable skill/move deployment workflows\n\n**资料来源：** [src/core/index.ts:1-50](https://github.com/BrettNye/stoa/blob/main/src/core/index.ts)\n\n---\n\n## High-Level Architecture\n\nThe system comprises three primary layers:\n\n1. **Transport Layer** — Handles MCP protocol communication (STDIO or HTTP)\n2. **Core Domain Layer** — Business logic, index management, linting, synthesis\n3. **Tools Layer** — Exposes MCP tools to calling agents\n\n```mermaid\ngraph TD\n    subgraph Transport[\"Transport Layer\"]\n        STDIO[STDIO Transport]\n        HTTP[HTTP Transport]\n    end\n\n    subgraph Core[\"Core Domain Layer\"]\n        INDEX[Index Management]\n        QUERY[Query Engine]\n        LINT[Lint Checks]\n        SYNTH[Synthesis Engine]\n        FAMILY[Family Resolution]\n        SKILLS[Skills Platform]\n        CACHE[State Cache]\n    end\n\n    subgraph Tools[\"Tools Layer\"]\n        RECALL[recall]\n        INBOX[inbox]\n        SYNTHESIZE[synthesize]\n        TASK[task-*]\n        CHANNEL[channel-*]\n        WAITFOR[wait-for*]\n    end\n\n    subgraph Vault[\"Flat-File Vault\"]\n        WIKIS[wikis/]\n        INDEX_VAULT[_index/]\n        ACTIVE_WIKI[.active-wiki]\n        ACTIVE_FAMILY[.active-family]\n    end\n\n    STDIO --> CORE\n    HTTP --> CORE\n    CORE --> INDEX\n    CORE --> TOOLS\n    INDEX --> VAULT\n    TOOLS --> VAULT\n```\n\n**资料来源：** [src/transport/stdio.ts:1-30](https://github.com/BrettNye/stoa/blob/main/src/transport/stdio.ts)\n\n---\n\n## Transport Layer\n\n### STDIO Transport\n\nThe STDIO transport enables integration with local MCP clients. It initializes the server state cache by walking the `wikis/` directory before processing change events.\n\nKey initialization steps:\n1. Load vault configuration\n2. Walk `wikis/` directory to warm state cache\n3. Connect STDIO server transport\n4. Log ready message with vault path and defaults\n\n```typescript\nconst transport = new StdioServerTransport();\nawait server.connect(transport);\nprocess.stderr.write(`vault-mcp stdio server ready (vault=${config.vaultPath}, default-wiki=${config.defaultWiki ?? \"<unset>\"}, default-family=${config.defaultFamily ?? \"<unset>\"})\\n`);\n```\n\n**资料来源：** [src/transport/stdio.ts:40-50](https://github.com/BrettNye/stoa/blob/main/src/transport/stdio.ts)\n\n### Transport Architecture Pattern\n\nThe transport layer is abstracted behind a common interface. Both STDIO and HTTP transports expose the same tool set, allowing clients to choose their preferred communication mechanism.\n\n| Transport | Use Case | Initialization |\n|-----------|----------|----------------|\n| STDIO | Local MCP clients, CLI tools | `StdioServerTransport` |\n| HTTP | Remote access, web clients | `HttpServerTransport` |\n\n---\n\n## Core Domain Layer\n\n### Index Management\n\nThe index is the primary data structure powering queries. It maintains:\n- **pages.json** — All page metadata (id, title, type, wiki, tags, status)\n- **tokens.json** — Tokenized text for full-text search\n- **links.json** — Wikilink references between pages\n- **wikis.json** — Wiki metadata\n- **profiles.json** — Agent profiles\n\n**资料来源：** [src/core/index.ts:60-100](https://github.com/BrettNye/stoa/blob/main/src/core/index.ts)\n\n#### Query Engine\n\nThe `queryPages` function supports filtering by:\n- `wiki` — Wiki identifier\n- `type` — Page type (concept, decision, guide, etc.)\n- `channel` — Coordination channel\n- `status` — Page status (draft, active, accepted, etc.)\n- `layer` — knowledge or execution\n\n```typescript\nexport function queryPages(idx: VaultIndex, f: PageFilter): IndexedPage[] {\n  return idx.pages.filter(p => {\n    if (f.wiki && wikiSet && !wikiSet.has(p.wiki)) return false;\n    if (f.type && p.type !== f.type) return false;\n    if (f.channel && p.channel !== f.channel) return false;\n    if (f.status && p.status !== f.status) return false;\n    if (f.layer && f.layer !== \"all\") {\n      const set = f.layer === \"knowledge\" ? KNOWLEDGE_TYPES : EXECUTION_TYPES;\n      if (!set.includes(p.type)) return false;\n    }\n    return true;\n  });\n}\n```\n\n**资料来源：** [src/core/index.ts:30-55](https://github.com/BrettNye/stoa/blob/main/src/core/index.ts)\n\n#### Tokenization and Search\n\nSearch uses Porter stemming with stop-word removal for relevance ranking.\n\n```typescript\nconst upsertStemmer = natural.PorterStemmer;\nconst UPSERT_STOP_WORDS = new Set([\"the\",\"and\",\"of\",\"a\",\"an\",\"in\",\"to\",\"is\",\"for\",\"on\",\"with\",\"as\",\"at\",\"by\",\"or\",\"be\",\"this\",\"that\",\"it\",\"from\",\"are\",\"was\",\"were\",\"not\",\"but\",\"if\"]);\n\nfunction upsertTokenize(text: string): string[] {\n  return text.toLowerCase()\n    .replace(/[^a-z0-9\\s]/g, \" \")\n    .split(/\\s+/)\n    .filter(t => t.length > 1 && !UPSERT_STOP_WORDS.has(t))\n    .map(t => upsertStemmer.stem(t));\n}\n```\n\n**资料来源：** [src/core/index.ts:35-48](https://github.com/BrettNye/stoa/blob/main/src/core/index.ts)\n\n---\n\n### Family Resolution\n\nStoa supports hierarchical organization through **families** (collections of related wikis) and **wikis** (individual knowledge bases within a family).\n\n```mermaid\ngraph TD\n    FAM[Family<br/>e.g., \"stadium\"] --> W1[Wiki: pokemon]\n    FAM --> W2[Wiki: moves]\n    FAM --> W3[Wiki: trainers]\n    \n    W1 --> P1[Pages...]\n    W2 --> P2[Pages...]\n    W3 --> P3[Pages...]\n```\n\n#### Resolution Order\n\nFamily resolution follows a priority order:\n\n| Priority | Source | CLI Flag |\n|----------|--------|----------|\n| 1 | Explicit `familyArg` | `--default-family` |\n| 2 | Context default | `ctx.defaultFamily` |\n| 3 | Vault file | `.active-family` |\n| 4 | null | — |\n\n```typescript\nexport function resolveFamily(\n  ctx: FamilyResolveCtx,\n  familyArg?: string,\n  wikiArg?: string,\n  knownWikis?: Record<string, { family?: string | null }>\n): string | null {\n  if (familyArg !== undefined && familyArg !== \"\") {\n    if (wikiArg !== undefined && knownWikis !== undefined) {\n      const wikiEntry = knownWikis[wikiArg];\n      const wikiFamily = wikiEntry?.family ?? null;\n      if (wikiFamily !== familyArg) {\n        throw new FamilyMismatchError(...);\n      }\n    }\n    return familyArg;\n  }\n  // ... fallback chain\n}\n```\n\n**资料来源：** [src/core/family.ts:1-50](https://github.com/BrettNye/stoa/blob/main/src/core/family.ts)\n\n---\n\n### Page Management\n\n#### Page Types\n\n| Type | Description | Filename Pattern |\n|------|-------------|------------------|\n| `concept` | Knowledge concept | `concept-<slug>.md` |\n| `decision` | Decision record | `decision-YYYY-MM-DD-<slug>.md` |\n| `journal` | Journal entry | `journal-YYYY-MM-DD-HHMM-<slug>.md` |\n| `guide` | Procedural guide | `guide-<slug>.md` |\n| `move` | Skill/move | `move-<slug>/SKILL.md` |\n| `map` | Wiki map | `map.md` |\n| `synthesis` | Synthesized content | Varies |\n\n**资料来源：** [src/core/ids.ts:1-40](https://github.com/BrettNye/stoa/blob/main/src/core/ids.ts)\n\n#### Write Operations\n\nPages are written with optimistic concurrency via `expectedUpdated` checks:\n\n```typescript\nexport function writePage(vaultPath: string, input: WritePageInput): WritePageResult {\n  const path = pathForPage(vaultPath, input.id, input.type, input.wiki);\n  if (existsSync(path) && input.expectedUpdated !== undefined) {\n    const existing = readFileSync(path, \"utf8\");\n    const { frontmatter: existingFm } = parseFrontmatter(existing);\n    const actualUpdated = toIsoDate(existingFm.updated ?? existingFm.created);\n    // Check for conflicts\n  }\n}\n```\n\n**资料来源：** [src/core/pages.ts:50-80](https://github.com/BrettNye/stoa/blob/main/src/core/pages.ts)\n\n---\n\n### Frontmatter Schema\n\nAll pages use YAML frontmatter with Zod validation:\n\n| Field | Type | Required | Description |\n|-------|------|----------|-------------|\n| `id` | string | Yes | Unique identifier (kebab-case) |\n| `title` | string | Yes | Display title |\n| `type` | NoteType | Yes | Page classification |\n| `created` | ISO date | Yes | Creation timestamp |\n| `channel` | string | No | Coordination channel (kebab-case) |\n| `status` | enum | No | draft, active, accepted, superseded, archived |\n| `confidence` | enum | No | high, medium, low |\n| `curation_priority` | enum | No | high, medium, low |\n| `wiki` | string | Yes | Wiki identifier |\n| `tags` | string[] | No | Taxonomy tags |\n| `last_compiled` | ISO date | No | Synthesis compilation timestamp |\n\n**资料来源：** [src/core/frontmatter.ts:1-60](https://github.com/BrettNye/stoa/blob/main/src/core/frontmatter.ts)\n\n---\n\n### Wikilink System\n\nWikilinks follow the pattern: `[[wikis/<wiki>/<type>/<id>(|alias)?]]`\n\nThe wikilink extractor:\n- Is code-fence-aware (skips links inside ``` blocks)\n- Extracts from both body content and frontmatter `related:` arrays\n- Returns structured `WikilinkRef` objects\n\n```typescript\nexport interface WikilinkRef {\n  raw: string;\n  wiki: string;\n  type: string;\n  id: string;\n  alias?: string;\n  source: \"body\" | \"frontmatter\";\n}\n```\n\n**Trade-offs:**\n- Top-level fenced blocks are stripped\n- Indented fenced blocks (e.g., inside list items) are NOT stripped\n- Inline single-backtick code spans are NOT stripped\n\n**资料来源：** [src/core/wikilinks.ts:1-50](https://github.com/BrettNye/stoa/blob/main/src/core/wikilinks.ts)\n\n---\n\n### Synthesis Engine\n\nSynthesis pages aggregate related content from hard-knowledge types (concept, decision, spec).\n\n#### Synthesis Debt Detection\n\nThe lint system identifies clusters of related pages that lack synthesis coverage:\n\n```typescript\nconst HARD_KNOWLEDGE_TYPES = new Set([\"concept\", \"decision\", \"spec\"]);\n// Excluded: guide (procedural), source (external citation), idea, question\n\nfunction findSynthesisDebt(\n  pages: IndexedPage[],\n  minSize: number = DEFAULT_MIN_CLUSTER_SIZE,\n): ClusterDebt[] {\n  // Group by (wiki, tag) → hard-knowledge ids\n  // Check if any synthesis page covers the same tag\n  // Emit debt when: cluster size >= minSize AND no synthesis exists\n}\n```\n\n**Default minimum cluster size:** 3\n\n**资料来源：** [src/core/lint-checks/synthesis-debt.ts:1-80](https://github.com/BrettNye/stoa/blob/main/src/core/lint-checks/synthesis-debt.ts)\n\n#### Synthesis Generation\n\n```typescript\nconst fm: Record<string, any> = {\n  id,\n  title: scope === \"memory\"\n    ? `${input.by_agent} memory — synthesis`\n    : `${input.topic} — synthesis`,\n  type: \"synthesis\",\n  wiki,\n  status: \"draft\",\n  sources: inputIds.map(i => `[[wikis/${wiki}/${typeFolderForId(i)}/${i}]]`)\n};\n```\n\n**资料来源：** [src/core/synthesize.ts:60-100](https://github.com/BrettNye/stoa/blob/main/src/core/synthesize.ts)\n\n---\n\n### Marker-Based Section Rendering\n\nManaged regions within files are bounded by HTML comment markers:\n\n```\n<!-- <name>:start (rendered: YYYY-MM-DD, half-life: Nd) -->\n<section-content>\n<!-- <name>:end -->\n```\n\nCharacteristics:\n- **Idempotent** — Re-rendering produces byte-identical output\n- **Independent** — Different `markerName` values don't interfere\n- **Append fallback** — If markers are absent, content is appended\n\n**资料来源：** [src/core/marker-render.ts:1-50](https://github.com/BrettNye/stoa/blob/main/src/core/marker-render.ts)\n\n---\n\n### Skills Platform\n\nThe skills platform manages deployment drift detection between canonical vault sources and deployed skills.\n\n```mermaid\ngraph LR\n    CANON[Canonical<br/>wikis/_agents/moves/<id>/SKILL.md]\n    DEPLOY[Deployed<br/><skills_dir>/<id>/SKILL.md]\n    HASH[Hash Comparison]\n    REPORT[Drift Report]\n    \n    CANON --> HASH\n    DEPLOY --> HASH\n    HASH --> REPORT\n```\n\n**Drift Detection Rules:**\n\n| Scenario | Behavior |\n|----------|----------|\n| Canonical missing | Throws (vault-integrity bug) |\n| Deployed missing | Emit `missing` |\n| Hashes differ | Emit `hash-mismatch` |\n| Hashes match | Omit (no entry) |\n\n**资料来源：** [src/core/skills-platform.ts:40-80](https://github.com/BrettNye/stoa/blob/main/src/core/skills-platform.ts)\n\n---\n\n### Channel System\n\nChannels enable cross-instance coordination through journal entries tagged with channel identifiers.\n\n```typescript\nexport interface ChannelSummary {\n  name: string;\n  wiki: string;\n  lastEntry: ChannelEntry | null;\n  count24h: number;\n}\n```\n\n**资料来源：** [src/core/channel.ts:1-60](https://github.com/BrettNye/stoa/blob/main/src/core/channel.ts)\n\n---\n\n### State Cache\n\nThe `StateCache` provides in-memory state tracking with a composite key:\n\n```typescript\nexport class StateCache {\n  private key(source: string, wiki: string, id: string): string {\n    return `${source}:${wiki}:${id}`;\n  }\n  \n  get<T>(source: string, wiki: string, id: string): T | undefined;\n  set<T>(source: string, wiki: string, id: string, state: T): void;\n  has(source: string, wiki: string, id: string): boolean;\n  size(): number;\n}\n```\n\n**Use cases:**\n- Pre-warming cache before processing change events\n- Tracking prior state for diff computation\n\n**资料来源：** [src/core/eventbus/state-cache.ts](https://github.com/BrettNye/stoa/blob/main/src/core/eventbus/state-cache.ts)\n\n---\n\n## Configuration\n\n### Wiki Resolution Order\n\n| Priority | Source |\n|----------|--------|\n| 1 | Explicit `wiki:` arg on tool call |\n| 2 | `--default-wiki=<name>` server flag |\n| 3 | `.active-wiki` file at vault root |\n| 4 | Error (no resolution possible) |\n\n### Environment Variables\n\n| Variable | Purpose |\n|----------|---------|\n| `STOA_VAULT_PATH` | Default vault path (skip `--vault=` flag) |\n\n---\n\n## Data Flow\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant Transport\n    participant Tools\n    participant Core\n    participant Index\n    participant Vault\n\n    Client->>Transport: MCP Tool Call\n    Transport->>Tools: Route to handler\n    Tools->>Core: Domain logic\n    Core->>Index: Query/Update\n    Index->>Vault: Read/Write files\n    Vault-->>Index: Data\n    Index-->>Core: Results\n    Core-->>Tools: Processed data\n    Tools-->>Transport: Response\n    Transport-->>Client: MCP Result\n```\n\n---\n\n## Key Design Decisions\n\n| Decision | Rationale | Trade-off |\n|----------|-----------|-----------|\n| Flat-file storage | Human-editable, version-control friendly | Slower random access than DB |\n| Code-fence-aware wikilinks | Prevents link extraction from examples | Indented code blocks still processed |\n| Single-backtick spans NOT stripped | Simplifies extraction logic | Wikilinks in inline code returned |\n| Family/wikis hierarchy | Enables multi-tenant deployments | Additional resolution complexity |\n| Marker-based sections | Allows human editing in managed regions | Collision possible with same marker names |\n\n---\n\n## Related Documentation\n\n- [Installation](docs/installation.md) — Full installation walkthrough\n- [Manual Smoke Test](docs/manual-smoke-test.md) — Verification procedures\n- [Wait-For Primitives](docs/wait-for.md) — Event-based synchronization\n\n---\n\n<a id='event-bus-system'></a>\n\n## Event Bus System\n\n### 相关页面\n\n相关主题：[Architecture and Design](#architecture-design), [Channels and Claims](#channels-claims)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/core/eventbus/state-cache.ts](https://github.com/BrettNye/stoa/blob/main/src/core/eventbus/state-cache.ts)\n- [src/core/eventbus/matchers/task.ts](https://github.com/BrettNye/stoa/blob/main/src/core/eventbus/matchers/task.ts)\n- [src/tools/wait-for.ts](https://github.com/BrettNye/stoa/blob/main/src/tools/wait-for.ts)\n- [src/transport/stdio.ts](https://github.com/BrettNye/stoa/blob/main/src/transport/stdio.ts)\n- [src/core/index.ts](https://github.com/BrettNye/stoa/blob/main/src/core/index.ts)\n</details>\n\n# Event Bus System\n\nThe Event Bus System is a core infrastructure component in Stoa that provides reactive, push-based primitives for monitoring vault changes. Rather than polling for updates, the system leverages the local filesystem watch event bus to notify consumers when specific conditions are met.\n\n## Overview\n\nThe Event Bus System enables agents and tools to:\n\n- **React to vault mutations** — page creation, updates, deletions trigger events\n- **Track state transitions** — monitor changes to structured data like task status\n- **Block until conditions** — wait-for primitives that return only when matching events occur\n- **Warm state on startup** — preload current state before processing live events\n\n资料来源：[src/transport/stdio.ts:27-28]()\n\n## Architecture\n\nThe system consists of several interconnected layers:\n\n| Layer | Purpose |\n|-------|---------|\n| **Watcher** | Filesystem observer that monitors vault paths |\n| **State Cache** | In-memory Map storing prior state for diffing |\n| **Matchers** | Rule-based filters that determine when to emit events |\n| **Bus** | Event dispatcher connecting watchers to consumers |\n| **Wait-For Tools** | Blocking API surface for callers |\n\n```mermaid\ngraph TD\n    A[Vault Filesystem] -->|FS Events| B[Watcher]\n    B --> C[State Cache]\n    C -->|Prior State| D[Matchers]\n    D -->|Emit Decision| E[Event Bus]\n    E -->|VaultEvent| F[Wait-For API]\n    E -->|VaultEvent| G[Other Consumers]\n    \n    H[Startup] -->|walkInitablePaths| I[Warm Cache]\n    I --> C\n```\n\n资料来源：[src/core/eventbus/state-cache.ts:1-15]()\n\n## State Cache\n\nThe `StateCache` class provides an in-memory snapshot of vault entity states, enabling diff-based change detection.\n\n### Key Methods\n\n| Method | Signature | Purpose |\n|--------|-----------|---------|\n| `get` | `<T>(source, wiki, id) => T \\| undefined` | Retrieve cached state |\n| `set` | `<T>(source, wiki, id, state) => void` | Store state snapshot |\n| `has` | `(source, wiki, id) => boolean` | Check if state exists |\n| `size` | `() => number` | Return cache entry count |\n\n### Key Generation\n\nStates are stored using a composite key format:\n\n```\n${source}:${wiki}:${id}\n```\n\nThis allows isolated state tracking per source (e.g., `file-watcher`, `mcp-tool`) across wikis and page IDs.\n\n资料来源：[src/core/eventbus/state-cache.ts:3-22]()\n\n### Initialization\n\nBefore accepting live events, the system warms the cache by walking existing files:\n\n```typescript\nfunction walkInitablePaths(vaultPath: string): string[] {\n  const root = join(vaultPath, \"wikis\");\n  if (!existsSync(root)) return [];\n  // ...\n}\n```\n\nThis ensures the first change event has valid prior state for diffing.\n\n资料来源：[src/transport/stdio.ts:30-46]()\n\n## Matchers\n\nMatchers are pure functions that determine whether a filesystem change should emit a `VaultEvent`. Each matcher handles a specific entity type.\n\n### Task Matcher\n\nThe task matcher tracks frontmatter changes on task pages and emits enrichment data for status/owner transitions.\n\n#### State Picking\n\n```typescript\nfunction pickTaskState(frontmatter): Partial<VaultEvent> {\n  return {\n    status: frontmatter.status,\n    owner: frontmatter.owner\n  };\n}\n```\n\n#### Change Detection Logic\n\n| Condition | Action |\n|-----------|--------|\n| Status changed | Add `task_status_change: { from, to }` |\n| Owner changed | Add `task_owner_change: { from, to }` |\n| Both unchanged | Emit `false` (no event) |\n| Both changed | Emit `true` with both enrichments |\n\n```typescript\nnextState(parsed) { return pickTaskState(parsed.frontmatter); },\ninit(_path, parsed) { return pickTaskState(parsed.frontmatter); },\n```\n\n资料来源：[src/core/eventbus/matchers/task.ts:1-26]()\n\n### Matcher Contract\n\nMatchers implement three functions:\n\n1. **`compare(prev, cur)`** — Returns `{ emit: boolean, enrichment?: Partial<VaultEvent> }`\n2. **`nextState(parsed)`** — Extracts state fields from current file parse\n3. **`init(path, parsed)`** — Provides initial state for a newly discovered entity\n\n## VaultEvent Structure\n\nEvents emitted by the bus carry structured change data:\n\n```typescript\ninterface VaultEvent {\n  type: string;           // Event type identifier\n  wiki: string;           // Wiki containing the entity\n  id: string;             // Entity identifier\n  source: string;         // Origin of the event\n  timestamp?: string;     // ISO timestamp\n  task_status_change?: { from: string; to: string };\n  task_owner_change?: { from: string; to: string };\n}\n```\n\n## Wait-For Primitives\n\nThe Event Bus exposes blocking wait operations for callers that need to pause until conditions are met.\n\n### Available Primitives\n\n| Tool | Behavior |\n|------|----------|\n| `vault.wait-for` | Block until one matching event lands; cursor-based catch-up |\n| `vault.wait-for-any` | Wake on first match across N filters (race semantics) |\n| `vault.wait-for-all` | Wake when all N filters have matched at least once |\n| `vault.wait-for-many` | Bounded batch over a window |\n\nThese primitives connect to the filesystem watch event bus, providing push semantics instead of polling.\n\n资料来源：[README.md:18-25]()\n\n## Event Flow\n\n```mermaid\nsequenceDiagram\n    participant FS as Filesystem\n    participant Watcher\n    participant Cache as State Cache\n    participant Matcher\n    participant Bus\n    participant Consumer\n\n    Note over FS,Consumer: Startup Phase\n    Consumer->>Watcher: walkInitablePaths()\n    Watcher->>FS: Read existing files\n    Watcher->>Cache: set() prior states\n    Cache-->>Consumer: Cache warmed\n\n    Note over FS,Consumer: Live Event Phase\n    FS->>Watcher: File change detected\n    Watcher->>Cache: get() prior state\n    Cache-->>Watcher: Return previous state\n    Watcher->>Matcher: compare(prev, cur)\n    Matcher-->>Watcher: { emit, enrichment }\n    Watcher->>Bus: Emit VaultEvent\n    Bus->>Consumer: Deliver event\n```\n\n## Integration Points\n\n### With Index System\n\nThe event bus integrates with the vault index for querying wikis and pages:\n\n```typescript\nexport function queryWikis(idx: VaultIndex): IndexedWiki[] {\n  return idx.wikis;\n}\n```\n\n资料来源：[src/core/index.ts:1-10]()\n\n### With Lint System\n\nLint checks consume event data for validation:\n\n```typescript\nlintAliasDrift(vaultPath, input.wiki, diagnostics);\nlintAgentsWiki(vaultPath, diagnostics);\n```\n\n资料来源：[src/core/lint.ts:1-30]()\n\n## Configuration\n\nThe system relies on vault path resolution:\n\n| Source | Priority | Environment Variable |\n|--------|----------|----------------------|\n| CLI `--vault` | 1 (highest) | — |\n| `STOA_VAULT_PATH` | 2 | `STOA_VAULT_PATH` |\n| Default | 3 (lowest) | — |\n\nActive wiki/family files (`.active-wiki`, `.active-family`) influence which entities are monitored.\n\n## Error Handling\n\n| Scenario | Behavior |\n|----------|----------|\n| Unknown wiki | Events filtered out; no error |\n| File read failure | Error propagates to watcher |\n| State not in cache | Treat as new entity; use `init` |\n| Matcher throws | Error propagates; event not emitted |\n\n---\n\n<a id='profiles-evolution'></a>\n\n## Agent Profiles and Evolution\n\n### 相关页面\n\n相关主题：[Core Concepts and Vocabulary](#concepts-vocabulary), [Runtime Adapters](#runtime-adapters)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/tools/profile-register.ts](https://github.com/BrettNye/stoa/blob/main/src/tools/profile-register.ts)\n- [src/transport/ui/routes-write.ts](https://github.com/BrettNye/stoa/blob/main/src/transport/ui/routes-write.ts)\n- [src/core/frontmatter.ts](https://github.com/BrettNye/stoa/blob/main/src/core/frontmatter.ts)\n- [src/core/pages.ts](https://github.com/BrettNye/stoa/blob/main/src/core/pages.ts)\n- [src/core/evolution-claims.ts](https://github.com/BrettNye/stoa/blob/main/src/core/evolution-claims.ts)\n</details>\n\n# Agent Profiles and Evolution\n\n## Overview\n\nAgent Profiles and Evolution is a gamified system within the Stoa vault that models agent identities as collectible profiles with species characteristics, evolution stages, and platform-tracked statistics. The system combines the vault's knowledge management with external platform integration via the Stadium API to create persistent, trackable agent personas.\n\n**资料来源：** [src/tools/profile-register.ts:1-28]()\n\n## Architecture\n\n```mermaid\ngraph TD\n    subgraph \"Vault Layer\"\n        P[Profile Page]\n        FM[Frontmatter]\n        W[Wikis Directory]\n    end\n    \n    subgraph \"Profile Creation\"\n        RT[routes-write.ts]\n        NT[newTool.handler]\n        RR[Rarity Roll]\n        SR[Shiny Roll]\n    end\n    \n    subgraph \"Platform Integration\"\n        SC[StadiumClient]\n        PA[/profiles/register API]\n        PR[Platform Response]\n    end\n    \n    subgraph \"Evolution System\"\n        EC[evolution-claims.ts]\n        EV[Evolution Logic]\n    end\n    \n    P --> FM\n    FM --> RT\n    W --> P\n    RT --> NT\n    NT --> RR\n    RR --> SR\n    SR --> SC\n    SC --> PA\n    PA --> PR\n    PR --> EC\n    EC --> EV\n    \n    style P fill:#e1f5fe\n    style SC fill:#fff3e0\n    style EV fill:#e8f5e9\n```\n\n## Profile Structure\n\n### Profile File Location\n\nProfiles are stored as markdown files in the vault with a standardized path structure:\n\n```\nwikis/<wiki>/profiles/<profile_id>.md\n```\n\n**资料来源：** [src/tools/profile-register.ts:17-18]()\n\n### Frontmatter Schema\n\nProfile pages use a specialized frontmatter schema with the following key fields:\n\n| Field | Type | Required | Description |\n|-------|------|----------|-------------|\n| `id` | string | Yes | Must match `^profile-` pattern |\n| `title` | string | Yes | Display name for the profile |\n| `type` | enum | Yes | Always `\"profile\"` |\n| `wiki` | string | Yes | Parent wiki namespace |\n| `status` | enum | No | Page status (draft/active/accepted/superseded/archived) |\n| `pokemon` | string | No | Species name (v1.5 convention) |\n| `species_name` | string | No | Legacy species name (fallback) |\n| `evolution_stage` | string | No | Stage identifier (defaults to \"basic\") |\n| `pokemon_type` | string | No | Type classification |\n| `dev_specialty` | string | No | Developer specialty marker |\n| `platform_profile_id` | string | No | Stadium platform ID (set post-registration) |\n| `platform_stats` | object | No | Stats returned from platform |\n\n**资料来源：** [src/core/frontmatter.ts:23-45](), [src/transport/ui/routes-write.ts:88-92]()\n\n## Profile Registration Flow\n\nThe registration process synchronizes vault profiles with the external Stadium platform:\n\n```mermaid\nsequenceDiagram\n    participant Agent\n    participant MCP as MCP Server\n    participant Vault as Vault FS\n    participant Stadium as Stadium API\n    \n    Agent->>MCP: profile-register(profile_id)\n    MCP->>Vault: Read wikis/<wiki>/profiles/<id>.md\n    Vault->>MCP: Raw file content\n    MCP->>MCP: parseFrontmatter()\n    Note over MCP: Extract pokemon/species_name\n    MCP->>Stadium: POST /profiles/register\n    Stadium->>MCP: { profile_id, stats }\n    MCP->>Vault: upsertPage() with platform fields\n    MCP->>Agent: Registration result\n```\n\n**资料来源：** [src/tools/profile-register.ts:13-27]()\n\n### Registration Tool Interface\n\n```typescript\nconst Input = z.object({\n  profile_id: z.string().regex(/^profile-/),\n  wiki: z.string().optional()\n});\n```\n\n**资料来源：** [src/tools/profile-register.ts:20-24]()\n\n## Profile Creation (UI Routes)\n\nThe `routes-write.ts` module handles interactive profile creation with gamification elements:\n\n**资料来源：** [src/transport/ui/routes-write.ts:78-130]()\n\n### Creation Parameters\n\n| Parameter | Source | Description |\n|-----------|--------|-------------|\n| `wiki` | Computed | Defaults to `\"_agents\"` |\n| `title` | Computed | Format: `<species> agent` |\n| `frontmatterExtras.pokemon` | `selected_species` | Species name |\n| `frontmatterExtras.evolution_stage` | `evolution_stage` | Defaults to `\"basic\"` |\n| `frontmatterExtras.pokemon_type` | `pokemon_type` | Optional type |\n| `frontmatterExtras.dev_specialty` | `dev_specialty` | Optional specialty |\n\n**资料来源：** [src/transport/ui/routes-write.ts:80-93]()\n\n### Gamification: Rarity and Shiny Rolls\n\nDuring profile creation, two gamification rolls occur before the file is written:\n\n```typescript\nlet rarity: \"common\" | \"baby\" | \"legendary\" | \"mythical\" = \"common\";\nlet isShiny = false;\n```\n\n**资料来源：** [src/transport/ui/routes-write.ts:96-97]()\n\n| Roll | Probability | Effect |\n|------|-------------|--------|\n| Rarity | Varies by species | Determines rarity tier |\n| Shiny | 1/64 (1.5625%) | Applies shiny modifier to profile |\n\nThe shiny roll fetches species data and persists the result into the profile frontmatter.\n\n**资料来源：** [src/transport/ui/routes-write.ts:98-112]()\n\n## Evolution System\n\nThe evolution system is implemented across multiple modules that track and process evolution-related claims:\n\n### Evolution Claims\n\nThe `evolution-claims.ts` module handles the logic for processing evolution-related claims within the claims store. This system validates evolution conditions and updates profile states accordingly.\n\n**资料来源：** [src/core/evolution-claims.ts](file context provided in repository)\n\n### Evolution Workflow\n\n```mermaid\ngraph LR\n    A[Profile Created] --> B{Claims Accumulated}\n    B -->|Sufficient| C[Evolution Trigger]\n    B -->|Insufficient| D[Wait State]\n    C --> E[Evolution Validation]\n    E -->|Valid| F[Profile Updated]\n    E -->|Invalid| G[Reject Evolution]\n    F --> H[Platform Sync]\n    D --> B\n```\n\n## Profile Identification\n\n### Supported ID Patterns\n\nThe system supports multiple profile identification patterns:\n\n| Pattern | Description | Example |\n|---------|-------------|---------|\n| Standard | `profile-<slug>.md` | `profile-fire-type.md` |\n| Agent-specific | `profile-<agent-name>` | `profile-claude` |\n\n**资料来源：** [src/core/pages.ts:45-60]()\n\n### Path Resolution\n\nThe `pathForPage` function resolves profile paths:\n\n```typescript\n// Profile pages use the profiles subdirectory\nconst path = join(vaultPath, \"wikis\", wiki, \"profiles\", `${id}.md`);\n```\n\n**资料来源：** [src/core/pages.ts:47-49]()\n\n## Stadium Platform Integration\n\n### Client Architecture\n\nThe `StadiumClient` handles all communication with the Stadium platform:\n\n- **Base URL**: Configured via `resolveStadiumConfig()`\n- **Endpoint**: `/profiles/register` for profile creation\n- **Error Handling**: Propagates `StadiumApiError` with `error_code`\n\n**资料来源：** [src/tools/profile-register.ts:23]()\n\n### Platform Data Flow\n\n```\n┌─────────────────┐     ┌──────────────────┐     ┌─────────────────┐\n│   Vault File    │────▶│  profile-register │────▶│ Stadium API     │\n│   (pokemon: X)  │     │  Tool            │     │ POST /register  │\n└─────────────────┘     └──────────────────┘     └─────────────────┘\n                              │                        │\n                              ▼                        ▼\n                        ┌──────────────────┐     ┌─────────────────┐\n                        │ upsertPage()     │◀────│ profile_id      │\n                        │ (persist result) │     │ stats           │\n                        └──────────────────┘     └─────────────────┘\n```\n\n### Error Propagation\n\nServer errors from the Stadium platform are propagated as `StadiumApiError`. Common error codes include:\n\n- `pokeapi_unknown_species`: Species not found in platform\n- Network failures: Caught and returned with descriptive messages\n\n**资料来源：** [src/transport/ui/routes-write.ts:100-105]()\n\n## Configuration and Defaults\n\n| Setting | Default | Source |\n|---------|---------|--------|\n| Default Wiki | `_agents` | [routes-write.ts:78]() |\n| Evolution Stage | `\"basic\"` | [routes-write.ts:90]() |\n| Shiny Probability | 1/64 | [routes-write.ts:98-112]() |\n| Platform Endpoint | `/profiles/register` | [profile-register.ts:23]() |\n\n## Related Tools\n\n| Tool | Purpose |\n|------|---------|\n| `vault.profile-register` | Register profile with Stadium platform |\n| `vault.evolve-profile` | Trigger evolution on eligible profiles |\n| `vault.refresh-profile-memory` | Update agent memory in profile |\n\n**资料来源：** [src/tools/profile-register.ts:31-35]()\n\n## Future Considerations\n\nThe current implementation (v1.5 convention) stores species information in the `pokemon` frontmatter field. The system maintains backward compatibility with the legacy `species_name` field for existing profiles. Future versions may expand the evolution system to include:\n\n- Multi-stage evolution chains\n- Evolution condition validation via claims\n- Platform-synced evolution history\n\n---\n\n<a id='task-workflow'></a>\n\n## Task Workflow System\n\n### 相关页面\n\n相关主题：[Channels and Claims](#channels-claims), [Core Concepts and Vocabulary](#concepts-vocabulary)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/core/tasks.ts](https://github.com/BrettNye/stoa/blob/main/src/core/tasks.ts)\n- [src/tools/merge-record.ts](https://github.com/BrettNye/stoa/blob/main/src/tools/merge-record.ts)\n- [src/core/frontmatter.ts](https://github.com/BrettNye/stoa/blob/main/src/core/frontmatter.ts)\n- [src/core/eventbus/matchers/task.ts](https://github.com/BrettNye/stoa/blob/main/src/core/eventbus/matchers/task.ts)\n- [src/core/disk-fallback.ts](https://github.com/BrettNye/stoa/blob/main/src/core/disk-fallback.ts)\n- [README.md](https://github.com/BrettNye/stoa/blob/main/README.md)\n</details>\n\n# Task Workflow System\n\nThe Task Workflow System in Stoa provides a structured mechanism for creating, tracking, claiming, and resolving tasks across the vault's wiki-based knowledge management environment. It integrates with the broader event bus system for real-time state change notifications and supports atomic task claiming to prevent race conditions in multi-agent scenarios.\n\n## Overview\n\nThe Task Workflow System serves as the coordination backbone for agent-driven work items within Stoa. It enables:\n\n- **Task lifecycle management** — creation, status tracking, and resolution\n- **Atomic claiming** — race-safe task assignment to agents\n- **Two-phase task lookup** — fast index-based retrieval with disk-scan fallback\n- **Event-driven state propagation** — real-time task status change notifications via the event bus\n- **Optimistic Concurrency Control (OCC)** — safe concurrent updates using `expected_updated` timestamps\n\n资料来源：[README.md:1-20]()\n\n## Core Data Model\n\n### Task Interface\n\n```typescript\ninterface Task {\n  id: string;\n  title: string;\n  type: string;\n  wiki: string;\n  status: string;\n  claimed_by?: string;\n  claimed_at?: string;\n  updated: string;\n  body: string;\n}\n```\n\nThe `Task` interface represents a work item stored as markdown frontmatter within `wikis/<wiki>/tasks/` directories. Key fields include:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `id` | `string` | Unique task identifier (kebab-case per `HARD_KNOWLEDGE_TYPES`) |\n| `wiki` | `string` | The wiki namespace containing this task |\n| `status` | `string` | Current task status (e.g., `pending`, `claimed`, `merged`) |\n| `claimed_by` | `string?` | Agent ID that claimed this task |\n| `claimed_at` | `string?` | ISO timestamp when the task was claimed |\n| `updated` | `string` | ISO date of last modification (used for OCC) |\n\n资料来源：[src/core/tasks.ts:1-30]()\n\n### Task Status Values\n\nThe system uses a defined set of task statuses aligned with the `PageStatus` enum:\n\n| Status | Description |\n|--------|-------------|\n| `draft` | Initial state; task created but not ready for work |\n| `active` | Task is open and in progress |\n| `claimed` | Task has been assigned to an agent |\n| `merged` | Task work has been merged/completed |\n| `archived` | Task is no longer active |\n\n资料来源：[src/core/frontmatter.ts:1-20]()\n\n## Task Lookup Architecture\n\nStox implements a two-phase task lookup strategy to balance performance with data freshness.\n\n```mermaid\ngraph TD\n    A[Find Task by ID] --> B{Fast Path:<br/>Index Lookup}\n    B -->|Found| C[Return Task]\n    B -->|Not Found| D{Slow Path:<br/>Disk Scan}\n    D -->|Found| C\n    D -->|Not Found| E[Return null]\n```\n\n### Phase 1: Fast Path — Index Lookup\n\nThe system first queries `_index/pages.json` for the task:\n\n```typescript\nconst idx = loadIndex(vaultPath);\nconst hit = idx.pages.find(p => p.id === taskId && p.type === \"task\");\nif (hit) {\n  return {\n    wiki: hit.wiki,\n    updated: hit.updated,\n    status: String((hit as any).status ?? \"\")\n  };\n}\n```\n\nThis path executes in O(n) on the index array and succeeds for all tasks that have been indexed since their last modification. 资料来源：[src/tools/merge-record.ts:1-40]()\n\n### Phase 2: Slow Path — Disk Scan Fallback\n\nWhen the index lacks the task (e.g., tasks authored directly on disk between reindexes), the system falls back to a disk scan:\n\n```typescript\nreturn findTaskOnDisk(vaultPath, taskId);\n```\n\nThe `findTaskOnDisk` function delegates to the generalized `findOnDisk` utility in `core/disk-fallback.ts`, restricting results to `type: \"task\"`. This handles the case surfaced in Phase-3 Wave 5 T5-3 where tasks created via direct file authoring were immediately followed by a `vault.merge-record` call that silently missed the transition. 资料来源：[src/core/tasks.ts:1-30]()\n\n## Task Claiming\n\nThe atomic task claiming mechanism prevents race conditions when multiple agents attempt to claim the same task simultaneously.\n\n### Claim Operation\n\n```typescript\nexport class AlreadyClaimedError extends Error {\n  code = \"AlreadyClaimed\" as const;\n}\n```\n\nWhen an agent attempts to claim a task:\n\n1. The system loads the current task state\n2. If `claimed_by` is already set, the race-loser receives `AlreadyClaimedError`\n3. If unclaimed, the task is atomically updated with `claimed_by` and `claimed_at`\n\nThe `vault.task-claim` tool implements this atomicity, ensuring only one agent successfully claims a task. 资料来源：[src/tools/task-claim.ts]()\n\n### Task Transition Rules\n\nThe `merge-record.ts` module defines conditional task transition logic:\n\n```typescript\nfunction computeTaskTransition(status: string, task_id: string): TaskTransition | null {\n  // Returns a transition only when status === \"merged\" AND task_id is non-empty\n  // For all halt/fail statuses it returns null and the task is NOT touched\n}\n```\n\nThis rule ensures that:\n- Only `merged` status triggers a task transition\n- The journal is written regardless of whether the task update succeeds\n- Failure/halt journals are safe to re-run without side effects\n\n资料来源：[src/tools/merge-record.ts:1-60]()\n\n## Event Bus Integration\n\nThe task system integrates with Stoa's event bus for real-time state change notifications.\n\n### Task State Matcher\n\n```typescript\nexport const taskStateMatcher: VaultStateMatcher = {\n  key: \"task\",\n  extractKey(parsed) { return String(parsed.frontmatter.id); },\n  diff(prev, cur) {\n    if (cur.status === prev.status && cur.owner === prev.owner) {\n      return { emit: false };\n    }\n    const enrichment: Partial<VaultEvent> = {};\n    if (cur.status !== prev.status) {\n      enrichment.task_status_change = { from: prev.status, to: cur.status };\n    }\n    if (cur.owner !== prev.owner) {\n      enrichment.task_owner_change = { from: prev.owner, to: cur.owner };\n    }\n    return { emit: true, enrichment };\n  },\n  nextState(parsed) { return pickTaskState(parsed.frontmatter); },\n  init(_path, parsed) { return pickTaskState(parsed.frontmatter); },\n};\n```\n\nThe matcher extracts task state from frontmatter and emits events for:\n- `task_status_change` — when status transitions (e.g., `active` → `merged`)\n- `task_owner_change` — when `claimed_by` changes\n\n资料来源：[src/core/eventbus/matchers/task.ts:1-30]()\n\n### State Extraction\n\n```typescript\nfunction pickTaskState(fm: Record<string, any>): TaskState {\n  return {\n    status: String(fm.status ?? \"draft\"),\n    owner: fm.claimed_by ? String(fm.claimed_by) : undefined,\n  };\n}\n```\n\n## Task Operations\n\n### Available Task Tools\n\n| Tool | Description |\n|------|-------------|\n| `vault.task-create` | Create a new task in a specified wiki |\n| `vault.task-list` | List tasks with optional filters |\n| `vault.task-update` | Update task fields (status, claimed_by, etc.) |\n| `vault.task-claim` | Atomically claim a pending task |\n\n资料来源：[README.md:1-20]()\n\n### Optimistic Concurrency Control\n\nTask updates use OCC to prevent lost updates:\n\n```typescript\ninterface ReleaseInput {\n  task_id: string;\n  expected_updated: string;  // Timestamp from last known state\n  wiki: string;\n  reason?: string;\n}\n```\n\nThe system compares the provided `expected_updated` against the current `updated` value. If they match, the update proceeds; otherwise, it fails to prevent concurrent modification.\n\n## Journal Integration\n\nWhen `merge-record.ts` processes a merged pull request:\n\n1. Writes journal file at `wikis/_agents/journal/<journal_id>.md`\n2. Idempotent rewrite — same `now` + same input produces same `journal_id`\n3. Conditional task transition via `computeTaskTransition`\n4. `task_updated: false` when task_id not found, but journal still written\n\n资料来源：[src/tools/merge-record.ts:1-30]()\n\n## Configuration\n\nTask behavior is configurable via `_meta/lint-config.yaml`:\n\n| Key | Default | Description |\n|-----|---------|-------------|\n| `task.min_cluster_size` | `3` | Minimum cluster size for synthesis debt detection |\n\nNote: Task-specific configuration loading is pending (resolution-lifecycle spec implementation).\n\n## Related Concepts\n\n- **Synthesis Debt** — Tasks may be created to address synthesis clusters\n- **Claim Clustering** — Related claim grouping logic\n- **Task Readiness** — Determines when tasks are ready for claiming\n- **Event Bus** — Real-time task event propagation\n\n---\n\n<a id='channels-claims'></a>\n\n## Channels and Claims\n\n### 相关页面\n\n相关主题：[Task Workflow System](#task-workflow), [Event Bus System](#event-bus-system)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/core/channel.ts](https://github.com/BrettNye/stoa/blob/main/src/core/channel.ts)\n- [src/core/decay.ts](https://github.com/BrettNye/stoa/blob/main/src/core/decay.ts)\n- [src/core/claim-render.ts](https://github.com/BrettNye/stoa/blob/main/src/core/claim-render.ts)\n- [src/tools/claim.ts](https://github.com/BrettNye/stoa/blob/main/src/tools/claim.ts)\n- [src/core/synthesize.ts](https://github.com/BrettNye/stoa/blob/main/src/core/synthesize.ts)\n- [src/core/frontmatter.ts](https://github.com/BrettNye/stoa/blob/main/src/core/frontmatter.ts)\n- [src/core/lint.ts](https://github.com/BrettNye/stoa/blob/main/src/core/lint.ts)\n</details>\n\n# Channels and Claims\n\n## Overview\n\nChannels and Claims are two interconnected systems within the Stoa vault that enable coordination and knowledge assertion respectively. Channels provide a pub/sub mechanism for cross-instance communication, while Claims represent structured knowledge assertions with built-in confidence scoring and temporal decay.\n\n## Channels\n\n### Purpose\n\nChannels enable coordination and communication across multiple vault instances or agents. They function as a lightweight messaging layer backed by journal pages stored directly in the vault filesystem.\n\n### Architecture\n\nChannels are implemented as journal pages with a `channel` field in their frontmatter. The system leverages the existing page indexing infrastructure rather than maintaining a separate message broker.\n\n```mermaid\ngraph TD\n    A[Agent/Instance] -->|vault.channel-post| B[Journal Page]\n    B -->|type: journal<br/>channel: &lt;name&gt;<br/>wiki: &lt;wiki&gt;| C[Vault FS]\n    D[Other Agent] -->|vault.channel-tail| E[Channel Summary]\n    C -->|queryPages idx| E\n```\n\n### Channel Naming Convention\n\nChannels must follow a strict naming format validated at lint time:\n\n| Format | Regex | Example |\n|--------|-------|---------|\n| Lowercase kebab-case | `^[a-z0-9]+(-[a-z0-9]+)*$` | `pr-reviews`, `task-alerts` |\n\nValidation is enforced in `src/core/lint.ts`:\n\n```typescript\nif (p.channel && !/^[a-z0-9]+(-[a-z0-9]+)*$/.test(p.channel)) {\n  diagnostics.push({\n    severity: \"warning\", code: \"BAD_CHANNEL_FORMAT\",\n    page_id: p.id, wiki: p.wiki,\n    message: `channel \"${p.channel}\" must be lowercase kebab-case`\n  });\n}\n```\n资料来源：[src/core/lint.ts:47-54]()\n\n### Channel Summaries\n\nThe `channel-tail` tool aggregates journal entries into summaries containing:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `name` | string | Channel identifier |\n| `wiki` | string | Wiki where the channel exists |\n| `lastEntry` | object | Most recent entry with id, author, ts, excerpt |\n| `count24h` | number | Entries within the last 24 hours |\n\nEach summary caches author information and body excerpts (first 240 characters) from the actual page files to avoid repeated filesystem reads during aggregation.\n\n资料来源：[src/core/channel.ts:21-35]()\n\n### Resolving Channel Scope\n\nChannel queries are scoped by wiki. When listing or tailing channels, the system filters pages by:\n\n1. `type === \"journal\"` — Only journal pages participate in channels\n2. `wiki === opts.wiki` — Wiki isolation is enforced\n\n```typescript\nconst pages = queryPages(idx, { type: \"journal\", wiki: opts.wiki });\n```\n资料来源：[src/core/channel.ts:18]()\n\n## Claims\n\n### Purpose\n\nClaims represent structured knowledge assertions within the vault. They carry explicit confidence levels that decay over time, creating a system where knowledge freshness is tracked and surfaced.\n\n### Data Model\n\nClaims are stored as pages with the following frontmatter structure:\n\n```yaml\nid: <slug>\ntype: claim\ntitle: <human-readable title>\nauthored_by: <agent-or-human>\nconfidence: high | medium | low\nstatus: pending | accepted | retracted | rejected\nevidence:\n  - [[wikis/<wiki>/<type>/<id>]]\nlast_validated: YYYY-MM-DD\ncreated: YYYY-MM-DD\nupdated: YYYY-MM-DD\n```\n\n### Confidence Decay\n\nClaims use a temporal decay model to represent knowledge staleness. The effective confidence decreases based on:\n\n1. **Initial confidence level** — `high`, `medium`, or `low`\n2. **Time since last validation** — Measured in days\n3. **Configured half-life** — Number of days for confidence to halve\n\nThe effective confidence formula is documented in `claim-render.ts`:\n\n```typescript\nconst eff = effectiveConfidence(\n  {\n    confidence: claim.confidence,\n    last_validated: claim.last_validated,\n    status: claim.status,\n  },\n  today,\n  {\n    half_life_days: config.half_life_days,\n    effective_floor: config.effective_floor,\n  }\n);\n```\n资料来源：[src/core/claim-render.ts:45-57]()\n\n### Effective Confidence Computation\n\nThe decay system applies a floor to prevent confidence from reaching zero:\n\n| Parameter | Default | Purpose |\n|-----------|---------|---------|\n| `half_life_days` | Configurable | Days for confidence to halve |\n| `effective_floor` | Configurable | Minimum confidence value |\n\n### Rendering Claims\n\nClaims are rendered as bullet points in synthesis pages:\n\n```markdown\n- **`<key>`** — <body>. *(confidence <eff> as of <render-date>, validated <last_validated>, evidence: [[<first>]])*\n```\n\nThe system:\n- Rounds effective confidence to 2 decimal places\n- Uses `claim.summary` if available, falling back to `claim.body`\n- Includes only the first evidence entry\n- Collapses internal whitespace to maintain single-line bullets\n\n```typescript\n// Collapse all internal whitespace runs (incl. embedded newlines) to a\n// single space. `.trim()` alone leaves embedded `\\n` intact, which would\n// break the single-line bullet and corrupt the vault-claims:start..end\n```\n资料来源：[src/core/claim-render.ts:64-70]()\n\n### Claim Lifecycle\n\n```mermaid\nstateDiagram-v2\n  [*] --> pending: Creation\n  pending --> accepted: Validation by curator\n  pending --> rejected: Conflicting higher-confidence claim\n  accepted --> retracted: Author retracts\n  accepted --> rejected: Override with strictly higher confidence\n  retracted --> [*]\n  rejected --> [*]\n```\n\n### Claim Operations\n\n#### Retraction\n\nAuthors may retract their own claims, recording:\n- `retracted_at`: Timestamp of retraction\n- `retracted_by`: Author performing retraction\n- `retraction_reason`: Human-readable explanation\n\nOnly the original author may retract a claim:\n\n```typescript\nif (target.authored_by !== as) {\n  throw new Error(\n    `only the original author may retract claim ${claimId}: authored_by=${target.authored_by ?? \"<unset>\"}, as=${as}`,\n  );\n}\n```\n资料来源：[src/tools/claim.ts:85-90]()\n\n#### Rejection\n\nClaims are rejected when a higher-confidence claim on the same assertion already exists:\n\n```typescript\nreturn {\n  claim_id: ex.id,\n  action: \"rejected\",\n  rejection: {\n    reason: `existing claim ${ex.id} has effective confidence ${existingEffective.toFixed(3)}; submission's ${yourConfidence} is not strictly higher`,\n    existing_id: ex.id,\n    existing_effective_confidence: existingEffective,\n    your_confidence: yourConfidence,\n  },\n};\n```\n资料来源：[src/tools/claim.ts:99-108]()\n\n### Claim Sorting in Syntheses\n\nWhen rendering synthesis pages, claims are sorted by a scoring function that accounts for effective confidence and profile affinity:\n\n```typescript\nconst score = (c: ParsedClaim) => {\n  const eff = effectiveConfidence(/* ... */);\n  const boost = (c.profile ?? []).includes(deployingProfileId) ? 0.1 : 0;\n  return eff + boost;\n};\nreturn [...claims].sort((a, b) => score(b) - score(a));\n```\n资料来源：[src/core/claim-render.ts:26-34]()\n\n### Synthesis Integration\n\nClaims are incorporated into synthesis pages via the `sources` frontmatter field:\n\n```typescript\nsources: inputIds.map(i => `[[wikis/${wiki}/${typeFolderForId(i)}/${i}]]`)\n```\n资料来源：[src/core/synthesize.ts:62]()\n\nThe synthesis metadata includes:\n\n| Field | Value |\n|-------|-------|\n| `type` | `synthesis` |\n| `status` | `draft` |\n| `last_compiled` | ISO date of generation |\n\n## Lint Rules\n\n### Claim Scope Validation\n\nClaims without scope (profile, move, scope_wiki, or tags) receive a warning:\n\n```typescript\nif (!allEmpty) return [];\nreturn [{\n  ruleId: \"claim-with-no-scope\",\n  severity: \"warn\",\n  line: 1,\n  message: \"Claim has no scope (profile/move/scope_wiki/tags all empty); no read path will surface it.\",\n}];\n```\n资料来源：[src/core/lint-checks/claim-with-no-scope.ts:17-24]()\n\n### Channel Format Validation\n\nChannel identifiers are validated during lint runs to ensure consistency:\n\n| Check | Severity | Message |\n|-------|----------|---------|\n| Invalid kebab-case format | `warning` | `channel \"<name>\" must be lowercase kebab-case` |\n\n## Related Tools\n\n| Tool | Purpose |\n|------|---------|\n| `vault.channel-post` | Post a message to a coordination channel |\n| `vault.channel-tail` | Pull recent entries from a channel |\n| `vault.claim` | Submit, validate, or retract claims |\n| `vault.synthesize` | Compile synthesis pages incorporating claims |\n\n---\n\n<a id='runtime-adapters'></a>\n\n## Runtime Adapters\n\n### 相关页面\n\n相关主题：[Sync Agents and Skills](#sync-agents-skills), [Agent Profiles and Evolution](#profiles-evolution)\n\nThe repository context provided does not contain the source files required for this topic:\n\n- `src/core/runtime-adapters/types.ts`\n- `src/core/runtime-adapters/registry.ts`\n- `src/core/runtime-adapters/claude-code.ts`\n- `src/core/subagent-protocol.ts`\n- `src/core/subagent-intent.ts`\n\nThese files are listed in the `<details>` block requirements but are **not present** in the retrieved repository context. Without access to these source files, I cannot generate an accurate technical wiki page about the Runtime Adapters feature.\n\n**Available alternatives in the context:**\n\nThe context does contain `src/core/deployments.ts` which has partial runtime-related code:\n\n```typescript\nexport interface DeploymentEntry {\n  repo_path: string;\n  target: \"claude-code\" | \"openclaw\" | \"codex\";\n  mode: DeployMode;\n  actual_mode?: DeployMode;\n  synced_at: string;\n  runtime?: RuntimeName;\n  source_revision?: string;\n  subagent_def_path?: string;\n}\n```\n\nThis shows runtime targets exist (`claude-code`, `openclaw`, `codex`) and a `RuntimeName` type is referenced, but the core runtime-adapters module files are needed to document the complete system.\n\n**To proceed, please provide the content of the following files:**\n\n1. `src/core/runtime-adapters/types.ts`\n2. `src/core/runtime-adapters/registry.ts`\n3. `src/core/runtime-adapters/claude-code.ts`\n4. `src/core/subagent-protocol.ts`\n5. `src/core/subagent-intent.ts`\n\nOnce these files are provided, I can generate the comprehensive technical wiki page with proper citations, Mermaid diagrams, and tables as requested.\n\n---\n\n<a id='sync-agents-skills'></a>\n\n## Sync Agents and Skills\n\n### 相关页面\n\n相关主题：[Runtime Adapters](#runtime-adapters), [Agent Profiles and Evolution](#profiles-evolution)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/tools/sync-skills.ts](https://github.com/BrettNye/stoa/blob/main/src/tools/sync-skills.ts)\n- [src/core/skills.ts](https://github.com/BrettNye/stoa/blob/main/src/core/skills.ts)\n- [src/core/skills-platform.ts](https://github.com/BrettNye/stoa/blob/main/src/core/skills-platform.ts)\n- [src/core/deployments.ts](https://github.com/BrettNye/stoa/blob/main/src/core/deployments.ts)\n- [src/tools/claim.ts](https://github.com/BrettNye/stoa/blob/main/src/tools/claim.ts)\n</details>\n\n# Sync Agents and Skills\n\nThe sync agents and skills system is a core deployment mechanism that bridges the vault's canonical knowledge store with agent runtime environments. It provides two synchronized capabilities: **agent profile deployment** and **skills (moveset) deployment**, enabling consistent agent behavior across different execution contexts.\n\n## Architecture Overview\n\nThe system operates across three layers:\n\n| Layer | Purpose | Key Files |\n|-------|---------|-----------|\n| **CLI/API** | User-facing entry points | `src/tools/sync-skills.ts`, `src/cli/commands/sync-agents.ts` |\n| **Core Logic** | Business rules and deployment orchestration | `src/core/skills.ts`, `src/core/skills-platform.ts` |\n| **Persistence** | Deployment registry management | `src/core/deployments.ts` |\n\n```mermaid\ngraph TD\n    A[\"vault.sync-skills<br/>(MCP Tool)\"] --> B[\"Read Profile<br/>wikis/&lt;wiki&gt;/profiles/&lt;profileId&gt;.md\"]\n    B --> C[\"Extract moves[]<br/>from profile frontmatter\"]\n    C --> D{\"For each move\"}\n    D -->|Canonical path| E[\"wikis/_agents/moves/&lt;moveId&gt;/SKILL.md\"]\n    D -->|Deployed path| F[\"&lt;deployment.skills_dir&gt;/&lt;moveId&gt;/SKILL.md\"]\n    E --> G[\"probeSymlinkSupport()\"]\n    G --> H{\"Host supports symlinks?\"}\n    H -->|Yes| I[\"fs.symlinkSync()\"]\n    H -->|No| J[\"recursiveCopy()\"]\n    I --> K[\"mode: 'symlink'\"]\n    J --> L[\"mode: 'copy'\"]\n    K --> M[\"Update _index/deployments.json\"]\n    L --> M\n    M --> N[\"Return DeploymentEntry[]\"]\n```\n\n资料来源：[src/tools/sync-skills.ts](https://github.com/BrettNye/stoa/blob/main/src/tools/sync-skills.ts)\n\n## Core Concepts\n\n### Deployment Target\n\nThe system supports multiple agent runtimes:\n\n```typescript\ntype DeployTarget = \"claude-code\" | \"openclaw\" | \"codex\";\n```\n\nEach target represents a distinct agent runtime that consumes skills from the local filesystem. 资料来源：[src/core/deployments.ts:14](https://github.com/BrettNye/stoa/blob/main/src/core/deployments.ts#L14)\n\n### Deploy Mode\n\nTwo deployment modes control how skills are materialized:\n\n| Mode | Behavior | Fallback |\n|------|----------|----------|\n| `symlink` | Creates symbolic links from deployment directory to canonical vault files | Auto-falls back to `copy` on EPERM/EACCES/EEXIST |\n| `copy` | Recursively copies the move directory to the deployment path | None |\n\nThe system automatically probes symlink support at `<targetDir>/.symlink-probe-<random>` before attempting symlink deployment. 资料来源：[src/core/skills-platform.ts:63-75](https://github.com/BrettNye/stoa/blob/main/src/core/skills-platform.ts#L63-L75)\n\n### Drift Detection\n\nThe `detectDriftAt()` function compares canonical and deployed skill files using content hashing:\n\n```typescript\nexport function detectDriftAt(\n  deployment: DriftDeployment,\n  vaultPath: string\n): DriftReport[]\n```\n\n**Drift report rules:**\n\n| Condition | Report | Action |\n|-----------|--------|--------|\n| Canonical missing | Throws | Vault integrity bug |\n| Deployed missing | `{ kind: \"missing\", actual_hash: undefined }` | Deploy needed |\n| Hashes differ | `{ kind: \"hash-mismatch\", actual_hash }` | Re-deploy needed |\n| Hashes match | No entry (omit) | No action |\n\n资料来源：[src/core/skills-platform.ts:27-40](https://github.com/BrettNye/stoa/blob/main/src/core/skills-platform.ts#L27-L40)\n\n## Data Models\n\n### DeploymentEntry\n\n```typescript\nexport interface DeploymentEntry {\n  repo_path: string;\n  target: \"claude-code\" | \"openclaw\" | \"codex\";\n  mode: DeployMode;\n  actual_mode?: DeployMode;\n  synced_at: string;\n\n  // v1.7 additions\n  runtime?: RuntimeName;\n  source_revision?: string;\n  subagent_def_path?: string;\n}\n```\n\nThe `actual_mode` field records whether symlinking was actually used (vs requested), enabling truthful reporting. 资料来源：[src/core/deployments.ts:19-31](https://github.com/BrettNye/stoa/blob/main/src/core/deployments.ts#L19-L31)\n\n### DeploymentRegistry\n\n```typescript\nexport type DeploymentRegistry = Record<string, DeploymentEntry[]>;\n```\n\nThe registry is keyed by `profileId`, with each entry representing one deployment of that profile. Stored at `_index/deployments.json` at the vault root. 资料来源：[src/core/deployments.ts:33-34](https://github.com/BrettNye/stoa/blob/main/src/core/deployments.ts#L33-L34)\n\n## Skills Structure\n\n### Move Directory Layout\n\nSkills (called \"moves\") follow a directory convention:\n\n```\nwikis/_agents/moves/\n├── move-flamethrower/\n│   └── SKILL.md\n├── move-thunderbolt/\n│   └── SKILL.md\n└── move-protect/\n    └── SKILL.md\n```\n\n- Each move is a directory containing a single `SKILL.md` file\n- Move IDs are used as directory names\n- The directory layout enables recursive deployment operations 资料来源：[src/core/skills-platform.ts:18-23](https://github.com/BrettNye/stoa/blob/main/src/core/skills-platform.ts#L18-L23)\n\n### Profile Structure\n\nProfiles reference moves via the `moves` frontmatter field:\n\n```yaml\n---\nid: profile-charizard\ntitle: Charizard Combat Profile\ntype: profile\nwiki: _agents\nmoves:\n  - move-flamethrower\n  - move-thunderbolt\n  - move-dragon-dance\n---\n```\n\nThe `moves` array is read during sync to determine which skills to deploy. 资料来源：[src/core/skills.ts](https://github.com/BrettNye/stoa/blob/main/src/core/skills.ts)\n\n## Sync Workflow\n\n### vault.sync-skills Tool\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant VaultMCP\n    participant ProfileStore\n    participant DeployModule\n    participant Registry\n\n    Client->>VaultMCP: vault.sync-skills({profile_id, wiki?})\n    VaultMCP->>ProfileStore: Read wikis/<wiki>/profiles/<profile_id>.md\n    ProfileStore-->>VaultMCP: Profile with moves[]\n    \n    VaultMCP->>VaultMCP: For each moveId in moves[]:\n    VaultMCP->>DeployModule: probeSymlinkSupport(targetDir)\n    DeployModule-->>VaultMCP: supportsSymlinks: boolean\n    \n    alt supportsSymlinks\n        VaultMCP->>DeployModule: deployMove(src, dest, \"symlink\")\n    else\n        VaultMCP->>DeployModule: deployMove(src, dest, \"copy\")\n    end\n    \n    DeployModule->>Registry: Update _index/deployments.json\n    VaultMCP-->>Client: DeploymentEntry[]\n```\n\n### Deployment Persistence\n\nThe registry stores each deployment with idempotent semantics:\n\n```typescript\nexport function writeDeployments(vaultPath: string, registry: DeploymentRegistry): void\nexport function readDeployments(vaultPath: string): DeploymentRegistry\n```\n\nRe-running sync with identical inputs produces byte-identical registry output. 资料来源：[src/core/deployments.ts:38-52](https://github.com/BrettNye/stoa/blob/main/src/core/deployments.ts#L38-L52)\n\n## Configuration\n\n### Vault Path Resolution\n\n| Priority | Source | Key |\n|----------|--------|-----|\n| 1 | `--vault=` CLI flag | `config.vaultPath` |\n| 2 | `STOA_VAULT_PATH` env var | Falls through to default |\n| 3 | Working directory | `.` |\n\n### Wiki Resolution\n\n| Priority | Source |\n|----------|--------|\n| 1 | `wiki:` argument on tool call |\n| 2 | `--default-wiki=<name>` CLI flag |\n| 3 | `.active-wiki` file at vault root |\n\n### Target Directory\n\nDeployment target directories are specified in the deployment registry entry. The `repo_path` determines where skills are deployed relative to the vault root or an absolute path.\n\n## Error Handling\n\n### Error Scenarios\n\n| Scenario | Behavior | Recovery |\n|----------|----------|----------|\n| Unknown profile ID | `UnknownProfileError` | Provide valid profile ID |\n| Missing canonical move | Throws during drift check | Vault integrity issue |\n| Symlink permission denied | Auto-fallback to `copy` | Transparent |\n| Deployment file locked | Propagates error | Retry |\n| Profile missing `moves` field | Empty deployment | Check profile definition |\n\n### Claim Retraction Integration\n\nThe deployment system integrates with the claims subsystem for agent identity verification:\n\n```typescript\nif (target.authored_by !== as) {\n  throw new Error(\n    `only the original author may retract claim ${claimId}`\n  );\n}\n```\n\nThis ensures deployment operations respect agent authorship boundaries. 资料来源：[src/tools/claim.ts:42-46](https://github.com/BrettNye/stoa/blob/main/src/tools/claim.ts#L42-L46)\n\n## CLI Integration\n\n### Commands\n\n```bash\nstoa --vault=/path/to/vault sync-skills --profile=profile-charizard --wiki=_agents\n```\n\n### Idempotency\n\n- Same profile + same inputs = same output (byte-identical)\n- `source_revision` enables short-circuit of re-deploys\n- Drift detection prevents unnecessary re-synchronization\n\n## Backward Compatibility\n\nThe deployment system maintains backward compatibility across versions:\n\n| Version | Change | Compatibility |\n|---------|--------|----------------|\n| v1.5 | Original schema | Base |\n| v1.6 | Added `actual_mode` | Defaults `actual_mode` to `mode` |\n| v1.7 | Added `runtime`, `source_revision`, `subagent_def_path` | Defaults `runtime` to `target` |\n\n```typescript\n// Back-compat: v1.5 entries lack actual_mode. Default to mode.\nconst actualMode = entry.actual_mode ?? entry.mode;\n\n---\n\n<a id='tool-categories'></a>\n\n## Tool Categories Reference\n\n### 相关页面\n\n相关主题：[Introduction to Stoa](#introduction), [Channels and Claims](#channels-claims)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/core/synthesize.ts](https://github.com/BrettNye/stoa/blob/main/src/core/synthesize.ts)\n- [src/core/syntheses.ts](https://github.com/BrettNye/stoa/blob/main/src/core/syntheses.ts)\n- [src/core/lint-checks/synthesis-debt.ts](https://github.com/BrettNye/stoa/blob/main/src/core/lint-checks/synthesis-debt.ts)\n- [src/core/channel.ts](https://github.com/BrettNye/stoa/blob/main/src/core/channel.ts)\n- [src/core/frontmatter.ts](https://github.com/BrettNye/stoa/blob/main/src/core/frontmatter.ts)\n- [src/transport/stdio.ts](https://github.com/BrettNye/stoa/blob/main/src/transport/stdio.ts)\n- [README.md](https://github.com/BrettNye/stoa/blob/main/README.md)\n</details>\n\n# Tool Categories Reference\n\n## Overview\n\nThe Stoa vault system exposes a collection of MCP (Model Context Protocol) tools organized into logical categories that handle knowledge retrieval, content creation, channel coordination, and linting operations. These tools operate on a vault directory structure where wikis contain typed pages with structured frontmatter and markdown bodies.\n\nThe tool system is designed around a wiki-centric data model where pages are typed (concept, spec, decision, synthesis, etc.), tagged, and optionally scoped to wikis or families. Tools provide both pull-based operations (read, recall) and push-based primitives (wait-for, channel-post), enabling both synchronous queries and event-driven workflows.\n\n资料来源：[README.md:1-50]()\n\n## Tool Category Taxonomy\n\nThe available tools are organized into four primary categories:\n\n| Category | Purpose | Typical Consumer |\n|----------|---------|------------------|\n| **Read — pull primitives** | Query existing vault content | Agents, humans |\n| **Write — content** | Create or modify vault pages | Agents |\n| **Wait — push primitives** | Block until vault events occur | Event-driven workflows |\n| **Coordination** | Cross-instance communication and task management | Multi-agent systems |\n\n资料来源：[README.md:1-50]()\n\n## Read Primitives\n\nRead tools retrieve information from the vault index or direct file access without modifying state.\n\n### Recall\n\nThe `vault.recall` tool searches the vault index for pages matching query parameters. It supports filtering by wiki, type, status, channel, and layer (knowledge vs execution types). Results include relevance-ranked hits with IDs and metadata.\n\n**Query Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `topic` | string | Search query text |\n| `wiki` | string (optional) | Limit to specific wiki |\n| `layer` | `\"all\" \\| \"knowledge\" \\| \"execution\"` | Filter by page type category |\n| `type` | string (optional) | Filter by exact page type |\n| `status` | string (optional) | Filter by page status |\n| `channel` | string (optional) | Filter by channel name |\n| `limit` | number | Maximum results (default 25) |\n\nThe recall mechanism uses tokenized full-text search with stop-word removal and stemming via the Porter stemmer. Results are ranked by relevance.\n\n资料来源：[src/core/index.ts:1-50]()\n\n### Read\n\nThe `vault.read` tool fetches a specific page by ID or path, returning parsed frontmatter and body content. Unlike recall which searches, read is a direct lookup operation.\n\n### Lint\n\nThe `vault.lint` tool runs diagnostic checks against the vault corpus. Lint checks validate structural properties and frontmatter invariants across the index.\n\n**Available Lint Checks:**\n\n| Code | Severity | Description |\n|------|----------|-------------|\n| `SYNTHESIS_DEBT` | warning | Hard-knowledge clusters without synthesis coverage |\n| `CLAIM_WITH_NO_SCOPE` | warn | Claims missing all scope fields |\n| `CROSS_WIKI_LINK_BROKEN` | error | Wikilinks pointing to non-existent pages |\n\nThe lint system distinguishes between Group A rules (fast, frontmatter-only) and Group B rules (claim-file parsing required). Synthesis debt is a structural-property rule that scales with vault growth since it requires no content reads.\n\n资料来源：[src/core/lint-checks/synthesis-debt.ts:1-60]()\n资料来源：[src/core/lint-checks/claim-with-no-scope.ts:1-30]()\n\n## Write Primitives\n\nWrite tools create or modify vault content. These operations are idempotent where possible and preserve manual edits.\n\n### Synthesize\n\nThe `vault.synthesize` tool compiles or refreshes a synthesis page from a set of input pages. Syntheses are mid-tier hub pages that distill clusters of related concepts, specs, or decisions into recallable views.\n\n**Synthesis Modes:**\n\n| Scope | ID Pattern | Wiki | Purpose |\n|-------|------------|------|---------|\n| `topic` | `synthesis-<slug>` | configurable (default: alpha) | General topic synthesis |\n| `memory` | `synthesis-<agent>-memory` | `_agents` | Per-agent memory compilation |\n\n**Frontmatter Template:**\n\n```yaml\nid: synthesis-<slug>\ntitle: \"<topic> — synthesis\"\ntype: synthesis\nwiki: alpha\nstatus: draft\ncreated: <today>\nupdated: <today>\nsummary: \"Synthesis of <N> pages on <topic>\"\ntags: []\nlast_compiled: <today>\nsources:\n  - [[wikis/alpha/concept/page-id-1]]\n  - [[wikis/alpha/spec/page-id-2]]\n```\n\nThe synthesis tool preserves manual edits in protected zones bounded by `<!-- manual_notes:start ... -->` and `<!-- manual_notes:end -->` markers. Re-compiles extract and re-apply content from these zones without losing human-authored prose.\n\n资料来源：[src/core/synthesize.ts:1-100]()\n资料来源：[src/core/frontmatter.ts:1-80]()\n\n### Inbox\n\nThe `vault.inbox` tool captures fleeting thoughts to the active wiki's `inbox/` directory. This provides a low-friction capture mechanism for ideas that don't yet warrant a full typed page.\n\n### New\n\nThe `vault.new` tool creates a typed page from a template. Supported types include:\n\n| Type | Filename Pattern | Notes |\n|------|------------------|-------|\n| `concept` | `concept-<slug>.md` | Knowledge atom |\n| `spec` | `spec-<slug>.md` | Technical specification |\n| `decision` | `decision-YYYY-MM-DD-<slug>.md` | Date-prefixed |\n| `journal` | `journal-YYYY-MM-DD-HHMM-<slug>.md` | Date+time required |\n| `move` | `move-<slug>/SKILL.md` | Directory layout |\n| `map` | `map.md` | Fixed canonical filename |\n| `synthesis` | `synthesis-<slug>.md` | Hub page |\n| `claim` | `claim-<slug>.md` | Assertion with evidence |\n| `idea` | `idea-<slug>.md` | Unvalidated concept |\n| `question` | `question-<slug>.md` | Open inquiry |\n| `source` | `source-<slug>.md` | External citation |\n| `guide` | `guide-<slug>.md` | Procedural documentation |\n\n资料来源：[src/core/ids.ts:1-50]()\n\n### Agent Journal\n\nThe `vault.agent-journal` tool appends a first-person agent reflection at end-of-task. Journals are typed pages with `channel: agent-log` that capture agent decision rationale and state transitions.\n\n## Wait (Push Primitives)\n\nWait tools implement blocking semantics for event-driven workflows, replacing polling with cursor-based catch-up.\n\n| Tool | Semantics |\n|------|-----------|\n| `vault.wait-for` | Block until one matching event lands |\n| `vault.wait-for-any` | Wake on first match across N filters (race) |\n| `vault.wait-for-all` | Wake when all N filters have matched at least once |\n| `vault.wait-for-many` | Bounded batch over a window |\n\nThese primitives use the stdio transport for MCP communication, maintaining a state cache for diffing prior and current vault events.\n\n资料来源：[src/transport/stdio.ts:1-80]()\n资料来源：[src/core/eventbus/state-cache.ts:1-40]()\n\n## Coordination Tools\n\n### Channel Post\n\nThe `vault.channel-post` tool posts to a coordination channel, enabling cross-instance communication. Channels are scoped to wikis and identified by kebab-case names.\n\n**Channel Entry Structure:**\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `id` | string | Page ID |\n| `channel` | string | Channel name |\n| `wiki` | string | Wiki scope |\n| `author` | string | Author identifier |\n| `ts` | ISO date | Timestamp |\n| `excerpt` | string | First 240 chars of body |\n| `pageId` | string | Reference to full page |\n\nThe channel system aggregates journal entries and provides 24-hour activity counts for monitoring.\n\n资料来源：[src/core/channel.ts:1-80]()\n\n### Task Claim\n\nThe `vault.task-claim` tool atomically claims a pending task. Race losers receive an `AlreadyClaimedError`, ensuring exactly-once task assignment in multi-agent scenarios.\n\n### Bootstrap Repo\n\nThe `vault.bootstrap-repo` tool wires a consuming repository with `.mcp.json` and a `CLAUDE.md` fragment, establishing the MCP configuration and agent instructions.\n\n### Sync Skills\n\nThe `vault.sync-skills` tool deploys agent profiles to a target skills directory, maintaining drift detection between canonical vault sources and deployed skill files.\n\n**Drift Detection:**\n\n| Condition | Behavior |\n|-----------|----------|\n| Canonical missing | Throw (vault-integrity bug) |\n| Deployed missing | Emit `{ kind: \"missing\", actual_hash: undefined }` |\n| Hash mismatch | Emit `{ kind: \"hash-mismatch\", actual_hash }` |\n| Hashes match | Omit from report |\n\n资料来源：[src/core/skills-platform.ts:1-80]()\n\n### Reindex\n\nThe `vault.reindex` tool regenerates `_index/` files and per-wiki `index.md`, rebuilding the search index after bulk operations or corruption recovery.\n\n## Synthesis Staleness Tracking\n\nThe system tracks when synthesis pages were last compiled to identify debt. Staleness is computed as the difference between current time and `last_compiled` frontmatter field.\n\n| Metric | Calculation |\n|--------|-------------|\n| `lag_days` | `(now - compiledMs) / MS_PER_DAY` |\n| Filter | `min_lag_days` threshold (default: none) |\n\nThis enables curators to identify syntheses that haven't been refreshed despite upstream changes to their source pages.\n\n资料来源：[src/core/syntheses.ts:1-80]()\n\n## Tool Data Flow\n\n```mermaid\ngraph TD\n    subgraph \"Read Primitives\"\n        R[Recall] -->|index query| I[VaultIndex]\n        RD[Read] -->|direct file| F[Markdown files]\n    end\n    \n    subgraph \"Write Primitives\"\n        S[Synthesize] -->|read prior| F\n        S -->|write| N[New file]\n        IN[Inbox] -->|append| I\n        AJ[Agent Journal] -->|append| C[Channel]\n    end\n    \n    subgraph \"Event System\"\n        W[Wait-for tools] -->|subscribe| E[Event Bus]\n        E -->|state diff| SC[State Cache]\n    end\n    \n    subgraph \"Coordination\"\n        CP[Channel Post] -->|broadcast| C\n        TC[Task Claim] -->|atomic| T[Task Registry]\n    end\n    \n    subgraph \"Validation\"\n        L[Lint] -->|check| CH[Claim Handlers]\n        L -->|check| SD[Synthesis Debt]\n        L -->|check| CW[Claim Scope]\n    end\n    \n    I -.->|rebuild| R\n    F -.->|parse| I\n```\n\n## Page Type Layering\n\nThe system distinguishes between two semantic layers:\n\n| Layer | Types | Role |\n|-------|-------|------|\n| **Knowledge** | concept, spec, decision, synthesis | Durable thinking content |\n| **Execution** | guide, source, idea, question | Procedural and citation |\n\nRecall and synthesis debt checks filter by layer, enabling scope-aware queries that don't mix execution metadata into knowledge graph traversals.\n\n资料来源：[src/core/index.ts:1-50]()\n资料来源：[src/core/lint-checks/synthesis-debt.ts:1-60]()\n\n## Family Resolution\n\nTools can operate at wiki or family scope. Family resolution follows a priority cascade:\n\n```mermaid\ngraph LR\n    A[CLI --family arg] --> B{Match?}\n    B -->|yes| Z[Return family]\n    B -->|no| C[Check .active-family file]\n    C --> D{Exists?}\n    D -->|yes| Z\n    D -->|no| E[Use defaultFamily config]\n    E --> F{Configured?}\n    F -->|yes| Z\n    F -->|no| G[Return null - single wiki]\n```\n\nWhen a wiki is explicitly specified alongside a family argument, the system validates consistency and throws `FamilyMismatchError` on mismatch.\n\n资料来源：[src/core/family.ts:1-80]()\n\n## Wikilink Resolution\n\nTools consume and produce wikilinks in the vault-root absolute form: `[[wikis/<wiki>/<type>/<id>(|alias)]]`. The wikilink extractor is code-fence-aware and handles both body content and frontmatter `related:` arrays.\n\n| Behavior | Scope |\n|----------|-------|\n| Top-level fenced blocks | Stripped |\n| Indented fenced blocks | Preserved |\n| Inline code spans | Preserved |\n| Malformed links | Silently skipped |\n\n资料来源：[src/core/wikilinks.ts:1-50]()\n\n## Configuration\n\nTools read configuration from `vault-mcp.json` in the vault root:\n\n| Key | Description |\n|-----|-------------|\n| `vaultPath` | Absolute path to vault directory |\n| `defaultWiki` | Fallback wiki when unspecified |\n| `defaultFamily` | Fallback family scope |\n\nThe stdio server logs its configuration on startup: `vault-mcp stdio server ready (vault=<path>, default-wiki=<wiki>, default-family=<family>)`.\n\n资料来源：[src/transport/stdio.ts:1-80]()\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：BrettNye/stoa\n\n摘要：发现 7 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：配置坑 - 可能修改宿主 AI 配置。\n\n## 1. 配置坑 · 可能修改宿主 AI 配置\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- 证据：capability.host_targets | github_repo:1229401738 | https://github.com/BrettNye/stoa | host_targets=mcp_host, claude, claude_code\n\n## 2. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:1229401738 | https://github.com/BrettNye/stoa | README/documentation is current enough for a first validation pass.\n\n## 3. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:1229401738 | https://github.com/BrettNye/stoa | last_activity_observed missing\n\n## 4. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:1229401738 | https://github.com/BrettNye/stoa | no_demo; severity=medium\n\n## 5. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:1229401738 | https://github.com/BrettNye/stoa | no_demo; severity=medium\n\n## 6. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:1229401738 | https://github.com/BrettNye/stoa | issue_or_pr_quality=unknown\n\n## 7. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:1229401738 | https://github.com/BrettNye/stoa | release_recency=unknown\n\n<!-- canonical_name: BrettNye/stoa; human_manual_source: deepwiki_human_wiki -->\n",
      "markdown_key": "stoa",
      "pages": "draft",
      "source_refs": [
        {
          "evidence_id": "github_repo:1229401738",
          "kind": "repo",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/BrettNye/stoa"
        },
        {
          "evidence_id": "art_fb38c6ad5653460cb95cb87f1efd1ea3",
          "kind": "docs",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/BrettNye/stoa#readme"
        }
      ],
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "stoa 说明书",
      "toc": [
        "https://github.com/BrettNye/stoa 项目说明书",
        "目录",
        "Introduction to Stoa",
        "Overview",
        "Architecture",
        "Key Features",
        "Tools Reference",
        "CLI Usage",
        "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": "b90a7ec706617767ac3100e0dd0dec1dbc794b6f",
    "repo_inspection_error": null,
    "repo_inspection_files": [
      "package.json",
      "README.md",
      "docs/task-coordination.md",
      "docs/manual-smoke-test.md",
      "docs/agent-memory.md",
      "docs/quickstart.md",
      "docs/common-workflows.md",
      "docs/installation.md",
      "docs/tool-reference.md",
      "docs/wait-for.md",
      "src/config.ts",
      "src/silence-dotenv.ts",
      "src/bin.ts",
      "src/cli/_ctx.ts",
      "src/cli/index.ts",
      "src/tools/list-invites.ts",
      "src/tools/refresh-profile-memory.ts",
      "src/tools/task-create.ts",
      "src/tools/suggest-pokemon.ts",
      "src/tools/inbox.ts",
      "src/tools/channel-tail.ts",
      "src/tools/_resolve-wiki.ts",
      "src/tools/task-list.ts",
      "src/tools/lint.ts",
      "src/tools/channel-post.ts",
      "src/tools/wait-for.ts",
      "src/tools/move-fuse.ts",
      "src/tools/merge-queue.ts",
      "src/tools/read.ts",
      "src/tools/list-platform-profiles.ts",
      "src/tools/new.ts",
      "src/tools/profile-register.ts",
      "src/tools/list-claims.ts",
      "src/tools/sync-skills.ts",
      "src/tools/bootstrap-repo.ts",
      "src/tools/list-wikis.ts",
      "src/tools/task-claim.ts",
      "src/tools/wait-for-any.ts",
      "src/tools/trainer-submit-move.ts",
      "src/tools/wait-for-all.ts"
    ],
    "repo_inspection_verified": true,
    "review_reasons": [
      "community_discussion_evidence_below_public_threshold"
    ],
    "tag_count_ok": true,
    "unsupported_claims": []
  },
  "schema_version": "0.1",
  "user_assets": {
    "ai_context_pack": {
      "asset_id": "ai_context_pack",
      "filename": "AI_CONTEXT_PACK.md",
      "markdown": "# @stoa-mcp/cli - Doramagic AI Context Pack\n\n> 定位：安装前体验与判断资产。它帮助宿主 AI 有一个好的开始，但不代表已经安装、执行或验证目标项目。\n\n## 充分原则\n\n- **充分原则，不是压缩原则**：AI Context Pack 应该充分到让宿主 AI 在开工前理解项目价值、能力边界、使用入口、风险和证据来源；它可以分层组织，但不以最短摘要为目标。\n- **压缩策略**：只压缩噪声和重复内容，不压缩会影响判断和开工质量的上下文。\n\n## 给宿主 AI 的使用方式\n\n你正在读取 Doramagic 为 @stoa-mcp/cli 编译的 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- **命令行启动或安装流程**（需要安装后验证）：项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 证据：`README.md` Claim：`clm_0001` supported 0.86\n\n## 怎么开始\n\n- `npm i -g @stoa-mcp/cli` 证据：`README.md` Claim：`clm_0003` supported 0.86\n\n## 继续前判断卡\n\n- **当前建议**：先做角色匹配试用\n- **为什么**：这个项目更像角色库，核心风险是选错角色或把角色文案当执行能力；先用 Prompt Preview 试角色匹配，再决定是否沙盒导入。\n\n### 30 秒判断\n\n- **现在怎么做**：先做角色匹配试用\n- **最小安全下一步**：先用 Prompt Preview 试角色匹配；满意后再隔离导入\n- **先别相信**：角色质量和任务匹配不能直接相信。\n- **继续会触碰**：角色选择偏差、命令执行、本地环境或项目文件\n\n### 现在可以相信\n\n- **适合人群线索：正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`README.md` Claim：`clm_0002` supported 0.86\n- **能力存在：命令行启动或安装流程**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`README.md` Claim：`clm_0001` supported 0.86\n- **存在 Quick Start / 安装命令线索**（supported）：可以相信项目文档出现过启动或安装入口；不要因此直接在主力环境运行。 证据：`README.md` Claim：`clm_0003` 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 的默认行为。\n- **可安全回滚不能默认相信。**（unverified）：除非项目明确提供卸载和恢复说明，否则必须先在隔离环境验证。\n- **真实安装后是否与用户当前宿主 AI 版本兼容？**（unverified）：兼容性只能通过实际宿主环境验证。\n- **项目输出质量是否满足用户具体任务？**（unverified）：安装前预览只能展示流程和边界，不能替代真实评测。\n\n### 继续会触碰什么\n\n- **角色选择偏差**：用户对任务应该由哪个专家角色处理的判断。 原因：选错角色会让 AI 从错误专业视角回答，浪费时间或误导决策。\n- **命令执行**：包管理器、网络下载、本地插件目录、项目配置或用户主目录。 原因：运行第一条命令就可能产生环境改动；必须先判断是否值得跑。 证据：`README.md`\n- **本地环境或项目文件**：安装结果、插件缓存、项目配置或本地依赖目录。 原因：安装前无法证明写入范围和回滚方式，需要隔离验证。 证据：`README.md`\n- **宿主 AI 上下文**：AI Context Pack、Prompt Preview、Skill 路由、风险规则和项目事实。 原因：导入上下文会影响宿主 AI 后续判断，必须避免把未验证项包装成事实。\n\n### 最小安全下一步\n\n- **先跑 Prompt Preview**：先用交互式试用验证任务画像和角色匹配，不要先导入整套角色库。（适用：任何项目都适用，尤其是输出质量未知时。）\n- **只在隔离目录或测试账号试装**：避免安装命令污染主力宿主 AI、真实项目或用户主目录。（适用：存在命令执行、插件配置或本地写入线索时。）\n- **安装后只验证一个最小任务**：先验证加载、兼容、输出质量和回滚，再决定是否深用。（适用：准备从试用进入真实工作流时。）\n\n### 退出方式\n\n- **保留安装前状态**：记录原始宿主配置和项目状态，后续才能判断是否可恢复。\n- **保留原始角色选择记录**：如果输出偏题，可以回到任务画像阶段重新选择角色，而不是继续沿着错误角色推进。\n- **记录安装命令和写入路径**：没有明确卸载说明时，至少要知道哪些目录或配置需要手动清理。\n- **如果没有回滚路径，不进入主力环境**：不可回滚是继续前阻断项，不应靠信任或运气继续。\n\n## 哪些只能预览\n\n- 解释项目适合谁和能做什么\n- 基于项目文档演示典型对话流程\n- 帮助用户判断是否值得安装或继续研究\n\n## 哪些必须安装后验证\n\n- 真实安装 Skill、插件或 CLI\n- 执行脚本、修改本地文件或访问外部服务\n- 验证真实输出质量、性能和兼容性\n\n## 边界与风险判断卡\n\n- **把安装前预览误认为真实运行**：用户可能高估项目已经完成的配置、权限和兼容性验证。 处理方式：明确区分 prompt_preview_can_do 与 runtime_required。 Claim：`clm_0004` inferred 0.45\n- **命令执行会修改本地环境**：安装命令可能写入用户主目录、宿主插件目录或项目配置。 处理方式：先在隔离环境或测试账号中运行。 证据：`README.md` Claim：`clm_0005` 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- **命令行启动或安装流程**：先说明这是安装后验证能力，再给出安装前检查清单。 边界：必须真实安装或运行后验证。 证据：`README.md` Claim：`clm_0001` supported 0.86\n\n### 上下文规模\n\n- 文件总数：469\n- 重要文件覆盖：35/469\n- 证据索引条目：35\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请基于 @stoa-mcp/cli 的 AI Context Pack，先问我 3 个必要问题，然后判断它是否适合我的任务。回答必须包含：适合谁、能做什么、不能做什么、是否值得安装、证据来自哪里。所有项目事实必须引用 evidence_refs、source_paths 或 claim_id。\n```\n\n### 安装前体验\n\n- 目标：让用户在安装前感受核心工作流，同时避免把预览包装成真实能力或营销承诺。\n- 预期输出：一段带边界标签的体验剧本、安装后验证清单和谨慎建议；不含真实运行承诺或强营销表述。\n\n```text\n请把 @stoa-mcp/cli 当作安装前体验资产，而不是已安装工具或真实运行环境。\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请基于 @stoa-mcp/cli 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。\n```\n\n\n## 角色 / Skill 索引\n\n- 共索引 22 个角色 / Skill / 项目文档条目。\n\n- **Stoa**（project_doc）：Persistent shared memory for AI coding agents. Your sessions stop forgetting things across days, repos, and machines. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`README.md`\n- **Vault schema fixture**（project_doc）：Fixture vault for integration tests. Mirrors v1 conventions but smaller. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`tests/fixtures/test-vault/CLAUDE.md`\n- **alpha — wiki conventions**（project_doc）：Mode: idea-map Scope: fixture for tests 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`tests/fixtures/test-vault/wikis/alpha/CLAUDE.md`\n- **beta — wiki conventions**（project_doc）：Mode: project-doc Scope: fixture demonstrating cross-wiki references 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`tests/fixtures/test-vault/wikis/beta/CLAUDE.md`\n- **agent-memory: identity-keyed working context**（project_doc）：agent-memory: identity-keyed working context 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/agent-memory.md`\n- **Common workflows**（project_doc）：Task-driven recipes for the things you'll actually do once stoa is installed. Each scenario is independent — skim the table of contents and skip to what you need. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/common-workflows.md`\n- **Installation**（project_doc）：- Node.js 20 or newer. Check with node --version . - A vault directory — a folder containing a CLAUDE.md at its root and optionally an index/ subdirectory. The index/ is created automatically on first reindex if missing. If you don't have a vault yet, create an empty folder and a one-line CLAUDE.md to start. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/installation.md`\n- **Manual cross-repo smoke test**（project_doc）：Run this once per release to verify the cross-repo workflow end-to-end. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/manual-smoke-test.md`\n- **Quickstart — your first useful recall in 5 minutes**（project_doc）：Quickstart — your first useful recall in 5 minutes 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/quickstart.md`\n- **Task coordination**（project_doc）：Stoa exposes a small set of tools for distributing units of work across agents or sessions. This page is the substrate contract: how task pages are shaped, how the state machine works, and how concurrent claims are arbitrated. It does not prescribe how any particular consumer should orchestrate work on top of it. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/task-coordination.md`\n- **Tool reference**（project_doc）：Alphabetical reference for every MCP tool exposed by stoa. All tools are registered under the vault. namespace and dispatched via the stdio transport or, in tests, the shared callTool harness . Tools requiring a wiki accept an optional wiki: field; resolution order is explicit arg → --default-wiki MCP flag → .active-wiki file → error see src/tools/ resolve-wiki.ts . Stadium tools instead use resolveTrainerContext se… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/tool-reference.md`\n- **wait-for: push primitives**（project_doc）：Cross-process event coordination over the local filesystem. Four MCP tools — vault.wait-for , vault.wait-for-any , vault.wait-for-all , vault.wait-for-many — let an agent register a single bounded wait that resolves on the next matching journal or task event, instead of polling vault.channel-tail on a timer. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/wait-for.md`\n- **claim page template — instantiated by vault.new claim \" \" .**（project_doc）：<!-- Claim body: 1-3 sentences explaining the assertion. Keep prose under ~280 characters when possible — this is what vault.sync-skills will render into the deployed SKILL.md, and longer prose gets truncated or wraps awkwardly in agent context windows. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`tests/fixtures/templates/claim.md`\n- **Wikis**（project_doc）：- alpha mode: idea-map — fixture wiki for tests - beta mode: project-doc — fixture wiki demonstrating cross-wiki links 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`tests/fixtures/test-vault/REGISTRY.md`\n- **Concept Bar**（project_doc）： 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`tests/fixtures/test-vault/wikis/alpha/concepts/concept-bar.md`\n- **Concept Foo**（project_doc）：The foo concept is fundamental to bar. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`tests/fixtures/test-vault/wikis/alpha/concepts/concept-foo.md`\n- **Decision 2026 04 01 Pick Foo**（project_doc）：After comparing options we picked foo. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`tests/fixtures/test-vault/wikis/alpha/decisions/decision-2026-04-01-pick-foo.md`\n- **alpha**（project_doc）： 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`tests/fixtures/test-vault/wikis/alpha/map.md`\n- **Synthesis Foo Vs Bar**（project_doc）：Compared foo and bar; foo wins for simplicity, bar wins for power. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`tests/fixtures/test-vault/wikis/alpha/synthesis/synthesis-foo-vs-bar.md`\n- **Task Implement Baz**（project_doc）： 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`tests/fixtures/test-vault/wikis/alpha/tasks/task-implement-baz.md`\n- **Concept Quux**（project_doc）： 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`tests/fixtures/test-vault/wikis/beta/concepts/concept-quux.md`\n- **beta**（project_doc）： 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`tests/fixtures/test-vault/wikis/beta/map.md`\n\n## 证据索引\n\n- 共索引 35 条证据。\n\n- **Stoa**（documentation）：Persistent shared memory for AI coding agents. Your sessions stop forgetting things across days, repos, and machines. 证据：`README.md`\n- **Package**（package_manifest）：{ \"name\": \"@stoa-mcp/cli\", \"version\": \"0.1.0\", \"description\": \"Persistent shared memory for AI coding agents MCP server + CLI \", \"type\": \"module\", \"license\": \"FSL-1.1-MIT\", \"bin\": { \"stoa\": \"./dist/bin.js\" }, \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/BrettNye/stoa.git\" }, \"homepage\": \"https://github.com/BrettNye/stoa readme\", \"bugs\": { \"url\": \"https://github.com/BrettNye/stoa/issues\" }, \"keywords\": \"mcp\", \"model-context-protocol\", \"claude\", \"claude-code\", \"memory\", \"knowledge-management\", \"ai-agents\" , \"files\": \"dist\", \"README.md\" , \"scripts\": { \"build\": \"tsc\", \"dev\": \"tsx src/bin.ts\", \"test\": \"vitest run\", \"test:watch\": \"vitest\", \"lint\": \"eslint src tests\" }, \"dependenc… 证据：`package.json`\n- **Vault schema fixture**（documentation）：Fixture vault for integration tests. Mirrors v1 conventions but smaller. 证据：`tests/fixtures/test-vault/CLAUDE.md`\n- **alpha — wiki conventions**（documentation）：Mode: idea-map Scope: fixture for tests 证据：`tests/fixtures/test-vault/wikis/alpha/CLAUDE.md`\n- **beta — wiki conventions**（documentation）：Mode: project-doc Scope: fixture demonstrating cross-wiki references 证据：`tests/fixtures/test-vault/wikis/beta/CLAUDE.md`\n- **Functional Source License, Version 1.1, MIT Future License**（source_file）：Functional Source License, Version 1.1, MIT Future License 证据：`LICENSE`\n- **agent-memory: identity-keyed working context**（documentation）：agent-memory: identity-keyed working context 证据：`docs/agent-memory.md`\n- **Common workflows**（documentation）：Task-driven recipes for the things you'll actually do once stoa is installed. Each scenario is independent — skim the table of contents and skip to what you need. 证据：`docs/common-workflows.md`\n- **Installation**（documentation）：- Node.js 20 or newer. Check with node --version . - A vault directory — a folder containing a CLAUDE.md at its root and optionally an index/ subdirectory. The index/ is created automatically on first reindex if missing. If you don't have a vault yet, create an empty folder and a one-line CLAUDE.md to start. 证据：`docs/installation.md`\n- **Manual cross-repo smoke test**（documentation）：Run this once per release to verify the cross-repo workflow end-to-end. 证据：`docs/manual-smoke-test.md`\n- **Quickstart — your first useful recall in 5 minutes**（documentation）：Quickstart — your first useful recall in 5 minutes 证据：`docs/quickstart.md`\n- **Task coordination**（documentation）：Stoa exposes a small set of tools for distributing units of work across agents or sessions. This page is the substrate contract: how task pages are shaped, how the state machine works, and how concurrent claims are arbitrated. It does not prescribe how any particular consumer should orchestrate work on top of it. 证据：`docs/task-coordination.md`\n- **Tool reference**（documentation）：Alphabetical reference for every MCP tool exposed by stoa. All tools are registered under the vault. namespace and dispatched via the stdio transport or, in tests, the shared callTool harness . Tools requiring a wiki accept an optional wiki: field; resolution order is explicit arg → --default-wiki MCP flag → .active-wiki file → error see src/tools/ resolve-wiki.ts . Stadium tools instead use resolveTrainerContext see src/core/resolve-trainer-context.ts : explicit trainer arg → STADIUM TRAINER env → ~/.vault/stadium.toml active= → error . 证据：`docs/tool-reference.md`\n- **wait-for: push primitives**（documentation）：Cross-process event coordination over the local filesystem. Four MCP tools — vault.wait-for , vault.wait-for-any , vault.wait-for-all , vault.wait-for-many — let an agent register a single bounded wait that resolves on the next matching journal or task event, instead of polling vault.channel-tail on a timer. 证据：`docs/wait-for.md`\n- **claim page template — instantiated by vault.new claim \" \" .**（documentation）：<!-- Claim body: 1-3 sentences explaining the assertion. Keep prose under ~280 characters when possible — this is what vault.sync-skills will render into the deployed SKILL.md, and longer prose gets truncated or wraps awkwardly in agent context windows. 证据：`tests/fixtures/templates/claim.md`\n- **.Eslintrc**（structured_config）：{ \"parser\": \"@typescript-eslint/parser\", \"plugins\": \"@typescript-eslint\" , \"extends\": \"eslint:recommended\", \"plugin:@typescript-eslint/recommended\" , \"rules\": { \"@typescript-eslint/no-unused-vars\": \"warn\", { \"argsIgnorePattern\": \"^ \", \"varsIgnorePattern\": \"^ \" } , \"@typescript-eslint/no-explicit-any\": \"off\", \"@typescript-eslint/no-unsafe-function-type\": \"off\", \"no-useless-escape\": \"off\", \"no-control-regex\": \"off\", \"no-constant-condition\": \"off\", \"prefer-const\": \"warn\" }, \"overrides\": { \"files\": \"src/transport/ui/static/ / .js\" , \"env\": { \"browser\": true } } } 证据：`.eslintrc.json`\n- **Tsconfig**（structured_config）：{ \"compilerOptions\": { \"target\": \"ES2022\", \"module\": \"ESNext\", \"moduleResolution\": \"bundler\", \"outDir\": \"./dist\", \"rootDir\": \"./src\", \"strict\": true, \"esModuleInterop\": true, \"skipLibCheck\": true, \"forceConsistentCasingInFileNames\": true, \"resolveJsonModule\": true, \"declaration\": true, \"sourceMap\": true }, \"include\": \"src/ / \" , \"exclude\": \"node modules\", \"dist\", \"tests\" } 证据：`tsconfig.json`\n- **.gitignore**（source_file）：node modules/ dist/ .log .DS Store coverage/ 证据：`.gitignore`\n- **statusline-pokemon.ps1 — emit a one-line statusline summary for the active vault Pokemon.**（source_file）：statusline-pokemon.ps1 — emit a one-line statusline summary for the active vault Pokemon. Usage: $env:STOA VAULT PATH= ; $env:VAULT POKEMON= ; .\\statusline-pokemon.ps1 证据：`scripts/statusline-pokemon.ps1`\n- **!/usr/bin/env bash**（source_file）：!/usr/bin/env bash statusline-pokemon.sh — emit a one-line statusline summary for the active vault Pokemon. Usage: env STOA VAULT PATH= VAULT POKEMON= statusline-pokemon.sh Wire into Claude Code statusline: \"statusLine\": { \"type\": \"command\", \"command\": \"bash /path/to/statusline-pokemon.sh\" } 证据：`scripts/statusline-pokemon.sh`\n- **!/usr/bin/env node**（source_file）：!/usr/bin/env node import \"./silence-dotenv.js\"; // MUST be first — see comment in that file import { parseConfig, ConfigError } from \"./config.js\"; import { setCtx } from \"./cli/ ctx.js\"; import { buildCli } from \"./cli/index.js\"; import { startStdio } from \"./transport/stdio.js\"; 证据：`src/bin.ts`\n- **Config**（source_file）：import { resolve } from \"node:path\"; import { z } from \"zod\"; 证据：`src/config.ts`\n- **Silence Dotenv**（source_file）：// Side-effect-only module. MUST be imported FIRST in bin.ts and any other // entrypoint — before any module that transitively pulls in natural . // // The natural package depends on dotenv@17+ , which prints unsolicited // \"tip:\" advertisements to stdout on import. That corrupts MCP's stdio // JSON-RPC framing and prevents clients from connecting. Setting // DOTENV CONFIG QUIET=true before dotenv loads suppresses the tips. // // ESM evaluates imports in source order, so as long as this module is // imported first, the env var is in place before natural's transitive // dotenv module runs its top-level code. process.env.DOTENV CONFIG QUIET = \"true\"; 证据：`src/silence-dotenv.ts`\n- **Wikis**（documentation）：- alpha mode: idea-map — fixture wiki for tests - beta mode: project-doc — fixture wiki demonstrating cross-wiki links 证据：`tests/fixtures/test-vault/REGISTRY.md`\n- **Concept Bar**（documentation）：--- id: concept-bar title: \"Bar concept\" type: concept wiki: alpha status: active created: 2026-04-01 updated: 2026-04-28 summary: \"The bar entity.\" tags: bar, testing --- Bar depends on foo. 证据：`tests/fixtures/test-vault/wikis/alpha/concepts/concept-bar.md`\n- **Concept Foo**（documentation）：The foo concept is fundamental to bar. 证据：`tests/fixtures/test-vault/wikis/alpha/concepts/concept-foo.md`\n- **Decision 2026 04 01 Pick Foo**（documentation）：After comparing options we picked foo. 证据：`tests/fixtures/test-vault/wikis/alpha/decisions/decision-2026-04-01-pick-foo.md`\n- **alpha**（documentation）：--- id: map-alpha title: \"alpha map\" type: map wiki: alpha status: active created: 2026-04-01 updated: 2026-04-28 summary: \"Map of the alpha wiki for fixture testing.\" --- alpha Fixture wiki content. 证据：`tests/fixtures/test-vault/wikis/alpha/map.md`\n- **Synthesis Foo Vs Bar**（documentation）：Compared foo and bar; foo wins for simplicity, bar wins for power. 证据：`tests/fixtures/test-vault/wikis/alpha/synthesis/synthesis-foo-vs-bar.md`\n- **Task Implement Baz**（documentation）：--- id: task-implement-baz title: \"Implement baz handler\" type: task wiki: alpha status: pending created: 2026-04-28 updated: 2026-04-28 summary: \"Implement the baz request handler.\" --- Add a handler for baz requests. 证据：`tests/fixtures/test-vault/wikis/alpha/tasks/task-implement-baz.md`\n- **Concept Quux**（documentation）：--- id: concept-quux title: \"Quux concept\" type: concept wiki: beta status: active created: 2026-04-01 updated: 2026-04-28 summary: \"Quux is a downstream concept; alpha cites this.\" tags: quux, testing --- Quux extends foo and bar. 证据：`tests/fixtures/test-vault/wikis/beta/concepts/concept-quux.md`\n- **beta**（documentation）：--- id: map-beta title: \"beta map\" type: map wiki: beta status: active created: 2026-04-01 updated: 2026-04-28 summary: \"Map of the beta wiki.\" --- beta 证据：`tests/fixtures/test-vault/wikis/beta/map.md`\n- **Helpers**（source_file）：// vault-mcp/tests/helpers.ts // // Shared test helpers for the claims plan Plan 1 test suites. Hoisted per // the plan's S7 test-helper hoisting + H8 import resolution hazards: 13 // downstream tasks import from this file, so it lives upstream of all of // them in the DAG. See wikis/ meta/plans/2026-05-02-vault-mcp-claims-plan- // 1-foundation-dag.md §task-test-helpers for the contract. // // Conventions: // - Temp vaults under os.tmpdir with mkdtempSync synchronous because // we want a stable directory name before any async work begins . // - Frontmatter is serialized via JSON.stringify per value to dodge YAML // escaping pitfalls matches the v1.5 friction T3-5 lesson on ISO date // quoti… 证据：`tests/helpers.ts`\n- **Setup**（source_file）：import { mkdtempSync } from \"node:fs\"; import { join } from \"node:path\"; import { tmpdir } from \"node:os\"; 证据：`tests/setup.ts`\n- **Vitest.Config**（source_file）：import { defineConfig } from \"vitest/config\"; 证据：`vitest.config.ts`\n\n## 宿主 AI 必须遵守的规则\n\n- **把本资产当作开工前上下文，而不是运行环境。**：AI Context Pack 只包含证据化项目理解，不包含目标项目的可执行状态。 证据：`README.md`, `package.json`, `tests/fixtures/test-vault/CLAUDE.md`\n- **回答用户时区分可预览内容与必须安装后才能验证的内容。**：安装前体验的消费者价值来自降低误装和误判，而不是伪装成真实运行。 证据：`README.md`, `package.json`, `tests/fixtures/test-vault/CLAUDE.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\n下面内容用于强化 Repomix/AI Context Pack 主体。Human Manual 只提供阅读骨架；踩坑日志会被转成宿主 AI 必须遵守的工作约束。\n\n## Human Manual 骨架\n\n使用规则：这里只是项目阅读路线和显著性信号，不是事实权威。具体事实仍必须回到 repo evidence / Claim Graph。\n\n宿主 AI 硬性规则：\n- 不得把页标题、章节顺序、摘要或 importance 当作项目事实证据。\n- 解释 Human Manual 骨架时，必须明确说它只是阅读路线/显著性信号。\n- 能力、安装、兼容性、运行状态和风险判断必须引用 repo evidence、source path 或 Claim Graph。\n\n- **Introduction to Stoa**：importance `high`\n  - source_paths: README.md, src/core/profiles.ts, src/core/pokemon.ts\n- **Core Concepts and Vocabulary**：importance `high`\n  - source_paths: src/core/pokemon.ts, src/core/tasks.ts, src/core/channel.ts, src/core/profiles.ts\n- **Architecture and Design**：importance `high`\n  - source_paths: src/tools/index.ts, src/cli/index.ts, src/core/index.ts, src/transport/stdio.ts, src/transport/http.ts\n- **Event Bus System**：importance `medium`\n  - source_paths: src/core/eventbus/watcher.ts, src/core/eventbus/bus.ts, src/core/eventbus/match.ts, src/core/eventbus/types.ts, src/tools/wait-for.ts\n- **Agent Profiles and Evolution**：importance `high`\n  - source_paths: src/core/profiles.ts, src/core/evolution.ts, src/core/evolution-claims.ts, src/tools/evolve-profile.ts, src/tools/refresh-profile-memory.ts\n- **Task Workflow System**：importance `high`\n  - source_paths: src/core/tasks.ts, src/core/task-readiness.ts, src/core/claim-clustering.ts, src/tools/task-claim.ts, src/tools/task-create.ts\n- **Channels and Claims**：importance `medium`\n  - source_paths: src/core/channel.ts, src/core/claims.ts, src/core/claims-index.ts, src/core/decay.ts, src/tools/channel-post.ts\n- **Runtime Adapters**：importance `medium`\n  - source_paths: src/core/runtime-adapters/types.ts, src/core/runtime-adapters/registry.ts, src/core/runtime-adapters/claude-code.ts, src/core/subagent-protocol.ts, src/core/subagent-intent.ts\n\n## Repo Inspection Evidence / 源码检查证据\n\n- repo_clone_verified: true\n- repo_inspection_verified: true\n- repo_commit: `b90a7ec706617767ac3100e0dd0dec1dbc794b6f`\n- inspected_files: `package.json`, `README.md`, `docs/task-coordination.md`, `docs/manual-smoke-test.md`, `docs/agent-memory.md`, `docs/quickstart.md`, `docs/common-workflows.md`, `docs/installation.md`, `docs/tool-reference.md`, `docs/wait-for.md`, `src/config.ts`, `src/silence-dotenv.ts`, `src/bin.ts`, `src/cli/_ctx.ts`, `src/cli/index.ts`, `src/tools/list-invites.ts`, `src/tools/refresh-profile-memory.ts`, `src/tools/task-create.ts`, `src/tools/suggest-pokemon.ts`, `src/tools/inbox.ts`\n\n宿主 AI 硬性规则：\n- 没有 repo_clone_verified=true 时，不得声称已经读过源码。\n- 没有 repo_inspection_verified=true 时，不得把 README/docs/package 文件判断写成事实。\n- 没有 quick_start_verified=true 时，不得声称 Quick Start 已跑通。\n\n## Doramagic Pitfall Constraints / 踩坑约束\n\n这些规则来自 Doramagic 发现、验证或编译过程中的项目专属坑点。宿主 AI 必须把它们当作工作约束，而不是普通说明文字。\n\n### Constraint 1: 可能修改宿主 AI 配置\n\n- Trigger: 项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- Host AI rule: 列出会写入的配置文件、目录和卸载/回滚步骤。\n- Why it matters: 安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- Evidence: capability.host_targets | github_repo:1229401738 | https://github.com/BrettNye/stoa | host_targets=mcp_host, claude, claude_code\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 2: 能力判断依赖假设\n\n- Trigger: README/documentation is current enough for a first validation pass.\n- Host AI rule: 将假设转成下游验证清单。\n- Why it matters: 假设不成立时，用户拿不到承诺的能力。\n- Evidence: capability.assumptions | github_repo:1229401738 | https://github.com/BrettNye/stoa | README/documentation is current enough for a first validation pass.\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 3: 维护活跃度未知\n\n- Trigger: 未记录 last_activity_observed。\n- Host AI rule: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Why it matters: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Evidence: evidence.maintainer_signals | github_repo:1229401738 | https://github.com/BrettNye/stoa | last_activity_observed missing\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 4: 下游验证发现风险项\n\n- Trigger: no_demo\n- Host AI rule: 进入安全/权限治理复核队列。\n- Why it matters: 下游已经要求复核，不能在页面中弱化。\n- Evidence: downstream_validation.risk_items | github_repo:1229401738 | https://github.com/BrettNye/stoa | no_demo; severity=medium\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 5: 存在评分风险\n\n- Trigger: no_demo\n- Host AI rule: 把风险写入边界卡，并确认是否需要人工复核。\n- Why it matters: 风险会影响是否适合普通用户安装。\n- Evidence: risks.scoring_risks | github_repo:1229401738 | https://github.com/BrettNye/stoa | no_demo; severity=medium\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 6: issue/PR 响应质量未知\n\n- Trigger: issue_or_pr_quality=unknown。\n- Host AI rule: 抽样最近 issue/PR，判断是否长期无人处理。\n- Why it matters: 用户无法判断遇到问题后是否有人维护。\n- Evidence: evidence.maintainer_signals | github_repo:1229401738 | https://github.com/BrettNye/stoa | issue_or_pr_quality=unknown\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 7: 发布节奏不明确\n\n- Trigger: release_recency=unknown。\n- Host AI rule: 确认最近 release/tag 和 README 安装命令是否一致。\n- Why it matters: 安装命令和文档可能落后于代码，用户踩坑概率升高。\n- Evidence: evidence.maintainer_signals | github_repo:1229401738 | https://github.com/BrettNye/stoa | release_recency=unknown\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n",
      "summary": "给宿主 AI 的上下文和工作边界。",
      "title": "AI Context Pack / 带给我的 AI"
    },
    "boundary_risk_card": {
      "asset_id": "boundary_risk_card",
      "filename": "BOUNDARY_RISK_CARD.md",
      "markdown": "# Boundary & Risk Card / 安装前决策卡\n\n项目：BrettNye/stoa\n\n## Doramagic 试用结论\n\n当前结论：可以进入发布前推荐检查；首次使用仍应从最小权限、临时目录和可回滚配置开始。\n\n## 用户现在可以做\n\n- 可以先阅读 Human Manual，理解项目目的和主要工作流。\n- 可以复制 Prompt Preview 做安装前体验；这只验证交互感，不代表真实运行。\n- 可以把官方 Quick Start 命令放到隔离环境中验证，不要直接进主力环境。\n\n## 现在不要做\n\n- 不要把 Prompt Preview 当成项目实际运行结果。\n- 不要把 metadata-only validation 当成沙箱安装验证。\n- 不要把未验证能力写成“已支持、已跑通、可放心安装”。\n- 不要在首次试用时交出生产数据、私人文件、真实密钥或主力配置目录。\n\n## 安装前检查\n\n- 宿主 AI 是否匹配：mcp_host, claude, claude_code\n- 官方安装入口状态：已发现官方入口\n- 是否在临时目录、临时宿主或容器中验证：必须是\n- 是否能回滚配置改动：必须能\n- 是否需要 API Key、网络访问、读写文件或修改宿主配置：未确认前按高风险处理\n- 是否记录了安装命令、实际输出和失败日志：必须记录\n\n## 当前阻塞项\n\n- review_required: community_discussion_evidence_below_public_threshold\n\n## 项目专属踩坑\n\n- 可能修改宿主 AI 配置（medium）：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 能力判断依赖假设（medium）：假设不成立时，用户拿不到承诺的能力。 建议检查：将假设转成下游验证清单。\n- 维护活跃度未知（medium）：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 下游验证发现风险项（medium）：下游已经要求复核，不能在页面中弱化。 建议检查：进入安全/权限治理复核队列。\n- 存在评分风险（medium）：风险会影响是否适合普通用户安装。 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n\n## 风险与权限提示\n\n- no_demo: medium\n\n## 证据缺口\n\n- 暂未发现结构化证据缺口。\n",
      "summary": "安装、权限、验证和推荐前风险。",
      "title": "Boundary & Risk Card / 边界与风险卡"
    },
    "human_manual": {
      "asset_id": "human_manual",
      "filename": "HUMAN_MANUAL.md",
      "markdown": "# https://github.com/BrettNye/stoa 项目说明书\n\n生成时间：2026-05-16 00:38:52 UTC\n\n## 目录\n\n- [Introduction to Stoa](#introduction)\n- [Core Concepts and Vocabulary](#concepts-vocabulary)\n- [Architecture and Design](#architecture-design)\n- [Event Bus System](#event-bus-system)\n- [Agent Profiles and Evolution](#profiles-evolution)\n- [Task Workflow System](#task-workflow)\n- [Channels and Claims](#channels-claims)\n- [Runtime Adapters](#runtime-adapters)\n- [Sync Agents and Skills](#sync-agents-skills)\n- [Tool Categories Reference](#tool-categories)\n\n<a id='introduction'></a>\n\n## Introduction to Stoa\n\n### 相关页面\n\n相关主题：[Core Concepts and Vocabulary](#concepts-vocabulary), [Architecture and Design](#architecture-design)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/BrettNye/stoa/blob/main/README.md)\n- [src/core/profiles.ts](https://github.com/BrettNye/stoa/blob/main/src/core/profiles.ts)\n- [src/core/pokemon.ts](https://github.com/BrettNye/stoa/blob/main/src/core/pokemon.ts)\n- [src/core/synthesize.ts](https://github.com/BrettNye/stoa/blob/main/src/core/synthesize.ts)\n- [src/core/index.ts](https://github.com/BrettNye/stoa/blob/main/src/core/index.ts)\n- [src/core/wikilinks.ts](https://github.com/BrettNye/stoa/blob/main/src/core/wikilinks.ts)\n- [src/core/pages.ts](https://github.com/BrettNye/stoa/blob/main/src/core/pages.ts)\n- [src/core/pokeapi.ts](https://github.com/BrettNye/stoa/blob/main/src/core/pokeapi.ts)\n</details>\n\n# Introduction to Stoa\n\nStoa is a vault-based knowledge management system powered by MCP (Model Context Protocol). It provides a structured wiki infrastructure for organizing, synthesizing, and retrieving information across multiple knowledge domains. The system combines a file-based vault architecture with intelligent tooling for content discovery, cross-referencing, and collaborative agent workflows.\n\n## Overview\n\nStoa operates as an MCP server that manages a hierarchical vault of wiki pages. The vault structure organizes content into wikis, each containing typed pages (concepts, guides, decisions, journals, etc.) with frontmatter metadata and markdown body content.\n\nThe system provides:\n\n- **File-based storage**: All content stored as markdown files with YAML frontmatter\n- **MCP tooling**: Standardized tools for read, write, search, and coordination operations\n- **Multi-wiki support**: Independent wiki spaces with cross-wiki linking via wikilinks\n- **Agent profiles**: Named agent identities with associated skills and capabilities\n- **Synthesis engine**: Automated compilation of related pages into synthesized summaries\n\n## Architecture\n\n### Core Components\n\n```mermaid\ngraph TD\n    subgraph \"Transport Layer\"\n        STDIO[Stdio Transport]\n        HTTP[HTTP Transport]\n    end\n    \n    subgraph \"Core Engine\"\n        IDX[Index Engine]\n        SYN[Synthesis Engine]\n        WL[Wikilink Parser]\n        FM[Frontmatter Handler]\n    end\n    \n    subgraph \"Tools\"\n        RECALL[Recall - Search]\n        INBOX[Inbox - Capture]\n        NEW[New - Create]\n        SYNTH[Synthesize]\n        CLAIM[Claims]\n        TASKS[Tasks]\n    end\n    \n    subgraph \"Platform Integration\"\n        POKEAPI[PokeAPI Client]\n        STADIUM[Stadium Platform]\n        SKILLS[Skills Platform]\n    end\n    \n    STDIO --> SERVER[MCP Server]\n    HTTP --> SERVER\n    SERVER --> TOOLS[Tools Registry]\n    TOOLS --> CORE[Core Engine]\n    CORE --> IDX\n    CORE --> SYN\n    CORE --> WL\n    CORE --> FM\n    TOOLS --> PLATFORM[Platform APIs]\n```\n\n### Page Types\n\nThe system supports multiple page types with distinct conventions:\n\n| Type | Filename Pattern | Description |\n|------|------------------|-------------|\n| `concept` | `concept-<slug>.md` | Knowledge concepts and definitions |\n| `guide` | `guide-<slug>.md` | Procedural how-to documentation |\n| `decision` | `decision-YYYY-MM-DD-<slug>.md` | Decision records with date prefix |\n| `journal` | `journal-YYYY-MM-DD-HHMM-<slug>.md` | Time-stamped reflection entries |\n| `move` | `move-<slug>/SKILL.md` | Directory-based skill/move definitions |\n| `map` | `map.md` | Fixed filename for wiki maps |\n| `profile` | `profile-<slug>.md` | Agent profiles |\n| `synthesis` | `synthesis-<slug>.md` | Compiled summaries of related pages |\n\n资料来源：[src/core/ids.ts:25-35]()\n\n### Vault Structure\n\n```mermaid\ngraph TD\n    VAULT[Vault Root]\n    WIKIS[wikis/]\n    META[_meta/]\n    INDEX[_index/]\n    AGENTS[wikis/_agents/]\n    \n    VAULT --> WIKIS\n    VAULT --> META\n    VAULT --> INDEX\n    VAULT --> AGENTS\n    \n    WIKIS --> WIKI1[alpha/]\n    WIKIS --> WIKI2[beta/]\n    \n    WIKI1 --> TYPES1[concepts/ guides/ decisions/]\n    WIKI2 --> TYPES2[concepts/ guides/ synthesis/]\n    \n    AGENTS --> PROFILES[profiles/]\n    AGENTS --> MOVES[moves/]\n    AGENTS --> JOURNALS[journal/]\n```\n\n## Key Features\n\n### Recall (Search)\n\nThe `vault.recall` tool provides full-text search across the vault using an inverted token index. Search results are filtered by topic, wiki, layer (knowledge vs execution), and other metadata criteria.\n\nThe indexing process:\n1. Tokenizes page content using a Porter stemmer\n2. Filters stop words (the, and, of, a, an, in, to, is, etc.)\n3. Builds inverted index mapping tokens to page IDs\n4. Supports frontmatter fields in search scope\n\n```typescript\n// Tokenization logic from index.ts\nconst UPSERT_STOP_WORDS = new Set([\n  \"the\",\"and\",\"of\",\"a\",\"an\",\"in\",\"to\",\"is\",\"for\",\"on\",\"with\",\"as\",\"at\",\"by\",\"or\",\"be\",\n  \"this\",\"that\",\"it\",\"from\",\"are\",\"was\",\"were\",\"not\",\"but\",\"if\"\n]);\n\nfunction upsertTokenize(text: string): string[] {\n  return text.toLowerCase()\n    .replace(/[^a-z0-9\\s]/g, \" \")\n    .split(/\\s+/)\n    .filter(t => t.length > 1 && !UPSERT_STOP_WORDS.has(t))\n    .map(t => upsertStemmer.stem(t));\n}\n```\n\n资料来源：[src/core/index.ts:45-52]()\n\n### Synthesis Engine\n\nThe synthesis feature compiles related pages into structured summaries. The engine:\n\n1. Discovers input pages by topic recall or explicit agent memory\n2. Generates frontmatter with metadata, sources, and tags\n3. Creates marker-bounded content regions for idempotent re-rendering\n4. Supports per-agent memory synthesis scoped to `wikis/_agents`\n\n```mermaid\ngraph LR\n    INPUT[Input Pages] --> RECALL[Recall Query]\n    RECALL --> FILTER[Filter by Topic/Wiki/Agent]\n    FILTER --> BUILD[Build Synthesis Frontmatter]\n    BUILD --> RENDER[Render Marker-Bounded Content]\n    RENDER --> OUTPUT[Synthesis Page]\n```\n\nThe synthesis frontmatter includes:\n\n| Field | Description |\n|-------|-------------|\n| `id` | Unique synthesis identifier |\n| `title` | Synthesis title with topic/agent context |\n| `type` | Always \"synthesis\" |\n| `wiki` | Target wiki namespace |\n| `status` | Draft status |\n| `sources` | Array of wikilinks to contributing pages |\n| `last_compiled` | ISO date of last synthesis refresh |\n\n资料来源：[src/core/synthesize.ts:1-85]()\n\n### Wikilink System\n\nStoa uses vault-root absolute wikilinks for cross-page references:\n\n```\n[[wikis/<wiki>/<type>/<id>(|alias)]]\n```\n\nThe wikilink parser:\n- Extracts links from page bodies and frontmatter `related:` arrays\n- Skips links inside fenced code blocks\n- Silently skips malformed links\n- Preserves inline code spans\n\n```typescript\nexport interface WikilinkRef {\n  raw: string;\n  wiki: string;\n  type: string;\n  id: string;\n  alias?: string;\n  source: \"body\" | \"frontmatter\";\n}\n```\n\n资料来源：[src/core/wikilinks.ts:1-30]()\n\n### Profile System\n\nAgent profiles define identities within the system. Each profile:\n\n- Has a unique `profile-<slug>` ID\n- Stores species/pokemon data via frontmatter\n- Links to skills/moves in `wikis/_agents/moves/`\n- Can be registered with the Stadium platform\n\n```mermaid\ngraph TD\n    PROFILE[Profile Page] --> FRONTMATTER[Frontmatter]\n    PROFILE --> BODY[Body Content]\n    \n    FRONTMATTER --> SPECIES[pokemon: species_name]\n    FRONTMATTER --> TYPE[pokemon_type: type]\n    FRONTMATTER --> SPECIALTY[dev_specialty: specialty]\n    FRONTMATTER --> STAGE[evolution_stage: basic|stage1|stage2]\n    \n    PROFILE --> REGISTER[Profile Register Tool]\n    REGISTER --> STADIUM[Stadium Platform API]\n```\n\n资料来源：[src/core/profiles.ts:1-30]()\n\n### PokeAPI Integration\n\nThe system integrates with the PokeAPI to enrich agent profiles with game-related data:\n\n| Function | Purpose |\n|----------|---------|\n| `fetchSpecies()` | Get legendary/mythical/baby flags and evolution data |\n| `fetchPokemonSpecies()` | Full species data with evolution chain |\n| `filterByEvolutionStage()` | Filter candidates by basic/stage1/stage2 |\n\nData is cached locally to minimize API calls.\n\n资料来源：[src/core/pokeapi.ts:1-80]()\n\n### Page Operations\n\n```mermaid\ngraph TD\n    READ[readPage] --> PARSE[Parse Frontmatter + Body]\n    READ --> VALIDATE[Validate Page Type]\n    \n    WRITE[writePage] --> PATH[Resolve Path for Type]\n    WRITE --> MERGE[Merge Frontmatter]\n    WRITE --> SERIALIZE[Serialize to Markdown]\n    \n    UPSERT[upsertPage] --> CONDITIONAL[Read then Write]\n    UPSERT --> REINDEX[Update Token Index]\n```\n\nThe `WritePageInput` interface:\n\n```typescript\nexport interface WritePageInput {\n  id: string;\n  type: NoteType;\n  wiki: string;\n  frontmatter: Record<string, any>;\n  body: string;\n  expectedUpdated?: string;  // Optimistic locking\n}\n```\n\n资料来源：[src/core/pages.ts:40-70]()\n\n## Tools Reference\n\n### Read Tools\n\n| Tool | Description |\n|------|-------------|\n| `vault.recall` | Full-text search across vault |\n| `vault.inbox-list` | List captured thoughts |\n| `vault.page-read` | Read specific page by ID |\n| `vault.channel-tail` | Pull recent channel entries |\n\n### Write Tools\n\n| Tool | Description |\n|------|-------------|\n| `vault.inbox` | Capture fleeting thoughts |\n| `vault.new` | Create typed page from template |\n| `vault.new-wiki` | Scaffold new wiki space |\n| `vault.synthesize` | Compile synthesis from matching pages |\n| `vault.set-active` | Set ambient active wiki |\n| `vault.agent-journal` | Append agent reflection |\n| `vault.reindex` | Regenerate index files |\n\n### Coordination Tools\n\n| Tool | Description |\n|------|-------------|\n| `vault.channel-post` | Post to coordination channel |\n| `vault.task-*` | Task lifecycle (create, list, claim, update) |\n| `vault.claims-*` | Claims management (submit, list, retract, reject) |\n\n### Platform Tools\n\n| Tool | Description |\n|------|-------------|\n| `vault.profile-register` | Register profile with Stadium platform |\n| `vault.sync-skills` | Deploy agent moveset as local skills |\n| `vault.bootstrap-repo` | Wire consuming repo with MCP config |\n\n### Wait Primitives\n\n| Tool | Description |\n|------|-------------|\n| `vault.wait-for` | Block until matching event |\n| `vault.wait-for-any` | Wake on first match (race) |\n| `vault.wait-for-all` | Wake when all filters matched |\n| `vault.wait-for-many` | Bounded batch over window |\n\n资料来源：[README.md:1-60]()\n\n## CLI Usage\n\n```bash\n# Set vault path environment variable\nexport STOA_VAULT_PATH=/path/to/vault\n\n# Recall search\nstoa recall \"topic query\"\n\n# Capture a thought\nstoa inbox \"thought to capture\"\n\n# List wikis\nstoa list-wikis\n\n# With explicit vault path\nstoa --vault=/path/to/vault recall \"search terms\"\n```\n\n## Configuration\n\n### Wiki Parameter Resolution\n\nThe `wiki:` parameter resolves in this order:\n\n1. Explicit `wiki:` argument on tool call\n2. `--default-wiki=<name>` server flag\n3. `.active-wiki` file at vault root\n4. Error if none found\n\n### Server Configuration\n\n```bash\nstoa --vault=/path/to/vault \\\n     --default-wiki=alpha \\\n     --default-family=my-family\n```\n\n## Related Documentation\n\n- [Installation Guide](docs/installation.md) — Full setup and configuration walkthrough\n- [Manual Smoke Test](docs/manual-smoke-test.md) — Verify your installation\n- [Wait-For Primitives](docs/wait-for.md) — Push primitives documentation\n\n## License\n\nFSL-1 (Functional Source License)\n\n---\n\n<a id='concepts-vocabulary'></a>\n\n## Core Concepts and Vocabulary\n\n### 相关页面\n\n相关主题：[Introduction to Stoa](#introduction), [Agent Profiles and Evolution](#profiles-evolution)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/core/index.ts](https://github.com/BrettNye/stoa/blob/main/src/core/index.ts)\n- [src/core/wikilinks.ts](https://github.com/BrettNye/stoa/blob/main/src/core/wikilinks.ts)\n- [src/core/pages.ts](https://github.com/BrettNye/stoa/blob/main/src/core/pages.ts)\n- [src/core/ids.ts](https://github.com/BrettNye/stoa/blob/main/src/core/ids.ts)\n- [src/core/synthesize.ts](https://github.com/BrettNye/stoa/blob/main/src/core/synthesize.ts)\n- [src/core/syntheses.ts](https://github.com/BrettNye/stoa/blob/main/src/core/syntheses.ts)\n- [src/core/family.ts](https://github.com/BrettNye/stoa/blob/main/src/core/family.ts)\n- [src/core/eventbus/state-cache.ts](https://github.com/BrettNye/stoa/blob/main/src/core/eventbus/state-cache.ts)\n</details>\n\n# Core Concepts and Vocabulary\n\nThis document provides a comprehensive reference for the fundamental concepts, data structures, and terminology used throughout the stoa vault management system. Understanding these core concepts is essential for working effectively with the vault infrastructure, creating and managing pages, and integrating with the MCP (Model Context Protocol) server.\n\n## Vault Structure\n\nThe stoa system operates on a directory-based vault architecture where all content is organized within a hierarchical folder structure. The vault serves as the single source of truth for all wiki pages, profiles, agents, and metadata.\n\n### Vault Root Organization\n\n```\n<vault-path>/\n├── wikis/\n│   ├── <wiki-name>/\n│   │   ├── index.md\n│   │   ├── map.md\n│   │   ├── <type>-<slug>.md\n│   │   ├── profiles/\n│   │   ├── synthesis/\n│   │   └── ...\n│   └── _agents/\n│       ├── synthesis/\n│       └── journal/\n├── _index/\n│   ├── pages.json\n│   ├── tokens.json\n│   ├── links.json\n│   ├── wikis.json\n│   └── profiles.json\n├── .active-wiki\n└── .active-family\n```\n\n资料来源：[src/core/index.ts:1-50]()\n\n### Wiki Hierarchy\n\nWikis are the primary organizational unit within the vault. Each wiki contains typed pages organized by content type. The system supports multiple wikis per vault, with each wiki potentially belonging to a family for grouped operations.\n\n```mermaid\ngraph TD\n    A[Vault Root] --> B[wikis/]\n    B --> C[<wiki-name>]\n    B --> D[_agents]\n    B --> E[_meta]\n    C --> F[concepts/]\n    C --> G[decisions/]\n    C --> H[guides/]\n    C --> I[profiles/]\n    C --> J[synthesis/]\n    C --> K[inbox/]\n```\n\n资料来源：[src/core/family.ts:1-30]()\n\n## Page System\n\n### Page Types\n\nPages in stoa are distinguished by their `type` field in frontmatter. The type determines the file naming convention, storage location, and how the page is processed by various tools.\n\n| Type | Filename Pattern | Description |\n|------|------------------|-------------|\n| `concept` | `concept-<slug>.md` | Knowledge concepts and definitions |\n| `decision` | `decision-YYYY-MM-DD-<slug>.md` | Decision records with date prefix |\n| `guide` | `guide-<slug>.md` | Procedural guides |\n| `source` | `source-<slug>.md` | External citations and references |\n| `idea` | `idea-<slug>.md` | Ideas and brainstorms |\n| `question` | `question-<slug>.md` | Questions for investigation |\n| `profile` | `profile-<slug>.md` | Agent or entity profiles |\n| `synthesis` | `synthesis-<slug>.md` | Compiled synthesis pages |\n| `journal` | `journal-YYYY-MM-DD-HHMM-<slug>.md` | Agent journal entries |\n| `move` | `move-<slug>/SKILL.md` | Skills/moves (directory layout) |\n| `map` | `map.md` | Wiki map page (fixed filename) |\n\n资料来源：[src/core/ids.ts:1-50]()\n\n### Page Data Model\n\nEvery page in the vault has a consistent structure combining YAML frontmatter with markdown body content.\n\n```typescript\ninterface IndexedPage {\n  id: string;           // Unique page identifier\n  path: string;         // Relative path from vault root\n  wiki: string;         // Wiki name containing this page\n  type: NoteType;       // Page type discriminator\n  title?: string;       // Human-readable title\n  tags?: string[];      // Categorization tags\n  status?: string;      // Lifecycle status (draft, published, etc.)\n  created?: string;     // ISO 8601 creation date\n  updated?: string;     // ISO 8601 last modified date\n  summary?: string;     // Brief description\n  layer?: string;       // knowledge | execution classification\n  sources?: string[];   // Referenced wikilinks\n}\n```\n\n资料来源：[src/core/pages.ts:1-40]()\n\n### Wikilink Format\n\nThe system uses a structured wikilink syntax for cross-referencing pages within the vault.\n\n```markdown\n[[wikis/<wiki>/<type>/<id>(|alias)]]\n```\n\n**Components:**\n- `wikis/` — Literal prefix indicating a vault-root absolute link\n- `<wiki>` — Target wiki name (e.g., `alpha`, `_agents`)\n- `<type>` — Page type folder (e.g., `concept`, `decision`, `profile`)\n- `<id>` — Page identifier\n- `|alias` — Optional display alias\n\n**Examples:**\n```markdown\n[[wikis/alpha/concept/trust-gradient-axes]]\n[[wikis/_agents/profile/pikachu-agent|My Agent]]\n```\n\n资料来源：[src/core/wikilinks.ts:1-60]()\n\n## Indexing System\n\n### Token-Based Search\n\nThe index system uses a custom tokenization pipeline for full-text search across all vault pages.\n\n```typescript\nfunction upsertTokenize(text: string): string[] {\n  return text.toLowerCase()\n    .replace(/[^a-z0-9\\s]/g, \" \")\n    .split(/\\s+/)\n    .filter(t => t.length > 1 && !UPSERT_STOP_WORDS.has(t))\n    .map(t => upsertStemmer.stem(t));  // Porter stemming\n}\n```\n\n**Tokenization Pipeline:**\n1. Lowercase normalization\n2. Strip non-alphanumeric characters\n3. Split on whitespace\n4. Filter stop words and single characters\n5. Apply Porter stemmer\n\n**Stop Words:** `the`, `and`, `of`, `a`, `an`, `in`, `to`, `is`, `for`, `on`, `with`, `as`, `at`, `by`, `or`, `be`, `this`, `that`, `it`, `from`, `are`, `was`, `were`, `not`, `but`, `if`\n\n资料来源：[src/core/index.ts:40-55]()\n\n### Index Files\n\nThe `_index/` directory contains aggregated metadata for efficient querying:\n\n| File | Purpose |\n|------|---------|\n| `pages.json` | Full page metadata with frontmatter |\n| `tokens.json` | Search tokens mapped to page IDs |\n| `links.json` | Inter-page references (wikilinks) |\n| `wikis.json` | Wiki registry and metadata |\n| `profiles.json` | Profile-specific metadata |\n\n资料来源：[src/core/index.ts:55-70]()\n\n### Layer Classification\n\nPages are classified into layers for filtering and organization:\n\n```typescript\nconst KNOWLEDGE_TYPES = [\"concept\", \"decision\", \"spec\", \"source\"];\nconst EXECUTION_TYPES = [\"guide\", \"idea\", \"question\"];\n```\n\n- **Knowledge Layer** — Factual, distillable content (concepts, decisions, specs, sources)\n- **Execution Layer** — Procedural and exploratory content (guides, ideas, questions)\n\n资料来源：[src/core/index.ts:20-30]()\n\n## Synthesis System\n\n### Synthesis Pages\n\nSynthesis pages compile multiple related pages into a cohesive document. They serve as \"second-order\" content that distills information from source pages.\n\n```typescript\ninterface SynthesisPage extends IndexedPage {\n  type: \"synthesis\";\n  topic: string;           // Synthesis subject\n  sources: string[];       // Wikilinks to contributing pages\n  last_compiled: string;   // ISO date of last regeneration\n  scope?: \"memory\";        // Agent memory synthesis flag\n  by_agent?: string;       // Agent identifier for memory syntheses\n}\n```\n\n资料来源：[src/core/synthesize.ts:1-50]()\n\n### Synthesis Generation\n\n```mermaid\ngraph TD\n    A[Synthesize Request] --> B{scope?}\n    B -->|memory| C[Collect Agent Pages]\n    B -->|topic| D[Recall Matching Pages]\n    C --> E[Filter by Author]\n    D --> E\n    E --> F[Build Frontmatter]\n    F --> G[Generate Synthesis File]\n    G --> H[Upsert to Index]\n```\n\n资料来源：[src/core/synthesize.ts:50-120]()\n\n### Synthesis Debt Detection\n\nThe lint system identifies clusters of related hard-knowledge pages that lack corresponding synthesis pages.\n\n**Debt Rule:**\n- Clusters pages by shared tags\n- Flags clusters with ≥3 pages that have no synthesis\n- Suggests `vault.synthesize` command with derived title\n\n**Hard-Knowledge Types:** `concept`, `decision`, `spec`\n\n资料来源：[src/core/lint-checks/synthesis-debt.ts:1-50]()\n\n### Synthesis Staleness\n\nThe system tracks how long synthesis pages have gone without recompilation:\n\n```typescript\ninterface SynthesisStaleness {\n  id: string;\n  lag_days: number | null;  // null if never compiled\n  last_compiled: string | null;\n  topic: string;\n}\n```\n\n资料来源：[src/core/syntheses.ts:1-50]()\n\n## Wiki Resolution\n\n### Family Resolution Order\n\nWhen determining the active family context, the system follows this precedence:\n\n1. `familyArg` — Explicit parameter passed to the function\n2. `defaultFamily` — Configured default (via `--default-family` CLI arg)\n3. `.active-family` file at vault root\n4. `null` — Falls through to single-wiki resolution\n\n资料来源：[src/core/family.ts:15-40]()\n\n### Wiki Resolution Order\n\nWiki parameter resolution follows this order:\n\n1. Explicit `wiki:` argument on tool call\n2. `--default-wiki=<name>` flag on server invocation\n3. `.active-wiki` file at vault root\n4. Error if no wiki can be determined\n\n资料来源：[README.md:1-30]()\n\n### Family-Wiki Validation\n\nWhen both `familyArg` and `wikiArg` are provided with `knownWikis`, the system validates consistency:\n\n```typescript\nif (knownWikis[wikiArg].family !== familyArg) {\n  throw new FamilyMismatchError(...);\n}\n```\n\n资料来源：[src/core/family.ts:25-35]()\n\n## Event Bus and State Cache\n\n### StateCache\n\nThe StateCache provides an in-memory cache for tracking page states across event sources.\n\n```typescript\nclass StateCache {\n  private states = new Map<string, unknown>();\n  \n  private key(source: string, wiki: string, id: string): string {\n    return `${source}:${wiki}:${id}`;\n  }\n  \n  get<T>(source: string, wiki: string, id: string): T | undefined;\n  set<T>(source: string, wiki: string, id: string, state: T): void;\n  has(source: string, wiki: string, id: string): boolean;\n  size(): number;\n}\n```\n\n**Key Format:** `source:wiki:id`\n\n资料来源：[src/core/eventbus/state-cache.ts:1-35]()\n\n### Cache Initialization\n\nThe system pre-warms the cache by walking the `wikis/` directory before accepting live events, ensuring the first change event has valid prior state for diffing.\n\n```typescript\nfunction walkInitablePaths(vaultPath: string): string[] {\n  // Recursively find all .md files in wikis/\n  // Returns paths where 'init' is defined for state tracking\n}\n```\n\n资料来源：[src/transport/stdio.ts:40-70]()\n\n## Frontmatter Schema\n\n### Standard Frontmatter Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `id` | string | Unique page identifier |\n| `title` | string | Display title |\n| `type` | string | Page type |\n| `wiki` | string | Wiki name |\n| `status` | string | Lifecycle status |\n| `created` | string | ISO 8601 creation date |\n| `updated` | string | ISO 8601 modification date |\n| `summary` | string | Brief description |\n| `tags` | string[] | Categorization tags |\n| `layer` | string | knowledge or execution |\n| `sources` | string[] | Wikilinks to source pages |\n\n### Profile-Specific Fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `pokemon` | string | Species name |\n| `evolution_stage` | string | basic, stage1, stage2 |\n| `pokemon_type` | string | Pokémon type (if applicable) |\n| `dev_specialty` | string | Developer specialty |\n| `rarity` | string | common, baby, legendary, mythical |\n| `platform_profile_id` | string | Stadium platform ID |\n| `platform_stats` | object | Persisted platform statistics |\n\n资料来源：[src/transport/ui/routes-write.ts:1-40]()\n\n## Marker Rendering\n\nThe marker system enables tools to maintain managed regions within human-editable files.\n\n### Marker Contract\n\n- **Start Marker:** `<!-- <name>:start (rendered: <date>, half-life: <N>d) -->`\n- **End Marker:** `<!-- <name>:end -->`\n- **Idempotent:** Same inputs produce byte-identical output\n- **Independent:** Different marker names don't interfere\n\n```typescript\ninterface MarkerOptions {\n  renderedDate?: string;   // ISO date YYYY-MM-DD\n  halfLifeDays?: number;   // Half-life in days\n}\n```\n\n**Applications:**\n- `synthesize` — Claims rollup\n- `sync-skills` — Moveset synchronization\n- `bootstrap-repo` — Agent documentation patches\n\n资料来源：[src/core/marker-render.ts:1-50]()\n\n## Tool Categories\n\n### Read Primitives\n\n| Tool | Purpose |\n|------|---------|\n| `vault.recall` | Full-text search with filters |\n| `vault.page-read` | Read single page by ID |\n| `vault.channel-tail` | Pull coordination channel entries |\n| `vault.synthesis-staleness` | Check synthesis freshness |\n\n### Wait (Push Primitives)\n\n| Tool | Purpose |\n|------|---------|\n| `vault.wait-for` | Block until matching event |\n| `vault.wait-for-any` | Wake on first match across N filters |\n| `vault.wait-for-all` | Wake when all N filters matched |\n| `vault.wait-for-many` | Bounded batch over window |\n\n### Write — Content\n\n| Tool | Purpose |\n|------|---------|\n| `vault.inbox` | Capture fleeting thoughts |\n| `vault.new` | Create typed page from template |\n| `vault.new-wiki` | Scaffold new wiki structure |\n| `vault.set-active` | Set ambient active wiki |\n| `vault.synthesize` | Compile synthesis page |\n| `vault.agent-journal` | Append agent reflection |\n\n### Write — System\n\n| Tool | Purpose |\n|------|---------|\n| `vault.reindex` | Regenerate `_index/` files |\n\n### Coordination\n\n| Tool | Purpose |\n|------|---------|\n| `vault.channel-post` | Post to coordination channel |\n| `vault.task-claim` | Atomically claim pending task |\n| `vault.task-create` | Create new task |\n| `vault.task-list` | List tasks |\n| `vault.task-update` | Update task state |\n| `vault.bootstrap-repo` | Wire consuming repo with MCP config |\n| `vault.sync-skills` | Deploy agent moveset as local skills |\n\n资料来源：[README.md:30-80]()\n\n## Configuration Files\n\n### Server Configuration\n\n| Config Method | Description |\n|---------------|-------------|\n| `--vault=<path>` | Vault root directory |\n| `--default-wiki=<name>` | Default wiki for operations |\n| `--default-family=<name>` | Default family for multi-wiki ops |\n| `STOA_VAULT_PATH` | Environment variable alternative |\n\n### Active Context Files\n\n| File | Purpose |\n|------|---------|\n| `.active-wiki` | Current active wiki name |\n| `.active-family` | Current active family name |\n\n## Common Patterns\n\n### Idempotent Page Creation\n\nPages use upsert semantics — creating a page with an existing ID updates rather than duplicates:\n\n```typescript\nfunction writePage(vaultPath: string, input: WritePageInput): WritePageResult {\n  const path = pathForPage(vaultPath, input.id, input.type, input.wiki);\n  // Uses expectedUpdated for optimistic concurrency control\n}\n```\n\n资料来源：[src/core/pages.ts:40-80]()\n\n### Three-Step Alias Resolution\n\nProfile and agent references resolve through multiple resolution steps:\n\n```typescript\nfunction normalizeProfileId(vaultPath: string, raw: string): string {\n  const r1 = resolveCurrent(vaultPath, raw);\n  if (r1 !== raw) return r1;\n  const candidate = raw.startsWith(\"profile-\") ? raw : `profile-${raw}`;\n  return resolveCurrent(vaultPath, candidate);\n}\n```\n\n资料来源：[src/tools/sync-agents.ts:1-40]()\n\n### Lint Rule Pattern\n\nNew lint rules follow a consistent structure:\n\n```typescript\nexport const LINT_RULE = {\n  ruleId: \"rule-name\",\n  severity: \"warn\" | \"error\",\n  message: \"Human-readable description\",\n};\n```\n\n资料来源：[src/core/lint-checks/claim-with-no-scope.ts:1-30]()\n\n## Terminology Summary\n\n| Term | Definition |\n|------|------------|\n| **Vault** | Root directory containing all wikis and metadata |\n| **Wiki** | Organizational unit containing typed pages |\n| **Family** | Grouping of related wikis |\n| **Page** | Single markdown document with frontmatter |\n| **Type** | Page classification determining storage and behavior |\n| **Wikilink** | Cross-reference syntax `[[wikis/...]]` |\n| **Synthesis** | Compiled page aggregating multiple sources |\n| **Layer** | Knowledge vs execution classification |\n| **Marker** | HTML comment bounding managed file regions |\n| **Index** | Aggregated metadata for efficient querying |\n| **Debt** | Gap between source pages and their synthesis |\n\n---\n\n<a id='architecture-design'></a>\n\n## Architecture and Design\n\n### 相关页面\n\n相关主题：[Introduction to Stoa](#introduction), [Event Bus System](#event-bus-system)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/core/index.ts](https://github.com/BrettNye/stoa/blob/main/src/core/index.ts)\n- [src/transport/stdio.ts](https://github.com/BrettNye/stoa/blob/main/src/transport/stdio.ts)\n- [src/core/family.ts](https://github.com/BrettNye/stoa/blob/main/src/core/family.ts)\n- [src/core/skills-platform.ts](https://github.com/BrettNye/stoa/blob/main/src/core/skills-platform.ts)\n- [src/core/pages.ts](https://github.com/BrettNye/stoa/blob/main/src/core/pages.ts)\n- [src/core/frontmatter.ts](https://github.com/BrettNye/stoa/blob/main/src/core/frontmatter.ts)\n- [src/core/synthesize.ts](https://github.com/BrettNye/stoa/blob/main/src/core/synthesize.ts)\n- [src/core/wikilinks.ts](https://github.com/BrettNye/stoa/blob/main/src/core/wikilinks.ts)\n- [src/core/lint-checks/synthesis-debt.ts](https://github.com/BrettNye/stoa/blob/main/src/core/lint-checks/synthesis-debt.ts)\n- [src/core/channel.ts](https://github.com/BrettNye/stoa/blob/main/src/core/channel.ts)\n</details>\n\n# Architecture and Design\n\n## Overview\n\nStoa is an MCP (Model Context Protocol) server that provides structured access to a flat-file knowledge vault. It bridges AI agents with a wiki-based knowledge management system, enabling semantic search, cross-wiki linking, task management, and skill deployment. The architecture follows a layered design with clear separation between transport mechanisms, core domain logic, and tool interfaces.\n\n**Purpose and Scope:**\n- Expose vault operations via MCP protocol (STDIO or HTTP transports)\n- Maintain a search index for full-text and structured queries\n- Enforce wiki semantics and validation rules through lint checks\n- Support multi-wiki, multi-family deployments\n- Enable skill/move deployment workflows\n\n**资料来源：** [src/core/index.ts:1-50](https://github.com/BrettNye/stoa/blob/main/src/core/index.ts)\n\n---\n\n## High-Level Architecture\n\nThe system comprises three primary layers:\n\n1. **Transport Layer** — Handles MCP protocol communication (STDIO or HTTP)\n2. **Core Domain Layer** — Business logic, index management, linting, synthesis\n3. **Tools Layer** — Exposes MCP tools to calling agents\n\n```mermaid\ngraph TD\n    subgraph Transport[\"Transport Layer\"]\n        STDIO[STDIO Transport]\n        HTTP[HTTP Transport]\n    end\n\n    subgraph Core[\"Core Domain Layer\"]\n        INDEX[Index Management]\n        QUERY[Query Engine]\n        LINT[Lint Checks]\n        SYNTH[Synthesis Engine]\n        FAMILY[Family Resolution]\n        SKILLS[Skills Platform]\n        CACHE[State Cache]\n    end\n\n    subgraph Tools[\"Tools Layer\"]\n        RECALL[recall]\n        INBOX[inbox]\n        SYNTHESIZE[synthesize]\n        TASK[task-*]\n        CHANNEL[channel-*]\n        WAITFOR[wait-for*]\n    end\n\n    subgraph Vault[\"Flat-File Vault\"]\n        WIKIS[wikis/]\n        INDEX_VAULT[_index/]\n        ACTIVE_WIKI[.active-wiki]\n        ACTIVE_FAMILY[.active-family]\n    end\n\n    STDIO --> CORE\n    HTTP --> CORE\n    CORE --> INDEX\n    CORE --> TOOLS\n    INDEX --> VAULT\n    TOOLS --> VAULT\n```\n\n**资料来源：** [src/transport/stdio.ts:1-30](https://github.com/BrettNye/stoa/blob/main/src/transport/stdio.ts)\n\n---\n\n## Transport Layer\n\n### STDIO Transport\n\nThe STDIO transport enables integration with local MCP clients. It initializes the server state cache by walking the `wikis/` directory before processing change events.\n\nKey initialization steps:\n1. Load vault configuration\n2. Walk `wikis/` directory to warm state cache\n3. Connect STDIO server transport\n4. Log ready message with vault path and defaults\n\n```typescript\nconst transport = new StdioServerTransport();\nawait server.connect(transport);\nprocess.stderr.write(`vault-mcp stdio server ready (vault=${config.vaultPath}, default-wiki=${config.defaultWiki ?? \"<unset>\"}, default-family=${config.defaultFamily ?? \"<unset>\"})\\n`);\n```\n\n**资料来源：** [src/transport/stdio.ts:40-50](https://github.com/BrettNye/stoa/blob/main/src/transport/stdio.ts)\n\n### Transport Architecture Pattern\n\nThe transport layer is abstracted behind a common interface. Both STDIO and HTTP transports expose the same tool set, allowing clients to choose their preferred communication mechanism.\n\n| Transport | Use Case | Initialization |\n|-----------|----------|----------------|\n| STDIO | Local MCP clients, CLI tools | `StdioServerTransport` |\n| HTTP | Remote access, web clients | `HttpServerTransport` |\n\n---\n\n## Core Domain Layer\n\n### Index Management\n\nThe index is the primary data structure powering queries. It maintains:\n- **pages.json** — All page metadata (id, title, type, wiki, tags, status)\n- **tokens.json** — Tokenized text for full-text search\n- **links.json** — Wikilink references between pages\n- **wikis.json** — Wiki metadata\n- **profiles.json** — Agent profiles\n\n**资料来源：** [src/core/index.ts:60-100](https://github.com/BrettNye/stoa/blob/main/src/core/index.ts)\n\n#### Query Engine\n\nThe `queryPages` function supports filtering by:\n- `wiki` — Wiki identifier\n- `type` — Page type (concept, decision, guide, etc.)\n- `channel` — Coordination channel\n- `status` — Page status (draft, active, accepted, etc.)\n- `layer` — knowledge or execution\n\n```typescript\nexport function queryPages(idx: VaultIndex, f: PageFilter): IndexedPage[] {\n  return idx.pages.filter(p => {\n    if (f.wiki && wikiSet && !wikiSet.has(p.wiki)) return false;\n    if (f.type && p.type !== f.type) return false;\n    if (f.channel && p.channel !== f.channel) return false;\n    if (f.status && p.status !== f.status) return false;\n    if (f.layer && f.layer !== \"all\") {\n      const set = f.layer === \"knowledge\" ? KNOWLEDGE_TYPES : EXECUTION_TYPES;\n      if (!set.includes(p.type)) return false;\n    }\n    return true;\n  });\n}\n```\n\n**资料来源：** [src/core/index.ts:30-55](https://github.com/BrettNye/stoa/blob/main/src/core/index.ts)\n\n#### Tokenization and Search\n\nSearch uses Porter stemming with stop-word removal for relevance ranking.\n\n```typescript\nconst upsertStemmer = natural.PorterStemmer;\nconst UPSERT_STOP_WORDS = new Set([\"the\",\"and\",\"of\",\"a\",\"an\",\"in\",\"to\",\"is\",\"for\",\"on\",\"with\",\"as\",\"at\",\"by\",\"or\",\"be\",\"this\",\"that\",\"it\",\"from\",\"are\",\"was\",\"were\",\"not\",\"but\",\"if\"]);\n\nfunction upsertTokenize(text: string): string[] {\n  return text.toLowerCase()\n    .replace(/[^a-z0-9\\s]/g, \" \")\n    .split(/\\s+/)\n    .filter(t => t.length > 1 && !UPSERT_STOP_WORDS.has(t))\n    .map(t => upsertStemmer.stem(t));\n}\n```\n\n**资料来源：** [src/core/index.ts:35-48](https://github.com/BrettNye/stoa/blob/main/src/core/index.ts)\n\n---\n\n### Family Resolution\n\nStoa supports hierarchical organization through **families** (collections of related wikis) and **wikis** (individual knowledge bases within a family).\n\n```mermaid\ngraph TD\n    FAM[Family<br/>e.g., \"stadium\"] --> W1[Wiki: pokemon]\n    FAM --> W2[Wiki: moves]\n    FAM --> W3[Wiki: trainers]\n    \n    W1 --> P1[Pages...]\n    W2 --> P2[Pages...]\n    W3 --> P3[Pages...]\n```\n\n#### Resolution Order\n\nFamily resolution follows a priority order:\n\n| Priority | Source | CLI Flag |\n|----------|--------|----------|\n| 1 | Explicit `familyArg` | `--default-family` |\n| 2 | Context default | `ctx.defaultFamily` |\n| 3 | Vault file | `.active-family` |\n| 4 | null | — |\n\n```typescript\nexport function resolveFamily(\n  ctx: FamilyResolveCtx,\n  familyArg?: string,\n  wikiArg?: string,\n  knownWikis?: Record<string, { family?: string | null }>\n): string | null {\n  if (familyArg !== undefined && familyArg !== \"\") {\n    if (wikiArg !== undefined && knownWikis !== undefined) {\n      const wikiEntry = knownWikis[wikiArg];\n      const wikiFamily = wikiEntry?.family ?? null;\n      if (wikiFamily !== familyArg) {\n        throw new FamilyMismatchError(...);\n      }\n    }\n    return familyArg;\n  }\n  // ... fallback chain\n}\n```\n\n**资料来源：** [src/core/family.ts:1-50](https://github.com/BrettNye/stoa/blob/main/src/core/family.ts)\n\n---\n\n### Page Management\n\n#### Page Types\n\n| Type | Description | Filename Pattern |\n|------|-------------|------------------|\n| `concept` | Knowledge concept | `concept-<slug>.md` |\n| `decision` | Decision record | `decision-YYYY-MM-DD-<slug>.md` |\n| `journal` | Journal entry | `journal-YYYY-MM-DD-HHMM-<slug>.md` |\n| `guide` | Procedural guide | `guide-<slug>.md` |\n| `move` | Skill/move | `move-<slug>/SKILL.md` |\n| `map` | Wiki map | `map.md` |\n| `synthesis` | Synthesized content | Varies |\n\n**资料来源：** [src/core/ids.ts:1-40](https://github.com/BrettNye/stoa/blob/main/src/core/ids.ts)\n\n#### Write Operations\n\nPages are written with optimistic concurrency via `expectedUpdated` checks:\n\n```typescript\nexport function writePage(vaultPath: string, input: WritePageInput): WritePageResult {\n  const path = pathForPage(vaultPath, input.id, input.type, input.wiki);\n  if (existsSync(path) && input.expectedUpdated !== undefined) {\n    const existing = readFileSync(path, \"utf8\");\n    const { frontmatter: existingFm } = parseFrontmatter(existing);\n    const actualUpdated = toIsoDate(existingFm.updated ?? existingFm.created);\n    // Check for conflicts\n  }\n}\n```\n\n**资料来源：** [src/core/pages.ts:50-80](https://github.com/BrettNye/stoa/blob/main/src/core/pages.ts)\n\n---\n\n### Frontmatter Schema\n\nAll pages use YAML frontmatter with Zod validation:\n\n| Field | Type | Required | Description |\n|-------|------|----------|-------------|\n| `id` | string | Yes | Unique identifier (kebab-case) |\n| `title` | string | Yes | Display title |\n| `type` | NoteType | Yes | Page classification |\n| `created` | ISO date | Yes | Creation timestamp |\n| `channel` | string | No | Coordination channel (kebab-case) |\n| `status` | enum | No | draft, active, accepted, superseded, archived |\n| `confidence` | enum | No | high, medium, low |\n| `curation_priority` | enum | No | high, medium, low |\n| `wiki` | string | Yes | Wiki identifier |\n| `tags` | string[] | No | Taxonomy tags |\n| `last_compiled` | ISO date | No | Synthesis compilation timestamp |\n\n**资料来源：** [src/core/frontmatter.ts:1-60](https://github.com/BrettNye/stoa/blob/main/src/core/frontmatter.ts)\n\n---\n\n### Wikilink System\n\nWikilinks follow the pattern: `[[wikis/<wiki>/<type>/<id>(|alias)?]]`\n\nThe wikilink extractor:\n- Is code-fence-aware (skips links inside ``` blocks)\n- Extracts from both body content and frontmatter `related:` arrays\n- Returns structured `WikilinkRef` objects\n\n```typescript\nexport interface WikilinkRef {\n  raw: string;\n  wiki: string;\n  type: string;\n  id: string;\n  alias?: string;\n  source: \"body\" | \"frontmatter\";\n}\n```\n\n**Trade-offs:**\n- Top-level fenced blocks are stripped\n- Indented fenced blocks (e.g., inside list items) are NOT stripped\n- Inline single-backtick code spans are NOT stripped\n\n**资料来源：** [src/core/wikilinks.ts:1-50](https://github.com/BrettNye/stoa/blob/main/src/core/wikilinks.ts)\n\n---\n\n### Synthesis Engine\n\nSynthesis pages aggregate related content from hard-knowledge types (concept, decision, spec).\n\n#### Synthesis Debt Detection\n\nThe lint system identifies clusters of related pages that lack synthesis coverage:\n\n```typescript\nconst HARD_KNOWLEDGE_TYPES = new Set([\"concept\", \"decision\", \"spec\"]);\n// Excluded: guide (procedural), source (external citation), idea, question\n\nfunction findSynthesisDebt(\n  pages: IndexedPage[],\n  minSize: number = DEFAULT_MIN_CLUSTER_SIZE,\n): ClusterDebt[] {\n  // Group by (wiki, tag) → hard-knowledge ids\n  // Check if any synthesis page covers the same tag\n  // Emit debt when: cluster size >= minSize AND no synthesis exists\n}\n```\n\n**Default minimum cluster size:** 3\n\n**资料来源：** [src/core/lint-checks/synthesis-debt.ts:1-80](https://github.com/BrettNye/stoa/blob/main/src/core/lint-checks/synthesis-debt.ts)\n\n#### Synthesis Generation\n\n```typescript\nconst fm: Record<string, any> = {\n  id,\n  title: scope === \"memory\"\n    ? `${input.by_agent} memory — synthesis`\n    : `${input.topic} — synthesis`,\n  type: \"synthesis\",\n  wiki,\n  status: \"draft\",\n  sources: inputIds.map(i => `[[wikis/${wiki}/${typeFolderForId(i)}/${i}]]`)\n};\n```\n\n**资料来源：** [src/core/synthesize.ts:60-100](https://github.com/BrettNye/stoa/blob/main/src/core/synthesize.ts)\n\n---\n\n### Marker-Based Section Rendering\n\nManaged regions within files are bounded by HTML comment markers:\n\n```\n<!-- <name>:start (rendered: YYYY-MM-DD, half-life: Nd) -->\n<section-content>\n<!-- <name>:end -->\n```\n\nCharacteristics:\n- **Idempotent** — Re-rendering produces byte-identical output\n- **Independent** — Different `markerName` values don't interfere\n- **Append fallback** — If markers are absent, content is appended\n\n**资料来源：** [src/core/marker-render.ts:1-50](https://github.com/BrettNye/stoa/blob/main/src/core/marker-render.ts)\n\n---\n\n### Skills Platform\n\nThe skills platform manages deployment drift detection between canonical vault sources and deployed skills.\n\n```mermaid\ngraph LR\n    CANON[Canonical<br/>wikis/_agents/moves/<id>/SKILL.md]\n    DEPLOY[Deployed<br/><skills_dir>/<id>/SKILL.md]\n    HASH[Hash Comparison]\n    REPORT[Drift Report]\n    \n    CANON --> HASH\n    DEPLOY --> HASH\n    HASH --> REPORT\n```\n\n**Drift Detection Rules:**\n\n| Scenario | Behavior |\n|----------|----------|\n| Canonical missing | Throws (vault-integrity bug) |\n| Deployed missing | Emit `missing` |\n| Hashes differ | Emit `hash-mismatch` |\n| Hashes match | Omit (no entry) |\n\n**资料来源：** [src/core/skills-platform.ts:40-80](https://github.com/BrettNye/stoa/blob/main/src/core/skills-platform.ts)\n\n---\n\n### Channel System\n\nChannels enable cross-instance coordination through journal entries tagged with channel identifiers.\n\n```typescript\nexport interface ChannelSummary {\n  name: string;\n  wiki: string;\n  lastEntry: ChannelEntry | null;\n  count24h: number;\n}\n```\n\n**资料来源：** [src/core/channel.ts:1-60](https://github.com/BrettNye/stoa/blob/main/src/core/channel.ts)\n\n---\n\n### State Cache\n\nThe `StateCache` provides in-memory state tracking with a composite key:\n\n```typescript\nexport class StateCache {\n  private key(source: string, wiki: string, id: string): string {\n    return `${source}:${wiki}:${id}`;\n  }\n  \n  get<T>(source: string, wiki: string, id: string): T | undefined;\n  set<T>(source: string, wiki: string, id: string, state: T): void;\n  has(source: string, wiki: string, id: string): boolean;\n  size(): number;\n}\n```\n\n**Use cases:**\n- Pre-warming cache before processing change events\n- Tracking prior state for diff computation\n\n**资料来源：** [src/core/eventbus/state-cache.ts](https://github.com/BrettNye/stoa/blob/main/src/core/eventbus/state-cache.ts)\n\n---\n\n## Configuration\n\n### Wiki Resolution Order\n\n| Priority | Source |\n|----------|--------|\n| 1 | Explicit `wiki:` arg on tool call |\n| 2 | `--default-wiki=<name>` server flag |\n| 3 | `.active-wiki` file at vault root |\n| 4 | Error (no resolution possible) |\n\n### Environment Variables\n\n| Variable | Purpose |\n|----------|---------|\n| `STOA_VAULT_PATH` | Default vault path (skip `--vault=` flag) |\n\n---\n\n## Data Flow\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant Transport\n    participant Tools\n    participant Core\n    participant Index\n    participant Vault\n\n    Client->>Transport: MCP Tool Call\n    Transport->>Tools: Route to handler\n    Tools->>Core: Domain logic\n    Core->>Index: Query/Update\n    Index->>Vault: Read/Write files\n    Vault-->>Index: Data\n    Index-->>Core: Results\n    Core-->>Tools: Processed data\n    Tools-->>Transport: Response\n    Transport-->>Client: MCP Result\n```\n\n---\n\n## Key Design Decisions\n\n| Decision | Rationale | Trade-off |\n|----------|-----------|-----------|\n| Flat-file storage | Human-editable, version-control friendly | Slower random access than DB |\n| Code-fence-aware wikilinks | Prevents link extraction from examples | Indented code blocks still processed |\n| Single-backtick spans NOT stripped | Simplifies extraction logic | Wikilinks in inline code returned |\n| Family/wikis hierarchy | Enables multi-tenant deployments | Additional resolution complexity |\n| Marker-based sections | Allows human editing in managed regions | Collision possible with same marker names |\n\n---\n\n## Related Documentation\n\n- [Installation](docs/installation.md) — Full installation walkthrough\n- [Manual Smoke Test](docs/manual-smoke-test.md) — Verification procedures\n- [Wait-For Primitives](docs/wait-for.md) — Event-based synchronization\n\n---\n\n<a id='event-bus-system'></a>\n\n## Event Bus System\n\n### 相关页面\n\n相关主题：[Architecture and Design](#architecture-design), [Channels and Claims](#channels-claims)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/core/eventbus/state-cache.ts](https://github.com/BrettNye/stoa/blob/main/src/core/eventbus/state-cache.ts)\n- [src/core/eventbus/matchers/task.ts](https://github.com/BrettNye/stoa/blob/main/src/core/eventbus/matchers/task.ts)\n- [src/tools/wait-for.ts](https://github.com/BrettNye/stoa/blob/main/src/tools/wait-for.ts)\n- [src/transport/stdio.ts](https://github.com/BrettNye/stoa/blob/main/src/transport/stdio.ts)\n- [src/core/index.ts](https://github.com/BrettNye/stoa/blob/main/src/core/index.ts)\n</details>\n\n# Event Bus System\n\nThe Event Bus System is a core infrastructure component in Stoa that provides reactive, push-based primitives for monitoring vault changes. Rather than polling for updates, the system leverages the local filesystem watch event bus to notify consumers when specific conditions are met.\n\n## Overview\n\nThe Event Bus System enables agents and tools to:\n\n- **React to vault mutations** — page creation, updates, deletions trigger events\n- **Track state transitions** — monitor changes to structured data like task status\n- **Block until conditions** — wait-for primitives that return only when matching events occur\n- **Warm state on startup** — preload current state before processing live events\n\n资料来源：[src/transport/stdio.ts:27-28]()\n\n## Architecture\n\nThe system consists of several interconnected layers:\n\n| Layer | Purpose |\n|-------|---------|\n| **Watcher** | Filesystem observer that monitors vault paths |\n| **State Cache** | In-memory Map storing prior state for diffing |\n| **Matchers** | Rule-based filters that determine when to emit events |\n| **Bus** | Event dispatcher connecting watchers to consumers |\n| **Wait-For Tools** | Blocking API surface for callers |\n\n```mermaid\ngraph TD\n    A[Vault Filesystem] -->|FS Events| B[Watcher]\n    B --> C[State Cache]\n    C -->|Prior State| D[Matchers]\n    D -->|Emit Decision| E[Event Bus]\n    E -->|VaultEvent| F[Wait-For API]\n    E -->|VaultEvent| G[Other Consumers]\n    \n    H[Startup] -->|walkInitablePaths| I[Warm Cache]\n    I --> C\n```\n\n资料来源：[src/core/eventbus/state-cache.ts:1-15]()\n\n## State Cache\n\nThe `StateCache` class provides an in-memory snapshot of vault entity states, enabling diff-based change detection.\n\n### Key Methods\n\n| Method | Signature | Purpose |\n|--------|-----------|---------|\n| `get` | `<T>(source, wiki, id) => T \\| undefined` | Retrieve cached state |\n| `set` | `<T>(source, wiki, id, state) => void` | Store state snapshot |\n| `has` | `(source, wiki, id) => boolean` | Check if state exists |\n| `size` | `() => number` | Return cache entry count |\n\n### Key Generation\n\nStates are stored using a composite key format:\n\n```\n${source}:${wiki}:${id}\n```\n\nThis allows isolated state tracking per source (e.g., `file-watcher`, `mcp-tool`) across wikis and page IDs.\n\n资料来源：[src/core/eventbus/state-cache.ts:3-22]()\n\n### Initialization\n\nBefore accepting live events, the system warms the cache by walking existing files:\n\n```typescript\nfunction walkInitablePaths(vaultPath: string): string[] {\n  const root = join(vaultPath, \"wikis\");\n  if (!existsSync(root)) return [];\n  // ...\n}\n```\n\nThis ensures the first change event has valid prior state for diffing.\n\n资料来源：[src/transport/stdio.ts:30-46]()\n\n## Matchers\n\nMatchers are pure functions that determine whether a filesystem change should emit a `VaultEvent`. Each matcher handles a specific entity type.\n\n### Task Matcher\n\nThe task matcher tracks frontmatter changes on task pages and emits enrichment data for status/owner transitions.\n\n#### State Picking\n\n```typescript\nfunction pickTaskState(frontmatter): Partial<VaultEvent> {\n  return {\n    status: frontmatter.status,\n    owner: frontmatter.owner\n  };\n}\n```\n\n#### Change Detection Logic\n\n| Condition | Action |\n|-----------|--------|\n| Status changed | Add `task_status_change: { from, to }` |\n| Owner changed | Add `task_owner_change: { from, to }` |\n| Both unchanged | Emit `false` (no event) |\n| Both changed | Emit `true` with both enrichments |\n\n```typescript\nnextState(parsed) { return pickTaskState(parsed.frontmatter); },\ninit(_path, parsed) { return pickTaskState(parsed.frontmatter); },\n```\n\n资料来源：[src/core/eventbus/matchers/task.ts:1-26]()\n\n### Matcher Contract\n\nMatchers implement three functions:\n\n1. **`compare(prev, cur)`** — Returns `{ emit: boolean, enrichment?: Partial<VaultEvent> }`\n2. **`nextState(parsed)`** — Extracts state fields from current file parse\n3. **`init(path, parsed)`** — Provides initial state for a newly discovered entity\n\n## VaultEvent Structure\n\nEvents emitted by the bus carry structured change data:\n\n```typescript\ninterface VaultEvent {\n  type: string;           // Event type identifier\n  wiki: string;           // Wiki containing the entity\n  id: string;             // Entity identifier\n  source: string;         // Origin of the event\n  timestamp?: string;     // ISO timestamp\n  task_status_change?: { from: string; to: string };\n  task_owner_change?: { from: string; to: string };\n}\n```\n\n## Wait-For Primitives\n\nThe Event Bus exposes blocking wait operations for callers that need to pause until conditions are met.\n\n### Available Primitives\n\n| Tool | Behavior |\n|------|----------|\n| `vault.wait-for` | Block until one matching event lands; cursor-based catch-up |\n| `vault.wait-for-any` | Wake on first match across N filters (race semantics) |\n| `vault.wait-for-all` | Wake when all N filters have matched at least once |\n| `vault.wait-for-many` | Bounded batch over a window |\n\nThese primitives connect to the filesystem watch event bus, providing push semantics instead of polling.\n\n资料来源：[README.md:18-25]()\n\n## Event Flow\n\n```mermaid\nsequenceDiagram\n    participant FS as Filesystem\n    participant Watcher\n    participant Cache as State Cache\n    participant Matcher\n    participant Bus\n    participant Consumer\n\n    Note over FS,Consumer: Startup Phase\n    Consumer->>Watcher: walkInitablePaths()\n    Watcher->>FS: Read existing files\n    Watcher->>Cache: set() prior states\n    Cache-->>Consumer: Cache warmed\n\n    Note over FS,Consumer: Live Event Phase\n    FS->>Watcher: File change detected\n    Watcher->>Cache: get() prior state\n    Cache-->>Watcher: Return previous state\n    Watcher->>Matcher: compare(prev, cur)\n    Matcher-->>Watcher: { emit, enrichment }\n    Watcher->>Bus: Emit VaultEvent\n    Bus->>Consumer: Deliver event\n```\n\n## Integration Points\n\n### With Index System\n\nThe event bus integrates with the vault index for querying wikis and pages:\n\n```typescript\nexport function queryWikis(idx: VaultIndex): IndexedWiki[] {\n  return idx.wikis;\n}\n```\n\n资料来源：[src/core/index.ts:1-10]()\n\n### With Lint System\n\nLint checks consume event data for validation:\n\n```typescript\nlintAliasDrift(vaultPath, input.wiki, diagnostics);\nlintAgentsWiki(vaultPath, diagnostics);\n```\n\n资料来源：[src/core/lint.ts:1-30]()\n\n## Configuration\n\nThe system relies on vault path resolution:\n\n| Source | Priority | Environment Variable |\n|--------|----------|----------------------|\n| CLI `--vault` | 1 (highest) | — |\n| `STOA_VAULT_PATH` | 2 | `STOA_VAULT_PATH` |\n| Default | 3 (lowest) | — |\n\nActive wiki/family files (`.active-wiki`, `.active-family`) influence which entities are monitored.\n\n## Error Handling\n\n| Scenario | Behavior |\n|----------|----------|\n| Unknown wiki | Events filtered out; no error |\n| File read failure | Error propagates to watcher |\n| State not in cache | Treat as new entity; use `init` |\n| Matcher throws | Error propagates; event not emitted |\n\n---\n\n<a id='profiles-evolution'></a>\n\n## Agent Profiles and Evolution\n\n### 相关页面\n\n相关主题：[Core Concepts and Vocabulary](#concepts-vocabulary), [Runtime Adapters](#runtime-adapters)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/tools/profile-register.ts](https://github.com/BrettNye/stoa/blob/main/src/tools/profile-register.ts)\n- [src/transport/ui/routes-write.ts](https://github.com/BrettNye/stoa/blob/main/src/transport/ui/routes-write.ts)\n- [src/core/frontmatter.ts](https://github.com/BrettNye/stoa/blob/main/src/core/frontmatter.ts)\n- [src/core/pages.ts](https://github.com/BrettNye/stoa/blob/main/src/core/pages.ts)\n- [src/core/evolution-claims.ts](https://github.com/BrettNye/stoa/blob/main/src/core/evolution-claims.ts)\n</details>\n\n# Agent Profiles and Evolution\n\n## Overview\n\nAgent Profiles and Evolution is a gamified system within the Stoa vault that models agent identities as collectible profiles with species characteristics, evolution stages, and platform-tracked statistics. The system combines the vault's knowledge management with external platform integration via the Stadium API to create persistent, trackable agent personas.\n\n**资料来源：** [src/tools/profile-register.ts:1-28]()\n\n## Architecture\n\n```mermaid\ngraph TD\n    subgraph \"Vault Layer\"\n        P[Profile Page]\n        FM[Frontmatter]\n        W[Wikis Directory]\n    end\n    \n    subgraph \"Profile Creation\"\n        RT[routes-write.ts]\n        NT[newTool.handler]\n        RR[Rarity Roll]\n        SR[Shiny Roll]\n    end\n    \n    subgraph \"Platform Integration\"\n        SC[StadiumClient]\n        PA[/profiles/register API]\n        PR[Platform Response]\n    end\n    \n    subgraph \"Evolution System\"\n        EC[evolution-claims.ts]\n        EV[Evolution Logic]\n    end\n    \n    P --> FM\n    FM --> RT\n    W --> P\n    RT --> NT\n    NT --> RR\n    RR --> SR\n    SR --> SC\n    SC --> PA\n    PA --> PR\n    PR --> EC\n    EC --> EV\n    \n    style P fill:#e1f5fe\n    style SC fill:#fff3e0\n    style EV fill:#e8f5e9\n```\n\n## Profile Structure\n\n### Profile File Location\n\nProfiles are stored as markdown files in the vault with a standardized path structure:\n\n```\nwikis/<wiki>/profiles/<profile_id>.md\n```\n\n**资料来源：** [src/tools/profile-register.ts:17-18]()\n\n### Frontmatter Schema\n\nProfile pages use a specialized frontmatter schema with the following key fields:\n\n| Field | Type | Required | Description |\n|-------|------|----------|-------------|\n| `id` | string | Yes | Must match `^profile-` pattern |\n| `title` | string | Yes | Display name for the profile |\n| `type` | enum | Yes | Always `\"profile\"` |\n| `wiki` | string | Yes | Parent wiki namespace |\n| `status` | enum | No | Page status (draft/active/accepted/superseded/archived) |\n| `pokemon` | string | No | Species name (v1.5 convention) |\n| `species_name` | string | No | Legacy species name (fallback) |\n| `evolution_stage` | string | No | Stage identifier (defaults to \"basic\") |\n| `pokemon_type` | string | No | Type classification |\n| `dev_specialty` | string | No | Developer specialty marker |\n| `platform_profile_id` | string | No | Stadium platform ID (set post-registration) |\n| `platform_stats` | object | No | Stats returned from platform |\n\n**资料来源：** [src/core/frontmatter.ts:23-45](), [src/transport/ui/routes-write.ts:88-92]()\n\n## Profile Registration Flow\n\nThe registration process synchronizes vault profiles with the external Stadium platform:\n\n```mermaid\nsequenceDiagram\n    participant Agent\n    participant MCP as MCP Server\n    participant Vault as Vault FS\n    participant Stadium as Stadium API\n    \n    Agent->>MCP: profile-register(profile_id)\n    MCP->>Vault: Read wikis/<wiki>/profiles/<id>.md\n    Vault->>MCP: Raw file content\n    MCP->>MCP: parseFrontmatter()\n    Note over MCP: Extract pokemon/species_name\n    MCP->>Stadium: POST /profiles/register\n    Stadium->>MCP: { profile_id, stats }\n    MCP->>Vault: upsertPage() with platform fields\n    MCP->>Agent: Registration result\n```\n\n**资料来源：** [src/tools/profile-register.ts:13-27]()\n\n### Registration Tool Interface\n\n```typescript\nconst Input = z.object({\n  profile_id: z.string().regex(/^profile-/),\n  wiki: z.string().optional()\n});\n```\n\n**资料来源：** [src/tools/profile-register.ts:20-24]()\n\n## Profile Creation (UI Routes)\n\nThe `routes-write.ts` module handles interactive profile creation with gamification elements:\n\n**资料来源：** [src/transport/ui/routes-write.ts:78-130]()\n\n### Creation Parameters\n\n| Parameter | Source | Description |\n|-----------|--------|-------------|\n| `wiki` | Computed | Defaults to `\"_agents\"` |\n| `title` | Computed | Format: `<species> agent` |\n| `frontmatterExtras.pokemon` | `selected_species` | Species name |\n| `frontmatterExtras.evolution_stage` | `evolution_stage` | Defaults to `\"basic\"` |\n| `frontmatterExtras.pokemon_type` | `pokemon_type` | Optional type |\n| `frontmatterExtras.dev_specialty` | `dev_specialty` | Optional specialty |\n\n**资料来源：** [src/transport/ui/routes-write.ts:80-93]()\n\n### Gamification: Rarity and Shiny Rolls\n\nDuring profile creation, two gamification rolls occur before the file is written:\n\n```typescript\nlet rarity: \"common\" | \"baby\" | \"legendary\" | \"mythical\" = \"common\";\nlet isShiny = false;\n```\n\n**资料来源：** [src/transport/ui/routes-write.ts:96-97]()\n\n| Roll | Probability | Effect |\n|------|-------------|--------|\n| Rarity | Varies by species | Determines rarity tier |\n| Shiny | 1/64 (1.5625%) | Applies shiny modifier to profile |\n\nThe shiny roll fetches species data and persists the result into the profile frontmatter.\n\n**资料来源：** [src/transport/ui/routes-write.ts:98-112]()\n\n## Evolution System\n\nThe evolution system is implemented across multiple modules that track and process evolution-related claims:\n\n### Evolution Claims\n\nThe `evolution-claims.ts` module handles the logic for processing evolution-related claims within the claims store. This system validates evolution conditions and updates profile states accordingly.\n\n**资料来源：** [src/core/evolution-claims.ts](file context provided in repository)\n\n### Evolution Workflow\n\n```mermaid\ngraph LR\n    A[Profile Created] --> B{Claims Accumulated}\n    B -->|Sufficient| C[Evolution Trigger]\n    B -->|Insufficient| D[Wait State]\n    C --> E[Evolution Validation]\n    E -->|Valid| F[Profile Updated]\n    E -->|Invalid| G[Reject Evolution]\n    F --> H[Platform Sync]\n    D --> B\n```\n\n## Profile Identification\n\n### Supported ID Patterns\n\nThe system supports multiple profile identification patterns:\n\n| Pattern | Description | Example |\n|---------|-------------|---------|\n| Standard | `profile-<slug>.md` | `profile-fire-type.md` |\n| Agent-specific | `profile-<agent-name>` | `profile-claude` |\n\n**资料来源：** [src/core/pages.ts:45-60]()\n\n### Path Resolution\n\nThe `pathForPage` function resolves profile paths:\n\n```typescript\n// Profile pages use the profiles subdirectory\nconst path = join(vaultPath, \"wikis\", wiki, \"profiles\", `${id}.md`);\n```\n\n**资料来源：** [src/core/pages.ts:47-49]()\n\n## Stadium Platform Integration\n\n### Client Architecture\n\nThe `StadiumClient` handles all communication with the Stadium platform:\n\n- **Base URL**: Configured via `resolveStadiumConfig()`\n- **Endpoint**: `/profiles/register` for profile creation\n- **Error Handling**: Propagates `StadiumApiError` with `error_code`\n\n**资料来源：** [src/tools/profile-register.ts:23]()\n\n### Platform Data Flow\n\n```\n┌─────────────────┐     ┌──────────────────┐     ┌─────────────────┐\n│   Vault File    │────▶│  profile-register │────▶│ Stadium API     │\n│   (pokemon: X)  │     │  Tool            │     │ POST /register  │\n└─────────────────┘     └──────────────────┘     └─────────────────┘\n                              │                        │\n                              ▼                        ▼\n                        ┌──────────────────┐     ┌─────────────────┐\n                        │ upsertPage()     │◀────│ profile_id      │\n                        │ (persist result) │     │ stats           │\n                        └──────────────────┘     └─────────────────┘\n```\n\n### Error Propagation\n\nServer errors from the Stadium platform are propagated as `StadiumApiError`. Common error codes include:\n\n- `pokeapi_unknown_species`: Species not found in platform\n- Network failures: Caught and returned with descriptive messages\n\n**资料来源：** [src/transport/ui/routes-write.ts:100-105]()\n\n## Configuration and Defaults\n\n| Setting | Default | Source |\n|---------|---------|--------|\n| Default Wiki | `_agents` | [routes-write.ts:78]() |\n| Evolution Stage | `\"basic\"` | [routes-write.ts:90]() |\n| Shiny Probability | 1/64 | [routes-write.ts:98-112]() |\n| Platform Endpoint | `/profiles/register` | [profile-register.ts:23]() |\n\n## Related Tools\n\n| Tool | Purpose |\n|------|---------|\n| `vault.profile-register` | Register profile with Stadium platform |\n| `vault.evolve-profile` | Trigger evolution on eligible profiles |\n| `vault.refresh-profile-memory` | Update agent memory in profile |\n\n**资料来源：** [src/tools/profile-register.ts:31-35]()\n\n## Future Considerations\n\nThe current implementation (v1.5 convention) stores species information in the `pokemon` frontmatter field. The system maintains backward compatibility with the legacy `species_name` field for existing profiles. Future versions may expand the evolution system to include:\n\n- Multi-stage evolution chains\n- Evolution condition validation via claims\n- Platform-synced evolution history\n\n---\n\n<a id='task-workflow'></a>\n\n## Task Workflow System\n\n### 相关页面\n\n相关主题：[Channels and Claims](#channels-claims), [Core Concepts and Vocabulary](#concepts-vocabulary)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/core/tasks.ts](https://github.com/BrettNye/stoa/blob/main/src/core/tasks.ts)\n- [src/tools/merge-record.ts](https://github.com/BrettNye/stoa/blob/main/src/tools/merge-record.ts)\n- [src/core/frontmatter.ts](https://github.com/BrettNye/stoa/blob/main/src/core/frontmatter.ts)\n- [src/core/eventbus/matchers/task.ts](https://github.com/BrettNye/stoa/blob/main/src/core/eventbus/matchers/task.ts)\n- [src/core/disk-fallback.ts](https://github.com/BrettNye/stoa/blob/main/src/core/disk-fallback.ts)\n- [README.md](https://github.com/BrettNye/stoa/blob/main/README.md)\n</details>\n\n# Task Workflow System\n\nThe Task Workflow System in Stoa provides a structured mechanism for creating, tracking, claiming, and resolving tasks across the vault's wiki-based knowledge management environment. It integrates with the broader event bus system for real-time state change notifications and supports atomic task claiming to prevent race conditions in multi-agent scenarios.\n\n## Overview\n\nThe Task Workflow System serves as the coordination backbone for agent-driven work items within Stoa. It enables:\n\n- **Task lifecycle management** — creation, status tracking, and resolution\n- **Atomic claiming** — race-safe task assignment to agents\n- **Two-phase task lookup** — fast index-based retrieval with disk-scan fallback\n- **Event-driven state propagation** — real-time task status change notifications via the event bus\n- **Optimistic Concurrency Control (OCC)** — safe concurrent updates using `expected_updated` timestamps\n\n资料来源：[README.md:1-20]()\n\n## Core Data Model\n\n### Task Interface\n\n```typescript\ninterface Task {\n  id: string;\n  title: string;\n  type: string;\n  wiki: string;\n  status: string;\n  claimed_by?: string;\n  claimed_at?: string;\n  updated: string;\n  body: string;\n}\n```\n\nThe `Task` interface represents a work item stored as markdown frontmatter within `wikis/<wiki>/tasks/` directories. Key fields include:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `id` | `string` | Unique task identifier (kebab-case per `HARD_KNOWLEDGE_TYPES`) |\n| `wiki` | `string` | The wiki namespace containing this task |\n| `status` | `string` | Current task status (e.g., `pending`, `claimed`, `merged`) |\n| `claimed_by` | `string?` | Agent ID that claimed this task |\n| `claimed_at` | `string?` | ISO timestamp when the task was claimed |\n| `updated` | `string` | ISO date of last modification (used for OCC) |\n\n资料来源：[src/core/tasks.ts:1-30]()\n\n### Task Status Values\n\nThe system uses a defined set of task statuses aligned with the `PageStatus` enum:\n\n| Status | Description |\n|--------|-------------|\n| `draft` | Initial state; task created but not ready for work |\n| `active` | Task is open and in progress |\n| `claimed` | Task has been assigned to an agent |\n| `merged` | Task work has been merged/completed |\n| `archived` | Task is no longer active |\n\n资料来源：[src/core/frontmatter.ts:1-20]()\n\n## Task Lookup Architecture\n\nStox implements a two-phase task lookup strategy to balance performance with data freshness.\n\n```mermaid\ngraph TD\n    A[Find Task by ID] --> B{Fast Path:<br/>Index Lookup}\n    B -->|Found| C[Return Task]\n    B -->|Not Found| D{Slow Path:<br/>Disk Scan}\n    D -->|Found| C\n    D -->|Not Found| E[Return null]\n```\n\n### Phase 1: Fast Path — Index Lookup\n\nThe system first queries `_index/pages.json` for the task:\n\n```typescript\nconst idx = loadIndex(vaultPath);\nconst hit = idx.pages.find(p => p.id === taskId && p.type === \"task\");\nif (hit) {\n  return {\n    wiki: hit.wiki,\n    updated: hit.updated,\n    status: String((hit as any).status ?? \"\")\n  };\n}\n```\n\nThis path executes in O(n) on the index array and succeeds for all tasks that have been indexed since their last modification. 资料来源：[src/tools/merge-record.ts:1-40]()\n\n### Phase 2: Slow Path — Disk Scan Fallback\n\nWhen the index lacks the task (e.g., tasks authored directly on disk between reindexes), the system falls back to a disk scan:\n\n```typescript\nreturn findTaskOnDisk(vaultPath, taskId);\n```\n\nThe `findTaskOnDisk` function delegates to the generalized `findOnDisk` utility in `core/disk-fallback.ts`, restricting results to `type: \"task\"`. This handles the case surfaced in Phase-3 Wave 5 T5-3 where tasks created via direct file authoring were immediately followed by a `vault.merge-record` call that silently missed the transition. 资料来源：[src/core/tasks.ts:1-30]()\n\n## Task Claiming\n\nThe atomic task claiming mechanism prevents race conditions when multiple agents attempt to claim the same task simultaneously.\n\n### Claim Operation\n\n```typescript\nexport class AlreadyClaimedError extends Error {\n  code = \"AlreadyClaimed\" as const;\n}\n```\n\nWhen an agent attempts to claim a task:\n\n1. The system loads the current task state\n2. If `claimed_by` is already set, the race-loser receives `AlreadyClaimedError`\n3. If unclaimed, the task is atomically updated with `claimed_by` and `claimed_at`\n\nThe `vault.task-claim` tool implements this atomicity, ensuring only one agent successfully claims a task. 资料来源：[src/tools/task-claim.ts]()\n\n### Task Transition Rules\n\nThe `merge-record.ts` module defines conditional task transition logic:\n\n```typescript\nfunction computeTaskTransition(status: string, task_id: string): TaskTransition | null {\n  // Returns a transition only when status === \"merged\" AND task_id is non-empty\n  // For all halt/fail statuses it returns null and the task is NOT touched\n}\n```\n\nThis rule ensures that:\n- Only `merged` status triggers a task transition\n- The journal is written regardless of whether the task update succeeds\n- Failure/halt journals are safe to re-run without side effects\n\n资料来源：[src/tools/merge-record.ts:1-60]()\n\n## Event Bus Integration\n\nThe task system integrates with Stoa's event bus for real-time state change notifications.\n\n### Task State Matcher\n\n```typescript\nexport const taskStateMatcher: VaultStateMatcher = {\n  key: \"task\",\n  extractKey(parsed) { return String(parsed.frontmatter.id); },\n  diff(prev, cur) {\n    if (cur.status === prev.status && cur.owner === prev.owner) {\n      return { emit: false };\n    }\n    const enrichment: Partial<VaultEvent> = {};\n    if (cur.status !== prev.status) {\n      enrichment.task_status_change = { from: prev.status, to: cur.status };\n    }\n    if (cur.owner !== prev.owner) {\n      enrichment.task_owner_change = { from: prev.owner, to: cur.owner };\n    }\n    return { emit: true, enrichment };\n  },\n  nextState(parsed) { return pickTaskState(parsed.frontmatter); },\n  init(_path, parsed) { return pickTaskState(parsed.frontmatter); },\n};\n```\n\nThe matcher extracts task state from frontmatter and emits events for:\n- `task_status_change` — when status transitions (e.g., `active` → `merged`)\n- `task_owner_change` — when `claimed_by` changes\n\n资料来源：[src/core/eventbus/matchers/task.ts:1-30]()\n\n### State Extraction\n\n```typescript\nfunction pickTaskState(fm: Record<string, any>): TaskState {\n  return {\n    status: String(fm.status ?? \"draft\"),\n    owner: fm.claimed_by ? String(fm.claimed_by) : undefined,\n  };\n}\n```\n\n## Task Operations\n\n### Available Task Tools\n\n| Tool | Description |\n|------|-------------|\n| `vault.task-create` | Create a new task in a specified wiki |\n| `vault.task-list` | List tasks with optional filters |\n| `vault.task-update` | Update task fields (status, claimed_by, etc.) |\n| `vault.task-claim` | Atomically claim a pending task |\n\n资料来源：[README.md:1-20]()\n\n### Optimistic Concurrency Control\n\nTask updates use OCC to prevent lost updates:\n\n```typescript\ninterface ReleaseInput {\n  task_id: string;\n  expected_updated: string;  // Timestamp from last known state\n  wiki: string;\n  reason?: string;\n}\n```\n\nThe system compares the provided `expected_updated` against the current `updated` value. If they match, the update proceeds; otherwise, it fails to prevent concurrent modification.\n\n## Journal Integration\n\nWhen `merge-record.ts` processes a merged pull request:\n\n1. Writes journal file at `wikis/_agents/journal/<journal_id>.md`\n2. Idempotent rewrite — same `now` + same input produces same `journal_id`\n3. Conditional task transition via `computeTaskTransition`\n4. `task_updated: false` when task_id not found, but journal still written\n\n资料来源：[src/tools/merge-record.ts:1-30]()\n\n## Configuration\n\nTask behavior is configurable via `_meta/lint-config.yaml`:\n\n| Key | Default | Description |\n|-----|---------|-------------|\n| `task.min_cluster_size` | `3` | Minimum cluster size for synthesis debt detection |\n\nNote: Task-specific configuration loading is pending (resolution-lifecycle spec implementation).\n\n## Related Concepts\n\n- **Synthesis Debt** — Tasks may be created to address synthesis clusters\n- **Claim Clustering** — Related claim grouping logic\n- **Task Readiness** — Determines when tasks are ready for claiming\n- **Event Bus** — Real-time task event propagation\n\n---\n\n<a id='channels-claims'></a>\n\n## Channels and Claims\n\n### 相关页面\n\n相关主题：[Task Workflow System](#task-workflow), [Event Bus System](#event-bus-system)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/core/channel.ts](https://github.com/BrettNye/stoa/blob/main/src/core/channel.ts)\n- [src/core/decay.ts](https://github.com/BrettNye/stoa/blob/main/src/core/decay.ts)\n- [src/core/claim-render.ts](https://github.com/BrettNye/stoa/blob/main/src/core/claim-render.ts)\n- [src/tools/claim.ts](https://github.com/BrettNye/stoa/blob/main/src/tools/claim.ts)\n- [src/core/synthesize.ts](https://github.com/BrettNye/stoa/blob/main/src/core/synthesize.ts)\n- [src/core/frontmatter.ts](https://github.com/BrettNye/stoa/blob/main/src/core/frontmatter.ts)\n- [src/core/lint.ts](https://github.com/BrettNye/stoa/blob/main/src/core/lint.ts)\n</details>\n\n# Channels and Claims\n\n## Overview\n\nChannels and Claims are two interconnected systems within the Stoa vault that enable coordination and knowledge assertion respectively. Channels provide a pub/sub mechanism for cross-instance communication, while Claims represent structured knowledge assertions with built-in confidence scoring and temporal decay.\n\n## Channels\n\n### Purpose\n\nChannels enable coordination and communication across multiple vault instances or agents. They function as a lightweight messaging layer backed by journal pages stored directly in the vault filesystem.\n\n### Architecture\n\nChannels are implemented as journal pages with a `channel` field in their frontmatter. The system leverages the existing page indexing infrastructure rather than maintaining a separate message broker.\n\n```mermaid\ngraph TD\n    A[Agent/Instance] -->|vault.channel-post| B[Journal Page]\n    B -->|type: journal<br/>channel: &lt;name&gt;<br/>wiki: &lt;wiki&gt;| C[Vault FS]\n    D[Other Agent] -->|vault.channel-tail| E[Channel Summary]\n    C -->|queryPages idx| E\n```\n\n### Channel Naming Convention\n\nChannels must follow a strict naming format validated at lint time:\n\n| Format | Regex | Example |\n|--------|-------|---------|\n| Lowercase kebab-case | `^[a-z0-9]+(-[a-z0-9]+)*$` | `pr-reviews`, `task-alerts` |\n\nValidation is enforced in `src/core/lint.ts`:\n\n```typescript\nif (p.channel && !/^[a-z0-9]+(-[a-z0-9]+)*$/.test(p.channel)) {\n  diagnostics.push({\n    severity: \"warning\", code: \"BAD_CHANNEL_FORMAT\",\n    page_id: p.id, wiki: p.wiki,\n    message: `channel \"${p.channel}\" must be lowercase kebab-case`\n  });\n}\n```\n资料来源：[src/core/lint.ts:47-54]()\n\n### Channel Summaries\n\nThe `channel-tail` tool aggregates journal entries into summaries containing:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `name` | string | Channel identifier |\n| `wiki` | string | Wiki where the channel exists |\n| `lastEntry` | object | Most recent entry with id, author, ts, excerpt |\n| `count24h` | number | Entries within the last 24 hours |\n\nEach summary caches author information and body excerpts (first 240 characters) from the actual page files to avoid repeated filesystem reads during aggregation.\n\n资料来源：[src/core/channel.ts:21-35]()\n\n### Resolving Channel Scope\n\nChannel queries are scoped by wiki. When listing or tailing channels, the system filters pages by:\n\n1. `type === \"journal\"` — Only journal pages participate in channels\n2. `wiki === opts.wiki` — Wiki isolation is enforced\n\n```typescript\nconst pages = queryPages(idx, { type: \"journal\", wiki: opts.wiki });\n```\n资料来源：[src/core/channel.ts:18]()\n\n## Claims\n\n### Purpose\n\nClaims represent structured knowledge assertions within the vault. They carry explicit confidence levels that decay over time, creating a system where knowledge freshness is tracked and surfaced.\n\n### Data Model\n\nClaims are stored as pages with the following frontmatter structure:\n\n```yaml\nid: <slug>\ntype: claim\ntitle: <human-readable title>\nauthored_by: <agent-or-human>\nconfidence: high | medium | low\nstatus: pending | accepted | retracted | rejected\nevidence:\n  - [[wikis/<wiki>/<type>/<id>]]\nlast_validated: YYYY-MM-DD\ncreated: YYYY-MM-DD\nupdated: YYYY-MM-DD\n```\n\n### Confidence Decay\n\nClaims use a temporal decay model to represent knowledge staleness. The effective confidence decreases based on:\n\n1. **Initial confidence level** — `high`, `medium`, or `low`\n2. **Time since last validation** — Measured in days\n3. **Configured half-life** — Number of days for confidence to halve\n\nThe effective confidence formula is documented in `claim-render.ts`:\n\n```typescript\nconst eff = effectiveConfidence(\n  {\n    confidence: claim.confidence,\n    last_validated: claim.last_validated,\n    status: claim.status,\n  },\n  today,\n  {\n    half_life_days: config.half_life_days,\n    effective_floor: config.effective_floor,\n  }\n);\n```\n资料来源：[src/core/claim-render.ts:45-57]()\n\n### Effective Confidence Computation\n\nThe decay system applies a floor to prevent confidence from reaching zero:\n\n| Parameter | Default | Purpose |\n|-----------|---------|---------|\n| `half_life_days` | Configurable | Days for confidence to halve |\n| `effective_floor` | Configurable | Minimum confidence value |\n\n### Rendering Claims\n\nClaims are rendered as bullet points in synthesis pages:\n\n```markdown\n- **`<key>`** — <body>. *(confidence <eff> as of <render-date>, validated <last_validated>, evidence: [[<first>]])*\n```\n\nThe system:\n- Rounds effective confidence to 2 decimal places\n- Uses `claim.summary` if available, falling back to `claim.body`\n- Includes only the first evidence entry\n- Collapses internal whitespace to maintain single-line bullets\n\n```typescript\n// Collapse all internal whitespace runs (incl. embedded newlines) to a\n// single space. `.trim()` alone leaves embedded `\\n` intact, which would\n// break the single-line bullet and corrupt the vault-claims:start..end\n```\n资料来源：[src/core/claim-render.ts:64-70]()\n\n### Claim Lifecycle\n\n```mermaid\nstateDiagram-v2\n  [*] --> pending: Creation\n  pending --> accepted: Validation by curator\n  pending --> rejected: Conflicting higher-confidence claim\n  accepted --> retracted: Author retracts\n  accepted --> rejected: Override with strictly higher confidence\n  retracted --> [*]\n  rejected --> [*]\n```\n\n### Claim Operations\n\n#### Retraction\n\nAuthors may retract their own claims, recording:\n- `retracted_at`: Timestamp of retraction\n- `retracted_by`: Author performing retraction\n- `retraction_reason`: Human-readable explanation\n\nOnly the original author may retract a claim:\n\n```typescript\nif (target.authored_by !== as) {\n  throw new Error(\n    `only the original author may retract claim ${claimId}: authored_by=${target.authored_by ?? \"<unset>\"}, as=${as}`,\n  );\n}\n```\n资料来源：[src/tools/claim.ts:85-90]()\n\n#### Rejection\n\nClaims are rejected when a higher-confidence claim on the same assertion already exists:\n\n```typescript\nreturn {\n  claim_id: ex.id,\n  action: \"rejected\",\n  rejection: {\n    reason: `existing claim ${ex.id} has effective confidence ${existingEffective.toFixed(3)}; submission's ${yourConfidence} is not strictly higher`,\n    existing_id: ex.id,\n    existing_effective_confidence: existingEffective,\n    your_confidence: yourConfidence,\n  },\n};\n```\n资料来源：[src/tools/claim.ts:99-108]()\n\n### Claim Sorting in Syntheses\n\nWhen rendering synthesis pages, claims are sorted by a scoring function that accounts for effective confidence and profile affinity:\n\n```typescript\nconst score = (c: ParsedClaim) => {\n  const eff = effectiveConfidence(/* ... */);\n  const boost = (c.profile ?? []).includes(deployingProfileId) ? 0.1 : 0;\n  return eff + boost;\n};\nreturn [...claims].sort((a, b) => score(b) - score(a));\n```\n资料来源：[src/core/claim-render.ts:26-34]()\n\n### Synthesis Integration\n\nClaims are incorporated into synthesis pages via the `sources` frontmatter field:\n\n```typescript\nsources: inputIds.map(i => `[[wikis/${wiki}/${typeFolderForId(i)}/${i}]]`)\n```\n资料来源：[src/core/synthesize.ts:62]()\n\nThe synthesis metadata includes:\n\n| Field | Value |\n|-------|-------|\n| `type` | `synthesis` |\n| `status` | `draft` |\n| `last_compiled` | ISO date of generation |\n\n## Lint Rules\n\n### Claim Scope Validation\n\nClaims without scope (profile, move, scope_wiki, or tags) receive a warning:\n\n```typescript\nif (!allEmpty) return [];\nreturn [{\n  ruleId: \"claim-with-no-scope\",\n  severity: \"warn\",\n  line: 1,\n  message: \"Claim has no scope (profile/move/scope_wiki/tags all empty); no read path will surface it.\",\n}];\n```\n资料来源：[src/core/lint-checks/claim-with-no-scope.ts:17-24]()\n\n### Channel Format Validation\n\nChannel identifiers are validated during lint runs to ensure consistency:\n\n| Check | Severity | Message |\n|-------|----------|---------|\n| Invalid kebab-case format | `warning` | `channel \"<name>\" must be lowercase kebab-case` |\n\n## Related Tools\n\n| Tool | Purpose |\n|------|---------|\n| `vault.channel-post` | Post a message to a coordination channel |\n| `vault.channel-tail` | Pull recent entries from a channel |\n| `vault.claim` | Submit, validate, or retract claims |\n| `vault.synthesize` | Compile synthesis pages incorporating claims |\n\n---\n\n<a id='runtime-adapters'></a>\n\n## Runtime Adapters\n\n### 相关页面\n\n相关主题：[Sync Agents and Skills](#sync-agents-skills), [Agent Profiles and Evolution](#profiles-evolution)\n\nThe repository context provided does not contain the source files required for this topic:\n\n- `src/core/runtime-adapters/types.ts`\n- `src/core/runtime-adapters/registry.ts`\n- `src/core/runtime-adapters/claude-code.ts`\n- `src/core/subagent-protocol.ts`\n- `src/core/subagent-intent.ts`\n\nThese files are listed in the `<details>` block requirements but are **not present** in the retrieved repository context. Without access to these source files, I cannot generate an accurate technical wiki page about the Runtime Adapters feature.\n\n**Available alternatives in the context:**\n\nThe context does contain `src/core/deployments.ts` which has partial runtime-related code:\n\n```typescript\nexport interface DeploymentEntry {\n  repo_path: string;\n  target: \"claude-code\" | \"openclaw\" | \"codex\";\n  mode: DeployMode;\n  actual_mode?: DeployMode;\n  synced_at: string;\n  runtime?: RuntimeName;\n  source_revision?: string;\n  subagent_def_path?: string;\n}\n```\n\nThis shows runtime targets exist (`claude-code`, `openclaw`, `codex`) and a `RuntimeName` type is referenced, but the core runtime-adapters module files are needed to document the complete system.\n\n**To proceed, please provide the content of the following files:**\n\n1. `src/core/runtime-adapters/types.ts`\n2. `src/core/runtime-adapters/registry.ts`\n3. `src/core/runtime-adapters/claude-code.ts`\n4. `src/core/subagent-protocol.ts`\n5. `src/core/subagent-intent.ts`\n\nOnce these files are provided, I can generate the comprehensive technical wiki page with proper citations, Mermaid diagrams, and tables as requested.\n\n---\n\n<a id='sync-agents-skills'></a>\n\n## Sync Agents and Skills\n\n### 相关页面\n\n相关主题：[Runtime Adapters](#runtime-adapters), [Agent Profiles and Evolution](#profiles-evolution)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/tools/sync-skills.ts](https://github.com/BrettNye/stoa/blob/main/src/tools/sync-skills.ts)\n- [src/core/skills.ts](https://github.com/BrettNye/stoa/blob/main/src/core/skills.ts)\n- [src/core/skills-platform.ts](https://github.com/BrettNye/stoa/blob/main/src/core/skills-platform.ts)\n- [src/core/deployments.ts](https://github.com/BrettNye/stoa/blob/main/src/core/deployments.ts)\n- [src/tools/claim.ts](https://github.com/BrettNye/stoa/blob/main/src/tools/claim.ts)\n</details>\n\n# Sync Agents and Skills\n\nThe sync agents and skills system is a core deployment mechanism that bridges the vault's canonical knowledge store with agent runtime environments. It provides two synchronized capabilities: **agent profile deployment** and **skills (moveset) deployment**, enabling consistent agent behavior across different execution contexts.\n\n## Architecture Overview\n\nThe system operates across three layers:\n\n| Layer | Purpose | Key Files |\n|-------|---------|-----------|\n| **CLI/API** | User-facing entry points | `src/tools/sync-skills.ts`, `src/cli/commands/sync-agents.ts` |\n| **Core Logic** | Business rules and deployment orchestration | `src/core/skills.ts`, `src/core/skills-platform.ts` |\n| **Persistence** | Deployment registry management | `src/core/deployments.ts` |\n\n```mermaid\ngraph TD\n    A[\"vault.sync-skills<br/>(MCP Tool)\"] --> B[\"Read Profile<br/>wikis/&lt;wiki&gt;/profiles/&lt;profileId&gt;.md\"]\n    B --> C[\"Extract moves[]<br/>from profile frontmatter\"]\n    C --> D{\"For each move\"}\n    D -->|Canonical path| E[\"wikis/_agents/moves/&lt;moveId&gt;/SKILL.md\"]\n    D -->|Deployed path| F[\"&lt;deployment.skills_dir&gt;/&lt;moveId&gt;/SKILL.md\"]\n    E --> G[\"probeSymlinkSupport()\"]\n    G --> H{\"Host supports symlinks?\"}\n    H -->|Yes| I[\"fs.symlinkSync()\"]\n    H -->|No| J[\"recursiveCopy()\"]\n    I --> K[\"mode: 'symlink'\"]\n    J --> L[\"mode: 'copy'\"]\n    K --> M[\"Update _index/deployments.json\"]\n    L --> M\n    M --> N[\"Return DeploymentEntry[]\"]\n```\n\n资料来源：[src/tools/sync-skills.ts](https://github.com/BrettNye/stoa/blob/main/src/tools/sync-skills.ts)\n\n## Core Concepts\n\n### Deployment Target\n\nThe system supports multiple agent runtimes:\n\n```typescript\ntype DeployTarget = \"claude-code\" | \"openclaw\" | \"codex\";\n```\n\nEach target represents a distinct agent runtime that consumes skills from the local filesystem. 资料来源：[src/core/deployments.ts:14](https://github.com/BrettNye/stoa/blob/main/src/core/deployments.ts#L14)\n\n### Deploy Mode\n\nTwo deployment modes control how skills are materialized:\n\n| Mode | Behavior | Fallback |\n|------|----------|----------|\n| `symlink` | Creates symbolic links from deployment directory to canonical vault files | Auto-falls back to `copy` on EPERM/EACCES/EEXIST |\n| `copy` | Recursively copies the move directory to the deployment path | None |\n\nThe system automatically probes symlink support at `<targetDir>/.symlink-probe-<random>` before attempting symlink deployment. 资料来源：[src/core/skills-platform.ts:63-75](https://github.com/BrettNye/stoa/blob/main/src/core/skills-platform.ts#L63-L75)\n\n### Drift Detection\n\nThe `detectDriftAt()` function compares canonical and deployed skill files using content hashing:\n\n```typescript\nexport function detectDriftAt(\n  deployment: DriftDeployment,\n  vaultPath: string\n): DriftReport[]\n```\n\n**Drift report rules:**\n\n| Condition | Report | Action |\n|-----------|--------|--------|\n| Canonical missing | Throws | Vault integrity bug |\n| Deployed missing | `{ kind: \"missing\", actual_hash: undefined }` | Deploy needed |\n| Hashes differ | `{ kind: \"hash-mismatch\", actual_hash }` | Re-deploy needed |\n| Hashes match | No entry (omit) | No action |\n\n资料来源：[src/core/skills-platform.ts:27-40](https://github.com/BrettNye/stoa/blob/main/src/core/skills-platform.ts#L27-L40)\n\n## Data Models\n\n### DeploymentEntry\n\n```typescript\nexport interface DeploymentEntry {\n  repo_path: string;\n  target: \"claude-code\" | \"openclaw\" | \"codex\";\n  mode: DeployMode;\n  actual_mode?: DeployMode;\n  synced_at: string;\n\n  // v1.7 additions\n  runtime?: RuntimeName;\n  source_revision?: string;\n  subagent_def_path?: string;\n}\n```\n\nThe `actual_mode` field records whether symlinking was actually used (vs requested), enabling truthful reporting. 资料来源：[src/core/deployments.ts:19-31](https://github.com/BrettNye/stoa/blob/main/src/core/deployments.ts#L19-L31)\n\n### DeploymentRegistry\n\n```typescript\nexport type DeploymentRegistry = Record<string, DeploymentEntry[]>;\n```\n\nThe registry is keyed by `profileId`, with each entry representing one deployment of that profile. Stored at `_index/deployments.json` at the vault root. 资料来源：[src/core/deployments.ts:33-34](https://github.com/BrettNye/stoa/blob/main/src/core/deployments.ts#L33-L34)\n\n## Skills Structure\n\n### Move Directory Layout\n\nSkills (called \"moves\") follow a directory convention:\n\n```\nwikis/_agents/moves/\n├── move-flamethrower/\n│   └── SKILL.md\n├── move-thunderbolt/\n│   └── SKILL.md\n└── move-protect/\n    └── SKILL.md\n```\n\n- Each move is a directory containing a single `SKILL.md` file\n- Move IDs are used as directory names\n- The directory layout enables recursive deployment operations 资料来源：[src/core/skills-platform.ts:18-23](https://github.com/BrettNye/stoa/blob/main/src/core/skills-platform.ts#L18-L23)\n\n### Profile Structure\n\nProfiles reference moves via the `moves` frontmatter field:\n\n```yaml\n---\nid: profile-charizard\ntitle: Charizard Combat Profile\ntype: profile\nwiki: _agents\nmoves:\n  - move-flamethrower\n  - move-thunderbolt\n  - move-dragon-dance\n---\n```\n\nThe `moves` array is read during sync to determine which skills to deploy. 资料来源：[src/core/skills.ts](https://github.com/BrettNye/stoa/blob/main/src/core/skills.ts)\n\n## Sync Workflow\n\n### vault.sync-skills Tool\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant VaultMCP\n    participant ProfileStore\n    participant DeployModule\n    participant Registry\n\n    Client->>VaultMCP: vault.sync-skills({profile_id, wiki?})\n    VaultMCP->>ProfileStore: Read wikis/<wiki>/profiles/<profile_id>.md\n    ProfileStore-->>VaultMCP: Profile with moves[]\n    \n    VaultMCP->>VaultMCP: For each moveId in moves[]:\n    VaultMCP->>DeployModule: probeSymlinkSupport(targetDir)\n    DeployModule-->>VaultMCP: supportsSymlinks: boolean\n    \n    alt supportsSymlinks\n        VaultMCP->>DeployModule: deployMove(src, dest, \"symlink\")\n    else\n        VaultMCP->>DeployModule: deployMove(src, dest, \"copy\")\n    end\n    \n    DeployModule->>Registry: Update _index/deployments.json\n    VaultMCP-->>Client: DeploymentEntry[]\n```\n\n### Deployment Persistence\n\nThe registry stores each deployment with idempotent semantics:\n\n```typescript\nexport function writeDeployments(vaultPath: string, registry: DeploymentRegistry): void\nexport function readDeployments(vaultPath: string): DeploymentRegistry\n```\n\nRe-running sync with identical inputs produces byte-identical registry output. 资料来源：[src/core/deployments.ts:38-52](https://github.com/BrettNye/stoa/blob/main/src/core/deployments.ts#L38-L52)\n\n## Configuration\n\n### Vault Path Resolution\n\n| Priority | Source | Key |\n|----------|--------|-----|\n| 1 | `--vault=` CLI flag | `config.vaultPath` |\n| 2 | `STOA_VAULT_PATH` env var | Falls through to default |\n| 3 | Working directory | `.` |\n\n### Wiki Resolution\n\n| Priority | Source |\n|----------|--------|\n| 1 | `wiki:` argument on tool call |\n| 2 | `--default-wiki=<name>` CLI flag |\n| 3 | `.active-wiki` file at vault root |\n\n### Target Directory\n\nDeployment target directories are specified in the deployment registry entry. The `repo_path` determines where skills are deployed relative to the vault root or an absolute path.\n\n## Error Handling\n\n### Error Scenarios\n\n| Scenario | Behavior | Recovery |\n|----------|----------|----------|\n| Unknown profile ID | `UnknownProfileError` | Provide valid profile ID |\n| Missing canonical move | Throws during drift check | Vault integrity issue |\n| Symlink permission denied | Auto-fallback to `copy` | Transparent |\n| Deployment file locked | Propagates error | Retry |\n| Profile missing `moves` field | Empty deployment | Check profile definition |\n\n### Claim Retraction Integration\n\nThe deployment system integrates with the claims subsystem for agent identity verification:\n\n```typescript\nif (target.authored_by !== as) {\n  throw new Error(\n    `only the original author may retract claim ${claimId}`\n  );\n}\n```\n\nThis ensures deployment operations respect agent authorship boundaries. 资料来源：[src/tools/claim.ts:42-46](https://github.com/BrettNye/stoa/blob/main/src/tools/claim.ts#L42-L46)\n\n## CLI Integration\n\n### Commands\n\n```bash\nstoa --vault=/path/to/vault sync-skills --profile=profile-charizard --wiki=_agents\n```\n\n### Idempotency\n\n- Same profile + same inputs = same output (byte-identical)\n- `source_revision` enables short-circuit of re-deploys\n- Drift detection prevents unnecessary re-synchronization\n\n## Backward Compatibility\n\nThe deployment system maintains backward compatibility across versions:\n\n| Version | Change | Compatibility |\n|---------|--------|----------------|\n| v1.5 | Original schema | Base |\n| v1.6 | Added `actual_mode` | Defaults `actual_mode` to `mode` |\n| v1.7 | Added `runtime`, `source_revision`, `subagent_def_path` | Defaults `runtime` to `target` |\n\n```typescript\n// Back-compat: v1.5 entries lack actual_mode. Default to mode.\nconst actualMode = entry.actual_mode ?? entry.mode;\n\n---\n\n<a id='tool-categories'></a>\n\n## Tool Categories Reference\n\n### 相关页面\n\n相关主题：[Introduction to Stoa](#introduction), [Channels and Claims](#channels-claims)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/core/synthesize.ts](https://github.com/BrettNye/stoa/blob/main/src/core/synthesize.ts)\n- [src/core/syntheses.ts](https://github.com/BrettNye/stoa/blob/main/src/core/syntheses.ts)\n- [src/core/lint-checks/synthesis-debt.ts](https://github.com/BrettNye/stoa/blob/main/src/core/lint-checks/synthesis-debt.ts)\n- [src/core/channel.ts](https://github.com/BrettNye/stoa/blob/main/src/core/channel.ts)\n- [src/core/frontmatter.ts](https://github.com/BrettNye/stoa/blob/main/src/core/frontmatter.ts)\n- [src/transport/stdio.ts](https://github.com/BrettNye/stoa/blob/main/src/transport/stdio.ts)\n- [README.md](https://github.com/BrettNye/stoa/blob/main/README.md)\n</details>\n\n# Tool Categories Reference\n\n## Overview\n\nThe Stoa vault system exposes a collection of MCP (Model Context Protocol) tools organized into logical categories that handle knowledge retrieval, content creation, channel coordination, and linting operations. These tools operate on a vault directory structure where wikis contain typed pages with structured frontmatter and markdown bodies.\n\nThe tool system is designed around a wiki-centric data model where pages are typed (concept, spec, decision, synthesis, etc.), tagged, and optionally scoped to wikis or families. Tools provide both pull-based operations (read, recall) and push-based primitives (wait-for, channel-post), enabling both synchronous queries and event-driven workflows.\n\n资料来源：[README.md:1-50]()\n\n## Tool Category Taxonomy\n\nThe available tools are organized into four primary categories:\n\n| Category | Purpose | Typical Consumer |\n|----------|---------|------------------|\n| **Read — pull primitives** | Query existing vault content | Agents, humans |\n| **Write — content** | Create or modify vault pages | Agents |\n| **Wait — push primitives** | Block until vault events occur | Event-driven workflows |\n| **Coordination** | Cross-instance communication and task management | Multi-agent systems |\n\n资料来源：[README.md:1-50]()\n\n## Read Primitives\n\nRead tools retrieve information from the vault index or direct file access without modifying state.\n\n### Recall\n\nThe `vault.recall` tool searches the vault index for pages matching query parameters. It supports filtering by wiki, type, status, channel, and layer (knowledge vs execution types). Results include relevance-ranked hits with IDs and metadata.\n\n**Query Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `topic` | string | Search query text |\n| `wiki` | string (optional) | Limit to specific wiki |\n| `layer` | `\"all\" \\| \"knowledge\" \\| \"execution\"` | Filter by page type category |\n| `type` | string (optional) | Filter by exact page type |\n| `status` | string (optional) | Filter by page status |\n| `channel` | string (optional) | Filter by channel name |\n| `limit` | number | Maximum results (default 25) |\n\nThe recall mechanism uses tokenized full-text search with stop-word removal and stemming via the Porter stemmer. Results are ranked by relevance.\n\n资料来源：[src/core/index.ts:1-50]()\n\n### Read\n\nThe `vault.read` tool fetches a specific page by ID or path, returning parsed frontmatter and body content. Unlike recall which searches, read is a direct lookup operation.\n\n### Lint\n\nThe `vault.lint` tool runs diagnostic checks against the vault corpus. Lint checks validate structural properties and frontmatter invariants across the index.\n\n**Available Lint Checks:**\n\n| Code | Severity | Description |\n|------|----------|-------------|\n| `SYNTHESIS_DEBT` | warning | Hard-knowledge clusters without synthesis coverage |\n| `CLAIM_WITH_NO_SCOPE` | warn | Claims missing all scope fields |\n| `CROSS_WIKI_LINK_BROKEN` | error | Wikilinks pointing to non-existent pages |\n\nThe lint system distinguishes between Group A rules (fast, frontmatter-only) and Group B rules (claim-file parsing required). Synthesis debt is a structural-property rule that scales with vault growth since it requires no content reads.\n\n资料来源：[src/core/lint-checks/synthesis-debt.ts:1-60]()\n资料来源：[src/core/lint-checks/claim-with-no-scope.ts:1-30]()\n\n## Write Primitives\n\nWrite tools create or modify vault content. These operations are idempotent where possible and preserve manual edits.\n\n### Synthesize\n\nThe `vault.synthesize` tool compiles or refreshes a synthesis page from a set of input pages. Syntheses are mid-tier hub pages that distill clusters of related concepts, specs, or decisions into recallable views.\n\n**Synthesis Modes:**\n\n| Scope | ID Pattern | Wiki | Purpose |\n|-------|------------|------|---------|\n| `topic` | `synthesis-<slug>` | configurable (default: alpha) | General topic synthesis |\n| `memory` | `synthesis-<agent>-memory` | `_agents` | Per-agent memory compilation |\n\n**Frontmatter Template:**\n\n```yaml\nid: synthesis-<slug>\ntitle: \"<topic> — synthesis\"\ntype: synthesis\nwiki: alpha\nstatus: draft\ncreated: <today>\nupdated: <today>\nsummary: \"Synthesis of <N> pages on <topic>\"\ntags: []\nlast_compiled: <today>\nsources:\n  - [[wikis/alpha/concept/page-id-1]]\n  - [[wikis/alpha/spec/page-id-2]]\n```\n\nThe synthesis tool preserves manual edits in protected zones bounded by `<!-- manual_notes:start ... -->` and `<!-- manual_notes:end -->` markers. Re-compiles extract and re-apply content from these zones without losing human-authored prose.\n\n资料来源：[src/core/synthesize.ts:1-100]()\n资料来源：[src/core/frontmatter.ts:1-80]()\n\n### Inbox\n\nThe `vault.inbox` tool captures fleeting thoughts to the active wiki's `inbox/` directory. This provides a low-friction capture mechanism for ideas that don't yet warrant a full typed page.\n\n### New\n\nThe `vault.new` tool creates a typed page from a template. Supported types include:\n\n| Type | Filename Pattern | Notes |\n|------|------------------|-------|\n| `concept` | `concept-<slug>.md` | Knowledge atom |\n| `spec` | `spec-<slug>.md` | Technical specification |\n| `decision` | `decision-YYYY-MM-DD-<slug>.md` | Date-prefixed |\n| `journal` | `journal-YYYY-MM-DD-HHMM-<slug>.md` | Date+time required |\n| `move` | `move-<slug>/SKILL.md` | Directory layout |\n| `map` | `map.md` | Fixed canonical filename |\n| `synthesis` | `synthesis-<slug>.md` | Hub page |\n| `claim` | `claim-<slug>.md` | Assertion with evidence |\n| `idea` | `idea-<slug>.md` | Unvalidated concept |\n| `question` | `question-<slug>.md` | Open inquiry |\n| `source` | `source-<slug>.md` | External citation |\n| `guide` | `guide-<slug>.md` | Procedural documentation |\n\n资料来源：[src/core/ids.ts:1-50]()\n\n### Agent Journal\n\nThe `vault.agent-journal` tool appends a first-person agent reflection at end-of-task. Journals are typed pages with `channel: agent-log` that capture agent decision rationale and state transitions.\n\n## Wait (Push Primitives)\n\nWait tools implement blocking semantics for event-driven workflows, replacing polling with cursor-based catch-up.\n\n| Tool | Semantics |\n|------|-----------|\n| `vault.wait-for` | Block until one matching event lands |\n| `vault.wait-for-any` | Wake on first match across N filters (race) |\n| `vault.wait-for-all` | Wake when all N filters have matched at least once |\n| `vault.wait-for-many` | Bounded batch over a window |\n\nThese primitives use the stdio transport for MCP communication, maintaining a state cache for diffing prior and current vault events.\n\n资料来源：[src/transport/stdio.ts:1-80]()\n资料来源：[src/core/eventbus/state-cache.ts:1-40]()\n\n## Coordination Tools\n\n### Channel Post\n\nThe `vault.channel-post` tool posts to a coordination channel, enabling cross-instance communication. Channels are scoped to wikis and identified by kebab-case names.\n\n**Channel Entry Structure:**\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `id` | string | Page ID |\n| `channel` | string | Channel name |\n| `wiki` | string | Wiki scope |\n| `author` | string | Author identifier |\n| `ts` | ISO date | Timestamp |\n| `excerpt` | string | First 240 chars of body |\n| `pageId` | string | Reference to full page |\n\nThe channel system aggregates journal entries and provides 24-hour activity counts for monitoring.\n\n资料来源：[src/core/channel.ts:1-80]()\n\n### Task Claim\n\nThe `vault.task-claim` tool atomically claims a pending task. Race losers receive an `AlreadyClaimedError`, ensuring exactly-once task assignment in multi-agent scenarios.\n\n### Bootstrap Repo\n\nThe `vault.bootstrap-repo` tool wires a consuming repository with `.mcp.json` and a `CLAUDE.md` fragment, establishing the MCP configuration and agent instructions.\n\n### Sync Skills\n\nThe `vault.sync-skills` tool deploys agent profiles to a target skills directory, maintaining drift detection between canonical vault sources and deployed skill files.\n\n**Drift Detection:**\n\n| Condition | Behavior |\n|-----------|----------|\n| Canonical missing | Throw (vault-integrity bug) |\n| Deployed missing | Emit `{ kind: \"missing\", actual_hash: undefined }` |\n| Hash mismatch | Emit `{ kind: \"hash-mismatch\", actual_hash }` |\n| Hashes match | Omit from report |\n\n资料来源：[src/core/skills-platform.ts:1-80]()\n\n### Reindex\n\nThe `vault.reindex` tool regenerates `_index/` files and per-wiki `index.md`, rebuilding the search index after bulk operations or corruption recovery.\n\n## Synthesis Staleness Tracking\n\nThe system tracks when synthesis pages were last compiled to identify debt. Staleness is computed as the difference between current time and `last_compiled` frontmatter field.\n\n| Metric | Calculation |\n|--------|-------------|\n| `lag_days` | `(now - compiledMs) / MS_PER_DAY` |\n| Filter | `min_lag_days` threshold (default: none) |\n\nThis enables curators to identify syntheses that haven't been refreshed despite upstream changes to their source pages.\n\n资料来源：[src/core/syntheses.ts:1-80]()\n\n## Tool Data Flow\n\n```mermaid\ngraph TD\n    subgraph \"Read Primitives\"\n        R[Recall] -->|index query| I[VaultIndex]\n        RD[Read] -->|direct file| F[Markdown files]\n    end\n    \n    subgraph \"Write Primitives\"\n        S[Synthesize] -->|read prior| F\n        S -->|write| N[New file]\n        IN[Inbox] -->|append| I\n        AJ[Agent Journal] -->|append| C[Channel]\n    end\n    \n    subgraph \"Event System\"\n        W[Wait-for tools] -->|subscribe| E[Event Bus]\n        E -->|state diff| SC[State Cache]\n    end\n    \n    subgraph \"Coordination\"\n        CP[Channel Post] -->|broadcast| C\n        TC[Task Claim] -->|atomic| T[Task Registry]\n    end\n    \n    subgraph \"Validation\"\n        L[Lint] -->|check| CH[Claim Handlers]\n        L -->|check| SD[Synthesis Debt]\n        L -->|check| CW[Claim Scope]\n    end\n    \n    I -.->|rebuild| R\n    F -.->|parse| I\n```\n\n## Page Type Layering\n\nThe system distinguishes between two semantic layers:\n\n| Layer | Types | Role |\n|-------|-------|------|\n| **Knowledge** | concept, spec, decision, synthesis | Durable thinking content |\n| **Execution** | guide, source, idea, question | Procedural and citation |\n\nRecall and synthesis debt checks filter by layer, enabling scope-aware queries that don't mix execution metadata into knowledge graph traversals.\n\n资料来源：[src/core/index.ts:1-50]()\n资料来源：[src/core/lint-checks/synthesis-debt.ts:1-60]()\n\n## Family Resolution\n\nTools can operate at wiki or family scope. Family resolution follows a priority cascade:\n\n```mermaid\ngraph LR\n    A[CLI --family arg] --> B{Match?}\n    B -->|yes| Z[Return family]\n    B -->|no| C[Check .active-family file]\n    C --> D{Exists?}\n    D -->|yes| Z\n    D -->|no| E[Use defaultFamily config]\n    E --> F{Configured?}\n    F -->|yes| Z\n    F -->|no| G[Return null - single wiki]\n```\n\nWhen a wiki is explicitly specified alongside a family argument, the system validates consistency and throws `FamilyMismatchError` on mismatch.\n\n资料来源：[src/core/family.ts:1-80]()\n\n## Wikilink Resolution\n\nTools consume and produce wikilinks in the vault-root absolute form: `[[wikis/<wiki>/<type>/<id>(|alias)]]`. The wikilink extractor is code-fence-aware and handles both body content and frontmatter `related:` arrays.\n\n| Behavior | Scope |\n|----------|-------|\n| Top-level fenced blocks | Stripped |\n| Indented fenced blocks | Preserved |\n| Inline code spans | Preserved |\n| Malformed links | Silently skipped |\n\n资料来源：[src/core/wikilinks.ts:1-50]()\n\n## Configuration\n\nTools read configuration from `vault-mcp.json` in the vault root:\n\n| Key | Description |\n|-----|-------------|\n| `vaultPath` | Absolute path to vault directory |\n| `defaultWiki` | Fallback wiki when unspecified |\n| `defaultFamily` | Fallback family scope |\n\nThe stdio server logs its configuration on startup: `vault-mcp stdio server ready (vault=<path>, default-wiki=<wiki>, default-family=<family>)`.\n\n资料来源：[src/transport/stdio.ts:1-80]()\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：BrettNye/stoa\n\n摘要：发现 7 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：配置坑 - 可能修改宿主 AI 配置。\n\n## 1. 配置坑 · 可能修改宿主 AI 配置\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- 证据：capability.host_targets | github_repo:1229401738 | https://github.com/BrettNye/stoa | host_targets=mcp_host, claude, claude_code\n\n## 2. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:1229401738 | https://github.com/BrettNye/stoa | README/documentation is current enough for a first validation pass.\n\n## 3. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:1229401738 | https://github.com/BrettNye/stoa | last_activity_observed missing\n\n## 4. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:1229401738 | https://github.com/BrettNye/stoa | no_demo; severity=medium\n\n## 5. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:1229401738 | https://github.com/BrettNye/stoa | no_demo; severity=medium\n\n## 6. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:1229401738 | https://github.com/BrettNye/stoa | issue_or_pr_quality=unknown\n\n## 7. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:1229401738 | https://github.com/BrettNye/stoa | release_recency=unknown\n\n<!-- canonical_name: BrettNye/stoa; human_manual_source: deepwiki_human_wiki -->\n",
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "Human Manual / 人类版说明书"
    },
    "pitfall_log": {
      "asset_id": "pitfall_log",
      "filename": "PITFALL_LOG.md",
      "markdown": "# Pitfall Log / 踩坑日志\n\n项目：BrettNye/stoa\n\n摘要：发现 7 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：配置坑 - 可能修改宿主 AI 配置。\n\n## 1. 配置坑 · 可能修改宿主 AI 配置\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- 证据：capability.host_targets | github_repo:1229401738 | https://github.com/BrettNye/stoa | host_targets=mcp_host, claude, claude_code\n\n## 2. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:1229401738 | https://github.com/BrettNye/stoa | README/documentation is current enough for a first validation pass.\n\n## 3. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:1229401738 | https://github.com/BrettNye/stoa | last_activity_observed missing\n\n## 4. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:1229401738 | https://github.com/BrettNye/stoa | no_demo; severity=medium\n\n## 5. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:1229401738 | https://github.com/BrettNye/stoa | no_demo; severity=medium\n\n## 6. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:1229401738 | https://github.com/BrettNye/stoa | issue_or_pr_quality=unknown\n\n## 7. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:1229401738 | https://github.com/BrettNye/stoa | release_recency=unknown\n",
      "summary": "用户实践前最可能遇到的身份、安装、配置、运行和安全坑。",
      "title": "Pitfall Log / 踩坑日志"
    },
    "prompt_preview": {
      "asset_id": "prompt_preview",
      "filename": "PROMPT_PREVIEW.md",
      "markdown": "# stoa - 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 BrettNye/stoa.\n\nProject:\n- Name: stoa\n- Repository: https://github.com/BrettNye/stoa\n- Summary: Persistent shared memory for AI coding agents (MCP server + CLI)\n- Host target: mcp_host, claude, claude_code\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: Persistent shared memory for AI coding agents (MCP server + CLI)\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: Persistent shared memory for AI coding agents (MCP server + CLI)\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 Stoa. Produce one small intermediate artifact and wait for confirmation.\n2. concepts-vocabulary: Core Concepts and Vocabulary. Produce one small intermediate artifact and wait for confirmation.\n3. architecture-design: Architecture and Design. Produce one small intermediate artifact and wait for confirmation.\n4. profiles-evolution: Agent Profiles and Evolution. Produce one small intermediate artifact and wait for confirmation.\n5. task-workflow: Task Workflow System. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/BrettNye/stoa\n- https://github.com/BrettNye/stoa#readme\n- README.md\n- src/core/profiles.ts\n- src/core/pokemon.ts\n- src/core/tasks.ts\n- src/core/channel.ts\n- src/tools/index.ts\n- src/cli/index.ts\n- src/core/index.ts\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\n项目：BrettNye/stoa\n\n## 官方安装入口\n\n### Node.js / npm · 官方安装入口\n\n```bash\nnpm i -g @stoa-mcp/cli\n```\n\n来源：https://github.com/BrettNye/stoa#readme\n\n## 来源\n\n- repo: https://github.com/BrettNye/stoa\n- docs: https://github.com/BrettNye/stoa#readme\n",
      "summary": "从项目官方 README 或安装文档提取的开工入口。",
      "title": "Quick Start / 官方入口"
    }
  },
  "validation_id": "dval_413b9b2eea374cd085b8ac7ceb0dd907"
}
