{
  "canonical_name": "mnemopay/mnemopay-sdk",
  "compilation_id": "pack_f970dfa8491c4699900bbd4ef6ad3a6f",
  "created_at": "2026-05-15T07:01:50.490964+00:00",
  "created_by": "project-pack-compiler",
  "feedback": {
    "carrier_selection_notes": [
      "viable_asset_types=skill, recipe, host_instruction, eval, preflight",
      "recommended_asset_types=skill, recipe, host_instruction, eval, preflight"
    ],
    "evidence_delta": {
      "confirmed_claims": [
        "identity_anchor_present",
        "capability_and_host_targets_present",
        "install_path_declared_or_better"
      ],
      "missing_required_fields": [],
      "must_verify_forwarded": [
        "Run or inspect `npm install @mnemopay/sdk` in an isolated environment.",
        "Confirm the project exposes the claimed capability to at least one target host."
      ],
      "quickstart_execution_scope": "allowlisted_sandbox_smoke",
      "sandbox_command": "npm install @mnemopay/sdk",
      "sandbox_container_image": "node:22-slim",
      "sandbox_execution_backend": "docker",
      "sandbox_planner_decision": "deterministic_isolated_install",
      "sandbox_validation_id": "sbx_b4be2a78e42843819cab1bf4c00bac72"
    },
    "feedback_event_type": "project_pack_compilation_feedback",
    "learning_candidate_reasons": [],
    "template_gaps": []
  },
  "identity": {
    "canonical_id": "project_cc7826a84c7d2d02e2e33477ea309cf2",
    "canonical_name": "mnemopay/mnemopay-sdk",
    "homepage_url": null,
    "license": "unknown",
    "repo_url": "https://github.com/mnemopay/mnemopay-sdk",
    "slug": "mnemopay-sdk",
    "source_packet_id": "phit_4d003b454d5d45c992fc5d6d46ae3342",
    "source_validation_id": "dval_f51821c637ca4c598b463bd39c40f528"
  },
  "merchandising": {
    "best_for": "需要数据分析与投资研究能力，并使用 local_cli的用户",
    "github_forks": 1,
    "github_stars": 5,
    "one_liner_en": "Trust & reputation layer for AI agents. Agent Credit Score (300-850) + Merkle-anchored ledger + behavioral finance + EWMA anomaly detection. Memory + payments + identity + fraud in one SDK. npm i @mnemopay/sdk",
    "one_liner_zh": "Trust & reputation layer for AI agents. Agent Credit Score (300-850) + Merkle-anchored ledger + behavioral finance + EWMA anomaly detection. Memory + payments + identity + fraud in one SDK. npm i @mnemopay/sdk",
    "primary_category": {
      "category_id": "data-market-research",
      "confidence": "high",
      "name_en": "Data & Market Research",
      "name_zh": "数据分析与投资研究",
      "reason": "strong category phrase match from project identity and outcome"
    },
    "target_user": "使用 local_cli 等宿主 AI 的用户",
    "title_en": "mnemopay-sdk",
    "title_zh": "mnemopay-sdk 能力包",
    "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_4d003b454d5d45c992fc5d6d46ae3342",
  "page_model": {
    "artifacts": {
      "artifact_slug": "mnemopay-sdk",
      "files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json",
        "REPO_INSPECTION.md",
        "CAPABILITY_CONTRACT.json",
        "EVIDENCE_INDEX.json",
        "CLAIM_GRAPH.json"
      ],
      "required_files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json"
      ]
    },
    "detail": {
      "capability_source": "Project Hit Packet + DownstreamValidationResult",
      "commands": [
        {
          "command": "npm install @mnemopay/sdk",
          "label": "Node.js / npm · 官方安装入口",
          "source": "https://github.com/mnemopay/mnemopay-sdk#readme",
          "verified": true
        }
      ],
      "display_tags": [
        "浏览器 Agent",
        "网页任务自动化",
        "浏览器自动化",
        "页面观察与动作规划",
        "评测体系"
      ],
      "eyebrow": "数据分析与投资研究",
      "glance": [
        {
          "body": "判断自己是不是目标用户。",
          "label": "最适合谁",
          "value": "需要数据分析与投资研究能力，并使用 local_cli的用户"
        },
        {
          "body": "先理解能力边界，再决定是否继续。",
          "label": "核心价值",
          "value": "Trust & reputation layer for AI agents. Agent Credit Score (300-850) + Merkle-anchored ledger + behavioral finance + EWMA anomaly detection. Memory + payments + identity + fraud in one SDK. npm i @mnemopay/sdk"
        },
        {
          "body": "未完成验证前保持审慎。",
          "label": "继续前",
          "value": "publish to Doramagic.ai project surfaces"
        }
      ],
      "guardrail_source": "Boundary & Risk Card",
      "guardrails": [
        {
          "body": "Prompt Preview 只展示流程，不证明项目已安装或运行。",
          "label": "Check 1",
          "value": "不要把试用当真实运行"
        },
        {
          "body": "local_cli",
          "label": "Check 2",
          "value": "确认宿主兼容"
        },
        {
          "body": "publish to Doramagic.ai project surfaces",
          "label": "Check 3",
          "value": "先隔离验证"
        }
      ],
      "mode": "skill, recipe, host_instruction, eval, preflight",
      "pitfall_log": {
        "items": [
          {
            "body": "项目文本出现 secret/private key/privacy/trading/finance 等敏感关键词。",
            "category": "安全/权限坑",
            "evidence": [
              "packet_text.keyword_scan | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | matched secret / private key / privacy / trading / finance keyword"
            ],
            "severity": "high",
            "suggested_check": "补敏感数据流、密钥存储和权限边界审查。",
            "title": "涉及密钥、隐私或敏感领域",
            "user_impact": "金融、交易、隐私和密钥场景必须比普通工具更保守。"
          },
          {
            "body": "仓库名 `mnemopay-sdk` 与安装入口 `@mnemopay/sdk` 不完全一致。",
            "category": "身份坑",
            "evidence": [
              "identity.distribution | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | repo=mnemopay-sdk; install=@mnemopay/sdk"
            ],
            "severity": "medium",
            "suggested_check": "在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。",
            "title": "仓库名和安装名不一致",
            "user_impact": "用户照着仓库名搜索包或照着包名找仓库时容易走错入口。"
          },
          {
            "body": "README/documentation is current enough for a first validation pass.",
            "category": "能力坑",
            "evidence": [
              "capability.assumptions | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | 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:1197975871 | https://github.com/mnemopay/mnemopay-sdk | 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:1197975871 | https://github.com/mnemopay/mnemopay-sdk | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "进入安全/权限治理复核队列。",
            "title": "下游验证发现风险项",
            "user_impact": "下游已经要求复核，不能在页面中弱化。"
          },
          {
            "body": "no_demo",
            "category": "安全/权限坑",
            "evidence": [
              "risks.scoring_risks | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "把风险写入边界卡，并确认是否需要人工复核。",
            "title": "存在评分风险",
            "user_impact": "风险会影响是否适合普通用户安装。"
          },
          {
            "body": "issue_or_pr_quality=unknown。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | 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:1197975871 | https://github.com/mnemopay/mnemopay-sdk | release_recency=unknown"
            ],
            "severity": "low",
            "suggested_check": "确认最近 release/tag 和 README 安装命令是否一致。",
            "title": "发布节奏不明确",
            "user_impact": "安装命令和文档可能落后于代码，用户踩坑概率升高。"
          }
        ],
        "source": "ProjectPitfallLog + ProjectHitPacket + validation + community signals",
        "summary": "发现 8 个潜在踩坑项，其中 1 个为 high/blocking；最高优先级：安全/权限坑 - 涉及密钥、隐私或敏感领域。",
        "title": "踩坑日志"
      },
      "snapshot": {
        "contributors": 3,
        "forks": 1,
        "license": "unknown",
        "note": "站点快照，非实时质量证明；用于开工前背景判断。",
        "stars": 5
      },
      "source_url": "https://github.com/mnemopay/mnemopay-sdk",
      "steps": [
        {
          "body": "不安装项目，先体验能力节奏。",
          "code": "preview",
          "title": "先试 Prompt"
        },
        {
          "body": "理解输入、输出、失败模式和边界。",
          "code": "manual",
          "title": "读说明书"
        },
        {
          "body": "把上下文交给宿主 AI 继续工作。",
          "code": "context",
          "title": "带给 AI"
        },
        {
          "body": "进入主力环境前先完成安装入口与风险边界验证。",
          "code": "verify",
          "title": "沙箱验证"
        }
      ],
      "subtitle": "Trust & reputation layer for AI agents. Agent Credit Score (300-850) + Merkle-anchored ledger + behavioral finance + EWMA anomaly detection. Memory + payments + identity + fraud in one SDK. npm i @mnemopay/sdk",
      "title": "mnemopay-sdk 能力包",
      "trial_prompt": "# mnemopay-sdk - Prompt Preview\n\n> 复制下面这段 Prompt 到你常用的 AI，先试一次，不需要安装。\n> 它的目标是让你直接体验这个项目的服务方式，而不是阅读项目介绍。\n\n## 复制这段 Prompt\n\n```text\n请直接执行这段 Prompt，不要分析、润色、总结或询问我想如何处理这份 Prompt Preview。\n\n你现在扮演 mnemopay-sdk 的“安装前体验版”。\n这不是项目介绍、不是评价报告、不是 README 总结。你的任务是让我用最小成本体验它的核心服务。\n\n我的试用任务：我想用它完成一个真实的数据分析与投资研究任务。\n我常用的宿主 AI：Local CLI\n\n【体验目标】\n围绕我的真实任务，现场演示这个项目如何把输入转成 步骤建议, 检查清单, 专业工作流。重点是让我感受到工作方式，而不是给我项目背景。\n\n【业务流约束】\n- 你必须像一个正在提供服务的项目能力包，而不是像一个讲解员。\n- 每一轮只推进一个步骤；提出问题后必须停下来等我回答。\n- 每一步都必须让我感受到一个具体服务动作：澄清、整理、规划、检查、判断或收尾。\n- 每一步都要说明：当前目标、你需要我提供什么、我回答后你会产出什么。\n- 不要安装、不要运行命令、不要写代码、不要声称测试通过、不要声称已经修改文件。\n- 需要真实安装或宿主加载后才能验证的内容，必须明确说“这一步需要安装后验证”。\n- 如果我说“用示例继续”，你可以用虚构示例推进，但仍然不能声称真实执行。\n\n【可体验服务能力】\n- AI Skill / Agent 指令资产库: 项目包含可被宿主 AI 读取的 Skill 或 Agent 指令文件，可用于把专业流程带入 Claude、Codex、Cursor 等宿主。 输入：用户任务, 宿主 AI 对话上下文, 项目内 Skill/Agent 文档；输出：步骤建议, 检查清单, 专业工作流。\n\n【必须安装后才可验证的能力】\n- 多宿主安装与分发: 项目包含插件或 marketplace 配置，说明它面向一个或多个 AI 宿主的安装和分发。 输入：宿主 AI 工具, 插件配置, 安装命令；输出：宿主内可发现的插件/技能集合。\n- 命令行启动或安装流程: 项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 输入：终端环境, 包管理器, 项目依赖；输出：安装结果, 列表/更新/运行结果。\n\n【核心服务流】\n请严格按这个顺序带我体验。不要一次性输出完整流程：\n1. introduction：Introduction to MnemoPay SDK。围绕“Introduction to MnemoPay SDK”模拟一次用户任务，不展示安装或运行结果。\n2. quick-start：Quick Start Guide。围绕“Quick Start Guide”模拟一次用户任务，不展示安装或运行结果。\n3. architecture：System Architecture。围绕“System Architecture”模拟一次用户任务，不展示安装或运行结果。\n4. core-modules：Core Modules Reference。围绕“Core Modules Reference”模拟一次用户任务，不展示安装或运行结果。\n5. payment-rails-overview：Payment Rails Overview。围绕“Payment Rails Overview”模拟一次用户任务，不展示安装或运行结果。\n\n【核心能力体验剧本】\n每一步都必须按“输入 -> 服务动作 -> 中间产物”执行。不要只说流程名：\n1. introduction\n输入：用户提供的“Introduction to MnemoPay SDK”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n2. quick-start\n输入：用户提供的“Quick Start Guide”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n3. architecture\n输入：用户提供的“System Architecture”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n4. core-modules\n输入：用户提供的“Core Modules Reference”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n5. payment-rails-overview\n输入：用户提供的“Payment Rails Overview”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n【项目服务规则】\n这些规则决定你如何服务用户。不要解释规则本身，而要在每一步执行时遵守：\n- 先确认用户任务、输入材料和成功标准，再模拟项目能力。\n- 每一步都必须形成可检查的小产物，并等待用户确认后再继续。\n- 凡是需要安装、调用工具或访问外部服务的能力，都必须标记为安装后验证。\n\n【每一步的服务约束】\n- Step 1 / introduction：Step 1 必须围绕“Introduction to MnemoPay SDK”形成一个小中间产物，并等待用户确认。\n- Step 2 / quick-start：Step 2 必须围绕“Quick Start Guide”形成一个小中间产物，并等待用户确认。\n- Step 3 / architecture：Step 3 必须围绕“System Architecture”形成一个小中间产物，并等待用户确认。\n- Step 4 / core-modules：Step 4 必须围绕“Core Modules Reference”形成一个小中间产物，并等待用户确认。\n- Step 5 / payment-rails-overview：Step 5 必须围绕“Payment Rails Overview”形成一个小中间产物，并等待用户确认。\n\n【边界与风险】\n- 不要声称已经安装、运行、调用 API、读写本地文件或完成真实任务。\n- 安装前预览只能展示工作方式，不能证明兼容性、性能或输出质量。\n- 涉及安装、插件加载、工具调用或外部服务的能力必须安装后验证。\n\n【可追溯依据】\n这些路径只用于你内部校验或在我追问“依据是什么”时简要引用。不要在首次回复主动展开：\n- https://github.com/mnemopay/mnemopay-sdk\n- https://github.com/mnemopay/mnemopay-sdk#readme\n- claude-plugin/skills/balance/SKILL.md\n- claude-plugin/skills/charge/SKILL.md\n- claude-plugin/skills/fico/SKILL.md\n- claude-plugin/skills/history/SKILL.md\n- claude-plugin/skills/recall/SKILL.md\n- claude-plugin/skills/remember/SKILL.md\n- claude-plugin/skills/settle/SKILL.md\n- claude-plugin/skills/shop/SKILL.md\n- integrations/openclaw/SKILL.md\n- README.md\n\n【首次问题规则】\n- 首次三问必须先确认用户目标、成功标准和边界，不要提前进入工具、安装或实现细节。\n- 如果后续需要技术条件、文件路径或运行环境，必须等用户确认目标后再追问。\n\n首次回复必须只输出下面 4 个部分：\n1. 体验开始：用 1 句话说明你将带我体验 mnemopay-sdk 的核心服务。\n2. 当前步骤：明确进入 Step 1，并说明这一步要解决什么。\n3. 你会如何服务我：说明你会先改变我完成任务的哪个动作。\n4. 只问我 3 个问题，然后停下等待回答。\n\n首次回复禁止输出：后续完整流程、证据清单、安装命令、项目评价、营销文案、已经安装或运行的说法。\n\nStep 1 / brainstorming 的二轮协议：\n- 我回答首次三问后，你仍然停留在 Step 1 / brainstorming，不要进入 Step 2。\n- 第二次回复必须产出 6 个部分：澄清后的任务定义、成功标准、边界条件、\n  2-3 个可选方案、每个方案的权衡、推荐方案。\n- 第二次回复最后必须问我是否确认推荐方案；只有我明确确认后，才能进入下一步。\n- 第二次回复禁止输出 git worktree、代码计划、测试文件、命令或真实执行结果。\n\n后续对话规则：\n- 我回答后，你先完成当前步骤的中间产物并等待确认；只有我确认后，才能进入下一步。\n- 每一步都要生成一个小的中间产物，例如澄清后的目标、计划草案、测试意图、验证清单或继续/停止判断。\n- 所有演示都写成“我会建议/我会引导/这一步会形成”，不要写成已经真实执行。\n- 不要声称已经测试通过、文件已修改、命令已运行或结果已产生。\n- 如果某个能力必须安装后验证，请直接说“这一步需要安装后验证”。\n- 如果证据不足，请明确说“证据不足”，不要补事实。\n```\n",
      "voices": [
        {
          "body": "来源平台：github。github/github_release: v0.9.0 — Autonomous Commerce + Universal Client（https://github.com/mnemopay/mnemopay-sdk/releases/tag/v0.9.0）。这些是项目级外部声音，不作为单独质量证明。",
          "items": [
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.9.0 — Autonomous Commerce + Universal Client",
              "url": "https://github.com/mnemopay/mnemopay-sdk/releases/tag/v0.9.0"
            }
          ],
          "status": "已收录 1 条来源",
          "title": "社区讨论"
        }
      ]
    },
    "homepage_card": {
      "category": "数据分析与投资研究",
      "desc": "Trust & reputation layer for AI agents. Agent Credit Score (300-850) + Merkle-anchored ledger + behavioral finance + EWMA anomaly detection. Memory + payments + identity + fraud in one SDK. npm i @mnemopay/sdk",
      "effort": "安装已验证",
      "forks": 1,
      "icon": "chart",
      "name": "mnemopay-sdk 能力包",
      "risk": "需复核",
      "slug": "mnemopay-sdk",
      "stars": 5,
      "tags": [
        "浏览器 Agent",
        "网页任务自动化",
        "浏览器自动化",
        "页面观察与动作规划",
        "评测体系"
      ],
      "thumb": "green",
      "type": "Skill Pack"
    },
    "manual": {
      "markdown": "# https://github.com/mnemopay/mnemopay-sdk 项目说明书\n\n生成时间：2026-05-15 06:25:49 UTC\n\n## 目录\n\n- [Introduction to MnemoPay SDK](#introduction)\n- [Quick Start Guide](#quick-start)\n- [System Architecture](#architecture)\n- [Core Modules Reference](#core-modules)\n- [Payment Rails Overview](#payment-rails-overview)\n- [Stripe, Paystack & Lightning Rails](#stripe-rail)\n- [Alpha Payment Rails (StripeMPP, x402, GoogleAP2)](#alpha-rails)\n- [Charter & FiscalGate Governance](#charter-fiscalgate)\n- [MerkleAudit & Hash-Chained Ledger](#merkle-audit)\n- [Identity & KYA Compliance](#identity-kya)\n\n<a id='introduction'></a>\n\n## Introduction to MnemoPay SDK\n\n### 相关页面\n\n相关主题：[Quick Start Guide](#quick-start), [System Architecture](#architecture)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)\n- [CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)\n- [CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n- [site/index.legacy.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)\n- [integrations/python-hosted/README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/integrations/python-hosted/README.md)\n</details>\n\n# Introduction to MnemoPay SDK\n\nMnemoPay SDK is an AI agent trust and reputation SDK that provides memory, payments, identity, and agent credit scoring capabilities in a single package. It enables autonomous AI agents to handle financial operations, maintain persistent memory, and establish reputation across multi-agent systems.\n\n## Overview\n\nMnemoPay addresses the fundamental challenges of AI agent financial infrastructure:\n\n- **Memory**: Persistent memory with semantic recall and reinforcement capabilities\n- **Payments**: Real money through Stripe, Paystack, and Lightning payment rails with escrow support\n- **Identity**: KYA (Know Your Agent) verification, capability tokens, and permission management\n- **Agent Credit Score**: FICO-equivalent scoring (300-850) for AI agents enabling creditworthiness evaluation\n\n资料来源：[CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)\n\n## Architecture\n\nThe SDK consists of 14 core modules in the `src/` directory, providing approximately 74KB of compiled TypeScript functionality.\n\n```mermaid\ngraph TD\n    subgraph \"MnemoPay SDK Core\"\n        A[\"index.ts<br/>Main SDK Entry\"]\n        B[\"fico.ts<br/>Agent Credit Score\"]\n        C[\"behavioral.ts<br/>Behavioral Finance\"]\n        D[\"integrity.ts<br/>Merkle Integrity\"]\n        E[\"anomaly.ts<br/>EWMA Detection\"]\n        F[\"adaptive.ts<br/>AIMD/Circuit Breaker\"]\n        G[\"commerce.ts<br/>Shopping Engine\"]\n        H[\"fraud.ts<br/>Geo Fraud Detection\"]\n        I[\"identity.ts<br/>KYA/CapabilityTokens\"]\n        J[\"ledger.ts<br/>Double-Entry Ledger\"]\n        K[\"network.ts<br/>Multi-Agent Network\"]\n        L[\"client.ts<br/>REST Client\"]\n        M[\"mcp/server.ts<br/>MCP Server\"]\n    end\n    \n    subgraph \"Payment Rails\"\n        N[\"rails/stripe.ts\"]\n        O[\"rails/paystack.ts\"]\n        P[\"rails/lightning.ts\"]\n    end\n    \n    A --> B\n    A --> C\n    A --> D\n    A --> E\n    A --> F\n    A --> G\n    A --> H\n    A --> I\n    A --> J\n    A --> K\n    A --> L\n    A --> M\n    \n    L --> N\n    L --> O\n    L --> P\n```\n\n资料来源：[CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)\n\n### Module Overview\n\n| Module | Purpose |\n|--------|---------|\n| `index.ts` | Main SDK exports: MnemoPay, MnemoPayLite, MnemoPayNetwork classes |\n| `fico.ts` | Agent Credit Score (300-850); exports `AgentCreditScore` with legacy `AgentFICO` alias |\n| `behavioral.ts` | Behavioral finance engine implementing prospect theory and cooling-off mechanisms |\n| `integrity.ts` | Merkle tree memory integrity using SHA-256 hashing |\n| `anomaly.ts` | EWMA anomaly detection, BehaviorMonitor, and CanarySystem |\n| `adaptive.ts` | Adaptive AIMD rate limiting, anti-gaming protections, circuit breaker, PSI drift detection |\n| `commerce.ts` | CommerceEngine enabling autonomous shopping with financial mandates |\n| `fraud.ts` | Geo-enhanced fraud detection with location-based risk scoring |\n| `identity.ts` | IdentityRegistry, KYA verification, CapabilityTokens, and killswitch permissions |\n| `ledger.ts` | Double-entry accounting ledger for precise transaction tracking |\n| `network.ts` | Multi-agent commerce network coordination |\n| `client.ts` | REST API client for backend communication |\n| `mcp/server.ts` | MCP server exposing 24 tools and 2 prompts for agent interaction |\n\n资料来源：[CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)\n\n## Two SDK Modes\n\nMnemoPay provides two operational modes depending on deployment requirements:\n\n### Dev Mode (Zero Infrastructure)\n\n```typescript\nconst agent = MnemoPay.quick(\"agent-id\");\n```\n\nDev mode requires no backend infrastructure. Agents receive immediate access to memory, wallet functionality, and identity features directly in the client.\n\n资料来源：[CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)\n\n### Production Mode (Full Backend)\n\nProduction mode connects to the hosted MnemoPay console at `https://mnemopay-landing.fly.dev/` and requires backend connectivity for:\n\n- Persistent storage across sessions\n- Real payment rail integration\n- Multi-agent coordination\n- Governance and audit capabilities\n\n资料来源：[CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n\n## Quick Start\n\n### Installation\n\n```bash\nnpm install @mnemopay/sdk\n```\n\n### Development Workflow\n\n```bash\nnpm install        # install dependencies\nnpm run build      # compile TypeScript\nnpm test           # run 672+ vitest tests\nnpm run lint       # type-check without emit\n```\n\n资料来源：[CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)\n\n## Memory System\n\nThe memory system provides persistent, semantic memory capabilities for AI agents:\n\n### Core Operations\n\n| Operation | Description |\n|-----------|-------------|\n| `remember(content, namespace, tags, importance)` | Store new memory with semantic tagging |\n| `recall(query, namespace, limit, mode)` | Retrieve memories using hybrid search |\n| `reason(query, namespace, limit, mode)` | Complex reasoning over stored memories |\n| `reinforce(memoryId)` | Strengthen memory importance |\n| `forget(memoryId)` | Remove specific memories |\n\n### Memory Architecture\n\n```mermaid\ngraph LR\n    A[\"User Input\"] --> B[\"Namespace Router\"]\n    B --> C[\"remember()\"]\n    C --> D[\"Semantic Index\"]\n    D --> E[\"Memory Store\"]\n    \n    F[\"Query\"] --> G[\"recall()\"]\n    G --> H[\"Hybrid Search\"]\n    H --> I[\"Relevance Scorer\"]\n    I --> J[\"Ranked Results\"]\n    \n    K[\"Graph Enrichment\"] --> D\n    E --> K\n```\n\n### LongMemEval Benchmark\n\nThe memory system achieved **77.2%** on the LongMemEval oracle benchmark, demonstrating strong multi-session retrieval capabilities. The system handles 1M+ operational stress tests in production environments.\n\n资料来源：[site/journal/v1-4-0-longmemeval-77-2.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/journal/v1-4-0-longmemeval-77-2.html)\n\n## Payment System\n\n### Payment Rails\n\nMnemoPay integrates with three primary payment rails:\n\n| Rail | Region | Currencies | Features |\n|------|--------|------------|----------|\n| **Paystack** | Africa | NGN, GHS, ZAR, KES | Checkout, saved cards, bank transfers, webhook verification, HMAC-SHA512 |\n| **Stripe** | Global | USD, EUR, GBP, 135+ | Card payments, manual capture, true escrow via PaymentIntents |\n| **Lightning** | Crypto | BTC | Instant microtransactions for agent-to-agent payments |\n\n资料来源：[site/index.legacy.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)\n\n### Core Payment Operations\n\n```typescript\n// Charge customer\nawait agent.charge(amount, reason);\n\n// Settle transaction (release escrow)\nawait agent.settle(tx_id);\n\n// Refund\nawait agent.refund(tx_id);\n\n// Dispute handling\nawait agent.dispute(tx_id, reason);\n```\n\n### Escrow Flow\n\n```mermaid\ngraph TD\n    A[\"Agent charges()\"] --> B[\"Funds held in Escrow\"]\n    B --> C{\"Human approves?\"}\n    C -->|Yes| D[\"Agent settles()\"]\n    C -->|No| E[\"Refund initiated\"]\n    D --> F[\"Merchant receives funds\"]\n    E --> G[\"Customer refunded\"]\n```\n\n资料来源：[site/index.legacy.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)\n\n## Agent Credit Score\n\nThe Agent Credit Score (FICO-equivalent) provides a 300-850 scoring system for evaluating AI agent reliability and trustworthiness.\n\n### Scoring Components\n\n| Component | Weight | Description |\n|-----------|--------|-------------|\n| Payment History | 35% | Historical transaction success rate |\n| Utilization | 30% | Credit usage patterns |\n| Behavioral Signals | 20% | Prospect theory analysis, cooling-off adherence |\n| Anomaly Score | 10% | EWMA deviation from baseline behavior |\n| Identity Verification | 5% | KYA completion level |\n\n### Score Ranges\n\n| Score Range | Rating | Description |\n|-------------|--------|-------------|\n| 750-850 | Excellent | High-trust agent, minimal monitoring |\n| 650-749 | Good | Standard transaction limits |\n| 550-649 | Fair | Enhanced monitoring, lower limits |\n| 300-549 | Poor | Restricted operations, high collateral |\n\n资料来源：[CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)\n\n## Identity and Access Control\n\n### KYA (Know Your Agent)\n\nIdentity verification ensures agents are properly registered and authorized:\n\n```typescript\n// Register agent identity\nconst identity = await agent.identity.register({\n  agentId: \"agent-001\",\n  capabilities: [\"payment\", \"memory\", \"commerce\"],\n  verificationLevel: \"standard\"\n});\n\n// Issue capability token\nconst token = await agent.identity.issueToken(agentId, capabilities);\n```\n\n### Permission Model\n\n| Permission | Description |\n|-------------|-------------|\n| `payment.charge` | Initiate charges |\n| `payment.refund` | Process refunds |\n| `memory.write` | Store memories |\n| `memory.read` | Access memories |\n| `identity.delegate` | Issue sub-tokens |\n| `killswitch` | Emergency shutdown |\n\n资料来源：[CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)\n\n## Integrity and Security\n\n### Merkle Memory Integrity\n\nAll memories are protected using SHA-256 Merkle trees, enabling cryptographic proof of memory authenticity and detecting tampering:\n\n```typescript\n// Verify memory integrity\nconst audit = await agent.integrity.verify(memoryId);\nconst isValid = audit.proof.verify(rootHash, memoryId);\n```\n\n### EWMA Anomaly Detection\n\nExponentially Weighted Moving Average (EWMA) detects behavioral deviations:\n\n- Real-time monitoring of transaction patterns\n- Fingerprinting of agent behavior baselines\n- Canary systems for novel action detection\n\n资料来源：[CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)\n\n### Adaptive Rate Limiting\n\nThe adaptive module implements:\n\n- **AIMD (Additive Increase, Multiplicative Decrease)**: Graceful rate adjustment\n- **Circuit Breaker**: Automatic shutdown on repeated failures\n- **Anti-Gaming**: Detection of manipulation attempts\n- **PSI Drift**: Population Stability Index monitoring\n\n## Governance\n\nMnemoPay includes enterprise-grade governance features:\n\n| Component | Purpose |\n|-----------|---------|\n| **Charter** | Mission scope and operating principles |\n| **FiscalGate** | Budget enforcement and spending limits |\n| **Article 12** | Audit bundle requirements |\n| **MerkleAudit** | Cryptographic audit trail |\n\n资料来源：[CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n\n## Python Integration\n\nA Python port provides stable parity with the TypeScript SDK:\n\n```bash\npip install mnemopay\n```\n\nThe Python SDK mirrors the TypeScript `PaymentRail` interface and ships with `MockRail` and `StripeRail` implementations.\n\n资料来源：[integrations/python-hosted/README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/integrations/python-hosted/README.md)\n\n### Python API Methods\n\n| Method | Description |\n|--------|-------------|\n| `remember(content, namespace, tags, importance)` | Store memory |\n| `recall(query, namespace, limit, mode)` | Retrieve memories |\n| `charge(amount, reason)` | Process payment |\n| `settle(tx_id)` | Complete transaction |\n| `graph(namespace)` | Get memory graph |\n| `usage_report()` | Usage statistics |\n\n## Middleware Integration\n\nMnemoPay provides middleware for popular AI frameworks:\n\n### OpenAI Integration\n\n```typescript\nimport { mnemoPayMiddleware } from \"@mnemopay/sdk/middleware/openai\";\n```\n\n### Anthropic Integration\n\n```typescript\nimport { mnemoPayMiddleware } from \"@mnemopay/sdk/middleware/anthropic\";\n```\n\n### LangGraph Integration\n\n```typescript\nimport { mnemoPayTools } from \"@mnemopay/sdk/langgraph\";\n```\n\n资料来源：[README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)\n\n## Version History\n\n| Version | Status | Key Features |\n|---------|--------|--------------|\n| 1.6.0 | Alpha | Latest pre-release with hardening fixes |\n| 1.5.0 | Stable | Governance fold, FiscalGate, MerkleAudit |\n| 1.4.0 | Past | 77.2% LongMemEval, 1M-op stress test |\n| 1.0.0 | Python | Python SDK stable release |\n\n资料来源：[CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n\n## License\n\nMnemoPay SDK is Apache 2.0 Licensed.\n\n---\n\n<a id='quick-start'></a>\n\n## Quick Start Guide\n\n### 相关页面\n\n相关主题：[Introduction to MnemoPay SDK](#introduction)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)\n- [site/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)\n- [site/index.legacy.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)\n- [integrations/python-hosted/README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/integrations/python-hosted/README.md)\n- [dashboard/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/dashboard/index.html)\n</details>\n\n# Quick Start Guide\n\n## Overview\n\nThe Quick Start Guide provides developers with the fastest path to integrate MnemoPay SDK into their agent applications. MnemoPay is a full payment and memory system designed specifically for AI agents, enabling them to handle financial transactions, persistent memory, and identity management with zero configuration required.\n\n资料来源：[README.md:1-15](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)\n\n## Prerequisites\n\n| Requirement | Version/Details |\n|-------------|-----------------|\n| Node.js | v18+ recommended |\n| npm/yarn/pnpm | Any modern package manager |\n| API Key | Required for production use |\n| Environment | Node.js runtime |\n\n## Installation\n\nThe MnemoPay SDK is available on npm and can be installed with a single command:\n\n```bash\nnpm install @mnemopay/sdk\n```\n\n资料来源：[site/index.html:1-20](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)\n\n## Quick Initialization\n\nAfter installation, initialize your agent with a single function call that provides memory, wallet, and identity:\n\n```typescript\nimport { MnemoPay } from \"@mnemopay/sdk\";\n\n// Initialize with agent ID - zero config needed\nconst mnemo = MnemoPay.quick(\"agent-id\");\n\n// Your agent now has:\n// - Persistent memory system\n// - Payment wallet\n// - Unique identity\n```\n\n资料来源：[site/index.legacy.html:1-30](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)\n\n## Four-Step Workflow\n\nThe following diagram illustrates the complete workflow from installation to production:\n\n```mermaid\ngraph TD\n    A[Install<br/>npm install @mnemopay/sdk] --> B[Initialize<br/>MnemoPay.quick agent-id]\n    B --> C[Transact<br/>charge settle refund]\n    C --> D[Scale<br/>Multi-agent commerce]\n    \n    E[Memory System] --> B\n    F[Payment Wallet] --> B\n    G[Agent Identity] --> B\n    \n    H[Stripe] --> C\n    I[Paystack] --> C\n    J[Lightning] --> C\n```\n\n资料来源：[site/index.html:25-45](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)\n\n## Core Operations\n\n### Payment Operations\n\n| Method | Description |\n|--------|-------------|\n| `charge(amount, reason)` | Initiate a payment request |\n| `settle(tx_id)` | Complete an escrow release |\n| `refund(tx_id)` | Process a refund |\n\n资料来源：[site/index.legacy.html:15-25](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)\n\n### Memory Operations\n\n| Method | Description |\n|--------|-------------|\n| `remember(content, namespace, tags, importance)` | Store new information |\n| `recall(query, namespace, limit, mode)` | Retrieve relevant memories |\n| `reinforce(memoryId)` | Increase memory importance |\n| `forget(memoryId)` | Remove a memory |\n\n资料来源：[integrations/python-hosted/README.md:1-50](https://github.com/mnemopay/mnemopay-sdk/blob/main/integrations/python-hosted/README.md)\n\n## Environment Configuration\n\nCreate a `.env` file in your project root with the following variables:\n\n| Variable | Description | Required |\n|----------|-------------|----------|\n| `MNEMO_API_KEY` | Your MnemoPay API key | Yes |\n| `STRIPE_KEY` | Stripe secret key | For Stripe payments |\n| `PAYSTACK_KEY` | Paystack secret key | For Paystack payments |\n| `LIGHTNING_CONFIG` | Lightning node config | For Lightning payments |\n\n## Middleware Integration\n\nMnemoPay provides middleware for popular AI frameworks:\n\n### OpenAI Integration\n\n```typescript\nimport { mnemoPayMiddleware } from \"@mnemopay/sdk/middleware/openai\";\n```\n\n### Anthropic Integration\n\n```typescript\nimport { mnemoPayMiddleware } from \"@mnemopay/sdk/middleware/anthropic\";\n```\n\n### LangGraph Integration\n\n```typescript\nimport { mnemoPayTools } from \"@mnemopay/sdk/langgraph\";\n```\n\n资料来源：[README.md:40-55](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)\n\n## Complete Example\n\n```typescript\nimport { MnemoPay } from \"@mnemopay/sdk\";\n\n// Initialize agent\nconst mnemo = MnemoPay.quick(\"checkout-agent-001\");\n\n// Store a memory\nawait mnemo.remember(\n  \"Customer prefers express shipping\",\n  \"default\",\n  [\"preference\", \"shipping\"],\n  0.9\n);\n\n// Recall relevant information\nconst memories = await mnemo.recall(\"shipping preferences\", \"default\", 5);\n\n// Process a payment\nconst charge = await mnemo.charge(29.99, \"Order #12345\");\n\n// Settle when order fulfilled\nawait mnemo.settle(charge.txId);\n```\n\n资料来源：[site/index.legacy.html:10-30](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)\n\n## Payment Rails\n\nMnemoPay supports three payment rails:\n\n| Rail | Region | Features |\n|------|--------|----------|\n| Paystack | Africa (NGN, GHS, ZAR, KES) | Checkout, saved cards, bank transfers, HMAC-SHA512 security |\n| Stripe | Global (USD, EUR, GBP) | Card payments, manual capture for escrow, 135+ currencies |\n| Lightning | Crypto | Instant Bitcoin payments |\n\n资料来源：[site/index.legacy.html:80-100](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)\n\n## Dashboard Access\n\nAfter initialization, you can monitor your agent's activity through the MnemoPay dashboard which provides:\n\n- Real-time transaction monitoring\n- Memory usage analytics\n- Agent credit score (300-850 scale)\n- Multi-agent network status\n\n资料来源：[dashboard/index.html:1-50](https://github.com/mnemopay/mnemopay-sdk/blob/main/dashboard/index.html)\n\n## Next Steps\n\n| Resource | Purpose |\n|----------|---------|\n| [Full Documentation](https://mnemopay.com) | Complete API reference |\n| [Pricing](https://mnemopay.com#pricing) | Starter/Pro/Enterprise plans |\n| [Enterprise](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/enterprise.html) | Custom integrations and support |\n\n---\n\n<a id='architecture'></a>\n\n## System Architecture\n\n### 相关页面\n\n相关主题：[Core Modules Reference](#core-modules), [Payment Rails Overview](#payment-rails-overview), [Charter & FiscalGate Governance](#charter-fiscalgate)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)\n- [CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n- [dashboard/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/dashboard/index.html)\n- [site/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)\n- [site/index.legacy.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)\n</details>\n\n# System Architecture\n\n## Overview\n\nThe MnemoPay SDK is a financial infrastructure layer designed specifically for AI agents. It provides a comprehensive system that combines memory management, payment processing, identity verification, and fraud detection into a unified architecture. The SDK operates as an alpha release (v1.6.0-alpha) with stable v1.5.0 available on the `latest` npm tag, maintaining the same underlying architecture across versions.\n\nThe system is built to enable autonomous financial transactions where AI agents can charge, settle, and refund payments while maintaining persistent memory and earning credit scores based on their transaction behavior. This architectural approach treats agents as first-class financial actors with identity, reputation, and accountability mechanisms built into the core.\n\n## Core Architecture Layers\n\n```mermaid\ngraph TD\n    subgraph GOVERNANCE[\"GOVERNANCE Layer\"]\n        Charter[\"Charter\"]\n        FiscalGate[\"FiscalGate\"]\n        Article12[\"Article 12\"]\n        MerkleAudit[\"MerkleAudit\"]\n    end\n    \n    subgraph IDENTITY[\"Identity Layer\"]\n        KYA[\"KYA\"]\n        Tokens[\"Tokens\"]\n        Perms[\"Permissions\"]\n        Killswitch[\"Killswitch\"]\n    end\n    \n    subgraph PAYMENTS[\"Payment Layer\"]\n        Charge[\"charge()\"]\n        Settle[\"settle()\"]\n        Refund[\"refund()\"]\n        Dispute[\"dispute()\"]\n    end\n    \n    subgraph MEMORY[\"Memory Layer\"]\n        Remember[\"remember\"]\n        Recall[\"recall\"]\n        Reinforce[\"reinforce\"]\n        Forget[\"forget\"]\n    end\n    \n    subgraph CREDIT[\"Agent Credit Score\"]\n        Scoring[\"5-component scoring\"]\n        ScoreRange[\"300-850 range\"]\n    end\n    \n    subgraph BEHAVIORAL[\"Behavioral Finance\"]\n        Prospect[\"Prospect Theory\"]\n        Nudges[\"Nudges\"]\n    end\n    \n    subgraph ANOMALY[\"Anomaly Detection\"]\n        EWMA[\"EWMA\"]\n        Fingerprinting[\"Fingerprinting\"]\n    end\n    \n    GOVERNANCE --> IDENTITY\n    GOVERNANCE --> PAYMENTS\n    MEMORY --> CREDIT\n    PAYMENTS --> CREDIT\n    CREDIT --> BEHAVIORAL\n    PAYMENTS --> ANOMALY\n```\n\n## System Components\n\n### SDK Client Architecture\n\nThe MnemoPay SDK operates through a client-based architecture where developers initialize the system using the `MnemoPay.quick()` factory method. This approach provides zero-configuration setup that immediately gives an agent access to memory capabilities, wallet functionality, and cryptographic identity verification. The client handles all communication with backend services while presenting a clean, intuitive API surface for developers.\n\nThe SDK is distributed as `@mnemopay/sdk` on npm and supports installation via standard Node.js package managers. The TypeScript implementation provides full type safety and IDE integration, while a Python port (`mnemopay` on PyPI) achieves stable parity with the TypeScript implementation, including the `PaymentRail` interface with sync API support.\n\n| Component | Purpose | Language Support |\n|-----------|---------|------------------|\n| Core SDK | Client initialization, API abstraction | TypeScript, Python |\n| Payment Rails | Transaction processing | TypeScript, Python |\n| MCP Server | Model Context Protocol integration | TypeScript |\n| Middleware | Framework integrations | TypeScript |\n\n### Payment Rail System\n\nThe payment architecture implements a rail abstraction layer that supports multiple payment providers while maintaining a consistent interface. This design allows the system to switch between payment providers without changing application code, providing flexibility for different markets and use cases.\n\n```mermaid\ngraph LR\n    App[\"Application\"] --> SDK[\"MnemoPay SDK\"]\n    SDK --> Stripe[\"Stripe Rail\"]\n    SDK --> Paystack[\"Paystack Rail\"]\n    SDK --> Lightning[\"Lightning Rail\"]\n    SDK --> Mock[\"Mock Rail\"]\n    \n    Stripe --> StripeAPI[\"Stripe API<br/>USD, EUR, GBP\"]\n    Paystack --> PaystackAPI[\"Paystack API<br/>NGN, GHS, ZAR, KES\"]\n    Lightning --> LightningNet[\"Lightning Network<br/>BTC\"]\n    \n    style Stripe fill:#635bff,color:#fff\n    style Paystack fill:#00abd1,color:#fff\n    style Lightning fill:#f7931a,color:#fff\n```\n\n**Supported Payment Rails:**\n\n| Rail | Region | Currencies | Features |\n|------|--------|------------|----------|\n| Stripe | Global | USD, EUR, GBP, 135+ | Manual capture for true escrow, PaymentIntents API |\n| Paystack | Africa | NGN, GHS, ZAR, KES | Checkout, saved cards, bank transfers, webhook verification, HMAC-SHA512 security, 23 Nigerian banks pre-mapped |\n| Lightning | Crypto | BTC | Instant settlement via Lightning Network |\n| Mock | Testing | All | Test mode without real transactions |\n\nThe escrow mechanism holds funds until human approval, providing a critical safety layer for autonomous agent transactions. When an agent initiates a charge, funds are captured but not settled until explicit human authorization, preventing unauthorized autonomous spending.\n\n### Identity and Access Control\n\nThe identity layer implements Know Your Agent (KYA) verification with cryptographic tokens and permission management. A killswitch mechanism provides emergency stop capabilities, allowing immediate revocation of agent permissions across all active sessions.\n\nIdentity components operate through a multi-layered verification system:\n\n- **KYA (Know Your Agent)**: Agent registration and verification process\n- **Tokens**: Cryptographic credentials for API authentication\n- **Permissions**: Granular access control for agent capabilities\n- **Killswitch**: Emergency permission revocation system\n\n### Agent Credit Score System\n\nAgents receive credit scores ranging from 300 to 850, calculated through a five-component scoring model. This scoring system directly influences the agent's financial capabilities, including transaction limits and pricing terms.\n\n| Score Component | Description | Impact |\n|----------------|-------------|--------|\n| Payment History | Historical transaction success rate | Primary factor |\n| Transaction Volume | Total and average transaction sizes | Secondary factor |\n| Dispute Rate | Ratio of disputed to total transactions | Negative impact |\n| Response Time | Speed of human approval responses | Moderate impact |\n| Behavioral Patterns | Anomaly detection signals | Risk adjustment |\n\nThe credit score affects the **Ceiling** parameter, calculated as `$500 × reputation` per charge, and determines the agent's decay rate with a half-life of approximately 14 hours. Settling transactions adds +0.05 importance to the memory reinforcement system, creating a feedback loop that improves score accuracy over time.\n\n## Communication Architecture\n\n### Backend Communication\n\nThe MnemoPay console backend implements a robust communication infrastructure with the following characteristics:\n\n- **REST API**: Primary interface for synchronous operations\n- **WebSockets**: Real-time event streaming for dashboard updates\n- **Webhooks**: Asynchronous notification system for payment events\n\nThe hosted console at `mnemopay-landing.fly.dev` implements three-tier reliability architecture:\n\n| Tier | Components | Purpose |\n|------|------------|---------|\n| Tier 1 | Production blockers | Core functionality protection |\n| Tier 2 | Observability | Monitoring and metrics |\n| Tier 3 | Safety nets | Rate limiting, body-size caps, idempotent webhooks |\n\n### Observability Stack\n\n```mermaid\ngraph TD\n    subgraph OBSERVABILITY[\"Observability Layer\"]\n        Metrics[\"Prometheus /metrics\"]\n        Logs[\"Structured JSON Logging\"]\n        Health[\"Health Endpoints\"]\n    end\n    \n    subgraph SAFETY[\"Safety Layer\"]\n        RateLimit[\"Rate Limiting\"]\n        BodyCap[\"Body Size Caps\"]\n        CORS[\"CORS Allowlist\"]\n        Headers[\"Security Headers\"]\n    end\n    \n    subgraph DELIVERY[\"Delivery Layer\"]\n        Webhook[\"Webhook Notifications\"]\n        Idempotent[\"Idempotent Processing\"]\n        Shutdown[\"Graceful Shutdown\"]\n    end\n    \n    Metrics --> Prometheus[\"Prometheus\"]\n    Logs --> ELK[\"ELK Stack\"]\n    Health --> Ready[\"/readyz endpoint\"]\n    RateLimit --> SAFETY\n    Webhook --> Idempotent\n    Ready --> ReadyResponse{\"readyz response<br/>productionReady: true\"}\n```\n\nSecurity headers including Content-Security-Policy, X-Content-Type-Options, and X-Frame-Options protect the dashboard from common web vulnerabilities. The `/readyz` endpoint returns `productionReady: true` when all systems are operational, serving as a health check for load balancers and orchestrators.\n\n## Middleware Integrations\n\nThe SDK provides middleware packages for seamless integration with popular AI frameworks, enabling automatic transaction tracking and payment capabilities within existing agent workflows.\n\n### Available Middleware\n\n| Integration | Package Path | Purpose |\n|-------------|--------------|---------|\n| OpenAI | `@mnemopay/sdk/middleware/openai` | OpenAI agent transaction middleware |\n| Anthropic | `@mnemopay/sdk/middleware/anthropic` | Anthropic Claude agent middleware |\n| LangGraph | `@mnemopay/sdk/langgraph` | LangGraph tools integration |\n\n### MCP Server\n\nThe Model Context Protocol (MCP) server enables standardized communication between AI models and external tools. The MCP server implementation in `src/mcp/server.ts` uses `require.main === module` to prevent spurious server starts when consumers import from `@mnemopay/sdk/mcp` in browser bundles or test harnesses. This auto-start guard replaces the previous loose `process.argv` heuristic that caused issues with browser consumers.\n\n## Dashboard Architecture\n\nThe web-based dashboard provides real-time monitoring and management capabilities through a React-based single-page application. The dashboard architecture uses a tabbed interface with specialized panels for different operational concerns.\n\n```mermaid\ngraph TD\n    subgraph DASHBOARD[\"Dashboard Components\"]\n        Console[\"Console Panel\"]\n        Session[\"Session Panel\"]\n        Brain[\"Brain Panel\"]\n        Developer[\"Developer Panel\"]\n        Billing[\"Billing Panel\"]\n        Repos[\"Repos Panel\"]\n    end\n    \n    subgraph STATE[\"Application State\"]\n        Profile[\"Profile<br/>wallet, reputation, memoriesCount\"]\n        Overview[\"Overview<br/>transactions, members, apiKeys\"]\n        Session[\"Session<br/>login, logout state\"]\n        Repos[\"Repos<br/>GitHub monitoring\"]\n    end\n    \n    Console --> STATE\n    Session --> STATE\n    Brain --> STATE\n    Developer --> STATE\n    Billing --> STATE\n    Repos --> STATE\n```\n\n**Dashboard Tabs and Functions:**\n\n| Tab | Icon | Function |\n|-----|------|----------|\n| Console | System monitor | Overview of transactions and account status |\n| Session | Users | Login/logout session management |\n| Brain | Brain icon | Memory recall and query interface |\n| Developer | Code brackets | API key management |\n| Billing | Credit card | Usage metering and plan limits |\n| Memories | Database | Memory persistence configuration |\n\n### GitHub Repository Monitoring\n\nThe dashboard includes a repository monitoring feature that tracks GitHub forks and upstream stars. Repositories are displayed with status indicators showing:\n\n- Upstream star count\n- Last update date\n- Pull request information with title, number, and creation date\n- Error states when fetching fails\n\n## Behavioral Finance System\n\nThe architecture incorporates behavioral finance principles through prospect theory implementation and nudging mechanisms. These components work together to influence agent decision-making in financial contexts, encouraging optimal behavior while preventing risky transaction patterns.\n\n### Anomaly Detection\n\nTransaction anomaly detection uses Exponentially Weighted Moving Average (EWMA) statistical methods combined with behavioral fingerprinting. This dual approach identifies both statistical outliers and behavioral patterns that deviate from established agent profiles.\n\n| Detection Method | Function |\n|-----------------|----------|\n| EWMA | Statistical anomaly detection on transaction amounts and frequencies |\n| Fingerprinting | Behavioral pattern recognition across transaction sequences |\n\n## Governance Framework\n\nThe governance layer provides institutional controls over agent financial activities through four primary mechanisms:\n\n- **Charter**: Defines agent mission scope and authorized activities\n- **FiscalGate**: Budget enforcement for transaction limits\n- **Article 12**: Compliance and regulatory requirements\n- **MerkleAudit**: Cryptographic audit trail for transaction verification\n\nThis multi-layered governance ensures agents operate within defined parameters while maintaining full accountability for their financial actions.\n\n## SDK Installation and Quick Start\n\n```bash\n# Install the SDK\nnpm install @mnemopay/sdk\n\n# Python installation (alternative)\npip install mnemopay\n```\n\n```typescript\n// Initialize with zero configuration\nimport { MnemoPay } from \"@mnemopay/sdk\";\n\nconst agent = MnemoPay.quick(\"agent-id\");\n\n// The agent now has:\n// - Persistent memory\n// - Wallet functionality\n// - Cryptographic identity\n// - Payment capabilities\n```\n\n资料来源：[README.md:1-40](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)\n资料来源：[site/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)\n资料来源：[site/index.legacy.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)\n资料来源：[dashboard/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/dashboard/index.html)\n资料来源：[CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n\n---\n\n<a id='core-modules'></a>\n\n## Core Modules Reference\n\n### 相关页面\n\n相关主题：[System Architecture](#architecture)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/index.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/index.ts)\n- [src/recall/engine.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/recall/engine.ts)\n- [src/fraud.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/fraud.ts)\n- [src/identity/index.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/identity/index.ts)\n- [src/ledger.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/ledger.ts)\n- [src/fico.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/fico.ts)\n- [src/behavioral.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/behavioral.ts)\n- [src/integrity.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/integrity.ts)\n- [src/anomaly.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/anomaly.ts)\n- [src/adaptive.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/adaptive.ts)\n- [src/commerce.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/commerce.ts)\n- [src/mcp/server.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/mcp/server.ts)\n</details>\n\n# Core Modules Reference\n\nThe MnemoPay SDK comprises 14 core modules organized in the `src/` directory, providing a comprehensive trust and reputation infrastructure for AI agents that handle money. This reference documents all foundational modules, their responsibilities, and how they interrelate to form a complete payment and identity system.\n\n## Architecture Overview\n\nThe SDK architecture follows a layered design where core primitives (memory, ledger, identity) support higher-order features (payments, commerce, fraud detection). The main export `MnemoPay` bundles all modules into a unified interface (~74KB), while `MnemoPayLite` provides a lightweight alternative and `MnemoPayNetwork` extends functionality for multi-agent scenarios.\n\n```mermaid\ngraph TD\n    subgraph \"Core Layer\"\n        M[Memory/Recall]\n        L[Ledger]\n        I[Identity]\n    end\n    \n    subgraph \"Trust Layer\"\n        F[FICO - Agent Credit Score]\n        B[Behavioral Finance]\n        IN[Integrity - Merkle Trees]\n    end\n    \n    subgraph \"Safety Layer\"\n        A[Anomaly Detection]\n        AD[Adaptive - AIMD/Circuit Breaker]\n        FR[Fraud Detection]\n    end\n    \n    subgraph \"Commerce Layer\"\n        C[Commerce Engine]\n        N[Network]\n        R[Payment Rails]\n    end\n    \n    M --> F\n    M --> B\n    L --> A\n    I --> AD\n    F --> FR\n    B --> C\n    C --> R\n    N --> R\n    I --> N\n```\n\n资料来源：[README.md:40-55]()\n\n## Memory Module (`src/recall/`)\n\nThe memory module provides persistent, searchable memory capabilities for agents using semantic and hybrid retrieval. It supports the core memory operations: remember, recall, reinforce, forget, and consolidate.\n\n### Memory Operations\n\n| Operation | Purpose | Parameters |\n|-----------|---------|------------|\n| `remember(content, namespace?, tags?, importance?)` | Store a memory with optional importance score and tags | Content string, namespace ID, tag array, importance 0-1 |\n| `recall(query, namespace?, limit?, mode?)` | Retrieve relevant memories via semantic search | Query string, namespace, result limit, search mode |\n| `reinforce(memoryId)` | Boost a memory's importance score (+0.01 to +0.5) | Memory ID |\n| `forget(memoryId)` | Permanently delete a memory by ID | Memory ID |\n| `consolidate(namespace?)` | Prune stale memories below decay threshold | Optional namespace filter |\n\n### Search Modes\n\nThe recall engine supports multiple retrieval modes for different use cases:\n\n```mermaid\ngraph LR\n    A[Query] --> B{Mode}\n    B -->|semantic| C[Vector Embedding Search]\n    B -->|keyword| D[BM25 Full-Text Search]\n    B -->|hybrid| E[Weighted Combination]\n    C --> F[Results]\n    D --> F\n    E --> F\n```\n\n- **semantic**: Pure vector similarity search using embeddings\n- **keyword**: Traditional BM25-based keyword matching\n- **hybrid**: Weighted combination of both approaches (default)\n\n资料来源：[src/recall/engine.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/recall/engine.ts)\n\n### Memory Structure\n\nEach memory entry contains:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `id` | string | Unique memory identifier |\n| `content` | string | The memory content |\n| `namespace` | string | Logical partition for memory spaces |\n| `tags` | string[] | Categorization tags |\n| `importance` | number | 0-1 importance score for retrieval weighting |\n| `createdAt` | Date | Creation timestamp |\n| `updatedAt` | Date | Last modification timestamp |\n| `accessCount` | number | Number of times recalled |\n\n资料来源：[integrations/openclaw/SKILL.md:20-35]()\n\n## Ledger Module (`src/ledger.ts`)\n\nThe ledger implements double-entry bookkeeping for all financial transactions. Every monetary operation creates balanced entries ensuring accounting integrity across charges, settlements, and refunds.\n\n### Transaction Types\n\n| Type | Description | Ledger Impact |\n|------|-------------|---------------|\n| `charge` | Creates escrow hold for delivered work | Debit: Receivable, Credit: Escrow |\n| `settle` | Finalizes charge, moves funds to wallet | Debit: Escrow, Credit: Revenue |\n| `refund` | Reverses a transaction | Debit: Escrow, Credit: Receivable |\n| `dispute` | User-initiated chargeback | Triggers fraud analysis |\n\n### Transaction States\n\n```mermaid\nstateDiagram-v2\n    [*] --> pending: charge()\n    pending --> escrow: User Approval\n    pending --> cancelled: Timeout/Reject\n    escrow --> settled: settle()\n    escrow --> refunded: refund()\n    settled --> disputed: User Dispute\n    disputed --> refunded: Won Dispute\n    disputed --> settled: Lost Dispute\n```\n\n资料来源：[src/ledger.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/ledger.ts)\n\n## Identity Module (`src/identity/`)\n\nThe identity system manages agent identification, capabilities, and permissions through a multi-layered approach.\n\n### Components\n\n| Component | Purpose |\n|-----------|---------|\n| `IdentityRegistry` | Central registry mapping agent IDs to identities |\n| `KYA` (Know Your Agent) | Onboarding verification for new agents |\n| `CapabilityTokens` | Time-limited permission grants |\n| `killswitch` | Emergency capability revocation |\n\n### Identity Model\n\n```typescript\ninterface Identity {\n  agentId: string;\n  publicKey: string;\n  reputation: number;        // 0-1 score\n  kyaStatus: KYAStatus;\n  capabilities: Capability[];\n  createdAt: Date;\n  lastActive: Date;\n}\n```\n\n资料来源：[src/identity/index.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/identity/index.ts)\n\n## Agent Credit Score (`src/fico.ts`)\n\nThe Agent Credit Score provides a portable, standardized credit evaluation (300-850 range) for AI agents, enabling trust assessment across different platforms and use cases.\n\n### Scoring Components\n\nThe FICO module calculates scores using five weighted factors:\n\n| Component | Weight | Description |\n|-----------|--------|-------------|\n| Payment History | 35% | Track record of successful settlements |\n| Utilization | 30% | Current escrow exposure relative to limits |\n| Account Age | 15% | Duration of active account |\n| Diversity | 10% | Range of transaction types and rails used |\n| Reputation | 10% | Social/professional reputation signals |\n\n### Score Ranges\n\n| Range | Classification | Description |\n|-------|-----------------|-------------|\n| 800-850 | Exceptional | Highly reliable, lowest risk |\n| 740-799 | Very Good | Reliable with minimal risk |\n| 670-739 | Good | Acceptable risk level |\n| 580-669 | Fair | Elevated risk, monitor closely |\n| 300-579 | Poor | High risk, limited capabilities |\n\n资料来源：[src/fico.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/fico.ts)\n\n## Fraud Detection (`src/fraud.ts`)\n\nThe fraud module provides geo-enhanced fraud detection with pattern recognition and behavioral analysis.\n\n### Detection Mechanisms\n\n```mermaid\ngraph TD\n    A[Transaction Request] --> B[Geo Analysis]\n    A --> C[Pattern Matching]\n    A --> D[Velocity Check]\n    B --> E{Risk Score}\n    C --> E\n    D --> E\n    E -->|Low| F[Allow]\n    E -->|Medium| G[Flag for Review]\n    E -->|High| H[Block + Alert]\n```\n\n### Risk Factors\n\n| Factor | Description | Threshold |\n|--------|-------------|-----------|\n| `geoVelocity` | Rapid location changes impossible for user | >500km/hour |\n| `velocityVolume` | Unusual transaction frequency | >10 tx/hour |\n| `amountAnomaly` | Statistical outlier in transaction size | >3σ from mean |\n| `patternDeviation` | Deviation from established behavioral patterns | Similarity <0.6 |\n\n资料来源：[src/fraud.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/fraud.ts)\n\n## Anomaly Detection (`src/anomaly.ts`)\n\nEWMA (Exponentially Weighted Moving Average) anomaly detection monitors behavioral patterns and identifies deviations that may indicate compromise or abuse.\n\n### Components\n\n| Component | Purpose |\n|-----------|---------|\n| `EWMA` | Core statistical monitoring with exponential weighting |\n| `BehaviorMonitor` | Tracks behavioral baselines per agent |\n| `CanarySystem` | Synthetic transactions to verify system integrity |\n\n### Alert Levels\n\n```mermaid\ngraph LR\n    A[Metric Stream] --> B[EWMA Calculation]\n    B --> C{Deviation Check}\n    C -->|< 2σ| D[Normal]\n    C -->|2-3σ| E[Warning]\n    C -->|> 3σ| F[Critical Alert]\n    D --> G[No Action]\n    E --> H[Log + Notify]\n    F --> I[Block + Response]\n```\n\n资料来源：[src/anomaly.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/anomaly.ts)\n\n## Behavioral Finance (`src/behavioral.ts`)\n\nThe behavioral module implements concepts from behavioral economics to influence agent decision-making and user interactions.\n\n### Features\n\n| Feature | Description |\n|---------|-------------|\n| Prospect Theory | Loss aversion calculations (losses weighted 2x gains) |\n| Cooling-Off Periods | Mandatory waiting periods for high-value transactions |\n| Nudges | Behavioral prompts to encourage positive outcomes |\n\n### Cooling-Off Rules\n\nHigh-value transactions (>100 USD equivalent) trigger mandatory review periods:\n\n| Amount Range | Cooling Period |\n|--------------|-----------------|\n| $100-$500 | 24 hours |\n| $500-$1000 | 72 hours |\n| >$1000 | 7 days |\n\n资料来源：[src/behavioral.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/behavioral.ts)\n\n## Integrity Module (`src/integrity.ts`)\n\nMerkle tree-based memory integrity provides cryptographic proof of memory chain integrity using SHA-256 hashing.\n\n### Verification Process\n\n```mermaid\ngraph TD\n    A[Memory Entry] --> B[SHA-256 Hash]\n    B --> C[Merkle Tree Node]\n    C --> D{Root Hash}\n    D --> E[Audit Request]\n    E --> F[Prove Path]\n    F --> G[Verify against Root]\n    G --> H[Valid/Invalid]\n```\n\n### Audit Capabilities\n\n| Feature | Description |\n|---------|-------------|\n| `MerkleAudit` | Generates proof bundles for external verification |\n| Chain Verification | Validates no memories were tampered with |\n| Timestamping | Provides proof of memory existence at time T |\n\n资料来源：[src/integrity.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/integrity.ts)\n\n## Adaptive Module (`src/adaptive.ts`)\n\nAdaptive rate limiting and anti-gaming mechanisms prevent abuse while allowing legitimate high-throughput scenarios.\n\n### Components\n\n| Component | Purpose |\n|-----------|---------|\n| `AIMD` | Additive Increase, Multiplicative Decrease rate control |\n| Anti-Gaming | Detection of rate limit exploitation patterns |\n| `CircuitBreaker` | Prevents cascade failures |\n| `PSI Drift` | Population Stability Index for distribution shifts |\n\n### Circuit Breaker States\n\n```mermaid\nstateDiagram-v2\n    [*] --> Closed: Normal Operation\n    Closed --> Open: Failure Threshold\n    Open --> HalfOpen: Recovery Timeout\n    HalfOpen --> Closed: Success\n    HalfOpen --> Open: Failure\n```\n\n资料来源：[src/adaptive.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/adaptive.ts)\n\n## Commerce Engine (`src/commerce.ts`)\n\nThe commerce engine enables autonomous shopping with configurable mandates and spending policies.\n\n### Mandate Structure\n\n```typescript\ninterface Mandate {\n  id: string;\n  agentId: string;\n  rules: CommerceRule[];\n  maxAmount: number;\n  maxFrequency: number;\n  allowedCategories: string[];\n  createdAt: Date;\n}\n```\n\n### Shopping Workflow\n\n```mermaid\ngraph TD\n    A[User Request] --> B[Parse Intent]\n    B --> C[Check Mandate Permissions]\n    C -->|Permitted| D[Find Best Offer]\n    C -->|Denied| E[Return Error]\n    D --> F[Execute Purchase]\n    F --> G[Charge Escrow]\n    G --> H[Confirm to User]\n    E --> I[Log Denial]\n```\n\n资料来源：[src/commerce.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/commerce.ts)\n\n## MCP Server (`src/mcp/server.ts`)\n\nThe Model Context Protocol server exposes SDK functionality as MCP tools for integration with LLM agents.\n\n### Available Tools (24 total)\n\n#### Memory Tools (5)\n\n| Tool | Description |\n|------|-------------|\n| `mcp__mnemopay__remember` | Store a memory with optional importance and tags |\n| `mcp__mnemopay__recall` | Retrieve relevant memories via semantic search |\n| `mcp__mnemopay__forget` | Permanently delete a memory |\n| `mcp__mnemopay__reinforce` | Boost memory importance |\n| `mcp__mnemopay__consolidate` | Prune stale memories |\n\n#### Payment Tools (4)\n\n| Tool | Description |\n|------|-------------|\n| `mcp__mnemopay__charge` | Create escrow charge (max $500 × reputation) |\n| `mcp__mnemopay__settle` | Finalize pending charge |\n| `mcp__mnemopay__refund` | Process refund |\n| `mcp__mnemopay__dispute` | File dispute for chargeback |\n\n#### Additional Tools\n\n- Identity management tools\n- Ledger query tools\n- Reputation management tools\n- Usage and audit tools\n\n资料来源：[src/mcp/server.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/mcp/server.ts)\n资料来源：[integrations/openclaw/SKILL.md:40-60]()\n\n## Payment Rails (`src/rails/`)\n\nThe rails module provides abstraction over multiple payment providers, enabling cross-border commerce through standardized interfaces.\n\n### Supported Rails\n\n| Rail | Region | Currencies | Features |\n|------|--------|------------|----------|\n| Stripe | Global | USD, EUR, GBP, 135+ | PaymentIntents, Manual Capture, Webhooks |\n| Paystack | Africa | NGN, GHS, ZAR, KES | Checkout, Saved Cards, Bank Transfer, HMAC-SHA512 |\n| Lightning | Crypto | BTC | Instant settlement, Micropayments |\n\n### Rail Interface\n\n```typescript\ninterface PaymentRail {\n  charge(amount: number, currency: string, options: ChargeOptions): Promise<ChargeResult>;\n  settle(chargeId: string): Promise<SettlementResult>;\n  refund(chargeId: string, amount?: number): Promise<RefundResult>;\n  verifyWebhook(payload: any, signature: string): boolean;\n}\n```\n\n### Escrow Flow\n\n```mermaid\nsequenceDiagram\n    participant Agent\n    participant SDK\n    participant Rail\n    participant Escrow\n    participant User\n    \n    Agent->>SDK: charge(amount)\n    SDK->>Rail: Create PaymentIntent\n    Rail-->>SDK: Pending Charge\n    SDK->>Escrow: Hold Funds\n    User->>User: Review Work\n    alt Approved\n        User->>SDK: approve()\n        SDK->>Rail: Capture\n        SDK->>Escrow: Release to Wallet\n        SDK->>SDK: reputation += 0.01\n    else Rejected\n        User->>SDK: dispute()\n        SDK->>SDK: Fraud Analysis\n    end\n```\n\n资料来源：[src/index.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/index.ts)\n\n## Main SDK Entry (`src/index.ts`)\n\nThe main index exports three SDK variants optimized for different use cases.\n\n### SDK Variants\n\n| Variant | Size | Use Case |\n|---------|------|----------|\n| `MnemoPay` | ~74KB | Full-featured production use |\n| `MnemoPayLite` | <20KB | Browser, edge functions, constrained environments |\n| `MnemoPayNetwork` | +~15KB | Multi-agent scenarios |\n\n### Quick Start\n\n```typescript\nimport { MnemoPay } from '@mnemopay/sdk';\n\n// Development mode - zero infrastructure\nconst agent = MnemoPay.quick(\"agent-id\");\n\n// Store memory\nawait agent.remember(\"User prefers Express shipping\", { importance: 0.8 });\n\n// Recall previous context\nconst memories = await agent.recall(\"shipping preferences\");\n\n// Charge for work delivered\nconst charge = await agent.charge(25.00, \"Monthly report delivery\");\n\n// Settle after user approval\nawait agent.settle(charge.id);\n```\n\n### Initialization Modes\n\n| Mode | Description | Infrastructure Required |\n|------|-------------|------------------------|\n| `quick(agentId)` | Dev mode with mock services | None |\n| `init(config)` | Production mode with real services | API keys, secrets |\n| `network(config)` | Multi-agent network mode | Network registry |\n\n资料来源：[src/index.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/index.ts)\n资料来源：[README.md:55-75]()\n\n## Module Dependencies\n\nUnderstanding module dependencies is crucial for proper integration and troubleshooting.\n\n```mermaid\ngraph TD\n    R[Recall/Memory] --> L[Ledger]\n    I[Identity] --> R\n    I --> F[FICO]\n    F --> FR[Fraud]\n    B[Behavioral] --> C[Commerce]\n    A[Anomaly] --> L\n    AD[Adaptive] --> A\n    L --> N[Network]\n    I --> N\n    C --> RA[Rails]\n    R --> IN[Integrity]\n```\n\n## Configuration Reference\n\n### Required Configuration\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `agentId` | string | Unique agent identifier |\n| `apiKey` | string | API authentication key |\n| `networkId` | string | Network/tenant identifier |\n\n### Optional Configuration\n\n| Parameter | Default | Description |\n|-----------|---------|-------------|\n| `mode` | `\"dev\"` | Runtime mode: dev, production, network |\n| `rail` | `\"stripe\"` | Primary payment rail |\n| `region` | `\"us-east-1\"` | Deployment region |\n| `logLevel` | `\"warn\"` | Logging verbosity |\n\n资料来源：[src/index.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/index.ts)\n\n## Testing\n\nThe SDK includes 672+ vitest tests covering all modules:\n\n```bash\nnpm test           # Run all tests\nnpm run build      # Compile TypeScript\nnpm run lint       # Type-check without emit\n```\n\nTest coverage is distributed across:\n\n| Module | Test Focus |\n|--------|------------|\n| Memory | CRUD operations, search accuracy, consolidation |\n| Ledger | Double-entry balance, transaction states |\n| Identity | KYA flow, capability tokens, killswitch |\n| Fraud | Geo-velocity, pattern matching, thresholds |\n| Anomaly | EWMA calculation, alert thresholds |\n| Rails | Payment flows, webhook verification |\n\n---\n\n<a id='payment-rails-overview'></a>\n\n## Payment Rails Overview\n\n### 相关页面\n\n相关主题：[Stripe, Paystack & Lightning Rails](#stripe-rail), [Alpha Payment Rails (StripeMPP, x402, GoogleAP2)](#alpha-rails), [System Architecture](#architecture)\n\n<details>\n<summary>Related Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/rails/index.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/rails/index.ts)\n- [src/rails/stripe-mpp.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/rails/stripe-mpp.ts)\n- [src/rails/x402.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/rails/x402.ts)\n- [src/rails/google-ap2.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/rails/google-ap2.ts)\n</details>\n\n# Payment Rails Overview\n\n## Introduction\n\nThe MnemoPay SDK provides a unified payment abstraction layer called **Payment Rails**, which enables AI agents to process payments across multiple payment providers through a consistent interface. This architecture decouples business logic from payment provider specifics, allowing developers to switch between or combine payment rails without modifying core application code.\n\nThe Payment Rails system supports both stable, production-ready rails and preview/alpha rails for emerging payment methods. All rails share a common API contract, ensuring predictable behavior regardless of the underlying payment provider. 资料来源：[README.md:1-45]()\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    A[Agent / Application] --> B[MnemoPay SDK Core]\n    B --> C[Payment Rail Abstraction Layer]\n    C --> D[StripeRail]\n    C --> E[PaystackRail]\n    C --> F[LightningRail]\n    C --> G[StripeMPPRail]\n    C --> H[X402Rail]\n    C --> I[GoogleAP2Rail]\n    D --> J[Stripe API]\n    E --> K[Paystack API]\n    F --> L[LND / Lightning Network]\n    G --> M[Stripe MPP]\n    H --> N[Base / EIP-3009]\n    I --> O[Google AP2]\n```\n\n## Rail Classification\n\nPayment rails in MnemoPay are classified into two stability tiers:\n\n| Classification | Rails | Use Case | Status |\n|---|---|---|---|\n| **Stable** | `StripeRail`, `PaystackRail`, `LightningRail` | Production deployments | `latest` |\n| **Preview (Alpha)** | `StripeMPPRail`, `X402Rail`, `GoogleAP2Rail` | Evaluation and testing | `alpha` |\n\n资料来源：[README.md:8-16]()\n\n## Stable Rails\n\n### StripeRail\n\n`StripeRail` provides global card payment processing supporting USD, EUR, GBP, and 135+ currencies. It uses Stripe's PaymentIntents API with manual capture to enable true escrow functionality.\n\n**Supported Currencies:** USD, EUR, GBP, +135 currencies  \n**Use Cases:** Global payments, subscription billing, e-commerce  \n**Security:** PCI-compliant via Stripe\n\n**Initialization:**\n```ts\nimport { StripeRail } from \"@mnemopay/sdk\";\n\nconst stripe = new StripeRail(process.env.STRIPE_SECRET_KEY!);\n```\n\n资料来源：[README.md:20-24]()\n\n### PaystackRail\n\n`PaystackRail` focuses on African markets, supporting NGN (Nigerian Naira), GHS (Ghanaian Cedi), ZAR (South African Rand), and KES (Kenyan Shilling). It provides checkout, saved cards, bank transfers, and webhook verification with HMAC-SHA512 security.\n\n**Supported Currencies:** NGN, GHS, ZAR, KES  \n**Regional Coverage:** Africa (23 Nigerian banks pre-mapped)  \n**Security:** HMAC-SHA512 webhook verification\n\n**Initialization:**\n```ts\nimport { PaystackRail } from \"@mnemopay/sdk\";\n\nconst paystack = new PaystackRail(process.env.PAYSTACK_SECRET_KEY!);\n```\n\n资料来源：[README.md:21-22]()\n\n### LightningRail\n\n`LightningRail` enables Bitcoin sub-cent micropayments through the Lightning Network, ideal for high-frequency, low-value transactions that would be impractical on the base chain.\n\n**Supported:** BTC sub-cent micropayments  \n**Use Cases:** Microtransactions, pay-per-use API calls, tips  \n**Requirements:** LND URL and macaroon authentication\n\n**Initialization:**\n```ts\nimport { LightningRail } from \"@mnemopay/sdk\";\n\nconst lightning = new LightningRail(LND_URL, MACAROON);\n```\n\n资料来源：[README.md:23-24]()\n\n## Preview Rails (Alpha)\n\nPreview rails are available for evaluation but may have breaking changes in future releases.\n\n### StripeMPPRail\n\n`StripeMPPRail` enables crypto deposits on Tempo via Stripe's Mass Payment Program (MPP). This rail allows agents to accept cryptocurrency payments that are converted and settled through Stripe's infrastructure.\n\n**Supported:** Crypto deposits via Stripe MPP  \n**Status:** `alpha` (v1.6.0-alpha)  \n**Use Case:** Crypto-to-fiat settlement for agents\n\n```ts\nimport { StripeMPPRail } from \"@mnemopay/sdk\";\n\nconst mpp = new StripeMPPRail(process.env.STRIPE_SECRET_KEY!);\n```\n\n资料来源：[src/rails/stripe-mpp.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/rails/stripe-mpp.ts)\n\n### X402Rail\n\n`X402Rail` implements the EIP-3009 standard for USDC payments on Base. This rail enables transferWithAuthorization, a standardized way to execute payments with cryptographic authorization.\n\n**Supported:** USDC on Base via EIP-3009  \n**Status:** `alpha` (v1.6.0-alpha)  \n**Use Case:** On-chain USDC payments with standardized authorization\n\n```ts\nimport { X402Rail } from \"@mnemopay/sdk\";\nimport { YourEip3009Signer } from \"./your-signer\";\n\nconst x402 = new X402Rail({ signer: yourEip3009Signer });\n```\n\n**Requirements:** Bring-your-own EIP-3009 signer implementation\n\n资料来源：[src/rails/x402.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/rails/x402.ts)\n\n### GoogleAP2Rail\n\n`GoogleAP2Rail` implements the FIDO Alliance's AP2 v0.2 mandate-driven settlement specification. This rail uses mandate-based authorization flows for payment authorization.\n\n**Supported:** AP2 v0.2 mandate-driven settlement  \n**Standard:** FIDO Alliance  \n**Status:** `alpha` (v1.6.0-alpha)  \n**Use Case:** FIDO-aligned payment authorization\n\n```ts\nimport { GoogleAP2Rail } from \"@mnemopay/sdk\";\n\nconst ap2 = new GoogleAP2Rail({ mandate, endpoint, signer });\n```\n\n资料来源：[src/rails/google-ap2.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/rails/google-ap2.ts)\n\n## Common Payment Operations\n\nAll payment rails support the same core operations for payment lifecycle management:\n\n| Operation | Description |\n|---|---|\n| **Charge** | Initiate a payment from the customer's payment method |\n| **Escrow** | Hold funds in a secure state pending verification or delivery |\n| **Settle** | Release escrowed funds to the merchant/recipient |\n| **Refund** | Return funds to the customer |\n\nThe double-entry ledger system ensures every financial operation is recorded with corresponding debit and credit entries, maintaining balanced books with zero penny drift. 资料来源：[site/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)\n\n## Environment Configuration\n\n### Real Payment Rails\n\nFor production deployments using real payment providers:\n\n| Environment Variable | Purpose |\n|---|---|\n| `STRIPE_SECRET_KEY` | Stripe payments API key |\n| `PAYSTACK_SECRET_KEY` | Paystack payments API key |\n| `MNEMOPAY_PAYMENT_RAIL` | Active rail: `stripe`, `paystack`, or `mock` |\n| `MNEMOPAY_COMMERCE_PROVIDER` | Commerce provider: `firecrawl`, `shopify`, or `mock` |\n\n资料来源：[claude-plugin/README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/claude-plugin/README.md)\n\n### Mock/Sandbox Mode\n\nFor development and testing, the SDK defaults to mock/sandbox mode. Set `MNEMOPAY_PAYMENT_RAIL=mock` to use simulated payment operations without real money movement.\n\n## Quick Setup\n\n```ts\nimport {\n  PaystackRail, StripeRail, LightningRail,    // stable\n  StripeMPPRail, X402Rail, GoogleAP2Rail,     // alpha\n} from \"@mnemopay/sdk\";\n\n// Stable rails\nconst paystack  = new PaystackRail(process.env.PAYSTACK_SECRET_KEY!);\nconst stripe    = new StripeRail(process.env.STRIPE_SECRET_KEY!);\nconst lightning = new LightningRail(LND_URL, MACAROON);\n\n// Alpha rails (v1.6.0-alpha)\nconst mpp   = new StripeMPPRail(process.env.STRIPE_SECRET_KEY!);\nconst x402  = new X402Rail({ signer: yourEip3009Signer });\nconst ap2   = new GoogleAP2Rail({ mandate, endpoint, signer });\n\n// Quick agent initialization\nconst agent = MnemoPay.quick(\"my-agent\", {\n  rail: stripe,  // Use any configured rail\n  // ... other config\n});\n```\n\n资料来源：[README.md:26-40]()\n\n## Architecture Benefits\n\n| Benefit | Description |\n|---|---|\n| **Provider Abstraction** | Single API interface for multiple payment providers |\n| **Rail Switching** | Change payment providers without code modifications |\n| **Hybrid Rails** | Combine multiple rails in a single agent configuration |\n| **Consistent Error Handling** | Unified error responses across all providers |\n| **Audit Trail** | Every operation logged in the hash-chained ledger |\n\n## Choosing a Payment Rail\n\n| Scenario | Recommended Rail |\n|---|---|\n| Global card payments | `StripeRail` |\n| African markets (NGN, GHS, ZAR, KES) | `PaystackRail` |\n| BTC micropayments | `LightningRail` |\n| Crypto deposits settlement | `StripeMPPRail` |\n| On-chain USDC payments (Base) | `X402Rail` |\n| FIDO-aligned settlement | `GoogleAP2Rail` |\n\n## Summary\n\nThe Payment Rails system provides MnemoPay agents with flexible, production-ready payment infrastructure across six different payment providers. Stable rails (Stripe, Paystack, Lightning) handle traditional payment flows, while preview rails (StripeMPP, X402, GoogleAP2) enable emerging crypto and mandate-based payment methods. All rails share a common interface, allowing seamless switching and hybrid configurations.\n\n---\n\n<a id='stripe-rail'></a>\n\n## Stripe, Paystack & Lightning Rails\n\n### 相关页面\n\n相关主题：[Payment Rails Overview](#payment-rails-overview), [Alpha Payment Rails (StripeMPP, x402, GoogleAP2)](#alpha-rails)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)\n- [CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n- [CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)\n- [CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)\n- [dashboard/DEPLOYMENT.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/dashboard/DEPLOYMENT.md)\n- [site/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)\n</details>\n\n# Stripe, Paystack & Lightning Rails\n\n## Overview\n\nThe payment rails system in MnemoPay SDK provides a unified abstraction layer over multiple payment providers, enabling AI agents to process transactions across different geographic regions and payment methods through a consistent API. This architecture decouples business logic from provider-specific implementations, allowing seamless switching between payment rails without code changes.\n\nThe SDK currently supports three stable payment rails: **StripeRail** (global USD, EUR, GBP), **PaystackRail** (African markets), and **LightningRail** (Bitcoin micropayments). Additionally, preview rails include **StripeMPPRail** for crypto deposits, **X402Rail** for USDC on Base, and **GoogleAP2Rail** for mandate-driven settlement.\n\n资料来源：[README.md:1-25]()\n\n## Architecture\n\n### Unified PaymentRail Interface\n\nAll payment rails implement the `PaymentRail` interface, ensuring consistent behavior across providers. This abstraction allows developers to:\n\n- Process charges with identical method signatures regardless of provider\n- Access two-phase escrow (charge → settle/refund)\n- Utilize provider-specific features when needed\n- Switch rails with minimal configuration changes\n\n```typescript\nimport { PaystackRail, StripeRail, LightningRail } from \"@mnemopay/sdk\";\n\n// All three use the same API pattern\nconst paystack  = new PaystackRail(process.env.PAYSTACK_SECRET_KEY!);\nconst stripe    = new StripeRail(process.env.STRIPE_SECRET_KEY!);\nconst lightning = new LightningRail(LND_URL, MACAROON);\n```\n\n资料来源：[README.md:28-38]()\n\n### Rail Selection Matrix\n\n| Rail | Coverage | Channel | Status | Currencies |\n|------|----------|---------|--------|------------|\n| `StripeRail` | Global | stable (`latest`) | Stable | USD, EUR, GBP, + |\n| `PaystackRail` | Africa | stable (`latest`) | Stable | NGN, GHS, ZAR, KES |\n| `LightningRail` | BTC micropayments | stable (`latest`) | Stable | BTC |\n| `StripeMPPRail` | Crypto via Tempo | preview (`alpha`) | Alpha | Crypto deposits |\n| `X402Rail` | USDC on Base | preview (`alpha`) | Alpha | USDC |\n| `GoogleAP2Rail` | AP2 v0.2 mandate | preview (`alpha`) | Alpha | Multiple |\n\n资料来源：[README.md:1-12]()\n\n## Stable Rails\n\n### StripeRail\n\nStripeRail provides global card payment processing with manual capture for true escrow functionality. It uses Stripe's PaymentIntents API and supports 135+ currencies.\n\n**Key Features:**\n- Manual capture mode for two-phase escrow (charge → settle)\n- PaymentIntents API with full payment method support\n- Webhook verification for payment events\n- Refund handling with full/partial support\n\n**Configuration:**\n```typescript\nconst stripe = new StripeRail(process.env.STRIPE_SECRET_KEY!);\nconst agent = MnemoPay.quick(\"billing-agent\", { stripe: { secretKey: process.env.STRIPE_SECRET_KEY } });\n```\n\n资料来源：[README.md:30-32](), [site/index.html:45-50]()\n\n**Webhook Endpoint:**\n```\nPOST https://dashboard.mnemopay.com/api/v1/billing/stripe/webhook\n```\n\n**Handled Events:**\n- `checkout.session.completed`\n- `customer.subscription.updated`\n- `customer.subscription.deleted`\n\n资料来源：[dashboard/DEPLOYMENT.md:22-28]()\n\n### PaystackRail\n\nPaystackRail focuses on African markets with support for Nigerian Naira (NGN), Ghanaian Cedi (GHS), South African Rand (ZAR), and Kenyan Shilling (KES). It provides comprehensive checkout, saved cards, bank transfers, and webhook verification.\n\n**Key Features:**\n- 23 Nigerian banks pre-mapped\n- HMAC-SHA512 webhook security\n- Multiple payment methods (cards, bank transfer)\n- Checkout and saved card support\n\n**Configuration:**\n```typescript\nconst paystack = new PaystackRail(process.env.PAYSTACK_SECRET_KEY!);\n```\n\n资料来源：[README.md:31](), [site/index.html:58-62]()\n\n**Environment Variables:**\n```bash\nPAYSTACK_SECRET_KEY=sk_live_...  # Required for Paystack payments\nMNEMOPAY_PAYMENT_RAIL=paystack   # Set payment rail\n```\n\n资料来源：[claude-plugin/README.md:8-10]()\n\n### LightningRail\n\nLightningRail enables sub-cent Bitcoin micropayments through the Lightning Network. It connects to LND (Lightning Network Daemon) for instant, low-fee transactions.\n\n**Key Features:**\n- Sub-cent micropayments\n- Instant settlement via Lightning Network\n- LND connection with macaroon authentication\n- Low fees for high-frequency microtransactions\n\n**Configuration:**\n```typescript\nconst lightning = new LightningRail(LND_URL, MACAROON);\n```\n\n资料来源：[README.md:32]()\n\n## Preview Rails (Alpha)\n\n### StripeMPPRail\n\nStripe Machine Payments Protocol (MPP) rail routes agent payments as crypto deposits on the Tempo network via Stripe's MPP-enabled PaymentIntents API.\n\n**Technical Details:**\n- API version: `2026-03-04.preview`\n- Payment method types: `[\"crypto\"]`\n- Capture method: `\"manual\"` for two-phase escrow\n- In-flight capture deduplication\n- Idempotency-key forwarding\n\n**Configuration:**\n```typescript\nconst mpp = new StripeMPPRail(process.env.STRIPE_SECRET_KEY!);\n```\n\n**Key Methods:**\n- `fromClient(client, opts?)` — for tests and shared Stripe client patterns\n\n资料来源：[CHANGELOG.md:20-45]()\n\n### X402Rail\n\nThe x402 protocol implements HTTP 402 revival for USDC payments on Base L2 via EIP-3009 `transferWithAuthorization`. Agents sign transactions off-chain, and a facilitator submits to chain on capture.\n\n**Key Features:**\n- Pluggable `X402Signer` interface\n- Zero crypto dependencies in SDK\n- EIP-3009 `transferWithAuthorization` standard\n- USDC on Base L2\n\n**Configuration:**\n```typescript\nconst x402 = new X402Rail({ signer: yourEip3009Signer });\n```\n\n资料来源：[CHANGELOG.md:46-55]()\n\n### GoogleAP2Rail\n\nGoogle Agent Payment Protocol (AP2) v0.2 provides mandate-driven settlement through the FIDO Alliance open standard.\n\n**Configuration:**\n```typescript\nconst ap2 = new GoogleAP2Rail({ mandate, endpoint, signer });\n```\n\n资料来源：[CHANGELOG.md:56-60]()\n\n## Payment Flow Architecture\n\n```mermaid\ngraph TD\n    A[Agent Request] --> B[PaymentRail Interface]\n    B --> C{Provider Selection}\n    C -->|Global| D[StripeRail]\n    C -->|Africa| E[PaystackRail]\n    C -->|BTC| F[LightningRail]\n    D --> G[Charge with Escrow]\n    E --> G\n    F --> G\n    G --> H[Manual Capture]\n    H --> I[await settle()]\n    H --> J[await refund()]\n    I --> K[Funds Released]\n    J --> L[Funds Returned]\n```\n\n## Two-Phase Escrow Model\n\nAll payment rails implement a two-phase commit pattern:\n\n1. **Charge Phase** — Funds are authorized and held in escrow\n2. **Settlement Phase** — Funds are captured and transferred\n3. **Refund Phase** — Funds are returned to the customer\n\n```typescript\nconst tx = await agent.charge(49.00, \"Pro plan, monthly\");\n// Escrow holds funds until you approve\nawait agent.settle(tx.id);\n// Money moves. Ledger balanced. Credit score updated.\n```\n\n资料来源：[site/index.html:45-50]()\n\n## Double-Entry Ledger\n\nEvery financial operation in the payment rails is recorded in a double-entry ledger system, ensuring complete audit trails and preventing discrepancies.\n\n```typescript\n// Ledger maintains balance integrity across all rails\n// SHA-256 hash-chained for tamper evidence\n```\n\n资料来源：[site/index.html:15-17](), [CLAUDE.md:8]()\n\n## Environment Configuration\n\n| Variable | Rail | Description |\n|----------|------|-------------|\n| `STRIPE_SECRET_KEY` | Stripe, StripeMPP | Stripe API key |\n| `PAYSTACK_SECRET_KEY` | Paystack | Paystack API key |\n| `MNEMOPAY_PAYMENT_RAIL` | All | `stripe`, `paystack`, or `mock` |\n| `MNEMOPAY_COMMERCE_PROVIDER` | Shopping | `firecrawl`, `shopify`, or `mock` |\n\n资料来源：[claude-plugin/README.md:8-10]()\n\n## Integration Examples\n\n### Production Setup\n\n```typescript\nimport MnemoPay from \"@mnemopay/sdk\";\n\n// Production configuration with full features\nconst agent = await MnemoPay.create({\n  agentId: \"my-agent\",\n  storage: sqliteAdapter,\n  rail: stripeRail\n});\n\n// Charge with automatic escrow\nconst tx = await agent.charge(49.00, \"Pro plan, monthly\");\nawait agent.settle(tx.id);\n```\n\n### Quick Start (Dev Mode)\n\n```typescript\n// Dev mode - zero infrastructure required\nconst agent = MnemoPay.quick(\"my-agent\");\n\n// All features work, defaults to mock/sandbox\n// Swap to real rail with configuration\n```\n\n资料来源：[CLAUDE.md:20-35]()\n\n## CLI Commands\n\nThe Claude plugin provides payment management commands:\n\n| Command | Description |\n|---------|-------------|\n| `/mnemopay:charge <amount> <description>` | Charge specified amount |\n| `/mnemopay:balance` | Check account balance |\n| `/mnemopay:history <period>` | View transaction history |\n| `/mnemopay:settle` | Settle pending transactions |\n| `/mnemopay:fico` | View agent credit score |\n| `/mnemopay:remember <pref>` | Store payment preferences |\n| `/mnemopay:recall` | Retrieve payment preferences |\n\n资料来源：[claude-plugin/README.md:18-26]()\n\n## Testing\n\nThe payment rails have comprehensive test coverage:\n\n- StripeRail tests: Payment flows, webhooks, refunds\n- PaystackRail tests: Checkout, bank transfers, webhook verification\n- LightningRail tests: Invoice creation, payment forwarding\n- StripeMPPRail tests: 20 dedicated tests for MPP flow\n\n资料来源：[CHANGELOG.md:31-32](), [CHANGELOG.md:29]()\n\n## See Also\n\n- [Agent Credit Score](agent-credit-score) — Agent trust scoring (300-850)\n- [Double-Entry Ledger](ledger) — Financial transaction tracking\n- [Shopping Module](shopping) — Autonomous product discovery and purchase\n- [MCP Server](mcp-server) — 24 tools for agent payment operations\n\n---\n\n<a id='alpha-rails'></a>\n\n## Alpha Payment Rails (StripeMPP, x402, GoogleAP2)\n\n### 相关页面\n\n相关主题：[Payment Rails Overview](#payment-rails-overview), [Stripe, Paystack & Lightning Rails](#stripe-rail)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/rails/stripe-mpp.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/rails/stripe-mpp.ts)\n- [src/rails/x402.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/rails/x402.ts)\n- [src/rails/google-ap2.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/rails/google-ap2.ts)\n- [src/client.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/client.ts)\n</details>\n\n# Alpha Payment Rails (StripeMPP, x402, GoogleAP2)\n\n## Overview\n\nAlpha Payment Rails are experimental payment rail implementations introduced in MnemoPay SDK v1.6.0-alpha as part of the v1.6.x rail sprint. These rails provide alternative payment methods beyond the stable payment rails (Stripe, Paystack, Lightning) and enable crypto-native payment flows for AI agents.\n\n| Rail | Technology | Status | Channel |\n|------|-----------|--------|---------|\n| `StripeMPPRail` | Crypto deposits on Tempo via Stripe MPP | alpha | `npm install @mnemopay/sdk@alpha` |\n| `X402Rail` | USDC on Base via EIP-3009 transferWithAuthorization | alpha | `npm install @mnemopay/sdk@alpha` |\n| `GoogleAP2Rail` | AP2 v0.2 mandate-driven settlement (FIDO Alliance) | alpha | `npm install @mnemopay/sdk@alpha` |\n\n资料来源：[README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)\n\n## StripeMPPRail\n\nStripeMPPRail implements the Stripe Machine Payments Protocol (MPP), enabling agents to route payments as crypto deposits on the Tempo network through Stripe's MPP-enabled PaymentIntents API.\n\n### Key Features\n\n- **Crypto Payment Method**: Uses `payment_method_types: [\"crypto\"]` with `crypto.deposit_options.networks`\n- **Two-Phase Escrow**: Implements `capture_method: \"manual\"` for true escrow semantics\n- **Deduplication**: In-flight capture deduplication prevents double-settlement\n- **Idempotency**: Full idempotency-key forwarding for safe retries\n- **Drop-in Swap**: Same `PaymentRail` interface as `StripeRail` 资料来源：[CHANGELOG.md:19-36](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n\n### API Configuration\n\n```typescript\nimport { StripeMPPRail } from \"@mnemopay/sdk\";\n\n// Alpha preview (v1.6.0-alpha)\nconst mpp = new StripeMPPRail(process.env.STRIPE_SECRET_KEY!);\n```\n\n### Implementation Details\n\n- Pinned to Stripe API version: `2026-03-04.preview`\n- Tagged with `@experimental` decorator — preview API can change without semver guarantees\n- 20 dedicated tests in the test suite\n- Includes `fromClient(client, opts?)` factory for tests and shared Stripe client patterns\n\n资料来源：[CHANGELOG.md:20-35](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n\n## X402Rail\n\nX402Rail implements the EIP-3009 `transferWithAuthorization` standard, enabling USDC payments on Base network with off-chain authorization and on-chain settlement.\n\n### Features\n\n- **EIP-3009 Compliance**: Uses `transferWithAuthorization` for delegated transfers\n- **USDC Native**: Direct USDC transfers on Base L2\n- **Bring Your Own Signer**: Requires user-provided EIP-3009 signer implementation\n\n### Configuration\n\n```typescript\nimport { X402Rail } from \"@mnemopay/sdk\";\n\nconst x402 = new X402Rail({ signer: yourEip3009Signer });\n```\n\n资料来源：[README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)\n\n## GoogleAP2Rail\n\nGoogleAP2Rail implements the FIDO Alliance's AP2 (Authorizing Payment 2.0) v0.2 specification, providing mandate-driven settlement with FIDO-based authentication.\n\n### Features\n\n- **AP2 v0.2**: Implements FIDO Alliance payment authentication standard\n- **Mandate-Driven**: Settlement occurs based on pre-authorized mandates\n- **FIDO Integration**: Leverages FIDO authentication for payment authorization\n\n### Configuration\n\n```typescript\nimport { GoogleAP2Rail } from \"@mnemopay/sdk\";\n\nconst ap2 = new GoogleAP2Rail({ mandate, endpoint, signer });\n```\n\n资料来源：[README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[MnemoPay Agent] --> B[PaymentRail Interface]\n    B --> C[Stable Rails]\n    B --> D[Alpha Rails]\n    \n    C --> C1[StripeRail]\n    C --> C2[PaystackRail]\n    C --> C3[LightningRail]\n    \n    D --> D1[StripeMPPRail]\n    D --> D2[X402Rail]\n    D --> D3[GoogleAP2Rail]\n    \n    D1 --> D1A[Stripe MPP API<br/>2026-03-04.preview]\n    D1A --> D1B[Tempo Network<br/>Crypto Deposits]\n    \n    D2 --> D2A[EIP-3009<br/>transferWithAuthorization]\n    D2A --> D2B[Base Network<br/>USDC]\n    \n    D3 --> D3A[AP2 v0.2<br/>FIDO Alliance]\n    D3A --> D3B[Mandate-Driven<br/>Settlement]\n```\n\n## Payment Rail Comparison\n\n| Feature | StripeRail | StripeMPPRail | X402Rail | GoogleAP2Rail |\n|---------|------------|---------------|----------|---------------|\n| Currency | USD, EUR, GBP | Crypto (Tempo) | USDC | Multi-currency |\n| Network | Stripe | Tempo | Base L2 | FIDO Network |\n| Escrow | Manual capture | Manual capture | Authorization-based | Mandate-based |\n| Auth Method | Stripe Auth | Stripe MPP | EIP-3009 Signer | FIDO Auth |\n| Status | Stable | Alpha | Alpha | Alpha |\n| API Version | Latest | 2026-03-04.preview | N/A | v0.2 |\n\n## Installation\n\nAlpha rails are available under the `alpha` npm dist-tag:\n\n```bash\nnpm install @mnemopay/sdk@alpha\n```\n\nThe default `latest` dist-tag still points at `1.5.0` (stable). Opt in to alpha with the above command.\n\n资料来源：[CHANGELOG.md:6-14](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n\n## Usage Example\n\n```typescript\nimport {\n  PaystackRail, StripeRail, LightningRail,    // stable\n  StripeMPPRail, X402Rail, GoogleAP2Rail,      // alpha\n} from \"@mnemopay/sdk\";\n\n// Stable rails\nconst paystack  = new PaystackRail(process.env.PAYSTACK_SECRET_KEY!);\nconst stripe    = new StripeRail(process.env.STRIPE_SECRET_KEY!);\nconst lightning = new LightningRail(LND_URL, MACAROON);\n\n// Alpha preview rails\nconst mpp   = new StripeMPPRail(process.env.STRIPE_SECRET_KEY!);\nconst x402  = new X402Rail({ signer: yourEip3009Signer });   // bring-your-own crypto\nconst ap2   = new GoogleAP2Rail({ mandate, endpoint, signer });\n```\n\n资料来源：[README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)\n\n## Road to v1.6.0\n\nThe full `1.6.0` minor release will ship when the v1.6.x rail sprint completes, including:\n\n- Stripe MPP native integration\n- x402 native integration\n- Google AP2 native integration\n- Python rail port\n\n资料来源：[CHANGELOG.md:14-17](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n\n## Important Notes\n\n### Experimental Status\n\nAlpha rails are tagged `@experimental` and subject to API changes:\n\n> \"preview API can change without semver guarantees from Stripe; pin `apiVersion` in production\"\n\nFor production deployments of StripeMPPRail, it is recommended to pin the `apiVersion` to prevent unexpected breaking changes.\n\n资料来源：[CHANGELOG.md:34-35](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n\n### Future Stable Release\n\nWhen the v1.6.0 stable release ships, the `latest` npm tag will be updated to point to the version containing these rails as stable implementations.\n\n---\n\n<a id='charter-fiscalgate'></a>\n\n## Charter & FiscalGate Governance\n\n### 相关页面\n\n相关主题：[MerkleAudit & Hash-Chained Ledger](#merkle-audit), [Identity & KYA Compliance](#identity-kya), [System Architecture](#architecture)\n\n<details>\n<summary>Related Source Files</summary>\n\nThe following source files were used to generate this documentation:\n\n- [src/governance/charter.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/governance/charter.ts)\n- [src/governance/payments.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/governance/payments.ts)\n- [src/governance/article12.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/governance/article12.ts)\n- [src/governance/policies/eu-ai-act.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/governance/policies/eu-ai-act.ts)\n</details>\n\n# Charter & FiscalGate Governance\n\n## Overview\n\nThe **Charter & FiscalGate Governance** module is a first-class system within the MnemoPay SDK that provides budget enforcement, mission scoping, and regulatory audit capabilities for AI agents that handle financial operations. This governance layer ensures agents operate within defined constraints while maintaining transparent, verifiable audit trails.\n\n```\n┌──────────────────────────────────────────────────────────────────┐\n│                    GOVERNANCE LAYER                              │\n├──────────────────────────────────────────────────────────────────┤\n│  Charter · FiscalGate · Article 12 · MerkleAudit               │\n│  mission scope, budget enforcement, audit bundles                │\n└──────────────────────────────────────────────────────────────────┘\n```\n\n资料来源：[README.md]()\n\n## Purpose & Scope\n\nThe governance module addresses critical requirements for production AI agent deployments:\n\n1. **Mission Scope Declaration** — Defines what tools and operations an agent is authorized to perform\n2. **Budget Enforcement** — Reserves and limits financial resources before mission execution\n3. **Audit Trail** — Generates tamper-evident logs and regulator-ready documentation\n4. **Compliance** — Aligns with EU AI Act Article 12 requirements for high-risk AI systems\n\n资料来源：[CHANGELOG.md]()\n\n## Architecture\n\n### System Components\n\n```mermaid\ngraph TD\n    A[MnemoPay SDK] --> B[Governance Module]\n    B --> C[Charter]\n    B --> D[FiscalGate]\n    B --> E[MerkleAudit]\n    B --> F[Article12Bundle]\n    B --> G[PaymentsAdapter]\n    \n    C --> H[Mission Declaration]\n    C --> I[Allowed Tools]\n    C --> J[Budget Cap]\n    \n    D --> K[Budget Reservation]\n    D --> L[Agent Loop Execution]\n    D --> M[Spend Settlement]\n    \n    E --> N[SHA-256 Chain]\n    E --> O[Event Replay]\n    E --> P[Tamper Detection]\n    \n    F --> Q[mission.json]\n    F --> R[events.json]\n    F --> S[events.csv]\n    F --> T[chain.txt]\n    F --> U[manifest.json]\n```\n\n资料来源：[CHANGELOG.md]()\n\n### Data Flow\n\n```mermaid\nsequenceDiagram\n    participant A as Agent\n    participant C as Charter\n    participant F as FiscalGate\n    participant M as MerkleAudit\n    participant P as Payments\n    participant R as Regulator\n\n    A->>C: Submit mission declaration\n    C->>C: validateCharter()\n    C-->>F: Validated charter\n    \n    F->>M: Initialize audit chain\n    F->>P: Reserve budget (charter.budgetCap)\n    F->>A: Begin mission execution\n    \n    loop Mission Operations\n        A->>F: Operation request\n        F->>M: Log event (sha256)\n        F->>P: Check budget remaining\n        P-->>F: Budget status\n        F-->>A: Approved/Rejected\n    end\n    \n    alt Success\n        F->>P: Settle actual spend\n        F->>M: Finalize chain\n        F->>R: buildArticle12Bundle()\n    else Halt/Error\n        F->>P: Release reserved budget\n        F->>M: Log termination event\n    end\n```\n\n## Core Components\n\n### 1. Charter\n\nThe `Charter` schema declares an agent mission's goal, authorized tools, and budget constraints.\n\n```typescript\ninterface Charter {\n  missionId: string;\n  goal: string;\n  allowedTools: string[];\n  budgetCap: number;\n  currency: string;\n  createdAt: Date;\n}\n```\n\n#### Charter Validation\n\nThe `validateCharter()` function ensures mission declarations are well-formed and within acceptable parameters:\n\n- Validates required fields are present\n- Checks budget cap is a positive value\n- Verifies allowed tools list is non-empty\n- Ensures goal description is meaningful\n\n资料来源：[src/governance/charter.ts]()\n\n### 2. FiscalGate\n\nThe `FiscalGate` primitive (`runMission()`) is the core budget enforcement mechanism.\n\n```typescript\ninterface FiscalGateResult {\n  status: \"ok\" | \"halted\" | \"error\";\n  spentUsd: number;\n  outputs: any[];\n  auditDigest: string;\n  // ... additional fields\n}\n```\n\n#### Execution Flow\n\n```mermaid\ngraph TD\n    A[runMission ctx] --> B[Reserve full budget]\n    B --> C[Execute agent loop]\n    C --> D{All operations complete?}\n    D -->|Yes| E{Spent within budget?}\n    D -->|No| F[Log operation]\n    F --> C\n    E -->|Yes| G[Settle actual spend]\n    E -->|No| H[Release excess reservation]\n    G --> I[Return ok status]\n    H --> I\n    D -->|Halt signal| J[Release budget]\n    D -->|Error| K[Release budget]\n    J --> L[Return halted status]\n    K --> M[Return error status]\n```\n\n#### Key Behaviors\n\n| Scenario | Action | Result |\n|----------|--------|--------|\n| Mission succeeds | Settle actual spend | `status: \"ok\"` |\n| Mission halts early | Release reserved budget | `status: \"halted\"` |\n| Error occurs | Release reserved budget | `status: \"error\"` |\n| Overspend attempted | Block operation | Budget preserved |\n\n资料来源：[CHANGELOG.md](), [src/governance/payments.ts]()\n\n### 3. MerkleAudit\n\nThe `MerkleAudit` system provides a SHA-256 chained event log with verification capabilities.\n\n```typescript\ninterface MerkleAudit {\n  // Core methods\n  log(event: AuditEvent): void;\n  verify(): boolean;\n  toJSON(): AuditLog;\n  \n  // Event subscription\n  on(event: string, callback: Function): void;\n  \n  // Deterministic operations\n  replay(): AuditEvent[];\n}\n```\n\n#### Chain Structure\n\n```mermaid\ngraph LR\n    E1[Event 1] --> H1[Hash 1]\n    H1 --> E2[Event 2]\n    E2 --> H2[Hash 2]\n    H2 --> E3[Event 3]\n    E3 --> H3[Hash 3]\n    \n    style H1 fill:#f96\n    style H2 fill:#f96\n    style H3 fill:#f96\n```\n\n#### Verification Methods\n\n| Method | Purpose |\n|--------|---------|\n| `verify()` | Validates chain integrity |\n| `toJSON()` | Exports audit log for storage |\n| `replay()` | Reconstructs deterministic state |\n\n资料来源：[CHANGELOG.md]()\n\n### 4. Article 12 Bundle\n\nThe `buildArticle12Bundle()` function generates regulator-handable documentation for EU AI Act compliance.\n\n```typescript\ninterface Article12Bundle {\n  charter: Charter;\n  result: FiscalGateResult;\n  audit: MerkleAudit;\n  \n  // Output files\n  mission: string;      // mission.json\n  events: string;      // events.json\n  eventsCsv: string;   // events.csv\n  chain: string;       // chain.txt\n  manifest: {\n    checksums: Record<string, string>;\n    retention: {\n      policy: string;\n      expiresAt: string;\n    };\n  };\n}\n```\n\n#### Default Retention Policy\n\n| Jurisdiction | Retention Period | Legal Basis |\n|--------------|------------------|-------------|\n| European Union | 6 months | EU AI Act Article 12 |\n| Default | 6 months | EU AI Act Article 12 |\n\n资料来源：[CHANGELOG.md](), [src/governance/article12.ts](), [src/governance/policies/eu-ai-act.ts]()\n\n### 5. PaymentsAdapter\n\nA pluggable interface for payment processing backends.\n\n```typescript\ninterface PaymentsAdapter {\n  charge(amount: number, currency: string): Promise<ChargeResult>;\n  settle(transactionId: string): Promise<SettleResult>;\n  refund(transactionId: string): Promise<RefundResult>;\n  getBalance(): Promise<Balance>;\n}\n\nclass MockPayments implements PaymentsAdapter {\n  // Reference implementation for testing\n}\n```\n\n#### Built-in Implementations\n\n| Implementation | Use Case |\n|---------------|----------|\n| `MockPayments` | Unit testing, development |\n| `StripePaymentsAdapter` | Production (global) |\n| `PaystackPaymentsAdapter` | Production (Africa) |\n| `LightningPaymentsAdapter` | Production (micropayments) |\n\n资料来源：[CHANGELOG.md](), [src/governance/payments.ts]()\n\n## API Reference\n\n### Functions\n\n#### `validateCharter(charter: Charter): ValidationResult`\n\nValidates a charter declaration before mission execution.\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `charter` | `Charter` | Mission charter to validate |\n| **Returns** | `ValidationResult` | Contains `valid: boolean` and optional `errors: string[]` |\n\n#### `runMission(ctx: MissionContext): Promise<FiscalGateResult>`\n\nExecutes an agent mission with budget enforcement.\n\n```typescript\ninterface MissionContext {\n  charter: Charter;\n  agentLoop: () => Promise<void>;\n  onOperation?: (op: Operation) => void;\n}\n\ninterface FiscalGateResult {\n  status: \"ok\" | \"halted\" | \"error\";\n  spentUsd: number;\n  outputs: any[];\n  auditDigest: string;\n  terminatedAt?: Date;\n  error?: string;\n}\n```\n\n#### `buildArticle12Bundle(params: BundleParams): Article12Bundle`\n\nGenerates a regulatory audit bundle.\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `params.charter` | `Charter` | Mission charter |\n| `params.result` | `FiscalGateResult` | Mission execution result |\n| `params.audit` | `MerkleAudit` | Audit log |\n\n#### `new MerkleAudit(options?: AuditOptions): MerkleAudit`\n\nCreates a new audit chain instance.\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `chainId` | `string` | Auto-generated | Unique chain identifier |\n| `events` | `AuditEvent[]` | `[]` | Initial events |\n| `retentionDays` | `number` | `180` | Log retention period |\n\n资料来源：[src/governance/charter.ts](), [src/governance/payments.ts](), [src/governance/article12.ts]()\n\n## EU AI Act Compliance\n\nThe governance module implements compliance measures for EU AI Act Article 12, which requires high-risk AI systems to maintain:\n\n1. **Logging of operations** — All agent actions recorded with timestamps\n2. **Traceability** — Individual operations attributable to specific events\n3. **Transparency** — Audit bundles provide human-readable documentation\n4. **Retention** — 6-month minimum log retention\n\n```typescript\n// EU AI Act Article 12 compliance configuration\nconst euCompliance = {\n  article: \"Article 12\",\n  jurisdiction: \"European Union\",\n  retentionMonths: 6,\n  requirements: [\n    \"operation_logging\",\n    \"event_traceability\", \n    \"human_oversight\",\n    \"audit_trail\"\n  ]\n};\n```\n\n资料来源：[src/governance/policies/eu-ai-act.ts]()\n\n## Testing\n\nThe governance module includes comprehensive test coverage in `tests/governance.spec.ts`:\n\n| Test Category | Coverage |\n|---------------|----------|\n| Charter validation | Valid/invalid charter scenarios |\n| MerkleAudit chain | Hash linking, tamper detection |\n| FiscalGate paths | Happy path, halt, error scenarios |\n| Article 12 bundle | File generation, checksum validation |\n\n资料来源：[CHANGELOG.md]()\n\n## Usage Example\n\n```typescript\nimport { \n  Charter, \n  validateCharter, \n  runMission, \n  MerkleAudit, \n  buildArticle12Bundle,\n  MockPayments \n} from \"@mnemopay/sdk/governance\";\n\n// 1. Declare mission charter\nconst charter: Charter = {\n  missionId: \"procurement-001\",\n  goal: \"Purchase office supplies under $500\",\n  allowedTools: [\"search\", \"compare\", \"buy\"],\n  budgetCap: 500,\n  currency: \"USD\",\n  createdAt: new Date()\n};\n\n// 2. Validate charter\nconst validation = validateCharter(charter);\nif (!validation.valid) {\n  throw new Error(`Invalid charter: ${validation.errors.join(\", \")}`);\n}\n\n// 3. Create audit trail\nconst audit = new MerkleAudit({ retentionDays: 180 });\n\n// 4. Execute mission with budget enforcement\nconst result = await runMission({\n  charter,\n  agentLoop: async () => {\n    // Agent operations here\n  }\n});\n\n// 5. Generate regulatory bundle\nconst bundle = buildArticle12Bundle({\n  charter,\n  result,\n  audit\n});\n```\n\n## Summary\n\nThe Charter & FiscalGate Governance system provides:\n\n- **Declarative mission scoping** via Charter documents\n- **Automatic budget enforcement** through FiscalGate\n- **Tamper-evident logging** via MerkleAudit chains\n- **Regulatory compliance** with EU AI Act Article 12 bundles\n- **Pluggable payments** via PaymentsAdapter interface\n\nThis governance infrastructure ensures AI agents operate responsibly within financial constraints while maintaining the audit trails required for regulatory compliance and operational transparency.\n\n---\n\n<a id='merkle-audit'></a>\n\n## MerkleAudit & Hash-Chained Ledger\n\n### 相关页面\n\n相关主题：[Charter & FiscalGate Governance](#charter-fiscalgate), [Core Modules Reference](#core-modules)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/governance/audit-chain.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/governance/audit-chain.ts)\n- [src/governance/audit.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/governance/audit.ts)\n- [src/integrity.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/integrity.ts)\n- [src/ledger.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/ledger.ts)\n- [tests/governance.spec.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/tests/governance.spec.ts)\n</details>\n\n# MerkleAudit & Hash-Chained Ledger\n\n## Overview\n\nMerkleAudit and Hash-Chained Ledger form the cryptographic integrity backbone of the MnemoPay SDK. These two systems work together to provide verifiable, tamper-evident event logging and transaction recording for AI agents operating in financial workflows.\n\n**Purpose:** The system ensures that every event and ledger entry can be independently verified, that modifications to historical data are immediately detectable, and that audit trails meet regulatory requirements such as EU AI Act Article 12.\n\n**Key Characteristics:**\n- SHA-256 cryptographic chaining for sequential integrity\n- Merkle tree verification for memory integrity\n- Deterministic replay for audit verification\n- Listener subscriptions for real-time monitoring\n- Three independent tamper-detection layers\n\n资料来源：[CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n\n## Architecture\n\nThe integrity system consists of three independent layers working in concert:\n\n```mermaid\ngraph TD\n    A[Tamper Detection Layers] --> B[Hash-Chained Ledger]\n    A --> C[Merkle Integrity on Memories]\n    A --> D[HMAC on Transactions]\n    \n    B --> E[SHA-256 Sequential Linking]\n    C --> F[Merkle Tree Verification]\n    D --> G[HMAC-SHA512 Security]\n```\n\n### Layer 1: Hash-Chained Ledger\n\nThe ledger maintains a double-entry accounting system where every entry links to the previous entry via SHA-256 hash. If any entry is modified, the chain breaks instantly, making tampering immediately detectable.\n\n资料来源：[site/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)\n\n### Layer 2: Merkle Integrity on Memories\n\nThe MerkleAudit system provides Merkle tree-based verification for agent memories, ensuring that stored memory states can be cryptographically verified.\n\n### Layer 3: HMAC on Transactions\n\nTransaction-level HMAC-SHA512 security provides an additional verification layer for financial operations.\n\n## MerkleAudit System\n\n### Core Components\n\n| Component | Purpose |\n|-----------|---------|\n| `audit-chain.ts` | SHA-256 chained event log implementation |\n| `audit.ts` | Core audit primitives and verification |\n| `verify()` | Chain integrity verification method |\n| `toJSON()` | Serialization for audit export |\n| Listeners | Real-time event subscription system |\n| Deterministic Replay | Reproducible audit reconstruction |\n\n资料来源：[CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n\n### Event Log Structure\n\nThe MerkleAudit system maintains a sequentially chained event log where each event contains:\n\n```mermaid\ngraph LR\n    A[Event N] --> B[SHA-256 Hash of Event N]\n    B --> C[Links to Event N-1 Hash]\n    C --> D[Event N-1]\n    D --> E[SHA-256 Hash of Event N-1]\n    E --> F[Links to Event N-2 Hash]\n```\n\n### Verification Process\n\nThe `verify()` method performs chain integrity checks by:\n\n1. Computing the hash of each event in sequence\n2. Comparing computed hashes against stored hashes\n3. Validating chain link integrity between consecutive events\n4. Reporting any detected breaks or inconsistencies\n\n### Listener Subscriptions\n\nThe system supports listener subscriptions for real-time monitoring:\n\n- Events can trigger registered callbacks as they are appended\n- Listeners receive the full event context upon notification\n- Supports multiple concurrent subscribers\n\n### Deterministic Replay\n\nThe deterministic replay feature enables:\n\n- Complete reconstruction of audit state from the chain\n- Reproducible verification of past states\n- Compliance with regulatory audit requirements\n\n## Hash-Chained Ledger\n\n### Double-Entry Accounting\n\nThe ledger implements true double-entry bookkeeping where every transaction affects at least two accounts:\n\n```mermaid\ngraph TD\n    A[Transaction] --> B[Debit Entry]\n    A --> C[Credit Entry]\n    B --> D[Account A Balance]\n    C --> E[Account B Balance]\n    D --> F[Ledger Balanced ✓]\n    E --> F\n```\n\n### Chain Integrity Mechanism\n\n| Feature | Description |\n|---------|-------------|\n| Hash Algorithm | SHA-256 |\n| Chain Structure | Each entry references previous entry's hash |\n| Detection | Any modification breaks the chain instantly |\n| Verification | Sequential hash recomputation and comparison |\n\n资料来源：[site/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)\n\n### Transaction Flow\n\n```mermaid\nsequenceDiagram\n    participant Agent\n    participant Ledger\n    participant Escrow\n    participant Verification\n    \n    Agent->>Ledger: Initiate Transaction\n    Ledger->>Verification: Compute Previous Hash\n    Verification->>Ledger: Hash Verified\n    Ledger->>Ledger: Append with Chain Link\n    Ledger->>Escrow: Hold Funds\n    Escrow->>Agent: Escrow Confirmed\n```\n\n## API Reference\n\n### MerkleAudit Core Methods\n\n#### `verify()`\n\nVerifies the complete chain integrity.\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `startIndex` | `number` | Optional starting point for verification |\n| `endIndex` | `number` | Optional ending point for verification |\n\n#### `toJSON()`\n\nSerializes the audit chain to JSON format for export and storage.\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `compact` | `boolean` | Optional compact representation |\n\n### Ledger Methods\n\n#### Transaction Operations\n\n| Method | Purpose |\n|--------|---------|\n| `charge()` | Initiate a charge with escrow hold |\n| `settle()` | Release escrowed funds |\n| `refund()` | Process a refund transaction |\n| `dispute()` | Open a dispute on a transaction |\n\n资料来源：[site/index.legacy.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)\n\n## Test Coverage\n\nThe governance module includes comprehensive test coverage:\n\n- **11 governance tests** in `tests/governance.spec.ts`\n- Charter validation tests\n- MerkleAudit chain and tamper detection tests\n- FiscalGate happy path, halt, and error path tests\n- Article 12 bundle generation tests\n\n资料来源：[CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n\n### Test Categories\n\n| Category | Coverage |\n|----------|----------|\n| Chain Integrity | Verification of unbroken hash chain |\n| Tamper Detection | Detection of modified entries |\n| Replay Accuracy | Deterministic replay verification |\n| Listener Events | Real-time notification testing |\n\n## Integration with Governance Module\n\nMerkleAudit integrates deeply with the Governance module:\n\n### Article 12 Compliance\n\nThe system supports EU AI Act Article 12 audit requirements:\n\n- **6-month default retention** period\n- **Deterministic SHA-256 digest** for tamper detection\n- **Compliance bundle generation** via `buildArticle12Bundle()`\n\n### Audit Bundle Structure\n\nWhen generating Article 12 compliance bundles:\n\n```mermaid\ngraph TD\n    A[buildArticle12Bundle] --> B[mission.json]\n    A --> C[events.json]\n    A --> C2[events.csv]\n    A --> D[chain.txt]\n    A --> E[manifest.json]\n    \n    E --> F[Checksums]\n    E --> G[Retention Metadata]\n```\n\n### FiscalGate Integration\n\nThe `runMission(ctx)` function uses the audit chain for mission execution:\n\n1. Reserves full charter budget up-front\n2. Runs the agent loop with ledger recording\n3. Settles actual spend on success\n4. Releases reserved funds on halt/error\n5. Returns audit digest for verification\n\n## Security Properties\n\n### Tamper Detection\n\n| Attack Vector | Detection Mechanism |\n|---------------|---------------------|\n| Single Entry Modification | SHA-256 hash mismatch |\n| Chain Reordering | Sequential link validation |\n| Entry Deletion | Hash chain break detection |\n| Memory Manipulation | Merkle tree verification |\n\n### Cryptographic Guarantees\n\n- **Pre-image Resistance**: Cannot derive previous entries from current hash\n- **Collision Resistance**: Cannot find two events with same hash\n- **Chain Binding**: Each entry cryptographically bound to all predecessors\n\n## Best Practices\n\n### Audit Trail Maintenance\n\n1. **Regular Verification**: Periodically run `verify()` on the audit chain\n2. **Backup Chain State**: Export via `toJSON()` for disaster recovery\n3. **Monitor Listeners**: Implement listeners to track chain modifications\n4. **Retention Compliance**: Configure appropriate retention periods for regulatory needs\n\n### Ledger Operations\n\n1. **Always Verify Before Settlement**: Check chain integrity before fund release\n2. **Use Escrow**: Hold funds until human approval for autonomous transactions\n3. **Monitor Disputes**: Track dispute patterns for fraud detection\n4. **Maintain Credit Score**: Higher scores yield lower transaction fees\n\n## Conclusion\n\nMerkleAudit and the Hash-Chained Ledger provide the cryptographic foundation for trustworthy AI agent financial operations. With SHA-256 chaining, Merkle tree verification, and HMAC transaction security, the system ensures that every event and transaction is verifiable, tamper-evident, and compliant with regulatory requirements.\n\n资料来源：[site/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)\n\n---\n\n<a id='identity-kya'></a>\n\n## Identity & KYA Compliance\n\n### 相关页面\n\n相关主题：[Charter & FiscalGate Governance](#charter-fiscalgate)\n\n<details>\n<summary>Relevant Source Files</summary>\n\nThe following source files were retrieved and used to generate this documentation:\n\n- [dashboard/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/dashboard/index.html)\n- [README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)\n\nNote: The identity module source files (`src/identity/index.ts`, `src/identity/wallet.ts`, `src/identity/bundle.ts`, `src/identity/did.ts`) referenced in the task were not available in the retrieved repository context. This documentation is based on the architectural references and dashboard implementation found in the available context.\n</details>\n\n# Identity & KYA Compliance\n\n## Overview\n\nIdentity & KYA (Know Your Agent) Compliance is a core pillar of the MnemoPay SDK architecture, providing identity management, permission controls, and compliance verification for AI agents that handle financial transactions.\n\nThe Identity subsystem enables autonomous agents to establish verified digital identities, manage session authentication, control access permissions, and maintain compliance with regulatory requirements through a multi-layered approach.\n\n资料来源：[README.md:1-50]()\n\n## Architecture\n\n```mermaid\ngraph TD\n    subgraph Identity & KYA Compliance\n        DID[Decentralized ID]\n        SES[Session Management]\n        PERM[Permissions]\n        KILL[Killswitch]\n        TOKEN[Token Economy]\n        BRAIN[Memory Brain]\n    end\n    \n    subgraph Agent Operations\n        CHARGE[charge()]\n        SETTLE[settle()]\n        REFUND[refund()]\n    end\n    \n    DID --> SES\n    SES --> PERM\n    PERM --> KILL\n    SES --> TOKEN\n    DID --> BRAIN\n    \n    PERM --> CHARGE\n    PERM --> SETTLE\n    PERM --> REFUND\n```\n\n## Core Components\n\n### Session Management\n\nThe Session Panel provides authenticated session handling for agent identities. It integrates with the dashboard's operator console to manage sign-in and sign-out operations for agent accounts.\n\n| Component | Description |\n|-----------|-------------|\n| `session.session?.accountId` | Unique account identifier for the authenticated agent |\n| `session.session?.email` | Associated email for the session |\n| `session.authenticated` | Boolean flag indicating authentication status |\n| `onLogin` | Callback function for session authentication |\n| `onLogout` | Callback function for session termination |\n\n资料来源：[dashboard/index.html:200-230]()\n\n#### Session State Display\n\nThe dashboard conditionally renders session status based on authentication state:\n\n```tsx\n{session?.authenticated ? (\n  <div className=\"text-right\">\n    <div className=\"text-xs text-gray-500 uppercase tracking-wider\">Signed in as</div>\n    <div className=\"text-sm font-mono text-white\">{sanitize(session.session?.email || '—')}</div>\n    <div className=\"text-[10px] text-gray-500 font-mono\">account: {sanitize(session.session?.accountId || accountId)}</div>\n  </div>\n) : (\n  <div className=\"text-right\">\n    <div className=\"text-xs text-amber-400 uppercase tracking-wider\">Not signed in</div>\n    <div className=\"text-[10px] text-gray-500 font-mono\">account: {sanitize(accountId)} (anonymous)</div>\n  </div>\n)}\n```\n\n资料来源：[dashboard/index.html:150-170]()\n\n### Permission Controls\n\nThe permission system gates critical financial operations. Agents must have appropriate permissions before executing `charge()`, `settle()`, or `refund()` operations.\n\n| Permission Type | Purpose |\n|-----------------|---------|\n| Charge Permission | Allows agent to initiate payment collection |\n| Settle Permission | Allows agent to release escrowed funds |\n| Refund Permission | Allows agent to process refunds |\n| Admin Permission | Allows management of API keys and billing |\n\n### Killswitch\n\nThe killswitch mechanism provides emergency shutdown capability for agent operations. When triggered, it immediately revokes all active permissions and halts pending transactions.\n\n```mermaid\ngraph LR\n    A[Anomaly Detected] --> B{Killswitch Active?}\n    B -->|Yes| C[Revoke All Permissions]\n    B -->|No| D[Log Warning]\n    C --> E[Cancel Pending Transactions]\n    E --> F[Notify Compliance System]\n```\n\n### Token Economy\n\nThe Identity module integrates with MnemoPay's token-based economy:\n\n| Parameter | Value | Description |\n|-----------|-------|-------------|\n| Ceiling | `500 × reputation` | Maximum charge per transaction |\n| Decay | 0.05 | Half-life approximately 14 hours |\n| Feedback Loop | +0.05 | Importance reinforcement on settle |\n\n资料来源：[dashboard/index.html:350-360]()\n\n## Compliance Workflow\n\n```mermaid\ngraph TD\n    A[Agent Initialization] --> B[Create Session]\n    B --> C{KYA Verification}\n    C -->|Pass| D[Assign Permissions]\n    C -->|Fail| E[Restricted Mode]\n    D --> F[Enable Financial Ops]\n    E --> G[Monitor & Retry]\n    G --> C\n    F --> H[Log to Audit Trail]\n    H --> I[Periodic Compliance Check]\n    I -->|Compliant| F\n    I -->|Violation| J[Killswitch Triggered]\n```\n\n## Dashboard Integration\n\nThe Identity & KYA Compliance features are accessible through the MnemoPay Console dashboard via the Session tab:\n\n```tsx\n{tab === 'session' && <SessionPanel \n  session={session} \n  accountId={accountId} \n  members={overview?.members || []} \n  onLogin={loginSession} \n  onLogout={logoutSession} \n  onRefresh={fetchAll} \n/>}\n```\n\n资料来源：[dashboard/index.html:400-410]()\n\n### Available Controls\n\n| Control | Function |\n|---------|----------|\n| Account ID Input | Specify target account for session operations |\n| Refresh Button | Fetch latest session and compliance status |\n| Login | Authenticate and establish session |\n| Logout | Terminate session and clear credentials |\n| Members List | View team members with identity status |\n\n## Developer API Keys\n\nThe Developer Panel manages API keys that authenticate agent-to-platform communications:\n\n| Feature | Description |\n|---------|-------------|\n| List Keys | View all active API keys for the account |\n| Create Key | Generate new provisioning secret |\n| Revoke Key | Immediately invalidate an existing key |\n\n资料来源：[dashboard/index.html:280-310]()\n\n## Security Considerations\n\n### Authentication Flow\n\n1. Agent requests session with valid credentials\n2. System verifies KYA compliance status\n3. On success, session token is issued with scoped permissions\n4. All subsequent API calls include session token\n5. Session expires after configured TTL or manual logout\n\n### Anomaly Detection\n\nThe compliance system monitors agent behavior patterns:\n\n- Unusual transaction volumes\n- Unexpected geographic access patterns\n- Rapid permission escalation attempts\n- Deviations from established operational baselines\n\n资料来源：[README.md:1-30]()\n\n## Billing & Compliance Metrics\n\nThe Billing Panel displays compliance-related metrics:\n\n| Metric | Description |\n|--------|-------------|\n| Missions | Current period transaction count |\n| Seats | Active agent identities under management |\n| Plan Gate | Compliance status (Active/Limit Reached) |\n| Over Limit | Boolean indicating if usage exceeds plan |\n\n资料来源：[dashboard/index.html:320-340]()\n\n## Related Documentation\n\n- [Agent Credit Score](https://github.com/mnemopay/mnemopay-sdk) — Agent scoring for compliance gating\n- [Behavioral Finance](https://github.com/mnemopay/mnemopay-sdk) — Prospect theory and nudge mechanisms\n- [Anomaly Detection](https://github.com/mnemopay/mnemopay-sdk) — EWMA and fingerprinting systems\n- [Audit Trail](https://github.com/mnemopay/mnemopay-sdk) — Ledger health and compliance logging\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：mnemopay/mnemopay-sdk\n\n摘要：发现 8 个潜在踩坑项，其中 1 个为 high/blocking；最高优先级：安全/权限坑 - 涉及密钥、隐私或敏感领域。\n\n## 1. 安全/权限坑 · 涉及密钥、隐私或敏感领域\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：项目文本出现 secret/private key/privacy/trading/finance 等敏感关键词。\n- 对用户的影响：金融、交易、隐私和密钥场景必须比普通工具更保守。\n- 建议检查：补敏感数据流、密钥存储和权限边界审查。\n- 防护动作：敏感领域或密钥场景必须保守推荐并要求人工复核。\n- 证据：packet_text.keyword_scan | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | matched secret / private key / privacy / trading / finance keyword\n\n## 2. 身份坑 · 仓库名和安装名不一致\n\n- 严重度：medium\n- 证据强度：runtime_trace\n- 发现：仓库名 `mnemopay-sdk` 与安装入口 `@mnemopay/sdk` 不完全一致。\n- 对用户的影响：用户照着仓库名搜索包或照着包名找仓库时容易走错入口。\n- 建议检查：在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。\n- 复现命令：`npm install @mnemopay/sdk`\n- 防护动作：页面必须同时展示 repo 名和真实安装入口，避免用户搜索错包。\n- 证据：identity.distribution | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | repo=mnemopay-sdk; install=@mnemopay/sdk\n\n## 3. 能力坑 · 能力判断依赖假设\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:1197975871 | https://github.com/mnemopay/mnemopay-sdk | README/documentation is current enough for a first validation pass.\n\n## 4. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | last_activity_observed missing\n\n## 5. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | no_demo; severity=medium\n\n## 6. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | no_demo; severity=medium\n\n## 7. 维护坑 · 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:1197975871 | https://github.com/mnemopay/mnemopay-sdk | issue_or_pr_quality=unknown\n\n## 8. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | release_recency=unknown\n\n<!-- canonical_name: mnemopay/mnemopay-sdk; human_manual_source: deepwiki_human_wiki -->\n",
      "markdown_key": "mnemopay-sdk",
      "pages": "draft",
      "source_refs": [
        {
          "evidence_id": "github_repo:1197975871",
          "kind": "repo",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/mnemopay/mnemopay-sdk"
        },
        {
          "evidence_id": "art_797bd2c621934f13bff10e9e3de1dc3e",
          "kind": "docs",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/mnemopay/mnemopay-sdk#readme"
        }
      ],
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "mnemopay-sdk 说明书",
      "toc": [
        "https://github.com/mnemopay/mnemopay-sdk 项目说明书",
        "目录",
        "Introduction to MnemoPay SDK",
        "Overview",
        "Architecture",
        "Two SDK Modes",
        "Quick Start",
        "Memory System",
        "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": "c47f76cd6240494e55bea1c2e399a8d82f45f0cf",
    "repo_inspection_error": null,
    "repo_inspection_files": [
      "Dockerfile",
      "package.json",
      "README.md",
      "docker-compose.yml",
      "docs/agent-memory-sota-2026-04.md",
      "docs/AUTO-OBSERVER-DESIGN.md",
      "docs/PRODUCT-UPGRADE-ROADMAP-2026-05.md",
      "docs/agent-sdk-guide.md",
      "docs/aaif-rfc-agent-trust-attestation.md",
      "docs/CLAUDE-WORK-PATTERN.md",
      "docs/strategy-2026-05-06/mcp-hive-application.md",
      "docs/strategy-2026-05-06/session-summary.md",
      "docs/strategy-2026-05-06/praetor-split-execution-plan.md",
      "docs/pitch/linux-foundation-reply.md",
      "docs/pitch/claude-design-prompts.md",
      "docs/pitch/eu-ai-act-pitch.md",
      "docs/pitch/one-pager.md",
      "docs/pitch/investor-deck.md",
      "examples/01-quick-start.ts",
      "examples/03-anthropic-middleware.ts",
      "examples/04-langgraph-agent.ts",
      "examples/05-agents-hiring-agents.ts",
      "examples/02-openai-middleware.ts",
      "examples/06-production.ts",
      "src/behavioral.ts",
      "src/claude-cache.ts",
      "src/ledger.ts",
      "src/anomaly.ts",
      "src/adaptive.ts",
      "src/subagent-cost.ts",
      "src/fraud.ts",
      "src/network.ts",
      "src/index.ts",
      "src/client.ts",
      "src/commerce.ts",
      "src/fraud-ml.ts",
      "src/integrity.ts",
      "src/identity.ts",
      "src/fico.ts",
      "src/cli/setup.ts"
    ],
    "repo_inspection_verified": true,
    "review_reasons": [
      "community_discussion_evidence_below_public_threshold"
    ],
    "tag_count_ok": true,
    "unsupported_claims": []
  },
  "schema_version": "0.1",
  "user_assets": {
    "ai_context_pack": {
      "asset_id": "ai_context_pack",
      "filename": "AI_CONTEXT_PACK.md",
      "markdown": "# @mnemopay/sdk - Doramagic AI Context Pack\n\n> 定位：安装前体验与判断资产。它帮助宿主 AI 有一个好的开始，但不代表已经安装、执行或验证目标项目。\n\n## 充分原则\n\n- **充分原则，不是压缩原则**：AI Context Pack 应该充分到让宿主 AI 在开工前理解项目价值、能力边界、使用入口、风险和证据来源；它可以分层组织，但不以最短摘要为目标。\n- **压缩策略**：只压缩噪声和重复内容，不压缩会影响判断和开工质量的上下文。\n\n## 给宿主 AI 的使用方式\n\n你正在读取 Doramagic 为 @mnemopay/sdk 编译的 AI Context Pack。请把它当作开工前上下文：帮助用户理解适合谁、能做什么、如何开始、哪些必须安装后验证、风险在哪里。不要声称你已经安装、运行或执行了目标项目。\n\n## Claim 消费规则\n\n- **事实来源**：Repo Evidence + Claim/Evidence Graph；Human Wiki 只提供显著性、术语和叙事结构。\n- **事实最低状态**：`supported`\n- `supported`：可以作为项目事实使用，但回答中必须引用 claim_id 和证据路径。\n- `weak`：只能作为低置信度线索，必须要求用户继续核实。\n- `inferred`：只能用于风险提示或待确认问题，不能包装成项目事实。\n- `unverified`：不得作为事实使用，应明确说证据不足。\n- `contradicted`：必须展示冲突来源，不得替用户强行选择一个版本。\n\n## 它最适合谁\n\n- **正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**：README 或插件配置提到多个宿主 AI。 证据：`README.md` Claim：`clm_0004` supported 0.86\n- **希望把专业流程带进宿主 AI 的用户**：仓库包含 Skill 文档。 证据：`claude-plugin/skills/balance/SKILL.md`, `claude-plugin/skills/charge/SKILL.md`, `claude-plugin/skills/fico/SKILL.md`, `claude-plugin/skills/history/SKILL.md` 等 Claim：`clm_0005` supported 0.86\n\n## 它能做什么\n\n- **AI Skill / Agent 指令资产库**（可做安装前预览）：项目包含可被宿主 AI 读取的 Skill 或 Agent 指令文件，可用于把专业流程带入 Claude、Codex、Cursor 等宿主。 证据：`claude-plugin/skills/balance/SKILL.md`, `claude-plugin/skills/charge/SKILL.md`, `claude-plugin/skills/fico/SKILL.md`, `claude-plugin/skills/history/SKILL.md` 等 Claim：`clm_0001` supported 0.86\n- **多宿主安装与分发**（需要安装后验证）：项目包含插件或 marketplace 配置，说明它面向一个或多个 AI 宿主的安装和分发。 证据：`claude-plugin/.claude-plugin/plugin.json` Claim：`clm_0002` supported 0.86\n- **命令行启动或安装流程**（需要安装后验证）：项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 证据：`CLAUDE.md`, `README.md` Claim：`clm_0003` supported 0.86\n\n## 怎么开始\n\n- `npm install @mnemopay/sdk           # stable (v1.5.x)` 证据：`README.md` Claim：`clm_0006` supported 0.86\n- `npm install @mnemopay/sdk@alpha     # v1.6.x preview — Stripe MPP + x402 + Google AP2 rails` 证据：`README.md` Claim：`clm_0007` supported 0.86\n- `npm install @mnemopay/sdk@alpha` 证据：`README.md` Claim：`clm_0007` supported 0.86, `clm_0008` supported 0.86\n- `npx @mnemopay/sdk init` 证据：`README.md` Claim：`clm_0009` supported 0.86\n- `claude mcp add mnemopay -s user -- npx -y @mnemopay/sdk` 证据：`README.md` Claim：`clm_0010` supported 0.86\n- `npx @mnemopay/sdk --tools=all       # all 40 tools` 证据：`README.md` Claim：`clm_0011` supported 0.86\n- `npx @mnemopay/sdk --tools=agent     # essentials + commerce + hitl + payments + webhooks` 证据：`README.md` Claim：`clm_0012` supported 0.86\n- `npx @mnemopay/sdk --tools=fico      # Agent Credit Score only` 证据：`README.md` Claim：`clm_0013` supported 0.86\n- `npm install        # install deps` 证据：`CLAUDE.md` Claim：`clm_0014` supported 0.86\n\n## 继续前判断卡\n\n- **当前建议**：需要管理员/安全审批\n- **为什么**：继续前可能涉及密钥、账号、外部服务或敏感上下文，建议先经过管理员或安全审批。\n\n### 30 秒判断\n\n- **现在怎么做**：需要管理员/安全审批\n- **最小安全下一步**：先跑 Prompt Preview；若涉及凭证或企业环境，先审批再试装\n- **先别相信**：真实输出质量不能在安装前相信。\n- **继续会触碰**：命令执行、宿主 AI 配置、本地环境或项目文件\n\n### 现在可以相信\n\n- **适合人群线索：正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`README.md` Claim：`clm_0004` supported 0.86\n- **适合人群线索：希望把专业流程带进宿主 AI 的用户**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`claude-plugin/skills/balance/SKILL.md`, `claude-plugin/skills/charge/SKILL.md`, `claude-plugin/skills/fico/SKILL.md`, `claude-plugin/skills/history/SKILL.md` 等 Claim：`clm_0005` supported 0.86\n- **能力存在：AI Skill / Agent 指令资产库**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`claude-plugin/skills/balance/SKILL.md`, `claude-plugin/skills/charge/SKILL.md`, `claude-plugin/skills/fico/SKILL.md`, `claude-plugin/skills/history/SKILL.md` 等 Claim：`clm_0001` supported 0.86\n- **能力存在：多宿主安装与分发**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`claude-plugin/.claude-plugin/plugin.json` Claim：`clm_0002` supported 0.86\n- **能力存在：命令行启动或安装流程**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`CLAUDE.md`, `README.md` Claim：`clm_0003` supported 0.86\n- **存在 Quick Start / 安装命令线索**（supported）：可以相信项目文档出现过启动或安装入口；不要因此直接在主力环境运行。 证据：`README.md` Claim：`clm_0006` supported 0.86\n\n### 现在还不能相信\n\n- **真实输出质量不能在安装前相信。**（unverified）：Prompt Preview 只能展示引导方式，不能证明真实项目中的结果质量。\n- **宿主 AI 版本兼容性不能在安装前相信。**（unverified）：Claude、Cursor、Codex、Gemini 等宿主加载规则和版本差异必须在真实环境验证。\n- **不会污染现有宿主 AI 行为，不能直接相信。**（inferred）：Skill、plugin、AGENTS/CLAUDE/GEMINI 指令可能改变宿主 AI 的默认行为。 证据：`CLAUDE.md`, `GEMINI.md`, `claude-plugin/.claude-plugin/plugin.json`, `claude-plugin/skills/balance/SKILL.md` 等\n- **可安全回滚不能默认相信。**（unverified）：除非项目明确提供卸载和恢复说明，否则必须先在隔离环境验证。\n- **真实安装后是否与用户当前宿主 AI 版本兼容？**（unverified）：兼容性只能通过实际宿主环境验证。 证据：`claude-plugin/.claude-plugin/plugin.json`\n- **项目输出质量是否满足用户具体任务？**（unverified）：安装前预览只能展示流程和边界，不能替代真实评测。\n- **安装命令是否需要网络、权限或全局写入？**（unverified）：这影响企业环境和个人环境的安装风险。 证据：`README.md`\n\n### 继续会触碰什么\n\n- **命令执行**：包管理器、网络下载、本地插件目录、项目配置或用户主目录。 原因：运行第一条命令就可能产生环境改动；必须先判断是否值得跑。 证据：`CLAUDE.md`, `README.md`\n- **宿主 AI 配置**：Claude/Codex/Cursor/Gemini/OpenCode 等宿主的 plugin、Skill 或规则加载配置。 原因：宿主配置会改变 AI 后续工作方式，可能和用户已有规则冲突。 证据：`CLAUDE.md`, `GEMINI.md`, `claude-plugin/.claude-plugin/plugin.json`, `claude-plugin/skills/balance/SKILL.md` 等\n- **本地环境或项目文件**：安装结果、插件缓存、项目配置或本地依赖目录。 原因：安装前无法证明写入范围和回滚方式，需要隔离验证。 证据：`CLAUDE.md`, `README.md`, `claude-plugin/.claude-plugin/plugin.json`\n- **环境变量 / API Key**：项目入口文档明确出现 API key、token、secret 或账号凭证配置。 原因：如果真实安装需要凭证，应先使用测试凭证并经过权限/合规判断。 证据：`README.md`, `claude-plugin/README.md`, `src/mcp/server.ts`\n- **宿主 AI 上下文**：AI Context Pack、Prompt Preview、Skill 路由、风险规则和项目事实。 原因：导入上下文会影响宿主 AI 后续判断，必须避免把未验证项包装成事实。\n\n### 最小安全下一步\n\n- **先跑 Prompt Preview**：用安装前交互式试用判断工作方式是否匹配，不需要授权或改环境。（适用：任何项目都适用，尤其是输出质量未知时。）\n- **只在隔离目录或测试账号试装**：避免安装命令污染主力宿主 AI、真实项目或用户主目录。（适用：存在命令执行、插件配置或本地写入线索时。）\n- **先备份宿主 AI 配置**：Skill、plugin、规则文件可能改变 Claude/Cursor/Codex 的默认行为。（适用：存在插件 manifest、Skill 或宿主规则入口时。）\n- **不要使用真实生产凭证**：环境变量/API key 一旦进入宿主或工具链，可能产生账号和合规风险。（适用：出现 API、TOKEN、KEY、SECRET 等环境线索时。）\n- **安装后只验证一个最小任务**：先验证加载、兼容、输出质量和回滚，再决定是否深用。（适用：准备从试用进入真实工作流时。）\n\n### 退出方式\n\n- **保留安装前状态**：记录原始宿主配置和项目状态，后续才能判断是否可恢复。\n- **准备移除宿主 plugin / Skill / 规则入口**：如果试装后行为异常，可以把宿主 AI 恢复到试装前状态。\n- **记录安装命令和写入路径**：没有明确卸载说明时，至少要知道哪些目录或配置需要手动清理。\n- **准备撤销测试 API key 或 token**：测试凭证泄露或误用时，可以快速止损。\n- **如果没有回滚路径，不进入主力环境**：不可回滚是继续前阻断项，不应靠信任或运气继续。\n\n## 哪些只能预览\n\n- 解释项目适合谁和能做什么\n- 基于项目文档演示典型对话流程\n- 帮助用户判断是否值得安装或继续研究\n\n## 哪些必须安装后验证\n\n- 真实安装 Skill、插件或 CLI\n- 执行脚本、修改本地文件或访问外部服务\n- 验证真实输出质量、性能和兼容性\n\n## 边界与风险判断卡\n\n- **把安装前预览误认为真实运行**：用户可能高估项目已经完成的配置、权限和兼容性验证。 处理方式：明确区分 prompt_preview_can_do 与 runtime_required。 Claim：`clm_0015` inferred 0.45\n- **宿主 AI 插件或 Skill 规则冲突**：新规则可能改变用户现有宿主 AI 的工作方式。 处理方式：安装前先检查插件 manifest 和 Skill 文件，必要时隔离测试。 证据：`claude-plugin/.claude-plugin/plugin.json` Claim：`clm_0016` supported 0.86\n- **命令执行会修改本地环境**：安装命令可能写入用户主目录、宿主插件目录或项目配置。 处理方式：先在隔离环境或测试账号中运行。 证据：`CLAUDE.md`, `README.md` Claim：`clm_0017` supported 0.86\n- **待确认**：真实安装后是否与用户当前宿主 AI 版本兼容？。原因：兼容性只能通过实际宿主环境验证。\n- **待确认**：项目输出质量是否满足用户具体任务？。原因：安装前预览只能展示流程和边界，不能替代真实评测。\n- **待确认**：安装命令是否需要网络、权限或全局写入？。原因：这影响企业环境和个人环境的安装风险。\n\n## 开工前工作上下文\n\n### 加载顺序\n\n- 先读取 how_to_use.host_ai_instruction，建立安装前判断资产的边界。\n- 读取 claim_graph_summary，确认事实来自 Claim/Evidence Graph，而不是 Human Wiki 叙事。\n- 再读取 intended_users、capabilities 和 quick_start_candidates，判断用户是否匹配。\n- 需要执行具体任务时，优先查 role_skill_index，再查 evidence_index。\n- 遇到真实安装、文件修改、网络访问、性能或兼容性问题时，转入 risk_card 和 boundaries.runtime_required。\n\n### 任务路由\n\n- **AI Skill / Agent 指令资产库**：先基于 role_skill_index / evidence_index 帮用户挑选可用角色、Skill 或工作流。 边界：可做安装前 Prompt 体验。 证据：`claude-plugin/skills/balance/SKILL.md`, `claude-plugin/skills/charge/SKILL.md`, `claude-plugin/skills/fico/SKILL.md`, `claude-plugin/skills/history/SKILL.md` 等 Claim：`clm_0001` supported 0.86\n- **多宿主安装与分发**：先说明这是安装后验证能力，再给出安装前检查清单。 边界：必须真实安装或运行后验证。 证据：`claude-plugin/.claude-plugin/plugin.json` Claim：`clm_0002` supported 0.86\n- **命令行启动或安装流程**：先说明这是安装后验证能力，再给出安装前检查清单。 边界：必须真实安装或运行后验证。 证据：`CLAUDE.md`, `README.md` Claim：`clm_0003` supported 0.86\n\n### 上下文规模\n\n- 文件总数：301\n- 重要文件覆盖：40/301\n- 证据索引条目：80\n- 角色 / Skill 条目：9\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请基于 @mnemopay/sdk 的 AI Context Pack，先问我 3 个必要问题，然后判断它是否适合我的任务。回答必须包含：适合谁、能做什么、不能做什么、是否值得安装、证据来自哪里。所有项目事实必须引用 evidence_refs、source_paths 或 claim_id。\n```\n\n### 安装前体验\n\n- 目标：让用户在安装前感受核心工作流，同时避免把预览包装成真实能力或营销承诺。\n- 预期输出：一段带边界标签的体验剧本、安装后验证清单和谨慎建议；不含真实运行承诺或强营销表述。\n\n```text\n请把 @mnemopay/sdk 当作安装前体验资产，而不是已安装工具或真实运行环境。\n\n请严格输出四段：\n1. 先问我 3 个必要问题。\n2. 给出一段“体验剧本”：用 [安装前可预览]、[必须安装后验证]、[证据不足] 三种标签展示它可能如何引导工作流。\n3. 给出安装后验证清单：列出哪些能力只有真实安装、真实宿主加载、真实项目运行后才能确认。\n4. 给出谨慎建议：只能说“值得继续研究/试装”“先补充信息后再判断”或“不建议继续”，不得替项目背书。\n\n硬性边界：\n- 不要声称已经安装、运行、执行测试、修改文件或产生真实结果。\n- 不要写“自动适配”“确保通过”“完美适配”“强烈建议安装”等承诺性表达。\n- 如果描述安装后的工作方式，必须使用“如果安装成功且宿主正确加载 Skill，它可能会……”这种条件句。\n- 体验剧本只能写成“示例台词/假设流程”：使用“可能会询问/可能会建议/可能会展示”，不要写“已写入、已生成、已通过、正在运行、正在生成”。\n- Prompt Preview 不负责给安装命令；如用户准备试装，只能提示先阅读 Quick Start 和 Risk Card，并在隔离环境验证。\n- 所有项目事实必须来自 supported claim、evidence_refs 或 source_paths；inferred/unverified 只能作风险或待确认项。\n\n```\n\n### 角色 / Skill 选择\n\n- 目标：从项目里的角色或 Skill 中挑选最匹配的资产。\n- 预期输出：候选角色或 Skill 列表，每项包含适用场景、证据路径、风险边界和是否需要安装后验证。\n\n```text\n请读取 role_skill_index，根据我的目标任务推荐 3-5 个最相关的角色或 Skill。每个推荐都要说明适用场景、可能输出、风险边界和 evidence_refs。\n```\n\n### 风险预检\n\n- 目标：安装或引入前识别环境、权限、规则冲突和质量风险。\n- 预期输出：环境、权限、依赖、许可、宿主冲突、质量风险和未知项的检查清单。\n\n```text\n请基于 risk_card、boundaries 和 quick_start_candidates，给我一份安装前风险预检清单。不要替我执行命令，只说明我应该检查什么、为什么检查、失败会有什么影响。\n```\n\n### 宿主 AI 开工指令\n\n- 目标：把项目上下文转成一次对话开始前的宿主 AI 指令。\n- 预期输出：一段边界明确、证据引用明确、适合复制给宿主 AI 的开工前指令。\n\n```text\n请基于 @mnemopay/sdk 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。\n```\n\n\n## 角色 / Skill 索引\n\n- 共索引 9 个角色 / Skill / 项目文档条目。\n\n- **balance**（skill）：Check the current balance and financial status of an AI agent. Use when the user asks about funds, balance, or how much money is available. 激活提示：当用户任务与“balance”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`claude-plugin/skills/balance/SKILL.md`\n- **charge**（skill）：Charge an AI agent for a service or tool invocation. Use when the user wants to bill for API calls, tool usage, or any metered service. 激活提示：当用户任务与“charge”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`claude-plugin/skills/charge/SKILL.md`\n- **fico**（skill）：Check the Agent FICO credit score 300-850 and reputation of an AI agent. Use when the user asks about creditworthiness, trust, reputation, or agent scoring. 激活提示：当用户任务与“fico”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`claude-plugin/skills/fico/SKILL.md`\n- **history**（skill）：View transaction history and financial records. Use when the user asks about past transactions, spending, or payment history. 激活提示：当用户任务与“history”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`claude-plugin/skills/history/SKILL.md`\n- **recall**（skill）：Search and retrieve information from the agent's persistent memory. Use when the user asks to recall, look up, or find previously stored information. 激活提示：当用户任务与“recall”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`claude-plugin/skills/recall/SKILL.md`\n- **remember**（skill）：Store information in the agent's persistent memory. Use when the user wants to save facts, preferences, decisions, or any data for future recall. 激活提示：当用户任务与“remember”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`claude-plugin/skills/remember/SKILL.md`\n- **settle**（skill）：Settle pending transactions and release escrow. Use when the user wants to finalize payments, release held funds, or settle outstanding balances. 激活提示：当用户任务与“settle”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`claude-plugin/skills/settle/SKILL.md`\n- **shop**（skill）：Search for products and make purchases using autonomous shopping with escrow. Use when the user wants to buy something, search for products, or manage orders. 激活提示：当用户任务与“shop”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`claude-plugin/skills/shop/SKILL.md`\n- **mnemopay**（skill）： 激活提示：当用户任务与“mnemopay”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`integrations/openclaw/SKILL.md`\n\n## 证据索引\n\n- 共索引 80 条证据。\n\n- **MnemoPay SDK**（documentation）：AI agent trust & reputation SDK — memory + payments + identity + Agent Credit Score in one package. 证据：`CLAUDE.md`\n- **MnemoPay SDK - Context & Instructions**（documentation）：MnemoPay SDK - Context & Instructions 证据：`GEMINI.md`\n- **MnemoPay**（documentation）：The governance layer for AI agents that handle money. Charter-driven mission scope, FiscalGate budget enforcement, EU AI Act Article 12 audit bundles, Agent Credit Score 300-850 , and a tamper-evident MerkleAudit chain — across every payment rail an agent will ever touch. 证据：`README.md`\n- **MnemoPay Claude Code Plugin**（documentation）：Payment infrastructure for AI agents. Gives Claude Code a full financial stack: charge for services, manage balances, shop autonomously with escrow, track credit scores, and persist memories with cryptographic integrity. 证据：`claude-plugin/README.md`\n- **AgentOps-Bench**（documentation）：A public, reproducible benchmark for evaluating production agent deployments — not just memory, not just planning, not just tool use. Four pillars: memory , payments , identity , integrity . 证据：`benchmark/agentops-bench/README.md`\n- **LongMemEval Benchmark for MnemoPay**（documentation）：Benchmark adapter for LongMemEval https://github.com/xiaowu0162/LongMemEval ICLR 2025 , evaluating MnemoPay's memory system on 500 long-term conversation memory questions across 5 cognitive abilities. 证据：`benchmark/longmemeval/README.md`\n- **MnemoPay for Agno**（documentation）：Give any Agno agent persistent memory and micropayment capabilities. 证据：`integrations/agno/README.md`\n- **MnemoPay for Microsoft AutoGen**（documentation）：Give any AutoGen agent persistent memory and micropayment capabilities. 证据：`integrations/autogen/README.md`\n- **MnemoPay for Composio**（documentation）：Give any Composio-powered agent persistent memory and micropayments. Works with every framework Composio supports CrewAI, AutoGen, LangChain, Agno, etc. . 证据：`integrations/composio/README.md`\n- **MnemoPay for CrewAI**（documentation）：Give any CrewAI crew persistent cognitive memory and micropayment capabilities. 证据：`integrations/crewai/README.md`\n- **MnemoPay for Goose**（documentation）：Give any Goose https://github.com/block/goose agent persistent memory, micropayments, and fraud-aware trust scoring. 证据：`integrations/goose/README.md`\n- **MnemoPay Plugin for Hermes Agent**（documentation）：Give Hermes persistent cognitive memory and a micropayment wallet. 证据：`integrations/hermes-plugin/README.md`\n- **MnemoPay for Huawei AgentArts**（documentation）：Connect MnemoPay to Huawei's AgentArts https://www.huaweicloud.com/intl/en-us/product/pangulargemodels.html platform as an MCP service. 证据：`integrations/huawei-agentarts/README.md`\n- **MnemoPay x Lightning Network**（documentation）：Bridge MnemoPay's memory and trust layer with Lightning Network payments. 证据：`integrations/lightning/README.md`\n- **MnemoPay for OpenAI Agents SDK**（documentation）：Give any OpenAI agent persistent memory and micropayment capabilities. 证据：`integrations/openai-agents/README.md`\n- **MnemoPay for Pydantic AI**（documentation）：Give any Pydantic AI agent persistent memory and micropayment capabilities. 证据：`integrations/pydantic-ai/README.md`\n- **MnemoPay hosted Python client**（documentation）：Dependency-free Python client for the hosted MnemoPay API. 证据：`integrations/python-hosted/README.md`\n- **MnemoPay x x402 Trust Middleware**（documentation）：Add persistent memory, trust scoring, and fraud detection to x402 https://x402.org payments. 证据：`integrations/x402/README.md`\n- **Package**（package_manifest）：{ \"name\": \"mnemopay-dashboard\", \"version\": \"0.2.0\", \"private\": true, \"type\": \"commonjs\", \"description\": \"Hosted MnemoPay console/dashboard\", \"scripts\": { \"start\": \"node server.js\", \"test:unit\": \"node auth-email.test.cjs && node console-postgres-store.test.cjs && node stripe-billing.test.cjs && node drip-queue.test.cjs && node logger.test.cjs && node rate-limit.test.cjs && node metrics.test.cjs && node idempotency.test.cjs\", \"test:smoke\": \"node server.smoke.test.cjs\", \"test\": \"npm run test:unit && npm run test:smoke\" }, \"dependencies\": { \"@mnemopay/sdk\": \"^1.5.0\", \"better-sqlite3\": \"^11.5.0\", \"pg\": \"^8.16.3\" }, \"optionalDependencies\": { \"@xenova/transformers\": \"^2.17.2\" } } 证据：`dashboard/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@mnemopay/sdk\", \"mcpName\": \"com.mnemopay/sdk\", \"version\": \"1.8.0-alpha.0\", \"description\": \"Production payment infrastructure for AI agents — real Stripe/Paystack/Lightning rails, autonomous shopping with escrow, Agent Credit Score 300-850 , Ed25519 identity, behavioral finance, Merkle integrity, anomaly detection, human-in-the-loop approval. Battle-tested.\", \"main\": \"dist/index.js\", \"types\": \"dist/index.d.ts\", \"exports\": { \".\": { \"import\": \"./dist/index.js\", \"types\": \"./dist/index.d.ts\" }, \"./middleware/openai\": { \"import\": \"./dist/middleware/openai.js\", \"types\": \"./dist/middleware/openai.d.ts\" }, \"./middleware/anthropic\": { \"import\": \"./dist/middleware/anthropic.js\", \"types\": \".… 证据：`package.json`\n- **Contributing to MnemoPay SDK**（documentation）：Thanks for your interest. MnemoPay is the trust + reputation substrate for AI agents that handle money — every PR touches code that real agents will use to authorize real payments, so the bar is high. 证据：`CONTRIBUTING.md`\n- **Package**（package_manifest）：{ \"name\": \"@mnemopay/benchmark-longmemeval\", \"version\": \"1.0.0\", \"private\": true, \"description\": \"LongMemEval ICLR 2025 benchmark adapter for MnemoPay memory system\", \"type\": \"module\", \"scripts\": { \"download\": \"bash scripts/download-data.sh\", \"ingest\": \"tsx ingest.ts\", \"evaluate\": \"tsx evaluate.ts\", \"bench\": \"bash run.sh\", \"bench:oracle\": \"bash run.sh oracle\", \"bench:small\": \"bash run.sh s\", \"bench:medium\": \"bash run.sh m\" }, \"dependencies\": { \"@anthropic-ai/sdk\": \"^0.39.0\", \"@mnemopay/sdk\": \"file:../../\" }, \"devDependencies\": { \"tsx\": \"^4.19.0\", \"@types/node\": \"^22.0.0\", \"typescript\": \"^5.7.0\" } } 证据：`benchmark/longmemeval/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@mnemopay/langchain\", \"version\": \"1.1.0\", \"description\": \"MnemoPay tools for LangChain/LangGraph — agent memory + wallet\", \"main\": \"dist/index.js\", \"types\": \"dist/index.d.ts\", \"exports\": { \".\": { \"import\": \"./dist/index.js\", \"types\": \"./dist/index.d.ts\" } }, \"files\": \"dist\", \"README.md\" , \"scripts\": { \"build\": \"tsc\", \"prepublishOnly\": \"npm run build\" }, \"keywords\": \"langchain\", \"langgraph\", \"mnemopay\", \"agent\", \"memory\", \"wallet\", \"tools\" , \"author\": \"Jeremiah Omiagbo \", \"license\": \"MIT\", \"repository\": { \"type\": \"git\", \"url\": \"https://github.com/mnemopay/mnemopay-sdk.git\", \"directory\": \"integrations/langchain\" }, \"homepage\": \"https://github.com/mnemopay/mnemopay-sdk/tree/main/int… 证据：`integrations/langchain/package.json`\n- **Balance**（skill_instruction）：Use the MnemoPay MCP balance tool to check the agent's current balance. 证据：`claude-plugin/skills/balance/SKILL.md`\n- **Charge**（skill_instruction）：Use the MnemoPay MCP charge tool to bill an agent for a service. 证据：`claude-plugin/skills/charge/SKILL.md`\n- **Agent FICO Score**（skill_instruction）：Use the MnemoPay MCP agent fico score tool to check an agent's credit score. 证据：`claude-plugin/skills/fico/SKILL.md`\n- **Transaction History**（skill_instruction）：Use the MnemoPay MCP history tool to view past transactions. 证据：`claude-plugin/skills/history/SKILL.md`\n- **Recall**（skill_instruction）：Use the MnemoPay MCP recall tool to search persistent memory. 证据：`claude-plugin/skills/recall/SKILL.md`\n- **Remember**（skill_instruction）：Use the MnemoPay MCP remember tool to store information in persistent memory. 证据：`claude-plugin/skills/remember/SKILL.md`\n- **Settle**（skill_instruction）：Use the MnemoPay MCP settle tool to finalize pending transactions. 证据：`claude-plugin/skills/settle/SKILL.md`\n- **Shop**（skill_instruction）：Use MnemoPay's commerce tools for autonomous shopping with escrow protection. 证据：`claude-plugin/skills/shop/SKILL.md`\n- **MnemoPay — Agent Memory + Wallet**（skill_instruction）：Give any AI agent persistent memory and a micropayment wallet. MnemoPay unifies cognitive memory Mnemosyne and escrow economics AgentPay into a single MCP server. The core innovation: payment outcomes reinforce the memories that led to successful decisions. 证据：`integrations/openclaw/SKILL.md`\n- **Plugin**（structured_config）：{ \"name\": \"mnemopay\", \"description\": \"Payment infrastructure for AI agents — Agent Credit Score 300-850 , real payment rails Stripe/Paystack/Lightning , autonomous shopping with escrow, hash-chained ledger, behavioral finance. 100K-operation stress tested.\", \"version\": \"1.2.0\", \"author\": { \"name\": \"Jeremiah Omiagbo\", \"url\": \"https://github.com/mnemopay\" }, \"homepage\": \"https://github.com/mnemopay/mnemopay-sdk\", \"repository\": \"https://github.com/mnemopay/mnemopay-sdk\", \"license\": \"Apache-2.0\" } 证据：`claude-plugin/.claude-plugin/plugin.json`\n- **License**（source_file）：Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ 证据：`LICENSE`\n- **Auto-Observer Middleware — Design Note**（documentation）：Auto-Observer Middleware — Design Note 证据：`docs/AUTO-OBSERVER-DESIGN.md`\n- **Work Pattern reusable**（documentation）：Paste this block into any repo's CLAUDE.md to install the research → build → automate discipline. Jerry wants this across every project. 证据：`docs/CLAUDE-WORK-PATTERN.md`\n- **MnemoPay product upgrade roadmap**（documentation）：Use this as the public product frame: 证据：`docs/PRODUCT-UPGRADE-ROADMAP-2026-05.md`\n- **RFC: Agent Trust Attestation Protocol ATAP**（documentation）：RFC: Agent Trust Attestation Protocol ATAP 证据：`docs/aaif-rfc-agent-trust-attestation.md`\n- **Agent Memory State-of-the-Art — Deep Research Pass 2026-04-20**（documentation）：Agent Memory State-of-the-Art — Deep Research Pass 2026-04-20 证据：`docs/agent-memory-sota-2026-04.md`\n- **Claude Agent SDK + MnemoPay Integration Guide**（documentation）：Claude Agent SDK + MnemoPay Integration Guide 证据：`docs/agent-sdk-guide.md`\n- **Claude Design — Paste-Ready Prompts for MnemoPay**（documentation）：Claude Design — Paste-Ready Prompts for MnemoPay 证据：`docs/pitch/claude-design-prompts.md`\n- **MnemoPay — EU AI Act Pitch targeted**（documentation）：MnemoPay — EU AI Act Pitch targeted 证据：`docs/pitch/eu-ai-act-pitch.md`\n- **MnemoPay — Seed Round Deck 2026**（documentation）：Use this as a the source-of-truth script when talking through the deck, and b the content to paste into Claude Design see claude-design-prompts.md for the design brief . 证据：`docs/pitch/investor-deck.md`\n- **Linux Foundation reply — Christina Harter + Matt White**（documentation）：Linux Foundation reply — Christina Harter + Matt White 证据：`docs/pitch/linux-foundation-reply.md`\n- **MnemoPay — One-Pager**（documentation）：Paste the design brief from claude-design-prompts.md § 2 into Claude Design for the visual PDF. This file is the copy source-of-truth. 证据：`docs/pitch/one-pager.md`\n- **MCP Hive Founding-100 \"Project Ignite\" application — MnemoPay**（documentation）：MCP Hive Founding-100 \"Project Ignite\" application — MnemoPay 证据：`docs/strategy-2026-05-06/mcp-hive-application.md`\n- **Praetor → MnemoPay merge + repo split — execution plan**（documentation）：Praetor → MnemoPay merge + repo split — execution plan 证据：`docs/strategy-2026-05-06/praetor-split-execution-plan.md`\n- **Strategy session 2026-05-06 — what was decided + what was drafted**（documentation）：Strategy session 2026-05-06 — what was decided + what was drafted 证据：`docs/strategy-2026-05-06/session-summary.md`\n- **MnemoPay SDK — Benchmarks**（documentation）：Reproducible stress benchmarks for the MnemoPay SDK. Numbers below are from actual runs on commodity hardware — no ad-hoc synthetic shortcuts, no mocking of the payment path. Every operation goes through the same code paths a production agent would take. 证据：`BENCHMARKS.md`\n- **Changelog**（documentation）：All notable changes to @mnemopay/sdk are documented here. Format follows Keep a Changelog https://keepachangelog.com/en/1.1.0/ ; versions follow SemVer https://semver.org/ . 证据：`CHANGELOG.md`\n- **MnemoPay Design System Stripe-Inspired**（documentation）：MnemoPay Design System Stripe-Inspired 证据：`DESIGN.md`\n- **Security Policy**（documentation）：Version Supported --------- ----------- 1.7.x Yes — current stable 1.8.x-alpha Yes — preview channel 1.6.x Critical fixes only < 1.6 No 证据：`SECURITY.md`\n- **Annex IV Technical Documentation — @mnemopay/sdk**（documentation）：Annex IV Technical Documentation — @mnemopay/sdk 证据：`compliance/eu-ai-act-annex-iv.md`\n- **MnemoPay dashboard deployment**（documentation）：This dashboard is the hosted MnemoPay console: Brain, billing, usage, audit, members, and developer keys. 证据：`dashboard/DEPLOYMENT.md`\n- **vectorless RAG, in 500 lines of typescript**（documentation）：vectorless RAG, in 500 lines of typescript 证据：`marketing/blog-treeindex-vectorless-rag.md`\n- **Tweet drafts — TreeIndex launch**（documentation）：Two options. The single is the standalone post; the thread is for when the blog goes live and we need amplification. 证据：`marketing/tweet-treeindex-launch.md`\n- **SOC 2 prep**（documentation）：MnemoPay is not ready for a Type II audit yet, but it can start collecting evidence now. This file is the operating checklist until a formal compliance tool is adopted. 证据：`ops/SOC2-PREP-2026-05.md`\n- **Workflow Functional Audit — 2026-04-23**（documentation）：Workflow Functional Audit — 2026-04-23 证据：`ops/workflow-audit-2026-04-23.md`\n- **MnemoPay — Premium Video Scripts Production-Ready**（documentation）：MnemoPay — Premium Video Scripts Production-Ready HeyGen Avatar Shot + Seedance 2.0 Voiceover: Confident, measured, slightly amused 证据：`site/video-scripts-v2.md`\n- **MnemoPay Video Ad Scripts**（documentation）：MnemoPay Video Ad Scripts HeyGen Avatar Shot + Seedance 2.0 证据：`site/video-scripts.md`\n- 其余 20 条证据见 `AI_CONTEXT_PACK.json` 或 `EVIDENCE_INDEX.json`。\n\n## 宿主 AI 必须遵守的规则\n\n- **把本资产当作开工前上下文，而不是运行环境。**：AI Context Pack 只包含证据化项目理解，不包含目标项目的可执行状态。 证据：`CLAUDE.md`, `GEMINI.md`, `README.md`\n- **回答用户时区分可预览内容与必须安装后才能验证的内容。**：安装前体验的消费者价值来自降低误装和误判，而不是伪装成真实运行。 证据：`CLAUDE.md`, `GEMINI.md`, `README.md`\n\n## 用户开工前应该回答的问题\n\n- 你准备在哪个宿主 AI 或本地环境中使用它？\n- 你只是想先体验工作流，还是准备真实安装？\n- 你最在意的是安装成本、输出质量、还是和现有规则的冲突？\n\n## 验收标准\n\n- 所有能力声明都能回指到 evidence_refs 中的文件路径。\n- AI_CONTEXT_PACK.md 没有把预览包装成真实运行。\n- 用户能在 3 分钟内看懂适合谁、能做什么、如何开始和风险边界。\n\n---\n\n## Doramagic Context Augmentation\n\n下面内容用于强化 Repomix/AI Context Pack 主体。Human Manual 只提供阅读骨架；踩坑日志会被转成宿主 AI 必须遵守的工作约束。\n\n## Human Manual 骨架\n\n使用规则：这里只是项目阅读路线和显著性信号，不是事实权威。具体事实仍必须回到 repo evidence / Claim Graph。\n\n宿主 AI 硬性规则：\n- 不得把页标题、章节顺序、摘要或 importance 当作项目事实证据。\n- 解释 Human Manual 骨架时，必须明确说它只是阅读路线/显著性信号。\n- 能力、安装、兼容性、运行状态和风险判断必须引用 repo evidence、source path 或 Claim Graph。\n\n- **Introduction to MnemoPay SDK**：importance `high`\n  - source_paths: README.md, DESIGN.md, src/index.ts\n- **Quick Start Guide**：importance `high`\n  - source_paths: README.md, examples/01-quick-start.ts, package.json, .env.example\n- **System Architecture**：importance `high`\n  - source_paths: README.md, docs/AUTO-OBSERVER-DESIGN.md, src/index.ts, src/client.ts\n- **Core Modules Reference**：importance `high`\n  - source_paths: src/index.ts, src/recall/engine.ts, src/fraud.ts, src/identity/index.ts, src/ledger.ts\n- **Payment Rails Overview**：importance `high`\n  - source_paths: src/rails/index.ts, src/rails/stripe-mpp.ts, src/rails/x402.ts, src/rails/google-ap2.ts\n- **Stripe, Paystack & Lightning Rails**：importance `high`\n  - source_paths: src/rails/index.ts, src/rails/stripe-mpp.ts, src/rails/paystack.ts, examples/06-production.ts\n- **Alpha Payment Rails (StripeMPP, x402, GoogleAP2)**：importance `medium`\n  - source_paths: src/rails/stripe-mpp.ts, src/rails/x402.ts, src/rails/google-ap2.ts, src/client.ts\n- **Charter & FiscalGate Governance**：importance `high`\n  - source_paths: src/governance/charter.ts, src/governance/payments.ts, src/governance/article12.ts, src/governance/policies/eu-ai-act.ts\n\n## Repo Inspection Evidence / 源码检查证据\n\n- repo_clone_verified: true\n- repo_inspection_verified: true\n- repo_commit: `c47f76cd6240494e55bea1c2e399a8d82f45f0cf`\n- inspected_files: `Dockerfile`, `package.json`, `README.md`, `docker-compose.yml`, `docs/agent-memory-sota-2026-04.md`, `docs/AUTO-OBSERVER-DESIGN.md`, `docs/PRODUCT-UPGRADE-ROADMAP-2026-05.md`, `docs/agent-sdk-guide.md`, `docs/aaif-rfc-agent-trust-attestation.md`, `docs/CLAUDE-WORK-PATTERN.md`, `docs/strategy-2026-05-06/mcp-hive-application.md`, `docs/strategy-2026-05-06/session-summary.md`, `docs/strategy-2026-05-06/praetor-split-execution-plan.md`, `docs/pitch/linux-foundation-reply.md`, `docs/pitch/claude-design-prompts.md`, `docs/pitch/eu-ai-act-pitch.md`, `docs/pitch/one-pager.md`, `docs/pitch/investor-deck.md`, `examples/01-quick-start.ts`, `examples/03-anthropic-middleware.ts`\n\n宿主 AI 硬性规则：\n- 没有 repo_clone_verified=true 时，不得声称已经读过源码。\n- 没有 repo_inspection_verified=true 时，不得把 README/docs/package 文件判断写成事实。\n- 没有 quick_start_verified=true 时，不得声称 Quick Start 已跑通。\n\n## Doramagic Pitfall Constraints / 踩坑约束\n\n这些规则来自 Doramagic 发现、验证或编译过程中的项目专属坑点。宿主 AI 必须把它们当作工作约束，而不是普通说明文字。\n\n### Constraint 1: 涉及密钥、隐私或敏感领域\n\n- Trigger: 项目文本出现 secret/private key/privacy/trading/finance 等敏感关键词。\n- Host AI rule: 补敏感数据流、密钥存储和权限边界审查。\n- Why it matters: 金融、交易、隐私和密钥场景必须比普通工具更保守。\n- Evidence: packet_text.keyword_scan | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | matched secret / private key / privacy / trading / finance keyword\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 2: 仓库名和安装名不一致\n\n- Trigger: 仓库名 `mnemopay-sdk` 与安装入口 `@mnemopay/sdk` 不完全一致。\n- Host AI rule: 在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。\n- Why it matters: 用户照着仓库名搜索包或照着包名找仓库时容易走错入口。\n- Evidence: identity.distribution | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | repo=mnemopay-sdk; install=@mnemopay/sdk\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 3: 能力判断依赖假设\n\n- Trigger: README/documentation is current enough for a first validation pass.\n- Host AI rule: 将假设转成下游验证清单。\n- Why it matters: 假设不成立时，用户拿不到承诺的能力。\n- Evidence: capability.assumptions | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | README/documentation is current enough for a first validation pass.\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 4: 维护活跃度未知\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:1197975871 | https://github.com/mnemopay/mnemopay-sdk | last_activity_observed missing\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 5: 下游验证发现风险项\n\n- Trigger: no_demo\n- Host AI rule: 进入安全/权限治理复核队列。\n- Why it matters: 下游已经要求复核，不能在页面中弱化。\n- Evidence: downstream_validation.risk_items | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | no_demo; severity=medium\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 6: 存在评分风险\n\n- Trigger: no_demo\n- Host AI rule: 把风险写入边界卡，并确认是否需要人工复核。\n- Why it matters: 风险会影响是否适合普通用户安装。\n- Evidence: risks.scoring_risks | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | no_demo; severity=medium\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 7: issue/PR 响应质量未知\n\n- Trigger: issue_or_pr_quality=unknown。\n- Host AI rule: 抽样最近 issue/PR，判断是否长期无人处理。\n- Why it matters: 用户无法判断遇到问题后是否有人维护。\n- Evidence: evidence.maintainer_signals | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | issue_or_pr_quality=unknown\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 8: 发布节奏不明确\n\n- Trigger: release_recency=unknown。\n- Host AI rule: 确认最近 release/tag 和 README 安装命令是否一致。\n- Why it matters: 安装命令和文档可能落后于代码，用户踩坑概率升高。\n- Evidence: evidence.maintainer_signals | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | release_recency=unknown\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n",
      "summary": "给宿主 AI 的上下文和工作边界。",
      "title": "AI Context Pack / 带给我的 AI"
    },
    "boundary_risk_card": {
      "asset_id": "boundary_risk_card",
      "filename": "BOUNDARY_RISK_CARD.md",
      "markdown": "# Boundary & Risk Card / 安装前决策卡\n\n项目：mnemopay/mnemopay-sdk\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 是否匹配：local_cli\n- 官方安装入口状态：已发现官方入口\n- 是否在临时目录、临时宿主或容器中验证：必须是\n- 是否能回滚配置改动：必须能\n- 是否需要 API Key、网络访问、读写文件或修改宿主配置：未确认前按高风险处理\n- 是否记录了安装命令、实际输出和失败日志：必须记录\n\n## 当前阻塞项\n\n- review_required: community_discussion_evidence_below_public_threshold\n\n## 项目专属踩坑\n\n- 涉及密钥、隐私或敏感领域（high）：金融、交易、隐私和密钥场景必须比普通工具更保守。 建议检查：补敏感数据流、密钥存储和权限边界审查。\n- 仓库名和安装名不一致（medium）：用户照着仓库名搜索包或照着包名找仓库时容易走错入口。 建议检查：在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。\n- 能力判断依赖假设（medium）：假设不成立时，用户拿不到承诺的能力。 建议检查：将假设转成下游验证清单。\n- 维护活跃度未知（medium）：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 下游验证发现风险项（medium）：下游已经要求复核，不能在页面中弱化。 建议检查：进入安全/权限治理复核队列。\n\n## 风险与权限提示\n\n- no_demo: medium\n\n## 证据缺口\n\n- 暂未发现结构化证据缺口。\n",
      "summary": "安装、权限、验证和推荐前风险。",
      "title": "Boundary & Risk Card / 边界与风险卡"
    },
    "human_manual": {
      "asset_id": "human_manual",
      "filename": "HUMAN_MANUAL.md",
      "markdown": "# https://github.com/mnemopay/mnemopay-sdk 项目说明书\n\n生成时间：2026-05-15 06:25:49 UTC\n\n## 目录\n\n- [Introduction to MnemoPay SDK](#introduction)\n- [Quick Start Guide](#quick-start)\n- [System Architecture](#architecture)\n- [Core Modules Reference](#core-modules)\n- [Payment Rails Overview](#payment-rails-overview)\n- [Stripe, Paystack & Lightning Rails](#stripe-rail)\n- [Alpha Payment Rails (StripeMPP, x402, GoogleAP2)](#alpha-rails)\n- [Charter & FiscalGate Governance](#charter-fiscalgate)\n- [MerkleAudit & Hash-Chained Ledger](#merkle-audit)\n- [Identity & KYA Compliance](#identity-kya)\n\n<a id='introduction'></a>\n\n## Introduction to MnemoPay SDK\n\n### 相关页面\n\n相关主题：[Quick Start Guide](#quick-start), [System Architecture](#architecture)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)\n- [CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)\n- [CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n- [site/index.legacy.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)\n- [integrations/python-hosted/README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/integrations/python-hosted/README.md)\n</details>\n\n# Introduction to MnemoPay SDK\n\nMnemoPay SDK is an AI agent trust and reputation SDK that provides memory, payments, identity, and agent credit scoring capabilities in a single package. It enables autonomous AI agents to handle financial operations, maintain persistent memory, and establish reputation across multi-agent systems.\n\n## Overview\n\nMnemoPay addresses the fundamental challenges of AI agent financial infrastructure:\n\n- **Memory**: Persistent memory with semantic recall and reinforcement capabilities\n- **Payments**: Real money through Stripe, Paystack, and Lightning payment rails with escrow support\n- **Identity**: KYA (Know Your Agent) verification, capability tokens, and permission management\n- **Agent Credit Score**: FICO-equivalent scoring (300-850) for AI agents enabling creditworthiness evaluation\n\n资料来源：[CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)\n\n## Architecture\n\nThe SDK consists of 14 core modules in the `src/` directory, providing approximately 74KB of compiled TypeScript functionality.\n\n```mermaid\ngraph TD\n    subgraph \"MnemoPay SDK Core\"\n        A[\"index.ts<br/>Main SDK Entry\"]\n        B[\"fico.ts<br/>Agent Credit Score\"]\n        C[\"behavioral.ts<br/>Behavioral Finance\"]\n        D[\"integrity.ts<br/>Merkle Integrity\"]\n        E[\"anomaly.ts<br/>EWMA Detection\"]\n        F[\"adaptive.ts<br/>AIMD/Circuit Breaker\"]\n        G[\"commerce.ts<br/>Shopping Engine\"]\n        H[\"fraud.ts<br/>Geo Fraud Detection\"]\n        I[\"identity.ts<br/>KYA/CapabilityTokens\"]\n        J[\"ledger.ts<br/>Double-Entry Ledger\"]\n        K[\"network.ts<br/>Multi-Agent Network\"]\n        L[\"client.ts<br/>REST Client\"]\n        M[\"mcp/server.ts<br/>MCP Server\"]\n    end\n    \n    subgraph \"Payment Rails\"\n        N[\"rails/stripe.ts\"]\n        O[\"rails/paystack.ts\"]\n        P[\"rails/lightning.ts\"]\n    end\n    \n    A --> B\n    A --> C\n    A --> D\n    A --> E\n    A --> F\n    A --> G\n    A --> H\n    A --> I\n    A --> J\n    A --> K\n    A --> L\n    A --> M\n    \n    L --> N\n    L --> O\n    L --> P\n```\n\n资料来源：[CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)\n\n### Module Overview\n\n| Module | Purpose |\n|--------|---------|\n| `index.ts` | Main SDK exports: MnemoPay, MnemoPayLite, MnemoPayNetwork classes |\n| `fico.ts` | Agent Credit Score (300-850); exports `AgentCreditScore` with legacy `AgentFICO` alias |\n| `behavioral.ts` | Behavioral finance engine implementing prospect theory and cooling-off mechanisms |\n| `integrity.ts` | Merkle tree memory integrity using SHA-256 hashing |\n| `anomaly.ts` | EWMA anomaly detection, BehaviorMonitor, and CanarySystem |\n| `adaptive.ts` | Adaptive AIMD rate limiting, anti-gaming protections, circuit breaker, PSI drift detection |\n| `commerce.ts` | CommerceEngine enabling autonomous shopping with financial mandates |\n| `fraud.ts` | Geo-enhanced fraud detection with location-based risk scoring |\n| `identity.ts` | IdentityRegistry, KYA verification, CapabilityTokens, and killswitch permissions |\n| `ledger.ts` | Double-entry accounting ledger for precise transaction tracking |\n| `network.ts` | Multi-agent commerce network coordination |\n| `client.ts` | REST API client for backend communication |\n| `mcp/server.ts` | MCP server exposing 24 tools and 2 prompts for agent interaction |\n\n资料来源：[CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)\n\n## Two SDK Modes\n\nMnemoPay provides two operational modes depending on deployment requirements:\n\n### Dev Mode (Zero Infrastructure)\n\n```typescript\nconst agent = MnemoPay.quick(\"agent-id\");\n```\n\nDev mode requires no backend infrastructure. Agents receive immediate access to memory, wallet functionality, and identity features directly in the client.\n\n资料来源：[CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)\n\n### Production Mode (Full Backend)\n\nProduction mode connects to the hosted MnemoPay console at `https://mnemopay-landing.fly.dev/` and requires backend connectivity for:\n\n- Persistent storage across sessions\n- Real payment rail integration\n- Multi-agent coordination\n- Governance and audit capabilities\n\n资料来源：[CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n\n## Quick Start\n\n### Installation\n\n```bash\nnpm install @mnemopay/sdk\n```\n\n### Development Workflow\n\n```bash\nnpm install        # install dependencies\nnpm run build      # compile TypeScript\nnpm test           # run 672+ vitest tests\nnpm run lint       # type-check without emit\n```\n\n资料来源：[CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)\n\n## Memory System\n\nThe memory system provides persistent, semantic memory capabilities for AI agents:\n\n### Core Operations\n\n| Operation | Description |\n|-----------|-------------|\n| `remember(content, namespace, tags, importance)` | Store new memory with semantic tagging |\n| `recall(query, namespace, limit, mode)` | Retrieve memories using hybrid search |\n| `reason(query, namespace, limit, mode)` | Complex reasoning over stored memories |\n| `reinforce(memoryId)` | Strengthen memory importance |\n| `forget(memoryId)` | Remove specific memories |\n\n### Memory Architecture\n\n```mermaid\ngraph LR\n    A[\"User Input\"] --> B[\"Namespace Router\"]\n    B --> C[\"remember()\"]\n    C --> D[\"Semantic Index\"]\n    D --> E[\"Memory Store\"]\n    \n    F[\"Query\"] --> G[\"recall()\"]\n    G --> H[\"Hybrid Search\"]\n    H --> I[\"Relevance Scorer\"]\n    I --> J[\"Ranked Results\"]\n    \n    K[\"Graph Enrichment\"] --> D\n    E --> K\n```\n\n### LongMemEval Benchmark\n\nThe memory system achieved **77.2%** on the LongMemEval oracle benchmark, demonstrating strong multi-session retrieval capabilities. The system handles 1M+ operational stress tests in production environments.\n\n资料来源：[site/journal/v1-4-0-longmemeval-77-2.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/journal/v1-4-0-longmemeval-77-2.html)\n\n## Payment System\n\n### Payment Rails\n\nMnemoPay integrates with three primary payment rails:\n\n| Rail | Region | Currencies | Features |\n|------|--------|------------|----------|\n| **Paystack** | Africa | NGN, GHS, ZAR, KES | Checkout, saved cards, bank transfers, webhook verification, HMAC-SHA512 |\n| **Stripe** | Global | USD, EUR, GBP, 135+ | Card payments, manual capture, true escrow via PaymentIntents |\n| **Lightning** | Crypto | BTC | Instant microtransactions for agent-to-agent payments |\n\n资料来源：[site/index.legacy.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)\n\n### Core Payment Operations\n\n```typescript\n// Charge customer\nawait agent.charge(amount, reason);\n\n// Settle transaction (release escrow)\nawait agent.settle(tx_id);\n\n// Refund\nawait agent.refund(tx_id);\n\n// Dispute handling\nawait agent.dispute(tx_id, reason);\n```\n\n### Escrow Flow\n\n```mermaid\ngraph TD\n    A[\"Agent charges()\"] --> B[\"Funds held in Escrow\"]\n    B --> C{\"Human approves?\"}\n    C -->|Yes| D[\"Agent settles()\"]\n    C -->|No| E[\"Refund initiated\"]\n    D --> F[\"Merchant receives funds\"]\n    E --> G[\"Customer refunded\"]\n```\n\n资料来源：[site/index.legacy.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)\n\n## Agent Credit Score\n\nThe Agent Credit Score (FICO-equivalent) provides a 300-850 scoring system for evaluating AI agent reliability and trustworthiness.\n\n### Scoring Components\n\n| Component | Weight | Description |\n|-----------|--------|-------------|\n| Payment History | 35% | Historical transaction success rate |\n| Utilization | 30% | Credit usage patterns |\n| Behavioral Signals | 20% | Prospect theory analysis, cooling-off adherence |\n| Anomaly Score | 10% | EWMA deviation from baseline behavior |\n| Identity Verification | 5% | KYA completion level |\n\n### Score Ranges\n\n| Score Range | Rating | Description |\n|-------------|--------|-------------|\n| 750-850 | Excellent | High-trust agent, minimal monitoring |\n| 650-749 | Good | Standard transaction limits |\n| 550-649 | Fair | Enhanced monitoring, lower limits |\n| 300-549 | Poor | Restricted operations, high collateral |\n\n资料来源：[CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)\n\n## Identity and Access Control\n\n### KYA (Know Your Agent)\n\nIdentity verification ensures agents are properly registered and authorized:\n\n```typescript\n// Register agent identity\nconst identity = await agent.identity.register({\n  agentId: \"agent-001\",\n  capabilities: [\"payment\", \"memory\", \"commerce\"],\n  verificationLevel: \"standard\"\n});\n\n// Issue capability token\nconst token = await agent.identity.issueToken(agentId, capabilities);\n```\n\n### Permission Model\n\n| Permission | Description |\n|-------------|-------------|\n| `payment.charge` | Initiate charges |\n| `payment.refund` | Process refunds |\n| `memory.write` | Store memories |\n| `memory.read` | Access memories |\n| `identity.delegate` | Issue sub-tokens |\n| `killswitch` | Emergency shutdown |\n\n资料来源：[CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)\n\n## Integrity and Security\n\n### Merkle Memory Integrity\n\nAll memories are protected using SHA-256 Merkle trees, enabling cryptographic proof of memory authenticity and detecting tampering:\n\n```typescript\n// Verify memory integrity\nconst audit = await agent.integrity.verify(memoryId);\nconst isValid = audit.proof.verify(rootHash, memoryId);\n```\n\n### EWMA Anomaly Detection\n\nExponentially Weighted Moving Average (EWMA) detects behavioral deviations:\n\n- Real-time monitoring of transaction patterns\n- Fingerprinting of agent behavior baselines\n- Canary systems for novel action detection\n\n资料来源：[CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)\n\n### Adaptive Rate Limiting\n\nThe adaptive module implements:\n\n- **AIMD (Additive Increase, Multiplicative Decrease)**: Graceful rate adjustment\n- **Circuit Breaker**: Automatic shutdown on repeated failures\n- **Anti-Gaming**: Detection of manipulation attempts\n- **PSI Drift**: Population Stability Index monitoring\n\n## Governance\n\nMnemoPay includes enterprise-grade governance features:\n\n| Component | Purpose |\n|-----------|---------|\n| **Charter** | Mission scope and operating principles |\n| **FiscalGate** | Budget enforcement and spending limits |\n| **Article 12** | Audit bundle requirements |\n| **MerkleAudit** | Cryptographic audit trail |\n\n资料来源：[CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n\n## Python Integration\n\nA Python port provides stable parity with the TypeScript SDK:\n\n```bash\npip install mnemopay\n```\n\nThe Python SDK mirrors the TypeScript `PaymentRail` interface and ships with `MockRail` and `StripeRail` implementations.\n\n资料来源：[integrations/python-hosted/README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/integrations/python-hosted/README.md)\n\n### Python API Methods\n\n| Method | Description |\n|--------|-------------|\n| `remember(content, namespace, tags, importance)` | Store memory |\n| `recall(query, namespace, limit, mode)` | Retrieve memories |\n| `charge(amount, reason)` | Process payment |\n| `settle(tx_id)` | Complete transaction |\n| `graph(namespace)` | Get memory graph |\n| `usage_report()` | Usage statistics |\n\n## Middleware Integration\n\nMnemoPay provides middleware for popular AI frameworks:\n\n### OpenAI Integration\n\n```typescript\nimport { mnemoPayMiddleware } from \"@mnemopay/sdk/middleware/openai\";\n```\n\n### Anthropic Integration\n\n```typescript\nimport { mnemoPayMiddleware } from \"@mnemopay/sdk/middleware/anthropic\";\n```\n\n### LangGraph Integration\n\n```typescript\nimport { mnemoPayTools } from \"@mnemopay/sdk/langgraph\";\n```\n\n资料来源：[README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)\n\n## Version History\n\n| Version | Status | Key Features |\n|---------|--------|--------------|\n| 1.6.0 | Alpha | Latest pre-release with hardening fixes |\n| 1.5.0 | Stable | Governance fold, FiscalGate, MerkleAudit |\n| 1.4.0 | Past | 77.2% LongMemEval, 1M-op stress test |\n| 1.0.0 | Python | Python SDK stable release |\n\n资料来源：[CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n\n## License\n\nMnemoPay SDK is Apache 2.0 Licensed.\n\n---\n\n<a id='quick-start'></a>\n\n## Quick Start Guide\n\n### 相关页面\n\n相关主题：[Introduction to MnemoPay SDK](#introduction)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)\n- [site/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)\n- [site/index.legacy.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)\n- [integrations/python-hosted/README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/integrations/python-hosted/README.md)\n- [dashboard/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/dashboard/index.html)\n</details>\n\n# Quick Start Guide\n\n## Overview\n\nThe Quick Start Guide provides developers with the fastest path to integrate MnemoPay SDK into their agent applications. MnemoPay is a full payment and memory system designed specifically for AI agents, enabling them to handle financial transactions, persistent memory, and identity management with zero configuration required.\n\n资料来源：[README.md:1-15](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)\n\n## Prerequisites\n\n| Requirement | Version/Details |\n|-------------|-----------------|\n| Node.js | v18+ recommended |\n| npm/yarn/pnpm | Any modern package manager |\n| API Key | Required for production use |\n| Environment | Node.js runtime |\n\n## Installation\n\nThe MnemoPay SDK is available on npm and can be installed with a single command:\n\n```bash\nnpm install @mnemopay/sdk\n```\n\n资料来源：[site/index.html:1-20](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)\n\n## Quick Initialization\n\nAfter installation, initialize your agent with a single function call that provides memory, wallet, and identity:\n\n```typescript\nimport { MnemoPay } from \"@mnemopay/sdk\";\n\n// Initialize with agent ID - zero config needed\nconst mnemo = MnemoPay.quick(\"agent-id\");\n\n// Your agent now has:\n// - Persistent memory system\n// - Payment wallet\n// - Unique identity\n```\n\n资料来源：[site/index.legacy.html:1-30](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)\n\n## Four-Step Workflow\n\nThe following diagram illustrates the complete workflow from installation to production:\n\n```mermaid\ngraph TD\n    A[Install<br/>npm install @mnemopay/sdk] --> B[Initialize<br/>MnemoPay.quick agent-id]\n    B --> C[Transact<br/>charge settle refund]\n    C --> D[Scale<br/>Multi-agent commerce]\n    \n    E[Memory System] --> B\n    F[Payment Wallet] --> B\n    G[Agent Identity] --> B\n    \n    H[Stripe] --> C\n    I[Paystack] --> C\n    J[Lightning] --> C\n```\n\n资料来源：[site/index.html:25-45](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)\n\n## Core Operations\n\n### Payment Operations\n\n| Method | Description |\n|--------|-------------|\n| `charge(amount, reason)` | Initiate a payment request |\n| `settle(tx_id)` | Complete an escrow release |\n| `refund(tx_id)` | Process a refund |\n\n资料来源：[site/index.legacy.html:15-25](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)\n\n### Memory Operations\n\n| Method | Description |\n|--------|-------------|\n| `remember(content, namespace, tags, importance)` | Store new information |\n| `recall(query, namespace, limit, mode)` | Retrieve relevant memories |\n| `reinforce(memoryId)` | Increase memory importance |\n| `forget(memoryId)` | Remove a memory |\n\n资料来源：[integrations/python-hosted/README.md:1-50](https://github.com/mnemopay/mnemopay-sdk/blob/main/integrations/python-hosted/README.md)\n\n## Environment Configuration\n\nCreate a `.env` file in your project root with the following variables:\n\n| Variable | Description | Required |\n|----------|-------------|----------|\n| `MNEMO_API_KEY` | Your MnemoPay API key | Yes |\n| `STRIPE_KEY` | Stripe secret key | For Stripe payments |\n| `PAYSTACK_KEY` | Paystack secret key | For Paystack payments |\n| `LIGHTNING_CONFIG` | Lightning node config | For Lightning payments |\n\n## Middleware Integration\n\nMnemoPay provides middleware for popular AI frameworks:\n\n### OpenAI Integration\n\n```typescript\nimport { mnemoPayMiddleware } from \"@mnemopay/sdk/middleware/openai\";\n```\n\n### Anthropic Integration\n\n```typescript\nimport { mnemoPayMiddleware } from \"@mnemopay/sdk/middleware/anthropic\";\n```\n\n### LangGraph Integration\n\n```typescript\nimport { mnemoPayTools } from \"@mnemopay/sdk/langgraph\";\n```\n\n资料来源：[README.md:40-55](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)\n\n## Complete Example\n\n```typescript\nimport { MnemoPay } from \"@mnemopay/sdk\";\n\n// Initialize agent\nconst mnemo = MnemoPay.quick(\"checkout-agent-001\");\n\n// Store a memory\nawait mnemo.remember(\n  \"Customer prefers express shipping\",\n  \"default\",\n  [\"preference\", \"shipping\"],\n  0.9\n);\n\n// Recall relevant information\nconst memories = await mnemo.recall(\"shipping preferences\", \"default\", 5);\n\n// Process a payment\nconst charge = await mnemo.charge(29.99, \"Order #12345\");\n\n// Settle when order fulfilled\nawait mnemo.settle(charge.txId);\n```\n\n资料来源：[site/index.legacy.html:10-30](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)\n\n## Payment Rails\n\nMnemoPay supports three payment rails:\n\n| Rail | Region | Features |\n|------|--------|----------|\n| Paystack | Africa (NGN, GHS, ZAR, KES) | Checkout, saved cards, bank transfers, HMAC-SHA512 security |\n| Stripe | Global (USD, EUR, GBP) | Card payments, manual capture for escrow, 135+ currencies |\n| Lightning | Crypto | Instant Bitcoin payments |\n\n资料来源：[site/index.legacy.html:80-100](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)\n\n## Dashboard Access\n\nAfter initialization, you can monitor your agent's activity through the MnemoPay dashboard which provides:\n\n- Real-time transaction monitoring\n- Memory usage analytics\n- Agent credit score (300-850 scale)\n- Multi-agent network status\n\n资料来源：[dashboard/index.html:1-50](https://github.com/mnemopay/mnemopay-sdk/blob/main/dashboard/index.html)\n\n## Next Steps\n\n| Resource | Purpose |\n|----------|---------|\n| [Full Documentation](https://mnemopay.com) | Complete API reference |\n| [Pricing](https://mnemopay.com#pricing) | Starter/Pro/Enterprise plans |\n| [Enterprise](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/enterprise.html) | Custom integrations and support |\n\n---\n\n<a id='architecture'></a>\n\n## System Architecture\n\n### 相关页面\n\n相关主题：[Core Modules Reference](#core-modules), [Payment Rails Overview](#payment-rails-overview), [Charter & FiscalGate Governance](#charter-fiscalgate)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)\n- [CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n- [dashboard/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/dashboard/index.html)\n- [site/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)\n- [site/index.legacy.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)\n</details>\n\n# System Architecture\n\n## Overview\n\nThe MnemoPay SDK is a financial infrastructure layer designed specifically for AI agents. It provides a comprehensive system that combines memory management, payment processing, identity verification, and fraud detection into a unified architecture. The SDK operates as an alpha release (v1.6.0-alpha) with stable v1.5.0 available on the `latest` npm tag, maintaining the same underlying architecture across versions.\n\nThe system is built to enable autonomous financial transactions where AI agents can charge, settle, and refund payments while maintaining persistent memory and earning credit scores based on their transaction behavior. This architectural approach treats agents as first-class financial actors with identity, reputation, and accountability mechanisms built into the core.\n\n## Core Architecture Layers\n\n```mermaid\ngraph TD\n    subgraph GOVERNANCE[\"GOVERNANCE Layer\"]\n        Charter[\"Charter\"]\n        FiscalGate[\"FiscalGate\"]\n        Article12[\"Article 12\"]\n        MerkleAudit[\"MerkleAudit\"]\n    end\n    \n    subgraph IDENTITY[\"Identity Layer\"]\n        KYA[\"KYA\"]\n        Tokens[\"Tokens\"]\n        Perms[\"Permissions\"]\n        Killswitch[\"Killswitch\"]\n    end\n    \n    subgraph PAYMENTS[\"Payment Layer\"]\n        Charge[\"charge()\"]\n        Settle[\"settle()\"]\n        Refund[\"refund()\"]\n        Dispute[\"dispute()\"]\n    end\n    \n    subgraph MEMORY[\"Memory Layer\"]\n        Remember[\"remember\"]\n        Recall[\"recall\"]\n        Reinforce[\"reinforce\"]\n        Forget[\"forget\"]\n    end\n    \n    subgraph CREDIT[\"Agent Credit Score\"]\n        Scoring[\"5-component scoring\"]\n        ScoreRange[\"300-850 range\"]\n    end\n    \n    subgraph BEHAVIORAL[\"Behavioral Finance\"]\n        Prospect[\"Prospect Theory\"]\n        Nudges[\"Nudges\"]\n    end\n    \n    subgraph ANOMALY[\"Anomaly Detection\"]\n        EWMA[\"EWMA\"]\n        Fingerprinting[\"Fingerprinting\"]\n    end\n    \n    GOVERNANCE --> IDENTITY\n    GOVERNANCE --> PAYMENTS\n    MEMORY --> CREDIT\n    PAYMENTS --> CREDIT\n    CREDIT --> BEHAVIORAL\n    PAYMENTS --> ANOMALY\n```\n\n## System Components\n\n### SDK Client Architecture\n\nThe MnemoPay SDK operates through a client-based architecture where developers initialize the system using the `MnemoPay.quick()` factory method. This approach provides zero-configuration setup that immediately gives an agent access to memory capabilities, wallet functionality, and cryptographic identity verification. The client handles all communication with backend services while presenting a clean, intuitive API surface for developers.\n\nThe SDK is distributed as `@mnemopay/sdk` on npm and supports installation via standard Node.js package managers. The TypeScript implementation provides full type safety and IDE integration, while a Python port (`mnemopay` on PyPI) achieves stable parity with the TypeScript implementation, including the `PaymentRail` interface with sync API support.\n\n| Component | Purpose | Language Support |\n|-----------|---------|------------------|\n| Core SDK | Client initialization, API abstraction | TypeScript, Python |\n| Payment Rails | Transaction processing | TypeScript, Python |\n| MCP Server | Model Context Protocol integration | TypeScript |\n| Middleware | Framework integrations | TypeScript |\n\n### Payment Rail System\n\nThe payment architecture implements a rail abstraction layer that supports multiple payment providers while maintaining a consistent interface. This design allows the system to switch between payment providers without changing application code, providing flexibility for different markets and use cases.\n\n```mermaid\ngraph LR\n    App[\"Application\"] --> SDK[\"MnemoPay SDK\"]\n    SDK --> Stripe[\"Stripe Rail\"]\n    SDK --> Paystack[\"Paystack Rail\"]\n    SDK --> Lightning[\"Lightning Rail\"]\n    SDK --> Mock[\"Mock Rail\"]\n    \n    Stripe --> StripeAPI[\"Stripe API<br/>USD, EUR, GBP\"]\n    Paystack --> PaystackAPI[\"Paystack API<br/>NGN, GHS, ZAR, KES\"]\n    Lightning --> LightningNet[\"Lightning Network<br/>BTC\"]\n    \n    style Stripe fill:#635bff,color:#fff\n    style Paystack fill:#00abd1,color:#fff\n    style Lightning fill:#f7931a,color:#fff\n```\n\n**Supported Payment Rails:**\n\n| Rail | Region | Currencies | Features |\n|------|--------|------------|----------|\n| Stripe | Global | USD, EUR, GBP, 135+ | Manual capture for true escrow, PaymentIntents API |\n| Paystack | Africa | NGN, GHS, ZAR, KES | Checkout, saved cards, bank transfers, webhook verification, HMAC-SHA512 security, 23 Nigerian banks pre-mapped |\n| Lightning | Crypto | BTC | Instant settlement via Lightning Network |\n| Mock | Testing | All | Test mode without real transactions |\n\nThe escrow mechanism holds funds until human approval, providing a critical safety layer for autonomous agent transactions. When an agent initiates a charge, funds are captured but not settled until explicit human authorization, preventing unauthorized autonomous spending.\n\n### Identity and Access Control\n\nThe identity layer implements Know Your Agent (KYA) verification with cryptographic tokens and permission management. A killswitch mechanism provides emergency stop capabilities, allowing immediate revocation of agent permissions across all active sessions.\n\nIdentity components operate through a multi-layered verification system:\n\n- **KYA (Know Your Agent)**: Agent registration and verification process\n- **Tokens**: Cryptographic credentials for API authentication\n- **Permissions**: Granular access control for agent capabilities\n- **Killswitch**: Emergency permission revocation system\n\n### Agent Credit Score System\n\nAgents receive credit scores ranging from 300 to 850, calculated through a five-component scoring model. This scoring system directly influences the agent's financial capabilities, including transaction limits and pricing terms.\n\n| Score Component | Description | Impact |\n|----------------|-------------|--------|\n| Payment History | Historical transaction success rate | Primary factor |\n| Transaction Volume | Total and average transaction sizes | Secondary factor |\n| Dispute Rate | Ratio of disputed to total transactions | Negative impact |\n| Response Time | Speed of human approval responses | Moderate impact |\n| Behavioral Patterns | Anomaly detection signals | Risk adjustment |\n\nThe credit score affects the **Ceiling** parameter, calculated as `$500 × reputation` per charge, and determines the agent's decay rate with a half-life of approximately 14 hours. Settling transactions adds +0.05 importance to the memory reinforcement system, creating a feedback loop that improves score accuracy over time.\n\n## Communication Architecture\n\n### Backend Communication\n\nThe MnemoPay console backend implements a robust communication infrastructure with the following characteristics:\n\n- **REST API**: Primary interface for synchronous operations\n- **WebSockets**: Real-time event streaming for dashboard updates\n- **Webhooks**: Asynchronous notification system for payment events\n\nThe hosted console at `mnemopay-landing.fly.dev` implements three-tier reliability architecture:\n\n| Tier | Components | Purpose |\n|------|------------|---------|\n| Tier 1 | Production blockers | Core functionality protection |\n| Tier 2 | Observability | Monitoring and metrics |\n| Tier 3 | Safety nets | Rate limiting, body-size caps, idempotent webhooks |\n\n### Observability Stack\n\n```mermaid\ngraph TD\n    subgraph OBSERVABILITY[\"Observability Layer\"]\n        Metrics[\"Prometheus /metrics\"]\n        Logs[\"Structured JSON Logging\"]\n        Health[\"Health Endpoints\"]\n    end\n    \n    subgraph SAFETY[\"Safety Layer\"]\n        RateLimit[\"Rate Limiting\"]\n        BodyCap[\"Body Size Caps\"]\n        CORS[\"CORS Allowlist\"]\n        Headers[\"Security Headers\"]\n    end\n    \n    subgraph DELIVERY[\"Delivery Layer\"]\n        Webhook[\"Webhook Notifications\"]\n        Idempotent[\"Idempotent Processing\"]\n        Shutdown[\"Graceful Shutdown\"]\n    end\n    \n    Metrics --> Prometheus[\"Prometheus\"]\n    Logs --> ELK[\"ELK Stack\"]\n    Health --> Ready[\"/readyz endpoint\"]\n    RateLimit --> SAFETY\n    Webhook --> Idempotent\n    Ready --> ReadyResponse{\"readyz response<br/>productionReady: true\"}\n```\n\nSecurity headers including Content-Security-Policy, X-Content-Type-Options, and X-Frame-Options protect the dashboard from common web vulnerabilities. The `/readyz` endpoint returns `productionReady: true` when all systems are operational, serving as a health check for load balancers and orchestrators.\n\n## Middleware Integrations\n\nThe SDK provides middleware packages for seamless integration with popular AI frameworks, enabling automatic transaction tracking and payment capabilities within existing agent workflows.\n\n### Available Middleware\n\n| Integration | Package Path | Purpose |\n|-------------|--------------|---------|\n| OpenAI | `@mnemopay/sdk/middleware/openai` | OpenAI agent transaction middleware |\n| Anthropic | `@mnemopay/sdk/middleware/anthropic` | Anthropic Claude agent middleware |\n| LangGraph | `@mnemopay/sdk/langgraph` | LangGraph tools integration |\n\n### MCP Server\n\nThe Model Context Protocol (MCP) server enables standardized communication between AI models and external tools. The MCP server implementation in `src/mcp/server.ts` uses `require.main === module` to prevent spurious server starts when consumers import from `@mnemopay/sdk/mcp` in browser bundles or test harnesses. This auto-start guard replaces the previous loose `process.argv` heuristic that caused issues with browser consumers.\n\n## Dashboard Architecture\n\nThe web-based dashboard provides real-time monitoring and management capabilities through a React-based single-page application. The dashboard architecture uses a tabbed interface with specialized panels for different operational concerns.\n\n```mermaid\ngraph TD\n    subgraph DASHBOARD[\"Dashboard Components\"]\n        Console[\"Console Panel\"]\n        Session[\"Session Panel\"]\n        Brain[\"Brain Panel\"]\n        Developer[\"Developer Panel\"]\n        Billing[\"Billing Panel\"]\n        Repos[\"Repos Panel\"]\n    end\n    \n    subgraph STATE[\"Application State\"]\n        Profile[\"Profile<br/>wallet, reputation, memoriesCount\"]\n        Overview[\"Overview<br/>transactions, members, apiKeys\"]\n        Session[\"Session<br/>login, logout state\"]\n        Repos[\"Repos<br/>GitHub monitoring\"]\n    end\n    \n    Console --> STATE\n    Session --> STATE\n    Brain --> STATE\n    Developer --> STATE\n    Billing --> STATE\n    Repos --> STATE\n```\n\n**Dashboard Tabs and Functions:**\n\n| Tab | Icon | Function |\n|-----|------|----------|\n| Console | System monitor | Overview of transactions and account status |\n| Session | Users | Login/logout session management |\n| Brain | Brain icon | Memory recall and query interface |\n| Developer | Code brackets | API key management |\n| Billing | Credit card | Usage metering and plan limits |\n| Memories | Database | Memory persistence configuration |\n\n### GitHub Repository Monitoring\n\nThe dashboard includes a repository monitoring feature that tracks GitHub forks and upstream stars. Repositories are displayed with status indicators showing:\n\n- Upstream star count\n- Last update date\n- Pull request information with title, number, and creation date\n- Error states when fetching fails\n\n## Behavioral Finance System\n\nThe architecture incorporates behavioral finance principles through prospect theory implementation and nudging mechanisms. These components work together to influence agent decision-making in financial contexts, encouraging optimal behavior while preventing risky transaction patterns.\n\n### Anomaly Detection\n\nTransaction anomaly detection uses Exponentially Weighted Moving Average (EWMA) statistical methods combined with behavioral fingerprinting. This dual approach identifies both statistical outliers and behavioral patterns that deviate from established agent profiles.\n\n| Detection Method | Function |\n|-----------------|----------|\n| EWMA | Statistical anomaly detection on transaction amounts and frequencies |\n| Fingerprinting | Behavioral pattern recognition across transaction sequences |\n\n## Governance Framework\n\nThe governance layer provides institutional controls over agent financial activities through four primary mechanisms:\n\n- **Charter**: Defines agent mission scope and authorized activities\n- **FiscalGate**: Budget enforcement for transaction limits\n- **Article 12**: Compliance and regulatory requirements\n- **MerkleAudit**: Cryptographic audit trail for transaction verification\n\nThis multi-layered governance ensures agents operate within defined parameters while maintaining full accountability for their financial actions.\n\n## SDK Installation and Quick Start\n\n```bash\n# Install the SDK\nnpm install @mnemopay/sdk\n\n# Python installation (alternative)\npip install mnemopay\n```\n\n```typescript\n// Initialize with zero configuration\nimport { MnemoPay } from \"@mnemopay/sdk\";\n\nconst agent = MnemoPay.quick(\"agent-id\");\n\n// The agent now has:\n// - Persistent memory\n// - Wallet functionality\n// - Cryptographic identity\n// - Payment capabilities\n```\n\n资料来源：[README.md:1-40](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)\n资料来源：[site/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)\n资料来源：[site/index.legacy.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)\n资料来源：[dashboard/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/dashboard/index.html)\n资料来源：[CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n\n---\n\n<a id='core-modules'></a>\n\n## Core Modules Reference\n\n### 相关页面\n\n相关主题：[System Architecture](#architecture)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/index.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/index.ts)\n- [src/recall/engine.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/recall/engine.ts)\n- [src/fraud.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/fraud.ts)\n- [src/identity/index.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/identity/index.ts)\n- [src/ledger.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/ledger.ts)\n- [src/fico.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/fico.ts)\n- [src/behavioral.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/behavioral.ts)\n- [src/integrity.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/integrity.ts)\n- [src/anomaly.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/anomaly.ts)\n- [src/adaptive.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/adaptive.ts)\n- [src/commerce.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/commerce.ts)\n- [src/mcp/server.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/mcp/server.ts)\n</details>\n\n# Core Modules Reference\n\nThe MnemoPay SDK comprises 14 core modules organized in the `src/` directory, providing a comprehensive trust and reputation infrastructure for AI agents that handle money. This reference documents all foundational modules, their responsibilities, and how they interrelate to form a complete payment and identity system.\n\n## Architecture Overview\n\nThe SDK architecture follows a layered design where core primitives (memory, ledger, identity) support higher-order features (payments, commerce, fraud detection). The main export `MnemoPay` bundles all modules into a unified interface (~74KB), while `MnemoPayLite` provides a lightweight alternative and `MnemoPayNetwork` extends functionality for multi-agent scenarios.\n\n```mermaid\ngraph TD\n    subgraph \"Core Layer\"\n        M[Memory/Recall]\n        L[Ledger]\n        I[Identity]\n    end\n    \n    subgraph \"Trust Layer\"\n        F[FICO - Agent Credit Score]\n        B[Behavioral Finance]\n        IN[Integrity - Merkle Trees]\n    end\n    \n    subgraph \"Safety Layer\"\n        A[Anomaly Detection]\n        AD[Adaptive - AIMD/Circuit Breaker]\n        FR[Fraud Detection]\n    end\n    \n    subgraph \"Commerce Layer\"\n        C[Commerce Engine]\n        N[Network]\n        R[Payment Rails]\n    end\n    \n    M --> F\n    M --> B\n    L --> A\n    I --> AD\n    F --> FR\n    B --> C\n    C --> R\n    N --> R\n    I --> N\n```\n\n资料来源：[README.md:40-55]()\n\n## Memory Module (`src/recall/`)\n\nThe memory module provides persistent, searchable memory capabilities for agents using semantic and hybrid retrieval. It supports the core memory operations: remember, recall, reinforce, forget, and consolidate.\n\n### Memory Operations\n\n| Operation | Purpose | Parameters |\n|-----------|---------|------------|\n| `remember(content, namespace?, tags?, importance?)` | Store a memory with optional importance score and tags | Content string, namespace ID, tag array, importance 0-1 |\n| `recall(query, namespace?, limit?, mode?)` | Retrieve relevant memories via semantic search | Query string, namespace, result limit, search mode |\n| `reinforce(memoryId)` | Boost a memory's importance score (+0.01 to +0.5) | Memory ID |\n| `forget(memoryId)` | Permanently delete a memory by ID | Memory ID |\n| `consolidate(namespace?)` | Prune stale memories below decay threshold | Optional namespace filter |\n\n### Search Modes\n\nThe recall engine supports multiple retrieval modes for different use cases:\n\n```mermaid\ngraph LR\n    A[Query] --> B{Mode}\n    B -->|semantic| C[Vector Embedding Search]\n    B -->|keyword| D[BM25 Full-Text Search]\n    B -->|hybrid| E[Weighted Combination]\n    C --> F[Results]\n    D --> F\n    E --> F\n```\n\n- **semantic**: Pure vector similarity search using embeddings\n- **keyword**: Traditional BM25-based keyword matching\n- **hybrid**: Weighted combination of both approaches (default)\n\n资料来源：[src/recall/engine.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/recall/engine.ts)\n\n### Memory Structure\n\nEach memory entry contains:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `id` | string | Unique memory identifier |\n| `content` | string | The memory content |\n| `namespace` | string | Logical partition for memory spaces |\n| `tags` | string[] | Categorization tags |\n| `importance` | number | 0-1 importance score for retrieval weighting |\n| `createdAt` | Date | Creation timestamp |\n| `updatedAt` | Date | Last modification timestamp |\n| `accessCount` | number | Number of times recalled |\n\n资料来源：[integrations/openclaw/SKILL.md:20-35]()\n\n## Ledger Module (`src/ledger.ts`)\n\nThe ledger implements double-entry bookkeeping for all financial transactions. Every monetary operation creates balanced entries ensuring accounting integrity across charges, settlements, and refunds.\n\n### Transaction Types\n\n| Type | Description | Ledger Impact |\n|------|-------------|---------------|\n| `charge` | Creates escrow hold for delivered work | Debit: Receivable, Credit: Escrow |\n| `settle` | Finalizes charge, moves funds to wallet | Debit: Escrow, Credit: Revenue |\n| `refund` | Reverses a transaction | Debit: Escrow, Credit: Receivable |\n| `dispute` | User-initiated chargeback | Triggers fraud analysis |\n\n### Transaction States\n\n```mermaid\nstateDiagram-v2\n    [*] --> pending: charge()\n    pending --> escrow: User Approval\n    pending --> cancelled: Timeout/Reject\n    escrow --> settled: settle()\n    escrow --> refunded: refund()\n    settled --> disputed: User Dispute\n    disputed --> refunded: Won Dispute\n    disputed --> settled: Lost Dispute\n```\n\n资料来源：[src/ledger.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/ledger.ts)\n\n## Identity Module (`src/identity/`)\n\nThe identity system manages agent identification, capabilities, and permissions through a multi-layered approach.\n\n### Components\n\n| Component | Purpose |\n|-----------|---------|\n| `IdentityRegistry` | Central registry mapping agent IDs to identities |\n| `KYA` (Know Your Agent) | Onboarding verification for new agents |\n| `CapabilityTokens` | Time-limited permission grants |\n| `killswitch` | Emergency capability revocation |\n\n### Identity Model\n\n```typescript\ninterface Identity {\n  agentId: string;\n  publicKey: string;\n  reputation: number;        // 0-1 score\n  kyaStatus: KYAStatus;\n  capabilities: Capability[];\n  createdAt: Date;\n  lastActive: Date;\n}\n```\n\n资料来源：[src/identity/index.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/identity/index.ts)\n\n## Agent Credit Score (`src/fico.ts`)\n\nThe Agent Credit Score provides a portable, standardized credit evaluation (300-850 range) for AI agents, enabling trust assessment across different platforms and use cases.\n\n### Scoring Components\n\nThe FICO module calculates scores using five weighted factors:\n\n| Component | Weight | Description |\n|-----------|--------|-------------|\n| Payment History | 35% | Track record of successful settlements |\n| Utilization | 30% | Current escrow exposure relative to limits |\n| Account Age | 15% | Duration of active account |\n| Diversity | 10% | Range of transaction types and rails used |\n| Reputation | 10% | Social/professional reputation signals |\n\n### Score Ranges\n\n| Range | Classification | Description |\n|-------|-----------------|-------------|\n| 800-850 | Exceptional | Highly reliable, lowest risk |\n| 740-799 | Very Good | Reliable with minimal risk |\n| 670-739 | Good | Acceptable risk level |\n| 580-669 | Fair | Elevated risk, monitor closely |\n| 300-579 | Poor | High risk, limited capabilities |\n\n资料来源：[src/fico.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/fico.ts)\n\n## Fraud Detection (`src/fraud.ts`)\n\nThe fraud module provides geo-enhanced fraud detection with pattern recognition and behavioral analysis.\n\n### Detection Mechanisms\n\n```mermaid\ngraph TD\n    A[Transaction Request] --> B[Geo Analysis]\n    A --> C[Pattern Matching]\n    A --> D[Velocity Check]\n    B --> E{Risk Score}\n    C --> E\n    D --> E\n    E -->|Low| F[Allow]\n    E -->|Medium| G[Flag for Review]\n    E -->|High| H[Block + Alert]\n```\n\n### Risk Factors\n\n| Factor | Description | Threshold |\n|--------|-------------|-----------|\n| `geoVelocity` | Rapid location changes impossible for user | >500km/hour |\n| `velocityVolume` | Unusual transaction frequency | >10 tx/hour |\n| `amountAnomaly` | Statistical outlier in transaction size | >3σ from mean |\n| `patternDeviation` | Deviation from established behavioral patterns | Similarity <0.6 |\n\n资料来源：[src/fraud.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/fraud.ts)\n\n## Anomaly Detection (`src/anomaly.ts`)\n\nEWMA (Exponentially Weighted Moving Average) anomaly detection monitors behavioral patterns and identifies deviations that may indicate compromise or abuse.\n\n### Components\n\n| Component | Purpose |\n|-----------|---------|\n| `EWMA` | Core statistical monitoring with exponential weighting |\n| `BehaviorMonitor` | Tracks behavioral baselines per agent |\n| `CanarySystem` | Synthetic transactions to verify system integrity |\n\n### Alert Levels\n\n```mermaid\ngraph LR\n    A[Metric Stream] --> B[EWMA Calculation]\n    B --> C{Deviation Check}\n    C -->|< 2σ| D[Normal]\n    C -->|2-3σ| E[Warning]\n    C -->|> 3σ| F[Critical Alert]\n    D --> G[No Action]\n    E --> H[Log + Notify]\n    F --> I[Block + Response]\n```\n\n资料来源：[src/anomaly.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/anomaly.ts)\n\n## Behavioral Finance (`src/behavioral.ts`)\n\nThe behavioral module implements concepts from behavioral economics to influence agent decision-making and user interactions.\n\n### Features\n\n| Feature | Description |\n|---------|-------------|\n| Prospect Theory | Loss aversion calculations (losses weighted 2x gains) |\n| Cooling-Off Periods | Mandatory waiting periods for high-value transactions |\n| Nudges | Behavioral prompts to encourage positive outcomes |\n\n### Cooling-Off Rules\n\nHigh-value transactions (>100 USD equivalent) trigger mandatory review periods:\n\n| Amount Range | Cooling Period |\n|--------------|-----------------|\n| $100-$500 | 24 hours |\n| $500-$1000 | 72 hours |\n| >$1000 | 7 days |\n\n资料来源：[src/behavioral.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/behavioral.ts)\n\n## Integrity Module (`src/integrity.ts`)\n\nMerkle tree-based memory integrity provides cryptographic proof of memory chain integrity using SHA-256 hashing.\n\n### Verification Process\n\n```mermaid\ngraph TD\n    A[Memory Entry] --> B[SHA-256 Hash]\n    B --> C[Merkle Tree Node]\n    C --> D{Root Hash}\n    D --> E[Audit Request]\n    E --> F[Prove Path]\n    F --> G[Verify against Root]\n    G --> H[Valid/Invalid]\n```\n\n### Audit Capabilities\n\n| Feature | Description |\n|---------|-------------|\n| `MerkleAudit` | Generates proof bundles for external verification |\n| Chain Verification | Validates no memories were tampered with |\n| Timestamping | Provides proof of memory existence at time T |\n\n资料来源：[src/integrity.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/integrity.ts)\n\n## Adaptive Module (`src/adaptive.ts`)\n\nAdaptive rate limiting and anti-gaming mechanisms prevent abuse while allowing legitimate high-throughput scenarios.\n\n### Components\n\n| Component | Purpose |\n|-----------|---------|\n| `AIMD` | Additive Increase, Multiplicative Decrease rate control |\n| Anti-Gaming | Detection of rate limit exploitation patterns |\n| `CircuitBreaker` | Prevents cascade failures |\n| `PSI Drift` | Population Stability Index for distribution shifts |\n\n### Circuit Breaker States\n\n```mermaid\nstateDiagram-v2\n    [*] --> Closed: Normal Operation\n    Closed --> Open: Failure Threshold\n    Open --> HalfOpen: Recovery Timeout\n    HalfOpen --> Closed: Success\n    HalfOpen --> Open: Failure\n```\n\n资料来源：[src/adaptive.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/adaptive.ts)\n\n## Commerce Engine (`src/commerce.ts`)\n\nThe commerce engine enables autonomous shopping with configurable mandates and spending policies.\n\n### Mandate Structure\n\n```typescript\ninterface Mandate {\n  id: string;\n  agentId: string;\n  rules: CommerceRule[];\n  maxAmount: number;\n  maxFrequency: number;\n  allowedCategories: string[];\n  createdAt: Date;\n}\n```\n\n### Shopping Workflow\n\n```mermaid\ngraph TD\n    A[User Request] --> B[Parse Intent]\n    B --> C[Check Mandate Permissions]\n    C -->|Permitted| D[Find Best Offer]\n    C -->|Denied| E[Return Error]\n    D --> F[Execute Purchase]\n    F --> G[Charge Escrow]\n    G --> H[Confirm to User]\n    E --> I[Log Denial]\n```\n\n资料来源：[src/commerce.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/commerce.ts)\n\n## MCP Server (`src/mcp/server.ts`)\n\nThe Model Context Protocol server exposes SDK functionality as MCP tools for integration with LLM agents.\n\n### Available Tools (24 total)\n\n#### Memory Tools (5)\n\n| Tool | Description |\n|------|-------------|\n| `mcp__mnemopay__remember` | Store a memory with optional importance and tags |\n| `mcp__mnemopay__recall` | Retrieve relevant memories via semantic search |\n| `mcp__mnemopay__forget` | Permanently delete a memory |\n| `mcp__mnemopay__reinforce` | Boost memory importance |\n| `mcp__mnemopay__consolidate` | Prune stale memories |\n\n#### Payment Tools (4)\n\n| Tool | Description |\n|------|-------------|\n| `mcp__mnemopay__charge` | Create escrow charge (max $500 × reputation) |\n| `mcp__mnemopay__settle` | Finalize pending charge |\n| `mcp__mnemopay__refund` | Process refund |\n| `mcp__mnemopay__dispute` | File dispute for chargeback |\n\n#### Additional Tools\n\n- Identity management tools\n- Ledger query tools\n- Reputation management tools\n- Usage and audit tools\n\n资料来源：[src/mcp/server.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/mcp/server.ts)\n资料来源：[integrations/openclaw/SKILL.md:40-60]()\n\n## Payment Rails (`src/rails/`)\n\nThe rails module provides abstraction over multiple payment providers, enabling cross-border commerce through standardized interfaces.\n\n### Supported Rails\n\n| Rail | Region | Currencies | Features |\n|------|--------|------------|----------|\n| Stripe | Global | USD, EUR, GBP, 135+ | PaymentIntents, Manual Capture, Webhooks |\n| Paystack | Africa | NGN, GHS, ZAR, KES | Checkout, Saved Cards, Bank Transfer, HMAC-SHA512 |\n| Lightning | Crypto | BTC | Instant settlement, Micropayments |\n\n### Rail Interface\n\n```typescript\ninterface PaymentRail {\n  charge(amount: number, currency: string, options: ChargeOptions): Promise<ChargeResult>;\n  settle(chargeId: string): Promise<SettlementResult>;\n  refund(chargeId: string, amount?: number): Promise<RefundResult>;\n  verifyWebhook(payload: any, signature: string): boolean;\n}\n```\n\n### Escrow Flow\n\n```mermaid\nsequenceDiagram\n    participant Agent\n    participant SDK\n    participant Rail\n    participant Escrow\n    participant User\n    \n    Agent->>SDK: charge(amount)\n    SDK->>Rail: Create PaymentIntent\n    Rail-->>SDK: Pending Charge\n    SDK->>Escrow: Hold Funds\n    User->>User: Review Work\n    alt Approved\n        User->>SDK: approve()\n        SDK->>Rail: Capture\n        SDK->>Escrow: Release to Wallet\n        SDK->>SDK: reputation += 0.01\n    else Rejected\n        User->>SDK: dispute()\n        SDK->>SDK: Fraud Analysis\n    end\n```\n\n资料来源：[src/index.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/index.ts)\n\n## Main SDK Entry (`src/index.ts`)\n\nThe main index exports three SDK variants optimized for different use cases.\n\n### SDK Variants\n\n| Variant | Size | Use Case |\n|---------|------|----------|\n| `MnemoPay` | ~74KB | Full-featured production use |\n| `MnemoPayLite` | <20KB | Browser, edge functions, constrained environments |\n| `MnemoPayNetwork` | +~15KB | Multi-agent scenarios |\n\n### Quick Start\n\n```typescript\nimport { MnemoPay } from '@mnemopay/sdk';\n\n// Development mode - zero infrastructure\nconst agent = MnemoPay.quick(\"agent-id\");\n\n// Store memory\nawait agent.remember(\"User prefers Express shipping\", { importance: 0.8 });\n\n// Recall previous context\nconst memories = await agent.recall(\"shipping preferences\");\n\n// Charge for work delivered\nconst charge = await agent.charge(25.00, \"Monthly report delivery\");\n\n// Settle after user approval\nawait agent.settle(charge.id);\n```\n\n### Initialization Modes\n\n| Mode | Description | Infrastructure Required |\n|------|-------------|------------------------|\n| `quick(agentId)` | Dev mode with mock services | None |\n| `init(config)` | Production mode with real services | API keys, secrets |\n| `network(config)` | Multi-agent network mode | Network registry |\n\n资料来源：[src/index.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/index.ts)\n资料来源：[README.md:55-75]()\n\n## Module Dependencies\n\nUnderstanding module dependencies is crucial for proper integration and troubleshooting.\n\n```mermaid\ngraph TD\n    R[Recall/Memory] --> L[Ledger]\n    I[Identity] --> R\n    I --> F[FICO]\n    F --> FR[Fraud]\n    B[Behavioral] --> C[Commerce]\n    A[Anomaly] --> L\n    AD[Adaptive] --> A\n    L --> N[Network]\n    I --> N\n    C --> RA[Rails]\n    R --> IN[Integrity]\n```\n\n## Configuration Reference\n\n### Required Configuration\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `agentId` | string | Unique agent identifier |\n| `apiKey` | string | API authentication key |\n| `networkId` | string | Network/tenant identifier |\n\n### Optional Configuration\n\n| Parameter | Default | Description |\n|-----------|---------|-------------|\n| `mode` | `\"dev\"` | Runtime mode: dev, production, network |\n| `rail` | `\"stripe\"` | Primary payment rail |\n| `region` | `\"us-east-1\"` | Deployment region |\n| `logLevel` | `\"warn\"` | Logging verbosity |\n\n资料来源：[src/index.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/index.ts)\n\n## Testing\n\nThe SDK includes 672+ vitest tests covering all modules:\n\n```bash\nnpm test           # Run all tests\nnpm run build      # Compile TypeScript\nnpm run lint       # Type-check without emit\n```\n\nTest coverage is distributed across:\n\n| Module | Test Focus |\n|--------|------------|\n| Memory | CRUD operations, search accuracy, consolidation |\n| Ledger | Double-entry balance, transaction states |\n| Identity | KYA flow, capability tokens, killswitch |\n| Fraud | Geo-velocity, pattern matching, thresholds |\n| Anomaly | EWMA calculation, alert thresholds |\n| Rails | Payment flows, webhook verification |\n\n---\n\n<a id='payment-rails-overview'></a>\n\n## Payment Rails Overview\n\n### 相关页面\n\n相关主题：[Stripe, Paystack & Lightning Rails](#stripe-rail), [Alpha Payment Rails (StripeMPP, x402, GoogleAP2)](#alpha-rails), [System Architecture](#architecture)\n\n<details>\n<summary>Related Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/rails/index.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/rails/index.ts)\n- [src/rails/stripe-mpp.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/rails/stripe-mpp.ts)\n- [src/rails/x402.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/rails/x402.ts)\n- [src/rails/google-ap2.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/rails/google-ap2.ts)\n</details>\n\n# Payment Rails Overview\n\n## Introduction\n\nThe MnemoPay SDK provides a unified payment abstraction layer called **Payment Rails**, which enables AI agents to process payments across multiple payment providers through a consistent interface. This architecture decouples business logic from payment provider specifics, allowing developers to switch between or combine payment rails without modifying core application code.\n\nThe Payment Rails system supports both stable, production-ready rails and preview/alpha rails for emerging payment methods. All rails share a common API contract, ensuring predictable behavior regardless of the underlying payment provider. 资料来源：[README.md:1-45]()\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    A[Agent / Application] --> B[MnemoPay SDK Core]\n    B --> C[Payment Rail Abstraction Layer]\n    C --> D[StripeRail]\n    C --> E[PaystackRail]\n    C --> F[LightningRail]\n    C --> G[StripeMPPRail]\n    C --> H[X402Rail]\n    C --> I[GoogleAP2Rail]\n    D --> J[Stripe API]\n    E --> K[Paystack API]\n    F --> L[LND / Lightning Network]\n    G --> M[Stripe MPP]\n    H --> N[Base / EIP-3009]\n    I --> O[Google AP2]\n```\n\n## Rail Classification\n\nPayment rails in MnemoPay are classified into two stability tiers:\n\n| Classification | Rails | Use Case | Status |\n|---|---|---|---|\n| **Stable** | `StripeRail`, `PaystackRail`, `LightningRail` | Production deployments | `latest` |\n| **Preview (Alpha)** | `StripeMPPRail`, `X402Rail`, `GoogleAP2Rail` | Evaluation and testing | `alpha` |\n\n资料来源：[README.md:8-16]()\n\n## Stable Rails\n\n### StripeRail\n\n`StripeRail` provides global card payment processing supporting USD, EUR, GBP, and 135+ currencies. It uses Stripe's PaymentIntents API with manual capture to enable true escrow functionality.\n\n**Supported Currencies:** USD, EUR, GBP, +135 currencies  \n**Use Cases:** Global payments, subscription billing, e-commerce  \n**Security:** PCI-compliant via Stripe\n\n**Initialization:**\n```ts\nimport { StripeRail } from \"@mnemopay/sdk\";\n\nconst stripe = new StripeRail(process.env.STRIPE_SECRET_KEY!);\n```\n\n资料来源：[README.md:20-24]()\n\n### PaystackRail\n\n`PaystackRail` focuses on African markets, supporting NGN (Nigerian Naira), GHS (Ghanaian Cedi), ZAR (South African Rand), and KES (Kenyan Shilling). It provides checkout, saved cards, bank transfers, and webhook verification with HMAC-SHA512 security.\n\n**Supported Currencies:** NGN, GHS, ZAR, KES  \n**Regional Coverage:** Africa (23 Nigerian banks pre-mapped)  \n**Security:** HMAC-SHA512 webhook verification\n\n**Initialization:**\n```ts\nimport { PaystackRail } from \"@mnemopay/sdk\";\n\nconst paystack = new PaystackRail(process.env.PAYSTACK_SECRET_KEY!);\n```\n\n资料来源：[README.md:21-22]()\n\n### LightningRail\n\n`LightningRail` enables Bitcoin sub-cent micropayments through the Lightning Network, ideal for high-frequency, low-value transactions that would be impractical on the base chain.\n\n**Supported:** BTC sub-cent micropayments  \n**Use Cases:** Microtransactions, pay-per-use API calls, tips  \n**Requirements:** LND URL and macaroon authentication\n\n**Initialization:**\n```ts\nimport { LightningRail } from \"@mnemopay/sdk\";\n\nconst lightning = new LightningRail(LND_URL, MACAROON);\n```\n\n资料来源：[README.md:23-24]()\n\n## Preview Rails (Alpha)\n\nPreview rails are available for evaluation but may have breaking changes in future releases.\n\n### StripeMPPRail\n\n`StripeMPPRail` enables crypto deposits on Tempo via Stripe's Mass Payment Program (MPP). This rail allows agents to accept cryptocurrency payments that are converted and settled through Stripe's infrastructure.\n\n**Supported:** Crypto deposits via Stripe MPP  \n**Status:** `alpha` (v1.6.0-alpha)  \n**Use Case:** Crypto-to-fiat settlement for agents\n\n```ts\nimport { StripeMPPRail } from \"@mnemopay/sdk\";\n\nconst mpp = new StripeMPPRail(process.env.STRIPE_SECRET_KEY!);\n```\n\n资料来源：[src/rails/stripe-mpp.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/rails/stripe-mpp.ts)\n\n### X402Rail\n\n`X402Rail` implements the EIP-3009 standard for USDC payments on Base. This rail enables transferWithAuthorization, a standardized way to execute payments with cryptographic authorization.\n\n**Supported:** USDC on Base via EIP-3009  \n**Status:** `alpha` (v1.6.0-alpha)  \n**Use Case:** On-chain USDC payments with standardized authorization\n\n```ts\nimport { X402Rail } from \"@mnemopay/sdk\";\nimport { YourEip3009Signer } from \"./your-signer\";\n\nconst x402 = new X402Rail({ signer: yourEip3009Signer });\n```\n\n**Requirements:** Bring-your-own EIP-3009 signer implementation\n\n资料来源：[src/rails/x402.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/rails/x402.ts)\n\n### GoogleAP2Rail\n\n`GoogleAP2Rail` implements the FIDO Alliance's AP2 v0.2 mandate-driven settlement specification. This rail uses mandate-based authorization flows for payment authorization.\n\n**Supported:** AP2 v0.2 mandate-driven settlement  \n**Standard:** FIDO Alliance  \n**Status:** `alpha` (v1.6.0-alpha)  \n**Use Case:** FIDO-aligned payment authorization\n\n```ts\nimport { GoogleAP2Rail } from \"@mnemopay/sdk\";\n\nconst ap2 = new GoogleAP2Rail({ mandate, endpoint, signer });\n```\n\n资料来源：[src/rails/google-ap2.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/rails/google-ap2.ts)\n\n## Common Payment Operations\n\nAll payment rails support the same core operations for payment lifecycle management:\n\n| Operation | Description |\n|---|---|\n| **Charge** | Initiate a payment from the customer's payment method |\n| **Escrow** | Hold funds in a secure state pending verification or delivery |\n| **Settle** | Release escrowed funds to the merchant/recipient |\n| **Refund** | Return funds to the customer |\n\nThe double-entry ledger system ensures every financial operation is recorded with corresponding debit and credit entries, maintaining balanced books with zero penny drift. 资料来源：[site/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)\n\n## Environment Configuration\n\n### Real Payment Rails\n\nFor production deployments using real payment providers:\n\n| Environment Variable | Purpose |\n|---|---|\n| `STRIPE_SECRET_KEY` | Stripe payments API key |\n| `PAYSTACK_SECRET_KEY` | Paystack payments API key |\n| `MNEMOPAY_PAYMENT_RAIL` | Active rail: `stripe`, `paystack`, or `mock` |\n| `MNEMOPAY_COMMERCE_PROVIDER` | Commerce provider: `firecrawl`, `shopify`, or `mock` |\n\n资料来源：[claude-plugin/README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/claude-plugin/README.md)\n\n### Mock/Sandbox Mode\n\nFor development and testing, the SDK defaults to mock/sandbox mode. Set `MNEMOPAY_PAYMENT_RAIL=mock` to use simulated payment operations without real money movement.\n\n## Quick Setup\n\n```ts\nimport {\n  PaystackRail, StripeRail, LightningRail,    // stable\n  StripeMPPRail, X402Rail, GoogleAP2Rail,     // alpha\n} from \"@mnemopay/sdk\";\n\n// Stable rails\nconst paystack  = new PaystackRail(process.env.PAYSTACK_SECRET_KEY!);\nconst stripe    = new StripeRail(process.env.STRIPE_SECRET_KEY!);\nconst lightning = new LightningRail(LND_URL, MACAROON);\n\n// Alpha rails (v1.6.0-alpha)\nconst mpp   = new StripeMPPRail(process.env.STRIPE_SECRET_KEY!);\nconst x402  = new X402Rail({ signer: yourEip3009Signer });\nconst ap2   = new GoogleAP2Rail({ mandate, endpoint, signer });\n\n// Quick agent initialization\nconst agent = MnemoPay.quick(\"my-agent\", {\n  rail: stripe,  // Use any configured rail\n  // ... other config\n});\n```\n\n资料来源：[README.md:26-40]()\n\n## Architecture Benefits\n\n| Benefit | Description |\n|---|---|\n| **Provider Abstraction** | Single API interface for multiple payment providers |\n| **Rail Switching** | Change payment providers without code modifications |\n| **Hybrid Rails** | Combine multiple rails in a single agent configuration |\n| **Consistent Error Handling** | Unified error responses across all providers |\n| **Audit Trail** | Every operation logged in the hash-chained ledger |\n\n## Choosing a Payment Rail\n\n| Scenario | Recommended Rail |\n|---|---|\n| Global card payments | `StripeRail` |\n| African markets (NGN, GHS, ZAR, KES) | `PaystackRail` |\n| BTC micropayments | `LightningRail` |\n| Crypto deposits settlement | `StripeMPPRail` |\n| On-chain USDC payments (Base) | `X402Rail` |\n| FIDO-aligned settlement | `GoogleAP2Rail` |\n\n## Summary\n\nThe Payment Rails system provides MnemoPay agents with flexible, production-ready payment infrastructure across six different payment providers. Stable rails (Stripe, Paystack, Lightning) handle traditional payment flows, while preview rails (StripeMPP, X402, GoogleAP2) enable emerging crypto and mandate-based payment methods. All rails share a common interface, allowing seamless switching and hybrid configurations.\n\n---\n\n<a id='stripe-rail'></a>\n\n## Stripe, Paystack & Lightning Rails\n\n### 相关页面\n\n相关主题：[Payment Rails Overview](#payment-rails-overview), [Alpha Payment Rails (StripeMPP, x402, GoogleAP2)](#alpha-rails)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)\n- [CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n- [CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)\n- [CLAUDE.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CLAUDE.md)\n- [dashboard/DEPLOYMENT.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/dashboard/DEPLOYMENT.md)\n- [site/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)\n</details>\n\n# Stripe, Paystack & Lightning Rails\n\n## Overview\n\nThe payment rails system in MnemoPay SDK provides a unified abstraction layer over multiple payment providers, enabling AI agents to process transactions across different geographic regions and payment methods through a consistent API. This architecture decouples business logic from provider-specific implementations, allowing seamless switching between payment rails without code changes.\n\nThe SDK currently supports three stable payment rails: **StripeRail** (global USD, EUR, GBP), **PaystackRail** (African markets), and **LightningRail** (Bitcoin micropayments). Additionally, preview rails include **StripeMPPRail** for crypto deposits, **X402Rail** for USDC on Base, and **GoogleAP2Rail** for mandate-driven settlement.\n\n资料来源：[README.md:1-25]()\n\n## Architecture\n\n### Unified PaymentRail Interface\n\nAll payment rails implement the `PaymentRail` interface, ensuring consistent behavior across providers. This abstraction allows developers to:\n\n- Process charges with identical method signatures regardless of provider\n- Access two-phase escrow (charge → settle/refund)\n- Utilize provider-specific features when needed\n- Switch rails with minimal configuration changes\n\n```typescript\nimport { PaystackRail, StripeRail, LightningRail } from \"@mnemopay/sdk\";\n\n// All three use the same API pattern\nconst paystack  = new PaystackRail(process.env.PAYSTACK_SECRET_KEY!);\nconst stripe    = new StripeRail(process.env.STRIPE_SECRET_KEY!);\nconst lightning = new LightningRail(LND_URL, MACAROON);\n```\n\n资料来源：[README.md:28-38]()\n\n### Rail Selection Matrix\n\n| Rail | Coverage | Channel | Status | Currencies |\n|------|----------|---------|--------|------------|\n| `StripeRail` | Global | stable (`latest`) | Stable | USD, EUR, GBP, + |\n| `PaystackRail` | Africa | stable (`latest`) | Stable | NGN, GHS, ZAR, KES |\n| `LightningRail` | BTC micropayments | stable (`latest`) | Stable | BTC |\n| `StripeMPPRail` | Crypto via Tempo | preview (`alpha`) | Alpha | Crypto deposits |\n| `X402Rail` | USDC on Base | preview (`alpha`) | Alpha | USDC |\n| `GoogleAP2Rail` | AP2 v0.2 mandate | preview (`alpha`) | Alpha | Multiple |\n\n资料来源：[README.md:1-12]()\n\n## Stable Rails\n\n### StripeRail\n\nStripeRail provides global card payment processing with manual capture for true escrow functionality. It uses Stripe's PaymentIntents API and supports 135+ currencies.\n\n**Key Features:**\n- Manual capture mode for two-phase escrow (charge → settle)\n- PaymentIntents API with full payment method support\n- Webhook verification for payment events\n- Refund handling with full/partial support\n\n**Configuration:**\n```typescript\nconst stripe = new StripeRail(process.env.STRIPE_SECRET_KEY!);\nconst agent = MnemoPay.quick(\"billing-agent\", { stripe: { secretKey: process.env.STRIPE_SECRET_KEY } });\n```\n\n资料来源：[README.md:30-32](), [site/index.html:45-50]()\n\n**Webhook Endpoint:**\n```\nPOST https://dashboard.mnemopay.com/api/v1/billing/stripe/webhook\n```\n\n**Handled Events:**\n- `checkout.session.completed`\n- `customer.subscription.updated`\n- `customer.subscription.deleted`\n\n资料来源：[dashboard/DEPLOYMENT.md:22-28]()\n\n### PaystackRail\n\nPaystackRail focuses on African markets with support for Nigerian Naira (NGN), Ghanaian Cedi (GHS), South African Rand (ZAR), and Kenyan Shilling (KES). It provides comprehensive checkout, saved cards, bank transfers, and webhook verification.\n\n**Key Features:**\n- 23 Nigerian banks pre-mapped\n- HMAC-SHA512 webhook security\n- Multiple payment methods (cards, bank transfer)\n- Checkout and saved card support\n\n**Configuration:**\n```typescript\nconst paystack = new PaystackRail(process.env.PAYSTACK_SECRET_KEY!);\n```\n\n资料来源：[README.md:31](), [site/index.html:58-62]()\n\n**Environment Variables:**\n```bash\nPAYSTACK_SECRET_KEY=sk_live_...  # Required for Paystack payments\nMNEMOPAY_PAYMENT_RAIL=paystack   # Set payment rail\n```\n\n资料来源：[claude-plugin/README.md:8-10]()\n\n### LightningRail\n\nLightningRail enables sub-cent Bitcoin micropayments through the Lightning Network. It connects to LND (Lightning Network Daemon) for instant, low-fee transactions.\n\n**Key Features:**\n- Sub-cent micropayments\n- Instant settlement via Lightning Network\n- LND connection with macaroon authentication\n- Low fees for high-frequency microtransactions\n\n**Configuration:**\n```typescript\nconst lightning = new LightningRail(LND_URL, MACAROON);\n```\n\n资料来源：[README.md:32]()\n\n## Preview Rails (Alpha)\n\n### StripeMPPRail\n\nStripe Machine Payments Protocol (MPP) rail routes agent payments as crypto deposits on the Tempo network via Stripe's MPP-enabled PaymentIntents API.\n\n**Technical Details:**\n- API version: `2026-03-04.preview`\n- Payment method types: `[\"crypto\"]`\n- Capture method: `\"manual\"` for two-phase escrow\n- In-flight capture deduplication\n- Idempotency-key forwarding\n\n**Configuration:**\n```typescript\nconst mpp = new StripeMPPRail(process.env.STRIPE_SECRET_KEY!);\n```\n\n**Key Methods:**\n- `fromClient(client, opts?)` — for tests and shared Stripe client patterns\n\n资料来源：[CHANGELOG.md:20-45]()\n\n### X402Rail\n\nThe x402 protocol implements HTTP 402 revival for USDC payments on Base L2 via EIP-3009 `transferWithAuthorization`. Agents sign transactions off-chain, and a facilitator submits to chain on capture.\n\n**Key Features:**\n- Pluggable `X402Signer` interface\n- Zero crypto dependencies in SDK\n- EIP-3009 `transferWithAuthorization` standard\n- USDC on Base L2\n\n**Configuration:**\n```typescript\nconst x402 = new X402Rail({ signer: yourEip3009Signer });\n```\n\n资料来源：[CHANGELOG.md:46-55]()\n\n### GoogleAP2Rail\n\nGoogle Agent Payment Protocol (AP2) v0.2 provides mandate-driven settlement through the FIDO Alliance open standard.\n\n**Configuration:**\n```typescript\nconst ap2 = new GoogleAP2Rail({ mandate, endpoint, signer });\n```\n\n资料来源：[CHANGELOG.md:56-60]()\n\n## Payment Flow Architecture\n\n```mermaid\ngraph TD\n    A[Agent Request] --> B[PaymentRail Interface]\n    B --> C{Provider Selection}\n    C -->|Global| D[StripeRail]\n    C -->|Africa| E[PaystackRail]\n    C -->|BTC| F[LightningRail]\n    D --> G[Charge with Escrow]\n    E --> G\n    F --> G\n    G --> H[Manual Capture]\n    H --> I[await settle()]\n    H --> J[await refund()]\n    I --> K[Funds Released]\n    J --> L[Funds Returned]\n```\n\n## Two-Phase Escrow Model\n\nAll payment rails implement a two-phase commit pattern:\n\n1. **Charge Phase** — Funds are authorized and held in escrow\n2. **Settlement Phase** — Funds are captured and transferred\n3. **Refund Phase** — Funds are returned to the customer\n\n```typescript\nconst tx = await agent.charge(49.00, \"Pro plan, monthly\");\n// Escrow holds funds until you approve\nawait agent.settle(tx.id);\n// Money moves. Ledger balanced. Credit score updated.\n```\n\n资料来源：[site/index.html:45-50]()\n\n## Double-Entry Ledger\n\nEvery financial operation in the payment rails is recorded in a double-entry ledger system, ensuring complete audit trails and preventing discrepancies.\n\n```typescript\n// Ledger maintains balance integrity across all rails\n// SHA-256 hash-chained for tamper evidence\n```\n\n资料来源：[site/index.html:15-17](), [CLAUDE.md:8]()\n\n## Environment Configuration\n\n| Variable | Rail | Description |\n|----------|------|-------------|\n| `STRIPE_SECRET_KEY` | Stripe, StripeMPP | Stripe API key |\n| `PAYSTACK_SECRET_KEY` | Paystack | Paystack API key |\n| `MNEMOPAY_PAYMENT_RAIL` | All | `stripe`, `paystack`, or `mock` |\n| `MNEMOPAY_COMMERCE_PROVIDER` | Shopping | `firecrawl`, `shopify`, or `mock` |\n\n资料来源：[claude-plugin/README.md:8-10]()\n\n## Integration Examples\n\n### Production Setup\n\n```typescript\nimport MnemoPay from \"@mnemopay/sdk\";\n\n// Production configuration with full features\nconst agent = await MnemoPay.create({\n  agentId: \"my-agent\",\n  storage: sqliteAdapter,\n  rail: stripeRail\n});\n\n// Charge with automatic escrow\nconst tx = await agent.charge(49.00, \"Pro plan, monthly\");\nawait agent.settle(tx.id);\n```\n\n### Quick Start (Dev Mode)\n\n```typescript\n// Dev mode - zero infrastructure required\nconst agent = MnemoPay.quick(\"my-agent\");\n\n// All features work, defaults to mock/sandbox\n// Swap to real rail with configuration\n```\n\n资料来源：[CLAUDE.md:20-35]()\n\n## CLI Commands\n\nThe Claude plugin provides payment management commands:\n\n| Command | Description |\n|---------|-------------|\n| `/mnemopay:charge <amount> <description>` | Charge specified amount |\n| `/mnemopay:balance` | Check account balance |\n| `/mnemopay:history <period>` | View transaction history |\n| `/mnemopay:settle` | Settle pending transactions |\n| `/mnemopay:fico` | View agent credit score |\n| `/mnemopay:remember <pref>` | Store payment preferences |\n| `/mnemopay:recall` | Retrieve payment preferences |\n\n资料来源：[claude-plugin/README.md:18-26]()\n\n## Testing\n\nThe payment rails have comprehensive test coverage:\n\n- StripeRail tests: Payment flows, webhooks, refunds\n- PaystackRail tests: Checkout, bank transfers, webhook verification\n- LightningRail tests: Invoice creation, payment forwarding\n- StripeMPPRail tests: 20 dedicated tests for MPP flow\n\n资料来源：[CHANGELOG.md:31-32](), [CHANGELOG.md:29]()\n\n## See Also\n\n- [Agent Credit Score](agent-credit-score) — Agent trust scoring (300-850)\n- [Double-Entry Ledger](ledger) — Financial transaction tracking\n- [Shopping Module](shopping) — Autonomous product discovery and purchase\n- [MCP Server](mcp-server) — 24 tools for agent payment operations\n\n---\n\n<a id='alpha-rails'></a>\n\n## Alpha Payment Rails (StripeMPP, x402, GoogleAP2)\n\n### 相关页面\n\n相关主题：[Payment Rails Overview](#payment-rails-overview), [Stripe, Paystack & Lightning Rails](#stripe-rail)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/rails/stripe-mpp.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/rails/stripe-mpp.ts)\n- [src/rails/x402.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/rails/x402.ts)\n- [src/rails/google-ap2.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/rails/google-ap2.ts)\n- [src/client.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/client.ts)\n</details>\n\n# Alpha Payment Rails (StripeMPP, x402, GoogleAP2)\n\n## Overview\n\nAlpha Payment Rails are experimental payment rail implementations introduced in MnemoPay SDK v1.6.0-alpha as part of the v1.6.x rail sprint. These rails provide alternative payment methods beyond the stable payment rails (Stripe, Paystack, Lightning) and enable crypto-native payment flows for AI agents.\n\n| Rail | Technology | Status | Channel |\n|------|-----------|--------|---------|\n| `StripeMPPRail` | Crypto deposits on Tempo via Stripe MPP | alpha | `npm install @mnemopay/sdk@alpha` |\n| `X402Rail` | USDC on Base via EIP-3009 transferWithAuthorization | alpha | `npm install @mnemopay/sdk@alpha` |\n| `GoogleAP2Rail` | AP2 v0.2 mandate-driven settlement (FIDO Alliance) | alpha | `npm install @mnemopay/sdk@alpha` |\n\n资料来源：[README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)\n\n## StripeMPPRail\n\nStripeMPPRail implements the Stripe Machine Payments Protocol (MPP), enabling agents to route payments as crypto deposits on the Tempo network through Stripe's MPP-enabled PaymentIntents API.\n\n### Key Features\n\n- **Crypto Payment Method**: Uses `payment_method_types: [\"crypto\"]` with `crypto.deposit_options.networks`\n- **Two-Phase Escrow**: Implements `capture_method: \"manual\"` for true escrow semantics\n- **Deduplication**: In-flight capture deduplication prevents double-settlement\n- **Idempotency**: Full idempotency-key forwarding for safe retries\n- **Drop-in Swap**: Same `PaymentRail` interface as `StripeRail` 资料来源：[CHANGELOG.md:19-36](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n\n### API Configuration\n\n```typescript\nimport { StripeMPPRail } from \"@mnemopay/sdk\";\n\n// Alpha preview (v1.6.0-alpha)\nconst mpp = new StripeMPPRail(process.env.STRIPE_SECRET_KEY!);\n```\n\n### Implementation Details\n\n- Pinned to Stripe API version: `2026-03-04.preview`\n- Tagged with `@experimental` decorator — preview API can change without semver guarantees\n- 20 dedicated tests in the test suite\n- Includes `fromClient(client, opts?)` factory for tests and shared Stripe client patterns\n\n资料来源：[CHANGELOG.md:20-35](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n\n## X402Rail\n\nX402Rail implements the EIP-3009 `transferWithAuthorization` standard, enabling USDC payments on Base network with off-chain authorization and on-chain settlement.\n\n### Features\n\n- **EIP-3009 Compliance**: Uses `transferWithAuthorization` for delegated transfers\n- **USDC Native**: Direct USDC transfers on Base L2\n- **Bring Your Own Signer**: Requires user-provided EIP-3009 signer implementation\n\n### Configuration\n\n```typescript\nimport { X402Rail } from \"@mnemopay/sdk\";\n\nconst x402 = new X402Rail({ signer: yourEip3009Signer });\n```\n\n资料来源：[README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)\n\n## GoogleAP2Rail\n\nGoogleAP2Rail implements the FIDO Alliance's AP2 (Authorizing Payment 2.0) v0.2 specification, providing mandate-driven settlement with FIDO-based authentication.\n\n### Features\n\n- **AP2 v0.2**: Implements FIDO Alliance payment authentication standard\n- **Mandate-Driven**: Settlement occurs based on pre-authorized mandates\n- **FIDO Integration**: Leverages FIDO authentication for payment authorization\n\n### Configuration\n\n```typescript\nimport { GoogleAP2Rail } from \"@mnemopay/sdk\";\n\nconst ap2 = new GoogleAP2Rail({ mandate, endpoint, signer });\n```\n\n资料来源：[README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[MnemoPay Agent] --> B[PaymentRail Interface]\n    B --> C[Stable Rails]\n    B --> D[Alpha Rails]\n    \n    C --> C1[StripeRail]\n    C --> C2[PaystackRail]\n    C --> C3[LightningRail]\n    \n    D --> D1[StripeMPPRail]\n    D --> D2[X402Rail]\n    D --> D3[GoogleAP2Rail]\n    \n    D1 --> D1A[Stripe MPP API<br/>2026-03-04.preview]\n    D1A --> D1B[Tempo Network<br/>Crypto Deposits]\n    \n    D2 --> D2A[EIP-3009<br/>transferWithAuthorization]\n    D2A --> D2B[Base Network<br/>USDC]\n    \n    D3 --> D3A[AP2 v0.2<br/>FIDO Alliance]\n    D3A --> D3B[Mandate-Driven<br/>Settlement]\n```\n\n## Payment Rail Comparison\n\n| Feature | StripeRail | StripeMPPRail | X402Rail | GoogleAP2Rail |\n|---------|------------|---------------|----------|---------------|\n| Currency | USD, EUR, GBP | Crypto (Tempo) | USDC | Multi-currency |\n| Network | Stripe | Tempo | Base L2 | FIDO Network |\n| Escrow | Manual capture | Manual capture | Authorization-based | Mandate-based |\n| Auth Method | Stripe Auth | Stripe MPP | EIP-3009 Signer | FIDO Auth |\n| Status | Stable | Alpha | Alpha | Alpha |\n| API Version | Latest | 2026-03-04.preview | N/A | v0.2 |\n\n## Installation\n\nAlpha rails are available under the `alpha` npm dist-tag:\n\n```bash\nnpm install @mnemopay/sdk@alpha\n```\n\nThe default `latest` dist-tag still points at `1.5.0` (stable). Opt in to alpha with the above command.\n\n资料来源：[CHANGELOG.md:6-14](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n\n## Usage Example\n\n```typescript\nimport {\n  PaystackRail, StripeRail, LightningRail,    // stable\n  StripeMPPRail, X402Rail, GoogleAP2Rail,      // alpha\n} from \"@mnemopay/sdk\";\n\n// Stable rails\nconst paystack  = new PaystackRail(process.env.PAYSTACK_SECRET_KEY!);\nconst stripe    = new StripeRail(process.env.STRIPE_SECRET_KEY!);\nconst lightning = new LightningRail(LND_URL, MACAROON);\n\n// Alpha preview rails\nconst mpp   = new StripeMPPRail(process.env.STRIPE_SECRET_KEY!);\nconst x402  = new X402Rail({ signer: yourEip3009Signer });   // bring-your-own crypto\nconst ap2   = new GoogleAP2Rail({ mandate, endpoint, signer });\n```\n\n资料来源：[README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)\n\n## Road to v1.6.0\n\nThe full `1.6.0` minor release will ship when the v1.6.x rail sprint completes, including:\n\n- Stripe MPP native integration\n- x402 native integration\n- Google AP2 native integration\n- Python rail port\n\n资料来源：[CHANGELOG.md:14-17](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n\n## Important Notes\n\n### Experimental Status\n\nAlpha rails are tagged `@experimental` and subject to API changes:\n\n> \"preview API can change without semver guarantees from Stripe; pin `apiVersion` in production\"\n\nFor production deployments of StripeMPPRail, it is recommended to pin the `apiVersion` to prevent unexpected breaking changes.\n\n资料来源：[CHANGELOG.md:34-35](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n\n### Future Stable Release\n\nWhen the v1.6.0 stable release ships, the `latest` npm tag will be updated to point to the version containing these rails as stable implementations.\n\n---\n\n<a id='charter-fiscalgate'></a>\n\n## Charter & FiscalGate Governance\n\n### 相关页面\n\n相关主题：[MerkleAudit & Hash-Chained Ledger](#merkle-audit), [Identity & KYA Compliance](#identity-kya), [System Architecture](#architecture)\n\n<details>\n<summary>Related Source Files</summary>\n\nThe following source files were used to generate this documentation:\n\n- [src/governance/charter.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/governance/charter.ts)\n- [src/governance/payments.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/governance/payments.ts)\n- [src/governance/article12.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/governance/article12.ts)\n- [src/governance/policies/eu-ai-act.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/governance/policies/eu-ai-act.ts)\n</details>\n\n# Charter & FiscalGate Governance\n\n## Overview\n\nThe **Charter & FiscalGate Governance** module is a first-class system within the MnemoPay SDK that provides budget enforcement, mission scoping, and regulatory audit capabilities for AI agents that handle financial operations. This governance layer ensures agents operate within defined constraints while maintaining transparent, verifiable audit trails.\n\n```\n┌──────────────────────────────────────────────────────────────────┐\n│                    GOVERNANCE LAYER                              │\n├──────────────────────────────────────────────────────────────────┤\n│  Charter · FiscalGate · Article 12 · MerkleAudit               │\n│  mission scope, budget enforcement, audit bundles                │\n└──────────────────────────────────────────────────────────────────┘\n```\n\n资料来源：[README.md]()\n\n## Purpose & Scope\n\nThe governance module addresses critical requirements for production AI agent deployments:\n\n1. **Mission Scope Declaration** — Defines what tools and operations an agent is authorized to perform\n2. **Budget Enforcement** — Reserves and limits financial resources before mission execution\n3. **Audit Trail** — Generates tamper-evident logs and regulator-ready documentation\n4. **Compliance** — Aligns with EU AI Act Article 12 requirements for high-risk AI systems\n\n资料来源：[CHANGELOG.md]()\n\n## Architecture\n\n### System Components\n\n```mermaid\ngraph TD\n    A[MnemoPay SDK] --> B[Governance Module]\n    B --> C[Charter]\n    B --> D[FiscalGate]\n    B --> E[MerkleAudit]\n    B --> F[Article12Bundle]\n    B --> G[PaymentsAdapter]\n    \n    C --> H[Mission Declaration]\n    C --> I[Allowed Tools]\n    C --> J[Budget Cap]\n    \n    D --> K[Budget Reservation]\n    D --> L[Agent Loop Execution]\n    D --> M[Spend Settlement]\n    \n    E --> N[SHA-256 Chain]\n    E --> O[Event Replay]\n    E --> P[Tamper Detection]\n    \n    F --> Q[mission.json]\n    F --> R[events.json]\n    F --> S[events.csv]\n    F --> T[chain.txt]\n    F --> U[manifest.json]\n```\n\n资料来源：[CHANGELOG.md]()\n\n### Data Flow\n\n```mermaid\nsequenceDiagram\n    participant A as Agent\n    participant C as Charter\n    participant F as FiscalGate\n    participant M as MerkleAudit\n    participant P as Payments\n    participant R as Regulator\n\n    A->>C: Submit mission declaration\n    C->>C: validateCharter()\n    C-->>F: Validated charter\n    \n    F->>M: Initialize audit chain\n    F->>P: Reserve budget (charter.budgetCap)\n    F->>A: Begin mission execution\n    \n    loop Mission Operations\n        A->>F: Operation request\n        F->>M: Log event (sha256)\n        F->>P: Check budget remaining\n        P-->>F: Budget status\n        F-->>A: Approved/Rejected\n    end\n    \n    alt Success\n        F->>P: Settle actual spend\n        F->>M: Finalize chain\n        F->>R: buildArticle12Bundle()\n    else Halt/Error\n        F->>P: Release reserved budget\n        F->>M: Log termination event\n    end\n```\n\n## Core Components\n\n### 1. Charter\n\nThe `Charter` schema declares an agent mission's goal, authorized tools, and budget constraints.\n\n```typescript\ninterface Charter {\n  missionId: string;\n  goal: string;\n  allowedTools: string[];\n  budgetCap: number;\n  currency: string;\n  createdAt: Date;\n}\n```\n\n#### Charter Validation\n\nThe `validateCharter()` function ensures mission declarations are well-formed and within acceptable parameters:\n\n- Validates required fields are present\n- Checks budget cap is a positive value\n- Verifies allowed tools list is non-empty\n- Ensures goal description is meaningful\n\n资料来源：[src/governance/charter.ts]()\n\n### 2. FiscalGate\n\nThe `FiscalGate` primitive (`runMission()`) is the core budget enforcement mechanism.\n\n```typescript\ninterface FiscalGateResult {\n  status: \"ok\" | \"halted\" | \"error\";\n  spentUsd: number;\n  outputs: any[];\n  auditDigest: string;\n  // ... additional fields\n}\n```\n\n#### Execution Flow\n\n```mermaid\ngraph TD\n    A[runMission ctx] --> B[Reserve full budget]\n    B --> C[Execute agent loop]\n    C --> D{All operations complete?}\n    D -->|Yes| E{Spent within budget?}\n    D -->|No| F[Log operation]\n    F --> C\n    E -->|Yes| G[Settle actual spend]\n    E -->|No| H[Release excess reservation]\n    G --> I[Return ok status]\n    H --> I\n    D -->|Halt signal| J[Release budget]\n    D -->|Error| K[Release budget]\n    J --> L[Return halted status]\n    K --> M[Return error status]\n```\n\n#### Key Behaviors\n\n| Scenario | Action | Result |\n|----------|--------|--------|\n| Mission succeeds | Settle actual spend | `status: \"ok\"` |\n| Mission halts early | Release reserved budget | `status: \"halted\"` |\n| Error occurs | Release reserved budget | `status: \"error\"` |\n| Overspend attempted | Block operation | Budget preserved |\n\n资料来源：[CHANGELOG.md](), [src/governance/payments.ts]()\n\n### 3. MerkleAudit\n\nThe `MerkleAudit` system provides a SHA-256 chained event log with verification capabilities.\n\n```typescript\ninterface MerkleAudit {\n  // Core methods\n  log(event: AuditEvent): void;\n  verify(): boolean;\n  toJSON(): AuditLog;\n  \n  // Event subscription\n  on(event: string, callback: Function): void;\n  \n  // Deterministic operations\n  replay(): AuditEvent[];\n}\n```\n\n#### Chain Structure\n\n```mermaid\ngraph LR\n    E1[Event 1] --> H1[Hash 1]\n    H1 --> E2[Event 2]\n    E2 --> H2[Hash 2]\n    H2 --> E3[Event 3]\n    E3 --> H3[Hash 3]\n    \n    style H1 fill:#f96\n    style H2 fill:#f96\n    style H3 fill:#f96\n```\n\n#### Verification Methods\n\n| Method | Purpose |\n|--------|---------|\n| `verify()` | Validates chain integrity |\n| `toJSON()` | Exports audit log for storage |\n| `replay()` | Reconstructs deterministic state |\n\n资料来源：[CHANGELOG.md]()\n\n### 4. Article 12 Bundle\n\nThe `buildArticle12Bundle()` function generates regulator-handable documentation for EU AI Act compliance.\n\n```typescript\ninterface Article12Bundle {\n  charter: Charter;\n  result: FiscalGateResult;\n  audit: MerkleAudit;\n  \n  // Output files\n  mission: string;      // mission.json\n  events: string;      // events.json\n  eventsCsv: string;   // events.csv\n  chain: string;       // chain.txt\n  manifest: {\n    checksums: Record<string, string>;\n    retention: {\n      policy: string;\n      expiresAt: string;\n    };\n  };\n}\n```\n\n#### Default Retention Policy\n\n| Jurisdiction | Retention Period | Legal Basis |\n|--------------|------------------|-------------|\n| European Union | 6 months | EU AI Act Article 12 |\n| Default | 6 months | EU AI Act Article 12 |\n\n资料来源：[CHANGELOG.md](), [src/governance/article12.ts](), [src/governance/policies/eu-ai-act.ts]()\n\n### 5. PaymentsAdapter\n\nA pluggable interface for payment processing backends.\n\n```typescript\ninterface PaymentsAdapter {\n  charge(amount: number, currency: string): Promise<ChargeResult>;\n  settle(transactionId: string): Promise<SettleResult>;\n  refund(transactionId: string): Promise<RefundResult>;\n  getBalance(): Promise<Balance>;\n}\n\nclass MockPayments implements PaymentsAdapter {\n  // Reference implementation for testing\n}\n```\n\n#### Built-in Implementations\n\n| Implementation | Use Case |\n|---------------|----------|\n| `MockPayments` | Unit testing, development |\n| `StripePaymentsAdapter` | Production (global) |\n| `PaystackPaymentsAdapter` | Production (Africa) |\n| `LightningPaymentsAdapter` | Production (micropayments) |\n\n资料来源：[CHANGELOG.md](), [src/governance/payments.ts]()\n\n## API Reference\n\n### Functions\n\n#### `validateCharter(charter: Charter): ValidationResult`\n\nValidates a charter declaration before mission execution.\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `charter` | `Charter` | Mission charter to validate |\n| **Returns** | `ValidationResult` | Contains `valid: boolean` and optional `errors: string[]` |\n\n#### `runMission(ctx: MissionContext): Promise<FiscalGateResult>`\n\nExecutes an agent mission with budget enforcement.\n\n```typescript\ninterface MissionContext {\n  charter: Charter;\n  agentLoop: () => Promise<void>;\n  onOperation?: (op: Operation) => void;\n}\n\ninterface FiscalGateResult {\n  status: \"ok\" | \"halted\" | \"error\";\n  spentUsd: number;\n  outputs: any[];\n  auditDigest: string;\n  terminatedAt?: Date;\n  error?: string;\n}\n```\n\n#### `buildArticle12Bundle(params: BundleParams): Article12Bundle`\n\nGenerates a regulatory audit bundle.\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `params.charter` | `Charter` | Mission charter |\n| `params.result` | `FiscalGateResult` | Mission execution result |\n| `params.audit` | `MerkleAudit` | Audit log |\n\n#### `new MerkleAudit(options?: AuditOptions): MerkleAudit`\n\nCreates a new audit chain instance.\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `chainId` | `string` | Auto-generated | Unique chain identifier |\n| `events` | `AuditEvent[]` | `[]` | Initial events |\n| `retentionDays` | `number` | `180` | Log retention period |\n\n资料来源：[src/governance/charter.ts](), [src/governance/payments.ts](), [src/governance/article12.ts]()\n\n## EU AI Act Compliance\n\nThe governance module implements compliance measures for EU AI Act Article 12, which requires high-risk AI systems to maintain:\n\n1. **Logging of operations** — All agent actions recorded with timestamps\n2. **Traceability** — Individual operations attributable to specific events\n3. **Transparency** — Audit bundles provide human-readable documentation\n4. **Retention** — 6-month minimum log retention\n\n```typescript\n// EU AI Act Article 12 compliance configuration\nconst euCompliance = {\n  article: \"Article 12\",\n  jurisdiction: \"European Union\",\n  retentionMonths: 6,\n  requirements: [\n    \"operation_logging\",\n    \"event_traceability\", \n    \"human_oversight\",\n    \"audit_trail\"\n  ]\n};\n```\n\n资料来源：[src/governance/policies/eu-ai-act.ts]()\n\n## Testing\n\nThe governance module includes comprehensive test coverage in `tests/governance.spec.ts`:\n\n| Test Category | Coverage |\n|---------------|----------|\n| Charter validation | Valid/invalid charter scenarios |\n| MerkleAudit chain | Hash linking, tamper detection |\n| FiscalGate paths | Happy path, halt, error scenarios |\n| Article 12 bundle | File generation, checksum validation |\n\n资料来源：[CHANGELOG.md]()\n\n## Usage Example\n\n```typescript\nimport { \n  Charter, \n  validateCharter, \n  runMission, \n  MerkleAudit, \n  buildArticle12Bundle,\n  MockPayments \n} from \"@mnemopay/sdk/governance\";\n\n// 1. Declare mission charter\nconst charter: Charter = {\n  missionId: \"procurement-001\",\n  goal: \"Purchase office supplies under $500\",\n  allowedTools: [\"search\", \"compare\", \"buy\"],\n  budgetCap: 500,\n  currency: \"USD\",\n  createdAt: new Date()\n};\n\n// 2. Validate charter\nconst validation = validateCharter(charter);\nif (!validation.valid) {\n  throw new Error(`Invalid charter: ${validation.errors.join(\", \")}`);\n}\n\n// 3. Create audit trail\nconst audit = new MerkleAudit({ retentionDays: 180 });\n\n// 4. Execute mission with budget enforcement\nconst result = await runMission({\n  charter,\n  agentLoop: async () => {\n    // Agent operations here\n  }\n});\n\n// 5. Generate regulatory bundle\nconst bundle = buildArticle12Bundle({\n  charter,\n  result,\n  audit\n});\n```\n\n## Summary\n\nThe Charter & FiscalGate Governance system provides:\n\n- **Declarative mission scoping** via Charter documents\n- **Automatic budget enforcement** through FiscalGate\n- **Tamper-evident logging** via MerkleAudit chains\n- **Regulatory compliance** with EU AI Act Article 12 bundles\n- **Pluggable payments** via PaymentsAdapter interface\n\nThis governance infrastructure ensures AI agents operate responsibly within financial constraints while maintaining the audit trails required for regulatory compliance and operational transparency.\n\n---\n\n<a id='merkle-audit'></a>\n\n## MerkleAudit & Hash-Chained Ledger\n\n### 相关页面\n\n相关主题：[Charter & FiscalGate Governance](#charter-fiscalgate), [Core Modules Reference](#core-modules)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/governance/audit-chain.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/governance/audit-chain.ts)\n- [src/governance/audit.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/governance/audit.ts)\n- [src/integrity.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/integrity.ts)\n- [src/ledger.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/src/ledger.ts)\n- [tests/governance.spec.ts](https://github.com/mnemopay/mnemopay-sdk/blob/main/tests/governance.spec.ts)\n</details>\n\n# MerkleAudit & Hash-Chained Ledger\n\n## Overview\n\nMerkleAudit and Hash-Chained Ledger form the cryptographic integrity backbone of the MnemoPay SDK. These two systems work together to provide verifiable, tamper-evident event logging and transaction recording for AI agents operating in financial workflows.\n\n**Purpose:** The system ensures that every event and ledger entry can be independently verified, that modifications to historical data are immediately detectable, and that audit trails meet regulatory requirements such as EU AI Act Article 12.\n\n**Key Characteristics:**\n- SHA-256 cryptographic chaining for sequential integrity\n- Merkle tree verification for memory integrity\n- Deterministic replay for audit verification\n- Listener subscriptions for real-time monitoring\n- Three independent tamper-detection layers\n\n资料来源：[CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n\n## Architecture\n\nThe integrity system consists of three independent layers working in concert:\n\n```mermaid\ngraph TD\n    A[Tamper Detection Layers] --> B[Hash-Chained Ledger]\n    A --> C[Merkle Integrity on Memories]\n    A --> D[HMAC on Transactions]\n    \n    B --> E[SHA-256 Sequential Linking]\n    C --> F[Merkle Tree Verification]\n    D --> G[HMAC-SHA512 Security]\n```\n\n### Layer 1: Hash-Chained Ledger\n\nThe ledger maintains a double-entry accounting system where every entry links to the previous entry via SHA-256 hash. If any entry is modified, the chain breaks instantly, making tampering immediately detectable.\n\n资料来源：[site/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)\n\n### Layer 2: Merkle Integrity on Memories\n\nThe MerkleAudit system provides Merkle tree-based verification for agent memories, ensuring that stored memory states can be cryptographically verified.\n\n### Layer 3: HMAC on Transactions\n\nTransaction-level HMAC-SHA512 security provides an additional verification layer for financial operations.\n\n## MerkleAudit System\n\n### Core Components\n\n| Component | Purpose |\n|-----------|---------|\n| `audit-chain.ts` | SHA-256 chained event log implementation |\n| `audit.ts` | Core audit primitives and verification |\n| `verify()` | Chain integrity verification method |\n| `toJSON()` | Serialization for audit export |\n| Listeners | Real-time event subscription system |\n| Deterministic Replay | Reproducible audit reconstruction |\n\n资料来源：[CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n\n### Event Log Structure\n\nThe MerkleAudit system maintains a sequentially chained event log where each event contains:\n\n```mermaid\ngraph LR\n    A[Event N] --> B[SHA-256 Hash of Event N]\n    B --> C[Links to Event N-1 Hash]\n    C --> D[Event N-1]\n    D --> E[SHA-256 Hash of Event N-1]\n    E --> F[Links to Event N-2 Hash]\n```\n\n### Verification Process\n\nThe `verify()` method performs chain integrity checks by:\n\n1. Computing the hash of each event in sequence\n2. Comparing computed hashes against stored hashes\n3. Validating chain link integrity between consecutive events\n4. Reporting any detected breaks or inconsistencies\n\n### Listener Subscriptions\n\nThe system supports listener subscriptions for real-time monitoring:\n\n- Events can trigger registered callbacks as they are appended\n- Listeners receive the full event context upon notification\n- Supports multiple concurrent subscribers\n\n### Deterministic Replay\n\nThe deterministic replay feature enables:\n\n- Complete reconstruction of audit state from the chain\n- Reproducible verification of past states\n- Compliance with regulatory audit requirements\n\n## Hash-Chained Ledger\n\n### Double-Entry Accounting\n\nThe ledger implements true double-entry bookkeeping where every transaction affects at least two accounts:\n\n```mermaid\ngraph TD\n    A[Transaction] --> B[Debit Entry]\n    A --> C[Credit Entry]\n    B --> D[Account A Balance]\n    C --> E[Account B Balance]\n    D --> F[Ledger Balanced ✓]\n    E --> F\n```\n\n### Chain Integrity Mechanism\n\n| Feature | Description |\n|---------|-------------|\n| Hash Algorithm | SHA-256 |\n| Chain Structure | Each entry references previous entry's hash |\n| Detection | Any modification breaks the chain instantly |\n| Verification | Sequential hash recomputation and comparison |\n\n资料来源：[site/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)\n\n### Transaction Flow\n\n```mermaid\nsequenceDiagram\n    participant Agent\n    participant Ledger\n    participant Escrow\n    participant Verification\n    \n    Agent->>Ledger: Initiate Transaction\n    Ledger->>Verification: Compute Previous Hash\n    Verification->>Ledger: Hash Verified\n    Ledger->>Ledger: Append with Chain Link\n    Ledger->>Escrow: Hold Funds\n    Escrow->>Agent: Escrow Confirmed\n```\n\n## API Reference\n\n### MerkleAudit Core Methods\n\n#### `verify()`\n\nVerifies the complete chain integrity.\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `startIndex` | `number` | Optional starting point for verification |\n| `endIndex` | `number` | Optional ending point for verification |\n\n#### `toJSON()`\n\nSerializes the audit chain to JSON format for export and storage.\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `compact` | `boolean` | Optional compact representation |\n\n### Ledger Methods\n\n#### Transaction Operations\n\n| Method | Purpose |\n|--------|---------|\n| `charge()` | Initiate a charge with escrow hold |\n| `settle()` | Release escrowed funds |\n| `refund()` | Process a refund transaction |\n| `dispute()` | Open a dispute on a transaction |\n\n资料来源：[site/index.legacy.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.legacy.html)\n\n## Test Coverage\n\nThe governance module includes comprehensive test coverage:\n\n- **11 governance tests** in `tests/governance.spec.ts`\n- Charter validation tests\n- MerkleAudit chain and tamper detection tests\n- FiscalGate happy path, halt, and error path tests\n- Article 12 bundle generation tests\n\n资料来源：[CHANGELOG.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/CHANGELOG.md)\n\n### Test Categories\n\n| Category | Coverage |\n|----------|----------|\n| Chain Integrity | Verification of unbroken hash chain |\n| Tamper Detection | Detection of modified entries |\n| Replay Accuracy | Deterministic replay verification |\n| Listener Events | Real-time notification testing |\n\n## Integration with Governance Module\n\nMerkleAudit integrates deeply with the Governance module:\n\n### Article 12 Compliance\n\nThe system supports EU AI Act Article 12 audit requirements:\n\n- **6-month default retention** period\n- **Deterministic SHA-256 digest** for tamper detection\n- **Compliance bundle generation** via `buildArticle12Bundle()`\n\n### Audit Bundle Structure\n\nWhen generating Article 12 compliance bundles:\n\n```mermaid\ngraph TD\n    A[buildArticle12Bundle] --> B[mission.json]\n    A --> C[events.json]\n    A --> C2[events.csv]\n    A --> D[chain.txt]\n    A --> E[manifest.json]\n    \n    E --> F[Checksums]\n    E --> G[Retention Metadata]\n```\n\n### FiscalGate Integration\n\nThe `runMission(ctx)` function uses the audit chain for mission execution:\n\n1. Reserves full charter budget up-front\n2. Runs the agent loop with ledger recording\n3. Settles actual spend on success\n4. Releases reserved funds on halt/error\n5. Returns audit digest for verification\n\n## Security Properties\n\n### Tamper Detection\n\n| Attack Vector | Detection Mechanism |\n|---------------|---------------------|\n| Single Entry Modification | SHA-256 hash mismatch |\n| Chain Reordering | Sequential link validation |\n| Entry Deletion | Hash chain break detection |\n| Memory Manipulation | Merkle tree verification |\n\n### Cryptographic Guarantees\n\n- **Pre-image Resistance**: Cannot derive previous entries from current hash\n- **Collision Resistance**: Cannot find two events with same hash\n- **Chain Binding**: Each entry cryptographically bound to all predecessors\n\n## Best Practices\n\n### Audit Trail Maintenance\n\n1. **Regular Verification**: Periodically run `verify()` on the audit chain\n2. **Backup Chain State**: Export via `toJSON()` for disaster recovery\n3. **Monitor Listeners**: Implement listeners to track chain modifications\n4. **Retention Compliance**: Configure appropriate retention periods for regulatory needs\n\n### Ledger Operations\n\n1. **Always Verify Before Settlement**: Check chain integrity before fund release\n2. **Use Escrow**: Hold funds until human approval for autonomous transactions\n3. **Monitor Disputes**: Track dispute patterns for fraud detection\n4. **Maintain Credit Score**: Higher scores yield lower transaction fees\n\n## Conclusion\n\nMerkleAudit and the Hash-Chained Ledger provide the cryptographic foundation for trustworthy AI agent financial operations. With SHA-256 chaining, Merkle tree verification, and HMAC transaction security, the system ensures that every event and transaction is verifiable, tamper-evident, and compliant with regulatory requirements.\n\n资料来源：[site/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/site/index.html)\n\n---\n\n<a id='identity-kya'></a>\n\n## Identity & KYA Compliance\n\n### 相关页面\n\n相关主题：[Charter & FiscalGate Governance](#charter-fiscalgate)\n\n<details>\n<summary>Relevant Source Files</summary>\n\nThe following source files were retrieved and used to generate this documentation:\n\n- [dashboard/index.html](https://github.com/mnemopay/mnemopay-sdk/blob/main/dashboard/index.html)\n- [README.md](https://github.com/mnemopay/mnemopay-sdk/blob/main/README.md)\n\nNote: The identity module source files (`src/identity/index.ts`, `src/identity/wallet.ts`, `src/identity/bundle.ts`, `src/identity/did.ts`) referenced in the task were not available in the retrieved repository context. This documentation is based on the architectural references and dashboard implementation found in the available context.\n</details>\n\n# Identity & KYA Compliance\n\n## Overview\n\nIdentity & KYA (Know Your Agent) Compliance is a core pillar of the MnemoPay SDK architecture, providing identity management, permission controls, and compliance verification for AI agents that handle financial transactions.\n\nThe Identity subsystem enables autonomous agents to establish verified digital identities, manage session authentication, control access permissions, and maintain compliance with regulatory requirements through a multi-layered approach.\n\n资料来源：[README.md:1-50]()\n\n## Architecture\n\n```mermaid\ngraph TD\n    subgraph Identity & KYA Compliance\n        DID[Decentralized ID]\n        SES[Session Management]\n        PERM[Permissions]\n        KILL[Killswitch]\n        TOKEN[Token Economy]\n        BRAIN[Memory Brain]\n    end\n    \n    subgraph Agent Operations\n        CHARGE[charge()]\n        SETTLE[settle()]\n        REFUND[refund()]\n    end\n    \n    DID --> SES\n    SES --> PERM\n    PERM --> KILL\n    SES --> TOKEN\n    DID --> BRAIN\n    \n    PERM --> CHARGE\n    PERM --> SETTLE\n    PERM --> REFUND\n```\n\n## Core Components\n\n### Session Management\n\nThe Session Panel provides authenticated session handling for agent identities. It integrates with the dashboard's operator console to manage sign-in and sign-out operations for agent accounts.\n\n| Component | Description |\n|-----------|-------------|\n| `session.session?.accountId` | Unique account identifier for the authenticated agent |\n| `session.session?.email` | Associated email for the session |\n| `session.authenticated` | Boolean flag indicating authentication status |\n| `onLogin` | Callback function for session authentication |\n| `onLogout` | Callback function for session termination |\n\n资料来源：[dashboard/index.html:200-230]()\n\n#### Session State Display\n\nThe dashboard conditionally renders session status based on authentication state:\n\n```tsx\n{session?.authenticated ? (\n  <div className=\"text-right\">\n    <div className=\"text-xs text-gray-500 uppercase tracking-wider\">Signed in as</div>\n    <div className=\"text-sm font-mono text-white\">{sanitize(session.session?.email || '—')}</div>\n    <div className=\"text-[10px] text-gray-500 font-mono\">account: {sanitize(session.session?.accountId || accountId)}</div>\n  </div>\n) : (\n  <div className=\"text-right\">\n    <div className=\"text-xs text-amber-400 uppercase tracking-wider\">Not signed in</div>\n    <div className=\"text-[10px] text-gray-500 font-mono\">account: {sanitize(accountId)} (anonymous)</div>\n  </div>\n)}\n```\n\n资料来源：[dashboard/index.html:150-170]()\n\n### Permission Controls\n\nThe permission system gates critical financial operations. Agents must have appropriate permissions before executing `charge()`, `settle()`, or `refund()` operations.\n\n| Permission Type | Purpose |\n|-----------------|---------|\n| Charge Permission | Allows agent to initiate payment collection |\n| Settle Permission | Allows agent to release escrowed funds |\n| Refund Permission | Allows agent to process refunds |\n| Admin Permission | Allows management of API keys and billing |\n\n### Killswitch\n\nThe killswitch mechanism provides emergency shutdown capability for agent operations. When triggered, it immediately revokes all active permissions and halts pending transactions.\n\n```mermaid\ngraph LR\n    A[Anomaly Detected] --> B{Killswitch Active?}\n    B -->|Yes| C[Revoke All Permissions]\n    B -->|No| D[Log Warning]\n    C --> E[Cancel Pending Transactions]\n    E --> F[Notify Compliance System]\n```\n\n### Token Economy\n\nThe Identity module integrates with MnemoPay's token-based economy:\n\n| Parameter | Value | Description |\n|-----------|-------|-------------|\n| Ceiling | `500 × reputation` | Maximum charge per transaction |\n| Decay | 0.05 | Half-life approximately 14 hours |\n| Feedback Loop | +0.05 | Importance reinforcement on settle |\n\n资料来源：[dashboard/index.html:350-360]()\n\n## Compliance Workflow\n\n```mermaid\ngraph TD\n    A[Agent Initialization] --> B[Create Session]\n    B --> C{KYA Verification}\n    C -->|Pass| D[Assign Permissions]\n    C -->|Fail| E[Restricted Mode]\n    D --> F[Enable Financial Ops]\n    E --> G[Monitor & Retry]\n    G --> C\n    F --> H[Log to Audit Trail]\n    H --> I[Periodic Compliance Check]\n    I -->|Compliant| F\n    I -->|Violation| J[Killswitch Triggered]\n```\n\n## Dashboard Integration\n\nThe Identity & KYA Compliance features are accessible through the MnemoPay Console dashboard via the Session tab:\n\n```tsx\n{tab === 'session' && <SessionPanel \n  session={session} \n  accountId={accountId} \n  members={overview?.members || []} \n  onLogin={loginSession} \n  onLogout={logoutSession} \n  onRefresh={fetchAll} \n/>}\n```\n\n资料来源：[dashboard/index.html:400-410]()\n\n### Available Controls\n\n| Control | Function |\n|---------|----------|\n| Account ID Input | Specify target account for session operations |\n| Refresh Button | Fetch latest session and compliance status |\n| Login | Authenticate and establish session |\n| Logout | Terminate session and clear credentials |\n| Members List | View team members with identity status |\n\n## Developer API Keys\n\nThe Developer Panel manages API keys that authenticate agent-to-platform communications:\n\n| Feature | Description |\n|---------|-------------|\n| List Keys | View all active API keys for the account |\n| Create Key | Generate new provisioning secret |\n| Revoke Key | Immediately invalidate an existing key |\n\n资料来源：[dashboard/index.html:280-310]()\n\n## Security Considerations\n\n### Authentication Flow\n\n1. Agent requests session with valid credentials\n2. System verifies KYA compliance status\n3. On success, session token is issued with scoped permissions\n4. All subsequent API calls include session token\n5. Session expires after configured TTL or manual logout\n\n### Anomaly Detection\n\nThe compliance system monitors agent behavior patterns:\n\n- Unusual transaction volumes\n- Unexpected geographic access patterns\n- Rapid permission escalation attempts\n- Deviations from established operational baselines\n\n资料来源：[README.md:1-30]()\n\n## Billing & Compliance Metrics\n\nThe Billing Panel displays compliance-related metrics:\n\n| Metric | Description |\n|--------|-------------|\n| Missions | Current period transaction count |\n| Seats | Active agent identities under management |\n| Plan Gate | Compliance status (Active/Limit Reached) |\n| Over Limit | Boolean indicating if usage exceeds plan |\n\n资料来源：[dashboard/index.html:320-340]()\n\n## Related Documentation\n\n- [Agent Credit Score](https://github.com/mnemopay/mnemopay-sdk) — Agent scoring for compliance gating\n- [Behavioral Finance](https://github.com/mnemopay/mnemopay-sdk) — Prospect theory and nudge mechanisms\n- [Anomaly Detection](https://github.com/mnemopay/mnemopay-sdk) — EWMA and fingerprinting systems\n- [Audit Trail](https://github.com/mnemopay/mnemopay-sdk) — Ledger health and compliance logging\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：mnemopay/mnemopay-sdk\n\n摘要：发现 8 个潜在踩坑项，其中 1 个为 high/blocking；最高优先级：安全/权限坑 - 涉及密钥、隐私或敏感领域。\n\n## 1. 安全/权限坑 · 涉及密钥、隐私或敏感领域\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：项目文本出现 secret/private key/privacy/trading/finance 等敏感关键词。\n- 对用户的影响：金融、交易、隐私和密钥场景必须比普通工具更保守。\n- 建议检查：补敏感数据流、密钥存储和权限边界审查。\n- 防护动作：敏感领域或密钥场景必须保守推荐并要求人工复核。\n- 证据：packet_text.keyword_scan | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | matched secret / private key / privacy / trading / finance keyword\n\n## 2. 身份坑 · 仓库名和安装名不一致\n\n- 严重度：medium\n- 证据强度：runtime_trace\n- 发现：仓库名 `mnemopay-sdk` 与安装入口 `@mnemopay/sdk` 不完全一致。\n- 对用户的影响：用户照着仓库名搜索包或照着包名找仓库时容易走错入口。\n- 建议检查：在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。\n- 复现命令：`npm install @mnemopay/sdk`\n- 防护动作：页面必须同时展示 repo 名和真实安装入口，避免用户搜索错包。\n- 证据：identity.distribution | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | repo=mnemopay-sdk; install=@mnemopay/sdk\n\n## 3. 能力坑 · 能力判断依赖假设\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:1197975871 | https://github.com/mnemopay/mnemopay-sdk | README/documentation is current enough for a first validation pass.\n\n## 4. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | last_activity_observed missing\n\n## 5. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | no_demo; severity=medium\n\n## 6. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | no_demo; severity=medium\n\n## 7. 维护坑 · 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:1197975871 | https://github.com/mnemopay/mnemopay-sdk | issue_or_pr_quality=unknown\n\n## 8. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | release_recency=unknown\n\n<!-- canonical_name: mnemopay/mnemopay-sdk; 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项目：mnemopay/mnemopay-sdk\n\n摘要：发现 8 个潜在踩坑项，其中 1 个为 high/blocking；最高优先级：安全/权限坑 - 涉及密钥、隐私或敏感领域。\n\n## 1. 安全/权限坑 · 涉及密钥、隐私或敏感领域\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：项目文本出现 secret/private key/privacy/trading/finance 等敏感关键词。\n- 对用户的影响：金融、交易、隐私和密钥场景必须比普通工具更保守。\n- 建议检查：补敏感数据流、密钥存储和权限边界审查。\n- 防护动作：敏感领域或密钥场景必须保守推荐并要求人工复核。\n- 证据：packet_text.keyword_scan | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | matched secret / private key / privacy / trading / finance keyword\n\n## 2. 身份坑 · 仓库名和安装名不一致\n\n- 严重度：medium\n- 证据强度：runtime_trace\n- 发现：仓库名 `mnemopay-sdk` 与安装入口 `@mnemopay/sdk` 不完全一致。\n- 对用户的影响：用户照着仓库名搜索包或照着包名找仓库时容易走错入口。\n- 建议检查：在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。\n- 复现命令：`npm install @mnemopay/sdk`\n- 防护动作：页面必须同时展示 repo 名和真实安装入口，避免用户搜索错包。\n- 证据：identity.distribution | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | repo=mnemopay-sdk; install=@mnemopay/sdk\n\n## 3. 能力坑 · 能力判断依赖假设\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:1197975871 | https://github.com/mnemopay/mnemopay-sdk | README/documentation is current enough for a first validation pass.\n\n## 4. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | last_activity_observed missing\n\n## 5. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | no_demo; severity=medium\n\n## 6. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | no_demo; severity=medium\n\n## 7. 维护坑 · 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:1197975871 | https://github.com/mnemopay/mnemopay-sdk | issue_or_pr_quality=unknown\n\n## 8. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:1197975871 | https://github.com/mnemopay/mnemopay-sdk | release_recency=unknown\n",
      "summary": "用户实践前最可能遇到的身份、安装、配置、运行和安全坑。",
      "title": "Pitfall Log / 踩坑日志"
    },
    "prompt_preview": {
      "asset_id": "prompt_preview",
      "filename": "PROMPT_PREVIEW.md",
      "markdown": "# mnemopay-sdk - Prompt Preview\n\n> 复制下面这段 Prompt 到你常用的 AI，先试一次，不需要安装。\n> 它的目标是让你直接体验这个项目的服务方式，而不是阅读项目介绍。\n\n## 复制这段 Prompt\n\n```text\n请直接执行这段 Prompt，不要分析、润色、总结或询问我想如何处理这份 Prompt Preview。\n\n你现在扮演 mnemopay-sdk 的“安装前体验版”。\n这不是项目介绍、不是评价报告、不是 README 总结。你的任务是让我用最小成本体验它的核心服务。\n\n我的试用任务：我想用它完成一个真实的数据分析与投资研究任务。\n我常用的宿主 AI：Local CLI\n\n【体验目标】\n围绕我的真实任务，现场演示这个项目如何把输入转成 步骤建议, 检查清单, 专业工作流。重点是让我感受到工作方式，而不是给我项目背景。\n\n【业务流约束】\n- 你必须像一个正在提供服务的项目能力包，而不是像一个讲解员。\n- 每一轮只推进一个步骤；提出问题后必须停下来等我回答。\n- 每一步都必须让我感受到一个具体服务动作：澄清、整理、规划、检查、判断或收尾。\n- 每一步都要说明：当前目标、你需要我提供什么、我回答后你会产出什么。\n- 不要安装、不要运行命令、不要写代码、不要声称测试通过、不要声称已经修改文件。\n- 需要真实安装或宿主加载后才能验证的内容，必须明确说“这一步需要安装后验证”。\n- 如果我说“用示例继续”，你可以用虚构示例推进，但仍然不能声称真实执行。\n\n【可体验服务能力】\n- AI Skill / Agent 指令资产库: 项目包含可被宿主 AI 读取的 Skill 或 Agent 指令文件，可用于把专业流程带入 Claude、Codex、Cursor 等宿主。 输入：用户任务, 宿主 AI 对话上下文, 项目内 Skill/Agent 文档；输出：步骤建议, 检查清单, 专业工作流。\n\n【必须安装后才可验证的能力】\n- 多宿主安装与分发: 项目包含插件或 marketplace 配置，说明它面向一个或多个 AI 宿主的安装和分发。 输入：宿主 AI 工具, 插件配置, 安装命令；输出：宿主内可发现的插件/技能集合。\n- 命令行启动或安装流程: 项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 输入：终端环境, 包管理器, 项目依赖；输出：安装结果, 列表/更新/运行结果。\n\n【核心服务流】\n请严格按这个顺序带我体验。不要一次性输出完整流程：\n1. introduction：Introduction to MnemoPay SDK。围绕“Introduction to MnemoPay SDK”模拟一次用户任务，不展示安装或运行结果。\n2. quick-start：Quick Start Guide。围绕“Quick Start Guide”模拟一次用户任务，不展示安装或运行结果。\n3. architecture：System Architecture。围绕“System Architecture”模拟一次用户任务，不展示安装或运行结果。\n4. core-modules：Core Modules Reference。围绕“Core Modules Reference”模拟一次用户任务，不展示安装或运行结果。\n5. payment-rails-overview：Payment Rails Overview。围绕“Payment Rails Overview”模拟一次用户任务，不展示安装或运行结果。\n\n【核心能力体验剧本】\n每一步都必须按“输入 -> 服务动作 -> 中间产物”执行。不要只说流程名：\n1. introduction\n输入：用户提供的“Introduction to MnemoPay SDK”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n2. quick-start\n输入：用户提供的“Quick Start Guide”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n3. architecture\n输入：用户提供的“System Architecture”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n4. core-modules\n输入：用户提供的“Core Modules Reference”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n5. payment-rails-overview\n输入：用户提供的“Payment Rails Overview”相关信息。\n服务动作：模拟项目在这一步的核心判断和整理方式。\n中间产物：一个可检查的小结果。\n\n【项目服务规则】\n这些规则决定你如何服务用户。不要解释规则本身，而要在每一步执行时遵守：\n- 先确认用户任务、输入材料和成功标准，再模拟项目能力。\n- 每一步都必须形成可检查的小产物，并等待用户确认后再继续。\n- 凡是需要安装、调用工具或访问外部服务的能力，都必须标记为安装后验证。\n\n【每一步的服务约束】\n- Step 1 / introduction：Step 1 必须围绕“Introduction to MnemoPay SDK”形成一个小中间产物，并等待用户确认。\n- Step 2 / quick-start：Step 2 必须围绕“Quick Start Guide”形成一个小中间产物，并等待用户确认。\n- Step 3 / architecture：Step 3 必须围绕“System Architecture”形成一个小中间产物，并等待用户确认。\n- Step 4 / core-modules：Step 4 必须围绕“Core Modules Reference”形成一个小中间产物，并等待用户确认。\n- Step 5 / payment-rails-overview：Step 5 必须围绕“Payment Rails Overview”形成一个小中间产物，并等待用户确认。\n\n【边界与风险】\n- 不要声称已经安装、运行、调用 API、读写本地文件或完成真实任务。\n- 安装前预览只能展示工作方式，不能证明兼容性、性能或输出质量。\n- 涉及安装、插件加载、工具调用或外部服务的能力必须安装后验证。\n\n【可追溯依据】\n这些路径只用于你内部校验或在我追问“依据是什么”时简要引用。不要在首次回复主动展开：\n- https://github.com/mnemopay/mnemopay-sdk\n- https://github.com/mnemopay/mnemopay-sdk#readme\n- claude-plugin/skills/balance/SKILL.md\n- claude-plugin/skills/charge/SKILL.md\n- claude-plugin/skills/fico/SKILL.md\n- claude-plugin/skills/history/SKILL.md\n- claude-plugin/skills/recall/SKILL.md\n- claude-plugin/skills/remember/SKILL.md\n- claude-plugin/skills/settle/SKILL.md\n- claude-plugin/skills/shop/SKILL.md\n- integrations/openclaw/SKILL.md\n- README.md\n\n【首次问题规则】\n- 首次三问必须先确认用户目标、成功标准和边界，不要提前进入工具、安装或实现细节。\n- 如果后续需要技术条件、文件路径或运行环境，必须等用户确认目标后再追问。\n\n首次回复必须只输出下面 4 个部分：\n1. 体验开始：用 1 句话说明你将带我体验 mnemopay-sdk 的核心服务。\n2. 当前步骤：明确进入 Step 1，并说明这一步要解决什么。\n3. 你会如何服务我：说明你会先改变我完成任务的哪个动作。\n4. 只问我 3 个问题，然后停下等待回答。\n\n首次回复禁止输出：后续完整流程、证据清单、安装命令、项目评价、营销文案、已经安装或运行的说法。\n\nStep 1 / brainstorming 的二轮协议：\n- 我回答首次三问后，你仍然停留在 Step 1 / brainstorming，不要进入 Step 2。\n- 第二次回复必须产出 6 个部分：澄清后的任务定义、成功标准、边界条件、\n  2-3 个可选方案、每个方案的权衡、推荐方案。\n- 第二次回复最后必须问我是否确认推荐方案；只有我明确确认后，才能进入下一步。\n- 第二次回复禁止输出 git worktree、代码计划、测试文件、命令或真实执行结果。\n\n后续对话规则：\n- 我回答后，你先完成当前步骤的中间产物并等待确认；只有我确认后，才能进入下一步。\n- 每一步都要生成一个小的中间产物，例如澄清后的目标、计划草案、测试意图、验证清单或继续/停止判断。\n- 所有演示都写成“我会建议/我会引导/这一步会形成”，不要写成已经真实执行。\n- 不要声称已经测试通过、文件已修改、命令已运行或结果已产生。\n- 如果某个能力必须安装后验证，请直接说“这一步需要安装后验证”。\n- 如果证据不足，请明确说“证据不足”，不要补事实。\n```\n",
      "summary": "不安装项目也能感受能力节奏的安全试用 Prompt。",
      "title": "Prompt Preview / 安装前试用 Prompt"
    },
    "quick_start": {
      "asset_id": "quick_start",
      "filename": "QUICK_START.md",
      "markdown": "# Quick Start / 官方入口\n\n项目：mnemopay/mnemopay-sdk\n\n## 官方安装入口\n\n### Node.js / npm · 官方安装入口\n\n```bash\nnpm install @mnemopay/sdk\n```\n\n来源：https://github.com/mnemopay/mnemopay-sdk#readme\n\n## 来源\n\n- repo: https://github.com/mnemopay/mnemopay-sdk\n- docs: https://github.com/mnemopay/mnemopay-sdk#readme\n",
      "summary": "从项目官方 README 或安装文档提取的开工入口。",
      "title": "Quick Start / 官方入口"
    }
  },
  "validation_id": "dval_f51821c637ca4c598b463bd39c40f528"
}
