{
  "canonical_name": "jshsakura/oc-piloci",
  "compilation_id": "pack_13aec046938b4c6cb549b479bea237a1",
  "created_at": "2026-05-19T07:10:03.103276+00:00",
  "created_by": "project-pack-compiler",
  "feedback": {
    "carrier_selection_notes": [
      "viable_asset_types=mcp_config, recipe, host_instruction, eval, preflight",
      "recommended_asset_types=mcp_config, recipe, host_instruction, eval, preflight"
    ],
    "evidence_delta": {
      "confirmed_claims": [
        "identity_anchor_present",
        "capability_and_host_targets_present",
        "install_path_declared_or_better"
      ],
      "missing_required_fields": [],
      "must_verify_forwarded": [
        "Run or inspect `pip install -U oc-piloci` in an isolated environment.",
        "Confirm the project exposes the claimed capability to at least one target host."
      ],
      "quickstart_execution_scope": "allowlisted_sandbox_smoke",
      "sandbox_command": "pip install -U oc-piloci",
      "sandbox_container_image": "python:3.12-slim",
      "sandbox_execution_backend": "docker",
      "sandbox_planner_decision": "deterministic_isolated_install",
      "sandbox_validation_id": "sbx_2ac7b586aebd4fd296f66d60d385029b"
    },
    "feedback_event_type": "project_pack_compilation_feedback",
    "learning_candidate_reasons": [],
    "template_gaps": []
  },
  "identity": {
    "canonical_id": "project_6eaf22f90405bdd68162483bad7adca7",
    "canonical_name": "jshsakura/oc-piloci",
    "homepage_url": null,
    "license": "unknown",
    "repo_url": "https://github.com/jshsakura/oc-piloci",
    "slug": "oc-piloci",
    "source_packet_id": "phit_6f45e23bf27d4c24a5f1e8ede240ba8d",
    "source_validation_id": "dval_62149c64d2c84acca3177f8f49f930fc"
  },
  "merchandising": {
    "best_for": "需要工具连接与集成能力，并使用 mcp_host的用户",
    "github_forks": 0,
    "github_stars": 0,
    "one_liner_en": "piLoci is a self-hosted MCP memory server built to save tokens, I/O, and LLM calls on low-power devices like Raspberry Pi.",
    "one_liner_zh": "piLoci is a self-hosted MCP memory server built to save tokens, I/O, and LLM calls on low-power devices like Raspberry Pi.",
    "primary_category": {
      "category_id": "tool-integrations",
      "confidence": "high",
      "name_en": "Tool Integrations",
      "name_zh": "工具连接与集成",
      "reason": "matched_keywords:mcp, server, github"
    },
    "target_user": "使用 mcp_host, claude 等宿主 AI 的用户",
    "title_en": "oc-piloci",
    "title_zh": "oc-piloci 能力包",
    "visible_tags": [
      {
        "label_en": "Security & Permissions",
        "label_zh": "安全审查与权限治理",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "product_domain-security-permissions",
        "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": "Browser Automation",
        "label_zh": "浏览器自动化",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "core_capability-browser-automation",
        "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": "Evaluation Suite",
        "label_zh": "评测体系",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "selection_signal-evaluation-suite",
        "type": "selection_signal"
      }
    ]
  },
  "packet_id": "phit_6f45e23bf27d4c24a5f1e8ede240ba8d",
  "page_model": {
    "artifacts": {
      "artifact_slug": "oc-piloci",
      "files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json",
        "REPO_INSPECTION.md",
        "CAPABILITY_CONTRACT.json",
        "EVIDENCE_INDEX.json",
        "CLAIM_GRAPH.json"
      ],
      "required_files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json"
      ]
    },
    "detail": {
      "capability_source": "Project Hit Packet + DownstreamValidationResult",
      "commands": [
        {
          "command": "pip install -U oc-piloci",
          "label": "Python / pip · 官方安装入口",
          "source": "https://github.com/jshsakura/oc-piloci#readme",
          "verified": true
        }
      ],
      "display_tags": [
        "安全审查与权限治理",
        "网页任务自动化",
        "浏览器自动化",
        "页面观察与动作规划",
        "评测体系"
      ],
      "eyebrow": "工具连接与集成",
      "glance": [
        {
          "body": "判断自己是不是目标用户。",
          "label": "最适合谁",
          "value": "需要工具连接与集成能力，并使用 mcp_host的用户"
        },
        {
          "body": "先理解能力边界，再决定是否继续。",
          "label": "核心价值",
          "value": "piLoci is a self-hosted MCP memory server built to save tokens, I/O, and LLM calls on low-power devices like Raspberry Pi."
        },
        {
          "body": "未完成验证前保持审慎。",
          "label": "继续前",
          "value": "publish to Doramagic.ai project surfaces"
        }
      ],
      "guardrail_source": "Boundary & Risk Card",
      "guardrails": [
        {
          "body": "Prompt Preview 只展示流程，不证明项目已安装或运行。",
          "label": "Check 1",
          "value": "不要把试用当真实运行"
        },
        {
          "body": "mcp_host, claude",
          "label": "Check 2",
          "value": "确认宿主兼容"
        },
        {
          "body": "publish to Doramagic.ai project surfaces",
          "label": "Check 3",
          "value": "先隔离验证"
        }
      ],
      "mode": "mcp_config, recipe, host_instruction, eval, preflight",
      "pitfall_log": {
        "items": [
          {
            "body": "Developers should check this installation risk before relying on the project: Release v0.3.61",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_release | fmev_238385c7d11f6862a1b9d0c024a94181 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.61 | Release v0.3.61"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.61. Context: Observed when using docker",
            "title": "失败模式：installation: Release v0.3.61",
            "user_impact": "Upgrade or migration may change expected behavior: Release v0.3.61"
          },
          {
            "body": "Developers should check this installation risk before relying on the project: Release v0.3.62",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_release | fmev_115c2527b334fad79621b999d3e94857 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.62 | Release v0.3.62"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.62. Context: Observed when using docker",
            "title": "失败模式：installation: Release v0.3.62",
            "user_impact": "Upgrade or migration may change expected behavior: Release v0.3.62"
          },
          {
            "body": "Developers should check this installation risk before relying on the project: Release v0.3.63",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_release | fmev_348782b397ba2bb56859e630ea890c99 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.63 | Release v0.3.63"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.63. Context: Observed when using docker",
            "title": "失败模式：installation: Release v0.3.63",
            "user_impact": "Upgrade or migration may change expected behavior: Release v0.3.63"
          },
          {
            "body": "Developers should check this installation risk before relying on the project: Release v0.3.64",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_release | fmev_a5608f313037217768976fadbcbd00e3 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.64 | Release v0.3.64"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.64. Context: Observed when using docker",
            "title": "失败模式：installation: Release v0.3.64",
            "user_impact": "Upgrade or migration may change expected behavior: Release v0.3.64"
          },
          {
            "body": "Developers should check this installation risk before relying on the project: Release v0.3.65",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_release | fmev_593467b90b436b99ecac227152d65f93 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.65 | Release v0.3.65"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.65. Context: Observed when using docker",
            "title": "失败模式：installation: Release v0.3.65",
            "user_impact": "Upgrade or migration may change expected behavior: Release v0.3.65"
          },
          {
            "body": "Developers should check this installation risk before relying on the project: Release v0.3.66",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_release | fmev_41cea4cedb6fe85b101b1ee1e744a2a2 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.66 | Release v0.3.66"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.66. Context: Observed when using docker",
            "title": "失败模式：installation: Release v0.3.66",
            "user_impact": "Upgrade or migration may change expected behavior: Release v0.3.66"
          },
          {
            "body": "Developers should check this installation risk before relying on the project: Release v0.3.67",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_release | fmev_51ad1a6fbbb3b6c3fdc1be72bcfae7ea | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.67 | Release v0.3.67"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.67. Context: Observed when using docker",
            "title": "失败模式：installation: Release v0.3.67",
            "user_impact": "Upgrade or migration may change expected behavior: Release v0.3.67"
          },
          {
            "body": "Developers should check this installation risk before relying on the project: Release v0.3.68",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_release | fmev_7bc0641dd202d881746e1010d1b03fe5 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.68 | Release v0.3.68"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.68. Context: Observed when using docker",
            "title": "失败模式：installation: Release v0.3.68",
            "user_impact": "Upgrade or migration may change expected behavior: Release v0.3.68"
          },
          {
            "body": "Developers should check this installation risk before relying on the project: Release v0.3.69",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_release | fmev_ba1666889342a143a76dda2fa013ddf2 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.69 | Release v0.3.69"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.69. Context: Observed when using docker",
            "title": "失败模式：installation: Release v0.3.69",
            "user_impact": "Upgrade or migration may change expected behavior: Release v0.3.69"
          },
          {
            "body": "Developers should check this installation risk before relying on the project: Release v0.3.70",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_release | fmev_18504a4306cc5d44261e6d0f5ec47f54 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.70 | Release v0.3.70"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.70. Context: Observed when using docker",
            "title": "失败模式：installation: Release v0.3.70",
            "user_impact": "Upgrade or migration may change expected behavior: Release v0.3.70"
          },
          {
            "body": "Developers should check this installation risk before relying on the project: Release v0.3.71",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_release | fmev_4f40f1505195306061984312ceafb8d8 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.71 | Release v0.3.71"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.71. Context: Observed when using docker",
            "title": "失败模式：installation: Release v0.3.71",
            "user_impact": "Upgrade or migration may change expected behavior: Release v0.3.71"
          },
          {
            "body": "Developers should check this installation risk before relying on the project: Release v0.3.72",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_release | fmev_a62aef6e3f8ef8401a1d0bb3ce5d66d5 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.72 | Release v0.3.72"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.72. Context: Observed when using docker",
            "title": "失败模式：installation: Release v0.3.72",
            "user_impact": "Upgrade or migration may change expected behavior: Release v0.3.72"
          },
          {
            "body": "Developers should check this installation risk before relying on the project: Release v0.3.73",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_release | fmev_402be624902b0ff4a70763241e96f92a | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.73 | Release v0.3.73"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.73. Context: Observed when using docker",
            "title": "失败模式：installation: Release v0.3.73",
            "user_impact": "Upgrade or migration may change expected behavior: Release v0.3.73"
          },
          {
            "body": "Developers should check this installation risk before relying on the project: Release v0.3.74",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_release | fmev_f1c1782e6dc53172212d524d1e194b8f | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.74 | Release v0.3.74"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.74. Context: Observed when using docker",
            "title": "失败模式：installation: Release v0.3.74",
            "user_impact": "Upgrade or migration may change expected behavior: Release v0.3.74"
          },
          {
            "body": "Developers should check this installation risk before relying on the project: Release v0.3.75",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_release | fmev_65320a1ebb2900791f1e9b16cbf8e8d6 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.75 | Release v0.3.75"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.75. Context: Observed when using docker",
            "title": "失败模式：installation: Release v0.3.75",
            "user_impact": "Upgrade or migration may change expected behavior: Release v0.3.75"
          },
          {
            "body": "Developers should check this installation risk before relying on the project: Release v0.3.76",
            "category": "安装坑",
            "evidence": [
              "failure_mode_cluster:github_release | fmev_78ad7e0a2110bee066ed708a51554c0d | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.76 | Release v0.3.76"
            ],
            "severity": "medium",
            "suggested_check": "Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.76. Context: Observed when using docker",
            "title": "失败模式：installation: Release v0.3.76",
            "user_impact": "Upgrade or migration may change expected behavior: Release v0.3.76"
          }
        ],
        "source": "ProjectPitfallLog + ProjectHitPacket + validation + community signals",
        "summary": "发现 33 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：安装坑 - 失败模式：installation: Release v0.3.61。",
        "title": "踩坑日志"
      },
      "snapshot": {
        "contributors": 3,
        "forks": 0,
        "license": "unknown",
        "note": "站点快照，非实时质量证明；用于开工前背景判断。",
        "stars": 0
      },
      "source_url": "https://github.com/jshsakura/oc-piloci",
      "steps": [
        {
          "body": "不安装项目，先体验能力节奏。",
          "code": "preview",
          "title": "先试 Prompt"
        },
        {
          "body": "理解输入、输出、失败模式和边界。",
          "code": "manual",
          "title": "读说明书"
        },
        {
          "body": "把上下文交给宿主 AI 继续工作。",
          "code": "context",
          "title": "带给 AI"
        },
        {
          "body": "进入主力环境前先完成安装入口与风险边界验证。",
          "code": "verify",
          "title": "沙箱验证"
        }
      ],
      "subtitle": "piLoci is a self-hosted MCP memory server built to save tokens, I/O, and LLM calls on low-power devices like Raspberry Pi.",
      "title": "oc-piloci 能力包",
      "trial_prompt": "# oc-piloci - 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 jshsakura/oc-piloci.\n\nProject:\n- Name: oc-piloci\n- Repository: https://github.com/jshsakura/oc-piloci\n- Summary: piLoci is a self-hosted MCP memory server built to save tokens, I/O, and LLM calls on low-power devices like Raspberry Pi.\n- Host target: mcp_host, claude\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: piLoci is a self-hosted MCP memory server built to save tokens, I/O, and LLM calls on low-power devices like Raspberry Pi.\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: piLoci is a self-hosted MCP memory server built to save tokens, I/O, and LLM calls on low-power devices like Raspberry Pi.\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 piLoci. Produce one small intermediate artifact and wait for confirmation.\n2. getting-started: Getting Started. Produce one small intermediate artifact and wait for confirmation.\n3. architecture-overview: System Architecture. Produce one small intermediate artifact and wait for confirmation.\n4. mcp-server: MCP Server Implementation. Produce one small intermediate artifact and wait for confirmation.\n5. authentication: Authentication & Security. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/jshsakura/oc-piloci\n- https://github.com/jshsakura/oc-piloci#readme\n- README.md\n- PLAN.md\n- src/piloci/version.py\n- .env.example\n- docker-compose.yml\n- deploy/setup.sh\n- src/piloci/config.py\n- src/piloci/main.py\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "voices": [
        {
          "body": "来源平台：github。github/github_release: Release v0.3.77（https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.77）；github/github_release: Release v0.3.76（https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.76）；github/github_release: Release v0.3.75（https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.75）；github/github_release: Release v0.3.74（https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.74）；github/github_release: Release v0.3.73（https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.73）；github/github_release: Release v0.3.72（https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.72）；github/github_release: Release v0.3.71（https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.71）；github/github_release: Release v0.3.70（https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.70）；github/github_release: Release v0.3.69（https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.69）；github/github_release: Release v0.3.68（https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.68）；github/github_release: Release v0.3.67（https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.67）；github/github_release: Release v0.3.66（https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.66）。这些是项目级外部声音，不作为单独质量证明。",
          "items": [
            {
              "kind": "github_release",
              "source": "github",
              "title": "Release v0.3.77",
              "url": "https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.77"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "Release v0.3.76",
              "url": "https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.76"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "Release v0.3.75",
              "url": "https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.75"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "Release v0.3.74",
              "url": "https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.74"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "Release v0.3.73",
              "url": "https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.73"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "Release v0.3.72",
              "url": "https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.72"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "Release v0.3.71",
              "url": "https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.71"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "Release v0.3.70",
              "url": "https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.70"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "Release v0.3.69",
              "url": "https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.69"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "Release v0.3.68",
              "url": "https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.68"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "Release v0.3.67",
              "url": "https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.67"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "Release v0.3.66",
              "url": "https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.66"
            }
          ],
          "status": "已收录 12 条来源",
          "title": "社区讨论"
        }
      ]
    },
    "homepage_card": {
      "category": "工具连接与集成",
      "desc": "piLoci is a self-hosted MCP memory server built to save tokens, I/O, and LLM calls on low-power devices like Raspberry Pi.",
      "effort": "安装已验证",
      "forks": 0,
      "icon": "link",
      "name": "oc-piloci 能力包",
      "risk": "可发布",
      "slug": "oc-piloci",
      "stars": 0,
      "tags": [
        "安全审查与权限治理",
        "网页任务自动化",
        "浏览器自动化",
        "页面观察与动作规划",
        "评测体系"
      ],
      "thumb": "gray",
      "type": "MCP 配置"
    },
    "manual": {
      "markdown": "# https://github.com/jshsakura/oc-piloci 项目说明书\n\n生成时间：2026-05-18 00:58:38 UTC\n\n## 目录\n\n- [Introduction to piLoci](#introduction)\n- [Getting Started](#getting-started)\n- [System Architecture](#architecture-overview)\n- [Technology Stack](#tech-stack)\n- [MCP Server Implementation](#mcp-server)\n- [Authentication & Security](#authentication)\n- [API Routes](#api-routes)\n- [Curator Pipeline](#curator-pipeline)\n- [Storage Layer](#storage-layer)\n- [Database Models](#database-models)\n- [Web Dashboard](#web-dashboard)\n- [Workspace UI & Team Features](#workspace-ui)\n\n<a id='introduction'></a>\n\n## Introduction to piLoci\n\n### 相关页面\n\n相关主题：[System Architecture](#architecture-overview), [Getting Started](#getting-started), [Technology Stack](#tech-stack)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n- [README.ko.md](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n- [DESIGN-HARNESS.md](https://github.com/jshsakura/oc-piloci/blob/main/web/DESIGN-HARNESS.md)\n- [CLAUDE.md](https://github.com/jshsakura/oc-piloci/blob/main/CLAUDE.md)\n- [MEMORY.md](https://github.com/jshsakura/oc-piloci/blob/main/MEMORY.md)\n- [src/piloci/installer.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/installer.py)\n- [src/piloci/cli.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/cli.py)\n- [web/lib/api.ts](https://github.com/jshsakura/oc-piloci/blob/main/web/lib/api.ts)\n</details>\n\n# Introduction to piLoci\n\npiLoci is a lightweight, self-hosted memory curation system designed for AI coding assistants. It acts as a \"quiet automatic memory curator\" — silently capturing, organizing, and surfacing context from coding sessions to enhance productivity across projects. The system runs on Raspberry Pi 5 or any server, providing privacy-first memory management without relying on external cloud services.\n\n## Overview\n\npiLoci bridges the gap between ephemeral AI coding sessions and persistent knowledge storage. When developers use AI assistants like Claude Code or OpenCode, piLoci captures session context, extracts actionable memories, and stores them in a searchable vector database. This enables developers to build a cumulative knowledge base that improves over time.\n\n### Core Value Proposition\n\n| Aspect | Description |\n|--------|-------------|\n| **Privacy** | Self-hosted on local hardware; no data leaves your network |\n| **Automatic** | Silent capture of sessions without manual intervention |\n| **Project-scoped** | Memories organized by project for clean isolation |\n| **MCP-enabled** | Native integration with Model Context Protocol tools |\n\n资料来源：[README.md](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n\n### Design Philosophy\n\npiLoci embodies the metaphor of a \"behind-the-scenes assistant quietly organizing notes\" (뒤에서 조용히 돕는 자동 기억 큐레이터). The design direction emphasizes:\n\n- **Curation over collection** — Not just storing everything, but organizing meaningful insights\n- **Graph/workspace representation** — Visualizing relationships between memories and sessions\n- **Minimal friction** — One-line pairing, automatic capture, zero-token exposure\n\n资料来源：[CLAUDE.md](https://github.com/jshsakura/oc-piloci/blob/main/CLAUDE.md)\n\n## Architecture\n\n### System Components\n\n```mermaid\ngraph TD\n    subgraph Client[\"Client Side\"]\n        ClaudeCode[Claude Code]\n        OpenCode[OpenCode]\n        Cursor[Cursor IDE]\n    end\n\n    subgraph MCP[\"MCP Layer\"]\n        Memory[MCP: memory]\n        Recall[MCP: recall]\n        Recommend[MCP: recommend]\n    end\n\n    subgraph Server[\"piLoci Server\"]\n        API[Python API Server]\n        SQLite[(SQLite<br/>Identity Data)]\n        LanceDB[(LanceDB<br/>Vector Store)]\n        Redis[(Redis<br/>Sessions)]\n        Embed[FastEmbed/ONNX]\n    end\n\n    subgraph WebUI[\"Web Frontend\"]\n        Dashboard[Dashboard]\n        Projects[Project Workspace]\n        Admin[Admin Console]\n    end\n\n    ClaudeCode <--> MCP\n    OpenCode <--> MCP\n    Cursor <--> MCP\n    MCP <--> API\n    API <--> SQLite\n    API <--> LanceDB\n    API <--> Redis\n    API <--> Embed\n    API <--> WebUI\n```\n\n### Technology Stack\n\n| Component | Technology | Purpose |\n|-----------|------------|---------|\n| **Backend** | Python | MCP-enabled API server |\n| **Identity DB** | SQLite | User accounts, projects, sessions |\n| **Vector Store** | LanceDB | Embedded memory storage |\n| **Session Cache** | Redis | Session state management |\n| **Embeddings** | FastEmbed (ONNX) | Fast on-device inference |\n| **Frontend** | Next.js | Web UI, dashboard, settings |\n\n资料来源：[README.md](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n\n### Web Frontend Structure\n\nThe web application follows a consistent page pattern defined in `web/DESIGN-HARNESS.md`:\n\n```tsx\n<AppShell>\n  <div className=\"pi-page\">\n    <section className=\"pi-page-hero\">\n      <p className=\"pi-eyebrow\">Area label</p>\n      <h1 className=\"pi-title mt-2\">Page title</h1>\n      <p className=\"pi-subtitle\">One sentence explaining the page.</p>\n    </section>\n\n    <section className=\"grid gap-3 sm:grid-cols-3\">\n      <div className=\"pi-metric-card\">...</div>\n    </section>\n\n    <section className=\"pi-panel p-3\">...</section>\n  </div>\n</AppShell>\n```\n\n#### Baseline Pages\n\n| Page | Component | Purpose |\n|------|-----------|---------|\n| Dashboard | `app/dashboard/page.tsx` + `DashboardSummaryPanels.tsx` | User overview with metrics |\n| Admin Console | `app/admin/users/page.tsx` | User management |\n| Project Workspace | `app/projects/page.tsx` + `ProjectListView.tsx` | Project-level memory access |\n| Privacy | `app/privacy/page.tsx` | Privacy policy |\n| Terms | `app/terms/page.tsx` | Terms of service |\n\n资料来源：[DESIGN-HARNESS.md](https://github.com/jshsakura/oc-piloci/blob/main/web/DESIGN-HARNESS.md)\n\n## Client Connection Flow\n\n### Supported Clients\n\npiLoci integrates with multiple AI coding assistants through MCP:\n\n| Client | Session Capture | MCP Tools |\n|--------|----------------|-----------|\n| **Claude Code** | SessionStart/Stop hooks | memory, recall, recommend |\n| **Claude Desktop** | Static config | memory, recall, recommend |\n| **OpenCode** | Static config only | memory, recall, recommend |\n| **Cursor** | Static config | memory, recall, recommend |\n\n资料来源：[web/components/TokenManager.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/components/TokenManager.tsx)\n\n### Connection Process\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant CLI\n    participant WebUI\n    participant Server\n\n    User->>CLI: piloci login\n    CLI->>Server: OAuth or install code request\n    Server->>WebUI: Redirect to /device\n    User->>WebUI: Login + approve\n    WebUI->>CLI: Token ready\n    CLI->>Server: Poll and receive token\n    Server->>CLI: Token + URLs\n    CLI->>User: Configuration complete\n\n    User->>CLI: piloci install\n    CLI->>Server: Download MCP server config\n    Server->>CLI: .mcp.json + hooks\n    CLI->>User: MCP tools available\n```\n\n### What Connection Establishes\n\nThe pairing process creates the following artifacts:\n\n```\n~/.config/piloci/\n├── config.json     # Token + ingest/analyze URLs (mode 0600)\n├── hook.py         # SessionStart catch-up (Claude only)\n└── stop-hook.sh    # Stop live push (Claude only)\n\n~/.claude.json              # MCP server entry (Claude only)\n~/.claude/settings.json     # SessionStart + Stop hooks (Claude only)\n~/.config/opencode/         # MCP server entry (OpenCode)\n```\n\n资料来源：[README.ko.md](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n\n## CLI Commands\n\nThe `piloci` CLI provides complete installation and management capabilities:\n\n| Command | Description |\n|---------|-------------|\n| `piloci login` | Authenticate with the server (OAuth or install code) |\n| `piloci install` | Install MCP server and hooks for AI clients |\n| `piloci uninstall` | Remove all piLoci artifacts, optionally restore backups |\n| `piloci restore` | Restore client configs from .piloci-bak snapshots |\n| `piloci backfill-cwd` | Fix legacy slug-collision bug in session data |\n\n### Install Command Options\n\n| Flag | Purpose |\n|------|---------|\n| `--server` | Override server URL when only install code is provided |\n| `--token` | Use token directly instead of resolving URL |\n| `--force` | Wipe existing plugin folders and reinstall fresh |\n\n### Uninstall Command Options\n\n| Flag | Purpose |\n|------|---------|\n| `--yes` | Skip confirmation prompt |\n| `--no-restore` | Remove entries surgically instead of restoring backups |\n\n资料来源：[src/piloci/cli.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/cli.py)\n\n## Plugin Installation Structure\n\nFor Claude Code, piLoci installs as a Claude plugin with hooks:\n\n```\npiloci/\n├── .claude-plugin/\n│   └── plugin.json          # Manifest with name, version, description\n├── hooks/\n│   ├── hooks.json           # SessionStart + Stop wired to scripts\n│   ├── hook.py              # Downloaded from /api/hook/script\n│   └── stop-hook.sh         # Downloaded from /api/hook/stop-script\n└── .mcp.json                # MCP server config for memory/recall/recommend\n```\n\n资料来源：[src/piloci/installer.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/installer.py)\n\n## Data Models\n\n### API Client Functions\n\nThe frontend communicates with the backend through typed API functions:\n\n```typescript\n// Project operations\ngetProjects: () => request<Project[]>(\"api/projects\")\ngetProjectBySlug: (slug: string) => request<Project>(`api/projects/slug/${slug}`)\ncreateProject: (body) => request<Project>(\"api/projects\", { method: \"POST\", body })\ngetProjectFreshness: (projectId) => request<ProjectFreshness>(`api/projects/${projectId}/freshness`)\n\n// Session operations\ngetSessions: () => request<Session[]>(\"api/sessions\")\n\n// Memory operations\ncreateMemory: (projectId, body) => request<Memory>(`api/memories`, { method: \"POST\", body })\n\n// Distillation operations\nrunDistillationNow: () => request<{ woken: boolean; note: string }>(\"/api/distillation/run-now\", { method: \"POST\" })\ngetDistillationPreferences: () => request<DistillationPreferences>(\"api/preferences\")\nupdateDistillationPreferences: (body) => request<DistillationPreferences>(\"api/preferences\", { method: \"PATCH\", body })\n\n// Budget operations\nbudgetUsage: () => request<BudgetUsage>(\"api/budget/usage\")\n```\n\n资料来源：[web/lib/api.ts](https://github.com/jshsakura/oc-piloci/blob/main/web/lib/api.ts)\n\n### Project Sessions Panel\n\nThe session viewer displays captured coding sessions:\n\n| Field | Description |\n|-------|-------------|\n| `ingest_id` | Unique session identifier |\n| `client` | AI client used (Claude Code, OpenCode, etc.) |\n| `project_slug` | Associated project |\n| `project_name` | Human-readable project name |\n| `created_at` | Session start timestamp |\n| `processed_at` | When distillation completed |\n| `memories_extracted` | Number of memories extracted |\n| `error` | Any processing errors |\n| `transcript` | Full session transcript (expandable) |\n\n资料来源：[web/components/ProjectSessionsPanel.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/components/ProjectSessionsPanel.tsx)\n\n### Instincts (Top Knacks)\n\nInstincts are triggered memory patterns:\n\n| Field | Description |\n|-------|-------------|\n| `instinct_id` | Unique instinct identifier |\n| `trigger` | Condition pattern (\"when...\") |\n| `action` | Suggested action (\"→...\") |\n| `project_slug` | Associated project |\n| `domain` | Knowledge domain |\n| `instinct_count` | Number of times triggered |\n\n资料来源：[web/components/DashboardSummaryPanels.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/components/DashboardSummaryPanels.tsx)\n\n## Usage Scenarios\n\n### Scenario A — Team Project Memory Hub\n\nA small team sets up one piLoci on a shared Raspberry Pi 5. Each member creates an account, joins shared projects, and stores memories via MCP tools. Everyone benefits from the same knowledge base while project isolation keeps unrelated work separate.\n\n### Scenario B — Multi-Project Workspace\n\nA solo developer runs several projects (e.g., \"thesis research\", \"side project\", \"client work\") on one piLoci. Each project's memories stay isolated, and the workspace viewer shows notes and relationships per project.\n\n### Scenario C — Obsidian Export\n\nGenerate workspace notes and export to an Obsidian vault:\n\n```bash\ncurl -sS http://localhost:8314/api/projects/slug/my-project/workspace\n```\n\nOr download a ready-made archive:\n\n```bash\ncurl -OJ http://localhost:8314/api/vault/my-project/export\n```\n\n资料来源：[README.md](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n\n## Deployment Configuration\n\n### Environment Variables\n\nWhen running behind a reverse proxy, the `BASE_URL` environment variable is required:\n\n```env\nBASE_URL=https://piloci.example.com\n```\n\nThis ensures Google OAuth redirect URIs match exactly:\n\n```\nhttps://piloci.example.com/auth/google/callback\n```\n\nWithout `BASE_URL`, the backend may generate callbacks based on internal request hosts, causing `redirect_uri_mismatch` errors.\n\n### Port Configuration\n\nThe default port is `8314`. When exposing via reverse proxy or tunnel (Cloudflare Tunnel, Caddy, nginx), proxy external traffic to `http://127.0.0.1:8314`.\n\n资料来源：[README.ko.md](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n\n## Version Management\n\npiLoci uses a single-source version system:\n\n| Rule | Description |\n|------|-------------|\n| **Source** | `pyproject.toml` → `[project].version` |\n| **Default bump** | `+0.0.1` patch only |\n| **Major/Minor** | Requires explicit approval |\n| **Release trigger** | Git tag push: `git tag v{version} && git push origin main v{version}` |\n| **Tag format** | Must match: `v0.2.0` ↔ `0.2.0` |\n\n### Pre-release Checklist\n\nBefore tagging:\n\n1. Update version in `pyproject.toml`\n2. Run tests: `pytest tests/ -v`\n3. Build package: `uv build`\n4. Build web (if changed): `pnpm build` in `web/`\n\n### GitHub Actions Pipeline\n\nThe `publish.yml` workflow handles:\n\n- Version guard (tag matches `pyproject.toml`)\n- Test gate\n- Web build artifact\n- Multi-arch Docker image publish\n- GitHub Release creation\n- PyPI publish as `oc-piloci`\n\n资料来源：[CLAUDE.md](https://github.com/jshsakura/oc-piloci/blob/main/CLAUDE.md)\n\n## Development Workflow\n\n### Starting an Implementation Session\n\n1. Begin each session at `PLAN.md`\n2. Check `## 현재 상태` (Current Status) for incomplete items\n3. Implement the next pending item\n4. Document completion in PLAN.md\n\n### Current Development Focus\n\nBased on recent changes documented in `MEMORY.md`:\n\n- **Memory creation UI speed** — Narrow v0.3 slice for faster memory creation\n- **Graph UI direction** — Planning for React Flow-based interactive memory visualization\n- **Copy style** — Landing page emphasizes \"quiet automatic memory curator\" metaphor\n- **Vault caching** — Tests added for `tests/test_vault_cache.py`\n\n资料来源：[MEMORY.md](https://github.com/jshsakura/oc-piloci/blob/main/MEMORY.md)\n\n### Design Guidelines for Frontend\n\nKey principles from `CLAUDE.md`:\n\n- **Avoid dash-heavy feature lists** — Use paragraph-based Korean/English copy\n- **Translate optimizations to UX** — Don't just list technical features\n- **Maintain metaphor** — \"뒤에서 조용히 돕는 자동 기억 큐레이터\" (behind-the-scenes quiet assistant)\n- **Graph direction** — Visual metaphor of a curator organizing post-it notes\n\n---\n\n<a id='getting-started'></a>\n\n## Getting Started\n\n### 相关页面\n\n相关主题：[Introduction to piLoci](#introduction)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [.env.example](https://github.com/jshsakura/oc-piloci/blob/main/.env.example)\n- [docker-compose.yml](https://github.com/jshsakura/oc-piloci/blob/main/docker-compose.yml)\n- [deploy/setup.sh](https://github.com/jshsakura/oc-piloci/blob/main/deploy/setup.sh)\n- [src/piloci/config.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/config.py)\n</details>\n\n# Getting Started\n\npiLoci is a personal memory hub designed for AI coding assistants. It runs on a local server (typically Raspberry Pi 5) and captures, stores, and retrieves contextual memories from AI-assisted coding sessions. This guide walks you through the complete setup process from hardware prerequisites to first login.\n\n## Prerequisites\n\n### Hardware Requirements\n\n| Component | Minimum | Recommended |\n|-----------|---------|-------------|\n| Device | Raspberry Pi 5 (4GB+) | Raspberry Pi 5 (8GB) |\n| Storage | 32GB SD card | 64GB+ SSD via USB |\n| Network | Ethernet or WiFi | Ethernet |\n| OS | Raspberry Pi OS (64-bit) | Raspberry Pi OS (64-bit) |\n\n资料来源：[README.md](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n\n### Software Requirements\n\n- **Docker** and **Docker Compose** installed on the host\n- **Google OAuth credentials** (for authentication)\n- A domain name (optional, for remote access via Cloudflare Tunnel)\n\n## Installation\n\n### Step 1: Clone the Repository\n\n```bash\ngit clone https://github.com/jshsakura/oc-piloci.git\ncd oc-piloci\n```\n\n### Step 2: Configure Environment Variables\n\nCopy the example environment file and configure it:\n\n```bash\ncp .env.example .env\n```\n\nEdit `.env` with your specific settings:\n\n```env\n# Required: Set your external HTTPS domain if behind a reverse proxy\nBASE_URL=https://piloci.example.com\n\n# Google OAuth credentials (required for authentication)\nGOOGLE_CLIENT_ID=your_client_id_here\nGOOGLE_CLIENT_SECRET=your_client_secret_here\n\n# Secret key for session encryption\nSECRET_KEY=your_random_secret_key_here\n```\n\n> **Important:** When deploying behind a reverse proxy, you MUST set `BASE_URL` to your external HTTPS domain. Without it, Google OAuth redirect URIs will fail with `redirect_uri_mismatch`. 资料来源：[README.ko.md](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n\n#### Google OAuth Setup\n\n1. Go to [Google Cloud Console](https://console.cloud.google.com/)\n2. Create a new project or select an existing one\n3. Navigate to **APIs & Services** → **Credentials**\n4. Create an **OAuth 2.0 Client ID** (Web application type)\n5. Add the following authorized redirect URI (replace with your domain):\n\n```\nhttps://piloci.example.com/auth/google/callback\n```\n\nThe callback URI must match **exactly**, including trailing slashes. 资料来源：[README.ko.md](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n\n### Step 3: Deploy with Docker Compose\n\nThe project uses Docker Compose for container orchestration:\n\n```bash\ndocker compose up -d\n```\n\nThis starts the following services:\n\n| Service | Port | Purpose |\n|---------|------|---------|\n| web | 8314 | Next.js frontend + API server |\n| redis | 6379 | Session storage |\n| worker | - | Background distillation worker |\n\n资料来源：[docker-compose.yml](https://github.com/jshsakura/oc-piloci/blob/main/docker-compose.yml)\n\n### Step 4: Verify Deployment\n\nCheck the health status:\n\n```bash\ncurl http://localhost:8314/healthz\n```\n\nA successful response indicates the application is running correctly.\n\n## Architecture Overview\n\n```mermaid\ngraph TB\n    subgraph \"Client Side\"\n        CC[Claude Code / Claude Desktop]\n        OC[OpenCode]\n        CU[Cursor]\n    end\n    \n    subgraph \"piLoci Server\"\n        WEB[Web App :8314]\n        REDIS[(Redis<br/>Sessions)]\n        WORKER[Distillation<br/>Worker]\n        DB[(LanceDB<br/>Memories)]\n    end\n    \n    subgraph \"AI Clients → piLoci\"\n        CC --> MCP[MCP Server]\n        OC --> MCP\n        CU --> MCP\n    end\n    \n    MCP -->|Ingest| WEB\n    WEB --> REDIS\n    WEB --> DB\n    WORKER --> DB\n    WORKER -->|Distill| CC\n```\n\n资料来源：[README.md](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n\n## Client Connection\n\n### Claude Code Setup\n\n1. Navigate to **Settings → Tokens** in the web UI\n2. Generate an install code\n3. Run the pairing command:\n\n```bash\npiloci login --pair <install_code>\npiloci install\n```\n\nOr use the one-liner:\n\n```bash\ncurl -sSL https://piloci.example.com/install/<install_code> | bash\n```\n\nThis automatically:\n- Writes token + URLs to `~/.config/piloci/config.json`\n- Registers the MCP server in `~/.claude.json`\n- Configures session capture hooks in `~/.claude/settings.json`\n\n资料来源：[README.ko.md](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n\n### What Gets Installed\n\n```\n~/.config/piloci/\n├── config.json     # Token + ingest/analyze URLs (mode 0600)\n├── hook.py         # SessionStart catch-up hook (Claude Code only)\n└── stop-hook.sh    # Stop live push (Claude Code only)\n\n~/.claude.json              # MCP server entry (Claude Code only)\n~/.claude/settings.json     # SessionStart + Stop hooks (Claude Code only)\n```\n\n资料来源：[README.ko.md](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n\n## Remote Access\n\n### Exposing Port 8314\n\nConfigure your reverse proxy or tunnel to expose port 8314:\n\n| Proxy/Tunnel | Configuration |\n|--------------|---------------|\n| Cloudflare Tunnel | Point to `http://127.0.0.1:8314` |\n| Caddy | Proxy to `localhost:8314` |\n| nginx | Proxy pass to `127.0.0.1:8314` |\n\n### Cloudflare Tunnel Setup\n\n```bash\ncloudflared tunnel --url http://localhost:8314\n```\n\n资料来源：[README.ko.md](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n\n## Configuration Reference\n\n### Environment Variables\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `BASE_URL` | Yes (remote) | `http://localhost:8314` | External HTTPS URL when behind proxy |\n| `GOOGLE_CLIENT_ID` | Yes | - | Google OAuth Client ID |\n| `GOOGLE_CLIENT_SECRET` | Yes | - | Google OAuth Client Secret |\n| `SECRET_KEY` | Yes | - | Session encryption key |\n| `DATA_DIR` | No | `./data` | Data persistence directory |\n| `REDIS_URL` | No | `redis://redis:6379` | Redis connection URL |\n\n资料来源：[src/piloci/config.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/config.py)\n\n### Data Storage\n\nThe application stores data in:\n\n- **SQLite**: User identity and authentication data\n- **LanceDB**: Embedded vector storage for memories\n- **Redis**: Session data and real-time state\n\n资料来源：[README.md](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n\n## Development Mode\n\n### Local Stack Development\n\n```bash\n# Start backend with hot reload\nuv run uvicorn src.piloci.main:app --reload --port 8314\n\n# In another terminal, start worker\nuv run python -m piloci.worker.distillation\n```\n\n### Web Frontend Development\n\n```bash\ncd web\npnpm install --frozen-lockfile\npnpm dev\n```\n\n资料来源：[README.md](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n\n## Next Steps\n\nAfter successful installation:\n\n1. **Create an account** via the web UI at `http://localhost:8314/signup`\n2. **Connect your AI client** using the pairing flow\n3. **Create projects** to organize your memories\n4. **Explore the dashboard** to view session history and extracted memories\n\nFor troubleshooting, check the logs:\n\n```bash\ndocker compose logs -f web\ndocker compose logs -f worker\n\n---\n\n<a id='architecture-overview'></a>\n\n## System Architecture\n\n### 相关页面\n\n相关主题：[Introduction to piLoci](#introduction), [Technology Stack](#tech-stack), [Storage Layer](#storage-layer), [MCP Server Implementation](#mcp-server)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n- [CLAUDE.md](https://github.com/jshsakura/oc-piloci/blob/main/CLAUDE.md)\n- [web/lib/api.ts](https://github.com/jshsakura/oc-piloci/blob/main/web/lib/api.ts)\n- [src/piloci/installer.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/installer.py)\n- [web/DESIGN-HARNESS.md](https://github.com/jshsakura/oc-piloci/blob/main/web/DESIGN-HARNESS.md)\n- [MEMORY.md](https://github.com/jshsakura/oc-piloci/blob/main/MEMORY.md)\n- [web/app/page.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/app/page.tsx)\n- [web/components/DashboardSummaryPanels.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/components/DashboardSummaryPanels.tsx)\n- [web/app/admin/users/page.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/app/admin/users/page.tsx)\n</details>\n\n# System Architecture\n\npiLoci is a self-hosted memory curation system designed for AI-assisted development workflows. It operates as a client-server architecture where a Raspberry Pi (or any server) acts as a central hub for capturing, processing, and retrieving contextual memories from AI coding sessions. The system bridges the gap between ephemeral AI conversations and persistent, searchable knowledge bases.\n\n## High-Level Architecture Overview\n\npiLoci follows a layered architecture pattern comprising four primary tiers: a frontend presentation layer, a backend API layer, a storage abstraction layer, and a client integration layer. Each tier is independently deployable and communicates through well-defined interfaces, enabling flexibility in deployment scenarios.\n\nThe backend is built with Python and leverages the Model Context Protocol (MCP) to expose memory management tools to AI clients such as Claude Code and OpenCode. The frontend is a Next.js application that provides both user-facing interfaces and administrative capabilities. The storage layer abstracts away the complexity of handling different database technologies, providing a unified API for memory operations.\n\n```mermaid\ngraph TD\n    subgraph Client[\"Client Layer\"]\n        ClaudeCode[\"Claude Code\"]\n        OpenCode[\"OpenCode\"]\n        Cursor[\"Cursor IDE\"]\n    end\n\n    subgraph Server[\"piLoci Server\"]\n        API[\"FastAPI Server<br/>(Port 8314)\"]\n        MCP[\"MCP Tools<br/>memory/recall/recommend\"]\n    end\n\n    subgraph Storage[\"Storage Layer\"]\n        SQLite[\"SQLite<br/>(Identity)\"]\n        LanceDB[\"LanceDB<br/>(Vectors)\"]\n        Redis[\"Redis<br/>(Sessions)\"]\n    end\n\n    subgraph Frontend[\"Frontend Layer\"]\n        NextJS[\"Next.js App<br/>(Web UI)\"]\n        Admin[\"Admin Console\"]\n        Dashboard[\"User Dashboard\"]\n    end\n\n    Client -->|HTTP/MCP| Server\n    NextJS -->|REST API| API\n    API --> Storage\n    API --> MCP\n```\n\n资料来源：[README.md:1-50]()\n\n## Technology Stack\n\npiLoci's architecture leverages a carefully selected technology stack optimized for self-hosted deployment on resource-constrained hardware like the Raspberry Pi 5. Each component serves a specific purpose in the overall system.\n\n| Component | Technology | Purpose | Location |\n|-----------|------------|---------|----------|\n| Backend API | FastAPI | REST API + MCP server | `src/piloci/` |\n| Vector Storage | LanceDB | Embedded memory storage with vector search | `src/piloci/storage/` |\n| Identity DB | SQLite | User/project identity and metadata | `src/piloci/db/` |\n| Session Cache | Redis | Temporary session data caching | `docker-compose.yml` |\n| Embeddings | fastembed (ONNX) | Local CPU-based embedding inference | `src/piloci/storage/` |\n| Frontend | Next.js 14 | React-based web application | `web/` |\n| Styling | Tailwind CSS | Utility-first design system | `web/` |\n| Container | Docker | Self-contained deployment | `docker-compose.yml` |\n\n资料来源：[README.md:85-95]()\n\n### Embedding Infrastructure\n\nThe system uses fastembed for ONNX-based embeddings, enabling fast, on-device inference without requiring GPU resources. This design choice is critical for the target deployment environment of Raspberry Pi devices where power efficiency and thermal constraints are primary concerns.\n\nThe embedding service processes text content and generates vector representations that capture semantic meaning. These vectors are stored in LanceDB, which provides efficient similarity search capabilities essential for the recall and recommendation features.\n\n资料来源：[README.md:90]()\n\n## Frontend Architecture\n\nThe Next.js frontend follows a component-driven architecture with clear separation between presentation components, data fetching logic, and layout structures. The application is organized around a shell-based layout pattern that provides consistent navigation and authentication state across all pages.\n\n### Page Structure Pattern\n\nAll application pages follow a standardized layout defined in `AppShell.tsx` with specific section patterns for different content types.\n\n```mermaid\ngraph TD\n    AppShell[\"AppShell Component<br/>(web/components/AppShell.tsx)\"]\n    Hero[\"pi-page-hero<br/>(Title + Subtitle)\"]\n    Metrics[\"pi-metric-card<br/>(Data Cards)\"]\n    Panel[\"pi-panel<br/>(Content Sections)\"]\n\n    AppShell --> Hero\n    AppShell --> Metrics\n    AppShell --> Panel\n```\n\nThe component hierarchy follows this pattern:\n\n```\nAppShell\n└── div.pi-page\n    ├── section.pi-page-hero\n    │   ├── p.pi-eyebrow\n    │   ├── h1.pi-title\n    │   └── p.pi-subtitle\n    ├── section.pi-page (metrics grid)\n    │   └── div.pi-metric-card\n    └── section.pi-panel (content areas)\n```\n\n资料来源：[web/DESIGN-HARNESS.md:10-30]()\n\n### Key Frontend Components\n\n| Component | File Path | Responsibility |\n|-----------|-----------|----------------|\n| AppShell | `web/components/AppShell.tsx` | Authenticated shell with glass navigation |\n| DashboardSummaryPanels | `web/components/DashboardSummaryPanels.tsx` | User dashboard with metrics and session lists |\n| ProjectSessionsPanel | `web/components/ProjectSessionsPanel.tsx` | Project-specific session viewer with transcripts |\n| TokenManager | `web/components/TokenManager.tsx` | Installation token generation and display |\n| DistillationSettings | `web/components/DistillationSettingsPanel.tsx` | Memory processing configuration |\n\n资料来源：[web/components/DashboardSummaryPanels.tsx:1-80]()\n\n### API Client Layer\n\nThe frontend communicates with the backend through a typed API client defined in `web/lib/api.ts`. This module provides a centralized request function that handles authentication, error handling, and response typing.\n\n```typescript\n// Simplified API client structure\nconst api = {\n  projects: {\n    list: () => request<Project[]>(\"/api/projects\"),\n    create: (body) => request<Project>(\"/api/projects\", { method: \"POST\", body }),\n    getBySlug: (slug) => request<Project>(`/api/projects/slug/${slug}`),\n  },\n  memories: {\n    create: (projectId, body) => request<Memory>(`/api/projects/${projectId}/memories`, { method: \"POST\", body }),\n    list: (projectId) => request<Memory[]>(`/api/projects/${projectId}/memories`),\n  },\n  distillation: {\n    runNow: () => request<{ woken: boolean; note: string }>(\"/api/distillation/run-now\", { method: \"POST\" }),\n    getPreferences: () => request<DistillationPreferences>(\"/api/preferences\"),\n    updatePreferences: (body) => request<DistillationPreferences>(\"/api/preferences\", { method: \"PATCH\", body }),\n  },\n};\n```\n\n资料来源：[web/lib/api.ts:1-50]()\n\n### Landing Page Architecture\n\nThe landing page (`web/app/page.tsx`) serves as the public-facing entry point for unauthenticated users and implements a conversion-focused design with feature highlights and installation guidance.\n\n```mermaid\ngraph LR\n    Hero[\"Hero Section<br/>(CTA: Signup/Dashboard)\"]\n    Features[\"Features Grid<br/>(4-column)\"]\n    Install[\"Installation Guide<br/>(CLI + bash options)\"]\n    Uninstall[\"Uninstall Note<br/>(Removal instructions)\"]\n\n    Hero --> Features\n    Features --> Install\n    Install --> Uninstall\n```\n\n资料来源：[web/app/page.tsx:1-60]()\n\n## Backend Architecture\n\nThe Python backend implements a FastAPI application that serves both REST API endpoints and MCP tool interfaces. The architecture emphasizes separation of concerns through distinct modules for API routes, database operations, and storage abstraction.\n\n### Application Entry Point\n\nThe main application module (`src/piloci/main.py`) initializes the FastAPI server with middleware configuration, CORS settings, and route registration. The application listens on port 8314 by default and supports configuration through environment variables.\n\nKey configuration parameters:\n\n| Parameter | Default | Purpose |\n|-----------|---------|---------|\n| `BASE_URL` | (auto-detected) | External HTTPS domain for OAuth callbacks |\n| `DATABASE_URL` | (local path) | SQLite database location |\n| `REDIS_URL` | (local) | Redis connection for session caching |\n| `PORT` | 8314 | HTTP server port |\n\n资料来源：[README.ko.md:1-30]()\n\n### Database Architecture\n\nThe system uses three distinct storage mechanisms, each optimized for specific data access patterns.\n\n```mermaid\ngraph TD\n    API[\"FastAPI Server\"]\n    Session[\"Session Management\"]\n    Identity[\"SQLite<br/>(Identity Data)\"]\n    Vectors[\"LanceDB<br/>(Memory Vectors)\"]\n    Cache[\"Redis<br/>(Session Cache)\"]\n\n    API --> Session\n    Session --> Identity\n    Session --> Vectors\n    Session --> Cache\n```\n\n#### Identity Database (SQLite)\n\nSQLite handles persistent identity data including user accounts, project metadata, and session records. The session module (`src/piloci/db/session.py`) provides an abstraction layer for database operations.\n\n```python\n# Session database schema concept\nclass Session:\n    id: str\n    user_id: str\n    project_id: str\n    client: str  # \"claude-code\" | \"opencode\" | \"cursor\"\n    ingest_id: str\n    created_at: datetime\n    processed_at: Optional[datetime]\n    memories_extracted: int\n    error: Optional[str]\n```\n\n资料来源：[web/components/DashboardSummaryPanels.tsx:30-50]()\n\n#### Vector Storage (LanceDB)\n\nLanceDB stores embedded memory content with vector representations for semantic search. The storage module provides CRUD operations for memories and supports similarity-based retrieval for the recall and recommendation features.\n\n#### Session Cache (Redis)\n\nRedis provides low-latency caching for active sessions and real-time processing state. The distillation worker uses Redis for queue management and processing state tracking.\n\n资料来源：[README.md:85-90]()\n\n### API Route Organization\n\nAPI routes are organized by resource type and follow RESTful conventions:\n\n| Route Prefix | Handler | Purpose |\n|--------------|---------|---------|\n| `/api/auth/*` | Authentication | OAuth flows, session management |\n| `/api/projects/*` | Project management | CRUD, slug lookup, freshness |\n| `/api/memories/*` | Memory operations | Create, list, vector search |\n| `/api/budget/*` | Budget tracking | Usage reporting |\n| `/api/preferences` | User settings | Distillation configuration |\n| `/api/distillation/*` | Worker control | Manual trigger, status |\n\n资料来源：[web/lib/api.ts:1-40]()\n\n## Installer Architecture\n\nThe installer module (`src/piloci/installer.py`) handles client-side setup by creating configuration files and registering MCP servers with supported AI clients. It follows a plugin-based architecture for each supported client type.\n\n### Claude Code Installer Layout\n\n```mermaid\ngraph TD\n    Plugin[\"Claude Plugin<br/>~/.claude/plugins/piloci/\"]\n    PluginManifest[\".claude-plugin/plugin.json\"]\n    Hooks[\"hooks/hooks.json\"]\n    Scripts[\"hooks/hook.py<br/>hooks/stop-hook.sh\"]\n    MCP[\".mcp.json<br/>(MCP Server Config)\"]\n\n    Plugin --> PluginManifest\n    Plugin --> Hooks\n    Plugin --> Scripts\n    Plugin --> MCP\n```\n\n资料来源：[src/piloci/installer.py:20-50]()\n\n### Installation Workflow\n\n1. **Manifest Creation**: Generates `plugin.json` with version, description, and author metadata\n2. **Hook Configuration**: Creates `hooks.json` linking SessionStart and Stop events to plugin scripts\n3. **Script Download**: Fetches `hook.py` and `stop-hook.sh` from the server's `/api/hook/` endpoints\n4. **MCP Registration**: Creates `.mcp.json` exposing memory, recall, and recommend tools\n\n资料来源：[src/piloci/installer.py:50-80]()\n\n## Deployment Architecture\n\npiLoci is designed for self-hosted deployment, typically on a Raspberry Pi 5 within the user's local network. The system supports exposure through reverse proxies or tunnels for remote access.\n\n### Docker Deployment\n\nThe recommended deployment uses Docker Compose with the following service structure:\n\n```yaml\nservices:\n  piloci:\n    image: ghcr.io/jshsakura/oc-piloci:latest\n    ports:\n      - \"8314:8314\"\n    volumes:\n      - ./data:/data\n    environment:\n      - BASE_URL=https://piloci.example.com\n      - DATABASE_URL=sqlite:///data/piloci.db\n```\n\n资料来源：[docker-compose.yml](https://github.com/jshsakura/oc-piloci/blob/main/docker-compose.yml)\n\n### Reverse Proxy Configuration\n\nWhen deploying behind a reverse proxy (Cloudflare Tunnel, Caddy, nginx), port 8314 should be exposed externally. The `BASE_URL` environment variable must be set to the external HTTPS domain for proper OAuth callback URL generation.\n\nGoogle OAuth requires exact callback URI matching:\n```\nhttps://piloci.opencourse.kr/auth/google/callback\n```\n\n资料来源：[README.ko.md:25-40]()\n\n## Client Connection Flow\n\nThe system supports multiple AI clients through standardized MCP interfaces. Each client has specific integration requirements.\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant CLI as piloci CLI\n    participant Browser\n    participant Server as piLoci Server\n    participant Claude as Claude Code\n\n    User->>CLI: piloci login\n    CLI->>Browser: Opens /device page\n    User->>Browser: Login + Approve\n    Browser->>Server: Token exchange\n    Server->>CLI: Token + URLs\n    CLI->>CLI: Write ~/.config/piloci/config.json\n    CLI->>Server: Register MCP server\n    User->>Claude: Start session\n    Claude->>CLI: MCP tool calls (memory/recall/recommend)\n    CLI->>Server: API requests\n    Server->>Claude: Memory results\n```\n\n资料来源：[README.ko.md:1-20]()\n\n### Supported Clients\n\n| Client | MCP Support | Hook Support | Configuration Location |\n|--------|-------------|--------------|------------------------|\n| Claude Code | Full | SessionStart + Stop | `~/.claude.json`, `~/.claude/settings.json` |\n| Claude Desktop | Full | N/A | `~/Library/Application Support/Claude/` |\n| OpenCode | Full | N/A | `~/.config/opencode/opencode.json` |\n| Cursor | Partial | N/A | Cursor MCP settings |\n\n资料来源：[web/components/TokenManager.tsx:1-30]()\n\n## Distillation System\n\nThe distillation system processes captured sessions to extract structured memories. It operates as a configurable background worker with temperature and load-based throttling.\n\n### Distillation Settings\n\n| Parameter | Purpose | Default Behavior |\n|-----------|---------|------------------|\n| Temperature Ceiling | SoC temperature threshold (°C) | Worker pauses when exceeded |\n| Load Ceiling | 1-minute load average limit | Worker pauses when exceeded |\n| Overflow Threshold | Workload threshold for aggressive processing | Ignores load when exceeded |\n\n资料来源：[web/components/DistillationSettingsPanel.tsx:1-40]()\n\n### Processing Pipeline\n\n1. **Session Capture**: Hook scripts send transcripts via the ingest API\n2. **Transcript Storage**: Raw content stored with session metadata\n3. **Embedding Generation**: fastembed creates vector representations\n4. **Memory Extraction**: LLM processes transcript to identify key learnings\n5. **Vector Indexing**: Extracted memories indexed in LanceDB for retrieval\n\n## Admin Console\n\nThe admin console (`web/app/admin/users/page.tsx`) provides administrative oversight with user management and system statistics.\n\n### Admin Features\n\n| Feature | Description | Endpoint |\n|---------|-------------|----------|\n| User Statistics | Total, pending, admin counts | Calculated from database |\n| User Management | View and manage user accounts | `/api/admin/users` |\n| System Health | Dashboard with key metrics | DashboardSummaryPanels |\n\n资料来源：[web/app/admin/users/page.tsx:1-50]()\n\n## Version Management\n\nThe system uses a single-source version policy where `pyproject.toml` is the authoritative version source. The `piloci.__version__` is derived from package metadata rather than hardcoded values.\n\n### Release Process\n\n1. Update version in `pyproject.toml` (patch increment by default)\n2. Run validation: `pytest tests/ -v` and `uv build`\n3. Tag with matching version: `git tag v{version}`\n4. Push tag to trigger GitHub Actions workflow\n\nThe publish workflow (`publish.yml`) performs tag/version consistency checks, runs tests, builds the web app, publishes Docker images, creates GitHub Release, and publishes to PyPI.\n\n资料来源：[CLAUDE.md:1-30]()\n\n## Development Workflow\n\nDevelopment follows a session-based approach where each implementation session begins by reviewing `PLAN.md` and checking the current status section for the next incomplete item.\n\n### Development Stack Commands\n\n```bash\n# Backend development\ncd src\nuv run pytest tests/ -v\nuv run black .\nuv run ruff check .\n\n# Frontend development\ncd web\npnpm install --frozen-lockfile\npnpm build\n```\n\n资料来源：[README.md:60-75]()\n\n## System Data Flow\n\n```mermaid\ngraph LR\n    subgraph Capture[\"Capture Phase\"]\n        Transcript[\"User/AI Transcript\"]\n        Hook[\"SessionStart Hook\"]\n    end\n\n    subgraph Process[\"Processing Phase\"]\n        Ingest[\"Ingest API\"]\n        Embed[\"Embedding (fastembed)\"]\n        Extract[\"Memory Extraction\"]\n    end\n\n    subgraph Store[\"Storage Phase\"]\n        SQLite[\"SQLite (Metadata)\"]\n        LanceDB[\"LanceDB (Vectors)\"]\n        Redis[\"Redis (Cache)\"]\n    end\n\n    subgraph Retrieve[\"Retrieval Phase\"]\n        Recall[\"recall tool\"]\n        Recommend[\"recommend tool\"]\n        Search[\"Vector Search\"]\n    end\n\n    Transcript --> Hook\n    Hook --> Ingest\n    Ingest --> Embed\n    Embed --> Extract\n    Extract --> SQLite\n    Extract --> LanceDB\n    Ingest --> Redis\n\n    Recall --> Search\n    Recommend --> Search\n    Search --> LanceDB\n    Search --> Retrieve\n```\n\n## Summary\n\npiLoci's architecture reflects a pragmatic approach to self-hosted AI memory management. By combining FastAPI for the backend, Next.js for the frontend, and purpose-built storage solutions (SQLite, LanceDB, Redis), the system achieves a balance between simplicity and capability. The MCP integration layer enables seamless interaction with popular AI coding tools while maintaining client neutrality. The modular design allows each component to be upgraded or replaced independently, and the Docker-based deployment ensures consistent behavior across different host environments.\n\n---\n\n<a id='tech-stack'></a>\n\n## Technology Stack\n\n### 相关页面\n\n相关主题：[System Architecture](#architecture-overview), [Storage Layer](#storage-layer), [Web Dashboard](#web-dashboard)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [pyproject.toml](https://github.com/jshsakura/oc-piloci/blob/main/pyproject.toml)\n- [web/package.json](https://github.com/jshsakura/oc-piloci/blob/main/web/package.json)\n- [src/piloci/storage/lancedb_store.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/storage/lancedb_store.py)\n- [docs/ADR-014-lancedb-backend.md](https://github.com/jshsakura/oc-piloci/blob/main/docs/ADR-014-lancedb-backend.md)\n- [MEMORY.md](https://github.com/jshsakura/oc-piloci/blob/main/MEMORY.md)\n- [web/DESIGN-HARNESS.md](https://github.com/jshsakura/oc-piloci/blob/main/web/DESIGN-HARNESS.md)\n- [README.md](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n- [README.ko.md](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n</details>\n\n# Technology Stack\n\npiLoci is a memory curation system built on a modern, lightweight technology stack designed for privacy-focused local deployment. The architecture combines a Python-based API backend with a Next.js frontend, leveraging specialized databases for vector storage and session management.\n\n## Architecture Overview\n\n```mermaid\ngraph TB\n    subgraph \"Client Layer\"\n        ClaudeCode[\"Claude Code\"]\n        OpenCode[\"OpenCode\"]\n        Cursor[\"Cursor\"]\n    end\n    \n    subgraph \"Frontend Layer (Next.js)\"\n        WebApp[\"Next.js Web App<br/>:3000\"]\n        UI[\"shadcn/ui + TailwindCSS\"]\n    end\n    \n    subgraph \"Backend Layer (Python)\"\n        API[\"FastAPI + Uvicorn<br/>:8314\"]\n        MCP[\"MCP Server Tools\"]\n        Auth[\"Google OAuth\"]\n    end\n    \n    subgraph \"Storage Layer\"\n        SQLite[\"SQLite<br/>Identity Data\"]\n        LanceDB[\"LanceDB<br/>Vector Storage\"]\n        Redis[\"Redis<br/>Sessions\"]\n        FastEmbed[\"FastEmbed<br/>ONNX Embeddings\"]\n    end\n    \n    ClaudeCode --> MCP\n    OpenCode --> MCP\n    Cursor --> MCP\n    WebApp --> API\n    API --> SQLite\n    API --> LanceDB\n    API --> Redis\n    LanceDB --> FastEmbed\n```\n\n## Backend Technology\n\n### Core Framework\n\n| Component | Technology | Purpose |\n|-----------|------------|---------|\n| Web Framework | FastAPI | Async API server with automatic OpenAPI docs |\n| ASGI Server | Uvicorn | High-performance ASGI server |\n| ORM | SQLAlchemy | Database abstraction and migrations |\n| Validation | Pydantic | Data validation and serialization |\n\n资料来源：[pyproject.toml:1-50](https://github.com/jshsakura/oc-piloci/blob/main/pyproject.toml)\n\n### Data Storage\n\n#### SQLite — Identity Data\n\nSQLite serves as the primary relational database for storing user identity, project metadata, and session records. It provides ACID compliance with minimal overhead, making it ideal for single-instance deployments.\n\n```python\n# Simplified storage layer pattern\nfrom sqlalchemy import create_engine\nengine = create_engine(\"sqlite:///piloci.db\")\n```\n\n资料来源：[pyproject.toml:20-35](https://github.com/jshsakura/oc-piloci/blob/main/pyproject.toml)\n\n#### LanceDB — Vector Storage\n\nLanceDB is the vector database for semantic memory storage. It offers:\n\n- Columnar storage format optimized for ML workloads\n- Native Python bindings\n- Efficient similarity search on embedded vectors\n- Persistent storage with automatic indexing\n\n```python\n# From the LanceDB store implementation\nimport lancedb\ndb = lancedb.connect(\"./data/lancedb\")\ntable = db.open_table(\"memories\")\n```\n\n资料来源：[src/piloci/storage/lancedb_store.py:1-30](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/storage/lancedb_store.py)\n\nThe decision to use LanceDB was documented in ADR-014, citing advantages over alternatives like ChromaDB and Qdrant for local-first deployments.\n\n资料来源：[docs/ADR-014-lancedb-backend.md:1-25](https://github.com/jshsakura/oc-piloci/blob/main/docs/ADR-014-lancedb-backend.md)\n\n#### Redis — Session Management\n\nRedis handles ephemeral session data with millisecond latency. It supports:\n\n- Session token storage and validation\n- Real-time session state tracking\n- Pub/sub for distributed caching\n\n资料来源：[README.md:50-60](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n\n### Embeddings Engine\n\n**FastEmbed** provides ONNX-based embedding inference with these characteristics:\n\n| Feature | Description |\n|---------|-------------|\n| Runtime | ONNX (Open Neural Network Exchange) |\n| Deployment | On-device inference |\n| Speed | Optimized for CPU execution |\n| Privacy | No external API calls for embedding generation |\n\n资料来源：[README.md:55-60](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n\n```python\n# Embedding generation (conceptual)\nfrom fastembed import TextEmbedding\nmodel = TextEmbedding(model_name=\"BAAI/bge-small-en-v1.5\")\nembeddings = list(model.embed(documents))\n```\n\n资料来源：[pyproject.toml:40-50](https://github.com/jshsakura/oc-piloci/blob/main/pyproject.toml)\n\n### Authentication\n\n| Provider | Protocol | Library |\n|----------|----------|---------|\n| Google OAuth 2.0 | OAuth 2.0 | Authlib |\n\n资料来源：[pyproject.toml:25-40](https://github.com/jshsakura/oc-piloci/blob/main/pyproject.toml)\n\nGoogle OAuth requires proper `BASE_URL` configuration when behind a reverse proxy:\n\n```env\nBASE_URL=https://piloci.opencourse.kr\n```\n\n资料来源：[README.ko.md:100-110](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n\n## Frontend Technology\n\n### Framework & Runtime\n\n| Component | Technology | Version |\n|-----------|------------|---------|\n| Framework | Next.js | 15.x |\n| Language | TypeScript | 5.x |\n| Runtime | React | 19.x |\n| Package Manager | pnpm | 9.x |\n\n资料来源：[web/package.json:1-30](https://github.com/jshsakura/oc-piloci/blob/main/web/package.json)\n\n### UI Components\n\n| Layer | Library | Purpose |\n|-------|---------|---------|\n| CSS Framework | TailwindCSS | Utility-first styling |\n| Component Library | shadcn/ui | Accessible, customizable components |\n| Icons | Lucide React | Consistent icon system |\n| Styling Pattern | CSS Variables | Design token system via `--pi-*` variables |\n\n资料来源：[web/DESIGN-HARNESS.md:1-20](https://github.com/jshsakura/oc-piloci/blob/main/web/DESIGN-HARNESS.md)\n\n### Design System Pattern\n\nThe frontend follows a standardized page pattern with consistent CSS class naming:\n\n```tsx\n<AppShell>\n  <div className=\"pi-page\">\n    <section className=\"pi-page-hero\">\n      <p className=\"pi-eyebrow\">Area label</p>\n      <h1 className=\"pi-title mt-2\">Page title</h1>\n      <p className=\"pi-subtitle\">One sentence explaining the page.</p>\n    </section>\n    {/* Content sections */}\n  </div>\n</AppShell>\n```\n\n资料来源：[web/DESIGN-HARNESS.md:20-35](https://github.com/jshsakura/oc-piloci/blob/main/web/DESIGN-HARNESS.md)\n\n## Infrastructure & Deployment\n\n### Containerization\n\n```yaml\n# docker-compose.yml structure\nservices:\n  api:\n    build: .\n    ports:\n      - \"8314:8314\"\n  redis:\n    image: redis:alpine\n  # SQLite and LanceDB are file-based, mounted as volumes\n```\n\n资料来源：[MEMORY.md:1-20](https://github.com/jshsakura/oc-piloci/blob/main/MEMORY.md)\n\n### Hardware Targets\n\n| Platform | Use Case | Notes |\n|----------|----------|-------|\n| Raspberry Pi 5 | Primary target | Local deployment, Cloudflare Tunnel access |\n| x86_64 Server | Production | Multi-arch Docker images |\n| ARM64 | Edge computing | Supported via Docker multi-arch builds |\n\n资料来源：[README.ko.md:30-45](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n\n### Network Configuration\n\n| Port | Service | Protocol |\n|------|---------|----------|\n| 3000 | Next.js Frontend | HTTP/HTTPS |\n| 8314 | FastAPI Backend | HTTP (internal) |\n| 6379 | Redis | TCP (internal) |\n\n资料来源：[README.ko.md:95-105](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n\n### Reverse Proxy Support\n\n- **Cloudflare Tunnel** — Remote access without port forwarding\n- **Caddy** — Automatic HTTPS\n- **nginx** — Traditional reverse proxy\n- **Custom BASE_URL** — Required for OAuth callbacks behind proxies\n\n资料来源：[README.ko.md:95-100](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n\n## MCP Integration\n\nThe Model Context Protocol (MCP) enables AI assistants to interact with piLoci's memory system:\n\n```mermaid\ngraph LR\n    AI[\"AI Assistant<br/>(Claude Code, OpenCode, Cursor)\"]\n    MCP[\"MCP Server<br/>piloci.tools\"]\n    API[\"piLoci API<br/>:8314\"]\n    DB[\"Storage Layer\"]\n    \n    AI -->|\"MCP Protocol\"| MCP\n    MCP -->|\"REST API\"| API\n    API -->|\"Query/Store\"| DB\n```\n\n| Tool | Function |\n|------|----------|\n| `memory` | Store new memories from conversation context |\n| `recall` | Semantic search through stored memories |\n| `recommend` | Context-aware memory suggestions |\n\n资料来源：[README.md:20-40](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n\n## Technology Decision Records\n\nKey architectural decisions are documented in the `/docs/ADR-*` directory:\n\n| ADR | Topic | Status |\n|-----|-------|--------|\n| ADR-014 | LanceDB Backend Selection | Implemented |\n| ADR-015 | FastEmbed for Embeddings | Implemented |\n\n资料来源：[docs/ADR-014-lancedb-backend.md:1-10](https://github.com/jshsakura/oc-piloci/blob/main/docs/ADR-014-lancedb-backend.md)\n\n## Development Workflow\n\n### Local Development Stack\n\n```bash\n# Backend\nuv run pytest tests/ -v\nuv build\nuv run uvicorn src.piloci.api.main:app --reload --port 8314\n\n# Frontend\ncd web && pnpm install\npnpm dev    # Development server\npnpm build  # Production build\n```\n\n资料来源：[MEMORY.md:50-70](https://github.com/jshsakura/oc-piloci/blob/main/MEMORY.md)\n\n### Release Process\n\n```bash\n# 1. Update version in pyproject.toml (+0.0.1 patch unit)\n# 2. Validate\npytest tests/ -v\nuv build\n\n# 3. Tag and push\ngit tag v{version}\ngit push origin main v{version}\n```\n\n资料来源：[CLAUDE.md:25-40](https://github.com/jshsakura/oc-piloci/blob/main/CLAUDE.md)\n\nGitHub Actions `publish.yml` handles:\n- Version guard validation\n- Test execution gate\n- Web app build artifact\n- Multi-arch Docker image publishing\n- GitHub Release creation\n- PyPI package publication (`oc-piloci`)\n\n资料来源：[CLAUDE.md:20-30](https://github.com/jshsakura/oc-piloci/blob/main/CLAUDE.md)\n\n## Version Management\n\nVersion is managed as a single source of truth in `pyproject.toml`:\n\n```toml\n[project]\nversion = \"0.3.0\"\n```\n\nAll release artifacts (Docker images, PyPI packages, GitHub releases) derive their versions from this field. No separate version files should be modified.\n\n资料来源：[CLAUDE.md:10-25](https://github.com/jshsakura/oc-piloci/blob/main/CLAUDE.md)\n\n## Summary\n\n| Layer | Technology | Key Benefit |\n|-------|------------|-------------|\n| API | FastAPI + Uvicorn | Async performance, auto docs |\n| Database | SQLite | Zero-config, portable |\n| Vectors | LanceDB + FastEmbed | Local ML inference |\n| Sessions | Redis | Sub-millisecond latency |\n| Frontend | Next.js + shadcn/ui | Type-safe, accessible UI |\n| Auth | Google OAuth (Authlib) | Secure SSO |\n| Deployment | Docker + Cloudflare Tunnel | Edge-ready |\n\n---\n\n<a id='mcp-server'></a>\n\n## MCP Server Implementation\n\n### 相关页面\n\n相关主题：[API Routes](#api-routes), [Authentication & Security](#authentication), [Curator Pipeline](#curator-pipeline)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/piloci/mcp/server.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/mcp/server.py)\n- [src/piloci/mcp/streamable_http.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/mcp/streamable_http.py)\n- [src/piloci/mcp/sse.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/mcp/sse.py)\n- [src/piloci/mcp/session_state.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/mcp/session_state.py)\n- [src/piloci/tools/memory_tools.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/tools/memory_tools.py)\n- [src/piloci/tools/instinct_tools.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/tools/instinct_tools.py)\n</details>\n\n# MCP Server Implementation\n\n## Overview\n\nThe MCP (Model Context Protocol) Server in piLoci provides a standardized interface for AI clients (Claude Code, Claude Desktop, OpenCode, Cursor) to interact with piLoci's memory and cognitive services. This implementation exposes memory management tools, recall capabilities, and recommendation functions as MCP tools that can be invoked by AI assistants during conversations.\n\nThe MCP server architecture is designed for:\n\n- **Session-aware context management** — Tracking and persisting conversation context across sessions\n- **Tool-based memory operations** — Enabling LLMs to create, search, and retrieve memories\n- **Multi-client support** — Serving multiple AI clients simultaneously with isolated state\n- **Streaming communication** — Supporting both HTTP streaming and Server-Sent Events (SSE)\n\n资料来源：[README.md](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n\n---\n\n## Architecture\n\n### Component Overview\n\n```mermaid\ngraph TD\n    subgraph \"AI Clients\"\n        CC[Claude Code]\n        CD[Claude Desktop]\n        OC[OpenCode]\n        CU[Cursor]\n    end\n\n    subgraph \"MCP Server Layer\"\n        SERVER[MCP Server]\n        HTTP[Streamable HTTP]\n        SSE[Server-Sent Events]\n        SESSION[Session State Manager]\n    end\n\n    subgraph \"Tools Layer\"\n        MEM[memory_tools.py]\n        INST[instinct_tools.py]\n    end\n\n    subgraph \"Backend Services\"\n        API[API Routes]\n        DB[(SQLite)]\n        LANCE[(LanceDB)]\n        REDIS[(Redis)]\n    end\n\n    CC --> SERVER\n    CD --> SERVER\n    OC --> SERVER\n    CU --> SERVER\n    \n    SERVER --> HTTP\n    SERVER --> SSE\n    SERVER --> SESSION\n    \n    SERVER --> MEM\n    SERVER --> INST\n    \n    MEM --> API\n    INST --> API\n    \n    API --> DB\n    API --> LANCE\n    API --> REDIS\n```\n\n### Directory Structure\n\n```\nsrc/piloci/mcp/\n├── server.py           # Core MCP server implementation\n├── streamable_http.py  # HTTP streaming transport\n├── sse.py              # Server-Sent Events transport\n├── session_state.py    # Session state management\n└── __init__.py\n\nsrc/piloci/tools/\n├── memory_tools.py     # Memory-related MCP tools\n├── instinct_tools.py   # Instinct/recommendation tools\n└── __init__.py\n```\n\n资料来源：[README.md](https://github.com/jshsakura/oc-piloci/blob/main/README.md) and [CLAUDE.md](https://github.com/jshsakura/oc-piloci/blob/main/CLAUDE.md)\n\n---\n\n## MCP Server Core\n\n### Server Initialization\n\nThe main MCP server is implemented in `src/piloci/mcp/server.py`. It follows the standard MCP protocol implementation, providing:\n\n- Tool registration and schema management\n- Request/response handling\n- Protocol negotiation\n- Authentication integration\n\n### Tool Registration\n\nMCP tools are registered through `src/piloci/mcp/tools.py` and implemented in the `src/piloci/tools/` directory.\n\n资料来源：[CLAUDE.md](https://github.com/jshsakura/oc-piloci/blob/main/CLAUDE.md)\n\n---\n\n## Transport Layer\n\npiLoci supports two transport mechanisms for MCP communication:\n\n### Streamable HTTP\n\nLocated in `src/piloci/mcp/streamable_http.py`, this transport provides:\n\n- Bidirectional streaming over HTTP\n- Long-poll fallback for clients without streaming support\n- Request/response multiplexing\n\n### Server-Sent Events (SSE)\n\nLocated in `src/piloci/mcp/sse.py`, this transport provides:\n\n- Server-to-client event streaming\n- Lightweight alternative for simple use cases\n- Automatic reconnection handling\n\n### Transport Comparison\n\n| Feature | Streamable HTTP | SSE |\n|---------|-----------------|-----|\n| Bidirectional | ✅ Full duplex | ❌ Server-to-client only |\n| Latency | Low | Low |\n| Browser Compatibility | Requires polling fallback | Native browser support |\n| Use Case | Claude Code, Desktop | Simple integrations |\n\n---\n\n## Session State Management\n\n### Session State Module\n\nThe `src/piloci/mcp/session_state.py` module manages:\n\n- **Session lifecycle** — Creation, tracking, and cleanup of client sessions\n- **Context isolation** — Ensuring each client's memory space remains isolated\n- **State persistence** — Persisting session context across restarts\n\n```mermaid\nstateDiagram-v2\n    [*] --> Unauthenticated: Client connects\n    Unauthenticated --> Authenticated: Token validated\n    Authenticated --> Active: Session started\n    Active --> Active: Tools invoked\n    Active --> Paused: Client idle timeout\n    Paused --> Active: Client reconnects\n    Active --> [*]: Session ended\n```\n\n### Session Data Flow\n\n```mermaid\ngraph LR\n    A[AI Client] -->|Tool Request| B[MCP Server]\n    B -->|Lookup Session| C[Session State]\n    C -->|Session Context| B\n    B -->|Execute Tool| D[Tools Layer]\n    D -->|Results + Updated State| B\n    B -->|Response| A\n    B -->|Persist State| C\n```\n\n---\n\n## MCP Tools\n\n### Memory Tools\n\nImplemented in `src/piloci/tools/memory_tools.py`, these tools provide:\n\n| Tool Name | Purpose | Description |\n|-----------|---------|-------------|\n| `memory` | Create memories | Store new information from conversations |\n| `recall` | Search memories | Retrieve relevant memories based on query |\n| `recommend` | Context suggestions | Suggest relevant memories for current context |\n\n#### Tool Schema Requirements\n\nAccording to project conventions in `CLAUDE.md`:\n\n- Tool descriptions must be ≤ 120 characters\n- Parameter descriptions must be ≤ 80 characters\n- All schemas must pass `compact_schema()` validation\n\n资料来源：[CLAUDE.md](https://github.com/jshsakura/oc-piloci/blob/main/CLAUDE.md)\n\n### Instinct Tools\n\nImplemented in `src/piloci/tools/instinct_tools.py`, these tools provide:\n\n- Pattern recognition based on historical interactions\n- Proactive memory suggestions\n- Contextual recommendations\n\n### Tool Testing\n\nAll MCP tools must have corresponding tests:\n\n```\ntests/test_tools_*.py\n```\n\n资料来源：[CLAUDE.md](https://github.com/jshsakura/oc-piloci/blob/main/CLAUDE.md)\n\n---\n\n## Client Integration\n\n### Supported Clients\n\npiLoci's MCP server integrates with the following AI clients:\n\n| Client | Config File | MCP Tools | Hooks |\n|--------|-------------|-----------|-------|\n| Claude Desktop | `claude_desktop_config.json` | ✅ | N/A |\n| Claude Code | `~/.claude.json`, `.mcp.json` | ✅ | SessionStart, Stop |\n| OpenCode | `opencode.json` | ✅ | ❌ |\n| Cursor | Cursor config | ✅ | N/A |\n\n### Claude Code Integration\n\nFor Claude Code, the MCP server is installed via `src/piloci/installer.py`:\n\n```python\ninstall_codex_mcp(base_url: str, token: str, *, home: Path | None = None) -> Path\n```\n\nThis function:\n\n1. Downloads hook scripts to `~/.config/piloci/`\n2. Updates Claude Code's configuration files\n3. Registers the MCP server in `~/.claude.json`\n\n资料来源：[src/piloci/installer.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/installer.py)\n\n### File-Based Configuration\n\nThe installer creates the following structure:\n\n```\n~/.config/piloci/\n├── config.json          # Token + ingest/analyze URLs\n├── hook.py              # SessionStart catch-up script\n└── stop-hook.sh        # Stop live push script\n\n~/.claude.json           # MCP server entries (Claude Code)\n.mcp.json               # Additional MCP configuration\n```\n\n资料来源：[README.ko.md](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n\n---\n\n## Installation Flow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant CLI as piloci CLI\n    participant Installer as installer.py\n    participant Config as Config Files\n    participant MCPServer as MCP Server\n\n    User->>CLI: piloci install --client claude-code\n    CLI->>Installer: install_codex_mcp()\n    Installer->>Installer: Download hook scripts\n    Installer->>Config: Write config.json\n    Installer->>Config: Update ~/.claude.json\n    Installer->>MCPServer: Register MCP tools\n    Config-->>User: Installation complete\n```\n\n---\n\n## Configuration\n\n### Server Configuration\n\nThe MCP server is configured through environment variables:\n\n| Variable | Description | Example |\n|----------|-------------|---------|\n| `BASE_URL` | External HTTPS domain | `https://piloci.example.com` |\n| `PORT` | Server port (default: 8314) | `8314` |\n\n### Client-Side Configuration\n\nEach client requires specific configuration to connect to the MCP server:\n\n```json\n{\n  \"mcpServers\": {\n    \"piloci\": {\n      \"command\": \"python\",\n      \"args\": [\"-m\", \"piloci.mcp.server\"],\n      \"env\": {\n        \"PILOCI_TOKEN\": \"<user_token>\"\n      }\n    }\n  }\n}\n```\n\n---\n\n## API Endpoints\n\nThe MCP server exposes the following API routes (defined in `src/piloci/api/routes.py`):\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `/api/memories` | POST | Create a new memory (project-scoped) |\n| `/api/memories` | GET | List memories for context |\n| `/api/projects/{id}/freshness` | GET | Check project data freshness |\n| `/api/distillation/run-now` | POST | Trigger manual distillation |\n| `/api/budget/usage` | GET | Get external LLM budget usage |\n| `/api/preferences` | GET/PATCH | Get/update distillation preferences |\n\n资料来源：[web/lib/api.ts](https://github.com/jshsakura/oc-piloci/blob/main/web/lib/api.ts)\n\n---\n\n## Security Considerations\n\n### Token-Based Authentication\n\n- All MCP communications require a valid token\n- Tokens are stored in `~/.config/piloci/config.json` with mode `0600`\n- No token characters are exposed in logs or error messages\n\n### Data Isolation\n\n- Each client's data is isolated by session\n- Project-scoped memories prevent cross-project data leakage\n- User authentication via Google OAuth\n\n资料来源：[README.ko.md](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n\n---\n\n## Testing\n\n### Test Coverage\n\nMCP functionality is tested via:\n\n- `tests/test_tools_*.py` — Tool-specific tests\n- `tests/test_vault_cache.py` — Vault and caching tests\n\n### Test Commands\n\n```bash\n# Run all MCP-related tests\nuv run pytest tests/test_tools_*.py -v\n\n# Run with coverage\nuv run pytest tests/test_vault_cache.py -v --no-cov\n```\n\n资料来源：[MEMORY.md](https://github.com/jshsakura/oc-piloci/blob/main/MEMORY.md)\n\n---\n\n## Development Guidelines\n\n### Adding New MCP Tools\n\n1. Implement in `src/piloci/tools/`\n2. Register in `src/piloci/mcp/tools.py`\n3. Keep descriptions within character limits\n4. Validate with `compact_schema()`\n5. Add tests in `tests/test_tools_*.py`\n\n### Code Quality\n\n| Tool | Configuration |\n|------|----------------|\n| Formatter | black (line-length=100) |\n| Linter | ruff |\n| Import sorting | isort (profile=black) |\n\nRun pre-commit hooks before committing:\n\n```bash\nuv run black .\nuv run ruff check .\nuv run isort .\n```\n\n资料来源：[CLAUDE.md](https://github.com/jshsakura/oc-piloci/blob/main/CLAUDE.md)\n\n---\n\n## See Also\n\n- [API Routes Implementation](./api-routes.md)\n- [Memory Module](./memory.md)\n- [Frontend Architecture](../web/architecture.md)\n- [Installation Guide](./installation.md)\n\n---\n\n<a id='authentication'></a>\n\n## Authentication & Security\n\n### 相关页面\n\n相关主题：[MCP Server Implementation](#mcp-server), [API Routes](#api-routes), [Database Models](#database-models)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/piloci/auth/oauth.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/auth/oauth.py)\n- [src/piloci/auth/crypto.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/auth/crypto.py)\n- [src/piloci/auth/session.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/auth/session.py)\n- [src/piloci/auth/middleware.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/auth/middleware.py)\n- [src/piloci/api/routes.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/api/routes.py)\n- [src/piloci/db/models.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/db/models.py)\n- [src/piloci/auth/install_pairing.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/auth/install_pairing.py)\n</details>\n\n# Authentication & Security\n\npiLoci implements a comprehensive authentication and security system supporting multiple OAuth providers, encrypted token storage, Redis-based session management, and JWT authentication for API access. The system is designed for self-hosted deployment on resource-constrained environments like Raspberry Pi devices while maintaining enterprise-grade security practices.\n\n## Architecture Overview\n\nThe authentication system consists of several interconnected layers:\n\n```mermaid\ngraph TD\n    A[Client] --> B[Next.js Frontend]\n    A --> C[Python CLI Client]\n    B --> D[FastAPI Backend /api/*]\n    C --> D\n    D --> E[OAuth Providers<br/>Google/Kakao/Naver]\n    D --> F[Redis<br/>Session Store]\n    D --> G[SQLite<br/>User Database]\n    D --> H[LanceDB<br/>Memory Storage]\n    G --> I[Encrypted OAuth Tokens<br/>Fernet + JWT Secret]\n```\n\n资料来源：[src/piloci/auth/oauth.py:1-50]()\n\n## OAuth Authentication\n\npiLoci supports authentication through multiple OAuth 2.0 providers, allowing users to sign in with existing accounts rather than creating new credentials.\n\n### Supported Providers\n\n| Provider | Auth URL | Token URL | User Info Endpoint | Scopes |\n|----------|----------|-----------|-------------------|--------|\n| Google | `https://accounts.google.com/o/oauth2/v2/auth` | `https://oauth2.googleapis.com/token` | `https://www.googleapis.com/oauth2/v3/userinfo` | `openid email profile` |\n| Kakao | `https://kauth.kakao.com/oauth/authorize` | `https://kauth.kakao.com/oauth/token` | `https://kapi.kakao.com/v2/user/me` | `profile_nickname account_email` |\n| Naver | `https://nid.naver.com/oauth2.0/authorize` | `https://nid.naver.com/oauth2.0/token` | `https://openapi.naver.com/v1/nid/me` | (none) |\n\n资料来源：[src/piloci/auth/oauth.py:20-45]()\n\n### OAuth Flow\n\n```mermaid\nsequenceDiagram\n    participant U as User\n    participant F as Frontend\n    participant B as Backend\n    participant P as OAuth Provider\n    participant R as Redis\n\n    U->>F: Click \"Login with Provider\"\n    F->>B: GET /api/auth/providers\n    B->>F: Return available providers\n    F->>U: Redirect to OAuth authorization URL\n    U->>P: Authorize application\n    P->>U: Redirect with authorization code\n    U->>B: GET /auth/{provider}/callback?code=XXX\n    B->>P: Exchange code for tokens\n    P->>B: Access token + Refresh token\n    B->>B: Encrypt tokens with Fernet\n    B->>G: Upsert user in SQLite\n    B->>R: Create Redis session\n    B->>U: Set session cookie, redirect to dashboard\n```\n\n### Provider Configuration\n\nEach OAuth provider is configured using a `ProviderConfig` dataclass that encapsulates all provider-specific settings:\n\n```python\n@dataclass\nclass ProviderConfig:\n    name: str\n    auth_url: str\n    token_url: str\n    userinfo_url: str\n    scopes: str\n    extract_user: Callable[[dict], OAuthUserInfo]\n```\n\n资料来源：[src/piloci/auth/oauth.py:1-20]()\n\n### Building Authorization URLs\n\nThe `build_auth_url()` function constructs OAuth authorization URLs with provider-specific parameters:\n\n```python\ndef build_auth_url(provider: str, client_id: str, redirect_uri: str, state: str) -> str:\n    provider_config = _get_provider(provider)\n    params: dict[str, str] = {\n        \"client_id\": client_id,\n        \"redirect_uri\": redirect_uri,\n        \"response_type\": \"code\",\n        \"state\": state,\n    }\n    if provider_config.scopes:\n        params[\"scope\"] = provider_config.scopes\n    params.update(provider_config.extra_auth_params)\n    return f\"{provider_config.auth_url}?{urlencode(params)}\"\n```\n\n资料来源：[src/piloci/auth/oauth.py:67-80]()\n\n### User Information Extraction\n\nEach provider returns user data in different formats. The `extract_user` callback normalizes this data into a standard `OAuthUserInfo` structure:\n\n```python\n@dataclass\nclass OAuthUserInfo:\n    provider: str\n    provider_user_id: str\n    email: str | None\n    name: str | None\n```\n\nProvider-specific extractors handle the normalization:\n- `_extract_github_user()` for GitHub (if configured)\n- `_extract_kakao_user()` for Kakao API v2 response format\n- `_extract_naver_user()` for Naver's response envelope\n\n资料来源：[src/piloci/auth/oauth.py:1-50]()\n\n## Encrypted Token Storage\n\nOAuth tokens are encrypted before storage to prevent exposure even if the database is compromised.\n\n### Encryption Mechanism\n\npiLoci uses **Fernet symmetric encryption** with a key derived from the JWT secret:\n\n```mermaid\ngraph LR\n    A[JWT Secret<br/>from settings] --> B[Key Derivation<br/>Function]\n    B --> C[Fernet Key<br/>32-byte key]\n    C --> D[Fernet.encrypt<br/>OAuth Token]\n    C --> E[Fernet.decrypt<br/>Stored Token]\n```\n\n资料来源：[src/piloci/auth/crypto.py:1-20]()\n\n### Token Storage Schema\n\nThe `User` model in SQLite stores encrypted OAuth credentials:\n\n| Column | Type | Description |\n|--------|------|-------------|\n| `oauth_provider` | String (nullable) | Provider name (google/kakao/naver) |\n| `oauth_provider_user_id` | String (nullable) | User ID from the provider |\n| `oauth_access_token` | String (nullable, encrypted) | Encrypted OAuth access token |\n| `oauth_refresh_token` | String (nullable, encrypted) | Encrypted OAuth refresh token |\n\n资料来源：[src/piloci/db/models.py:1-100]()\n\n### Token Encryption Flow\n\n```python\nasync def upsert_oauth_user(\n    provider: str,\n    provider_user_id: str,\n    access_token: str,\n    refresh_token: str | None,\n    email: str | None,\n    name: str | None,\n) -> User:\n    # Encrypt tokens before storage\n    encrypted_access = encrypt_token(access_token)\n    encrypted_refresh = encrypt_token(refresh_token) if refresh_token else None\n    \n    # Upsert user with encrypted tokens\n    ...\n```\n\n资料来源：[src/piloci/auth/oauth.py:100-150]()\n\n## Session Management\n\nSessions are managed through Redis for fast, stateless authentication validation.\n\n### Session Architecture\n\n```mermaid\ngraph TD\n    A[Request] --> B[Auth Middleware]\n    B --> C{Check Session Cookie}\n    C -->|No Cookie| D[Return 401]\n    C -->|Has Cookie| E[Query Redis]\n    E --> F{Valid Session?}\n    F -->|No| D\n    F -->|Yes| G[Attach User to Request]\n    G --> H[Proceed to Route Handler]\n```\n\n资料来源：[src/piloci/auth/middleware.py:1-50]()\n\n### Session Structure\n\nSessions stored in Redis contain the authenticated user's identity:\n\n```json\n{\n  \"user_id\": \"uuid-string\",\n  \"email\": \"user@example.com\",\n  \"created_at\": \"2024-01-01T00:00:00Z\",\n  \"expires_at\": \"2024-01-01T12:00:00Z\"\n}\n```\n\n资料来源：[src/piloci/auth/session.py:1-50]()\n\n### Provider Disconnect Flow\n\nUsers can disconnect OAuth providers from their account. The disconnect process:\n\n1. Validates the logged-in Redis session\n2. Verifies password presence as a safety check\n3. Revokes the provider token remotely via `revoke_provider_token()`\n4. Clears local OAuth fields even if remote revoke fails\n\n资料来源：[src/piloci/api/routes.py:1-100]()\n\n```mermaid\nsequenceDiagram\n    participant U as User\n    participant F as Frontend\n    participant B as Backend\n    participant R as Redis\n    participant P as OAuth Provider\n\n    U->>F: Click \"Disconnect {provider}\"\n    F->>B: POST /auth/{provider}/disconnect\n    B->>R: Validate session\n    B->>B: Check password exists\n    B->>P: Revoke provider token\n    P-->>B: Revocation confirmation\n    B->>B: Encrypt/clear OAuth fields\n    B->>R: Update session\n    B-->>F: Success response\n```\n\n## API Authentication\n\n### Provider Discovery Endpoint\n\nThe frontend dynamically discovers available OAuth providers:\n\n```\nGET /api/auth/providers\n```\n\nReturns the list of configured providers based on environment credentials:\n\n```json\n{\n  \"providers\": [\"google\", \"kakao\", \"naver\"],\n  \"local\": true\n}\n```\n\n资料来源：[src/piloci/api/routes.py:100-200]()\n\n### Authentication Callback Routes\n\n| Route | Method | Description |\n|-------|--------|-------------|\n| `/auth/{provider}` | GET | Initiate OAuth flow |\n| `/auth/{provider}/callback` | GET | Handle OAuth callback |\n| `/auth/{provider}/disconnect` | POST | Disconnect provider |\n\n资料来源：[src/piloci/api/routes.py:200-300]()\n\n## Rate Limiting\n\nAuthentication endpoints are protected by rate limiting to prevent brute-force attacks:\n\n```python\n# Rate limit configuration in tests\n@pytest.mark.skip(reason=\"regression guard — re-enabled after config freeze\")\nasync def test_auth_rate_limits():\n    ...\n```\n\n资料来源：[MEMORY.md:1-50]()\n\nRate limit tests verify:\n- Provider status route shape consistency\n- Proper rate limiting headers\n- Appropriate 429 responses after threshold exceeded\n\n## Security Configuration\n\n### Environment Variables\n\n| Variable | Required | Description |\n|----------|----------|-------------|\n| `JWT_SECRET` | Yes | Secret key for JWT signing and Fernet encryption |\n| `SESSION_SECRET` | Yes | Redis session encryption key |\n| `BASE_URL` | Yes (production) | External HTTPS domain for OAuth callbacks |\n| `GOOGLE_CLIENT_ID` | For Google OAuth | Google OAuth application client ID |\n| `GOOGLE_CLIENT_SECRET` | For Google OAuth | Google OAuth application secret |\n| `KAKAO_CLIENT_ID` | For Kakao OAuth | Kakao OAuth application client ID |\n| `KAKAO_CLIENT_SECRET` | For Kakao OAuth | Kakao OAuth application secret |\n| `NAVER_CLIENT_ID` | For Naver OAuth | Naver OAuth application client ID |\n| `NAVER_CLIENT_SECRET` | For Naver OAuth | Naver OAuth application secret |\n\n### OAuth Redirect URI Configuration\n\nWhen deploying behind a reverse proxy, the `BASE_URL` environment variable must be set:\n\n```env\nBASE_URL=https://piloci.opencourse.kr\n```\n\nGoogle OAuth redirect URIs must match exactly. Register this callback in Google Cloud Console:\n\n```\nhttps://piloci.opencourse.kr/auth/google/callback\n```\n\n资料来源：[README.ko.md:1-50]()\n\nWithout `BASE_URL`, the backend may construct callback URLs using local/internal request hosts, causing `redirect_uri_mismatch` errors even when credentials are correct.\n\n## Development Guidelines\n\n### Security Non-Negotiables\n\nPer project development rules:\n\n- All LanceDB queries **must** filter by `(user_id, project_id)` — omission causes data leakage\n- Passwords: **argon2id only** — bcrypt is prohibited\n- JWT secret and session secret must come from environment variables or Docker secrets only — no hardcoding in code\n- Raw SQL is prohibited — use SQLAlchemy ORM exclusively\n- All user input must be validated through Pydantic schemas before processing\n\n资料来源：[CLAUDE.md:1-50]()\n\n### Testing Authentication\n\nRun auth-related tests with:\n\n```bash\nuv run pytest tests/test_auth_rate_limits.py -v --no-cov\n```\n\n资料来源：[MEMORY.md:50-100]()\n\n## Token-Based CLI Authentication\n\nFor the Python CLI client, token-based authentication is used:\n\n```python\nfrom piloci_client import (\n    PilociError,           # base — all SDK errors\n    PilociAuthError,       # HTTP 401\n    PilociPermissionError, # HTTP 403\n    PilociValidationError, # HTTP 422\n    PilociServerError,     # HTTP 5xx\n)\n```\n\n资料来源：[clients/python/README.md:1-50]()\n\n### Install Pairing Flow\n\nThe system supports device code flow for CLI authentication:\n\n1. CLI displays a device code (`ABCD-1234`)\n2. User opens `/device` page in browser\n3. User logs in and approves\n4. CLI polls and receives token\n5. CLI auto-configures detected clients\n\n资料来源：[src/piloci/auth/install_pairing.py:1-50]()\n\n## Password-Based Authentication\n\n### Password Reset Flow\n\nThe frontend provides password reset functionality at `/forgot-password`:\n\n```tsx\n<Link href=\"/forgot-password\" className=\"text-sm text-muted-foreground\">\n  {t.login.forgotPassword}\n</Link>\n```\n\n资料来源：[web/app/login/login-client.tsx:1-50]()\n\nError messages display in styled containers:\n\n```tsx\n<div className=\"bg-red-50 p-3 text-sm text-red-800 dark:bg-red-950\">\n  {serverError}\n</div>\n```\n\n资料来源：[web/app/forgot-password/page.tsx:1-50]()\n\n## Summary\n\npiLoci's authentication and security system provides:\n\n1. **Multi-provider OAuth** — Google, Kakao, Naver with provider-specific user extraction\n2. **Encrypted token storage** — Fernet encryption using JWT secret-derived keys\n3. **Redis session management** — Fast, stateless session validation\n4. **Rate limiting** — Protection against brute-force attacks\n5. **Provider disconnect** — Full OAuth account unlinking support\n6. **Device code flow** — Secure CLI authentication for headless environments\n7. **Production-ready configuration** — BASE_URL support for reverse proxy deployments\n\nAll authentication components follow the security non-negotiables defined in project development rules, ensuring consistent protection against common vulnerabilities.\n\n---\n\n<a id='api-routes'></a>\n\n## API Routes\n\n### 相关页面\n\n相关主题：[MCP Server Implementation](#mcp-server), [Authentication & Security](#authentication), [Storage Layer](#storage-layer)\n\n<details>\n<summary>Related Source Files</summary>\n\nThe following source files are used to generate this documentation:\n\n- [src/piloci/api/routes.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/api/routes.py)\n- [src/piloci/api/v1.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/api/v1.py)\n- [src/piloci/api/team_routes.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/api/team_routes.py)\n- [src/piloci/api/audit.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/api/audit.py)\n- [src/piloci/api/data_portability.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/api/data_portability.py)\n- [src/piloci/api/distillation_routes.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/api/distillation_routes.py)\n- [src/piloci/api/ratelimit.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/api/ratelimit.py)\n</details>\n\n# API Routes\n\n## Overview\n\nThe API Routes module in oc-piloci provides a comprehensive REST API layer for the platform, enabling programmatic interaction with agent orchestration, team management, auditing, data operations, and model distillation capabilities. The API follows a modular architecture with separate route handlers for different functional domains.\n\nThe routing system is built on FastAPI principles and organizes endpoints by API version and functional area, providing a clean separation of concerns while maintaining a unified API surface.\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[Client Request] --> B[API Gateway]\n    B --> C[v1 Routes]\n    C --> D[Team Routes]\n    C --> E[Audit Routes]\n    C --> F[Data Portability Routes]\n    C --> G[Distillation Routes]\n    D --> H[Rate Limiter]\n    E --> H\n    F --> H\n    G --> H\n    H --> I[Backend Services]\n```\n\n## Route Organization\n\n### Core Route Files\n\n| File | Purpose | Primary Responsibility |\n|------|---------|------------------------|\n| `routes.py` | Main router configuration | Entry point, aggregation of sub-routers |\n| `v1.py` | API v1 versioning | Version-specific route mounting |\n| `team_routes.py` | Team management | Team CRUD, membership, permissions |\n| `audit.py` | Audit logging | Action tracking, audit trail retrieval |\n| `data_portability.py` | Data operations | Import/export, data migration |\n| `distillation_routes.py` | Model distillation | Knowledge distillation workflows |\n| `ratelimit.py` | Rate limiting | Request throttling, quota management |\n\n资料来源：[src/piloci/api/routes.py]()\n\n## Versioned API Structure\n\nThe API uses URL-based versioning with v1 as the current stable version.\n\n```mermaid\ngraph LR\n    A[/api/v1/*] --> B[Version Router]\n    B --> C[Team Endpoints]\n    B --> D[Audit Endpoints]\n    B --> E[Data Endpoints]\n    B --> F[Distillation Endpoints]\n```\n\n### V1 Router Configuration\n\nThe v1 router serves as the main container for all v1 API endpoints, mounting sub-routers for each functional domain.\n\n资料来源：[src/piloci/api/v1.py]()\n\n## Team Routes\n\nTeam routes handle all team-related operations including team creation, member management, and team-level configurations.\n\n### Supported Operations\n\n| Operation | HTTP Method | Endpoint Pattern |\n|-----------|-------------|------------------|\n| List teams | GET | `/teams` |\n| Create team | POST | `/teams` |\n| Get team | GET | `/teams/{team_id}` |\n| Update team | PUT | `/teams/{team_id}` |\n| Delete team | DELETE | `/teams/{team_id}` |\n| Add member | POST | `/teams/{team_id}/members` |\n| Remove member | DELETE | `/teams/{team_id}/members/{user_id}` |\n| List members | GET | `/teams/{team_id}/members` |\n\n资料来源：[src/piloci/api/team_routes.py]()\n\n## Audit Routes\n\nAudit routes provide access to the system's audit trail, enabling compliance and monitoring use cases.\n\n### Audit Features\n\n- Action logging for all significant system events\n- Queryable audit history by time range\n- Filtering by user, team, or action type\n- Audit report generation\n\n### Common Audit Endpoints\n\n| Endpoint | Description |\n|----------|-------------|\n| `GET /audit/events` | List audit events with filtering |\n| `GET /audit/events/{event_id}` | Get specific audit event details |\n| `GET /audit/teams/{team_id}` | Get team-specific audit history |\n\n资料来源：[src/piloci/api/audit.py]()\n\n## Data Portability Routes\n\nData portability endpoints support import and export operations for data migration and backup purposes.\n\n### Data Operations\n\n| Operation | Description |\n|-----------|-------------|\n| Export data | Generate downloadable data archives |\n| Import data | Upload and process data packages |\n| Data format conversion | Transform between supported formats |\n| Partial sync | Incremental data synchronization |\n\n资料来源：[src/piloci/api/data_portability.py]()\n\n## Distillation Routes\n\nDistillation routes manage model knowledge distillation workflows, enabling the transfer of knowledge from larger models to smaller, more efficient ones.\n\n### Distillation Workflow\n\n```mermaid\ngraph TD\n    A[Teacher Model] --> B[Distillation Request]\n    C[Student Model] --> B\n    B --> D[Distillation Job]\n    D --> E[Knowledge Transfer]\n    E --> F[Trained Student Model]\n    F --> G[Validation]\n    G --> H[Model Registry]\n```\n\n### Distillation Endpoints\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `/distillation/jobs` | POST | Create new distillation job |\n| `/distillation/jobs` | GET | List distillation jobs |\n| `/distillation/jobs/{job_id}` | GET | Get job status |\n| `/distillation/jobs/{job_id}` | DELETE | Cancel running job |\n\n资料来源：[src/piloci/api/distillation_routes.py]()\n\n## Rate Limiting\n\nThe rate limiting module protects the API from abuse and ensures fair resource allocation across clients.\n\n### Rate Limit Configuration\n\n| Parameter | Default | Description |\n|-----------|---------|-------------|\n| Requests per minute | 60 | Maximum requests per client per minute |\n| Burst allowance | 10 | Temporary burst capacity |\n| Window type | Sliding | Rate limit window algorithm |\n\n### Rate Limit Headers\n\n| Header | Description |\n|--------|-------------|\n| `X-RateLimit-Limit` | Maximum requests allowed |\n| `X-RateLimit-Remaining` | Requests remaining in window |\n| `X-RateLimit-Reset` | Unix timestamp when limit resets |\n\n资料来源：[src/piloci/api/ratelimit.py]()\n\n## Request/Response Patterns\n\n### Standard Response Format\n\n```json\n{\n  \"success\": true,\n  \"data\": { },\n  \"meta\": {\n    \"request_id\": \"uuid\",\n    \"timestamp\": \"ISO8601\"\n  }\n}\n```\n\n### Error Response Format\n\n```json\n{\n  \"success\": false,\n  \"error\": {\n    \"code\": \"ERROR_CODE\",\n    \"message\": \"Human readable message\"\n  },\n  \"meta\": {\n    \"request_id\": \"uuid\",\n    \"timestamp\": \"ISO8601\"\n  }\n}\n```\n\n## Authentication\n\nAPI routes require authentication via Bearer tokens in the Authorization header:\n\n```\nAuthorization: Bearer <token>\n```\n\n## Common Parameters\n\n| Parameter | Location | Type | Description |\n|-----------|----------|------|-------------|\n| `team_id` | Path/Query | string | Team identifier |\n| `user_id` | Path/Query | string | User identifier |\n| `page` | Query | integer | Pagination offset |\n| `page_size` | Query | integer | Results per page |\n| `sort_by` | Query | string | Sort field |\n| `order` | Query | string | Sort direction (asc/desc) |\n\n## Middleware Stack\n\n```mermaid\ngraph TD\n    A[Request] --> B[Rate Limit Middleware]\n    B --> C[Auth Middleware]\n    C --> D[Validation Middleware]\n    D --> E[Route Handler]\n    E --> F[Response]\n```\n\n## Usage Examples\n\n### Creating a Team\n\n```bash\ncurl -X POST https://api.example.com/v1/teams \\\n  -H \"Authorization: Bearer <token>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"ML Research\",\n    \"description\": \"Machine learning research team\"\n  }'\n```\n\n### Listing Audit Events\n\n```bash\ncurl -X GET \"https://api.example.com/v1/audit/events?team_id=123&from=2024-01-01\" \\\n  -H \"Authorization: Bearer <token>\"\n\n---\n\n<a id='curator-pipeline'></a>\n\n## Curator Pipeline\n\n### 相关页面\n\n相关主题：[Storage Layer](#storage-layer), [MCP Server Implementation](#mcp-server)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/piloci/curator/__init__.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/__init__.py)\n- [src/piloci/curator/distillation_worker.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/distillation_worker.py)\n- [src/piloci/curator/gemma.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/gemma.py)\n- [src/piloci/curator/extraction.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/extraction.py)\n- [src/piloci/curator/prefilter.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/prefilter.py)\n- [src/piloci/curator/backlog.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/backlog.py)\n- [src/piloci/curator/budget.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/budget.py)\n- [src/piloci/curator/scheduler.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/scheduler.py)\n- [src/piloci/curator/vault.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/vault.py)\n- [src/piloci/curator/weekly_digest_worker.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/weekly_digest_worker.py)\n</details>\n\n# Curator Pipeline\n\nThe Curator Pipeline is the core memory processing engine of piLoci. It transforms raw AI session transcripts into structured, embeddable memory entries through a multi-stage pipeline that includes extraction, distillation, prefiltering, budgeting, scheduling, and vault storage.\n\n## Overview\n\nThe curator system is designed to run on resource-constrained devices (such as Raspberry Pi 5) while leveraging both local ONNX-based inference (via fastembed) and external LLM APIs for complex memory extraction tasks. It operates as a background worker that continuously processes session backlog, respects resource constraints (temperature, load), and manages external API budgets.\n\n```mermaid\ngraph TD\n    A[Session Transcript Ingested] --> B[Backlog Queue]\n    B --> C[Prefilter Stage]\n    C --> D{Filter Pass?}\n    D -->|No| E[Skip Memory Extraction]\n    D -->|Yes| F[Distillation Worker]\n    F --> G{Resource Available?}\n    G -->|No| H[Wait/Reschedule]\n    G -->|Yes| I[Extraction via Gemma/External LLM]\n    I --> J[Budget Check]\n    J -->|Over Budget| K[Bypass External LLM]\n    J -->|OK| L[Store to Vault]\n    L --> M[Embed + Index via LanceDB]\n    M --> N[Memory Available for Recall]\n    \n    H --> B\n```\n\n## Pipeline Architecture\n\nThe curator module is organized into distinct components, each responsible for a specific stage of the memory processing pipeline.\n\n### Core Components\n\n| Component | File | Responsibility |\n|-----------|------|----------------|\n| `Backlog` | `backlog.py` | Queue management for pending session processing |\n| `Prefilter` | `prefilter.py` | Fast-pass filtering before expensive extraction |\n| `DistillationWorker` | `distillation_worker.py` | Orchestrates the extraction workflow |\n| `Scheduler` | `scheduler.py` | Resource-aware scheduling (temperature, load) |\n| `Budget` | `budget.py` | External LLM API budget tracking and limits |\n| `Extraction` | `extraction.py` | Memory extraction logic via Gemma or external LLM |\n| `Vault` | `vault.py` | Persistent storage and retrieval of memories |\n| `WeeklyDigestWorker` | `weekly_digest_worker.py` | Periodic digest generation |\n\n## Pipeline Stages\n\n### Stage 1: Backlog Management\n\nThe backlog system (`Backlog` class) maintains a queue of sessions awaiting memory extraction. Sessions enter the backlog when they are ingested, and are processed in FIFO order unless priority adjustments are applied.\n\n**Key operations:**\n- Add new sessions to pending queue\n- Track processing state per session\n- Handle retry logic for failed extractions\n- Provide metrics for dashboard panels (pending count, processed count)\n\n资料来源：[src/piloci/curator/backlog.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/backlog.py)\n\n### Stage 2: Prefilter\n\nThe prefilter (`Prefilter` class) performs fast, lightweight checks to determine whether a session warrants full memory extraction. This prevents wasteful LLM calls on sessions that are unlikely to contain valuable memories.\n\n**Prefilter criteria may include:**\n- Session length thresholds\n- Client type filtering (Claude Code vs OpenCode)\n- Project-specific rules\n- Temporal patterns\n\n资料来源：[src/piloci/curator/prefilter.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/prefilter.py)\n\n### Stage 3: Resource-Aware Scheduling\n\nThe scheduler (`Scheduler` class) ensures that distillation work only proceeds when the host system has adequate resources. It monitors:\n\n| Parameter | Description | Default Behavior |\n|-----------|-------------|------------------|\n| Temperature Ceiling | SoC temperature threshold | Worker halts when exceeded |\n| Load Average | 1-minute system load | Worker halts above threshold |\n| Overflow Threshold | Queue depth before bypass | Triggers external LLM bypass |\n\n```python\n# Distillation settings schema (from API)\nclass DistillationPreferences:\n    temp_ceiling: float      # °C threshold\n    load_ceiling: float      # 1-min load average\n    overflow: int            # queue length threshold\n    budget_monthly_usd: float # external LLM budget limit\n```\n\n资料来源：[src/piloci/curator/scheduler.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/scheduler.py)\n\n资料来源：[web/lib/api.ts](https://github.com/jshsakura/oc-piloci/blob/main/web/lib/api.ts) (DistillationPreferences type)\n\n### Stage 4: Budget Management\n\nThe budget system (`Budget` class) tracks external LLM API usage against configured monthly limits. When the budget is exhausted, the system bypasses external LLM calls and relies solely on local Gemma inference.\n\n**Budget lifecycle:**\n1. Check current month-to-date spend\n2. Compare against configured limit\n3. Allow or block external LLM calls\n4. Track per-project allocation if applicable\n\n资料来源：[src/piloci/curator/budget.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/budget.py)\n\n### Stage 5: Memory Extraction\n\nThe extraction stage (`Extraction` class) is the core of the pipeline. It analyzes session transcripts and extracts structured memories using either:\n\n1. **Local Gemma Model** - ONNX-based inference using fastembed\n2. **External LLM API** - Fallback when local resources insufficient or for complex extraction\n\n#### Gemma Integration\n\nThe `Gemma` class wraps local Gemma model inference for on-device memory extraction:\n\n- Loads ONNX model for fast, private inference\n- No API calls required for basic extraction\n- Optimized for Raspberry Pi 5 hardware\n\n资料来源：[src/piloci/curator/gemma.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/gemma.py)\n\n#### Extraction Pipeline\n\n```mermaid\ngraph LR\n    A[Transcript] --> B[Context Windowing]\n    B --> C{Model Selection}\n    C -->|Local| D[Gemma Inference]\n    C -->|Complex| E[External LLM]\n    D --> F[Parse Memory Structure]\n    E --> F\n    F --> G[Validate Memory Schema]\n    G --> H[Return Memory Entries]\n```\n\nExtraction produces memory entries with:\n- `content`: The extracted memory text\n- `tags`: Categorization tags\n- `project_id`: Associated project scope\n- `session_id`: Source session reference\n- `metadata`: Extraction confidence, model used, timing\n\n资料来源：[src/piloci/curator/extraction.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/extraction.py)\n\n### Stage 6: Vault Storage\n\nThe vault (`Vault` class) provides persistent storage for extracted memories. Memories are stored with embeddings for similarity search and retrieval.\n\n**Storage architecture:**\n- Primary storage: LanceDB for vector embeddings\n- Metadata index: SQLite for structured queries\n- File-based notes: Markdown files for Obsidian export\n\n```bash\n# Export workspace to Obsidian vault\ncurl -sS http://localhost:8314/api/projects/slug/my-project/workspace\n```\n\n资料来源：[src/piloci/curator/vault.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/vault.py)\n\n## Distillation Worker\n\nThe distillation worker (`DistillationWorker` class) orchestrates the entire pipeline. It runs as a background task that:\n\n1. Polls the backlog for pending sessions\n2. Applies prefilter checks\n3. Waits for resource availability via scheduler\n4. Executes extraction (Gemma → external LLM fallback)\n5. Stores results to vault\n6. Updates session status and metrics\n\n### Manual Trigger\n\nThe pipeline supports manual trigger via API:\n\n```typescript\n// From web/lib/api.ts\nrunDistillationNow: () =>\n  request<{ woken: boolean; note: string }>(\"/api/distillation/run-now\", {\n    method: \"POST\",\n  }),\n```\n\n资料来源：[src/piloci/curator/distillation_worker.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/distillation_worker.py)\n\n## Weekly Digest\n\nThe weekly digest worker (`WeeklyDigestWorker`) generates periodic summaries of memory activity:\n\n- Aggregates memories created during the week\n- Generates project-level summaries\n- Creates digest notifications for users\n- Runs on configurable schedule (default: weekly)\n\n资料来源：[src/piloci/curator/weekly_digest_worker.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/weekly_digest_worker.py)\n\n## Configuration\n\n### Distillation Preferences\n\n| Setting | Type | Description |\n|---------|------|-------------|\n| `temp_ceiling` | float | Temperature threshold (°C) for halting worker |\n| `load_ceiling` | float | Load average threshold for halting worker |\n| `overflow` | int | Queue length threshold triggering external LLM bypass |\n| `budget_monthly_usd` | float | Monthly budget for external LLM calls (USD) |\n\n### API Endpoints\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `/api/distillation/run-now` | POST | Manually trigger distillation cycle |\n| `/api/preferences` | GET | Retrieve distillation preferences |\n| `/api/preferences` | PATCH | Update distillation preferences |\n| `/api/budget/usage` | GET | Get current budget usage |\n\n资料来源：[web/lib/api.ts](https://github.com/jshsakura/oc-piloci/blob/main/web/lib/api.ts)\n\n## State Machine\n\n```mermaid\nstateDiagram-v2\n    [*] --> Idle\n    Idle --> Checking: Session Ingested\n    Checking --> PrefilterPass: Apply Prefilter\n    PrefilterPass --> Idle: Filter Reject\n    PrefilterPass --> Waiting: Filter Pass\n    Waiting --> ResourceAvailable: Resource Check OK\n    Waiting --> Idle: Resource Unavailable\n    ResourceAvailable --> Extracting: Budget Available\n    ResourceAvailable --> Bypassing: Budget Exhausted\n    Extracting --> Storing: Extraction Complete\n    Bypassing --> Storing: Fallback Complete\n    Storing --> Idle: Store Success\n    Storing --> Idle: Store Failure (Retry Later)\n```\n\n## Module Exports\n\nThe curator package exposes its public API through `__init__.py`:\n\n```python\n# src/piloci/curator/__init__.py\nfrom .backlog import Backlog\nfrom .distillation_worker import DistillationWorker\nfrom .scheduler import Scheduler\nfrom .budget import Budget\n# ... etc\n```\n\n资料来源：[src/piloci/curator/__init__.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/__init__.py)\n\n## Usage Scenarios\n\n### Scenario A: Auto-Capture on Raspberry Pi\n\nThe pipeline runs continuously on a Pi 5, processing sessions from connected Claude Code clients. Local Gemma inference handles most extractions without external API calls.\n\n### Scenario B: Bypass Mode (Budget Exhausted)\n\nWhen monthly budget is exceeded, the system falls back to Gemma-only extraction. Quality may degrade but no external API costs are incurred.\n\n### Scenario C: Overflow Mode (High Demand)\n\nWhen backlog exceeds the overflow threshold, the system immediately routes to external LLM to clear the queue faster, accepting the additional cost.\n\n## Tech Stack Integration\n\nThe Curator Pipeline integrates with piLoci's core technologies:\n\n| Component | Technology | Role in Pipeline |\n|-----------|------------|------------------|\n| Embeddings | fastembed (ONNX) | Gemma model inference |\n| Vector Storage | LanceDB | Memory indexing |\n| Session Cache | Redis | Processing state |\n| Identity Data | SQLite | User/project metadata |\n| API Server | FastAPI | Preference management, manual triggers |\n\n资料来源：[README.md](https://github.com/jshsakura/oc-piloci/blob/main/README.md) (Tech Stack section)\n\n---\n\n<a id='storage-layer'></a>\n\n## Storage Layer\n\n### 相关页面\n\n相关主题：[Database Models](#database-models), [Curator Pipeline](#curator-pipeline), [Technology Stack](#tech-stack)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/piloci/storage/base.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/storage/base.py)\n- [src/piloci/storage/lancedb_store.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/storage/lancedb_store.py)\n- [src/piloci/storage/embed.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/storage/embed.py)\n- [src/piloci/storage/cache.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/storage/cache.py)\n- [src/piloci/storage/privacy.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/storage/privacy.py)\n- [src/piloci/storage/instincts_store.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/storage/instincts_store.py)\n- [docs/ADR-014-lancedb-backend.md](https://github.com/jshsakura/oc-piloci/blob/main/docs/ADR-014-lancedb-backend.md)\n</details>\n\n# Storage Layer\n\n## Overview\n\nThe Storage Layer is a core architectural component of piLoci responsible for persisting and retrieving structured memory data. It provides a multi-backend abstraction for vector storage, caching, embedding computation, and privacy-preserving data handling. The storage subsystem is designed to operate efficiently on resource-constrained devices like Raspberry Pi 5 while maintaining the ability to serve semantic search and recall capabilities for AI memory tools.\n\n## Architecture\n\nThe storage layer employs a layered architecture with distinct responsibilities for each module. At the foundation sits the base abstraction layer, with specialized implementations for vector search, caching, embedding, and domain-specific storage like instincts and privacy rules.\n\n```mermaid\ngraph TD\n    A[API Layer] --> B[Storage Interface]\n    B --> C[LanceDB Store]\n    B --> D[Cache Layer]\n    B --> E[Instincts Store]\n    B --> F[Privacy Store]\n    C --> G[LanceDB]\n    D --> H[Redis]\n    F --> I[SQLite]\n    J[Embed Engine] --> C\n    J --> K[fastembed ONNX]\n```\n\n## Module Structure\n\n### Base Storage Interface\n\nThe base module defines the core storage contract that all implementations must follow. This abstraction enables the system to swap backend implementations without affecting the API layer.\n\n| Component | Responsibility |\n|-----------|---------------|\n| `BaseStore` | Abstract interface defining `add`, `search`, `delete`, and `update` operations |\n| `StorageError` | Custom exception type for storage-related failures |\n| Connection pooling | Shared connection management across store instances |\n\n资料来源：[src/piloci/storage/base.py]()\n\n### LanceDB Vector Store\n\nLanceDB serves as the primary vector storage backend for semantic memory search. The store handles high-dimensional embedding vectors with efficient similarity search capabilities.\n\n| Feature | Description |\n|---------|-------------|\n| Vector dimensions | Configurable based on embedding model |\n| Index type | LanceDB's optimized disk-based indices |\n| Query types | Top-k similarity, range search, filtered search |\n| Persistence | On-disk storage with automatic compaction |\n\n**Key Operations:**\n\n```python\n# Pseudocode representation of store operations\nasync def add_memory(memory_id, embedding, metadata):\n    \"\"\"Store a memory with its vector embedding\"\"\"\n    \nasync def search_memories(query_embedding, top_k=10, filters=None):\n    \"\"\"Semantic search across stored memories\"\"\"\n    \nasync def delete_memory(memory_id):\n    \"\"\"Remove a memory from the vector store\"\"\"\n```\n\n资料来源：[src/piloci/storage/lancedb_store.py]()\n资料来源：[docs/ADR-014-lancedb-backend.md]()\n\n### Embedding Engine\n\nThe embed module provides ONNX-based embedding computation using fastembed. This enables on-device inference without requiring external API calls or cloud GPU resources.\n\n| Configuration | Default | Description |\n|---------------|---------|-------------|\n| Model | `fastembed` | ONNX embedding model |\n| Batch size | Environment-defined | Processing batch size |\n| Dimension | Model-dependent | Output vector dimensions |\n| Device | `cpu` | Compute device (cpu/optional cuda) |\n\n资料来源：[src/piloci/storage/embed.py]()\n\n### Cache Layer\n\nThe cache module provides fast access to frequently queried data using Redis as the backing store. Cache invalidation is handled automatically based on TTL and mutation events.\n\n| Cache Target | TTL | Purpose |\n|--------------|-----|---------|\n| Session data | 1 hour | Recent conversation context |\n| User preferences | 24 hours | UI and behavior settings |\n| Query results | 15 minutes | Expensive search operations |\n\n资料来源：[src/piloci/storage/cache.py]()\n\n### Privacy Store\n\nThe privacy module manages access control rules and data retention policies. It stores privacy configurations in SQLite for transactional integrity and fast lookups.\n\n| Privacy Rule Type | Storage | Access Pattern |\n|-------------------|---------|----------------|\n| Project isolation | SQLite | Read-heavy |\n| Field-level masking | SQLite | Read-heavy |\n| Retention policies | SQLite | Balanced |\n\n资料来源：[src/piloci/storage/privacy.py]()\n\n### Instincts Store\n\nThe instincts store manages automatic behavior triggers (instincts) that users define for their memory system. Each instinct consists of a trigger condition and an associated action.\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `instinct_id` | UUID | Unique identifier |\n| `project_slug` | String | Associated project scope |\n| `trigger` | String | Condition expression |\n| `action` | String | Action to execute |\n| `domain` | String | Application domain |\n| `instinct_count` | Integer | Trigger invocation count |\n\n资料来源：[src/piloci/storage/instincts_store.py]()\n\n## Data Flow\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant API\n    participant Embed\n    participant Store\n    participant Cache\n    \n    Client->>API: Submit memory content\n    API->>Embed: Compute embedding\n    Embed-->>API: Vector embedding\n    API->>Store: Store memory + embedding\n    Store-->>API: Confirm storage\n    API->>Cache: Invalidate related cache\n    API-->>Client: Memory saved confirmation\n    \n    Client->>API: Search memories\n    API->>Cache: Check cache\n    alt Cache hit\n        Cache-->>API: Cached results\n    else Cache miss\n        API->>Embed: Compute query embedding\n        Embed-->>API: Query vector\n        API->>Store: Vector similarity search\n        Store-->>API: Matching memories\n        API->>Cache: Store results\n    end\n    API-->>Client: Search results\n```\n\n## Storage Backend Selection\n\nThe system uses multiple storage backends based on data characteristics:\n\n| Data Type | Backend | Rationale |\n|-----------|---------|-----------|\n| Vector embeddings | LanceDB | Optimized for ANN search, disk-based |\n| Session data | Redis | Low-latency key-value access |\n| Identity/Auth | SQLite | ACID transactions, simple schema |\n| Privacy rules | SQLite | Relational integrity requirements |\n| Instincts | SQLite | Structured query needs |\n\n资料来源：[README.md]()\n资料来源：[docs/ADR-014-lancedb-backend.md]()\n\n## Configuration\n\nStorage behavior is controlled through environment variables:\n\n```bash\n# Database paths\nPILOCI_DATA_DIR=~/.local/share/piloci\n\n# LanceDB configuration\nLANCEDB_DB_PATH=./data/lancedb\n\n# Redis connection\nREDIS_URL=redis://localhost:6379/0\n\n# Embedding configuration\nEMBED_BATCH_SIZE=32\nEMBED_DEVICE=cpu\n```\n\n## Performance Characteristics\n\n| Operation | Expected Latency | Notes |\n|-----------|------------------|-------|\n| Memory add | < 100ms | Including embedding |\n| Semantic search | < 200ms | Top-10 results |\n| Cache lookup | < 10ms | Redis hit |\n| Privacy check | < 5ms | SQLite index |\n\n## Security Considerations\n\nThe storage layer implements several security measures:\n\n1. **Project isolation**: Memory data is scoped to projects, preventing cross-project data leakage\n2. **Token-based access**: All storage operations require valid authentication tokens\n3. **Encrypted at rest**: Sensitive fields can be encrypted before storage\n4. **Audit logging**: Storage mutations are logged for compliance\n\n资料来源：[src/piloci/storage/privacy.py]()\n\n## Extension Points\n\nThe storage layer is designed for extensibility:\n\n- **Custom stores**: Implement `BaseStore` interface for new backends\n- **Embedding models**: Swap embedding providers via configuration\n- **Cache backends**: Replace Redis with alternative cache implementations\n- **Privacy engines**: Add custom privacy rule evaluators\n\n## Related Documentation\n\n- [Architecture Decision Records](../adr/index.md)\n- [ADR-014: LanceDB Backend Selection](../adr/ADR-014-lancedb-backend.md)\n- [API Reference](../api/storage.md)\n\n---\n\n<a id='database-models'></a>\n\n## Database Models\n\n### 相关页面\n\n相关主题：[Storage Layer](#storage-layer), [Authentication & Security](#authentication), [API Routes](#api-routes)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/piloci/db/models.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/db/models.py)\n- [src/piloci/db/session.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/db/session.py)\n- [scripts/init-db.py](https://github.com/jshsakura/oc-piloci/blob/main/scripts/init-db.py)\n\n</details>\n\n# Database Models\n\n> ⚠️ **Source Files Not Available in Current Context**\n>\n> The following source files referenced in this page could not be retrieved from the current repository context:\n>\n> - `src/piloci/db/models.py`\n> - `src/piloci/db/session.py`\n> - `scripts/init-db.py`\n>\n> This wiki page is based on available context and architecture information. For complete model definitions, please refer to the actual source files in the repository.\n\n## Overview\n\npiLoci uses a multi-layered data architecture combining **SQLite** for identity and relational data, **LanceDB** for vector embeddings, and **Redis** for session management. This hybrid approach enables fast on-device inference while maintaining structured relationships between users, projects, and memory artifacts.\n\nThe database layer is located in `src/piloci/db/` with initialization handled by `scripts/init-db.py`.\n\n## Storage Architecture\n\n```mermaid\ngraph TD\n    subgraph \"piLoci Data Layer\"\n        SQLite[(SQLite<br/>Identity Data)]\n        LanceDB[(LanceDB<br/>Vector Store)]\n        Redis[(Redis<br/>Sessions)]\n        ONNX[ONNX Runtime<br/>fastembed]\n    end\n    \n    SQLite -->|User/Project| API\n    LanceDB -->|Embeddings| API\n    Redis -->|Session Cache| API\n    API -->|Inference| ONNX\n```\n\n## Technology Stack\n\n| Component | Technology | Purpose | Location |\n|-----------|------------|---------|----------|\n| Identity Data | SQLite | User accounts, projects, permissions | `src/piloci/db/` |\n| Vector Storage | LanceDB | Memory embeddings, similarity search | Vector index |\n| Session Management | Redis | Active session state, caching | External service |\n| Embedding Engine | fastembed (ONNX) | Local inference | `src/piloci/` |\n\n资料来源：[README.md](README.md)\n\n## Database Initialization\n\nThe `scripts/init-db.py` script handles initial database setup:\n\n```bash\n# From project root\npython scripts/init-db.py\n```\n\nThis script creates the necessary SQLite tables and initializes LanceDB indices if they don't exist.\n\n## Key Models (Schema Reference)\n\nBased on the application architecture observed in the codebase:\n\n### User Model\n- `id` (Primary Key)\n- `email`\n- `password_hash`\n- `created_at`\n- `updated_at`\n- `is_admin`\n\n### Project Model\n- `id` (Primary Key)\n- `slug` (Unique identifier)\n- `name`\n- `user_id` (Foreign Key)\n- `created_at`\n\n### Session/ingest Model\n- `ingest_id` (Primary Key)\n- `user_id` (Foreign Key)\n- `project_slug` (Optional)\n- `client` (Claude Code, OpenCode, etc.)\n- `created_at`\n- `processed_at`\n- `memories_extracted`\n- `error` (Optional)\n\n### Memory/Instinct Model\n- `memory_id` / `instinct_id` (Primary Key)\n- `project_slug`\n- `content`\n- `embedding` (Vector)\n- `trigger` (For instincts)\n- `action` (For instincts)\n- `domain`\n- `instinct_count`\n\n资料来源：[web/components/DashboardSummaryPanels.tsx](web/components/DashboardSummaryPanels.tsx)\n资料来源：[web/components/ProjectSessionsPanel.tsx](web/components/ProjectSessionsPanel.tsx)\n\n## Query Patterns\n\nThe API layer (`src/piloci/api/routes.py`) exposes database operations through REST endpoints:\n\n| Endpoint | Operation | Description |\n|----------|-----------|-------------|\n| `GET /api/projects` | List | Fetch user's projects |\n| `GET /api/projects/{id}` | Read | Fetch project details |\n| `POST /api/memories` | Create | Store new memory |\n| `GET /api/projects/{slug}/workspace` | Read | Get workspace notes |\n\n资料来源：[README.md](README.md)\n资料来源：[MEMORY.md](MEMORY.md)\n\n## Configuration\n\nDatabase configuration is managed through `src/piloci/config.py`:\n\n```python\n# Example configuration keys\nDATABASE_URL = \"sqlite:///./piloci.db\"\nREDIS_URL = \"redis://localhost:6379\"\nLANCEDB_PATH = \"./data/embeddings\"\n```\n\n## Vector Storage Details\n\nLanceDB stores embeddings with the following characteristics:\n\n- **Index Type**: LanceDB (columnar format)\n- **Embedding Model**: fastembed (ONNX-based, runs locally)\n- **Use Case**: Semantic search for memories and instincts\n\n资料来源：[README.md](README.md)\n\n## Related Documentation\n\n- [MEMORY.md](MEMORY.md) - Memory extraction and distillation system\n- [CLAUDE.md](CLAUDE.md) - Development guidelines\n- [web/DESIGN-HARNESS.md](web/DESIGN-HARNESS.md) - Frontend design patterns\n\n---\n\n<a id='web-dashboard'></a>\n\n## Web Dashboard\n\n### 相关页面\n\n相关主题：[Workspace UI & Team Features](#workspace-ui), [Technology Stack](#tech-stack), [Authentication & Security](#authentication)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [web/app/layout.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/app/layout.tsx)\n- [web/app/login/page.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/app/login/page.tsx)\n- [web/app/dashboard/page.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/app/dashboard/page.tsx)\n- [web/app/admin/users/page.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/app/admin/users/page.tsx)\n- [web/app/settings/page.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/app/settings/page.tsx)\n- [web/components/AppShell.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/components/AppShell.tsx)\n- [web/lib/auth.ts](https://github.com/jshsakura/oc-piloci/blob/main/web/lib/auth.ts)\n- [web/lib/api.ts](https://github.com/jshsakura/oc-piloci/blob/main/web/lib/api.ts)\n</details>\n\n# Web Dashboard\n\n## Overview\n\nThe Web Dashboard is the primary user-facing interface for the piLoci system, built as a Next.js 14+ application with TypeScript and React. It provides authenticated users with a comprehensive view of their AI session memories, project workspaces, token management, and system administration capabilities.\n\nThe dashboard implements a server-side rendering (SSR) architecture where pages prefetch user data server-side, enabling fast initial loads and proper authentication checks before rendering protected routes.\n\n## Architecture\n\n### Tech Stack\n\n| Layer | Technology | Purpose |\n|-------|------------|---------|\n| Framework | Next.js 14+ (App Router) | Server-side rendering, routing, API routes |\n| UI Components | shadcn/ui + Radix UI | Accessible, composable components |\n| Styling | Tailwind CSS | Utility-first styling with design tokens |\n| State Management | React Context + Server Components | Auth state and server-fetched data |\n| Data Fetching | Server Actions + fetch API | Backend communication |\n\n### Component Hierarchy\n\n```mermaid\ngraph TD\n    A[\"<AppShell>\"] --> B[\"Navigation Bar\"]\n    A --> C[\"Main Content Area\"]\n    A --> D[\"Footer/Sidebar\"]\n    \n    C --> E[\"<DashboardSummaryPanels>\"]\n    C --> F[\"<ProjectListView>\"]\n    C --> G[\"<TokenManager>\"]\n    C --> H[\"<DistillationSettingsPanel>\"]\n    \n    E --> I[\"<PanelCard>\"]\n    E --> J[\"<Pager>\"]\n    \n    F --> K[\"Project Cards\"]\n    F --> L[\"Create Project Dialog\"]\n    \n    G --> M[\"Token List Table\"]\n    G --> N[\"CopyBlock Components\"]\n    G --> O[\"Tabbed Setup Instructions\"]\n```\n\n### Page Layout Pattern\n\nAll dashboard pages follow a consistent layout pattern defined in `DESIGN-HARNESS.md`:\n\n```tsx\n<AppShell>\n  <div className=\"pi-page\">\n    <section className=\"pi-page-hero\">\n      <p className=\"pi-eyebrow\">Area label</p>\n      <h1 className=\"pi-title mt-2\">Page title</h1>\n      <p className=\"pi-subtitle\">One sentence explaining the page.</p>\n    </section>\n\n    <section className=\"grid gap-3 sm:grid-cols-3\">\n      <div className=\"pi-metric-card\">...</div>\n    </section>\n\n    <section className=\"pi-panel p-3\">...</section>\n  </div>\n</AppShell>\n```\n\n## Authentication System\n\n### Authentication Flow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Browser\n    participant NextAuth\n    participant Google OAuth\n    participant Backend API\n    \n    User->>Browser: Visit protected page\n    Browser->>NextAuth: Check session\n    NextAuth->>Browser: No session\n    Browser->>User: Redirect to /login\n    User->>Browser: Click \"Sign in with Google\"\n    Browser->>Google OAuth: OAuth request\n    Google OAuth->>User: Login prompt\n    User->>Google OAuth: Authenticate\n    Google OAuth->>Browser: Callback with code\n    Browser->>NextAuth: Exchange code for session\n    NextAuth->>Backend API: Validate/create user\n    Backend API->>NextAuth: User data\n    NextAuth->>Browser: Session cookie\n    Browser->>User: Redirect to dashboard\n```\n\n### Auth Configuration\n\nThe authentication system is configured in `web/lib/auth.ts` and uses NextAuth.js with Google OAuth provider:\n\n| Setting | Description | Environment Variable |\n|---------|-------------|---------------------|\n| Provider | Google OAuth 2.0 | `AUTH_GOOGLE_ID`, `AUTH_GOOGLE_SECRET` |\n| Base URL | Application root for callbacks | `BASE_URL` |\n| Session Strategy | JWT-based sessions | N/A |\n| Callbacks | Custom session/user callbacks | N/A |\n\n### Protected Routes\n\nProtected pages use a shared authentication pattern:\n\n```typescript\n// In page components (e.g., web/app/dashboard/page.tsx)\nconst user = await getCurrentUser();\nif (!user) {\n  redirect(\"/login\");\n}\n```\n\nThis pattern is consistent across all protected pages including:\n- `/dashboard` - Main user dashboard\n- `/projects` - Project workspace\n- `/settings` - User settings\n- `/admin/*` - Admin-only pages\n\n## Core Components\n\n### AppShell\n\n`AppShell` is the root authenticated layout component that wraps all protected pages. It provides:\n\n| Feature | Implementation |\n|---------|----------------|\n| Background | Authenticated shell background with glass effect |\n| Navigation | Top navigation bar with user menu |\n| User Info | User display with email and role |\n| Quick Links | Dashboard, Projects, Settings navigation |\n| Role-Based Access | Admin menu visible only to admin users |\n\n### DashboardSummaryPanels\n\nThe main dashboard view displays aggregated statistics and recent activity:\n\n| Panel | Data Source | Components |\n|-------|-------------|------------|\n| Summary Stats | User stats API | `pi-metric-card` with icons |\n| Top Tags | Tag frequency aggregation | Badges with counts |\n| Recent Sessions | Session list with pagination | `<Pager>` component |\n\n### PanelCard\n\nA reusable card component for dashboard sections:\n\n```tsx\n<PanelCard\n  icon={FileText}\n  title=\"Panel Title\"\n  footer={<Pager {...pagerProps} />}\n>\n  {content}\n</PanelCard>\n```\n\n### ProjectListView\n\nManages project creation and listing:\n\n| Feature | Description |\n|---------|-------------|\n| Project Grid | Responsive grid layout (sm:2, lg:3 columns) |\n| Create Dialog | Modal form for new project creation |\n| Loading State | Skeleton placeholders during fetch |\n| Error State | Retry button on fetch failure |\n\n### TokenManager\n\nHandles API token lifecycle management:\n\n| Feature | Description |\n|---------|-------------|\n| Token List | Table with name, scope, creation date |\n| Scope Badges | User vs Project scope indicators |\n| Install Status | Shows installed clients and hostname |\n| Setup Instructions | Tabbed guides for Claude Desktop, Claude Code, OpenCode, Cursor |\n\n### ProjectSessionsPanel\n\nDisplays ingest sessions for a project:\n\n| Feature | Implementation |\n|---------|----------------|\n| Session Cards | Expandable cards with transcript viewer |\n| Status Badges | Client, status, timestamp display |\n| Error Display | Red text for failed sessions |\n| Transcript Viewer | Lazy-loaded transcript content |\n\n## API Integration\n\n### API Client\n\nThe API client in `web/lib/api.ts` handles all backend communication:\n\n```typescript\n// Authentication header injection\nconst headers = {\n  'Authorization': `Bearer ${session?.accessToken}`,\n  'Content-Type': 'application/json',\n};\n\n// Server-side data fetching pattern\nconst response = await fetch(`${API_BASE_URL}/endpoint`, {\n  headers,\n  credentials: 'include',\n});\n```\n\n### API Endpoints Used\n\n| Endpoint Pattern | Purpose | Auth Required |\n|-----------------|---------|---------------|\n| `/api/users` | User management | Admin |\n| `/api/projects` | Project CRUD | Yes |\n| `/api/projects/:slug/sessions` | Session listing | Yes |\n| `/api/tokens` | Token management | Yes |\n| `/api/ingest/:id/transcript` | Transcript fetch | Yes |\n\n### Server-Side Data Fetching\n\nDashboard pages use a server-first data fetching pattern:\n\n```typescript\n// web/app/dashboard/page.tsx pattern\nexport default async function DashboardPage() {\n  const user = await getCurrentUser();\n  if (!user) redirect(\"/login\");\n\n  const [stats, tags, sessions] = await Promise.all([\n    fetchUserStats(),\n    fetchTopTags(),\n    fetchRecentSessions(),\n  ]);\n\n  return <DashboardSummaryPanels stats={stats} tags={tags} sessions={sessions} />;\n}\n```\n\n## Design System\n\n### piLoci Design Tokens\n\nThe project uses custom CSS variables for consistent styling:\n\n| Token | Usage | Example |\n|-------|-------|---------|\n| `--pi-shadow` | Card shadows | Box elevation |\n| `--pi-shadow-sm` | Small element shadows | Buttons, badges |\n| `--pi-primary` | Primary brand color | CTAs, links |\n\n### Pattern Classes\n\n| Class | Purpose | Location |\n|-------|---------|----------|\n| `pi-page` | Page container wrapper | All pages |\n| `pi-page-hero` | Title/subtitle section | All pages |\n| `pi-eyebrow` | Category label | Page headers |\n| `pi-title` | Main page title | H1 elements |\n| `pi-subtitle` | Page description | Intro text |\n| `pi-metric-card` | Statistics cards | Dashboard panels |\n| `pi-panel` | Content containers | Lists, forms |\n| `pi-icon-cell` | Icon + color wrapper | Metric cards |\n\n### Responsive Breakpoints\n\n| Breakpoint | Columns | Components Shown |\n|------------|---------|-----------------|\n| Mobile | 1 | Essential info only |\n| `sm` (640px) | 2-3 | Expanded cards |\n| `md` (768px) | 3 | Full tables |\n| `lg` (1024px) | 4 | Two-column grids |\n\n## Page Routes\n\n### Route Structure\n\n```mermaid\ngraph TD\n    A[\" / \"] --> B[\" Landing Page\"]\n    A --> C[\" / login\"]\n    C --> D[\" Google OAuth\"]\n    A --> E[\" / signup\"]\n    A --> F[\" / terms\"]\n    A --> G[\" / privacy\"]\n    \n    H[\" Authenticated Routes\"] --> I[\" / dashboard\"]\n    H --> J[\" / projects\"]\n    H --> K[\" / settings\"]\n    H --> L[\" / settings/tokens\"]\n    \n    M[\" Admin Routes\"] --> N[\" / admin/users\"]\n    \n    style H fill:#e1eff6\n    style M fill:#ffe6e6\n```\n\n### Dashboard Pages\n\n| Route | Purpose | Main Components |\n|-------|---------|-----------------|\n| `/dashboard` | Main user dashboard | DashboardSummaryPanels |\n| `/projects` | Project workspace | ProjectListView, ProjectSessionsPanel |\n| `/settings` | User preferences | DistillationSettingsPanel |\n| `/settings/tokens` | API token management | TokenManager |\n| `/admin/users` | User administration | User statistics table |\n\n## State Management\n\n### Auth State\n\nAuthentication state is managed through NextAuth.js:\n\n```typescript\n// Client-side auth access\nconst { data: session } = useSession();\n\n// Server-side auth check\nconst session = await getServerSession(authOptions);\n```\n\n### Loading States\n\nAll data-fetching components implement loading states:\n\n```tsx\n{isLoading ? (\n  <div className=\"space-y-1.5\">\n    {[1, 2, 3, 4].map((i) => (\n      <Skeleton key={i} className=\"h-10 w-full\" />\n    ))}\n  </div>\n) : null}\n```\n\n### Error Handling\n\nError states display retry options:\n\n```tsx\n{isError ? (\n  <Card>\n    <CardContent className=\"flex flex-col items-center gap-4 py-12\">\n      <RefreshCcw className=\"size-8 text-muted-foreground\" />\n      <p className=\"text-sm text-muted-foreground\">Error loading data</p>\n      <Button variant=\"outline\" onClick={() => refetch()}>\n        {t.dashboard.error.retry}\n      </Button>\n    </CardContent>\n  </Card>\n) : null}\n```\n\n## Internationalization\n\nThe application uses a translation system (likely next-intl) with keys structured by page:\n\n| Namespace | Usage |\n|-----------|-------|\n| `landing` | Landing page content |\n| `authLayout` | Auth page headers/footers |\n| `dashboard` | Dashboard labels and messages |\n| `admin` | Admin page content |\n| `tokenManager` | Token management strings |\n| `projects` | Project page content |\n\n## Security Considerations\n\n### Route Protection\n\nAll sensitive routes check authentication before rendering:\n\n```typescript\n// Pattern used in all protected pages\nconst user = await getCurrentUser();\nif (!user) {\n  redirect(\"/login\");\n}\n```\n\n### Role-Based Access\n\nAdmin routes check for admin role:\n\n```typescript\nif (user.role !== \"admin\") {\n  redirect(\"/dashboard\");\n}\n```\n\n### Token Handling\n\n- Tokens are transmitted via HTTP-only cookies or Authorization headers\n- API keys are never exposed in client-side code\n- Install codes are single-use with 10-minute expiration\n\n## Related Documentation\n\n- [API Backend Documentation](../api/overview)\n- [Authentication System](../auth/overview)\n- [Design System Reference](./design-system)\n\n---\n\n<a id='workspace-ui'></a>\n\n## Workspace UI & Team Features\n\n### 相关页面\n\n相关主题：[Web Dashboard](#web-dashboard), [Curator Pipeline](#curator-pipeline)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [web/app/projects/page.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/app/projects/page.tsx)\n- [web/app/teams/page.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/app/teams/page.tsx)\n- [web/components/ProjectSessionsPanel.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/components/ProjectSessionsPanel.tsx)\n- [web/components/DashboardSummaryPanels.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/components/DashboardSummaryPanels.tsx)\n- [web/components/VaultNoteDetail.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/components/VaultNoteDetail.tsx)\n- [web/components/ProjectKnacksPanel.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/components/ProjectKnacksPanel.tsx)\n- [web/app/memory/page.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/app/memory/page.tsx)\n- [web/components/TokenManager.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/components/TokenManager.tsx)\n</details>\n\n# Workspace UI & Team Features\n\n## Overview\n\nThe Workspace UI & Team Features module in piLoci provides a comprehensive interface for managing projects, teams, and collaborative memory curation. This system enables users to organize AI-assisted memory sessions into project-based workspaces, view memory graphs, manage vault notes, and collaborate with team members through shared access tokens and session tracking.\n\nThe workspace architecture follows a project-scoped model where memories are isolated per project, allowing both individual users and teams to maintain separate knowledge bases while benefiting from shared curated content.\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    A[User Dashboard] --> B[Project Workspace]\n    A --> C[Team Management]\n    B --> D[Memory Graph Panel]\n    B --> E[Vault Notes]\n    B --> F[Session Sessions]\n    C --> G[Token Manager]\n    C --> H[Team Members]\n    F --> I[Transcript Viewer]\n    D --> J[Memory Tags]\n    E --> K[Note Links]\n```\n\n## Core Components\n\n### Project Workspace (`web/app/projects/page.tsx`)\n\nThe project workspace serves as the central hub for managing project-specific memories and settings. It provides:\n\n- Project listing with slug-based navigation\n- Workspace view with notes and relationships per project\n- Session history and memory extraction metrics\n\n**Key Features:**\n- Slug-based project routing (`/projects/?slug={slug}`)\n- Integration with `ProjectListView.tsx` for listing projects\n- Dashboard summary panels for quick metrics\n\n资料来源：[web/app/projects/page.tsx]()\n\n### Team Management (`web/app/teams/page.tsx`)\n\nThe team page enables users to manage collaborative workspaces and invite team members. Team features include:\n\n- Team member listing with roles and permissions\n- Shared project access control\n- Token-based client installation for team members\n\n资料来源：[web/app/teams/page.tsx]()\n\n## Session Management\n\n### Project Sessions Panel (`web/components/ProjectSessionsPanel.tsx`)\n\nThe `ProjectSessionsPanel` displays historical AI client sessions within a project context.\n\n**Component Structure:**\n\n```tsx\n<div className=\"flex flex-col gap-3\">\n  <Card>\n    <CardHeader className=\"pb-2\">\n      <div className=\"flex items-center justify-between\">\n        {/* Session header */}\n      </div>\n    </CardHeader>\n    <CardContent>\n      {/* Expandable transcript viewer */}\n    </CardContent>\n  </Card>\n</div>\n```\n\n**Session Display Elements:**\n\n| Element | Description |\n|---------|-------------|\n| Client Badge | Shows client type (e.g., Claude Desktop, Claude Code, OpenCode) |\n| Status | Processing status with timestamps |\n| Memory Count | Extracted memories count or pending indicator |\n| Error Display | Session errors in red text |\n| Transcript | Expandable transcript viewer |\n\n**Session Metadata Display:**\n\n```tsx\n<div className=\"flex flex-wrap items-center gap-1.5 text-[11px] text-muted-foreground\">\n  <Badge variant=\"outline\" className=\"text-[10px]\">{s.client}</Badge>\n  <span>{meta}</span>\n  <span>·</span>\n  <span>{status}</span>\n  <span>·</span>\n  <span>{fmt(s.created_at)}</span>\n</div>\n```\n\n**Transcript Expansion:**\n- Toggle button with chevron icons (up/down)\n- `TranscriptViewer` component renders full session transcript\n- State management via `isExp` boolean mapped to `ingest_id`\n\n资料来源：[web/components/ProjectSessionsPanel.tsx:1-60]()\n\n### Dashboard Summary Panels (`web/components/DashboardSummaryPanels.tsx`)\n\nThe dashboard provides aggregated views of project activity across all workspaces.\n\n**Panel Types:**\n\n| Panel | Icon | Content |\n|-------|------|---------|\n| Recent Sessions | FileText | Last processed sessions with memory counts |\n| Top Tags | Sparkles | Most used memory tags with usage frequency |\n| Project Stats | Varies | Metrics per project |\n\n**Recent Sessions Entry:**\n```tsx\n<li className=\"flex flex-wrap items-center justify-between gap-2 py-2 text-xs\">\n  <div className=\"flex min-w-0 items-center gap-2\">\n    <Link href={`/projects/?slug=${s.project_slug}`}>\n      {s.project_name}\n    </Link>\n    <span className=\"text-muted-foreground\">\n      {s.processed_at\n        ? summary.sessionMemories.replace(\"{count}\", String(s.memories_extracted))\n        : summary.sessionPending}\n    </span>\n  </div>\n  <span className=\"text-muted-foreground\">{timeFmt(s.created_at)}</span>\n</li>\n```\n\n**Tag Display with Pager:**\n```tsx\n<div className=\"flex flex-wrap gap-1.5\">\n  {tagPager.slice.map((tag) => (\n    <Badge key={tag.tag} variant=\"secondary\" className=\"break-all\">\n      #{tag.tag} <span className=\"ms-1 opacity-60 tabular-nums\">×{tag.count}</span>\n    </Badge>\n  ))}\n</div>\n```\n\n资料来源：[web/components/DashboardSummaryPanels.tsx:1-80]()\n\n## Memory Visualization\n\n### Memory Graph Panel\n\nThe Memory Graph Panel provides a visual representation of memory relationships within a project. Based on the design guidelines, future graph UI should:\n\n- Keep current landing preview dependency-free\n- Prefer **React Flow** for polished interactive curated-memory graphs\n- Reserve **Sigma.js/WebGL** for large workspace graphs if React Flow hits node-count limits\n\n资料来源：[MEMORY.md]()\n\n## Vault Notes System\n\n### Vault Note Detail (`web/components/VaultNoteDetail.tsx`)\n\nThe vault notes system displays individual memories with their metadata, tags, and inter-note relationships.\n\n**Note Display Structure:**\n\n```tsx\n<div className=\"space-y-3\">\n  {/* Header with title */}\n  <div>\n    <h2 className=\"text-xl font-semibold\">{note.title}</h2>\n    {note.tags?.length > 0 && (\n      <div className=\"flex flex-wrap gap-1.5 mt-2\">\n        {/* Tag badges */}\n      </div>\n    )}\n  </div>\n  \n  {/* Path display */}\n  <div className=\"break-all rounded-md bg-muted px-3 py-2 font-mono text-xs\">\n    {note.path}\n  </div>\n  \n  {/* Content */}\n  <pre className=\"whitespace-pre-wrap break-all\">\n    {note.markdown ?? note.excerpt}\n  </pre>\n  \n  {/* Linked notes */}\n  {note.links.length > 0 && <LinkedNotesSection />}\n</div>\n```\n\n**Note Metadata Fields:**\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `title` | string | Note title |\n| `path` | string | File system path |\n| `markdown` | string | Full markdown content |\n| `excerpt` | string | Short preview text |\n| `tags` | string[] | Associated tags |\n| `links` | string[] | Related note paths |\n\n**Linked Notes Section:**\n```tsx\n<Separator className=\"my-4\" />\n<div>\n  <p className=\"mb-2 text-sm font-medium text-muted-foreground\">\n    {t.vaultNote.linkedNotes}\n  </p>\n  <div className=\"flex flex-wrap gap-1.5\">\n    {note.links.map((link) => (\n      <Badge key={link} variant=\"outline\">{link}</Badge>\n    ))}\n  </div>\n</div>\n```\n\n资料来源：[web/components/VaultNoteDetail.tsx:1-50]()\n\n### Obsidian Export\n\nThe workspace system supports export to Obsidian vaults:\n\n```bash\ncurl -OJ http://localhost:8314/api/vault/my-project/export\n```\n\n**Export Process:**\n1. Fetch workspace data from `/api/projects/slug/{slug}/workspace`\n2. Create project directory structure in `~/.config/piloci/projects/slug/{slug}/workspace`\n3. Write each `workspace.notes[].markdown` to corresponding `workspace.notes[].path`\n4. Open directory as Obsidian vault or sync to existing vault\n\n资料来源：[README.md](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n\n## Team Collaboration\n\n### Token Manager (`web/components/TokenManager.tsx`)\n\nThe Token Manager provides a UI for generating and managing API tokens for team members.\n\n**Supported Client Types:**\n\n| Client | Config File | Features |\n|--------|-------------|----------|\n| Claude Desktop | `~/Library/Application Support/Claude/claude_desktop_config.json` | MCP server + hooks |\n| Claude Code | `~/.claude.json` / `.mcp.json` | MCP server + auto-capture hooks |\n| OpenCode | `opencode.json` | MCP server only |\n\n**Token Installation Status:**\n```tsx\n{token.installed_at ? (\n  <span className=\"text-[11px] text-muted-foreground\">\n    {t.tokenManager.installedOn} {formatDate(token.installed_at)}\n    {token.client_kinds && token.client_kinds.length > 0 && (\n      <> · {token.client_kinds.join(\" + \")}</>\n    )}\n    {token.hostname && <> · {token.hostname}</>}\n  </span>\n) : (\n  <span className=\"text-[11px] text-muted-foreground/70\">\n    {t.tokenManager.notInstalled}\n  </span>\n)}\n```\n\n**Token Scope Badge:**\n```tsx\n<Badge variant={token.scope === \"user\" ? \"default\" : \"secondary\"}>\n  {token.scope}\n</Badge>\n```\n\n**Installation Methods:**\n\n1. **CLI Installation:**\n   ```bash\n   piloci login\n   piloci install\n   ```\n\n2. **One-line Bash:**\n   ```bash\n   curl -sSL https://piloci.example.com/install/<install_code> | bash\n   ```\n\n3. **Manual Hook Setup:**\n   ```bash\n   # Step 1: Install hook\n   piloci hook install\n   \n   # Step 2: Configure client\n   # Copy generated JSON to client config file\n   ```\n\n资料来源：[web/components/TokenManager.tsx:1-100]()\n\n### Client-Side Setup\n\n**What the Connection Does:**\n\n- Records token + ingest/analyze URL to `~/.config/piloci/config.json` (mode 0600)\n- **Claude Code**: Registers MCP server in `~/.claude.json` with `memory`/`recall`/`recommend` tools, plus auto-capture hooks in `~/.claude/settings.json`\n- **OpenCode**: Registers MCP server in `~/.config/opencode/opencode.json`\n\n**Hook Behavior by Client:**\n\n| Client | SessionStart Hook | SessionStop Hook |\n|--------|-------------------|------------------|\n| Claude Code | Catch-up batch retrieve | Live push each turn |\n| OpenCode | N/A (no hook mechanism) | N/A |\n\n资料来源：[README.ko.md](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n\n## Project Management\n\n### Project Knacks Panel (`web/components/ProjectKnacksPanel.tsx`)\n\nThe Project Knacks Panel displays project-specific insights and instinct metrics.\n\n**Instinct Display:**\n```tsx\n<div className=\"flex items-center gap-2\">\n  <Badge variant=\"outline\" className=\"text-[10px]\">\n    {i.domain}\n  </Badge>\n  <span className=\"tabular-nums\">×{i.instinct_count}</span>\n</div>\n```\n\n资料来源：[web/components/ProjectKnacksPanel.tsx]()\n\n### Distillation Settings (`web/components/DistillationSettingsPanel.tsx`)\n\nProject-level settings control memory processing behavior:\n\n| Setting | Type | Description |\n|---------|------|-------------|\n| Temperature Ceiling | °C | Worker stops when SoC temp exceeds threshold |\n| Load Ceiling | float | Worker stops when load avg exceeds threshold |\n| Overflow Limit | number | Optional external bypass cap |\n\n资料来源：[web/components/DistillationSettingsPanel.tsx:1-60]()\n\n## API Integration\n\n### Memory API\n\nThe backend exposes project-scoped memory endpoints:\n\n**Endpoint:** `POST /api/memories`\n\n**Features:**\n- Uses existing embed/store pipeline\n- Project-scoped isolation\n- Memory extraction from session transcripts\n\n资料来源：[MEMORY.md]()\n\n### Workspace Export API\n\n**Endpoint:** `GET /api/projects/slug/{slug}/workspace`\n\nReturns workspace data including notes, paths, and relationships for Obsidian export.\n\n## Usage Scenarios\n\n### Scenario A — Team Project Memory Hub\n\nA small team sets up one piLoci instance on shared hardware. Each member creates an account, joins shared projects, and stores memories via MCP tools. Project isolation keeps unrelated work separate while everyone benefits from the shared knowledge base.\n\n### Scenario B — Multi-Project Workspace\n\nA solo developer or researcher runs several projects (thesis research, side project, client work) on one piLoci. Each project's memories stay isolated, and the workspace viewer shows notes and relationships per project.\n\n### Scenario C — Obsidian Export\n\nGenerate workspace notes and export to an Obsidian vault via simple API call for teams who want to curate knowledge in Obsidian after collection.\n\n## Page Design Patterns\n\nFollowing the piLoci design harness guidelines:\n\n```tsx\n<AppShell>\n  <div className=\"pi-page\">\n    <section className=\"pi-page-hero\">\n      <p className=\"pi-eyebrow\">Area label</p>\n      <h1 className=\"pi-title mt-2\">Page title</h1>\n      <p className=\"pi-subtitle\">One sentence explaining the page.</p>\n    </section>\n\n    <section className=\"grid gap-3 sm:grid-cols-3\">\n      <div className=\"pi-metric-card\">...</div>\n    </section>\n\n    <section className=\"pi-panel p-3\">...</section>\n  </div>\n</AppShell>\n```\n\n**Design Classes:**\n\n| Class | Usage |\n|-------|-------|\n| `pi-page` | Main page container |\n| `pi-page-hero` | Hero section with title and subtitle |\n| `pi-eyebrow` | Small label above title |\n| `pi-title` | Page title (H1) |\n| `pi-subtitle` | Descriptive subtitle |\n| `pi-metric-card` | Metric display cards |\n| `pi-panel` | Content panels with consistent styling |\n\n资料来源：[web/DESIGN-HARNESS.md](https://github.com/jshsakura/oc-piloci/blob/main/web/DESIGN-HARNESS.md)\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：jshsakura/oc-piloci\n\n摘要：发现 33 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：安装坑 - 失败模式：installation: Release v0.3.61。\n\n## 1. 安装坑 · 失败模式：installation: Release v0.3.61\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.61\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.61\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.61. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_238385c7d11f6862a1b9d0c024a94181 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.61 | Release v0.3.61\n\n## 2. 安装坑 · 失败模式：installation: Release v0.3.62\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.62\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.62\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.62. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_115c2527b334fad79621b999d3e94857 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.62 | Release v0.3.62\n\n## 3. 安装坑 · 失败模式：installation: Release v0.3.63\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.63\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.63\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.63. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_348782b397ba2bb56859e630ea890c99 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.63 | Release v0.3.63\n\n## 4. 安装坑 · 失败模式：installation: Release v0.3.64\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.64\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.64\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.64. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_a5608f313037217768976fadbcbd00e3 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.64 | Release v0.3.64\n\n## 5. 安装坑 · 失败模式：installation: Release v0.3.65\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.65\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.65\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.65. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_593467b90b436b99ecac227152d65f93 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.65 | Release v0.3.65\n\n## 6. 安装坑 · 失败模式：installation: Release v0.3.66\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.66\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.66\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.66. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_41cea4cedb6fe85b101b1ee1e744a2a2 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.66 | Release v0.3.66\n\n## 7. 安装坑 · 失败模式：installation: Release v0.3.67\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.67\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.67\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.67. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_51ad1a6fbbb3b6c3fdc1be72bcfae7ea | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.67 | Release v0.3.67\n\n## 8. 安装坑 · 失败模式：installation: Release v0.3.68\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.68\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.68\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.68. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_7bc0641dd202d881746e1010d1b03fe5 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.68 | Release v0.3.68\n\n## 9. 安装坑 · 失败模式：installation: Release v0.3.69\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.69\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.69\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.69. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_ba1666889342a143a76dda2fa013ddf2 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.69 | Release v0.3.69\n\n## 10. 安装坑 · 失败模式：installation: Release v0.3.70\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.70\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.70\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.70. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_18504a4306cc5d44261e6d0f5ec47f54 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.70 | Release v0.3.70\n\n## 11. 安装坑 · 失败模式：installation: Release v0.3.71\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.71\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.71\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.71. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_4f40f1505195306061984312ceafb8d8 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.71 | Release v0.3.71\n\n## 12. 安装坑 · 失败模式：installation: Release v0.3.72\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.72\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.72\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.72. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_a62aef6e3f8ef8401a1d0bb3ce5d66d5 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.72 | Release v0.3.72\n\n## 13. 安装坑 · 失败模式：installation: Release v0.3.73\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.73\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.73\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.73. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_402be624902b0ff4a70763241e96f92a | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.73 | Release v0.3.73\n\n## 14. 安装坑 · 失败模式：installation: Release v0.3.74\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.74\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.74\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.74. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_f1c1782e6dc53172212d524d1e194b8f | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.74 | Release v0.3.74\n\n## 15. 安装坑 · 失败模式：installation: Release v0.3.75\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.75\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.75\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.75. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_65320a1ebb2900791f1e9b16cbf8e8d6 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.75 | Release v0.3.75\n\n## 16. 安装坑 · 失败模式：installation: Release v0.3.76\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.76\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.76\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.76. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_78ad7e0a2110bee066ed708a51554c0d | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.76 | Release v0.3.76\n\n## 17. 安装坑 · 来源证据：Release v0.3.15\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.15\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_ab726a10491d4c14b7fa95fd35beee64 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.15 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 18. 安装坑 · 来源证据：Release v0.3.16\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.16\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_bc556664008b404db3fc774023736dcb | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.16 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 19. 安装坑 · 来源证据：Release v0.3.17\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.17\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_013d47bb794f4f13b2f8e2a5859cdabf | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.17 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 20. 安装坑 · 来源证据：Release v0.3.22\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.22\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_4bfd96a53e7e4d859637f79a8ee350d1 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.22 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 21. 安装坑 · 来源证据：Release v0.3.23\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.23\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_38baea4290d648a887a4c7575a3c8c55 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.23 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 22. 安装坑 · 来源证据：Release v0.3.24\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.24\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_654bcb552e094dd18bcc59cfdc2a83b5 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.24 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 23. 安装坑 · 来源证据：Release v0.3.25\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.25\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_e2f6528bce8040c0bab4d074214b33c5 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.25 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 24. 安装坑 · 来源证据：Release v0.3.26\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.26\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_f358a19a360f476bbd41bb4e35bca86e | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.26 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 25. 安装坑 · 来源证据：Release v0.3.27\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.27\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_973b50ab39634ba4af49b7df022af9a1 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.27 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 26. 安装坑 · 来源证据：Release v0.3.28\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.28\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_ca63e0beff7c4da8844cdea3d52415b6 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.28 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 27. 配置坑 · 可能修改宿主 AI 配置\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- 证据：capability.host_targets | github_repo:1219455965 | https://github.com/jshsakura/oc-piloci | host_targets=mcp_host, claude\n\n## 28. 能力坑 · 能力判断依赖假设\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:1219455965 | https://github.com/jshsakura/oc-piloci | README/documentation is current enough for a first validation pass.\n\n## 29. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:1219455965 | https://github.com/jshsakura/oc-piloci | last_activity_observed missing\n\n## 30. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:1219455965 | https://github.com/jshsakura/oc-piloci | no_demo; severity=medium\n\n## 31. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:1219455965 | https://github.com/jshsakura/oc-piloci | no_demo; severity=medium\n\n## 32. 维护坑 · 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:1219455965 | https://github.com/jshsakura/oc-piloci | issue_or_pr_quality=unknown\n\n## 33. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:1219455965 | https://github.com/jshsakura/oc-piloci | release_recency=unknown\n\n<!-- canonical_name: jshsakura/oc-piloci; human_manual_source: deepwiki_human_wiki -->\n",
      "markdown_key": "oc-piloci",
      "pages": "draft",
      "source_refs": [
        {
          "evidence_id": "github_repo:1219455965",
          "kind": "repo",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/jshsakura/oc-piloci"
        },
        {
          "evidence_id": "art_bd304ff09145408a83456c9e5eb30999",
          "kind": "docs",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/jshsakura/oc-piloci#readme"
        }
      ],
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "oc-piloci 说明书",
      "toc": [
        "https://github.com/jshsakura/oc-piloci 项目说明书",
        "目录",
        "Introduction to piLoci",
        "Overview",
        "Architecture",
        "Client Connection Flow",
        "CLI Commands",
        "Plugin Installation Structure",
        "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": "5631c42c22f1d8b2870af00c86c9dc5fbd44f59a",
    "repo_inspection_error": null,
    "repo_inspection_files": [
      "pyproject.toml",
      "Dockerfile",
      "README.md",
      "docker-compose.yml",
      "uv.lock",
      "docs/index.md",
      "docs/ADR-001-storage-isolation.md",
      "docs/WEB_BUILD.md",
      "docs/ADR-014-lancedb-backend.md",
      "src/piloci/version.py",
      "src/piloci/cli_ingest.py",
      "src/piloci/cli.py",
      "src/piloci/installer.py",
      "src/piloci/profiling_baseline.py",
      "src/piloci/llm.py",
      "src/piloci/main.py",
      "src/piloci/chat.py",
      "src/piloci/__init__.py",
      "src/piloci/config.py",
      "src/piloci/__main__.py",
      "src/piloci/api/static.py",
      "src/piloci/api/distillation_routes.py",
      "src/piloci/api/security.py",
      "src/piloci/api/data_portability.py",
      "src/piloci/api/team_routes.py",
      "src/piloci/api/routes.py",
      "src/piloci/api/v1.py",
      "src/piloci/api/__init__.py",
      "src/piloci/api/ratelimit.py",
      "src/piloci/api/audit.py",
      "src/piloci/mcp/sse.py",
      "src/piloci/mcp/server.py",
      "src/piloci/mcp/__init__.py",
      "src/piloci/mcp/streamable_http.py",
      "src/piloci/mcp/session_state.py",
      "src/piloci/notify/telegram.py",
      "src/piloci/notify/telegram_bot.py",
      "src/piloci/notify/health.py",
      "src/piloci/notify/__init__.py",
      "src/piloci/tools/instinct_tools.py"
    ],
    "repo_inspection_verified": true,
    "review_reasons": [],
    "tag_count_ok": true,
    "unsupported_claims": []
  },
  "schema_version": "0.1",
  "user_assets": {
    "ai_context_pack": {
      "asset_id": "ai_context_pack",
      "filename": "AI_CONTEXT_PACK.md",
      "markdown": "# @piloci/sdk - Doramagic AI Context Pack\n\n> 定位：安装前体验与判断资产。它帮助宿主 AI 有一个好的开始，但不代表已经安装、执行或验证目标项目。\n\n## 充分原则\n\n- **充分原则，不是压缩原则**：AI Context Pack 应该充分到让宿主 AI 在开工前理解项目价值、能力边界、使用入口、风险和证据来源；它可以分层组织，但不以最短摘要为目标。\n- **压缩策略**：只压缩噪声和重复内容，不压缩会影响判断和开工质量的上下文。\n\n## 给宿主 AI 的使用方式\n\n你正在读取 Doramagic 为 @piloci/sdk 编译的 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- `curl -OJ http://localhost:8314/api/vault/my-project/export` 证据：`README.md` Claim：`clm_0003` supported 0.86\n- `curl -sS http://localhost:8314/api/projects/slug/my-project/workspace` 证据：`README.md` Claim：`clm_0004` supported 0.86\n- `curl -fsSLo docker-compose.yml https://raw.githubusercontent.com/jshsakura/oc-piloci/main/docker-compose.yml` 证据：`README.md` Claim：`clm_0005` supported 0.86\n- `curl -fsSLo .env.example https://raw.githubusercontent.com/jshsakura/oc-piloci/main/.env.example` 证据：`README.md` Claim：`clm_0006` supported 0.86\n- `curl -fsSLo deploy/setup.sh https://raw.githubusercontent.com/jshsakura/oc-piloci/main/deploy/setup.sh` 证据：`README.md` Claim：`clm_0007` supported 0.86\n- `git clone https://github.com/jshsakura/oc-piloci.git` 证据：`README.md` Claim：`clm_0008` supported 0.86\n- `pip install -U oc-piloci && python -m piloci setup --server https://piloci.example.com` 证据：`README.md` Claim：`clm_0009` supported 0.86\n- `curl -sSL https://piloci.example.com/install/<install_code> | bash` 证据：`README.md` Claim：`clm_0010` supported 0.86\n\n## 继续前判断卡\n\n- **当前建议**：需要管理员/安全审批\n- **为什么**：继续前可能涉及密钥、账号、外部服务或敏感上下文，建议先经过管理员或安全审批。\n\n### 30 秒判断\n\n- **现在怎么做**：需要管理员/安全审批\n- **最小安全下一步**：先跑 Prompt Preview；若涉及凭证或企业环境，先审批再试装\n- **先别相信**：工具权限边界不能在安装前相信。\n- **继续会触碰**：命令执行、宿主 AI 配置、本地环境或项目文件\n\n### 现在可以相信\n\n- **适合人群线索：正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`README.md` Claim：`clm_0002` supported 0.86\n- **能力存在：命令行启动或安装流程**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`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）：MCP/tool 类项目通常会触碰文件、网络、浏览器或外部 API，必须真实检查权限和日志。\n- **真实输出质量不能在安装前相信。**（unverified）：Prompt Preview 只能展示引导方式，不能证明真实项目中的结果质量。\n- **宿主 AI 版本兼容性不能在安装前相信。**（unverified）：Claude、Cursor、Codex、Gemini 等宿主加载规则和版本差异必须在真实环境验证。\n- **不会污染现有宿主 AI 行为，不能直接相信。**（inferred）：Skill、plugin、AGENTS/CLAUDE/GEMINI 指令可能改变宿主 AI 的默认行为。 证据：`CLAUDE.md`\n- **可安全回滚不能默认相信。**（unverified）：除非项目明确提供卸载和恢复说明，否则必须先在隔离环境验证。\n- **真实安装后是否与用户当前宿主 AI 版本兼容？**（unverified）：兼容性只能通过实际宿主环境验证。\n- **项目输出质量是否满足用户具体任务？**（unverified）：安装前预览只能展示流程和边界，不能替代真实评测。\n- **安装命令是否需要网络、权限或全局写入？**（unverified）：这影响企业环境和个人环境的安装风险。 证据：`README.md`\n\n### 继续会触碰什么\n\n- **命令执行**：包管理器、网络下载、本地插件目录、项目配置或用户主目录。 原因：运行第一条命令就可能产生环境改动；必须先判断是否值得跑。 证据：`README.md`\n- **宿主 AI 配置**：Claude/Codex/Cursor/Gemini/OpenCode 等宿主的 plugin、Skill 或规则加载配置。 原因：宿主配置会改变 AI 后续工作方式，可能和用户已有规则冲突。 证据：`CLAUDE.md`\n- **本地环境或项目文件**：安装结果、插件缓存、项目配置或本地依赖目录。 原因：安装前无法证明写入范围和回滚方式，需要隔离验证。 证据：`README.md`\n- **环境变量 / API Key**：项目入口文档明确出现 API key、token、secret 或账号凭证配置。 原因：如果真实安装需要凭证，应先使用测试凭证并经过权限/合规判断。 证据：`MEMORY.md`, `PLAN.md`, `README.ko.md`, `README.md` 等\n- **宿主 AI 上下文**：AI Context Pack、Prompt Preview、Skill 路由、风险规则和项目事实。 原因：导入上下文会影响宿主 AI 后续判断，必须避免把未验证项包装成事实。\n\n### 最小安全下一步\n\n- **先跑 Prompt Preview**：用安装前交互式试用判断工作方式是否匹配，不需要授权或改环境。（适用：任何项目都适用，尤其是输出质量未知时。）\n- **只在隔离目录或测试账号试装**：避免安装命令污染主力宿主 AI、真实项目或用户主目录。（适用：存在命令执行、插件配置或本地写入线索时。）\n- **先备份宿主 AI 配置**：Skill、plugin、规则文件可能改变 Claude/Cursor/Codex 的默认行为。（适用：存在插件 manifest、Skill 或宿主规则入口时。）\n- **不要使用真实生产凭证**：环境变量/API key 一旦进入宿主或工具链，可能产生账号和合规风险。（适用：出现 API、TOKEN、KEY、SECRET 等环境线索时。）\n- **安装后只验证一个最小任务**：先验证加载、兼容、输出质量和回滚，再决定是否深用。（适用：准备从试用进入真实工作流时。）\n\n### 退出方式\n\n- **保留安装前状态**：记录原始宿主配置和项目状态，后续才能判断是否可恢复。\n- **准备移除宿主 plugin / Skill / 规则入口**：如果试装后行为异常，可以把宿主 AI 恢复到试装前状态。\n- **记录安装命令和写入路径**：没有明确卸载说明时，至少要知道哪些目录或配置需要手动清理。\n- **准备撤销测试 API key 或 token**：测试凭证泄露或误用时，可以快速止损。\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_0011` inferred 0.45\n- **命令执行会修改本地环境**：安装命令可能写入用户主目录、宿主插件目录或项目配置。 处理方式：先在隔离环境或测试账号中运行。 证据：`README.md` Claim：`clm_0012` 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- 文件总数：304\n- 重要文件覆盖：40/304\n- 证据索引条目：44\n- 角色 / Skill 条目：13\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请基于 @piloci/sdk 的 AI Context Pack，先问我 3 个必要问题，然后判断它是否适合我的任务。回答必须包含：适合谁、能做什么、不能做什么、是否值得安装、证据来自哪里。所有项目事实必须引用 evidence_refs、source_paths 或 claim_id。\n```\n\n### 安装前体验\n\n- 目标：让用户在安装前感受核心工作流，同时避免把预览包装成真实能力或营销承诺。\n- 预期输出：一段带边界标签的体验剧本、安装后验证清单和谨慎建议；不含真实运行承诺或强营销表述。\n\n```text\n请把 @piloci/sdk 当作安装前体验资产，而不是已安装工具或真实运行环境。\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请基于 @piloci/sdk 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。\n```\n\n\n## 角色 / Skill 索引\n\n- 共索引 13 个角色 / Skill / 项目文档条目。\n\n- **piLoci — Development Rules**（project_doc）：구현 세션 시작 시: 1. PLAN.md 읽기 → 현재 상태 체크박스 확인 2. 다음 미완료 항목부터 시작 3. 작업 완료 시 체크박스 업데이트 + MEMORY.md 갱신 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CLAUDE.md`\n- **piLoci**（project_doc）：! Website https://img.shields.io/badge/website-piloci.jshsakura.com-blue https://piloci.jshsakura.com/ ! 한국어 https://img.shields.io/badge/문서-한국어-green ./README.ko.md 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`README.md`\n- **@piloci/sdk**（project_doc）：TypeScript SDK for the piLoci https://github.com/Sisyphus-Junior/piloci self-hosted memory server. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`clients/js/README.md`\n- **piloci-client**（project_doc）：Python SDK for piLoci https://github.com/Sisyphus-Junior/piloci — a self-hosted memory service for LLM assistants. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`clients/python/README.md`\n- **ADR-001: Storage Isolation Model**（project_doc）：Accepted. Updated for the LanceDB backend. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/ADR-001-storage-isolation.md`\n- **ADR-014: LanceDB As The Embedded Vector Backend**（project_doc）：ADR-014: LanceDB As The Embedded Vector Backend 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/ADR-014-lancedb-backend.md`\n- **Web Build**（project_doc）：docker-compose.dev.yml 에서 web 빌드를 Python 서비스 시작 전에 자동 실행하려면 아래처럼 profiles 를 활용하거나 별도 서비스를 추가합니다. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/WEB_BUILD.md`\n- **piLoci Documentation**（project_doc）：Live site : piloci.jshsakura.com https://piloci.jshsakura.com/ 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/index.md`\n- **MEMORY**（project_doc）：- Closed the security/product hardening pass: added double-submit CSRF for cookie-authenticated unsafe requests, Redis-backed slowapi storage with broader route coverage, persisted Bearer-token revocation checks, stale session/user revalidation, MCP Streamable HTTP session-summary parity, LLM provider private-network URL rejection by default, and stricter LanceDB user/project/tag validation. - Surfaced the previousl… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`MEMORY.md`\n- **piLoci — 개발 계획서**（project_doc）：이 문서는 계획 세션 Opus 4.7 과 구현 세션 Sonnet 4.6 사이의 인수인계 문서입니다. 새 세션을 시작하면 이 문서부터 읽고 현재 상태 섹션을 확인하세요. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`PLAN.md`\n- **piLoci**（project_doc）：! Website https://img.shields.io/badge/website-piloci.jshsakura.com-blue https://piloci.jshsakura.com/ ! English https://img.shields.io/badge/docs-English-blue ./README.md 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`README.ko.md`\n- **Security Policy**（project_doc）：Reporting a Vulnerability 취약점 발견 시 GitHub Security Advisories private 로 신고. 공개 Issue 금지. 응답 SLA: 7일 이내 acknowledgement, 90일 이내 패치. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`SECURITY.md`\n- **piLoci Design Harness**（project_doc）：piLoci UI should feel like a calm memory infrastructure product: clear, spatial, low-noise, and trustworthy. Use the shared pi- classes in app/globals.css before inventing new page-level styling. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`web/DESIGN-HARNESS.md`\n\n## 证据索引\n\n- 共索引 44 条证据。\n\n- **piLoci — Development Rules**（documentation）：구현 세션 시작 시: 1. PLAN.md 읽기 → 현재 상태 체크박스 확인 2. 다음 미완료 항목부터 시작 3. 작업 완료 시 체크박스 업데이트 + MEMORY.md 갱신 证据：`CLAUDE.md`\n- **piLoci**（documentation）：! Website https://img.shields.io/badge/website-piloci.jshsakura.com-blue https://piloci.jshsakura.com/ ! 한국어 https://img.shields.io/badge/문서-한국어-green ./README.ko.md 证据：`README.md`\n- **@piloci/sdk**（documentation）：TypeScript SDK for the piLoci https://github.com/Sisyphus-Junior/piloci self-hosted memory server. 证据：`clients/js/README.md`\n- **piloci-client**（documentation）：Python SDK for piLoci https://github.com/Sisyphus-Junior/piloci — a self-hosted memory service for LLM assistants. 证据：`clients/python/README.md`\n- **Package**（package_manifest）：{ \"name\": \"piloci-web\", \"private\": true, \"version\": \"0.0.1\", \"scripts\": { \"dev\": \"next dev --turbopack\", \"build\": \"next build\", \"start\": \"next start\", \"lint\": \"next lint\", \"test\": \"vitest run\", \"test:watch\": \"vitest\", \"test:coverage\": \"vitest run --coverage\", \"e2e\": \"playwright test\" }, \"dependencies\": { \"@hookform/resolvers\": \"^5.0.1\", \"@radix-ui/react-accordion\": \"^1.2.3\", \"@radix-ui/react-alert-dialog\": \"^1.1.6\", \"@radix-ui/react-avatar\": \"^1.1.3\", \"@radix-ui/react-checkbox\": \"^1.1.4\", \"@radix-ui/react-dialog\": \"^1.1.6\", \"@radix-ui/react-dropdown-menu\": \"^2.1.6\", \"@radix-ui/react-label\": \"^2.1.2\", \"@radix-ui/react-popover\": \"^1.1.6\", \"@radix-ui/react-progress\": \"^1.1.2\", \"@radix-ui/react… 证据：`web/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@piloci/sdk\", \"version\": \"0.1.0\", \"description\": \"TypeScript SDK for the piLoci self-hosted memory server\", \"type\": \"module\", \"main\": \"./dist/index.cjs\", \"module\": \"./dist/index.js\", \"types\": \"./dist/index.d.ts\", \"exports\": { \".\": { \"import\": { \"types\": \"./dist/index.d.ts\", \"default\": \"./dist/index.js\" }, \"require\": { \"types\": \"./dist/index.d.cts\", \"default\": \"./dist/index.cjs\" } } }, \"files\": \"dist\", \"README.md\" , \"scripts\": { \"build\": \"tsup\", \"test\": \"vitest run\", \"test:watch\": \"vitest\", \"typecheck\": \"tsc --noEmit\" }, \"devDependencies\": { \"tsup\": \"^8.3.5\", \"typescript\": \"^5.7.3\", \"vitest\": \"^3.1.3\" }, \"engines\": { \"node\": \" =18.0.0\" }, \"license\": \"MIT\", \"keywords\": \"piloci\", \"m… 证据：`clients/js/package.json`\n- **License**（source_file）：Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files the \"Software\" , to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 证据：`LICENSE`\n- **ADR-001: Storage Isolation Model**（documentation）：Accepted. Updated for the LanceDB backend. 证据：`docs/ADR-001-storage-isolation.md`\n- **ADR-014: LanceDB As The Embedded Vector Backend**（documentation）：ADR-014: LanceDB As The Embedded Vector Backend 证据：`docs/ADR-014-lancedb-backend.md`\n- **Web Build**（documentation）：docker-compose.dev.yml 에서 web 빌드를 Python 서비스 시작 전에 자동 실행하려면 아래처럼 profiles 를 활용하거나 별도 서비스를 추가합니다. 证据：`docs/WEB_BUILD.md`\n- **piLoci Documentation**（documentation）：Live site : piloci.jshsakura.com https://piloci.jshsakura.com/ 证据：`docs/index.md`\n- **MEMORY**（documentation）：- Closed the security/product hardening pass: added double-submit CSRF for cookie-authenticated unsafe requests, Redis-backed slowapi storage with broader route coverage, persisted Bearer-token revocation checks, stale session/user revalidation, MCP Streamable HTTP session-summary parity, LLM provider private-network URL rejection by default, and stricter LanceDB user/project/tag validation. - Surfaced the previously API-only team feature in the web app: /teams is now in the app shell navigation and supports team creation, pending invite handling, member visibility, email invites, and shared team document create/update/delete flows through typed frontend API methods. - Added backend regress… 证据：`MEMORY.md`\n- **piLoci — 개발 계획서**（documentation）：이 문서는 계획 세션 Opus 4.7 과 구현 세션 Sonnet 4.6 사이의 인수인계 문서입니다. 새 세션을 시작하면 이 문서부터 읽고 현재 상태 섹션을 확인하세요. 证据：`PLAN.md`\n- **piLoci**（documentation）：! Website https://img.shields.io/badge/website-piloci.jshsakura.com-blue https://piloci.jshsakura.com/ ! English https://img.shields.io/badge/docs-English-blue ./README.md 证据：`README.ko.md`\n- **Security Policy**（documentation）：Reporting a Vulnerability 취약점 발견 시 GitHub Security Advisories private 로 신고. 공개 Issue 금지. 응답 SLA: 7일 이내 acknowledgement, 90일 이내 패치. 证据：`SECURITY.md`\n- **piLoci Design Harness**（documentation）：piLoci UI should feel like a calm memory infrastructure product: clear, spatial, low-noise, and trustworthy. Use the shared pi- classes in app/globals.css before inventing new page-level styling. 证据：`web/DESIGN-HARNESS.md`\n- **.Eslintrc**（structured_config）：{ \"extends\": \"next/core-web-vitals\", \"plugins\": \"@typescript-eslint\" , \"rules\": { \"@typescript-eslint/no-unused-vars\": \"warn\" } } 证据：`web/.eslintrc.json`\n- **Components**（structured_config）：{ \"$schema\": \"https://ui.shadcn.com/schema.json\", \"style\": \"new-york\", \"rsc\": true, \"tsx\": true, \"tailwind\": { \"config\": \"\", \"css\": \"app/globals.css\", \"baseColor\": \"neutral\", \"cssVariables\": true, \"prefix\": \"\" }, \"aliases\": { \"components\": \"@/components\", \"utils\": \"@/lib/utils\", \"ui\": \"@/components/ui\", \"lib\": \"@/lib\", \"hooks\": \"@/hooks\" }, \"iconLibrary\": \"lucide\" } 证据：`web/components.json`\n- **Tsconfig**（structured_config）：{ \"compilerOptions\": { \"target\": \"ES2017\", \"lib\": \"dom\", \"dom.iterable\", \"esnext\" , \"allowJs\": true, \"skipLibCheck\": true, \"strict\": true, \"noEmit\": true, \"esModuleInterop\": true, \"module\": \"esnext\", \"moduleResolution\": \"bundler\", \"resolveJsonModule\": true, \"isolatedModules\": true, \"jsx\": \"preserve\", \"incremental\": true, \"plugins\": { \"name\": \"next\" } , \"paths\": { \"@/ \": \"./ \" } }, \"include\": \"next-env.d.ts\", \" / .ts\", \" / .tsx\", \".next/types/ / .ts\" , \"exclude\": \"node modules\" } 证据：`web/tsconfig.json`\n- **Tsconfig**（structured_config）：{ \"compilerOptions\": { \"target\": \"ES2022\", \"module\": \"ESNext\", \"moduleResolution\": \"bundler\", \"strict\": true, \"declaration\": true, \"declarationMap\": true, \"sourceMap\": true, \"esModuleInterop\": true, \"skipLibCheck\": true, \"outDir\": \"./dist\", \"rootDir\": \"./src\", \"lib\": \"ES2022\", \"DOM\" }, \"include\": \"src/ / \" , \"exclude\": \"node modules\", \"dist\", \"test\" } 证据：`clients/js/tsconfig.json`\n- **.dockerignore**（source_file）：.env .env. .envrc secrets/ .git/ .gitignore .venv/ venv/ pycache / .pyc .egg-info/ dist/ build/ sdist/ wheels/ .pytest cache/ .mypy cache/ .ruff cache/ .pyre/ .pytype/ .tox/ .nox/ .hypothesis/ .dmypy.json htmlcov/ .coverage .coverage. tests/ docs/ deploy/ web/node modules/ web/.next/ web/out/ node modules/ .log data/ qdrant data/ redis data/ .fastembed cache/ .lance/ .ipynb checkpoints/ .idea/ .vscode/ .claude/ .sisyphus/ opencode.json PLAN.md CLAUDE.md MEMORY.md 证据：`.dockerignore`\n- **piLoci Environment Variables**（source_file）：piLoci Environment Variables Copy to .env and fill in values. Never commit .env. 证据：`.env.example`\n- **To get started with Dependabot version updates, you'll need to specify which**（source_file）：To get started with Dependabot version updates, you'll need to specify which package ecosystems to update and where the package manifests are located. Please see the documentation for all configuration options: https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file 证据：`.github/dependabot.yml`\n- **── Environment & Secrets ──────────────────────────**（source_file）：── Environment & Secrets ────────────────────────── .env .env. !.env.example .envrc secrets/ 证据：`.gitignore`\n- **.Mcp.Json**（source_file）：{ \"mcpServers\": { \"piloci\": { \"type\": \"http\", \"url\": \"https://piloci.example.com/mcp/http\", \"headers\": { \"Authorization\": \"Bearer \" } } } } 证据：`.mcp.json.example`\n- **Two-stage hook setup:**（source_file）：Two-stage hook setup: - pre-commit every git commit → formatters + lint, ~1-2s - pre-push every git push → pytest + vitest, ~30-60s Run once after editing this file so both hook types are installed: pre-commit install The default install hook types line below makes pre-commit install wire up both hook types in one shot. default install hook types: pre-commit, pre-push 证据：`.pre-commit-config.yaml`\n- **piLoci — Multi-stage Dockerfile ARM64 / Raspberry Pi 5**（source_file）：piLoci — Multi-stage Dockerfile ARM64 / Raspberry Pi 5 证据：`Dockerfile`\n- **─────────────────────────────────────────────────────────────────────────────**（source_file）：───────────────────────────────────────────────────────────────────────────── Stage 1: pnpm install + next build ───────────────────────────────────────────────────────────────────────────── FROM public.ecr.aws/docker/library/node:22-slim AS builder 证据：`Dockerfile.web`\n- **!/usr/bin/env bash**（source_file）：!/usr/bin/env bash ────────────────────────────────────────────────────────────── piLoci — First Deploy Setup Script Creates .env and fills in runtime secrets for production deployment. Usage: chmod +x deploy/setup.sh ./deploy/setup.sh Safe to re-run — keeps an existing .env untouched. ────────────────────────────────────────────────────────────── set -euo pipefail 证据：`deploy/setup.sh`\n- **── Dev proxy single external port ─────────────────────────**（source_file）：services: ── Dev proxy single external port ───────────────────────── nginx: image: nginx:alpine ports: - \"28314:80\" volumes: - ./deploy/nginx/dev.conf:/etc/nginx/conf.d/default.conf:ro extra hosts: - \"host.docker.internal:host-gateway\" reach native pnpm dev on host depends on: - piloci networks: piloci net restart: \"no\" 证据：`docker-compose.dev.yml`\n- **nginx: routes external port 28314 → native backend on host:8314**（source_file）：services: nginx: routes external port 28314 → native backend on host:8314 nginx: image: nginx:alpine ports: - \"28314:80\" volumes: - ./deploy/nginx/native.conf:/etc/nginx/conf.d/default.conf:ro extra hosts: - \"host.docker.internal:host-gateway\" depends on: - redis networks: piloci net restart: unless-stopped 证据：`docker-compose.native.yml`\n- **──────────────────────────────────────────────────────────────**（source_file）：────────────────────────────────────────────────────────────── piLoci — Production Docker Compose Quick start: 1. ./deploy/setup.sh generate .env with runtime secrets 2. docker compose pull 3. docker compose up -d Architecture: host:${PILOCI HOST PORT:-8314} → piloci:8314 ← redis:6379 └── SQLite + LanceDB on /data volume Reverse proxy Cloudflare Tunnel, nginx, Caddy, etc. is managed outside this compose file and should point at the published host port. ────────────────────────────────────────────────────────────── services: bootstrap: image: ${PILOCI IMAGE:-jshsakura/piloci:latest} restart: \"no\" read only: true user: \"1000:1000\" cap drop: ALL security opt: no-new-privileges:true tmpfs: - /t… 证据：`docker-compose.yml`\n- **Vector DB**（source_file）：build-system requires = \"hatchling\" build-backend = \"hatchling.build\" 证据：`pyproject.toml`\n- **!/usr/bin/env python3**（source_file）：!/usr/bin/env python3 \"\"\"piLoci launcher — kill existing and restart. 证据：`run.py`\n- **Ensure src/ is on the path when running as a script**（source_file）：import asyncio import sys from pathlib import Path 证据：`scripts/init-db.py`\n- **!/usr/bin/env bash**（source_file）：!/usr/bin/env bash piloci Stop hook — pushes the current session's transcript at end of turn. Reads token + URL from ~/.config/piloci/config.json no secrets in this file . This script is the canonical Stop hook served by /api/hook/stop-script and laid down at ~/.config/piloci/stop-hook.sh by the install flow. The copy kept in this repo exists for visibility — keep it in sync with the STOP HOOK SCRIPT constant in src/piloci/tools/install script.py . set -euo pipefail 证据：`scripts/piloci-stop-hook.sh`\n- **!/usr/bin/env bash**（source_file）：!/usr/bin/env bash Sync styleseed engine + linear skin into web/ set -e STYLESEED=\"/home/pi/app/jupyterLab/notebooks/styleseed\" WEB=\"$ dirname \"$0\" /../web\" 证据：`scripts/sync-styleseed.sh`\n- **Ensure every test session has valid secrets even when .env is absent CI .**（source_file）：import os from unittest.mock import AsyncMock 证据：`tests/conftest.py`\n- **Next Env.D**（source_file）：// NOTE: This file should not be edited // see https://nextjs.org/docs/app/api-reference/config/typescript for more information. 证据：`web/next-env.d.ts`\n- **Next.Config**（source_file）：import type { NextConfig } from \"next\"; 证据：`web/next.config.ts`\n- **Playwright.Config**（source_file）：import { defineConfig, devices } from \"@playwright/test\"; 证据：`web/playwright.config.ts`\n- **Postcss.Config**（source_file）：const config = { plugins: { \"@tailwindcss/postcss\": {}, }, }; export default config; 证据：`web/postcss.config.mjs`\n- **Vitest.Config**（source_file）：import { defineConfig } from \"vitest/config\"; import react from \"@vitejs/plugin-react\"; import path from \"path\"; 证据：`web/vitest.config.ts`\n- **Vitest.Setup**（source_file）：import \"@testing-library/jest-dom\"; 证据：`web/vitest.setup.ts`\n\n## 宿主 AI 必须遵守的规则\n\n- **把本资产当作开工前上下文，而不是运行环境。**：AI Context Pack 只包含证据化项目理解，不包含目标项目的可执行状态。 证据：`CLAUDE.md`, `README.md`, `clients/js/README.md`\n- **回答用户时区分可预览内容与必须安装后才能验证的内容。**：安装前体验的消费者价值来自降低误装和误判，而不是伪装成真实运行。 证据：`CLAUDE.md`, `README.md`, `clients/js/README.md`\n\n## 用户开工前应该回答的问题\n\n- 你准备在哪个宿主 AI 或本地环境中使用它？\n- 你只是想先体验工作流，还是准备真实安装？\n- 你最在意的是安装成本、输出质量、还是和现有规则的冲突？\n\n## 验收标准\n\n- 所有能力声明都能回指到 evidence_refs 中的文件路径。\n- AI_CONTEXT_PACK.md 没有把预览包装成真实运行。\n- 用户能在 3 分钟内看懂适合谁、能做什么、如何开始和风险边界。\n\n---\n\n## Doramagic Context Augmentation\n\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 piLoci**：importance `high`\n  - source_paths: README.md, PLAN.md, src/piloci/version.py\n- **Getting Started**：importance `high`\n  - source_paths: .env.example, docker-compose.yml, deploy/setup.sh, src/piloci/config.py\n- **System Architecture**：importance `high`\n  - source_paths: src/piloci/main.py, docker-compose.yml, src/piloci/db/session.py, src/piloci/storage/__init__.py\n- **Technology Stack**：importance `medium`\n  - source_paths: pyproject.toml, web/package.json, src/piloci/storage/lancedb_store.py, docs/ADR-014-lancedb-backend.md\n- **MCP Server Implementation**：importance `high`\n  - source_paths: src/piloci/mcp/server.py, src/piloci/mcp/streamable_http.py, src/piloci/mcp/sse.py, src/piloci/mcp/session_state.py, src/piloci/tools/memory_tools.py\n- **Authentication & Security**：importance `high`\n  - source_paths: src/piloci/auth/jwt_utils.py, src/piloci/auth/password.py, src/piloci/auth/totp.py, src/piloci/auth/oauth.py, src/piloci/auth/middleware.py\n- **API Routes**：importance `high`\n  - source_paths: src/piloci/api/routes.py, src/piloci/api/v1.py, src/piloci/api/team_routes.py, src/piloci/api/audit.py, src/piloci/api/data_portability.py\n- **Curator Pipeline**：importance `medium`\n  - source_paths: src/piloci/curator/__init__.py, src/piloci/curator/distillation_worker.py, src/piloci/curator/gemma.py, src/piloci/curator/extraction.py, src/piloci/curator/prefilter.py\n\n## Repo Inspection Evidence / 源码检查证据\n\n- repo_clone_verified: true\n- repo_inspection_verified: true\n- repo_commit: `5631c42c22f1d8b2870af00c86c9dc5fbd44f59a`\n- inspected_files: `pyproject.toml`, `Dockerfile`, `README.md`, `docker-compose.yml`, `uv.lock`, `docs/index.md`, `docs/ADR-001-storage-isolation.md`, `docs/WEB_BUILD.md`, `docs/ADR-014-lancedb-backend.md`, `src/piloci/version.py`, `src/piloci/cli_ingest.py`, `src/piloci/cli.py`, `src/piloci/installer.py`, `src/piloci/profiling_baseline.py`, `src/piloci/llm.py`, `src/piloci/main.py`, `src/piloci/chat.py`, `src/piloci/__init__.py`, `src/piloci/config.py`, `src/piloci/__main__.py`\n\n宿主 AI 硬性规则：\n- 没有 repo_clone_verified=true 时，不得声称已经读过源码。\n- 没有 repo_inspection_verified=true 时，不得把 README/docs/package 文件判断写成事实。\n- 没有 quick_start_verified=true 时，不得声称 Quick Start 已跑通。\n\n## Doramagic Pitfall Constraints / 踩坑约束\n\n这些规则来自 Doramagic 发现、验证或编译过程中的项目专属坑点。宿主 AI 必须把它们当作工作约束，而不是普通说明文字。\n\n### Constraint 1: 失败模式：installation: Release v0.3.61\n\n- Trigger: Developers should check this installation risk before relying on the project: Release v0.3.61\n- Host AI rule: Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.61. Context: Observed when using docker\n- Why it matters: Upgrade or migration may change expected behavior: Release v0.3.61\n- Evidence: failure_mode_cluster:github_release | fmev_238385c7d11f6862a1b9d0c024a94181 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.61 | Release v0.3.61\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 2: 失败模式：installation: Release v0.3.62\n\n- Trigger: Developers should check this installation risk before relying on the project: Release v0.3.62\n- Host AI rule: Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.62. Context: Observed when using docker\n- Why it matters: Upgrade or migration may change expected behavior: Release v0.3.62\n- Evidence: failure_mode_cluster:github_release | fmev_115c2527b334fad79621b999d3e94857 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.62 | Release v0.3.62\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 3: 失败模式：installation: Release v0.3.63\n\n- Trigger: Developers should check this installation risk before relying on the project: Release v0.3.63\n- Host AI rule: Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.63. Context: Observed when using docker\n- Why it matters: Upgrade or migration may change expected behavior: Release v0.3.63\n- Evidence: failure_mode_cluster:github_release | fmev_348782b397ba2bb56859e630ea890c99 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.63 | Release v0.3.63\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 4: 失败模式：installation: Release v0.3.64\n\n- Trigger: Developers should check this installation risk before relying on the project: Release v0.3.64\n- Host AI rule: Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.64. Context: Observed when using docker\n- Why it matters: Upgrade or migration may change expected behavior: Release v0.3.64\n- Evidence: failure_mode_cluster:github_release | fmev_a5608f313037217768976fadbcbd00e3 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.64 | Release v0.3.64\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 5: 失败模式：installation: Release v0.3.65\n\n- Trigger: Developers should check this installation risk before relying on the project: Release v0.3.65\n- Host AI rule: Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.65. Context: Observed when using docker\n- Why it matters: Upgrade or migration may change expected behavior: Release v0.3.65\n- Evidence: failure_mode_cluster:github_release | fmev_593467b90b436b99ecac227152d65f93 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.65 | Release v0.3.65\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 6: 失败模式：installation: Release v0.3.66\n\n- Trigger: Developers should check this installation risk before relying on the project: Release v0.3.66\n- Host AI rule: Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.66. Context: Observed when using docker\n- Why it matters: Upgrade or migration may change expected behavior: Release v0.3.66\n- Evidence: failure_mode_cluster:github_release | fmev_41cea4cedb6fe85b101b1ee1e744a2a2 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.66 | Release v0.3.66\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 7: 失败模式：installation: Release v0.3.67\n\n- Trigger: Developers should check this installation risk before relying on the project: Release v0.3.67\n- Host AI rule: Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.67. Context: Observed when using docker\n- Why it matters: Upgrade or migration may change expected behavior: Release v0.3.67\n- Evidence: failure_mode_cluster:github_release | fmev_51ad1a6fbbb3b6c3fdc1be72bcfae7ea | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.67 | Release v0.3.67\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 8: 失败模式：installation: Release v0.3.68\n\n- Trigger: Developers should check this installation risk before relying on the project: Release v0.3.68\n- Host AI rule: Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.68. Context: Observed when using docker\n- Why it matters: Upgrade or migration may change expected behavior: Release v0.3.68\n- Evidence: failure_mode_cluster:github_release | fmev_7bc0641dd202d881746e1010d1b03fe5 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.68 | Release v0.3.68\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 9: 失败模式：installation: Release v0.3.69\n\n- Trigger: Developers should check this installation risk before relying on the project: Release v0.3.69\n- Host AI rule: Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.69. Context: Observed when using docker\n- Why it matters: Upgrade or migration may change expected behavior: Release v0.3.69\n- Evidence: failure_mode_cluster:github_release | fmev_ba1666889342a143a76dda2fa013ddf2 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.69 | Release v0.3.69\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 10: 失败模式：installation: Release v0.3.70\n\n- Trigger: Developers should check this installation risk before relying on the project: Release v0.3.70\n- Host AI rule: Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.70. Context: Observed when using docker\n- Why it matters: Upgrade or migration may change expected behavior: Release v0.3.70\n- Evidence: failure_mode_cluster:github_release | fmev_18504a4306cc5d44261e6d0f5ec47f54 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.70 | Release v0.3.70\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项目：jshsakura/oc-piloci\n\n## Doramagic 试用结论\n\n当前结论：可以进入发布前推荐检查；首次使用仍应从最小权限、临时目录和可回滚配置开始。\n\n## 用户现在可以做\n\n- 可以先阅读 Human Manual，理解项目目的和主要工作流。\n- 可以复制 Prompt Preview 做安装前体验；这只验证交互感，不代表真实运行。\n- 可以把官方 Quick Start 命令放到隔离环境中验证，不要直接进主力环境。\n\n## 现在不要做\n\n- 不要把 Prompt Preview 当成项目实际运行结果。\n- 不要把 metadata-only validation 当成沙箱安装验证。\n- 不要把未验证能力写成“已支持、已跑通、可放心安装”。\n- 不要在首次试用时交出生产数据、私人文件、真实密钥或主力配置目录。\n\n## 安装前检查\n\n- 宿主 AI 是否匹配：mcp_host, claude\n- 官方安装入口状态：已发现官方入口\n- 是否在临时目录、临时宿主或容器中验证：必须是\n- 是否能回滚配置改动：必须能\n- 是否需要 API Key、网络访问、读写文件或修改宿主配置：未确认前按高风险处理\n- 是否记录了安装命令、实际输出和失败日志：必须记录\n\n## 当前阻塞项\n\n- 无阻塞项。\n\n## 项目专属踩坑\n\n- 失败模式：installation: Release v0.3.61（medium）：Upgrade or migration may change expected behavior: Release v0.3.61 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.61. Context: Observed when using docker\n- 失败模式：installation: Release v0.3.62（medium）：Upgrade or migration may change expected behavior: Release v0.3.62 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.62. Context: Observed when using docker\n- 失败模式：installation: Release v0.3.63（medium）：Upgrade or migration may change expected behavior: Release v0.3.63 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.63. Context: Observed when using docker\n- 失败模式：installation: Release v0.3.64（medium）：Upgrade or migration may change expected behavior: Release v0.3.64 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.64. Context: Observed when using docker\n- 失败模式：installation: Release v0.3.65（medium）：Upgrade or migration may change expected behavior: Release v0.3.65 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.65. Context: Observed when using docker\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/jshsakura/oc-piloci 项目说明书\n\n生成时间：2026-05-18 00:58:38 UTC\n\n## 目录\n\n- [Introduction to piLoci](#introduction)\n- [Getting Started](#getting-started)\n- [System Architecture](#architecture-overview)\n- [Technology Stack](#tech-stack)\n- [MCP Server Implementation](#mcp-server)\n- [Authentication & Security](#authentication)\n- [API Routes](#api-routes)\n- [Curator Pipeline](#curator-pipeline)\n- [Storage Layer](#storage-layer)\n- [Database Models](#database-models)\n- [Web Dashboard](#web-dashboard)\n- [Workspace UI & Team Features](#workspace-ui)\n\n<a id='introduction'></a>\n\n## Introduction to piLoci\n\n### 相关页面\n\n相关主题：[System Architecture](#architecture-overview), [Getting Started](#getting-started), [Technology Stack](#tech-stack)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n- [README.ko.md](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n- [DESIGN-HARNESS.md](https://github.com/jshsakura/oc-piloci/blob/main/web/DESIGN-HARNESS.md)\n- [CLAUDE.md](https://github.com/jshsakura/oc-piloci/blob/main/CLAUDE.md)\n- [MEMORY.md](https://github.com/jshsakura/oc-piloci/blob/main/MEMORY.md)\n- [src/piloci/installer.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/installer.py)\n- [src/piloci/cli.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/cli.py)\n- [web/lib/api.ts](https://github.com/jshsakura/oc-piloci/blob/main/web/lib/api.ts)\n</details>\n\n# Introduction to piLoci\n\npiLoci is a lightweight, self-hosted memory curation system designed for AI coding assistants. It acts as a \"quiet automatic memory curator\" — silently capturing, organizing, and surfacing context from coding sessions to enhance productivity across projects. The system runs on Raspberry Pi 5 or any server, providing privacy-first memory management without relying on external cloud services.\n\n## Overview\n\npiLoci bridges the gap between ephemeral AI coding sessions and persistent knowledge storage. When developers use AI assistants like Claude Code or OpenCode, piLoci captures session context, extracts actionable memories, and stores them in a searchable vector database. This enables developers to build a cumulative knowledge base that improves over time.\n\n### Core Value Proposition\n\n| Aspect | Description |\n|--------|-------------|\n| **Privacy** | Self-hosted on local hardware; no data leaves your network |\n| **Automatic** | Silent capture of sessions without manual intervention |\n| **Project-scoped** | Memories organized by project for clean isolation |\n| **MCP-enabled** | Native integration with Model Context Protocol tools |\n\n资料来源：[README.md](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n\n### Design Philosophy\n\npiLoci embodies the metaphor of a \"behind-the-scenes assistant quietly organizing notes\" (뒤에서 조용히 돕는 자동 기억 큐레이터). The design direction emphasizes:\n\n- **Curation over collection** — Not just storing everything, but organizing meaningful insights\n- **Graph/workspace representation** — Visualizing relationships between memories and sessions\n- **Minimal friction** — One-line pairing, automatic capture, zero-token exposure\n\n资料来源：[CLAUDE.md](https://github.com/jshsakura/oc-piloci/blob/main/CLAUDE.md)\n\n## Architecture\n\n### System Components\n\n```mermaid\ngraph TD\n    subgraph Client[\"Client Side\"]\n        ClaudeCode[Claude Code]\n        OpenCode[OpenCode]\n        Cursor[Cursor IDE]\n    end\n\n    subgraph MCP[\"MCP Layer\"]\n        Memory[MCP: memory]\n        Recall[MCP: recall]\n        Recommend[MCP: recommend]\n    end\n\n    subgraph Server[\"piLoci Server\"]\n        API[Python API Server]\n        SQLite[(SQLite<br/>Identity Data)]\n        LanceDB[(LanceDB<br/>Vector Store)]\n        Redis[(Redis<br/>Sessions)]\n        Embed[FastEmbed/ONNX]\n    end\n\n    subgraph WebUI[\"Web Frontend\"]\n        Dashboard[Dashboard]\n        Projects[Project Workspace]\n        Admin[Admin Console]\n    end\n\n    ClaudeCode <--> MCP\n    OpenCode <--> MCP\n    Cursor <--> MCP\n    MCP <--> API\n    API <--> SQLite\n    API <--> LanceDB\n    API <--> Redis\n    API <--> Embed\n    API <--> WebUI\n```\n\n### Technology Stack\n\n| Component | Technology | Purpose |\n|-----------|------------|---------|\n| **Backend** | Python | MCP-enabled API server |\n| **Identity DB** | SQLite | User accounts, projects, sessions |\n| **Vector Store** | LanceDB | Embedded memory storage |\n| **Session Cache** | Redis | Session state management |\n| **Embeddings** | FastEmbed (ONNX) | Fast on-device inference |\n| **Frontend** | Next.js | Web UI, dashboard, settings |\n\n资料来源：[README.md](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n\n### Web Frontend Structure\n\nThe web application follows a consistent page pattern defined in `web/DESIGN-HARNESS.md`:\n\n```tsx\n<AppShell>\n  <div className=\"pi-page\">\n    <section className=\"pi-page-hero\">\n      <p className=\"pi-eyebrow\">Area label</p>\n      <h1 className=\"pi-title mt-2\">Page title</h1>\n      <p className=\"pi-subtitle\">One sentence explaining the page.</p>\n    </section>\n\n    <section className=\"grid gap-3 sm:grid-cols-3\">\n      <div className=\"pi-metric-card\">...</div>\n    </section>\n\n    <section className=\"pi-panel p-3\">...</section>\n  </div>\n</AppShell>\n```\n\n#### Baseline Pages\n\n| Page | Component | Purpose |\n|------|-----------|---------|\n| Dashboard | `app/dashboard/page.tsx` + `DashboardSummaryPanels.tsx` | User overview with metrics |\n| Admin Console | `app/admin/users/page.tsx` | User management |\n| Project Workspace | `app/projects/page.tsx` + `ProjectListView.tsx` | Project-level memory access |\n| Privacy | `app/privacy/page.tsx` | Privacy policy |\n| Terms | `app/terms/page.tsx` | Terms of service |\n\n资料来源：[DESIGN-HARNESS.md](https://github.com/jshsakura/oc-piloci/blob/main/web/DESIGN-HARNESS.md)\n\n## Client Connection Flow\n\n### Supported Clients\n\npiLoci integrates with multiple AI coding assistants through MCP:\n\n| Client | Session Capture | MCP Tools |\n|--------|----------------|-----------|\n| **Claude Code** | SessionStart/Stop hooks | memory, recall, recommend |\n| **Claude Desktop** | Static config | memory, recall, recommend |\n| **OpenCode** | Static config only | memory, recall, recommend |\n| **Cursor** | Static config | memory, recall, recommend |\n\n资料来源：[web/components/TokenManager.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/components/TokenManager.tsx)\n\n### Connection Process\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant CLI\n    participant WebUI\n    participant Server\n\n    User->>CLI: piloci login\n    CLI->>Server: OAuth or install code request\n    Server->>WebUI: Redirect to /device\n    User->>WebUI: Login + approve\n    WebUI->>CLI: Token ready\n    CLI->>Server: Poll and receive token\n    Server->>CLI: Token + URLs\n    CLI->>User: Configuration complete\n\n    User->>CLI: piloci install\n    CLI->>Server: Download MCP server config\n    Server->>CLI: .mcp.json + hooks\n    CLI->>User: MCP tools available\n```\n\n### What Connection Establishes\n\nThe pairing process creates the following artifacts:\n\n```\n~/.config/piloci/\n├── config.json     # Token + ingest/analyze URLs (mode 0600)\n├── hook.py         # SessionStart catch-up (Claude only)\n└── stop-hook.sh    # Stop live push (Claude only)\n\n~/.claude.json              # MCP server entry (Claude only)\n~/.claude/settings.json     # SessionStart + Stop hooks (Claude only)\n~/.config/opencode/         # MCP server entry (OpenCode)\n```\n\n资料来源：[README.ko.md](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n\n## CLI Commands\n\nThe `piloci` CLI provides complete installation and management capabilities:\n\n| Command | Description |\n|---------|-------------|\n| `piloci login` | Authenticate with the server (OAuth or install code) |\n| `piloci install` | Install MCP server and hooks for AI clients |\n| `piloci uninstall` | Remove all piLoci artifacts, optionally restore backups |\n| `piloci restore` | Restore client configs from .piloci-bak snapshots |\n| `piloci backfill-cwd` | Fix legacy slug-collision bug in session data |\n\n### Install Command Options\n\n| Flag | Purpose |\n|------|---------|\n| `--server` | Override server URL when only install code is provided |\n| `--token` | Use token directly instead of resolving URL |\n| `--force` | Wipe existing plugin folders and reinstall fresh |\n\n### Uninstall Command Options\n\n| Flag | Purpose |\n|------|---------|\n| `--yes` | Skip confirmation prompt |\n| `--no-restore` | Remove entries surgically instead of restoring backups |\n\n资料来源：[src/piloci/cli.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/cli.py)\n\n## Plugin Installation Structure\n\nFor Claude Code, piLoci installs as a Claude plugin with hooks:\n\n```\npiloci/\n├── .claude-plugin/\n│   └── plugin.json          # Manifest with name, version, description\n├── hooks/\n│   ├── hooks.json           # SessionStart + Stop wired to scripts\n│   ├── hook.py              # Downloaded from /api/hook/script\n│   └── stop-hook.sh         # Downloaded from /api/hook/stop-script\n└── .mcp.json                # MCP server config for memory/recall/recommend\n```\n\n资料来源：[src/piloci/installer.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/installer.py)\n\n## Data Models\n\n### API Client Functions\n\nThe frontend communicates with the backend through typed API functions:\n\n```typescript\n// Project operations\ngetProjects: () => request<Project[]>(\"api/projects\")\ngetProjectBySlug: (slug: string) => request<Project>(`api/projects/slug/${slug}`)\ncreateProject: (body) => request<Project>(\"api/projects\", { method: \"POST\", body })\ngetProjectFreshness: (projectId) => request<ProjectFreshness>(`api/projects/${projectId}/freshness`)\n\n// Session operations\ngetSessions: () => request<Session[]>(\"api/sessions\")\n\n// Memory operations\ncreateMemory: (projectId, body) => request<Memory>(`api/memories`, { method: \"POST\", body })\n\n// Distillation operations\nrunDistillationNow: () => request<{ woken: boolean; note: string }>(\"/api/distillation/run-now\", { method: \"POST\" })\ngetDistillationPreferences: () => request<DistillationPreferences>(\"api/preferences\")\nupdateDistillationPreferences: (body) => request<DistillationPreferences>(\"api/preferences\", { method: \"PATCH\", body })\n\n// Budget operations\nbudgetUsage: () => request<BudgetUsage>(\"api/budget/usage\")\n```\n\n资料来源：[web/lib/api.ts](https://github.com/jshsakura/oc-piloci/blob/main/web/lib/api.ts)\n\n### Project Sessions Panel\n\nThe session viewer displays captured coding sessions:\n\n| Field | Description |\n|-------|-------------|\n| `ingest_id` | Unique session identifier |\n| `client` | AI client used (Claude Code, OpenCode, etc.) |\n| `project_slug` | Associated project |\n| `project_name` | Human-readable project name |\n| `created_at` | Session start timestamp |\n| `processed_at` | When distillation completed |\n| `memories_extracted` | Number of memories extracted |\n| `error` | Any processing errors |\n| `transcript` | Full session transcript (expandable) |\n\n资料来源：[web/components/ProjectSessionsPanel.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/components/ProjectSessionsPanel.tsx)\n\n### Instincts (Top Knacks)\n\nInstincts are triggered memory patterns:\n\n| Field | Description |\n|-------|-------------|\n| `instinct_id` | Unique instinct identifier |\n| `trigger` | Condition pattern (\"when...\") |\n| `action` | Suggested action (\"→...\") |\n| `project_slug` | Associated project |\n| `domain` | Knowledge domain |\n| `instinct_count` | Number of times triggered |\n\n资料来源：[web/components/DashboardSummaryPanels.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/components/DashboardSummaryPanels.tsx)\n\n## Usage Scenarios\n\n### Scenario A — Team Project Memory Hub\n\nA small team sets up one piLoci on a shared Raspberry Pi 5. Each member creates an account, joins shared projects, and stores memories via MCP tools. Everyone benefits from the same knowledge base while project isolation keeps unrelated work separate.\n\n### Scenario B — Multi-Project Workspace\n\nA solo developer runs several projects (e.g., \"thesis research\", \"side project\", \"client work\") on one piLoci. Each project's memories stay isolated, and the workspace viewer shows notes and relationships per project.\n\n### Scenario C — Obsidian Export\n\nGenerate workspace notes and export to an Obsidian vault:\n\n```bash\ncurl -sS http://localhost:8314/api/projects/slug/my-project/workspace\n```\n\nOr download a ready-made archive:\n\n```bash\ncurl -OJ http://localhost:8314/api/vault/my-project/export\n```\n\n资料来源：[README.md](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n\n## Deployment Configuration\n\n### Environment Variables\n\nWhen running behind a reverse proxy, the `BASE_URL` environment variable is required:\n\n```env\nBASE_URL=https://piloci.example.com\n```\n\nThis ensures Google OAuth redirect URIs match exactly:\n\n```\nhttps://piloci.example.com/auth/google/callback\n```\n\nWithout `BASE_URL`, the backend may generate callbacks based on internal request hosts, causing `redirect_uri_mismatch` errors.\n\n### Port Configuration\n\nThe default port is `8314`. When exposing via reverse proxy or tunnel (Cloudflare Tunnel, Caddy, nginx), proxy external traffic to `http://127.0.0.1:8314`.\n\n资料来源：[README.ko.md](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n\n## Version Management\n\npiLoci uses a single-source version system:\n\n| Rule | Description |\n|------|-------------|\n| **Source** | `pyproject.toml` → `[project].version` |\n| **Default bump** | `+0.0.1` patch only |\n| **Major/Minor** | Requires explicit approval |\n| **Release trigger** | Git tag push: `git tag v{version} && git push origin main v{version}` |\n| **Tag format** | Must match: `v0.2.0` ↔ `0.2.0` |\n\n### Pre-release Checklist\n\nBefore tagging:\n\n1. Update version in `pyproject.toml`\n2. Run tests: `pytest tests/ -v`\n3. Build package: `uv build`\n4. Build web (if changed): `pnpm build` in `web/`\n\n### GitHub Actions Pipeline\n\nThe `publish.yml` workflow handles:\n\n- Version guard (tag matches `pyproject.toml`)\n- Test gate\n- Web build artifact\n- Multi-arch Docker image publish\n- GitHub Release creation\n- PyPI publish as `oc-piloci`\n\n资料来源：[CLAUDE.md](https://github.com/jshsakura/oc-piloci/blob/main/CLAUDE.md)\n\n## Development Workflow\n\n### Starting an Implementation Session\n\n1. Begin each session at `PLAN.md`\n2. Check `## 현재 상태` (Current Status) for incomplete items\n3. Implement the next pending item\n4. Document completion in PLAN.md\n\n### Current Development Focus\n\nBased on recent changes documented in `MEMORY.md`:\n\n- **Memory creation UI speed** — Narrow v0.3 slice for faster memory creation\n- **Graph UI direction** — Planning for React Flow-based interactive memory visualization\n- **Copy style** — Landing page emphasizes \"quiet automatic memory curator\" metaphor\n- **Vault caching** — Tests added for `tests/test_vault_cache.py`\n\n资料来源：[MEMORY.md](https://github.com/jshsakura/oc-piloci/blob/main/MEMORY.md)\n\n### Design Guidelines for Frontend\n\nKey principles from `CLAUDE.md`:\n\n- **Avoid dash-heavy feature lists** — Use paragraph-based Korean/English copy\n- **Translate optimizations to UX** — Don't just list technical features\n- **Maintain metaphor** — \"뒤에서 조용히 돕는 자동 기억 큐레이터\" (behind-the-scenes quiet assistant)\n- **Graph direction** — Visual metaphor of a curator organizing post-it notes\n\n---\n\n<a id='getting-started'></a>\n\n## Getting Started\n\n### 相关页面\n\n相关主题：[Introduction to piLoci](#introduction)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [.env.example](https://github.com/jshsakura/oc-piloci/blob/main/.env.example)\n- [docker-compose.yml](https://github.com/jshsakura/oc-piloci/blob/main/docker-compose.yml)\n- [deploy/setup.sh](https://github.com/jshsakura/oc-piloci/blob/main/deploy/setup.sh)\n- [src/piloci/config.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/config.py)\n</details>\n\n# Getting Started\n\npiLoci is a personal memory hub designed for AI coding assistants. It runs on a local server (typically Raspberry Pi 5) and captures, stores, and retrieves contextual memories from AI-assisted coding sessions. This guide walks you through the complete setup process from hardware prerequisites to first login.\n\n## Prerequisites\n\n### Hardware Requirements\n\n| Component | Minimum | Recommended |\n|-----------|---------|-------------|\n| Device | Raspberry Pi 5 (4GB+) | Raspberry Pi 5 (8GB) |\n| Storage | 32GB SD card | 64GB+ SSD via USB |\n| Network | Ethernet or WiFi | Ethernet |\n| OS | Raspberry Pi OS (64-bit) | Raspberry Pi OS (64-bit) |\n\n资料来源：[README.md](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n\n### Software Requirements\n\n- **Docker** and **Docker Compose** installed on the host\n- **Google OAuth credentials** (for authentication)\n- A domain name (optional, for remote access via Cloudflare Tunnel)\n\n## Installation\n\n### Step 1: Clone the Repository\n\n```bash\ngit clone https://github.com/jshsakura/oc-piloci.git\ncd oc-piloci\n```\n\n### Step 2: Configure Environment Variables\n\nCopy the example environment file and configure it:\n\n```bash\ncp .env.example .env\n```\n\nEdit `.env` with your specific settings:\n\n```env\n# Required: Set your external HTTPS domain if behind a reverse proxy\nBASE_URL=https://piloci.example.com\n\n# Google OAuth credentials (required for authentication)\nGOOGLE_CLIENT_ID=your_client_id_here\nGOOGLE_CLIENT_SECRET=your_client_secret_here\n\n# Secret key for session encryption\nSECRET_KEY=your_random_secret_key_here\n```\n\n> **Important:** When deploying behind a reverse proxy, you MUST set `BASE_URL` to your external HTTPS domain. Without it, Google OAuth redirect URIs will fail with `redirect_uri_mismatch`. 资料来源：[README.ko.md](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n\n#### Google OAuth Setup\n\n1. Go to [Google Cloud Console](https://console.cloud.google.com/)\n2. Create a new project or select an existing one\n3. Navigate to **APIs & Services** → **Credentials**\n4. Create an **OAuth 2.0 Client ID** (Web application type)\n5. Add the following authorized redirect URI (replace with your domain):\n\n```\nhttps://piloci.example.com/auth/google/callback\n```\n\nThe callback URI must match **exactly**, including trailing slashes. 资料来源：[README.ko.md](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n\n### Step 3: Deploy with Docker Compose\n\nThe project uses Docker Compose for container orchestration:\n\n```bash\ndocker compose up -d\n```\n\nThis starts the following services:\n\n| Service | Port | Purpose |\n|---------|------|---------|\n| web | 8314 | Next.js frontend + API server |\n| redis | 6379 | Session storage |\n| worker | - | Background distillation worker |\n\n资料来源：[docker-compose.yml](https://github.com/jshsakura/oc-piloci/blob/main/docker-compose.yml)\n\n### Step 4: Verify Deployment\n\nCheck the health status:\n\n```bash\ncurl http://localhost:8314/healthz\n```\n\nA successful response indicates the application is running correctly.\n\n## Architecture Overview\n\n```mermaid\ngraph TB\n    subgraph \"Client Side\"\n        CC[Claude Code / Claude Desktop]\n        OC[OpenCode]\n        CU[Cursor]\n    end\n    \n    subgraph \"piLoci Server\"\n        WEB[Web App :8314]\n        REDIS[(Redis<br/>Sessions)]\n        WORKER[Distillation<br/>Worker]\n        DB[(LanceDB<br/>Memories)]\n    end\n    \n    subgraph \"AI Clients → piLoci\"\n        CC --> MCP[MCP Server]\n        OC --> MCP\n        CU --> MCP\n    end\n    \n    MCP -->|Ingest| WEB\n    WEB --> REDIS\n    WEB --> DB\n    WORKER --> DB\n    WORKER -->|Distill| CC\n```\n\n资料来源：[README.md](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n\n## Client Connection\n\n### Claude Code Setup\n\n1. Navigate to **Settings → Tokens** in the web UI\n2. Generate an install code\n3. Run the pairing command:\n\n```bash\npiloci login --pair <install_code>\npiloci install\n```\n\nOr use the one-liner:\n\n```bash\ncurl -sSL https://piloci.example.com/install/<install_code> | bash\n```\n\nThis automatically:\n- Writes token + URLs to `~/.config/piloci/config.json`\n- Registers the MCP server in `~/.claude.json`\n- Configures session capture hooks in `~/.claude/settings.json`\n\n资料来源：[README.ko.md](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n\n### What Gets Installed\n\n```\n~/.config/piloci/\n├── config.json     # Token + ingest/analyze URLs (mode 0600)\n├── hook.py         # SessionStart catch-up hook (Claude Code only)\n└── stop-hook.sh    # Stop live push (Claude Code only)\n\n~/.claude.json              # MCP server entry (Claude Code only)\n~/.claude/settings.json     # SessionStart + Stop hooks (Claude Code only)\n```\n\n资料来源：[README.ko.md](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n\n## Remote Access\n\n### Exposing Port 8314\n\nConfigure your reverse proxy or tunnel to expose port 8314:\n\n| Proxy/Tunnel | Configuration |\n|--------------|---------------|\n| Cloudflare Tunnel | Point to `http://127.0.0.1:8314` |\n| Caddy | Proxy to `localhost:8314` |\n| nginx | Proxy pass to `127.0.0.1:8314` |\n\n### Cloudflare Tunnel Setup\n\n```bash\ncloudflared tunnel --url http://localhost:8314\n```\n\n资料来源：[README.ko.md](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n\n## Configuration Reference\n\n### Environment Variables\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `BASE_URL` | Yes (remote) | `http://localhost:8314` | External HTTPS URL when behind proxy |\n| `GOOGLE_CLIENT_ID` | Yes | - | Google OAuth Client ID |\n| `GOOGLE_CLIENT_SECRET` | Yes | - | Google OAuth Client Secret |\n| `SECRET_KEY` | Yes | - | Session encryption key |\n| `DATA_DIR` | No | `./data` | Data persistence directory |\n| `REDIS_URL` | No | `redis://redis:6379` | Redis connection URL |\n\n资料来源：[src/piloci/config.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/config.py)\n\n### Data Storage\n\nThe application stores data in:\n\n- **SQLite**: User identity and authentication data\n- **LanceDB**: Embedded vector storage for memories\n- **Redis**: Session data and real-time state\n\n资料来源：[README.md](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n\n## Development Mode\n\n### Local Stack Development\n\n```bash\n# Start backend with hot reload\nuv run uvicorn src.piloci.main:app --reload --port 8314\n\n# In another terminal, start worker\nuv run python -m piloci.worker.distillation\n```\n\n### Web Frontend Development\n\n```bash\ncd web\npnpm install --frozen-lockfile\npnpm dev\n```\n\n资料来源：[README.md](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n\n## Next Steps\n\nAfter successful installation:\n\n1. **Create an account** via the web UI at `http://localhost:8314/signup`\n2. **Connect your AI client** using the pairing flow\n3. **Create projects** to organize your memories\n4. **Explore the dashboard** to view session history and extracted memories\n\nFor troubleshooting, check the logs:\n\n```bash\ndocker compose logs -f web\ndocker compose logs -f worker\n\n---\n\n<a id='architecture-overview'></a>\n\n## System Architecture\n\n### 相关页面\n\n相关主题：[Introduction to piLoci](#introduction), [Technology Stack](#tech-stack), [Storage Layer](#storage-layer), [MCP Server Implementation](#mcp-server)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n- [CLAUDE.md](https://github.com/jshsakura/oc-piloci/blob/main/CLAUDE.md)\n- [web/lib/api.ts](https://github.com/jshsakura/oc-piloci/blob/main/web/lib/api.ts)\n- [src/piloci/installer.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/installer.py)\n- [web/DESIGN-HARNESS.md](https://github.com/jshsakura/oc-piloci/blob/main/web/DESIGN-HARNESS.md)\n- [MEMORY.md](https://github.com/jshsakura/oc-piloci/blob/main/MEMORY.md)\n- [web/app/page.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/app/page.tsx)\n- [web/components/DashboardSummaryPanels.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/components/DashboardSummaryPanels.tsx)\n- [web/app/admin/users/page.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/app/admin/users/page.tsx)\n</details>\n\n# System Architecture\n\npiLoci is a self-hosted memory curation system designed for AI-assisted development workflows. It operates as a client-server architecture where a Raspberry Pi (or any server) acts as a central hub for capturing, processing, and retrieving contextual memories from AI coding sessions. The system bridges the gap between ephemeral AI conversations and persistent, searchable knowledge bases.\n\n## High-Level Architecture Overview\n\npiLoci follows a layered architecture pattern comprising four primary tiers: a frontend presentation layer, a backend API layer, a storage abstraction layer, and a client integration layer. Each tier is independently deployable and communicates through well-defined interfaces, enabling flexibility in deployment scenarios.\n\nThe backend is built with Python and leverages the Model Context Protocol (MCP) to expose memory management tools to AI clients such as Claude Code and OpenCode. The frontend is a Next.js application that provides both user-facing interfaces and administrative capabilities. The storage layer abstracts away the complexity of handling different database technologies, providing a unified API for memory operations.\n\n```mermaid\ngraph TD\n    subgraph Client[\"Client Layer\"]\n        ClaudeCode[\"Claude Code\"]\n        OpenCode[\"OpenCode\"]\n        Cursor[\"Cursor IDE\"]\n    end\n\n    subgraph Server[\"piLoci Server\"]\n        API[\"FastAPI Server<br/>(Port 8314)\"]\n        MCP[\"MCP Tools<br/>memory/recall/recommend\"]\n    end\n\n    subgraph Storage[\"Storage Layer\"]\n        SQLite[\"SQLite<br/>(Identity)\"]\n        LanceDB[\"LanceDB<br/>(Vectors)\"]\n        Redis[\"Redis<br/>(Sessions)\"]\n    end\n\n    subgraph Frontend[\"Frontend Layer\"]\n        NextJS[\"Next.js App<br/>(Web UI)\"]\n        Admin[\"Admin Console\"]\n        Dashboard[\"User Dashboard\"]\n    end\n\n    Client -->|HTTP/MCP| Server\n    NextJS -->|REST API| API\n    API --> Storage\n    API --> MCP\n```\n\n资料来源：[README.md:1-50]()\n\n## Technology Stack\n\npiLoci's architecture leverages a carefully selected technology stack optimized for self-hosted deployment on resource-constrained hardware like the Raspberry Pi 5. Each component serves a specific purpose in the overall system.\n\n| Component | Technology | Purpose | Location |\n|-----------|------------|---------|----------|\n| Backend API | FastAPI | REST API + MCP server | `src/piloci/` |\n| Vector Storage | LanceDB | Embedded memory storage with vector search | `src/piloci/storage/` |\n| Identity DB | SQLite | User/project identity and metadata | `src/piloci/db/` |\n| Session Cache | Redis | Temporary session data caching | `docker-compose.yml` |\n| Embeddings | fastembed (ONNX) | Local CPU-based embedding inference | `src/piloci/storage/` |\n| Frontend | Next.js 14 | React-based web application | `web/` |\n| Styling | Tailwind CSS | Utility-first design system | `web/` |\n| Container | Docker | Self-contained deployment | `docker-compose.yml` |\n\n资料来源：[README.md:85-95]()\n\n### Embedding Infrastructure\n\nThe system uses fastembed for ONNX-based embeddings, enabling fast, on-device inference without requiring GPU resources. This design choice is critical for the target deployment environment of Raspberry Pi devices where power efficiency and thermal constraints are primary concerns.\n\nThe embedding service processes text content and generates vector representations that capture semantic meaning. These vectors are stored in LanceDB, which provides efficient similarity search capabilities essential for the recall and recommendation features.\n\n资料来源：[README.md:90]()\n\n## Frontend Architecture\n\nThe Next.js frontend follows a component-driven architecture with clear separation between presentation components, data fetching logic, and layout structures. The application is organized around a shell-based layout pattern that provides consistent navigation and authentication state across all pages.\n\n### Page Structure Pattern\n\nAll application pages follow a standardized layout defined in `AppShell.tsx` with specific section patterns for different content types.\n\n```mermaid\ngraph TD\n    AppShell[\"AppShell Component<br/>(web/components/AppShell.tsx)\"]\n    Hero[\"pi-page-hero<br/>(Title + Subtitle)\"]\n    Metrics[\"pi-metric-card<br/>(Data Cards)\"]\n    Panel[\"pi-panel<br/>(Content Sections)\"]\n\n    AppShell --> Hero\n    AppShell --> Metrics\n    AppShell --> Panel\n```\n\nThe component hierarchy follows this pattern:\n\n```\nAppShell\n└── div.pi-page\n    ├── section.pi-page-hero\n    │   ├── p.pi-eyebrow\n    │   ├── h1.pi-title\n    │   └── p.pi-subtitle\n    ├── section.pi-page (metrics grid)\n    │   └── div.pi-metric-card\n    └── section.pi-panel (content areas)\n```\n\n资料来源：[web/DESIGN-HARNESS.md:10-30]()\n\n### Key Frontend Components\n\n| Component | File Path | Responsibility |\n|-----------|-----------|----------------|\n| AppShell | `web/components/AppShell.tsx` | Authenticated shell with glass navigation |\n| DashboardSummaryPanels | `web/components/DashboardSummaryPanels.tsx` | User dashboard with metrics and session lists |\n| ProjectSessionsPanel | `web/components/ProjectSessionsPanel.tsx` | Project-specific session viewer with transcripts |\n| TokenManager | `web/components/TokenManager.tsx` | Installation token generation and display |\n| DistillationSettings | `web/components/DistillationSettingsPanel.tsx` | Memory processing configuration |\n\n资料来源：[web/components/DashboardSummaryPanels.tsx:1-80]()\n\n### API Client Layer\n\nThe frontend communicates with the backend through a typed API client defined in `web/lib/api.ts`. This module provides a centralized request function that handles authentication, error handling, and response typing.\n\n```typescript\n// Simplified API client structure\nconst api = {\n  projects: {\n    list: () => request<Project[]>(\"/api/projects\"),\n    create: (body) => request<Project>(\"/api/projects\", { method: \"POST\", body }),\n    getBySlug: (slug) => request<Project>(`/api/projects/slug/${slug}`),\n  },\n  memories: {\n    create: (projectId, body) => request<Memory>(`/api/projects/${projectId}/memories`, { method: \"POST\", body }),\n    list: (projectId) => request<Memory[]>(`/api/projects/${projectId}/memories`),\n  },\n  distillation: {\n    runNow: () => request<{ woken: boolean; note: string }>(\"/api/distillation/run-now\", { method: \"POST\" }),\n    getPreferences: () => request<DistillationPreferences>(\"/api/preferences\"),\n    updatePreferences: (body) => request<DistillationPreferences>(\"/api/preferences\", { method: \"PATCH\", body }),\n  },\n};\n```\n\n资料来源：[web/lib/api.ts:1-50]()\n\n### Landing Page Architecture\n\nThe landing page (`web/app/page.tsx`) serves as the public-facing entry point for unauthenticated users and implements a conversion-focused design with feature highlights and installation guidance.\n\n```mermaid\ngraph LR\n    Hero[\"Hero Section<br/>(CTA: Signup/Dashboard)\"]\n    Features[\"Features Grid<br/>(4-column)\"]\n    Install[\"Installation Guide<br/>(CLI + bash options)\"]\n    Uninstall[\"Uninstall Note<br/>(Removal instructions)\"]\n\n    Hero --> Features\n    Features --> Install\n    Install --> Uninstall\n```\n\n资料来源：[web/app/page.tsx:1-60]()\n\n## Backend Architecture\n\nThe Python backend implements a FastAPI application that serves both REST API endpoints and MCP tool interfaces. The architecture emphasizes separation of concerns through distinct modules for API routes, database operations, and storage abstraction.\n\n### Application Entry Point\n\nThe main application module (`src/piloci/main.py`) initializes the FastAPI server with middleware configuration, CORS settings, and route registration. The application listens on port 8314 by default and supports configuration through environment variables.\n\nKey configuration parameters:\n\n| Parameter | Default | Purpose |\n|-----------|---------|---------|\n| `BASE_URL` | (auto-detected) | External HTTPS domain for OAuth callbacks |\n| `DATABASE_URL` | (local path) | SQLite database location |\n| `REDIS_URL` | (local) | Redis connection for session caching |\n| `PORT` | 8314 | HTTP server port |\n\n资料来源：[README.ko.md:1-30]()\n\n### Database Architecture\n\nThe system uses three distinct storage mechanisms, each optimized for specific data access patterns.\n\n```mermaid\ngraph TD\n    API[\"FastAPI Server\"]\n    Session[\"Session Management\"]\n    Identity[\"SQLite<br/>(Identity Data)\"]\n    Vectors[\"LanceDB<br/>(Memory Vectors)\"]\n    Cache[\"Redis<br/>(Session Cache)\"]\n\n    API --> Session\n    Session --> Identity\n    Session --> Vectors\n    Session --> Cache\n```\n\n#### Identity Database (SQLite)\n\nSQLite handles persistent identity data including user accounts, project metadata, and session records. The session module (`src/piloci/db/session.py`) provides an abstraction layer for database operations.\n\n```python\n# Session database schema concept\nclass Session:\n    id: str\n    user_id: str\n    project_id: str\n    client: str  # \"claude-code\" | \"opencode\" | \"cursor\"\n    ingest_id: str\n    created_at: datetime\n    processed_at: Optional[datetime]\n    memories_extracted: int\n    error: Optional[str]\n```\n\n资料来源：[web/components/DashboardSummaryPanels.tsx:30-50]()\n\n#### Vector Storage (LanceDB)\n\nLanceDB stores embedded memory content with vector representations for semantic search. The storage module provides CRUD operations for memories and supports similarity-based retrieval for the recall and recommendation features.\n\n#### Session Cache (Redis)\n\nRedis provides low-latency caching for active sessions and real-time processing state. The distillation worker uses Redis for queue management and processing state tracking.\n\n资料来源：[README.md:85-90]()\n\n### API Route Organization\n\nAPI routes are organized by resource type and follow RESTful conventions:\n\n| Route Prefix | Handler | Purpose |\n|--------------|---------|---------|\n| `/api/auth/*` | Authentication | OAuth flows, session management |\n| `/api/projects/*` | Project management | CRUD, slug lookup, freshness |\n| `/api/memories/*` | Memory operations | Create, list, vector search |\n| `/api/budget/*` | Budget tracking | Usage reporting |\n| `/api/preferences` | User settings | Distillation configuration |\n| `/api/distillation/*` | Worker control | Manual trigger, status |\n\n资料来源：[web/lib/api.ts:1-40]()\n\n## Installer Architecture\n\nThe installer module (`src/piloci/installer.py`) handles client-side setup by creating configuration files and registering MCP servers with supported AI clients. It follows a plugin-based architecture for each supported client type.\n\n### Claude Code Installer Layout\n\n```mermaid\ngraph TD\n    Plugin[\"Claude Plugin<br/>~/.claude/plugins/piloci/\"]\n    PluginManifest[\".claude-plugin/plugin.json\"]\n    Hooks[\"hooks/hooks.json\"]\n    Scripts[\"hooks/hook.py<br/>hooks/stop-hook.sh\"]\n    MCP[\".mcp.json<br/>(MCP Server Config)\"]\n\n    Plugin --> PluginManifest\n    Plugin --> Hooks\n    Plugin --> Scripts\n    Plugin --> MCP\n```\n\n资料来源：[src/piloci/installer.py:20-50]()\n\n### Installation Workflow\n\n1. **Manifest Creation**: Generates `plugin.json` with version, description, and author metadata\n2. **Hook Configuration**: Creates `hooks.json` linking SessionStart and Stop events to plugin scripts\n3. **Script Download**: Fetches `hook.py` and `stop-hook.sh` from the server's `/api/hook/` endpoints\n4. **MCP Registration**: Creates `.mcp.json` exposing memory, recall, and recommend tools\n\n资料来源：[src/piloci/installer.py:50-80]()\n\n## Deployment Architecture\n\npiLoci is designed for self-hosted deployment, typically on a Raspberry Pi 5 within the user's local network. The system supports exposure through reverse proxies or tunnels for remote access.\n\n### Docker Deployment\n\nThe recommended deployment uses Docker Compose with the following service structure:\n\n```yaml\nservices:\n  piloci:\n    image: ghcr.io/jshsakura/oc-piloci:latest\n    ports:\n      - \"8314:8314\"\n    volumes:\n      - ./data:/data\n    environment:\n      - BASE_URL=https://piloci.example.com\n      - DATABASE_URL=sqlite:///data/piloci.db\n```\n\n资料来源：[docker-compose.yml](https://github.com/jshsakura/oc-piloci/blob/main/docker-compose.yml)\n\n### Reverse Proxy Configuration\n\nWhen deploying behind a reverse proxy (Cloudflare Tunnel, Caddy, nginx), port 8314 should be exposed externally. The `BASE_URL` environment variable must be set to the external HTTPS domain for proper OAuth callback URL generation.\n\nGoogle OAuth requires exact callback URI matching:\n```\nhttps://piloci.opencourse.kr/auth/google/callback\n```\n\n资料来源：[README.ko.md:25-40]()\n\n## Client Connection Flow\n\nThe system supports multiple AI clients through standardized MCP interfaces. Each client has specific integration requirements.\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant CLI as piloci CLI\n    participant Browser\n    participant Server as piLoci Server\n    participant Claude as Claude Code\n\n    User->>CLI: piloci login\n    CLI->>Browser: Opens /device page\n    User->>Browser: Login + Approve\n    Browser->>Server: Token exchange\n    Server->>CLI: Token + URLs\n    CLI->>CLI: Write ~/.config/piloci/config.json\n    CLI->>Server: Register MCP server\n    User->>Claude: Start session\n    Claude->>CLI: MCP tool calls (memory/recall/recommend)\n    CLI->>Server: API requests\n    Server->>Claude: Memory results\n```\n\n资料来源：[README.ko.md:1-20]()\n\n### Supported Clients\n\n| Client | MCP Support | Hook Support | Configuration Location |\n|--------|-------------|--------------|------------------------|\n| Claude Code | Full | SessionStart + Stop | `~/.claude.json`, `~/.claude/settings.json` |\n| Claude Desktop | Full | N/A | `~/Library/Application Support/Claude/` |\n| OpenCode | Full | N/A | `~/.config/opencode/opencode.json` |\n| Cursor | Partial | N/A | Cursor MCP settings |\n\n资料来源：[web/components/TokenManager.tsx:1-30]()\n\n## Distillation System\n\nThe distillation system processes captured sessions to extract structured memories. It operates as a configurable background worker with temperature and load-based throttling.\n\n### Distillation Settings\n\n| Parameter | Purpose | Default Behavior |\n|-----------|---------|------------------|\n| Temperature Ceiling | SoC temperature threshold (°C) | Worker pauses when exceeded |\n| Load Ceiling | 1-minute load average limit | Worker pauses when exceeded |\n| Overflow Threshold | Workload threshold for aggressive processing | Ignores load when exceeded |\n\n资料来源：[web/components/DistillationSettingsPanel.tsx:1-40]()\n\n### Processing Pipeline\n\n1. **Session Capture**: Hook scripts send transcripts via the ingest API\n2. **Transcript Storage**: Raw content stored with session metadata\n3. **Embedding Generation**: fastembed creates vector representations\n4. **Memory Extraction**: LLM processes transcript to identify key learnings\n5. **Vector Indexing**: Extracted memories indexed in LanceDB for retrieval\n\n## Admin Console\n\nThe admin console (`web/app/admin/users/page.tsx`) provides administrative oversight with user management and system statistics.\n\n### Admin Features\n\n| Feature | Description | Endpoint |\n|---------|-------------|----------|\n| User Statistics | Total, pending, admin counts | Calculated from database |\n| User Management | View and manage user accounts | `/api/admin/users` |\n| System Health | Dashboard with key metrics | DashboardSummaryPanels |\n\n资料来源：[web/app/admin/users/page.tsx:1-50]()\n\n## Version Management\n\nThe system uses a single-source version policy where `pyproject.toml` is the authoritative version source. The `piloci.__version__` is derived from package metadata rather than hardcoded values.\n\n### Release Process\n\n1. Update version in `pyproject.toml` (patch increment by default)\n2. Run validation: `pytest tests/ -v` and `uv build`\n3. Tag with matching version: `git tag v{version}`\n4. Push tag to trigger GitHub Actions workflow\n\nThe publish workflow (`publish.yml`) performs tag/version consistency checks, runs tests, builds the web app, publishes Docker images, creates GitHub Release, and publishes to PyPI.\n\n资料来源：[CLAUDE.md:1-30]()\n\n## Development Workflow\n\nDevelopment follows a session-based approach where each implementation session begins by reviewing `PLAN.md` and checking the current status section for the next incomplete item.\n\n### Development Stack Commands\n\n```bash\n# Backend development\ncd src\nuv run pytest tests/ -v\nuv run black .\nuv run ruff check .\n\n# Frontend development\ncd web\npnpm install --frozen-lockfile\npnpm build\n```\n\n资料来源：[README.md:60-75]()\n\n## System Data Flow\n\n```mermaid\ngraph LR\n    subgraph Capture[\"Capture Phase\"]\n        Transcript[\"User/AI Transcript\"]\n        Hook[\"SessionStart Hook\"]\n    end\n\n    subgraph Process[\"Processing Phase\"]\n        Ingest[\"Ingest API\"]\n        Embed[\"Embedding (fastembed)\"]\n        Extract[\"Memory Extraction\"]\n    end\n\n    subgraph Store[\"Storage Phase\"]\n        SQLite[\"SQLite (Metadata)\"]\n        LanceDB[\"LanceDB (Vectors)\"]\n        Redis[\"Redis (Cache)\"]\n    end\n\n    subgraph Retrieve[\"Retrieval Phase\"]\n        Recall[\"recall tool\"]\n        Recommend[\"recommend tool\"]\n        Search[\"Vector Search\"]\n    end\n\n    Transcript --> Hook\n    Hook --> Ingest\n    Ingest --> Embed\n    Embed --> Extract\n    Extract --> SQLite\n    Extract --> LanceDB\n    Ingest --> Redis\n\n    Recall --> Search\n    Recommend --> Search\n    Search --> LanceDB\n    Search --> Retrieve\n```\n\n## Summary\n\npiLoci's architecture reflects a pragmatic approach to self-hosted AI memory management. By combining FastAPI for the backend, Next.js for the frontend, and purpose-built storage solutions (SQLite, LanceDB, Redis), the system achieves a balance between simplicity and capability. The MCP integration layer enables seamless interaction with popular AI coding tools while maintaining client neutrality. The modular design allows each component to be upgraded or replaced independently, and the Docker-based deployment ensures consistent behavior across different host environments.\n\n---\n\n<a id='tech-stack'></a>\n\n## Technology Stack\n\n### 相关页面\n\n相关主题：[System Architecture](#architecture-overview), [Storage Layer](#storage-layer), [Web Dashboard](#web-dashboard)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [pyproject.toml](https://github.com/jshsakura/oc-piloci/blob/main/pyproject.toml)\n- [web/package.json](https://github.com/jshsakura/oc-piloci/blob/main/web/package.json)\n- [src/piloci/storage/lancedb_store.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/storage/lancedb_store.py)\n- [docs/ADR-014-lancedb-backend.md](https://github.com/jshsakura/oc-piloci/blob/main/docs/ADR-014-lancedb-backend.md)\n- [MEMORY.md](https://github.com/jshsakura/oc-piloci/blob/main/MEMORY.md)\n- [web/DESIGN-HARNESS.md](https://github.com/jshsakura/oc-piloci/blob/main/web/DESIGN-HARNESS.md)\n- [README.md](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n- [README.ko.md](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n</details>\n\n# Technology Stack\n\npiLoci is a memory curation system built on a modern, lightweight technology stack designed for privacy-focused local deployment. The architecture combines a Python-based API backend with a Next.js frontend, leveraging specialized databases for vector storage and session management.\n\n## Architecture Overview\n\n```mermaid\ngraph TB\n    subgraph \"Client Layer\"\n        ClaudeCode[\"Claude Code\"]\n        OpenCode[\"OpenCode\"]\n        Cursor[\"Cursor\"]\n    end\n    \n    subgraph \"Frontend Layer (Next.js)\"\n        WebApp[\"Next.js Web App<br/>:3000\"]\n        UI[\"shadcn/ui + TailwindCSS\"]\n    end\n    \n    subgraph \"Backend Layer (Python)\"\n        API[\"FastAPI + Uvicorn<br/>:8314\"]\n        MCP[\"MCP Server Tools\"]\n        Auth[\"Google OAuth\"]\n    end\n    \n    subgraph \"Storage Layer\"\n        SQLite[\"SQLite<br/>Identity Data\"]\n        LanceDB[\"LanceDB<br/>Vector Storage\"]\n        Redis[\"Redis<br/>Sessions\"]\n        FastEmbed[\"FastEmbed<br/>ONNX Embeddings\"]\n    end\n    \n    ClaudeCode --> MCP\n    OpenCode --> MCP\n    Cursor --> MCP\n    WebApp --> API\n    API --> SQLite\n    API --> LanceDB\n    API --> Redis\n    LanceDB --> FastEmbed\n```\n\n## Backend Technology\n\n### Core Framework\n\n| Component | Technology | Purpose |\n|-----------|------------|---------|\n| Web Framework | FastAPI | Async API server with automatic OpenAPI docs |\n| ASGI Server | Uvicorn | High-performance ASGI server |\n| ORM | SQLAlchemy | Database abstraction and migrations |\n| Validation | Pydantic | Data validation and serialization |\n\n资料来源：[pyproject.toml:1-50](https://github.com/jshsakura/oc-piloci/blob/main/pyproject.toml)\n\n### Data Storage\n\n#### SQLite — Identity Data\n\nSQLite serves as the primary relational database for storing user identity, project metadata, and session records. It provides ACID compliance with minimal overhead, making it ideal for single-instance deployments.\n\n```python\n# Simplified storage layer pattern\nfrom sqlalchemy import create_engine\nengine = create_engine(\"sqlite:///piloci.db\")\n```\n\n资料来源：[pyproject.toml:20-35](https://github.com/jshsakura/oc-piloci/blob/main/pyproject.toml)\n\n#### LanceDB — Vector Storage\n\nLanceDB is the vector database for semantic memory storage. It offers:\n\n- Columnar storage format optimized for ML workloads\n- Native Python bindings\n- Efficient similarity search on embedded vectors\n- Persistent storage with automatic indexing\n\n```python\n# From the LanceDB store implementation\nimport lancedb\ndb = lancedb.connect(\"./data/lancedb\")\ntable = db.open_table(\"memories\")\n```\n\n资料来源：[src/piloci/storage/lancedb_store.py:1-30](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/storage/lancedb_store.py)\n\nThe decision to use LanceDB was documented in ADR-014, citing advantages over alternatives like ChromaDB and Qdrant for local-first deployments.\n\n资料来源：[docs/ADR-014-lancedb-backend.md:1-25](https://github.com/jshsakura/oc-piloci/blob/main/docs/ADR-014-lancedb-backend.md)\n\n#### Redis — Session Management\n\nRedis handles ephemeral session data with millisecond latency. It supports:\n\n- Session token storage and validation\n- Real-time session state tracking\n- Pub/sub for distributed caching\n\n资料来源：[README.md:50-60](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n\n### Embeddings Engine\n\n**FastEmbed** provides ONNX-based embedding inference with these characteristics:\n\n| Feature | Description |\n|---------|-------------|\n| Runtime | ONNX (Open Neural Network Exchange) |\n| Deployment | On-device inference |\n| Speed | Optimized for CPU execution |\n| Privacy | No external API calls for embedding generation |\n\n资料来源：[README.md:55-60](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n\n```python\n# Embedding generation (conceptual)\nfrom fastembed import TextEmbedding\nmodel = TextEmbedding(model_name=\"BAAI/bge-small-en-v1.5\")\nembeddings = list(model.embed(documents))\n```\n\n资料来源：[pyproject.toml:40-50](https://github.com/jshsakura/oc-piloci/blob/main/pyproject.toml)\n\n### Authentication\n\n| Provider | Protocol | Library |\n|----------|----------|---------|\n| Google OAuth 2.0 | OAuth 2.0 | Authlib |\n\n资料来源：[pyproject.toml:25-40](https://github.com/jshsakura/oc-piloci/blob/main/pyproject.toml)\n\nGoogle OAuth requires proper `BASE_URL` configuration when behind a reverse proxy:\n\n```env\nBASE_URL=https://piloci.opencourse.kr\n```\n\n资料来源：[README.ko.md:100-110](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n\n## Frontend Technology\n\n### Framework & Runtime\n\n| Component | Technology | Version |\n|-----------|------------|---------|\n| Framework | Next.js | 15.x |\n| Language | TypeScript | 5.x |\n| Runtime | React | 19.x |\n| Package Manager | pnpm | 9.x |\n\n资料来源：[web/package.json:1-30](https://github.com/jshsakura/oc-piloci/blob/main/web/package.json)\n\n### UI Components\n\n| Layer | Library | Purpose |\n|-------|---------|---------|\n| CSS Framework | TailwindCSS | Utility-first styling |\n| Component Library | shadcn/ui | Accessible, customizable components |\n| Icons | Lucide React | Consistent icon system |\n| Styling Pattern | CSS Variables | Design token system via `--pi-*` variables |\n\n资料来源：[web/DESIGN-HARNESS.md:1-20](https://github.com/jshsakura/oc-piloci/blob/main/web/DESIGN-HARNESS.md)\n\n### Design System Pattern\n\nThe frontend follows a standardized page pattern with consistent CSS class naming:\n\n```tsx\n<AppShell>\n  <div className=\"pi-page\">\n    <section className=\"pi-page-hero\">\n      <p className=\"pi-eyebrow\">Area label</p>\n      <h1 className=\"pi-title mt-2\">Page title</h1>\n      <p className=\"pi-subtitle\">One sentence explaining the page.</p>\n    </section>\n    {/* Content sections */}\n  </div>\n</AppShell>\n```\n\n资料来源：[web/DESIGN-HARNESS.md:20-35](https://github.com/jshsakura/oc-piloci/blob/main/web/DESIGN-HARNESS.md)\n\n## Infrastructure & Deployment\n\n### Containerization\n\n```yaml\n# docker-compose.yml structure\nservices:\n  api:\n    build: .\n    ports:\n      - \"8314:8314\"\n  redis:\n    image: redis:alpine\n  # SQLite and LanceDB are file-based, mounted as volumes\n```\n\n资料来源：[MEMORY.md:1-20](https://github.com/jshsakura/oc-piloci/blob/main/MEMORY.md)\n\n### Hardware Targets\n\n| Platform | Use Case | Notes |\n|----------|----------|-------|\n| Raspberry Pi 5 | Primary target | Local deployment, Cloudflare Tunnel access |\n| x86_64 Server | Production | Multi-arch Docker images |\n| ARM64 | Edge computing | Supported via Docker multi-arch builds |\n\n资料来源：[README.ko.md:30-45](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n\n### Network Configuration\n\n| Port | Service | Protocol |\n|------|---------|----------|\n| 3000 | Next.js Frontend | HTTP/HTTPS |\n| 8314 | FastAPI Backend | HTTP (internal) |\n| 6379 | Redis | TCP (internal) |\n\n资料来源：[README.ko.md:95-105](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n\n### Reverse Proxy Support\n\n- **Cloudflare Tunnel** — Remote access without port forwarding\n- **Caddy** — Automatic HTTPS\n- **nginx** — Traditional reverse proxy\n- **Custom BASE_URL** — Required for OAuth callbacks behind proxies\n\n资料来源：[README.ko.md:95-100](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n\n## MCP Integration\n\nThe Model Context Protocol (MCP) enables AI assistants to interact with piLoci's memory system:\n\n```mermaid\ngraph LR\n    AI[\"AI Assistant<br/>(Claude Code, OpenCode, Cursor)\"]\n    MCP[\"MCP Server<br/>piloci.tools\"]\n    API[\"piLoci API<br/>:8314\"]\n    DB[\"Storage Layer\"]\n    \n    AI -->|\"MCP Protocol\"| MCP\n    MCP -->|\"REST API\"| API\n    API -->|\"Query/Store\"| DB\n```\n\n| Tool | Function |\n|------|----------|\n| `memory` | Store new memories from conversation context |\n| `recall` | Semantic search through stored memories |\n| `recommend` | Context-aware memory suggestions |\n\n资料来源：[README.md:20-40](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n\n## Technology Decision Records\n\nKey architectural decisions are documented in the `/docs/ADR-*` directory:\n\n| ADR | Topic | Status |\n|-----|-------|--------|\n| ADR-014 | LanceDB Backend Selection | Implemented |\n| ADR-015 | FastEmbed for Embeddings | Implemented |\n\n资料来源：[docs/ADR-014-lancedb-backend.md:1-10](https://github.com/jshsakura/oc-piloci/blob/main/docs/ADR-014-lancedb-backend.md)\n\n## Development Workflow\n\n### Local Development Stack\n\n```bash\n# Backend\nuv run pytest tests/ -v\nuv build\nuv run uvicorn src.piloci.api.main:app --reload --port 8314\n\n# Frontend\ncd web && pnpm install\npnpm dev    # Development server\npnpm build  # Production build\n```\n\n资料来源：[MEMORY.md:50-70](https://github.com/jshsakura/oc-piloci/blob/main/MEMORY.md)\n\n### Release Process\n\n```bash\n# 1. Update version in pyproject.toml (+0.0.1 patch unit)\n# 2. Validate\npytest tests/ -v\nuv build\n\n# 3. Tag and push\ngit tag v{version}\ngit push origin main v{version}\n```\n\n资料来源：[CLAUDE.md:25-40](https://github.com/jshsakura/oc-piloci/blob/main/CLAUDE.md)\n\nGitHub Actions `publish.yml` handles:\n- Version guard validation\n- Test execution gate\n- Web app build artifact\n- Multi-arch Docker image publishing\n- GitHub Release creation\n- PyPI package publication (`oc-piloci`)\n\n资料来源：[CLAUDE.md:20-30](https://github.com/jshsakura/oc-piloci/blob/main/CLAUDE.md)\n\n## Version Management\n\nVersion is managed as a single source of truth in `pyproject.toml`:\n\n```toml\n[project]\nversion = \"0.3.0\"\n```\n\nAll release artifacts (Docker images, PyPI packages, GitHub releases) derive their versions from this field. No separate version files should be modified.\n\n资料来源：[CLAUDE.md:10-25](https://github.com/jshsakura/oc-piloci/blob/main/CLAUDE.md)\n\n## Summary\n\n| Layer | Technology | Key Benefit |\n|-------|------------|-------------|\n| API | FastAPI + Uvicorn | Async performance, auto docs |\n| Database | SQLite | Zero-config, portable |\n| Vectors | LanceDB + FastEmbed | Local ML inference |\n| Sessions | Redis | Sub-millisecond latency |\n| Frontend | Next.js + shadcn/ui | Type-safe, accessible UI |\n| Auth | Google OAuth (Authlib) | Secure SSO |\n| Deployment | Docker + Cloudflare Tunnel | Edge-ready |\n\n---\n\n<a id='mcp-server'></a>\n\n## MCP Server Implementation\n\n### 相关页面\n\n相关主题：[API Routes](#api-routes), [Authentication & Security](#authentication), [Curator Pipeline](#curator-pipeline)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/piloci/mcp/server.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/mcp/server.py)\n- [src/piloci/mcp/streamable_http.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/mcp/streamable_http.py)\n- [src/piloci/mcp/sse.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/mcp/sse.py)\n- [src/piloci/mcp/session_state.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/mcp/session_state.py)\n- [src/piloci/tools/memory_tools.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/tools/memory_tools.py)\n- [src/piloci/tools/instinct_tools.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/tools/instinct_tools.py)\n</details>\n\n# MCP Server Implementation\n\n## Overview\n\nThe MCP (Model Context Protocol) Server in piLoci provides a standardized interface for AI clients (Claude Code, Claude Desktop, OpenCode, Cursor) to interact with piLoci's memory and cognitive services. This implementation exposes memory management tools, recall capabilities, and recommendation functions as MCP tools that can be invoked by AI assistants during conversations.\n\nThe MCP server architecture is designed for:\n\n- **Session-aware context management** — Tracking and persisting conversation context across sessions\n- **Tool-based memory operations** — Enabling LLMs to create, search, and retrieve memories\n- **Multi-client support** — Serving multiple AI clients simultaneously with isolated state\n- **Streaming communication** — Supporting both HTTP streaming and Server-Sent Events (SSE)\n\n资料来源：[README.md](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n\n---\n\n## Architecture\n\n### Component Overview\n\n```mermaid\ngraph TD\n    subgraph \"AI Clients\"\n        CC[Claude Code]\n        CD[Claude Desktop]\n        OC[OpenCode]\n        CU[Cursor]\n    end\n\n    subgraph \"MCP Server Layer\"\n        SERVER[MCP Server]\n        HTTP[Streamable HTTP]\n        SSE[Server-Sent Events]\n        SESSION[Session State Manager]\n    end\n\n    subgraph \"Tools Layer\"\n        MEM[memory_tools.py]\n        INST[instinct_tools.py]\n    end\n\n    subgraph \"Backend Services\"\n        API[API Routes]\n        DB[(SQLite)]\n        LANCE[(LanceDB)]\n        REDIS[(Redis)]\n    end\n\n    CC --> SERVER\n    CD --> SERVER\n    OC --> SERVER\n    CU --> SERVER\n    \n    SERVER --> HTTP\n    SERVER --> SSE\n    SERVER --> SESSION\n    \n    SERVER --> MEM\n    SERVER --> INST\n    \n    MEM --> API\n    INST --> API\n    \n    API --> DB\n    API --> LANCE\n    API --> REDIS\n```\n\n### Directory Structure\n\n```\nsrc/piloci/mcp/\n├── server.py           # Core MCP server implementation\n├── streamable_http.py  # HTTP streaming transport\n├── sse.py              # Server-Sent Events transport\n├── session_state.py    # Session state management\n└── __init__.py\n\nsrc/piloci/tools/\n├── memory_tools.py     # Memory-related MCP tools\n├── instinct_tools.py   # Instinct/recommendation tools\n└── __init__.py\n```\n\n资料来源：[README.md](https://github.com/jshsakura/oc-piloci/blob/main/README.md) and [CLAUDE.md](https://github.com/jshsakura/oc-piloci/blob/main/CLAUDE.md)\n\n---\n\n## MCP Server Core\n\n### Server Initialization\n\nThe main MCP server is implemented in `src/piloci/mcp/server.py`. It follows the standard MCP protocol implementation, providing:\n\n- Tool registration and schema management\n- Request/response handling\n- Protocol negotiation\n- Authentication integration\n\n### Tool Registration\n\nMCP tools are registered through `src/piloci/mcp/tools.py` and implemented in the `src/piloci/tools/` directory.\n\n资料来源：[CLAUDE.md](https://github.com/jshsakura/oc-piloci/blob/main/CLAUDE.md)\n\n---\n\n## Transport Layer\n\npiLoci supports two transport mechanisms for MCP communication:\n\n### Streamable HTTP\n\nLocated in `src/piloci/mcp/streamable_http.py`, this transport provides:\n\n- Bidirectional streaming over HTTP\n- Long-poll fallback for clients without streaming support\n- Request/response multiplexing\n\n### Server-Sent Events (SSE)\n\nLocated in `src/piloci/mcp/sse.py`, this transport provides:\n\n- Server-to-client event streaming\n- Lightweight alternative for simple use cases\n- Automatic reconnection handling\n\n### Transport Comparison\n\n| Feature | Streamable HTTP | SSE |\n|---------|-----------------|-----|\n| Bidirectional | ✅ Full duplex | ❌ Server-to-client only |\n| Latency | Low | Low |\n| Browser Compatibility | Requires polling fallback | Native browser support |\n| Use Case | Claude Code, Desktop | Simple integrations |\n\n---\n\n## Session State Management\n\n### Session State Module\n\nThe `src/piloci/mcp/session_state.py` module manages:\n\n- **Session lifecycle** — Creation, tracking, and cleanup of client sessions\n- **Context isolation** — Ensuring each client's memory space remains isolated\n- **State persistence** — Persisting session context across restarts\n\n```mermaid\nstateDiagram-v2\n    [*] --> Unauthenticated: Client connects\n    Unauthenticated --> Authenticated: Token validated\n    Authenticated --> Active: Session started\n    Active --> Active: Tools invoked\n    Active --> Paused: Client idle timeout\n    Paused --> Active: Client reconnects\n    Active --> [*]: Session ended\n```\n\n### Session Data Flow\n\n```mermaid\ngraph LR\n    A[AI Client] -->|Tool Request| B[MCP Server]\n    B -->|Lookup Session| C[Session State]\n    C -->|Session Context| B\n    B -->|Execute Tool| D[Tools Layer]\n    D -->|Results + Updated State| B\n    B -->|Response| A\n    B -->|Persist State| C\n```\n\n---\n\n## MCP Tools\n\n### Memory Tools\n\nImplemented in `src/piloci/tools/memory_tools.py`, these tools provide:\n\n| Tool Name | Purpose | Description |\n|-----------|---------|-------------|\n| `memory` | Create memories | Store new information from conversations |\n| `recall` | Search memories | Retrieve relevant memories based on query |\n| `recommend` | Context suggestions | Suggest relevant memories for current context |\n\n#### Tool Schema Requirements\n\nAccording to project conventions in `CLAUDE.md`:\n\n- Tool descriptions must be ≤ 120 characters\n- Parameter descriptions must be ≤ 80 characters\n- All schemas must pass `compact_schema()` validation\n\n资料来源：[CLAUDE.md](https://github.com/jshsakura/oc-piloci/blob/main/CLAUDE.md)\n\n### Instinct Tools\n\nImplemented in `src/piloci/tools/instinct_tools.py`, these tools provide:\n\n- Pattern recognition based on historical interactions\n- Proactive memory suggestions\n- Contextual recommendations\n\n### Tool Testing\n\nAll MCP tools must have corresponding tests:\n\n```\ntests/test_tools_*.py\n```\n\n资料来源：[CLAUDE.md](https://github.com/jshsakura/oc-piloci/blob/main/CLAUDE.md)\n\n---\n\n## Client Integration\n\n### Supported Clients\n\npiLoci's MCP server integrates with the following AI clients:\n\n| Client | Config File | MCP Tools | Hooks |\n|--------|-------------|-----------|-------|\n| Claude Desktop | `claude_desktop_config.json` | ✅ | N/A |\n| Claude Code | `~/.claude.json`, `.mcp.json` | ✅ | SessionStart, Stop |\n| OpenCode | `opencode.json` | ✅ | ❌ |\n| Cursor | Cursor config | ✅ | N/A |\n\n### Claude Code Integration\n\nFor Claude Code, the MCP server is installed via `src/piloci/installer.py`:\n\n```python\ninstall_codex_mcp(base_url: str, token: str, *, home: Path | None = None) -> Path\n```\n\nThis function:\n\n1. Downloads hook scripts to `~/.config/piloci/`\n2. Updates Claude Code's configuration files\n3. Registers the MCP server in `~/.claude.json`\n\n资料来源：[src/piloci/installer.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/installer.py)\n\n### File-Based Configuration\n\nThe installer creates the following structure:\n\n```\n~/.config/piloci/\n├── config.json          # Token + ingest/analyze URLs\n├── hook.py              # SessionStart catch-up script\n└── stop-hook.sh        # Stop live push script\n\n~/.claude.json           # MCP server entries (Claude Code)\n.mcp.json               # Additional MCP configuration\n```\n\n资料来源：[README.ko.md](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n\n---\n\n## Installation Flow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant CLI as piloci CLI\n    participant Installer as installer.py\n    participant Config as Config Files\n    participant MCPServer as MCP Server\n\n    User->>CLI: piloci install --client claude-code\n    CLI->>Installer: install_codex_mcp()\n    Installer->>Installer: Download hook scripts\n    Installer->>Config: Write config.json\n    Installer->>Config: Update ~/.claude.json\n    Installer->>MCPServer: Register MCP tools\n    Config-->>User: Installation complete\n```\n\n---\n\n## Configuration\n\n### Server Configuration\n\nThe MCP server is configured through environment variables:\n\n| Variable | Description | Example |\n|----------|-------------|---------|\n| `BASE_URL` | External HTTPS domain | `https://piloci.example.com` |\n| `PORT` | Server port (default: 8314) | `8314` |\n\n### Client-Side Configuration\n\nEach client requires specific configuration to connect to the MCP server:\n\n```json\n{\n  \"mcpServers\": {\n    \"piloci\": {\n      \"command\": \"python\",\n      \"args\": [\"-m\", \"piloci.mcp.server\"],\n      \"env\": {\n        \"PILOCI_TOKEN\": \"<user_token>\"\n      }\n    }\n  }\n}\n```\n\n---\n\n## API Endpoints\n\nThe MCP server exposes the following API routes (defined in `src/piloci/api/routes.py`):\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `/api/memories` | POST | Create a new memory (project-scoped) |\n| `/api/memories` | GET | List memories for context |\n| `/api/projects/{id}/freshness` | GET | Check project data freshness |\n| `/api/distillation/run-now` | POST | Trigger manual distillation |\n| `/api/budget/usage` | GET | Get external LLM budget usage |\n| `/api/preferences` | GET/PATCH | Get/update distillation preferences |\n\n资料来源：[web/lib/api.ts](https://github.com/jshsakura/oc-piloci/blob/main/web/lib/api.ts)\n\n---\n\n## Security Considerations\n\n### Token-Based Authentication\n\n- All MCP communications require a valid token\n- Tokens are stored in `~/.config/piloci/config.json` with mode `0600`\n- No token characters are exposed in logs or error messages\n\n### Data Isolation\n\n- Each client's data is isolated by session\n- Project-scoped memories prevent cross-project data leakage\n- User authentication via Google OAuth\n\n资料来源：[README.ko.md](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n\n---\n\n## Testing\n\n### Test Coverage\n\nMCP functionality is tested via:\n\n- `tests/test_tools_*.py` — Tool-specific tests\n- `tests/test_vault_cache.py` — Vault and caching tests\n\n### Test Commands\n\n```bash\n# Run all MCP-related tests\nuv run pytest tests/test_tools_*.py -v\n\n# Run with coverage\nuv run pytest tests/test_vault_cache.py -v --no-cov\n```\n\n资料来源：[MEMORY.md](https://github.com/jshsakura/oc-piloci/blob/main/MEMORY.md)\n\n---\n\n## Development Guidelines\n\n### Adding New MCP Tools\n\n1. Implement in `src/piloci/tools/`\n2. Register in `src/piloci/mcp/tools.py`\n3. Keep descriptions within character limits\n4. Validate with `compact_schema()`\n5. Add tests in `tests/test_tools_*.py`\n\n### Code Quality\n\n| Tool | Configuration |\n|------|----------------|\n| Formatter | black (line-length=100) |\n| Linter | ruff |\n| Import sorting | isort (profile=black) |\n\nRun pre-commit hooks before committing:\n\n```bash\nuv run black .\nuv run ruff check .\nuv run isort .\n```\n\n资料来源：[CLAUDE.md](https://github.com/jshsakura/oc-piloci/blob/main/CLAUDE.md)\n\n---\n\n## See Also\n\n- [API Routes Implementation](./api-routes.md)\n- [Memory Module](./memory.md)\n- [Frontend Architecture](../web/architecture.md)\n- [Installation Guide](./installation.md)\n\n---\n\n<a id='authentication'></a>\n\n## Authentication & Security\n\n### 相关页面\n\n相关主题：[MCP Server Implementation](#mcp-server), [API Routes](#api-routes), [Database Models](#database-models)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/piloci/auth/oauth.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/auth/oauth.py)\n- [src/piloci/auth/crypto.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/auth/crypto.py)\n- [src/piloci/auth/session.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/auth/session.py)\n- [src/piloci/auth/middleware.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/auth/middleware.py)\n- [src/piloci/api/routes.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/api/routes.py)\n- [src/piloci/db/models.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/db/models.py)\n- [src/piloci/auth/install_pairing.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/auth/install_pairing.py)\n</details>\n\n# Authentication & Security\n\npiLoci implements a comprehensive authentication and security system supporting multiple OAuth providers, encrypted token storage, Redis-based session management, and JWT authentication for API access. The system is designed for self-hosted deployment on resource-constrained environments like Raspberry Pi devices while maintaining enterprise-grade security practices.\n\n## Architecture Overview\n\nThe authentication system consists of several interconnected layers:\n\n```mermaid\ngraph TD\n    A[Client] --> B[Next.js Frontend]\n    A --> C[Python CLI Client]\n    B --> D[FastAPI Backend /api/*]\n    C --> D\n    D --> E[OAuth Providers<br/>Google/Kakao/Naver]\n    D --> F[Redis<br/>Session Store]\n    D --> G[SQLite<br/>User Database]\n    D --> H[LanceDB<br/>Memory Storage]\n    G --> I[Encrypted OAuth Tokens<br/>Fernet + JWT Secret]\n```\n\n资料来源：[src/piloci/auth/oauth.py:1-50]()\n\n## OAuth Authentication\n\npiLoci supports authentication through multiple OAuth 2.0 providers, allowing users to sign in with existing accounts rather than creating new credentials.\n\n### Supported Providers\n\n| Provider | Auth URL | Token URL | User Info Endpoint | Scopes |\n|----------|----------|-----------|-------------------|--------|\n| Google | `https://accounts.google.com/o/oauth2/v2/auth` | `https://oauth2.googleapis.com/token` | `https://www.googleapis.com/oauth2/v3/userinfo` | `openid email profile` |\n| Kakao | `https://kauth.kakao.com/oauth/authorize` | `https://kauth.kakao.com/oauth/token` | `https://kapi.kakao.com/v2/user/me` | `profile_nickname account_email` |\n| Naver | `https://nid.naver.com/oauth2.0/authorize` | `https://nid.naver.com/oauth2.0/token` | `https://openapi.naver.com/v1/nid/me` | (none) |\n\n资料来源：[src/piloci/auth/oauth.py:20-45]()\n\n### OAuth Flow\n\n```mermaid\nsequenceDiagram\n    participant U as User\n    participant F as Frontend\n    participant B as Backend\n    participant P as OAuth Provider\n    participant R as Redis\n\n    U->>F: Click \"Login with Provider\"\n    F->>B: GET /api/auth/providers\n    B->>F: Return available providers\n    F->>U: Redirect to OAuth authorization URL\n    U->>P: Authorize application\n    P->>U: Redirect with authorization code\n    U->>B: GET /auth/{provider}/callback?code=XXX\n    B->>P: Exchange code for tokens\n    P->>B: Access token + Refresh token\n    B->>B: Encrypt tokens with Fernet\n    B->>G: Upsert user in SQLite\n    B->>R: Create Redis session\n    B->>U: Set session cookie, redirect to dashboard\n```\n\n### Provider Configuration\n\nEach OAuth provider is configured using a `ProviderConfig` dataclass that encapsulates all provider-specific settings:\n\n```python\n@dataclass\nclass ProviderConfig:\n    name: str\n    auth_url: str\n    token_url: str\n    userinfo_url: str\n    scopes: str\n    extract_user: Callable[[dict], OAuthUserInfo]\n```\n\n资料来源：[src/piloci/auth/oauth.py:1-20]()\n\n### Building Authorization URLs\n\nThe `build_auth_url()` function constructs OAuth authorization URLs with provider-specific parameters:\n\n```python\ndef build_auth_url(provider: str, client_id: str, redirect_uri: str, state: str) -> str:\n    provider_config = _get_provider(provider)\n    params: dict[str, str] = {\n        \"client_id\": client_id,\n        \"redirect_uri\": redirect_uri,\n        \"response_type\": \"code\",\n        \"state\": state,\n    }\n    if provider_config.scopes:\n        params[\"scope\"] = provider_config.scopes\n    params.update(provider_config.extra_auth_params)\n    return f\"{provider_config.auth_url}?{urlencode(params)}\"\n```\n\n资料来源：[src/piloci/auth/oauth.py:67-80]()\n\n### User Information Extraction\n\nEach provider returns user data in different formats. The `extract_user` callback normalizes this data into a standard `OAuthUserInfo` structure:\n\n```python\n@dataclass\nclass OAuthUserInfo:\n    provider: str\n    provider_user_id: str\n    email: str | None\n    name: str | None\n```\n\nProvider-specific extractors handle the normalization:\n- `_extract_github_user()` for GitHub (if configured)\n- `_extract_kakao_user()` for Kakao API v2 response format\n- `_extract_naver_user()` for Naver's response envelope\n\n资料来源：[src/piloci/auth/oauth.py:1-50]()\n\n## Encrypted Token Storage\n\nOAuth tokens are encrypted before storage to prevent exposure even if the database is compromised.\n\n### Encryption Mechanism\n\npiLoci uses **Fernet symmetric encryption** with a key derived from the JWT secret:\n\n```mermaid\ngraph LR\n    A[JWT Secret<br/>from settings] --> B[Key Derivation<br/>Function]\n    B --> C[Fernet Key<br/>32-byte key]\n    C --> D[Fernet.encrypt<br/>OAuth Token]\n    C --> E[Fernet.decrypt<br/>Stored Token]\n```\n\n资料来源：[src/piloci/auth/crypto.py:1-20]()\n\n### Token Storage Schema\n\nThe `User` model in SQLite stores encrypted OAuth credentials:\n\n| Column | Type | Description |\n|--------|------|-------------|\n| `oauth_provider` | String (nullable) | Provider name (google/kakao/naver) |\n| `oauth_provider_user_id` | String (nullable) | User ID from the provider |\n| `oauth_access_token` | String (nullable, encrypted) | Encrypted OAuth access token |\n| `oauth_refresh_token` | String (nullable, encrypted) | Encrypted OAuth refresh token |\n\n资料来源：[src/piloci/db/models.py:1-100]()\n\n### Token Encryption Flow\n\n```python\nasync def upsert_oauth_user(\n    provider: str,\n    provider_user_id: str,\n    access_token: str,\n    refresh_token: str | None,\n    email: str | None,\n    name: str | None,\n) -> User:\n    # Encrypt tokens before storage\n    encrypted_access = encrypt_token(access_token)\n    encrypted_refresh = encrypt_token(refresh_token) if refresh_token else None\n    \n    # Upsert user with encrypted tokens\n    ...\n```\n\n资料来源：[src/piloci/auth/oauth.py:100-150]()\n\n## Session Management\n\nSessions are managed through Redis for fast, stateless authentication validation.\n\n### Session Architecture\n\n```mermaid\ngraph TD\n    A[Request] --> B[Auth Middleware]\n    B --> C{Check Session Cookie}\n    C -->|No Cookie| D[Return 401]\n    C -->|Has Cookie| E[Query Redis]\n    E --> F{Valid Session?}\n    F -->|No| D\n    F -->|Yes| G[Attach User to Request]\n    G --> H[Proceed to Route Handler]\n```\n\n资料来源：[src/piloci/auth/middleware.py:1-50]()\n\n### Session Structure\n\nSessions stored in Redis contain the authenticated user's identity:\n\n```json\n{\n  \"user_id\": \"uuid-string\",\n  \"email\": \"user@example.com\",\n  \"created_at\": \"2024-01-01T00:00:00Z\",\n  \"expires_at\": \"2024-01-01T12:00:00Z\"\n}\n```\n\n资料来源：[src/piloci/auth/session.py:1-50]()\n\n### Provider Disconnect Flow\n\nUsers can disconnect OAuth providers from their account. The disconnect process:\n\n1. Validates the logged-in Redis session\n2. Verifies password presence as a safety check\n3. Revokes the provider token remotely via `revoke_provider_token()`\n4. Clears local OAuth fields even if remote revoke fails\n\n资料来源：[src/piloci/api/routes.py:1-100]()\n\n```mermaid\nsequenceDiagram\n    participant U as User\n    participant F as Frontend\n    participant B as Backend\n    participant R as Redis\n    participant P as OAuth Provider\n\n    U->>F: Click \"Disconnect {provider}\"\n    F->>B: POST /auth/{provider}/disconnect\n    B->>R: Validate session\n    B->>B: Check password exists\n    B->>P: Revoke provider token\n    P-->>B: Revocation confirmation\n    B->>B: Encrypt/clear OAuth fields\n    B->>R: Update session\n    B-->>F: Success response\n```\n\n## API Authentication\n\n### Provider Discovery Endpoint\n\nThe frontend dynamically discovers available OAuth providers:\n\n```\nGET /api/auth/providers\n```\n\nReturns the list of configured providers based on environment credentials:\n\n```json\n{\n  \"providers\": [\"google\", \"kakao\", \"naver\"],\n  \"local\": true\n}\n```\n\n资料来源：[src/piloci/api/routes.py:100-200]()\n\n### Authentication Callback Routes\n\n| Route | Method | Description |\n|-------|--------|-------------|\n| `/auth/{provider}` | GET | Initiate OAuth flow |\n| `/auth/{provider}/callback` | GET | Handle OAuth callback |\n| `/auth/{provider}/disconnect` | POST | Disconnect provider |\n\n资料来源：[src/piloci/api/routes.py:200-300]()\n\n## Rate Limiting\n\nAuthentication endpoints are protected by rate limiting to prevent brute-force attacks:\n\n```python\n# Rate limit configuration in tests\n@pytest.mark.skip(reason=\"regression guard — re-enabled after config freeze\")\nasync def test_auth_rate_limits():\n    ...\n```\n\n资料来源：[MEMORY.md:1-50]()\n\nRate limit tests verify:\n- Provider status route shape consistency\n- Proper rate limiting headers\n- Appropriate 429 responses after threshold exceeded\n\n## Security Configuration\n\n### Environment Variables\n\n| Variable | Required | Description |\n|----------|----------|-------------|\n| `JWT_SECRET` | Yes | Secret key for JWT signing and Fernet encryption |\n| `SESSION_SECRET` | Yes | Redis session encryption key |\n| `BASE_URL` | Yes (production) | External HTTPS domain for OAuth callbacks |\n| `GOOGLE_CLIENT_ID` | For Google OAuth | Google OAuth application client ID |\n| `GOOGLE_CLIENT_SECRET` | For Google OAuth | Google OAuth application secret |\n| `KAKAO_CLIENT_ID` | For Kakao OAuth | Kakao OAuth application client ID |\n| `KAKAO_CLIENT_SECRET` | For Kakao OAuth | Kakao OAuth application secret |\n| `NAVER_CLIENT_ID` | For Naver OAuth | Naver OAuth application client ID |\n| `NAVER_CLIENT_SECRET` | For Naver OAuth | Naver OAuth application secret |\n\n### OAuth Redirect URI Configuration\n\nWhen deploying behind a reverse proxy, the `BASE_URL` environment variable must be set:\n\n```env\nBASE_URL=https://piloci.opencourse.kr\n```\n\nGoogle OAuth redirect URIs must match exactly. Register this callback in Google Cloud Console:\n\n```\nhttps://piloci.opencourse.kr/auth/google/callback\n```\n\n资料来源：[README.ko.md:1-50]()\n\nWithout `BASE_URL`, the backend may construct callback URLs using local/internal request hosts, causing `redirect_uri_mismatch` errors even when credentials are correct.\n\n## Development Guidelines\n\n### Security Non-Negotiables\n\nPer project development rules:\n\n- All LanceDB queries **must** filter by `(user_id, project_id)` — omission causes data leakage\n- Passwords: **argon2id only** — bcrypt is prohibited\n- JWT secret and session secret must come from environment variables or Docker secrets only — no hardcoding in code\n- Raw SQL is prohibited — use SQLAlchemy ORM exclusively\n- All user input must be validated through Pydantic schemas before processing\n\n资料来源：[CLAUDE.md:1-50]()\n\n### Testing Authentication\n\nRun auth-related tests with:\n\n```bash\nuv run pytest tests/test_auth_rate_limits.py -v --no-cov\n```\n\n资料来源：[MEMORY.md:50-100]()\n\n## Token-Based CLI Authentication\n\nFor the Python CLI client, token-based authentication is used:\n\n```python\nfrom piloci_client import (\n    PilociError,           # base — all SDK errors\n    PilociAuthError,       # HTTP 401\n    PilociPermissionError, # HTTP 403\n    PilociValidationError, # HTTP 422\n    PilociServerError,     # HTTP 5xx\n)\n```\n\n资料来源：[clients/python/README.md:1-50]()\n\n### Install Pairing Flow\n\nThe system supports device code flow for CLI authentication:\n\n1. CLI displays a device code (`ABCD-1234`)\n2. User opens `/device` page in browser\n3. User logs in and approves\n4. CLI polls and receives token\n5. CLI auto-configures detected clients\n\n资料来源：[src/piloci/auth/install_pairing.py:1-50]()\n\n## Password-Based Authentication\n\n### Password Reset Flow\n\nThe frontend provides password reset functionality at `/forgot-password`:\n\n```tsx\n<Link href=\"/forgot-password\" className=\"text-sm text-muted-foreground\">\n  {t.login.forgotPassword}\n</Link>\n```\n\n资料来源：[web/app/login/login-client.tsx:1-50]()\n\nError messages display in styled containers:\n\n```tsx\n<div className=\"bg-red-50 p-3 text-sm text-red-800 dark:bg-red-950\">\n  {serverError}\n</div>\n```\n\n资料来源：[web/app/forgot-password/page.tsx:1-50]()\n\n## Summary\n\npiLoci's authentication and security system provides:\n\n1. **Multi-provider OAuth** — Google, Kakao, Naver with provider-specific user extraction\n2. **Encrypted token storage** — Fernet encryption using JWT secret-derived keys\n3. **Redis session management** — Fast, stateless session validation\n4. **Rate limiting** — Protection against brute-force attacks\n5. **Provider disconnect** — Full OAuth account unlinking support\n6. **Device code flow** — Secure CLI authentication for headless environments\n7. **Production-ready configuration** — BASE_URL support for reverse proxy deployments\n\nAll authentication components follow the security non-negotiables defined in project development rules, ensuring consistent protection against common vulnerabilities.\n\n---\n\n<a id='api-routes'></a>\n\n## API Routes\n\n### 相关页面\n\n相关主题：[MCP Server Implementation](#mcp-server), [Authentication & Security](#authentication), [Storage Layer](#storage-layer)\n\n<details>\n<summary>Related Source Files</summary>\n\nThe following source files are used to generate this documentation:\n\n- [src/piloci/api/routes.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/api/routes.py)\n- [src/piloci/api/v1.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/api/v1.py)\n- [src/piloci/api/team_routes.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/api/team_routes.py)\n- [src/piloci/api/audit.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/api/audit.py)\n- [src/piloci/api/data_portability.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/api/data_portability.py)\n- [src/piloci/api/distillation_routes.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/api/distillation_routes.py)\n- [src/piloci/api/ratelimit.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/api/ratelimit.py)\n</details>\n\n# API Routes\n\n## Overview\n\nThe API Routes module in oc-piloci provides a comprehensive REST API layer for the platform, enabling programmatic interaction with agent orchestration, team management, auditing, data operations, and model distillation capabilities. The API follows a modular architecture with separate route handlers for different functional domains.\n\nThe routing system is built on FastAPI principles and organizes endpoints by API version and functional area, providing a clean separation of concerns while maintaining a unified API surface.\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[Client Request] --> B[API Gateway]\n    B --> C[v1 Routes]\n    C --> D[Team Routes]\n    C --> E[Audit Routes]\n    C --> F[Data Portability Routes]\n    C --> G[Distillation Routes]\n    D --> H[Rate Limiter]\n    E --> H\n    F --> H\n    G --> H\n    H --> I[Backend Services]\n```\n\n## Route Organization\n\n### Core Route Files\n\n| File | Purpose | Primary Responsibility |\n|------|---------|------------------------|\n| `routes.py` | Main router configuration | Entry point, aggregation of sub-routers |\n| `v1.py` | API v1 versioning | Version-specific route mounting |\n| `team_routes.py` | Team management | Team CRUD, membership, permissions |\n| `audit.py` | Audit logging | Action tracking, audit trail retrieval |\n| `data_portability.py` | Data operations | Import/export, data migration |\n| `distillation_routes.py` | Model distillation | Knowledge distillation workflows |\n| `ratelimit.py` | Rate limiting | Request throttling, quota management |\n\n资料来源：[src/piloci/api/routes.py]()\n\n## Versioned API Structure\n\nThe API uses URL-based versioning with v1 as the current stable version.\n\n```mermaid\ngraph LR\n    A[/api/v1/*] --> B[Version Router]\n    B --> C[Team Endpoints]\n    B --> D[Audit Endpoints]\n    B --> E[Data Endpoints]\n    B --> F[Distillation Endpoints]\n```\n\n### V1 Router Configuration\n\nThe v1 router serves as the main container for all v1 API endpoints, mounting sub-routers for each functional domain.\n\n资料来源：[src/piloci/api/v1.py]()\n\n## Team Routes\n\nTeam routes handle all team-related operations including team creation, member management, and team-level configurations.\n\n### Supported Operations\n\n| Operation | HTTP Method | Endpoint Pattern |\n|-----------|-------------|------------------|\n| List teams | GET | `/teams` |\n| Create team | POST | `/teams` |\n| Get team | GET | `/teams/{team_id}` |\n| Update team | PUT | `/teams/{team_id}` |\n| Delete team | DELETE | `/teams/{team_id}` |\n| Add member | POST | `/teams/{team_id}/members` |\n| Remove member | DELETE | `/teams/{team_id}/members/{user_id}` |\n| List members | GET | `/teams/{team_id}/members` |\n\n资料来源：[src/piloci/api/team_routes.py]()\n\n## Audit Routes\n\nAudit routes provide access to the system's audit trail, enabling compliance and monitoring use cases.\n\n### Audit Features\n\n- Action logging for all significant system events\n- Queryable audit history by time range\n- Filtering by user, team, or action type\n- Audit report generation\n\n### Common Audit Endpoints\n\n| Endpoint | Description |\n|----------|-------------|\n| `GET /audit/events` | List audit events with filtering |\n| `GET /audit/events/{event_id}` | Get specific audit event details |\n| `GET /audit/teams/{team_id}` | Get team-specific audit history |\n\n资料来源：[src/piloci/api/audit.py]()\n\n## Data Portability Routes\n\nData portability endpoints support import and export operations for data migration and backup purposes.\n\n### Data Operations\n\n| Operation | Description |\n|-----------|-------------|\n| Export data | Generate downloadable data archives |\n| Import data | Upload and process data packages |\n| Data format conversion | Transform between supported formats |\n| Partial sync | Incremental data synchronization |\n\n资料来源：[src/piloci/api/data_portability.py]()\n\n## Distillation Routes\n\nDistillation routes manage model knowledge distillation workflows, enabling the transfer of knowledge from larger models to smaller, more efficient ones.\n\n### Distillation Workflow\n\n```mermaid\ngraph TD\n    A[Teacher Model] --> B[Distillation Request]\n    C[Student Model] --> B\n    B --> D[Distillation Job]\n    D --> E[Knowledge Transfer]\n    E --> F[Trained Student Model]\n    F --> G[Validation]\n    G --> H[Model Registry]\n```\n\n### Distillation Endpoints\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `/distillation/jobs` | POST | Create new distillation job |\n| `/distillation/jobs` | GET | List distillation jobs |\n| `/distillation/jobs/{job_id}` | GET | Get job status |\n| `/distillation/jobs/{job_id}` | DELETE | Cancel running job |\n\n资料来源：[src/piloci/api/distillation_routes.py]()\n\n## Rate Limiting\n\nThe rate limiting module protects the API from abuse and ensures fair resource allocation across clients.\n\n### Rate Limit Configuration\n\n| Parameter | Default | Description |\n|-----------|---------|-------------|\n| Requests per minute | 60 | Maximum requests per client per minute |\n| Burst allowance | 10 | Temporary burst capacity |\n| Window type | Sliding | Rate limit window algorithm |\n\n### Rate Limit Headers\n\n| Header | Description |\n|--------|-------------|\n| `X-RateLimit-Limit` | Maximum requests allowed |\n| `X-RateLimit-Remaining` | Requests remaining in window |\n| `X-RateLimit-Reset` | Unix timestamp when limit resets |\n\n资料来源：[src/piloci/api/ratelimit.py]()\n\n## Request/Response Patterns\n\n### Standard Response Format\n\n```json\n{\n  \"success\": true,\n  \"data\": { },\n  \"meta\": {\n    \"request_id\": \"uuid\",\n    \"timestamp\": \"ISO8601\"\n  }\n}\n```\n\n### Error Response Format\n\n```json\n{\n  \"success\": false,\n  \"error\": {\n    \"code\": \"ERROR_CODE\",\n    \"message\": \"Human readable message\"\n  },\n  \"meta\": {\n    \"request_id\": \"uuid\",\n    \"timestamp\": \"ISO8601\"\n  }\n}\n```\n\n## Authentication\n\nAPI routes require authentication via Bearer tokens in the Authorization header:\n\n```\nAuthorization: Bearer <token>\n```\n\n## Common Parameters\n\n| Parameter | Location | Type | Description |\n|-----------|----------|------|-------------|\n| `team_id` | Path/Query | string | Team identifier |\n| `user_id` | Path/Query | string | User identifier |\n| `page` | Query | integer | Pagination offset |\n| `page_size` | Query | integer | Results per page |\n| `sort_by` | Query | string | Sort field |\n| `order` | Query | string | Sort direction (asc/desc) |\n\n## Middleware Stack\n\n```mermaid\ngraph TD\n    A[Request] --> B[Rate Limit Middleware]\n    B --> C[Auth Middleware]\n    C --> D[Validation Middleware]\n    D --> E[Route Handler]\n    E --> F[Response]\n```\n\n## Usage Examples\n\n### Creating a Team\n\n```bash\ncurl -X POST https://api.example.com/v1/teams \\\n  -H \"Authorization: Bearer <token>\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"ML Research\",\n    \"description\": \"Machine learning research team\"\n  }'\n```\n\n### Listing Audit Events\n\n```bash\ncurl -X GET \"https://api.example.com/v1/audit/events?team_id=123&from=2024-01-01\" \\\n  -H \"Authorization: Bearer <token>\"\n\n---\n\n<a id='curator-pipeline'></a>\n\n## Curator Pipeline\n\n### 相关页面\n\n相关主题：[Storage Layer](#storage-layer), [MCP Server Implementation](#mcp-server)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/piloci/curator/__init__.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/__init__.py)\n- [src/piloci/curator/distillation_worker.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/distillation_worker.py)\n- [src/piloci/curator/gemma.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/gemma.py)\n- [src/piloci/curator/extraction.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/extraction.py)\n- [src/piloci/curator/prefilter.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/prefilter.py)\n- [src/piloci/curator/backlog.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/backlog.py)\n- [src/piloci/curator/budget.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/budget.py)\n- [src/piloci/curator/scheduler.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/scheduler.py)\n- [src/piloci/curator/vault.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/vault.py)\n- [src/piloci/curator/weekly_digest_worker.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/weekly_digest_worker.py)\n</details>\n\n# Curator Pipeline\n\nThe Curator Pipeline is the core memory processing engine of piLoci. It transforms raw AI session transcripts into structured, embeddable memory entries through a multi-stage pipeline that includes extraction, distillation, prefiltering, budgeting, scheduling, and vault storage.\n\n## Overview\n\nThe curator system is designed to run on resource-constrained devices (such as Raspberry Pi 5) while leveraging both local ONNX-based inference (via fastembed) and external LLM APIs for complex memory extraction tasks. It operates as a background worker that continuously processes session backlog, respects resource constraints (temperature, load), and manages external API budgets.\n\n```mermaid\ngraph TD\n    A[Session Transcript Ingested] --> B[Backlog Queue]\n    B --> C[Prefilter Stage]\n    C --> D{Filter Pass?}\n    D -->|No| E[Skip Memory Extraction]\n    D -->|Yes| F[Distillation Worker]\n    F --> G{Resource Available?}\n    G -->|No| H[Wait/Reschedule]\n    G -->|Yes| I[Extraction via Gemma/External LLM]\n    I --> J[Budget Check]\n    J -->|Over Budget| K[Bypass External LLM]\n    J -->|OK| L[Store to Vault]\n    L --> M[Embed + Index via LanceDB]\n    M --> N[Memory Available for Recall]\n    \n    H --> B\n```\n\n## Pipeline Architecture\n\nThe curator module is organized into distinct components, each responsible for a specific stage of the memory processing pipeline.\n\n### Core Components\n\n| Component | File | Responsibility |\n|-----------|------|----------------|\n| `Backlog` | `backlog.py` | Queue management for pending session processing |\n| `Prefilter` | `prefilter.py` | Fast-pass filtering before expensive extraction |\n| `DistillationWorker` | `distillation_worker.py` | Orchestrates the extraction workflow |\n| `Scheduler` | `scheduler.py` | Resource-aware scheduling (temperature, load) |\n| `Budget` | `budget.py` | External LLM API budget tracking and limits |\n| `Extraction` | `extraction.py` | Memory extraction logic via Gemma or external LLM |\n| `Vault` | `vault.py` | Persistent storage and retrieval of memories |\n| `WeeklyDigestWorker` | `weekly_digest_worker.py` | Periodic digest generation |\n\n## Pipeline Stages\n\n### Stage 1: Backlog Management\n\nThe backlog system (`Backlog` class) maintains a queue of sessions awaiting memory extraction. Sessions enter the backlog when they are ingested, and are processed in FIFO order unless priority adjustments are applied.\n\n**Key operations:**\n- Add new sessions to pending queue\n- Track processing state per session\n- Handle retry logic for failed extractions\n- Provide metrics for dashboard panels (pending count, processed count)\n\n资料来源：[src/piloci/curator/backlog.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/backlog.py)\n\n### Stage 2: Prefilter\n\nThe prefilter (`Prefilter` class) performs fast, lightweight checks to determine whether a session warrants full memory extraction. This prevents wasteful LLM calls on sessions that are unlikely to contain valuable memories.\n\n**Prefilter criteria may include:**\n- Session length thresholds\n- Client type filtering (Claude Code vs OpenCode)\n- Project-specific rules\n- Temporal patterns\n\n资料来源：[src/piloci/curator/prefilter.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/prefilter.py)\n\n### Stage 3: Resource-Aware Scheduling\n\nThe scheduler (`Scheduler` class) ensures that distillation work only proceeds when the host system has adequate resources. It monitors:\n\n| Parameter | Description | Default Behavior |\n|-----------|-------------|------------------|\n| Temperature Ceiling | SoC temperature threshold | Worker halts when exceeded |\n| Load Average | 1-minute system load | Worker halts above threshold |\n| Overflow Threshold | Queue depth before bypass | Triggers external LLM bypass |\n\n```python\n# Distillation settings schema (from API)\nclass DistillationPreferences:\n    temp_ceiling: float      # °C threshold\n    load_ceiling: float      # 1-min load average\n    overflow: int            # queue length threshold\n    budget_monthly_usd: float # external LLM budget limit\n```\n\n资料来源：[src/piloci/curator/scheduler.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/scheduler.py)\n\n资料来源：[web/lib/api.ts](https://github.com/jshsakura/oc-piloci/blob/main/web/lib/api.ts) (DistillationPreferences type)\n\n### Stage 4: Budget Management\n\nThe budget system (`Budget` class) tracks external LLM API usage against configured monthly limits. When the budget is exhausted, the system bypasses external LLM calls and relies solely on local Gemma inference.\n\n**Budget lifecycle:**\n1. Check current month-to-date spend\n2. Compare against configured limit\n3. Allow or block external LLM calls\n4. Track per-project allocation if applicable\n\n资料来源：[src/piloci/curator/budget.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/budget.py)\n\n### Stage 5: Memory Extraction\n\nThe extraction stage (`Extraction` class) is the core of the pipeline. It analyzes session transcripts and extracts structured memories using either:\n\n1. **Local Gemma Model** - ONNX-based inference using fastembed\n2. **External LLM API** - Fallback when local resources insufficient or for complex extraction\n\n#### Gemma Integration\n\nThe `Gemma` class wraps local Gemma model inference for on-device memory extraction:\n\n- Loads ONNX model for fast, private inference\n- No API calls required for basic extraction\n- Optimized for Raspberry Pi 5 hardware\n\n资料来源：[src/piloci/curator/gemma.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/gemma.py)\n\n#### Extraction Pipeline\n\n```mermaid\ngraph LR\n    A[Transcript] --> B[Context Windowing]\n    B --> C{Model Selection}\n    C -->|Local| D[Gemma Inference]\n    C -->|Complex| E[External LLM]\n    D --> F[Parse Memory Structure]\n    E --> F\n    F --> G[Validate Memory Schema]\n    G --> H[Return Memory Entries]\n```\n\nExtraction produces memory entries with:\n- `content`: The extracted memory text\n- `tags`: Categorization tags\n- `project_id`: Associated project scope\n- `session_id`: Source session reference\n- `metadata`: Extraction confidence, model used, timing\n\n资料来源：[src/piloci/curator/extraction.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/extraction.py)\n\n### Stage 6: Vault Storage\n\nThe vault (`Vault` class) provides persistent storage for extracted memories. Memories are stored with embeddings for similarity search and retrieval.\n\n**Storage architecture:**\n- Primary storage: LanceDB for vector embeddings\n- Metadata index: SQLite for structured queries\n- File-based notes: Markdown files for Obsidian export\n\n```bash\n# Export workspace to Obsidian vault\ncurl -sS http://localhost:8314/api/projects/slug/my-project/workspace\n```\n\n资料来源：[src/piloci/curator/vault.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/vault.py)\n\n## Distillation Worker\n\nThe distillation worker (`DistillationWorker` class) orchestrates the entire pipeline. It runs as a background task that:\n\n1. Polls the backlog for pending sessions\n2. Applies prefilter checks\n3. Waits for resource availability via scheduler\n4. Executes extraction (Gemma → external LLM fallback)\n5. Stores results to vault\n6. Updates session status and metrics\n\n### Manual Trigger\n\nThe pipeline supports manual trigger via API:\n\n```typescript\n// From web/lib/api.ts\nrunDistillationNow: () =>\n  request<{ woken: boolean; note: string }>(\"/api/distillation/run-now\", {\n    method: \"POST\",\n  }),\n```\n\n资料来源：[src/piloci/curator/distillation_worker.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/distillation_worker.py)\n\n## Weekly Digest\n\nThe weekly digest worker (`WeeklyDigestWorker`) generates periodic summaries of memory activity:\n\n- Aggregates memories created during the week\n- Generates project-level summaries\n- Creates digest notifications for users\n- Runs on configurable schedule (default: weekly)\n\n资料来源：[src/piloci/curator/weekly_digest_worker.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/weekly_digest_worker.py)\n\n## Configuration\n\n### Distillation Preferences\n\n| Setting | Type | Description |\n|---------|------|-------------|\n| `temp_ceiling` | float | Temperature threshold (°C) for halting worker |\n| `load_ceiling` | float | Load average threshold for halting worker |\n| `overflow` | int | Queue length threshold triggering external LLM bypass |\n| `budget_monthly_usd` | float | Monthly budget for external LLM calls (USD) |\n\n### API Endpoints\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `/api/distillation/run-now` | POST | Manually trigger distillation cycle |\n| `/api/preferences` | GET | Retrieve distillation preferences |\n| `/api/preferences` | PATCH | Update distillation preferences |\n| `/api/budget/usage` | GET | Get current budget usage |\n\n资料来源：[web/lib/api.ts](https://github.com/jshsakura/oc-piloci/blob/main/web/lib/api.ts)\n\n## State Machine\n\n```mermaid\nstateDiagram-v2\n    [*] --> Idle\n    Idle --> Checking: Session Ingested\n    Checking --> PrefilterPass: Apply Prefilter\n    PrefilterPass --> Idle: Filter Reject\n    PrefilterPass --> Waiting: Filter Pass\n    Waiting --> ResourceAvailable: Resource Check OK\n    Waiting --> Idle: Resource Unavailable\n    ResourceAvailable --> Extracting: Budget Available\n    ResourceAvailable --> Bypassing: Budget Exhausted\n    Extracting --> Storing: Extraction Complete\n    Bypassing --> Storing: Fallback Complete\n    Storing --> Idle: Store Success\n    Storing --> Idle: Store Failure (Retry Later)\n```\n\n## Module Exports\n\nThe curator package exposes its public API through `__init__.py`:\n\n```python\n# src/piloci/curator/__init__.py\nfrom .backlog import Backlog\nfrom .distillation_worker import DistillationWorker\nfrom .scheduler import Scheduler\nfrom .budget import Budget\n# ... etc\n```\n\n资料来源：[src/piloci/curator/__init__.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/curator/__init__.py)\n\n## Usage Scenarios\n\n### Scenario A: Auto-Capture on Raspberry Pi\n\nThe pipeline runs continuously on a Pi 5, processing sessions from connected Claude Code clients. Local Gemma inference handles most extractions without external API calls.\n\n### Scenario B: Bypass Mode (Budget Exhausted)\n\nWhen monthly budget is exceeded, the system falls back to Gemma-only extraction. Quality may degrade but no external API costs are incurred.\n\n### Scenario C: Overflow Mode (High Demand)\n\nWhen backlog exceeds the overflow threshold, the system immediately routes to external LLM to clear the queue faster, accepting the additional cost.\n\n## Tech Stack Integration\n\nThe Curator Pipeline integrates with piLoci's core technologies:\n\n| Component | Technology | Role in Pipeline |\n|-----------|------------|------------------|\n| Embeddings | fastembed (ONNX) | Gemma model inference |\n| Vector Storage | LanceDB | Memory indexing |\n| Session Cache | Redis | Processing state |\n| Identity Data | SQLite | User/project metadata |\n| API Server | FastAPI | Preference management, manual triggers |\n\n资料来源：[README.md](https://github.com/jshsakura/oc-piloci/blob/main/README.md) (Tech Stack section)\n\n---\n\n<a id='storage-layer'></a>\n\n## Storage Layer\n\n### 相关页面\n\n相关主题：[Database Models](#database-models), [Curator Pipeline](#curator-pipeline), [Technology Stack](#tech-stack)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/piloci/storage/base.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/storage/base.py)\n- [src/piloci/storage/lancedb_store.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/storage/lancedb_store.py)\n- [src/piloci/storage/embed.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/storage/embed.py)\n- [src/piloci/storage/cache.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/storage/cache.py)\n- [src/piloci/storage/privacy.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/storage/privacy.py)\n- [src/piloci/storage/instincts_store.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/storage/instincts_store.py)\n- [docs/ADR-014-lancedb-backend.md](https://github.com/jshsakura/oc-piloci/blob/main/docs/ADR-014-lancedb-backend.md)\n</details>\n\n# Storage Layer\n\n## Overview\n\nThe Storage Layer is a core architectural component of piLoci responsible for persisting and retrieving structured memory data. It provides a multi-backend abstraction for vector storage, caching, embedding computation, and privacy-preserving data handling. The storage subsystem is designed to operate efficiently on resource-constrained devices like Raspberry Pi 5 while maintaining the ability to serve semantic search and recall capabilities for AI memory tools.\n\n## Architecture\n\nThe storage layer employs a layered architecture with distinct responsibilities for each module. At the foundation sits the base abstraction layer, with specialized implementations for vector search, caching, embedding, and domain-specific storage like instincts and privacy rules.\n\n```mermaid\ngraph TD\n    A[API Layer] --> B[Storage Interface]\n    B --> C[LanceDB Store]\n    B --> D[Cache Layer]\n    B --> E[Instincts Store]\n    B --> F[Privacy Store]\n    C --> G[LanceDB]\n    D --> H[Redis]\n    F --> I[SQLite]\n    J[Embed Engine] --> C\n    J --> K[fastembed ONNX]\n```\n\n## Module Structure\n\n### Base Storage Interface\n\nThe base module defines the core storage contract that all implementations must follow. This abstraction enables the system to swap backend implementations without affecting the API layer.\n\n| Component | Responsibility |\n|-----------|---------------|\n| `BaseStore` | Abstract interface defining `add`, `search`, `delete`, and `update` operations |\n| `StorageError` | Custom exception type for storage-related failures |\n| Connection pooling | Shared connection management across store instances |\n\n资料来源：[src/piloci/storage/base.py]()\n\n### LanceDB Vector Store\n\nLanceDB serves as the primary vector storage backend for semantic memory search. The store handles high-dimensional embedding vectors with efficient similarity search capabilities.\n\n| Feature | Description |\n|---------|-------------|\n| Vector dimensions | Configurable based on embedding model |\n| Index type | LanceDB's optimized disk-based indices |\n| Query types | Top-k similarity, range search, filtered search |\n| Persistence | On-disk storage with automatic compaction |\n\n**Key Operations:**\n\n```python\n# Pseudocode representation of store operations\nasync def add_memory(memory_id, embedding, metadata):\n    \"\"\"Store a memory with its vector embedding\"\"\"\n    \nasync def search_memories(query_embedding, top_k=10, filters=None):\n    \"\"\"Semantic search across stored memories\"\"\"\n    \nasync def delete_memory(memory_id):\n    \"\"\"Remove a memory from the vector store\"\"\"\n```\n\n资料来源：[src/piloci/storage/lancedb_store.py]()\n资料来源：[docs/ADR-014-lancedb-backend.md]()\n\n### Embedding Engine\n\nThe embed module provides ONNX-based embedding computation using fastembed. This enables on-device inference without requiring external API calls or cloud GPU resources.\n\n| Configuration | Default | Description |\n|---------------|---------|-------------|\n| Model | `fastembed` | ONNX embedding model |\n| Batch size | Environment-defined | Processing batch size |\n| Dimension | Model-dependent | Output vector dimensions |\n| Device | `cpu` | Compute device (cpu/optional cuda) |\n\n资料来源：[src/piloci/storage/embed.py]()\n\n### Cache Layer\n\nThe cache module provides fast access to frequently queried data using Redis as the backing store. Cache invalidation is handled automatically based on TTL and mutation events.\n\n| Cache Target | TTL | Purpose |\n|--------------|-----|---------|\n| Session data | 1 hour | Recent conversation context |\n| User preferences | 24 hours | UI and behavior settings |\n| Query results | 15 minutes | Expensive search operations |\n\n资料来源：[src/piloci/storage/cache.py]()\n\n### Privacy Store\n\nThe privacy module manages access control rules and data retention policies. It stores privacy configurations in SQLite for transactional integrity and fast lookups.\n\n| Privacy Rule Type | Storage | Access Pattern |\n|-------------------|---------|----------------|\n| Project isolation | SQLite | Read-heavy |\n| Field-level masking | SQLite | Read-heavy |\n| Retention policies | SQLite | Balanced |\n\n资料来源：[src/piloci/storage/privacy.py]()\n\n### Instincts Store\n\nThe instincts store manages automatic behavior triggers (instincts) that users define for their memory system. Each instinct consists of a trigger condition and an associated action.\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `instinct_id` | UUID | Unique identifier |\n| `project_slug` | String | Associated project scope |\n| `trigger` | String | Condition expression |\n| `action` | String | Action to execute |\n| `domain` | String | Application domain |\n| `instinct_count` | Integer | Trigger invocation count |\n\n资料来源：[src/piloci/storage/instincts_store.py]()\n\n## Data Flow\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant API\n    participant Embed\n    participant Store\n    participant Cache\n    \n    Client->>API: Submit memory content\n    API->>Embed: Compute embedding\n    Embed-->>API: Vector embedding\n    API->>Store: Store memory + embedding\n    Store-->>API: Confirm storage\n    API->>Cache: Invalidate related cache\n    API-->>Client: Memory saved confirmation\n    \n    Client->>API: Search memories\n    API->>Cache: Check cache\n    alt Cache hit\n        Cache-->>API: Cached results\n    else Cache miss\n        API->>Embed: Compute query embedding\n        Embed-->>API: Query vector\n        API->>Store: Vector similarity search\n        Store-->>API: Matching memories\n        API->>Cache: Store results\n    end\n    API-->>Client: Search results\n```\n\n## Storage Backend Selection\n\nThe system uses multiple storage backends based on data characteristics:\n\n| Data Type | Backend | Rationale |\n|-----------|---------|-----------|\n| Vector embeddings | LanceDB | Optimized for ANN search, disk-based |\n| Session data | Redis | Low-latency key-value access |\n| Identity/Auth | SQLite | ACID transactions, simple schema |\n| Privacy rules | SQLite | Relational integrity requirements |\n| Instincts | SQLite | Structured query needs |\n\n资料来源：[README.md]()\n资料来源：[docs/ADR-014-lancedb-backend.md]()\n\n## Configuration\n\nStorage behavior is controlled through environment variables:\n\n```bash\n# Database paths\nPILOCI_DATA_DIR=~/.local/share/piloci\n\n# LanceDB configuration\nLANCEDB_DB_PATH=./data/lancedb\n\n# Redis connection\nREDIS_URL=redis://localhost:6379/0\n\n# Embedding configuration\nEMBED_BATCH_SIZE=32\nEMBED_DEVICE=cpu\n```\n\n## Performance Characteristics\n\n| Operation | Expected Latency | Notes |\n|-----------|------------------|-------|\n| Memory add | < 100ms | Including embedding |\n| Semantic search | < 200ms | Top-10 results |\n| Cache lookup | < 10ms | Redis hit |\n| Privacy check | < 5ms | SQLite index |\n\n## Security Considerations\n\nThe storage layer implements several security measures:\n\n1. **Project isolation**: Memory data is scoped to projects, preventing cross-project data leakage\n2. **Token-based access**: All storage operations require valid authentication tokens\n3. **Encrypted at rest**: Sensitive fields can be encrypted before storage\n4. **Audit logging**: Storage mutations are logged for compliance\n\n资料来源：[src/piloci/storage/privacy.py]()\n\n## Extension Points\n\nThe storage layer is designed for extensibility:\n\n- **Custom stores**: Implement `BaseStore` interface for new backends\n- **Embedding models**: Swap embedding providers via configuration\n- **Cache backends**: Replace Redis with alternative cache implementations\n- **Privacy engines**: Add custom privacy rule evaluators\n\n## Related Documentation\n\n- [Architecture Decision Records](../adr/index.md)\n- [ADR-014: LanceDB Backend Selection](../adr/ADR-014-lancedb-backend.md)\n- [API Reference](../api/storage.md)\n\n---\n\n<a id='database-models'></a>\n\n## Database Models\n\n### 相关页面\n\n相关主题：[Storage Layer](#storage-layer), [Authentication & Security](#authentication), [API Routes](#api-routes)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/piloci/db/models.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/db/models.py)\n- [src/piloci/db/session.py](https://github.com/jshsakura/oc-piloci/blob/main/src/piloci/db/session.py)\n- [scripts/init-db.py](https://github.com/jshsakura/oc-piloci/blob/main/scripts/init-db.py)\n\n</details>\n\n# Database Models\n\n> ⚠️ **Source Files Not Available in Current Context**\n>\n> The following source files referenced in this page could not be retrieved from the current repository context:\n>\n> - `src/piloci/db/models.py`\n> - `src/piloci/db/session.py`\n> - `scripts/init-db.py`\n>\n> This wiki page is based on available context and architecture information. For complete model definitions, please refer to the actual source files in the repository.\n\n## Overview\n\npiLoci uses a multi-layered data architecture combining **SQLite** for identity and relational data, **LanceDB** for vector embeddings, and **Redis** for session management. This hybrid approach enables fast on-device inference while maintaining structured relationships between users, projects, and memory artifacts.\n\nThe database layer is located in `src/piloci/db/` with initialization handled by `scripts/init-db.py`.\n\n## Storage Architecture\n\n```mermaid\ngraph TD\n    subgraph \"piLoci Data Layer\"\n        SQLite[(SQLite<br/>Identity Data)]\n        LanceDB[(LanceDB<br/>Vector Store)]\n        Redis[(Redis<br/>Sessions)]\n        ONNX[ONNX Runtime<br/>fastembed]\n    end\n    \n    SQLite -->|User/Project| API\n    LanceDB -->|Embeddings| API\n    Redis -->|Session Cache| API\n    API -->|Inference| ONNX\n```\n\n## Technology Stack\n\n| Component | Technology | Purpose | Location |\n|-----------|------------|---------|----------|\n| Identity Data | SQLite | User accounts, projects, permissions | `src/piloci/db/` |\n| Vector Storage | LanceDB | Memory embeddings, similarity search | Vector index |\n| Session Management | Redis | Active session state, caching | External service |\n| Embedding Engine | fastembed (ONNX) | Local inference | `src/piloci/` |\n\n资料来源：[README.md](README.md)\n\n## Database Initialization\n\nThe `scripts/init-db.py` script handles initial database setup:\n\n```bash\n# From project root\npython scripts/init-db.py\n```\n\nThis script creates the necessary SQLite tables and initializes LanceDB indices if they don't exist.\n\n## Key Models (Schema Reference)\n\nBased on the application architecture observed in the codebase:\n\n### User Model\n- `id` (Primary Key)\n- `email`\n- `password_hash`\n- `created_at`\n- `updated_at`\n- `is_admin`\n\n### Project Model\n- `id` (Primary Key)\n- `slug` (Unique identifier)\n- `name`\n- `user_id` (Foreign Key)\n- `created_at`\n\n### Session/ingest Model\n- `ingest_id` (Primary Key)\n- `user_id` (Foreign Key)\n- `project_slug` (Optional)\n- `client` (Claude Code, OpenCode, etc.)\n- `created_at`\n- `processed_at`\n- `memories_extracted`\n- `error` (Optional)\n\n### Memory/Instinct Model\n- `memory_id` / `instinct_id` (Primary Key)\n- `project_slug`\n- `content`\n- `embedding` (Vector)\n- `trigger` (For instincts)\n- `action` (For instincts)\n- `domain`\n- `instinct_count`\n\n资料来源：[web/components/DashboardSummaryPanels.tsx](web/components/DashboardSummaryPanels.tsx)\n资料来源：[web/components/ProjectSessionsPanel.tsx](web/components/ProjectSessionsPanel.tsx)\n\n## Query Patterns\n\nThe API layer (`src/piloci/api/routes.py`) exposes database operations through REST endpoints:\n\n| Endpoint | Operation | Description |\n|----------|-----------|-------------|\n| `GET /api/projects` | List | Fetch user's projects |\n| `GET /api/projects/{id}` | Read | Fetch project details |\n| `POST /api/memories` | Create | Store new memory |\n| `GET /api/projects/{slug}/workspace` | Read | Get workspace notes |\n\n资料来源：[README.md](README.md)\n资料来源：[MEMORY.md](MEMORY.md)\n\n## Configuration\n\nDatabase configuration is managed through `src/piloci/config.py`:\n\n```python\n# Example configuration keys\nDATABASE_URL = \"sqlite:///./piloci.db\"\nREDIS_URL = \"redis://localhost:6379\"\nLANCEDB_PATH = \"./data/embeddings\"\n```\n\n## Vector Storage Details\n\nLanceDB stores embeddings with the following characteristics:\n\n- **Index Type**: LanceDB (columnar format)\n- **Embedding Model**: fastembed (ONNX-based, runs locally)\n- **Use Case**: Semantic search for memories and instincts\n\n资料来源：[README.md](README.md)\n\n## Related Documentation\n\n- [MEMORY.md](MEMORY.md) - Memory extraction and distillation system\n- [CLAUDE.md](CLAUDE.md) - Development guidelines\n- [web/DESIGN-HARNESS.md](web/DESIGN-HARNESS.md) - Frontend design patterns\n\n---\n\n<a id='web-dashboard'></a>\n\n## Web Dashboard\n\n### 相关页面\n\n相关主题：[Workspace UI & Team Features](#workspace-ui), [Technology Stack](#tech-stack), [Authentication & Security](#authentication)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [web/app/layout.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/app/layout.tsx)\n- [web/app/login/page.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/app/login/page.tsx)\n- [web/app/dashboard/page.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/app/dashboard/page.tsx)\n- [web/app/admin/users/page.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/app/admin/users/page.tsx)\n- [web/app/settings/page.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/app/settings/page.tsx)\n- [web/components/AppShell.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/components/AppShell.tsx)\n- [web/lib/auth.ts](https://github.com/jshsakura/oc-piloci/blob/main/web/lib/auth.ts)\n- [web/lib/api.ts](https://github.com/jshsakura/oc-piloci/blob/main/web/lib/api.ts)\n</details>\n\n# Web Dashboard\n\n## Overview\n\nThe Web Dashboard is the primary user-facing interface for the piLoci system, built as a Next.js 14+ application with TypeScript and React. It provides authenticated users with a comprehensive view of their AI session memories, project workspaces, token management, and system administration capabilities.\n\nThe dashboard implements a server-side rendering (SSR) architecture where pages prefetch user data server-side, enabling fast initial loads and proper authentication checks before rendering protected routes.\n\n## Architecture\n\n### Tech Stack\n\n| Layer | Technology | Purpose |\n|-------|------------|---------|\n| Framework | Next.js 14+ (App Router) | Server-side rendering, routing, API routes |\n| UI Components | shadcn/ui + Radix UI | Accessible, composable components |\n| Styling | Tailwind CSS | Utility-first styling with design tokens |\n| State Management | React Context + Server Components | Auth state and server-fetched data |\n| Data Fetching | Server Actions + fetch API | Backend communication |\n\n### Component Hierarchy\n\n```mermaid\ngraph TD\n    A[\"<AppShell>\"] --> B[\"Navigation Bar\"]\n    A --> C[\"Main Content Area\"]\n    A --> D[\"Footer/Sidebar\"]\n    \n    C --> E[\"<DashboardSummaryPanels>\"]\n    C --> F[\"<ProjectListView>\"]\n    C --> G[\"<TokenManager>\"]\n    C --> H[\"<DistillationSettingsPanel>\"]\n    \n    E --> I[\"<PanelCard>\"]\n    E --> J[\"<Pager>\"]\n    \n    F --> K[\"Project Cards\"]\n    F --> L[\"Create Project Dialog\"]\n    \n    G --> M[\"Token List Table\"]\n    G --> N[\"CopyBlock Components\"]\n    G --> O[\"Tabbed Setup Instructions\"]\n```\n\n### Page Layout Pattern\n\nAll dashboard pages follow a consistent layout pattern defined in `DESIGN-HARNESS.md`:\n\n```tsx\n<AppShell>\n  <div className=\"pi-page\">\n    <section className=\"pi-page-hero\">\n      <p className=\"pi-eyebrow\">Area label</p>\n      <h1 className=\"pi-title mt-2\">Page title</h1>\n      <p className=\"pi-subtitle\">One sentence explaining the page.</p>\n    </section>\n\n    <section className=\"grid gap-3 sm:grid-cols-3\">\n      <div className=\"pi-metric-card\">...</div>\n    </section>\n\n    <section className=\"pi-panel p-3\">...</section>\n  </div>\n</AppShell>\n```\n\n## Authentication System\n\n### Authentication Flow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Browser\n    participant NextAuth\n    participant Google OAuth\n    participant Backend API\n    \n    User->>Browser: Visit protected page\n    Browser->>NextAuth: Check session\n    NextAuth->>Browser: No session\n    Browser->>User: Redirect to /login\n    User->>Browser: Click \"Sign in with Google\"\n    Browser->>Google OAuth: OAuth request\n    Google OAuth->>User: Login prompt\n    User->>Google OAuth: Authenticate\n    Google OAuth->>Browser: Callback with code\n    Browser->>NextAuth: Exchange code for session\n    NextAuth->>Backend API: Validate/create user\n    Backend API->>NextAuth: User data\n    NextAuth->>Browser: Session cookie\n    Browser->>User: Redirect to dashboard\n```\n\n### Auth Configuration\n\nThe authentication system is configured in `web/lib/auth.ts` and uses NextAuth.js with Google OAuth provider:\n\n| Setting | Description | Environment Variable |\n|---------|-------------|---------------------|\n| Provider | Google OAuth 2.0 | `AUTH_GOOGLE_ID`, `AUTH_GOOGLE_SECRET` |\n| Base URL | Application root for callbacks | `BASE_URL` |\n| Session Strategy | JWT-based sessions | N/A |\n| Callbacks | Custom session/user callbacks | N/A |\n\n### Protected Routes\n\nProtected pages use a shared authentication pattern:\n\n```typescript\n// In page components (e.g., web/app/dashboard/page.tsx)\nconst user = await getCurrentUser();\nif (!user) {\n  redirect(\"/login\");\n}\n```\n\nThis pattern is consistent across all protected pages including:\n- `/dashboard` - Main user dashboard\n- `/projects` - Project workspace\n- `/settings` - User settings\n- `/admin/*` - Admin-only pages\n\n## Core Components\n\n### AppShell\n\n`AppShell` is the root authenticated layout component that wraps all protected pages. It provides:\n\n| Feature | Implementation |\n|---------|----------------|\n| Background | Authenticated shell background with glass effect |\n| Navigation | Top navigation bar with user menu |\n| User Info | User display with email and role |\n| Quick Links | Dashboard, Projects, Settings navigation |\n| Role-Based Access | Admin menu visible only to admin users |\n\n### DashboardSummaryPanels\n\nThe main dashboard view displays aggregated statistics and recent activity:\n\n| Panel | Data Source | Components |\n|-------|-------------|------------|\n| Summary Stats | User stats API | `pi-metric-card` with icons |\n| Top Tags | Tag frequency aggregation | Badges with counts |\n| Recent Sessions | Session list with pagination | `<Pager>` component |\n\n### PanelCard\n\nA reusable card component for dashboard sections:\n\n```tsx\n<PanelCard\n  icon={FileText}\n  title=\"Panel Title\"\n  footer={<Pager {...pagerProps} />}\n>\n  {content}\n</PanelCard>\n```\n\n### ProjectListView\n\nManages project creation and listing:\n\n| Feature | Description |\n|---------|-------------|\n| Project Grid | Responsive grid layout (sm:2, lg:3 columns) |\n| Create Dialog | Modal form for new project creation |\n| Loading State | Skeleton placeholders during fetch |\n| Error State | Retry button on fetch failure |\n\n### TokenManager\n\nHandles API token lifecycle management:\n\n| Feature | Description |\n|---------|-------------|\n| Token List | Table with name, scope, creation date |\n| Scope Badges | User vs Project scope indicators |\n| Install Status | Shows installed clients and hostname |\n| Setup Instructions | Tabbed guides for Claude Desktop, Claude Code, OpenCode, Cursor |\n\n### ProjectSessionsPanel\n\nDisplays ingest sessions for a project:\n\n| Feature | Implementation |\n|---------|----------------|\n| Session Cards | Expandable cards with transcript viewer |\n| Status Badges | Client, status, timestamp display |\n| Error Display | Red text for failed sessions |\n| Transcript Viewer | Lazy-loaded transcript content |\n\n## API Integration\n\n### API Client\n\nThe API client in `web/lib/api.ts` handles all backend communication:\n\n```typescript\n// Authentication header injection\nconst headers = {\n  'Authorization': `Bearer ${session?.accessToken}`,\n  'Content-Type': 'application/json',\n};\n\n// Server-side data fetching pattern\nconst response = await fetch(`${API_BASE_URL}/endpoint`, {\n  headers,\n  credentials: 'include',\n});\n```\n\n### API Endpoints Used\n\n| Endpoint Pattern | Purpose | Auth Required |\n|-----------------|---------|---------------|\n| `/api/users` | User management | Admin |\n| `/api/projects` | Project CRUD | Yes |\n| `/api/projects/:slug/sessions` | Session listing | Yes |\n| `/api/tokens` | Token management | Yes |\n| `/api/ingest/:id/transcript` | Transcript fetch | Yes |\n\n### Server-Side Data Fetching\n\nDashboard pages use a server-first data fetching pattern:\n\n```typescript\n// web/app/dashboard/page.tsx pattern\nexport default async function DashboardPage() {\n  const user = await getCurrentUser();\n  if (!user) redirect(\"/login\");\n\n  const [stats, tags, sessions] = await Promise.all([\n    fetchUserStats(),\n    fetchTopTags(),\n    fetchRecentSessions(),\n  ]);\n\n  return <DashboardSummaryPanels stats={stats} tags={tags} sessions={sessions} />;\n}\n```\n\n## Design System\n\n### piLoci Design Tokens\n\nThe project uses custom CSS variables for consistent styling:\n\n| Token | Usage | Example |\n|-------|-------|---------|\n| `--pi-shadow` | Card shadows | Box elevation |\n| `--pi-shadow-sm` | Small element shadows | Buttons, badges |\n| `--pi-primary` | Primary brand color | CTAs, links |\n\n### Pattern Classes\n\n| Class | Purpose | Location |\n|-------|---------|----------|\n| `pi-page` | Page container wrapper | All pages |\n| `pi-page-hero` | Title/subtitle section | All pages |\n| `pi-eyebrow` | Category label | Page headers |\n| `pi-title` | Main page title | H1 elements |\n| `pi-subtitle` | Page description | Intro text |\n| `pi-metric-card` | Statistics cards | Dashboard panels |\n| `pi-panel` | Content containers | Lists, forms |\n| `pi-icon-cell` | Icon + color wrapper | Metric cards |\n\n### Responsive Breakpoints\n\n| Breakpoint | Columns | Components Shown |\n|------------|---------|-----------------|\n| Mobile | 1 | Essential info only |\n| `sm` (640px) | 2-3 | Expanded cards |\n| `md` (768px) | 3 | Full tables |\n| `lg` (1024px) | 4 | Two-column grids |\n\n## Page Routes\n\n### Route Structure\n\n```mermaid\ngraph TD\n    A[\" / \"] --> B[\" Landing Page\"]\n    A --> C[\" / login\"]\n    C --> D[\" Google OAuth\"]\n    A --> E[\" / signup\"]\n    A --> F[\" / terms\"]\n    A --> G[\" / privacy\"]\n    \n    H[\" Authenticated Routes\"] --> I[\" / dashboard\"]\n    H --> J[\" / projects\"]\n    H --> K[\" / settings\"]\n    H --> L[\" / settings/tokens\"]\n    \n    M[\" Admin Routes\"] --> N[\" / admin/users\"]\n    \n    style H fill:#e1eff6\n    style M fill:#ffe6e6\n```\n\n### Dashboard Pages\n\n| Route | Purpose | Main Components |\n|-------|---------|-----------------|\n| `/dashboard` | Main user dashboard | DashboardSummaryPanels |\n| `/projects` | Project workspace | ProjectListView, ProjectSessionsPanel |\n| `/settings` | User preferences | DistillationSettingsPanel |\n| `/settings/tokens` | API token management | TokenManager |\n| `/admin/users` | User administration | User statistics table |\n\n## State Management\n\n### Auth State\n\nAuthentication state is managed through NextAuth.js:\n\n```typescript\n// Client-side auth access\nconst { data: session } = useSession();\n\n// Server-side auth check\nconst session = await getServerSession(authOptions);\n```\n\n### Loading States\n\nAll data-fetching components implement loading states:\n\n```tsx\n{isLoading ? (\n  <div className=\"space-y-1.5\">\n    {[1, 2, 3, 4].map((i) => (\n      <Skeleton key={i} className=\"h-10 w-full\" />\n    ))}\n  </div>\n) : null}\n```\n\n### Error Handling\n\nError states display retry options:\n\n```tsx\n{isError ? (\n  <Card>\n    <CardContent className=\"flex flex-col items-center gap-4 py-12\">\n      <RefreshCcw className=\"size-8 text-muted-foreground\" />\n      <p className=\"text-sm text-muted-foreground\">Error loading data</p>\n      <Button variant=\"outline\" onClick={() => refetch()}>\n        {t.dashboard.error.retry}\n      </Button>\n    </CardContent>\n  </Card>\n) : null}\n```\n\n## Internationalization\n\nThe application uses a translation system (likely next-intl) with keys structured by page:\n\n| Namespace | Usage |\n|-----------|-------|\n| `landing` | Landing page content |\n| `authLayout` | Auth page headers/footers |\n| `dashboard` | Dashboard labels and messages |\n| `admin` | Admin page content |\n| `tokenManager` | Token management strings |\n| `projects` | Project page content |\n\n## Security Considerations\n\n### Route Protection\n\nAll sensitive routes check authentication before rendering:\n\n```typescript\n// Pattern used in all protected pages\nconst user = await getCurrentUser();\nif (!user) {\n  redirect(\"/login\");\n}\n```\n\n### Role-Based Access\n\nAdmin routes check for admin role:\n\n```typescript\nif (user.role !== \"admin\") {\n  redirect(\"/dashboard\");\n}\n```\n\n### Token Handling\n\n- Tokens are transmitted via HTTP-only cookies or Authorization headers\n- API keys are never exposed in client-side code\n- Install codes are single-use with 10-minute expiration\n\n## Related Documentation\n\n- [API Backend Documentation](../api/overview)\n- [Authentication System](../auth/overview)\n- [Design System Reference](./design-system)\n\n---\n\n<a id='workspace-ui'></a>\n\n## Workspace UI & Team Features\n\n### 相关页面\n\n相关主题：[Web Dashboard](#web-dashboard), [Curator Pipeline](#curator-pipeline)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [web/app/projects/page.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/app/projects/page.tsx)\n- [web/app/teams/page.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/app/teams/page.tsx)\n- [web/components/ProjectSessionsPanel.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/components/ProjectSessionsPanel.tsx)\n- [web/components/DashboardSummaryPanels.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/components/DashboardSummaryPanels.tsx)\n- [web/components/VaultNoteDetail.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/components/VaultNoteDetail.tsx)\n- [web/components/ProjectKnacksPanel.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/components/ProjectKnacksPanel.tsx)\n- [web/app/memory/page.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/app/memory/page.tsx)\n- [web/components/TokenManager.tsx](https://github.com/jshsakura/oc-piloci/blob/main/web/components/TokenManager.tsx)\n</details>\n\n# Workspace UI & Team Features\n\n## Overview\n\nThe Workspace UI & Team Features module in piLoci provides a comprehensive interface for managing projects, teams, and collaborative memory curation. This system enables users to organize AI-assisted memory sessions into project-based workspaces, view memory graphs, manage vault notes, and collaborate with team members through shared access tokens and session tracking.\n\nThe workspace architecture follows a project-scoped model where memories are isolated per project, allowing both individual users and teams to maintain separate knowledge bases while benefiting from shared curated content.\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    A[User Dashboard] --> B[Project Workspace]\n    A --> C[Team Management]\n    B --> D[Memory Graph Panel]\n    B --> E[Vault Notes]\n    B --> F[Session Sessions]\n    C --> G[Token Manager]\n    C --> H[Team Members]\n    F --> I[Transcript Viewer]\n    D --> J[Memory Tags]\n    E --> K[Note Links]\n```\n\n## Core Components\n\n### Project Workspace (`web/app/projects/page.tsx`)\n\nThe project workspace serves as the central hub for managing project-specific memories and settings. It provides:\n\n- Project listing with slug-based navigation\n- Workspace view with notes and relationships per project\n- Session history and memory extraction metrics\n\n**Key Features:**\n- Slug-based project routing (`/projects/?slug={slug}`)\n- Integration with `ProjectListView.tsx` for listing projects\n- Dashboard summary panels for quick metrics\n\n资料来源：[web/app/projects/page.tsx]()\n\n### Team Management (`web/app/teams/page.tsx`)\n\nThe team page enables users to manage collaborative workspaces and invite team members. Team features include:\n\n- Team member listing with roles and permissions\n- Shared project access control\n- Token-based client installation for team members\n\n资料来源：[web/app/teams/page.tsx]()\n\n## Session Management\n\n### Project Sessions Panel (`web/components/ProjectSessionsPanel.tsx`)\n\nThe `ProjectSessionsPanel` displays historical AI client sessions within a project context.\n\n**Component Structure:**\n\n```tsx\n<div className=\"flex flex-col gap-3\">\n  <Card>\n    <CardHeader className=\"pb-2\">\n      <div className=\"flex items-center justify-between\">\n        {/* Session header */}\n      </div>\n    </CardHeader>\n    <CardContent>\n      {/* Expandable transcript viewer */}\n    </CardContent>\n  </Card>\n</div>\n```\n\n**Session Display Elements:**\n\n| Element | Description |\n|---------|-------------|\n| Client Badge | Shows client type (e.g., Claude Desktop, Claude Code, OpenCode) |\n| Status | Processing status with timestamps |\n| Memory Count | Extracted memories count or pending indicator |\n| Error Display | Session errors in red text |\n| Transcript | Expandable transcript viewer |\n\n**Session Metadata Display:**\n\n```tsx\n<div className=\"flex flex-wrap items-center gap-1.5 text-[11px] text-muted-foreground\">\n  <Badge variant=\"outline\" className=\"text-[10px]\">{s.client}</Badge>\n  <span>{meta}</span>\n  <span>·</span>\n  <span>{status}</span>\n  <span>·</span>\n  <span>{fmt(s.created_at)}</span>\n</div>\n```\n\n**Transcript Expansion:**\n- Toggle button with chevron icons (up/down)\n- `TranscriptViewer` component renders full session transcript\n- State management via `isExp` boolean mapped to `ingest_id`\n\n资料来源：[web/components/ProjectSessionsPanel.tsx:1-60]()\n\n### Dashboard Summary Panels (`web/components/DashboardSummaryPanels.tsx`)\n\nThe dashboard provides aggregated views of project activity across all workspaces.\n\n**Panel Types:**\n\n| Panel | Icon | Content |\n|-------|------|---------|\n| Recent Sessions | FileText | Last processed sessions with memory counts |\n| Top Tags | Sparkles | Most used memory tags with usage frequency |\n| Project Stats | Varies | Metrics per project |\n\n**Recent Sessions Entry:**\n```tsx\n<li className=\"flex flex-wrap items-center justify-between gap-2 py-2 text-xs\">\n  <div className=\"flex min-w-0 items-center gap-2\">\n    <Link href={`/projects/?slug=${s.project_slug}`}>\n      {s.project_name}\n    </Link>\n    <span className=\"text-muted-foreground\">\n      {s.processed_at\n        ? summary.sessionMemories.replace(\"{count}\", String(s.memories_extracted))\n        : summary.sessionPending}\n    </span>\n  </div>\n  <span className=\"text-muted-foreground\">{timeFmt(s.created_at)}</span>\n</li>\n```\n\n**Tag Display with Pager:**\n```tsx\n<div className=\"flex flex-wrap gap-1.5\">\n  {tagPager.slice.map((tag) => (\n    <Badge key={tag.tag} variant=\"secondary\" className=\"break-all\">\n      #{tag.tag} <span className=\"ms-1 opacity-60 tabular-nums\">×{tag.count}</span>\n    </Badge>\n  ))}\n</div>\n```\n\n资料来源：[web/components/DashboardSummaryPanels.tsx:1-80]()\n\n## Memory Visualization\n\n### Memory Graph Panel\n\nThe Memory Graph Panel provides a visual representation of memory relationships within a project. Based on the design guidelines, future graph UI should:\n\n- Keep current landing preview dependency-free\n- Prefer **React Flow** for polished interactive curated-memory graphs\n- Reserve **Sigma.js/WebGL** for large workspace graphs if React Flow hits node-count limits\n\n资料来源：[MEMORY.md]()\n\n## Vault Notes System\n\n### Vault Note Detail (`web/components/VaultNoteDetail.tsx`)\n\nThe vault notes system displays individual memories with their metadata, tags, and inter-note relationships.\n\n**Note Display Structure:**\n\n```tsx\n<div className=\"space-y-3\">\n  {/* Header with title */}\n  <div>\n    <h2 className=\"text-xl font-semibold\">{note.title}</h2>\n    {note.tags?.length > 0 && (\n      <div className=\"flex flex-wrap gap-1.5 mt-2\">\n        {/* Tag badges */}\n      </div>\n    )}\n  </div>\n  \n  {/* Path display */}\n  <div className=\"break-all rounded-md bg-muted px-3 py-2 font-mono text-xs\">\n    {note.path}\n  </div>\n  \n  {/* Content */}\n  <pre className=\"whitespace-pre-wrap break-all\">\n    {note.markdown ?? note.excerpt}\n  </pre>\n  \n  {/* Linked notes */}\n  {note.links.length > 0 && <LinkedNotesSection />}\n</div>\n```\n\n**Note Metadata Fields:**\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `title` | string | Note title |\n| `path` | string | File system path |\n| `markdown` | string | Full markdown content |\n| `excerpt` | string | Short preview text |\n| `tags` | string[] | Associated tags |\n| `links` | string[] | Related note paths |\n\n**Linked Notes Section:**\n```tsx\n<Separator className=\"my-4\" />\n<div>\n  <p className=\"mb-2 text-sm font-medium text-muted-foreground\">\n    {t.vaultNote.linkedNotes}\n  </p>\n  <div className=\"flex flex-wrap gap-1.5\">\n    {note.links.map((link) => (\n      <Badge key={link} variant=\"outline\">{link}</Badge>\n    ))}\n  </div>\n</div>\n```\n\n资料来源：[web/components/VaultNoteDetail.tsx:1-50]()\n\n### Obsidian Export\n\nThe workspace system supports export to Obsidian vaults:\n\n```bash\ncurl -OJ http://localhost:8314/api/vault/my-project/export\n```\n\n**Export Process:**\n1. Fetch workspace data from `/api/projects/slug/{slug}/workspace`\n2. Create project directory structure in `~/.config/piloci/projects/slug/{slug}/workspace`\n3. Write each `workspace.notes[].markdown` to corresponding `workspace.notes[].path`\n4. Open directory as Obsidian vault or sync to existing vault\n\n资料来源：[README.md](https://github.com/jshsakura/oc-piloci/blob/main/README.md)\n\n## Team Collaboration\n\n### Token Manager (`web/components/TokenManager.tsx`)\n\nThe Token Manager provides a UI for generating and managing API tokens for team members.\n\n**Supported Client Types:**\n\n| Client | Config File | Features |\n|--------|-------------|----------|\n| Claude Desktop | `~/Library/Application Support/Claude/claude_desktop_config.json` | MCP server + hooks |\n| Claude Code | `~/.claude.json` / `.mcp.json` | MCP server + auto-capture hooks |\n| OpenCode | `opencode.json` | MCP server only |\n\n**Token Installation Status:**\n```tsx\n{token.installed_at ? (\n  <span className=\"text-[11px] text-muted-foreground\">\n    {t.tokenManager.installedOn} {formatDate(token.installed_at)}\n    {token.client_kinds && token.client_kinds.length > 0 && (\n      <> · {token.client_kinds.join(\" + \")}</>\n    )}\n    {token.hostname && <> · {token.hostname}</>}\n  </span>\n) : (\n  <span className=\"text-[11px] text-muted-foreground/70\">\n    {t.tokenManager.notInstalled}\n  </span>\n)}\n```\n\n**Token Scope Badge:**\n```tsx\n<Badge variant={token.scope === \"user\" ? \"default\" : \"secondary\"}>\n  {token.scope}\n</Badge>\n```\n\n**Installation Methods:**\n\n1. **CLI Installation:**\n   ```bash\n   piloci login\n   piloci install\n   ```\n\n2. **One-line Bash:**\n   ```bash\n   curl -sSL https://piloci.example.com/install/<install_code> | bash\n   ```\n\n3. **Manual Hook Setup:**\n   ```bash\n   # Step 1: Install hook\n   piloci hook install\n   \n   # Step 2: Configure client\n   # Copy generated JSON to client config file\n   ```\n\n资料来源：[web/components/TokenManager.tsx:1-100]()\n\n### Client-Side Setup\n\n**What the Connection Does:**\n\n- Records token + ingest/analyze URL to `~/.config/piloci/config.json` (mode 0600)\n- **Claude Code**: Registers MCP server in `~/.claude.json` with `memory`/`recall`/`recommend` tools, plus auto-capture hooks in `~/.claude/settings.json`\n- **OpenCode**: Registers MCP server in `~/.config/opencode/opencode.json`\n\n**Hook Behavior by Client:**\n\n| Client | SessionStart Hook | SessionStop Hook |\n|--------|-------------------|------------------|\n| Claude Code | Catch-up batch retrieve | Live push each turn |\n| OpenCode | N/A (no hook mechanism) | N/A |\n\n资料来源：[README.ko.md](https://github.com/jshsakura/oc-piloci/blob/main/README.ko.md)\n\n## Project Management\n\n### Project Knacks Panel (`web/components/ProjectKnacksPanel.tsx`)\n\nThe Project Knacks Panel displays project-specific insights and instinct metrics.\n\n**Instinct Display:**\n```tsx\n<div className=\"flex items-center gap-2\">\n  <Badge variant=\"outline\" className=\"text-[10px]\">\n    {i.domain}\n  </Badge>\n  <span className=\"tabular-nums\">×{i.instinct_count}</span>\n</div>\n```\n\n资料来源：[web/components/ProjectKnacksPanel.tsx]()\n\n### Distillation Settings (`web/components/DistillationSettingsPanel.tsx`)\n\nProject-level settings control memory processing behavior:\n\n| Setting | Type | Description |\n|---------|------|-------------|\n| Temperature Ceiling | °C | Worker stops when SoC temp exceeds threshold |\n| Load Ceiling | float | Worker stops when load avg exceeds threshold |\n| Overflow Limit | number | Optional external bypass cap |\n\n资料来源：[web/components/DistillationSettingsPanel.tsx:1-60]()\n\n## API Integration\n\n### Memory API\n\nThe backend exposes project-scoped memory endpoints:\n\n**Endpoint:** `POST /api/memories`\n\n**Features:**\n- Uses existing embed/store pipeline\n- Project-scoped isolation\n- Memory extraction from session transcripts\n\n资料来源：[MEMORY.md]()\n\n### Workspace Export API\n\n**Endpoint:** `GET /api/projects/slug/{slug}/workspace`\n\nReturns workspace data including notes, paths, and relationships for Obsidian export.\n\n## Usage Scenarios\n\n### Scenario A — Team Project Memory Hub\n\nA small team sets up one piLoci instance on shared hardware. Each member creates an account, joins shared projects, and stores memories via MCP tools. Project isolation keeps unrelated work separate while everyone benefits from the shared knowledge base.\n\n### Scenario B — Multi-Project Workspace\n\nA solo developer or researcher runs several projects (thesis research, side project, client work) on one piLoci. Each project's memories stay isolated, and the workspace viewer shows notes and relationships per project.\n\n### Scenario C — Obsidian Export\n\nGenerate workspace notes and export to an Obsidian vault via simple API call for teams who want to curate knowledge in Obsidian after collection.\n\n## Page Design Patterns\n\nFollowing the piLoci design harness guidelines:\n\n```tsx\n<AppShell>\n  <div className=\"pi-page\">\n    <section className=\"pi-page-hero\">\n      <p className=\"pi-eyebrow\">Area label</p>\n      <h1 className=\"pi-title mt-2\">Page title</h1>\n      <p className=\"pi-subtitle\">One sentence explaining the page.</p>\n    </section>\n\n    <section className=\"grid gap-3 sm:grid-cols-3\">\n      <div className=\"pi-metric-card\">...</div>\n    </section>\n\n    <section className=\"pi-panel p-3\">...</section>\n  </div>\n</AppShell>\n```\n\n**Design Classes:**\n\n| Class | Usage |\n|-------|-------|\n| `pi-page` | Main page container |\n| `pi-page-hero` | Hero section with title and subtitle |\n| `pi-eyebrow` | Small label above title |\n| `pi-title` | Page title (H1) |\n| `pi-subtitle` | Descriptive subtitle |\n| `pi-metric-card` | Metric display cards |\n| `pi-panel` | Content panels with consistent styling |\n\n资料来源：[web/DESIGN-HARNESS.md](https://github.com/jshsakura/oc-piloci/blob/main/web/DESIGN-HARNESS.md)\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：jshsakura/oc-piloci\n\n摘要：发现 33 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：安装坑 - 失败模式：installation: Release v0.3.61。\n\n## 1. 安装坑 · 失败模式：installation: Release v0.3.61\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.61\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.61\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.61. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_238385c7d11f6862a1b9d0c024a94181 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.61 | Release v0.3.61\n\n## 2. 安装坑 · 失败模式：installation: Release v0.3.62\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.62\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.62\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.62. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_115c2527b334fad79621b999d3e94857 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.62 | Release v0.3.62\n\n## 3. 安装坑 · 失败模式：installation: Release v0.3.63\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.63\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.63\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.63. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_348782b397ba2bb56859e630ea890c99 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.63 | Release v0.3.63\n\n## 4. 安装坑 · 失败模式：installation: Release v0.3.64\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.64\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.64\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.64. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_a5608f313037217768976fadbcbd00e3 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.64 | Release v0.3.64\n\n## 5. 安装坑 · 失败模式：installation: Release v0.3.65\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.65\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.65\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.65. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_593467b90b436b99ecac227152d65f93 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.65 | Release v0.3.65\n\n## 6. 安装坑 · 失败模式：installation: Release v0.3.66\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.66\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.66\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.66. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_41cea4cedb6fe85b101b1ee1e744a2a2 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.66 | Release v0.3.66\n\n## 7. 安装坑 · 失败模式：installation: Release v0.3.67\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.67\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.67\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.67. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_51ad1a6fbbb3b6c3fdc1be72bcfae7ea | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.67 | Release v0.3.67\n\n## 8. 安装坑 · 失败模式：installation: Release v0.3.68\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.68\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.68\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.68. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_7bc0641dd202d881746e1010d1b03fe5 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.68 | Release v0.3.68\n\n## 9. 安装坑 · 失败模式：installation: Release v0.3.69\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.69\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.69\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.69. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_ba1666889342a143a76dda2fa013ddf2 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.69 | Release v0.3.69\n\n## 10. 安装坑 · 失败模式：installation: Release v0.3.70\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.70\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.70\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.70. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_18504a4306cc5d44261e6d0f5ec47f54 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.70 | Release v0.3.70\n\n## 11. 安装坑 · 失败模式：installation: Release v0.3.71\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.71\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.71\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.71. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_4f40f1505195306061984312ceafb8d8 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.71 | Release v0.3.71\n\n## 12. 安装坑 · 失败模式：installation: Release v0.3.72\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.72\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.72\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.72. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_a62aef6e3f8ef8401a1d0bb3ce5d66d5 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.72 | Release v0.3.72\n\n## 13. 安装坑 · 失败模式：installation: Release v0.3.73\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.73\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.73\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.73. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_402be624902b0ff4a70763241e96f92a | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.73 | Release v0.3.73\n\n## 14. 安装坑 · 失败模式：installation: Release v0.3.74\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.74\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.74\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.74. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_f1c1782e6dc53172212d524d1e194b8f | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.74 | Release v0.3.74\n\n## 15. 安装坑 · 失败模式：installation: Release v0.3.75\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.75\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.75\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.75. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_65320a1ebb2900791f1e9b16cbf8e8d6 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.75 | Release v0.3.75\n\n## 16. 安装坑 · 失败模式：installation: Release v0.3.76\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.76\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.76\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.76. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_78ad7e0a2110bee066ed708a51554c0d | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.76 | Release v0.3.76\n\n## 17. 安装坑 · 来源证据：Release v0.3.15\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.15\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_ab726a10491d4c14b7fa95fd35beee64 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.15 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 18. 安装坑 · 来源证据：Release v0.3.16\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.16\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_bc556664008b404db3fc774023736dcb | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.16 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 19. 安装坑 · 来源证据：Release v0.3.17\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.17\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_013d47bb794f4f13b2f8e2a5859cdabf | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.17 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 20. 安装坑 · 来源证据：Release v0.3.22\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.22\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_4bfd96a53e7e4d859637f79a8ee350d1 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.22 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 21. 安装坑 · 来源证据：Release v0.3.23\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.23\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_38baea4290d648a887a4c7575a3c8c55 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.23 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 22. 安装坑 · 来源证据：Release v0.3.24\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.24\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_654bcb552e094dd18bcc59cfdc2a83b5 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.24 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 23. 安装坑 · 来源证据：Release v0.3.25\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.25\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_e2f6528bce8040c0bab4d074214b33c5 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.25 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 24. 安装坑 · 来源证据：Release v0.3.26\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.26\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_f358a19a360f476bbd41bb4e35bca86e | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.26 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 25. 安装坑 · 来源证据：Release v0.3.27\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.27\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_973b50ab39634ba4af49b7df022af9a1 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.27 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 26. 安装坑 · 来源证据：Release v0.3.28\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.28\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_ca63e0beff7c4da8844cdea3d52415b6 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.28 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 27. 配置坑 · 可能修改宿主 AI 配置\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- 证据：capability.host_targets | github_repo:1219455965 | https://github.com/jshsakura/oc-piloci | host_targets=mcp_host, claude\n\n## 28. 能力坑 · 能力判断依赖假设\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:1219455965 | https://github.com/jshsakura/oc-piloci | README/documentation is current enough for a first validation pass.\n\n## 29. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:1219455965 | https://github.com/jshsakura/oc-piloci | last_activity_observed missing\n\n## 30. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:1219455965 | https://github.com/jshsakura/oc-piloci | no_demo; severity=medium\n\n## 31. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:1219455965 | https://github.com/jshsakura/oc-piloci | no_demo; severity=medium\n\n## 32. 维护坑 · 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:1219455965 | https://github.com/jshsakura/oc-piloci | issue_or_pr_quality=unknown\n\n## 33. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:1219455965 | https://github.com/jshsakura/oc-piloci | release_recency=unknown\n\n<!-- canonical_name: jshsakura/oc-piloci; 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项目：jshsakura/oc-piloci\n\n摘要：发现 33 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：安装坑 - 失败模式：installation: Release v0.3.61。\n\n## 1. 安装坑 · 失败模式：installation: Release v0.3.61\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.61\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.61\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.61. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_238385c7d11f6862a1b9d0c024a94181 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.61 | Release v0.3.61\n\n## 2. 安装坑 · 失败模式：installation: Release v0.3.62\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.62\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.62\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.62. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_115c2527b334fad79621b999d3e94857 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.62 | Release v0.3.62\n\n## 3. 安装坑 · 失败模式：installation: Release v0.3.63\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.63\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.63\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.63. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_348782b397ba2bb56859e630ea890c99 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.63 | Release v0.3.63\n\n## 4. 安装坑 · 失败模式：installation: Release v0.3.64\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.64\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.64\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.64. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_a5608f313037217768976fadbcbd00e3 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.64 | Release v0.3.64\n\n## 5. 安装坑 · 失败模式：installation: Release v0.3.65\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.65\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.65\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.65. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_593467b90b436b99ecac227152d65f93 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.65 | Release v0.3.65\n\n## 6. 安装坑 · 失败模式：installation: Release v0.3.66\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.66\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.66\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.66. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_41cea4cedb6fe85b101b1ee1e744a2a2 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.66 | Release v0.3.66\n\n## 7. 安装坑 · 失败模式：installation: Release v0.3.67\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.67\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.67\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.67. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_51ad1a6fbbb3b6c3fdc1be72bcfae7ea | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.67 | Release v0.3.67\n\n## 8. 安装坑 · 失败模式：installation: Release v0.3.68\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.68\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.68\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.68. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_7bc0641dd202d881746e1010d1b03fe5 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.68 | Release v0.3.68\n\n## 9. 安装坑 · 失败模式：installation: Release v0.3.69\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.69\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.69\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.69. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_ba1666889342a143a76dda2fa013ddf2 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.69 | Release v0.3.69\n\n## 10. 安装坑 · 失败模式：installation: Release v0.3.70\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.70\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.70\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.70. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_18504a4306cc5d44261e6d0f5ec47f54 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.70 | Release v0.3.70\n\n## 11. 安装坑 · 失败模式：installation: Release v0.3.71\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.71\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.71\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.71. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_4f40f1505195306061984312ceafb8d8 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.71 | Release v0.3.71\n\n## 12. 安装坑 · 失败模式：installation: Release v0.3.72\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.72\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.72\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.72. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_a62aef6e3f8ef8401a1d0bb3ce5d66d5 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.72 | Release v0.3.72\n\n## 13. 安装坑 · 失败模式：installation: Release v0.3.73\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.73\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.73\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.73. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_402be624902b0ff4a70763241e96f92a | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.73 | Release v0.3.73\n\n## 14. 安装坑 · 失败模式：installation: Release v0.3.74\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.74\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.74\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.74. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_f1c1782e6dc53172212d524d1e194b8f | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.74 | Release v0.3.74\n\n## 15. 安装坑 · 失败模式：installation: Release v0.3.75\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.75\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.75\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.75. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_65320a1ebb2900791f1e9b16cbf8e8d6 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.75 | Release v0.3.75\n\n## 16. 安装坑 · 失败模式：installation: Release v0.3.76\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Developers should check this installation risk before relying on the project: Release v0.3.76\n- 对用户的影响：Upgrade or migration may change expected behavior: Release v0.3.76\n- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Release v0.3.76. Context: Observed when using docker\n- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.\n- 证据：failure_mode_cluster:github_release | fmev_78ad7e0a2110bee066ed708a51554c0d | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.76 | Release v0.3.76\n\n## 17. 安装坑 · 来源证据：Release v0.3.15\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.15\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_ab726a10491d4c14b7fa95fd35beee64 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.15 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 18. 安装坑 · 来源证据：Release v0.3.16\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.16\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_bc556664008b404db3fc774023736dcb | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.16 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 19. 安装坑 · 来源证据：Release v0.3.17\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.17\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_013d47bb794f4f13b2f8e2a5859cdabf | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.17 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 20. 安装坑 · 来源证据：Release v0.3.22\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.22\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_4bfd96a53e7e4d859637f79a8ee350d1 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.22 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 21. 安装坑 · 来源证据：Release v0.3.23\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.23\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_38baea4290d648a887a4c7575a3c8c55 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.23 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 22. 安装坑 · 来源证据：Release v0.3.24\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.24\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_654bcb552e094dd18bcc59cfdc2a83b5 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.24 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 23. 安装坑 · 来源证据：Release v0.3.25\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.25\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_e2f6528bce8040c0bab4d074214b33c5 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.25 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 24. 安装坑 · 来源证据：Release v0.3.26\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.26\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_f358a19a360f476bbd41bb4e35bca86e | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.26 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 25. 安装坑 · 来源证据：Release v0.3.27\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.27\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_973b50ab39634ba4af49b7df022af9a1 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.27 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 26. 安装坑 · 来源证据：Release v0.3.28\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Release v0.3.28\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_ca63e0beff7c4da8844cdea3d52415b6 | https://github.com/jshsakura/oc-piloci/releases/tag/v0.3.28 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 27. 配置坑 · 可能修改宿主 AI 配置\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- 证据：capability.host_targets | github_repo:1219455965 | https://github.com/jshsakura/oc-piloci | host_targets=mcp_host, claude\n\n## 28. 能力坑 · 能力判断依赖假设\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:1219455965 | https://github.com/jshsakura/oc-piloci | README/documentation is current enough for a first validation pass.\n\n## 29. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:1219455965 | https://github.com/jshsakura/oc-piloci | last_activity_observed missing\n\n## 30. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:1219455965 | https://github.com/jshsakura/oc-piloci | no_demo; severity=medium\n\n## 31. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:1219455965 | https://github.com/jshsakura/oc-piloci | no_demo; severity=medium\n\n## 32. 维护坑 · 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:1219455965 | https://github.com/jshsakura/oc-piloci | issue_or_pr_quality=unknown\n\n## 33. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:1219455965 | https://github.com/jshsakura/oc-piloci | release_recency=unknown\n",
      "summary": "用户实践前最可能遇到的身份、安装、配置、运行和安全坑。",
      "title": "Pitfall Log / 踩坑日志"
    },
    "prompt_preview": {
      "asset_id": "prompt_preview",
      "filename": "PROMPT_PREVIEW.md",
      "markdown": "# oc-piloci - 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 jshsakura/oc-piloci.\n\nProject:\n- Name: oc-piloci\n- Repository: https://github.com/jshsakura/oc-piloci\n- Summary: piLoci is a self-hosted MCP memory server built to save tokens, I/O, and LLM calls on low-power devices like Raspberry Pi.\n- Host target: mcp_host, claude\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: piLoci is a self-hosted MCP memory server built to save tokens, I/O, and LLM calls on low-power devices like Raspberry Pi.\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: piLoci is a self-hosted MCP memory server built to save tokens, I/O, and LLM calls on low-power devices like Raspberry Pi.\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 piLoci. Produce one small intermediate artifact and wait for confirmation.\n2. getting-started: Getting Started. Produce one small intermediate artifact and wait for confirmation.\n3. architecture-overview: System Architecture. Produce one small intermediate artifact and wait for confirmation.\n4. mcp-server: MCP Server Implementation. Produce one small intermediate artifact and wait for confirmation.\n5. authentication: Authentication & Security. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/jshsakura/oc-piloci\n- https://github.com/jshsakura/oc-piloci#readme\n- README.md\n- PLAN.md\n- src/piloci/version.py\n- .env.example\n- docker-compose.yml\n- deploy/setup.sh\n- src/piloci/config.py\n- src/piloci/main.py\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "summary": "不安装项目也能感受能力节奏的安全试用 Prompt。",
      "title": "Prompt Preview / 安装前试用 Prompt"
    },
    "quick_start": {
      "asset_id": "quick_start",
      "filename": "QUICK_START.md",
      "markdown": "# Quick Start / 官方入口\n\n项目：jshsakura/oc-piloci\n\n## 官方安装入口\n\n### Python / pip · 官方安装入口\n\n```bash\npip install -U oc-piloci\n```\n\n来源：https://github.com/jshsakura/oc-piloci#readme\n\n## 来源\n\n- repo: https://github.com/jshsakura/oc-piloci\n- docs: https://github.com/jshsakura/oc-piloci#readme\n",
      "summary": "从项目官方 README 或安装文档提取的开工入口。",
      "title": "Quick Start / 官方入口"
    }
  },
  "validation_id": "dval_62149c64d2c84acca3177f8f49f930fc"
}
