# 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 用于表达: ```text 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 最重要的边界之一。 ```text Workflow │ orchestration │ ┌────────────┼────────────┐ ↓ ↓ ↓ Action Task Agent │ │ │ ↓ ↓ ↓ Action Runtime Task Runtime Agent Runtime │ │ │ └────────────┼────────────┘ ↓ Execution ↓ Event ``` ## 3.1 Action Action 解决: > **具体执行什么操作?** 例如: ```text seo.website.scan content.article.publish github.repository.create email.send server.deploy ``` Action 是原子能力。 --- ## 3.2 Task Task 解决: > **这项工作如何可靠地异步完成?** 例如: ```text 生成100篇文章 扫描1000个 URL 部署多个服务器 批量导入数据 ``` Task 可以包含多个 Job。 --- ## 3.3 Workflow Workflow 解决: > **这些步骤按照什么业务规则组织起来?** 例如: ```text 扫描网站 ↓ 分析结果 ↓ 如果评分 < 60 ↓ 生成优化建议 ↓ 人工审批 ↓ 执行优化 ``` --- ## 3.4 Agent Agent 解决: > **当路径不是完全预先确定时,应该如何动态解决目标?** Agent 可以: ```text Observe ↓ Plan ↓ Act ↓ Observe ↓ Evaluate ↓ Replan ``` Agent 可以动态选择 Skill / Capability / Action。 Workflow 通常不应该动态改变自身结构。 --- # 4. 四个核心边界 必须永久遵守: ```text Workflow = Orchestrate Agent = Reason Action = Execute Task = Durable Work ``` 进一步: ```text Event = Signal Approval = Human Decision Scheduler = Time Trigger Plugin = Capability Provider MCP = Capability Access/Transport ``` 因此: ```text Workflow 不替代 Agent Workflow 不替代 Action Workflow 不替代 Task Workflow 不替代 Event ``` --- # 5. 总体架构 ```text 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 的逻辑定义。 推荐: ```text WorkflowDefinition ``` 包含: ```ts 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 } ``` --- # 7. Workflow Version Workflow 必须不可变版本化。 例如: ```text seo.content.pipeline@1.0.0 seo.content.pipeline@1.1.0 seo.content.pipeline@2.0.0 ``` 禁止: ```text 修改正在运行的 Workflow Version ``` 正确方式: ```text v1 → immutable 修改 ↓ 创建 v2 ↓ publish v2 ``` 已经运行的 Workflow Run: ```text 继续使用 v1 ``` 新运行: ```text 使用 v2 ``` --- # 8. Workflow Run Workflow Run 是 Workflow Definition 的一次实际执行。 ```ts 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 } ``` --- # 9. Workflow Run 必须锁定版本 Run 创建时必须记录: ```text workflowId workflowVersion runtimeVersion pluginVersions actionVersions skillVersions mcpVersions configSnapshot ``` 这样未来才能回答: > 这个 Workflow 为什么当时这样执行? --- # 10. Workflow Node Node 是 Workflow 的执行单位。 第一版支持: ```text action query task agent condition branch parallel join loop delay wait approval human_task subworkflow webhook transform ``` --- # 11. Action Node 示例: ```yaml - id: scan type: action action: seo.website.scan input: websiteId: ${inputs.websiteId} ``` 执行: ```text Workflow ↓ Action Node ↓ Action Runtime ↓ Execution ``` Workflow 不允许: ```ts prisma.website.find(...) ``` 也不允许: ```ts fetch(...) ``` 必须: ```ts actionRuntime.execute(...) ``` --- # 12. Query Node Query Node 用于读取数据。 例如: ```yaml - id: website type: query query: seo.website.get input: id: ${inputs.websiteId} ``` Query 必须进入: ```text Data Runtime ``` 而不是: ```text Workflow → Prisma ``` --- # 13. Task Node 当某个步骤本身是长时间异步工作时,可以使用 Task Node。 例如: ```yaml - id: generate type: task taskType: content.bulk_generate ``` 运行: ```text Workflow Node ↓ Task Runtime ↓ Task ↓ Jobs ↓ Queue ↓ Workers ``` Workflow 不得重新实现: ```text Queue Worker Retry Lease Heartbeat ``` --- # 14. Agent Node Agent Node 用于动态问题。 例如: ```yaml - id: analyze type: agent agent: skill: seo.content.analysis goal: | Analyze the website and recommend the highest-impact content improvements. ``` 执行: ```text Workflow ↓ Agent Node ↓ Agent Runtime ↓ Agent Goal ↓ Agent Plan ↓ Skill / Capability ↓ Action ``` Workflow 只关心: ```text Agent 输入 Agent 状态 Agent 输出 Agent 是否成功 ``` 不保存或展示隐藏 Chain-of-Thought。 --- # 15. Agent Node 的重要边界 Agent Node 可以内部动态规划: ```text Agent ├── Action A ├── Action B ├── Skill C └── Replan ``` 但 Workflow Engine 不应该接管 Agent 的内部推理。 Workflow 只看到: ```text Agent Started Agent Completed Agent Failed Agent Result Agent Artifacts ``` --- # 16. Condition Node Condition 用于布尔判断。 例如: ```yaml - id: check_score type: condition expression: "${steps.scan.output.score < 60}" ``` 输出: ```text true false ``` 然后进入 Branch。 --- # 17. Branch Node 例如: ```yaml - 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。 禁止: ```yaml expression: "eval(...)" ``` 禁止: ```yaml expression: "${new Function(...)}" ``` 禁止: ```yaml expression: "${require('child_process').exec(...)}" ``` 必须使用受控表达式语言。 例如: ```text ${inputs.websiteId} ${steps.scan.output.score} ${steps.scan.output.score < 60} ${variables.retryCount + 1} ``` 允许: ```text 比较 布尔运算 数学运算 字符串操作 数组操作 对象读取 有限内置函数 ``` 禁止: ```text 文件系统 网络 Shell 动态 import 任意代码执行 数据库访问 Secret 读取 ``` --- # 19. Variable Workflow Variable 分为: ```text Input Static Variable Runtime Variable Node Output System Variable ``` 例如: ```yaml inputs: websiteId: type: string variables: retryCount: type: number default: 0 ``` 运行期间: ```text inputs.websiteId variables.retryCount steps.scan.output ``` --- # 20. Secret Variable Secret 不允许进入普通 Workflow Variable。 错误: ```yaml variables: openaiKey: "sk-xxxx" ``` 正确: ```yaml provider: credential: openai/default ``` 或: ```text secret://openai/default ``` Workflow 可以引用 Secret Reference。 Workflow persistence 中: ```text 只保存 Secret Reference ``` 不能保存: ```text Secret Plaintext ``` --- # 21. Parallel Node 用于并行执行多个分支。 ```yaml - id: parallel type: parallel branches: - generate - image - seo ``` 实际: ```text parallel / | \ ↓ ↓ ↓ generate image seo \ | / ↓ join ``` Parallel 必须受: ```text concurrency quota budget rate limit environment policy ``` 控制。 --- # 22. Join Node Join 用于并行汇合。 支持: ```text all any quorum ``` 例如: ```yaml - id: join type: join policy: all ``` Quorum: ```yaml policy: type: quorum required: 2 ``` --- # 23. Loop Node Loop 必须显式存在。 禁止 Workflow 隐式无限循环。 例如: ```yaml - id: loop type: loop items: ${steps.urls.output} maxIterations: 1000 ``` 必须有: ```text maxIterations timeout budget ``` 至少一个硬限制,生产环境建议同时存在。 --- # 24. Loop 的执行模型 不要: ```text Workflow Engine while(true) ``` 而应该: ```text Loop Node ↓ Generate Iteration ↓ Create execution units ↓ Persist checkpoint ↓ Execute ↓ Persist result ↓ Next iteration ``` 这样才能: - crash recovery - pause - resume - retry - observability --- # 25. Delay Node Delay 是时间等待。 例如: ```yaml - id: wait_10m type: delay duration: 10m ``` 禁止 Worker: ```text await sleep(10 * 60 * 1000) ``` 正确方式: ```text Delay Node ↓ Persist wakeAt ↓ Worker release ↓ Scheduler reactivates ``` Worker 不应该长期占用资源等待。 --- # 26. Wait Node Wait 用于等待外部条件。 例如: ```text 等待: - Event - Webhook - Human action - External callback ``` 状态: ```text running ↓ waiting ↓ event received ↓ resume ``` --- # 27. Approval Node Approval 必须复用: ```text Approval Runtime ``` 例如: ```yaml - id: approve type: approval approval: risk: high title: Publish article ``` 执行: ```text Workflow ↓ Approval Runtime ↓ pending ↓ approved / rejected / expired ↓ Workflow Resume ``` Workflow 不允许自己创建: ```text approval table approval permission approval policy ``` --- # 28. Human Task Human Task 是比 Approval 更一般的人工任务。 例如: ```text 审核文章 填写字段 选择方案 确认部署 处理异常 ``` 可以: ```text assign user assign role assign organization assign project ``` 完成后: ```text Human Task Result ↓ Workflow Resume ``` --- # 29. Subworkflow Workflow 可以调用另一个 Workflow。 例如: ```yaml - id: publish_pipeline type: subworkflow workflow: id: content.publish version: 2.1.0 ``` 推荐默认: > Subworkflow 必须锁定版本。 禁止: ```text workflow: content.publish@latest ``` 生产 Workflow 必须使用: ```text content.publish@2.1.0 ``` --- # 30. Workflow Trigger 支持: ```text manual schedule event webhook action resource task workflow ``` 例如: ```text Event ↓ seo.website.scan.completed ↓ Workflow Trigger ↓ Workflow Run ``` --- # 31. Manual Trigger 用户可以从 UI/API: ```text Run Workflow ``` 创建: ```text Workflow Run ``` 必须经过: ```text Authentication Authorization Scope Policy ``` --- # 32. Schedule Trigger 例如: ```yaml trigger: type: schedule cron: "0 2 * * *" timezone: "Asia/Tokyo" ``` 执行: ```text Scheduler ↓ Trigger ↓ Workflow Run ``` Scheduler 不直接执行 Workflow Node。 --- # 33. Event Trigger 例如: ```yaml trigger: type: event event: seo.website.scan.completed ``` Event Runtime: ```text Event ↓ Subscription ↓ Workflow Trigger ↓ Workflow Run ``` 必须处理: ```text deduplication idempotency ordering scope correlation causation ``` --- # 34. Webhook Trigger Webhook: ```text External System ↓ API ↓ Authentication ↓ Signature Verification ↓ Event ↓ Workflow Trigger ``` Webhook 不应该: ```text Webhook Controller ↓ 直接运行 Workflow ``` 而应该进入统一 Event/Trigger Runtime。 --- # 35. Trigger 去重 Webhook/Event/Scheduler 都可能重复触发。 因此 Trigger 必须支持: ```text idempotencyKey eventId deduplicationKey ``` 例如: ```text workflowId + triggerType + eventId ``` 构成唯一约束。 --- # 36. Workflow Execution Workflow Run 本身不是 Action Execution。 关系: ```text WorkflowRun │ ├── NodeRun │ │ │ └── Action │ ↓ │ Execution │ └── Task ↓ Job ``` 因此: ```text Workflow Run ≠ Execution Workflow Node Run ≠ Execution Task ≠ Workflow ``` --- # 37. Node Run 推荐: ```ts 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 } ``` --- # 38. Workflow Engine Workflow Engine 负责: ```text 读取 Workflow Definition ↓ 解析 Node / Edge ↓ 确定可执行 Node ↓ 检查 Condition ↓ 创建 Node Run ↓ 调用 Runtime ↓ 等待结果 ↓ 推进 Graph ↓ Checkpoint ``` Workflow Engine 不负责: ```text 实际业务执行 ``` --- # 39. Workflow Engine 的核心循环 逻辑模型: ```text 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 必须允许: ```text Worker Crash Process Crash Machine Crash Network Failure Redis Restart Database Restart ``` 之后恢复。 依赖: ```text PostgreSQL durable state + Task/Job Runtime + Checkpoint + Idempotency ``` --- # 41. Checkpoint Workflow 需要持久化 checkpoint。 至少保存: ```text workflowRunId currentNodes completedNodes waitingNodes variables nodeOutputs loopState parallelState updatedAt ``` 不要仅依赖: ```text memory Redis only ``` --- # 42. Pause Workflow 可以: ```text running ↓ paused ``` Pause 后: ```text 不创建新的 Node Run ``` 已经运行的 Action: - 默认允许完成 - 高风险情况可以取消 - 行为由 Policy 决定 --- # 43. Resume ```text paused ↓ resume ↓ load checkpoint ↓ validate current version ↓ continue ``` 如果 Workflow Version 已经不兼容: ```text 拒绝 Resume ``` 或者进入: ```text Migration Required ``` --- # 44. Cancel 取消 Workflow: ```text Workflow Run ↓ cancel requested ↓ cancel pending nodes ↓ cancel active tasks when supported ↓ stop future scheduling ↓ persist cancellation ``` 不能简单: ```ts delete workflowRun ``` --- # 45. Retry Retry 可以发生在: ```text Action Runtime Task Runtime Workflow Node Workflow Run ``` 但必须避免: > **重复 Retry。** 例如 Action Runtime 已经: ```text attempt 1 attempt 2 attempt 3 ``` Workflow 不应该再无条件: ```text retry 3 times ``` 否则可能: ```text 3 × 3 = 9 ``` 次实际调用。 --- # 46. Retry Ownership 推荐规则: ```text Action transient failure → Action Runtime Retry Task execution failure → Task Runtime Retry Workflow control failure → Workflow Runtime Retry ``` Workflow Definition 可以声明策略: ```yaml retry: maxAttempts: 3 backoff: exponential ``` 但具体执行应委托给对应 Runtime。 --- # 47. Timeout 支持: ```text Node timeout Workflow timeout Task timeout Agent timeout Approval timeout Wait timeout ``` 例如: ```yaml settings: timeout: 24h ``` 超时: ```text timed_out ``` 并生成: ```text Workflow Event Audit Observability record ``` --- # 48. Idempotency Workflow 默认不能假设: ```text exactly once ``` DevOS 默认: ```text at least once ``` 因此所有副作用 Action 必须支持: ```text idempotencyKey ``` 例如: ```text workflowRunId + nodeId + attempt ``` 或者业务级: ```text projectId + operation + businessKey ``` --- # 49. Exactly Once 的正确理解 不要宣传: > Workflow Exactly Once Execution 正确表述: > **At-least-once orchestration + idempotent side effects** 这样才能真实面对: ```text 网络超时 Worker Crash Response Lost Retry Duplicate Delivery ``` --- # 50. Compensation / Saga 长 Workflow 不应该依赖: ```text 一个数据库事务 ``` 例如: ```text Create Order ↓ Charge Payment ↓ Provision Server ↓ Send Email ``` 不能: ```text BEGIN ... COMMIT ``` 整个 Workflow。 应该支持: ```text Forward Action ↓ Compensation Action ``` 例如: ```text Charge Payment ↓ Provision Failed ↓ Refund Payment ``` 这属于: ```text Saga / Compensation ``` --- # 51. Compensation 定义 例如: ```yaml - id: charge type: action action: payment.charge compensation: action: payment.refund ``` Compensation 必须: - 显式定义 - 可审计 - 可重试 - 可取消 - 有权限 - 有风险级别 --- # 52. Error Handling Workflow 错误至少分为: ```text validation_error authorization_error scope_error configuration_error provider_error network_error timeout_error rate_limit_error business_error dependency_error internal_error ``` 每个错误应该有: ```text code message retryable severity fingerprint ``` --- # 53. Workflow Failure Policy Workflow 可以定义: ```text fail_fast continue fallback retry compensate manual_intervention ``` 例如: ```yaml onError: strategy: manual_intervention ``` 错误进入: ```text Human Task ``` --- # 54. Dead Letter 无法自动继续的 Workflow 可以进入: ```text Workflow DLQ ``` 例如: ```text workflow failed ↓ retry exhausted ↓ DLQ ↓ operator review ↓ retry / resume / migrate / cancel ``` 不能简单删除失败 Run。 --- # 55. Replay Workflow 必须支持有限 replay。 Replay 不是: ```text 从头无条件再次执行所有副作用 ``` 而应该支持: ```text Replay for diagnosis Replay from checkpoint Replay failed node Replay with new version ``` 生产副作用 Replay 必须显式确认。 --- # 56. Workflow Data Model 至少包括: ```text workflow_definitions workflow_versions workflow_triggers workflow_schedules workflow_runs workflow_node_runs workflow_variables workflow_checkpoints workflow_artifacts workflow_templates ``` --- # 57. WorkflowDefinition ```text id namespace name description currentVersion status organizationId projectId createdBy createdAt updatedAt ``` --- # 58. WorkflowVersion ```text id workflowId version definition checksum status createdBy createdAt publishedAt deprecatedAt ``` Definition 建议: ```text JSONB ``` 但必须经过: ```text Schema Validation Semantic Validation Graph Validation Capability Validation Security Validation ``` --- # 59. WorkflowRun ```text id workflowId workflowVersion organizationId projectId environmentId actorId status input correlationId startedAt completedAt createdAt updatedAt ``` --- # 60. WorkflowNodeRun ```text id workflowRunId nodeId status attempt input output executionId taskId error startedAt completedAt ``` --- # 61. WorkflowCheckpoint ```text id workflowRunId sequence state createdAt ``` Checkpoint 必须支持: ```text resume recovery diagnostics ``` --- # 62. Graph Validation Workflow Publish 前必须检查: ```text 所有 Node ID 唯一 所有 Edge 合法 所有引用 Node 存在 Trigger 合法 起点存在 终点可达 无非法 Cycle Loop 显式声明 所有 Action 存在 所有 Query 存在 所有 Skill 存在 所有 Workflow 存在 Expression 合法 Input 类型正确 Output 类型正确 权限可满足 ``` --- # 63. Cycle Validation 普通 DAG: ```text A → B → C ``` 合法。 普通 Cycle: ```text A → B → C → A ``` 默认非法。 Loop: ```text A → Loop → B ↑ └── explicit loop ``` 可以合法。 --- # 64. Unreachable Node 以下必须报错: ```text Start → A → B C → D ``` 因为: ```text C / D ``` 不可达。 除非它们被定义为: ```text separate trigger entry ``` --- # 65. Type Validation 例如: ```text Action Output: { score: number } ``` 下一个节点: ```text condition: ${steps.scan.output.score < 60} ``` 合法。 如果: ```text ${steps.scan.output.score.foo} ``` 则 Publish 阶段应尽可能发现。 --- # 66. Capability Validation Workflow Publish 时检查: ```text Action Registry Query Registry Skill Registry Agent Registry Workflow Registry Plugin Registry ``` 例如: ```text seo.website.scan ``` 不存在: ```text Publish Failed ``` 而不是运行时才发现。 --- # 67. Security Validation Workflow Publish / Run 都必须检查: ```text Actor Organization Project Environment Permission Policy Scope Capability Plugin Credential ``` Workflow 不能因为它是“自动化”就获得更高权限。 --- # 68. Workflow Security Context Workflow Run 继承: ```text actor organization project environment permissions roles scopes policy ``` 每一个 Action: ```text Workflow ↓ Action ↓ SecurityContext ↓ Authorization ↓ Scope ↓ Action Runtime ``` --- # 69. Agent 权限 如果 Workflow 调用 Agent: ```text Workflow Permission ∩ Agent Policy ∩ Actor Delegated Permission ∩ Project Scope ``` 得到实际权限。 Agent 不得: ```text 自动升级权限 ``` --- # 70. Production Protection Production Workflow 应支持: ```text protected environment approval required restricted actions restricted plugins restricted credentials restricted network ``` 例如: ```text production.deploy ``` 可能要求: ```text Approval ``` --- # 71. Concurrency Workflow 需要限制: ```text per workflow per project per organization per environment per node ``` 例如: ```yaml settings: concurrency: maxRuns: 10 ``` --- # 72. Duplicate Run Policy 可以配置: ```text allow reject queue replace deduplicate ``` 例如: ```text 同一个 project 每次只能运行一个 deploy workflow ``` 第二次: ```text queue ``` 或者: ```text reject ``` --- # 73. Rate Limit Workflow 必须尊重: ```text Action Rate Limit Provider Rate Limit Organization Quota Project Quota Agent Budget ``` Workflow 自己不能绕过。 --- # 74. Budget Workflow 可以设置: ```text maxDuration maxActions maxTasks maxIterations maxCost maxTokens maxNetworkCalls ``` 例如: ```yaml budget: maxActions: 500 maxDuration: 2h maxCost: 10 ``` 超过: ```text Workflow Budget Exceeded ``` --- # 75. Artifact Workflow 可以产生: ```text File Artifact Report Dataset Log ``` 必须进入: ```text Storage / Artifact Runtime ``` 而不是: ```text workflow directory ``` --- # 76. Workflow Event Workflow 本身产生事件: ```text 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 ``` 这些进入: ```text Event Runtime ``` --- # 77. Workflow 与 Event 的关系 Workflow 可以: ```text Event → Trigger Workflow ``` Workflow 也可以: ```text Workflow → Emit Event ``` 例如: ```text content.article.published ``` 但是 Event 发布必须走: ```text Event Runtime ``` 而不是 Workflow 自己实现 Event Bus。 --- # 78. Outbox 如果 Workflow Node 完成同时需要: ```text DB State + Event ``` 必须使用: ```text Outbox Pattern ``` 保证: ```text State persisted + Event eventually published ``` 避免: ```text DB 成功 Event 丢失 ``` --- # 79. Observability 每个 Workflow 必须可追踪: ```text workflowRunId workflowNodeRunId executionId taskId jobId requestId correlationId traceId actorId organizationId projectId environmentId ``` 推荐: ```text Workflow ↓ Node ↓ Execution / Task ↓ Event ``` 形成完整 Trace。 --- # 80. Workflow Timeline UI 应显示: ```text 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: ```text 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 提供: ```text 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 可使用: ```text React Flow ``` 或其他成熟 Graph Editor。 但: > UI Editor 不是 Workflow Runtime。 UI 负责: ```text Graph Editing Schema Editing Validation Feedback ``` 最终生成: ```text Workflow Definition ``` --- # 84. Visual Editor 的原则 用户拖拽: ```text Action Condition Parallel Approval ``` 最终必须转换成: ```text Declarative Workflow Definition ``` 而不是: ```text UI state ``` 作为真正运行状态。 --- # 85. Workflow Run UI 必须能看到: ```text Status Started Duration Current Node Completed Nodes Waiting Nodes Failed Nodes Tasks Executions Artifacts Events Errors Approvals ``` --- # 86. Node Detail UI Node Detail: ```text Input Output Status Attempts Execution Task Error Retry Logs Trace Artifacts ``` Secret: ```text 永远 Mask ``` --- # 87. Workflow Template Workflow 可以模板化。 例如: ```text SEO Website Audit Content Publishing Deployment Pipeline Data Import Lead Processing Backup Pipeline ``` Template: ```text parameters variables triggers nodes edges ``` 可以由: ```text Plugin Module Project Factory Marketplace ``` 提供。 --- # 88. Plugin Workflow Contribution Plugin 可以提供: ```text Workflow Node Workflow Template Workflow Trigger Workflow Action Workflow Query ``` 例如 GitHub Plugin: ```text github.pull_request.opened github.repository.updated ``` 可以成为 Workflow Trigger。 但 Plugin: > 不得创建自己的 Workflow Engine。 --- # 89. Plugin Node Plugin 可以注册: ```text plugin.github.pull_request.wait ``` 但真正执行: ```text Plugin Action ↓ Action Runtime ``` --- # 90. Agent 创建 Workflow Agent 可以根据自然语言生成: ```text Workflow Draft ``` 例如: > 每天凌晨扫描所有网站,如果 SEO 分数低于 60,就生成优化建议并提交人工审批。 Agent 可以生成: ```text Schedule ↓ Scan ↓ Condition ↓ Agent ↓ Approval ↓ Action ``` 但: > Agent 生成的 Workflow 默认必须是 Draft。 --- # 91. Agent 不应直接发布高风险 Workflow 推荐: ```text Agent ↓ Draft Workflow ↓ Validation ↓ Security Check ↓ Human Approval ↓ Publish ``` 特别是: ```text Production Financial Deletion Deployment Credential External communication ``` 等高风险 Workflow。 --- # 92. Workflow 与 Skill Skill 是: ```text How to solve a domain problem ``` Workflow 是: ```text How to orchestrate known steps ``` 例如: ```text Skill: SEO Content Analysis Workflow: Scan ↓ SEO Analysis Skill ↓ Approval ↓ Publish ``` Skill 可以被 Workflow 调用,但不能替代 Workflow Engine。 --- # 93. Workflow 与 MCP MCP: ```text Capability Access / Transport ``` Workflow: ```text Orchestration ``` 所以: ```text Workflow ↓ Action / Capability ↓ MCP ↓ External System ``` MCP 不得绕过: ```text Security Action Runtime Audit Observability ``` --- # 94. API 推荐: ```text 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: ```text Authentication Authorization Scope Policy Action/Workflow Runtime ``` --- # 95. CLI 推荐: ```bash 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 devos workflow pause devos workflow resume devos workflow cancel devos workflow retry ``` --- # 96. YAML 示例 完整示例: ```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 核心接口: ```ts interface WorkflowRuntime { createDefinition( input: CreateWorkflowInput ): Promise validate( definition: WorkflowDefinition ): Promise publish( workflowId: string, version: string ): Promise start( workflowId: string, input: unknown, context: SecurityContext ): Promise pause( runId: string ): Promise resume( runId: string ): Promise cancel( runId: string ): Promise retry( runId: string, options?: RetryOptions ): Promise } ``` --- # 98. Workflow Engine API ```ts interface WorkflowEngine { startRun(runId: string): Promise continueRun(runId: string): Promise executeNode( runId: string, nodeId: string ): Promise resumeWaitingNode( runId: string, nodeId: string, event: unknown ): Promise recover(runId: string): Promise } ``` --- # 99. Workflow Registry Workflow 必须进入 Registry。 Registry 可以提供: ```text find workflow find version find trigger find template find node ``` 例如: ```ts workflowRegistry.resolve( 'seo.content.pipeline', '1.0.0' ) ``` --- # 100. Workflow Capability Discovery Agent 不需要看到全部 Workflow Definition。 可以采用: ```text Level 1 Workflow summary Level 2 Inputs / Outputs Level 3 Full schema Level 4 Instructions ``` 保持: > Progressive Disclosure 避免给模型发送大量 Workflow JSON。 --- # 101. Workflow Import / Export 支持: ```text YAML JSON ``` 导出时必须: ```text 去除 Secret Plaintext ``` 并可包含: ```text workflow version dependencies required capabilities required plugins ``` --- # 102. Workflow Dependency Workflow 可能依赖: ```text Plugin Action Query Skill Agent Provider Credential Subworkflow ``` Publish 前检查依赖。 --- # 103. Dependency Lock 生产 Workflow 建议生成: ```text workflow.lock ``` 记录: ```text Workflow Version Plugin Version Action Version Skill Version MCP Version Provider Version ``` 避免: ```text latest ``` 造成不可复现。 --- # 104. Workflow Migration 如果: ```text v1 ``` 正在运行。 然后: ```text v2 ``` 修改了: ```text Node ID Input Output Graph Action ``` 旧 Run 默认继续使用: ```text v1 ``` 如果需要迁移: ```text Workflow Migration ↓ Validate Mapping ↓ Checkpoint Conversion ↓ Security Revalidation ↓ Resume ``` --- # 105. Node ID 是稳定标识 Node ID 不是 UI 临时 ID。 例如: ```text scan analyze approval publish ``` 运行历史依赖 Node ID。 因此: > 修改 Node ID 应视为兼容性变化。 --- # 106. Workflow Schema Version Definition Schema 本身也要版本化: ```yaml schemaVersion: "1" ``` 未来: ```text schemaVersion: 2 ``` 通过 Migration Runtime 转换。 --- # 107. Workflow Definition 不可变原则 发布之后: ```text Immutable ``` 如果修改: ```text Create New Version ``` 禁止: ```text UPDATE published_definition ``` --- # 108. Database Transaction Workflow Engine 可以使用短数据库事务保存状态: ```text Node State Checkpoint Outbox ``` 但不能: ```text 一个 Workflow Run = 一个长事务 ``` --- # 109. Workflow State Machine Definition: ```text draft ↓ active ↓ deprecated ↓ archived ``` Run: ```text pending ↓ running ↓ waiting ↓ running ↓ completed ``` 异常: ```text running ↓ failed running ↓ cancelled running ↓ timed_out running ↓ paused ``` --- # 110. Workflow Node State Machine ```text pending ↓ running ↓ completed ``` 或者: ```text running ↓ failed ↓ retrying ↓ running ``` 或者: ```text running ↓ waiting ↓ running ``` --- # 111. Event-driven Resume 例如 Approval: ```text Workflow ↓ Approval Pending ↓ Workflow Node = waiting ``` 之后: ```text Approval Approved Event ↓ Event Runtime ↓ Workflow Resume Handler ↓ Node Completed ↓ Next Node ``` 不能: ```text Worker 永久等待 ``` --- # 112. Scheduler Integration Scheduler 只负责: ```text 什么时候触发 ``` Workflow Runtime 负责: ```text 触发后运行什么 ``` 因此: ```text Scheduler ≠ Workflow Engine ``` --- # 113. Task Integration 长时间 Workflow: ```text Workflow Run ``` 本身可以是: ```text Task-backed execution ``` 但不要重复创建第二套 Task 系统。 推荐: ```text Workflow Run │ └── Task Runtime metadata ``` 具体长任务: ```text Workflow Node ↓ Task ↓ Jobs ``` --- # 114. Queue Integration Workflow Engine 可以通过 Queue 驱动: ```text workflow.resume workflow.node.execute workflow.trigger workflow.timeout workflow.wakeup ``` Queue 仍然属于: ```text Task/Queue Runtime ``` Workflow 不创建私有 Queue。 --- # 115. Worker Integration Worker: ```text 领取 Workflow Engine Job ↓ Load Workflow State ↓ Execute one orchestration step ↓ Persist state ↓ Exit ``` 不要: ```text Worker 永久持有 Workflow ``` 这样才能水平扩展。 --- # 116. Horizontal Scaling 可以运行: ```text Worker 1 Worker 2 Worker 3 Worker 4 ``` 共同处理: ```text Workflow Runs ``` 依赖: ```text DB locking Lease Idempotency Queue Checkpoint ``` --- # 117. Concurrency Control 必须防止: ```text Worker A + Worker B ``` 同时推进同一个 Workflow Run。 推荐: ```text workflowRunId lease ``` 或者: ```text optimistic locking ``` 例如: ```text version = version + 1 ``` CAS 更新。 --- # 118. Workflow Run Lock 推荐: ```text workflow_run.version ``` 每次状态更新: ```text WHERE id = ? AND version = ? ``` 成功: ```text version++ ``` 否则: ```text concurrent update ``` 然后重新读取。 --- # 119. Artifact Lineage Workflow Artifact 必须记录: ```text workflowRunId nodeRunId executionId taskId createdBy createdAt source version checksum ``` 这样可以回答: > 这个报告是谁生成的? 以及: > 这个文件是哪个 Workflow 的哪个步骤产生的? --- # 120. Workflow Security Boundaries 禁止: ```text Workflow → Prisma Workflow → Redis Workflow → Raw SQL Workflow → Secret DB Workflow → filesystem Workflow → shell Workflow → Docker socket Workflow → external API ``` 正确: ```text Workflow ↓ Action / Query / Task / Agent ↓ 对应 Runtime ``` --- # 121. Architecture Import Rules 建议 ESLint / dependency-cruiser / Nx boundaries 禁止: ```text workflow package ↓ @prisma/client ``` 禁止: ```text workflow ↓ redis client ``` 禁止: ```text workflow ↓ provider SDK ``` Workflow 只能依赖: ```text workflow contracts action runtime task runtime event runtime security runtime data runtime config runtime observability ``` --- # 122. Package Structure 推荐: ```text packages/ workflow/ workflow-schema/ workflow-runtime/ workflow-engine/ workflow-expression/ workflow-trigger/ workflow-template/ workflow-sdk/ ``` 如果规模较小,可以先合并: ```text packages/workflow/ ``` 但逻辑边界必须存在。 --- # 123. Workflow Package Responsibilities ```text 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 改造成: ```text BPMN Platform ``` 或者: ```text Enterprise Workflow Suite ``` 也不要立即引入大量: ```text 复杂 BPMN DMN 复杂规则引擎 复杂表单引擎 ``` DevOS 第一阶段需要的是: > **轻量、可靠、可扩展的 Action-Oriented Workflow Runtime。** --- # 125. 外部 Workflow Engine 的位置 未来如果规模达到: ```text 百万级 Workflow Run 超长运行 复杂 Durable Execution 跨区域调度 极高可靠性 ``` 可以评估成熟基础设施,例如: ```text Temporal ``` 但即使未来引入: ```text Temporal ``` 也不能让 Temporal 成为 DevOS 的业务边界。 正确: ```text DevOS Workflow Contract ↓ Workflow Adapter ↓ Temporal ``` 而不是: ```text 业务代码 ↓ Temporal SDK ``` 这样未来仍然可以替换实现。 --- # 126. Workflow Adapter 建议抽象: ```ts interface WorkflowExecutionBackend { start(runId: string): Promise resume(runId: string): Promise pause(runId: string): Promise cancel(runId: string): Promise } ``` 第一版: ```text DevOS Native Engine ``` 未来: ```text Temporal Adapter ``` --- # 127. Workflow Certification Workflow 可以定义认证等级: ```text Basic Validated Secure Production Ready Official ``` Production Ready 至少需要: ```text Schema Valid Graph Valid Capability Valid Security Valid Retry Valid Timeout Valid Observability Valid Idempotency Valid ``` --- # 128. Workflow Test Model 必须支持: ```text Definition Test Graph Test Expression Test Runtime Test Integration Test Security Test Recovery Test Migration Test ``` --- # 129. Deterministic Workflow Test 例如: ```text Input: score = 50 ``` 预期: ```text scan ↓ condition = true ↓ approval ``` 使用 Mock Action: ```text seo.website.scan ``` 返回: ```json { "score": 50 } ``` 验证: ```text Node sequence Condition Output Final state ``` --- # 130. Workflow Test Fixture 测试环境: ```text Ephemeral PostgreSQL Ephemeral Redis Mock Action Registry Mock Event Bus Mock Task Runtime Mock Agent Runtime Fake Clock ``` Fake Clock 非常重要。 可以测试: ```text Delay Timeout Schedule Approval Expiration ``` 而不需要真的等待。 --- # 131. Required Workflow Tests 至少测试: ```text 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 必须测试: ```text manual trigger schedule trigger event trigger webhook trigger duplicate event out-of-order event invalid signature expired event wrong tenant event ``` --- # 133. Security Tests 至少: ```text 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 模拟: ```text Worker killed DB transaction interrupted Network timeout Action response lost Queue duplicate Redis unavailable ``` 验证: ```text Workflow eventually resumes correctly ``` 并且: ```text 副作用不会无限重复 ``` --- # 135. Workflow Contract Test 建立统一: ```text Workflow Contract Test Suite ``` 所有 Workflow Engine Backend 都必须通过: ```text Native Engine Temporal Adapter Future Backend ``` 这样 DevOS Runtime Contract 不被实现细节绑定。 --- # 136. API Contract Test 检查: ```text OpenAPI Workflow Schema Error Contract Async Response Task/Run relationship Version behavior ``` --- # 137. Plugin Contract Test Plugin 提供 Workflow Node 时必须验证: ```text manifest capability permission schema action trigger health version upgrade disable ``` --- # 138. Workflow Marketplace 未来 Marketplace 可以发布: ```text Workflow Templates ``` 例如: ```text SEO Audit Pipeline GitHub Release Pipeline Content Publishing Pipeline Lead Qualification Daily Backup Server Deployment ``` Marketplace 条目必须包含: ```text version dependencies required permissions required plugins required providers security level author checksum signature ``` --- # 139. Workflow Template 安全 安装 Template 时: ```text Download ↓ Verify ↓ Validate ↓ Show Permissions ↓ Show Dependencies ↓ User Approval ↓ Install ``` 不能: ```text Install ↓ 立即拥有生产权限 ``` --- # 140. Configuration Workflow 可以引用: ```text Config Provider Credential Environment ``` 例如: ```yaml action: email.send config: provider: smtp/default ``` 实际 Credential 由: ```text Credential Runtime ``` 解析。 --- # 141. Environment 同一个 Workflow: ```text development staging production ``` 可以拥有不同: ```text Config Provider Credential Permission Approval Policy ``` Workflow Definition 不应该硬编码: ```text production secret ``` --- # 142. Workflow Input Validation Start Run 时必须: ```text Validate Input Schema ↓ Validate Security Scope ↓ Validate Dependencies ↓ Create Run ``` 错误输入不能进入 Engine。 --- # 143. Workflow Output Workflow 可以定义: ```yaml outputs: articleId: type: string ``` 最终: ```text Workflow Run Output ``` 可以用于: ```text API Agent Subworkflow Event UI ``` --- # 144. Workflow Event Output 完成后可以: ```text workflow.completed ``` payload 可以包含: ```text runId workflowId version status outputs artifactIds ``` 禁止包含: ```text Secret 内部敏感凭证 隐藏 Chain-of-Thought ``` --- # 145. Workflow Context Workflow Context 建议: ```ts 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: ```text 当前运行状态 ``` Agent Memory: ```text 长期 / 可检索上下文 ``` 两者必须分开。 --- # 147. Workflow 与 Agent Memory Agent Node 可以读取: ```text Agent Memory Runtime ``` 但 Workflow 不应直接访问: ```text memory tables ``` 正确: ```text Workflow ↓ Agent Runtime ↓ Memory Runtime ``` --- # 148. Workflow Logging 每个 Node 应生成结构化日志: ```text workflowRunId nodeRunId nodeId executionId taskId ``` 日志中禁止: ```text secret token password credential API key ``` --- # 149. Metrics 至少: ```text 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 平台级可以定义: ```text Workflow Trigger Latency Workflow Completion Rate Workflow Recovery Time Workflow Failure Rate Node Success Rate ``` --- # 151. Workflow Doctor 建议: ```bash devos workflow doctor ``` 检查: ```text 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 可能长时间: ```text running ``` 但没有任何 Progress。 Diagnostics 应检测: ```text last heartbeat last state update last node activity last event ``` 然后产生: ```text Potentially Stuck Workflow ``` --- # 153. Workflow Garbage Collection 历史 Run 不应无限增长。 根据: ```text retention policy organization policy project policy environment policy ``` 进行: ```text archive purge ``` 但: ```text Audit Artifacts Compliance data ``` 可能需要更长保留。 --- # 154. Workflow Data Retention 不同数据: ```text Workflow Definition Workflow Run Node Run Logs Events Artifacts Audit ``` 分别拥有 retention。 不能统一: ```text delete after 7 days ``` --- # 155. Workflow Performance 优化优先级: ```text Database state updates Queue throughput Node scheduling Expression evaluation Event delivery ``` 不要一开始就优化: ```text Graph rendering ``` 真正瓶颈通常在: ```text Durable State External Provider Queue DB ``` --- # 156. Batch Workflow 大量对象: ```text 10000 URLs 1000 articles 500 servers ``` 不要创建: ```text 10000 independent Workflow Runs ``` 除非业务确实需要。 可以: ```text One Workflow ↓ Batch Node ↓ Task ↓ Jobs ``` 或者: ```text Workflow ↓ Loop ↓ Task Batch ``` --- # 157. Workflow Fan-out 限制 必须防止: ```text 1 Node ↓ 1,000,000 Nodes ``` 造成平台雪崩。 限制: ```text maxFanOut maxIterations maxParallelism maxTasks maxCost ``` --- # 158. Backpressure Workflow 必须尊重: ```text Queue capacity Worker capacity Provider rate limit Project quota Organization quota ``` 当系统拥塞: ```text Workflow waits ``` 而不是: ```text 无限创建 Job ``` --- # 159. Workflow Budget 推荐最终预算模型: ```text Workflow Budget ├── Runtime ├── Actions ├── Tasks ├── Jobs ├── Tokens ├── Cost ├── Network ├── Storage └── Fan-out ``` --- # 160. Workflow 与 Cost Attribution 每次 Action / Agent / Provider 调用都记录: ```text workflowRunId nodeRunId projectId organizationId actorId ``` 从而可以计算: ```text 这个 Workflow 花了多少钱? ``` 以及: ```text 哪个 Node 最贵? ``` --- # 161. Workflow Cost UI Run Detail 可以显示: ```text Total Cost Actions: $0.20 Agent: $1.20 Storage: $0.03 Network: $0.01 Total: $1.44 ``` 具体计费数据由: ```text Usage / Observability Runtime ``` 提供。 --- # 162. Workflow Governance 组织可以制定: ```text 允许哪些 Workflow 允许哪些 Plugins 允许哪些 Actions 允许哪些 Providers 允许哪些 Environments 是否必须 Approval 最大预算 最大运行时间 ``` Policy Runtime 统一执行。 --- # 163. Workflow Governance 不放在 Workflow Engine 禁止: ```text WorkflowEngine if production: requireApproval() ``` 这种业务化安全代码。 应该: ```text Workflow ↓ Security Policy ↓ Approval Runtime ``` --- # 164. Workflow SDK 提供: ```ts @devos/workflow-sdk ``` 允许开发者: ```ts defineWorkflow(...) defineActionNode(...) defineCondition(...) defineParallel(...) defineApproval(...) ``` 但 SDK 不拥有 Runtime。 --- # 165. Declarative SDK 例如: ```ts defineWorkflow({ id: 'content.pipeline', nodes: [ action('generate', 'content.generate'), approval('approve'), action('publish', 'content.publish'), ], edges: [ edge('generate', 'approve'), edge('approve', 'publish'), ], }) ``` 最终生成: ```text Workflow Definition ``` --- # 166. Workflow Definition as Source of Truth 可以有: ```text YAML JSON TypeScript SDK Visual Editor Agent Generated Draft ``` 但最终都必须转换成: ```text Canonical Workflow Definition ``` 只有 Canonical Definition 可以 Publish。 --- # 167. Canonicalization Publish 前: ```text Parse ↓ Normalize ↓ Sort stable fields ↓ Validate ↓ Canonical JSON ↓ Checksum ``` 这样: ```text 同一个 Definition = 同一个 checksum ``` --- # 168. Workflow Checksum 记录: ```text definitionChecksum ``` 用于: ```text reproducibility upgrade audit marketplace migration debugging ``` --- # 169. Workflow Security Checklist 每个 Workflow Publish 必须: ```text [ ] 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。 严格按照: ```text 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 必须是: ```text Create Workflow ↓ Validate ↓ Publish ↓ Manual Trigger ↓ Workflow Run ↓ Action Node ↓ Execution ↓ Event ↓ Workflow Continue ↓ Completed ``` 不要第一步就实现: ```text BPMN Loop Parallel Agent Marketplace Visual Editor ``` --- # 172. 第二 Vertical Slice ```text Schedule ↓ Workflow ↓ Condition ↓ Branch ↓ Action ↓ Completed ``` --- # 173. 第三 Vertical Slice ```text Workflow ↓ Task Node ↓ Task ↓ Jobs ↓ Worker ↓ Task Completed Event ↓ Workflow Resume ``` --- # 174. 第四 Vertical Slice ```text Workflow ↓ Approval ↓ Waiting ↓ Approval Event ↓ Resume ↓ Action ↓ Completed ``` --- # 175. 第五 Vertical Slice ```text Workflow ↓ Agent Node ↓ Agent Runtime ↓ Skill ↓ Action ↓ Agent Result ↓ Workflow Continue ``` --- # 176. Definition of Done Workflow Runtime 第一阶段完成必须满足: ```text [ ] 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 必须自动验证: ```text Workflow → Action Runtime Workflow → Task Runtime Workflow → Event Runtime Workflow → Security Runtime Workflow → Config Runtime Workflow → Storage Runtime ``` 而不是: ```text Workflow → DB Workflow → Redis Workflow → Provider Workflow → Secret ``` --- # 178. Forbidden Patterns 以下代码视为架构违规: ```ts // 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 功能时,必须遵守: ```text 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 提交代码前必须回答: ```text 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 的最终关系 完整关系: ```text 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 可以生成: ```text Workflow Workflow Templates Workflow Actions Workflow Triggers ``` 例如: ```text devos create project seo-platform ``` 自动获得: ```text SEO capabilities + Workflow Runtime + Task Runtime + Agent Runtime ``` 业务项目只定义: ```text Workflow Definitions ``` 而不是重新实现: ```text Workflow Engine ``` --- # 183. Workflow 与官方 Modules 官方 Module 可以提供: ```text SEO Workflow Templates DevOps Deployment Workflows CRM Lead Workflows Content Workflows Data Import Workflows ``` 例如: ```text seo.daily.audit seo.content.pipeline devops.deploy.production crm.lead.qualification ``` Module 提供业务定义。 DevOS 提供 Runtime。 --- # 184. Workflow 与 Plugin Marketplace 最终生态可以形成: ```text Plugin ├── Actions ├── Queries ├── Providers ├── Triggers ├── Workflow Nodes └── Workflow Templates ``` 因此一个 Plugin 可以: ```text 安装 GitHub Plugin ↓ 获得 GitHub Actions ↓ 获得 GitHub Events ↓ 获得 GitHub Workflow Templates ``` 但: > GitHub Plugin 不需要自己的 Workflow Engine。 --- # 185. DevOS Workflow 的核心优势 DevOS Workflow 不追求: ```text 做一个最复杂的 BPMN 平台 ``` 而追求: ```text Resource ↓ Action ↓ Workflow ↓ Task ↓ Agent ↓ Event ↓ Execution ``` 所有能力都能够: ```text UI API CLI Plugin MCP Skill Agent Workflow ``` 共享。 --- # 186. 最终 Runtime 分工 必须固定为: ```text 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 最终必须形成: ```text 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 应能够明确实现: ```text [✓] 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 的最终边界:** ```text Workflow ↓ ORCHESTRATION Action ↓ EXECUTION Task ↓ DURABLE WORK Agent ↓ REASONING Event ↓ SIGNAL Approval ↓ HUMAN DECISION ``` **DevOS 不允许任何一个 Runtime 吞掉其他 Runtime 的职责。**