Files
devos/Docs/DevOS-Platform-v2/10_EVENT_AUDIT_OBSERVABILITY_RUNTIME.md
phptits b1f17cf637 v2 platform foundation (docs 01/02/03): Action Runtime + Registry + unified API
- v2 foundation: ActionResult/DevError/ActorContext/ResourceRef/Execution types
- ActionRegistry + ResourceRegistry (namespaced types, FAIL FAST on duplicates)
- ActionRuntime pipeline: validate -> authorize -> middleware -> handler ->
  output validation -> audit -> event -> execution persisted (devos_action_executions)
- Legacy bridge: v1 services registered as devops.*/core.* resources & actions (47 actions, 9 resources)
- Unified Action API: POST /api/v2/actions/:actionId, GET discovery (actions/resources)
- 10 v2 unit tests (registry fail-fast, validation, authz, failure audit, events)
2026-09-10 21:09:44 +00:00

42 KiB
Raw Permalink Blame History

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 中所有重要行为都应该形成:

Action
  ↓
Execution
  ↓
Event
  ├── Audit
  ├── Log
  ├── Metric
  ├── Trace
  ├── Notification
  ├── Task Update
  ├── Agent Observation
  └── Webhook / Integration

最终形成:

              ┌───────────────┐
              │     Action    │
              └───────┬───────┘
                      ↓
              ┌───────────────┐
              │   Execution   │
              └───────┬───────┘
                      ↓
              ┌───────────────┐
              │     Event     │
              └───────┬───────┘
          ┌───────────┼───────────┐
          ↓           ↓           ↓
       Audit        Log        Metric
          ↓           ↓           ↓
       Security    Debugging   Monitoring
          │
          └──────────┬──────────┘
                     ↓
                 Observability
                     ↓
            Human / Agent / UI

3. Event 与 Audit 的区别

必须严格区分。

Event

Event 表示:

系统中发生了一件事情。

例如:

user.created
website.scanned
task.created
task.completed
job.failed
server.deployed
agent.run.completed
plugin.installed

Event 是系统运行机制的一部分。


Audit

Audit 表示:

谁,在什么上下文中,对什么对象,执行了什么行为,以及结果是什么。

例如:

User Alice
    ↓
Action: server.production.deploy
    ↓
Server: srv-001
    ↓
Result: success

Audit 是安全、合规、追责记录。


4. Event 类型

Event 必须使用 namespace。

格式:

<namespace>.<resource>.<event>

例如:

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

禁止使用:

created
updated
failed
success

这种没有 namespace 的 Event。


5. Event Schema

推荐:

export interface DevEvent<T = unknown> {
  id: string

  type: string

  version: number

  timestamp: Date

  organizationId?: string

  projectId?: string

  actor?: EventActor

  resource?: EventResource

  payload: T

  metadata?: Record<string, unknown>

  correlationId?: string

  causationId?: string

  requestId?: string

  executionId?: string

  taskId?: string

  jobId?: string
}

6. Event Actor

export interface EventActor {
  type: 'user' | 'agent' | 'service' | 'system'

  id?: string

  name?: string
}

例如:

{
  "type": "agent",
  "id": "agent-seo"
}

7. Event Resource

export interface EventResource {
  type: string

  id: string

  name?: string
}

例如:

{
  "type": "seo.website",
  "id": "website_123"
}

8. Correlation ID

必须支持:

correlationId

用于把多个操作关联起来。

例如:

User Request
    correlationId = abc
        ↓
Agent Run
        ↓
Task
        ↓
Job
        ↓
Action
        ↓
Execution
        ↓
External API

所有下游 Event 都应该携带:

correlationId = abc

这样 UI 可以展示完整执行链。


9. Causation ID

必须支持:

causationId

表示:

当前 Event 是由哪个 Event 导致的。

例如:

website.updated
      ↓
website.scan.requested
      ↓
task.created
      ↓
job.created
      ↓
execution.started

这样可以构建事件因果链。


10. Event Bus

实现统一:

interface EventBus {
  publish<T>(event: DevEvent<T>): Promise<void>

  publishMany(events: DevEvent[]): Promise<void>

  subscribe(
    pattern: string,
    handler: EventHandler
  ): Promise<Subscription>

  unsubscribe(
    subscriptionId: string
  ): Promise<void>
}

11. Event Handler

export interface EventHandler<T = unknown> {
  (
    event: DevEvent<T>,
    context: EventContext
  ): Promise<void>
}

Context:

export interface EventContext {
  correlationId: string

  signal: AbortSignal

  metadata: Record<string, unknown>
}

12. Event 不应该直接调用业务逻辑

错误:

eventBus.subscribe(
  'seo.website.updated',
  async event => {
    await db.website.update(...)
    await crawler.scan(...)
    await sendEmail(...)
  }
)

Event Handler 应该创建正常的:

Task
Job
Action

而不是绕过 Runtime。

正确:

Event
 ↓
Event Handler
 ↓
Task
 ↓
Job
 ↓
Action Runtime

13. Event Delivery

默认采用:

At Least Once

不假设:

Exactly Once

因此 Handler 必须支持:

idempotency

14. Event Inbox

对于重要 Consumer,应实现 Inbox。

interface EventInbox {
  eventId: string

  consumerId: string

  processedAt?: Date

  status: 'pending' | 'processed' | 'failed'

  error?: string
}

处理逻辑:

Receive Event
      ↓
Check Inbox
      ↓
Already processed?
   ↓ Yes       ↓ No
 Ignore       Execute
                ↓
             Mark Done

防止重复消费。


15. Event Outbox

必须实现:

Transactional Outbox

禁止:

await db.task.create()

await eventBus.publish(...)

因为可能出现:

DB 成功
Event 失败

导致系统状态不一致。


16. Outbox Schema

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:

DB Transaction
    ├── Business Data
    └── Outbox Event
          ↓
       Commit
          ↓
    Outbox Worker
          ↓
      Event Bus

17. Event Retention

Event 必须区分:

Operational Event

例如:

job.progress
worker.heartbeat
execution.log

可以短期保存。

Domain Event

例如:

website.created
server.deployed
user.created

应该长期保存。

Audit Event

根据安全/合规要求长期保存。


18. Audit Runtime

实现:

interface AuditService {
  record(input: AuditInput): Promise<AuditRecord>
}

19. Audit Schema

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<string, unknown>
}

20. Audit 必须在 Action Runtime 中自动生成

不能依赖开发者手动调用。

错误:

await action()

await audit.record(...)

正确:

ActionRuntime
   ↓
Authorization
   ↓
Audit Start
   ↓
Execute
   ↓
Audit Result

21. Audit 权限

Audit 本身也是敏感 Resource:

core.audit

Actions:

core.audit.list
core.audit.get
core.audit.export

普通用户不能查看所有 Audit。

必须支持:

organization scope
project scope
resource scope
actor scope

22. Audit 不保存敏感原文

禁止直接保存:

password
access_token
refresh_token
api_key
private_key
cookie
secret

必须经过:

Sensitive Data Redaction

例如:

{
  "apiKey": "[REDACTED]",
  "password": "[REDACTED]"
}

23. Log Runtime

实现统一:

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

禁止:

console.log(
  `Deploy server ${serverId} failed`
)

应该:

logger.error(
  'Server deployment failed',
  {
    serverId,
    executionId,
    taskId,
    correlationId,
    errorCode
  }
)

25. Log Schema

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<string, unknown>
}

26. Log 与 Event 不混合

Event:

website.scan.completed

Log:

crawler request took 1.2s

Event 是系统事实。

Log 是运行过程信息。


27. Task Log

Task 必须能够关联 Log。

例如:

Task
 ├── Event timeline
 ├── Jobs
 ├── Executions
 ├── Logs
 ├── Artifacts
 └── Audit

UI 可以:

Task #123
──────────────────────
Timeline
Logs
Jobs
Executions
Artifacts
Audit

28. Metric Runtime

必须提供:

interface Metrics {
  counter(
    name: string,
    value?: number,
    labels?: Record<string, string>
  ): void

  gauge(
    name: string,
    value: number,
    labels?: Record<string, string>
  ): void

  histogram(
    name: string,
    value: number,
    labels?: Record<string, string>
  ): void
}

29. 标准 Metric

至少实现:

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

推荐:

action_id
namespace
status
queue
worker
plugin

禁止把:

user_id
request_id
execution_id

这种高基数字段作为 Metric Label。

这些应该进入 Log/Trace。


31. Trace Runtime

DevOS 应支持分布式 Trace。

核心:

traceId
spanId
parentSpanId

例如:

HTTP Request
    trace
      ↓
Agent Run
      ↓
Task
      ↓
Job
      ↓
Action
      ↓
MCP
      ↓
External API

32. Trace Schema

interface TraceContext {
  traceId: string

  spanId: string

  parentSpanId?: string
}

所有 Runtime Context 应该能够携带 Trace。


33. Action Trace

Action Runtime 自动创建:

action.execute

Span:

action.execute
├── authorization
├── validation
├── transaction
├── handler
├── external-call
└── event-publish

34. Agent Trace

Agent Run:

agent.run
 ├── goal.parse
 ├── capability.search
 ├── planning
 ├── task.create
 ├── action.execute
 ├── observation
 ├── evaluation
 └── completion

注意:

不要记录隐藏 Chain of Thought。

只记录:

decision summary
selected capability
action
result
reason summary

35. Agent Observation Event

Agent 可以订阅:

task.completed
task.failed
job.completed
job.failed
execution.completed
execution.failed

然后:

Observation
   ↓
Agent Evaluation
   ↓
Continue
Replan
Retry
Ask Human
Finish

36. Notification Runtime

实现:

interface NotificationService {
  notify(input: NotificationInput): Promise<void>
}

支持:

in-app
email
webhook
Slack
Discord
Telegram

具体 Provider 应该 Plugin 化。


37. Notification Resource

定义:

core.notification
core.notification.channel
core.notification.preference

Actions:

core.notification.send
core.notification.channel.create
core.notification.channel.update
core.notification.channel.delete

38. Notification Event

例如:

task.failed
agent.approval.required
server.deployment.failed
budget.exceeded
worker.unhealthy

通过 Notification Policy:

Event
 ↓
Notification Rule
 ↓
Channel
 ↓
Notification

39. Notification Rule

interface NotificationRule {
  id: string

  name: string

  eventPattern: string

  enabled: boolean

  conditions?: Record<string, unknown>

  channels: string[]

  template?: string

  cooldownSeconds?: number
}

例如:

{
  "eventPattern": "core.task.failed",
  "channels": ["email-admin"],
  "cooldownSeconds": 300
}

40. Notification 防爆

不能:

1000 jobs failed
↓
1000 emails

必须支持:

deduplication
aggregation
cooldown
rate limit
batch notification

例如:

100 jobs failed
      ↓
5 minutes aggregation
      ↓
1 notification

41. Webhook Event Sink

DevOS 可以把 Event 发送到外部 Webhook:

core.webhook

配置:

interface WebhookEndpoint {
  id: string

  url: string

  events: string[]

  enabled: boolean

  secret?: string

  headers?: Record<string, string>
}

必须支持:

signature
retry
timeout
backoff
dead letter

42. Webhook Security

请求应该包含:

X-DevOS-Event
X-DevOS-Event-Id
X-DevOS-Timestamp
X-DevOS-Signature

Signature:

HMAC-SHA256

防止伪造。


43. Observability Resource

统一:

core.event
core.audit
core.log
core.metric
core.trace
core.notification

但:

不是所有 Resource 都需要完整 CRUD UI。

例如:

Metric
Trace
Log

主要提供:

search
filter
view
aggregation

44. Event Resource Actions

core.event.list
core.event.get
core.event.search
core.event.replay

Replay 必须经过权限检查。

禁止普通用户随意 Replay:

payment.completed
server.deployed

这种高风险 Event。


45. Event Replay

Event Replay 不应该直接重新执行原始 Handler。

应该:

Event
 ↓
Replay Request
 ↓
Authorization
 ↓
New Task / Job
 ↓
Action Runtime

并产生新的:

correlationId

以及:

causationId = originalEventId

46. Observability API

提供:

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 最重要的接口之一:

GET /api/tasks/:taskId/timeline

返回:

[
  {
    "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

必须提供:

Task #123
────────────────────────────────

● Task created
│
● Job #1 queued
│
● Job #1 started
│
● Website scan started
│
● MCP request
│
● Action completed
│
● Job #1 completed
│
● Task completed

点击任意节点:

Event
Execution
Logs
Audit
Trace
Input
Output

49. UI:Global Event Explorer

提供:

Events
──────────────────────────────

Search events...

Type
Actor
Resource
Status
Organization
Project
Time Range

──────────────────────────────

event
timestamp
actor
resource
correlation

50. UI:Audit Explorer

提供:

Audit
──────────────────────────────

Actor
Action
Resource
Status
Time
Organization
Project

──────────────────────────────

Alice
server.deploy
server-001
SUCCESS

支持:

Search
Filter
Export
Detail

51. UI:Execution Detail

Execution 页面:

Execution #123

Status
Duration
Action
Actor
Task
Job

──────────────────

Input
Output
Logs
Trace
Events
Audit
Error

52. UI:Agent Run

Agent Run:

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:

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

统一:

core.execution.failed
core.job.failed
core.task.failed

Payload:

{
  "error": {
    "code": "EXTERNAL_TIMEOUT",
    "category": "timeout",
    "retryable": true
  }
}

55. Observability Correlation

所有日志/Event/Audit/Trace 至少应该尽可能携带:

organizationId
projectId
actor
requestId
correlationId
taskId
jobId
executionId
traceId

形成:

Organization
   ↓
Project
   ↓
Actor
   ↓
Request
   ↓
Correlation
   ↓
Task
   ↓
Job
   ↓
Execution
   ↓
Trace
   ↓
Event
   ↓
Log
   ↓
Audit

56. Storage

推荐:

PostgreSQL

保存:

Event
Audit
Outbox
Inbox
Notification
NotificationRule
Webhook

Redis

保存:

Event Queue
Pub/Sub
Rate Limit
Notification Dedup
Short-lived Trace State

Log Storage

第一阶段可以:

PostgreSQL

但必须抽象:

interface LogStore

未来可以接:

Loki
Elasticsearch
OpenSearch
ClickHouse

57. Metric Storage

不要把高频 Metric 永久写 PostgreSQL。

设计:

interface MetricProvider {
  counter(...)

  gauge(...)

  histogram(...)
}

默认可以接:

Prometheus / OpenTelemetry

58. Trace Provider

设计:

interface TraceProvider {
  startSpan(...)

  endSpan(...)

  addEvent(...)

  setAttribute(...)
}

推荐:

OpenTelemetry

不要自行实现完整分布式 Trace 协议。


59. OpenTelemetry Integration

DevOS 应尽量兼容:

OpenTelemetry

统一生成:

Trace
Span
Metric
Log correlation

这样以后可以接:

Grafana
Prometheus
Tempo
Loki
Jaeger

而无需修改业务代码。


60. Event-driven Architecture

DevOS 不应该成为纯 CRUD Backend。

应该逐渐形成:

Command
   ↓
Action
   ↓
State Change
   ↓
Event
   ↓
Reaction

例如:

server.deploy
      ↓
server.updated
      ↓
server.deployment.completed
      ↓
notification
      ↓
audit
      ↓
agent observation

61. Event 与 Agent

Agent 不应该轮询数据库:

错误:

while true:
  SELECT task WHERE status = completed

应该:

Event Bus
   ↓
Agent Observation

Agent 可以订阅:

task.completed
task.failed
job.failed
approval.completed

62. Event 与 Plugin

Plugin 安装后可以声明:

interface PluginEventSubscription {
  pattern: string

  handler: string
}

例如 SEO Plugin:

core.task.completed
seo.website.updated

但 Handler 最终必须通过:

Action Runtime
Task Runtime

执行业务操作。


63. Event 与 MCP

MCP 不应该拥有自己的 Event System。

MCP:

MCP request
   ↓
Action Runtime
   ↓
Execution
   ↓
Event

如果外部 MCP 触发 DevOS:

MCP
 ↓
Action
 ↓
Task
 ↓
Event

64. Event 与 Scheduler

Scheduler 产生:

schedule.triggered

然后:

Schedule
 ↓
Event
 ↓
Task / Agent Goal

例如:

Every day 09:00
      ↓
schedule.triggered
      ↓
Agent Goal
      ↓
Task

65. Event 与 Webhook

外部:

GitHub
Stripe
Cloudflare
CI/CD

发送:

Webhook
 ↓
Verify
 ↓
Normalize
 ↓
Event
 ↓
Event Bus

Webhook Handler 不应该直接修改业务数据。


66. Event Schema Versioning

Event 必须有:

version

例如:

seo.website.scanned v1
seo.website.scanned v2

Consumer 必须明确支持版本。

禁止无版本 Event Schema。


67. Backward Compatibility

推荐:

v1
v2

同时支持一段时间。

禁止直接修改:

v1 payload

导致旧 Plugin 崩溃。


68. Event Naming Rules

统一:

<namespace>.<resource>.<past-tense-event>

推荐:

website.created
website.updated
website.deleted
website.scanned
website.published

不要:

createWebsite
websiteCreate
scanWebsiteNow

69. Security Event

必须支持安全事件:

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 可以进入:

Audit
Notification
Security Dashboard

70. Approval Event

与前面的危险 Action 集成:

approval.requested
approval.approved
approval.rejected
approval.expired

流程:

Agent
 ↓
Dangerous Action
 ↓
Approval Required
 ↓
approval.requested
 ↓
Human
 ↓
approval.approved
 ↓
Action Runtime
 ↓
Execution

71. Budget Event

Agent / Task / Organization Budget:

budget.warning
budget.exceeded
budget.blocked

例如:

Agent token budget > 80%
      ↓
budget.warning

超过:

budget.exceeded
      ↓
Agent stopped

72. Health Event

Worker:

worker.started
worker.healthy
worker.unhealthy
worker.stopped

Queue:

queue.backpressure
queue.stalled

Plugin:

plugin.health.failed

MCP:

mcp.health.failed

73. Observability Dashboard

DevOS 首页应该提供基础:

System Health

Tasks
Jobs
Workers
Queues
Actions
Agents
MCP
Plugins
Errors
Costs

例如:

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 必须提供:

health()

例如:

interface HealthCheck {
  name: string

  status: 'healthy' | 'degraded' | 'unhealthy'

  latencyMs?: number

  details?: Record<string, unknown>
}

系统:

GET /health
GET /health/ready
GET /health/live

75. Readiness

Readiness 应检查:

PostgreSQL
Redis
Queue
Worker
Event Bus

如果数据库不可用:

ready = false

76. Plugin Health

Plugin Runtime 必须支持:

Plugin
 ├── enabled
 ├── installed
 ├── configured
 └── healthy

Plugin Health 可以产生:

plugin.health.failed

77. MCP Health

MCP Server:

connected
degraded
disconnected

产生:

mcp.connected
mcp.disconnected
mcp.health.failed

78. Cost Observability

Agent / Action / MCP 都应该可以记录成本:

interface UsageRecord {
  provider?: string

  model?: string

  tokensInput?: number

  tokensOutput?: number

  requests?: number

  estimatedCost?: number

  currency?: string
}

最终形成:

Organization
 ↓
Project
 ↓
Agent
 ↓
Task
 ↓
Job
 ↓
Execution
 ↓
Provider
 ↓
Cost

79. Cost Event

例如:

ai.usage.recorded
ai.budget.warning
ai.budget.exceeded

80. 数据脱敏

所有:

Log
Event
Audit
Trace
Notification

进入 Storage 前都可以经过:

RedactionService

接口:

interface RedactionService {
  redact(input: unknown): unknown
}

默认敏感字段:

password
token
accessToken
refreshToken
apiKey
secret
privateKey
authorization
cookie

81. Observability Middleware

Action Runtime:

Request
 ↓
Trace Middleware
 ↓
Auth Middleware
 ↓
Audit Middleware
 ↓
Metrics Middleware
 ↓
Logger Context
 ↓
Action
 ↓
Event

82. Runtime Context

统一 Context:

interface RuntimeContext {
  requestId: string

  correlationId: string

  traceId?: string

  actor: Actor

  organizationId?: string

  projectId?: string

  taskId?: string

  jobId?: string

  executionId?: string

  metadata: Record<string, unknown>

  signal: AbortSignal
}

Action / Task / Agent / MCP 都应该尽量复用。


83. Package Architecture

Zcode 必须实现:

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

至少:

events
event_outbox
event_inbox

audit_records

notification_rules
notification_channels
notifications

webhook_endpoints
webhook_deliveries

Log/Metric/Trace Storage 应通过 Provider 抽象。


85. Event Registry

实现:

interface EventDefinition {
  type: string

  version: number

  description: string

  payloadSchema: ZodSchema

  sensitiveFields?: string[]
}

Plugin 可以注册:

eventRegistry.register(...)

例如:

seo.website.scanned

86. Schema Validation

Event Publish 时:

publish()
 ↓
Event Registry
 ↓
Find Definition
 ↓
Validate Payload
 ↓
Redact
 ↓
Persist Outbox
 ↓
Publish

未知 Event:

development: error
production: configurable

推荐生产环境也拒绝没有 Schema 的 Domain Event。


87. Event Permission

Event 本身可以定义 visibility:

visibility:
  | 'public'
  | 'organization'
  | 'project'
  | 'private'
  | 'system'

例如:

core.user.created

不能让任意 Agent 读取完整 User Event。

必须经过:

Capability Discovery
+
Permission
+
Scope

88. Agent Event Access

Agent 不能:

读取所有 Event

必须:

Agent Policy
 ↓
Allowed Event Types
 ↓
Organization Scope
 ↓
Resource Scope

89. Event Search

支持:

type
actor
resource
organization
project
task
job
execution
correlationId
time range
status

例如:

GET /api/events?
type=core.execution.failed&
taskId=task_123

90. Audit Search

支持:

actor
action
resource
status
organization
project
time
ip

91. Timeline Aggregation

Task Timeline 不应该查询十几个表后由前端拼接。

后端提供:

TimelineService

统一聚合:

Events
Audit
Executions
Jobs
Logs
Approvals
Notifications

然后输出:

interface TimelineItem {
  id: string

  timestamp: Date

  type: string

  title: string

  status?: string

  resource?: EventResource

  actor?: EventActor

  metadata?: unknown
}

92. Streaming

Task/Agent/Execution 页面支持实时更新:

推荐:

SSE

例如:

GET /api/tasks/:id/stream

事件:

task.progress
job.started
execution.log
execution.completed
task.completed

WebSocket 可以作为未来扩展。

第一阶段优先 SSE。


93. Streaming Architecture

Action
 ↓
Event Bus
 ↓
Event Stream
 ↓
SSE Gateway
 ↓
Browser

禁止 UI 直接连接 Worker。


94. Real-time Agent UI

Agent Chat 可以实时显示:

Agent:
我正在分析目标...

Capability:
seo.website.scan

Task:
Task #123 created

Execution:
Scanning website...

Result:
Found 37 issues

Agent:
正在生成修复计划...

所有这些都应该来自:

Event

而不是 Agent Runtime 直接操作 UI。


95. Audit 与 Agent

Agent 执行:

Agent
 ↓
Action

Audit 必须记录:

actorType = agent
actorId = agent_x

同时应该保留:

initiatedByUser

如果数据模型需要:

initiator?: {
  type: 'user' | 'agent' | 'system'
  id?: string
}

最终可以追溯:

User Alice
 ↓
Agent SEO
 ↓
Task
 ↓
Action
 ↓
Execution

96. Golden Rule

整个 DevOS 的可观察性必须遵循:

ONE EVENT SYSTEM
ONE AUDIT SYSTEM
ONE LOGGING SYSTEM
ONE METRIC SYSTEM
ONE TRACE SYSTEM
ONE NOTIFICATION SYSTEM

禁止:

Plugin EventBus
Agent EventBus
Task EventBus
MCP EventBus
SEO EventBus

这些都必须接入:

DevOS Event Runtime

97. 与前面 Runtime 的完整关系

现在 DevOS Runtime 形成:

                    User
                      │
                    Agent
                      │
                    Goal
                      │
                    Task
                      │
                     Job
                      │
                    Queue
                      │
                    Worker
                      │
                    Action
                      │
              Action Runtime
                      │
                 Execution
                      │
             ┌────────┴────────┐
             ↓                 ↓
           Event              Result
             │
     ┌───────┼────────┐
     ↓       ↓        ↓
   Audit    Log     Metric
     │       │        │
     └───────┼────────┘
             ↓
           Trace
             ↓
       Observability
             │
      ┌──────┼──────┐
      ↓      ↓      ↓
     UI   Agent   Notification

98. Zcode 禁止事项

以下全部禁止:

❌ 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

Action
 ↓
Execution
 ↓
Event
 ↓
Audit

验证整个链条存在。

Test 2

DB Transaction
 ↓
Outbox
 ↓
Event Bus

验证事务一致性。

Test 3

重复 Event:

same eventId
 ↓
Inbox
 ↓
only once handler effect

Test 4

Agent:

Goal
 ↓
Task
 ↓
Job
 ↓
Action
 ↓
Execution
 ↓
Event
 ↓
Agent Observation

Test 5

Plugin:

Plugin
 ↓
Action
 ↓
Event
 ↓
Audit

Test 6

MCP:

MCP
 ↓
Action Runtime
 ↓
Execution
 ↓
Event
 ↓
Audit

Test 7

权限:

Unauthorized Event
 ↓
Access Denied

Test 8

敏感数据:

password/token/apiKey
 ↓
Log/Audit/Event
 ↓
REDACTED

Test 9

Task Timeline:

Task
Job
Execution
Event
Audit
Log

能够被统一聚合。

Test 10

SSE:

Task running
 ↓
Event
 ↓
SSE
 ↓
Browser

验证实时 UI。


101. 最终架构

完成 10 之后,DevOS 的基础 Runtime 应该已经形成:

┌────────────────────────────────────────────┐
│                  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 到目前为止必须严格遵守:

Resource
   ↓
Action
   ↓
Action Runtime
   ↓
Execution
   ↓
Event
   ↓
Observability

异步:

Task
 ↓
Job
 ↓
Queue
 ↓
Worker
 ↓
Action Runtime
 ↓
Execution
 ↓
Event

Agent:

Goal
 ↓
Agent
 ↓
Skill
 ↓
Capability
 ↓
Task
 ↓
Action
 ↓
Execution
 ↓
Event
 ↓
Observation
 ↓
Agent

Plugin:

Plugin
 ├── Resource
 ├── Action
 ├── Skill
 ├── MCP
 ├── Workflow
 ├── Event
 └── UI
        ↓
   DevOS Registry
        ↓
   DevOS Runtime

最终禁止任何模块建立第二套 Runtime。

DevOS 的核心不是:

一堆 CRUD

而是:

Resource
+
Action
+
Task
+
Execution
+
Event
+
Agent
+
Capability
+
Observability

这才是整个 DevOS 能够持续扩展、让 SEO / DevOps / CRM / Content 等应用共享同一套底座的核心。