dApp Docs/AI Agent 执行包与命令注册表指南
Development reference. Not independently verified for production.

AI Agent 执行包(execution_pack)与命令注册表指南

⚠️ No-Go Disclaimer: MSGChain 主网裁决为 No-Go。本文件所有内容反映的是开发阶段的技术设计,不代表主网未独立核验上线状态。生产部署状态请以白皮书为准:https://msgchain.org/whitepaper/

1. 概述

1.1 什么是执行包

执行包(execution_pack)是 MSG Chain Whitepaper 机器可读开发者入口体系中的核心目录。它将"让 AI agent 能够真正执行命令、运行工作流"这件事,从自然语言描述升级为结构化的 JSON 契约。开发者通过 https://msgchain.org/whitepaper/execution_pack/ 可以访问该目录的所有文件。

AI agent 通过读取 execution_pack/index.json 发现可用的命令集、工作流、审批门禁和证据要求,然后用真实的命令输出和链上查询结果来证明开发进度。没有执行包,AI agent 只能依靠自然语言提示猜测要运行什么命令,无法保证正确性和安全性。

1.2 在 onboarding 顺序中的位置

摘自 developer_entry.json 的 recommended_full_lifecycle_order:

product_delivery_entry.json
developer_entry.json
quickstart/index.json
quickstart/contract_and_dapp_minimal.json
chain_config/developer_sandbox_strategy.json
contract_reference/index.json
contract_reference/core_contracts.json
api_specs/formal_contracts.json
integration_examples/external_ai_agent_bootstrap_prompt.json
developer_capability_matrix.json
chain_config/index.json
contract_templates/index.json
examples/index.json
execution_pack/index.json                    ← 此处
execution_pack/delivery_workflows.json
execution_pack/command_registry.json
release_pack/index.json
e2e_fixtures/index.json
modules/review_playbook.html
modules/evidence_index.html

合约引导顺序(摘自 developer_entry.json#recommended_contract_bootstrap_order):

... → contract_templates/index.json → recipes/contract_minimal.json
→ execution_pack/index.json → execution_pack/command_registry.json
→ e2e_fixtures/index.json → modules/contract.html → ...

dApp 引导顺序(摘自 developer_entry.json#recommended_dapp_bootstrap_order):

... → examples/index.json → recipes/dapp_minimal.json
→ execution_pack/index.json → execution_pack/command_registry.json
→ release_pack/index.json → modules/keplr.html → ...

execution_pack 始终出现在模板和配方之后、发布包和 e2e 之前。其角色是在 AI 生成代码之后、正式发布之前,提供可机器执行的构建/测试/验证/发布门禁。

1.3 文件层级

根据 execution_pack/index.json 的 files 数组,该目录包含 8 个注册文件:

https://msgchain.org/whitepaper/execution_pack/
├── index.json                    # 主索引文件(schema_version, files[], boundary)
├── command_registry.json         # 命令注册表(11 条命令,按 stage 分组)
├── delivery_workflows.json       # 交付工作流(3 条工作流定义)
├── approval_gates.json           # 审批门禁(4 个门禁类型 + agent 行为规则)
├── evidence_requirements.json    # 证据要求(10 项检查 + boundary 声明)
├── ci_cd_templates.json          # CI/CD 模板(2 个模板 + approval_gate 引用)
├── governance_templates.json     # 治理提案模板(2 个模板 + mandatory_gates)
├── multisig_approval_flow.json   # 多签审批流程(4 阶段 + boundary)
└── artifact_contracts.json       # 制品契约(5 种制品 + expected_paths + produced_by)

被以下外部文件引用:

1.4 核心设计原则

msg_execution_pack_design_principles:
1. 命令即契约 — 每条命令都有 id/stage/safe_for_agent/requires_human_approval 标记
2. 门禁即边界 — 审批门禁决定 AI 能做什么、不能做什么、在什么条件下做
3. 证据即凭证 — 无 raw query/receipt/log,不得宣称开发完成或上线完成
4. 人类即闸门 — 部署、签名、资金、治理动作必须经过人工确认和审批通过

index.json 的 boundary 数组是执行包的最高行为准则:

"boundary": [
  "执行层协议包把流程机器化,不等于授权 AI 跨越生产审批。",
  "涉及真实部署、私钥、资金、治理、域名与 CI/CD 权限时必须转入人工确认。"
]

1.5 schema 版本与元数据

public 表示文件面向公众开放无需认证;stable 表示格式不会在不通知的情况下变更。AI agent 应始终检查 schema_version 以兼容未来版本。

1.6 合同包数量

index.json 记录 contract_package_count: 46,预览前 12 个合约包:

adapter_registry_v1        adapter-registry-v1
agent_a2a_v1               agent-a2a-v1
agent_intent_v1            agent-intent-v1
agent_model_v1             agent-model-v1
agent_payment_v1           agent-payment-v1
agent_registry_v1          agent-registry-v1
agent_sandbox_v1           agent-sandbox-v1
agent_verify_v1            agent-verify-v1
agent_work_v1              agent-work-v1
ai_agent_constitution_v1   ai-agent-constitution-v1
aidid_did_registry_v1      aidid-did-registry-v1
block_reward_decay_v1      block-reward-decay

每个包记录 cargo_toml 路径、cargo_test_command 和 cargo_build_wasm_command,AI agent 可直接用于单合约构建与测试。

1.7 设计哲学:Guarded Autonomy

摘自 developer_entry.json 的 goal_state:

Drive AI-assisted coding toward guarded contract and dApp delivery
with machine-readable capability mapping, execution workflows,
API summaries, templates, starters, release packs, fixture workflows,
and human approval gates.

翻译:通过机器可读的能力映射、执行工作流、API 摘要、模板、starter、发布包、fixture 工作流和人类审批门禁,推动 AI 辅助编程走向有防护的合约与 dApp 交付。

2. 执行包索引

2.1 索引文件结构

{
  "schema_version": "v1",
  "generated_by": "msg_whitepaper_pipeline_v1",
  "description": "Execution-oriented machine pack for turning MSG AI coding into guarded build/test/deploy/verify workflows.",
  "files": [ ... ],
  "contract_package_count": 46,
  "contract_package_preview": [ ... ],
  "boundary": [ ... ],
  "metadata_profile": "public_stable"
}

2.2 files 数组:8 个注册文件

每个文件记录 id、path、public_url:

id path public_url
command_registry execution_pack/command_registry.json https://msgchain.org/whitepaper/execution_pack/command_registry.json
approval_gates execution_pack/approval_gates.json https://msgchain.org/whitepaper/execution_pack/approval_gates.json
delivery_workflows execution_pack/delivery_workflows.json https://msgchain.org/whitepaper/execution_pack/delivery_workflows.json
ci_cd_templates execution_pack/ci_cd_templates.json https://msgchain.org/whitepaper/execution_pack/ci_cd_templates.json
governance_templates execution_pack/governance_templates.json https://msgchain.org/whitepaper/execution_pack/governance_templates.json
multisig_approval_flow execution_pack/multisig_approval_flow.json https://msgchain.org/whitepaper/execution_pack/multisig_approval_flow.json
evidence_requirements execution_pack/evidence_requirements.json https://msgchain.org/whitepaper/execution_pack/evidence_requirements.json
artifact_contracts execution_pack/artifact_contracts.json https://msgchain.org/whitepaper/execution_pack/artifact_contracts.json

2.3 AI Agent 发现流程

AI agent 通过 HTTP 从 execution_pack/index.json 发现所有可用的执行资源:

import httpx
from typing import Dict, Any, List, Optional
from dataclasses import dataclass, field

MSG_BASE = 'https://msgchain.org/whitepaper'

async def msg_discover_execution_pack() -> Dict[str, Any]:
    """读取 execution_pack/index.json 并加载所有子文件"""
    url = f'{MSG_BASE}/execution_pack/index.json'
    async with httpx.AsyncClient() as client:
        resp = await client.get(url)
        resp.raise_for_status()
        index = resp.json()

    pack = {
        'schema_version': index.get('schema_version'),
        'files': index.get('files', []),
        'contract_count': index.get('contract_package_count'),
        'boundary': index.get('boundary', []),
    }

    manifests = {}
    for f in pack['files']:
        async with httpx.AsyncClient() as client:
            r = await client.get(f['public_url'])
            r.raise_for_status()
            manifests[f['id']] = r.json()

    return manifests

2.4 合约预览条目结构

每条预览记录包含 4 个关键字段,使 AI agent 无需事先了解合约目录结构即可执行操作:

{
  "contract_dir": "adapter_registry_v1",
  "package_name": "adapter-registry-v1",
  "cargo_toml": "contracts/cosmwasm/all/adapter_registry_v1/Cargo.toml",
  "cargo_test_command": "cd contracts/cosmwasm/all/adapter_registry_v1 && cargo test",
  "cargo_build_wasm_command": "cd contracts/cosmwasm/all/adapter_registry_v1 && cargo build --target wasm32-unknown-unknown --release"
}

2.5 从索引到执行的完整链路

index.json
       │
       ├── command_registry.json      → 可执行命令列表(11 条)
       ├── delivery_workflows.json    → 交付工作流(3 条)
       ├── approval_gates.json        → 审批门禁规则(4 种)
       ├── ci_cd_templates.json       → CI/CD 模板(2 个)
       ├── governance_templates.json  → 治理模板(2 个)
       ├── multisig_approval_flow.json→ 多签流程(4 阶段)
       ├── evidence_requirements.json → 证据要求(10 项)
       └── artifact_contracts.json    → 制品契约(5 种)

AI agent 典型引导流程:

  1. 读取 index.json 发现所有子文件
  2. 根据任务类型(合约/dApp/全生命周期)选择对应工作流
  3. 从 command_registry.json 获取可执行命令
  4. 在每个阶段检查 approval_gates.json 的门禁要求
  5. 执行后根据 evidence_requirements.json 收集证据
  6. 根据 artifact_contracts.json 验证制品输出

2.6 索引的演进策略

当前 schema_version 为 v1。版本递增的触发条件:

AI agent 应始终检查 schema_version,并对未知版本采取保守行为(进入 plan 模式而非直接执行)。

3. 命令注册表

3.1 注册表概览

execution_pack/command_registry.json 定义了当前仓库中已验证可用的执行入口。命令注册表只收录已存在或已验证的执行入口。

{
  "schema_version": "v1",
  "generated_by": "msg_whitepaper_pipeline_v1",
  "project_root": ".",
  "commands": [ ... ],
  "contract_package_preview": [ ... ],
  "notes": [
    "命令注册表只收录当前仓库已存在或已验证的执行入口。",
    "涉及发布、token、域名、私钥、多签或治理动作时,AI agent 必须转入审批态。"
  ],
  "metadata_profile": "public_stable"
}

notes 数组包含两条重要警告:

  1. 命令注册表不是愿望清单。AI agent 不能假设注册表之外的命令存在。
  2. 即使注册表列出了一个命令,如果该命令涉及发布/域名/私钥等,AI 仍需转入审批态。

3.2 命令列表(11 条)

准备阶段(stage: prepare)

命令:deps

{
  "id": "deps",
  "command": "make deps",
  "cwd": ".",
  "stage": "prepare",
  "safe_for_agent": true,
  "requires_human_approval": false,
  "outputs": ["Go module cache", "dependency verification"],
  "source": ["Makefile"]
}

AI 可自动执行。输出:Go module 缓存 + 依赖校验。

质量门禁(stage: quality_gate)

命令:lint

{
  "id": "lint",
  "command": "make lint",
  "cwd": ".",
  "stage": "quality_gate",
  "safe_for_agent": true,
  "requires_human_approval": false,
  "outputs": ["gofmt check", "go vet", "golangci-lint"],
  "source": ["Makefile"]
}

命令:test

{
  "id": "test",
  "command": "make test",
  "cwd": ".",
  "stage": "quality_gate",
  "safe_for_agent": true,
  "requires_human_approval": false,
  "outputs": ["pkg test results"],
  "source": ["Makefile"]
}

命令:test_quantum

{
  "id": "test_quantum",
  "command": "make test-quantum",
  "cwd": ".",
  "stage": "quality_gate",
  "safe_for_agent": true,
  "requires_human_approval": false,
  "outputs": ["pkg/quantum test results"],
  "source": ["Makefile"]
}

三条命令构成 CI 基础质量门禁:lint(Go 风格检查 + vet + golangci-lint)、test(标准测试)、test_quantum(量子模块专项测试)。三者 AI 均可自动执行。

构建阶段(stage: build)

命令:build_linux

{
  "id": "build_linux",
  "command": "make build-linux",
  "cwd": ".",
  "stage": "build",
  "safe_for_agent": true,
  "requires_human_approval": false,
  "outputs": ["bin/genesis_node_linux", "bin/quantum_node_linux"],
  "source": ["Makefile"]
}

构建两个 Linux 节点二进制:创世节点和量子节点。AI 可自动执行。

合约验证阶段(stage: contract_validation)

命令:ci_contracts

{
  "id": "ci_contracts",
  "command": "make ci-contracts",
  "cwd": ".",
  "stage": "contract_validation",
  "safe_for_agent": true,
  "requires_human_approval": false,
  "outputs": ["all contract wasm build", "all contract cargo test"],
  "source": ["Makefile"]
}

对所有 CosmWasm 合约执行 wasm 构建和 cargo test。contract_package_preview 提供了 12 个合约的独立命令:

cd contracts/cosmwasm/all/adapter_registry_v1 && cargo test
cd contracts/cosmwasm/all/adapter_registry_v1 && cargo build --target wasm32-unknown-unknown --release

制品打包阶段(stage: artifact_packaging)

命令:package_deploy

{
  "id": "package_deploy",
  "command": "make package",
  "cwd": ".",
  "stage": "artifact_packaging",
  "safe_for_agent": true,
  "requires_human_approval": false,
  "outputs": ["deploy-<version>", "deploy-<version>.tar.gz"],
  "source": ["Makefile", "scripts/package_deploy.sh"]
}

打包构建产物为可部署归档。AI 可执行,但产物在通过审批门禁前不应实际部署。

文档生成阶段(stage: docs_generate)

命令:whitepaper_generate

{
  "id": "whitepaper_generate",
  "command": "whitepaper_build_pipeline",
  "cwd": ".",
  "stage": "docs_generate",
  "safe_for_agent": true,
  "requires_human_approval": false,
  "outputs": ["docs/architecture_diagrams/*.json", "docs/architecture_diagrams/*.html"],
  "source": ["whitepaper_build_pipeline"]
}

whitepaper_build_pipeline 是一个脚本引用,运行后产生架构图 JSON 和 HTML。

文档质量门禁阶段(stage: docs_quality_gate)

命令:whitepaper_audit

{
  "id": "whitepaper_audit",
  "command": "whitepaper_quality_gate",
  "cwd": ".",
  "stage": "docs_quality_gate",
  "safe_for_agent": true,
  "requires_human_approval": false,
  "outputs": ["module_audit_report.json"],
  "source": ["whitepaper_quality_gate"]
}

文档质量检查工具,输出 module_audit_report.json。

站点同步阶段(stage: site_sync)

命令:whitepaper_sync

{
  "id": "whitepaper_sync",
  "command": "python3 scripts/sync_whitepaper.py",
  "cwd": "../msgchainorg",
  "stage": "site_sync",
  "safe_for_agent": true,
  "requires_human_approval": false,
  "outputs": ["../msgchainorg/whitepaper/*"],
  "source": ["../msgchainorg/scripts/sync_whitepaper.py"]
}

注意工作目录是 ../msgchainorg。AI 可执行同步,但正式发布需要 production_release 门禁。

发布阶段(stage: release)

命令:cloudflare_pages_deploy

{
  "id": "cloudflare_pages_deploy",
  "command": "npx wrangler pages deploy . --project-name msgchainorg --branch msgchainorg --commit-dirty=true",
  "cwd": "../msgchainorg",
  "stage": "release",
  "safe_for_agent": false,
  "requires_human_approval": true,
  "outputs": ["pages deployment", "pages.dev preview", "custom domain rollout"],
  "source": ["../msgchainorg/DEPLOY_CLOUDFLARE.md"]
}

注册表中唯一 safe_for_agent: false 的命令。涉及生产域名、CI/CD 权限、公开站点更新。AI agent 不得自动执行,必须先等待人类审批。

3.3 命令参数字段详解

字段 类型 说明 约束
id string 命令唯一标识符 不得重复
command string 实际 shell 命令 必须是当前系统可执行的命令
cwd string 工作目录,相对 project_root 必须存在否则命令失败
stage string 阶段分类(8 个分类之一) prepare/quality_gate/build/contract_validation/artifact_packaging/docs_generate/docs_quality_gate/site_sync/release
safe_for_agent boolean AI 是否可自动执行 false 时 AI 不得执行
requires_human_approval boolean 是否需要人类批准 true 时 AI 必须暂停等待
outputs string[] 命令预期产生的内容 AI 验证输出是否存在
source string[] 命令定义的来源文件 AI agent 可验证文件是否存在

3.4 安全边界分类

safe_for_agent=true  + requires_human_approval=false  → AI 自动执行
safe_for_agent=true  + requires_human_approval=true   → 需人类确认
safe_for_agent=false + requires_human_approval=true   → AI 不得执行

当前注册表中:

3.5 执行上下文

大多数命令的 cwd 为 ".",但有两条命令操作 ../msgchainorg 目录:

AI agent 需要确保:

  1. ../msgchainorg 目录存在(官网仓库已 clone)
  2. 路径解析正确
  3. 有适当的写入权限
  4. 工作目录不可访问时不得忽略错误继续执行

3.6 错误处理

AI agent 应区分以下错误类型并采取相应恢复策略:

编译错误

命令:make build-linux、make ci-contracts

特征:stderr 中包含编译失败、语法错误、找不到符号等

恢复:读取完整 stderr → 定位源文件 → 修复 → 重新执行

测试失败

命令:make test、make test-quantum、ci-contracts(含 cargo test)

特征:输出中包含 --- FAIL、FAIL、非零退出码

恢复:记录失败用例 → 获取详细输出 → 定位原因 → 修复 → 重新运行

合约构建失败

命令:make ci-contracts

恢复:使用 contract_package_preview 单合约命令隔离测试:

cd contracts/cosmwasm/all/<特定合约> && cargo test
cd contracts/cosmwasm/all/<特定合约> && cargo build --target wasm32-unknown-unknown --release

工作目录不存在

命令:whitepaper_sync、cloudflare_pages_deploy

cwd 指向 ../msgchainorg,如果目录不存在,AI agent 必须先 clone 官网仓库,不能跳过检查直接运行。

门禁阻止

命令:cloudflare_pages_deploy(safe_for_agent: false)

AI agent 不得绕过 safe_for_agent 检查。必须输出等待人类审批的报告。

3.7 命令链执行

推荐的质量门禁执行顺序:

# 第 1 步:安装依赖
make deps

# 第 2 步:代码风格与静态检查
make lint

# 第 3 步:标准测试
make test

# 第 4 步:量子模块测试
make test-quantum

# 第 5 步:Linux 二进制构建
make build-linux

# 第 6 步:合约构建与测试
make ci-contracts

可选扩展:

# 第 7 步:打包部署产物
make package

# 第 8 步:白皮书生成
whitepaper_build_pipeline

# 第 9 步:文档质量门禁
whitepaper_quality_gate

ci_cd_templates.json 提供了两个标准模板来组织这些步骤:

模板 1:contract_ci_local_guarded

{
  "id": "contract_ci_local_guarded",
  "purpose": "本地或 CI 中执行合约质量门禁",
  "steps": [
    {"command_id": "deps", "goal": "安装依赖"},
    {"command_id": "lint", "goal": "静态检查"},
    {"command_id": "test", "goal": "Go 侧测试"},
    {"command_id": "ci_contracts", "goal": "合约 build + cargo test"}
  ],
  "required_outputs": ["make lint 输出", "make test 输出", "make ci-contracts 输出"],
  "boundary": ["没有真实 receipt/query/log 时,不得把 CI 通过等同于链上上线成功。"]
}

模板 2:docs_and_site_sync_guarded

{
  "id": "docs_and_site_sync_guarded",
  "purpose": "对白皮书与官网站点改动进行生成、同步与发布前检查",
  "steps": [
    {"command_id": "whitepaper_generate", "goal": "重生成白皮书产物"},
    {"command_id": "whitepaper_audit", "goal": "执行文档质量门禁"},
    {"command_id": "whitepaper_sync", "goal": "同步到官网仓库"}
  ],
  "required_outputs": ["最新 JSON/HTML 产物", "module_audit_report.json", "官网仓库白皮书目录同步结果"],
  "approval_gate": "production_release",
  "boundary": ["站点正式发布仍要求人类审批、发布凭据与回滚确认。"]
}

3.8 命令注册表的扩展性

notes 说明:"命令注册表只收录当前仓库已存在或已验证的执行入口。"这意味着:

4. 交付工作流

4.1 工作流概览

execution_pack/delivery_workflows.json 定义了 3 条标准化交付工作流:

  1. contract_delivery_guarded_v1 — CosmWasm 合约交付(5 阶段)
  2. dapp_delivery_guarded_v1 — MSG dApp 交付(4 阶段)
  3. product_launch_guarded_v1 — 合约 + dApp + 文档组合上线(3 阶段)

每条工作流由 phases 组成,每个 phase 包含:

4.2 工作流定义模型

{
  "workflow_id": "contract_delivery_guarded_v1",
  "applies_to": ["CosmWasm contract delivery"],
  "phases": [
    {
      "id": "scope",
      "consumes": ["product_delivery_entry.json"],
      "produces": ["需求范围", "验收标准"],
      "approval_gate": "scope_lock"
    },
    {
      "id": "design_and_codegen",
      "consumes": ["developer_entry.json", "contract_templates/index.json", "recipes/contract_minimal.json"],
      "produces": ["合约源码", "测试骨架"],
      "approval_gate": null
    }
  ]
}

4.3 工作流 1:合约交付(contract_delivery_guarded_v1)

适用于 CosmWasm 合约的完整交付,5 个阶段:

阶段 1:scope(范围锁定)

AI agent 先读取 product_delivery_entry.json 获取产品目标与业务规则。范围锁定之前不能进入代码生成阶段。

阶段 2:design_and_codegen(设计与代码生成)

AI 读取开发者入口、合约模板目录和最小合约配方,生成合约代码和测试骨架。

阶段 3:build_and_test(构建与测试)

AI 使用命令注册表中的命令执行构建与测试。输出是命令的原始输出文本,不是制品的最终确认。

阶段 4:deploy_plan(部署计划)

AI 制定部署计划和链上查询校验方案。secret_injection 门禁要求有真实签名账户和环境变量才能进入下一阶段。

阶段 5:real_release(真实发布)

最终阶段。production_release 门禁通过后才能执行。证据必须包含完整的 tx hash、receipt、后状态查询、原始日志。

4.4 工作流 2:dApp 交付(dapp_delivery_guarded_v1)

适用于 MSG dApp 交付,4 个阶段:

阶段 1:scope(范围锁定)

阶段 2:scaffold(脚手架生成)

阶段 3:quality_gate(质量门禁)

阶段 4:site_release(站点发布)

4.5 工作流 3:产品上线(product_launch_guarded_v1)

适用于合约 + dApp + 文档的组合上线,3 个阶段:

阶段 1:compose(组合编排)

阶段 2:evidence_closeout(证据结案)

阶段 3:launch(上线)

4.6 交付门禁汇总

三个工作流共用的门禁类型和人类输入要求:

门禁 ID 适用阶段 必须的人类输入
scope_lock before_codegen 产品目标、业务规则、验收标准
secret_injection before_real_write_or_deploy 真实签名账户、API token、环境变量、域名/CI/CD 权限
production_release before_launch 最终审批、回滚确认、资金与治理风险确认

4.7 phase 到 product_delivery_entry 的映射

product_delivery_entry       contract_delivery         dapp_delivery          product_launch
─────────────                ─────────────             ──────────             ─────────────
scope                        scope                     scope                  compose
codegen                      design_and_codegen        scaffold               compose
quality_gate                 build_and_test            quality_gate           evidence_closeout
deploy_and_verify            deploy_plan               site_release           evidence_closeout
launch                       real_release              site_release           launch

4.8 阶段间输入输出链

contract_delivery_guarded_v1 的输入输出流:

scope:
  consumes: product_delivery_entry.json
  produces: 需求范围, 验收标准
  gate: scope_lock
       │
       ▼
design_and_codegen:
  consumes: developer_entry.json, contract_templates/index.json, recipes/contract_minimal.json
  produces: 合约源码, 测试骨架
  gate: null
       │
       ▼
build_and_test:
  consumes: command_registry.json
  produces: make lint, make test, make ci-contracts, cargo test 原始输出
  gate: null
       │
       ▼
deploy_plan:
  consumes: release_pack/index.json, e2e_fixtures/index.json
  produces: 部署计划, query/receipt 校验计划, rollback plan
  gate: secret_injection
       │
       ▼
real_release:
  consumes: approval_gates.json
  produces: tx hash, receipt, post-state query, raw evidence
  gate: production_release

4.9 工作流选择与状态追踪

async def msg_select_workflow(task_type: str, manifests: dict) -> dict:
    workflows = manifests['delivery_workflows']['workflows']
    workflow_id = {
        'contract': 'contract_delivery_guarded_v1',
        'dapp': 'dapp_delivery_guarded_v1',
        'launch': 'product_launch_guarded_v1',
    }.get(task_type)
    if not workflow_id:
        raise ValueError(f'Unknown task type: {task_type}')
    return next(w for w in workflows if w['workflow_id'] == workflow_id)

@dataclass
class msg_PhaseState:
    phase_id: str
    status: str  # pending, in_progress, completed, blocked
    approval_gate: Optional[str]
    outputs: List[str]

@dataclass
class msg_WorkflowState:
    workflow_id: str
    phases: Dict[str, msg_PhaseState]
    current_phase: str

def msg_get_phase_gate(workflow: dict, phase_id: str) -> Optional[str]:
    phase = next((p for p in workflow['phases'] if p['id'] == phase_id), None)
    return phase.get('approval_gate') if phase else None

4.10 工作流边界说明

工作流定义本身不包含执行逻辑。它是一个状态机定义。实际执行需要:

  1. 命令注册表中的实际命令
  2. 审批门禁中的人类参与
  3. 证据要求中的链上查询
  4. 制品契约中的路径验证

AI agent 不能因为"工作流定义说可以做"就认为可以执行。工作流中的 consumes 和 produces 是声明式引用,不产生副作用。

5. 与 product_delivery_entry 集成

5.1 product_delivery_entry 的五阶段生命周期

product_delivery_entry.json 定义了从范围锁定到上线的完整生命周期:

"phases": [
  {"id": "scope",         "goal": "先锁定产品范围、业务规则、验收口径", "requires_human_input": true},
  {"id": "codegen",       "goal": "用 developer machine pack 生成合约或 dApp 起步资产", "requires_human_input": false},
  {"id": "quality_gate",  "goal": "按真实命令执行 lint/test/build/contract test", "requires_human_input": false},
  {"id": "deploy_and_verify", "goal": "准备发布计划、执行 smoke check、收集 query/receipt/log 证据", "requires_human_input": true},
  {"id": "launch",        "goal": "在审批通过后上线并保留 rollback 句柄", "requires_human_input": true}
]

3 个阶段需要人类输入,2 个阶段 AI 可自主完成。

5.2 执行包在各阶段的具体支持

scope 阶段

人类提供产品目标、业务规则、验收标准。approval_gates.json 的 scope_lock 门禁:

{
  "id": "scope_lock",
  "stage": "before_codegen",
  "required_human_inputs": ["产品目标", "业务规则", "验收标准"],
  "agent_action_if_missing": "stop_and_request_scope"
}

AI 缺少输入时输出 msg_awaiting_human_input 报告,包含阶段、需要的信息和建议动作。

codegen 阶段

AI 自主执行,读取 developer_entry.json、contract_templates/index.json、recipes/contract_minimal.json 生成代码。

quality_gate 阶段

AI 自主执行,这是 execution_pack 介入最深的阶段:

  1. 读取 command_registry.json 获取命令
  2. 按 ci_cd_templates.json 的 contract_ci_local_guarded 模板执行
  3. 收集所有命令的原始输出
  4. 根据 evidence_requirements.json 验证 10 项检查

deploy_and_verify 阶段

需要人类输入。approval_gates.json 的 secret_injection 门禁:

{
  "id": "secret_injection",
  "stage": "before_real_write_or_deploy",
  "required_human_inputs": ["真实签名账户", "API token", "环境变量", "域名/CI/CD 权限"],
  "agent_action_if_missing": "remain_in_stub_or_plan_mode"
}

AI 没有签名账户和 API token 时必须保持在计划态或 stub 态,不能执行实际部署。

launch 阶段

需要人类输入。approval_gates.json 的 production_release 门禁:

{
  "id": "production_release",
  "stage": "before_launch",
  "required_human_inputs": ["最终审批", "回滚确认", "资金与治理风险确认"],
  "agent_action_if_missing": "stop_before_release"
}

5.3 完整集成示例:从入口到执行

import httpx

MSG_BASE = 'https://msgchain.org/whitepaper'

async def msg_bootstrap_delivery():
    """从 product_delivery_entry 启动,逐步加载 execution_pack"""
    async with httpx.AsyncClient() as client:
        # 1. 加载 product_delivery_entry
        entry = (await client.get(f'{MSG_BASE}/product_delivery_entry.json')).json()
        phases = entry['phases']
        human_phases = [p['id'] for p in phases if p.get('requires_human_input')]
        auto_phases = [p['id'] for p in phases if not p.get('requires_human_input')]

        # 2. 加载 execution_pack 索引
        index = (await client.get(f'{MSG_BASE}/execution_pack/index.json')).json()

        # 3. 加载命令注册表(quality_gate 需要)
        cmd_reg = (await client.get(
            f'{MSG_BASE}/execution_pack/command_registry.json'
        )).json()

        # 4. 加载审批门禁(deploy_and_verify、launch 需要)
        gates = (await client.get(
            f'{MSG_BASE}/execution_pack/approval_gates.json'
        )).json()

        # 5. 加载证据要求(quality_gate 验证需要)
        evidence = (await client.get(
            f'{MSG_BASE}/execution_pack/evidence_requirements.json'
        )).json()

    return {
        'entry': entry,
        'human_phases': human_phases,
        'auto_phases': auto_phases,
        'index': index,
        'command_registry': cmd_reg,
        'approval_gates': gates,
        'evidence_requirements': evidence,
    }

5.4 多签与高风险场景的集成

对于治理或多签任务,multisig_approval_flow.json 定义了 4 阶段审批流程:

request_scope  →  governance_validation  →  secret_injection  →  final_release
   │                    │                       │                    │
   ▼                    ▼                       ▼                    ▼
scope_lock        governance_or_treasury    secret_injection    production_release

每个阶段需要的输入:

request_scope: 操作目标、影响范围、风险说明
governance_validation: DAO 通过、timelock 完成、动态阈值确认
secret_injection: 真实签名账户、执行窗口、环境变量
final_release: 最终人工确认、回滚确认、receipt/query/log 计划

边界声明:

"boundary": [
  "该流程是 AI 可读的审批框架,不是自动签名或自动放款接口。",
  "任一审批门禁缺失时,AI 必须停在计划态或拒绝执行。"
]

5.5 治理模板

governance_templates.json 定义了两种治理模板:

模板 1:governance_proposal_guarded

{
  "id": "governance_proposal_guarded",
  "required_sections": [
    "proposal_scope", "risk_summary", "affected_contracts_or_modules",
    "pre_state_queries", "post_state_queries", "rollback_or_abort_path",
    "raw_evidence_plan"
  ],
  "mandatory_gates": ["scope_lock", "governance_or_treasury", "production_release"],
  "boundary": ["治理提案模板只给出结构,不代表提案已经通过或可以自动执行。"]
}

模板 2:treasury_or_multisig_execution_guarded

{
  "id": "treasury_or_multisig_execution_guarded",
  "required_sections": [
    "dao_approval_ref", "timelock_ref", "dynamic_threshold_ref",
    "expected_receipt_bundle", "beneficiary_or_target_validation"
  ],
  "mandatory_gates": ["governance_or_treasury", "production_release"],
  "boundary": ["涉及 treasury、治理或多签的动作必须保留真实审批与签名,不允许 AI 越权执行。"]
}

5.6 制品验证集成

artifact_contracts.json 定义 5 种制品,AI agent 在 quality_gate 后应检查:

id 预期路径 生产者 检查方法
node_binaries bin/genesis_node_linux, bin/quantum_node_linux make build-linux ls 检查文件存在
whitepaper_outputs docs/architecture_diagrams/*.json whitepaper_build_pipeline glob 检查文件生成
site_sync_outputs ../msgchainorg/whitepaper/*.json python3 scripts/sync_whitepaper.py 验证目标目录
deploy_bundle deploy-<version>/, deploy-<version>.tar.gz make package ls 验证归档
contract_release_evidence tx hash, receipt, post-state query real deploy workflow 仅链上环境可产

5.7 集成边界

product_delivery_entry.json 的 hard_boundaries:

"hard_boundaries": [
  "不能把执行层协议包解释成 100% 零人工生产上线承诺。",
  "没有真实环境变量、签名账户、审批和 raw evidence 时,AI agent 必须停在计划态或 stub 态。"
]

6. AI Agent 使用模式

6.1 执行包的发现模式

AI agent 通过 msg_ExecutionPackClient 封装 HTTP 发现逻辑:

import httpx
from typing import Dict, Any, List, Optional
from dataclasses import dataclass, field

MSG_WHITEPAPER_BASE = 'https://msgchain.org/whitepaper'

class msg_ExecutionPackClient:
    """执行包 HTTP 客户端"""

    def __init__(self, base_url: str = MSG_WHITEPAPER_BASE):
        self.base_url = base_url
        self._manifests: Dict[str, Any] = {}
        self._index: Dict[str, Any] = {}

    async def discover(self) -> Dict[str, Any]:
        async with httpx.AsyncClient() as client:
            resp = await client.get(f'{self.base_url}/execution_pack/index.json')
            resp.raise_for_status()
            self._index = resp.json()

            for file_entry in self._index.get('files', []):
                file_resp = await client.get(file_entry['public_url'])
                file_resp.raise_for_status()
                self._manifests[file_entry['id']] = file_resp.json()

        return self._manifests

    def get_command_registry(self) -> List[Dict]:
        return self._manifests.get('command_registry', {}).get('commands', [])

    def get_workflows(self) -> List[Dict]:
        return self._manifests.get('delivery_workflows', {}).get('workflows', [])

    def get_approval_gates(self) -> List[Dict]:
        return self._manifests.get('approval_gates', {}).get('gates', [])

    def get_evidence_requirements(self) -> List[Dict]:
        return self._manifests.get('evidence_requirements', {}).get('required_checks', [])

    def get_artifact_contracts(self) -> List[Dict]:
        return self._manifests.get('artifact_contracts', {}).get('artifacts', [])

    def get_boundaries(self) -> List[str]:
        boundaries = list(self._index.get('boundary', []))
        evidence = self._manifests.get('evidence_requirements', {}).get('boundary', [])
        boundaries.extend(evidence)
        return boundaries

6.2 命令执行模式

安全地执行命令注册表中的命令:

import subprocess
from datetime import datetime
from pathlib import Path

@dataclass
class msg_CommandResult:
    command_id: str
    exit_code: int
    stdout: str
    stderr: str
    executed_at: str
    duration_ms: int
    success: bool

class msg_CommandExecutor:
    def __init__(self, project_root: str):
        self.project_root = Path(project_root).resolve()

    async def execute(self, cmd_def: Dict[str, Any], dry_run: bool = False) -> msg_CommandResult:
        # 安全检查
        if not cmd_def.get('safe_for_agent', False):
            raise PermissionError(
                f'Command {cmd_def["id"]} is not safe for agent execution. '
                'Requires human approval.'
            )

        cwd = self._resolve_cwd(cmd_def.get('cwd', '.'))
        command = cmd_def['command']
        start = datetime.utcnow()

        if dry_run:
            return msg_CommandResult(
                command_id=cmd_def['id'], exit_code=0,
                stdout=f'[DRY RUN] Would execute: {command} in {cwd}',
                stderr='', executed_at=start.isoformat(),
                duration_ms=0, success=True
            )

        result = subprocess.run(
            command, shell=True, cwd=str(cwd),
            capture_output=True, text=True, timeout=600  # 10 min timeout
        )

        duration = int((datetime.utcnow() - start).total_seconds() * 1000)

        return msg_CommandResult(
            command_id=cmd_def['id'],
            exit_code=result.returncode,
            stdout=result.stdout, stderr=result.stderr,
            executed_at=start.isoformat(),
            duration_ms=duration,
            success=result.returncode == 0
        )

    def _resolve_cwd(self, cwd: str) -> Path:
        target = (self.project_root / cwd).resolve()
        if not target.exists():
            raise FileNotFoundError(f'Working directory not found: {target}')
        return target

6.3 安全边界检查模式

class msg_SafetyBoundary:
    def __init__(self, manifests: Dict[str, Any]):
        self.manifests = manifests
        self.boundaries = manifests.get('index', {}).get('boundary', [])

    def check_command_safety(self, cmd_def: Dict[str, Any]) -> Dict[str, Any]:
        result = {
            'command_id': cmd_def['id'],
            'can_execute': True,
            'warnings': [],
            'blocks': []
        }
        if not cmd_def.get('safe_for_agent', True):
            result['can_execute'] = False
            result['blocks'].append('Command is not safe for agent execution')
        if cmd_def.get('requires_human_approval', False):
            result['can_execute'] = False
            result['blocks'].append('Command requires human approval')
        return result

    def check_phase_safety(self, phase: Dict[str, Any]) -> Dict[str, Any]:
        gate_id = phase.get('approval_gate')
        if not gate_id:
            return {'phase_id': phase['id'], 'safe': True}

        gates = self.manifests.get('approval_gates', {}).get('gates', [])
        gate = next((g for g in gates if g['id'] == gate_id), None)
        if not gate:
            return {'phase_id': phase['id'], 'safe': True}

        required = gate.get('required_human_inputs', [])
        if required:
            return {
                'phase_id': phase['id'],
                'safe': False,
                'gate': gate_id,
                'required_inputs': required,
                'action': gate.get('agent_action_if_missing', 'stop')
            }
        return {'phase_id': phase['id'], 'safe': True}

    def get_safe_commands_for_stage(self, stage: str) -> List[Dict]:
        commands = self.manifests.get('command_registry', {}).get('commands', [])
        return [
            c for c in commands
            if c.get('stage') == stage
            and c.get('safe_for_agent', False)
            and not c.get('requires_human_approval', False)
        ]

6.4 验证门禁模式

class msg_GateKeeper:
    def __init__(self, manifests: Dict[str, Any]):
        gates = manifests.get('approval_gates', {}).get('gates', [])
        self.gates = {g['id']: g for g in gates}

    def check_gate(self, gate_id: str, context: Dict[str, Any]) -> Dict[str, Any]:
        gate = self.gates.get(gate_id)
        if not gate:
            return {'gate_id': gate_id, 'status': 'unknown'}

        required = gate.get('required_human_inputs', [])
        missing = [inp for inp in required if inp not in context]

        if missing:
            return {
                'gate_id': gate_id,
                'status': 'blocked',
                'missing_inputs': missing,
                'agent_action': gate.get('agent_action_if_missing', 'stop')
            }
        return {'gate_id': gate_id, 'status': 'passed', 'agent_action': 'proceed'}

    def is_production_release_blocked(self, context: Dict[str, Any]) -> bool:
        return self.check_gate('production_release', context)['status'] == 'blocked'

    def get_required_inputs_for_gate(self, gate_id: str) -> List[str]:
        gate = self.gates.get(gate_id)
        return gate.get('required_human_inputs', []) if gate else []

6.5 证据收集模式

evidence_requirements.json 定义 10 项检查,按类型分组:

id type command_or_probe
lint build_output make lint
test test_output make test
test_quantum test_output make test-quantum
build_linux artifact_output make build-linux
contracts contract_output make ci-contracts
query_balances chain_query query balances
query_emission_state chain_query query emission state
query_pending_reward chain_query query pending reward
query_registry_canonical_key chain_query query registry canonical key
tx_receipt_bundle receipt_bundle tx hash + receipt + post-state query + raw log
class msg_EvidenceCollector:
    def __init__(self, manifests: Dict[str, Any]):
        self.checks = manifests.get('evidence_requirements', {}).get('required_checks', [])
        self.boundaries = manifests.get('evidence_requirements', {}).get('boundary', [])

    async def collect_evidence(self, command_results: List[msg_CommandResult]) -> Dict[str, Any]:
        evidence = {}
        for check in self.checks:
            check_id = check['id']
            check_type = check['type']

            if check_type in ('build_output', 'test_output', 'artifact_output', 'contract_output'):
                cmd_results = [r for r in command_results if r.command_id == check.get('command')]
                evidence[check_id] = {
                    'check_id': check_id,
                    'type': check_type,
                    'all_passed': all(r.success for r in cmd_results),
                    'results': [r.stdout for r in cmd_results],
                    'status': 'collected' if cmd_results else 'missing'
                }
            elif check_type == 'chain_query':
                evidence[check_id] = {
                    'type': 'chain_query',
                    'required': True,
                    'status': 'pending',
                    'note': 'Requires live chain connection to collect'
                }
            elif check_type == 'receipt_bundle':
                evidence[check_id] = {
                    'type': 'receipt_bundle',
                    'required': True,
                    'components': ['tx hash', 'receipt', 'post-state query', 'raw log'],
                    'status': 'pending',
                    'note': 'Requires real deployment to collect'
                }
        return evidence

    def get_missing_evidence(self, evidence: Dict[str, Any]) -> List[str]:
        return [k for k, v in evidence.items() if v.get('status') == 'pending']

    def all_command_evidence_passed(self, evidence: Dict[str, Any]) -> bool:
        command_checks = [v for v in evidence.values()
                         if v['type'] in ('build_output', 'test_output', 'artifact_output', 'contract_output')]
        return all(v.get('all_passed', False) for v in command_checks)

6.6 错误恢复模式

class msg_ErrorRecovery:
    RECOVERY_MAP = {
        'compile_error': 'fix_and_rebuild',
        'test_failure': 'fix_and_retest',
        'lint_error': 'auto_format_and_relint',
        'contract_build_failure': 'isolate_and_debug_contract',
        'missing_directory': 'clone_or_create_and_retry',
        'gate_blocked': 'wait_for_human_approval',
    }

    @staticmethod
    def analyze_error(result: msg_CommandResult) -> str:
        if not result.success:
            stderr = result.stderr.lower()
            if 'compile' in stderr or 'cannot find' in stderr:
                return 'compile_error'
            if 'test fail' in stderr or '--- fail' in stderr:
                return 'test_failure'
            if 'lint' in stderr or 'not gofmt' in stderr:
                return 'lint_error'
            if 'cargo' in stderr or 'wasm' in stderr:
                return 'contract_build_failure'
            if 'no such file' in stderr or 'directory' in stderr:
                return 'missing_directory'
        return 'unknown'

    @staticmethod
    def get_recovery_plan(error_type: str) -> Dict[str, Any]:
        strategy = msg_ErrorRecovery.RECOVERY_MAP.get(error_type, 'manual_investigation')
        return {
            'error_type': error_type,
            'strategy': strategy,
            'requires_human': strategy == 'wait_for_human_approval'
        }

    @staticmethod
    async def auto_recover(
        result: msg_CommandResult,
        executor: msg_CommandExecutor,
        cmd_def: Dict[str, Any]
    ) -> Optional[msg_CommandResult]:
        error_type = msg_ErrorRecovery.analyze_error(result)
        plan = msg_ErrorRecovery.get_recovery_plan(error_type)

        if plan['requires_human']:
            return None

        if error_type == 'lint_error':
            subprocess.run('gofmt -w .', shell=True, cwd=executor.project_root)
            return await executor.execute(cmd_def)

        if error_type == 'missing_directory':
            path = executor._resolve_cwd(cmd_def.get('cwd', '.'))
            path.mkdir(parents=True, exist_ok=True)
            return await executor.execute(cmd_def)

        return None

6.7 完整交付流程示例

async def msg_complete_contract_delivery(project_root: str, task_type: str = 'contract'):
    """从发现执行包到完成合约交付的完整流程"""

    # 第 1 步:发现执行包
    client = msg_ExecutionPackClient()
    manifests = await client.discover()

    # 第 2 步:选择工作流
    workflow = next(
        w for w in client.get_workflows()
        if w['workflow_id'] == {
            'contract': 'contract_delivery_guarded_v1',
            'dapp': 'dapp_delivery_guarded_v1',
            'launch': 'product_launch_guarded_v1',
        }[task_type]
    )

    # 第 3 步:初始化安全边界检查
    safety = msg_SafetyBoundary(manifests)
    gate_keeper = msg_GateKeeper(manifests)
    executor = msg_CommandExecutor(project_root)

    report = {
        'workflow_id': workflow['workflow_id'],
        'phases': [],
        'evidence': {},
        'blocked': False
    }

    # 第 4 步:逐阶段执行
    for phase in workflow['phases']:
        phase_id = phase['id']
        gate_id = phase.get('approval_gate')

        phase_report = {
            'phase_id': phase_id,
            'status': 'pending',
            'gate': gate_id
        }

        # 检查门禁
        if gate_id:
            gate_check = safety.check_phase_safety(phase)
            if gate_check.get('safe') == False:
                phase_report['status'] = 'blocked'
                phase_report['gate_check'] = gate_check
                report['phases'].append(phase_report)
                report['blocked'] = True
                break

        # 执行 quality_gate 阶段的命令
        if phase_id in ('build_and_test', 'quality_gate'):
            commands = client.get_command_registry()
            stage_commands = [c for c in commands if c['stage'] in ('prepare', 'quality_gate')]

            results = []
            for cmd in stage_commands:
                check = safety.check_command_safety(cmd)
                if check['can_execute']:
                    result = await executor.execute(cmd)
                    results.append(result)

            # 收集证据
            collector = msg_EvidenceCollector(manifests)
            evidence = await collector.collect_evidence(results)
            report['evidence'] = evidence

            phase_report['status'] = 'completed'
            phase_report['commands'] = [r.command_id for r in results]
            phase_report['all_passed'] = all(r.success for r in results)

        elif phase_id == 'deploy_plan':
            phase_report['status'] = 'completed'
            phase_report['note'] = 'Deploy plan prepared, awaiting secret_injection gate'

        elif phase_id == 'real_release':
            release_check = gate_keeper.check_gate('production_release', {
                '最终审批': 'pending',
                '回滚确认': 'pending',
                '资金与治理风险确认': 'pending'
            })
            phase_report['status'] = 'waiting_for_human'
            phase_report['gate_check'] = release_check

        else:
            phase_report['status'] = 'completed'

        report['phases'].append(phase_report)

    return report

6.8 AI Agent 输出契约

AI agent 在各个阶段的输出应遵循结构化格式:

阶段状态报告:

{
  "msg_phase_report": {
    "workflow_id": "contract_delivery_guarded_v1",
    "phase_id": "build_and_test",
    "status": "completed",
    "commands_executed": [
      {"id": "deps", "exit_code": 0, "success": true},
      {"id": "lint", "exit_code": 0, "success": true},
      {"id": "test", "exit_code": 0, "success": true},
      {"id": "ci_contracts", "exit_code": 0, "success": true}
    ],
    "evidence_collected": ["lint", "test", "test_quantum", "build_linux", "contracts"],
    "next_phase": "deploy_plan",
    "blocked_by": "secret_injection"
  }
}

等待人类输入报告:

{
  "msg_awaiting_human_input": {
    "gate": "secret_injection",
    "required_inputs": [
      "真实签名账户",
      "API token",
      "环境变量",
      "域名/CI/CD 权限"
    ],
    "current_state": "deploy_plan_ready",
    "suggested_actions": [
      "准备签名账户私钥",
      "配置 MSG chain RPC endpoint",
      "设置 CI/CD 发布凭证"
    ]
  }
}

错误报告:

{
  "msg_error_report": {
    "command_id": "ci_contracts",
    "error_type": "contract_build_failure",
    "exit_code": 1,
    "recovery_attempted": true,
    "recovery_strategy": "isolate_and_debug_contract",
    "isolated_failure": "agent_a2a_v1",
    "suggested_fix": "检查 contracts/cosmwasm/all/agent_a2a_v1/Cargo.toml 依赖版本"
  }
}

7. 边界与注意事项

7.1 当前实现的能力边界

命令注册表覆盖 11 条命令,涉及 Go 项目构建与测试、CosmWasm 合约构建与测试、白皮书文档生成与审计、站点头同步、Cloudflare Pages 发布。

未覆盖的生产领域:

工作流中没有任何步骤包含实际的链上交易发送。"real_release" 阶段需要人类执行实际部署。

7.2 生产环境缺失环节

当前 execution_pack 不包含以下生产必需能力:

contract_release_evidence 制品(tx hash、receipt、post-state query)的 produced_by 为 "real deploy workflow",表示其不是 AI 可自动生成的。

7.3 Human-in-the-Loop 要求

根据 approval_gates.json 和 multisig_approval_flow.json:

必须在代码生成前获得人类输入(scope_lock):

必须在部署前由人类提供(secret_injection):

必须在发布前由人类审批(production_release):

高风险写操作必须通过治理(governance_or_treasury):

AI agent 行为规则:

scope 输入缺失        → stop_and_request_scope
secret 缺失           → remain_in_stub_or_plan_mode
release 审批缺失      → stop_before_release
governance 缺失       → forbid_execution

7.4 测试指南

验证命令注册表:

# 命令数量
curl -s https://msgchain.org/whitepaper/execution_pack/command_registry.json \
  | jq '.commands | length'
# 预期:11

# 不可 AI 执行的命令
curl -s https://msgchain.org/whitepaper/execution_pack/command_registry.json \
  | jq '[.commands[] | select(.safe_for_agent == false)] | .[].id'
# 预期:"cloudflare_pages_deploy"

# 按阶段分组
curl -s https://msgchain.org/whitepaper/execution_pack/command_registry.json \
  | jq '[.commands[] | .stage] | unique'
# 预期:["artifact_packaging", "build", "contract_validation",
#        "docs_generate", "docs_quality_gate", "prepare",
#        "quality_gate", "release", "site_sync"]

验证工作流:

# 工作流数量
curl -s https://msgchain.org/whitepaper/execution_pack/delivery_workflows.json \
  | jq '.workflows | length'
# 预期:3

# 某工作流的阶段数
curl -s https://msgchain.org/whitepaper/execution_pack/delivery_workflows.json \
  | jq '.workflows[] | select(.workflow_id == "contract_delivery_guarded_v1") | .phases | length'
# 预期:5

# 所有门禁类型
curl -s https://msgchain.org/whitepaper/execution_pack/delivery_workflows.json \
  | jq '[.workflows[].phases[].approval_gate] | unique'
# 预期:["production_release", "scope_lock", "secret_injection", null]

验证审批门禁:

# 门禁数量
curl -s https://msgchain.org/whitepaper/execution_pack/approval_gates.json \
  | jq '.gates | length'
# 预期:4

# 缺少输入时的 agent 行为
curl -s https://msgchain.org/whitepaper/execution_pack/approval_gates.json \
  | jq '[.gates[] | {id: .id, action: .agent_action_if_missing}]'
# 预期:4 个门禁各有不同行为

验证证据要求:

# 检查项数量
curl -s https://msgchain.org/whitepaper/execution_pack/evidence_requirements.json \
  | jq '.required_checks | length'
# 预期:10

# 按类型分组
curl -s https://msgchain.org/whitepaper/execution_pack/evidence_requirements.json \
  | jq '[.required_checks[] | .type] | unique'
# 预期:["artifact_output", "build_output", "chain_query",
#        "contract_output", "receipt_bundle", "test_output"]

7.5 AI Agent 自检清单

AI agent 在与执行包交互时应持续检查:

□ 已读取 execution_pack/index.json 发现所有 8 个注册文件?
□ 已根据任务类型(contract/dapp/launch)选择正确的工作流?
□ 已检查当前阶段是否需要审批门禁?
□ 已验证当前阶段的审批输入是否齐全?
□ 执行命令前已检查 safe_for_agent 标记?
□ 执行命令后已收集原始输出作为证据?
□ 缺失链上证据(chain_query/receipt_bundle)时已如实标记 pending?
□ 到达 release 阶段前已请求人类审批?
□ 涉及治理/多签时已检查 governance_or_treasury 门禁?
□ 输出中引用了证据文件路径而非虚构结果?

7.6 已知限制

合约预览的覆盖范围

contract_package_count 为 46,但预览只展示前 12 个。AI agent 不能假设所有 46 个合约包的 cargo_test_command 都遵循相同的 pattern。

命令来源的可验证性

source 字段指向定义命令的源文件。当前来源包括:

AI agent 应验证这些源文件在项目仓库中确实存在。

证据要求的链上依赖

evidence_requirements.json 的 10 项检查中,5 项不依赖链上环境(build_output、test_output、artifact_output、contract_output),5 项依赖链上环境:

无链上环境时这些证据无法收集,AI agent 不能模拟或虚构。

7.7 边界声明汇总

execution_pack/index.json:

执行层协议包把流程机器化,不等于授权 AI 跨越生产审批。
涉及真实部署、私钥、资金、治理、域名与 CI/CD 权限时必须转入人工确认。

execution_pack/command_registry.json:

命令注册表只收录当前仓库已存在或已验证的执行入口。
涉及发布、token、域名、私钥、多签或治理动作时,AI agent 必须转入审批态。

execution_pack/approval_gates.json(各门禁的 agent_action_if_missing):

execution_pack/evidence_requirements.json:

无 raw query/receipt/log,不得宣称开发完成或上线完成。
白皮书机器层只能给出验证合同,不能伪造链上成功结果。

execution_pack/ci_cd_templates.json:

没有真实 receipt/query/log 时,不得把 CI 通过等同于链上上线成功。
站点正式发布仍要求人类审批、发布凭据与回滚确认。

execution_pack/governance_templates.json:

治理提案模板只给出结构,不代表提案已经通过或可以自动执行。
涉及 treasury、治理或多签的动作必须保留真实审批与签名,不允许 AI 越权执行。

execution_pack/multisig_approval_flow.json:

该流程是 AI 可读的审批框架,不是自动签名或自动放款接口。
任一审批门禁缺失时,AI 必须停在计划态或拒绝执行。

developer_entry.json current_boundaries:

当前开发协议层可显著提升 AI coding 的可执行性,但仍不能诚实承诺
"只靠入口即可 100% 自动完成任何产品上线"。
当前已补 Quick Start、source-backed 合约消费索引、正式 API/Schema
契约索引与 fail-closed sandbox 策略,但仍不等于 signed public SDK、
public sandbox 或 not independently verified for production 交付。
涉及私钥、部署权限、生产域名、资金操作、DAO/timelock/threshold 的动作,
必须保留人类确认与审批门禁。

product_delivery_entry.json hard_boundaries:

不能把执行层协议包解释成 100% 零人工生产上线承诺。
没有真实环境变量、签名账户、审批和 raw evidence 时,
AI agent 必须停在计划态或 stub 态。

7.8 总结

execution_pack 提供了一套结构化的、机器可读的执行契约,使 AI agent 能够:

  1. 发现可用的命令和工作流
  2. 安全地执行构建、测试、验证
  3. 在审批门禁前暂停等待人类介入
  4. 收集结构化的执行证据
  5. 明确知道何时需要人类批准

它不是为取代人工审批或实现全自动生产上线,而是为了在 AI 自主性和人类控制之间建立清晰的、契约化的边界。

developer_entry.json 的 recommended_full_lifecycle_order 中,execution_pack 的三个文件(index.json、delivery_workflows.json、command_registry.json)依次出现在引导顺序的后半段,连接了"AI 可以生成代码"和"AI 可以执行质量门禁"这两个能力域。

AI agent 在任何时候都应记住 evidence_requirements.json 中最核心的那条边界:

无 raw query/receipt/log,不得宣称开发完成或上线完成。
白皮书机器层只能给出验证合同,不能伪造链上成功结果。

这是整个执行包的灵魂:它提供的是验证框架,不是自动完成的魔法。


本文档内容基于 MSGChain 代码库真实状态编写,非 AI 自动生成。
主网状态: No-Go | 白皮书: https://msgchain.org/whitepaper/