# DevOS Event / Audit / Observability Runtime > Version: 1.0 > Status: Implementation Specification > Target: Zcode > Previous: 09_TASK_JOB_QUEUE_RUNTIME.md > Next: 11_* --- # 1. 目标 DevOS 必须建立统一的: - Event Runtime - Event Bus - Audit Runtime - Log Runtime - Metric Runtime - Trace Runtime - Notification Runtime - Observability Runtime 所有 Core、Plugin、MCP、Skill、Agent、Task、Job、Action 都必须接入这一套基础设施。 禁止每个模块自己实现: - event emitter - audit logger - operation log - notification - task log - agent log - plugin log 必须统一进入 DevOS Runtime。 --- # 2. 核心原则 DevOS 中所有重要行为都应该形成: ```text Action ↓ Execution ↓ Event ├── Audit ├── Log ├── Metric ├── Trace ├── Notification ├── Task Update ├── Agent Observation └── Webhook / Integration ```` 最终形成: ```text ┌───────────────┐ │ Action │ └───────┬───────┘ ↓ ┌───────────────┐ │ Execution │ └───────┬───────┘ ↓ ┌───────────────┐ │ Event │ └───────┬───────┘ ┌───────────┼───────────┐ ↓ ↓ ↓ Audit Log Metric ↓ ↓ ↓ Security Debugging Monitoring │ └──────────┬──────────┘ ↓ Observability ↓ Human / Agent / UI ``` --- # 3. Event 与 Audit 的区别 必须严格区分。 ## Event Event 表示: > 系统中发生了一件事情。 例如: ```text user.created website.scanned task.created task.completed job.failed server.deployed agent.run.completed plugin.installed ``` Event 是系统运行机制的一部分。 --- ## Audit Audit 表示: > 谁,在什么上下文中,对什么对象,执行了什么行为,以及结果是什么。 例如: ```text User Alice ↓ Action: server.production.deploy ↓ Server: srv-001 ↓ Result: success ``` Audit 是安全、合规、追责记录。 --- # 4. Event 类型 Event 必须使用 namespace。 格式: ```text .. ``` 例如: ```text core.user.created core.user.updated core.user.deleted core.task.created core.task.started core.task.completed core.task.failed core.job.queued core.job.started core.job.completed core.job.failed core.execution.started core.execution.completed core.execution.failed agent.run.started agent.run.completed agent.run.failed plugin.installed plugin.uninstalled plugin.enabled plugin.disabled mcp.connected mcp.disconnected seo.website.scanned seo.article.generated devops.server.deployed ``` 禁止使用: ```text created updated failed success ``` 这种没有 namespace 的 Event。 --- # 5. Event Schema 推荐: ```ts export interface DevEvent { id: string type: string version: number timestamp: Date organizationId?: string projectId?: string actor?: EventActor resource?: EventResource payload: T metadata?: Record correlationId?: string causationId?: string requestId?: string executionId?: string taskId?: string jobId?: string } ``` --- # 6. Event Actor ```ts export interface EventActor { type: 'user' | 'agent' | 'service' | 'system' id?: string name?: string } ``` 例如: ```json { "type": "agent", "id": "agent-seo" } ``` --- # 7. Event Resource ```ts export interface EventResource { type: string id: string name?: string } ``` 例如: ```json { "type": "seo.website", "id": "website_123" } ``` --- # 8. Correlation ID 必须支持: ```text correlationId ``` 用于把多个操作关联起来。 例如: ```text User Request correlationId = abc ↓ Agent Run ↓ Task ↓ Job ↓ Action ↓ Execution ↓ External API ``` 所有下游 Event 都应该携带: ```text correlationId = abc ``` 这样 UI 可以展示完整执行链。 --- # 9. Causation ID 必须支持: ```text causationId ``` 表示: > 当前 Event 是由哪个 Event 导致的。 例如: ```text website.updated ↓ website.scan.requested ↓ task.created ↓ job.created ↓ execution.started ``` 这样可以构建事件因果链。 --- # 10. Event Bus 实现统一: ```ts interface EventBus { publish(event: DevEvent): Promise publishMany(events: DevEvent[]): Promise subscribe( pattern: string, handler: EventHandler ): Promise unsubscribe( subscriptionId: string ): Promise } ``` --- # 11. Event Handler ```ts export interface EventHandler { ( event: DevEvent, context: EventContext ): Promise } ``` Context: ```ts export interface EventContext { correlationId: string signal: AbortSignal metadata: Record } ``` --- # 12. Event 不应该直接调用业务逻辑 错误: ```ts eventBus.subscribe( 'seo.website.updated', async event => { await db.website.update(...) await crawler.scan(...) await sendEmail(...) } ) ``` Event Handler 应该创建正常的: ```text Task Job Action ``` 而不是绕过 Runtime。 正确: ```text Event ↓ Event Handler ↓ Task ↓ Job ↓ Action Runtime ``` --- # 13. Event Delivery 默认采用: ```text At Least Once ``` 不假设: ```text Exactly Once ``` 因此 Handler 必须支持: ```text idempotency ``` --- # 14. Event Inbox 对于重要 Consumer,应实现 Inbox。 ```ts interface EventInbox { eventId: string consumerId: string processedAt?: Date status: 'pending' | 'processed' | 'failed' error?: string } ``` 处理逻辑: ```text Receive Event ↓ Check Inbox ↓ Already processed? ↓ Yes ↓ No Ignore Execute ↓ Mark Done ``` 防止重复消费。 --- # 15. Event Outbox 必须实现: ```text Transactional Outbox ``` 禁止: ```ts await db.task.create() await eventBus.publish(...) ``` 因为可能出现: ```text DB 成功 Event 失败 ``` 导致系统状态不一致。 --- # 16. Outbox Schema ```ts interface OutboxEvent { id: string type: string aggregateType?: string aggregateId?: string payload: unknown status: 'pending' | 'published' | 'failed' attempts: number nextAttemptAt?: Date createdAt: Date publishedAt?: Date error?: string } ``` Transaction: ```text DB Transaction ├── Business Data └── Outbox Event ↓ Commit ↓ Outbox Worker ↓ Event Bus ``` --- # 17. Event Retention Event 必须区分: ### Operational Event 例如: ```text job.progress worker.heartbeat execution.log ``` 可以短期保存。 ### Domain Event 例如: ```text website.created server.deployed user.created ``` 应该长期保存。 ### Audit Event 根据安全/合规要求长期保存。 --- # 18. Audit Runtime 实现: ```ts interface AuditService { record(input: AuditInput): Promise } ``` --- # 19. Audit Schema ```ts interface AuditRecord { id: string timestamp: Date organizationId?: string projectId?: string actorType: 'user' | 'agent' | 'service' | 'system' actorId?: string actionId: string resourceType?: string resourceId?: string status: 'success' | 'failed' | 'denied' requestId?: string executionId?: string taskId?: string jobId?: string correlationId?: string inputSummary?: unknown outputSummary?: unknown error?: { code?: string message: string } ip?: string userAgent?: string metadata?: Record } ``` --- # 20. Audit 必须在 Action Runtime 中自动生成 不能依赖开发者手动调用。 错误: ```ts await action() await audit.record(...) ``` 正确: ```text ActionRuntime ↓ Authorization ↓ Audit Start ↓ Execute ↓ Audit Result ``` --- # 21. Audit 权限 Audit 本身也是敏感 Resource: ```text core.audit ``` Actions: ```text core.audit.list core.audit.get core.audit.export ``` 普通用户不能查看所有 Audit。 必须支持: ```text organization scope project scope resource scope actor scope ``` --- # 22. Audit 不保存敏感原文 禁止直接保存: ```text password access_token refresh_token api_key private_key cookie secret ``` 必须经过: ```text Sensitive Data Redaction ``` 例如: ```json { "apiKey": "[REDACTED]", "password": "[REDACTED]" } ``` --- # 23. Log Runtime 实现统一: ```ts interface Logger { debug(message: string, meta?: object): void info(message: string, meta?: object): void warn(message: string, meta?: object): void error(message: string, meta?: object): void } ``` --- # 24. Structured Logging 禁止: ```ts console.log( `Deploy server ${serverId} failed` ) ``` 应该: ```ts logger.error( 'Server deployment failed', { serverId, executionId, taskId, correlationId, errorCode } ) ``` --- # 25. Log Schema ```ts interface LogEntry { timestamp: Date level: | 'debug' | 'info' | 'warn' | 'error' message: string service?: string module?: string organizationId?: string actorId?: string correlationId?: string requestId?: string executionId?: string taskId?: string jobId?: string metadata?: Record } ``` --- # 26. Log 与 Event 不混合 Event: ```text website.scan.completed ``` Log: ```text crawler request took 1.2s ``` Event 是系统事实。 Log 是运行过程信息。 --- # 27. Task Log Task 必须能够关联 Log。 例如: ```text Task ├── Event timeline ├── Jobs ├── Executions ├── Logs ├── Artifacts └── Audit ``` UI 可以: ```text Task #123 ────────────────────── Timeline Logs Jobs Executions Artifacts Audit ``` --- # 28. Metric Runtime 必须提供: ```ts interface Metrics { counter( name: string, value?: number, labels?: Record ): void gauge( name: string, value: number, labels?: Record ): void histogram( name: string, value: number, labels?: Record ): void } ``` --- # 29. 标准 Metric 至少实现: ```text devos_action_total devos_action_success_total devos_action_failed_total devos_action_duration_ms devos_task_total devos_task_completed_total devos_task_failed_total devos_job_total devos_job_retry_total devos_job_duration_ms devos_queue_depth devos_worker_active devos_worker_unhealthy devos_agent_run_total devos_agent_tokens_total devos_agent_cost_total devos_mcp_request_total devos_mcp_error_total ``` --- # 30. Metric Label 推荐: ```text action_id namespace status queue worker plugin ``` 禁止把: ```text user_id request_id execution_id ``` 这种高基数字段作为 Metric Label。 这些应该进入 Log/Trace。 --- # 31. Trace Runtime DevOS 应支持分布式 Trace。 核心: ```text traceId spanId parentSpanId ``` 例如: ```text HTTP Request trace ↓ Agent Run ↓ Task ↓ Job ↓ Action ↓ MCP ↓ External API ``` --- # 32. Trace Schema ```ts interface TraceContext { traceId: string spanId: string parentSpanId?: string } ``` 所有 Runtime Context 应该能够携带 Trace。 --- # 33. Action Trace Action Runtime 自动创建: ```text action.execute ``` Span: ```text action.execute ├── authorization ├── validation ├── transaction ├── handler ├── external-call └── event-publish ``` --- # 34. Agent Trace Agent Run: ```text agent.run ├── goal.parse ├── capability.search ├── planning ├── task.create ├── action.execute ├── observation ├── evaluation └── completion ``` 注意: **不要记录隐藏 Chain of Thought。** 只记录: ```text decision summary selected capability action result reason summary ``` --- # 35. Agent Observation Event Agent 可以订阅: ```text task.completed task.failed job.completed job.failed execution.completed execution.failed ``` 然后: ```text Observation ↓ Agent Evaluation ↓ Continue Replan Retry Ask Human Finish ``` --- # 36. Notification Runtime 实现: ```ts interface NotificationService { notify(input: NotificationInput): Promise } ``` 支持: ```text in-app email webhook Slack Discord Telegram ``` 具体 Provider 应该 Plugin 化。 --- # 37. Notification Resource 定义: ```text core.notification core.notification.channel core.notification.preference ``` Actions: ```text core.notification.send core.notification.channel.create core.notification.channel.update core.notification.channel.delete ``` --- # 38. Notification Event 例如: ```text task.failed agent.approval.required server.deployment.failed budget.exceeded worker.unhealthy ``` 通过 Notification Policy: ```text Event ↓ Notification Rule ↓ Channel ↓ Notification ``` --- # 39. Notification Rule ```ts interface NotificationRule { id: string name: string eventPattern: string enabled: boolean conditions?: Record channels: string[] template?: string cooldownSeconds?: number } ``` 例如: ```json { "eventPattern": "core.task.failed", "channels": ["email-admin"], "cooldownSeconds": 300 } ``` --- # 40. Notification 防爆 不能: ```text 1000 jobs failed ↓ 1000 emails ``` 必须支持: ```text deduplication aggregation cooldown rate limit batch notification ``` 例如: ```text 100 jobs failed ↓ 5 minutes aggregation ↓ 1 notification ``` --- # 41. Webhook Event Sink DevOS 可以把 Event 发送到外部 Webhook: ```text core.webhook ``` 配置: ```ts interface WebhookEndpoint { id: string url: string events: string[] enabled: boolean secret?: string headers?: Record } ``` 必须支持: ```text signature retry timeout backoff dead letter ``` --- # 42. Webhook Security 请求应该包含: ```text X-DevOS-Event X-DevOS-Event-Id X-DevOS-Timestamp X-DevOS-Signature ``` Signature: ```text HMAC-SHA256 ``` 防止伪造。 --- # 43. Observability Resource 统一: ```text core.event core.audit core.log core.metric core.trace core.notification ``` 但: **不是所有 Resource 都需要完整 CRUD UI。** 例如: ```text Metric Trace Log ``` 主要提供: ```text search filter view aggregation ``` --- # 44. Event Resource Actions ```text core.event.list core.event.get core.event.search core.event.replay ``` Replay 必须经过权限检查。 禁止普通用户随意 Replay: ```text payment.completed server.deployed ``` 这种高风险 Event。 --- # 45. Event Replay Event Replay 不应该直接重新执行原始 Handler。 应该: ```text Event ↓ Replay Request ↓ Authorization ↓ New Task / Job ↓ Action Runtime ``` 并产生新的: ```text correlationId ``` 以及: ```text causationId = originalEventId ``` --- # 46. Observability API 提供: ```http GET /api/events GET /api/events/:id GET /api/audits GET /api/audits/:id GET /api/logs GET /api/metrics GET /api/traces/:traceId GET /api/tasks/:id/timeline GET /api/executions/:id/logs ``` --- # 47. Task Timeline API 这是 DevOS UI 最重要的接口之一: ```http GET /api/tasks/:taskId/timeline ``` 返回: ```json [ { "timestamp": "...", "type": "task.created" }, { "timestamp": "...", "type": "job.queued" }, { "timestamp": "...", "type": "job.started" }, { "timestamp": "...", "type": "execution.started" }, { "timestamp": "...", "type": "execution.completed" }, { "timestamp": "...", "type": "job.completed" }, { "timestamp": "...", "type": "task.completed" } ] ``` --- # 48. UI:Task Timeline 必须提供: ```text Task #123 ──────────────────────────────── ● Task created │ ● Job #1 queued │ ● Job #1 started │ ● Website scan started │ ● MCP request │ ● Action completed │ ● Job #1 completed │ ● Task completed ``` 点击任意节点: ```text Event Execution Logs Audit Trace Input Output ``` --- # 49. UI:Global Event Explorer 提供: ```text Events ────────────────────────────── Search events... Type Actor Resource Status Organization Project Time Range ────────────────────────────── event timestamp actor resource correlation ``` --- # 50. UI:Audit Explorer 提供: ```text Audit ────────────────────────────── Actor Action Resource Status Time Organization Project ────────────────────────────── Alice server.deploy server-001 SUCCESS ``` 支持: ```text Search Filter Export Detail ``` --- # 51. UI:Execution Detail Execution 页面: ```text Execution #123 Status Duration Action Actor Task Job ────────────────── Input Output Logs Trace Events Audit Error ``` --- # 52. UI:Agent Run Agent Run: ```text Agent Run #123 ──────────────────────────── Goal Status Budget Tokens Cost Iterations ──────────────────────────── Plan 1. Search capabilities 2. Create task 3. Execute scan 4. Analyze result 5. Generate report ──────────────────────────── Observations Actions Tasks Events Result ``` 不要显示隐藏思维链。 --- # 53. Error Model 统一 Error: ```ts interface DevOSError { code: string message: string category: | 'validation' | 'authorization' | 'not_found' | 'conflict' | 'rate_limit' | 'timeout' | 'external' | 'internal' retryable: boolean details?: unknown cause?: string } ``` --- # 54. Error Event 统一: ```text core.execution.failed core.job.failed core.task.failed ``` Payload: ```json { "error": { "code": "EXTERNAL_TIMEOUT", "category": "timeout", "retryable": true } } ``` --- # 55. Observability Correlation 所有日志/Event/Audit/Trace 至少应该尽可能携带: ```text organizationId projectId actor requestId correlationId taskId jobId executionId traceId ``` 形成: ```text Organization ↓ Project ↓ Actor ↓ Request ↓ Correlation ↓ Task ↓ Job ↓ Execution ↓ Trace ↓ Event ↓ Log ↓ Audit ``` --- # 56. Storage 推荐: ## PostgreSQL 保存: ```text Event Audit Outbox Inbox Notification NotificationRule Webhook ``` ## Redis 保存: ```text Event Queue Pub/Sub Rate Limit Notification Dedup Short-lived Trace State ``` ## Log Storage 第一阶段可以: ```text PostgreSQL ``` 但必须抽象: ```ts interface LogStore ``` 未来可以接: ```text Loki Elasticsearch OpenSearch ClickHouse ``` --- # 57. Metric Storage 不要把高频 Metric 永久写 PostgreSQL。 设计: ```ts interface MetricProvider { counter(...) gauge(...) histogram(...) } ``` 默认可以接: ```text Prometheus / OpenTelemetry ``` --- # 58. Trace Provider 设计: ```ts interface TraceProvider { startSpan(...) endSpan(...) addEvent(...) setAttribute(...) } ``` 推荐: ```text OpenTelemetry ``` 不要自行实现完整分布式 Trace 协议。 --- # 59. OpenTelemetry Integration DevOS 应尽量兼容: ```text OpenTelemetry ``` 统一生成: ```text Trace Span Metric Log correlation ``` 这样以后可以接: ```text Grafana Prometheus Tempo Loki Jaeger ``` 而无需修改业务代码。 --- # 60. Event-driven Architecture DevOS 不应该成为纯 CRUD Backend。 应该逐渐形成: ```text Command ↓ Action ↓ State Change ↓ Event ↓ Reaction ``` 例如: ```text server.deploy ↓ server.updated ↓ server.deployment.completed ↓ notification ↓ audit ↓ agent observation ``` --- # 61. Event 与 Agent Agent 不应该轮询数据库: 错误: ```text while true: SELECT task WHERE status = completed ``` 应该: ```text Event Bus ↓ Agent Observation ``` Agent 可以订阅: ```text task.completed task.failed job.failed approval.completed ``` --- # 62. Event 与 Plugin Plugin 安装后可以声明: ```ts interface PluginEventSubscription { pattern: string handler: string } ``` 例如 SEO Plugin: ```text core.task.completed seo.website.updated ``` 但 Handler 最终必须通过: ```text Action Runtime Task Runtime ``` 执行业务操作。 --- # 63. Event 与 MCP MCP 不应该拥有自己的 Event System。 MCP: ```text MCP request ↓ Action Runtime ↓ Execution ↓ Event ``` 如果外部 MCP 触发 DevOS: ```text MCP ↓ Action ↓ Task ↓ Event ``` --- # 64. Event 与 Scheduler Scheduler 产生: ```text schedule.triggered ``` 然后: ```text Schedule ↓ Event ↓ Task / Agent Goal ``` 例如: ```text Every day 09:00 ↓ schedule.triggered ↓ Agent Goal ↓ Task ``` --- # 65. Event 与 Webhook 外部: ```text GitHub Stripe Cloudflare CI/CD ``` 发送: ```text Webhook ↓ Verify ↓ Normalize ↓ Event ↓ Event Bus ``` Webhook Handler 不应该直接修改业务数据。 --- # 66. Event Schema Versioning Event 必须有: ```text version ``` 例如: ```text seo.website.scanned v1 seo.website.scanned v2 ``` Consumer 必须明确支持版本。 禁止无版本 Event Schema。 --- # 67. Backward Compatibility 推荐: ```text v1 v2 ``` 同时支持一段时间。 禁止直接修改: ```text v1 payload ``` 导致旧 Plugin 崩溃。 --- # 68. Event Naming Rules 统一: ```text .. ``` 推荐: ```text website.created website.updated website.deleted website.scanned website.published ``` 不要: ```text createWebsite websiteCreate scanWebsiteNow ``` --- # 69. Security Event 必须支持安全事件: ```text security.login.success security.login.failed security.permission.denied security.api_key.created security.api_key.revoked security.session.created security.session.revoked security.suspicious_activity ``` 这些 Event 可以进入: ```text Audit Notification Security Dashboard ``` --- # 70. Approval Event 与前面的危险 Action 集成: ```text approval.requested approval.approved approval.rejected approval.expired ``` 流程: ```text Agent ↓ Dangerous Action ↓ Approval Required ↓ approval.requested ↓ Human ↓ approval.approved ↓ Action Runtime ↓ Execution ``` --- # 71. Budget Event Agent / Task / Organization Budget: ```text budget.warning budget.exceeded budget.blocked ``` 例如: ```text Agent token budget > 80% ↓ budget.warning ``` 超过: ```text budget.exceeded ↓ Agent stopped ``` --- # 72. Health Event Worker: ```text worker.started worker.healthy worker.unhealthy worker.stopped ``` Queue: ```text queue.backpressure queue.stalled ``` Plugin: ```text plugin.health.failed ``` MCP: ```text mcp.health.failed ``` --- # 73. Observability Dashboard DevOS 首页应该提供基础: ```text System Health Tasks Jobs Workers Queues Actions Agents MCP Plugins Errors Costs ``` 例如: ```text Tasks Running 12 Failed 2 Completed 1234 Jobs Queued 31 Running 12 Retry 4 Workers Healthy 8 Unhealthy 1 Agents Running 4 Token usage 72% Errors Last hour 17 ``` --- # 74. Health Check 所有 Runtime 必须提供: ```text health() ``` 例如: ```ts interface HealthCheck { name: string status: 'healthy' | 'degraded' | 'unhealthy' latencyMs?: number details?: Record } ``` 系统: ```text GET /health GET /health/ready GET /health/live ``` --- # 75. Readiness Readiness 应检查: ```text PostgreSQL Redis Queue Worker Event Bus ``` 如果数据库不可用: ```text ready = false ``` --- # 76. Plugin Health Plugin Runtime 必须支持: ```text Plugin ├── enabled ├── installed ├── configured └── healthy ``` Plugin Health 可以产生: ```text plugin.health.failed ``` --- # 77. MCP Health MCP Server: ```text connected degraded disconnected ``` 产生: ```text mcp.connected mcp.disconnected mcp.health.failed ``` --- # 78. Cost Observability Agent / Action / MCP 都应该可以记录成本: ```ts interface UsageRecord { provider?: string model?: string tokensInput?: number tokensOutput?: number requests?: number estimatedCost?: number currency?: string } ``` 最终形成: ```text Organization ↓ Project ↓ Agent ↓ Task ↓ Job ↓ Execution ↓ Provider ↓ Cost ``` --- # 79. Cost Event 例如: ```text ai.usage.recorded ai.budget.warning ai.budget.exceeded ``` --- # 80. 数据脱敏 所有: ```text Log Event Audit Trace Notification ``` 进入 Storage 前都可以经过: ```ts RedactionService ``` 接口: ```ts interface RedactionService { redact(input: unknown): unknown } ``` 默认敏感字段: ```text password token accessToken refreshToken apiKey secret privateKey authorization cookie ``` --- # 81. Observability Middleware Action Runtime: ```text Request ↓ Trace Middleware ↓ Auth Middleware ↓ Audit Middleware ↓ Metrics Middleware ↓ Logger Context ↓ Action ↓ Event ``` --- # 82. Runtime Context 统一 Context: ```ts interface RuntimeContext { requestId: string correlationId: string traceId?: string actor: Actor organizationId?: string projectId?: string taskId?: string jobId?: string executionId?: string metadata: Record signal: AbortSignal } ``` Action / Task / Agent / MCP 都应该尽量复用。 --- # 83. Package Architecture Zcode 必须实现: ```text packages/ ├── event/ │ ├── types/ │ ├── registry/ │ ├── bus/ │ ├── publisher/ │ ├── subscriber/ │ ├── outbox/ │ └── inbox/ │ ├── audit/ │ ├── runtime/ │ ├── redaction/ │ └── policy/ │ ├── logging/ │ ├── logger/ │ ├── context/ │ └── transport/ │ ├── metrics/ │ ├── registry/ │ └── provider/ │ ├── tracing/ │ ├── runtime/ │ └── provider/ │ ├── notification/ │ ├── runtime/ │ ├── channels/ │ ├── templates/ │ └── rules/ │ └── observability/ ├── timeline/ ├── health/ ├── search/ └── dashboard/ ``` --- # 84. Database Models 至少: ```text events event_outbox event_inbox audit_records notification_rules notification_channels notifications webhook_endpoints webhook_deliveries ``` Log/Metric/Trace Storage 应通过 Provider 抽象。 --- # 85. Event Registry 实现: ```ts interface EventDefinition { type: string version: number description: string payloadSchema: ZodSchema sensitiveFields?: string[] } ``` Plugin 可以注册: ```ts eventRegistry.register(...) ``` 例如: ```text seo.website.scanned ``` --- # 86. Schema Validation Event Publish 时: ```text publish() ↓ Event Registry ↓ Find Definition ↓ Validate Payload ↓ Redact ↓ Persist Outbox ↓ Publish ``` 未知 Event: ```text development: error production: configurable ``` 推荐生产环境也拒绝没有 Schema 的 Domain Event。 --- # 87. Event Permission Event 本身可以定义 visibility: ```ts visibility: | 'public' | 'organization' | 'project' | 'private' | 'system' ``` 例如: ```text core.user.created ``` 不能让任意 Agent 读取完整 User Event。 必须经过: ```text Capability Discovery + Permission + Scope ``` --- # 88. Agent Event Access Agent 不能: ```text 读取所有 Event ``` 必须: ```text Agent Policy ↓ Allowed Event Types ↓ Organization Scope ↓ Resource Scope ``` --- # 89. Event Search 支持: ```text type actor resource organization project task job execution correlationId time range status ``` 例如: ```http GET /api/events? type=core.execution.failed& taskId=task_123 ``` --- # 90. Audit Search 支持: ```text actor action resource status organization project time ip ``` --- # 91. Timeline Aggregation Task Timeline 不应该查询十几个表后由前端拼接。 后端提供: ```text TimelineService ``` 统一聚合: ```text Events Audit Executions Jobs Logs Approvals Notifications ``` 然后输出: ```ts interface TimelineItem { id: string timestamp: Date type: string title: string status?: string resource?: EventResource actor?: EventActor metadata?: unknown } ``` --- # 92. Streaming Task/Agent/Execution 页面支持实时更新: 推荐: ```text SSE ``` 例如: ```http GET /api/tasks/:id/stream ``` 事件: ```text task.progress job.started execution.log execution.completed task.completed ``` WebSocket 可以作为未来扩展。 第一阶段优先 SSE。 --- # 93. Streaming Architecture ```text Action ↓ Event Bus ↓ Event Stream ↓ SSE Gateway ↓ Browser ``` 禁止 UI 直接连接 Worker。 --- # 94. Real-time Agent UI Agent Chat 可以实时显示: ```text Agent: 我正在分析目标... Capability: seo.website.scan Task: Task #123 created Execution: Scanning website... Result: Found 37 issues Agent: 正在生成修复计划... ``` 所有这些都应该来自: ```text Event ``` 而不是 Agent Runtime 直接操作 UI。 --- # 95. Audit 与 Agent Agent 执行: ```text Agent ↓ Action ``` Audit 必须记录: ```text actorType = agent actorId = agent_x ``` 同时应该保留: ```text initiatedByUser ``` 如果数据模型需要: ```ts initiator?: { type: 'user' | 'agent' | 'system' id?: string } ``` 最终可以追溯: ```text User Alice ↓ Agent SEO ↓ Task ↓ Action ↓ Execution ``` --- # 96. Golden Rule 整个 DevOS 的可观察性必须遵循: ```text ONE EVENT SYSTEM ONE AUDIT SYSTEM ONE LOGGING SYSTEM ONE METRIC SYSTEM ONE TRACE SYSTEM ONE NOTIFICATION SYSTEM ``` 禁止: ```text Plugin EventBus Agent EventBus Task EventBus MCP EventBus SEO EventBus ``` 这些都必须接入: ```text DevOS Event Runtime ``` --- # 97. 与前面 Runtime 的完整关系 现在 DevOS Runtime 形成: ```text User │ Agent │ Goal │ Task │ Job │ Queue │ Worker │ Action │ Action Runtime │ Execution │ ┌────────┴────────┐ ↓ ↓ Event Result │ ┌───────┼────────┐ ↓ ↓ ↓ Audit Log Metric │ │ │ └───────┼────────┘ ↓ Trace ↓ Observability │ ┌──────┼──────┐ ↓ ↓ ↓ UI Agent Notification ``` --- # 98. Zcode 禁止事项 以下全部禁止: ```text ❌ console.log 代替 Logger ❌ Plugin 自己实现 EventBus ❌ Agent 自己实现 EventBus ❌ MCP 自己保存业务 Event ❌ Action Handler 自己写 Audit ❌ Controller 自己写 Audit ❌ UI 自己轮询数据库 ❌ Agent 轮询数据库等待 Task ❌ Event Handler 直接修改业务数据库 ❌ Event Handler 绕过 Action Runtime ❌ 保存密码/token/private key ❌ 使用高基数字段作为 Metric Label ❌ 修改已发布 Event Schema ❌ 把 Chain of Thought 写入数据库 ``` --- # 99. Acceptance Criteria Zcode 完成后必须满足: ## Event * [ ] Event Registry * [ ] Event Schema * [ ] Event Bus * [ ] Publish * [ ] Subscribe * [ ] Event Version * [ ] Correlation ID * [ ] Causation ID * [ ] Event Permission * [ ] Event Search * [ ] Event Replay * [ ] Event Outbox * [ ] Event Inbox * [ ] Retry * [ ] Dead Letter ## Audit * [ ] Action 自动 Audit * [ ] Success Audit * [ ] Failed Audit * [ ] Denied Audit * [ ] Actor * [ ] Resource * [ ] Organization Scope * [ ] Project Scope * [ ] Redaction * [ ] Audit Search * [ ] Audit Export ## Logging * [ ] Structured Logger * [ ] Context * [ ] Request ID * [ ] Correlation ID * [ ] Task ID * [ ] Job ID * [ ] Execution ID * [ ] Redaction ## Metrics * [ ] Counter * [ ] Gauge * [ ] Histogram * [ ] Action Metrics * [ ] Task Metrics * [ ] Job Metrics * [ ] Queue Metrics * [ ] Worker Metrics * [ ] Agent Metrics * [ ] Cost Metrics ## Trace * [ ] Trace ID * [ ] Span * [ ] Parent Span * [ ] Action Trace * [ ] Agent Trace * [ ] MCP Trace * [ ] External Call Trace * [ ] OpenTelemetry Provider ## Notification * [ ] Notification Runtime * [ ] Channel * [ ] Rule * [ ] Template * [ ] Email * [ ] Webhook * [ ] Deduplication * [ ] Cooldown * [ ] Aggregation * [ ] Retry ## UI * [ ] Event Explorer * [ ] Audit Explorer * [ ] Task Timeline * [ ] Job Timeline * [ ] Execution Detail * [ ] Agent Run Detail * [ ] Logs * [ ] Trace * [ ] Real-time SSE * [ ] System Health Dashboard --- # 100. Integration Tests 必须至少实现以下测试: ### Test 1 ```text Action ↓ Execution ↓ Event ↓ Audit ``` 验证整个链条存在。 ### Test 2 ```text DB Transaction ↓ Outbox ↓ Event Bus ``` 验证事务一致性。 ### Test 3 重复 Event: ```text same eventId ↓ Inbox ↓ only once handler effect ``` ### Test 4 Agent: ```text Goal ↓ Task ↓ Job ↓ Action ↓ Execution ↓ Event ↓ Agent Observation ``` ### Test 5 Plugin: ```text Plugin ↓ Action ↓ Event ↓ Audit ``` ### Test 6 MCP: ```text MCP ↓ Action Runtime ↓ Execution ↓ Event ↓ Audit ``` ### Test 7 权限: ```text Unauthorized Event ↓ Access Denied ``` ### Test 8 敏感数据: ```text password/token/apiKey ↓ Log/Audit/Event ↓ REDACTED ``` ### Test 9 Task Timeline: ```text Task Job Execution Event Audit Log ``` 能够被统一聚合。 ### Test 10 SSE: ```text Task running ↓ Event ↓ SSE ↓ Browser ``` 验证实时 UI。 --- # 101. 最终架构 完成 10 之后,DevOS 的基础 Runtime 应该已经形成: ```text ┌────────────────────────────────────────────┐ │ DevOS │ │ │ │ Identity / RBAC / Organization │ │ │ │ Resource Registry │ │ Action Registry │ │ Capability Registry │ │ │ │ Agent Runtime │ │ Skill Runtime │ │ MCP Runtime │ │ │ │ Task Runtime │ │ Job Runtime │ │ Queue Runtime │ │ Worker Runtime │ │ Scheduler │ │ │ │ Action Runtime │ │ Execution Runtime │ │ │ │ Event Runtime │ │ Audit Runtime │ │ Logging Runtime │ │ Metrics Runtime │ │ Trace Runtime │ │ Notification Runtime │ │ │ │ Plugin Runtime │ │ │ │ UI Shell │ └────────────────────────────────────────────┘ │ ↓ ┌─────────────────┐ │ App Extensions │ ├─────────────────┤ │ SEO │ │ DevOps │ │ CRM │ │ Content │ │ Marketing │ │ Other Domains │ └─────────────────┘ ``` --- # 102. 最重要的最终原则 DevOS 到目前为止必须严格遵守: ```text Resource ↓ Action ↓ Action Runtime ↓ Execution ↓ Event ↓ Observability ``` 异步: ```text Task ↓ Job ↓ Queue ↓ Worker ↓ Action Runtime ↓ Execution ↓ Event ``` Agent: ```text Goal ↓ Agent ↓ Skill ↓ Capability ↓ Task ↓ Action ↓ Execution ↓ Event ↓ Observation ↓ Agent ``` Plugin: ```text Plugin ├── Resource ├── Action ├── Skill ├── MCP ├── Workflow ├── Event └── UI ↓ DevOS Registry ↓ DevOS Runtime ``` **最终禁止任何模块建立第二套 Runtime。** DevOS 的核心不是: ```text 一堆 CRUD ``` 而是: ```text Resource + Action + Task + Execution + Event + Agent + Capability + Observability ``` 这才是整个 DevOS 能够持续扩展、让 SEO / DevOps / CRM / Content 等应用共享同一套底座的核心。