{
  "canonical_name": "Evilander/Audrey",
  "compilation_id": "pack_fe52da66ecd44713a6bb013be9175cc0",
  "created_at": "2026-05-16T06:15:29.025284+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 `npx audrey` 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": "npx audrey",
      "sandbox_container_image": "node:22-slim",
      "sandbox_execution_backend": "docker",
      "sandbox_planner_decision": "deterministic_isolated_install",
      "sandbox_validation_id": "sbx_d3ff37d0ac634526b46b6084a3996db8"
    },
    "feedback_event_type": "project_pack_compilation_feedback",
    "learning_candidate_reasons": [],
    "template_gaps": []
  },
  "identity": {
    "canonical_id": "project_f0b2823ca69f8fc9b5862c0578f5ec5d",
    "canonical_name": "Evilander/Audrey",
    "homepage_url": null,
    "license": "unknown",
    "repo_url": "https://github.com/Evilander/Audrey",
    "slug": "audrey",
    "source_packet_id": "phit_e1185f748c1f4ccdaf8ccc20d6f3429d",
    "source_validation_id": "dval_bcf396c2d9534088a3eb88304c9c4a26"
  },
  "merchandising": {
    "best_for": "需要软件开发与交付能力，并使用 mcp_host的用户",
    "github_forks": 5,
    "github_stars": 23,
    "one_liner_en": "Persistent memory and continuity engine for Claude Code and AI agents.",
    "one_liner_zh": "Persistent memory and continuity engine for Claude Code and AI agents.",
    "primary_category": {
      "category_id": "software-development",
      "confidence": "medium",
      "name_en": "Software Development",
      "name_zh": "软件开发与交付",
      "reason": "matched_keywords:code, git"
    },
    "target_user": "使用 mcp_host, claude, claude_code 等宿主 AI 的用户",
    "title_en": "Audrey",
    "title_zh": "Audrey 能力包",
    "visible_tags": [
      {
        "label_en": "Browser Agents",
        "label_zh": "浏览器 Agent",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "product_domain-browser-agents",
        "type": "product_domain"
      },
      {
        "label_en": "Web Task Automation",
        "label_zh": "网页任务自动化",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "user_job-web-task-automation",
        "type": "user_job"
      },
      {
        "label_en": "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_e1185f748c1f4ccdaf8ccc20d6f3429d",
  "page_model": {
    "artifacts": {
      "artifact_slug": "audrey",
      "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": "npx audrey",
          "label": "Node.js / npx · 官方安装入口",
          "source": "https://github.com/Evilander/Audrey#readme",
          "verified": true
        }
      ],
      "display_tags": [
        "浏览器 Agent",
        "网页任务自动化",
        "浏览器自动化",
        "页面观察与动作规划",
        "评测体系"
      ],
      "eyebrow": "软件开发与交付",
      "glance": [
        {
          "body": "判断自己是不是目标用户。",
          "label": "最适合谁",
          "value": "需要软件开发与交付能力，并使用 mcp_host的用户"
        },
        {
          "body": "先理解能力边界，再决定是否继续。",
          "label": "核心价值",
          "value": "Persistent memory and continuity engine for Claude Code and AI agents."
        },
        {
          "body": "未完成验证前保持审慎。",
          "label": "继续前",
          "value": "publish to Doramagic.ai project surfaces"
        }
      ],
      "guardrail_source": "Boundary & Risk Card",
      "guardrails": [
        {
          "body": "Prompt Preview 只展示流程，不证明项目已安装或运行。",
          "label": "Check 1",
          "value": "不要把试用当真实运行"
        },
        {
          "body": "mcp_host, claude, claude_code",
          "label": "Check 2",
          "value": "确认宿主兼容"
        },
        {
          "body": "publish to Doramagic.ai project surfaces",
          "label": "Check 3",
          "value": "先隔离验证"
        }
      ],
      "mode": "mcp_config, recipe, host_instruction, eval, preflight",
      "pitfall_log": {
        "items": [
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Audrey 1.0.1 — honest GuardBench gate, Guard time decay, structured validate errors",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_135b992964ae468aa28f88ee639816d1 | https://github.com/Evilander/Audrey/releases/tag/v1.0.1 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：Audrey 1.0.1 — honest GuardBench gate, Guard time decay, structured validate errors",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Audrey Guard 0.23.0",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_9c913c644e2c4c099ea01523623f080e | https://github.com/Evilander/Audrey/releases/tag/v0.23.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：Audrey Guard 0.23.0",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.16.0",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_a7c5c62d4f034e50ba2e9c36e0798882 | https://github.com/Evilander/Audrey/releases/tag/v0.16.0 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：v0.16.0",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.16.1 — Windows MCP fix",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_c0141ccf0a3245ec8c8ba112af7948e0 | https://github.com/Evilander/Audrey/releases/tag/v0.16.1 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：v0.16.1 — Windows MCP fix",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.17.0",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_9617863b3f954035926b8670b5bbea29 | https://github.com/Evilander/Audrey/releases/tag/v0.17.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：v0.17.0",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。",
            "category": "配置坑",
            "evidence": [
              "capability.host_targets | github_repo:1161444210 | https://github.com/Evilander/Audrey | host_targets=mcp_host, claude, claude_code"
            ],
            "severity": "medium",
            "suggested_check": "列出会写入的配置文件、目录和卸载/回滚步骤。",
            "title": "可能修改宿主 AI 配置",
            "user_impact": "安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。"
          },
          {
            "body": "README/documentation is current enough for a first validation pass.",
            "category": "能力坑",
            "evidence": [
              "capability.assumptions | github_repo:1161444210 | https://github.com/Evilander/Audrey | README/documentation is current enough for a first validation pass."
            ],
            "severity": "medium",
            "suggested_check": "将假设转成下游验证清单。",
            "title": "能力判断依赖假设",
            "user_impact": "假设不成立时，用户拿不到承诺的能力。"
          },
          {
            "body": "未记录 last_activity_observed。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:1161444210 | https://github.com/Evilander/Audrey | last_activity_observed missing"
            ],
            "severity": "medium",
            "suggested_check": "补 GitHub 最近 commit、release、issue/PR 响应信号。",
            "title": "维护活跃度未知",
            "user_impact": "新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。"
          },
          {
            "body": "no_demo",
            "category": "安全/权限坑",
            "evidence": [
              "downstream_validation.risk_items | github_repo:1161444210 | https://github.com/Evilander/Audrey | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "进入安全/权限治理复核队列。",
            "title": "下游验证发现风险项",
            "user_impact": "下游已经要求复核，不能在页面中弱化。"
          },
          {
            "body": "no_demo",
            "category": "安全/权限坑",
            "evidence": [
              "risks.scoring_risks | github_repo:1161444210 | https://github.com/Evilander/Audrey | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "把风险写入边界卡，并确认是否需要人工复核。",
            "title": "存在评分风险",
            "user_impact": "风险会影响是否适合普通用户安装。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Audrey 1.0.0",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_d30d964956da40a2b5e26dc7404861f8 | https://github.com/Evilander/Audrey/releases/tag/v1.0.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：Audrey 1.0.0",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.22.2 — correctness pass + legitimate benchmarking",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_f9c004c97d31437ebdc3699d6f1ba2f4 | https://github.com/Evilander/Audrey/releases/tag/v0.22.2 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：v0.22.2 — correctness pass + legitimate benchmarking",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "issue_or_pr_quality=unknown。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:1161444210 | https://github.com/Evilander/Audrey | issue_or_pr_quality=unknown"
            ],
            "severity": "low",
            "suggested_check": "抽样最近 issue/PR，判断是否长期无人处理。",
            "title": "issue/PR 响应质量未知",
            "user_impact": "用户无法判断遇到问题后是否有人维护。"
          },
          {
            "body": "release_recency=unknown。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:1161444210 | https://github.com/Evilander/Audrey | release_recency=unknown"
            ],
            "severity": "low",
            "suggested_check": "确认最近 release/tag 和 README 安装命令是否一致。",
            "title": "发布节奏不明确",
            "user_impact": "安装命令和文档可能落后于代码，用户踩坑概率升高。"
          }
        ],
        "source": "ProjectPitfallLog + ProjectHitPacket + validation + community signals",
        "summary": "发现 14 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：安装坑 - 来源证据：Audrey 1.0.1 — honest GuardBench gate, Guard time decay, structured validate errors。",
        "title": "踩坑日志"
      },
      "snapshot": {
        "contributors": 4,
        "forks": 5,
        "license": "unknown",
        "note": "站点快照，非实时质量证明；用于开工前背景判断。",
        "stars": 23
      },
      "source_url": "https://github.com/Evilander/Audrey",
      "steps": [
        {
          "body": "不安装项目，先体验能力节奏。",
          "code": "preview",
          "title": "先试 Prompt"
        },
        {
          "body": "理解输入、输出、失败模式和边界。",
          "code": "manual",
          "title": "读说明书"
        },
        {
          "body": "把上下文交给宿主 AI 继续工作。",
          "code": "context",
          "title": "带给 AI"
        },
        {
          "body": "进入主力环境前先完成安装入口与风险边界验证。",
          "code": "verify",
          "title": "沙箱验证"
        }
      ],
      "subtitle": "Persistent memory and continuity engine for Claude Code and AI agents.",
      "title": "Audrey 能力包",
      "trial_prompt": "# Audrey - 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 Evilander/Audrey.\n\nProject:\n- Name: Audrey\n- Repository: https://github.com/Evilander/Audrey\n- Summary: Persistent memory and continuity engine for Claude Code and AI agents.\n- Host target: mcp_host, claude, claude_code\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: Persistent memory and continuity engine for Claude Code and AI agents.\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: Persistent memory and continuity engine for Claude Code and AI agents.\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. page-overview: Audrey Overview. Produce one small intermediate artifact and wait for confirmation.\n2. page-quick-start: Quick Start Guide. Produce one small intermediate artifact and wait for confirmation.\n3. page-system-architecture: System Architecture. Produce one small intermediate artifact and wait for confirmation.\n4. page-memory-model: Memory Model. Produce one small intermediate artifact and wait for confirmation.\n5. page-audrey-guard: Audrey Guard. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/Evilander/Audrey\n- https://github.com/Evilander/Audrey#readme\n- README.md\n- src/types.ts\n- src/audrey.ts\n- package.json\n- src/index.ts\n- src/controller.ts\n- src/server.ts\n- src/db.ts\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "voices": [
        {
          "body": "来源平台：github。github/github_release: Audrey 1.0.1 — honest GuardBench gate, Guard time decay, structured vali（https://github.com/Evilander/Audrey/releases/tag/v1.0.1）；github/github_release: Audrey 1.0.0（https://github.com/Evilander/Audrey/releases/tag/v1.0.0）；github/github_release: Audrey Guard 0.23.0（https://github.com/Evilander/Audrey/releases/tag/v0.23.0）；github/github_release: v0.22.2 — correctness pass + legitimate benchmarking（https://github.com/Evilander/Audrey/releases/tag/v0.22.2）；github/github_release: v0.17.0（https://github.com/Evilander/Audrey/releases/tag/v0.17.0）；github/github_release: v0.16.1 — Windows MCP fix（https://github.com/Evilander/Audrey/releases/tag/v0.16.1）；github/github_release: v0.16.0（https://github.com/Evilander/Audrey/releases/tag/v0.16.0）。这些是项目级外部声音，不作为单独质量证明。",
          "items": [
            {
              "kind": "github_release",
              "source": "github",
              "title": "Audrey 1.0.1 — honest GuardBench gate, Guard time decay, structured vali",
              "url": "https://github.com/Evilander/Audrey/releases/tag/v1.0.1"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "Audrey 1.0.0",
              "url": "https://github.com/Evilander/Audrey/releases/tag/v1.0.0"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "Audrey Guard 0.23.0",
              "url": "https://github.com/Evilander/Audrey/releases/tag/v0.23.0"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.22.2 — correctness pass + legitimate benchmarking",
              "url": "https://github.com/Evilander/Audrey/releases/tag/v0.22.2"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.17.0",
              "url": "https://github.com/Evilander/Audrey/releases/tag/v0.17.0"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.16.1 — Windows MCP fix",
              "url": "https://github.com/Evilander/Audrey/releases/tag/v0.16.1"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.16.0",
              "url": "https://github.com/Evilander/Audrey/releases/tag/v0.16.0"
            }
          ],
          "status": "已收录 7 条来源",
          "title": "社区讨论"
        }
      ]
    },
    "homepage_card": {
      "category": "软件开发与交付",
      "desc": "Persistent memory and continuity engine for Claude Code and AI agents.",
      "effort": "安装已验证",
      "forks": 5,
      "icon": "code",
      "name": "Audrey 能力包",
      "risk": "可发布",
      "slug": "audrey",
      "stars": 23,
      "tags": [
        "浏览器 Agent",
        "网页任务自动化",
        "浏览器自动化",
        "页面观察与动作规划",
        "评测体系"
      ],
      "thumb": "gray",
      "type": "MCP 配置"
    },
    "manual": {
      "markdown": "# https://github.com/Evilander/Audrey 项目说明书\n\n生成时间：2026-05-16 05:12:58 UTC\n\n## 目录\n\n- [Audrey Overview](#page-overview)\n- [Quick Start Guide](#page-quick-start)\n- [System Architecture](#page-system-architecture)\n- [Memory Model](#page-memory-model)\n- [Audrey Guard](#page-audrey-guard)\n- [Core Memory Operations](#page-memory-operations)\n- [Preflight and Reflexes](#page-reflexes-preflight)\n- [Data Storage](#page-data-storage)\n- [MCP Server](#page-mcp-server)\n- [REST API](#page-rest-api)\n\n<a id='page-overview'></a>\n\n## Audrey Overview\n\n### 相关页面\n\n相关主题：[System Architecture](#page-system-architecture), [Memory Model](#page-memory-model), [Quick Start Guide](#page-quick-start)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/Evilander/Audrey/blob/main/README.md)\n- [python/README.md](https://github.com/Evilander/Audrey/blob/main/python/README.md)\n- [src/audrey.ts](https://github.com/Evilander/Audrey/blob/main/src/audrey.ts)\n- [src/routes.ts](https://github.com/Evilander/Audrey/blob/main/src/routes.ts)\n- [src/impact.ts](https://github.com/Evilander/Audrey/blob/main/src/impact.ts)\n- [src/capsule.ts](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n- [src/redact.ts](https://github.com/Evilander/Audrey/blob/main/src/redact.ts)\n- [src/rules-compiler.ts](https://github.com/Evilander/Audrey/blob/main/src/rules-compiler.ts)\n- [mcp-server/index.ts](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n- [CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n</details>\n\n# Audrey Overview\n\nAudrey is a local-first memory firewall for AI agents. It provides a durable, SQLite-backed memory layer that enables AI agents to remember past mistakes, learned principles, and project-specific rules across sessions. Audrey acts as a continuity layer that sits under any local or sidecar agent loop, preventing agents from repeating the same mistakes and enabling smarter, more context-aware behavior.\n\n资料来源：[README.md:1-10]()\n\n## What Problem Audrey Solves\n\nAI agents typically suffer from \"cold start\" problems—they treat every new session as if they've never interacted with the project before. They repeat broken commands, lose project-specific rules, miss contradictions, and forget the exact mistakes they made yesterday.\n\nAudrey addresses this by implementing a closed feedback loop:\n\n1. **Record** what happened during agent actions\n2. **Remember** what mattered from those events\n3. **Check** before new actions using stored memories\n4. **Return** decisions (`allow`, `warn`, or `block`) with evidence\n5. **Validate** whether the memory helped improve outcomes\n\n资料来源：[README.md:25-40]()\n\n## Architecture Overview\n\nAudrey is built with a layered architecture that separates concerns between memory storage, retrieval, governance, and agent integration.\n\n```mermaid\ngraph TD\n    subgraph Client Layer\n        CLI[CLI Tool<br>npx audrey]\n        PythonSDK[Python SDK<br>audrey_memory]\n        MCPServer[MCP Server]\n    end\n    \n    subgraph Integration Layer\n        Hooks[Claude Code Hooks<br>PreToolUse/PostToolUse]\n        MCPConfig[MCP Config<br>Codex, VSCode, etc.]\n    end\n    \n    subgraph Core Engine\n        Guard[Audrey Guard<br>Memory-before-action]\n        Routes[REST API<br>/v1/*]\n    end\n    \n    subgraph Memory Layer\n        SQLite[(SQLite<br>WAL Mode)]\n        Episodic[Episodic<br>Memory]\n        Semantic[Semantic<br>Memory]\n        Procedural[Procedural<br>Memory]\n    end\n    \n    subgraph Embedding\n        ONNX[ONNX Runtime<br>Local Embeddings]\n        Providers[Cloud Providers<br>OpenAI, Anthropic]\n    end\n    \n    CLI --> Routes\n    PythonSDK --> Routes\n    MCPServer --> Routes\n    Hooks --> Guard\n    MCPConfig --> MCPServer\n    Guard --> Routes\n    Routes --> SQLite\n    SQLite --> Episodic\n    SQLite --> Semantic\n    SQLite --> Procedural\n    Routes --> ONNX\n    Routes --> Providers\n```\n\n资料来源：[README.md:1-50]()\n\n## Core Components\n\n### Memory Types\n\nAudrey manages three distinct types of memory, each serving a different purpose:\n\n| Memory Type | Purpose | Examples |\n|------------|---------|----------|\n| **Episodic** | Records specific events and outcomes | \"Deploy failed at 3:42 PM with OOM error\" |\n| **Semantic** | Stores learned facts, principles, and rules | \"Stripe rate limits are 100 req/s\" |\n| **Procedural** | Captures how-to knowledge and workflows | \"To deploy, run `npm run deploy` after `npm test`\" |\n\nEach memory type can be tagged, sourced, and validated independently. Memories gain salience through usage—memories that are repeatedly helpful become more prominent, while unused memories decay over time.\n\n资料来源：[README.md:40-55]()\n\n### Audrey Guard\n\nAudrey Guard is the core decision-making component that checks memories before agent actions execute. It implements a preflight check that returns structured decisions:\n\n```mermaid\ngraph LR\n    Action[Agent Action<br>tool + parameters] --> Guard\n    Guard --> Recall[Recall Relevant<br>Memories]\n    Recall --> Decision{Decision}\n    Decision -->|No issues| ALLOW[allow]\n    Decision -->|Potential risk| WARN[warn<br>+ evidence]\n    Decision -->|Dangerous| BLOCK[block<br>+ reason]\n    Decision -->|Uncertain| QUERY[Query<br>Human]\n```\n\nThe Guard returns a decision with supporting evidence, allowing the agent to make informed choices. When set to strict mode, warnings are treated as blocks.\n\n资料来源：[README.md:25-35]()\n\n### Memory Capsule\n\nThe Memory Capsule is a structured response format that bundles contextual information for agent preflight checks:\n\n| Section | Description |\n|---------|-------------|\n| `recent_changes` | Memories created/modified within the recent-change window |\n| `must_follow` | Critical rules tagged as mandatory |\n| `procedures` | Step-by-step workflows relevant to the query |\n| `user_preferences` | Explicitly stated user preferences |\n| `risks` | Warnings and risk indicators |\n| `uncertain_or_disputed` | Low-confidence or contested memories |\n\n资料来源：[src/capsule.ts:1-50]()\n\n### Impact Tracking\n\nAudrey tracks the effectiveness of its memories through a closed validation loop:\n\n```mermaid\ngraph TD\n    Action[Action with Memory] --> Outcome{Outcome}\n    Outcome -->|helpful| Boost[Boost salience<br>+usage_count]\n    Outcome -->|used| Maintain[Maintain salience]\n    Outcome -->|wrong| Challenge[Challenge memory<br>Decrease salience]\n    Boost --> Consolidation[Consolidation<br>Dream cycle]\n    Maintain --> Consolidation\n    Challenge --> Consolidation\n    Consolidation --> Principles[New Semantic<br>Principles]\n```\n\nOutcome types:\n- **helpful**: The memory contributed to a successful outcome\n- **used**: The memory was consulted but didn't directly contribute\n- **wrong**: The memory led to an incorrect decision\n\n资料来源：[src/impact.ts:1-60]()\n\n## Installation Methods\n\nAudrey supports multiple installation patterns depending on your use case.\n\n### CLI Installation\n\nFor direct terminal usage:\n\n```bash\nnpx audrey doctor          # Verify setup\nnpx audrey demo --scenario repeated-failure  # Run demo\nnpx audrey guard --tool Bash \"npm run deploy\"  # Check before action\n```\n\n资料来源：[README.md:55-65]()\n\n### MCP Server Integration\n\nFor integration with agents like Codex, Claude Desktop, Cursor, and VS Code:\n\n```bash\n# Generate MCP configuration\nnpx audrey mcp-config codex\nnpx audrey mcp-config generic\nnpx audrey mcp-config vscode\n```\n\n资料来源：[mcp-server/index.ts:1-40]()\n\n### Claude Code Hooks\n\nFor Claude Code, install directly and configure memory-before-action hooks:\n\n```bash\nnpx audrey install\nclaude mcp list\n\n# Apply hooks to project or user scope\nnpx audrey hook-config claude-code --apply --scope project  # Project-local\nnpx audrey hook-config claude-code --apply --scope user     # User-wide\n```\n\nThe generated hooks include:\n- `PreToolUse`: Runs `audrey guard --hook --fail-on-warn`\n- `PostToolUse`: Records successful tool executions\n- `PostToolUseFailure`: Records failed tool executions\n\n资料来源：[README.md:67-85]()\n\n### Python SDK\n\nFor Python-based agent integrations:\n\n```bash\npip install audrey-memory\n```\n\n```python\nfrom audrey_memory import Audrey\n\nbrain = Audrey(\n    base_url=\"http://127.0.0.1:7437\",\n    api_key=\"secret\",\n    agent=\"support-agent\",\n)\n\n# Encode new memories\nmemory_id = brain.encode(\n    \"Stripe returns HTTP 429 above 100 req/s\",\n    source=\"direct-observation\",\n    tags=[\"stripe\", \"rate-limit\"],\n)\n\n# Recall relevant memories\nresults = brain.recall(\"stripe rate limits\", limit=5)\n\n# Close connection\nbrain.close()\n```\n\n资料来源：[python/README.md:1-50]()\n\n## REST API Reference\n\nThe Audrey REST API exposes core memory operations via HTTP.\n\n### Endpoints Overview\n\n| Method | Endpoint | Description |\n|--------|----------|-------------|\n| `GET` | `/health` | Server health check |\n| `POST` | `/v1/encode` | Store a new memory |\n| `POST` | `/v1/recall` | Retrieve memories by semantic similarity |\n| `POST` | `/v1/preflight` | Memory-before-action check |\n| `POST` | `/v1/validate` | Submit outcome feedback |\n| `POST` | `/v1/impact` | Get impact statistics |\n\n资料来源：[src/routes.ts:1-80]()\n\n### Core API Operations\n\n#### Encode Memory\n\n```typescript\ninterface EncodeRequest {\n  content: string;           // The memory content\n  memory_type: 'episodic' | 'semantic' | 'procedural';\n  source: string;            // e.g., \"direct-observation\", \"told-by-user\"\n  tags?: string[];\n  private?: boolean;        // Agent-only memory\n  wait_for_consolidation?: boolean;\n}\n```\n\n资料来源：[src/routes.ts:80-120]()\n\n#### Recall Memories\n\n```typescript\ninterface RecallRequest {\n  query: string;\n  limit?: number;           // Default: 5\n  budget_chars?: number;    // Context budget\n  retrieval?: 'hybrid' | 'vector';  // Default: hybrid\n  mood?: {                  // Optional affect configuration\n    min_valence?: number;\n    min_arousal?: number;\n  };\n}\n```\n\n#### Preflight Check\n\n```typescript\ninterface PreflightRequest {\n  tool: string;             // e.g., \"Bash\", \"Write\"\n  action: string;           // The specific action/command\n  session_id?: string;\n  cwd?: string;\n  include_capsule?: boolean;\n  include_preflight?: boolean;\n  record_event?: boolean;\n}\n```\n\n#### Validate Outcome\n\n```typescript\ninterface ValidateRequest {\n  receipt_id: string;       // From preflight response\n  outcome: 'helpful' | 'used' | 'wrong';\n  evidence_feedback?: Record<string, 'helpful' | 'used' | 'wrong'>;\n  metadata?: Record<string, unknown>;\n}\n```\n\n资料来源：[src/routes.ts:120-200]()\n\n## Configuration\n\n### Environment Variables\n\n| Variable | Default | Purpose |\n|----------|---------|---------|\n| `AUDREY_DATA_DIR` | `~/.audrey` | SQLite data directory (set per tenant/agent) |\n| `AUDREY_EMBEDDING_PROVIDER` | `onnx` | Embedding provider: `onnx`, `openai`, `anthropic`, `google` |\n| `AUDREY_LLM_PROVIDER` | `openai` | LLM provider for consolidation |\n| `AUDREY_MODEL` | varies | Specific model to use |\n| `AUDREY_HOST` | `127.0.0.1` | REST sidecar bind address |\n| `AUDREY_PORT` | `7437` | REST sidecar port |\n| `AUDREY_API_KEY` | unset | Bearer token for non-loopback access |\n| `AUDREY_ALLOW_NO_AUTH` | `0` | Allow non-loopback without API key (not recommended) |\n| `AUDREY_ENABLE_ADMIN_TOOLS` | `0` | Enable export/import/forget routes |\n| `AUDREY_DEBUG` | `0` | Enable debug logging |\n| `AUDREY_PROFILE` | `0` | Emit per-stage diagnostics |\n| `AUDREY_DISABLE_WARMUP` | `0` | Skip embedding warmup at boot |\n| `AUDREY_CONTEXT_BUDGET_CHARS` | `4000` | Default capsule character budget |\n\n资料来源：[README.md:150-180]()\n\n### Data Isolation\n\n> SQLite uses WAL mode without an advisory lock, so two processes sharing a directory will contend on writes. Isolation is a hard requirement for multi-agent setups.\n\n**Important**: Set a distinct `AUDREY_DATA_DIR` per tenant, agent identity, or concurrent host to avoid write contention.\n\n资料来源：[README.md:55-60]()\n\n## Security\n\n### Redaction\n\nAudrey automatically redacts sensitive information from stored memories and logs:\n\n| Class | Patterns |\n|-------|----------|\n| `api_key` | `api_key`, `apiKey`, `API_KEY` patterns |\n| `password` | `password`, `passwd`, `pwd` |\n| `token` | `token`, `bearer_token`, `access_token`, `jwt` |\n| `secret` | `secret`, `client_secret`, `private_key` |\n\nThe redaction system walks JSON structures recursively and applies pattern matching to both keys and values.\n\n资料来源：[src/redact.ts:1-60]()\n\n### Access Control\n\n- HTTP API key comparison uses `crypto.timingSafeEqual` to prevent timing attacks\n- `audrey serve` defaults to binding `127.0.0.1` (was `0.0.0.0`)\n- Non-loopback bind requires `AUDREY_API_KEY` or explicit `AUDREY_ALLOW_NO_AUTH=1`\n- Private memories have ACL enforcement at the recall endpoint\n- `sanitizeRecallOptions()` allowlists HTTP body parameters to prevent option injection\n\n资料来源：[CHANGELOG.md:1-30]()\n\n## Production Readiness\n\n### Release Gates\n\n```bash\nnpm run release:gate           # Full release checklist\nnpm run python:release:check   # Python package verification\nnpm run bench:guard:card       # Guard performance benchmarks\nnpm run bench:guard:validate   # Guard accuracy validation\nnpx audrey doctor              # Runtime health check\nnpx audrey status --json --fail-on-unhealthy\n```\n\n### Production Checklist\n\n- Set one `AUDREY_DATA_DIR` per tenant, environment, or isolation boundary\n- Pin `AUDREY_EMBEDDING_PROVIDER` and `AUDREY_LLM_PROVIDER` explicitly\n- Back up the SQLite data directory before provider or dimension changes\n- Keep API keys and raw credentials out of encoded memory content\n- Use `AUDREY_API_KEY` if the REST sidecar is reachable beyond local process boundary\n- Run `audrey dream` on a schedule for consolidation and decay\n- Add application-level encryption, retention, access control, and audit logging for regulated environments\n\n资料来源：[README.md:100-125]()\n\n## Memory Lifecycle\n\n```mermaid\ngraph TD\n    Event[Agent Event<br>Action/Failure] --> Encode[Encode Memory<br>episodic]\n    Encode --> Salience[Initial Salience<br>from confidence]\n    Salience --> Usage[Usage Cycle]\n    \n    Usage --> Preflight[Preflight Check]\n    Preflight --> Decision[Guard Decision]\n    Decision --> Action[Execute Action]\n    Action --> Outcome{Outcome}\n    \n    Outcome -->|Success| Boost[Boost Salience<br/>usage_count++]\n    Outcome -->|Partial| Maintain[Maintain]\n    Outcome -->|Failure| Challenge[Challenge<br/>decay confidence]\n    \n    Boost --> Consolidation{Dream Cycle}\n    Maintain --> Consolidation\n    Challenge --> Consolidation\n    \n    Consolidation --> Principle[Extract Principle<br/>semantic memory]\n    Consolidation --> Decay[Apply Decay<br/>unused memories]\n    \n    Principle --> NewMemory[New Semantic<br/>Memory]\n    Decay --> Prune[Prune Very Low<br/>salience memories]\n```\n\n### Dream Cycle\n\nThe `memory_dream` operation consolidates episodes into principles and applies decay:\n\n- **Consolidation**: Groups related episodic memories into higher-level semantic principles\n- **Decay**: Reduces salience of memories that haven't been used recently\n- **Challenge**: Flags memories that led to wrong outcomes for review\n\n资料来源：[README.md:40-50]()\n\n## Supported Integrations\n\n| Agent/IDE | Integration Method | Features |\n|-----------|-------------------|----------|\n| Claude Code | Hooks + MCP | Full memory-guard loop |\n| Codex | MCP Config | Memory recall |\n| Claude Desktop | MCP | Memory access |\n| Cursor | MCP Config | Memory recall |\n| Windsurf | MCP Config | Memory recall |\n| VS Code | MCP Config | Memory recall |\n| JetBrains | MCP Config | Memory recall |\n| Ollama | Generic MCP | Memory recall |\n| Custom Agents | REST API / Python SDK | Full integration |\n\n资料来源：[README.md:10-20]()\n\n## Key Files Reference\n\n| File | Purpose |\n|------|---------|\n| `src/audrey.ts` | Core Audrey class with memory operations |\n| `src/routes.ts` | REST API route handlers |\n| `src/capsule.ts` | Memory capsule builder |\n| `src/impact.ts` | Impact tracking and validation |\n| `src/redact.ts` | Sensitive data redaction |\n| `src/rules-compiler.ts` | Rule file generation from memories |\n| `mcp-server/index.ts` | MCP server and CLI commands |\n| `python/` | Python SDK implementation |\n\n资料来源：[src/audrey.ts](), [src/routes.ts](), [src/capsule.ts](), [src/impact.ts](), [src/redact.ts](), [src/rules-compiler.ts](), [mcp-server/index.ts](), [python/README.md]()\n\n---\n\n<a id='page-quick-start'></a>\n\n## Quick Start Guide\n\n### 相关页面\n\n相关主题：[Audrey Overview](#page-overview)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/Evilander/Audrey/blob/main/README.md)\n- [CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n- [python/README.md](https://github.com/Evilander/Audrey/blob/main/python/README.md)\n- [src/routes.ts](https://github.com/Evilander/Audrey/blob/main/src/routes.ts)\n- [mcp-server/index.ts](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n- [src/impact.ts](https://github.com/Evilander/Audrey/blob/main/src/impact.ts)\n</details>\n\n# Quick Start Guide\n\n## Overview\n\nAudrey is a local-first memory firewall for AI agents that provides a durable memory layer they can check before executing tools. This guide covers installation, configuration, and basic usage patterns across all supported surfaces: CLI, REST API, JavaScript SDK, and Python client.\n\n## Prerequisites\n\n| Requirement | Version/Details |\n|-------------|-----------------|\n| Node.js | v18+ recommended |\n| npm | v8+ |\n| Python | 3.9+ (for Python SDK) |\n| SQLite | Built-in (bundled) |\n| Docker | Optional for containerized deployment |\n\n## Installation\n\n### CLI Installation\n\n```bash\nnpm install -g audrey\n```\n\nVerify installation:\n\n```bash\naudrey --version\n```\n\n### Python SDK Installation\n\n```bash\npip install audrey-memory\n```\n\n资料来源：[python/README.md:1-20](https://github.com/Evilander/Audrey/blob/main/python/README.md)\n\n## Quick Setup\n\n### 1. Run the Health Check\n\n```bash\naudrey doctor\n```\n\nThis command validates the installation and checks for any configuration issues.\n\n资料来源：[mcp-server/index.ts:85-120](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n\n### 2. Start the REST API Server\n\n```bash\nnpx audrey serve\n```\n\nBy default, the server binds to `127.0.0.1:7437`. Configure using environment variables:\n\n| Environment Variable | Default | Description |\n|---------------------|---------|-------------|\n| `AUDREY_PORT` | `7437` | REST API port |\n| `AUDREY_HOST` | `127.0.0.1` | REST sidecar bind address |\n| `AUDREY_API_KEY` | unset | Bearer token for non-loopback traffic |\n| `AUDREY_DATA_DIR` | `~/.audrey` | Data directory path |\n\n资料来源：[README.md:1-50](https://github.com/Evilander/Audrey/blob/main/README.md)\n\n### 3. Install MCP Configuration\n\nFor Claude Code integration:\n\n```bash\naudrey install --host claude-code\n```\n\nGenerate MCP config without applying:\n\n```bash\naudrey mcp-config --host claude-code --dry-run\n```\n\nApply project hooks:\n\n```bash\naudrey hook-config claude-code --apply --scope project\n```\n\nApply user hooks:\n\n```bash\naudrey hook-config claude-code --apply --scope user\n```\n\n资料来源：[mcp-server/index.ts:40-75](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n\n## Core Usage Patterns\n\n### Memory Guard Workflow\n\nThe primary safety loop that records events, checks memory before action, and returns decisions:\n\n```mermaid\ngraph TD\n    A[Agent Action] --> B[audrey guard --tool Bash npm run deploy]\n    B --> C{Memory Check}\n    C -->|allow| D[Execute Action]\n    C -->|warn| E[Execute with Warning]\n    C -->|block| F[Block Action]\n    D --> G[Record Outcome]\n    E --> G\n    F --> G\n    G --> H[Memory Consolidation]\n```\n\nExecute the guard command:\n\n```bash\naudrey guard --tool Bash \"npm run deploy\"\n```\n\nParameters:\n\n| Parameter | Description |\n|-----------|-------------|\n| `--tool` | Tool name (Bash, Write, Read, etc.) |\n| `--session-id` | Session identifier |\n| `--files` | File paths involved |\n| `--strict` | Fail on warning |\n\n资料来源：[mcp-server/index.ts:150-200](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n\n### Encoding Memories\n\n#### Via REST API\n\n```bash\ncurl -X POST http://127.0.0.1:7437/v1/encode \\\n  -H \"Authorization: Bearer secret\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"content\": \"Stripe returns HTTP 429 above 100 req/s\",\n    \"source\": \"direct-observation\",\n    \"tags\": [\"stripe\", \"rate-limit\"]\n  }'\n```\n\n#### Via Python SDK\n\n```python\nfrom audrey_memory import Audrey\n\nbrain = Audrey(\n    base_url=\"http://127.0.0.1:7437\",\n    api_key=\"secret\",\n    agent=\"support-agent\",\n)\n\nmemory_id = brain.encode(\n    \"Stripe returns HTTP 429 above 100 req/s\",\n    source=\"direct-observation\",\n    tags=[\"stripe\", \"rate-limit\"],\n)\n```\n\n资料来源：[python/README.md:25-45](https://github.com/Evilander/Audrey/blob/main/python/README.md)\n\n### Recalling Memories\n\n#### Via REST API\n\n```bash\ncurl -X POST http://127.0.0.1:7437/v1/recall \\\n  -H \"Authorization: Bearer secret\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"query\": \"stripe rate limits\",\n    \"limit\": 5,\n    \"retrieval\": \"hybrid\"\n  }'\n```\n\n#### Via Python SDK\n\n```python\nresults = brain.recall(\"stripe rate limits\", limit=5)\n```\n\n#### Available Recall Options\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `query` | string | required | Search query |\n| `limit` | number | 10 | Maximum results |\n| `budget_chars` | number | 4000 | Context budget in characters |\n| `retrieval` | string | \"hybrid\" | \"hybrid\" or \"vector\" mode |\n| `include_private` | boolean | false | Include private memories |\n| `agent` | string | - | Filter by agent name |\n\n资料来源：[src/routes.ts:1-50](https://github.com/Evilander/Audrey/blob/main/src/routes.ts)\n\n### Getting Memory Capsule\n\nA turn-sized memory packet containing relevant context:\n\n```bash\ncurl -X POST http://127.0.0.1:7437/v1/capsule \\\n  -H \"Authorization: Bearer secret\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"query\": \"current deploy status\",\n    \"budget_chars\": 4000\n  }'\n```\n\nThe capsule contains sections:\n\n- `recent_changes` - Memories from recent window\n- `must_follow` - Critical rules\n- `procedures` - Step-by-step memories\n- `user_preferences` - User-stated preferences\n- `risks` - Warnings and risks\n- `uncertain_or_disputed` - Low-confidence items\n\n资料来源：[src/capsule.ts:1-60](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n\n### Check Health\n\n```bash\ncurl http://127.0.0.1:7437/v1/status\n```\n\nAsync version:\n\n```python\nimport asyncio\nfrom audrey_memory import AsyncAudrey\n\nasync def main():\n    async with AsyncAudrey(base_url=\"http://127.0.0.1:7437\", api_key=\"secret\") as brain:\n        health = await brain.health()\n        print(health)\n\nasyncio.run(main())\n```\n\n资料来源：[python/README.md:50-70](https://github.com/Evilander/Audrey/blob/main/python/README.md)\n\n## Advanced CLI Commands\n\n### Dream - Consolidate Memory\n\n```bash\naudrey dream\n```\n\nTriggers memory consolidation process.\n\n### Reembed - Rebuild Vector Indices\n\n```bash\naudrey reembed\n```\n\nRebuilds embedding indices after schema changes.\n\n### Observe Tool\n\nRecord tool execution results:\n\n```bash\naudrey observe-tool --tool Bash --input '{\"command\": \"npm test\"}' --output '{\"exitCode\": 0}'\n```\n\n### Impact Report\n\nGenerate memory impact analysis:\n\n```bash\naudrey impact --window-days 30 --limit 10\n```\n\nThe report includes:\n\n- Memory counts by type (episodic, semantic, procedural)\n- Validated memories count\n- Outcome breakdown (helpful, wrong, used)\n- Top used memories\n- Weakest memories by salience\n- Recent activity\n\n资料来源：[src/impact.ts:1-80](https://github.com/Evilander/Audrey/blob/main/src/impact.ts)\n\n### Promote - Extract Rules\n\nPromote memory candidates to reviewable Markdown files:\n\n```bash\naudrey promote --yes\n```\n\nRules are saved to `.claude/rules/` with YAML front matter for traceability.\n\n### Check Status\n\n```bash\naudrey status\n```\n\nDisplays:\n\n- Current mood (valence, arousal)\n- Memory counts\n- Learned principles\n- Recent memories\n- Unresolved threads\n\n资料来源：[mcp-server/index.ts:200-280](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n\n## MCP Server Tools\n\nAudrey provides 20 tools via MCP stdio protocol:\n\n| Tool | Purpose |\n|------|---------|\n| `memory_encode` | Record new memories |\n| `memory_recall` | Retrieve relevant memories |\n| `memory_capsule` | Get turn-sized context packet |\n| `preflight_check` | Validate before action |\n| `record_outcome` | Record action results |\n| `promote_memory` | Convert to persistent rule |\n| `impact_report` | Analyze memory effectiveness |\n\nResources include:\n\n- `status` - System health\n- `recent` - Recent memories\n- `principles` - Semantic memories\n- `briefing` - Current context\n\nPrompts include:\n\n- `memory-recall` - Search memories\n- `memory-reflection` - Self-analysis\n\n资料来源：[README.md:60-90](https://github.com/Evilander/Audrey/blob/main/README.md)\n\n## Configuration Reference\n\n### Environment Variables\n\n| Variable | Default | Description |\n|----------|---------|-------------|\n| `AUDREY_PORT` | `7437` | REST API port |\n| `AUDREY_HOST` | `127.0.0.1` | Bind address |\n| `AUDREY_API_KEY` | unset | Bearer token |\n| `AUDREY_DATA_DIR` | `~/.audrey` | Data directory |\n| `AUDREY_ENABLE_ADMIN_TOOLS` | `0` | Enable export/import routes |\n| `AUDREY_PROMOTE_ROOTS` | unset | Extra write roots |\n| `AUDREY_DEBUG` | `0` | Enable debug logging |\n| `AUDREY_PROFILE` | `0` | Emit per-stage timings |\n| `AUDREY_DISABLE_WARMUP` | `0` | Skip embedding warmup |\n| `AUDREY_CONTEXT_BUDGET_CHARS` | `4000` | Default capsule budget |\n\n资料来源：[README.md:40-55](https://github.com/Evilander/Audrey/blob/main/README.md)\n\n### Privacy Controls\n\nBy default, private memories are ACL-protected:\n\n- `include_private: true` is restricted in HTTP API\n- `confidenceConfig` overrides are blocked via `sanitizeRecallOptions()`\n\nFor full control, use the SDK directly or enable admin tools:\n\n```bash\nAUDREY_ENABLE_ADMIN_TOOLS=1 audrey serve\n```\n\n资料来源：[CHANGELOG.md:1-30](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n## Deployment Options\n\n### Docker\n\n```bash\ndocker run -p 7437:7437 \\\n  -e AUDREY_API_KEY=secret \\\n  -v audrey-data:/root/.audrey \\\n  audrey:latest\n```\n\n### Docker Compose\n\nUse the provided `docker-compose.yml` for persistent deployments with volume mounts.\n\n### Host-Specific Setup\n\nGenerate platform-specific MCP configurations:\n\n```bash\naudrey mcp-config --host claude-code\naudrey mcp-config --host cursor\naudrey mcp-config --host windsurf\n```\n\n资料来源：[README.md:80-100](https://github.com/Evilander/Audrey/blob/main/README.md)\n\n## Next Steps\n\n- Review `audrey doctor` output for any warnings\n- Configure `AUDREY_API_KEY` for production deployments\n- Set up MCP integration for your preferred IDE/agent\n- Explore memory types: episodic, semantic, procedural\n- Enable impact tracking to measure memory effectiveness\n\nFor detailed API documentation, see the REST API endpoints at `/v1/*` when the server is running.\n\n---\n\n<a id='page-system-architecture'></a>\n\n## System Architecture\n\n### 相关页面\n\n相关主题：[Audrey Overview](#page-overview), [Memory Model](#page-memory-model), [Data Storage](#page-data-storage), [MCP Server](#page-mcp-server), [REST API](#page-rest-api)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/audrey.ts](https://github.com/Evilander/Audrey/blob/main/src/audrey.ts)\n- [src/controller.ts](https://github.com/Evilander/Audrey/blob/main/src/controller.ts)\n- [src/server.ts](https://github.com/Evilander/Audrey/blob/main/src/server.ts)\n- [src/db.ts](https://github.com/Evilander/Audrey/blob/main/src/db.ts)\n- [mcp-server/index.ts](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n- [src/embedding.ts](https://github.com/Evilander/Audrey/blob/main/src/embedding.ts)\n</details>\n\n# System Architecture\n\n## Overview\n\nAudrey is a local-first memory runtime designed to give AI agents persistent, queryable memory across sessions. It operates as a **stateful infrastructure layer** that records observations, consolidates principles, and provides memory-before-action checks through multiple interfaces.\n\nThe system is built around a closed-loop safety architecture where every tool action can be validated against stored memory before execution, returning `allow`, `warn`, or `block` decisions with supporting evidence.\n\n## Core Design Principles\n\n| Principle | Description |\n|-----------|-------------|\n| Local-first | All data stored in local SQLite; no external database required |\n| Agent-agnostic | Works with Codex, Claude Code, Cursor, Windsurf, VS Code, JetBrains, Ollama, and custom agents |\n| Safety loop | Pre-action validation through Audrey Guard before tool execution |\n| Isolation per tenant | One `AUDREY_DATA_DIR` per tenant/agent/isolation boundary |\n| Privacy-by-default | Audrey Guard redacts tool traces; private memory ACL enforcement |\n\n## High-Level Component Architecture\n\n```mermaid\ngraph TD\n    subgraph \"Agent Host\"\n        A[AI Agent<br/>Claude Code / Codex / Cursor]\n    end\n    \n    subgraph \"Audrey Runtime\"\n        CLI[CLI<br/>doctor, demo, guard,<br/>install, status, dream]\n        MCP[MCP Server<br/>stdio interface]\n        REST[REST API<br/>Hono server :7437]\n        SDK[JS SDK<br/>TypeScript/Node]\n        PY[Python SDK<br/>audrey-memory]\n    end\n    \n    subgraph \"Core Engine\"\n        AUD[Audrey Core<br/>encode, recall, consolidate,<br/>validate, impact]\n        MEM[(Memory Store<br/>SQLite + sqlite-vec)]\n        EMB[Embedding Engine<br/>ONNX runtime]\n        CAUSAL[Causal Validation<br/>confidence scoring]\n    end\n    \n    A <--> MCP\n    A <--> REST\n    CLI --> MCP\n    CLI --> REST\n    SDK --> REST\n    PY --> REST\n    AUD <--> MEM\n    AUD <--> EMB\n    AUD <--> CAUSAL\n```\n\n## Component Specifications\n\n### MCP Server (`mcp-server/index.ts`)\n\nThe MCP stdio server provides 20+ tools plus status, recent, principles resources and briefing/recall/reflection prompts.\n\n| Interface Type | Count | Purpose |\n|----------------|-------|---------|\n| Tools | 20+ | encode, recall, capsule, guard, promote, impact, dream, reembed, observe-tool |\n| Resources | 3 | status, recent, principles |\n| Prompts | 3 | briefing, recall, reflection |\n\nThe server processes CLI arguments before entering stdio mode to handle `--help`, `--version`, and subcommands like `install`, `mcp-config`, `hook-config`. 资料来源：[mcp-server/index.ts:1-100]()\n\n### REST API (`src/routes.ts`)\n\nHono-based HTTP server exposing the following endpoints:\n\n| Endpoint | Method | Purpose |\n|----------|--------|---------|\n| `/health` | GET | Health check |\n| `/v1/encode` | POST | Store memory with source, tags, salience |\n| `/v1/recall` | POST | Retrieve relevant context |\n| `/v1/capsule` | POST | Get turn-sized memory packet |\n| `/v1/status` | GET | Runtime status |\n| `/v1/observe` | POST | Record tool outcome |\n| `/v1/validate` | POST | Validate memory usefulness |\n\n**Security**: HTTP recall/capsule routes use `sanitizeRecallOptions()` to prevent private-memory ACL bypass via caller-supplied options. API key comparison uses `crypto.timingSafeEqual` to prevent timing attacks. 资料来源：[src/routes.ts:1-80]()\n\n### Audrey Core (`src/audrey.ts`)\n\nThe central engine handling memory operations:\n\n```mermaid\ngraph LR\n    ENC[encode] --> VEC[Vector Embedding]\n    ENC --> DB[(SQLite)]\n    REC[recall] --> VEC\n    REC --> DB\n    VEC --> EMB[Embedding Engine]\n    DB --> CAUSAL[Causal Validation]\n    CAUSAL --> CONF[Confidence Scoring]\n```\n\n**Key operations:**\n- `encode()`: Stores episodic, semantic, or procedural memory with vector embedding\n- `recall()`: Retrieves memories using hybrid (vector + FTS) search\n- `consolidate()`: Extracts principles from repeated evidence\n- `decay()`: Reduces authority of stale, low-confidence memories\n- `beforeAction()`: Guard check returning `allow`/`warn`/`block`\n- `afterAction()`: Records tool execution outcomes\n\n### Storage Layer (`src/db.ts`)\n\nSQLite with `sqlite-vec` extension for vector search.\n\n| Feature | Configuration |\n|---------|---------------|\n| Mode | WAL (Write-Ahead Logging) |\n| Concurrency | No advisory lock; single writer per `AUDREY_DATA_DIR` |\n| Indexing | sqlite-vec for vector similarity; FTS for full-text |\n| Isolation | One directory per tenant required |\n\nThe `AUDREY_PRAGMA_DEFAULTS` environment variable (default `1`) applies custom PRAGMA tuning. Set to `0` to revert to better-sqlite3 defaults.\n\n### Embedding Engine (`src/embedding.ts`)\n\nONNX runtime for local vector embedding without external API calls by default.\n\n| Feature | Behavior |\n|---------|----------|\n| Warmup | Background embedding warmup at MCP boot (skippable with `AUDREY_DISABLE_WARMUP=1`) |\n| Cold-start | First encode: ~525ms cold, ~28ms warm |\n| Verbosity | `AUDREY_ONNX_VERBOSE=1` restores EP-assignment warnings |\n| Reuse | Validation, interference, affect resonance reuse main content vector |\n\n**Performance targets (v0.22.0):**\n- Encode p50: 15.2ms (40% faster than prior)\n- Hybrid recall p50: 14.3ms (2.1x faster)\n- Embedding reuse eliminated 3 of 4 redundant calls\n\n## Memory Model Architecture\n\n```mermaid\ngraph TD\n    subgraph \"Memory Types\"\n        EPI[Episodic<br/>Specific observations,<br/>tool results, facts]\n        SEM[Semantic<br/>Consolidated principles<br/>from evidence]\n        PROC[Procedural<br/>Remembered ways to act,<br/>avoid, retry, verify]\n    end\n    \n    subgraph \"Memory Properties\"\n        AFF[Affect & Salience<br/>Emotional weight, importance]\n        DEC[Interference & Decay<br/>Stale/conflicting lose authority]\n        CON[Contradiction Handling<br/>Competing claims tracked]\n    end\n    \n    EPI --> AFF\n    SEM --> AFF\n    PROC --> AFF\n    EPI --> DEC\n    SEM --> CON\n    CON --> DEC\n```\n\n### Memory Types\n\n| Type | Description | Example |\n|------|-------------|---------|\n| Episodic | Specific observations, tool results, session facts | \"Stripe returns HTTP 429 above 100 req/s\" |\n| Semantic | Consolidated principles from repeated evidence | \"Always check rate limits before batch operations\" |\n| Procedural | Remembered ways to act, avoid, retry, verify | \"Retry with exponential backoff on network failures\" |\n\n### Capsule Generation (`src/capsule.ts`)\n\nThe capsule endpoint assembles a turn-sized memory packet with sections:\n\n```mermaid\ngraph TD\n    CAP[POST /v1/capsule] --> SEC[Section Assigner]\n    SEC --> R[recent_changes<br/>Created/reinforced recently]\n    SEC --> M[must_follow<br/>Critical rules]\n    SEC --> P[procedures<br/>Procedural memories]\n    SEC --> U[user_preferences<br/>Stated or tagged preferences]\n    SEC --> RK[risks<br/>Warnings and recent failures]\n    SEC --> UN[uncertain_or_disputed<br/>Disputed or low-confidence]\n```\n\nEach section includes a `reason` field explaining why the entry was included. Recent tool failures (last 7 days) are automatically added to risks when `includeRisks` is enabled.\n\n## Audrey Guard Safety Loop\n\n```mermaid\nsequenceDiagram\n    participant Agent\n    participant Guard as Audrey Guard\n    participant Memory as Memory Store\n    participant LLM as LLM Provider\n    \n    Agent->>Guard: tool + action\n    Guard->>Memory: recall(relevant)\n    Memory-->>Guard: context entries\n    Guard->>LLM: preflight check\n    LLM-->>Guard: decision + evidence\n    Guard-->>Agent: allow/warn/block + reasoning\n    Agent->>Guard: outcome (success/failure/wrong)\n    Guard->>Memory: record outcome\n```\n\n### Guard Modes\n\n| Mode | Behavior |\n|------|----------|\n| `allow` | Action proceeds normally |\n| `warn` | Action allowed but user notified |\n| `block` | Action prevented with evidence |\n| `caution` | Maps to `warn` display |\n\nCLI usage:\n```bash\naudrey guard --tool Bash \"npm run deploy\"\naudrey guard --hook --fail-on-warn  # For hook integration\n```\n\n### Validation Pipeline\n\nThe causal validation system (via `src/causal.ts` and `src/validate.ts`) evaluates whether stored memories actually helped:\n\n1. **Confidence scoring** uses reinforcement formula from `confidence.ts`\n2. **Evidence tracking** updates `usage_count` and `last_used_at`\n3. **Outcome classification**: `used`, `helpful`, `wrong`\n4. **Impact metrics** aggregated by memory type\n\n## Deployment Architecture\n\n```mermaid\ngraph LR\n    subgraph \"Deployment Options\"\n        NPM[npm package<br/>npx audrey]\n        DOCKER[Docker<br/>audrey-runtime]\n        COMPOSE[Docker Compose<br/>Full stack]\n        HOST[MCP Config<br/>Host-specific]\n    end\n    \n    subgraph \"Environment\"\n        ENV1[AUDREY_DATA_DIR]\n        ENV2[AUDREY_LLM_PROVIDER]\n        ENV3[AUDREY_EMBEDDING_PROVIDER]\n        ENV4[AUDREY_API_KEY]\n    end\n    \n    NPM --> ENV1\n    DOCKER --> ENV1\n    COMPOSE --> ENV1\n    HOST --> ENV2\n    HOST --> ENV3\n```\n\n### Interface Options by Agent\n\n| Agent | Integration |\n|-------|-------------|\n| Claude Code | `npx audrey install --host claude-code` + hook-config |\n| Claude Desktop | MCP config via `npx audrey mcp-config generic` |\n| Codex | MCP config via `npx audrey mcp-config codex` |\n| Cursor | MCP config |\n| Windsurf | MCP config |\n| VS Code | MCP config |\n| JetBrains | MCP config |\n| Ollama | MCP config |\n| Custom | REST API or JS/Python SDK |\n\n### REST Sidecar Security\n\n| Configuration | Bind Address | Auth Required |\n|---------------|--------------|---------------|\n| Default | `127.0.0.1:7437` | No (loopback) |\n| Production | `0.0.0.0:7437` | `AUDREY_API_KEY` required |\n| Unsafe override | Any host | `AUDREY_ALLOW_NO_AUTH=1` (not recommended) |\n\n`AUDREY_HOST` env var explicitly opts in to network exposure.\n\n## CLI Architecture\n\n```mermaid\ngraph TD\n    CLI[audrey CLI] --> PARSE[Argument Parser]\n    PARSE --> KNOWN[Known Subcommands]\n    KNOWN --> INSTALL[install]\n    KNOWN --> UNINSTALL[uninstall]\n    KNOWN --> MCP[mcp-config]\n    KNOWN --> HOOK[hook-config]\n    KNOWN --> DOCTOR[doctor]\n    KNOWN --> DEMO[demo]\n    KNOWN --> GUARD[guard]\n    KNOWN --> DREAM[dream]\n    KNOWN --> REEMBED[reembed]\n    KNOWN --> PROMOTE[promote]\n    KNOWN --> IMPACT[impact]\n    KNOWN --> UNKNOWN[Unknown/No subcommand]\n    \n    UNKNOWN --> TTY{Human TTY?}\n    TTY -->|Yes| HELP[Print help]\n    TTY -->|No| MCP_SERVER[Start MCP server]\n    \n    INSTALL --> HOST[Host-specific config]\n    HOOK --> APPLY[Apply hooks to settings]\n    PROMOTE --> WRITES[Write to project files]\n```\n\n### Key CLI Commands\n\n| Command | Purpose |\n|---------|---------|\n| `audrey doctor` | Diagnose configuration issues |\n| `audrey status` | Show runtime health |\n| `audrey demo` | Run interactive demonstration |\n| `audrey guard` | Check action against memory |\n| `audrey install` | Register Audrey with host |\n| `audrey mcp-config` | Generate MCP server configuration |\n| `audrey hook-config` | Generate agent hook configuration |\n| `audrey dream` | Trigger consolidation and decay |\n| `audrey reembed` | Re-embed all memories |\n| `audrey promote` | Write memories to project rules |\n| `audrey impact` | Show memory effectiveness report |\n\n## Configuration Environment Variables\n\n| Variable | Default | Purpose |\n|----------|---------|---------|\n| `AUDREY_DATA_DIR` | System temp | Memory storage directory |\n| `AUDREY_HOST` | `127.0.0.1` | REST sidecar bind address |\n| `AUDREY_PORT` | `7437` | REST sidecar port |\n| `AUDREY_API_KEY` | unset | Bearer token for non-loopback |\n| `AUDREY_LLM_PROVIDER` | Configured | LLM for causal/validation |\n| `AUDREY_EMBEDDING_PROVIDER` | Configured | Embedding generation |\n| `AUDREY_EMBEDDING_MODEL` | Configured | Model name for embeddings |\n| `AUDREY_EMBEDDING_DIM` | Configured | Vector dimensions |\n| `AUDREY_CONTEXT_BUDGET_CHARS` | `4000` | Capsule character budget |\n| `AUDREY_DISABLE_WARMUP` | `0` | Skip embedding warmup |\n| `AUDREY_DEBUG` | `0` | Enable MCP debug logs |\n| `AUDREY_PROFILE` | `0` | Emit per-stage timings |\n| `AUDREY_PROMOTE_ROOTS` | unset | Allowed write roots for promote |\n| `AUDREY_ENABLE_ADMIN_TOOLS` | `0` | Enable export/import/forget |\n\n## SDK Architecture\n\n### JavaScript SDK\n\nDirect TypeScript/Node import from `audrey` package:\n\n```typescript\nimport Audrey from 'audrey';\n\nconst brain = new Audrey({ \n  baseUrl: 'http://127.0.0.1:7437',\n  agent: 'support-agent'\n});\n\nawait brain.encode('Deploy failed due to OOM', { \n  source: 'direct-observation' \n});\n\nconst results = await brain.recall('deploy failure', { limit: 5 });\n```\n\n### Python SDK (`audrey-memory`)\n\n```python\nfrom audrey_memory import Audrey\n\nbrain = Audrey(\n    base_url=\"http://127.0.0.1:7437\",\n    api_key=\"secret\",\n    agent=\"support-agent\",\n)\n\nmemory_id = brain.encode(\n    \"Stripe returns HTTP 429 above 100 req/s\",\n    source=\"direct-observation\",\n    tags=[\"stripe\", \"rate-limit\"],\n)\n```\n\nAsync clients available via `AsyncAudrey` / `asyncio` support.\n\n## Release Readiness Gates\n\n```mermaid\ngraph LR\n    GATE[release:gate] --> CI[CI Workflow]\n    GATE --> PY[python:release:check]\n    GATE --> BENCH[bench:guard:*]\n    GATE --> DOCTOR[audrey doctor]\n    GATE --> DEMO[audrey demo]\n```\n\n| Check | Purpose |\n|-------|---------|\n| `npm run release:gate` | Full release readiness checklist |\n| `npm run python:release:check` | Python artifact verification |\n| `npm run bench:guard:card` | Guard benchmark suite |\n| `npm run bench:guard:validate` | Validation benchmarks |\n| `npx audrey doctor` | Runtime diagnostics |\n| `npx audrey demo` | Functional verification |\n\n## Data Flow: Encode to Recall\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant API as REST API<br/>/v1/encode\n    participant Audrey as Audrey Core\n    participant Embed as Embedding Engine\n    participant DB as SQLite + vec\n    \n    Client->>API: POST /v1/encode<br/>content, source, tags\n    API->>Audrey: encode(content, options)\n    Audrey->>Embed: generateEmbedding(content)\n    Embed-->>Audrey: vector[1536]\n    Audrey->>DB: INSERT memory + vector\n    DB-->>Audrey: memory_id\n    Audrey-->>API: { id, confidence, ... }\n    API-->>Client: { id, ... }\n```\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant API as REST API<br/>/v1/recall\n    participant Audrey as Audrey Core\n    participant Embed as Embedding Engine\n    participant DB as SQLite + vec\n    participant Causal as Causal Validator\n    \n    Client->>API: POST /v1/recall<br/>query, limit, scope\n    API->>Audrey: recall(query, options)\n    Audrey->>Embed: generateEmbedding(query)\n    Embed-->>Audrey: query_vector\n    Audrey->>DB: hybrid search<br/>vector_similarity + FTS\n    DB-->>Audrey: [entries]\n    Audrey->>Causal: score(entries)\n    Causal-->>Audrey: [scored_entries]\n    Audrey-->>API: { results, ... }\n    API-->>Client: { results, ... }\n```\n\n## Key Architectural Decisions\n\n| Decision | Rationale |\n|----------|----------|\n| Local-only storage | Eliminates dependency on external services; ensures data isolation |\n| SQLite + sqlite-vec | Proven reliability, no separate vector DB required |\n| WAL mode without advisory lock | Performance for single-process; isolation required for multi-agent |\n| Separate `AUDREY_DATA_DIR` per tenant | Hard isolation boundary; prevents cross-tenant contamination |\n| REST sidecar defaulting to loopback | Security by default; non-loopback requires explicit opt-in |\n| Embedding warmup at boot | Eliminates cold-start penalty (~18.7x improvement) |\n| Closed-loop validation | Closed feedback loop lifts autopilot ALIVE dimension |\n\n---\n\n<a id='page-memory-model'></a>\n\n## Memory Model\n\n### 相关页面\n\n相关主题：[System Architecture](#page-system-architecture), [Core Memory Operations](#page-memory-operations), [Preflight and Reflexes](#page-reflexes-preflight)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/consolidate.ts](https://github.com/Evilander/Audrey/blob/main/src/consolidate.ts)\n- [src/decay.ts](https://github.com/Evilander/Audrey/blob/main/src/decay.ts)\n- [src/interference.ts](https://github.com/Evilander/Audrey/blob/main/src/interference.ts)\n- [src/affect.ts](https://github.com/Evilander/Audrey/blob/main/src/affect.ts)\n- [src/confidence.ts](https://github.com/Evilander/Audrey/blob/main/src/confidence.ts)\n- [src/causal.ts](https://github.com/Evilander/Audrey/blob/main/src/causal.ts)\n</details>\n\n# Memory Model\n\nAudrey's Memory Model is a cognitive-inspired system that provides AI agents with persistent, evolving memory capabilities. Unlike simple vector databases, it implements a multi-layered memory architecture that mirrors human memory structures—episodic, semantic, and procedural—while incorporating affect, salience, and decay mechanisms to ensure memories remain relevant and actionable.\n\n## Architecture Overview\n\nThe Memory Model consists of several interconnected subsystems that work together to store, retrieve, consolidate, and forget information over time.\n\n```mermaid\ngraph TD\n    A[User/Agent Input] --> B[Episodic Memory]\n    B --> C[Consolidation Process]\n    C --> D[Semantic Memory]\n    C --> E[Procedural Memory]\n    D --> F[Confidence Scoring]\n    E --> F\n    B --> G[Affect Module]\n    F --> G\n    G --> H[Salience Calculation]\n    H --> I[Recall Ranking]\n    I --> J[Preflight Check]\n    J --> K[Guard Decision]\n    L[Interference] -.->F\n    L -.->I\n    M[Decay Engine] -.->D\n    M -.->E\n```\n\n资料来源：[README.md](https://github.com/Evilander/Audrey/blob/main/README.md)\n\n## Memory Types\n\nAudrey distinguishes between three primary memory types, each serving a distinct role in agent cognition.\n\n### Episodic Memory\n\nEpisodic memory stores specific observations, tool results, preferences, and session facts. These are the raw recordings of events and interactions that agents experience directly.\n\n| Property | Description |\n|----------|-------------|\n| `memory_type` | `episode` |\n| `source` | `direct-observation`, `told-by-user`, `retrieved` |\n| `confidence` | Initial high confidence that decays over time |\n| `retrieval_count` | Number of times this memory was recalled |\n\n资料来源：[src/capsule.ts](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n\n### Semantic Memory\n\nSemantic memory represents consolidated principles extracted from repeated evidence. These memories encode general knowledge and learned rules that persist beyond specific sessions.\n\n| Property | Description |\n|----------|-------------|\n| `memory_type` | `semantic` |\n| `confidence` | Derived from supporting episode frequency |\n| `supporting_count` | Number of episodes supporting this principle |\n| `challenge_count` | Number of contradictory episodes |\n\n资料来源：[src/causal.ts](https://github.com/Evilander/Audrey/blob/main/src/causal.ts)\n\n### Procedural Memory\n\nProcedural memory stores remembered ways to act, avoid, retry, or verify. These encode action patterns and procedures that agents have learned through experience.\n\n| Property | Description |\n|----------|-------------|\n| `memory_type` | `procedural` |\n| `tags` | `procedure`, `retry`, `avoid`, `verify` |\n| `confidence` | Reinforced by successful outcomes |\n\n资料来源：[src/capsule.ts](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n\n## Confidence System\n\nThe confidence system is the foundational mechanism that determines memory reliability and recall priority. It incorporates multiple signals including recency, reinforcement, and affect.\n\n### Confidence Calculation\n\n```mermaid\ngraph LR\n    A[Base Confidence] --> B[Recency Decay]\n    B --> C[Reinforcement Boost]\n    C --> D[Affect Adjustment]\n    D --> E[Interference Penalty]\n    E --> F[Final Confidence]\n```\n\n资料来源：[src/confidence.ts](https://github.com/Evilander/Audrey/blob/main/src/confidence.ts)\n\n### Recency Decay\n\nMemory confidence decreases over time through a half-life decay mechanism. Memories become less authoritative unless reinforced through retrieval or validation.\n\n```typescript\n// From src/confidence.ts\nrecencyDecay(halfLifeDays: number, createdAt: Date): number\n```\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `halfLifeDays` | `number` | Days until confidence halves |\n| `createdAt` | `Date` | Memory creation timestamp |\n\nThe decay function throws `RangeError` when `halfLifeDays <= 0` to prevent NaN or Infinity results.\n\n资料来源：[src/confidence.ts](https://github.com/Evilander/Audrey/blob/main/src/confidence.ts)\n\n### Reinforcement Formula\n\nValidation outcomes reinforce or diminish memory confidence through the feedback loop:\n\n| Outcome | Effect |\n|---------|--------|\n| `helpful` | Increases salience, bumps `retrieval_count` for semantic/procedural |\n| `wrong` | Decreases salience, bumps `challenge_count` for semantic |\n| `used` | Neutral signal with smaller salience delta |\n\nThe math reuses the existing reinforcement formula from `confidence.ts`.\n\n资料来源：[CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n## Consolidation System\n\nConsolidation transforms episodic memories into semantic and procedural knowledge through periodic processing, often called \"dream\" mode.\n\n### Consolidation Workflow\n\n```mermaid\ngraph TD\n    A[Nightly Dream Process] --> B[Identify Repeated Episodes]\n    B --> C[Extract Common Patterns]\n    C --> D[Generate Semantic Principles]\n    C --> E[Extract Procedures]\n    D --> F[Create New Semantic Memory]\n    E --> G[Create/Update Procedural Memory]\n    F --> H[Link Supporting Episodes]\n    G --> H\n```\n\n资料来源：[README.md](https://github.com/Evilander/Audrey/blob/main/README.md)\n\n### Consolidation Implementation\n\nThe consolidation process runs through `memory_dream` and is scheduled to ensure that consolidation and decay remain current.\n\n```typescript\n// From src/consolidate.ts - conceptual interface\nasync function consolidate(audrey: Audrey, options?: ConsolidateOptions): Promise<ConsolidationResult>\n```\n\nConsolidation moves SELECTs inside the surrounding transaction to prevent concurrent writers from slipping rows in or out between read and write.\n\n资料来源：[CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n## Decay Engine\n\nThe decay engine implements forgetting curves that reduce memory authority over time, ensuring stale information doesn't dominate recall.\n\n### Decay Mechanism\n\n```mermaid\ngraph LR\n    A[Time Passes] --> B{Still Being Used?}\n    B -->|Yes| C[Decay Paused]\n    B -->|No| D[Gradual Decay]\n    D --> E[Confidence Decreases]\n    E --> F[Memory Becomes Less Authoritative]\n```\n\n资料来源：[src/decay.ts](https://github.com/Evilander/Audrey/blob/main/src/decay.ts)\n\n### Decay Parameters\n\n| Parameter | Default | Purpose |\n|-----------|---------|---------|\n| `halfLifeDays` | Configurable | Base decay rate |\n| `minConfidence` | 0.1 | Floor value |\n| `decayEnabled` | true | Global on/off |\n\nDecay applies to semantic and procedural memories differently, with semantic memories decaying faster unless reinforced.\n\n资料来源：[src/decay.ts](https://github.com/Evilander/Audrey/blob/main/src/decay.ts)\n\n## Affect and Salience\n\nAffect (emotional weight and importance) influences salience, determining which memories demand attention and which fade into background knowledge.\n\n### Affect Module\n\n```mermaid\ngraph TD\n    A[Memory Event] --> B[Detect Emotional Signals]\n    B --> C[Calculate Valence]\n    B --> D[Calculate Arousal]\n    C --> E[Determine Mood State]\n    D --> E\n    E --> F[Affect Boost/Penalty]\n    F --> G[Effective Salience]\n```\n\n资料来源：[src/affect.ts](https://github.com/Evilander/Audrey/blob/main/src/affect.ts)\n\n### Salience Calculation\n\nEffective salience is clamped to the range `[0, 1]` to prevent unbounded values from extreme arousal boosts. The formula considers:\n\n- Memory type (episodic, semantic, procedural)\n- Confidence level\n- Recency\n- Emotional valence and arousal\n\n```typescript\n// From src/affect.ts\neffectiveSalience(baseSalience: number, arousalBoost: number): number\n```\n\nThe `timeDeltaDays` function no longer propagates NaN from invalid `created_at` timestamps.\n\n资料来源：[src/affect.ts](https://github.com/Evilander/Audrey/blob/main/src/affect.ts)\n\n## Interference Handling\n\nInterference prevents conflicting or competing memories from silently overwriting each other, maintaining an accurate picture of contradictory knowledge.\n\n### Interference Types\n\n```mermaid\ngraph TD\n    A[New Memory] --> B{Conflicting Memory Exists?}\n    B -->|Yes| C[Track Contradiction]\n    B -->|No| D[Normal Storage]\n    C --> E[Disputed State]\n    E --> F[Monitor Both]\n    F --> G[Resolution Through Validation]\n```\n\n资料来源：[src/interference.ts](https://github.com/Evilander/Audrey/blob/main/src/interference.ts)\n\n### Memory States for Contradictions\n\n| State | Description |\n|-------|-------------|\n| `active` | Default stable state |\n| `disputed` | Competing claims detected |\n| `context_dependent` | Truth depends on context |\n| `superseded` | Older knowledge replaced |\n\nWhen memories have contradictory content, both are preserved with appropriate states rather than silently overwriting.\n\n资料来源：[src/capsule.ts](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n\n## Causal Inference\n\nThe causal module extracts cause-effect relationships from episodic memory patterns, enabling agents to understand why certain actions lead to certain outcomes.\n\n### Causal Analysis\n\n```typescript\n// From src/causal.ts - conceptual interface\nasync function analyzeCausalLinks(episodes: Episode[]): Promise<CausalRelationship[]>\n```\n\nThe causal module validates LLM response shapes before reading fields and rejects non-finite confidence values.\n\n资料来源：[src/causal.ts](https://github.com/Evilander/Audrey/blob/main/src/causal.ts)\n\n### Causal Memory Properties\n\n| Property | Description |\n|----------|-------------|\n| `cause_id` | Memory that triggers outcome |\n| `effect_id` | Resulting memory |\n| `confidence` | Causal link strength |\n| `evidence_count` | Episodes supporting this link |\n\n## Validation Feedback Loop\n\nThe closed-loop feedback system enables continuous improvement of memory accuracy through agent validation.\n\n### Validation Flow\n\n```mermaid\ngraph TD\n    A[Memory Recall] --> B[Agent Uses Memory]\n    B --> C[Validation Request]\n    C --> D{Helpful?}\n    D -->|Yes| E[Reinforce: helpful]\n    D -->|No| F{Wrong?}\n    F -->|Yes| G[Diminish: wrong]\n    F -->|No| H[Mark: used]\n    E --> I[Update Salience & Stats]\n    G --> I\n    H --> I\n```\n\n资料来源：[CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n### Validation API\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `/v1/validate` | POST | Canonical validation endpoint |\n| `/v1/mark-used` | POST | Legacy alias (defaults to `outcome=used`) |\n\nThe `memory_validate` MCP tool accepts outcomes: `helpful`, `wrong`, or `used`.\n\n资料来源：[CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n## Recall and Retrieval\n\nMemory recall uses hybrid retrieval combining vector similarity and full-text search to balance precision and recall.\n\n### Retrieval Modes\n\n| Mode | Description |\n|------|-------------|\n| `hybrid` | Vector similarity + FTS (default) |\n| `vector` | FTS-bypass fast path |\n\nThe `hybrid` mode was the default since v0.22.0, replacing the removed `hybrid_strict` mode (which was a silent alias with no behavioral difference).\n\n资料来源：[CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n### Recall Factors\n\nWhen ranking results, Audrey considers:\n\n1. **Semantic similarity** - Vector distance from query\n2. **Recency** - Time since creation or last retrieval\n3. **Confidence** - Current confidence score\n4. **Salience** - Effective importance (affect-adjusted)\n5. **Agent relevance** - Scope and ownership\n\n## Tool-Trace Learning\n\nAudrey learns from tool execution traces, converting tool results into memory events that inform future actions.\n\n### Tool-Trace Memory Cycle\n\n```mermaid\ngraph TD\n    A[Tool Execution] --> B[Capture Tool Trace]\n    B --> C[Extract Results & Errors]\n    C --> D{Successful?}\n    D -->|Yes| E[Encode Success Pattern]\n    D -->|No| F[Encode Failure Pattern]\n    E --> G[Episodic Memory]\n    F --> G\n    G --> H[Consolidation]\n    H --> I[Procedural Memory]\n```\n\nThe `memory_preflight` function checks prior failures, risks, rules, and relevant procedures before an action executes.\n\n资料来源：[README.md](https://github.com/Evilander/Audrey/blob/main/README.md)\n\n## Memory Capsule\n\nThe Memory Capsule provides a turn-sized memory packet containing categorized sections relevant to the current context.\n\n### Capsule Sections\n\n| Section | Content |\n|---------|---------|\n| `must_follow` | Trusted rules and critical constraints |\n| `risks` | Identified dangers and warnings |\n| `procedures` | Known action procedures |\n| `user_preferences` | Stated and inferred preferences |\n| `uncertain_or_disputed` | Contested or low-confidence knowledge |\n| `recent_changes` | Freshly updated memories |\n| `project_facts` | Default for semantic/episodic |\n\n资料来源：[src/capsule.ts](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n\n### Capsule Generation\n\nCapsule sections are determined by memory type, tags, source trust level, state, confidence, and recency:\n\n```typescript\n// From src/capsule.ts\ndetermineSections(\n  entry: MemoryEntry,\n  result: RecallResult,\n  tags: string[],\n  recentWindowMs: number\n): Array<keyof MemoryCapsule['sections']>\n```\n\nTrusted sources include `direct-observation` and `told-by-user`; these can populate `must_follow` sections.\n\n资料来源：[src/capsule.ts](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n\n## Guard Integration\n\nThe Memory Guard uses the Memory Model to enforce pre-action checks, returning `allow`, `warn`, or `block` decisions with evidence.\n\n### Guard Decision Flow\n\n```mermaid\ngraph TD\n    A[Action Request] --> B[Preflight Check]\n    B --> C[Recall Relevant Memory]\n    C --> D[Apply Reflexes]\n    D --> E{Blocking Reflex?}\n    E -->|Yes| F[BLOCK]\n    E -->|No| G{Warning Reflex?}\n    G -->|Yes| H[ WARN]\n    G -->|No| I[ALLOW]\n```\n\nThe Guard decision reuses existing preflight and reflex machinery without performing two independent recall passes.\n\n资料来源：[CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n## Summary\n\nAudrey's Memory Model provides a comprehensive cognitive architecture for AI agents:\n\n- **Multi-type storage** with episodic, semantic, and procedural memories\n- **Dynamic confidence** that evolves through use and validation\n- **Consolidation** that transforms experience into knowledge\n- **Decay** that prevents stale information from dominating\n- **Affect** that weights memories by emotional importance\n- **Interference tracking** that maintains truth in the face of contradictions\n- **Causal inference** that extracts cause-effect relationships\n- **Closed-loop validation** that continuously improves accuracy\n\nThis architecture ensures agents remember what matters, forget what doesn't, and maintain coherent, actionable knowledge across sessions.\n\n---\n\n<a id='page-audrey-guard'></a>\n\n## Audrey Guard\n\n### 相关页面\n\n相关主题：[Core Memory Operations](#page-memory-operations), [Preflight and Reflexes](#page-reflexes-preflight)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/preflight.ts](https://github.com/Evilander/Audrey/blob/main/src/preflight.ts)\n- [src/feedback.ts](https://github.com/Evilander/Audrey/blob/main/src/feedback.ts)\n- [src/events.ts](https://github.com/Evilander/Audrey/blob/main/src/events.ts)\n- [src/action-key.ts](https://github.com/Evilander/Audrey/blob/main/src/action-key.ts)\n- [src/redact.ts](https://github.com/Evilander/Audrey/blob/main/src/redact.ts)\n- [src/tool-trace.ts](https://github.com/Evilander/Audrey/blob/main/src/tool-trace.ts)\n</details>\n\n# Audrey Guard\n\n## Overview\n\nAudrey Guard is the headline memory loop in the Audrey system—a **memory-before-action** enforcement mechanism that checks AI agents' intended operations against accumulated memory before execution. It serves as a firewall layer that can `allow`, `warn`, or `block` tool invocations based on historical evidence, prior failures, project rules, and risk patterns.\n\nThe Guard operates by retrieving relevant memories through semantic recall, evaluating them against the proposed action, and returning a structured decision with supporting evidence. This enables agents to avoid repeating past mistakes, respect project-specific rules, and make informed decisions grounded in durable context.\n\n**资料来源:** [README.md](https://github.com/Evilander/Audrey/blob/main/README.md)\n\n## Purpose and Scope\n\nAudrey Guard addresses a fundamental problem: **agents forget the exact mistakes they made yesterday**. They repeat broken commands, lose project-specific rules, miss contradictions, and treat every new session like a cold start.\n\nGuard's scope encompasses:\n\n| Concern | Description |\n|---------|-------------|\n| **Failure Prevention** | Block or warn on repeated failures identified through `memory_recall` |\n| **Risk Awareness** | Surface prior failures, risks, and warnings as preflight evidence |\n| **Rule Enforcement** | Check must-follow rules and procedures before action |\n| **Evidence Generation** | Return structured decisions with provenance metadata |\n| **Closed-Loop Validation** | Validate whether the memory helped after action execution |\n\n**资料来源:** [README.md](https://github.com/Evilander/Audrey/blob/main/README.md)\n\n## Architecture\n\n### High-Level Components\n\n```mermaid\ngraph TD\n    A[Agent Tool Call] --> B[Audrey Guard]\n    B --> C[memory_preflight]\n    C --> D[memory_recall]\n    D --> E[SQLite Store<br/>Episodic + Semantic + Procedural]\n    C --> F[Rule Evaluation]\n    F --> G[Reflex Pattern Matching]\n    C --> H[Decision Engine]\n    H --> I[block<br/>warn<br/>allow]\n    I --> J[Evidence Capsule]\n    J --> K[Agent Action Execution]\n    K --> L[memory_validate]\n    L --> M[Outcome: helpful<br/>used<br/>wrong]\n    M --> E\n```\n\n### Guard Decision Flow\n\nThe Guard evaluates incoming tool actions through a multi-stage pipeline:\n\n1. **Action Canonicalization** - Normalize the tool name and action string\n2. **Semantic Recall** - Query memory store for relevant past experiences\n3. **Risk Assessment** - Evaluate prior failures, warnings, and risks\n4. **Rule Matching** - Check against must-follow rules and procedures\n5. **Decision Synthesis** - Combine signals into block/warn/allow verdict\n6. **Evidence Packaging** - Return decision with provenance and references\n\n**资料来源:** [src/reflexes.ts](https://github.com/Evilander/Audrey/blob/main/src/reflexes.ts)\n\n## CLI Interface\n\n### Command Syntax\n\n```bash\naudrey guard --tool <tool_name> \"<action_command>\" [options]\n```\n\n### Core Options\n\n| Option | Description | Default |\n|--------|-------------|---------|\n| `--tool <name>` | The tool category (e.g., `Bash`, `Write`, `Edit`) | Required |\n| `<action>` | The specific action string to evaluate | Required |\n| `--cwd <path>` | Working directory for context | Current directory |\n| `--session-id <id>` | Session identifier for event correlation | Auto-generated |\n| `--hook` | Run in hook mode (for agent integration) | `false` |\n| `--fail-on-warn` | Treat warnings as errors (exit code non-zero) | `false` |\n| `--strict` | Enable strict preflight evaluation | `false` |\n| `--json` | Output results as JSON | `false` |\n| `--explain` | Include detailed explanation in output | `false` |\n| `--include-capsule` | Embed full memory capsule in response | `false` |\n\n**资料来源:** [mcp-server/index.ts](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n\n### Example Usage\n\n```bash\n# Block a repeated failed deploy\naudrey guard --tool Bash \"npm run deploy\"\n\n# Warn on risky file operations\naudrey guard --tool Write --strict \"database.sql\"\n\n# Hook mode for Claude Code integration\naudrey guard --tool Bash --hook \"rm -rf node_modules\"\n```\n\n## SDK Integration\n\n### Sync Client\n\n```typescript\nimport Audrey from 'audrey-memory';\n\nconst brain = new Audrey({\n  base_url: 'http://127.0.0.1:7437',\n  agent: 'support-agent',\n});\n\nconst decision = await brain.beforeAction({\n  tool: 'Bash',\n  action: 'npm run deploy',\n});\n\nconsole.log(decision.decision); // 'block' | 'warn' | 'allow'\nconsole.log(decision.evidence); // Array of MemoryEvidence\nbrain.close();\n```\n\n### Preflight Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `tool` | `string` | Tool category being evaluated |\n| `action` | `string` | Action string to preflight |\n| `sessionId` | `string` | Correlation ID for event tracking |\n| `mode` | `'standard' \\| 'strict'` | Evaluation strictness |\n| `includeCapsule` | `boolean` | Include full memory capsule |\n| `failureWindowHours` | `number` | Hours to look back for failures |\n| `recentChangeWindowHours` | `number` | Hours for recent-change rules |\n\n**资料来源:** [src/routes.ts](https://github.com/Evilander/Audrey/blob/main/src/routes.ts)\n\n## Decision Outcomes\n\n### Verdict Types\n\n| Decision | Description | Agent Behavior |\n|----------|-------------|----------------|\n| `block` | Action is prohibited based on memory | Must not execute |\n| `warn` | Action has risk indicators | Should pause and confirm |\n| `allow` | No memory conflicts detected | May proceed |\n\n### Decision Display Mapping\n\n```typescript\nfunction guardDisplayDecision(result: GuardCliResult): 'allow' | 'warn' | 'block' {\n  if (result.decision === 'block') return 'block';\n  if (result.decision === 'caution') return 'warn';\n  return 'allow';\n}\n```\n\n**资料来源:** [mcp-server/index.ts](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n\n## Memory Preflight\n\nThe `memory_preflight` function checks prior failures, risks, rules, and relevant procedures before an action executes. It builds a structured preflight report containing:\n\n### Capsule Sections\n\n| Section | Content Source | Trigger Condition |\n|---------|----------------|-------------------|\n| `recent_changes` | Memories within recent-change window | Created or reinforced recently |\n| `must_follow` | Must-follow rules | Tagged as must-follow |\n| `procedures` | Procedural memories + procedures | Matching query or tagged |\n| `user_preferences` | User-stated preferences | User-told or tagged |\n| `risks` | Risk-tagged memories + recent failures | Tagged risk or 7-day failures |\n| `uncertain_or_disputed` | Low-confidence or disputed memories | Low confidence or disputed state |\n\n**资料来源:** [src/capsule.ts](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n\n## Reflex System\n\nMemory reflexes convert remembered evidence into trigger-response guidance that agents can follow.\n\n### Reflex Response Types\n\n| Type | Description |\n|------|-------------|\n| `block` | Strict prohibition based on evidence |\n| `warn` | Caution signal with context |\n| `guide` | Recommended action or approach |\n\n### Reflex Report Generation\n\n```typescript\nfunction summarizeReflexes(decision: PreflightDecision, reflexes: MemoryReflex[]): string {\n  const blocks = reflexes.filter(r => r.response_type === 'block').length;\n  const warnings = reflexes.filter(r => r.response_type === 'warn').length;\n  const guides = reflexes.filter(r => r.response_type === 'guide').length;\n  // Returns human-readable summary\n}\n```\n\n**资料来源:** [src/reflexes.ts](https://github.com/Evilander/Audrey/blob/main/src/reflexes.ts)\n\n## Validation Loop\n\nAfter action execution, agents validate whether the memory helped:\n\n### Outcome Types\n\n| Outcome | Meaning | Effect |\n|---------|---------|--------|\n| `helpful` | Memory was correct and beneficial | Increases salience |\n| `used` | Memory was referenced | Updates usage metrics |\n| `wrong` | Memory was incorrect | Triggers decay or dispute |\n\n### Validation Endpoint\n\n```\nPOST /v1/event\n```\n\n```json\n{\n  \"outcome\": \"helpful\",\n  \"receipt_id\": \"receipt-from-preflight\",\n  \"evidence_feedback\": {\n    \"evidence-id-1\": \"used\",\n    \"evidence-id-2\": \"helpful\"\n  }\n}\n```\n\n**资料来源:** [src/routes.ts](https://github.com/Evilander/Audrey/blob/main/src/routes.ts)\n\n## Failure Decay\n\nStarting from version 1.0.1, Audrey Guard implements **failure decay** to prevent stale blocks:\n\n| Configuration | Default | Behavior |\n|---------------|---------|----------|\n| `failureDecayDays` | `7` | Same-action failures older than window treated as stale |\n\nTo restore pre-1.0.1 blocking behavior (permanent blocks):\n\n```typescript\nconst controller = new MemoryController({\n  failureDecayDays: 0,\n});\n```\n\n**资料来源:** [CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n## Security Considerations\n\n### HTTP API Security\n\n- Default bind address changed from `0.0.0.0` to `127.0.0.1`\n- Refuses to start on non-loopback without `AUDREY_API_KEY` or `AUDREY_ALLOW_NO_AUTH=1`\n- API key comparison uses `crypto.timingSafeEqual` to prevent timing attacks\n- `/v1/recall` and `/v1/capsule` no longer body-spread caller options\n\n**资料来源:** [CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n### Hook Configuration Safety\n\nThe `audrey promote --yes` command refuses to write `.claude/rules/*.md` outside `process.cwd()` unless the target path is in `AUDREY_PROMOTE_ROOTS`. This prevents prompt-injection attacks via malicious MCP callers.\n\n## Tool Trace Handling\n\nTool traces are recorded through PostToolUse hooks with redaction applied:\n\n1. **Redaction** - Sensitive fields (API keys, tokens, credentials) are masked\n2. **Action Key Generation** - Deterministic ID for trace correlation\n3. **Event Recording** - Tool inputs/outputs stored with session context\n\n**资料来源:** [mcp-server/index.ts](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n\n## Demo Scenario: Repeated Failure\n\nThe repeated-failure demo demonstrates Guard's blocking behavior:\n\n```bash\nnpx audrey demo --scenario repeated-failure\n```\n\nThis no-key, no-network demo:\n1. Creates a temporary memory store\n2. Records a failed deploy with the fix\n3. Teaches Audrey the failure pattern\n4. Shows Guard blocking the repeated attempt with evidence\n\n**资料来源:** [README.md](https://github.com/Evilander/Audrey/blob/main/README.md)\n\n## See Also\n\n- [Memory Recall](memory-recall) - Semantic retrieval system\n- [Memory Reflexes](reflexes) - Trigger-response guidance\n- [Impact Reporting](impact) - Memory effectiveness metrics\n- [Audrey Doctor](doctor) - Runtime health verification\n\n---\n\n<a id='page-memory-operations'></a>\n\n## Core Memory Operations\n\n### 相关页面\n\n相关主题：[Memory Model](#page-memory-model), [Audrey Guard](#page-audrey-guard), [Preflight and Reflexes](#page-reflexes-preflight), [Data Storage](#page-data-storage)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/encode.ts](https://github.com/Evilander/Audrey/blob/main/src/encode.ts)\n- [src/recall.ts](https://github.com/Evilander/Audrey/blob/main/src/recall.ts)\n- [src/hybrid-recall.ts](https://github.com/Evilander/Audrey/blob/main/src/hybrid-recall.ts)\n- [src/fts.ts](https://github.com/Evilander/Audrey/blob/main/src/fts.ts)\n- [src/impact.ts](https://github.com/Evilander/Audrey/blob/main/src/impact.ts)\n- [src/capsule.ts](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n</details>\n\n# Core Memory Operations\n\nThis page documents the fundamental memory operations in Audrey: encoding, recall, hybrid retrieval, capsule generation, and impact tracking. Together, these operations form the core pipeline that enables agents to store, retrieve, and learn from persistent memory across sessions.\n\n## Overview\n\nAudrey's Core Memory Operations handle the complete lifecycle of memory within the system. The operations are designed around a local-first, SQLite-backed architecture that provides semantic search capabilities without requiring external vector databases or hosted services.\n\n```mermaid\ngraph LR\n    A[Encode] -->|store| B[(SQLite)]\n    B -->|recall| C[Recall]\n    C -->|hybrid| D[Hybrid Search]\n    D -->|compose| E[Capsule]\n    E -->|track| F[Impact]\n    F -->|reinforce| A\n```\n\nThe primary design goals are:\n\n- **Durability**: All memories persist in local SQLite storage\n- **Semantic Search**: Vector embeddings enable similarity-based recall\n- **Hybrid Retrieval**: Combines vector and keyword search for accuracy\n- **Feedback Loop**: Impact tracking enables continuous memory reinforcement\n\n## Memory Types\n\nAudrey distinguishes between three primary memory types that influence retrieval behavior and storage strategy.\n\n| Memory Type | Description | Typical Content |\n|-------------|-------------|------------------|\n| `episodic` | Specific observations and session facts | Tool results, error messages, user feedback |\n| `semantic` | Consolidated principles extracted from evidence | Learned rules, best practices, project conventions |\n| `procedural` | Remembered ways to act, avoid, or verify | Deployment procedures, recovery steps, verification commands |\n\nEach memory type has distinct promotion criteria. Procedural memories can be promoted to rules with lower evidence thresholds, while semantic memories require higher confidence and evidence counts before promotion.\n\n资料来源：[src/recall.ts:15-17](https://github.com/Evilander/Audrey/blob/main/src/recall.ts)\n\n## Memory Encoding\n\nThe encoding operation transforms raw observations into persistent memory entries. When encoding, Audrey generates embeddings, assigns salience scores, and stores metadata that enables future retrieval.\n\n### Encode Process Flow\n\n```mermaid\ngraph TD\n    A[Input: Raw Text] --> B[Generate Embedding]\n    B --> C[Calculate Salience]\n    C --> D[Assign Memory Type]\n    D --> E[Tag Analysis]\n    E --> F[Store in SQLite]\n    F --> G[Update Vector Index]\n```\n\n### Encode Options\n\nThe encode operation accepts several configuration parameters:\n\n| Parameter | Type | Default | Purpose |\n|-----------|------|---------|---------|\n| `source` | `string` | `'direct-observation'` | Origin of the memory |\n| `memory_type` | `string` | `'episodic'` | Classification of memory content |\n| `tags` | `string[]` | `[]` | Categorical labels for filtering |\n| `wait_for_consolidation` | `boolean` | `false` | Opt-in read-after-write semantics |\n\n资料来源：[src/encode.ts](https://github.com/Evilander/Audrey/blob/main/src/encode.ts)\n\n### Source Types\n\nMemory sources indicate provenance and affect how memories are treated during recall:\n\n| Source | Trust Level | Description |\n|--------|-------------|-------------|\n| `direct-observation` | High | Agent's own observations from tool execution |\n| `told-by-user` | High | Explicit user-provided information |\n| `inferred` | Medium | AI-inferred conclusions |\n| `external` | Low | Information from external systems |\n\nTrusted sources (direct-observation, told-by-user) can populate must-follow sections in capsules, while untrusted sources are flagged as uncertain or disputed.\n\n资料来源：[src/capsule.ts:18-20](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n\n## Memory Recall\n\nRecall is the primary mechanism for retrieving relevant memories based on semantic similarity and keyword matching. The recall operation searches across all memory types using configurable retrieval strategies.\n\n### Retrieval Modes\n\nAudrey supports three retrieval modes that determine how search results are computed:\n\n| Mode | Description | Use Case |\n|------|-------------|----------|\n| `hybrid` | Combines vector similarity with FTS keyword matching (default) | Balanced accuracy for general queries |\n| `vector` | Pure semantic similarity using embeddings | When keywords are ambiguous |\n| `keyword` | Full-text search only, bypasses vector index | Fast, keyword-exact matching |\n\n资料来源：[src/recall.ts:12-14](https://github.com/Evilander/Audrey/blob/main/src/recall.ts)\n\n### Recall Architecture\n\n```mermaid\ngraph TD\n    A[Query Input] --> B{Mode Check}\n    B -->|hybrid| C[Vector Pass]\n    B -->|hybrid| D[Keyword Pass]\n    B -->|vector| E[Vector Pass Only]\n    B -->|keyword| F[Keyword Pass Only]\n    C --> G[Merge & Score]\n    D --> G\n    G --> H[Filter by Confidence]\n    H --> I[Apply Filters]\n    I --> J[Return Results]\n```\n\n### Recall Options\n\nThe recall operation accepts a comprehensive set of filtering and result-shaping options:\n\n| Parameter | Type | Default | Purpose |\n|-----------|------|---------|---------|\n| `minConfidence` | `number` | `0` | Minimum confidence threshold (0-1) |\n| `types` | `MemoryType[]` | `['episodic', 'semantic', 'procedural']` | Memory types to search |\n| `limit` | `number` | `10` | Maximum results to return |\n| `includeProvenance` | `boolean` | `false` | Include source metadata |\n| `includeDormant` | `boolean` | `false` | Include decayed/inactive memories |\n| `tags` | `string[]` | `undefined` | Filter by tags |\n| `sources` | `string[]` | `undefined` | Filter by source type |\n| `after` | `Date` | `undefined` | Filter memories created after date |\n| `before` | `Date` | `undefined` | Filter memories created before date |\n| `includePrivate` | `boolean` | `false` | Include agent-private memories |\n| `retrieval` | `string` | `'hybrid'` | Retrieval mode selection |\n| `scope` | `'agent' \\| 'shared'` | `'agent'` | Memory scope filter |\n\n资料来源：[src/recall.ts:5-22](https://github.com/Evilander/Audrey/blob/main/src/recall.ts)\n\n### RecallFilters Structure\n\n```typescript\ninterface RecallFilters {\n  tags?: string[];\n  sources?: string[];\n  after?: Date;\n  before?: Date;\n  agent?: string;  // Filtered by scope when scope === 'agent'\n}\n```\n\nFilters are combined with AND logic—memories must match all specified filters to be included in results.\n\n### Agent and Scope Filtering\n\nThe `scope` parameter determines which memories are accessible:\n\n- `agent` (default): Only memories associated with the requesting agent\n- `shared`: Memories marked as shared across agents\n\nWhen `scope` is `'agent'`, the `agent` filter is automatically set to the requesting agent's identity. This ensures memory isolation between different agents.\n\n## Hybrid Search\n\nHybrid search combines vector similarity and full-text search to achieve more accurate recall results than either method alone.\n\n### Hybrid Recall Pipeline\n\n```mermaid\ngraph LR\n    A[Query] --> B[Embedding Model]\n    A --> C[FTS Index]\n    B --> D[Vector Scores]\n    C --> E[Keyword Scores]\n    D --> F[Score Normalization]\n    E --> F\n    F --> G[Weighted Merge]\n    G --> H[Ranked Results]\n```\n\n### Score Merging Strategy\n\nThe hybrid approach normalizes scores from both vector and keyword passes before merging. This ensures that memories matched by keywords are not overshadowed by high vector similarity scores, and vice versa.\n\n资料来源：[src/hybrid-recall.ts](https://github.com/Evilander/Audrey/blob/main/src/hybrid-recall.ts)\n\n### Full-Text Search Integration\n\nThe FTS module provides keyword-based search capabilities:\n\n```typescript\ninterface FTSResult {\n  memory_id: string;\n  rank: number;\n  snippet?: string;\n}\n```\n\nFTS uses SQLite's built-in FTS5 extension for fast keyword matching. The FTS index is updated synchronously during encoding to ensure keyword search reflects current memory state.\n\n资料来源：[src/fts.ts](https://github.com/Evilander/Audrey/blob/main/src/fts.ts)\n\n## Memory Capsule\n\nThe capsule is a turn-sized memory packet that organizes relevant memories into actionable sections for agent consumption. It synthesizes recall results into a structured format optimized for quick agent review.\n\n### Capsule Sections\n\n| Section | Purpose | Trigger Conditions |\n|---------|---------|-------------------|\n| `must_follow` | High-priority directives | Trusted source + must-follow tags |\n| `uncertain_or_disputed` | Flagged content requiring verification | Low confidence, disputed state, or untrusted source |\n| `risks` | Known risks and hazards | Risk-related tags |\n| `procedures` | Step-by-step instructions | Procedural memory type or procedure tags |\n| `user_preferences` | User-specific preferences | Preference tags or told-by-user source |\n| `project_facts` | Consolidated project knowledge | Semantic memories with no other section match |\n| `recent_changes` | Recently updated information | Memories within recent time window |\n\n资料来源：[src/capsule.ts:22-38](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n\n### Section Determination Logic\n\n```mermaid\ngraph TD\n    A[Memory Entry] --> B{Source Trusted?}\n    B -->|Yes| C{Has Must-Follow Tags?}\n    B -->|No| D[Uncertain/Disputed]\n    C -->|Yes| E[Must-Follow Section]\n    C -->|No| F{Has Risk Tags?}\n    D --> F\n    F -->|Yes| G[Risks Section]\n    F -->|No| H{Procedural Type?}\n    H -->|Yes| I[Procedures Section]\n    H -->|No| J{Has Preference Tags?}\n    J -->|Yes| K[User Preferences]\n    J -->|No| L{Uncertain State?}\n    L -->|Yes| M[Uncertain/Disputed]\n    L -->|No| N[Project Facts]\n```\n\n### Capsule Structure\n\n```typescript\ninterface MemoryCapsule {\n  generated_at: string;\n  sections: {\n    must_follow?: MemorySection;\n    uncertain_or_disputed?: MemorySection;\n    risks?: MemorySection;\n    procedures?: MemorySection;\n    user_preferences?: MemorySection;\n    project_facts?: MemorySection;\n    recent_changes?: MemorySection;\n  };\n}\n```\n\n### Tag-Based Section Assignment\n\nCapsule generation uses predefined tag sets to categorize memories:\n\n| Tag Set | Matching Tags |\n|---------|---------------|\n| `MUST_FOLLOW_TAGS` | Critical directives that must be followed |\n| `RISK_TAGS` | Risk-related keywords |\n| `PROCEDURE_TAGS` | Procedure-related keywords |\n| `PREFERENCE_TAGS` | User preference keywords |\n\n资料来源：[src/capsule.ts:12-15](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n\n## Impact Tracking\n\nImpact tracking closes the feedback loop by recording whether recalled memories proved useful. This enables continuous reinforcement of valuable memories and decay of misleading ones.\n\n### Outcome Types\n\n| Outcome | Description | Effect on Memory |\n|---------|-------------|------------------|\n| `helpful` | Memory drove a correct action | Increases salience, bumps retrieval_count |\n| `wrong` | Memory was misleading | Decreases salience, bumps challenge_count |\n| `used` | Memory was referenced | Small positive salience delta |\n\n资料来源：[src/impact.ts](https://github.com/Evilander/Audrey/blob/main/src/impact.ts)\n\n### Impact Report Structure\n\n```typescript\ninterface ImpactReport {\n  generatedAt: string;\n  windowDays: number;\n  totals: {\n    episodic: number;\n    semantic: number;\n    procedural: number;\n  };\n  validatedTotal: number;\n  validatedInWindow: number;\n  byType: {\n    episodic: { validated: number; recent: number };\n    semantic: { validated: number; recent: number; challenged: number };\n    procedural: { validated: number; recent: number };\n  };\n  outcomeBreakdownInWindow: {\n    helpful: number;\n    wrong: number;\n    used: number;\n  };\n  topUsed: MemoryStat[];\n  weakest: MemoryStat[];\n  recentActivity: MemoryStat[];\n}\n```\n\n### Impact Metrics\n\nThe impact system tracks several key metrics:\n\n- **usage_count**: Number of times a memory was successfully used\n- **salience**: Computed importance score based on reinforcement history\n- **validation events**: Recorded outcomes linked to specific recall events\n- **challenge_count**: Number of times a memory was marked as wrong\n\nThis data feeds into consolidation and decay processes, ensuring that frequently useful memories remain prominent while stale or misleading memories lose authority over time.\n\n## Data Flow Summary\n\n```mermaid\ngraph LR\n    subgraph Encode\n        A1[Text Input] --> A2[Embed]\n        A2 --> A3[Salience]\n        A3 --> A4[Store]\n    end\n    \n    subgraph Recall\n        B1[Query] --> B2[Hybrid Search]\n        B2 --> B3[Score & Rank]\n        B3 --> B4[Filter]\n        B4 --> B5[Recall Results]\n    end\n    \n    subgraph Capsule\n        C1[Recall Results] --> C2[Section Analysis]\n        C2 --> C3[Tag Matching]\n        C3 --> C4[Capsule Output]\n    end\n    \n    subgraph Impact\n        D1[Agent Feedback] --> D2[Outcome Recording]\n        D2 --> D3[Reinforce/Decay]\n        D3 --> A3\n    end\n    \n    A4 --> B5\n    B5 --> C1\n    C4 --> D1\n```\n\n## Configuration Considerations\n\nWhen deploying Audrey's core memory operations, consider these configuration points:\n\n| Setting | Recommendation | Impact |\n|---------|---------------|--------|\n| `AUDREY_EMBEDDING_PROVIDER` | Pin explicitly | Determines embedding quality |\n| `AUDREY_LLM_PROVIDER` | Pin explicitly | Affects consolidation quality |\n| `AUDREY_DATA_DIR` | Separate per tenant/environment | Ensures isolation and backup simplicity |\n| Retrieval mode | Use `hybrid` for most cases | Balances precision and recall |\n| `wait_for_consolidation` | Enable for critical writes | Guarantees read-after-write consistency |\n\n## Related Operations\n\nThe core memory operations interact with several supporting systems:\n\n- **Guard**: Uses preflight checks before tool execution\n- **Reflexes**: Trigger-response patterns derived from memory\n- **Consolidation**: Extracts semantic memories from episodic evidence\n- **Decay**: Reduces authority of stale memories over time\n- **Promotion**: Converts high-value memories to Claude rules\n\n---\n\n<a id='page-reflexes-preflight'></a>\n\n## Preflight and Reflexes\n\n### 相关页面\n\n相关主题：[Audrey Guard](#page-audrey-guard), [Core Memory Operations](#page-memory-operations)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/preflight.ts](https://github.com/Evilander/Audrey/blob/main/src/preflight.ts)\n- [src/reflexes.ts](https://github.com/Evilander/Audrey/blob/main/src/reflexes.ts)\n- [src/validate.ts](https://github.com/Evilander/Audrey/blob/main/src/validate.ts)\n- [src/rules-compiler.ts](https://github.com/Evilander/Audrey/blob/main/src/rules-compiler.ts)\n- [src/capsule.ts](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n- [mcp-server/index.ts](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n</details>\n\n# Preflight and Reflexes\n\n## Overview\n\nPreflight and Reflexes form Audrey's core decision-making loop for AI agents. Before any tool action executes, Audrey performs a preflight check that consults memory to determine whether the action should be allowed, warned about, or blocked entirely.\n\nThe system operates as Audrey's \"memory firewall\"—a security and guidance layer that prevents agents from repeating mistakes, reinforces learned behaviors, and surfaces relevant context before sensitive operations. This mechanism transforms episodic and semantic memories into actionable guidance that agents can evaluate in real-time.\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[Agent Action Request] --> B[Preflight Check]\n    B --> C{Memory Recall}\n    C --> D[Episodic Memory]\n    C --> E[Semantic Memory]\n    C --> F[Procedural Memory]\n    D --> G[Memory Reflexes]\n    E --> G\n    F --> G\n    G --> H{Decision?}\n    H -->|Match Found| I[Return Reflex Result]\n    H -->|No Match| J[Allow Action]\n    I --> K{block}\n    I --> L[warn]\n    I --> M[guide]\n    K --> N[Block with Evidence]\n    L --> O[Warn with Guidance]\n    M --> P[Proceed with Hints]\n```\n\n## Memory Reflexes\n\nMemory Reflexes are the atomic decision units within the Preflight system. Each reflex contains a trigger condition, a response type, and optional guidance content.\n\n### Response Types\n\n| Response Type | Decision | Description |\n|---------------|----------|-------------|\n| `block` | `block` | Prevents the action entirely; returns blocking evidence |\n| `warn` | `caution` | Allows action but presents warning with recommendations |\n| `guide` | `allow` | Provides informational guidance without blocking |\n\n资料来源：[src/reflexes.ts:1-50](https://github.com/Evilander/Audrey/blob/main/src/reflexes.ts)\n\n### Reflex Structure\n\n```typescript\ninterface MemoryReflex {\n  response_type: 'block' | 'warn' | 'guide';\n  triggered_by: string;       // Memory tag or rule identifier\n  message: string;            // Human-readable explanation\n  recommended_action?: string; // Suggested alternative\n  memory_ids: string[];        // Source memories that triggered this reflex\n  confidence: number;         // Reflex confidence score\n}\n```\n\n## Preflight Process\n\n### Decision Flow\n\nThe preflight process evaluates incoming actions against three memory types and returns a consolidated decision:\n\n```mermaid\ngraph LR\n    A[Action + Context] --> B[Tag Extraction]\n    B --> C{Must-Follow Rules?}\n    C -->|Yes| D[BLOCK or UNCERTAIN]\n    C -->|No| E{Risk Tags?}\n    E -->|Yes| F[Add to WARN]\n    E -->|No| G{Procedures?}\n    G -->|Yes| H[Add GUIDANCE]\n    G -->|No| I{Preferences?}\n    I -->|Yes| J[Include in Capsule]\n    I -->|No| K[Default ALLOW]\n```\n\n### Decision Types\n\n| Decision | Meaning | Exit Code Behavior |\n|----------|---------|-------------------|\n| `allow` | Action proceeds normally | Continue execution |\n| `caution` | Action proceeds with warning | Log warning, continue |\n| `block` | Action is prevented | Return error, halt |\n\n资料来源：[mcp-server/index.ts:80-95](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n\n### Memory Capsule Integration\n\nPreflight builds a **Memory Capsule**—a structured context bundle that aggregates relevant memories by category. The capsule sections determine which memories appear in the agent's context window.\n\n```typescript\ninterface MemoryCapsule {\n  sections: {\n    must_follow: MemoryReflex[];        // Critical rules\n    recent_changes: MemoryReflex[];     // New learnings\n    procedures: MemoryReflex[];        // How-to guidance\n    user_preferences: MemoryReflex[];   // Stated preferences\n    risks: MemoryReflex[];              // Warnings and hazards\n    uncertain_or_disputed: MemoryReflex[]; // Low-confidence or contested\n    project_facts: MemoryReflex[];      // Relevant facts\n  };\n  triggered_by: string;\n  generated_at: string;\n}\n```\n\n资料来源：[src/capsule.ts:1-50](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n\n### Tag-Based Classification\n\nMemory reflexes are classified using tag matching against predefined tag sets:\n\n| Tag Set | Purpose | Associated Section |\n|---------|---------|---------------------|\n| `MUST_FOLLOW_TAGS` | Critical rules that must be obeyed | `must_follow` |\n| `RISK_TAGS` | Potential hazards or warnings | `risks` |\n| `PROCEDURE_TAGS` | Step-by-step guidance | `procedures` |\n| `PREFERENCE_TAGS` | User-stated preferences | `user_preferences` |\n\n资料来源：[src/capsule.ts:50-100](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n\n## Building Reflex Reports\n\n### Report Generation\n\nThe `buildReflexReport` function constructs a complete preflight report from an action:\n\n```typescript\nexport async function buildReflexReport(\n  audrey: Audrey,\n  action: string,\n  options: ReflexOptions = {},\n): Promise<MemoryReflexReport>\n```\n\n### Report Structure\n\n```typescript\ninterface MemoryReflexReport {\n  decision: 'allow' | 'caution' | 'block';\n  reflexes: MemoryReflex[];\n  capsule: MemoryCapsule;\n  summary: string;           // Human-readable summary\n  triggered_at: string;      // ISO timestamp\n  session_id?: string;      // Optional session context\n}\n```\n\n资料来源：[src/reflexes.ts:80-120](https://github.com/Evilander/Audrey/blob/main/src/reflexes.ts)\n\n### Summarization Logic\n\nThe `summarizeReflexes` function generates human-readable summaries:\n\n```typescript\nfunction summarizeReflexes(\n  decision: PreflightDecision,\n  reflexes: MemoryReflex[],\n): string {\n  const blocks = reflexes.filter(r => r.response_type === 'block').length;\n  const warnings = reflexes.filter(r => r.response_type === 'warn').length;\n  const guides = reflexes.filter(r => r.response_type === 'guide').length;\n  \n  // Returns format: \"Stop: 2 blocking, 1 warning, 3 guidance matched.\"\n  // Or: \"Slow down: ...\" or \"Proceed: ...\"\n}\n```\n\n## Validation Layer\n\nBefore reflexes are applied, the validation layer ensures response integrity:\n\n### Response Validation\n\n```typescript\n// From src/validate.ts\n// Validates LLM response shape before reading fields\n// - Rejects non-object/array conditions\n// - Only counts new evidence toward supporting_count\n// - Throws on malformed response shapes\n```\n\n资料来源：[src/validate.ts](https://github.com/Evilander/Audrey/blob/main/src/validate.ts)\n\n### Validation Behavior\n\n| Check | Invalid Condition | Behavior |\n|-------|-------------------|----------|\n| Response Shape | Non-object/array | Reject and throw |\n| Evidence Count | Missing supporting_count | Skip from count |\n| Confidence | Non-finite value | Reject in causal module |\n\n资料来源：[CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n## CLI Integration\n\n### Guard Command\n\nThe `audrey guard` command exposes preflight checks via terminal:\n\n```bash\naudrey guard --tool Bash \"npm run deploy\"\n```\n\n### Guard Options\n\n| Option | Description |\n|--------|-------------|\n| `--tool <name>` | Tool name being invoked |\n| `--action <command>` | Specific action/command |\n| `--cwd <path>` | Working directory |\n| `--session-id <id>` | Session identifier |\n| `--files <paths>` | Files affected by action |\n| `--json` | Output results as JSON |\n| `--strict` | Fail on warnings |\n| `--include-capsule` | Include full memory capsule |\n| `--explain` | Show reasoning breakdown |\n\n资料来源：[mcp-server/index.ts:40-70](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n\n### Display Mapping\n\nThe CLI maps internal decisions to display messages:\n\n```typescript\nfunction guardDisplayDecision(result: GuardCliResult): 'allow' | 'warn' | 'block' {\n  if (result.decision === 'block') return 'block';\n  if (result.decision === 'caution') return 'warn';\n  return 'allow';\n}\n```\n\n## Configuration Options\n\n### Environment Variables\n\n| Variable | Default | Purpose |\n|----------|---------|---------|\n| `AUDREY_CONTEXT_BUDGET_CHARS` | `4000` | Memory capsule character budget |\n| `AUDREY_ENABLE_ADMIN_TOOLS` | `0` | Enable export/import/forget routes |\n| `AUDREY_DEBUG` | `0` | Print MCP info logs |\n\n### Runtime Options\n\n```typescript\ninterface ReflexOptions {\n  agent?: string;                    // Agent identifier\n  sessionId?: string;               // Session context\n  includeCapsule?: boolean;          // Include full capsule\n  includePreflight?: boolean;       // Include preflight details\n  context?: Record<string, string>; // Additional context\n  mood?: MoodConfig;                // Emotional context\n}\n```\n\n## Memory Types and Section Assignment\n\n### Assignment Logic\n\n```mermaid\ngraph TD\n    A[Memory Entry] --> B{Source Trusted?}\n    B -->|Yes + Must-Follow Tags| C[must_follow section]\n    B -->|No + Must-Follow Tags| D[uncertain_or_disputed]\n    B -->|Risk Tags| E[risks section]\n    B -->|Procedural Type/Tags| F[procedures section]\n    B -->|Preference Tags| G[user_preferences section]\n    A --> H{State or Low Confidence?}\n    H -->|disputed/context_dependent/confidence<0.55| I[uncertain_or_disputed]\n    A --> J{Recent Window?}\n    J -->|Yes| K[recent_changes section]\n    J -->|No| L[Default: project_facts]\n```\n\n### Threshold Values\n\n| Condition | Threshold | Section Assignment |\n|-----------|-----------|-------------------|\n| Confidence (disputed) | < 0.55 | `uncertain_or_disputed` |\n| Recent Window | 7 days | `recent_changes` |\n| Tool Failure | 7 days | `risks` |\n\n## Data Flow Example\n\n```mermaid\nsequenceDiagram\n    participant Agent\n    participant MCP as MCP Server\n    participant Audrey\n    participant Memory\n    participant Reflex\n\n    Agent->>MCP: tool_use(Bash, \"rm -rf /\")\n    MCP->>Audrey: buildPreflight(audrey, action)\n    Audrey->>Memory: recall(action, context)\n    Memory-->>Audrey: MemoryReflex[]\n    Audrey->>Reflex: classifyAndScore(reflexes)\n    Reflex-->>Audrey: MemoryReflexReport\n    Audrey-->>MCP: PreflightDecision\n    MCP-->>Agent: block/caution/allow response\n```\n\n## Security Considerations\n\n### HTTP Endpoint Protection\n\nThe preflight system includes security hardening for HTTP access:\n\n- REST endpoints default to loopback-only binding\n- API key comparison uses `crypto.timingSafeEqual` to prevent timing attacks\n- Options like `includePrivate: true` cannot be passed via HTTP bodies\n- Non-loopback binding requires explicit `AUDREY_API_KEY`\n\n资料来源：[src/routes.ts](https://github.com/Evilander/Audrey/blob/main/src/routes.ts)\n\n### Recall Sanitization\n\nHTTP `/v1/recall` and `/v1/capsule` endpoints sanitize input through `sanitizeRecallOptions()`:\n\n```typescript\n// Allowed keys only\nconst ALLOWED_KEYS = ['limit', 'agent', 'tags', 'sources', 'after', 'before', 'context', 'mood', 'retrieval', 'scope'];\n```\n\nAny keys not in the allowlist are silently dropped before processing.\n\n## Related Components\n\n| Component | File | Role |\n|-----------|------|------|\n| Rules Compiler | `src/rules-compiler.ts` | Compiles memories into Claude rules |\n| Validation | `src/validate.ts` | Validates LLM response integrity |\n| Impact Tracking | `src/impact.ts` | Tracks reflex effectiveness over time |\n| Memory Capsule | `src/capsule.ts` | Structures context bundles |\n\n## See Also\n\n- [Memory Types and Tagging](./memory-types.md)\n- [Confidence and Decay System](./confidence.md)\n- [CLI Reference](./cli-reference.md)\n- [REST API Documentation](./api.md)\n\n---\n\n<a id='page-data-storage'></a>\n\n## Data Storage\n\n### 相关页面\n\n相关主题：[System Architecture](#page-system-architecture), [Core Memory Operations](#page-memory-operations)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/db.ts](https://github.com/Evilander/Audrey/blob/main/src/db.ts)\n- [src/hybrid-recall.ts](https://github.com/Evilander/Audrey/blob/main/src/hybrid-recall.ts)\n- [src/fts.ts](https://github.com/Evilander/Audrey/blob/main/src/fts.ts)\n- [src/embedding.ts](https://github.com/Evilander/Audrey/blob/main/src/embedding.ts)\n- [src/export.ts](https://github.com/Evilander/Audrey/blob/main/src/export.ts)\n- [src/import.ts](https://github.com/Evilander/Audrey/blob/main/src/import.ts)\n- [src/migrate.ts](https://github.com/Evilander/Audrey/blob/main/src/migrate.ts)\n</details>\n\n# Data Storage\n\n## Overview\n\nAudrey's data storage layer is built as a local-first, SQLite-backed persistence system designed for AI agent memory continuity. The storage architecture eliminates external database dependencies while providing vector similarity search capabilities through `sqlite-vec`, enabling semantic memory retrieval without cloud infrastructure.\n\nThe storage system serves as the foundation for Audrey's multi-type memory model, supporting episodic, semantic, and procedural memory with built-in confidence tracking, contradiction handling, and temporal decay mechanisms.\n\n## Storage Architecture\n\n### Core Technology Stack\n\n| Component | Technology | Purpose |\n|-----------|------------|---------|\n| Primary Database | SQLite | Structured memory storage, ACID transactions |\n| Vector Search | sqlite-vec | Semantic similarity search on embeddings |\n| Data Directory | `AUDREY_DATA_DIR` | Tenant/environment isolation boundary |\n\nThe storage backend runs entirely locally, requiring no hosted database services. Each tenant or environment should use a dedicated `AUDREY_DATA_DIR` to maintain isolation boundaries.\n\n资料来源：[README.md](https://github.com/Evilander/Audrey/blob/main/README.md)\n\n### Database Schema Design\n\nAudrey maintains three primary memory tables that correspond to its memory model:\n\n```mermaid\nerDiagram\n    MEMORIES ||--o{ VECTORS : contains\n    MEMORIES {\n        string id PK\n        string content\n        string memory_type\n        float confidence\n        float salience\n        string state\n        int evidence_count\n        int usage_count\n        timestamp created_at\n        timestamp last_used_at\n    }\n    VECTORS {\n        int rowid\n        float vector\n        text content\n    }\n```\n\n#### Memory Type Storage\n\n| Memory Type | Description | Key Attributes |\n|-------------|-------------|-----------------|\n| **episodic** | Specific observations, tool results, session facts | `source`, `tags`, `created_at` |\n| **semantic** | Consolidated principles from repeated evidence | `evidence_count`, `supporting_count`, `contradicting_count` |\n| **procedural** | Remembered procedures, actions to avoid or retry | `usage_count`, `failure_prevented`, `tags` |\n\n资料来源：[src/promote.ts](https://github.com/Evilander/Audrey/blob/main/src/promote.ts)\n\n## Memory Model Implementation\n\n### Episodic Memory Storage\n\nEpisodic memories capture specific observations and session-level facts. These entries are created during direct agent interactions and tool executions.\n\nKey storage characteristics:\n- High-volume insertion during active sessions\n- Temporal ordering via `created_at` timestamps\n- Tag-based categorization for filtered retrieval\n- Source attribution (`direct-observation`, `told-by-user`)\n\n### Semantic Memory Storage\n\nSemantic memories represent consolidated principles extracted from accumulated episodic evidence. The promotion system converts episodic memories into semantic rules when confidence thresholds are met.\n\nThe promotion criteria for semantic memories include:\n- Minimum evidence count threshold (default: 3)\n- Zero contradicting evidence\n- State must be `active`\n\n资料来源：[src/promote.ts:78-92](https://github.com/Evilander/Audrey/blob/main/src/promote.ts)\n\n### Procedural Memory Storage\n\nProcedural memories track action sequences and their outcomes. These are distinguished by usage tracking and failure prevention metrics.\n\nProcedural candidates are promoted when:\n- `evidence_count >= minEvidence`\n- `contradicting_count === 0`\n- `retrieval_count > 0` OR `failure_prevented > 0`\n\n## Confidence and Salience Tracking\n\n### Confidence Scoring\n\nConfidence scores are computed from supporting versus contradicting evidence:\n\n```\nconfidence = supporting / max(evidence, 1)\n```\n\nThe confidence value is clamped to the range `[0, 1]` to prevent invalid states. Negative salience values from malformed arousal calculations are also clamped.\n\n资料来源：[CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n### Salience System\n\nSalience represents the importance and emotional weight of memories, influencing recall priority. The `effectiveSalience` calculation factors in:\n\n- Base salience from evidence strength\n- Temporal decay over time\n- Arousal/affect resonance from recent memories\n- Validation feedback (`helpful`, `wrong`, `used` outcomes)\n\n### Validation Feedback Loop\n\nThe closed-loop validation system updates salience based on memory utility:\n\n| Outcome | Salience Effect | Counts Updated |\n|---------|-----------------|----------------|\n| `helpful` | Increases | `retrieval_count`, salience |\n| `wrong` | Decreases | `challenge_count` (semantic only) |\n| `used` | Neutral/slight | `usage_count` |\n\n资料来源：[CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n## Retrieval and Search\n\n### Hybrid Recall Architecture\n\nAudrey implements a hybrid retrieval strategy combining vector similarity with keyword matching:\n\n```mermaid\ngraph TD\n    A[Query Input] --> B[Embedding Provider]\n    B --> C[Vector Similarity Search]\n    A --> D[Full-Text Search FTS]\n    C --> E[Confidence Scoring]\n    D --> E\n    E --> F[Memory Filtering]\n    F --> G[Ranked Results]\n```\n\n#### Retrieval Modes\n\n| Mode | Behavior |\n|------|----------|\n| `hybrid` (default) | Combines vector + FTS for balanced recall |\n| `vector` | Pure semantic similarity, bypasses FTS |\n| `keyword` | Skips vector pass, uses FTS only |\n\nThe `vector` mode serves as a fast path when FTS overhead is unacceptable.\n\n资料来源：[src/recall.ts](https://github.com/Evilander/Audrey/blob/main/src/recall.ts)\n\n### Filtering Capabilities\n\nRecall operations support multiple filter dimensions:\n\n- **tags**: Array of tag values to match\n- **sources**: Array of source identifiers\n- **after/before**: Temporal bounds via ISO timestamps\n- **scope**: `shared` or `agent`-scoped memories\n- **types**: Filter by memory type (episodic/semantic/procedural)\n\n### Private Memory Isolation\n\nThe `includePrivate` flag controls access to agent-specific private memories. The HTTP API implements an allowlist-based sanitizer (`sanitizeRecallOptions()`) that prevents bypassing private-memory ACL controls through body options.\n\n资料来源：[src/routes.ts](https://github.com/Evilander/Audrey/blob/main/src/routes.ts)\n\n## Data Lifecycle\n\n### Consolidation and Decay\n\nThe `audrey dream` command triggers memory consolidation:\n\n1. Episodic memories are evaluated for principle extraction\n2. Low-confidence or conflicting memories undergo decay\n3. Stale memories lose retrieval authority over time\n4. Contradicting claims are tracked rather than silently overwritten\n\n资料来源：[README.md](https://github.com/Evilander/Audrey/blob/main/README.md)\n\n### Rollback Operations\n\nThe rollback system (`src/rollback.ts`) updates memories with verification:\n\n- Checks `.changes` to confirm affected rows\n- Aggregates real counts rather than assuming success\n- Reports failure when targeted IDs don't exist\n\n资料来源：[CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n### Reembedding\n\nWhen embedding models or dimensions change, reembedding regenerates all vector representations:\n\n- Chunks embeddings into 256-row batches\n- Labels failures by kind and row range\n- Provides clear error messages for partial failures\n\n资料来源：[CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n## Import and Export\n\n### Data Portability\n\nAudrey supports full data export and import for:\n\n- Snapshot restoration to fresh stores\n- Backup before configuration changes\n- Migration between environments\n\nExported snapshots should only be restored into empty Audrey stores with fresh `AUDREY_DATA_DIR` to prevent data corruption.\n\n资料来源：[python/README.md](https://github.com/Evilander/Audrey/blob/main/python/README.md)\n\n### Export Process\n\nExport operations create portable snapshots containing:\n- All memory records (episodic, semantic, procedural)\n- Associated metadata (timestamps, confidence scores)\n- Configuration state\n\n### Import Validation\n\nImport operations verify store emptiness before restoration:\n\n```typescript\nisDatabaseEmpty() // Checks both records and vector tables\n```\n\n资料来源：[CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n## Security Considerations\n\n### Credential Protection\n\nRaw credentials and API keys must be excluded from encoded memory content. Audrey provides redaction functionality to prevent sensitive data exposure:\n\n```typescript\nconst SENSITIVE_KEY_PATTERN = /(password|secret|api[_-]?key|auth[_-]?token|...)$/i;\n```\n\n资料来源：[src/redact.ts](https://github.com/Evilander/Audrey/blob/main/src/redact.ts)\n\n### API Security\n\n- Audrey serve defaults to binding `127.0.0.1` (previously `0.0.0.0`)\n- Non-loopback hosts require `AUDREY_API_KEY` or explicit `AUDREY_ALLOW_NO_AUTH=1`\n- HTTP API key comparison uses `crypto.timingSafeEqual` to prevent timing attacks\n\n资料来源：[CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n### Production Recommendations\n\n| Recommendation | Rationale |\n|----------------|-----------|\n| Set one `AUDREY_DATA_DIR` per tenant | Isolation boundary |\n| Pin embedding and LLM providers | Reproducibility |\n| Backup before provider changes | Data integrity |\n| Keep credentials out of memory content | Security |\n| Use `AUDREY_API_KEY` for network exposure | Access control |\n\n## Configuration\n\n### Environment Variables\n\n| Variable | Default | Purpose |\n|----------|---------|---------|\n| `AUDREY_DATA_DIR` | - | Data directory path (required for isolation) |\n| `AUDREY_EMBEDDING_PROVIDER` | - | Embedding model provider |\n| `AUDREY_LLM_PROVIDER` | - | LLM provider for memory operations |\n| `AUDREY_API_KEY` | - | API authentication key |\n| `AUDREY_HOST` | `127.0.0.1` | Network binding address |\n| `AUDREY_ALLOW_NO_AUTH` | `0` | Allow unauthenticated access |\n\n资料来源：[README.md](https://github.com/Evilander/Audrey/blob/main/README.md)\n\n## Related Documentation\n\n- [Memory Model](../memory-model) - Multi-type memory architecture\n- [Recall System](../recall-system) - Retrieval and search mechanisms\n- [Guard Loop](../guard-loop) - Pre-action memory checking\n- [Impact Analysis](../impact) - Memory effectiveness tracking\n\n---\n\n<a id='page-mcp-server'></a>\n\n## MCP Server\n\n### 相关页面\n\n相关主题：[System Architecture](#page-system-architecture), [REST API](#page-rest-api)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [mcp-server/index.ts](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n- [mcp-server/config.ts](https://github.com/Evilander/Audrey/blob/main/mcp-server/config.ts)\n- [README.md](https://github.com/Evilander/Audrey/blob/main/README.md)\n- [CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n- [src/capsule.ts](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n- [src/rules-compiler.ts](https://github.com/Evilander/Audrey/blob/main/src/rules-compiler.ts)\n- [src/impact.ts](https://github.com/Evilander/Audrey/blob/main/src/impact.ts)\n</details>\n\n# MCP Server\n\n## Overview\n\nThe Audrey MCP Server is a Model Context Protocol (MCP) stdio server that provides a local-first memory layer for AI agents. It enables agents to encode experiences into persistent memory, recall relevant context before actions, and maintain a durable memory state across sessions. 资料来源：[README.md]()\n\nThe server exposes 20+ tools plus status, recent, and principles resources, along with briefing, recall, and reflection prompts. It communicates via stdio (standard input/output), making it compatible with MCP-compatible hosts like Claude Code, Claude Desktop, Cursor, Windsurf, and VS Code. 资料来源：[README.md]()\n\n## Architecture\n\n### System Context\n\n```mermaid\ngraph TD\n    subgraph \"MCP Hosts\"\n        A[Claude Code]\n        B[Claude Desktop]\n        C[Cursor]\n        D[Windsurf]\n        E[VS Code]\n        F[Other MCP Clients]\n    end\n    \n    subgraph \"Audrey MCP Server\"\n        G[MCP stdio Server]\n        H[Tool Handlers]\n        I[Resource Providers]\n        J[Prompt Templates]\n    end\n    \n    subgraph \"Audrey Core\"\n        K[Memory Store<br/>SQLite + sqlite-vec]\n        L[Embedding Engine<br/>ONNX]\n        M[Retrieval Engine]\n    end\n    \n    A --> G\n    B --> G\n    C --> G\n    D --> G\n    E --> G\n    F --> G\n    \n    G --> H\n    G --> I\n    G --> J\n    \n    H --> K\n    I --> K\n    J --> K\n    \n    K --> L\n    K --> M\n```\n\n### Server Initialization Flow\n\n```mermaid\nsequenceDiagram\n    participant Host as MCP Host\n    participant Server as McpServer\n    participant Audrey as Audrey Instance\n    participant Store as Memory Store\n    \n    Host->>Server: Start Process\n    Server->>Audrey: Initialize with config\n    Audrey->>Store: Open SQLite + sqlite-vec\n    alt Warmup Enabled\n        Audrey->>Store: Pre-compute embeddings\n    end\n    Server->>Server: registerHostResources()\n    Server->>Server: registerHostPrompts()\n    Server->>Server: Register Tools\n    Server->>Host: Ready (stdio)\n```\n\n## Server Components\n\n### Core Server Setup\n\nThe MCP server is initialized with a name and version, then configured with resources, prompts, and tools: 资料来源：[mcp-server/index.ts:101-106]()\n\n```typescript\nconst server = new McpServer({\n  name: SERVER_NAME,\n  version: VERSION,\n});\n\nregisterHostResources(server, audrey);\nregisterHostPrompts(server);\n```\n\n### Tool Registry\n\nThe server registers the following tool categories:\n\n| Category | Tools | Purpose |\n|----------|-------|---------|\n| Memory Operations | `memory_encode`, `memory_recall` | Store and retrieve memories |\n| Memory Management | `memory_import`, `memory_export`, `memory_forget` | Data management |\n| Impact Tracking | `mark_used`, `impact_report` | Memory utility tracking |\n| Promotion | `promote_memory`, `rule_review` | Memory-to-rules conversion |\n\n## Tools Reference\n\n### memory_encode\n\nEncodes new information into the memory store with diagnostic support.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `content` | string | Yes | The memory content to encode |\n| `source` | string | No | Source identifier (e.g., \"direct-observation\", \"told-by-user\") |\n| `tags` | string[] | No | Classification tags |\n| `salience` | number | No | Importance weight (0-1) |\n| `private` | boolean | No | Mark as private memory |\n| `context` | object | No | Additional context metadata |\n| `affect` | object | No | Emotional/valence metadata |\n| `wait_for_consolidation` | boolean | No | Opt-in read-after-write semantics (default: false) |\n\n**Returns:** Tool result with memory ID, content, source, and optionally diagnostics. 资料来源：[mcp-server/index.ts:108-133]()\n\n### memory_recall\n\nRetrieves relevant memories based on a query with filtering options.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `query` | string | Yes | Search query |\n| `limit` | number | No | Maximum results (default: 10) |\n| `types` | string[] | No | Filter by memory types |\n| `min_confidence` | number | No | Minimum confidence threshold |\n| `tags` | string[] | No | Filter by tags |\n| `sources` | string[] | No | Filter by sources |\n| `after` | string | No | ISO timestamp lower bound |\n| `before` | string | No | ISO timestamp upper bound |\n| `context` | object | No | Context filtering |\n| `mood` | string | No | Mood-based filtering |\n\n**Returns:** Array of recall results with confidence scores and metadata. 资料来源：[mcp-server/index.ts:135-142]()\n\n### Additional Tools\n\n| Tool | Purpose |\n|------|---------|\n| `memory_import` | Import memory snapshots |\n| `memory_export` | Export memory snapshots |\n| `memory_forget` | Delete specific memories |\n| `mark_used` | Record memory utility |\n| `impact_report` | Generate impact analytics |\n| `promote_memory` | Convert memory to rule |\n| `rule_review` | Review promotion candidates |\n\n## Command Line Interface\n\n### Command Routing\n\nThe MCP server entry point (`mcp-server/index.ts`) handles CLI subcommands before starting the stdio loop: 资料来源：[mcp-server/index.ts:200-240]()\n\n```mermaid\ngraph TD\n    A[audrey CLI] --> B{Subcommand?}\n    \n    B -->|--help / -h / help| C[printHelp]\n    B -->|--version / -v / version| D[printVersion]\n    B -->|install| E[install]\n    B -->|uninstall| F[uninstall]\n    B -->|mcp-config| G[printMcpConfig]\n    B -->|hook-config| H[printHookConfig]\n    B -->|demo| I[runDemoCommand]\n    B -->|reembed| J[reembed]\n    B -->|dream| K[dream]\n    B -->|greeting| L[greeting]\n    B -->|NONE| M[Start MCP Server]\n    \n    C --> N[Exit 0]\n    D --> N\n    E --> N\n    F --> N\n    G --> N\n    H --> N\n    I --> N\n    J --> N\n    K --> N\n    L --> N\n    M --> O[stdio Loop]\n```\n\n### Available Subcommands\n\n| Command | Description |\n|---------|-------------|\n| `audrey install` | Register Audrey with host MCP configuration |\n| `audrey uninstall` | Remove Audrey from host configuration |\n| `audrey mcp-config` | Print MCP server configuration |\n| `audrey hook-config` | Generate Claude Code hook configurations |\n| `audrey demo` | Run interactive demonstration |\n| `audrey reembed` | Regenerate embeddings |\n| `audrey dream` | Generate reflection/memory consolidation |\n| `audrey greeting` | Display greeting message |\n| `audrey doctor` | Run diagnostic checks |\n| `audrey guard` | Check memory before action |\n| `audrey status` | Show memory system status |\n| `audrey promote` | Promote memories to rules |\n| `audrey impact` | Generate impact reports |\n| `audrey observe-tool` | Monitor tool execution |\n\n### Help and Version Short-Circuit\n\nHelp and version flags MUST short-circuit before falling through to the MCP server. A user running `audrey --help` should see help, not be dropped into a stdio loop: 资料来源：[mcp-server/index.ts:201-206]()\n\n```typescript\nif (subcommand === '--help' || subcommand === '-h' || subcommand === 'help') {\n  printHelp();\n  process.exit(0);\n} else if (subcommand === '--version' || subcommand === '-v' || subcommand === 'version') {\n  printVersion();\n  process.exit(0);\n}\n```\n\n## Configuration Management\n\n### MCP Host Configuration\n\nThe `config.ts` module provides functions to generate host-specific MCP configurations: 资料来源：[mcp-server/config.ts:1-50]()\n\n```typescript\nexport function formatMcpHostConfig(\n  host: string | undefined = 'generic',\n  env: Record<string, string | undefined> = process.env,\n): string\n```\n\n**Supported Hosts:**\n\n| Host | Config Format | Notes |\n|------|---------------|-------|\n| `codex` | TOML | GitHub MCP config style |\n| `claude-code` | JSON | Claude Code MCP settings |\n| `claude-desktop` | JSON | Claude Desktop config |\n| `cursor` | JSON | Cursor MCP config |\n| `windsurf` | JSON | Windsurf MCP config |\n| `vscode` | JSON | VS Code MCP config |\n| `jetbrains` | JSON | JetBrains MCP config |\n| `generic` | JSON | Generic MCP fallback |\n\n### Installation Arguments\n\nThe `buildInstallArgs()` function generates CLI arguments for installing the MCP server: 资料来源：[mcp-server/config.ts:52-66]()\n\n```typescript\nexport function buildInstallArgs(\n  env: Record<string, string | undefined> = process.env,\n  options: McpEnvOptions = {},\n): string[]\n```\n\n**Generated Output Example:**\n\n```bash\nmcp add -s user audrey -e AUDREY_AGENT=claude-code -e AUDREY_DATA_DIR=... -- node /path/to/mcp-entrypoint\n```\n\n### Install Guide Generation\n\nThe `formatInstallGuide()` function generates human-readable installation instructions: 资料来源：[mcp-server/index.ts:18-48]()\n\n```typescript\nexport function formatInstallGuide(\n  host: string,\n  env: Record<string, string | undefined> = process.env,\n  dryRun = false,\n): string\n```\n\n**Output Sections:**\n\n1. Title (with dry-run or config-only indicator)\n2. No-modification notice\n3. Generated MCP config\n4. Generated Claude Code hook config (for Claude Code host)\n5. Next steps\n\n## Host-Specific Resources\n\n### Resource Registration\n\nResources are registered per-host to provide context: 资料来源：[mcp-server/index.ts:103]()\n\n```typescript\nregisterHostResources(server, audrey);\nregisterHostPrompts(server);\n```\n\n### Available Resources\n\n| Resource | Type | Description |\n|----------|------|-------------|\n| `status` | Resource | Current system status |\n| `recent` | Resource | Recent memory activity |\n| `principles` | Resource | Core operational principles |\n\n### Available Prompts\n\n| Prompt | Purpose |\n|--------|---------|\n| `briefing` | Get current session briefing |\n| `recall` | Perform focused recall |\n| `reflection` | Generate self-reflection |\n\n## Error Handling\n\n### Tool Error Response\n\nTool handlers return structured error responses: 资料来源：[mcp-server/index.ts:100]()\n\n```typescript\nfunction toolError(err: unknown): CallToolResult {\n  return {\n    content: [{ type: 'text', text: `[audrey] error: ${err}` }],\n    isError: true,\n  };\n}\n```\n\n### Tool Success Response\n\nTool handlers return structured success responses with optional diagnostics: 资料来源：[mcp-server/index.ts:99]()\n\n```typescript\nfunction toolResult(data: unknown, diagnostics?: unknown): CallToolResult {\n  return {\n    content: [{ type: 'text', text: JSON.stringify(data) }],\n    _meta: diagnostics ? { diagnostics } : undefined,\n  };\n}\n```\n\n## Environment Variables\n\n| Variable | Default | Description |\n|----------|---------|-------------|\n| `AUDREY_AGENT` | `claude-code` | Host agent identifier |\n| `AUDREY_DATA_DIR` | Platform-specific | Data directory path |\n| `AUDREY_PROFILE` | `0` | Enable profiling diagnostics |\n| `AUDREY_DEBUG` | `0` | Enable debug logging |\n| `AUDREY_DISABLE_WARMUP` | `0` | Skip embedding warmup |\n| `AUDREY_API_KEY` | unset | REST API authentication |\n| `AUDREY_HOST` | `127.0.0.1` | REST bind address |\n| `AUDREY_PORT` | `7437` | REST server port |\n\n## Performance Characteristics\n\n### v0.22.0 Performance Metrics\n\n| Operation | Before | After | Improvement |\n|-----------|--------|-------|-------------|\n| Encode response (p50) | 24.7ms | 15.2ms | ~40% faster |\n| Cold-start first encode | 525ms | 28ms (with warmup) | ~18.7x faster |\n| Hybrid recall (p50) | 30.2ms | 14.3ms | ~2.1x faster |\n\n### Optimization Details\n\n- Eliminated 3 of 4 redundant embedding calls during encode\n- Validation, interference, and affect resonance reuse the main content vector\n- Background embedding warmup at MCP boot reduces cold-start latency 资料来源：[CHANGELOG.md]()\n\n## Security\n\n### API Key Timing Safety\n\nHTTP API key comparison uses `crypto.timingSafeEqual` to prevent timing attacks: 资料来源：[CHANGELOG.md]()\n\n### Recall Options Sanitization\n\nHTTP `/v1/recall` and `/v1/capsule` sanitize request bodies to prevent ACL bypass: 资料来源：[CHANGELOG.md]()\n\n### Promote Path Restrictions\n\n`audrey promote --yes` restricts writes to `process.cwd()` unless target is in `AUDREY_PROMOTE_ROOTS`, preventing prompt-injection attacks. 资料来源：[CHANGELOG.md]()\n\n## Profiling Mode\n\nWhen `AUDREY_PROFILE=1`, tools return diagnostic metadata: 资料来源：[mcp-server/index.ts:110-120]()\n\n```typescript\nif (profileEnabled) {\n  const { id, diagnostics } = await audrey.encodeWithDiagnostics({\n    content,\n    source,\n    tags,\n    salience,\n    private: isPrivate,\n    context,\n    affect,\n    waitForConsolidation: wait_for_consolidation,\n  });\n  return toolResult({ id, content, source, private: isPrivate ?? false }, diagnostics);\n}\n```\n\n**Diagnostic Data Includes:**\n\n- Per-stage timing information\n- Embedding generation time\n- Retrieval latency breakdown\n\n## Related Documentation\n\n- [README.md](README.md) - Main project documentation\n- [CHANGELOG.md](CHANGELOG.md) - Version history and release notes\n- [src/capsule.ts](src/capsule.ts) - Memory capsule generation\n- [src/rules-compiler.ts](src/rules-compiler.ts) - Memory-to-rules promotion\n- [src/impact.ts](src/impact.ts) - Impact analytics reporting\n\n---\n\n<a id='page-rest-api'></a>\n\n## REST API\n\n### 相关页面\n\n相关主题：[System Architecture](#page-system-architecture), [MCP Server](#page-mcp-server)\n\n<details>\n<summary>Related Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/routes.ts](https://github.com/Evilander/Audrey/blob/main/src/routes.ts)\n- [src/server.ts](https://github.com/Evilander/Audrey/blob/main/src/server.ts)\n- [README.md](https://github.com/Evilander/Audrey/blob/main/README.md)\n- [python/README.md](https://github.com/Evilander/Audrey/blob/main/python/README.md)\n- [mcp-server/index.ts](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n- [src/impact.ts](https://github.com/Evilander/Audrey/blob/main/src/impact.ts)\n</details>\n\n# REST API\n\nThe Audrey REST API provides a local-first HTTP interface for memory management operations, enabling external agents and services to interact with Audrey's memory system without direct database access.\n\n## Overview\n\nAudrey's REST API is built on [Hono](https://hono.dev/), a lightweight, high-performance web framework for Edge environments. The API serves as a sidecar service that wraps the core memory engine with HTTP endpoints for encoding, recalling, and managing memory entries.\n\n**Key characteristics:**\n- Local-first design with no external database dependencies\n- SQLite + sqlite-vec for storage and vector search\n- Bearer token authentication for non-loopback access\n- Type-safe request/response handling\n\n资料来源：[README.md:60]()\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[Client<br>Python/JS SDK] --> B[REST API<br>Hono Server]\n    B --> C[Audrey Core Engine]\n    C --> D[SQLite<br>Memory Store]\n    C --> E[sqlite-vec<br>Vector Index]\n    B --> F[/health]\n    B --> G[/v1/recall]\n    B --> H[/v1/capsule]\n    B --> I[/v1/encode]\n    B --> J[Admin Routes<br>/v1/import<br>/v1/export]\n```\n\n## Server Configuration\n\n### Environment Variables\n\n| Variable | Default | Description |\n|----------|---------|-------------|\n| `AUDREY_HOST` | `127.0.0.1` | REST sidecar bind address. Set to `0.0.0.0` only with `AUDREY_API_KEY`. |\n| `AUDREY_PORT` | `7437` | Port for the REST server to listen on. |\n| `AUDREY_API_KEY` | unset | Bearer token required for non-loopback REST traffic. |\n| `AUDREY_ALLOW_NO_AUTH` | `0` | Set to `1` to allow non-loopback bind without an API key. Not recommended. |\n| `AUDREY_ENABLE_ADMIN_TOOLS` | `0` | Set to `1` to enable export, import, and forget routes/tools. Disabled by default. |\n| `AUDREY_PRAGMA_DEFAULTS` | `1` | Set to `0` to revert SQLite PRAGMA tuning to better-sqlite3 defaults. |\n| `AUDREY_DEBUG` | `0` | Set to `1` to print MCP info logs. Errors always log. |\n\n资料来源：[README.md:44-52]()\n\n### Starting the Server\n\n```bash\n# Default (loopback only)\nnpx audrey serve\n\n# With explicit port\nAUDREY_PORT=8080 npx audrey serve\n\n# Network-exposed with API key\nAUDREY_HOST=0.0.0.0 AUDREY_API_KEY=secret npx audrey serve\n```\n\n资料来源：[python/README.md:18]()\n\n## API Endpoints\n\n### Health Check\n\n| Method | Path | Description |\n|--------|------|-------------|\n| `GET` | `/health` | Returns server health status |\n\n**Response:**\n```json\n{\n  \"status\": \"ok\",\n  \"version\": \"0.22.1\",\n  \"timestamp\": \"2026-04-30T12:00:00.000Z\"\n}\n```\n\n资料来源：[README.md:58]()\n\n### Memory Operations\n\n| Method | Path | Description |\n|--------|------|-------------|\n| `POST` | `/v1/encode` | Store a new memory entry |\n| `POST` | `/v1/recall` | Retrieve relevant memories by query |\n| `POST` | `/v1/capsule` | Get a turn-sized memory packet |\n| `POST` | `/v1/mark-used` | Mark memory as used with outcome feedback |\n| `POST` | `/v1/observe-tool` | Record tool execution results |\n| `POST` | `/v1/before-action` | Preflight check before tool execution |\n| `POST` | `/v1/validate` | Validate memory helpfulness |\n\n资料来源：[README.md:58](), [src/routes.ts:1-50]()\n\n## Request Body Schema\n\nThe REST API accepts a unified `RouteBody` type with optional fields:\n\n```typescript\ntype RouteBody = {\n  action?: string;\n  query?: string;\n  tool?: string;\n  session_id?: string;\n  sessionId?: string;\n  cwd?: string;\n  files?: string[];\n  strict?: boolean;\n  limit?: number;\n  budget_chars?: number;\n  budgetChars?: number;\n  mode?: PreflightOptions['mode'];\n  failure_window_hours?: number;\n  recent_failure_window_hours?: number;\n  recentFailureWindowHours?: number;\n  recent_change_window_hours?: number;\n  recentChangeWindowHours?: number;\n  include_capsule?: boolean;\n  includeCapsule?: boolean;\n  include_status?: boolean;\n  includeStatus?: boolean;\n  record_event?: boolean;\n  recordEvent?: boolean;\n  include_preflight?: boolean;\n  includePreflight?: boolean;\n  receipt_id?: string;\n  receiptId?: string;\n  input?: unknown;\n  output?: unknown;\n  outcome?: EventOutcome;\n  error_summary?: string;\n  errorSummary?: string;\n  metadata?: Record<string, unknown>;\n  retain_details?: boolean;\n  retainDetails?: boolean;\n  evidence_feedback?: Record<string, 'used' | 'helpful' | 'wrong'>;\n  evidenceFeedback?: Record<string, 'used' | 'helpful' | 'wrong'>;\n};\n```\n\n资料来源：[src/routes.ts:5-46]()\n\n## Security Model\n\n### Authentication\n\nNon-loopback REST traffic requires a Bearer token:\n\n```bash\ncurl -H \"Authorization: Bearer your-secret-token\" \\\n  http://localhost:7437/v1/recall \\\n  -d '{\"query\": \"deploy failures\"}'\n```\n\n**Security measures:**\n- HTTP API key comparison uses `crypto.timingSafeEqual` instead of string `!==` to prevent timing attacks 资料来源：[README.md:41]()\n- Server defaults to binding `127.0.0.1` (was `0.0.0.0`) 资料来源：[README.md:40]()\n- Refuses to start on non-loopback host without `AUDREY_API_KEY` unless `AUDREY_ALLOW_NO_AUTH=1`\n\n### Recall Options Sanitization\n\nHTTP `/v1/recall` and `/v1/capsule` no longer body-spread caller options into internal calls. The `sanitizeRecallOptions()` function implements an allowlist that drops anything not in a known-safe key set:\n\n```typescript\nexport function sanitizeRecallOptions(options: unknown): SanitizedRecallOptions {\n  // Only allows: budget_chars, limit, retrieval, includePrivate, sessionId\n}\n```\n\nThis prevents bypassing private-memory ACL and integrity controls via `includePrivate: true` or `confidenceConfig` overrides in HTTP bodies.\n\n资料来源：[README.md:39-40](), [CHANGELOG.md:0.22.1]()\n\n### Admin Tools\n\nAdmin routes (`/v1/import`, `/v1/export`, `/v1/forget`) are disabled by default. Enable with:\n\n```bash\nAUDREY_ENABLE_ADMIN_TOOLS=1 npx audrey serve\n```\n\n资料来源：[README.md:48]()\n\n## Client Integration\n\n### Python SDK\n\n```python\nfrom audrey_memory import Audrey\n\nbrain = Audrey(\n    base_url=\"http://127.0.0.1:7437\",\n    api_key=\"secret\",\n    agent=\"support-agent\",\n)\n\n# Encode a memory\nmemory_id = brain.encode(\n    \"Stripe returns HTTP 429 above 100 req/s\",\n    source=\"direct-observation\",\n    tags=[\"stripe\", \"rate-limit\"],\n)\n\n# Recall relevant memories\nresults = brain.recall(\"stripe rate limits\", limit=5)\n\n# Create snapshot for backup\nsnapshot = brain.snapshot()\nbrain.close()\n```\n\n**Async usage:**\n```python\nimport asyncio\nfrom audrey_memory import AsyncAudrey\n\nasync def main() -> None:\n    async with AsyncAudrey(base_url=\"http://127.0.0.1:7437\") as brain:\n        await brain.health()\n        await brain.encode(\"Deploy failed due to OOM\", source=\"direct-observation\")\n        await brain.recall(\"deploy failure\", limit=3)\n\nasyncio.run(main())\n```\n\n资料来源：[python/README.md:22-45]()\n\n### Connection URL Correction\n\n> **Note:** Python client `DEFAULT_BASE_URL` was corrected from `http://127.0.0.1:3487` to `http://127.0.0.1:7437` in v0.22.1 to match the TS server's default port.\n\n资料来源：[CHANGELOG.md:0.22.1]()\n\n## Impact Reporting\n\nThe REST API exposes impact analytics through the `audrey impact` CLI, which calls internal Audrey methods:\n\n| Endpoint | Description |\n|----------|-------------|\n| Total memories by type | episodic, semantic, procedural counts |\n| All-time validated count | Memories validated as helpful/wrong |\n| Recent validations | Validation activity in time window |\n| Top-N most-used memories | Memories with highest `usage_count` |\n| Weakest-N memories | Lowest salience candidates for forgetting |\n| Recent activity timeline | `last_used_at` based activity log |\n\n```bash\n# Basic report\naudrey impact\n\n# JSON output for automation\naudrey impact --json\n\n# Custom window and limits\naudrey impact --window 30 --limit 20\n```\n\n资料来源：[src/impact.ts:1-50](), [CHANGELOG.md:0.22.1]()\n\n## Deployment\n\n### Docker\n\n```yaml\n# docker-compose.yml\nservices:\n  audrey:\n    image: ghcr.io/evilander/audrey:latest\n    ports:\n      - \"7437:7437\"\n    environment:\n      - AUDREY_API_KEY=your-secret-token\n      - AUDREY_HOST=0.0.0.0\n    volumes:\n      - audrey-data:/data\n```\n\n### Doctor Check\n\nThe `audrey doctor` command validates REST server configuration:\n\n```bash\nnpx audrey doctor\n```\n\n**Checks performed:**\n| Check | Description |\n|-------|-------------|\n| `serve-bind-safety` | Validates bind address with auth configuration |\n| `node-runtime` | Node.js version >= 20 |\n| `entrypoint-exists` | MCP stdio entrypoint file exists |\n| `data-dir` | Data directory accessibility |\n| `embedding` | Embedding provider configuration |\n| `llm` | LLM provider configuration |\n\n```mermaid\ngraph TD\n    A[audrey doctor] --> B{Is bind loopback?}\n    B -->|Yes| C[✅ loopback only]\n    B -->|No| D{Has AUDREY_API_KEY?}\n    D -->|Yes| E[✅ non-loopback with API key]\n    D -->|No| F{Has AUDREY_ALLOW_NO_AUTH?}\n    F -->|Yes| G[⚠️ warning - network exposure]\n    F -->|No| H[❌ error - refuse to start]\n```\n\n资料来源：[mcp-server/index.ts:100-130]()\n\n## Error Handling\n\n### Common Issues\n\n| Error | Cause | Solution |\n|-------|-------|----------|\n| Connection refused | Wrong port or host | Check `AUDREY_PORT` and `AUDREY_HOST` |\n| 401 Unauthorized | Missing/invalid API key | Provide `Authorization: Bearer <token>` header |\n| 404 Not Found | Wrong endpoint | Use `/v1/*` routes, not `/openapi.json` or `/docs` |\n| Validation error | Malformed request body | Check RouteBody schema |\n\n### Status Codes\n\n| Code | Meaning |\n|------|---------|\n| `200` | Success |\n| `400` | Bad request (malformed body) |\n| `401` | Unauthorized (missing/invalid API key) |\n| `404` | Endpoint not found |\n| `500` | Internal server error |\n\n> **Note:** `/openapi.json` and `/docs` routes are not currently wired. The README matches the actual surface (`/health` + `/v1/*`).\n\n资料来源：[CHANGELOG.md:0.22.1](), [README.md:58]()\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：Evilander/Audrey\n\n摘要：发现 14 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：安装坑 - 来源证据：Audrey 1.0.1 — honest GuardBench gate, Guard time decay, structured validate errors。\n\n## 1. 安装坑 · 来源证据：Audrey 1.0.1 — honest GuardBench gate, Guard time decay, structured validate errors\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Audrey 1.0.1 — honest GuardBench gate, Guard time decay, structured validate errors\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_135b992964ae468aa28f88ee639816d1 | https://github.com/Evilander/Audrey/releases/tag/v1.0.1 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 2. 安装坑 · 来源证据：Audrey Guard 0.23.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Audrey Guard 0.23.0\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_9c913c644e2c4c099ea01523623f080e | https://github.com/Evilander/Audrey/releases/tag/v0.23.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 3. 安装坑 · 来源证据：v0.16.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.16.0\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_a7c5c62d4f034e50ba2e9c36e0798882 | https://github.com/Evilander/Audrey/releases/tag/v0.16.0 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 4. 安装坑 · 来源证据：v0.16.1 — Windows MCP fix\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.16.1 — Windows MCP fix\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_c0141ccf0a3245ec8c8ba112af7948e0 | https://github.com/Evilander/Audrey/releases/tag/v0.16.1 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。\n\n## 5. 安装坑 · 来源证据：v0.17.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.17.0\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_9617863b3f954035926b8670b5bbea29 | https://github.com/Evilander/Audrey/releases/tag/v0.17.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 6. 配置坑 · 可能修改宿主 AI 配置\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- 证据：capability.host_targets | github_repo:1161444210 | https://github.com/Evilander/Audrey | host_targets=mcp_host, claude, claude_code\n\n## 7. 能力坑 · 能力判断依赖假设\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:1161444210 | https://github.com/Evilander/Audrey | README/documentation is current enough for a first validation pass.\n\n## 8. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:1161444210 | https://github.com/Evilander/Audrey | last_activity_observed missing\n\n## 9. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:1161444210 | https://github.com/Evilander/Audrey | no_demo; severity=medium\n\n## 10. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:1161444210 | https://github.com/Evilander/Audrey | no_demo; severity=medium\n\n## 11. 安全/权限坑 · 来源证据：Audrey 1.0.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Audrey 1.0.0\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_d30d964956da40a2b5e26dc7404861f8 | https://github.com/Evilander/Audrey/releases/tag/v1.0.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 12. 安全/权限坑 · 来源证据：v0.22.2 — correctness pass + legitimate benchmarking\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.22.2 — correctness pass + legitimate benchmarking\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_f9c004c97d31437ebdc3699d6f1ba2f4 | https://github.com/Evilander/Audrey/releases/tag/v0.22.2 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 13. 维护坑 · 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:1161444210 | https://github.com/Evilander/Audrey | issue_or_pr_quality=unknown\n\n## 14. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:1161444210 | https://github.com/Evilander/Audrey | release_recency=unknown\n\n<!-- canonical_name: Evilander/Audrey; human_manual_source: deepwiki_human_wiki -->\n",
      "markdown_key": "audrey",
      "pages": "draft",
      "source_refs": [
        {
          "evidence_id": "github_repo:1161444210",
          "kind": "repo",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/Evilander/Audrey"
        },
        {
          "evidence_id": "art_08565dd035d847d3b742eed1801b7f8a",
          "kind": "docs",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/Evilander/Audrey#readme"
        }
      ],
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "Audrey 说明书",
      "toc": [
        "https://github.com/Evilander/Audrey 项目说明书",
        "目录",
        "Audrey Overview",
        "What Problem Audrey Solves",
        "Architecture Overview",
        "Core Components",
        "Installation Methods",
        "Generate MCP configuration",
        "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": "82b0e9979680acf751b9e80f6f90f8c6ac74befb",
    "repo_inspection_error": null,
    "repo_inspection_files": [
      "Dockerfile",
      "package.json",
      "README.md",
      "docker-compose.yml",
      "docs/PRODUCTION_BACKLOG.md",
      "docs/MEMORY_BENCHMARKING.md",
      "docs/AUDREY_PAPER_OUTLINE.md",
      "docs/paper/06-implementation.md",
      "docs/paper/browser-launch-plan.schema.json",
      "docs/paper/00-master.md",
      "docs/paper/publication-pack.json",
      "docs/paper/03-problem-definition.md",
      "docs/paper/claim-register.schema.json",
      "docs/paper/publication-pack.schema.json",
      "docs/paper/02-related-work.md",
      "docs/paper/01-introduction.md",
      "docs/paper/08-discussion-limitations.md",
      "docs/paper/evidence-ledger.md",
      "docs/paper/arxiv-source.schema.json",
      "docs/paper/audrey-paper-v1.md",
      "docs/paper/07-evaluation.md",
      "docs/paper/claim-register.json",
      "docs/paper/arxiv-compile-report.schema.json",
      "docs/paper/04-design.md",
      "docs/paper/browser-launch-results.json",
      "docs/paper/browser-launch-results.schema.json",
      "docs/paper/SUBMISSION_README.md",
      "docs/paper/05-guardbench-spec.md",
      "docs/paper/browser-launch-plan.json",
      "docs/paper/paper-submission-bundle.schema.json",
      "docs/paper/09-conclusion.md",
      "docs/paper/appendix-a-demo-transcript.md",
      "docs/superpowers/specs/2026-05-05-audrey-guard-controller-design.md",
      "docs/superpowers/plans/2026-05-05-audrey-guard-controller-implementation.md",
      "examples/healthcare-ops-demo.js",
      "examples/fintech-ops-demo.js",
      "examples/stripe-demo.js",
      "examples/ollama-memory-agent.js",
      "src/feedback.ts",
      "src/events.ts"
    ],
    "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": "# audrey - Doramagic AI Context Pack\n\n> 定位：安装前体验与判断资产。它帮助宿主 AI 有一个好的开始，但不代表已经安装、执行或验证目标项目。\n\n## 充分原则\n\n- **充分原则，不是压缩原则**：AI Context Pack 应该充分到让宿主 AI 在开工前理解项目价值、能力边界、使用入口、风险和证据来源；它可以分层组织，但不以最短摘要为目标。\n- **压缩策略**：只压缩噪声和重复内容，不压缩会影响判断和开工质量的上下文。\n\n## 给宿主 AI 的使用方式\n\n你正在读取 Doramagic 为 audrey 编译的 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- **AI 研究者或研究型 Agent 构建者**：README 明确围绕研究、实验或论文工作流展开。 证据：`README.md` Claim：`clm_0002` supported 0.86\n- **正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**：README 或插件配置提到多个宿主 AI。 证据：`README.md` Claim：`clm_0003` supported 0.86\n\n## 它能做什么\n\n- **命令行启动或安装流程**（需要安装后验证）：项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 证据：`README.md` Claim：`clm_0001` supported 0.86\n\n## 怎么开始\n\n- `npx audrey doctor` 证据：`README.md` Claim：`clm_0004` supported 0.86, `clm_0019` supported 0.86\n- `npx audrey demo --scenario repeated-failure` 证据：`README.md` Claim：`clm_0005` supported 0.86\n- `npx audrey guard --tool Bash \"npm run deploy\"` 证据：`README.md` Claim：`clm_0006` supported 0.86\n- `npx audrey install --host codex --dry-run` 证据：`README.md` Claim：`clm_0007` supported 0.86\n- `npx audrey install --host claude-code --dry-run` 证据：`README.md` Claim：`clm_0008` supported 0.86\n- `npx audrey install --host generic --dry-run` 证据：`README.md` Claim：`clm_0009` supported 0.86\n- `npx audrey mcp-config codex` 证据：`README.md` Claim：`clm_0010` supported 0.86\n- `npx audrey mcp-config generic` 证据：`README.md` Claim：`clm_0011` supported 0.86\n- `npx audrey mcp-config vscode` 证据：`README.md` Claim：`clm_0012` supported 0.86\n- `npx audrey hook-config claude-code` 证据：`README.md` Claim：`clm_0013` supported 0.86\n\n## 继续前判断卡\n\n- **当前建议**：需要管理员/安全审批\n- **为什么**：继续前可能涉及密钥、账号、外部服务或敏感上下文，建议先经过管理员或安全审批。\n\n### 30 秒判断\n\n- **现在怎么做**：需要管理员/安全审批\n- **最小安全下一步**：先跑 Prompt Preview；若涉及凭证或企业环境，先审批再试装\n- **先别相信**：角色质量和任务匹配不能直接相信。\n- **继续会触碰**：角色选择偏差、命令执行、本地环境或项目文件\n\n### 现在可以相信\n\n- **适合人群线索：AI 研究者或研究型 Agent 构建者**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`README.md` Claim：`clm_0002` supported 0.86\n- **适合人群线索：正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`README.md` Claim：`clm_0003` supported 0.86\n- **能力存在：命令行启动或安装流程**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`README.md` Claim：`clm_0001` supported 0.86\n- **存在 Quick Start / 安装命令线索**（supported）：可以相信项目文档出现过启动或安装入口；不要因此直接在主力环境运行。 证据：`README.md` Claim：`clm_0004` supported 0.86, `clm_0019` supported 0.86\n\n### 现在还不能相信\n\n- **角色质量和任务匹配不能直接相信。**（unverified）：角色库证明有很多角色，不证明每个角色都适合你的具体任务，也不证明角色能产生高质量结果。\n- **不能把角色文案当成真实执行能力。**（unverified）：安装前只能判断角色描述和任务画像是否匹配，不能证明它能在宿主 AI 里完成任务。\n- **真实输出质量不能在安装前相信。**（unverified）：Prompt Preview 只能展示引导方式，不能证明真实项目中的结果质量。\n- **宿主 AI 版本兼容性不能在安装前相信。**（unverified）：Claude、Cursor、Codex、Gemini 等宿主加载规则和版本差异必须在真实环境验证。\n- **不会污染现有宿主 AI 行为，不能直接相信。**（inferred）：Skill、plugin、AGENTS/CLAUDE/GEMINI 指令可能改变宿主 AI 的默认行为。\n- **可安全回滚不能默认相信。**（unverified）：除非项目明确提供卸载和恢复说明，否则必须先在隔离环境验证。\n- **真实安装后是否与用户当前宿主 AI 版本兼容？**（unverified）：兼容性只能通过实际宿主环境验证。\n- **项目输出质量是否满足用户具体任务？**（unverified）：安装前预览只能展示流程和边界，不能替代真实评测。\n\n### 继续会触碰什么\n\n- **角色选择偏差**：用户对任务应该由哪个专家角色处理的判断。 原因：选错角色会让 AI 从错误专业视角回答，浪费时间或误导决策。\n- **命令执行**：包管理器、网络下载、本地插件目录、项目配置或用户主目录。 原因：运行第一条命令就可能产生环境改动；必须先判断是否值得跑。 证据：`README.md`\n- **本地环境或项目文件**：安装结果、插件缓存、项目配置或本地依赖目录。 原因：安装前无法证明写入范围和回滚方式，需要隔离验证。 证据：`README.md`\n- **环境变量 / API Key**：项目入口文档明确出现 API key、token、secret 或账号凭证配置。 原因：如果真实安装需要凭证，应先使用测试凭证并经过权限/合规判断。 证据：`CHANGELOG.md`, `README.md`, `benchmarks/adapters/registry.json`, `docs/PRODUCTION_BACKLOG.md` 等\n- **宿主 AI 上下文**：AI Context Pack、Prompt Preview、Skill 路由、风险规则和项目事实。 原因：导入上下文会影响宿主 AI 后续判断，必须避免把未验证项包装成事实。\n\n### 最小安全下一步\n\n- **先跑 Prompt Preview**：先用交互式试用验证任务画像和角色匹配，不要先导入整套角色库。（适用：任何项目都适用，尤其是输出质量未知时。）\n- **只在隔离目录或测试账号试装**：避免安装命令污染主力宿主 AI、真实项目或用户主目录。（适用：存在命令执行、插件配置或本地写入线索时。）\n- **不要使用真实生产凭证**：环境变量/API key 一旦进入宿主或工具链，可能产生账号和合规风险。（适用：出现 API、TOKEN、KEY、SECRET 等环境线索时。）\n- **安装后只验证一个最小任务**：先验证加载、兼容、输出质量和回滚，再决定是否深用。（适用：准备从试用进入真实工作流时。）\n\n### 退出方式\n\n- **保留安装前状态**：记录原始宿主配置和项目状态，后续才能判断是否可恢复。\n- **保留原始角色选择记录**：如果输出偏题，可以回到任务画像阶段重新选择角色，而不是继续沿着错误角色推进。\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_0028` inferred 0.45\n- **命令执行会修改本地环境**：安装命令可能写入用户主目录、宿主插件目录或项目配置。 处理方式：先在隔离环境或测试账号中运行。 证据：`README.md` Claim：`clm_0029` 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- 文件总数：220\n- 重要文件覆盖：40/220\n- 证据索引条目：80\n- 角色 / Skill 条目：25\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请基于 audrey 的 AI Context Pack，先问我 3 个必要问题，然后判断它是否适合我的任务。回答必须包含：适合谁、能做什么、不能做什么、是否值得安装、证据来自哪里。所有项目事实必须引用 evidence_refs、source_paths 或 claim_id。\n```\n\n### 安装前体验\n\n- 目标：让用户在安装前感受核心工作流，同时避免把预览包装成真实能力或营销承诺。\n- 预期输出：一段带边界标签的体验剧本、安装后验证清单和谨慎建议；不含真实运行承诺或强营销表述。\n\n```text\n请把 audrey 当作安装前体验资产，而不是已安装工具或真实运行环境。\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请基于 audrey 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。\n```\n\n\n## 角色 / Skill 索引\n\n- 共索引 25 个角色 / Skill / 项目文档条目。\n\n- **Why Audrey Exists**（project_doc）：The local-first memory firewall for AI agents. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`README.md`\n- **Audrey Python SDK**（project_doc）：Typed Python client for the Audrey REST API. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`python/README.md`\n- **Contributing**（project_doc）：Audrey is a production-focused memory layer, so contributions should optimize for correctness, observability, and safe operations. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CONTRIBUTING.md`\n- **Audrey Paper Outline**（project_doc）：Audrey Guard: Local-First Pre-Action Memory Control for Tool-Using Agents 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/AUDREY_PAPER_OUTLINE.md`\n- **Audrey Memory Benchmarking Strategy**（project_doc）：Audrey Memory Benchmarking Strategy 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/MEMORY_BENCHMARKING.md`\n- **Audrey Production Backlog**（project_doc）：Updated: 2026-05-13 after the Audrey 1.0 release-cut and paper-gate pass. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/PRODUCTION_BACKLOG.md`\n- **Agent Memory Should Control Tool Use: Audrey Guard and Pre-Action Memory Control**（project_doc）：Agent Memory Should Control Tool Use: Audrey Guard and Pre-Action Memory Control 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/paper/00-master.md`\n- **1. Introduction**（project_doc）：Tool-using agents fail in ways that ordinary chat-memory evaluation does not measure. They repeat broken shell commands after a previous run already exposed the error. They ignore project-specific setup rules that were learned in an earlier session. They lose the causal link between a failed action and the fix that made a later action safe. They treat degraded retrieval as complete memory and act anyway. In Audrey's… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/paper/01-introduction.md`\n- **2. Related Work**（project_doc）：This section organizes prior work by the behavior each system optimizes. The point of comparison is not whether a system has memory. It is whether memory runs before tool use and produces an evidence-linked action decision. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/paper/02-related-work.md`\n- **3. Problem Definition: Pre-Action Memory Control**（project_doc）：3. Problem Definition: Pre-Action Memory Control 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/paper/03-problem-definition.md`\n- **4. Design: Audrey Guard as a Pre-Action Memory Controller**（project_doc）：4. Design: Audrey Guard as a Pre-Action Memory Controller 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/paper/04-design.md`\n- **5. GuardBench Specification**（project_doc）：GuardBench is a benchmark specification for pre-action memory control. It evaluates whether memory changes a future tool action before the tool is invoked, not only whether a system retrieves relevant text. The benchmark target is an agent-memory system that receives a proposed action and returns a decision, evidence, and an auditable rationale. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/paper/05-guardbench-spec.md`\n- **6. Implementation**（project_doc）：Audrey is implemented as a local-first Node and TypeScript runtime with SQLite storage, vector and full-text indexes, MCP stdio tools, a REST sidecar, a Python client, a CLI, and release gates. The implementation is small enough to inspect directly, which is why this paper treats source-linked evidence as part of the artifact. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/paper/06-implementation.md`\n- **7. Evaluation**（project_doc）：This Stage-A evaluation reports implemented Audrey artifacts and local GuardBench adapters only. Section 5 specifies GuardBench as a reproducibility contract for pre-action memory control. The empirical claims below come from the repository's existing performance snapshot, the current behavioral regression output, the local comparative GuardBench runner, source-linked implementation inspection, and a freshly capture… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/paper/07-evaluation.md`\n- **8. Discussion and Limitations**（project_doc）：Repeated-failure prevention is the clearest implemented behavior. The demo records one failed npm run deploy , stores the operational lesson that Prisma generation must run first, and blocks the identical future action before tool use. The guard output includes a BLOCKED decision, risk score 0.90 , two blocking reflexes, one warning reflex, evidence IDs, concrete recommendations, and impact accounting Ledger: E25, E… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/paper/08-discussion-limitations.md`\n- **9. Conclusion**（project_doc）：Agent memory should be judged by whether it changes future tool actions. Audrey implements that claim for local agents through a host-side memory controller that runs before tool use and returns an auditable allow , warn , or block decision with evidence. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/paper/09-conclusion.md`\n- **Submission README**（project_doc）：- Nine drafted body sections in 01-introduction.md through 09-conclusion.md . - Consolidated Markdown master: audrey-paper-v1.md . - Evidence ledger with 97 rows: evidence-ledger.md . - Machine-readable claim register: claim-register.json . - Machine-readable publication pack: publication-pack.json . - Machine-readable browser launch plan: browser-launch-plan.json . - Machine-readable browser launch results ledger:… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/paper/SUBMISSION_README.md`\n- **Appendix A. Repeated-Failure Demo Transcript**（project_doc）：Appendix A. Repeated-Failure Demo Transcript 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/paper/appendix-a-demo-transcript.md`\n- **Agent Memory Should Control Tool Use: Audrey Guard and Pre-Action Memory Control**（project_doc）：Agent Memory Should Control Tool Use: Audrey Guard and Pre-Action Memory Control 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/paper/audrey-paper-v1.md`\n- **Audrey Paper Evidence Ledger**（project_doc）：Every implementation claim in the paper should point to one or more ledger IDs in this file. Use the JSON snapshot as the canonical benchmark source for paper numbers; the README sample table is tracked as a follow-up below. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/paper/evidence-ledger.md`\n- **Audrey Guard Controller Implementation Plan**（project_doc）：Audrey Guard Controller Implementation Plan 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/superpowers/plans/2026-05-05-audrey-guard-controller-implementation.md`\n- **Audrey Guard Controller Design**（project_doc）：Date: 2026-05-05 Status: draft for user review Target release: v0.23 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/superpowers/specs/2026-05-05-audrey-guard-controller-design.md`\n- **Summary**（project_doc）：Describe the problem this PR fixes and the user-facing or operator-facing outcome. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.github/pull_request_template.md`\n- **Changelog**（project_doc）：- GuardBench pass gate rewritten. The passed check no longer requires Audrey-specific lineage substrings \"failed before\" , \"recall:\" , \"must-follow\" , etc. in the subject's summary . A scenario passes when the decision matches the expected verdict, no seeded secrets leak, and for block / warn scenarios the subject returns at least one evidence id. The prior phrase-substring gate was structurally biased toward Audrey… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CHANGELOG.md`\n- **Security Policy**（project_doc）：Security fixes are best-effort for the current published release line and the current default branch. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`SECURITY.md`\n\n## 证据索引\n\n- 共索引 80 条证据。\n\n- **Why Audrey Exists**（documentation）：The local-first memory firewall for AI agents. 证据：`README.md`\n- **Audrey Python SDK**（documentation）：Typed Python client for the Audrey REST API. 证据：`python/README.md`\n- **Package**（package_manifest）：{ \"name\": \"audrey\", \"version\": \"1.0.1\", \"description\": \"Local-first memory runtime for AI agents with recall, consolidation, memory reflexes, contradiction detection, and tool-trace learning\", \"type\": \"module\", \"main\": \"dist/src/index.js\", \"types\": \"dist/src/index.d.ts\", \"exports\": { \".\": { \"types\": \"./dist/src/index.d.ts\", \"default\": \"./dist/src/index.js\" }, \"./mcp\": { \"types\": \"./dist/mcp-server/index.d.ts\", \"default\": \"./dist/mcp-server/index.js\" }, \"./server\": { \"types\": \"./dist/src/server.d.ts\", \"default\": \"./dist/src/server.js\" } }, \"bin\": { \"audrey\": \"dist/mcp-server/index.js\", \"audrey-mcp\": \"dist/mcp-server/index.js\" }, \"files\": \"dist/\", \"benchmarks/ .js\", \"benchmarks/ .mjs\", \"bench… 证据：`package.json`\n- **Contributing**（documentation）：Audrey is a production-focused memory layer, so contributions should optimize for correctness, observability, and safe operations. 证据：`CONTRIBUTING.md`\n- **License**（source_file）：Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files the \"Software\" , to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 证据：`LICENSE`\n- **Audrey Paper Outline**（documentation）：Audrey Guard: Local-First Pre-Action Memory Control for Tool-Using Agents 证据：`docs/AUDREY_PAPER_OUTLINE.md`\n- **Audrey Memory Benchmarking Strategy**（documentation）：Audrey Memory Benchmarking Strategy 证据：`docs/MEMORY_BENCHMARKING.md`\n- **Audrey Production Backlog**（documentation）：Updated: 2026-05-13 after the Audrey 1.0 release-cut and paper-gate pass. 证据：`docs/PRODUCTION_BACKLOG.md`\n- **Agent Memory Should Control Tool Use: Audrey Guard and Pre-Action Memory Control**（documentation）：Agent Memory Should Control Tool Use: Audrey Guard and Pre-Action Memory Control 证据：`docs/paper/00-master.md`\n- **1. Introduction**（documentation）：Tool-using agents fail in ways that ordinary chat-memory evaluation does not measure. They repeat broken shell commands after a previous run already exposed the error. They ignore project-specific setup rules that were learned in an earlier session. They lose the causal link between a failed action and the fix that made a later action safe. They treat degraded retrieval as complete memory and act anyway. In Audrey's repeated-failure demo, an agent first runs npm run deploy and fails because the Prisma client was not generated. Audrey records the failed tool event, stores the operational rule, and blocks the same action when it is proposed again. The transcript ends with the intended behavio… 证据：`docs/paper/01-introduction.md`\n- **2. Related Work**（documentation）：This section organizes prior work by the behavior each system optimizes. The point of comparison is not whether a system has memory. It is whether memory runs before tool use and produces an evidence-linked action decision. 证据：`docs/paper/02-related-work.md`\n- **3. Problem Definition: Pre-Action Memory Control**（documentation）：3. Problem Definition: Pre-Action Memory Control 证据：`docs/paper/03-problem-definition.md`\n- **4. Design: Audrey Guard as a Pre-Action Memory Controller**（documentation）：4. Design: Audrey Guard as a Pre-Action Memory Controller 证据：`docs/paper/04-design.md`\n- **5. GuardBench Specification**（documentation）：GuardBench is a benchmark specification for pre-action memory control. It evaluates whether memory changes a future tool action before the tool is invoked, not only whether a system retrieves relevant text. The benchmark target is an agent-memory system that receives a proposed action and returns a decision, evidence, and an auditable rationale. 证据：`docs/paper/05-guardbench-spec.md`\n- **6. Implementation**（documentation）：Audrey is implemented as a local-first Node and TypeScript runtime with SQLite storage, vector and full-text indexes, MCP stdio tools, a REST sidecar, a Python client, a CLI, and release gates. The implementation is small enough to inspect directly, which is why this paper treats source-linked evidence as part of the artifact. 证据：`docs/paper/06-implementation.md`\n- **7. Evaluation**（documentation）：This Stage-A evaluation reports implemented Audrey artifacts and local GuardBench adapters only. Section 5 specifies GuardBench as a reproducibility contract for pre-action memory control. The empirical claims below come from the repository's existing performance snapshot, the current behavioral regression output, the local comparative GuardBench runner, source-linked implementation inspection, and a freshly captured repeated-failure demo transcript. 证据：`docs/paper/07-evaluation.md`\n- **8. Discussion and Limitations**（documentation）：Repeated-failure prevention is the clearest implemented behavior. The demo records one failed npm run deploy , stores the operational lesson that Prisma generation must run first, and blocks the identical future action before tool use. The guard output includes a BLOCKED decision, risk score 0.90 , two blocking reflexes, one warning reflex, evidence IDs, concrete recommendations, and impact accounting Ledger: E25, E42 . The change is not better recall in a chat answer. The change is that the second tool call does not happen. 证据：`docs/paper/08-discussion-limitations.md`\n- **9. Conclusion**（documentation）：Agent memory should be judged by whether it changes future tool actions. Audrey implements that claim for local agents through a host-side memory controller that runs before tool use and returns an auditable allow , warn , or block decision with evidence. 证据：`docs/paper/09-conclusion.md`\n- **Submission README**（documentation）：- Nine drafted body sections in 01-introduction.md through 09-conclusion.md . - Consolidated Markdown master: audrey-paper-v1.md . - Evidence ledger with 97 rows: evidence-ledger.md . - Machine-readable claim register: claim-register.json . - Machine-readable publication pack: publication-pack.json . - Machine-readable browser launch plan: browser-launch-plan.json . - Machine-readable browser launch results ledger: browser-launch-results.json . - Machine-readable arXiv source package: docs/paper/output/arxiv/ . - Machine-readable arXiv compile report: docs/paper/output/arxiv-compile-report.json . - Compiled arXiv PDF and compile log: docs/paper/output/arxiv-compile/main.pdf , docs/paper/out… 证据：`docs/paper/SUBMISSION_README.md`\n- **Appendix A. Repeated-Failure Demo Transcript**（documentation）：Appendix A. Repeated-Failure Demo Transcript 证据：`docs/paper/appendix-a-demo-transcript.md`\n- **Agent Memory Should Control Tool Use: Audrey Guard and Pre-Action Memory Control**（documentation）：Agent Memory Should Control Tool Use: Audrey Guard and Pre-Action Memory Control 证据：`docs/paper/audrey-paper-v1.md`\n- **Audrey Paper Evidence Ledger**（documentation）：Every implementation claim in the paper should point to one or more ledger IDs in this file. Use the JSON snapshot as the canonical benchmark source for paper numbers; the README sample table is tracked as a follow-up below. 证据：`docs/paper/evidence-ledger.md`\n- **Audrey Guard Controller Implementation Plan**（documentation）：Audrey Guard Controller Implementation Plan 证据：`docs/superpowers/plans/2026-05-05-audrey-guard-controller-implementation.md`\n- **Audrey Guard Controller Design**（documentation）：Date: 2026-05-05 Status: draft for user review Target release: v0.23 证据：`docs/superpowers/specs/2026-05-05-audrey-guard-controller-design.md`\n- **Summary**（documentation）：Describe the problem this PR fixes and the user-facing or operator-facing outcome. 证据：`.github/pull_request_template.md`\n- **Changelog**（documentation）：- GuardBench pass gate rewritten. The passed check no longer requires Audrey-specific lineage substrings \"failed before\" , \"recall:\" , \"must-follow\" , etc. in the subject's summary . A scenario passes when the decision matches the expected verdict, no seeded secrets leak, and for block / warn scenarios the subject returns at least one evidence id. The prior phrase-substring gate was structurally biased toward Audrey because only its controller emitted those exact tokens; baselines or external adapters that produced semantically correct decisions could still fail the gate on phrasing alone. The Audrey-style lineage match is preserved as a separate lineageTextMatched field per row and lineage… 证据：`CHANGELOG.md`\n- **Security Policy**（documentation）：Security fixes are best-effort for the current published release line and the current default branch. 证据：`SECURITY.md`\n- **Tsconfig**（structured_config）：{ \"compilerOptions\": { \"target\": \"ES2022\", \"module\": \"Node16\", \"moduleResolution\": \"Node16\", \"lib\": \"ES2022\" , \"outDir\": \"./dist\", \"rootDir\": \".\", \"declaration\": true, \"declarationMap\": true, \"sourceMap\": true, \"strict\": true, \"esModuleInterop\": true, \"skipLibCheck\": true, \"forceConsistentCasingInFileNames\": true, \"resolveJsonModule\": true, \"isolatedModules\": true, \"noUncheckedIndexedAccess\": true, \"noUnusedLocals\": false, \"noUnusedParameters\": false }, \"include\": \"src/ / .ts\", \"mcp-server/ / .ts\" , \"exclude\": \"node modules\", \"dist\", \"tests\", \"benchmarks\", \"examples\" } 证据：`tsconfig.json`\n- **Registry**（structured_config）：{ \"schemaVersion\": \"1.0.0\", \"suite\": \"GuardBench adapter registry\", \"adapters\": { \"id\": \"example-allow\", \"name\": \"Example Allow Adapter\", \"path\": \"benchmarks/adapters/example-allow.mjs\", \"status\": \"reference\", \"credentialMode\": \"none\", \"requiredEnv\": , \"description\": \"Credential-free reference adapter for validating module loading, self-test generation, and report validation.\", \"commands\": { \"moduleValidate\": \"npm run bench:guard:adapter-module:validate -- --adapter benchmarks/adapters/example-allow.mjs\", \"selfTest\": \"npm run bench:guard:adapter-self-test -- --adapter benchmarks/adapters/example-allow.mjs\", \"selfTestValidate\": \"npm run bench:guard:adapter-self-test:validate -- --report benc… 证据：`benchmarks/adapters/registry.json`\n- **Guardbench Adapter Registry.Schema**（structured_config）：{ \"$schema\": \"https://json-schema.org/draft/2020-12/schema\", \"$id\": \"https://audrey-memory.org/schemas/guardbench-adapter-registry.schema.json\", \"title\": \"GuardBench Adapter Registry\", \"type\": \"object\", \"additionalProperties\": false, \"required\": \"schemaVersion\", \"suite\", \"adapters\" , \"properties\": { \"schemaVersion\": { \"const\": \"1.0.0\" }, \"suite\": { \"const\": \"GuardBench adapter registry\" }, \"adapters\": { \"type\": \"array\", \"minItems\": 1, \"items\": { \"$ref\": \" /$defs/adapter\" } } }, \"$defs\": { \"adapter\": { \"type\": \"object\", \"additionalProperties\": false, \"required\": \"id\", \"name\", \"path\", \"status\", \"credentialMode\", \"requiredEnv\", \"description\", \"commands\" , \"properties\": { \"id\": { \"type\": \"strin… 证据：`benchmarks/schemas/guardbench-adapter-registry.schema.json`\n- **Guardbench Adapter Self Test.Schema**（structured_config）：{ \"$schema\": \"https://json-schema.org/draft/2020-12/schema\", \"$id\": \"https://audrey-memory.org/schemas/guardbench-adapter-self-test.schema.json\", \"title\": \"GuardBench Adapter Self-Test\", \"type\": \"object\", \"additionalProperties\": false, \"required\": \"schemaVersion\", \"suite\", \"generatedAt\", \"ok\", \"adapter\", \"conformance\", \"score\", \"contract\", \"failures\" , \"properties\": { \"schemaVersion\": { \"const\": \"1.0.0\" }, \"suite\": { \"const\": \"GuardBench adapter self-test\" }, \"generatedAt\": { \"type\": \"string\", \"minLength\": 1 }, \"ok\": { \"type\": \"boolean\" }, \"adapter\": { \"$ref\": \" /$defs/adapter\" }, \"conformance\": { \"$ref\": \" /$defs/conformance\" }, \"score\": { \"$ref\": \" /$defs/score\" }, \"contract\": { \"$ref\": \"… 证据：`benchmarks/schemas/guardbench-adapter-self-test.schema.json`\n- **Guardbench Conformance Card.Schema**（structured_config）：{ \"$schema\": \"https://json-schema.org/draft/2020-12/schema\", \"$id\": \"https://audrey-memory.org/schemas/guardbench-conformance-card.schema.json\", \"title\": \"GuardBench Conformance Card\", \"type\": \"object\", \"additionalProperties\": false, \"required\": \"schemaVersion\", \"suite\", \"generatedAt\", \"sourceDir\", \"manifestVersion\", \"suiteId\", \"subject\", \"run\", \"score\", \"conformance\", \"integrity\", \"provenance\" , \"properties\": { \"schemaVersion\": { \"const\": \"1.0.0\" }, \"suite\": { \"const\": \"GuardBench conformance card\" }, \"generatedAt\": { \"type\": \"string\", \"minLength\": 1 }, \"sourceDir\": { \"type\": \"string\", \"minLength\": 1 }, \"manifestVersion\": { \"type\": \"string\", \"minLength\": 1 }, \"suiteId\": { \"type\": \"string\",… 证据：`benchmarks/schemas/guardbench-conformance-card.schema.json`\n- **Guardbench External Dry Run.Schema**（structured_config）：{ \"$schema\": \"https://json-schema.org/draft/2020-12/schema\", \"$id\": \"https://audrey-memory.org/schemas/guardbench-external-dry-run.schema.json\", \"title\": \"GuardBench External Adapter Dry-Run Matrix\", \"type\": \"object\", \"additionalProperties\": false, \"required\": \"schemaVersion\", \"suite\", \"generatedAt\", \"ok\", \"registry\", \"outRoot\", \"adapters\", \"failures\" , \"properties\": { \"schemaVersion\": { \"const\": \"1.0.0\" }, \"suite\": { \"const\": \"GuardBench external adapter dry-run matrix\" }, \"generatedAt\": { \"type\": \"string\", \"minLength\": 1 }, \"ok\": { \"type\": \"boolean\" }, \"registry\": { \"type\": \"string\", \"minLength\": 1 }, \"outRoot\": { \"type\": \"string\", \"minLength\": 1 }, \"adapters\": { \"type\": \"array\", \"minItem… 证据：`benchmarks/schemas/guardbench-external-dry-run.schema.json`\n- **Guardbench External Evidence.Schema**（structured_config）：{ \"$schema\": \"https://json-schema.org/draft/2020-12/schema\", \"$id\": \"https://audrey-memory.org/schemas/guardbench-external-evidence.schema.json\", \"title\": \"GuardBench External Evidence Verification\", \"type\": \"object\", \"additionalProperties\": false, \"required\": \"schemaVersion\", \"suite\", \"generatedAt\", \"ok\", \"allowPending\", \"registry\", \"outRoot\", \"adapters\", \"failures\" , \"properties\": { \"schemaVersion\": { \"const\": \"1.0.0\" }, \"suite\": { \"const\": \"GuardBench external evidence verification\" }, \"generatedAt\": { \"type\": \"string\", \"minLength\": 1 }, \"ok\": { \"type\": \"boolean\" }, \"allowPending\": { \"type\": \"boolean\" }, \"registry\": { \"type\": \"string\", \"minLength\": 1 }, \"outRoot\": { \"type\": \"string\", \"mi… 证据：`benchmarks/schemas/guardbench-external-evidence.schema.json`\n- **Guardbench External Run.Schema**（structured_config）：{ \"$schema\": \"https://json-schema.org/draft/2020-12/schema\", \"$id\": \"https://audrey-memory.org/schemas/guardbench-external-run.schema.json\", \"title\": \"GuardBench External Run Metadata\", \"type\": \"object\", \"additionalProperties\": false, \"required\": \"suite\", \"startedAt\", \"adapter\", \"adapterPath\", \"outDir\", \"requiredEnv\", \"missingEnv\", \"command\", \"validationCommand\", \"dryRun\", \"status\" , \"properties\": { \"suite\": { \"const\": \"GuardBench external adapter run\" }, \"startedAt\": { \"type\": \"string\", \"minLength\": 1 }, \"completedAt\": { \"type\": \"string\", \"minLength\": 1 }, \"adapter\": { \"type\": \"string\", \"minLength\": 1 }, \"adapterPath\": { \"type\": \"string\", \"minLength\": 1 }, \"outDir\": { \"type\": \"string\", \"mi… 证据：`benchmarks/schemas/guardbench-external-run.schema.json`\n- **Guardbench Leaderboard.Schema**（structured_config）：{ \"$schema\": \"https://json-schema.org/draft/2020-12/schema\", \"$id\": \"https://audrey-memory.org/schemas/guardbench-leaderboard.schema.json\", \"title\": \"GuardBench Leaderboard\", \"type\": \"object\", \"additionalProperties\": false, \"required\": \"schemaVersion\", \"suite\", \"generatedAt\", \"ranking\", \"rows\", \"failures\" , \"properties\": { \"schemaVersion\": { \"const\": \"1.0.0\" }, \"suite\": { \"const\": \"GuardBench leaderboard\" }, \"generatedAt\": { \"type\": \"string\", \"minLength\": 1 }, \"ranking\": { \"type\": \"array\", \"minItems\": 1, \"items\": { \"type\": \"string\", \"minLength\": 1 } }, \"rows\": { \"type\": \"array\", \"items\": { \"$ref\": \" /$defs/row\" } }, \"failures\": { \"type\": \"array\", \"items\": { \"type\": \"string\" } } }, \"$defs\":… 证据：`benchmarks/schemas/guardbench-leaderboard.schema.json`\n- **Guardbench Manifest.Schema**（structured_config）：{ \"$schema\": \"https://json-schema.org/draft/2020-12/schema\", \"$id\": \"https://audrey-memory.org/schemas/guardbench-manifest.schema.json\", \"title\": \"GuardBench Manifest\", \"type\": \"object\", \"additionalProperties\": false, \"required\": \"manifestVersion\", \"suiteId\", \"suiteName\", \"generatedBy\", \"decisionVocabulary\", \"subjects\", \"metrics\", \"contract\", \"scenarios\" , \"properties\": { \"manifestVersion\": { \"type\": \"string\", \"minLength\": 1 }, \"suiteId\": { \"type\": \"string\", \"minLength\": 1 }, \"suiteName\": { \"type\": \"string\", \"minLength\": 1 }, \"generatedBy\": { \"type\": \"string\", \"minLength\": 1 }, \"decisionVocabulary\": { \"type\": \"array\", \"minItems\": 3, \"items\": { \"enum\": \"allow\", \"warn\", \"block\" }, \"contains\":… 证据：`benchmarks/schemas/guardbench-manifest.schema.json`\n- **Guardbench Publication Verification.Schema**（structured_config）：{ \"$schema\": \"https://json-schema.org/draft/2020-12/schema\", \"$id\": \"https://audrey-memory.org/schemas/guardbench-publication-verification.schema.json\", \"title\": \"GuardBench Publication Artifact Verification\", \"type\": \"object\", \"additionalProperties\": false, \"required\": \"schemaVersion\", \"suite\", \"generatedAt\", \"ok\", \"checks\", \"failures\" , \"properties\": { \"schemaVersion\": { \"const\": \"1.0.0\" }, \"suite\": { \"const\": \"GuardBench publication artifact verification\" }, \"generatedAt\": { \"type\": \"string\", \"minLength\": 1 }, \"ok\": { \"type\": \"boolean\" }, \"checks\": { \"type\": \"object\", \"additionalProperties\": false, \"required\": \"registry\", \"adapterModule\", \"selfTest\", \"artifacts\", \"bundle\", \"externalDryRu… 证据：`benchmarks/schemas/guardbench-publication-verification.schema.json`\n- **Guardbench Raw.Schema**（structured_config）：{ \"$schema\": \"https://json-schema.org/draft/2020-12/schema\", \"$id\": \"https://audrey-memory.org/schemas/guardbench-raw.schema.json\", \"title\": \"GuardBench Raw Output\", \"type\": \"object\", \"additionalProperties\": false, \"required\": \"suite\", \"generatedAt\", \"manifestVersion\", \"provenance\", \"cases\", \"artifactRedactionSweep\" , \"properties\": { \"suite\": { \"const\": \"GuardBench comparative\" }, \"generatedAt\": { \"type\": \"string\", \"minLength\": 1 }, \"manifestVersion\": { \"type\": \"string\", \"minLength\": 1 }, \"provenance\": { \"$ref\": \" /$defs/provenance\" }, \"cases\": { \"type\": \"array\", \"minItems\": 10, \"items\": { \"$ref\": \" /$defs/caseResult\" } }, \"artifactRedactionSweep\": { \"$ref\": \" /$defs/artifactRedactionSweep\"… 证据：`benchmarks/schemas/guardbench-raw.schema.json`\n- **Guardbench Submission Manifest.Schema**（structured_config）：{ \"$schema\": \"https://json-schema.org/draft/2020-12/schema\", \"$id\": \"https://audrey-memory.org/schemas/guardbench-submission-manifest.schema.json\", \"title\": \"GuardBench Submission Manifest\", \"type\": \"object\", \"additionalProperties\": false, \"required\": \"schemaVersion\", \"suite\", \"generatedAt\", \"sourceDir\", \"subject\", \"score\", \"conformance\", \"validation\", \"files\" , \"properties\": { \"schemaVersion\": { \"const\": \"1.0.0\" }, \"suite\": { \"const\": \"GuardBench submission bundle\" }, \"generatedAt\": { \"type\": \"string\", \"minLength\": 1 }, \"sourceDir\": { \"type\": \"string\", \"minLength\": 1 }, \"subject\": { \"$ref\": \" /$defs/subject\" }, \"score\": { \"$ref\": \" /$defs/score\" }, \"conformance\": { \"$ref\": \" /$defs/conform… 证据：`benchmarks/schemas/guardbench-submission-manifest.schema.json`\n- **Guardbench Summary.Schema**（structured_config）：{ \"$schema\": \"https://json-schema.org/draft/2020-12/schema\", \"$id\": \"https://audrey-memory.org/schemas/guardbench-summary.schema.json\", \"title\": \"GuardBench Summary\", \"type\": \"object\", \"additionalProperties\": false, \"required\": \"suite\", \"generatedAt\", \"manifest\", \"provenance\", \"subjects\", \"scenarios\", \"passed\", \"passRate\", \"preventionRate\", \"falseBlockRate\", \"decisionAccuracy\", \"evidenceRecall\", \"redactionLeaks\", \"recallDegradationDetectionRate\", \"latency\", \"systemSummaries\", \"comparisons\", \"rows\", \"cases\", \"artifactRedactionSweep\" , \"properties\": { \"suite\": { \"const\": \"GuardBench comparative\" }, \"generatedAt\": { \"type\": \"string\", \"minLength\": 1 }, \"manifest\": { \"type\": \"object\" }, \"provena… 证据：`benchmarks/schemas/guardbench-summary.schema.json`\n- **Perf 0.22.2**（structured_config）：{ \"generatedAt\": \"2026-05-01T02:15:29.400Z\", \"durationMs\": 4600, \"audreyVersion\": null, \"gitSha\": \"e2e821b\", \"methodology\": { \"embedding\": \"mock provider, 64 dimensions in-process, no network \", \"llm\": \"mock provider in-process \", \"retrieval\": \"hybrid vector + lexical with limit=5\", \"sizes\": 100, 1000, 5000 , \"recallRunsPerSize\": 50, \"notes\": \"Latency is wall-clock for a single call from a JS caller. Cloud and local 384-dim providers will report higher recall latency dominated by embedding cost and network. Run on your own hardware before quoting.\" }, \"machine\": { \"node\": \"25.5.0\", \"v8\": \"14.1.146.11-node.18\", \"platform\": \"win32\", \"arch\": \"x64\", \"osRelease\": \"10.0.26200\", \"cpuCount\": 24, \"c… 证据：`benchmarks/snapshots/perf-0.22.2.json`\n- **Perf 0.23.0**（structured_config）：{ \"generatedAt\": \"2026-05-05T17:32:45.578Z\", \"durationMs\": 1042, \"audreyVersion\": \"0.23.0\", \"gitSha\": \"20cdde0\", \"methodology\": { \"embedding\": \"mock provider, 64 dimensions in-process, no network \", \"llm\": \"mock provider in-process \", \"retrieval\": \"hybrid vector + lexical with limit=5\", \"sizes\": 100, 1000, 5000 , \"recallRunsPerSize\": 50, \"notes\": \"Latency is wall-clock for a single call from a JS caller. Cloud and local 384-dim providers will report higher recall latency dominated by embedding cost and network. Run on your own hardware before quoting.\" }, \"machine\": { \"node\": \"25.9.0\", \"v8\": \"14.1.146.11-node.25\", \"platform\": \"darwin\", \"arch\": \"arm64\", \"osRelease\": \"25.4.0\", \"cpuCount\": 18,… 证据：`benchmarks/snapshots/perf-0.23.0.json`\n- **Arxiv Compile Report.Schema**（structured_config）：{ \"$schema\": \"https://json-schema.org/draft/2020-12/schema\", \"$id\": \"https://audrey-memory.org/schemas/audrey-arxiv-compile-report.schema.json\", \"title\": \"Audrey arXiv Compile Report\", \"type\": \"object\", \"additionalProperties\": false, \"required\": \"schemaVersion\", \"suite\", \"generatedAt\", \"source\", \"outputDir\", \"status\", \"compiler\", \"outputPdf\", \"outputPdfSha256\", \"logFile\", \"blockers\", \"failures\" , \"properties\": { \"schemaVersion\": { \"const\": \"1.0.0\" }, \"suite\": { \"const\": \"Audrey arXiv compile check\" }, \"generatedAt\": { \"type\": \"string\", \"minLength\": 1 }, \"source\": { \"anyOf\": { \"type\": \"null\" }, { \"type\": \"object\", \"additionalProperties\": false, \"required\": \"sourceDir\", \"manifest\", \"manifestS… 证据：`docs/paper/arxiv-compile-report.schema.json`\n- **Arxiv Source.Schema**（structured_config）：{ \"$schema\": \"https://json-schema.org/draft/2020-12/schema\", \"$id\": \"https://audrey-memory.org/schemas/audrey-arxiv-source-manifest.schema.json\", \"title\": \"Audrey arXiv Source Manifest\", \"type\": \"object\", \"additionalProperties\": false, \"required\": \"schemaVersion\", \"suite\", \"generatedAt\", \"sourceMarkdown\", \"publicationPack\", \"sourceHashes\", \"files\", \"tex\" , \"properties\": { \"schemaVersion\": { \"const\": \"1.0.0\" }, \"suite\": { \"const\": \"Audrey arXiv source package\" }, \"generatedAt\": { \"type\": \"string\", \"minLength\": 1 }, \"sourceMarkdown\": { \"type\": \"string\", \"minLength\": 1 }, \"publicationPack\": { \"type\": \"string\", \"minLength\": 1 }, \"sourceHashes\": { \"type\": \"object\", \"additionalProperties\": false,… 证据：`docs/paper/arxiv-source.schema.json`\n- **Browser Launch Plan**（structured_config）：{ \"schemaVersion\": \"1.0.0\", \"suite\": \"Audrey browser launch plan\", \"checkedAt\": \"2026-05-13\", \"publicationPack\": \"docs/paper/publication-pack.json\", \"sources\": { \"id\": \"arxiv-submission-guidelines\", \"url\": \"https://info.arxiv.org/help/submit/index.html\", \"checkedAt\": \"2026-05-13\", \"notes\": \"Use the registered-author user page to start a new submission; verify uploaded files and metadata before final submit.\" }, { \"id\": \"arxiv-category-taxonomy\", \"url\": \"https://arxiv.org/category taxonomy\", \"checkedAt\": \"2026-05-13\", \"notes\": \"cs.AI covers artificial intelligence; cs.CR covers cryptography and security. Use cs.AI primary and cs.CR secondary only if the final paper framing still matches both… 证据：`docs/paper/browser-launch-plan.json`\n- **Browser Launch Plan.Schema**（structured_config）：{ \"$schema\": \"https://json-schema.org/draft/2020-12/schema\", \"$id\": \"https://audrey-memory.org/schemas/audrey-browser-launch-plan.schema.json\", \"title\": \"Audrey Browser Launch Plan\", \"type\": \"object\", \"additionalProperties\": false, \"required\": \"schemaVersion\", \"suite\", \"checkedAt\", \"publicationPack\", \"sources\", \"preflightCommands\", \"targets\" , \"properties\": { \"schemaVersion\": { \"const\": \"1.0.0\" }, \"suite\": { \"const\": \"Audrey browser launch plan\" }, \"checkedAt\": { \"type\": \"string\", \"minLength\": 1 }, \"publicationPack\": { \"type\": \"string\", \"minLength\": 1 }, \"sources\": { \"type\": \"array\", \"minItems\": 1, \"items\": { \"$ref\": \" /$defs/source\" } }, \"preflightCommands\": { \"type\": \"array\", \"minItems\":… 证据：`docs/paper/browser-launch-plan.schema.json`\n- **Browser Launch Results**（structured_config）：{ \"schemaVersion\": \"1.0.0\", \"suite\": \"Audrey browser launch results\", \"capturedAt\": \"2026-05-13\", \"plan\": \"docs/paper/browser-launch-plan.json\", \"targets\": { \"id\": \"arxiv-preprint\", \"platform\": \"arxiv\", \"status\": \"pending\", \"publicUrl\": null, \"artifactUrl\": \"https://paper-site-r3jdakujn-evilanders-projects.vercel.app\", \"submittedAt\": null, \"operatorVerified\": false, \"manualRuleCheckCompleted\": true, \"postSubmitChecksCompleted\": , \"blocker\": \"arXiv accepted the paper as submit/7591154, but the account page currently shows status on hold, so no public arXiv identifier or public abstract URL has been assigned yet.\", \"notes\": \"arXiv support confirmed the active username is Evilands and suspende… 证据：`docs/paper/browser-launch-results.json`\n- **Browser Launch Results.Schema**（structured_config）：{ \"$schema\": \"https://json-schema.org/draft/2020-12/schema\", \"$id\": \"https://audrey-memory.org/schemas/audrey-browser-launch-results.schema.json\", \"title\": \"Audrey Browser Launch Results\", \"type\": \"object\", \"additionalProperties\": false, \"required\": \"schemaVersion\", \"suite\", \"capturedAt\", \"plan\", \"targets\" , \"properties\": { \"schemaVersion\": { \"const\": \"1.0.0\" }, \"suite\": { \"const\": \"Audrey browser launch results\" }, \"capturedAt\": { \"type\": \"string\", \"minLength\": 1 }, \"plan\": { \"type\": \"string\", \"minLength\": 1 }, \"targets\": { \"type\": \"array\", \"minItems\": 1, \"items\": { \"$ref\": \" /$defs/targetResult\" } } }, \"$defs\": { \"nullableHttpsUrl\": { \"anyOf\": { \"type\": \"null\" }, { \"type\": \"string\", \"patt… 证据：`docs/paper/browser-launch-results.schema.json`\n- **Claim Register**（structured_config）：{ \"schemaVersion\": \"1.0.0\", \"suite\": \"Audrey paper claim register\", \"claims\": { \"id\": \"C01\", \"status\": \"supported\", \"claim\": \"Audrey Guard passes the local Stage-A GuardBench comparative suite without leaking seeded secrets in published artifacts.\", \"evidence\": \"benchmarks/output/guardbench-summary.json\", \"benchmarks/output/guardbench-raw.json\", \"docs/paper/evidence-ledger.md E46\", \"docs/paper/evidence-ledger.md E65\" , \"artifactChecks\": \"guardbench-local-passed\", \"no-published-secret-leaks\" , \"requiredText\": { \"path\": \"README.md\", \"text\": \"Latest local result in this checkout: 10/10 scenarios passed\" }, { \"path\": \"docs/paper/audrey-paper-v1.md\", \"text\": \"Local comparative GuardBench reports… 证据：`docs/paper/claim-register.json`\n- **Claim Register.Schema**（structured_config）：{ \"$schema\": \"https://json-schema.org/draft/2020-12/schema\", \"$id\": \"https://audrey-memory.org/schemas/audrey-paper-claim-register.schema.json\", \"title\": \"Audrey Paper Claim Register\", \"type\": \"object\", \"additionalProperties\": false, \"required\": \"schemaVersion\", \"suite\", \"claims\" , \"properties\": { \"schemaVersion\": { \"const\": \"1.0.0\" }, \"suite\": { \"const\": \"Audrey paper claim register\" }, \"claims\": { \"type\": \"array\", \"minItems\": 1, \"items\": { \"$ref\": \" /$defs/claim\" } } }, \"$defs\": { \"claim\": { \"type\": \"object\", \"additionalProperties\": false, \"required\": \"id\", \"status\", \"claim\", \"evidence\", \"artifactChecks\", \"requiredText\", \"forbiddenText\" , \"properties\": { \"id\": { \"type\": \"string\", \"pattern… 证据：`docs/paper/claim-register.schema.json`\n- **Paper Submission Bundle.Schema**（structured_config）：{ \"$schema\": \"https://json-schema.org/draft/2020-12/schema\", \"$id\": \"https://audrey-memory.org/schemas/audrey-paper-submission-bundle.schema.json\", \"title\": \"Audrey Paper Submission Bundle\", \"type\": \"object\", \"additionalProperties\": false, \"required\": \"schemaVersion\", \"suite\", \"generatedAt\", \"sourceRoot\", \"outDir\", \"claimVerification\", \"publicationPackVerification\", \"guardBenchSnapshot\", \"files\" , \"properties\": { \"schemaVersion\": { \"const\": \"1.0.0\" }, \"suite\": { \"const\": \"Audrey paper submission bundle\" }, \"generatedAt\": { \"type\": \"string\", \"minLength\": 1 }, \"sourceRoot\": { \"type\": \"string\", \"minLength\": 1 }, \"outDir\": { \"type\": \"string\", \"minLength\": 1 }, \"claimVerification\": { \"$ref\": \" /… 证据：`docs/paper/paper-submission-bundle.schema.json`\n- **Publication Pack**（structured_config）：{ \"schemaVersion\": \"1.0.0\", \"suite\": \"Audrey publication pack\", \"claimRegister\": \"docs/paper/claim-register.json\", \"entries\": { \"id\": \"arxiv-title\", \"platform\": \"arxiv\", \"kind\": \"title\", \"claimIds\": \"C01\", \"C03\" , \"maxChars\": 180, \"text\": \"Audrey: Local-First Pre-Action Memory Control for AI Agents\" }, { \"id\": \"arxiv-abstract\", \"platform\": \"arxiv\", \"kind\": \"abstract\", \"claimIds\": \"C01\", \"C02\", \"C03\", \"C04\" , \"maxChars\": 1920, \"text\": \"AI agents increasingly rely on long-running tool use, but most memory systems are evaluated as retrieval layers rather than as pre-action control systems. Audrey is a local-first memory runtime that records episodes, procedures, contradictions, tool traces, va… 证据：`docs/paper/publication-pack.json`\n- **Publication Pack.Schema**（structured_config）：{ \"$schema\": \"https://json-schema.org/draft/2020-12/schema\", \"$id\": \"https://audrey-memory.org/schemas/audrey-publication-pack.schema.json\", \"title\": \"Audrey Publication Pack\", \"type\": \"object\", \"additionalProperties\": false, \"required\": \"schemaVersion\", \"suite\", \"claimRegister\", \"entries\" , \"properties\": { \"schemaVersion\": { \"const\": \"1.0.0\" }, \"suite\": { \"const\": \"Audrey publication pack\" }, \"claimRegister\": { \"type\": \"string\", \"minLength\": 1 }, \"entries\": { \"type\": \"array\", \"minItems\": 1, \"items\": { \"$ref\": \" /$defs/entry\" } } }, \"$defs\": { \"entry\": { \"type\": \"object\", \"additionalProperties\": false, \"required\": \"id\", \"platform\", \"kind\", \"claimIds\", \"maxChars\", \"text\" , \"properties\": { \"i… 证据：`docs/paper/publication-pack.schema.json`\n- **Build artifacts and dependencies — rebuilt inside the image**（source_file）：Build artifacts and dependencies — rebuilt inside the image node modules dist .tsbuildinfo 证据：`.dockerignore`\n- **Docker-specific Audrey configuration**（source_file）：Docker-specific Audrey configuration Copy to .env and edit before running: docker compose up -d --build 证据：`.env.docker.example`\n- **Audrey Memory Configuration**（source_file）：Audrey Memory Configuration Copy to .env or set as environment variables 证据：`.env.example`\n- **.gitattributes**（source_file）：.js text eol=lf .json text eol=lf .md text eol=lf .svg text eol=lf .yml text eol=lf 证据：`.gitattributes`\n- **Node build output**（source_file）：node modules/ .npm-cache/ .tmp-npm-cache/ .audrey-demo-tmp/ .claude/settings.local.json audrey-data/ .tmp/ .tmp-vitest/ .archive/ .worktrees/ .db .db-wal .db-shm .env CLAUDE.md benchmarks/output/ benchmarks/.tmp/ benchmarks/.tmp-guardbench/ docs/paper/output/ memorybench/ windows-smoke-job- .log gcm-diagnose.log .log audrey-arxiv-preview.png 证据：`.gitignore`\n- **.npmignore**（source_file）：tests/ docs/ examples/ node modules/ test- -data/ .git/ .gitignore .env CLAUDE.md vitest.config.js package-lock.json .db .db-wal .db-shm 证据：`.npmignore`\n- 其余 20 条证据见 `AI_CONTEXT_PACK.json` 或 `EVIDENCE_INDEX.json`。\n\n## 宿主 AI 必须遵守的规则\n\n- **把本资产当作开工前上下文，而不是运行环境。**：AI Context Pack 只包含证据化项目理解，不包含目标项目的可执行状态。 证据：`README.md`, `python/README.md`, `package.json`\n- **回答用户时区分可预览内容与必须安装后才能验证的内容。**：安装前体验的消费者价值来自降低误装和误判，而不是伪装成真实运行。 证据：`README.md`, `python/README.md`, `package.json`\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- **Audrey Overview**：importance `high`\n  - source_paths: README.md, src/types.ts, src/audrey.ts\n- **Quick Start Guide**：importance `high`\n  - source_paths: README.md, package.json, src/index.ts\n- **System Architecture**：importance `high`\n  - source_paths: src/audrey.ts, src/controller.ts, src/server.ts, src/db.ts, mcp-server/index.ts\n- **Memory Model**：importance `high`\n  - source_paths: src/consolidate.ts, src/decay.ts, src/interference.ts, src/affect.ts, src/confidence.ts\n- **Audrey Guard**：importance `high`\n  - source_paths: src/preflight.ts, src/feedback.ts, src/events.ts, src/action-key.ts, src/redact.ts\n- **Core Memory Operations**：importance `high`\n  - source_paths: src/encode.ts, src/recall.ts, src/hybrid-recall.ts, src/fts.ts, src/impact.ts\n- **Preflight and Reflexes**：importance `high`\n  - source_paths: src/preflight.ts, src/reflexes.ts, src/validate.ts, src/rules-compiler.ts\n- **Data Storage**：importance `high`\n  - source_paths: src/db.ts, src/hybrid-recall.ts, src/fts.ts, src/embedding.ts, src/export.ts\n\n## Repo Inspection Evidence / 源码检查证据\n\n- repo_clone_verified: true\n- repo_inspection_verified: true\n- repo_commit: `82b0e9979680acf751b9e80f6f90f8c6ac74befb`\n- inspected_files: `Dockerfile`, `package.json`, `README.md`, `docker-compose.yml`, `docs/PRODUCTION_BACKLOG.md`, `docs/MEMORY_BENCHMARKING.md`, `docs/AUDREY_PAPER_OUTLINE.md`, `docs/paper/06-implementation.md`, `docs/paper/browser-launch-plan.schema.json`, `docs/paper/00-master.md`, `docs/paper/publication-pack.json`, `docs/paper/03-problem-definition.md`, `docs/paper/claim-register.schema.json`, `docs/paper/publication-pack.schema.json`, `docs/paper/02-related-work.md`, `docs/paper/01-introduction.md`, `docs/paper/08-discussion-limitations.md`, `docs/paper/evidence-ledger.md`, `docs/paper/arxiv-source.schema.json`, `docs/paper/audrey-paper-v1.md`\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: 来源证据：Audrey 1.0.1 — honest GuardBench gate, Guard time decay, structured validate errors\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Audrey 1.0.1 — honest GuardBench gate, Guard time decay, structured validate errors\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_135b992964ae468aa28f88ee639816d1 | https://github.com/Evilander/Audrey/releases/tag/v1.0.1 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 2: 来源证据：Audrey Guard 0.23.0\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Audrey Guard 0.23.0\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_9c913c644e2c4c099ea01523623f080e | https://github.com/Evilander/Audrey/releases/tag/v0.23.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 3: 来源证据：v0.16.0\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.16.0\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_a7c5c62d4f034e50ba2e9c36e0798882 | https://github.com/Evilander/Audrey/releases/tag/v0.16.0 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 4: 来源证据：v0.16.1 — Windows MCP fix\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.16.1 — Windows MCP fix\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_c0141ccf0a3245ec8c8ba112af7948e0 | https://github.com/Evilander/Audrey/releases/tag/v0.16.1 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 5: 来源证据：v0.17.0\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.17.0\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_9617863b3f954035926b8670b5bbea29 | https://github.com/Evilander/Audrey/releases/tag/v0.17.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 6: 可能修改宿主 AI 配置\n\n- Trigger: 项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- Host AI rule: 列出会写入的配置文件、目录和卸载/回滚步骤。\n- Why it matters: 安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- Evidence: capability.host_targets | github_repo:1161444210 | https://github.com/Evilander/Audrey | host_targets=mcp_host, claude, claude_code\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 7: 能力判断依赖假设\n\n- Trigger: README/documentation is current enough for a first validation pass.\n- Host AI rule: 将假设转成下游验证清单。\n- Why it matters: 假设不成立时，用户拿不到承诺的能力。\n- Evidence: capability.assumptions | github_repo:1161444210 | https://github.com/Evilander/Audrey | README/documentation is current enough for a first validation pass.\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 8: 维护活跃度未知\n\n- Trigger: 未记录 last_activity_observed。\n- Host AI rule: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Why it matters: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Evidence: evidence.maintainer_signals | github_repo:1161444210 | https://github.com/Evilander/Audrey | last_activity_observed missing\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 9: 下游验证发现风险项\n\n- Trigger: no_demo\n- Host AI rule: 进入安全/权限治理复核队列。\n- Why it matters: 下游已经要求复核，不能在页面中弱化。\n- Evidence: downstream_validation.risk_items | github_repo:1161444210 | https://github.com/Evilander/Audrey | no_demo; severity=medium\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 10: 存在评分风险\n\n- Trigger: no_demo\n- Host AI rule: 把风险写入边界卡，并确认是否需要人工复核。\n- Why it matters: 风险会影响是否适合普通用户安装。\n- Evidence: risks.scoring_risks | github_repo:1161444210 | https://github.com/Evilander/Audrey | no_demo; severity=medium\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项目：Evilander/Audrey\n\n## Doramagic 试用结论\n\n当前结论：可以进入发布前推荐检查；首次使用仍应从最小权限、临时目录和可回滚配置开始。\n\n## 用户现在可以做\n\n- 可以先阅读 Human Manual，理解项目目的和主要工作流。\n- 可以复制 Prompt Preview 做安装前体验；这只验证交互感，不代表真实运行。\n- 可以把官方 Quick Start 命令放到隔离环境中验证，不要直接进主力环境。\n\n## 现在不要做\n\n- 不要把 Prompt Preview 当成项目实际运行结果。\n- 不要把 metadata-only validation 当成沙箱安装验证。\n- 不要把未验证能力写成“已支持、已跑通、可放心安装”。\n- 不要在首次试用时交出生产数据、私人文件、真实密钥或主力配置目录。\n\n## 安装前检查\n\n- 宿主 AI 是否匹配：mcp_host, claude, claude_code\n- 官方安装入口状态：已发现官方入口\n- 是否在临时目录、临时宿主或容器中验证：必须是\n- 是否能回滚配置改动：必须能\n- 是否需要 API Key、网络访问、读写文件或修改宿主配置：未确认前按高风险处理\n- 是否记录了安装命令、实际输出和失败日志：必须记录\n\n## 当前阻塞项\n\n- 无阻塞项。\n\n## 项目专属踩坑\n\n- 来源证据：Audrey 1.0.1 — honest GuardBench gate, Guard time decay, structured validate errors（medium）：可能增加新用户试用和生产接入成本。 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 来源证据：Audrey Guard 0.23.0（medium）：可能增加新用户试用和生产接入成本。 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 来源证据：v0.16.0（medium）：可能增加新用户试用和生产接入成本。 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 来源证据：v0.16.1 — Windows MCP fix（medium）：可能增加新用户试用和生产接入成本。 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 来源证据：v0.17.0（medium）：可能增加新用户试用和生产接入成本。 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n\n## 风险与权限提示\n\n- no_demo: medium\n\n## 证据缺口\n\n- 暂未发现结构化证据缺口。\n",
      "summary": "安装、权限、验证和推荐前风险。",
      "title": "Boundary & Risk Card / 边界与风险卡"
    },
    "human_manual": {
      "asset_id": "human_manual",
      "filename": "HUMAN_MANUAL.md",
      "markdown": "# https://github.com/Evilander/Audrey 项目说明书\n\n生成时间：2026-05-16 05:12:58 UTC\n\n## 目录\n\n- [Audrey Overview](#page-overview)\n- [Quick Start Guide](#page-quick-start)\n- [System Architecture](#page-system-architecture)\n- [Memory Model](#page-memory-model)\n- [Audrey Guard](#page-audrey-guard)\n- [Core Memory Operations](#page-memory-operations)\n- [Preflight and Reflexes](#page-reflexes-preflight)\n- [Data Storage](#page-data-storage)\n- [MCP Server](#page-mcp-server)\n- [REST API](#page-rest-api)\n\n<a id='page-overview'></a>\n\n## Audrey Overview\n\n### 相关页面\n\n相关主题：[System Architecture](#page-system-architecture), [Memory Model](#page-memory-model), [Quick Start Guide](#page-quick-start)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/Evilander/Audrey/blob/main/README.md)\n- [python/README.md](https://github.com/Evilander/Audrey/blob/main/python/README.md)\n- [src/audrey.ts](https://github.com/Evilander/Audrey/blob/main/src/audrey.ts)\n- [src/routes.ts](https://github.com/Evilander/Audrey/blob/main/src/routes.ts)\n- [src/impact.ts](https://github.com/Evilander/Audrey/blob/main/src/impact.ts)\n- [src/capsule.ts](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n- [src/redact.ts](https://github.com/Evilander/Audrey/blob/main/src/redact.ts)\n- [src/rules-compiler.ts](https://github.com/Evilander/Audrey/blob/main/src/rules-compiler.ts)\n- [mcp-server/index.ts](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n- [CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n</details>\n\n# Audrey Overview\n\nAudrey is a local-first memory firewall for AI agents. It provides a durable, SQLite-backed memory layer that enables AI agents to remember past mistakes, learned principles, and project-specific rules across sessions. Audrey acts as a continuity layer that sits under any local or sidecar agent loop, preventing agents from repeating the same mistakes and enabling smarter, more context-aware behavior.\n\n资料来源：[README.md:1-10]()\n\n## What Problem Audrey Solves\n\nAI agents typically suffer from \"cold start\" problems—they treat every new session as if they've never interacted with the project before. They repeat broken commands, lose project-specific rules, miss contradictions, and forget the exact mistakes they made yesterday.\n\nAudrey addresses this by implementing a closed feedback loop:\n\n1. **Record** what happened during agent actions\n2. **Remember** what mattered from those events\n3. **Check** before new actions using stored memories\n4. **Return** decisions (`allow`, `warn`, or `block`) with evidence\n5. **Validate** whether the memory helped improve outcomes\n\n资料来源：[README.md:25-40]()\n\n## Architecture Overview\n\nAudrey is built with a layered architecture that separates concerns between memory storage, retrieval, governance, and agent integration.\n\n```mermaid\ngraph TD\n    subgraph Client Layer\n        CLI[CLI Tool<br>npx audrey]\n        PythonSDK[Python SDK<br>audrey_memory]\n        MCPServer[MCP Server]\n    end\n    \n    subgraph Integration Layer\n        Hooks[Claude Code Hooks<br>PreToolUse/PostToolUse]\n        MCPConfig[MCP Config<br>Codex, VSCode, etc.]\n    end\n    \n    subgraph Core Engine\n        Guard[Audrey Guard<br>Memory-before-action]\n        Routes[REST API<br>/v1/*]\n    end\n    \n    subgraph Memory Layer\n        SQLite[(SQLite<br>WAL Mode)]\n        Episodic[Episodic<br>Memory]\n        Semantic[Semantic<br>Memory]\n        Procedural[Procedural<br>Memory]\n    end\n    \n    subgraph Embedding\n        ONNX[ONNX Runtime<br>Local Embeddings]\n        Providers[Cloud Providers<br>OpenAI, Anthropic]\n    end\n    \n    CLI --> Routes\n    PythonSDK --> Routes\n    MCPServer --> Routes\n    Hooks --> Guard\n    MCPConfig --> MCPServer\n    Guard --> Routes\n    Routes --> SQLite\n    SQLite --> Episodic\n    SQLite --> Semantic\n    SQLite --> Procedural\n    Routes --> ONNX\n    Routes --> Providers\n```\n\n资料来源：[README.md:1-50]()\n\n## Core Components\n\n### Memory Types\n\nAudrey manages three distinct types of memory, each serving a different purpose:\n\n| Memory Type | Purpose | Examples |\n|------------|---------|----------|\n| **Episodic** | Records specific events and outcomes | \"Deploy failed at 3:42 PM with OOM error\" |\n| **Semantic** | Stores learned facts, principles, and rules | \"Stripe rate limits are 100 req/s\" |\n| **Procedural** | Captures how-to knowledge and workflows | \"To deploy, run `npm run deploy` after `npm test`\" |\n\nEach memory type can be tagged, sourced, and validated independently. Memories gain salience through usage—memories that are repeatedly helpful become more prominent, while unused memories decay over time.\n\n资料来源：[README.md:40-55]()\n\n### Audrey Guard\n\nAudrey Guard is the core decision-making component that checks memories before agent actions execute. It implements a preflight check that returns structured decisions:\n\n```mermaid\ngraph LR\n    Action[Agent Action<br>tool + parameters] --> Guard\n    Guard --> Recall[Recall Relevant<br>Memories]\n    Recall --> Decision{Decision}\n    Decision -->|No issues| ALLOW[allow]\n    Decision -->|Potential risk| WARN[warn<br>+ evidence]\n    Decision -->|Dangerous| BLOCK[block<br>+ reason]\n    Decision -->|Uncertain| QUERY[Query<br>Human]\n```\n\nThe Guard returns a decision with supporting evidence, allowing the agent to make informed choices. When set to strict mode, warnings are treated as blocks.\n\n资料来源：[README.md:25-35]()\n\n### Memory Capsule\n\nThe Memory Capsule is a structured response format that bundles contextual information for agent preflight checks:\n\n| Section | Description |\n|---------|-------------|\n| `recent_changes` | Memories created/modified within the recent-change window |\n| `must_follow` | Critical rules tagged as mandatory |\n| `procedures` | Step-by-step workflows relevant to the query |\n| `user_preferences` | Explicitly stated user preferences |\n| `risks` | Warnings and risk indicators |\n| `uncertain_or_disputed` | Low-confidence or contested memories |\n\n资料来源：[src/capsule.ts:1-50]()\n\n### Impact Tracking\n\nAudrey tracks the effectiveness of its memories through a closed validation loop:\n\n```mermaid\ngraph TD\n    Action[Action with Memory] --> Outcome{Outcome}\n    Outcome -->|helpful| Boost[Boost salience<br>+usage_count]\n    Outcome -->|used| Maintain[Maintain salience]\n    Outcome -->|wrong| Challenge[Challenge memory<br>Decrease salience]\n    Boost --> Consolidation[Consolidation<br>Dream cycle]\n    Maintain --> Consolidation\n    Challenge --> Consolidation\n    Consolidation --> Principles[New Semantic<br>Principles]\n```\n\nOutcome types:\n- **helpful**: The memory contributed to a successful outcome\n- **used**: The memory was consulted but didn't directly contribute\n- **wrong**: The memory led to an incorrect decision\n\n资料来源：[src/impact.ts:1-60]()\n\n## Installation Methods\n\nAudrey supports multiple installation patterns depending on your use case.\n\n### CLI Installation\n\nFor direct terminal usage:\n\n```bash\nnpx audrey doctor          # Verify setup\nnpx audrey demo --scenario repeated-failure  # Run demo\nnpx audrey guard --tool Bash \"npm run deploy\"  # Check before action\n```\n\n资料来源：[README.md:55-65]()\n\n### MCP Server Integration\n\nFor integration with agents like Codex, Claude Desktop, Cursor, and VS Code:\n\n```bash\n# Generate MCP configuration\nnpx audrey mcp-config codex\nnpx audrey mcp-config generic\nnpx audrey mcp-config vscode\n```\n\n资料来源：[mcp-server/index.ts:1-40]()\n\n### Claude Code Hooks\n\nFor Claude Code, install directly and configure memory-before-action hooks:\n\n```bash\nnpx audrey install\nclaude mcp list\n\n# Apply hooks to project or user scope\nnpx audrey hook-config claude-code --apply --scope project  # Project-local\nnpx audrey hook-config claude-code --apply --scope user     # User-wide\n```\n\nThe generated hooks include:\n- `PreToolUse`: Runs `audrey guard --hook --fail-on-warn`\n- `PostToolUse`: Records successful tool executions\n- `PostToolUseFailure`: Records failed tool executions\n\n资料来源：[README.md:67-85]()\n\n### Python SDK\n\nFor Python-based agent integrations:\n\n```bash\npip install audrey-memory\n```\n\n```python\nfrom audrey_memory import Audrey\n\nbrain = Audrey(\n    base_url=\"http://127.0.0.1:7437\",\n    api_key=\"secret\",\n    agent=\"support-agent\",\n)\n\n# Encode new memories\nmemory_id = brain.encode(\n    \"Stripe returns HTTP 429 above 100 req/s\",\n    source=\"direct-observation\",\n    tags=[\"stripe\", \"rate-limit\"],\n)\n\n# Recall relevant memories\nresults = brain.recall(\"stripe rate limits\", limit=5)\n\n# Close connection\nbrain.close()\n```\n\n资料来源：[python/README.md:1-50]()\n\n## REST API Reference\n\nThe Audrey REST API exposes core memory operations via HTTP.\n\n### Endpoints Overview\n\n| Method | Endpoint | Description |\n|--------|----------|-------------|\n| `GET` | `/health` | Server health check |\n| `POST` | `/v1/encode` | Store a new memory |\n| `POST` | `/v1/recall` | Retrieve memories by semantic similarity |\n| `POST` | `/v1/preflight` | Memory-before-action check |\n| `POST` | `/v1/validate` | Submit outcome feedback |\n| `POST` | `/v1/impact` | Get impact statistics |\n\n资料来源：[src/routes.ts:1-80]()\n\n### Core API Operations\n\n#### Encode Memory\n\n```typescript\ninterface EncodeRequest {\n  content: string;           // The memory content\n  memory_type: 'episodic' | 'semantic' | 'procedural';\n  source: string;            // e.g., \"direct-observation\", \"told-by-user\"\n  tags?: string[];\n  private?: boolean;        // Agent-only memory\n  wait_for_consolidation?: boolean;\n}\n```\n\n资料来源：[src/routes.ts:80-120]()\n\n#### Recall Memories\n\n```typescript\ninterface RecallRequest {\n  query: string;\n  limit?: number;           // Default: 5\n  budget_chars?: number;    // Context budget\n  retrieval?: 'hybrid' | 'vector';  // Default: hybrid\n  mood?: {                  // Optional affect configuration\n    min_valence?: number;\n    min_arousal?: number;\n  };\n}\n```\n\n#### Preflight Check\n\n```typescript\ninterface PreflightRequest {\n  tool: string;             // e.g., \"Bash\", \"Write\"\n  action: string;           // The specific action/command\n  session_id?: string;\n  cwd?: string;\n  include_capsule?: boolean;\n  include_preflight?: boolean;\n  record_event?: boolean;\n}\n```\n\n#### Validate Outcome\n\n```typescript\ninterface ValidateRequest {\n  receipt_id: string;       // From preflight response\n  outcome: 'helpful' | 'used' | 'wrong';\n  evidence_feedback?: Record<string, 'helpful' | 'used' | 'wrong'>;\n  metadata?: Record<string, unknown>;\n}\n```\n\n资料来源：[src/routes.ts:120-200]()\n\n## Configuration\n\n### Environment Variables\n\n| Variable | Default | Purpose |\n|----------|---------|---------|\n| `AUDREY_DATA_DIR` | `~/.audrey` | SQLite data directory (set per tenant/agent) |\n| `AUDREY_EMBEDDING_PROVIDER` | `onnx` | Embedding provider: `onnx`, `openai`, `anthropic`, `google` |\n| `AUDREY_LLM_PROVIDER` | `openai` | LLM provider for consolidation |\n| `AUDREY_MODEL` | varies | Specific model to use |\n| `AUDREY_HOST` | `127.0.0.1` | REST sidecar bind address |\n| `AUDREY_PORT` | `7437` | REST sidecar port |\n| `AUDREY_API_KEY` | unset | Bearer token for non-loopback access |\n| `AUDREY_ALLOW_NO_AUTH` | `0` | Allow non-loopback without API key (not recommended) |\n| `AUDREY_ENABLE_ADMIN_TOOLS` | `0` | Enable export/import/forget routes |\n| `AUDREY_DEBUG` | `0` | Enable debug logging |\n| `AUDREY_PROFILE` | `0` | Emit per-stage diagnostics |\n| `AUDREY_DISABLE_WARMUP` | `0` | Skip embedding warmup at boot |\n| `AUDREY_CONTEXT_BUDGET_CHARS` | `4000` | Default capsule character budget |\n\n资料来源：[README.md:150-180]()\n\n### Data Isolation\n\n> SQLite uses WAL mode without an advisory lock, so two processes sharing a directory will contend on writes. Isolation is a hard requirement for multi-agent setups.\n\n**Important**: Set a distinct `AUDREY_DATA_DIR` per tenant, agent identity, or concurrent host to avoid write contention.\n\n资料来源：[README.md:55-60]()\n\n## Security\n\n### Redaction\n\nAudrey automatically redacts sensitive information from stored memories and logs:\n\n| Class | Patterns |\n|-------|----------|\n| `api_key` | `api_key`, `apiKey`, `API_KEY` patterns |\n| `password` | `password`, `passwd`, `pwd` |\n| `token` | `token`, `bearer_token`, `access_token`, `jwt` |\n| `secret` | `secret`, `client_secret`, `private_key` |\n\nThe redaction system walks JSON structures recursively and applies pattern matching to both keys and values.\n\n资料来源：[src/redact.ts:1-60]()\n\n### Access Control\n\n- HTTP API key comparison uses `crypto.timingSafeEqual` to prevent timing attacks\n- `audrey serve` defaults to binding `127.0.0.1` (was `0.0.0.0`)\n- Non-loopback bind requires `AUDREY_API_KEY` or explicit `AUDREY_ALLOW_NO_AUTH=1`\n- Private memories have ACL enforcement at the recall endpoint\n- `sanitizeRecallOptions()` allowlists HTTP body parameters to prevent option injection\n\n资料来源：[CHANGELOG.md:1-30]()\n\n## Production Readiness\n\n### Release Gates\n\n```bash\nnpm run release:gate           # Full release checklist\nnpm run python:release:check   # Python package verification\nnpm run bench:guard:card       # Guard performance benchmarks\nnpm run bench:guard:validate   # Guard accuracy validation\nnpx audrey doctor              # Runtime health check\nnpx audrey status --json --fail-on-unhealthy\n```\n\n### Production Checklist\n\n- Set one `AUDREY_DATA_DIR` per tenant, environment, or isolation boundary\n- Pin `AUDREY_EMBEDDING_PROVIDER` and `AUDREY_LLM_PROVIDER` explicitly\n- Back up the SQLite data directory before provider or dimension changes\n- Keep API keys and raw credentials out of encoded memory content\n- Use `AUDREY_API_KEY` if the REST sidecar is reachable beyond local process boundary\n- Run `audrey dream` on a schedule for consolidation and decay\n- Add application-level encryption, retention, access control, and audit logging for regulated environments\n\n资料来源：[README.md:100-125]()\n\n## Memory Lifecycle\n\n```mermaid\ngraph TD\n    Event[Agent Event<br>Action/Failure] --> Encode[Encode Memory<br>episodic]\n    Encode --> Salience[Initial Salience<br>from confidence]\n    Salience --> Usage[Usage Cycle]\n    \n    Usage --> Preflight[Preflight Check]\n    Preflight --> Decision[Guard Decision]\n    Decision --> Action[Execute Action]\n    Action --> Outcome{Outcome}\n    \n    Outcome -->|Success| Boost[Boost Salience<br/>usage_count++]\n    Outcome -->|Partial| Maintain[Maintain]\n    Outcome -->|Failure| Challenge[Challenge<br/>decay confidence]\n    \n    Boost --> Consolidation{Dream Cycle}\n    Maintain --> Consolidation\n    Challenge --> Consolidation\n    \n    Consolidation --> Principle[Extract Principle<br/>semantic memory]\n    Consolidation --> Decay[Apply Decay<br/>unused memories]\n    \n    Principle --> NewMemory[New Semantic<br/>Memory]\n    Decay --> Prune[Prune Very Low<br/>salience memories]\n```\n\n### Dream Cycle\n\nThe `memory_dream` operation consolidates episodes into principles and applies decay:\n\n- **Consolidation**: Groups related episodic memories into higher-level semantic principles\n- **Decay**: Reduces salience of memories that haven't been used recently\n- **Challenge**: Flags memories that led to wrong outcomes for review\n\n资料来源：[README.md:40-50]()\n\n## Supported Integrations\n\n| Agent/IDE | Integration Method | Features |\n|-----------|-------------------|----------|\n| Claude Code | Hooks + MCP | Full memory-guard loop |\n| Codex | MCP Config | Memory recall |\n| Claude Desktop | MCP | Memory access |\n| Cursor | MCP Config | Memory recall |\n| Windsurf | MCP Config | Memory recall |\n| VS Code | MCP Config | Memory recall |\n| JetBrains | MCP Config | Memory recall |\n| Ollama | Generic MCP | Memory recall |\n| Custom Agents | REST API / Python SDK | Full integration |\n\n资料来源：[README.md:10-20]()\n\n## Key Files Reference\n\n| File | Purpose |\n|------|---------|\n| `src/audrey.ts` | Core Audrey class with memory operations |\n| `src/routes.ts` | REST API route handlers |\n| `src/capsule.ts` | Memory capsule builder |\n| `src/impact.ts` | Impact tracking and validation |\n| `src/redact.ts` | Sensitive data redaction |\n| `src/rules-compiler.ts` | Rule file generation from memories |\n| `mcp-server/index.ts` | MCP server and CLI commands |\n| `python/` | Python SDK implementation |\n\n资料来源：[src/audrey.ts](), [src/routes.ts](), [src/capsule.ts](), [src/impact.ts](), [src/redact.ts](), [src/rules-compiler.ts](), [mcp-server/index.ts](), [python/README.md]()\n\n---\n\n<a id='page-quick-start'></a>\n\n## Quick Start Guide\n\n### 相关页面\n\n相关主题：[Audrey Overview](#page-overview)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/Evilander/Audrey/blob/main/README.md)\n- [CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n- [python/README.md](https://github.com/Evilander/Audrey/blob/main/python/README.md)\n- [src/routes.ts](https://github.com/Evilander/Audrey/blob/main/src/routes.ts)\n- [mcp-server/index.ts](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n- [src/impact.ts](https://github.com/Evilander/Audrey/blob/main/src/impact.ts)\n</details>\n\n# Quick Start Guide\n\n## Overview\n\nAudrey is a local-first memory firewall for AI agents that provides a durable memory layer they can check before executing tools. This guide covers installation, configuration, and basic usage patterns across all supported surfaces: CLI, REST API, JavaScript SDK, and Python client.\n\n## Prerequisites\n\n| Requirement | Version/Details |\n|-------------|-----------------|\n| Node.js | v18+ recommended |\n| npm | v8+ |\n| Python | 3.9+ (for Python SDK) |\n| SQLite | Built-in (bundled) |\n| Docker | Optional for containerized deployment |\n\n## Installation\n\n### CLI Installation\n\n```bash\nnpm install -g audrey\n```\n\nVerify installation:\n\n```bash\naudrey --version\n```\n\n### Python SDK Installation\n\n```bash\npip install audrey-memory\n```\n\n资料来源：[python/README.md:1-20](https://github.com/Evilander/Audrey/blob/main/python/README.md)\n\n## Quick Setup\n\n### 1. Run the Health Check\n\n```bash\naudrey doctor\n```\n\nThis command validates the installation and checks for any configuration issues.\n\n资料来源：[mcp-server/index.ts:85-120](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n\n### 2. Start the REST API Server\n\n```bash\nnpx audrey serve\n```\n\nBy default, the server binds to `127.0.0.1:7437`. Configure using environment variables:\n\n| Environment Variable | Default | Description |\n|---------------------|---------|-------------|\n| `AUDREY_PORT` | `7437` | REST API port |\n| `AUDREY_HOST` | `127.0.0.1` | REST sidecar bind address |\n| `AUDREY_API_KEY` | unset | Bearer token for non-loopback traffic |\n| `AUDREY_DATA_DIR` | `~/.audrey` | Data directory path |\n\n资料来源：[README.md:1-50](https://github.com/Evilander/Audrey/blob/main/README.md)\n\n### 3. Install MCP Configuration\n\nFor Claude Code integration:\n\n```bash\naudrey install --host claude-code\n```\n\nGenerate MCP config without applying:\n\n```bash\naudrey mcp-config --host claude-code --dry-run\n```\n\nApply project hooks:\n\n```bash\naudrey hook-config claude-code --apply --scope project\n```\n\nApply user hooks:\n\n```bash\naudrey hook-config claude-code --apply --scope user\n```\n\n资料来源：[mcp-server/index.ts:40-75](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n\n## Core Usage Patterns\n\n### Memory Guard Workflow\n\nThe primary safety loop that records events, checks memory before action, and returns decisions:\n\n```mermaid\ngraph TD\n    A[Agent Action] --> B[audrey guard --tool Bash npm run deploy]\n    B --> C{Memory Check}\n    C -->|allow| D[Execute Action]\n    C -->|warn| E[Execute with Warning]\n    C -->|block| F[Block Action]\n    D --> G[Record Outcome]\n    E --> G\n    F --> G\n    G --> H[Memory Consolidation]\n```\n\nExecute the guard command:\n\n```bash\naudrey guard --tool Bash \"npm run deploy\"\n```\n\nParameters:\n\n| Parameter | Description |\n|-----------|-------------|\n| `--tool` | Tool name (Bash, Write, Read, etc.) |\n| `--session-id` | Session identifier |\n| `--files` | File paths involved |\n| `--strict` | Fail on warning |\n\n资料来源：[mcp-server/index.ts:150-200](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n\n### Encoding Memories\n\n#### Via REST API\n\n```bash\ncurl -X POST http://127.0.0.1:7437/v1/encode \\\n  -H \"Authorization: Bearer secret\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"content\": \"Stripe returns HTTP 429 above 100 req/s\",\n    \"source\": \"direct-observation\",\n    \"tags\": [\"stripe\", \"rate-limit\"]\n  }'\n```\n\n#### Via Python SDK\n\n```python\nfrom audrey_memory import Audrey\n\nbrain = Audrey(\n    base_url=\"http://127.0.0.1:7437\",\n    api_key=\"secret\",\n    agent=\"support-agent\",\n)\n\nmemory_id = brain.encode(\n    \"Stripe returns HTTP 429 above 100 req/s\",\n    source=\"direct-observation\",\n    tags=[\"stripe\", \"rate-limit\"],\n)\n```\n\n资料来源：[python/README.md:25-45](https://github.com/Evilander/Audrey/blob/main/python/README.md)\n\n### Recalling Memories\n\n#### Via REST API\n\n```bash\ncurl -X POST http://127.0.0.1:7437/v1/recall \\\n  -H \"Authorization: Bearer secret\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"query\": \"stripe rate limits\",\n    \"limit\": 5,\n    \"retrieval\": \"hybrid\"\n  }'\n```\n\n#### Via Python SDK\n\n```python\nresults = brain.recall(\"stripe rate limits\", limit=5)\n```\n\n#### Available Recall Options\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `query` | string | required | Search query |\n| `limit` | number | 10 | Maximum results |\n| `budget_chars` | number | 4000 | Context budget in characters |\n| `retrieval` | string | \"hybrid\" | \"hybrid\" or \"vector\" mode |\n| `include_private` | boolean | false | Include private memories |\n| `agent` | string | - | Filter by agent name |\n\n资料来源：[src/routes.ts:1-50](https://github.com/Evilander/Audrey/blob/main/src/routes.ts)\n\n### Getting Memory Capsule\n\nA turn-sized memory packet containing relevant context:\n\n```bash\ncurl -X POST http://127.0.0.1:7437/v1/capsule \\\n  -H \"Authorization: Bearer secret\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"query\": \"current deploy status\",\n    \"budget_chars\": 4000\n  }'\n```\n\nThe capsule contains sections:\n\n- `recent_changes` - Memories from recent window\n- `must_follow` - Critical rules\n- `procedures` - Step-by-step memories\n- `user_preferences` - User-stated preferences\n- `risks` - Warnings and risks\n- `uncertain_or_disputed` - Low-confidence items\n\n资料来源：[src/capsule.ts:1-60](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n\n### Check Health\n\n```bash\ncurl http://127.0.0.1:7437/v1/status\n```\n\nAsync version:\n\n```python\nimport asyncio\nfrom audrey_memory import AsyncAudrey\n\nasync def main():\n    async with AsyncAudrey(base_url=\"http://127.0.0.1:7437\", api_key=\"secret\") as brain:\n        health = await brain.health()\n        print(health)\n\nasyncio.run(main())\n```\n\n资料来源：[python/README.md:50-70](https://github.com/Evilander/Audrey/blob/main/python/README.md)\n\n## Advanced CLI Commands\n\n### Dream - Consolidate Memory\n\n```bash\naudrey dream\n```\n\nTriggers memory consolidation process.\n\n### Reembed - Rebuild Vector Indices\n\n```bash\naudrey reembed\n```\n\nRebuilds embedding indices after schema changes.\n\n### Observe Tool\n\nRecord tool execution results:\n\n```bash\naudrey observe-tool --tool Bash --input '{\"command\": \"npm test\"}' --output '{\"exitCode\": 0}'\n```\n\n### Impact Report\n\nGenerate memory impact analysis:\n\n```bash\naudrey impact --window-days 30 --limit 10\n```\n\nThe report includes:\n\n- Memory counts by type (episodic, semantic, procedural)\n- Validated memories count\n- Outcome breakdown (helpful, wrong, used)\n- Top used memories\n- Weakest memories by salience\n- Recent activity\n\n资料来源：[src/impact.ts:1-80](https://github.com/Evilander/Audrey/blob/main/src/impact.ts)\n\n### Promote - Extract Rules\n\nPromote memory candidates to reviewable Markdown files:\n\n```bash\naudrey promote --yes\n```\n\nRules are saved to `.claude/rules/` with YAML front matter for traceability.\n\n### Check Status\n\n```bash\naudrey status\n```\n\nDisplays:\n\n- Current mood (valence, arousal)\n- Memory counts\n- Learned principles\n- Recent memories\n- Unresolved threads\n\n资料来源：[mcp-server/index.ts:200-280](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n\n## MCP Server Tools\n\nAudrey provides 20 tools via MCP stdio protocol:\n\n| Tool | Purpose |\n|------|---------|\n| `memory_encode` | Record new memories |\n| `memory_recall` | Retrieve relevant memories |\n| `memory_capsule` | Get turn-sized context packet |\n| `preflight_check` | Validate before action |\n| `record_outcome` | Record action results |\n| `promote_memory` | Convert to persistent rule |\n| `impact_report` | Analyze memory effectiveness |\n\nResources include:\n\n- `status` - System health\n- `recent` - Recent memories\n- `principles` - Semantic memories\n- `briefing` - Current context\n\nPrompts include:\n\n- `memory-recall` - Search memories\n- `memory-reflection` - Self-analysis\n\n资料来源：[README.md:60-90](https://github.com/Evilander/Audrey/blob/main/README.md)\n\n## Configuration Reference\n\n### Environment Variables\n\n| Variable | Default | Description |\n|----------|---------|-------------|\n| `AUDREY_PORT` | `7437` | REST API port |\n| `AUDREY_HOST` | `127.0.0.1` | Bind address |\n| `AUDREY_API_KEY` | unset | Bearer token |\n| `AUDREY_DATA_DIR` | `~/.audrey` | Data directory |\n| `AUDREY_ENABLE_ADMIN_TOOLS` | `0` | Enable export/import routes |\n| `AUDREY_PROMOTE_ROOTS` | unset | Extra write roots |\n| `AUDREY_DEBUG` | `0` | Enable debug logging |\n| `AUDREY_PROFILE` | `0` | Emit per-stage timings |\n| `AUDREY_DISABLE_WARMUP` | `0` | Skip embedding warmup |\n| `AUDREY_CONTEXT_BUDGET_CHARS` | `4000` | Default capsule budget |\n\n资料来源：[README.md:40-55](https://github.com/Evilander/Audrey/blob/main/README.md)\n\n### Privacy Controls\n\nBy default, private memories are ACL-protected:\n\n- `include_private: true` is restricted in HTTP API\n- `confidenceConfig` overrides are blocked via `sanitizeRecallOptions()`\n\nFor full control, use the SDK directly or enable admin tools:\n\n```bash\nAUDREY_ENABLE_ADMIN_TOOLS=1 audrey serve\n```\n\n资料来源：[CHANGELOG.md:1-30](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n## Deployment Options\n\n### Docker\n\n```bash\ndocker run -p 7437:7437 \\\n  -e AUDREY_API_KEY=secret \\\n  -v audrey-data:/root/.audrey \\\n  audrey:latest\n```\n\n### Docker Compose\n\nUse the provided `docker-compose.yml` for persistent deployments with volume mounts.\n\n### Host-Specific Setup\n\nGenerate platform-specific MCP configurations:\n\n```bash\naudrey mcp-config --host claude-code\naudrey mcp-config --host cursor\naudrey mcp-config --host windsurf\n```\n\n资料来源：[README.md:80-100](https://github.com/Evilander/Audrey/blob/main/README.md)\n\n## Next Steps\n\n- Review `audrey doctor` output for any warnings\n- Configure `AUDREY_API_KEY` for production deployments\n- Set up MCP integration for your preferred IDE/agent\n- Explore memory types: episodic, semantic, procedural\n- Enable impact tracking to measure memory effectiveness\n\nFor detailed API documentation, see the REST API endpoints at `/v1/*` when the server is running.\n\n---\n\n<a id='page-system-architecture'></a>\n\n## System Architecture\n\n### 相关页面\n\n相关主题：[Audrey Overview](#page-overview), [Memory Model](#page-memory-model), [Data Storage](#page-data-storage), [MCP Server](#page-mcp-server), [REST API](#page-rest-api)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/audrey.ts](https://github.com/Evilander/Audrey/blob/main/src/audrey.ts)\n- [src/controller.ts](https://github.com/Evilander/Audrey/blob/main/src/controller.ts)\n- [src/server.ts](https://github.com/Evilander/Audrey/blob/main/src/server.ts)\n- [src/db.ts](https://github.com/Evilander/Audrey/blob/main/src/db.ts)\n- [mcp-server/index.ts](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n- [src/embedding.ts](https://github.com/Evilander/Audrey/blob/main/src/embedding.ts)\n</details>\n\n# System Architecture\n\n## Overview\n\nAudrey is a local-first memory runtime designed to give AI agents persistent, queryable memory across sessions. It operates as a **stateful infrastructure layer** that records observations, consolidates principles, and provides memory-before-action checks through multiple interfaces.\n\nThe system is built around a closed-loop safety architecture where every tool action can be validated against stored memory before execution, returning `allow`, `warn`, or `block` decisions with supporting evidence.\n\n## Core Design Principles\n\n| Principle | Description |\n|-----------|-------------|\n| Local-first | All data stored in local SQLite; no external database required |\n| Agent-agnostic | Works with Codex, Claude Code, Cursor, Windsurf, VS Code, JetBrains, Ollama, and custom agents |\n| Safety loop | Pre-action validation through Audrey Guard before tool execution |\n| Isolation per tenant | One `AUDREY_DATA_DIR` per tenant/agent/isolation boundary |\n| Privacy-by-default | Audrey Guard redacts tool traces; private memory ACL enforcement |\n\n## High-Level Component Architecture\n\n```mermaid\ngraph TD\n    subgraph \"Agent Host\"\n        A[AI Agent<br/>Claude Code / Codex / Cursor]\n    end\n    \n    subgraph \"Audrey Runtime\"\n        CLI[CLI<br/>doctor, demo, guard,<br/>install, status, dream]\n        MCP[MCP Server<br/>stdio interface]\n        REST[REST API<br/>Hono server :7437]\n        SDK[JS SDK<br/>TypeScript/Node]\n        PY[Python SDK<br/>audrey-memory]\n    end\n    \n    subgraph \"Core Engine\"\n        AUD[Audrey Core<br/>encode, recall, consolidate,<br/>validate, impact]\n        MEM[(Memory Store<br/>SQLite + sqlite-vec)]\n        EMB[Embedding Engine<br/>ONNX runtime]\n        CAUSAL[Causal Validation<br/>confidence scoring]\n    end\n    \n    A <--> MCP\n    A <--> REST\n    CLI --> MCP\n    CLI --> REST\n    SDK --> REST\n    PY --> REST\n    AUD <--> MEM\n    AUD <--> EMB\n    AUD <--> CAUSAL\n```\n\n## Component Specifications\n\n### MCP Server (`mcp-server/index.ts`)\n\nThe MCP stdio server provides 20+ tools plus status, recent, principles resources and briefing/recall/reflection prompts.\n\n| Interface Type | Count | Purpose |\n|----------------|-------|---------|\n| Tools | 20+ | encode, recall, capsule, guard, promote, impact, dream, reembed, observe-tool |\n| Resources | 3 | status, recent, principles |\n| Prompts | 3 | briefing, recall, reflection |\n\nThe server processes CLI arguments before entering stdio mode to handle `--help`, `--version`, and subcommands like `install`, `mcp-config`, `hook-config`. 资料来源：[mcp-server/index.ts:1-100]()\n\n### REST API (`src/routes.ts`)\n\nHono-based HTTP server exposing the following endpoints:\n\n| Endpoint | Method | Purpose |\n|----------|--------|---------|\n| `/health` | GET | Health check |\n| `/v1/encode` | POST | Store memory with source, tags, salience |\n| `/v1/recall` | POST | Retrieve relevant context |\n| `/v1/capsule` | POST | Get turn-sized memory packet |\n| `/v1/status` | GET | Runtime status |\n| `/v1/observe` | POST | Record tool outcome |\n| `/v1/validate` | POST | Validate memory usefulness |\n\n**Security**: HTTP recall/capsule routes use `sanitizeRecallOptions()` to prevent private-memory ACL bypass via caller-supplied options. API key comparison uses `crypto.timingSafeEqual` to prevent timing attacks. 资料来源：[src/routes.ts:1-80]()\n\n### Audrey Core (`src/audrey.ts`)\n\nThe central engine handling memory operations:\n\n```mermaid\ngraph LR\n    ENC[encode] --> VEC[Vector Embedding]\n    ENC --> DB[(SQLite)]\n    REC[recall] --> VEC\n    REC --> DB\n    VEC --> EMB[Embedding Engine]\n    DB --> CAUSAL[Causal Validation]\n    CAUSAL --> CONF[Confidence Scoring]\n```\n\n**Key operations:**\n- `encode()`: Stores episodic, semantic, or procedural memory with vector embedding\n- `recall()`: Retrieves memories using hybrid (vector + FTS) search\n- `consolidate()`: Extracts principles from repeated evidence\n- `decay()`: Reduces authority of stale, low-confidence memories\n- `beforeAction()`: Guard check returning `allow`/`warn`/`block`\n- `afterAction()`: Records tool execution outcomes\n\n### Storage Layer (`src/db.ts`)\n\nSQLite with `sqlite-vec` extension for vector search.\n\n| Feature | Configuration |\n|---------|---------------|\n| Mode | WAL (Write-Ahead Logging) |\n| Concurrency | No advisory lock; single writer per `AUDREY_DATA_DIR` |\n| Indexing | sqlite-vec for vector similarity; FTS for full-text |\n| Isolation | One directory per tenant required |\n\nThe `AUDREY_PRAGMA_DEFAULTS` environment variable (default `1`) applies custom PRAGMA tuning. Set to `0` to revert to better-sqlite3 defaults.\n\n### Embedding Engine (`src/embedding.ts`)\n\nONNX runtime for local vector embedding without external API calls by default.\n\n| Feature | Behavior |\n|---------|----------|\n| Warmup | Background embedding warmup at MCP boot (skippable with `AUDREY_DISABLE_WARMUP=1`) |\n| Cold-start | First encode: ~525ms cold, ~28ms warm |\n| Verbosity | `AUDREY_ONNX_VERBOSE=1` restores EP-assignment warnings |\n| Reuse | Validation, interference, affect resonance reuse main content vector |\n\n**Performance targets (v0.22.0):**\n- Encode p50: 15.2ms (40% faster than prior)\n- Hybrid recall p50: 14.3ms (2.1x faster)\n- Embedding reuse eliminated 3 of 4 redundant calls\n\n## Memory Model Architecture\n\n```mermaid\ngraph TD\n    subgraph \"Memory Types\"\n        EPI[Episodic<br/>Specific observations,<br/>tool results, facts]\n        SEM[Semantic<br/>Consolidated principles<br/>from evidence]\n        PROC[Procedural<br/>Remembered ways to act,<br/>avoid, retry, verify]\n    end\n    \n    subgraph \"Memory Properties\"\n        AFF[Affect & Salience<br/>Emotional weight, importance]\n        DEC[Interference & Decay<br/>Stale/conflicting lose authority]\n        CON[Contradiction Handling<br/>Competing claims tracked]\n    end\n    \n    EPI --> AFF\n    SEM --> AFF\n    PROC --> AFF\n    EPI --> DEC\n    SEM --> CON\n    CON --> DEC\n```\n\n### Memory Types\n\n| Type | Description | Example |\n|------|-------------|---------|\n| Episodic | Specific observations, tool results, session facts | \"Stripe returns HTTP 429 above 100 req/s\" |\n| Semantic | Consolidated principles from repeated evidence | \"Always check rate limits before batch operations\" |\n| Procedural | Remembered ways to act, avoid, retry, verify | \"Retry with exponential backoff on network failures\" |\n\n### Capsule Generation (`src/capsule.ts`)\n\nThe capsule endpoint assembles a turn-sized memory packet with sections:\n\n```mermaid\ngraph TD\n    CAP[POST /v1/capsule] --> SEC[Section Assigner]\n    SEC --> R[recent_changes<br/>Created/reinforced recently]\n    SEC --> M[must_follow<br/>Critical rules]\n    SEC --> P[procedures<br/>Procedural memories]\n    SEC --> U[user_preferences<br/>Stated or tagged preferences]\n    SEC --> RK[risks<br/>Warnings and recent failures]\n    SEC --> UN[uncertain_or_disputed<br/>Disputed or low-confidence]\n```\n\nEach section includes a `reason` field explaining why the entry was included. Recent tool failures (last 7 days) are automatically added to risks when `includeRisks` is enabled.\n\n## Audrey Guard Safety Loop\n\n```mermaid\nsequenceDiagram\n    participant Agent\n    participant Guard as Audrey Guard\n    participant Memory as Memory Store\n    participant LLM as LLM Provider\n    \n    Agent->>Guard: tool + action\n    Guard->>Memory: recall(relevant)\n    Memory-->>Guard: context entries\n    Guard->>LLM: preflight check\n    LLM-->>Guard: decision + evidence\n    Guard-->>Agent: allow/warn/block + reasoning\n    Agent->>Guard: outcome (success/failure/wrong)\n    Guard->>Memory: record outcome\n```\n\n### Guard Modes\n\n| Mode | Behavior |\n|------|----------|\n| `allow` | Action proceeds normally |\n| `warn` | Action allowed but user notified |\n| `block` | Action prevented with evidence |\n| `caution` | Maps to `warn` display |\n\nCLI usage:\n```bash\naudrey guard --tool Bash \"npm run deploy\"\naudrey guard --hook --fail-on-warn  # For hook integration\n```\n\n### Validation Pipeline\n\nThe causal validation system (via `src/causal.ts` and `src/validate.ts`) evaluates whether stored memories actually helped:\n\n1. **Confidence scoring** uses reinforcement formula from `confidence.ts`\n2. **Evidence tracking** updates `usage_count` and `last_used_at`\n3. **Outcome classification**: `used`, `helpful`, `wrong`\n4. **Impact metrics** aggregated by memory type\n\n## Deployment Architecture\n\n```mermaid\ngraph LR\n    subgraph \"Deployment Options\"\n        NPM[npm package<br/>npx audrey]\n        DOCKER[Docker<br/>audrey-runtime]\n        COMPOSE[Docker Compose<br/>Full stack]\n        HOST[MCP Config<br/>Host-specific]\n    end\n    \n    subgraph \"Environment\"\n        ENV1[AUDREY_DATA_DIR]\n        ENV2[AUDREY_LLM_PROVIDER]\n        ENV3[AUDREY_EMBEDDING_PROVIDER]\n        ENV4[AUDREY_API_KEY]\n    end\n    \n    NPM --> ENV1\n    DOCKER --> ENV1\n    COMPOSE --> ENV1\n    HOST --> ENV2\n    HOST --> ENV3\n```\n\n### Interface Options by Agent\n\n| Agent | Integration |\n|-------|-------------|\n| Claude Code | `npx audrey install --host claude-code` + hook-config |\n| Claude Desktop | MCP config via `npx audrey mcp-config generic` |\n| Codex | MCP config via `npx audrey mcp-config codex` |\n| Cursor | MCP config |\n| Windsurf | MCP config |\n| VS Code | MCP config |\n| JetBrains | MCP config |\n| Ollama | MCP config |\n| Custom | REST API or JS/Python SDK |\n\n### REST Sidecar Security\n\n| Configuration | Bind Address | Auth Required |\n|---------------|--------------|---------------|\n| Default | `127.0.0.1:7437` | No (loopback) |\n| Production | `0.0.0.0:7437` | `AUDREY_API_KEY` required |\n| Unsafe override | Any host | `AUDREY_ALLOW_NO_AUTH=1` (not recommended) |\n\n`AUDREY_HOST` env var explicitly opts in to network exposure.\n\n## CLI Architecture\n\n```mermaid\ngraph TD\n    CLI[audrey CLI] --> PARSE[Argument Parser]\n    PARSE --> KNOWN[Known Subcommands]\n    KNOWN --> INSTALL[install]\n    KNOWN --> UNINSTALL[uninstall]\n    KNOWN --> MCP[mcp-config]\n    KNOWN --> HOOK[hook-config]\n    KNOWN --> DOCTOR[doctor]\n    KNOWN --> DEMO[demo]\n    KNOWN --> GUARD[guard]\n    KNOWN --> DREAM[dream]\n    KNOWN --> REEMBED[reembed]\n    KNOWN --> PROMOTE[promote]\n    KNOWN --> IMPACT[impact]\n    KNOWN --> UNKNOWN[Unknown/No subcommand]\n    \n    UNKNOWN --> TTY{Human TTY?}\n    TTY -->|Yes| HELP[Print help]\n    TTY -->|No| MCP_SERVER[Start MCP server]\n    \n    INSTALL --> HOST[Host-specific config]\n    HOOK --> APPLY[Apply hooks to settings]\n    PROMOTE --> WRITES[Write to project files]\n```\n\n### Key CLI Commands\n\n| Command | Purpose |\n|---------|---------|\n| `audrey doctor` | Diagnose configuration issues |\n| `audrey status` | Show runtime health |\n| `audrey demo` | Run interactive demonstration |\n| `audrey guard` | Check action against memory |\n| `audrey install` | Register Audrey with host |\n| `audrey mcp-config` | Generate MCP server configuration |\n| `audrey hook-config` | Generate agent hook configuration |\n| `audrey dream` | Trigger consolidation and decay |\n| `audrey reembed` | Re-embed all memories |\n| `audrey promote` | Write memories to project rules |\n| `audrey impact` | Show memory effectiveness report |\n\n## Configuration Environment Variables\n\n| Variable | Default | Purpose |\n|----------|---------|---------|\n| `AUDREY_DATA_DIR` | System temp | Memory storage directory |\n| `AUDREY_HOST` | `127.0.0.1` | REST sidecar bind address |\n| `AUDREY_PORT` | `7437` | REST sidecar port |\n| `AUDREY_API_KEY` | unset | Bearer token for non-loopback |\n| `AUDREY_LLM_PROVIDER` | Configured | LLM for causal/validation |\n| `AUDREY_EMBEDDING_PROVIDER` | Configured | Embedding generation |\n| `AUDREY_EMBEDDING_MODEL` | Configured | Model name for embeddings |\n| `AUDREY_EMBEDDING_DIM` | Configured | Vector dimensions |\n| `AUDREY_CONTEXT_BUDGET_CHARS` | `4000` | Capsule character budget |\n| `AUDREY_DISABLE_WARMUP` | `0` | Skip embedding warmup |\n| `AUDREY_DEBUG` | `0` | Enable MCP debug logs |\n| `AUDREY_PROFILE` | `0` | Emit per-stage timings |\n| `AUDREY_PROMOTE_ROOTS` | unset | Allowed write roots for promote |\n| `AUDREY_ENABLE_ADMIN_TOOLS` | `0` | Enable export/import/forget |\n\n## SDK Architecture\n\n### JavaScript SDK\n\nDirect TypeScript/Node import from `audrey` package:\n\n```typescript\nimport Audrey from 'audrey';\n\nconst brain = new Audrey({ \n  baseUrl: 'http://127.0.0.1:7437',\n  agent: 'support-agent'\n});\n\nawait brain.encode('Deploy failed due to OOM', { \n  source: 'direct-observation' \n});\n\nconst results = await brain.recall('deploy failure', { limit: 5 });\n```\n\n### Python SDK (`audrey-memory`)\n\n```python\nfrom audrey_memory import Audrey\n\nbrain = Audrey(\n    base_url=\"http://127.0.0.1:7437\",\n    api_key=\"secret\",\n    agent=\"support-agent\",\n)\n\nmemory_id = brain.encode(\n    \"Stripe returns HTTP 429 above 100 req/s\",\n    source=\"direct-observation\",\n    tags=[\"stripe\", \"rate-limit\"],\n)\n```\n\nAsync clients available via `AsyncAudrey` / `asyncio` support.\n\n## Release Readiness Gates\n\n```mermaid\ngraph LR\n    GATE[release:gate] --> CI[CI Workflow]\n    GATE --> PY[python:release:check]\n    GATE --> BENCH[bench:guard:*]\n    GATE --> DOCTOR[audrey doctor]\n    GATE --> DEMO[audrey demo]\n```\n\n| Check | Purpose |\n|-------|---------|\n| `npm run release:gate` | Full release readiness checklist |\n| `npm run python:release:check` | Python artifact verification |\n| `npm run bench:guard:card` | Guard benchmark suite |\n| `npm run bench:guard:validate` | Validation benchmarks |\n| `npx audrey doctor` | Runtime diagnostics |\n| `npx audrey demo` | Functional verification |\n\n## Data Flow: Encode to Recall\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant API as REST API<br/>/v1/encode\n    participant Audrey as Audrey Core\n    participant Embed as Embedding Engine\n    participant DB as SQLite + vec\n    \n    Client->>API: POST /v1/encode<br/>content, source, tags\n    API->>Audrey: encode(content, options)\n    Audrey->>Embed: generateEmbedding(content)\n    Embed-->>Audrey: vector[1536]\n    Audrey->>DB: INSERT memory + vector\n    DB-->>Audrey: memory_id\n    Audrey-->>API: { id, confidence, ... }\n    API-->>Client: { id, ... }\n```\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant API as REST API<br/>/v1/recall\n    participant Audrey as Audrey Core\n    participant Embed as Embedding Engine\n    participant DB as SQLite + vec\n    participant Causal as Causal Validator\n    \n    Client->>API: POST /v1/recall<br/>query, limit, scope\n    API->>Audrey: recall(query, options)\n    Audrey->>Embed: generateEmbedding(query)\n    Embed-->>Audrey: query_vector\n    Audrey->>DB: hybrid search<br/>vector_similarity + FTS\n    DB-->>Audrey: [entries]\n    Audrey->>Causal: score(entries)\n    Causal-->>Audrey: [scored_entries]\n    Audrey-->>API: { results, ... }\n    API-->>Client: { results, ... }\n```\n\n## Key Architectural Decisions\n\n| Decision | Rationale |\n|----------|----------|\n| Local-only storage | Eliminates dependency on external services; ensures data isolation |\n| SQLite + sqlite-vec | Proven reliability, no separate vector DB required |\n| WAL mode without advisory lock | Performance for single-process; isolation required for multi-agent |\n| Separate `AUDREY_DATA_DIR` per tenant | Hard isolation boundary; prevents cross-tenant contamination |\n| REST sidecar defaulting to loopback | Security by default; non-loopback requires explicit opt-in |\n| Embedding warmup at boot | Eliminates cold-start penalty (~18.7x improvement) |\n| Closed-loop validation | Closed feedback loop lifts autopilot ALIVE dimension |\n\n---\n\n<a id='page-memory-model'></a>\n\n## Memory Model\n\n### 相关页面\n\n相关主题：[System Architecture](#page-system-architecture), [Core Memory Operations](#page-memory-operations), [Preflight and Reflexes](#page-reflexes-preflight)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/consolidate.ts](https://github.com/Evilander/Audrey/blob/main/src/consolidate.ts)\n- [src/decay.ts](https://github.com/Evilander/Audrey/blob/main/src/decay.ts)\n- [src/interference.ts](https://github.com/Evilander/Audrey/blob/main/src/interference.ts)\n- [src/affect.ts](https://github.com/Evilander/Audrey/blob/main/src/affect.ts)\n- [src/confidence.ts](https://github.com/Evilander/Audrey/blob/main/src/confidence.ts)\n- [src/causal.ts](https://github.com/Evilander/Audrey/blob/main/src/causal.ts)\n</details>\n\n# Memory Model\n\nAudrey's Memory Model is a cognitive-inspired system that provides AI agents with persistent, evolving memory capabilities. Unlike simple vector databases, it implements a multi-layered memory architecture that mirrors human memory structures—episodic, semantic, and procedural—while incorporating affect, salience, and decay mechanisms to ensure memories remain relevant and actionable.\n\n## Architecture Overview\n\nThe Memory Model consists of several interconnected subsystems that work together to store, retrieve, consolidate, and forget information over time.\n\n```mermaid\ngraph TD\n    A[User/Agent Input] --> B[Episodic Memory]\n    B --> C[Consolidation Process]\n    C --> D[Semantic Memory]\n    C --> E[Procedural Memory]\n    D --> F[Confidence Scoring]\n    E --> F\n    B --> G[Affect Module]\n    F --> G\n    G --> H[Salience Calculation]\n    H --> I[Recall Ranking]\n    I --> J[Preflight Check]\n    J --> K[Guard Decision]\n    L[Interference] -.->F\n    L -.->I\n    M[Decay Engine] -.->D\n    M -.->E\n```\n\n资料来源：[README.md](https://github.com/Evilander/Audrey/blob/main/README.md)\n\n## Memory Types\n\nAudrey distinguishes between three primary memory types, each serving a distinct role in agent cognition.\n\n### Episodic Memory\n\nEpisodic memory stores specific observations, tool results, preferences, and session facts. These are the raw recordings of events and interactions that agents experience directly.\n\n| Property | Description |\n|----------|-------------|\n| `memory_type` | `episode` |\n| `source` | `direct-observation`, `told-by-user`, `retrieved` |\n| `confidence` | Initial high confidence that decays over time |\n| `retrieval_count` | Number of times this memory was recalled |\n\n资料来源：[src/capsule.ts](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n\n### Semantic Memory\n\nSemantic memory represents consolidated principles extracted from repeated evidence. These memories encode general knowledge and learned rules that persist beyond specific sessions.\n\n| Property | Description |\n|----------|-------------|\n| `memory_type` | `semantic` |\n| `confidence` | Derived from supporting episode frequency |\n| `supporting_count` | Number of episodes supporting this principle |\n| `challenge_count` | Number of contradictory episodes |\n\n资料来源：[src/causal.ts](https://github.com/Evilander/Audrey/blob/main/src/causal.ts)\n\n### Procedural Memory\n\nProcedural memory stores remembered ways to act, avoid, retry, or verify. These encode action patterns and procedures that agents have learned through experience.\n\n| Property | Description |\n|----------|-------------|\n| `memory_type` | `procedural` |\n| `tags` | `procedure`, `retry`, `avoid`, `verify` |\n| `confidence` | Reinforced by successful outcomes |\n\n资料来源：[src/capsule.ts](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n\n## Confidence System\n\nThe confidence system is the foundational mechanism that determines memory reliability and recall priority. It incorporates multiple signals including recency, reinforcement, and affect.\n\n### Confidence Calculation\n\n```mermaid\ngraph LR\n    A[Base Confidence] --> B[Recency Decay]\n    B --> C[Reinforcement Boost]\n    C --> D[Affect Adjustment]\n    D --> E[Interference Penalty]\n    E --> F[Final Confidence]\n```\n\n资料来源：[src/confidence.ts](https://github.com/Evilander/Audrey/blob/main/src/confidence.ts)\n\n### Recency Decay\n\nMemory confidence decreases over time through a half-life decay mechanism. Memories become less authoritative unless reinforced through retrieval or validation.\n\n```typescript\n// From src/confidence.ts\nrecencyDecay(halfLifeDays: number, createdAt: Date): number\n```\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `halfLifeDays` | `number` | Days until confidence halves |\n| `createdAt` | `Date` | Memory creation timestamp |\n\nThe decay function throws `RangeError` when `halfLifeDays <= 0` to prevent NaN or Infinity results.\n\n资料来源：[src/confidence.ts](https://github.com/Evilander/Audrey/blob/main/src/confidence.ts)\n\n### Reinforcement Formula\n\nValidation outcomes reinforce or diminish memory confidence through the feedback loop:\n\n| Outcome | Effect |\n|---------|--------|\n| `helpful` | Increases salience, bumps `retrieval_count` for semantic/procedural |\n| `wrong` | Decreases salience, bumps `challenge_count` for semantic |\n| `used` | Neutral signal with smaller salience delta |\n\nThe math reuses the existing reinforcement formula from `confidence.ts`.\n\n资料来源：[CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n## Consolidation System\n\nConsolidation transforms episodic memories into semantic and procedural knowledge through periodic processing, often called \"dream\" mode.\n\n### Consolidation Workflow\n\n```mermaid\ngraph TD\n    A[Nightly Dream Process] --> B[Identify Repeated Episodes]\n    B --> C[Extract Common Patterns]\n    C --> D[Generate Semantic Principles]\n    C --> E[Extract Procedures]\n    D --> F[Create New Semantic Memory]\n    E --> G[Create/Update Procedural Memory]\n    F --> H[Link Supporting Episodes]\n    G --> H\n```\n\n资料来源：[README.md](https://github.com/Evilander/Audrey/blob/main/README.md)\n\n### Consolidation Implementation\n\nThe consolidation process runs through `memory_dream` and is scheduled to ensure that consolidation and decay remain current.\n\n```typescript\n// From src/consolidate.ts - conceptual interface\nasync function consolidate(audrey: Audrey, options?: ConsolidateOptions): Promise<ConsolidationResult>\n```\n\nConsolidation moves SELECTs inside the surrounding transaction to prevent concurrent writers from slipping rows in or out between read and write.\n\n资料来源：[CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n## Decay Engine\n\nThe decay engine implements forgetting curves that reduce memory authority over time, ensuring stale information doesn't dominate recall.\n\n### Decay Mechanism\n\n```mermaid\ngraph LR\n    A[Time Passes] --> B{Still Being Used?}\n    B -->|Yes| C[Decay Paused]\n    B -->|No| D[Gradual Decay]\n    D --> E[Confidence Decreases]\n    E --> F[Memory Becomes Less Authoritative]\n```\n\n资料来源：[src/decay.ts](https://github.com/Evilander/Audrey/blob/main/src/decay.ts)\n\n### Decay Parameters\n\n| Parameter | Default | Purpose |\n|-----------|---------|---------|\n| `halfLifeDays` | Configurable | Base decay rate |\n| `minConfidence` | 0.1 | Floor value |\n| `decayEnabled` | true | Global on/off |\n\nDecay applies to semantic and procedural memories differently, with semantic memories decaying faster unless reinforced.\n\n资料来源：[src/decay.ts](https://github.com/Evilander/Audrey/blob/main/src/decay.ts)\n\n## Affect and Salience\n\nAffect (emotional weight and importance) influences salience, determining which memories demand attention and which fade into background knowledge.\n\n### Affect Module\n\n```mermaid\ngraph TD\n    A[Memory Event] --> B[Detect Emotional Signals]\n    B --> C[Calculate Valence]\n    B --> D[Calculate Arousal]\n    C --> E[Determine Mood State]\n    D --> E\n    E --> F[Affect Boost/Penalty]\n    F --> G[Effective Salience]\n```\n\n资料来源：[src/affect.ts](https://github.com/Evilander/Audrey/blob/main/src/affect.ts)\n\n### Salience Calculation\n\nEffective salience is clamped to the range `[0, 1]` to prevent unbounded values from extreme arousal boosts. The formula considers:\n\n- Memory type (episodic, semantic, procedural)\n- Confidence level\n- Recency\n- Emotional valence and arousal\n\n```typescript\n// From src/affect.ts\neffectiveSalience(baseSalience: number, arousalBoost: number): number\n```\n\nThe `timeDeltaDays` function no longer propagates NaN from invalid `created_at` timestamps.\n\n资料来源：[src/affect.ts](https://github.com/Evilander/Audrey/blob/main/src/affect.ts)\n\n## Interference Handling\n\nInterference prevents conflicting or competing memories from silently overwriting each other, maintaining an accurate picture of contradictory knowledge.\n\n### Interference Types\n\n```mermaid\ngraph TD\n    A[New Memory] --> B{Conflicting Memory Exists?}\n    B -->|Yes| C[Track Contradiction]\n    B -->|No| D[Normal Storage]\n    C --> E[Disputed State]\n    E --> F[Monitor Both]\n    F --> G[Resolution Through Validation]\n```\n\n资料来源：[src/interference.ts](https://github.com/Evilander/Audrey/blob/main/src/interference.ts)\n\n### Memory States for Contradictions\n\n| State | Description |\n|-------|-------------|\n| `active` | Default stable state |\n| `disputed` | Competing claims detected |\n| `context_dependent` | Truth depends on context |\n| `superseded` | Older knowledge replaced |\n\nWhen memories have contradictory content, both are preserved with appropriate states rather than silently overwriting.\n\n资料来源：[src/capsule.ts](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n\n## Causal Inference\n\nThe causal module extracts cause-effect relationships from episodic memory patterns, enabling agents to understand why certain actions lead to certain outcomes.\n\n### Causal Analysis\n\n```typescript\n// From src/causal.ts - conceptual interface\nasync function analyzeCausalLinks(episodes: Episode[]): Promise<CausalRelationship[]>\n```\n\nThe causal module validates LLM response shapes before reading fields and rejects non-finite confidence values.\n\n资料来源：[src/causal.ts](https://github.com/Evilander/Audrey/blob/main/src/causal.ts)\n\n### Causal Memory Properties\n\n| Property | Description |\n|----------|-------------|\n| `cause_id` | Memory that triggers outcome |\n| `effect_id` | Resulting memory |\n| `confidence` | Causal link strength |\n| `evidence_count` | Episodes supporting this link |\n\n## Validation Feedback Loop\n\nThe closed-loop feedback system enables continuous improvement of memory accuracy through agent validation.\n\n### Validation Flow\n\n```mermaid\ngraph TD\n    A[Memory Recall] --> B[Agent Uses Memory]\n    B --> C[Validation Request]\n    C --> D{Helpful?}\n    D -->|Yes| E[Reinforce: helpful]\n    D -->|No| F{Wrong?}\n    F -->|Yes| G[Diminish: wrong]\n    F -->|No| H[Mark: used]\n    E --> I[Update Salience & Stats]\n    G --> I\n    H --> I\n```\n\n资料来源：[CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n### Validation API\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `/v1/validate` | POST | Canonical validation endpoint |\n| `/v1/mark-used` | POST | Legacy alias (defaults to `outcome=used`) |\n\nThe `memory_validate` MCP tool accepts outcomes: `helpful`, `wrong`, or `used`.\n\n资料来源：[CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n## Recall and Retrieval\n\nMemory recall uses hybrid retrieval combining vector similarity and full-text search to balance precision and recall.\n\n### Retrieval Modes\n\n| Mode | Description |\n|------|-------------|\n| `hybrid` | Vector similarity + FTS (default) |\n| `vector` | FTS-bypass fast path |\n\nThe `hybrid` mode was the default since v0.22.0, replacing the removed `hybrid_strict` mode (which was a silent alias with no behavioral difference).\n\n资料来源：[CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n### Recall Factors\n\nWhen ranking results, Audrey considers:\n\n1. **Semantic similarity** - Vector distance from query\n2. **Recency** - Time since creation or last retrieval\n3. **Confidence** - Current confidence score\n4. **Salience** - Effective importance (affect-adjusted)\n5. **Agent relevance** - Scope and ownership\n\n## Tool-Trace Learning\n\nAudrey learns from tool execution traces, converting tool results into memory events that inform future actions.\n\n### Tool-Trace Memory Cycle\n\n```mermaid\ngraph TD\n    A[Tool Execution] --> B[Capture Tool Trace]\n    B --> C[Extract Results & Errors]\n    C --> D{Successful?}\n    D -->|Yes| E[Encode Success Pattern]\n    D -->|No| F[Encode Failure Pattern]\n    E --> G[Episodic Memory]\n    F --> G\n    G --> H[Consolidation]\n    H --> I[Procedural Memory]\n```\n\nThe `memory_preflight` function checks prior failures, risks, rules, and relevant procedures before an action executes.\n\n资料来源：[README.md](https://github.com/Evilander/Audrey/blob/main/README.md)\n\n## Memory Capsule\n\nThe Memory Capsule provides a turn-sized memory packet containing categorized sections relevant to the current context.\n\n### Capsule Sections\n\n| Section | Content |\n|---------|---------|\n| `must_follow` | Trusted rules and critical constraints |\n| `risks` | Identified dangers and warnings |\n| `procedures` | Known action procedures |\n| `user_preferences` | Stated and inferred preferences |\n| `uncertain_or_disputed` | Contested or low-confidence knowledge |\n| `recent_changes` | Freshly updated memories |\n| `project_facts` | Default for semantic/episodic |\n\n资料来源：[src/capsule.ts](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n\n### Capsule Generation\n\nCapsule sections are determined by memory type, tags, source trust level, state, confidence, and recency:\n\n```typescript\n// From src/capsule.ts\ndetermineSections(\n  entry: MemoryEntry,\n  result: RecallResult,\n  tags: string[],\n  recentWindowMs: number\n): Array<keyof MemoryCapsule['sections']>\n```\n\nTrusted sources include `direct-observation` and `told-by-user`; these can populate `must_follow` sections.\n\n资料来源：[src/capsule.ts](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n\n## Guard Integration\n\nThe Memory Guard uses the Memory Model to enforce pre-action checks, returning `allow`, `warn`, or `block` decisions with evidence.\n\n### Guard Decision Flow\n\n```mermaid\ngraph TD\n    A[Action Request] --> B[Preflight Check]\n    B --> C[Recall Relevant Memory]\n    C --> D[Apply Reflexes]\n    D --> E{Blocking Reflex?}\n    E -->|Yes| F[BLOCK]\n    E -->|No| G{Warning Reflex?}\n    G -->|Yes| H[ WARN]\n    G -->|No| I[ALLOW]\n```\n\nThe Guard decision reuses existing preflight and reflex machinery without performing two independent recall passes.\n\n资料来源：[CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n## Summary\n\nAudrey's Memory Model provides a comprehensive cognitive architecture for AI agents:\n\n- **Multi-type storage** with episodic, semantic, and procedural memories\n- **Dynamic confidence** that evolves through use and validation\n- **Consolidation** that transforms experience into knowledge\n- **Decay** that prevents stale information from dominating\n- **Affect** that weights memories by emotional importance\n- **Interference tracking** that maintains truth in the face of contradictions\n- **Causal inference** that extracts cause-effect relationships\n- **Closed-loop validation** that continuously improves accuracy\n\nThis architecture ensures agents remember what matters, forget what doesn't, and maintain coherent, actionable knowledge across sessions.\n\n---\n\n<a id='page-audrey-guard'></a>\n\n## Audrey Guard\n\n### 相关页面\n\n相关主题：[Core Memory Operations](#page-memory-operations), [Preflight and Reflexes](#page-reflexes-preflight)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/preflight.ts](https://github.com/Evilander/Audrey/blob/main/src/preflight.ts)\n- [src/feedback.ts](https://github.com/Evilander/Audrey/blob/main/src/feedback.ts)\n- [src/events.ts](https://github.com/Evilander/Audrey/blob/main/src/events.ts)\n- [src/action-key.ts](https://github.com/Evilander/Audrey/blob/main/src/action-key.ts)\n- [src/redact.ts](https://github.com/Evilander/Audrey/blob/main/src/redact.ts)\n- [src/tool-trace.ts](https://github.com/Evilander/Audrey/blob/main/src/tool-trace.ts)\n</details>\n\n# Audrey Guard\n\n## Overview\n\nAudrey Guard is the headline memory loop in the Audrey system—a **memory-before-action** enforcement mechanism that checks AI agents' intended operations against accumulated memory before execution. It serves as a firewall layer that can `allow`, `warn`, or `block` tool invocations based on historical evidence, prior failures, project rules, and risk patterns.\n\nThe Guard operates by retrieving relevant memories through semantic recall, evaluating them against the proposed action, and returning a structured decision with supporting evidence. This enables agents to avoid repeating past mistakes, respect project-specific rules, and make informed decisions grounded in durable context.\n\n**资料来源:** [README.md](https://github.com/Evilander/Audrey/blob/main/README.md)\n\n## Purpose and Scope\n\nAudrey Guard addresses a fundamental problem: **agents forget the exact mistakes they made yesterday**. They repeat broken commands, lose project-specific rules, miss contradictions, and treat every new session like a cold start.\n\nGuard's scope encompasses:\n\n| Concern | Description |\n|---------|-------------|\n| **Failure Prevention** | Block or warn on repeated failures identified through `memory_recall` |\n| **Risk Awareness** | Surface prior failures, risks, and warnings as preflight evidence |\n| **Rule Enforcement** | Check must-follow rules and procedures before action |\n| **Evidence Generation** | Return structured decisions with provenance metadata |\n| **Closed-Loop Validation** | Validate whether the memory helped after action execution |\n\n**资料来源:** [README.md](https://github.com/Evilander/Audrey/blob/main/README.md)\n\n## Architecture\n\n### High-Level Components\n\n```mermaid\ngraph TD\n    A[Agent Tool Call] --> B[Audrey Guard]\n    B --> C[memory_preflight]\n    C --> D[memory_recall]\n    D --> E[SQLite Store<br/>Episodic + Semantic + Procedural]\n    C --> F[Rule Evaluation]\n    F --> G[Reflex Pattern Matching]\n    C --> H[Decision Engine]\n    H --> I[block<br/>warn<br/>allow]\n    I --> J[Evidence Capsule]\n    J --> K[Agent Action Execution]\n    K --> L[memory_validate]\n    L --> M[Outcome: helpful<br/>used<br/>wrong]\n    M --> E\n```\n\n### Guard Decision Flow\n\nThe Guard evaluates incoming tool actions through a multi-stage pipeline:\n\n1. **Action Canonicalization** - Normalize the tool name and action string\n2. **Semantic Recall** - Query memory store for relevant past experiences\n3. **Risk Assessment** - Evaluate prior failures, warnings, and risks\n4. **Rule Matching** - Check against must-follow rules and procedures\n5. **Decision Synthesis** - Combine signals into block/warn/allow verdict\n6. **Evidence Packaging** - Return decision with provenance and references\n\n**资料来源:** [src/reflexes.ts](https://github.com/Evilander/Audrey/blob/main/src/reflexes.ts)\n\n## CLI Interface\n\n### Command Syntax\n\n```bash\naudrey guard --tool <tool_name> \"<action_command>\" [options]\n```\n\n### Core Options\n\n| Option | Description | Default |\n|--------|-------------|---------|\n| `--tool <name>` | The tool category (e.g., `Bash`, `Write`, `Edit`) | Required |\n| `<action>` | The specific action string to evaluate | Required |\n| `--cwd <path>` | Working directory for context | Current directory |\n| `--session-id <id>` | Session identifier for event correlation | Auto-generated |\n| `--hook` | Run in hook mode (for agent integration) | `false` |\n| `--fail-on-warn` | Treat warnings as errors (exit code non-zero) | `false` |\n| `--strict` | Enable strict preflight evaluation | `false` |\n| `--json` | Output results as JSON | `false` |\n| `--explain` | Include detailed explanation in output | `false` |\n| `--include-capsule` | Embed full memory capsule in response | `false` |\n\n**资料来源:** [mcp-server/index.ts](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n\n### Example Usage\n\n```bash\n# Block a repeated failed deploy\naudrey guard --tool Bash \"npm run deploy\"\n\n# Warn on risky file operations\naudrey guard --tool Write --strict \"database.sql\"\n\n# Hook mode for Claude Code integration\naudrey guard --tool Bash --hook \"rm -rf node_modules\"\n```\n\n## SDK Integration\n\n### Sync Client\n\n```typescript\nimport Audrey from 'audrey-memory';\n\nconst brain = new Audrey({\n  base_url: 'http://127.0.0.1:7437',\n  agent: 'support-agent',\n});\n\nconst decision = await brain.beforeAction({\n  tool: 'Bash',\n  action: 'npm run deploy',\n});\n\nconsole.log(decision.decision); // 'block' | 'warn' | 'allow'\nconsole.log(decision.evidence); // Array of MemoryEvidence\nbrain.close();\n```\n\n### Preflight Options\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `tool` | `string` | Tool category being evaluated |\n| `action` | `string` | Action string to preflight |\n| `sessionId` | `string` | Correlation ID for event tracking |\n| `mode` | `'standard' \\| 'strict'` | Evaluation strictness |\n| `includeCapsule` | `boolean` | Include full memory capsule |\n| `failureWindowHours` | `number` | Hours to look back for failures |\n| `recentChangeWindowHours` | `number` | Hours for recent-change rules |\n\n**资料来源:** [src/routes.ts](https://github.com/Evilander/Audrey/blob/main/src/routes.ts)\n\n## Decision Outcomes\n\n### Verdict Types\n\n| Decision | Description | Agent Behavior |\n|----------|-------------|----------------|\n| `block` | Action is prohibited based on memory | Must not execute |\n| `warn` | Action has risk indicators | Should pause and confirm |\n| `allow` | No memory conflicts detected | May proceed |\n\n### Decision Display Mapping\n\n```typescript\nfunction guardDisplayDecision(result: GuardCliResult): 'allow' | 'warn' | 'block' {\n  if (result.decision === 'block') return 'block';\n  if (result.decision === 'caution') return 'warn';\n  return 'allow';\n}\n```\n\n**资料来源:** [mcp-server/index.ts](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n\n## Memory Preflight\n\nThe `memory_preflight` function checks prior failures, risks, rules, and relevant procedures before an action executes. It builds a structured preflight report containing:\n\n### Capsule Sections\n\n| Section | Content Source | Trigger Condition |\n|---------|----------------|-------------------|\n| `recent_changes` | Memories within recent-change window | Created or reinforced recently |\n| `must_follow` | Must-follow rules | Tagged as must-follow |\n| `procedures` | Procedural memories + procedures | Matching query or tagged |\n| `user_preferences` | User-stated preferences | User-told or tagged |\n| `risks` | Risk-tagged memories + recent failures | Tagged risk or 7-day failures |\n| `uncertain_or_disputed` | Low-confidence or disputed memories | Low confidence or disputed state |\n\n**资料来源:** [src/capsule.ts](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n\n## Reflex System\n\nMemory reflexes convert remembered evidence into trigger-response guidance that agents can follow.\n\n### Reflex Response Types\n\n| Type | Description |\n|------|-------------|\n| `block` | Strict prohibition based on evidence |\n| `warn` | Caution signal with context |\n| `guide` | Recommended action or approach |\n\n### Reflex Report Generation\n\n```typescript\nfunction summarizeReflexes(decision: PreflightDecision, reflexes: MemoryReflex[]): string {\n  const blocks = reflexes.filter(r => r.response_type === 'block').length;\n  const warnings = reflexes.filter(r => r.response_type === 'warn').length;\n  const guides = reflexes.filter(r => r.response_type === 'guide').length;\n  // Returns human-readable summary\n}\n```\n\n**资料来源:** [src/reflexes.ts](https://github.com/Evilander/Audrey/blob/main/src/reflexes.ts)\n\n## Validation Loop\n\nAfter action execution, agents validate whether the memory helped:\n\n### Outcome Types\n\n| Outcome | Meaning | Effect |\n|---------|---------|--------|\n| `helpful` | Memory was correct and beneficial | Increases salience |\n| `used` | Memory was referenced | Updates usage metrics |\n| `wrong` | Memory was incorrect | Triggers decay or dispute |\n\n### Validation Endpoint\n\n```\nPOST /v1/event\n```\n\n```json\n{\n  \"outcome\": \"helpful\",\n  \"receipt_id\": \"receipt-from-preflight\",\n  \"evidence_feedback\": {\n    \"evidence-id-1\": \"used\",\n    \"evidence-id-2\": \"helpful\"\n  }\n}\n```\n\n**资料来源:** [src/routes.ts](https://github.com/Evilander/Audrey/blob/main/src/routes.ts)\n\n## Failure Decay\n\nStarting from version 1.0.1, Audrey Guard implements **failure decay** to prevent stale blocks:\n\n| Configuration | Default | Behavior |\n|---------------|---------|----------|\n| `failureDecayDays` | `7` | Same-action failures older than window treated as stale |\n\nTo restore pre-1.0.1 blocking behavior (permanent blocks):\n\n```typescript\nconst controller = new MemoryController({\n  failureDecayDays: 0,\n});\n```\n\n**资料来源:** [CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n## Security Considerations\n\n### HTTP API Security\n\n- Default bind address changed from `0.0.0.0` to `127.0.0.1`\n- Refuses to start on non-loopback without `AUDREY_API_KEY` or `AUDREY_ALLOW_NO_AUTH=1`\n- API key comparison uses `crypto.timingSafeEqual` to prevent timing attacks\n- `/v1/recall` and `/v1/capsule` no longer body-spread caller options\n\n**资料来源:** [CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n### Hook Configuration Safety\n\nThe `audrey promote --yes` command refuses to write `.claude/rules/*.md` outside `process.cwd()` unless the target path is in `AUDREY_PROMOTE_ROOTS`. This prevents prompt-injection attacks via malicious MCP callers.\n\n## Tool Trace Handling\n\nTool traces are recorded through PostToolUse hooks with redaction applied:\n\n1. **Redaction** - Sensitive fields (API keys, tokens, credentials) are masked\n2. **Action Key Generation** - Deterministic ID for trace correlation\n3. **Event Recording** - Tool inputs/outputs stored with session context\n\n**资料来源:** [mcp-server/index.ts](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n\n## Demo Scenario: Repeated Failure\n\nThe repeated-failure demo demonstrates Guard's blocking behavior:\n\n```bash\nnpx audrey demo --scenario repeated-failure\n```\n\nThis no-key, no-network demo:\n1. Creates a temporary memory store\n2. Records a failed deploy with the fix\n3. Teaches Audrey the failure pattern\n4. Shows Guard blocking the repeated attempt with evidence\n\n**资料来源:** [README.md](https://github.com/Evilander/Audrey/blob/main/README.md)\n\n## See Also\n\n- [Memory Recall](memory-recall) - Semantic retrieval system\n- [Memory Reflexes](reflexes) - Trigger-response guidance\n- [Impact Reporting](impact) - Memory effectiveness metrics\n- [Audrey Doctor](doctor) - Runtime health verification\n\n---\n\n<a id='page-memory-operations'></a>\n\n## Core Memory Operations\n\n### 相关页面\n\n相关主题：[Memory Model](#page-memory-model), [Audrey Guard](#page-audrey-guard), [Preflight and Reflexes](#page-reflexes-preflight), [Data Storage](#page-data-storage)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/encode.ts](https://github.com/Evilander/Audrey/blob/main/src/encode.ts)\n- [src/recall.ts](https://github.com/Evilander/Audrey/blob/main/src/recall.ts)\n- [src/hybrid-recall.ts](https://github.com/Evilander/Audrey/blob/main/src/hybrid-recall.ts)\n- [src/fts.ts](https://github.com/Evilander/Audrey/blob/main/src/fts.ts)\n- [src/impact.ts](https://github.com/Evilander/Audrey/blob/main/src/impact.ts)\n- [src/capsule.ts](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n</details>\n\n# Core Memory Operations\n\nThis page documents the fundamental memory operations in Audrey: encoding, recall, hybrid retrieval, capsule generation, and impact tracking. Together, these operations form the core pipeline that enables agents to store, retrieve, and learn from persistent memory across sessions.\n\n## Overview\n\nAudrey's Core Memory Operations handle the complete lifecycle of memory within the system. The operations are designed around a local-first, SQLite-backed architecture that provides semantic search capabilities without requiring external vector databases or hosted services.\n\n```mermaid\ngraph LR\n    A[Encode] -->|store| B[(SQLite)]\n    B -->|recall| C[Recall]\n    C -->|hybrid| D[Hybrid Search]\n    D -->|compose| E[Capsule]\n    E -->|track| F[Impact]\n    F -->|reinforce| A\n```\n\nThe primary design goals are:\n\n- **Durability**: All memories persist in local SQLite storage\n- **Semantic Search**: Vector embeddings enable similarity-based recall\n- **Hybrid Retrieval**: Combines vector and keyword search for accuracy\n- **Feedback Loop**: Impact tracking enables continuous memory reinforcement\n\n## Memory Types\n\nAudrey distinguishes between three primary memory types that influence retrieval behavior and storage strategy.\n\n| Memory Type | Description | Typical Content |\n|-------------|-------------|------------------|\n| `episodic` | Specific observations and session facts | Tool results, error messages, user feedback |\n| `semantic` | Consolidated principles extracted from evidence | Learned rules, best practices, project conventions |\n| `procedural` | Remembered ways to act, avoid, or verify | Deployment procedures, recovery steps, verification commands |\n\nEach memory type has distinct promotion criteria. Procedural memories can be promoted to rules with lower evidence thresholds, while semantic memories require higher confidence and evidence counts before promotion.\n\n资料来源：[src/recall.ts:15-17](https://github.com/Evilander/Audrey/blob/main/src/recall.ts)\n\n## Memory Encoding\n\nThe encoding operation transforms raw observations into persistent memory entries. When encoding, Audrey generates embeddings, assigns salience scores, and stores metadata that enables future retrieval.\n\n### Encode Process Flow\n\n```mermaid\ngraph TD\n    A[Input: Raw Text] --> B[Generate Embedding]\n    B --> C[Calculate Salience]\n    C --> D[Assign Memory Type]\n    D --> E[Tag Analysis]\n    E --> F[Store in SQLite]\n    F --> G[Update Vector Index]\n```\n\n### Encode Options\n\nThe encode operation accepts several configuration parameters:\n\n| Parameter | Type | Default | Purpose |\n|-----------|------|---------|---------|\n| `source` | `string` | `'direct-observation'` | Origin of the memory |\n| `memory_type` | `string` | `'episodic'` | Classification of memory content |\n| `tags` | `string[]` | `[]` | Categorical labels for filtering |\n| `wait_for_consolidation` | `boolean` | `false` | Opt-in read-after-write semantics |\n\n资料来源：[src/encode.ts](https://github.com/Evilander/Audrey/blob/main/src/encode.ts)\n\n### Source Types\n\nMemory sources indicate provenance and affect how memories are treated during recall:\n\n| Source | Trust Level | Description |\n|--------|-------------|-------------|\n| `direct-observation` | High | Agent's own observations from tool execution |\n| `told-by-user` | High | Explicit user-provided information |\n| `inferred` | Medium | AI-inferred conclusions |\n| `external` | Low | Information from external systems |\n\nTrusted sources (direct-observation, told-by-user) can populate must-follow sections in capsules, while untrusted sources are flagged as uncertain or disputed.\n\n资料来源：[src/capsule.ts:18-20](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n\n## Memory Recall\n\nRecall is the primary mechanism for retrieving relevant memories based on semantic similarity and keyword matching. The recall operation searches across all memory types using configurable retrieval strategies.\n\n### Retrieval Modes\n\nAudrey supports three retrieval modes that determine how search results are computed:\n\n| Mode | Description | Use Case |\n|------|-------------|----------|\n| `hybrid` | Combines vector similarity with FTS keyword matching (default) | Balanced accuracy for general queries |\n| `vector` | Pure semantic similarity using embeddings | When keywords are ambiguous |\n| `keyword` | Full-text search only, bypasses vector index | Fast, keyword-exact matching |\n\n资料来源：[src/recall.ts:12-14](https://github.com/Evilander/Audrey/blob/main/src/recall.ts)\n\n### Recall Architecture\n\n```mermaid\ngraph TD\n    A[Query Input] --> B{Mode Check}\n    B -->|hybrid| C[Vector Pass]\n    B -->|hybrid| D[Keyword Pass]\n    B -->|vector| E[Vector Pass Only]\n    B -->|keyword| F[Keyword Pass Only]\n    C --> G[Merge & Score]\n    D --> G\n    G --> H[Filter by Confidence]\n    H --> I[Apply Filters]\n    I --> J[Return Results]\n```\n\n### Recall Options\n\nThe recall operation accepts a comprehensive set of filtering and result-shaping options:\n\n| Parameter | Type | Default | Purpose |\n|-----------|------|---------|---------|\n| `minConfidence` | `number` | `0` | Minimum confidence threshold (0-1) |\n| `types` | `MemoryType[]` | `['episodic', 'semantic', 'procedural']` | Memory types to search |\n| `limit` | `number` | `10` | Maximum results to return |\n| `includeProvenance` | `boolean` | `false` | Include source metadata |\n| `includeDormant` | `boolean` | `false` | Include decayed/inactive memories |\n| `tags` | `string[]` | `undefined` | Filter by tags |\n| `sources` | `string[]` | `undefined` | Filter by source type |\n| `after` | `Date` | `undefined` | Filter memories created after date |\n| `before` | `Date` | `undefined` | Filter memories created before date |\n| `includePrivate` | `boolean` | `false` | Include agent-private memories |\n| `retrieval` | `string` | `'hybrid'` | Retrieval mode selection |\n| `scope` | `'agent' \\| 'shared'` | `'agent'` | Memory scope filter |\n\n资料来源：[src/recall.ts:5-22](https://github.com/Evilander/Audrey/blob/main/src/recall.ts)\n\n### RecallFilters Structure\n\n```typescript\ninterface RecallFilters {\n  tags?: string[];\n  sources?: string[];\n  after?: Date;\n  before?: Date;\n  agent?: string;  // Filtered by scope when scope === 'agent'\n}\n```\n\nFilters are combined with AND logic—memories must match all specified filters to be included in results.\n\n### Agent and Scope Filtering\n\nThe `scope` parameter determines which memories are accessible:\n\n- `agent` (default): Only memories associated with the requesting agent\n- `shared`: Memories marked as shared across agents\n\nWhen `scope` is `'agent'`, the `agent` filter is automatically set to the requesting agent's identity. This ensures memory isolation between different agents.\n\n## Hybrid Search\n\nHybrid search combines vector similarity and full-text search to achieve more accurate recall results than either method alone.\n\n### Hybrid Recall Pipeline\n\n```mermaid\ngraph LR\n    A[Query] --> B[Embedding Model]\n    A --> C[FTS Index]\n    B --> D[Vector Scores]\n    C --> E[Keyword Scores]\n    D --> F[Score Normalization]\n    E --> F\n    F --> G[Weighted Merge]\n    G --> H[Ranked Results]\n```\n\n### Score Merging Strategy\n\nThe hybrid approach normalizes scores from both vector and keyword passes before merging. This ensures that memories matched by keywords are not overshadowed by high vector similarity scores, and vice versa.\n\n资料来源：[src/hybrid-recall.ts](https://github.com/Evilander/Audrey/blob/main/src/hybrid-recall.ts)\n\n### Full-Text Search Integration\n\nThe FTS module provides keyword-based search capabilities:\n\n```typescript\ninterface FTSResult {\n  memory_id: string;\n  rank: number;\n  snippet?: string;\n}\n```\n\nFTS uses SQLite's built-in FTS5 extension for fast keyword matching. The FTS index is updated synchronously during encoding to ensure keyword search reflects current memory state.\n\n资料来源：[src/fts.ts](https://github.com/Evilander/Audrey/blob/main/src/fts.ts)\n\n## Memory Capsule\n\nThe capsule is a turn-sized memory packet that organizes relevant memories into actionable sections for agent consumption. It synthesizes recall results into a structured format optimized for quick agent review.\n\n### Capsule Sections\n\n| Section | Purpose | Trigger Conditions |\n|---------|---------|-------------------|\n| `must_follow` | High-priority directives | Trusted source + must-follow tags |\n| `uncertain_or_disputed` | Flagged content requiring verification | Low confidence, disputed state, or untrusted source |\n| `risks` | Known risks and hazards | Risk-related tags |\n| `procedures` | Step-by-step instructions | Procedural memory type or procedure tags |\n| `user_preferences` | User-specific preferences | Preference tags or told-by-user source |\n| `project_facts` | Consolidated project knowledge | Semantic memories with no other section match |\n| `recent_changes` | Recently updated information | Memories within recent time window |\n\n资料来源：[src/capsule.ts:22-38](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n\n### Section Determination Logic\n\n```mermaid\ngraph TD\n    A[Memory Entry] --> B{Source Trusted?}\n    B -->|Yes| C{Has Must-Follow Tags?}\n    B -->|No| D[Uncertain/Disputed]\n    C -->|Yes| E[Must-Follow Section]\n    C -->|No| F{Has Risk Tags?}\n    D --> F\n    F -->|Yes| G[Risks Section]\n    F -->|No| H{Procedural Type?}\n    H -->|Yes| I[Procedures Section]\n    H -->|No| J{Has Preference Tags?}\n    J -->|Yes| K[User Preferences]\n    J -->|No| L{Uncertain State?}\n    L -->|Yes| M[Uncertain/Disputed]\n    L -->|No| N[Project Facts]\n```\n\n### Capsule Structure\n\n```typescript\ninterface MemoryCapsule {\n  generated_at: string;\n  sections: {\n    must_follow?: MemorySection;\n    uncertain_or_disputed?: MemorySection;\n    risks?: MemorySection;\n    procedures?: MemorySection;\n    user_preferences?: MemorySection;\n    project_facts?: MemorySection;\n    recent_changes?: MemorySection;\n  };\n}\n```\n\n### Tag-Based Section Assignment\n\nCapsule generation uses predefined tag sets to categorize memories:\n\n| Tag Set | Matching Tags |\n|---------|---------------|\n| `MUST_FOLLOW_TAGS` | Critical directives that must be followed |\n| `RISK_TAGS` | Risk-related keywords |\n| `PROCEDURE_TAGS` | Procedure-related keywords |\n| `PREFERENCE_TAGS` | User preference keywords |\n\n资料来源：[src/capsule.ts:12-15](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n\n## Impact Tracking\n\nImpact tracking closes the feedback loop by recording whether recalled memories proved useful. This enables continuous reinforcement of valuable memories and decay of misleading ones.\n\n### Outcome Types\n\n| Outcome | Description | Effect on Memory |\n|---------|-------------|------------------|\n| `helpful` | Memory drove a correct action | Increases salience, bumps retrieval_count |\n| `wrong` | Memory was misleading | Decreases salience, bumps challenge_count |\n| `used` | Memory was referenced | Small positive salience delta |\n\n资料来源：[src/impact.ts](https://github.com/Evilander/Audrey/blob/main/src/impact.ts)\n\n### Impact Report Structure\n\n```typescript\ninterface ImpactReport {\n  generatedAt: string;\n  windowDays: number;\n  totals: {\n    episodic: number;\n    semantic: number;\n    procedural: number;\n  };\n  validatedTotal: number;\n  validatedInWindow: number;\n  byType: {\n    episodic: { validated: number; recent: number };\n    semantic: { validated: number; recent: number; challenged: number };\n    procedural: { validated: number; recent: number };\n  };\n  outcomeBreakdownInWindow: {\n    helpful: number;\n    wrong: number;\n    used: number;\n  };\n  topUsed: MemoryStat[];\n  weakest: MemoryStat[];\n  recentActivity: MemoryStat[];\n}\n```\n\n### Impact Metrics\n\nThe impact system tracks several key metrics:\n\n- **usage_count**: Number of times a memory was successfully used\n- **salience**: Computed importance score based on reinforcement history\n- **validation events**: Recorded outcomes linked to specific recall events\n- **challenge_count**: Number of times a memory was marked as wrong\n\nThis data feeds into consolidation and decay processes, ensuring that frequently useful memories remain prominent while stale or misleading memories lose authority over time.\n\n## Data Flow Summary\n\n```mermaid\ngraph LR\n    subgraph Encode\n        A1[Text Input] --> A2[Embed]\n        A2 --> A3[Salience]\n        A3 --> A4[Store]\n    end\n    \n    subgraph Recall\n        B1[Query] --> B2[Hybrid Search]\n        B2 --> B3[Score & Rank]\n        B3 --> B4[Filter]\n        B4 --> B5[Recall Results]\n    end\n    \n    subgraph Capsule\n        C1[Recall Results] --> C2[Section Analysis]\n        C2 --> C3[Tag Matching]\n        C3 --> C4[Capsule Output]\n    end\n    \n    subgraph Impact\n        D1[Agent Feedback] --> D2[Outcome Recording]\n        D2 --> D3[Reinforce/Decay]\n        D3 --> A3\n    end\n    \n    A4 --> B5\n    B5 --> C1\n    C4 --> D1\n```\n\n## Configuration Considerations\n\nWhen deploying Audrey's core memory operations, consider these configuration points:\n\n| Setting | Recommendation | Impact |\n|---------|---------------|--------|\n| `AUDREY_EMBEDDING_PROVIDER` | Pin explicitly | Determines embedding quality |\n| `AUDREY_LLM_PROVIDER` | Pin explicitly | Affects consolidation quality |\n| `AUDREY_DATA_DIR` | Separate per tenant/environment | Ensures isolation and backup simplicity |\n| Retrieval mode | Use `hybrid` for most cases | Balances precision and recall |\n| `wait_for_consolidation` | Enable for critical writes | Guarantees read-after-write consistency |\n\n## Related Operations\n\nThe core memory operations interact with several supporting systems:\n\n- **Guard**: Uses preflight checks before tool execution\n- **Reflexes**: Trigger-response patterns derived from memory\n- **Consolidation**: Extracts semantic memories from episodic evidence\n- **Decay**: Reduces authority of stale memories over time\n- **Promotion**: Converts high-value memories to Claude rules\n\n---\n\n<a id='page-reflexes-preflight'></a>\n\n## Preflight and Reflexes\n\n### 相关页面\n\n相关主题：[Audrey Guard](#page-audrey-guard), [Core Memory Operations](#page-memory-operations)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/preflight.ts](https://github.com/Evilander/Audrey/blob/main/src/preflight.ts)\n- [src/reflexes.ts](https://github.com/Evilander/Audrey/blob/main/src/reflexes.ts)\n- [src/validate.ts](https://github.com/Evilander/Audrey/blob/main/src/validate.ts)\n- [src/rules-compiler.ts](https://github.com/Evilander/Audrey/blob/main/src/rules-compiler.ts)\n- [src/capsule.ts](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n- [mcp-server/index.ts](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n</details>\n\n# Preflight and Reflexes\n\n## Overview\n\nPreflight and Reflexes form Audrey's core decision-making loop for AI agents. Before any tool action executes, Audrey performs a preflight check that consults memory to determine whether the action should be allowed, warned about, or blocked entirely.\n\nThe system operates as Audrey's \"memory firewall\"—a security and guidance layer that prevents agents from repeating mistakes, reinforces learned behaviors, and surfaces relevant context before sensitive operations. This mechanism transforms episodic and semantic memories into actionable guidance that agents can evaluate in real-time.\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[Agent Action Request] --> B[Preflight Check]\n    B --> C{Memory Recall}\n    C --> D[Episodic Memory]\n    C --> E[Semantic Memory]\n    C --> F[Procedural Memory]\n    D --> G[Memory Reflexes]\n    E --> G\n    F --> G\n    G --> H{Decision?}\n    H -->|Match Found| I[Return Reflex Result]\n    H -->|No Match| J[Allow Action]\n    I --> K{block}\n    I --> L[warn]\n    I --> M[guide]\n    K --> N[Block with Evidence]\n    L --> O[Warn with Guidance]\n    M --> P[Proceed with Hints]\n```\n\n## Memory Reflexes\n\nMemory Reflexes are the atomic decision units within the Preflight system. Each reflex contains a trigger condition, a response type, and optional guidance content.\n\n### Response Types\n\n| Response Type | Decision | Description |\n|---------------|----------|-------------|\n| `block` | `block` | Prevents the action entirely; returns blocking evidence |\n| `warn` | `caution` | Allows action but presents warning with recommendations |\n| `guide` | `allow` | Provides informational guidance without blocking |\n\n资料来源：[src/reflexes.ts:1-50](https://github.com/Evilander/Audrey/blob/main/src/reflexes.ts)\n\n### Reflex Structure\n\n```typescript\ninterface MemoryReflex {\n  response_type: 'block' | 'warn' | 'guide';\n  triggered_by: string;       // Memory tag or rule identifier\n  message: string;            // Human-readable explanation\n  recommended_action?: string; // Suggested alternative\n  memory_ids: string[];        // Source memories that triggered this reflex\n  confidence: number;         // Reflex confidence score\n}\n```\n\n## Preflight Process\n\n### Decision Flow\n\nThe preflight process evaluates incoming actions against three memory types and returns a consolidated decision:\n\n```mermaid\ngraph LR\n    A[Action + Context] --> B[Tag Extraction]\n    B --> C{Must-Follow Rules?}\n    C -->|Yes| D[BLOCK or UNCERTAIN]\n    C -->|No| E{Risk Tags?}\n    E -->|Yes| F[Add to WARN]\n    E -->|No| G{Procedures?}\n    G -->|Yes| H[Add GUIDANCE]\n    G -->|No| I{Preferences?}\n    I -->|Yes| J[Include in Capsule]\n    I -->|No| K[Default ALLOW]\n```\n\n### Decision Types\n\n| Decision | Meaning | Exit Code Behavior |\n|----------|---------|-------------------|\n| `allow` | Action proceeds normally | Continue execution |\n| `caution` | Action proceeds with warning | Log warning, continue |\n| `block` | Action is prevented | Return error, halt |\n\n资料来源：[mcp-server/index.ts:80-95](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n\n### Memory Capsule Integration\n\nPreflight builds a **Memory Capsule**—a structured context bundle that aggregates relevant memories by category. The capsule sections determine which memories appear in the agent's context window.\n\n```typescript\ninterface MemoryCapsule {\n  sections: {\n    must_follow: MemoryReflex[];        // Critical rules\n    recent_changes: MemoryReflex[];     // New learnings\n    procedures: MemoryReflex[];        // How-to guidance\n    user_preferences: MemoryReflex[];   // Stated preferences\n    risks: MemoryReflex[];              // Warnings and hazards\n    uncertain_or_disputed: MemoryReflex[]; // Low-confidence or contested\n    project_facts: MemoryReflex[];      // Relevant facts\n  };\n  triggered_by: string;\n  generated_at: string;\n}\n```\n\n资料来源：[src/capsule.ts:1-50](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n\n### Tag-Based Classification\n\nMemory reflexes are classified using tag matching against predefined tag sets:\n\n| Tag Set | Purpose | Associated Section |\n|---------|---------|---------------------|\n| `MUST_FOLLOW_TAGS` | Critical rules that must be obeyed | `must_follow` |\n| `RISK_TAGS` | Potential hazards or warnings | `risks` |\n| `PROCEDURE_TAGS` | Step-by-step guidance | `procedures` |\n| `PREFERENCE_TAGS` | User-stated preferences | `user_preferences` |\n\n资料来源：[src/capsule.ts:50-100](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n\n## Building Reflex Reports\n\n### Report Generation\n\nThe `buildReflexReport` function constructs a complete preflight report from an action:\n\n```typescript\nexport async function buildReflexReport(\n  audrey: Audrey,\n  action: string,\n  options: ReflexOptions = {},\n): Promise<MemoryReflexReport>\n```\n\n### Report Structure\n\n```typescript\ninterface MemoryReflexReport {\n  decision: 'allow' | 'caution' | 'block';\n  reflexes: MemoryReflex[];\n  capsule: MemoryCapsule;\n  summary: string;           // Human-readable summary\n  triggered_at: string;      // ISO timestamp\n  session_id?: string;      // Optional session context\n}\n```\n\n资料来源：[src/reflexes.ts:80-120](https://github.com/Evilander/Audrey/blob/main/src/reflexes.ts)\n\n### Summarization Logic\n\nThe `summarizeReflexes` function generates human-readable summaries:\n\n```typescript\nfunction summarizeReflexes(\n  decision: PreflightDecision,\n  reflexes: MemoryReflex[],\n): string {\n  const blocks = reflexes.filter(r => r.response_type === 'block').length;\n  const warnings = reflexes.filter(r => r.response_type === 'warn').length;\n  const guides = reflexes.filter(r => r.response_type === 'guide').length;\n  \n  // Returns format: \"Stop: 2 blocking, 1 warning, 3 guidance matched.\"\n  // Or: \"Slow down: ...\" or \"Proceed: ...\"\n}\n```\n\n## Validation Layer\n\nBefore reflexes are applied, the validation layer ensures response integrity:\n\n### Response Validation\n\n```typescript\n// From src/validate.ts\n// Validates LLM response shape before reading fields\n// - Rejects non-object/array conditions\n// - Only counts new evidence toward supporting_count\n// - Throws on malformed response shapes\n```\n\n资料来源：[src/validate.ts](https://github.com/Evilander/Audrey/blob/main/src/validate.ts)\n\n### Validation Behavior\n\n| Check | Invalid Condition | Behavior |\n|-------|-------------------|----------|\n| Response Shape | Non-object/array | Reject and throw |\n| Evidence Count | Missing supporting_count | Skip from count |\n| Confidence | Non-finite value | Reject in causal module |\n\n资料来源：[CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n## CLI Integration\n\n### Guard Command\n\nThe `audrey guard` command exposes preflight checks via terminal:\n\n```bash\naudrey guard --tool Bash \"npm run deploy\"\n```\n\n### Guard Options\n\n| Option | Description |\n|--------|-------------|\n| `--tool <name>` | Tool name being invoked |\n| `--action <command>` | Specific action/command |\n| `--cwd <path>` | Working directory |\n| `--session-id <id>` | Session identifier |\n| `--files <paths>` | Files affected by action |\n| `--json` | Output results as JSON |\n| `--strict` | Fail on warnings |\n| `--include-capsule` | Include full memory capsule |\n| `--explain` | Show reasoning breakdown |\n\n资料来源：[mcp-server/index.ts:40-70](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n\n### Display Mapping\n\nThe CLI maps internal decisions to display messages:\n\n```typescript\nfunction guardDisplayDecision(result: GuardCliResult): 'allow' | 'warn' | 'block' {\n  if (result.decision === 'block') return 'block';\n  if (result.decision === 'caution') return 'warn';\n  return 'allow';\n}\n```\n\n## Configuration Options\n\n### Environment Variables\n\n| Variable | Default | Purpose |\n|----------|---------|---------|\n| `AUDREY_CONTEXT_BUDGET_CHARS` | `4000` | Memory capsule character budget |\n| `AUDREY_ENABLE_ADMIN_TOOLS` | `0` | Enable export/import/forget routes |\n| `AUDREY_DEBUG` | `0` | Print MCP info logs |\n\n### Runtime Options\n\n```typescript\ninterface ReflexOptions {\n  agent?: string;                    // Agent identifier\n  sessionId?: string;               // Session context\n  includeCapsule?: boolean;          // Include full capsule\n  includePreflight?: boolean;       // Include preflight details\n  context?: Record<string, string>; // Additional context\n  mood?: MoodConfig;                // Emotional context\n}\n```\n\n## Memory Types and Section Assignment\n\n### Assignment Logic\n\n```mermaid\ngraph TD\n    A[Memory Entry] --> B{Source Trusted?}\n    B -->|Yes + Must-Follow Tags| C[must_follow section]\n    B -->|No + Must-Follow Tags| D[uncertain_or_disputed]\n    B -->|Risk Tags| E[risks section]\n    B -->|Procedural Type/Tags| F[procedures section]\n    B -->|Preference Tags| G[user_preferences section]\n    A --> H{State or Low Confidence?}\n    H -->|disputed/context_dependent/confidence<0.55| I[uncertain_or_disputed]\n    A --> J{Recent Window?}\n    J -->|Yes| K[recent_changes section]\n    J -->|No| L[Default: project_facts]\n```\n\n### Threshold Values\n\n| Condition | Threshold | Section Assignment |\n|-----------|-----------|-------------------|\n| Confidence (disputed) | < 0.55 | `uncertain_or_disputed` |\n| Recent Window | 7 days | `recent_changes` |\n| Tool Failure | 7 days | `risks` |\n\n## Data Flow Example\n\n```mermaid\nsequenceDiagram\n    participant Agent\n    participant MCP as MCP Server\n    participant Audrey\n    participant Memory\n    participant Reflex\n\n    Agent->>MCP: tool_use(Bash, \"rm -rf /\")\n    MCP->>Audrey: buildPreflight(audrey, action)\n    Audrey->>Memory: recall(action, context)\n    Memory-->>Audrey: MemoryReflex[]\n    Audrey->>Reflex: classifyAndScore(reflexes)\n    Reflex-->>Audrey: MemoryReflexReport\n    Audrey-->>MCP: PreflightDecision\n    MCP-->>Agent: block/caution/allow response\n```\n\n## Security Considerations\n\n### HTTP Endpoint Protection\n\nThe preflight system includes security hardening for HTTP access:\n\n- REST endpoints default to loopback-only binding\n- API key comparison uses `crypto.timingSafeEqual` to prevent timing attacks\n- Options like `includePrivate: true` cannot be passed via HTTP bodies\n- Non-loopback binding requires explicit `AUDREY_API_KEY`\n\n资料来源：[src/routes.ts](https://github.com/Evilander/Audrey/blob/main/src/routes.ts)\n\n### Recall Sanitization\n\nHTTP `/v1/recall` and `/v1/capsule` endpoints sanitize input through `sanitizeRecallOptions()`:\n\n```typescript\n// Allowed keys only\nconst ALLOWED_KEYS = ['limit', 'agent', 'tags', 'sources', 'after', 'before', 'context', 'mood', 'retrieval', 'scope'];\n```\n\nAny keys not in the allowlist are silently dropped before processing.\n\n## Related Components\n\n| Component | File | Role |\n|-----------|------|------|\n| Rules Compiler | `src/rules-compiler.ts` | Compiles memories into Claude rules |\n| Validation | `src/validate.ts` | Validates LLM response integrity |\n| Impact Tracking | `src/impact.ts` | Tracks reflex effectiveness over time |\n| Memory Capsule | `src/capsule.ts` | Structures context bundles |\n\n## See Also\n\n- [Memory Types and Tagging](./memory-types.md)\n- [Confidence and Decay System](./confidence.md)\n- [CLI Reference](./cli-reference.md)\n- [REST API Documentation](./api.md)\n\n---\n\n<a id='page-data-storage'></a>\n\n## Data Storage\n\n### 相关页面\n\n相关主题：[System Architecture](#page-system-architecture), [Core Memory Operations](#page-memory-operations)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/db.ts](https://github.com/Evilander/Audrey/blob/main/src/db.ts)\n- [src/hybrid-recall.ts](https://github.com/Evilander/Audrey/blob/main/src/hybrid-recall.ts)\n- [src/fts.ts](https://github.com/Evilander/Audrey/blob/main/src/fts.ts)\n- [src/embedding.ts](https://github.com/Evilander/Audrey/blob/main/src/embedding.ts)\n- [src/export.ts](https://github.com/Evilander/Audrey/blob/main/src/export.ts)\n- [src/import.ts](https://github.com/Evilander/Audrey/blob/main/src/import.ts)\n- [src/migrate.ts](https://github.com/Evilander/Audrey/blob/main/src/migrate.ts)\n</details>\n\n# Data Storage\n\n## Overview\n\nAudrey's data storage layer is built as a local-first, SQLite-backed persistence system designed for AI agent memory continuity. The storage architecture eliminates external database dependencies while providing vector similarity search capabilities through `sqlite-vec`, enabling semantic memory retrieval without cloud infrastructure.\n\nThe storage system serves as the foundation for Audrey's multi-type memory model, supporting episodic, semantic, and procedural memory with built-in confidence tracking, contradiction handling, and temporal decay mechanisms.\n\n## Storage Architecture\n\n### Core Technology Stack\n\n| Component | Technology | Purpose |\n|-----------|------------|---------|\n| Primary Database | SQLite | Structured memory storage, ACID transactions |\n| Vector Search | sqlite-vec | Semantic similarity search on embeddings |\n| Data Directory | `AUDREY_DATA_DIR` | Tenant/environment isolation boundary |\n\nThe storage backend runs entirely locally, requiring no hosted database services. Each tenant or environment should use a dedicated `AUDREY_DATA_DIR` to maintain isolation boundaries.\n\n资料来源：[README.md](https://github.com/Evilander/Audrey/blob/main/README.md)\n\n### Database Schema Design\n\nAudrey maintains three primary memory tables that correspond to its memory model:\n\n```mermaid\nerDiagram\n    MEMORIES ||--o{ VECTORS : contains\n    MEMORIES {\n        string id PK\n        string content\n        string memory_type\n        float confidence\n        float salience\n        string state\n        int evidence_count\n        int usage_count\n        timestamp created_at\n        timestamp last_used_at\n    }\n    VECTORS {\n        int rowid\n        float vector\n        text content\n    }\n```\n\n#### Memory Type Storage\n\n| Memory Type | Description | Key Attributes |\n|-------------|-------------|-----------------|\n| **episodic** | Specific observations, tool results, session facts | `source`, `tags`, `created_at` |\n| **semantic** | Consolidated principles from repeated evidence | `evidence_count`, `supporting_count`, `contradicting_count` |\n| **procedural** | Remembered procedures, actions to avoid or retry | `usage_count`, `failure_prevented`, `tags` |\n\n资料来源：[src/promote.ts](https://github.com/Evilander/Audrey/blob/main/src/promote.ts)\n\n## Memory Model Implementation\n\n### Episodic Memory Storage\n\nEpisodic memories capture specific observations and session-level facts. These entries are created during direct agent interactions and tool executions.\n\nKey storage characteristics:\n- High-volume insertion during active sessions\n- Temporal ordering via `created_at` timestamps\n- Tag-based categorization for filtered retrieval\n- Source attribution (`direct-observation`, `told-by-user`)\n\n### Semantic Memory Storage\n\nSemantic memories represent consolidated principles extracted from accumulated episodic evidence. The promotion system converts episodic memories into semantic rules when confidence thresholds are met.\n\nThe promotion criteria for semantic memories include:\n- Minimum evidence count threshold (default: 3)\n- Zero contradicting evidence\n- State must be `active`\n\n资料来源：[src/promote.ts:78-92](https://github.com/Evilander/Audrey/blob/main/src/promote.ts)\n\n### Procedural Memory Storage\n\nProcedural memories track action sequences and their outcomes. These are distinguished by usage tracking and failure prevention metrics.\n\nProcedural candidates are promoted when:\n- `evidence_count >= minEvidence`\n- `contradicting_count === 0`\n- `retrieval_count > 0` OR `failure_prevented > 0`\n\n## Confidence and Salience Tracking\n\n### Confidence Scoring\n\nConfidence scores are computed from supporting versus contradicting evidence:\n\n```\nconfidence = supporting / max(evidence, 1)\n```\n\nThe confidence value is clamped to the range `[0, 1]` to prevent invalid states. Negative salience values from malformed arousal calculations are also clamped.\n\n资料来源：[CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n### Salience System\n\nSalience represents the importance and emotional weight of memories, influencing recall priority. The `effectiveSalience` calculation factors in:\n\n- Base salience from evidence strength\n- Temporal decay over time\n- Arousal/affect resonance from recent memories\n- Validation feedback (`helpful`, `wrong`, `used` outcomes)\n\n### Validation Feedback Loop\n\nThe closed-loop validation system updates salience based on memory utility:\n\n| Outcome | Salience Effect | Counts Updated |\n|---------|-----------------|----------------|\n| `helpful` | Increases | `retrieval_count`, salience |\n| `wrong` | Decreases | `challenge_count` (semantic only) |\n| `used` | Neutral/slight | `usage_count` |\n\n资料来源：[CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n## Retrieval and Search\n\n### Hybrid Recall Architecture\n\nAudrey implements a hybrid retrieval strategy combining vector similarity with keyword matching:\n\n```mermaid\ngraph TD\n    A[Query Input] --> B[Embedding Provider]\n    B --> C[Vector Similarity Search]\n    A --> D[Full-Text Search FTS]\n    C --> E[Confidence Scoring]\n    D --> E\n    E --> F[Memory Filtering]\n    F --> G[Ranked Results]\n```\n\n#### Retrieval Modes\n\n| Mode | Behavior |\n|------|----------|\n| `hybrid` (default) | Combines vector + FTS for balanced recall |\n| `vector` | Pure semantic similarity, bypasses FTS |\n| `keyword` | Skips vector pass, uses FTS only |\n\nThe `vector` mode serves as a fast path when FTS overhead is unacceptable.\n\n资料来源：[src/recall.ts](https://github.com/Evilander/Audrey/blob/main/src/recall.ts)\n\n### Filtering Capabilities\n\nRecall operations support multiple filter dimensions:\n\n- **tags**: Array of tag values to match\n- **sources**: Array of source identifiers\n- **after/before**: Temporal bounds via ISO timestamps\n- **scope**: `shared` or `agent`-scoped memories\n- **types**: Filter by memory type (episodic/semantic/procedural)\n\n### Private Memory Isolation\n\nThe `includePrivate` flag controls access to agent-specific private memories. The HTTP API implements an allowlist-based sanitizer (`sanitizeRecallOptions()`) that prevents bypassing private-memory ACL controls through body options.\n\n资料来源：[src/routes.ts](https://github.com/Evilander/Audrey/blob/main/src/routes.ts)\n\n## Data Lifecycle\n\n### Consolidation and Decay\n\nThe `audrey dream` command triggers memory consolidation:\n\n1. Episodic memories are evaluated for principle extraction\n2. Low-confidence or conflicting memories undergo decay\n3. Stale memories lose retrieval authority over time\n4. Contradicting claims are tracked rather than silently overwritten\n\n资料来源：[README.md](https://github.com/Evilander/Audrey/blob/main/README.md)\n\n### Rollback Operations\n\nThe rollback system (`src/rollback.ts`) updates memories with verification:\n\n- Checks `.changes` to confirm affected rows\n- Aggregates real counts rather than assuming success\n- Reports failure when targeted IDs don't exist\n\n资料来源：[CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n### Reembedding\n\nWhen embedding models or dimensions change, reembedding regenerates all vector representations:\n\n- Chunks embeddings into 256-row batches\n- Labels failures by kind and row range\n- Provides clear error messages for partial failures\n\n资料来源：[CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n## Import and Export\n\n### Data Portability\n\nAudrey supports full data export and import for:\n\n- Snapshot restoration to fresh stores\n- Backup before configuration changes\n- Migration between environments\n\nExported snapshots should only be restored into empty Audrey stores with fresh `AUDREY_DATA_DIR` to prevent data corruption.\n\n资料来源：[python/README.md](https://github.com/Evilander/Audrey/blob/main/python/README.md)\n\n### Export Process\n\nExport operations create portable snapshots containing:\n- All memory records (episodic, semantic, procedural)\n- Associated metadata (timestamps, confidence scores)\n- Configuration state\n\n### Import Validation\n\nImport operations verify store emptiness before restoration:\n\n```typescript\nisDatabaseEmpty() // Checks both records and vector tables\n```\n\n资料来源：[CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n## Security Considerations\n\n### Credential Protection\n\nRaw credentials and API keys must be excluded from encoded memory content. Audrey provides redaction functionality to prevent sensitive data exposure:\n\n```typescript\nconst SENSITIVE_KEY_PATTERN = /(password|secret|api[_-]?key|auth[_-]?token|...)$/i;\n```\n\n资料来源：[src/redact.ts](https://github.com/Evilander/Audrey/blob/main/src/redact.ts)\n\n### API Security\n\n- Audrey serve defaults to binding `127.0.0.1` (previously `0.0.0.0`)\n- Non-loopback hosts require `AUDREY_API_KEY` or explicit `AUDREY_ALLOW_NO_AUTH=1`\n- HTTP API key comparison uses `crypto.timingSafeEqual` to prevent timing attacks\n\n资料来源：[CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n\n### Production Recommendations\n\n| Recommendation | Rationale |\n|----------------|-----------|\n| Set one `AUDREY_DATA_DIR` per tenant | Isolation boundary |\n| Pin embedding and LLM providers | Reproducibility |\n| Backup before provider changes | Data integrity |\n| Keep credentials out of memory content | Security |\n| Use `AUDREY_API_KEY` for network exposure | Access control |\n\n## Configuration\n\n### Environment Variables\n\n| Variable | Default | Purpose |\n|----------|---------|---------|\n| `AUDREY_DATA_DIR` | - | Data directory path (required for isolation) |\n| `AUDREY_EMBEDDING_PROVIDER` | - | Embedding model provider |\n| `AUDREY_LLM_PROVIDER` | - | LLM provider for memory operations |\n| `AUDREY_API_KEY` | - | API authentication key |\n| `AUDREY_HOST` | `127.0.0.1` | Network binding address |\n| `AUDREY_ALLOW_NO_AUTH` | `0` | Allow unauthenticated access |\n\n资料来源：[README.md](https://github.com/Evilander/Audrey/blob/main/README.md)\n\n## Related Documentation\n\n- [Memory Model](../memory-model) - Multi-type memory architecture\n- [Recall System](../recall-system) - Retrieval and search mechanisms\n- [Guard Loop](../guard-loop) - Pre-action memory checking\n- [Impact Analysis](../impact) - Memory effectiveness tracking\n\n---\n\n<a id='page-mcp-server'></a>\n\n## MCP Server\n\n### 相关页面\n\n相关主题：[System Architecture](#page-system-architecture), [REST API](#page-rest-api)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [mcp-server/index.ts](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n- [mcp-server/config.ts](https://github.com/Evilander/Audrey/blob/main/mcp-server/config.ts)\n- [README.md](https://github.com/Evilander/Audrey/blob/main/README.md)\n- [CHANGELOG.md](https://github.com/Evilander/Audrey/blob/main/CHANGELOG.md)\n- [src/capsule.ts](https://github.com/Evilander/Audrey/blob/main/src/capsule.ts)\n- [src/rules-compiler.ts](https://github.com/Evilander/Audrey/blob/main/src/rules-compiler.ts)\n- [src/impact.ts](https://github.com/Evilander/Audrey/blob/main/src/impact.ts)\n</details>\n\n# MCP Server\n\n## Overview\n\nThe Audrey MCP Server is a Model Context Protocol (MCP) stdio server that provides a local-first memory layer for AI agents. It enables agents to encode experiences into persistent memory, recall relevant context before actions, and maintain a durable memory state across sessions. 资料来源：[README.md]()\n\nThe server exposes 20+ tools plus status, recent, and principles resources, along with briefing, recall, and reflection prompts. It communicates via stdio (standard input/output), making it compatible with MCP-compatible hosts like Claude Code, Claude Desktop, Cursor, Windsurf, and VS Code. 资料来源：[README.md]()\n\n## Architecture\n\n### System Context\n\n```mermaid\ngraph TD\n    subgraph \"MCP Hosts\"\n        A[Claude Code]\n        B[Claude Desktop]\n        C[Cursor]\n        D[Windsurf]\n        E[VS Code]\n        F[Other MCP Clients]\n    end\n    \n    subgraph \"Audrey MCP Server\"\n        G[MCP stdio Server]\n        H[Tool Handlers]\n        I[Resource Providers]\n        J[Prompt Templates]\n    end\n    \n    subgraph \"Audrey Core\"\n        K[Memory Store<br/>SQLite + sqlite-vec]\n        L[Embedding Engine<br/>ONNX]\n        M[Retrieval Engine]\n    end\n    \n    A --> G\n    B --> G\n    C --> G\n    D --> G\n    E --> G\n    F --> G\n    \n    G --> H\n    G --> I\n    G --> J\n    \n    H --> K\n    I --> K\n    J --> K\n    \n    K --> L\n    K --> M\n```\n\n### Server Initialization Flow\n\n```mermaid\nsequenceDiagram\n    participant Host as MCP Host\n    participant Server as McpServer\n    participant Audrey as Audrey Instance\n    participant Store as Memory Store\n    \n    Host->>Server: Start Process\n    Server->>Audrey: Initialize with config\n    Audrey->>Store: Open SQLite + sqlite-vec\n    alt Warmup Enabled\n        Audrey->>Store: Pre-compute embeddings\n    end\n    Server->>Server: registerHostResources()\n    Server->>Server: registerHostPrompts()\n    Server->>Server: Register Tools\n    Server->>Host: Ready (stdio)\n```\n\n## Server Components\n\n### Core Server Setup\n\nThe MCP server is initialized with a name and version, then configured with resources, prompts, and tools: 资料来源：[mcp-server/index.ts:101-106]()\n\n```typescript\nconst server = new McpServer({\n  name: SERVER_NAME,\n  version: VERSION,\n});\n\nregisterHostResources(server, audrey);\nregisterHostPrompts(server);\n```\n\n### Tool Registry\n\nThe server registers the following tool categories:\n\n| Category | Tools | Purpose |\n|----------|-------|---------|\n| Memory Operations | `memory_encode`, `memory_recall` | Store and retrieve memories |\n| Memory Management | `memory_import`, `memory_export`, `memory_forget` | Data management |\n| Impact Tracking | `mark_used`, `impact_report` | Memory utility tracking |\n| Promotion | `promote_memory`, `rule_review` | Memory-to-rules conversion |\n\n## Tools Reference\n\n### memory_encode\n\nEncodes new information into the memory store with diagnostic support.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `content` | string | Yes | The memory content to encode |\n| `source` | string | No | Source identifier (e.g., \"direct-observation\", \"told-by-user\") |\n| `tags` | string[] | No | Classification tags |\n| `salience` | number | No | Importance weight (0-1) |\n| `private` | boolean | No | Mark as private memory |\n| `context` | object | No | Additional context metadata |\n| `affect` | object | No | Emotional/valence metadata |\n| `wait_for_consolidation` | boolean | No | Opt-in read-after-write semantics (default: false) |\n\n**Returns:** Tool result with memory ID, content, source, and optionally diagnostics. 资料来源：[mcp-server/index.ts:108-133]()\n\n### memory_recall\n\nRetrieves relevant memories based on a query with filtering options.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `query` | string | Yes | Search query |\n| `limit` | number | No | Maximum results (default: 10) |\n| `types` | string[] | No | Filter by memory types |\n| `min_confidence` | number | No | Minimum confidence threshold |\n| `tags` | string[] | No | Filter by tags |\n| `sources` | string[] | No | Filter by sources |\n| `after` | string | No | ISO timestamp lower bound |\n| `before` | string | No | ISO timestamp upper bound |\n| `context` | object | No | Context filtering |\n| `mood` | string | No | Mood-based filtering |\n\n**Returns:** Array of recall results with confidence scores and metadata. 资料来源：[mcp-server/index.ts:135-142]()\n\n### Additional Tools\n\n| Tool | Purpose |\n|------|---------|\n| `memory_import` | Import memory snapshots |\n| `memory_export` | Export memory snapshots |\n| `memory_forget` | Delete specific memories |\n| `mark_used` | Record memory utility |\n| `impact_report` | Generate impact analytics |\n| `promote_memory` | Convert memory to rule |\n| `rule_review` | Review promotion candidates |\n\n## Command Line Interface\n\n### Command Routing\n\nThe MCP server entry point (`mcp-server/index.ts`) handles CLI subcommands before starting the stdio loop: 资料来源：[mcp-server/index.ts:200-240]()\n\n```mermaid\ngraph TD\n    A[audrey CLI] --> B{Subcommand?}\n    \n    B -->|--help / -h / help| C[printHelp]\n    B -->|--version / -v / version| D[printVersion]\n    B -->|install| E[install]\n    B -->|uninstall| F[uninstall]\n    B -->|mcp-config| G[printMcpConfig]\n    B -->|hook-config| H[printHookConfig]\n    B -->|demo| I[runDemoCommand]\n    B -->|reembed| J[reembed]\n    B -->|dream| K[dream]\n    B -->|greeting| L[greeting]\n    B -->|NONE| M[Start MCP Server]\n    \n    C --> N[Exit 0]\n    D --> N\n    E --> N\n    F --> N\n    G --> N\n    H --> N\n    I --> N\n    J --> N\n    K --> N\n    L --> N\n    M --> O[stdio Loop]\n```\n\n### Available Subcommands\n\n| Command | Description |\n|---------|-------------|\n| `audrey install` | Register Audrey with host MCP configuration |\n| `audrey uninstall` | Remove Audrey from host configuration |\n| `audrey mcp-config` | Print MCP server configuration |\n| `audrey hook-config` | Generate Claude Code hook configurations |\n| `audrey demo` | Run interactive demonstration |\n| `audrey reembed` | Regenerate embeddings |\n| `audrey dream` | Generate reflection/memory consolidation |\n| `audrey greeting` | Display greeting message |\n| `audrey doctor` | Run diagnostic checks |\n| `audrey guard` | Check memory before action |\n| `audrey status` | Show memory system status |\n| `audrey promote` | Promote memories to rules |\n| `audrey impact` | Generate impact reports |\n| `audrey observe-tool` | Monitor tool execution |\n\n### Help and Version Short-Circuit\n\nHelp and version flags MUST short-circuit before falling through to the MCP server. A user running `audrey --help` should see help, not be dropped into a stdio loop: 资料来源：[mcp-server/index.ts:201-206]()\n\n```typescript\nif (subcommand === '--help' || subcommand === '-h' || subcommand === 'help') {\n  printHelp();\n  process.exit(0);\n} else if (subcommand === '--version' || subcommand === '-v' || subcommand === 'version') {\n  printVersion();\n  process.exit(0);\n}\n```\n\n## Configuration Management\n\n### MCP Host Configuration\n\nThe `config.ts` module provides functions to generate host-specific MCP configurations: 资料来源：[mcp-server/config.ts:1-50]()\n\n```typescript\nexport function formatMcpHostConfig(\n  host: string | undefined = 'generic',\n  env: Record<string, string | undefined> = process.env,\n): string\n```\n\n**Supported Hosts:**\n\n| Host | Config Format | Notes |\n|------|---------------|-------|\n| `codex` | TOML | GitHub MCP config style |\n| `claude-code` | JSON | Claude Code MCP settings |\n| `claude-desktop` | JSON | Claude Desktop config |\n| `cursor` | JSON | Cursor MCP config |\n| `windsurf` | JSON | Windsurf MCP config |\n| `vscode` | JSON | VS Code MCP config |\n| `jetbrains` | JSON | JetBrains MCP config |\n| `generic` | JSON | Generic MCP fallback |\n\n### Installation Arguments\n\nThe `buildInstallArgs()` function generates CLI arguments for installing the MCP server: 资料来源：[mcp-server/config.ts:52-66]()\n\n```typescript\nexport function buildInstallArgs(\n  env: Record<string, string | undefined> = process.env,\n  options: McpEnvOptions = {},\n): string[]\n```\n\n**Generated Output Example:**\n\n```bash\nmcp add -s user audrey -e AUDREY_AGENT=claude-code -e AUDREY_DATA_DIR=... -- node /path/to/mcp-entrypoint\n```\n\n### Install Guide Generation\n\nThe `formatInstallGuide()` function generates human-readable installation instructions: 资料来源：[mcp-server/index.ts:18-48]()\n\n```typescript\nexport function formatInstallGuide(\n  host: string,\n  env: Record<string, string | undefined> = process.env,\n  dryRun = false,\n): string\n```\n\n**Output Sections:**\n\n1. Title (with dry-run or config-only indicator)\n2. No-modification notice\n3. Generated MCP config\n4. Generated Claude Code hook config (for Claude Code host)\n5. Next steps\n\n## Host-Specific Resources\n\n### Resource Registration\n\nResources are registered per-host to provide context: 资料来源：[mcp-server/index.ts:103]()\n\n```typescript\nregisterHostResources(server, audrey);\nregisterHostPrompts(server);\n```\n\n### Available Resources\n\n| Resource | Type | Description |\n|----------|------|-------------|\n| `status` | Resource | Current system status |\n| `recent` | Resource | Recent memory activity |\n| `principles` | Resource | Core operational principles |\n\n### Available Prompts\n\n| Prompt | Purpose |\n|--------|---------|\n| `briefing` | Get current session briefing |\n| `recall` | Perform focused recall |\n| `reflection` | Generate self-reflection |\n\n## Error Handling\n\n### Tool Error Response\n\nTool handlers return structured error responses: 资料来源：[mcp-server/index.ts:100]()\n\n```typescript\nfunction toolError(err: unknown): CallToolResult {\n  return {\n    content: [{ type: 'text', text: `[audrey] error: ${err}` }],\n    isError: true,\n  };\n}\n```\n\n### Tool Success Response\n\nTool handlers return structured success responses with optional diagnostics: 资料来源：[mcp-server/index.ts:99]()\n\n```typescript\nfunction toolResult(data: unknown, diagnostics?: unknown): CallToolResult {\n  return {\n    content: [{ type: 'text', text: JSON.stringify(data) }],\n    _meta: diagnostics ? { diagnostics } : undefined,\n  };\n}\n```\n\n## Environment Variables\n\n| Variable | Default | Description |\n|----------|---------|-------------|\n| `AUDREY_AGENT` | `claude-code` | Host agent identifier |\n| `AUDREY_DATA_DIR` | Platform-specific | Data directory path |\n| `AUDREY_PROFILE` | `0` | Enable profiling diagnostics |\n| `AUDREY_DEBUG` | `0` | Enable debug logging |\n| `AUDREY_DISABLE_WARMUP` | `0` | Skip embedding warmup |\n| `AUDREY_API_KEY` | unset | REST API authentication |\n| `AUDREY_HOST` | `127.0.0.1` | REST bind address |\n| `AUDREY_PORT` | `7437` | REST server port |\n\n## Performance Characteristics\n\n### v0.22.0 Performance Metrics\n\n| Operation | Before | After | Improvement |\n|-----------|--------|-------|-------------|\n| Encode response (p50) | 24.7ms | 15.2ms | ~40% faster |\n| Cold-start first encode | 525ms | 28ms (with warmup) | ~18.7x faster |\n| Hybrid recall (p50) | 30.2ms | 14.3ms | ~2.1x faster |\n\n### Optimization Details\n\n- Eliminated 3 of 4 redundant embedding calls during encode\n- Validation, interference, and affect resonance reuse the main content vector\n- Background embedding warmup at MCP boot reduces cold-start latency 资料来源：[CHANGELOG.md]()\n\n## Security\n\n### API Key Timing Safety\n\nHTTP API key comparison uses `crypto.timingSafeEqual` to prevent timing attacks: 资料来源：[CHANGELOG.md]()\n\n### Recall Options Sanitization\n\nHTTP `/v1/recall` and `/v1/capsule` sanitize request bodies to prevent ACL bypass: 资料来源：[CHANGELOG.md]()\n\n### Promote Path Restrictions\n\n`audrey promote --yes` restricts writes to `process.cwd()` unless target is in `AUDREY_PROMOTE_ROOTS`, preventing prompt-injection attacks. 资料来源：[CHANGELOG.md]()\n\n## Profiling Mode\n\nWhen `AUDREY_PROFILE=1`, tools return diagnostic metadata: 资料来源：[mcp-server/index.ts:110-120]()\n\n```typescript\nif (profileEnabled) {\n  const { id, diagnostics } = await audrey.encodeWithDiagnostics({\n    content,\n    source,\n    tags,\n    salience,\n    private: isPrivate,\n    context,\n    affect,\n    waitForConsolidation: wait_for_consolidation,\n  });\n  return toolResult({ id, content, source, private: isPrivate ?? false }, diagnostics);\n}\n```\n\n**Diagnostic Data Includes:**\n\n- Per-stage timing information\n- Embedding generation time\n- Retrieval latency breakdown\n\n## Related Documentation\n\n- [README.md](README.md) - Main project documentation\n- [CHANGELOG.md](CHANGELOG.md) - Version history and release notes\n- [src/capsule.ts](src/capsule.ts) - Memory capsule generation\n- [src/rules-compiler.ts](src/rules-compiler.ts) - Memory-to-rules promotion\n- [src/impact.ts](src/impact.ts) - Impact analytics reporting\n\n---\n\n<a id='page-rest-api'></a>\n\n## REST API\n\n### 相关页面\n\n相关主题：[System Architecture](#page-system-architecture), [MCP Server](#page-mcp-server)\n\n<details>\n<summary>Related Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/routes.ts](https://github.com/Evilander/Audrey/blob/main/src/routes.ts)\n- [src/server.ts](https://github.com/Evilander/Audrey/blob/main/src/server.ts)\n- [README.md](https://github.com/Evilander/Audrey/blob/main/README.md)\n- [python/README.md](https://github.com/Evilander/Audrey/blob/main/python/README.md)\n- [mcp-server/index.ts](https://github.com/Evilander/Audrey/blob/main/mcp-server/index.ts)\n- [src/impact.ts](https://github.com/Evilander/Audrey/blob/main/src/impact.ts)\n</details>\n\n# REST API\n\nThe Audrey REST API provides a local-first HTTP interface for memory management operations, enabling external agents and services to interact with Audrey's memory system without direct database access.\n\n## Overview\n\nAudrey's REST API is built on [Hono](https://hono.dev/), a lightweight, high-performance web framework for Edge environments. The API serves as a sidecar service that wraps the core memory engine with HTTP endpoints for encoding, recalling, and managing memory entries.\n\n**Key characteristics:**\n- Local-first design with no external database dependencies\n- SQLite + sqlite-vec for storage and vector search\n- Bearer token authentication for non-loopback access\n- Type-safe request/response handling\n\n资料来源：[README.md:60]()\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[Client<br>Python/JS SDK] --> B[REST API<br>Hono Server]\n    B --> C[Audrey Core Engine]\n    C --> D[SQLite<br>Memory Store]\n    C --> E[sqlite-vec<br>Vector Index]\n    B --> F[/health]\n    B --> G[/v1/recall]\n    B --> H[/v1/capsule]\n    B --> I[/v1/encode]\n    B --> J[Admin Routes<br>/v1/import<br>/v1/export]\n```\n\n## Server Configuration\n\n### Environment Variables\n\n| Variable | Default | Description |\n|----------|---------|-------------|\n| `AUDREY_HOST` | `127.0.0.1` | REST sidecar bind address. Set to `0.0.0.0` only with `AUDREY_API_KEY`. |\n| `AUDREY_PORT` | `7437` | Port for the REST server to listen on. |\n| `AUDREY_API_KEY` | unset | Bearer token required for non-loopback REST traffic. |\n| `AUDREY_ALLOW_NO_AUTH` | `0` | Set to `1` to allow non-loopback bind without an API key. Not recommended. |\n| `AUDREY_ENABLE_ADMIN_TOOLS` | `0` | Set to `1` to enable export, import, and forget routes/tools. Disabled by default. |\n| `AUDREY_PRAGMA_DEFAULTS` | `1` | Set to `0` to revert SQLite PRAGMA tuning to better-sqlite3 defaults. |\n| `AUDREY_DEBUG` | `0` | Set to `1` to print MCP info logs. Errors always log. |\n\n资料来源：[README.md:44-52]()\n\n### Starting the Server\n\n```bash\n# Default (loopback only)\nnpx audrey serve\n\n# With explicit port\nAUDREY_PORT=8080 npx audrey serve\n\n# Network-exposed with API key\nAUDREY_HOST=0.0.0.0 AUDREY_API_KEY=secret npx audrey serve\n```\n\n资料来源：[python/README.md:18]()\n\n## API Endpoints\n\n### Health Check\n\n| Method | Path | Description |\n|--------|------|-------------|\n| `GET` | `/health` | Returns server health status |\n\n**Response:**\n```json\n{\n  \"status\": \"ok\",\n  \"version\": \"0.22.1\",\n  \"timestamp\": \"2026-04-30T12:00:00.000Z\"\n}\n```\n\n资料来源：[README.md:58]()\n\n### Memory Operations\n\n| Method | Path | Description |\n|--------|------|-------------|\n| `POST` | `/v1/encode` | Store a new memory entry |\n| `POST` | `/v1/recall` | Retrieve relevant memories by query |\n| `POST` | `/v1/capsule` | Get a turn-sized memory packet |\n| `POST` | `/v1/mark-used` | Mark memory as used with outcome feedback |\n| `POST` | `/v1/observe-tool` | Record tool execution results |\n| `POST` | `/v1/before-action` | Preflight check before tool execution |\n| `POST` | `/v1/validate` | Validate memory helpfulness |\n\n资料来源：[README.md:58](), [src/routes.ts:1-50]()\n\n## Request Body Schema\n\nThe REST API accepts a unified `RouteBody` type with optional fields:\n\n```typescript\ntype RouteBody = {\n  action?: string;\n  query?: string;\n  tool?: string;\n  session_id?: string;\n  sessionId?: string;\n  cwd?: string;\n  files?: string[];\n  strict?: boolean;\n  limit?: number;\n  budget_chars?: number;\n  budgetChars?: number;\n  mode?: PreflightOptions['mode'];\n  failure_window_hours?: number;\n  recent_failure_window_hours?: number;\n  recentFailureWindowHours?: number;\n  recent_change_window_hours?: number;\n  recentChangeWindowHours?: number;\n  include_capsule?: boolean;\n  includeCapsule?: boolean;\n  include_status?: boolean;\n  includeStatus?: boolean;\n  record_event?: boolean;\n  recordEvent?: boolean;\n  include_preflight?: boolean;\n  includePreflight?: boolean;\n  receipt_id?: string;\n  receiptId?: string;\n  input?: unknown;\n  output?: unknown;\n  outcome?: EventOutcome;\n  error_summary?: string;\n  errorSummary?: string;\n  metadata?: Record<string, unknown>;\n  retain_details?: boolean;\n  retainDetails?: boolean;\n  evidence_feedback?: Record<string, 'used' | 'helpful' | 'wrong'>;\n  evidenceFeedback?: Record<string, 'used' | 'helpful' | 'wrong'>;\n};\n```\n\n资料来源：[src/routes.ts:5-46]()\n\n## Security Model\n\n### Authentication\n\nNon-loopback REST traffic requires a Bearer token:\n\n```bash\ncurl -H \"Authorization: Bearer your-secret-token\" \\\n  http://localhost:7437/v1/recall \\\n  -d '{\"query\": \"deploy failures\"}'\n```\n\n**Security measures:**\n- HTTP API key comparison uses `crypto.timingSafeEqual` instead of string `!==` to prevent timing attacks 资料来源：[README.md:41]()\n- Server defaults to binding `127.0.0.1` (was `0.0.0.0`) 资料来源：[README.md:40]()\n- Refuses to start on non-loopback host without `AUDREY_API_KEY` unless `AUDREY_ALLOW_NO_AUTH=1`\n\n### Recall Options Sanitization\n\nHTTP `/v1/recall` and `/v1/capsule` no longer body-spread caller options into internal calls. The `sanitizeRecallOptions()` function implements an allowlist that drops anything not in a known-safe key set:\n\n```typescript\nexport function sanitizeRecallOptions(options: unknown): SanitizedRecallOptions {\n  // Only allows: budget_chars, limit, retrieval, includePrivate, sessionId\n}\n```\n\nThis prevents bypassing private-memory ACL and integrity controls via `includePrivate: true` or `confidenceConfig` overrides in HTTP bodies.\n\n资料来源：[README.md:39-40](), [CHANGELOG.md:0.22.1]()\n\n### Admin Tools\n\nAdmin routes (`/v1/import`, `/v1/export`, `/v1/forget`) are disabled by default. Enable with:\n\n```bash\nAUDREY_ENABLE_ADMIN_TOOLS=1 npx audrey serve\n```\n\n资料来源：[README.md:48]()\n\n## Client Integration\n\n### Python SDK\n\n```python\nfrom audrey_memory import Audrey\n\nbrain = Audrey(\n    base_url=\"http://127.0.0.1:7437\",\n    api_key=\"secret\",\n    agent=\"support-agent\",\n)\n\n# Encode a memory\nmemory_id = brain.encode(\n    \"Stripe returns HTTP 429 above 100 req/s\",\n    source=\"direct-observation\",\n    tags=[\"stripe\", \"rate-limit\"],\n)\n\n# Recall relevant memories\nresults = brain.recall(\"stripe rate limits\", limit=5)\n\n# Create snapshot for backup\nsnapshot = brain.snapshot()\nbrain.close()\n```\n\n**Async usage:**\n```python\nimport asyncio\nfrom audrey_memory import AsyncAudrey\n\nasync def main() -> None:\n    async with AsyncAudrey(base_url=\"http://127.0.0.1:7437\") as brain:\n        await brain.health()\n        await brain.encode(\"Deploy failed due to OOM\", source=\"direct-observation\")\n        await brain.recall(\"deploy failure\", limit=3)\n\nasyncio.run(main())\n```\n\n资料来源：[python/README.md:22-45]()\n\n### Connection URL Correction\n\n> **Note:** Python client `DEFAULT_BASE_URL` was corrected from `http://127.0.0.1:3487` to `http://127.0.0.1:7437` in v0.22.1 to match the TS server's default port.\n\n资料来源：[CHANGELOG.md:0.22.1]()\n\n## Impact Reporting\n\nThe REST API exposes impact analytics through the `audrey impact` CLI, which calls internal Audrey methods:\n\n| Endpoint | Description |\n|----------|-------------|\n| Total memories by type | episodic, semantic, procedural counts |\n| All-time validated count | Memories validated as helpful/wrong |\n| Recent validations | Validation activity in time window |\n| Top-N most-used memories | Memories with highest `usage_count` |\n| Weakest-N memories | Lowest salience candidates for forgetting |\n| Recent activity timeline | `last_used_at` based activity log |\n\n```bash\n# Basic report\naudrey impact\n\n# JSON output for automation\naudrey impact --json\n\n# Custom window and limits\naudrey impact --window 30 --limit 20\n```\n\n资料来源：[src/impact.ts:1-50](), [CHANGELOG.md:0.22.1]()\n\n## Deployment\n\n### Docker\n\n```yaml\n# docker-compose.yml\nservices:\n  audrey:\n    image: ghcr.io/evilander/audrey:latest\n    ports:\n      - \"7437:7437\"\n    environment:\n      - AUDREY_API_KEY=your-secret-token\n      - AUDREY_HOST=0.0.0.0\n    volumes:\n      - audrey-data:/data\n```\n\n### Doctor Check\n\nThe `audrey doctor` command validates REST server configuration:\n\n```bash\nnpx audrey doctor\n```\n\n**Checks performed:**\n| Check | Description |\n|-------|-------------|\n| `serve-bind-safety` | Validates bind address with auth configuration |\n| `node-runtime` | Node.js version >= 20 |\n| `entrypoint-exists` | MCP stdio entrypoint file exists |\n| `data-dir` | Data directory accessibility |\n| `embedding` | Embedding provider configuration |\n| `llm` | LLM provider configuration |\n\n```mermaid\ngraph TD\n    A[audrey doctor] --> B{Is bind loopback?}\n    B -->|Yes| C[✅ loopback only]\n    B -->|No| D{Has AUDREY_API_KEY?}\n    D -->|Yes| E[✅ non-loopback with API key]\n    D -->|No| F{Has AUDREY_ALLOW_NO_AUTH?}\n    F -->|Yes| G[⚠️ warning - network exposure]\n    F -->|No| H[❌ error - refuse to start]\n```\n\n资料来源：[mcp-server/index.ts:100-130]()\n\n## Error Handling\n\n### Common Issues\n\n| Error | Cause | Solution |\n|-------|-------|----------|\n| Connection refused | Wrong port or host | Check `AUDREY_PORT` and `AUDREY_HOST` |\n| 401 Unauthorized | Missing/invalid API key | Provide `Authorization: Bearer <token>` header |\n| 404 Not Found | Wrong endpoint | Use `/v1/*` routes, not `/openapi.json` or `/docs` |\n| Validation error | Malformed request body | Check RouteBody schema |\n\n### Status Codes\n\n| Code | Meaning |\n|------|---------|\n| `200` | Success |\n| `400` | Bad request (malformed body) |\n| `401` | Unauthorized (missing/invalid API key) |\n| `404` | Endpoint not found |\n| `500` | Internal server error |\n\n> **Note:** `/openapi.json` and `/docs` routes are not currently wired. The README matches the actual surface (`/health` + `/v1/*`).\n\n资料来源：[CHANGELOG.md:0.22.1](), [README.md:58]()\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：Evilander/Audrey\n\n摘要：发现 14 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：安装坑 - 来源证据：Audrey 1.0.1 — honest GuardBench gate, Guard time decay, structured validate errors。\n\n## 1. 安装坑 · 来源证据：Audrey 1.0.1 — honest GuardBench gate, Guard time decay, structured validate errors\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Audrey 1.0.1 — honest GuardBench gate, Guard time decay, structured validate errors\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_135b992964ae468aa28f88ee639816d1 | https://github.com/Evilander/Audrey/releases/tag/v1.0.1 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 2. 安装坑 · 来源证据：Audrey Guard 0.23.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Audrey Guard 0.23.0\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_9c913c644e2c4c099ea01523623f080e | https://github.com/Evilander/Audrey/releases/tag/v0.23.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 3. 安装坑 · 来源证据：v0.16.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.16.0\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_a7c5c62d4f034e50ba2e9c36e0798882 | https://github.com/Evilander/Audrey/releases/tag/v0.16.0 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 4. 安装坑 · 来源证据：v0.16.1 — Windows MCP fix\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.16.1 — Windows MCP fix\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_c0141ccf0a3245ec8c8ba112af7948e0 | https://github.com/Evilander/Audrey/releases/tag/v0.16.1 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。\n\n## 5. 安装坑 · 来源证据：v0.17.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.17.0\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_9617863b3f954035926b8670b5bbea29 | https://github.com/Evilander/Audrey/releases/tag/v0.17.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 6. 配置坑 · 可能修改宿主 AI 配置\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- 证据：capability.host_targets | github_repo:1161444210 | https://github.com/Evilander/Audrey | host_targets=mcp_host, claude, claude_code\n\n## 7. 能力坑 · 能力判断依赖假设\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:1161444210 | https://github.com/Evilander/Audrey | README/documentation is current enough for a first validation pass.\n\n## 8. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:1161444210 | https://github.com/Evilander/Audrey | last_activity_observed missing\n\n## 9. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:1161444210 | https://github.com/Evilander/Audrey | no_demo; severity=medium\n\n## 10. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:1161444210 | https://github.com/Evilander/Audrey | no_demo; severity=medium\n\n## 11. 安全/权限坑 · 来源证据：Audrey 1.0.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Audrey 1.0.0\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_d30d964956da40a2b5e26dc7404861f8 | https://github.com/Evilander/Audrey/releases/tag/v1.0.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 12. 安全/权限坑 · 来源证据：v0.22.2 — correctness pass + legitimate benchmarking\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.22.2 — correctness pass + legitimate benchmarking\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_f9c004c97d31437ebdc3699d6f1ba2f4 | https://github.com/Evilander/Audrey/releases/tag/v0.22.2 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 13. 维护坑 · 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:1161444210 | https://github.com/Evilander/Audrey | issue_or_pr_quality=unknown\n\n## 14. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:1161444210 | https://github.com/Evilander/Audrey | release_recency=unknown\n\n<!-- canonical_name: Evilander/Audrey; 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项目：Evilander/Audrey\n\n摘要：发现 14 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：安装坑 - 来源证据：Audrey 1.0.1 — honest GuardBench gate, Guard time decay, structured validate errors。\n\n## 1. 安装坑 · 来源证据：Audrey 1.0.1 — honest GuardBench gate, Guard time decay, structured validate errors\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Audrey 1.0.1 — honest GuardBench gate, Guard time decay, structured validate errors\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_135b992964ae468aa28f88ee639816d1 | https://github.com/Evilander/Audrey/releases/tag/v1.0.1 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 2. 安装坑 · 来源证据：Audrey Guard 0.23.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Audrey Guard 0.23.0\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_9c913c644e2c4c099ea01523623f080e | https://github.com/Evilander/Audrey/releases/tag/v0.23.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 3. 安装坑 · 来源证据：v0.16.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.16.0\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_a7c5c62d4f034e50ba2e9c36e0798882 | https://github.com/Evilander/Audrey/releases/tag/v0.16.0 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 4. 安装坑 · 来源证据：v0.16.1 — Windows MCP fix\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.16.1 — Windows MCP fix\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_c0141ccf0a3245ec8c8ba112af7948e0 | https://github.com/Evilander/Audrey/releases/tag/v0.16.1 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。\n\n## 5. 安装坑 · 来源证据：v0.17.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.17.0\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_9617863b3f954035926b8670b5bbea29 | https://github.com/Evilander/Audrey/releases/tag/v0.17.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 6. 配置坑 · 可能修改宿主 AI 配置\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- 证据：capability.host_targets | github_repo:1161444210 | https://github.com/Evilander/Audrey | host_targets=mcp_host, claude, claude_code\n\n## 7. 能力坑 · 能力判断依赖假设\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:1161444210 | https://github.com/Evilander/Audrey | README/documentation is current enough for a first validation pass.\n\n## 8. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:1161444210 | https://github.com/Evilander/Audrey | last_activity_observed missing\n\n## 9. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:1161444210 | https://github.com/Evilander/Audrey | no_demo; severity=medium\n\n## 10. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:1161444210 | https://github.com/Evilander/Audrey | no_demo; severity=medium\n\n## 11. 安全/权限坑 · 来源证据：Audrey 1.0.0\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Audrey 1.0.0\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_d30d964956da40a2b5e26dc7404861f8 | https://github.com/Evilander/Audrey/releases/tag/v1.0.0 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 12. 安全/权限坑 · 来源证据：v0.22.2 — correctness pass + legitimate benchmarking\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.22.2 — correctness pass + legitimate benchmarking\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_f9c004c97d31437ebdc3699d6f1ba2f4 | https://github.com/Evilander/Audrey/releases/tag/v0.22.2 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 13. 维护坑 · 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:1161444210 | https://github.com/Evilander/Audrey | issue_or_pr_quality=unknown\n\n## 14. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:1161444210 | https://github.com/Evilander/Audrey | release_recency=unknown\n",
      "summary": "用户实践前最可能遇到的身份、安装、配置、运行和安全坑。",
      "title": "Pitfall Log / 踩坑日志"
    },
    "prompt_preview": {
      "asset_id": "prompt_preview",
      "filename": "PROMPT_PREVIEW.md",
      "markdown": "# Audrey - 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 Evilander/Audrey.\n\nProject:\n- Name: Audrey\n- Repository: https://github.com/Evilander/Audrey\n- Summary: Persistent memory and continuity engine for Claude Code and AI agents.\n- Host target: mcp_host, claude, claude_code\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: Persistent memory and continuity engine for Claude Code and AI agents.\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: Persistent memory and continuity engine for Claude Code and AI agents.\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. page-overview: Audrey Overview. Produce one small intermediate artifact and wait for confirmation.\n2. page-quick-start: Quick Start Guide. Produce one small intermediate artifact and wait for confirmation.\n3. page-system-architecture: System Architecture. Produce one small intermediate artifact and wait for confirmation.\n4. page-memory-model: Memory Model. Produce one small intermediate artifact and wait for confirmation.\n5. page-audrey-guard: Audrey Guard. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/Evilander/Audrey\n- https://github.com/Evilander/Audrey#readme\n- README.md\n- src/types.ts\n- src/audrey.ts\n- package.json\n- src/index.ts\n- src/controller.ts\n- src/server.ts\n- src/db.ts\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "summary": "不安装项目也能感受能力节奏的安全试用 Prompt。",
      "title": "Prompt Preview / 安装前试用 Prompt"
    },
    "quick_start": {
      "asset_id": "quick_start",
      "filename": "QUICK_START.md",
      "markdown": "# Quick Start / 官方入口\n\n项目：Evilander/Audrey\n\n## 官方安装入口\n\n### Node.js / npx · 官方安装入口\n\n```bash\nnpx audrey\n```\n\n来源：https://github.com/Evilander/Audrey#readme\n\n## 来源\n\n- repo: https://github.com/Evilander/Audrey\n- docs: https://github.com/Evilander/Audrey#readme\n",
      "summary": "从项目官方 README 或安装文档提取的开工入口。",
      "title": "Quick Start / 官方入口"
    }
  },
  "validation_id": "dval_bcf396c2d9534088a3eb88304c9c4a26"
}
