# 流程任务自动化 v2 - 上下文驱动产品设计

> 文档版本：v2.0  
> 创建时间：2026-06-02  
> 关联项目：AI Lab Agent Platform / Chat  
> 状态：产品设计交接版  
> 目标读者：产品、前端、后端、Agent Runtime、测试、业务接入方

---

## 1. 设计结论

流程任务自动化不应设计成单纯的“流程图驱动系统”。更合理的产品和技术抽象是：

> 参与者注册 + 上下文契约 + 监听行动规则 + 运行轨迹渲染。

其中：

- 上下文是执行发动机。
- 参与者是数据来源或执行者。
- 监听规则决定谁看到什么信息后采取什么行动。
- 流程图是管理态的解释层和观测层，不是唯一执行源。
- 用户态保持原有对话产品结构：左侧记录、中间会话、右侧 Canvas。

本版本相较 v1 的核心变化：

| 设计点 | v1 倾向 | v2 结论 |
| --- | --- | --- |
| 流程推进 | 源码编排和节点状态机推进 | 上下文变化触发，节点按监听规则响应 |
| 流程图 | 手写或从源码编排生成 | 从参与者、上下文、监听规则和真实运行轨迹生成 |
| 外部系统 | 节点或接口 | 虚拟参与者，只负责写上下文或提供回调 |
| Agent 协同 | A 调 B 或工作流串联 | 所有 Agent 只读写上下文，不直接互相握手 |
| 动态分支 | 流程定义中预置 | 由上游上下文决定，例如供应商清单生成 N 条分支 |
| 管理重点 | 节点是否完成 | 谁写了什么上下文、谁监听了它、谁因此被激活 |

---

## 2. 产品目标

### 2.1 要解决的问题

1. 业务流程包含多个外部系统、多个 Agent、多人协同，不能靠固定线性流程表达。
2. 上游节点可能没有明确结束态，可能多次补充数据。
3. 供应商等分支数量由上游数据决定，不能提前写死。
4. 平台无法控制所有外部系统，只能要求外部系统按约定写入上下文。
5. 管理员需要看懂全流程，但普通用户只需要处理当前会话和 Canvas。
6. 后续要支持 100 个流程、每个流程 100 个实例、每个实例 10 个以上节点。

### 2.2 设计目标

1. 支持注册流程参与者，包括 Agent、外部系统、人、Canvas 页面。
2. 支持定义统一上下文契约，让 API 和 Agent 都能精确写入和读取。
3. 支持监听上下文变化并触发行动。
4. 支持根据规则生成预期流程图。
5. 支持根据真实运行日志生成运行轨迹图。
6. 支持动态分支，例如供应商列表写入后生成供应商分支。
7. 支持用户通过外部链接直接进入对应节点会话。
8. 支持管理态按流程定义、实例、节点、上下文逐层查看。

### 2.3 非目标

1. 一期不做拖拽式低代码流程编排。
2. 一期不要求所有外部系统迁入平台。
3. 一期不要求外部系统一定是 Agent。
4. 一期不把运行细节暴露给普通用户。
5. 一期不做完整可视化调试器，只做规则校验、预览图和试运行样例。

---

## 3. 核心概念

### 3.1 流程自动化定义

流程自动化定义是一类业务自动化能力，例如“数据采购自动化”。它包含：

- 基础信息；
- 参与者注册；
- 上下文契约；
- 监听行动规则；
- 版本；
- 试运行样例。

一个流程自动化定义下面可以有多个流程实例。

### 3.2 流程实例

流程实例是一次真实业务项目，例如“语音数据采购项目”。实例由外部业务事件或平台接口创建。

实例必须有稳定标识：

| 字段 | 说明 |
| --- | --- |
| flowInstanceId | 平台流程实例 ID |
| flowAutomationCode | 流程自动化编码 |
| flowAutomationVersion | 创建实例时绑定的流程版本 |
| bizId | 外部业务对象 ID |
| instanceName | 用户可读实例名称，优先由上游传入 |
| sourceSystem | 实例来源系统 |

实例命名规则：

1. 上游必须优先传入 `instanceName`。
2. 如果未传入，平台用 `流程名称 + bizId` 兜底。
3. 如果 `bizId` 也缺失，平台用 `流程名称 + 日期 + 序号` 兜底。
4. 兜底名称只用于可用性，不能替代业务侧命名责任。

### 3.3 参与者

参与者是流程里会提供数据、消费数据或执行动作的对象。

参与者分四类：

| 类型 | 说明 | 是否由平台调度 |
| --- | --- | --- |
| agent | 平台内 Agent 或 Skill | 是 |
| external_platform | 外部系统或虚拟平台，只提供数据 | 否 |
| human | 人或角色，通常通过会话处理 | 部分 |
| canvas | 右侧业务页面或产物面板 | 部分 |

### 3.4 上下文

上下文是所有参与者协同的中心资产。API、Agent、人、Canvas 都只围绕上下文读写，不直接互相调用。

上下文不是普通 KV，必须包含：

```text
flowInstanceId + key + scope + entity + source + value + version
```

这样才能在多供应商、多节点、多 Agent 并发时精确取数。

### 3.5 监听行动规则

监听行动规则描述：

```text
谁看什么上下文
满足什么条件
采取什么行动
写回什么上下文
```

例如：

```ts
listen({
  key: 'supplier.poc_result',
  entityType: 'supplier',
  condition: 'value.status === "passed"',
  action: 'run_negotiation_agent',
  writes: ['supplier.negotiation_strategy'],
});
```

---

## 4. 总体架构

```mermaid
flowchart LR
  API["外部系统 / API"] --> C["上下文中心"]
  A["Agent / Skill"] --> C
  H["人 / 会话"] --> C
  V["Canvas 页面"] --> C
  C --> E["context.changed"]
  E --> R["监听规则匹配"]
  R --> A2["运行 Agent"]
  R --> S["创建会话"]
  R --> N["通知人"]
  R --> V2["更新 Canvas"]
  A2 --> C
  S --> C
  N --> C
  V2 --> C
  C --> G["运行轨迹图"]
```

运行机制：

1. 外部系统、Agent、人或 Canvas 写入上下文。
2. 平台生成 `context.changed` 事件。
3. 规则引擎匹配订阅该上下文的参与者。
4. 命中后执行行动，例如运行 Agent、创建会话、通知人、更新 Canvas。
5. 行动结果继续写入上下文。
6. 管理态基于上下文和运行事件生成流程图、轨迹图和节点详情。

---

## 5. 参与者注册

### 5.1 参与者基础字段

```ts
type Participant = {
  code: string;
  name: string;
  type: 'agent' | 'external_platform' | 'human' | 'canvas';

  owner: string;
  description?: string;

  provides: string[];
  watches: string[];
  actions?: ActionRule[];

  enabled: boolean;
};
```

字段说明：

| 字段 | 是否必填 | 说明 |
| --- | --- | --- |
| code | 是 | 全流程内唯一编码 |
| name | 是 | 展示名称 |
| type | 是 | 参与者类型 |
| owner | 是 | 负责人 |
| provides | 是 | 该参与者会写入哪些上下文 key |
| watches | 否 | 该参与者监听哪些上下文 key |
| actions | 否 | 命中监听后采取什么行动 |
| enabled | 是 | 是否启用 |

### 5.2 Agent 参与者字段

```ts
type AgentParticipant = Participant & {
  type: 'agent';
  agentCode: string;
  skillCodes: string[];
  runtime: 'web_agent' | 'cloud_worker' | 'server_agent';
  inputContextKeys: string[];
  outputContextKeys: string[];
  timeoutSeconds?: number;
  retryPolicy?: RetryPolicy;
};
```

Agent 必须声明：

- 自己能执行哪些 skill；
- 读哪些上下文；
- 写哪些上下文；
- 运行失败如何处理。

示例：

```ts
{
  code: 'risk_review_agent',
  name: '供应商风险评估 Agent',
  type: 'agent',
  owner: '萧落',
  agentCode: 'supplier_risk_agent',
  skillCodes: ['supplier_risk_check'],
  runtime: 'server_agent',
  watches: ['supplier.shortlist'],
  provides: ['supplier.risk_result'],
  actions: [
    {
      watch: 'supplier.shortlist',
      condition: 'value.suppliers.length > 0',
      actionType: 'run_agent',
      actionCode: 'supplier_risk_check',
      writes: ['supplier.risk_result']
    }
  ],
  enabled: true
}
```

### 5.3 外部系统参与者字段

```ts
type ExternalPlatformParticipant = Participant & {
  type: 'external_platform';
  systemCode: string;
  systemName: string;
  writeMode: 'api' | 'webhook' | 'manual_import';
  expectedPayloads: ContextPayloadContract[];
  contactOwner?: string;
};
```

外部系统必须声明：

- 它负责提供哪些上下文；
- 通过什么方式写入；
- payload 结构；
- 谁负责对接。

示例：

```ts
{
  code: 'sourcing_system',
  name: '寻源系统',
  type: 'external_platform',
  owner: '采购平台',
  systemCode: 'sourcing',
  systemName: '寻源系统',
  writeMode: 'api',
  provides: [
    'supplier.shortlist',
    'supplier.research_feedback'
  ],
  watches: [],
  expectedPayloads: [
    {
      key: 'supplier.shortlist',
      schemaVersion: 'v1',
      requiredFields: ['suppliers[].id', 'suppliers[].name', 'suppliers[].contact']
    }
  ],
  enabled: true
}
```

### 5.4 人工参与者字段

```ts
type HumanParticipant = Participant & {
  type: 'human';
  roleCode: string;
  assignmentMode: 'fixed_user' | 'role' | 'from_context';
  assigneeSource?: string;
  sessionTemplateCode?: string;
};
```

人工参与者通常不直接写底层接口，而是通过会话、表单或 Canvas 写回上下文。

示例：

```ts
{
  code: 'procurement_owner',
  name: '采购负责人',
  type: 'human',
  owner: '萧落',
  roleCode: 'procurement_owner',
  assignmentMode: 'from_context',
  assigneeSource: 'requirement.owner',
  watches: ['supplier.negotiation_exception'],
  provides: ['human.procurement_decision'],
  actions: [
    {
      watch: 'supplier.negotiation_exception',
      actionType: 'create_session',
      actionCode: 'open_procurement_review_session',
      writes: ['human.procurement_decision']
    }
  ],
  enabled: true
}
```

### 5.5 Canvas 参与者字段

```ts
type CanvasParticipant = Participant & {
  type: 'canvas';
  canvasCode: string;
  renderMode: 'artifact' | 'embedded_page' | 'structured_view';
  inputContextKeys: string[];
  outputContextKeys?: string[];
};
```

Canvas 负责展示产物和业务页面。若 Canvas 支持编辑，编辑结果必须写回上下文。

---

## 6. 上下文设计

### 6.1 上下文 Key 定义

每个上下文 key 需要先定义契约。

```ts
type ContextKeyDefinition = {
  key: string;
  label: string;
  description?: string;

  scope: 'instance' | 'node' | 'branch' | 'session' | 'global';
  valueType: 'json' | 'text' | 'markdown' | 'file_ref' | 'table' | 'decision';

  entityRequired: boolean;
  entityType?: string;

  providerCodes: string[];
  consumerCodes: string[];

  schemaVersion: string;
  jsonSchema?: unknown;

  retentionPolicy?: string;
  sensitiveLevel?: 'normal' | 'internal' | 'sensitive';
};
```

示例：

```ts
{
  key: 'supplier.risk_result',
  label: '供应商风险评估结果',
  scope: 'branch',
  valueType: 'decision',
  entityRequired: true,
  entityType: 'supplier',
  providerCodes: ['risk_review_agent'],
  consumerCodes: ['negotiation_agent', 'termsheet_agent'],
  schemaVersion: 'v1'
}
```

### 6.2 上下文记录字段

```ts
type ContextRecord = {
  id: string;

  flowAutomationCode: string;
  flowAutomationVersion: string;
  flowInstanceId: string;

  key: string;
  label: string;
  scope: 'instance' | 'node' | 'branch' | 'session' | 'global';

  entityType?: string;
  entityId?: string;
  entityName?: string;

  nodeCode?: string;
  participantCode: string;
  sessionId?: string;
  artifactId?: string;

  sourceType: 'api' | 'agent' | 'human' | 'canvas';
  source: ApiContextSource | AgentContextSource | HumanContextSource | CanvasContextSource;

  valueType: 'json' | 'text' | 'markdown' | 'file_ref' | 'table' | 'decision';
  value: unknown;
  summary?: string;

  version: number;
  status: 'active' | 'superseded' | 'invalid';
  confidence?: number;

  createdAt: string;
  updatedAt: string;
};
```

### 6.3 API 来源字段

API 来源用于记录外部系统写入。

```ts
type ApiContextSource = {
  systemCode: string;
  systemName: string;

  apiName: string;
  requestId: string;
  traceId?: string;

  bizId?: string;
  idempotencyKey?: string;

  payloadSchemaVersion?: string;
  rawPayloadRef?: string;
  receivedAt: string;
};
```

API 写入示例：

```ts
{
  key: 'supplier.shortlist',
  label: '候选供应商清单',
  scope: 'instance',
  participantCode: 'sourcing_system',
  sourceType: 'api',
  source: {
    systemCode: 'sourcing',
    systemName: '寻源系统',
    apiName: 'supplier.shortlist.push',
    requestId: 'REQ-20260602-001',
    bizId: 'PR-20260602-009',
    idempotencyKey: 'sourcing-shortlist-PR-20260602-009'
  },
  valueType: 'json',
  value: {
    suppliers: [
      { id: 'supplier_a', name: '供应商 A' },
      { id: 'supplier_b', name: '供应商 B' }
    ]
  },
  version: 1,
  status: 'active'
}
```

### 6.4 Agent 来源字段

Agent 来源用于记录 Agent 运行输出。

```ts
type AgentContextSource = {
  agentCode: string;
  agentName: string;

  runId: string;
  skillCode?: string;
  nodeCode?: string;

  model?: string;
  promptVersion?: string;

  inputContextIds: string[];
  outputArtifactIds?: string[];

  startedAt: string;
  finishedAt: string;
};
```

Agent 写入示例：

```ts
{
  key: 'supplier.risk_result',
  label: '供应商风险评估结果',
  scope: 'branch',
  entityType: 'supplier',
  entityId: 'supplier_b',
  entityName: '供应商 B',
  participantCode: 'risk_review_agent',
  sourceType: 'agent',
  source: {
    agentCode: 'risk_agent',
    agentName: '风险评估 Agent',
    runId: 'run_89312',
    skillCode: 'supplier_risk_check',
    nodeCode: 'risk_review',
    inputContextIds: ['ctx_supplier_shortlist_001'],
    startedAt: '2026-06-02T16:12:00+08:00',
    finishedAt: '2026-06-02T16:13:30+08:00'
  },
  valueType: 'decision',
  value: {
    level: 'medium',
    passed: true,
    reasons: ['经营状态正常', '存在轻微诉讼记录']
  },
  summary: '供应商 B 可继续推进，但需增加交付保障条款。',
  version: 1,
  status: 'active'
}
```

### 6.5 人工来源字段

```ts
type HumanContextSource = {
  userId: string;
  userName: string;
  roleCode?: string;
  sessionId?: string;
  messageId?: string;
  submittedAt: string;
};
```

### 6.6 Canvas 来源字段

```ts
type CanvasContextSource = {
  canvasCode: string;
  artifactId?: string;
  pageUrl?: string;
  operation: 'view' | 'edit' | 'submit' | 'approve';
  submittedAt: string;
};
```

### 6.7 精确取数规则

Agent 不能只靠 `key` 取数，必须组合查询。

最小查询条件：

```ts
getContext({
  flowInstanceId,
  key,
  scope,
  entityType,
  entityId,
  latest: true
});
```

取供应商 B 风险结果：

```ts
getContext({
  flowInstanceId: 'inst_001',
  key: 'supplier.risk_result',
  scope: 'branch',
  entityType: 'supplier',
  entityId: 'supplier_b',
  latest: true
});
```

取整个实例需求摘要：

```ts
getContext({
  flowInstanceId: 'inst_001',
  key: 'requirement.summary',
  scope: 'instance',
  latest: true
});
```

---

## 7. 监听行动规则

### 7.1 规则字段

```ts
type ActionRule = {
  id?: string;
  name?: string;

  participantCode: string;
  watch: string;
  scope?: 'instance' | 'node' | 'branch' | 'session' | 'global';
  entityType?: string;

  condition?: string;

  actionType:
    | 'run_agent'
    | 'create_session'
    | 'update_canvas'
    | 'notify_human'
    | 'write_context'
    | 'call_api'
    | 'wait';

  actionCode: string;
  reads?: string[];
  writes?: string[];

  idempotencyKey?: string;
  maxRunsPerEntity?: number;
};
```

### 7.2 规则示例

供应商清单写入后，启动风险评估：

```ts
{
  participantCode: 'risk_review_agent',
  watch: 'supplier.shortlist',
  condition: 'value.suppliers.length > 0',
  actionType: 'run_agent',
  actionCode: 'supplier_risk_check',
  reads: ['supplier.shortlist'],
  writes: ['supplier.risk_result']
}
```

POC 通过后，启动谈判 Agent：

```ts
{
  participantCode: 'negotiation_agent',
  watch: 'supplier.poc_result',
  scope: 'branch',
  entityType: 'supplier',
  condition: 'value.status === "passed"',
  actionType: 'run_agent',
  actionCode: 'generate_negotiation_strategy',
  reads: [
    'supplier.poc_result',
    'supplier.research_feedback',
    'supplier.risk_result'
  ],
  writes: ['supplier.negotiation_strategy']
}
```

Term Sheet 条款齐全后，更新 Canvas：

```ts
{
  participantCode: 'termsheet_canvas',
  watch: 'termsheet.clause_pack',
  condition: 'value.ready === true',
  actionType: 'update_canvas',
  actionCode: 'render_termsheet',
  reads: ['termsheet.clause_pack'],
  writes: ['termsheet.canvas_state']
}
```

异常谈判需要人工介入：

```ts
{
  participantCode: 'procurement_owner',
  watch: 'supplier.negotiation_exception',
  scope: 'branch',
  entityType: 'supplier',
  actionType: 'create_session',
  actionCode: 'open_negotiation_exception_session',
  reads: ['supplier.negotiation_exception'],
  writes: ['human.procurement_decision']
}
```

### 7.3 规则匹配结果

规则命中后要记录运行事件。

```ts
type ParticipantActivation = {
  id: string;
  flowInstanceId: string;
  participantCode: string;
  ruleId: string;

  triggerContextId: string;
  triggerKey: string;
  entityType?: string;
  entityId?: string;

  actionType: string;
  actionCode: string;

  status: 'queued' | 'running' | 'done' | 'failed' | 'skipped';
  inputContextIds: string[];
  outputContextIds: string[];
  artifactIds?: string[];
  sessionIds?: string[];

  startedAt?: string;
  finishedAt?: string;
};
```

这个表是运行轨迹图、节点激活次数、排障审计的核心来源。

---

## 8. 流程图生成

### 8.1 预期关系图

预期关系图从参与者和上下文关系自动生成：

```text
A provides key
B watches key
所以图上有 A -> key -> B
```

```mermaid
flowchart LR
  S["寻源系统"] --> K1["supplier.shortlist"]
  K1 --> R["风险评估 Agent"]
  R --> K2["supplier.risk_result"]
  K2 --> N["谈判 Agent"]
  P["POC 系统"] --> K3["supplier.poc_result"]
  K3 --> N
  N --> K4["supplier.negotiation_strategy"]
  K4 --> C["谈判会话 / Canvas"]
```

### 8.2 运行轨迹图

运行轨迹图来自真实发生过的 `context.changed` 和 `participant.activation`。

展示内容：

- 哪个参与者被激活；
- 被激活几次；
- 最近一次由哪个上下文触发；
- 读了哪些上下文；
- 写了哪些上下文；
- 创建了哪些会话；
- 产出了哪些 Canvas 产物。

### 8.3 动态分支

供应商分支不能写死。规则如下：

1. 上游写入 `supplier.shortlist`。
2. 平台读取 `value.suppliers`。
3. 对每个供应商生成一个 `entityType=supplier`、`entityId=supplier_x` 的分支上下文。
4. 监听 `supplier.*` 的 Agent 按 entity 维度执行。
5. 图上动态显示 N 条供应商分支。

```ts
{
  key: 'supplier.shortlist',
  value: {
    suppliers: [
      { id: 'supplier_a', name: '供应商 A' },
      { id: 'supplier_b', name: '供应商 B' },
      { id: 'supplier_c', name: '供应商 C' }
    ]
  }
}
```

---

## 9. 页面设计

### 9.1 用户态

用户态保持原有结构：

```text
左侧记录
中间会话
右侧 Canvas
```

用户只看：

- 待处理；
- 待查阅；
- 已完成。

用户不看：

- 监听规则；
- 投递；
- 事件总线；
- 运行时；
- 技术源码；
- 全量上下文表。

### 9.2 管理态入口

入口仍在：

```text
自动化
  ├─ 定时任务
  └─ 流程任务
```

点击“流程任务”后左侧导航自动收起，进入全屏管理态。

### 9.3 流程任务管理结构

```text
流程任务
  ├─ 流程自动化列表
  └─ 流程自动化详情
      ├─ 设计
      ├─ 实例
      └─ 版本
```

设计 Tab：

- 基础信息；
- 参与者；
- 上下文；
- 监听规则；
- 预览图；
- 试运行。

实例 Tab：

- 搜索；
- 状态筛选；
- 分页；
- 实例列表；
- 实例详情入口。

版本 Tab：

- 当前版本；
- 历史版本；
- 复制源码；
- 创建草稿。

### 9.4 新建流程自动化

新建时采用渐进式表单：

1. 基础信息
2. 参与者
3. 上下文
4. 监听规则
5. 预览与试运行

必填字段：

| 模块 | 字段 |
| --- | --- |
| 基础信息 | 名称、Owner、描述、入口事件 |
| 参与者 | code、name、type、owner、provides |
| 上下文 | key、scope、valueType、provider、consumer |
| 监听规则 | participantCode、watch、actionType、actionCode |

非必填字段：

| 字段 | 说明 |
| --- | --- |
| retryPolicy | 可用默认值 |
| timeoutSeconds | 可用默认值 |
| condition | 没有条件时只要 key 变化就触发 |
| jsonSchema | 一期可先用示例校验 |
| sensitiveLevel | 默认 normal |

### 9.5 实例详情

实例详情保持三类信息：

```text
概览
节点
上下文
```

概览：

- 预期关系图；
- 运行轨迹图；
- 最近激活；
- 当前待处理；
- 关键上下文摘要。

节点：

- 参与者列表；
- 激活次数；
- 最近触发 key；
- 最近状态；
- 关联会话；
- 关联产物。

上下文：

- 分类 Tab；
- key 搜索；
- entity 筛选；
- 来源筛选；
- 版本查看；
- 原始引用查看。

---

## 10. API 设计

### 10.1 创建流程自动化

```text
POST /api/flow-automations
```

请求体：

```ts
{
  code: 'data_procurement',
  name: '数据采购自动化',
  owner: '萧落',
  description: '承载数据采购的需求接入、寻源、合规、POC、谈判和归档。',
  entryEvent: 'data_procurement.request.created',
  participants: Participant[],
  contextKeys: ContextKeyDefinition[],
  actionRules: ActionRule[]
}
```

### 10.2 创建流程实例

```text
POST /api/flow-instances
```

请求体：

```ts
{
  flowAutomationCode: 'data_procurement',
  flowAutomationVersion: 'v2.0',
  bizId: 'PR-20260602-009',
  instanceName: '语音数据采购项目',
  sourceSystem: 'requirement_system',
  initialContext: [
    {
      key: 'requirement.summary',
      value: {
        category: '语音数据',
        purpose: '模型训练',
        owner: '萧落'
      }
    }
  ]
}
```

### 10.3 写入上下文

```text
POST /api/flow-instances/{flowInstanceId}/contexts
```

请求体：

```ts
{
  key: 'supplier.shortlist',
  scope: 'instance',
  participantCode: 'sourcing_system',
  sourceType: 'api',
  source: {
    systemCode: 'sourcing',
    apiName: 'supplier.shortlist.push',
    requestId: 'REQ-001',
    idempotencyKey: 'supplier-shortlist-PR-20260602-009'
  },
  valueType: 'json',
  value: {
    suppliers: [
      { id: 'supplier_a', name: '供应商 A' },
      { id: 'supplier_b', name: '供应商 B' }
    ]
  }
}
```

响应后平台自动：

1. 保存上下文；
2. 生成新版本；
3. 发出 `context.changed`；
4. 匹配监听规则；
5. 创建 activation。

### 10.4 查询上下文

```text
GET /api/flow-instances/{flowInstanceId}/contexts
```

查询参数：

| 参数 | 说明 |
| --- | --- |
| key | 上下文 key |
| scope | 作用域 |
| entityType | 实体类型 |
| entityId | 实体 ID |
| sourceType | api / agent / human / canvas |
| participantCode | 来源参与者 |
| latest | 是否只取最新 |

### 10.5 查询运行轨迹

```text
GET /api/flow-instances/{flowInstanceId}/activations
```

返回参与者激活记录，用于渲染运行轨迹。

---

## 11. 数据模型建议

### 11.1 flow_automation_definition

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 主键 |
| code | string | 流程编码 |
| name | string | 名称 |
| owner | string | Owner |
| description | text | 描述 |
| entry_event | string | 入口事件 |
| status | string | active / paused / archived |
| current_version | string | 当前版本 |
| created_at | datetime | 创建时间 |
| updated_at | datetime | 更新时间 |

### 11.2 flow_automation_version

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 主键 |
| automation_code | string | 流程编码 |
| version | string | 版本 |
| participants | json | 参与者注册 |
| context_keys | json | 上下文契约 |
| action_rules | json | 监听规则 |
| source_code | text | 可选源码 |
| created_by | string | 创建人 |
| published_at | datetime | 发布时间 |

### 11.3 flow_instance

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 主键 |
| automation_code | string | 流程编码 |
| automation_version | string | 版本 |
| biz_id | string | 外部业务 ID |
| instance_name | string | 实例名称 |
| source_system | string | 来源系统 |
| status | string | running / waiting / done / failed |
| created_at | datetime | 创建时间 |
| updated_at | datetime | 更新时间 |

### 11.4 flow_context_record

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 主键 |
| flow_instance_id | string | 实例 ID |
| key | string | 上下文 key |
| scope | string | 作用域 |
| entity_type | string | 实体类型 |
| entity_id | string | 实体 ID |
| entity_name | string | 实体名称 |
| participant_code | string | 来源参与者 |
| source_type | string | api / agent / human / canvas |
| source_payload | json | 来源元信息 |
| value_type | string | 值类型 |
| value_payload | json/text | 值 |
| summary | text | 摘要 |
| version | int | 版本 |
| status | string | active / superseded / invalid |
| created_at | datetime | 创建时间 |
| updated_at | datetime | 更新时间 |

### 11.5 flow_participant_activation

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| id | string | 主键 |
| flow_instance_id | string | 实例 ID |
| participant_code | string | 被激活参与者 |
| rule_id | string | 命中规则 |
| trigger_context_id | string | 触发上下文 |
| trigger_key | string | 触发 key |
| entity_type | string | 实体类型 |
| entity_id | string | 实体 ID |
| action_type | string | 动作类型 |
| action_code | string | 动作编码 |
| status | string | queued / running / done / failed / skipped |
| input_context_ids | json | 读取上下文 |
| output_context_ids | json | 写入上下文 |
| artifact_ids | json | 产物 |
| session_ids | json | 会话 |
| started_at | datetime | 开始时间 |
| finished_at | datetime | 完成时间 |

---

## 12. 数据采购样例

### 12.1 参与者

| 参与者 | 类型 | 提供 | 监听 |
| --- | --- | --- | --- |
| 需求系统 | external_platform | requirement.summary | 无 |
| 寻源系统 | external_platform | supplier.shortlist、supplier.research_feedback | requirement.summary |
| 分类分级 Agent | agent | requirement.classification、compliance.required_clause | requirement.summary |
| 风险评估 Agent | agent | supplier.risk_result | supplier.shortlist |
| POC 系统 | external_platform | supplier.poc_result | supplier.shortlist |
| 谈判 Agent | agent | supplier.negotiation_strategy、supplier.negotiation_exception | supplier.poc_result、supplier.risk_result |
| Term Sheet Canvas | canvas | termsheet.canvas_state | termsheet.clause_pack |
| 采购负责人 | human | human.procurement_decision | supplier.negotiation_exception |

### 12.2 关键上下文

| key | scope | entity | 来源 | 消费 |
| --- | --- | --- | --- | --- |
| requirement.summary | instance | 无 | 需求系统 | 寻源、分类分级 |
| supplier.shortlist | instance | 无 | 寻源系统 | 风险评估、POC |
| supplier.research_feedback | branch | supplier | 调研系统 | 谈判 Agent |
| supplier.risk_result | branch | supplier | 风险评估 Agent | 谈判 Agent、Term Sheet |
| supplier.poc_result | branch | supplier | POC 系统 | 谈判 Agent |
| compliance.required_clause | instance | 无 | 分类分级 Agent | Term Sheet |
| termsheet.clause_pack | branch | supplier | Term Sheet Agent | Canvas、谈判 Agent |
| supplier.negotiation_strategy | branch | supplier | 谈判 Agent | 采购会话 |
| human.procurement_decision | branch | supplier | 采购负责人 | 谈判 Agent |

### 12.3 运行样例

```mermaid
sequenceDiagram
  participant Req as 需求系统
  participant Ctx as 上下文中心
  participant Src as 寻源系统
  participant Risk as 风险评估 Agent
  participant Poc as POC 系统
  participant Neg as 谈判 Agent
  participant Chat as 采购会话

  Req->>Ctx: 写入 requirement.summary
  Ctx-->>Src: 命中监听
  Src->>Ctx: 写入 supplier.shortlist
  Ctx-->>Risk: 命中 supplier.shortlist
  Risk->>Ctx: 写入 supplier.risk_result
  Poc->>Ctx: 写入 supplier.poc_result
  Ctx-->>Neg: 命中 supplier.poc_result + risk_result
  Neg->>Ctx: 写入 supplier.negotiation_strategy
  Ctx-->>Chat: 创建采购会话
```

---

## 13. 验收标准

### 13.1 产品验收

1. 可以创建流程自动化定义。
2. 可以注册 Agent、外部系统、人、Canvas 四类参与者。
3. 可以定义上下文 key、scope、entity、provider、consumer。
4. 可以配置监听规则。
5. 可以从规则生成预期关系图。
6. 可以创建流程实例。
7. 外部系统可以通过 API 写上下文。
8. 上下文变化后可以生成 `context.changed`。
9. 命中规则后可以生成参与者激活记录。
10. 实例详情可以查看上下文表和运行轨迹。
11. 用户侧仍然进入原有会话和 Canvas。

### 13.2 技术验收

1. 上下文写入支持幂等键。
2. 上下文支持版本。
3. Agent 可按 `flowInstanceId + key + scope + entity` 精确取数。
4. 规则执行有运行记录。
5. 动态供应商分支按 entity 生成。
6. 失败状态可回查触发上下文和输入上下文。
7. 版本发布后，新实例绑定新版本，旧实例不自动迁移。

---

## 14. 一期开发拆分

### 14.1 前端

1. 新建流程自动化表单改造为五步：基础信息、参与者、上下文、监听规则、预览。
2. 流程任务管理页增加“设计 / 实例 / 版本”结构。
3. 设计 Tab 展示参与者列表、上下文契约、监听规则。
4. 预览图从 `provides` 和 `watches` 生成。
5. 实例详情增加运行轨迹视图。
6. 上下文 Tab 支持 key、entity、source、participant 筛选。

### 14.2 后端

1. 新增流程定义、版本、实例、上下文、激活记录表。
2. 提供流程定义 CRUD。
3. 提供流程实例创建接口。
4. 提供上下文写入接口。
5. 上下文写入后生成事件并匹配规则。
6. 提供上下文查询接口。
7. 提供激活记录查询接口。

### 14.3 Runtime

1. 支持规则匹配。
2. 支持 Agent action 执行。
3. 支持创建会话 action。
4. 支持 Canvas 更新 action。
5. 支持失败、重试、跳过。
6. 支持上下文读取 SDK。

---

## 15. 风险与边界

| 风险 | 说明 | 处理 |
| --- | --- | --- |
| 外部系统不配合写上下文 | 自动化闭环断掉 | 明确 API 契约，无法接入时只能人工补录 |
| 上下文 key 混乱 | Agent 无法精确取数 | 必须先定义 key 契约 |
| 监听规则过多 | 运行变成黑盒 | 所有 activation 必须记录触发 key 和输入输出 |
| 流程图与真实运行不一致 | 管理员困惑 | 区分预期关系图和运行轨迹图 |
| 上游没有结束态 | 状态机难以表达 | 以 context.changed 驱动，不强依赖完成态 |
| 动态分支复杂 | 多供应商、多轮返工 | 使用 entityType/entityId 表达分支 |

---

## 16. 结论

本方案的核心不是让平台预判所有业务流程，而是提供一种稳定的协同方式：

```text
先注册谁在场
再定义谁提供什么上下文
再定义谁监听什么上下文
最后由上下文变化驱动执行
```

这样既能支撑 6 月底定制交付，也能逐步沉淀成通用流程自动化能力。

