Metadata-Version: 2.4
Name: aif-normbase
Version: 0.1.23
Summary: Agent Information Field - Norm Repository
Requires-Python: >=3.11
Description-Content-Type: text/markdown
Requires-Dist: fastapi>=0.109.0
Requires-Dist: uvicorn[standard]>=0.27.0
Requires-Dist: pydantic>=2.5.0
Requires-Dist: pydantic-settings>=2.1.0
Requires-Dist: sqlalchemy[asyncio]>=2.0.0
Requires-Dist: asyncpg>=0.29.0
Requires-Dist: aiosqlite>=0.19.0
Requires-Dist: redis>=5.0.0
Requires-Dist: qdrant-client>=1.17.0
Requires-Dist: openai>=1.10.0
Requires-Dist: anthropic>=0.18.0
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: google-genai>=0.3.0
Requires-Dist: cohere>=5.0.0
Requires-Dist: sentence-transformers>=2.2.0
Requires-Dist: aiohttp>=3.9.0
Requires-Dist: httpx>=0.26.0
Requires-Dist: mcp>=1.0.0
Requires-Dist: pyArchimate>=0.9.0
Requires-Dist: neo4j>=5.14.0
Requires-Dist: bcrypt>=4.1.0
Requires-Dist: PyJWT>=2.8.0
Requires-Dist: email-validator>=2.0.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"
Requires-Dist: black>=24.0.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"

# AIF (Agent Information Field)

**对外产品称呼（暂定）**：**AIF — Agent 信息场平台**（品牌确定后可调整；仓库与技术标识仍可保留 AIF）。

*Interim customer-facing name (EN): **AIF — Agent Information Field Platform**.*

基于组织符号学的 LLM Agent 协作治理基础设施。

**运行时关系（产品路径）**：终端用户只访问 **`aif_platform/web`**；浏览器请求经 Vite 代理到 **`aif-platform`**（BFF），再由平台服务调用 **`normbase`**、**`eda_agent`** 等上游。**不要**让浏览器直连 Normbase / EDA 端口。

## 项目状态

本仓库为 **Python 单分发包**（`pyproject.toml` 中项目名 `aif-normbase`），在根目录执行 **`pip install -e .`** 后，可将下列命令加入 PATH（定义见 `[project.scripts]`）：

| 命令 | 作用 |
| --- | --- |
| `aif-normbase` | 规范库 HTTP API（等价 `python -m normbase.main`） |
| `aif-eda` | EDA Agent HTTP API（等价 `python -m eda_agent.main`） |
| `aif-platform` | 产品线 BFF / 注册登录与租户 API（默认 `8020`） |
| `aif-mcp-normbase` | MCP 适配（Normbase-first） |
| `aif-mcp-eda` | MCP 适配（EDA-first） |
| `aif-field-import` | Field API Key 批量导入规范 CLI |
| `aif-platform-bootstrap-admin` | 引导平台管理员账号 |

另有 **Node 包装**：`npx -y --package @langxai/aif-mcp aif-mcp-normbase` / `npx -y --package @langxai/aif-mcp aif-mcp-eda`。

**产品前端**（落地页、控制台 UI）在 `aif_platform/web`（Vite + React），与内部技术看板 `dashboard/` 分离；开发方式见 [`aif_platform/web/README.md`](aif_platform/web/README.md)。

## 架构定位

在 AIF 中，`eda_agent` 不只是一个普通业务 Agent，而是外部用户 Agent 的社会封装层：

- 外部 Agent 通过 MCP 接入后，会在鉴权与治理链路中映射到内部 `agent_id`。
- 内部 `agent_id` 进入 EDA 心理-规范模型（Belief / NormBinding / ValueWeight）后再执行检索、绑定与决策。
- 这使得“接入信息场”的外部 Agent，在系统内都以可审计、可治理的 EDA Agent 形态运行。
- Norms 为 Agent 定义“可预期行动空间（predictable action envelope）”：在空间内可预期、可解释、可审计；超出空间边界时，不确定性上升并需要治理回路介入。

Architecture Positioning (EN):

- `eda_agent` acts as a social-governance wrapper for external user agents.
- After MCP ingress, callers are mapped into internal agent identities and processed through the EDA model.
- This turns external agents into governable, auditable EDA agents within the information field runtime.
- Norms define a predictable action envelope: behavior inside the envelope is expected and auditable, while behavior outside it increases uncertainty and should trigger governance controls.

## 项目结构

``` text
aif/
├── aif_platform/             # 平台产品线（用户向：后端 server + 前端 web；与 security / dashboard 分工）
│   ├── server/               # Python 后端（api / services / models / db / schemas）
│   └── web/                  # 用户向前端（Vite + React，见 aif_platform/web/README.md）
├── normbase/                 # 规范库核心模块
│   ├── api/                  # API 路由 (norms, retrieval, roles, fields, keys, compliance)
│   ├── services/             # 业务服务层 (norm/retrieval/role/field/key/compliance)
│   ├── models/               # 数据模型
│   ├── db/                   # 数据库 (schema.sql, connection)
│   └── schemas.py            # 统一请求/响应 Schema 入口
├── eda_agent/                # EDA Agent 模块
│   ├── api/                  # Agent API 路由
│   ├── services/             # 应用服务层 (agent/runtime/field/trace)
│   ├── infra/                # 基础设施适配 (llm, normbase_client)
│   ├── db/                   # EDA 持久化 schema/connection
│   ├── state.py              # EDA 状态管理 (Belief, NormBinding, ValueWeight)
│   └── engine.py             # 推理引擎 (E/D/A 组件)
├── integrations/mcp_normbase/         # MCP 适配层（Normbase-first, Stage 1）
├── integrations/mcp_eda/     # MCP 适配层（EDA-first, Stage 2）
├── llm/                      # LLM 调用抽象（多厂商、统一 env）
├── norm_extractor/           # 规范萃取（分块 / 提示词；由 normbase 编排调用）
├── dashboard/                # 内部技术看板（与产品 Web 分离）
├── scenarios/                # 场景构建工具 + scenario_* JSON 数据
│   ├── build_seed.py         # 统一入口（支持 --init-scenario / --scenario-name）
│   ├── *_seed.py             # field / eda_agent / norm 落库脚本
│   └── scenario_*/           # 每个场景目录（README + field.json + eda_agent.json + norms.json）
├── ontology/                 # 领域本体与概念资产
├── docs/                     # 产品、部署、API 与治理文档
├── scripts/                  # 构建/发布/运维脚本
├── security/                 # 认证鉴权与安全相关模块
├── tests/                    # 测试用例
├── background/               # 规划与背景资料
├── docker-compose.yml        # 本地开发环境
├── pyproject.toml            # Python 包配置 (aif-normbase)
├── requirements.txt          # 依赖
└── README.md                 # 项目说明
```

## 模块说明

模块文档导航（建议先看）：

- `aif_platform`（后端）：[`aif_platform/README.md`](aif_platform/README.md)
- `aif_platform/web`（前端）：[`aif_platform/web/README.md`](aif_platform/web/README.md)
- `normbase`：[`normbase/README.md`](normbase/README.md)
- `eda_agent`：[`eda_agent/README.md`](eda_agent/README.md)
- `integrations`：[`integrations/README.md`](integrations/README.md)
- `integrations/mcp_normbase`：[`integrations/mcp_normbase/README.md`](integrations/mcp_normbase/README.md)
- `integrations/mcp_eda`：[`integrations/mcp_eda/README.md`](integrations/mcp_eda/README.md)
- `integrations/openclaw`：[`integrations/openclaw/README.md`](integrations/openclaw/README.md)
- `dashboard`：[`dashboard/README.md`](dashboard/README.md)
- `scenarios`：[`scenarios/README.md`](scenarios/README.md)
- `ontology`：[`ontology/README.md`](ontology/README.md)
- `security`：[`security/README.md`](security/README.md)
- `scripts`：[`scripts/README.md`](scripts/README.md)
- `tests`：[`tests/README.md`](tests/README.md)
- `docs`：[`docs/README.md`](docs/README.md)

说明：

- `README.md` 关注项目总览与启动入口。
- 各模块 `README.md` 关注模块职责、接口与运行方式。
- 先阅读模块文档再进入 `docs/` 深入运行手册，可减少上下文切换成本。

### normbase

规范库核心，提供：

- ✅ 规范 CRUD 操作 (obligation/prohibition/permission)
- ✅ 检索：agent_role + field_ids 双通道 (RRF融合)
- ✅ 向量语义检索 (Qdrant)
- ✅ 版本管理 (norm_versions)
- ✅ 规范关系 (norm_relations)
- ✅ Redis 检索结果缓存（`retrieve_cache_*` + `CacheService`；见 `normbase/services/retrieval_service.py`）
- ✅ 规范萃取流水线（MVP：`/api/v1/extraction` 文本与批次文档萃取、过程 JSON；Dashboard **Extraction** 页草稿审核与激活）
- ⬜ 萃取扩展（见 `docs/norm-extraction-design.zh.md` 阶段 4）：✅ 长文分块 + LLM 单次字符预算、✅ PDF 文本（PyMuPDF）、✅ 后台萃取（`queued` + `?background=true`）；⬜ Word/Docling、⬜ 独立队列/多 worker、⬜ 分块合并策略增强
- ✅ MCP 适配（通过 `integrations/mcp_normbase` 暴露工具）

Schema 组织约定：

- 统一使用 `normbase/schemas.py` 作为请求/响应 Schema 入口。
- `api` 层不定义业务 Schema；仅引用 `normbase.schemas`。

详细说明见：[`normbase/README.md`](normbase/README.md)

### eda_agent

EDA Agent 运行时 (Phase 6 完成)：

- ✅ E（认识论）信念管理 (Belief)
- ✅ D（义务论）规范绑定 (NormBinding)
- ✅ A（价值论）权重推理 (ValueWeight)
- ✅ 合规校验基础
- ⬜ 完整推理流程

详细说明见：[`eda_agent/README.md`](eda_agent/README.md)

## 技术栈

- **后端**：FastAPI、PostgreSQL（JSONB）、SQLAlchemy 2.0（async）
- **检索**：Qdrant（向量）、Redis（检索缓存等，见 Normbase 配置）
- **LLM**：OpenAI / Anthropic 等（包 `llm`；环境变量 `LLM_PROVIDER`、`LLM_API_KEY`、`LLM_MODEL` 等，见 `.env.example`）
- **产品前端**：Vite、React、TypeScript、Tailwind CSS（`aif_platform/web`）

## 快速开始

**环境**：Python **`>=3.11`**（与 `pyproject.toml` 一致）。Node.js **18+**（仅开发产品前端时需要）。

```bash
# 创建并激活 conda 虚拟环境（首次）
conda create -n aif python=3.11 -y
conda activate aif

# （可选）使用 venv 而不是 conda
# python -m venv .venv
# .venv\Scripts\activate   # Windows
# source .venv/bin/activate  # Unix

# 启动本地依赖 (PostgreSQL + Qdrant + Redis 等，视 docker-compose 为准)
docker-compose up -d

# 安装依赖（全量工具与 CI 常用清单）
pip install -r requirements.txt

# 注册控制台命令（aif-normbase / aif-eda / aif-platform / MCP 等）
pip install -e .
```

**典型顺序（跑通产品页）**：在已安装依赖的前提下，依次或分终端启动 `aif-normbase` → `aif-eda` → `aif-platform`，再 `cd aif_platform/web && npm install && npm run dev`。仅玩 MCP / 单测 Normbase 时可省略部分进程。

### MCP（本地开发）

```bash
# Normbase-first（stdio）— 与下面 python -m 等价
aif-mcp-normbase --transport stdio
python -m integrations.mcp_normbase.server --transport stdio

# EDA-first（stdio）
aif-mcp-eda --transport stdio
python -m integrations.mcp_eda.server --transport stdio
```

### MCP（分发调用）

```bash
# Python 入口（Normbase-first）
uvx --from aif-normbase aif-mcp-normbase --transport stdio

# Python 入口（EDA-first）
uvx --from aif-normbase aif-mcp-eda --transport stdio

# Node 包装入口
npx -y --package @langxai/aif-mcp aif-mcp-normbase
npx -y --package @langxai/aif-mcp aif-mcp-eda
```

说明：

- 当前 `aif-mcp-normbase` 为稳定入口（Normbase-first）。
- 当前 `aif-mcp-eda` 已提供 EDA runtime 工具入口（`perceive` / `bind_norms` / `decide` / `execute` / `get_traces`），并通过 API key 绑定到对应 `eda_agent`。

### MCP 探针（Dashboard MCP Info）

默认推荐给 MCP 客户端使用 `stdio` 模式；如果需要让 Dashboard 的 MCP Info 显示实时状态，建议额外启动一个 `streamable-http` 的探针进程：

```bash
# 探针进程（HTTP）
python -m integrations.mcp_normbase.server --transport streamable-http
```

并将 Dashboard 的 `MCP_BASE_URL` 指向该进程（示例）：

```bash
MCP_BASE_URL=http://127.0.0.1:8000
```

验证方式：

- 打开 Dashboard 的 MCP Info 页面，`live=true` 且可列出 tools。
- 或调用 `GET /api/mcp/info` 查看实时探针结果。

### 启动 Normbase / EDA / 平台 API（开发）

端口以各自 `config` / 环境变量为准（常见：Normbase `8001`，EDA `8002`，平台 `8020`）。

```bash
# 规范库 API
aif-normbase
# 等价：python -m normbase.main

# EDA Agent API
aif-eda
# 等价：python -m eda_agent.main

# 产品线 BFF（浏览器与 `aif_platform/web` 只对接此服务）
aif-platform
# 等价：python -m uvicorn aif_platform.server.main:app --host 0.0.0.0 --port 8020
```

- Normbase OpenAPI：常见 <http://localhost:8001/docs>
- EDA OpenAPI：常见 <http://localhost:8002/docs>
- 平台 OpenAPI：<http://localhost:8020/docs>（路径前缀 `/api/v1`）

环境变量与首启建表说明见 [`aif_platform/README.md`](aif_platform/README.md)。

### 启动产品前端（Platform Web）

```bash
cd aif_platform/web
npm install
npm run dev
```

默认 <http://127.0.0.1:5173>，开发时通过 Vite 将 `/api` 代理到平台 API（默认 `http://127.0.0.1:8020`）。详见 [`aif_platform/web/README.md`](aif_platform/web/README.md)。

### 启动 Web 管理界面（Dashboard）

```bash
# AIF Technical Dashboard（默认端口 8010）
python -m dashboard.main
```

管理界面：<http://localhost:8010>

## 开发计划

详见 [background/plan.md](background/plan.md)

### 阶段进度

| Phase | 内容 | 状态 |
| --- | --- | --- |
| Phase 1 | 基础骨架 + CRUD + 管理UI | ✅ |
| Phase 2 | 检索核心 + 向量库 + 缓存 | ✅ |
| Phase 3 | 萃取流水线 + 审核UI | ✅ |
| Phase 4 | MCP集成 + API鉴权 | ✅ |
| Phase 5 | 打磨验证 + Demo | ⬜ |
| Phase 6 | EDA状态管理 + 持久化 | ✅ |
| Phase 7 | EDA推理引擎核心 | ⬜ |
| Phase 8 | 价值排序 + 合规校验 | ⬜ |
| Phase 9 | EDA端到端集成 | ⬜ |

说明：**Phase 3** 指「萃取 API + 过程 JSON + Dashboard 审核」的 **MVP**；与 `docs/norm-extraction-design.zh.md` **阶段 4**（解析管道、异步、长文/LLM 上下文）是后续增量，不在本表 Phase 3 范围内。

## API 说明

- **规范库（Normbase）** 对外 HTTP 示例（前缀 `/api/v1`，端口以本地配置为准）：
  - `GET /` — 健康检查
  - `GET /api/v1/norms` — 规范列表
  - `POST /api/v1/norms` — 创建规范
  - `GET /api/v1/norms/{id}` — 规范详情；创建以外的变更路由以 OpenAPI 为准
  - `GET /api/v1/retrieve` — 规范检索  
  完整列表以运行实例的 OpenAPI 为准（常见 <http://localhost:8001/docs>）。

- **产品线（Platform）**：注册登录、组织、场、规范代理、Agent 等，前缀 **`/api/v1`**，文档见 <http://localhost:8020/docs>（需先启动 `aif-platform`）。

- **EDA Agent**：常见 <http://localhost:8002/docs>。

## 测试数据

测试种子脚本位于 `scripts/dev/`:

- `seed_norms_api.py` - EU AI Act 测试规范（API 写入，支持外部种子文件）
- `seed_norms_db.py` - EU AI Act 测试规范（直写数据库）
