# PSMR AI-Facing API / MCP Contract v0.1

**AI-Native Program Semantic Mediation Runtime**  
**文件：** AI-Facing API / MCP Contract  
**版本：** v0.1  
**作者：** Neo.K  
**機構：** EveMissLab  
**日期：** 2026-09-15

**公司：** 一言諾科技有限公司  

---

## 0. 文件目的

本文件定義 AI Agent 如何存取 PSMR。

核心原則是：

> **AI 不應把 PSMR 當成另一個大型文字資料庫，而應把它視為可查詢、可運算、可驗證的語義工作空間。**

因此 AI-facing interface 不以「下載全部 Repository」為預設，而以：

$$
\boxed{
\text{Query}
\rightarrow
\text{Semantic Slice}
\rightarrow
\text{Operator}
\rightarrow
\text{Evidence}
}
$$

為基本互動模式。

此 Contract 可映射到：

- Local API；
- HTTP / RPC；
- MCP-compatible Tool Surface；
- Embedded Agent Runtime；
- IDE Agent Bridge；
- Cloud Agent Service。

本文定義的是**語義 Contract**，不綁定單一 transport。

---

# 一、設計目標

AI-facing interface 必須滿足：

1. Context Efficient
2. Evidence Grounded
3. Typed
4. Capability-Aware
5. Incremental
6. Auditable
7. Projection-Aware
8. Model-Agnostic

也就是：

$$
\boxed{
\text{AI Interface}
\neq
\text{Dump Entire Graph Into Prompt}
}
$$

---

# 二、API Surface 分層

PSMR AI-facing API 分為五層：

```text
Discovery
Query
Analysis
Modification
Execution / Verification
```

---

# 三、Discovery API

## 3.1 `workspace.describe`

用途：

> 告訴 AI 目前 Workspace 有什麼。

Request：

```json
{
  "workspace_id": "ws_..."
}
```

Response：

```json
{
  "workspace_id": "ws_...",
  "artifact_types": ["source_file", "git_revision"],
  "graph_types": ["cisg", "state", "motif"],
  "contract_types": ["test", "policy"],
  "available_operators": [],
  "capability_summary": {},
  "unknown_count": 0,
  "conflict_count": 0
}
```

---

## 3.2 `operator.list`

AI 不應假設系統一定有某個 Operator。

Request：

```json
{
  "workspace_id": "ws_...",
  "filter": {
    "input_type": "graph:cisg"
  }
}
```

---

## 3.3 `operator.describe`

返回：

```text
input contract
output contract
required capabilities
side effects
determinism
cache behavior
examples
```

---

# 四、Query API

## 4.1 `query.subgraph`

用途：

$$
\operatorname{Slice}(W,Q)
$$

Request：

```json
{
  "workspace_id": "ws_...",
  "anchor": {
    "kind": "symbol",
    "value": "pkg.auth.login"
  },
  "relations": [
    "calls",
    "called_by",
    "reads_state",
    "writes_state"
  ],
  "depth": 2,
  "include_evidence": true
}
```

Response 不必回傳整張 Graph，只回傳：

$$
G[S]
$$

---

## 4.2 `query.search`

搜尋：

```text
symbol
file
motif
finding
contract
state region
effect
boundary
artifact
```

搜尋結果必須返回 semantic identity，而不只顯示文字。

---

## 4.3 `query.evidence`

用途：

> 回到原始證據。

Request：

```json
{
  "evidence_ids": ["ev_1", "ev_2"]
}
```

Response 可包含：

```text
artifact reference
source span
runtime event
schema location
authority
status
```

---

## 4.4 `query.unknowns`

AI 必須可以主動查詢未知。

這是避免模型把缺失資訊自行補齊的重要介面。

---

## 4.5 `query.conflicts`

返回 Workspace 中未解決的 evidence / authority 衝突。

---

# 五、Analysis API

## 5.1 `analysis.impact`

```json
{
  "target": "semantic:pkg.auth.login",
  "depth": 3
}
```

Response：

```text
direct impact
derived impact
state coupling
boundaries
motifs
review files
likely tests
uncertainty
```

並保持：

$$
\text{Direct Impact}
\neq
\text{Derived Impact}
\neq
\text{Runtime Certainty}
$$

---

## 5.2 `analysis.semantic_diff`

Input：

```text
workspace A
workspace B
```

或：

```text
graph A
graph B
```

Output：

$$
\Delta G
$$

與 evidence。

---

## 5.3 `analysis.findings`

Filter：

```text
confirmed defect
anomaly
hotspot
```

三者不得合併。

---

## 5.4 `analysis.motifs`

可查：

```text
resource_scope
read_modify_write
boundary_adapter
stateful_orchestrator
```

未來可加入 domain-specific motifs。

---

## 5.5 `analysis.contracts`

輸出與目標節點相關的：

```text
precondition
postcondition
API contract
test contract
policy
intent constraint
```

---

# 六、Modification API

Modification API 不直接等同「寫檔」。

流程為：

$$
\text{Intent}
\rightarrow
\Delta W_{\mathrm{proposal}}
\rightarrow
\text{Validate}
\rightarrow
\text{Project}
\rightarrow
\text{Apply}
$$

---

## 6.1 `delta.propose`

Request：

```json
{
  "workspace_id": "ws_...",
  "intent": "Replace token validation without changing login behavior",
  "scope_refs": ["semantic:pkg.auth.login"],
  "constraints": []
}
```

Output：

```text
SemanticDelta
required assumptions
unknowns
affected contracts
suggested validation
```

預設 authority：

```text
ai_proposal
```

---

## 6.2 `delta.validate`

驗證：

```text
type compatibility
graph invariants
contracts
impact boundary
known defects
projection feasibility
```

---

## 6.3 `projection.preview`

把：

$$
\Delta W
$$

轉成：

```text
patch
source
test
schema
documentation
```

但不執行寫入。

---

## 6.4 `projection.apply`

這是 effectful operation。

需要：

$$
\operatorname{Cap}_{\mathrm{source-write}}
$$

或其他相應 capability。

---

# 七、Execution / Verification API

## 7.1 `execution.run_tests`

Effectful。

需要 process execution capability。

---

## 7.2 `verification.rebuild`

將投影後 artifact 重新導入 Workspace：

$$
Y
\xrightarrow{A}
W'
$$

---

## 7.3 `verification.roundtrip`

檢查：

$$
\Delta W_{\mathrm{intended}}
\stackrel{?}{\approx}
W'-W
$$

---

## 7.4 `verification.review`

輸出：

```text
new defects
resolved defects
semantic events
unexpected changes
unknowns
conflicts
```

---

# 八、AI Context Budget

每個 query 應接受：

```json
{
  "budget": {
    "max_nodes": 500,
    "max_edges": 1500,
    "max_evidence_items": 100,
    "max_text_bytes": 100000
  }
}
```

如果超出：

```text
truncated = true
continuation_token = ...
```

不得靜默截斷。

---

# 九、Semantic Slice Contract

返回 slice：

$$
S
=
(
N,
E,
K,
U,
C,
P
)
$$

其中：

- $N$：nodes；
- $E$：edges；
- $K$：contracts；
- $U$：unknowns；
- $C$：conflicts；
- $P$：provenance。

AI 不應只收到 Node / Edge 而看不到 Unknown。

---

# 十、Session 與 Workspace

AI Session 與 Workspace 必須分離。

$$
\text{Session}
\neq
\text{Workspace}
$$

Session 可結束。

Workspace 可以持續存在。

這使：

$$
\text{AI Context Lifecycle}
\neq
\text{Software Semantic Lifecycle}
$$

---

# 十一、Tool Result Envelope

建議所有 AI-facing tools 使用共同 envelope：

```json
{
  "schema": "psmr-tool-result-0.1",
  "request_id": "...",
  "status": "ok",
  "data": {},
  "evidence_refs": [],
  "unknown_refs": [],
  "conflict_refs": [],
  "warnings": [],
  "continuation": null
}
```

---

# 十二、錯誤類型

最低錯誤集合：

```text
WORKSPACE_NOT_FOUND
OBJECT_NOT_FOUND
INVALID_QUERY
TYPE_MISMATCH
CAPABILITY_DENIED
POLICY_BLOCKED
OPERATOR_UNAVAILABLE
UNSUPPORTED_PROJECTION
UNRESOLVED_REQUIRED_INPUT
CONFLICT_REQUIRES_REVIEW
EXECUTION_FAILED
VALIDATION_FAILED
```

---

# 十三、MCP-compatible Tool Surface

若映射為 MCP / tool calling，可提供：

```text
psmr_workspace_describe
psmr_query_subgraph
psmr_query_evidence
psmr_query_unknowns
psmr_impact
psmr_semantic_diff
psmr_findings
psmr_find_motif
psmr_get_contracts
psmr_delta_propose
psmr_delta_validate
psmr_projection_preview
psmr_projection_apply
psmr_verify_roundtrip
```

核心不依賴 MCP，但 MCP 是合理 transport 之一。

---

# 十四、禁止大型盲目輸出

預設不提供：

```text
dump_entire_workspace
dump_entire_repository
dump_entire_graph
```

若真的需要，應使用 export interface，而不是 Agent query interface。

---

# 十五、AI-facing API 與 Human-facing UI

Human UI：

$$
H(W)
$$

AI API：

$$
A(W)
$$

兩者共享同一 Workspace，但 Projection 不同。

因此：

$$
\boxed{
\text{Human View}
\neq
\text{AI View}
}
$$

但：

$$
\text{Underlying Semantic State}
$$

相同。

---

# 十六、AI 行為約束

AI-facing interface 應鼓勵：

```text
discover
query
slice
reason
propose
validate
project
verify
```

而不是：

```text
read everything
guess
rewrite
```

---

# 十七、第一版最小 API

PSMR Runtime v0.x 最小可先實作：

```text
workspace.describe
query.search
query.subgraph
query.evidence
query.unknowns
analysis.impact
analysis.semantic_diff
analysis.findings
analysis.motifs
analysis.contracts
```

也就是先做**只讀 AI semantic interface**。

修改能力可第二階段加入。

---

# 十八、與 PBSOI CISG v1.0 的映射

現有 PBSOI 可以直接支援：

```text
query.subgraph
query.evidence
analysis.impact
analysis.semantic_diff
analysis.findings
analysis.motifs
```

因此第一個 PSMR AI-facing Runtime 不需要重寫 analyzer。

只需要：

$$
\boxed{
\text{PBSOI Output}
\rightarrow
\text{Workspace}
\rightarrow
\text{AI-facing Contract}
}
$$

---

# 十九、結論

PSMR 的 AI-facing interface 不是讓模型「看到更多文字」，而是讓 AI 獲得：

$$
\boxed{
\text{Semantic Addressability}
}
$$

即：

> AI 可以直接定位、查詢、比較、運算與驗證軟體語義物件。

這是從：

$$
\text{AI reads code}
$$

走向：

$$
\boxed{
\text{AI operates software semantics}
}
$$

的必要接口。
