Files
devos/Docs/DevOS-Platform-v2/28_WORKFLOW_AUTOMATION_RUNTIME.md
phptits 851ccf1d7f v2 platform runtime (docs 22 Phase 2/4/7 + 17): Project/Environment + Config + Storage + Observability
- Project/Environment model with default environments (dev/staging/prod)
- Config Runtime: cascade resolution (platform→org→project→env), secrets via vault
- Storage Runtime: local provider, sha256 dedup, integrity check, file list/upload/delete
- Observability: execution query, per-action summary (success rate, avg, p95), health
- Realtime SSE: workspace event stream endpoint (GET /api/v1/v2/realtime/events)
- Phase 1 acceptance: core.health.check, core.user.create, core.user.list
- Actions: core.project.*, core.config.*, core.file.*, core.user.* (62 total)
2026-09-11 21:11:07 +00:00

67 KiB
Raw Permalink Blame History

28 — DEVOS WORKFLOW / AUTOMATION RUNTIME

Version: 1.0
Status: Architecture & Implementation Specification
Scope: DevOS Core Runtime
Priority: P1
Depends on: 03 Resource/Action、06 MCP/Skill/Agent、09 Task/Job/Queue、12 Versioning、16 Event、17 Observability、18 Configuration、25 Security、26 API、27 Plugin Runtime


1. 文档目标

本文件定义 DevOS 的统一:

  • Workflow Runtime
  • Workflow Definition
  • Workflow Version
  • Workflow Run
  • Workflow Node
  • Workflow Edge
  • Trigger
  • Condition
  • Branch
  • Loop
  • Parallel
  • Join
  • Wait
  • Delay
  • Approval
  • Human Task
  • Subworkflow
  • Schedule
  • Event Trigger
  • Webhook Trigger
  • Action Step
  • Query Step
  • Task Step
  • Agent Step
  • Expression
  • Variable
  • Checkpoint
  • Compensation
  • Workflow Template

以及它们与:

  • Action Runtime
  • Task Runtime
  • Event Runtime
  • Agent Runtime
  • Security Runtime
  • Configuration Runtime
  • Observability Runtime
  • Plugin Runtime
  • API Runtime
  • Project Factory

之间的边界。

核心目标:

Workflow 负责编排,不负责执行。


2. DevOS Workflow 的定位

DevOS Workflow 不是一个独立业务系统,也不是第二套 Agent Runtime。

Workflow 是 DevOS 的:

Declarative Deterministic Orchestration Runtime

即:

声明式、可追踪、可恢复、可暂停、可重放的确定性业务编排系统。

Workflow 用于表达:

A
 ↓
B
 ↓
判断
 ├── C
 └── D
 ↓
并行
 ├── E
 ├── F
 └── G
 ↓
汇合
 ↓
Approval
 ↓
H

Workflow 不应该负责:

  • 直接操作数据库
  • 直接调用 Redis
  • 直接调用第三方 API
  • 直接操作文件
  • 直接发送邮件
  • 直接运行 Shell
  • 直接执行模型
  • 自己实现 Retry Queue
  • 自己实现权限
  • 自己实现 Secret
  • 自己实现 Event Bus
  • 自己实现 Agent Loop

这些能力必须进入 DevOS Runtime。


3. Workflow 与其他 Runtime 的边界

这是 DevOS 最重要的边界之一。

                Workflow
                    │
             orchestration
                    │
       ┌────────────┼────────────┐
       ↓            ↓            ↓
     Action        Task         Agent
       │            │            │
       ↓            ↓            ↓
 Action Runtime  Task Runtime  Agent Runtime
       │            │            │
       └────────────┼────────────┘
                    ↓
                 Execution
                    ↓
                  Event

3.1 Action

Action 解决:

具体执行什么操作?

例如:

seo.website.scan
content.article.publish
github.repository.create
email.send
server.deploy

Action 是原子能力。


3.2 Task

Task 解决:

这项工作如何可靠地异步完成?

例如:

生成100篇文章
扫描1000个 URL
部署多个服务器
批量导入数据

Task 可以包含多个 Job。


3.3 Workflow

Workflow 解决:

这些步骤按照什么业务规则组织起来?

例如:

扫描网站
 ↓
分析结果
 ↓
如果评分 < 60
 ↓
生成优化建议
 ↓
人工审批
 ↓
执行优化

3.4 Agent

Agent 解决:

当路径不是完全预先确定时,应该如何动态解决目标?

Agent 可以:

Observe
 ↓
Plan
 ↓
Act
 ↓
Observe
 ↓
Evaluate
 ↓
Replan

Agent 可以动态选择 Skill / Capability / Action。

Workflow 通常不应该动态改变自身结构。


4. 四个核心边界

必须永久遵守:

Workflow = Orchestrate
Agent    = Reason
Action   = Execute
Task     = Durable Work

进一步:

Event    = Signal
Approval = Human Decision
Scheduler = Time Trigger
Plugin   = Capability Provider
MCP      = Capability Access/Transport

因此:

Workflow 不替代 Agent
Workflow 不替代 Action
Workflow 不替代 Task
Workflow 不替代 Event

5. 总体架构

                         Trigger
                            │
            ┌───────────────┼────────────────┐
            │               │                │
         Schedule          Event           Webhook
            │               │                │
            └───────────────┼────────────────┘
                            ↓
                    Workflow Definition
                            ↓
                    Workflow Version
                            ↓
                      Workflow Run
                            ↓
                    Workflow Engine
                            ↓
                 ┌──────────┼──────────┐
                 ↓          ↓          ↓
              Node       Condition   Parallel
                 │          │          │
                 ↓          ↓          ↓
              Action      Branch      Join
              Query
              Task
              Agent
              Approval
              Wait
              Delay
              Subworkflow
                 │
                 ↓
          DevOS Runtime Systems
                 │
        ┌────────┼─────────┐
        ↓        ↓         ↓
     Action     Task      Agent
     Runtime   Runtime    Runtime
        │        │         │
        └────────┼─────────┘
                 ↓
             Execution
                 ↓
               Event
                 ↓
        Observability / Audit

6. Workflow Definition

Workflow Definition 是 Workflow 的逻辑定义。

推荐:

WorkflowDefinition

包含:

interface WorkflowDefinition {
  id: string
  name: string
  description?: string

  namespace: string

  version: string

  status:
    | 'draft'
    | 'active'
    | 'deprecated'
    | 'archived'

  inputs: WorkflowInputDefinition[]

  variables?: WorkflowVariableDefinition[]

  triggers: WorkflowTriggerDefinition[]

  nodes: WorkflowNodeDefinition[]

  edges: WorkflowEdgeDefinition[]

  settings?: WorkflowSettings

  metadata?: Record<string, unknown>
}

7. Workflow Version

Workflow 必须不可变版本化。

例如:

seo.content.pipeline@1.0.0
seo.content.pipeline@1.1.0
seo.content.pipeline@2.0.0

禁止:

修改正在运行的 Workflow Version

正确方式:

v1 → immutable

修改
 ↓
创建 v2
 ↓
publish v2

已经运行的 Workflow Run:

继续使用 v1

新运行:

使用 v2

8. Workflow Run

Workflow Run 是 Workflow Definition 的一次实际执行。

interface WorkflowRun {
  id: string

  workflowId: string
  workflowVersion: string

  status:
    | 'pending'
    | 'running'
    | 'waiting'
    | 'paused'
    | 'completed'
    | 'failed'
    | 'cancelled'
    | 'timed_out'
    | 'partially_completed'

  actorId?: string

  organizationId: string
  projectId?: string
  environmentId?: string

  input: unknown

  startedAt?: Date
  completedAt?: Date

  correlationId: string

  metadata?: Record<string, unknown>
}

9. Workflow Run 必须锁定版本

Run 创建时必须记录:

workflowId
workflowVersion
runtimeVersion
pluginVersions
actionVersions
skillVersions
mcpVersions
configSnapshot

这样未来才能回答:

这个 Workflow 为什么当时这样执行?


10. Workflow Node

Node 是 Workflow 的执行单位。

第一版支持:

action
query
task
agent
condition
branch
parallel
join
loop
delay
wait
approval
human_task
subworkflow
webhook
transform

11. Action Node

示例:

- id: scan
  type: action
  action: seo.website.scan
  input:
    websiteId: ${inputs.websiteId}

执行:

Workflow
 ↓
Action Node
 ↓
Action Runtime
 ↓
Execution

Workflow 不允许:

prisma.website.find(...)

也不允许:

fetch(...)

必须:

actionRuntime.execute(...)

12. Query Node

Query Node 用于读取数据。

例如:

- id: website
  type: query
  query: seo.website.get
  input:
    id: ${inputs.websiteId}

Query 必须进入:

Data Runtime

而不是:

Workflow → Prisma

13. Task Node

当某个步骤本身是长时间异步工作时,可以使用 Task Node。

例如:

- id: generate
  type: task
  taskType: content.bulk_generate

运行:

Workflow Node
 ↓
Task Runtime
 ↓
Task
 ↓
Jobs
 ↓
Queue
 ↓
Workers

Workflow 不得重新实现:

Queue
Worker
Retry
Lease
Heartbeat

14. Agent Node

Agent Node 用于动态问题。

例如:

- id: analyze
  type: agent
  agent:
    skill: seo.content.analysis
    goal: |
      Analyze the website and recommend the highest-impact
      content improvements.

执行:

Workflow
 ↓
Agent Node
 ↓
Agent Runtime
 ↓
Agent Goal
 ↓
Agent Plan
 ↓
Skill / Capability
 ↓
Action

Workflow 只关心:

Agent 输入
Agent 状态
Agent 输出
Agent 是否成功

不保存或展示隐藏 Chain-of-Thought。


15. Agent Node 的重要边界

Agent Node 可以内部动态规划:

Agent
 ├── Action A
 ├── Action B
 ├── Skill C
 └── Replan

但 Workflow Engine 不应该接管 Agent 的内部推理。

Workflow 只看到:

Agent Started
Agent Completed
Agent Failed
Agent Result
Agent Artifacts

16. Condition Node

Condition 用于布尔判断。

例如:

- id: check_score
  type: condition
  expression: "${steps.scan.output.score < 60}"

输出:

true
false

然后进入 Branch。


17. Branch Node

例如:

- id: branch
  type: branch
  branches:
    - id: bad
      when: "${steps.scan.output.score < 60}"

    - id: good
      when: "${steps.scan.output.score >= 60}"

必须保证:

  • 条件可验证
  • 分支可追踪
  • 无隐式副作用
  • 默认分支明确
  • 类型合法

18. Expression Runtime

Workflow 不允许执行任意 JavaScript。

禁止:

expression: "eval(...)"

禁止:

expression: "${new Function(...)}"

禁止:

expression: "${require('child_process').exec(...)}"

必须使用受控表达式语言。

例如:

${inputs.websiteId}
${steps.scan.output.score}
${steps.scan.output.score < 60}
${variables.retryCount + 1}

允许:

比较
布尔运算
数学运算
字符串操作
数组操作
对象读取
有限内置函数

禁止:

文件系统
网络
Shell
动态 import
任意代码执行
数据库访问
Secret 读取

19. Variable

Workflow Variable 分为:

Input
Static Variable
Runtime Variable
Node Output
System Variable

例如:

inputs:
  websiteId:
    type: string

variables:
  retryCount:
    type: number
    default: 0

运行期间:

inputs.websiteId
variables.retryCount
steps.scan.output

20. Secret Variable

Secret 不允许进入普通 Workflow Variable。

错误:

variables:
  openaiKey: "sk-xxxx"

正确:

provider:
  credential: openai/default

或:

secret://openai/default

Workflow 可以引用 Secret Reference。

Workflow persistence 中:

只保存 Secret Reference

不能保存:

Secret Plaintext

21. Parallel Node

用于并行执行多个分支。

- id: parallel
  type: parallel
  branches:
    - generate
    - image
    - seo

实际:

              parallel
            /    |    \
           ↓     ↓     ↓
       generate image  seo
            \    |    /
                 ↓
                join

Parallel 必须受:

concurrency
quota
budget
rate limit
environment policy

控制。


22. Join Node

Join 用于并行汇合。

支持:

all
any
quorum

例如:

- id: join
  type: join
  policy: all

Quorum:

policy:
  type: quorum
  required: 2

23. Loop Node

Loop 必须显式存在。

禁止 Workflow 隐式无限循环。

例如:

- id: loop
  type: loop
  items: ${steps.urls.output}
  maxIterations: 1000

必须有:

maxIterations
timeout
budget

至少一个硬限制,生产环境建议同时存在。


24. Loop 的执行模型

不要:

Workflow Engine
  while(true)

而应该:

Loop Node
 ↓
Generate Iteration
 ↓
Create execution units
 ↓
Persist checkpoint
 ↓
Execute
 ↓
Persist result
 ↓
Next iteration

这样才能:

  • crash recovery
  • pause
  • resume
  • retry
  • observability

25. Delay Node

Delay 是时间等待。

例如:

- id: wait_10m
  type: delay
  duration: 10m

禁止 Worker:

await sleep(10 * 60 * 1000)

正确方式:

Delay Node
 ↓
Persist wakeAt
 ↓
Worker release
 ↓
Scheduler reactivates

Worker 不应该长期占用资源等待。


26. Wait Node

Wait 用于等待外部条件。

例如:

等待:
- Event
- Webhook
- Human action
- External callback

状态:

running
 ↓
waiting
 ↓
event received
 ↓
resume

27. Approval Node

Approval 必须复用:

Approval Runtime

例如:

- id: approve
  type: approval
  approval:
    risk: high
    title: Publish article

执行:

Workflow
 ↓
Approval Runtime
 ↓
pending
 ↓
approved / rejected / expired
 ↓
Workflow Resume

Workflow 不允许自己创建:

approval table
approval permission
approval policy

28. Human Task

Human Task 是比 Approval 更一般的人工任务。

例如:

审核文章
填写字段
选择方案
确认部署
处理异常

可以:

assign user
assign role
assign organization
assign project

完成后:

Human Task Result
 ↓
Workflow Resume

29. Subworkflow

Workflow 可以调用另一个 Workflow。

例如:

- id: publish_pipeline
  type: subworkflow
  workflow:
    id: content.publish
    version: 2.1.0

推荐默认:

Subworkflow 必须锁定版本。

禁止:

workflow: content.publish@latest

生产 Workflow 必须使用:

content.publish@2.1.0

30. Workflow Trigger

支持:

manual
schedule
event
webhook
action
resource
task
workflow

例如:

Event
 ↓
seo.website.scan.completed
 ↓
Workflow Trigger
 ↓
Workflow Run

31. Manual Trigger

用户可以从 UI/API:

Run Workflow

创建:

Workflow Run

必须经过:

Authentication
Authorization
Scope
Policy

32. Schedule Trigger

例如:

trigger:
  type: schedule
  cron: "0 2 * * *"
  timezone: "Asia/Tokyo"

执行:

Scheduler
 ↓
Trigger
 ↓
Workflow Run

Scheduler 不直接执行 Workflow Node。


33. Event Trigger

例如:

trigger:
  type: event
  event: seo.website.scan.completed

Event Runtime:

Event
 ↓
Subscription
 ↓
Workflow Trigger
 ↓
Workflow Run

必须处理:

deduplication
idempotency
ordering
scope
correlation
causation

34. Webhook Trigger

Webhook:

External System
 ↓
API
 ↓
Authentication
 ↓
Signature Verification
 ↓
Event
 ↓
Workflow Trigger

Webhook 不应该:

Webhook Controller
 ↓
直接运行 Workflow

而应该进入统一 Event/Trigger Runtime。


35. Trigger 去重

Webhook/Event/Scheduler 都可能重复触发。

因此 Trigger 必须支持:

idempotencyKey
eventId
deduplicationKey

例如:

workflowId
+
triggerType
+
eventId

构成唯一约束。


36. Workflow Execution

Workflow Run 本身不是 Action Execution。

关系:

WorkflowRun
   │
   ├── NodeRun
   │      │
   │      └── Action
   │              ↓
   │          Execution
   │
   └── Task
          ↓
         Job

因此:

Workflow Run ≠ Execution
Workflow Node Run ≠ Execution
Task ≠ Workflow

37. Node Run

推荐:

interface WorkflowNodeRun {
  id: string

  workflowRunId: string

  nodeId: string

  status:
    | 'pending'
    | 'running'
    | 'waiting'
    | 'retrying'
    | 'completed'
    | 'failed'
    | 'skipped'
    | 'cancelled'

  attempt: number

  input?: unknown
  output?: unknown

  startedAt?: Date
  completedAt?: Date

  executionId?: string
  taskId?: string

  errorCode?: string

  metadata?: Record<string, unknown>
}

38. Workflow Engine

Workflow Engine 负责:

读取 Workflow Definition
 ↓
解析 Node / Edge
 ↓
确定可执行 Node
 ↓
检查 Condition
 ↓
创建 Node Run
 ↓
调用 Runtime
 ↓
等待结果
 ↓
推进 Graph
 ↓
Checkpoint

Workflow Engine 不负责:

实际业务执行

39. Workflow Engine 的核心循环

逻辑模型:

Load Run
 ↓
Recover Checkpoint
 ↓
Find Ready Nodes
 ↓
Validate Scope
 ↓
Create Node Run
 ↓
Dispatch Runtime
 ↓
Observe Result
 ↓
Persist State
 ↓
Emit Event
 ↓
Find Next Nodes
 ↓
Continue / Wait / Complete

40. Crash Recovery

Workflow Engine 必须允许:

Worker Crash
Process Crash
Machine Crash
Network Failure
Redis Restart
Database Restart

之后恢复。

依赖:

PostgreSQL durable state
+
Task/Job Runtime
+
Checkpoint
+
Idempotency

41. Checkpoint

Workflow 需要持久化 checkpoint。

至少保存:

workflowRunId
currentNodes
completedNodes
waitingNodes
variables
nodeOutputs
loopState
parallelState
updatedAt

不要仅依赖:

memory
Redis only

42. Pause

Workflow 可以:

running
 ↓
paused

Pause 后:

不创建新的 Node Run

已经运行的 Action:

  • 默认允许完成
  • 高风险情况可以取消
  • 行为由 Policy 决定

43. Resume

paused
 ↓
resume
 ↓
load checkpoint
 ↓
validate current version
 ↓
continue

如果 Workflow Version 已经不兼容:

拒绝 Resume

或者进入:

Migration Required

44. Cancel

取消 Workflow:

Workflow Run
 ↓
cancel requested
 ↓
cancel pending nodes
 ↓
cancel active tasks when supported
 ↓
stop future scheduling
 ↓
persist cancellation

不能简单:

delete workflowRun

45. Retry

Retry 可以发生在:

Action Runtime
Task Runtime
Workflow Node
Workflow Run

但必须避免:

重复 Retry。

例如 Action Runtime 已经:

attempt 1
attempt 2
attempt 3

Workflow 不应该再无条件:

retry 3 times

否则可能:

3 × 3 = 9

次实际调用。


46. Retry Ownership

推荐规则:

Action transient failure
    → Action Runtime Retry

Task execution failure
    → Task Runtime Retry

Workflow control failure
    → Workflow Runtime Retry

Workflow Definition 可以声明策略:

retry:
  maxAttempts: 3
  backoff: exponential

但具体执行应委托给对应 Runtime。


47. Timeout

支持:

Node timeout
Workflow timeout
Task timeout
Agent timeout
Approval timeout
Wait timeout

例如:

settings:
  timeout: 24h

超时:

timed_out

并生成:

Workflow Event
Audit
Observability record

48. Idempotency

Workflow 默认不能假设:

exactly once

DevOS 默认:

at least once

因此所有副作用 Action 必须支持:

idempotencyKey

例如:

workflowRunId
+
nodeId
+
attempt

或者业务级:

projectId
+
operation
+
businessKey

49. Exactly Once 的正确理解

不要宣传:

Workflow Exactly Once Execution

正确表述:

At-least-once orchestration + idempotent side effects

这样才能真实面对:

网络超时
Worker Crash
Response Lost
Retry
Duplicate Delivery

50. Compensation / Saga

长 Workflow 不应该依赖:

一个数据库事务

例如:

Create Order
 ↓
Charge Payment
 ↓
Provision Server
 ↓
Send Email

不能:

BEGIN
...
COMMIT

整个 Workflow。

应该支持:

Forward Action
 ↓
Compensation Action

例如:

Charge Payment
 ↓
Provision Failed
 ↓
Refund Payment

这属于:

Saga / Compensation

51. Compensation 定义

例如:

- id: charge
  type: action
  action: payment.charge

  compensation:
    action: payment.refund

Compensation 必须:

  • 显式定义
  • 可审计
  • 可重试
  • 可取消
  • 有权限
  • 有风险级别

52. Error Handling

Workflow 错误至少分为:

validation_error
authorization_error
scope_error
configuration_error
provider_error
network_error
timeout_error
rate_limit_error
business_error
dependency_error
internal_error

每个错误应该有:

code
message
retryable
severity
fingerprint

53. Workflow Failure Policy

Workflow 可以定义:

fail_fast
continue
fallback
retry
compensate
manual_intervention

例如:

onError:
  strategy: manual_intervention

错误进入:

Human Task

54. Dead Letter

无法自动继续的 Workflow 可以进入:

Workflow DLQ

例如:

workflow failed
 ↓
retry exhausted
 ↓
DLQ
 ↓
operator review
 ↓
retry / resume / migrate / cancel

不能简单删除失败 Run。


55. Replay

Workflow 必须支持有限 replay。

Replay 不是:

从头无条件再次执行所有副作用

而应该支持:

Replay for diagnosis
Replay from checkpoint
Replay failed node
Replay with new version

生产副作用 Replay 必须显式确认。


56. Workflow Data Model

至少包括:

workflow_definitions
workflow_versions
workflow_triggers
workflow_schedules
workflow_runs
workflow_node_runs
workflow_variables
workflow_checkpoints
workflow_artifacts
workflow_templates

57. WorkflowDefinition

id
namespace
name
description
currentVersion
status
organizationId
projectId
createdBy
createdAt
updatedAt

58. WorkflowVersion

id
workflowId
version
definition
checksum
status
createdBy
createdAt
publishedAt
deprecatedAt

Definition 建议:

JSONB

但必须经过:

Schema Validation
Semantic Validation
Graph Validation
Capability Validation
Security Validation

59. WorkflowRun

id
workflowId
workflowVersion
organizationId
projectId
environmentId
actorId
status
input
correlationId
startedAt
completedAt
createdAt
updatedAt

60. WorkflowNodeRun

id
workflowRunId
nodeId
status
attempt
input
output
executionId
taskId
error
startedAt
completedAt

61. WorkflowCheckpoint

id
workflowRunId
sequence
state
createdAt

Checkpoint 必须支持:

resume
recovery
diagnostics

62. Graph Validation

Workflow Publish 前必须检查:

所有 Node ID 唯一
所有 Edge 合法
所有引用 Node 存在
Trigger 合法
起点存在
终点可达
无非法 Cycle
Loop 显式声明
所有 Action 存在
所有 Query 存在
所有 Skill 存在
所有 Workflow 存在
Expression 合法
Input 类型正确
Output 类型正确
权限可满足

63. Cycle Validation

普通 DAG:

A → B → C

合法。

普通 Cycle:

A → B → C → A

默认非法。

Loop:

A → Loop → B
       ↑
       └── explicit loop

可以合法。


64. Unreachable Node

以下必须报错:

Start → A → B

C → D

因为:

C / D

不可达。

除非它们被定义为:

separate trigger entry

65. Type Validation

例如:

Action Output:
{
  score: number
}

下一个节点:

condition:
${steps.scan.output.score < 60}

合法。

如果:

${steps.scan.output.score.foo}

则 Publish 阶段应尽可能发现。


66. Capability Validation

Workflow Publish 时检查:

Action Registry
Query Registry
Skill Registry
Agent Registry
Workflow Registry
Plugin Registry

例如:

seo.website.scan

不存在:

Publish Failed

而不是运行时才发现。


67. Security Validation

Workflow Publish / Run 都必须检查:

Actor
Organization
Project
Environment
Permission
Policy
Scope
Capability
Plugin
Credential

Workflow 不能因为它是“自动化”就获得更高权限。


68. Workflow Security Context

Workflow Run 继承:

actor
organization
project
environment
permissions
roles
scopes
policy

每一个 Action:

Workflow
 ↓
Action
 ↓
SecurityContext
 ↓
Authorization
 ↓
Scope
 ↓
Action Runtime

69. Agent 权限

如果 Workflow 调用 Agent:

Workflow Permission
∩
Agent Policy
∩
Actor Delegated Permission
∩
Project Scope

得到实际权限。

Agent 不得:

自动升级权限

70. Production Protection

Production Workflow 应支持:

protected environment
approval required
restricted actions
restricted plugins
restricted credentials
restricted network

例如:

production.deploy

可能要求:

Approval

71. Concurrency

Workflow 需要限制:

per workflow
per project
per organization
per environment
per node

例如:

settings:
  concurrency:
    maxRuns: 10

72. Duplicate Run Policy

可以配置:

allow
reject
queue
replace
deduplicate

例如:

同一个 project 每次只能运行一个 deploy workflow

第二次:

queue

或者:

reject

73. Rate Limit

Workflow 必须尊重:

Action Rate Limit
Provider Rate Limit
Organization Quota
Project Quota
Agent Budget

Workflow 自己不能绕过。


74. Budget

Workflow 可以设置:

maxDuration
maxActions
maxTasks
maxIterations
maxCost
maxTokens
maxNetworkCalls

例如:

budget:
  maxActions: 500
  maxDuration: 2h
  maxCost: 10

超过:

Workflow Budget Exceeded

75. Artifact

Workflow 可以产生:

File
Artifact
Report
Dataset
Log

必须进入:

Storage / Artifact Runtime

而不是:

workflow directory

76. Workflow Event

Workflow 本身产生事件:

workflow.created
workflow.published
workflow.started
workflow.paused
workflow.resumed
workflow.completed
workflow.failed
workflow.cancelled
workflow.timed_out
workflow.node.started
workflow.node.completed
workflow.node.failed
workflow.waiting

这些进入:

Event Runtime

77. Workflow 与 Event 的关系

Workflow 可以:

Event → Trigger Workflow

Workflow 也可以:

Workflow → Emit Event

例如:

content.article.published

但是 Event 发布必须走:

Event Runtime

而不是 Workflow 自己实现 Event Bus。


78. Outbox

如果 Workflow Node 完成同时需要:

DB State
+
Event

必须使用:

Outbox Pattern

保证:

State persisted
+
Event eventually published

避免:

DB 成功
Event 丢失

79. Observability

每个 Workflow 必须可追踪:

workflowRunId
workflowNodeRunId
executionId
taskId
jobId
requestId
correlationId
traceId
actorId
organizationId
projectId
environmentId

推荐:

Workflow
 ↓
Node
 ↓
Execution / Task
 ↓
Event

形成完整 Trace。


80. Workflow Timeline

UI 应显示:

10:00 Workflow Started
10:01 Scan Started
10:03 Scan Completed
10:03 Analysis Started
10:05 Analysis Completed
10:05 Approval Pending
11:20 Approval Approved
11:20 Publish Started
11:21 Publish Completed

这是 Workflow 最重要的运维能力之一。


81. Audit

以下必须进入 Audit:

Workflow Created
Workflow Updated
Workflow Published
Workflow Deprecated
Workflow Run
Workflow Pause
Workflow Resume
Workflow Cancel
Workflow Retry
Workflow Version Migration
Approval
Manual Intervention
Production Execution

Audit 不等于普通 Log。


82. Workflow UI

UI Shell 提供:

Workflow List
Workflow Detail
Workflow Editor
Workflow Version
Workflow Diff
Workflow Run
Node Run
Execution Detail
Timeline
Logs
Artifacts
Retry
Pause
Resume
Cancel

83. Workflow Editor

可使用:

React Flow

或其他成熟 Graph Editor。

但:

UI Editor 不是 Workflow Runtime。

UI 负责:

Graph Editing
Schema Editing
Validation Feedback

最终生成:

Workflow Definition

84. Visual Editor 的原则

用户拖拽:

Action
Condition
Parallel
Approval

最终必须转换成:

Declarative Workflow Definition

而不是:

UI state

作为真正运行状态。


85. Workflow Run UI

必须能看到:

Status
Started
Duration
Current Node
Completed Nodes
Waiting Nodes
Failed Nodes
Tasks
Executions
Artifacts
Events
Errors
Approvals

86. Node Detail UI

Node Detail:

Input
Output
Status
Attempts
Execution
Task
Error
Retry
Logs
Trace
Artifacts

Secret:

永远 Mask

87. Workflow Template

Workflow 可以模板化。

例如:

SEO Website Audit
Content Publishing
Deployment Pipeline
Data Import
Lead Processing
Backup Pipeline

Template:

parameters
variables
triggers
nodes
edges

可以由:

Plugin
Module
Project Factory
Marketplace

提供。


88. Plugin Workflow Contribution

Plugin 可以提供:

Workflow Node
Workflow Template
Workflow Trigger
Workflow Action
Workflow Query

例如 GitHub Plugin:

github.pull_request.opened
github.repository.updated

可以成为 Workflow Trigger。

但 Plugin:

不得创建自己的 Workflow Engine。


89. Plugin Node

Plugin 可以注册:

plugin.github.pull_request.wait

但真正执行:

Plugin Action
 ↓
Action Runtime

90. Agent 创建 Workflow

Agent 可以根据自然语言生成:

Workflow Draft

例如:

每天凌晨扫描所有网站,如果 SEO 分数低于 60,就生成优化建议并提交人工审批。

Agent 可以生成:

Schedule
 ↓
Scan
 ↓
Condition
 ↓
Agent
 ↓
Approval
 ↓
Action

但:

Agent 生成的 Workflow 默认必须是 Draft。


91. Agent 不应直接发布高风险 Workflow

推荐:

Agent
 ↓
Draft Workflow
 ↓
Validation
 ↓
Security Check
 ↓
Human Approval
 ↓
Publish

特别是:

Production
Financial
Deletion
Deployment
Credential
External communication

等高风险 Workflow。


92. Workflow 与 Skill

Skill 是:

How to solve a domain problem

Workflow 是:

How to orchestrate known steps

例如:

Skill:
SEO Content Analysis

Workflow:
Scan
 ↓
SEO Analysis Skill
 ↓
Approval
 ↓
Publish

Skill 可以被 Workflow 调用,但不能替代 Workflow Engine。


93. Workflow 与 MCP

MCP:

Capability Access / Transport

Workflow:

Orchestration

所以:

Workflow
 ↓
Action / Capability
 ↓
MCP
 ↓
External System

MCP 不得绕过:

Security
Action Runtime
Audit
Observability

94. API

推荐:

GET    /api/v1/workflows
POST   /api/v1/workflows
GET    /api/v1/workflows/:id
POST   /api/v1/workflows/:id/versions
POST   /api/v1/workflows/:id/publish
POST   /api/v1/workflows/:id/run

GET    /api/v1/workflow-runs/:id
POST   /api/v1/workflow-runs/:id/pause
POST   /api/v1/workflow-runs/:id/resume
POST   /api/v1/workflow-runs/:id/cancel
POST   /api/v1/workflow-runs/:id/retry

所有 API:

Authentication
Authorization
Scope
Policy
Action/Workflow Runtime

95. CLI

推荐:

devos workflow list

devos workflow create

devos workflow validate workflow.yaml

devos workflow publish workflow.yaml

devos workflow run seo.audit

devos workflow runs

devos workflow inspect <run-id>

devos workflow pause <run-id>

devos workflow resume <run-id>

devos workflow cancel <run-id>

devos workflow retry <run-id>

96. YAML 示例

完整示例:

id: seo.content.pipeline

name: SEO Content Pipeline

version: 1.0.0

inputs:
  websiteId:
    type: string
    required: true

trigger:
  type: manual

nodes:

  - id: scan
    type: action
    action: seo.website.scan
    input:
      websiteId: ${inputs.websiteId}

  - id: analyze
    type: agent
    agent:
      skill: seo.content.analysis
      goal: Analyze the website SEO results

  - id: quality
    type: condition
    expression: ${steps.scan.output.score < 60}

  - id: approval
    type: approval
    approval:
      risk: medium
      title: Approve SEO optimization

  - id: optimize
    type: action
    action: seo.website.optimize
    input:
      websiteId: ${inputs.websiteId}

edges:

  - from: scan
    to: analyze

  - from: analyze
    to: quality

  - from: quality
    to: approval
    when: ${steps.scan.output.score < 60}

  - from: approval
    to: optimize
    when: ${steps.approval.output.approved == true}

97. Workflow Runtime API

核心接口:

interface WorkflowRuntime {
  createDefinition(
    input: CreateWorkflowInput
  ): Promise<WorkflowDefinition>

  validate(
    definition: WorkflowDefinition
  ): Promise<WorkflowValidationResult>

  publish(
    workflowId: string,
    version: string
  ): Promise<void>

  start(
    workflowId: string,
    input: unknown,
    context: SecurityContext
  ): Promise<WorkflowRun>

  pause(
    runId: string
  ): Promise<void>

  resume(
    runId: string
  ): Promise<void>

  cancel(
    runId: string
  ): Promise<void>

  retry(
    runId: string,
    options?: RetryOptions
  ): Promise<void>
}

98. Workflow Engine API

interface WorkflowEngine {
  startRun(runId: string): Promise<void>

  continueRun(runId: string): Promise<void>

  executeNode(
    runId: string,
    nodeId: string
  ): Promise<void>

  resumeWaitingNode(
    runId: string,
    nodeId: string,
    event: unknown
  ): Promise<void>

  recover(runId: string): Promise<void>
}

99. Workflow Registry

Workflow 必须进入 Registry。

Registry 可以提供:

find workflow
find version
find trigger
find template
find node

例如:

workflowRegistry.resolve(
  'seo.content.pipeline',
  '1.0.0'
)

100. Workflow Capability Discovery

Agent 不需要看到全部 Workflow Definition。

可以采用:

Level 1
Workflow summary

Level 2
Inputs / Outputs

Level 3
Full schema

Level 4
Instructions

保持:

Progressive Disclosure

避免给模型发送大量 Workflow JSON。


101. Workflow Import / Export

支持:

YAML
JSON

导出时必须:

去除 Secret Plaintext

并可包含:

workflow version
dependencies
required capabilities
required plugins

102. Workflow Dependency

Workflow 可能依赖:

Plugin
Action
Query
Skill
Agent
Provider
Credential
Subworkflow

Publish 前检查依赖。


103. Dependency Lock

生产 Workflow 建议生成:

workflow.lock

记录:

Workflow Version
Plugin Version
Action Version
Skill Version
MCP Version
Provider Version

避免:

latest

造成不可复现。


104. Workflow Migration

如果:

v1

正在运行。

然后:

v2

修改了:

Node ID
Input
Output
Graph
Action

旧 Run 默认继续使用:

v1

如果需要迁移:

Workflow Migration
 ↓
Validate Mapping
 ↓
Checkpoint Conversion
 ↓
Security Revalidation
 ↓
Resume

105. Node ID 是稳定标识

Node ID 不是 UI 临时 ID。

例如:

scan
analyze
approval
publish

运行历史依赖 Node ID。

因此:

修改 Node ID 应视为兼容性变化。


106. Workflow Schema Version

Definition Schema 本身也要版本化:

schemaVersion: "1"

未来:

schemaVersion: 2

通过 Migration Runtime 转换。


107. Workflow Definition 不可变原则

发布之后:

Immutable

如果修改:

Create New Version

禁止:

UPDATE published_definition

108. Database Transaction

Workflow Engine 可以使用短数据库事务保存状态:

Node State
Checkpoint
Outbox

但不能:

一个 Workflow Run = 一个长事务

109. Workflow State Machine

Definition:

draft
 ↓
active
 ↓
deprecated
 ↓
archived

Run:

pending
 ↓
running
 ↓
waiting
 ↓
running
 ↓
completed

异常:

running
 ↓
failed

running
 ↓
cancelled

running
 ↓
timed_out

running
 ↓
paused

110. Workflow Node State Machine

pending
 ↓
running
 ↓
completed

或者:

running
 ↓
failed
 ↓
retrying
 ↓
running

或者:

running
 ↓
waiting
 ↓
running

111. Event-driven Resume

例如 Approval:

Workflow
 ↓
Approval Pending
 ↓
Workflow Node = waiting

之后:

Approval Approved Event
 ↓
Event Runtime
 ↓
Workflow Resume Handler
 ↓
Node Completed
 ↓
Next Node

不能:

Worker 永久等待

112. Scheduler Integration

Scheduler 只负责:

什么时候触发

Workflow Runtime 负责:

触发后运行什么

因此:

Scheduler ≠ Workflow Engine

113. Task Integration

长时间 Workflow:

Workflow Run

本身可以是:

Task-backed execution

但不要重复创建第二套 Task 系统。

推荐:

Workflow Run
    │
    └── Task Runtime metadata

具体长任务:

Workflow Node
 ↓
Task
 ↓
Jobs

114. Queue Integration

Workflow Engine 可以通过 Queue 驱动:

workflow.resume
workflow.node.execute
workflow.trigger
workflow.timeout
workflow.wakeup

Queue 仍然属于:

Task/Queue Runtime

Workflow 不创建私有 Queue。


115. Worker Integration

Worker:

领取 Workflow Engine Job
 ↓
Load Workflow State
 ↓
Execute one orchestration step
 ↓
Persist state
 ↓
Exit

不要:

Worker 永久持有 Workflow

这样才能水平扩展。


116. Horizontal Scaling

可以运行:

Worker 1
Worker 2
Worker 3
Worker 4

共同处理:

Workflow Runs

依赖:

DB locking
Lease
Idempotency
Queue
Checkpoint

117. Concurrency Control

必须防止:

Worker A
+
Worker B

同时推进同一个 Workflow Run。

推荐:

workflowRunId lease

或者:

optimistic locking

例如:

version = version + 1

CAS 更新。


118. Workflow Run Lock

推荐:

workflow_run.version

每次状态更新:

WHERE id = ?
AND version = ?

成功:

version++

否则:

concurrent update

然后重新读取。


119. Artifact Lineage

Workflow Artifact 必须记录:

workflowRunId
nodeRunId
executionId
taskId
createdBy
createdAt
source
version
checksum

这样可以回答:

这个报告是谁生成的?

以及:

这个文件是哪个 Workflow 的哪个步骤产生的?


120. Workflow Security Boundaries

禁止:

Workflow → Prisma
Workflow → Redis
Workflow → Raw SQL
Workflow → Secret DB
Workflow → filesystem
Workflow → shell
Workflow → Docker socket
Workflow → external API

正确:

Workflow
 ↓
Action / Query / Task / Agent
 ↓
对应 Runtime

121. Architecture Import Rules

建议 ESLint / dependency-cruiser / Nx boundaries 禁止:

workflow package
  ↓
@prisma/client

禁止:

workflow
  ↓
redis client

禁止:

workflow
  ↓
provider SDK

Workflow 只能依赖:

workflow contracts
action runtime
task runtime
event runtime
security runtime
data runtime
config runtime
observability

122. Package Structure

推荐:

packages/
  workflow/
  workflow-schema/
  workflow-runtime/
  workflow-engine/
  workflow-expression/
  workflow-trigger/
  workflow-template/
  workflow-sdk/

如果规模较小,可以先合并:

packages/workflow/

但逻辑边界必须存在。


123. Workflow Package Responsibilities

workflow/
  ├── definitions
  ├── versions
  ├── registry
  ├── validation
  └── public API

workflow-runtime/
  ├── run lifecycle
  ├── state
  ├── checkpoint
  └── recovery

workflow-engine/
  ├── graph execution
  ├── node scheduling
  └── continuation

workflow-expression/
  ├── parser
  ├── evaluator
  └── type validation

workflow-trigger/
  ├── manual
  ├── schedule
  ├── event
  └── webhook

124. 不要过早引入重型 Workflow Engine

第一阶段不要因为“Workflow”三个字就直接把 DevOS 改造成:

BPMN Platform

或者:

Enterprise Workflow Suite

也不要立即引入大量:

复杂 BPMN
DMN
复杂规则引擎
复杂表单引擎

DevOS 第一阶段需要的是:

轻量、可靠、可扩展的 Action-Oriented Workflow Runtime。


125. 外部 Workflow Engine 的位置

未来如果规模达到:

百万级 Workflow Run
超长运行
复杂 Durable Execution
跨区域调度
极高可靠性

可以评估成熟基础设施,例如:

Temporal

但即使未来引入:

Temporal

也不能让 Temporal 成为 DevOS 的业务边界。

正确:

DevOS Workflow Contract
        ↓
Workflow Adapter
        ↓
Temporal

而不是:

业务代码
 ↓
Temporal SDK

这样未来仍然可以替换实现。


126. Workflow Adapter

建议抽象:

interface WorkflowExecutionBackend {
  start(runId: string): Promise<void>

  resume(runId: string): Promise<void>

  pause(runId: string): Promise<void>

  cancel(runId: string): Promise<void>
}

第一版:

DevOS Native Engine

未来:

Temporal Adapter

127. Workflow Certification

Workflow 可以定义认证等级:

Basic
Validated
Secure
Production Ready
Official

Production Ready 至少需要:

Schema Valid
Graph Valid
Capability Valid
Security Valid
Retry Valid
Timeout Valid
Observability Valid
Idempotency Valid

128. Workflow Test Model

必须支持:

Definition Test
Graph Test
Expression Test
Runtime Test
Integration Test
Security Test
Recovery Test
Migration Test

129. Deterministic Workflow Test

例如:

Input:
score = 50

预期:

scan
 ↓
condition = true
 ↓
approval

使用 Mock Action:

seo.website.scan

返回:

{
  "score": 50
}

验证:

Node sequence
Condition
Output
Final state

130. Workflow Test Fixture

测试环境:

Ephemeral PostgreSQL
Ephemeral Redis
Mock Action Registry
Mock Event Bus
Mock Task Runtime
Mock Agent Runtime
Fake Clock

Fake Clock 非常重要。

可以测试:

Delay
Timeout
Schedule
Approval Expiration

而不需要真的等待。


131. Required Workflow Tests

至少测试:

simple linear workflow
condition
branch
parallel
join
loop
delay
wait
approval
human task
subworkflow
agent
task
retry
timeout
cancel
pause
resume
crash recovery
duplicate trigger
idempotency
version pinning
migration
security
tenant isolation
production approval

132. Trigger Tests

必须测试:

manual trigger
schedule trigger
event trigger
webhook trigger
duplicate event
out-of-order event
invalid signature
expired event
wrong tenant event

133. Security Tests

至少:

IDOR
cross-tenant access
cross-project access
cross-environment access
unauthorized action
agent privilege escalation
plugin privilege escalation
secret leakage
production bypass
approval bypass

134. Crash Recovery Tests

模拟:

Worker killed
DB transaction interrupted
Network timeout
Action response lost
Queue duplicate
Redis unavailable

验证:

Workflow eventually resumes correctly

并且:

副作用不会无限重复

135. Workflow Contract Test

建立统一:

Workflow Contract Test Suite

所有 Workflow Engine Backend 都必须通过:

Native Engine
Temporal Adapter
Future Backend

这样 DevOS Runtime Contract 不被实现细节绑定。


136. API Contract Test

检查:

OpenAPI
Workflow Schema
Error Contract
Async Response
Task/Run relationship
Version behavior

137. Plugin Contract Test

Plugin 提供 Workflow Node 时必须验证:

manifest
capability
permission
schema
action
trigger
health
version
upgrade
disable

138. Workflow Marketplace

未来 Marketplace 可以发布:

Workflow Templates

例如:

SEO Audit Pipeline
GitHub Release Pipeline
Content Publishing Pipeline
Lead Qualification
Daily Backup
Server Deployment

Marketplace 条目必须包含:

version
dependencies
required permissions
required plugins
required providers
security level
author
checksum
signature

139. Workflow Template 安全

安装 Template 时:

Download
 ↓
Verify
 ↓
Validate
 ↓
Show Permissions
 ↓
Show Dependencies
 ↓
User Approval
 ↓
Install

不能:

Install
 ↓
立即拥有生产权限

140. Configuration

Workflow 可以引用:

Config
Provider
Credential
Environment

例如:

action: email.send

config:
  provider: smtp/default

实际 Credential 由:

Credential Runtime

解析。


141. Environment

同一个 Workflow:

development
staging
production

可以拥有不同:

Config
Provider
Credential
Permission
Approval Policy

Workflow Definition 不应该硬编码:

production secret

142. Workflow Input Validation

Start Run 时必须:

Validate Input Schema
 ↓
Validate Security Scope
 ↓
Validate Dependencies
 ↓
Create Run

错误输入不能进入 Engine。


143. Workflow Output

Workflow 可以定义:

outputs:
  articleId:
    type: string

最终:

Workflow Run Output

可以用于:

API
Agent
Subworkflow
Event
UI

144. Workflow Event Output

完成后可以:

workflow.completed

payload 可以包含:

runId
workflowId
version
status
outputs
artifactIds

禁止包含:

Secret
内部敏感凭证
隐藏 Chain-of-Thought

145. Workflow Context

Workflow Context 建议:

interface WorkflowContext {
  runId: string
  workflowId: string
  workflowVersion: string

  actor: ActorContext

  organizationId: string
  projectId?: string
  environmentId?: string

  variables: WorkflowVariables

  correlationId: string
  signal: AbortSignal
}

146. Context 不等于 Memory

Workflow Context:

当前运行状态

Agent Memory:

长期 / 可检索上下文

两者必须分开。


147. Workflow 与 Agent Memory

Agent Node 可以读取:

Agent Memory Runtime

但 Workflow 不应直接访问:

memory tables

正确:

Workflow
 ↓
Agent Runtime
 ↓
Memory Runtime

148. Workflow Logging

每个 Node 应生成结构化日志:

workflowRunId
nodeRunId
nodeId
executionId
taskId

日志中禁止:

secret
token
password
credential
API key

149. Metrics

至少:

workflow_runs_total
workflow_runs_completed
workflow_runs_failed
workflow_run_duration
workflow_node_duration
workflow_node_failures
workflow_waiting_runs
workflow_retry_total
workflow_trigger_total
workflow_trigger_duplicates
workflow_active_runs

150. Workflow SLO

平台级可以定义:

Workflow Trigger Latency
Workflow Completion Rate
Workflow Recovery Time
Workflow Failure Rate
Node Success Rate

151. Workflow Doctor

建议:

devos workflow doctor

检查:

invalid definitions
missing capabilities
missing plugins
broken triggers
invalid expressions
version conflicts
stuck runs
expired approvals
dead letters
orphaned node runs

152. Stuck Workflow Detection

Workflow 可能长时间:

running

但没有任何 Progress。

Diagnostics 应检测:

last heartbeat
last state update
last node activity
last event

然后产生:

Potentially Stuck Workflow

153. Workflow Garbage Collection

历史 Run 不应无限增长。

根据:

retention policy
organization policy
project policy
environment policy

进行:

archive
purge

但:

Audit
Artifacts
Compliance data

可能需要更长保留。


154. Workflow Data Retention

不同数据:

Workflow Definition
Workflow Run
Node Run
Logs
Events
Artifacts
Audit

分别拥有 retention。

不能统一:

delete after 7 days

155. Workflow Performance

优化优先级:

Database state updates
Queue throughput
Node scheduling
Expression evaluation
Event delivery

不要一开始就优化:

Graph rendering

真正瓶颈通常在:

Durable State
External Provider
Queue
DB

156. Batch Workflow

大量对象:

10000 URLs
1000 articles
500 servers

不要创建:

10000 independent Workflow Runs

除非业务确实需要。

可以:

One Workflow
 ↓
Batch Node
 ↓
Task
 ↓
Jobs

或者:

Workflow
 ↓
Loop
 ↓
Task Batch

157. Workflow Fan-out 限制

必须防止:

1 Node
 ↓
1,000,000 Nodes

造成平台雪崩。

限制:

maxFanOut
maxIterations
maxParallelism
maxTasks
maxCost

158. Backpressure

Workflow 必须尊重:

Queue capacity
Worker capacity
Provider rate limit
Project quota
Organization quota

当系统拥塞:

Workflow waits

而不是:

无限创建 Job

159. Workflow Budget

推荐最终预算模型:

Workflow Budget
 ├── Runtime
 ├── Actions
 ├── Tasks
 ├── Jobs
 ├── Tokens
 ├── Cost
 ├── Network
 ├── Storage
 └── Fan-out

160. Workflow 与 Cost Attribution

每次 Action / Agent / Provider 调用都记录:

workflowRunId
nodeRunId
projectId
organizationId
actorId

从而可以计算:

这个 Workflow 花了多少钱?

以及:

哪个 Node 最贵?

161. Workflow Cost UI

Run Detail 可以显示:

Total Cost

Actions: $0.20
Agent:   $1.20
Storage: $0.03
Network: $0.01
Total:   $1.44

具体计费数据由:

Usage / Observability Runtime

提供。


162. Workflow Governance

组织可以制定:

允许哪些 Workflow
允许哪些 Plugins
允许哪些 Actions
允许哪些 Providers
允许哪些 Environments
是否必须 Approval
最大预算
最大运行时间

Policy Runtime 统一执行。


163. Workflow Governance 不放在 Workflow Engine

禁止:

WorkflowEngine
  if production:
     requireApproval()

这种业务化安全代码。

应该:

Workflow
 ↓
Security Policy
 ↓
Approval Runtime

164. Workflow SDK

提供:

@devos/workflow-sdk

允许开发者:

defineWorkflow(...)
defineActionNode(...)
defineCondition(...)
defineParallel(...)
defineApproval(...)

但 SDK 不拥有 Runtime。


165. Declarative SDK

例如:

defineWorkflow({
  id: 'content.pipeline',

  nodes: [
    action('generate', 'content.generate'),
    approval('approve'),
    action('publish', 'content.publish'),
  ],

  edges: [
    edge('generate', 'approve'),
    edge('approve', 'publish'),
  ],
})

最终生成:

Workflow Definition

166. Workflow Definition as Source of Truth

可以有:

YAML
JSON
TypeScript SDK
Visual Editor
Agent Generated Draft

但最终都必须转换成:

Canonical Workflow Definition

只有 Canonical Definition 可以 Publish。


167. Canonicalization

Publish 前:

Parse
 ↓
Normalize
 ↓
Sort stable fields
 ↓
Validate
 ↓
Canonical JSON
 ↓
Checksum

这样:

同一个 Definition
=
同一个 checksum

168. Workflow Checksum

记录:

definitionChecksum

用于:

reproducibility
upgrade
audit
marketplace
migration
debugging

169. Workflow Security Checklist

每个 Workflow Publish 必须:

[ ] Authentication context defined
[ ] Authorization validated
[ ] Organization scope validated
[ ] Project scope validated
[ ] Environment validated
[ ] Actions authorized
[ ] Plugins authorized
[ ] Credentials authorized
[ ] Expressions sandboxed
[ ] Secrets protected
[ ] Rate limits defined
[ ] Budget defined
[ ] Timeout defined
[ ] Retry policy defined
[ ] Idempotency considered
[ ] Approval policy validated

170. Zcode Implementation Order

Zcode 不应该一次实现全部 Workflow。

严格按照:

Step 1
Workflow Schema

Step 2
Definition Validator

Step 3
Workflow Registry

Step 4
Workflow Version

Step 5
Workflow Run State

Step 6
Linear Node Engine

Step 7
Action Node

Step 8
Query Node

Step 9
Task Node

Step 10
Condition / Branch

Step 11
Parallel / Join

Step 12
Delay / Wait

Step 13
Approval

Step 14
Event Trigger

Step 15
Schedule Trigger

Step 16
Agent Node

Step 17
Subworkflow

Step 18
Checkpoint / Recovery

Step 19
Retry / Timeout / Cancellation

Step 20
UI Editor

Step 21
Template / Plugin Integration

171. 第一 Vertical Slice

第一条完整 Vertical Slice 必须是:

Create Workflow
 ↓
Validate
 ↓
Publish
 ↓
Manual Trigger
 ↓
Workflow Run
 ↓
Action Node
 ↓
Execution
 ↓
Event
 ↓
Workflow Continue
 ↓
Completed

不要第一步就实现:

BPMN
Loop
Parallel
Agent
Marketplace
Visual Editor

172. 第二 Vertical Slice

Schedule
 ↓
Workflow
 ↓
Condition
 ↓
Branch
 ↓
Action
 ↓
Completed

173. 第三 Vertical Slice

Workflow
 ↓
Task Node
 ↓
Task
 ↓
Jobs
 ↓
Worker
 ↓
Task Completed Event
 ↓
Workflow Resume

174. 第四 Vertical Slice

Workflow
 ↓
Approval
 ↓
Waiting
 ↓
Approval Event
 ↓
Resume
 ↓
Action
 ↓
Completed

175. 第五 Vertical Slice

Workflow
 ↓
Agent Node
 ↓
Agent Runtime
 ↓
Skill
 ↓
Action
 ↓
Agent Result
 ↓
Workflow Continue

176. Definition of Done

Workflow Runtime 第一阶段完成必须满足:

[ ] Workflow Definition
[ ] Workflow Version
[ ] Workflow Run
[ ] Node Run
[ ] Action Node
[ ] Query Node
[ ] Condition
[ ] Branch
[ ] Manual Trigger
[ ] Event Trigger
[ ] Task Integration
[ ] Checkpoint
[ ] Recovery
[ ] Pause
[ ] Resume
[ ] Cancel
[ ] Retry
[ ] Timeout
[ ] Authorization
[ ] Scope
[ ] Audit
[ ] Observability
[ ] API
[ ] CLI
[ ] Contract Tests

177. Architecture Contract Tests

必须自动验证:

Workflow → Action Runtime
Workflow → Task Runtime
Workflow → Event Runtime
Workflow → Security Runtime
Workflow → Config Runtime
Workflow → Storage Runtime

而不是:

Workflow → DB
Workflow → Redis
Workflow → Provider
Workflow → Secret

178. Forbidden Patterns

以下代码视为架构违规:

// forbidden
const db = new PrismaClient()

// forbidden
await redis.set(...)

// forbidden
await fetch(providerUrl)

// forbidden
await fs.writeFile(...)

// forbidden
process.env.OPENAI_API_KEY

// forbidden
await prisma.workflow_runs.update(...)

Workflow Runtime 自己内部当然可以通过正式 Runtime Adapter 使用基础设施,但业务 Node/Plugin/Agent 不得绕过 Runtime。


179. Zcode Workflow Master Prompt

Zcode 实现 Workflow 功能时,必须遵守:

You are implementing DevOS Workflow Runtime.

Workflow is an orchestration layer, not a business execution layer.

MANDATORY RULES:

1. Workflow orchestrates.
2. Action executes.
3. Task schedules durable work.
4. Event signals.
5. Agent reasons.
6. Approval handles human authorization.
7. Scheduler handles time triggers.
8. Security Runtime handles authorization.
9. Config Runtime handles configuration.
10. Storage Runtime handles files/artifacts.

Never:
- access Prisma directly from workflow business nodes
- access Redis directly from workflow business nodes
- call external providers directly
- read secrets directly
- implement a private queue
- implement a private retry system
- implement a private event bus
- implement a private permission system
- persist hidden chain-of-thought
- bypass Action Runtime
- bypass Security Runtime
- mutate published workflow versions

Every workflow run must be:
- version pinned
- scoped
- auditable
- observable
- recoverable
- idempotent where side effects exist

Every new implementation must:
- reuse existing Runtime
- add contract tests
- add integration tests
- preserve architecture boundaries
- avoid duplicate infrastructure
- avoid unrelated refactoring

Implement one vertical slice at a time.

Do not introduce a heavyweight workflow engine unless
the current architecture and scale explicitly require it.

Before coding:
1. inspect existing architecture
2. identify reusable Runtime
3. identify conflicting implementations
4. produce bounded implementation plan
5. implement
6. test
7. run architecture checks
8. report changed files
9. report remaining risks

180. Zcode Workflow Review Checklist

提交代码前必须回答:

1. Workflow 是否直接访问 DB?
2. Workflow 是否直接访问 Redis?
3. Workflow 是否直接访问 Provider?
4. Workflow 是否绕过 Action Runtime?
5. Workflow 是否绕过 Security Runtime?
6. Workflow 是否绕过 Task Runtime?
7. Workflow 是否创建自己的 Queue?
8. Workflow 是否创建自己的 Retry?
9. Workflow 是否创建自己的 Event Bus?
10. Workflow Version 是否 immutable?
11. Workflow Run 是否 version pinned?
12. 是否支持 crash recovery?
13. 是否支持 idempotency?
14. 是否存在无限 Loop?
15. 是否存在无限 fan-out?
16. 是否保护 Secret?
17. 是否支持 Audit?
18. 是否支持 Trace?
19. 是否有 Contract Test?
20. 是否引入了重复 Runtime?

181. 与已有 DevOS Runtime 的最终关系

完整关系:

                         USER
                           │
                         GOAL
                           │
                ┌──────────┴──────────┐
                │                     │
             Workflow               Agent
                │                     │
          deterministic          dynamic reasoning
                │                     │
                └──────────┬──────────┘
                           ↓
                    Capability Layer
                           │
              ┌────────────┼────────────┐
              ↓            ↓            ↓
           Action         Task        Skill
              │            │            │
              ↓            ↓            ↓
        Action Runtime Task Runtime Agent Runtime
              │            │            │
              └────────────┼────────────┘
                           ↓
                       Execution
                           ↓
                         Event
                           ↓
       ┌───────────────────┼──────────────────┐
       ↓                   ↓                  ↓
 Notification          Realtime          Observability

182. Workflow 与 Project Factory

Project Factory 可以生成:

Workflow
Workflow Templates
Workflow Actions
Workflow Triggers

例如:

devos create project seo-platform

自动获得:

SEO capabilities
+
Workflow Runtime
+
Task Runtime
+
Agent Runtime

业务项目只定义:

Workflow Definitions

而不是重新实现:

Workflow Engine

183. Workflow 与官方 Modules

官方 Module 可以提供:

SEO Workflow Templates
DevOps Deployment Workflows
CRM Lead Workflows
Content Workflows
Data Import Workflows

例如:

seo.daily.audit
seo.content.pipeline
devops.deploy.production
crm.lead.qualification

Module 提供业务定义。

DevOS 提供 Runtime。


184. Workflow 与 Plugin Marketplace

最终生态可以形成:

Plugin
 ├── Actions
 ├── Queries
 ├── Providers
 ├── Triggers
 ├── Workflow Nodes
 └── Workflow Templates

因此一个 Plugin 可以:

安装 GitHub Plugin
 ↓
获得 GitHub Actions
 ↓
获得 GitHub Events
 ↓
获得 GitHub Workflow Templates

但:

GitHub Plugin 不需要自己的 Workflow Engine。


185. DevOS Workflow 的核心优势

DevOS Workflow 不追求:

做一个最复杂的 BPMN 平台

而追求:

Resource
 ↓
Action
 ↓
Workflow
 ↓
Task
 ↓
Agent
 ↓
Event
 ↓
Execution

所有能力都能够:

UI
API
CLI
Plugin
MCP
Skill
Agent
Workflow

共享。


186. 最终 Runtime 分工

必须固定为:

Resource
  = What exists

Query
  = How to read

Action
  = How to execute

Workflow
  = How to orchestrate

Task
  = How to persist durable work

Job
  = How to schedule work

Queue
  = How to distribute work

Worker
  = How to perform work

Event
  = What happened

Skill
  = How to solve a domain problem

Agent
  = How to dynamically achieve a goal

Approval
  = Whether a human permits an operation

Plugin
  = Who provides capabilities

MCP
  = How capabilities are exposed/accessed

187. 最终 Golden Rules

Rule 1

Workflow orchestrates; it does not execute business logic.

Rule 2

Action executes; Workflow never bypasses Action Runtime.

Rule 3

Task provides durable asynchronous work; Workflow never creates a second Task system.

Rule 4

Agent reasons; Workflow does not become a second Agent Runtime.

Rule 5

Event signals; Workflow does not implement a private Event Bus.

Rule 6

Approval authorizes human decisions; Workflow does not implement private authorization.

Rule 7

Every Workflow Run is version-pinned.

Rule 8

Published Workflow Versions are immutable.

Rule 9

Workflow execution is at-least-once; side effects require idempotency.

Rule 10

Long waits must be durable state, never sleeping Workers.

Rule 11

Loops and fan-out must have hard limits.

Rule 12

Secrets are references, never persisted plaintext.

Rule 13

Every Workflow is subject to Security Context + Authorization + Scope + Policy.

Rule 14

Every Workflow Run must be observable, auditable and recoverable.

Rule 15

Plugin may provide Workflow capabilities, but never its own Workflow Runtime.

Rule 16

Agent may generate Workflow Drafts, but high-risk publishing requires validation and appropriate approval.

Rule 17

Workflow UI is a definition editor and execution viewer, not a second runtime.

Rule 18

Workflow is declarative. Arbitrary code execution is forbidden inside expressions.

Rule 19

Prefer DevOS Runtime abstractions over direct infrastructure access.

Rule 20

Do not build a second DevOS inside Workflow.


188. Final Architecture Statement

DevOS Workflow 最终必须形成:

                    TRIGGER
                       ↓
                WORKFLOW VERSION
                       ↓
                  WORKFLOW RUN
                       ↓
                 WORKFLOW ENGINE
                       ↓
          ┌────────────┼────────────┐
          ↓            ↓            ↓
       CONDITION     PARALLEL      LOOP
          │            │            │
          └────────────┼────────────┘
                       ↓
                  NODE EXECUTION
                       ↓
       ┌───────────────┼────────────────┐
       ↓               ↓                ↓
     ACTION           TASK             AGENT
       ↓               ↓                ↓
 Action Runtime    Task Runtime     Agent Runtime
       │               │                │
       └───────────────┼────────────────┘
                       ↓
                   EXECUTION
                       ↓
                     EVENT
                       ↓
       ┌───────────────┼────────────────┐
       ↓               ↓                ↓
     AUDIT        OBSERVABILITY      REALTIME

最终一句话:

Workflow 负责“按规则组织工作”,Agent 负责“动态解决问题”,Action 负责“执行能力”,Task 负责“可靠完成工作”,Event 负责“传播发生了什么”。DevOS Workflow 必须成为这些 Runtime 之间的编排层,而绝不能成为另一个独立的执行平台。


189. Document Completion Criteria

28_WORKFLOW_AUTOMATION_RUNTIME.md 完成后,Zcode 应能够明确实现:

[✓] Workflow Definition
[✓] Workflow Version
[✓] Workflow Run
[✓] Node / Edge
[✓] Action Node
[✓] Query Node
[✓] Task Node
[✓] Agent Node
[✓] Condition
[✓] Branch
[✓] Parallel
[✓] Join
[✓] Loop
[✓] Delay
[✓] Wait
[✓] Approval
[✓] Human Task
[✓] Subworkflow
[✓] Manual Trigger
[✓] Schedule Trigger
[✓] Event Trigger
[✓] Webhook Trigger
[✓] Expression Runtime
[✓] Checkpoint
[✓] Recovery
[✓] Retry
[✓] Timeout
[✓] Pause / Resume
[✓] Cancellation
[✓] Idempotency
[✓] Compensation
[✓] Security
[✓] Audit
[✓] Observability
[✓] API
[✓] CLI
[✓] Plugin Extension
[✓] Agent Integration
[✓] Project Factory Integration
[✓] Contract Tests

Workflow Runtime 的最终边界:

Workflow
    ↓
ORCHESTRATION

Action
    ↓
EXECUTION

Task
    ↓
DURABLE WORK

Agent
    ↓
REASONING

Event
    ↓
SIGNAL

Approval
    ↓
HUMAN DECISION

DevOS 不允许任何一个 Runtime 吞掉其他 Runtime 的职责。