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

61 KiB
Raw Blame History

24 — DevOS Runtime Contracts

文件名:24_DEVOS_RUNTIME_CONTRACTS.md

本文定义 DevOS 所有 Runtime 的统一 Contract。

目标不是让所有 Runtime 变成一样,而是让所有 Runtime 遵循同一套:

Lifecycle / Context / Result / Error / Registry / Provider / Execution / Health / Version / Observability / Permission

本文是 01–23 文档的基础实现契约之一。

Zcode 实现任何新的 Runtime 时,必须遵守本文。


1. Purpose

DevOS 后续会存在:

Action Runtime
Data Runtime
Task Runtime
Job Runtime
Queue Runtime
Worker Runtime
Event Runtime
Storage Runtime
Search Runtime
Configuration Runtime
Secret Runtime
Provider Runtime
Plugin Runtime
MCP Runtime
Capability Runtime
Skill Runtime
Agent Runtime
Workflow Runtime
Notification Runtime
Observability Runtime

如果每个 Runtime 自己设计:

Context
Result
Error
Registry
Lifecycle
Health
Version
Provider

最终会变成:

Runtime A
 ├── AContext
 ├── AResult
 ├── AError
 └── ARegistry

Runtime B
 ├── BContext
 ├── BResult
 ├── BError
 └── BRegistry

Runtime C
 ├── CContext
 ├── CResult
 ├── CError
 └── CRegistry

这种设计会导致:

类型无法复用
错误无法统一
日志无法统一
权限无法统一
Agent 无法统一调用
Plugin 无法统一接入
测试无法统一

因此 DevOS 必须采用:

Common Runtime Contract + Runtime-specific Extension


2. Core Principle

所有 Runtime:

Common Contract
      ↓
Runtime Contract
      ↓
Provider / Implementation

例如:

RuntimeContract
      ↓
ActionRuntimeContract
      ↓
ActionRuntimeImpl

或者:

RuntimeContract
      ↓
StorageRuntimeContract
      ↓
S3StorageProvider

3. Runtime Contract Layers

统一分为五层:

Layer 1
Common Types

Layer 2
Runtime Lifecycle

Layer 3
Runtime Context

Layer 4
Runtime-specific Contract

Layer 5
Provider / Implementation

结构:

┌──────────────────────────────┐
│ Runtime-specific Contract    │
├──────────────────────────────┤
│ Common Runtime Contract      │
├──────────────────────────────┤
│ Context / Result / Error     │
├──────────────────────────────┤
│ Registry / Lifecycle         │
├──────────────────────────────┤
│ Provider / Implementation    │
└──────────────────────────────┘

4. Package Ownership

统一 Contract 应放在:

packages/contracts/

建议:

packages/contracts/
├── runtime/
│   ├── runtime.ts
│   ├── context.ts
│   ├── result.ts
│   ├── error.ts
│   ├── lifecycle.ts
│   ├── health.ts
│   ├── version.ts
│   ├── registry.ts
│   ├── provider.ts
│   └── execution.ts
│
├── resource/
├── action/
├── task/
├── event/
├── storage/
├── search/
├── plugin/
├── agent/
└── capability/

5. Dependency Rule

最底层 Contract:

packages/contracts

不得依赖:

Action Runtime
Task Runtime
Plugin
Agent
SEO
DevOps
Business Modules
UI

正确:

contracts
   ↑
runtime
   ↑
modules
   ↑
apps

6. Common Runtime Interface

所有 Runtime 必须实现:

export interface DevOSRuntime {
  readonly id: string;
  readonly version: string;
  readonly status: RuntimeStatus;

  initialize(context: RuntimeInitContext): Promise<void>;

  start(context: RuntimeStartContext): Promise<void>;

  stop(context: RuntimeStopContext): Promise<void>;

  health(context: RuntimeHealthContext): Promise<RuntimeHealth>;

  dispose(context: RuntimeDisposeContext): Promise<void>;
}

7. Runtime Status

统一:

export type RuntimeStatus =
  | "created"
  | "initializing"
  | "ready"
  | "starting"
  | "running"
  | "degraded"
  | "draining"
  | "stopping"
  | "stopped"
  | "failed";

生命周期:

created
   ↓
initializing
   ↓
ready
   ↓
starting
   ↓
running
   ↓
draining
   ↓
stopping
   ↓
stopped

异常:

initializing → failed
starting     → failed
running      → degraded

8. Runtime Lifecycle Rules

Runtime:

initialize()

负责:

配置加载
依赖解析
Schema 验证
Provider 准备
内部状态初始化

不得在:

initialize()

中偷偷执行:

业务操作
数据库大规模迁移
用户请求
Agent Task

9. Start

start()

负责:

启动监听器
Worker
Queue consumer
Event subscriber
Realtime connections

10. Stop

Runtime 必须支持 graceful shutdown:

stop()
 ↓
stop accepting new work
 ↓
drain active work
 ↓
flush buffers
 ↓
close connections
 ↓
stopped

11. Dispose

dispose()

负责释放:

memory
provider
connections
timers
listeners
subscriptions

12. Runtime Context

所有 Runtime Context 必须包含:

export interface RuntimeContext {
  requestId: string;
  correlationId: string;
  actor: ActorContext;

  organizationId?: string;
  projectId?: string;
  environmentId?: string;

  locale?: string;
  timezone?: string;

  signal?: AbortSignal;

  metadata?: Record<string, unknown>;
}

13. Actor Context

统一:

export type ActorType =
  | "user"
  | "agent"
  | "service"
  | "system";
export interface ActorContext {
  id: string;
  type: ActorType;

  sessionId?: string;

  roles?: string[];
  permissions?: string[];

  metadata?: Record<string, unknown>;
}

14. Never Create Different Actor Models

禁止:

UserContext
AgentContext
PluginContext
MCPContext
TaskContext

各自完全独立。

可以扩展:

interface AgentRuntimeContext extends RuntimeContext {
  agentRunId: string;
}

但必须继承:

RuntimeContext

15. Execution Context

需要执行具体操作时:

export interface ExecutionContext extends RuntimeContext {
  executionId: string;

  taskId?: string;
  jobId?: string;

  actionId?: string;
  actionVersion?: string;
}

16. Common Result

统一 Result:

export type Result<T, E = DevOSError> =
  | {
      success: true;
      data: T;
      metadata?: ResultMetadata;
    }
  | {
      success: false;
      error: E;
      metadata?: ResultMetadata;
    };

17. Result Metadata

export interface ResultMetadata {
  requestId?: string;
  correlationId?: string;
  executionId?: string;

  durationMs?: number;

  warnings?: string[];

  usage?: UsageMetadata;

  provider?: {
    id: string;
    version?: string;
  };
}

18. Do Not Return Raw Provider Objects

错误:

return openaiResponse;

或者:

return awsSdkResponse;

应该:

Provider
 ↓
Adapter
 ↓
DevOS Contract

这样业务层不依赖 Provider。


19. Common Error

统一:

export interface DevOSError {
  code: string;

  message: string;

  category: ErrorCategory;

  retryable: boolean;

  severity: ErrorSeverity;

  safeMessage?: string;

  details?: Record<string, unknown>;

  cause?: unknown;

  fingerprint?: string;

  requestId?: string;
  correlationId?: string;
  executionId?: string;
}

20. Error Categories

统一:

export type ErrorCategory =
  | "validation"
  | "authentication"
  | "authorization"
  | "not_found"
  | "conflict"
  | "rate_limit"
  | "timeout"
  | "dependency"
  | "provider"
  | "storage"
  | "database"
  | "network"
  | "configuration"
  | "resource_exhausted"
  | "cancelled"
  | "internal"
  | "unknown";

21. Error Severity

export type ErrorSeverity =
  | "info"
  | "warning"
  | "error"
  | "critical";

22. Error Code Naming

推荐:

<namespace>.<component>.<error>

例如:

core.action.not_found
core.action.forbidden
core.action.timeout

task.job.failed
task.job.retry_exhausted

storage.file.not_found
storage.upload.invalid_mime

plugin.install.incompatible

agent.budget.exceeded
agent.capability.denied

23. Error Must Be Machine-readable

不要:

throw new Error("Something went wrong");

应该:

throw new DevOSErrorException({
  code: "core.action.forbidden",
  category: "authorization",
  retryable: false,
  severity: "warning",
  safeMessage: "You do not have permission to execute this action."
});

24. Secret Safety

以下字段绝对不能自动进入:

Error
Log
Audit
Event
Trace
Result

包括:

password
apiKey
token
secret
privateKey
credentialValue
sessionToken

必须:

redact

25. Error Serialization

统一:

export interface SerializedError {
  code: string;
  category: ErrorCategory;
  retryable: boolean;
  severity: ErrorSeverity;
  safeMessage: string;

  requestId?: string;
  correlationId?: string;
  executionId?: string;
}

内部:

details
cause
stack

不应该默认返回客户端。


26. Runtime Registry

统一 Registry:

export interface RuntimeRegistry<T extends DevOSRuntime> {
  register(runtime: T): Promise<void> | void;

  unregister(id: string): Promise<void> | void;

  get(id: string): T | undefined;

  has(id: string): boolean;

  list(): T[];

  health(): Promise<RuntimeHealth[]>;
}

27. Registry Rules

Registry:

register
discover
resolve
health
unregister

不得承担:

business logic
execution logic
database workflow

28. Duplicate Registration

默认禁止:

register("action")
register("action")

除非明确:

replace

且必须:

permission
version
compatibility

29. Runtime ID

Runtime ID:

core.action
core.task
core.event
core.storage
core.search
core.plugin
core.agent

Plugin Runtime:

plugin.<pluginId>

但 Plugin 业务 Runtime 仍然不能取代 Core Runtime。


30. Runtime Version

必须:

interface RuntimeVersion {
  major: number;
  minor: number;
  patch: number;
}

推荐 SemVer。


31. Contract Version

Runtime Version 与 Contract Version 分离。

例如:

Runtime:
action-runtime 2.4.1

Contract:
action-contract 1

这样 Provider 可以独立升级。


32. Compatibility

统一:

export interface CompatibilityResult {
  compatible: boolean;

  issues: CompatibilityIssue[];

  warnings: CompatibilityIssue[];
}

33. Runtime Health

统一:

export interface RuntimeHealth {
  id: string;

  status:
    | "healthy"
    | "degraded"
    | "unhealthy";

  version: string;

  uptimeMs?: number;

  dependencies: RuntimeDependencyHealth[];

  metrics?: {
    latencyMs?: number;
    errorRate?: number;
    throughput?: number;
  };

  message?: string;
}

34. Dependency Health

export interface RuntimeDependencyHealth {
  id: string;

  status:
    | "healthy"
    | "degraded"
    | "unhealthy"
    | "unknown";

  latencyMs?: number;

  message?: string;
}

35. Runtime Provider Contract

所有可替换基础设施使用 Provider。

export interface DevOSProvider {
  readonly id: string;
  readonly type: string;
  readonly version: string;

  initialize(context: ProviderContext): Promise<void>;

  health(context: ProviderContext): Promise<ProviderHealth>;

  dispose(context: ProviderContext): Promise<void>;
}

36. Provider Context

export interface ProviderContext extends RuntimeContext {
  providerId: string;

  configuration: Record<string, unknown>;
}

敏感数据:

不得直接塞入 configuration

应通过:

Credential / Secret Runtime

解析。


37. Provider Resolution

统一:

Runtime
 ↓
Provider Registry
 ↓
Provider Resolver
 ↓
Provider

例如:

Storage Runtime
 ↓
Storage Provider Registry
 ↓
S3 Provider

38. Provider Failover

Provider 支持:

primary
 ↓
health check
 ↓
fallback

但:

Failover 必须由 Runtime Policy 控制。

业务代码不能:

if (s3Failed) {
  useLocalFs();
}

39. Runtime Policy

统一:

export interface RuntimePolicy {
  timeoutMs?: number;

  maxConcurrency?: number;

  retry?: RetryPolicy;

  rateLimit?: RateLimitPolicy;

  requireApproval?: boolean;

  allowedProviders?: string[];

  deniedProviders?: string[];
}

40. Retry Policy

export interface RetryPolicy {
  enabled: boolean;

  maxAttempts: number;

  strategy:
    | "fixed"
    | "linear"
    | "exponential";

  initialDelayMs?: number;
  maxDelayMs?: number;

  jitter?: boolean;
}

41. Runtime Execution

需要执行操作的 Runtime 应统一:

export interface RuntimeExecutor<I, O> {
  execute(
    input: I,
    context: ExecutionContext
  ): Promise<Result<O>>;
}

42. Cancellation

所有可能长时间运行的操作:

context.signal

必须被支持。

例如:

if (context.signal?.aborted) {
  throw cancelledError();
}

43. Timeout

Runtime 不应该无限等待 Provider。

必须支持:

Runtime Policy
 ↓
Timeout
 ↓
AbortSignal
 ↓
Execution cancelled / failed

44. Idempotency

涉及副作用的 Runtime 必须支持:

export interface IdempotencyContext {
  key: string;

  scope: string;

  ttlSeconds?: number;
}

例如:

action execution
payment
file upload
webhook
notification
job

45. Audit Contract

涉及:

security
permission
data mutation
external side effect

必须支持 Audit。

export interface AuditContext {
  actor: ActorContext;

  action?: string;

  resourceType?: string;
  resourceId?: string;

  reason?: string;

  before?: unknown;
  after?: unknown;

  approvalId?: string;
}

46. Event Contract

Runtime 产生事件必须遵循统一:

export interface DevOSEvent<T = unknown> {
  id: string;

  type: string;
  version: string;

  occurredAt: string;

  actor: ActorContext;

  organizationId?: string;
  projectId?: string;
  environmentId?: string;

  resource?: {
    type: string;
    id: string;
  };

  payload: T;

  correlationId: string;
  causationId?: string;

  requestId?: string;
  executionId?: string;
  taskId?: string;
  jobId?: string;
}

47. Observability Contract

Runtime 不需要自己实现 Logger。

统一使用:

export interface RuntimeObservability {
  logger: DevOSLogger;

  metrics: DevOSMetrics;

  tracer: DevOSTracer;
}

48. Logger

export interface DevOSLogger {
  debug(message: string, context?: LogContext): void;

  info(message: string, context?: LogContext): void;

  warn(message: string, context?: LogContext): void;

  error(message: string, context?: LogContext): void;
}

49. Log Context

export interface LogContext {
  requestId?: string;
  correlationId?: string;
  executionId?: string;
  taskId?: string;
  jobId?: string;

  runtime?: string;
  action?: string;

  actorId?: string;

  metadata?: Record<string, unknown>;
}

50. Metrics Contract

export interface DevOSMetrics {
  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;
}

51. Trace Contract

export interface DevOSTracer {
  startSpan(
    name: string,
    context?: TraceContext
  ): TraceSpan;
}

实现优先:

OpenTelemetry

但业务 Runtime 依赖:

DevOSTracer

而不是直接依赖 OpenTelemetry API。


52. Permission Contract

所有 Runtime 操作都应该能够检查:

export interface PermissionChecker {
  check(
    permission: string,
    context: RuntimeContext,
    resource?: ResourceScope
  ): Promise<PermissionResult>;
}

53. Permission Result

export interface PermissionResult {
  allowed: boolean;

  reason?: string;

  matchedPolicies?: string[];

  scope?: ResourceScope;
}

54. Scope Contract

export interface ResourceScope {
  organizationId?: string;
  projectId?: string;
  environmentId?: string;

  resourceType?: string;
  resourceId?: string;
}

55. Runtime Authorization Rule

Runtime 不应该只检查:

permission === true

至少:

Actor
 ↓
Permission
 ↓
Resource
 ↓
Scope
 ↓
Policy

56. Configuration Contract

Runtime 配置必须声明:

export interface RuntimeConfigDefinition {
  runtimeId: string;

  schema: unknown;

  defaults?: Record<string, unknown>;

  reloadable?: boolean;
}

实际值来自:

Configuration Runtime

而不是 Runtime 自己从:

process.env

读取。


57. Secret Contract

Runtime 如果需要 Secret:

export interface SecretReference {
  type: "secret";
  id: string;
}

Runtime 请求:

Secret Runtime

而不是:

process.env.API_KEY

58. Resource Contract

Runtime 创建 Resource 时:

export interface ResourceDefinition {
  id: string;

  version: string;

  namespace: string;

  name: string;

  schema: unknown;

  permissions: string[];

  actions: string[];

  events?: string[];

  search?: unknown;

  ui?: unknown;
}

59. Action Contract

统一:

export interface ActionDefinition<I = unknown, O = unknown> {
  id: string;

  version: string;

  name: string;

  description: string;

  inputSchema: unknown;

  outputSchema: unknown;

  mode: "sync" | "async" | "stream";

  permissions: string[];

  timeoutMs?: number;

  idempotency?: boolean;

  requiresApproval?: boolean;

  handler(
    input: I,
    context: ExecutionContext
  ): Promise<O>;
}

60. Action Registration

interface ActionRegistry {
  register(action: ActionDefinition): void;

  get(id: string, version?: string): ActionDefinition | undefined;

  list(): ActionDefinition[];

  resolve(
    id: string,
    context: RuntimeContext
  ): Promise<ActionDefinition>;
}

61. Task Contract

export interface TaskDefinition {
  id: string;

  type: string;

  name: string;

  actor: ActorContext;

  status: TaskStatus;

  input?: unknown;

  output?: unknown;

  progress?: TaskProgress;
}

62. Job Contract

export interface JobDefinition {
  id: string;

  taskId: string;

  actionId: string;

  actionVersion: string;

  input: unknown;

  attempts: number;

  maxAttempts: number;

  status: JobStatus;
}

63. Execution Contract

export interface ExecutionRecord {
  id: string;

  actionId: string;
  actionVersion: string;

  actor: ActorContext;

  status: ExecutionStatus;

  startedAt?: string;
  completedAt?: string;

  input?: unknown;
  output?: unknown;

  error?: DevOSError;
}

64. Event Runtime Contract

export interface EventRuntime extends DevOSRuntime {
  publish<T>(
    event: DevOSEvent<T>,
    context: RuntimeContext
  ): Promise<Result<void>>;

  subscribe(
    subscription: EventSubscription,
    context: RuntimeContext
  ): Promise<Result<string>>;

  unsubscribe(
    subscriptionId: string,
    context: RuntimeContext
  ): Promise<Result<void>>;

  replay(
    request: EventReplayRequest,
    context: RuntimeContext
  ): Promise<Result<EventReplayResult>>;
}

65. Storage Runtime Contract

export interface StorageRuntime extends DevOSRuntime {
  upload(
    input: StorageUploadInput,
    context: ExecutionContext
  ): Promise<Result<StorageObject>>;

  download(
    input: StorageDownloadInput,
    context: ExecutionContext
  ): Promise<Result<StorageDownloadResult>>;

  delete(
    input: StorageDeleteInput,
    context: ExecutionContext
  ): Promise<Result<void>>;

  getMetadata(
    input: StorageMetadataInput,
    context: RuntimeContext
  ): Promise<Result<StorageObject>>;
}

66. Search Runtime Contract

export interface SearchRuntime extends DevOSRuntime {
  search(
    input: SearchInput,
    context: RuntimeContext
  ): Promise<Result<SearchResult>>;

  index(
    input: IndexInput,
    context: ExecutionContext
  ): Promise<Result<void>>;

  rebuild(
    input: RebuildIndexInput,
    context: ExecutionContext
  ): Promise<Result<void>>;
}

67. Configuration Runtime Contract

export interface ConfigurationRuntime extends DevOSRuntime {
  resolve(
    input: ResolveConfigInput,
    context: RuntimeContext
  ): Promise<Result<ResolvedConfig>>;

  set(
    input: SetConfigInput,
    context: ExecutionContext
  ): Promise<Result<void>>;

  rollback(
    input: RollbackConfigInput,
    context: ExecutionContext
  ): Promise<Result<void>>;
}

68. Secret Runtime Contract

export interface SecretRuntime extends DevOSRuntime {
  create(
    input: CreateSecretInput,
    context: ExecutionContext
  ): Promise<Result<SecretMetadata>>;

  resolve(
    reference: SecretReference,
    context: RuntimeContext
  ): Promise<Result<SecretValue>>;

  rotate(
    input: RotateSecretInput,
    context: ExecutionContext
  ): Promise<Result<SecretMetadata>>;

  revoke(
    input: RevokeSecretInput,
    context: ExecutionContext
  ): Promise<Result<void>>;
}

SecretValue:

interface SecretValue {
  value: string;
}

只允许在:

secure runtime boundary

短暂存在。


69. Plugin Runtime Contract

export interface PluginRuntime extends DevOSRuntime {
  install(
    input: PluginInstallInput,
    context: ExecutionContext
  ): Promise<Result<PluginInstance>>;

  enable(
    pluginId: string,
    context: ExecutionContext
  ): Promise<Result<void>>;

  disable(
    pluginId: string,
    context: ExecutionContext
  ): Promise<Result<void>>;

  upgrade(
    input: PluginUpgradeInput,
    context: ExecutionContext
  ): Promise<Result<PluginInstance>>;

  uninstall(
    pluginId: string,
    context: ExecutionContext
  ): Promise<Result<void>>;
}

70. Capability Runtime Contract

export interface CapabilityRegistry {
  register(
    capability: CapabilityDefinition
  ): void;

  unregister(
    id: string
  ): void;

  get(
    id: string,
    version?: string
  ): CapabilityDefinition | undefined;

  search(
    input: CapabilitySearchInput,
    context: RuntimeContext
  ): Promise<Result<CapabilitySearchResult>>;
}

71. Agent Runtime Contract

export interface AgentRuntime extends DevOSRuntime {
  createGoal(
    input: AgentGoalInput,
    context: RuntimeContext
  ): Promise<Result<AgentGoal>>;

  run(
    goalId: string,
    context: ExecutionContext
  ): Promise<Result<AgentRun>>;

  cancel(
    runId: string,
    context: ExecutionContext
  ): Promise<Result<void>>;

  observe(
    runId: string,
    context: RuntimeContext
  ): Promise<Result<AgentObservation[]>>;
}

72. Agent Runtime Restrictions

Agent Runtime:

可以:
Goal
Plan
Capability Discovery
Action
Task
Observation
Replan

不能:

Direct DB
Direct Redis
Direct filesystem
Direct Queue
Direct Secret Store

73. MCP Runtime Contract

export interface MCPRuntime extends DevOSRuntime {
  connect(
    input: MCPConnectionInput,
    context: RuntimeContext
  ): Promise<Result<MCPConnection>>;

  discover(
    connectionId: string,
    context: RuntimeContext
  ): Promise<Result<MCPTool[]>>;

  invoke(
    input: MCPInvokeInput,
    context: ExecutionContext
  ): Promise<Result<unknown>>;

  disconnect(
    connectionId: string,
    context: RuntimeContext
  ): Promise<Result<void>>;
}

74. MCP Invocation Rule

内部执行必须:

MCP
 ↓
Capability
 ↓
Permission
 ↓
Action Runtime
 ↓
Execution

75. Workflow Runtime Contract

export interface WorkflowRuntime extends DevOSRuntime {
  validate(
    workflow: WorkflowDefinition,
    context: RuntimeContext
  ): Promise<Result<WorkflowValidationResult>>;

  start(
    input: WorkflowStartInput,
    context: ExecutionContext
  ): Promise<Result<TaskDefinition>>;

  cancel(
    workflowRunId: string,
    context: ExecutionContext
  ): Promise<Result<void>>;
}

Workflow 不应该重新实现:

Task
Job
Queue
Action
Event

而应该组合这些 Runtime。


76. Notification Runtime Contract

export interface NotificationRuntime extends DevOSRuntime {
  send(
    input: NotificationInput,
    context: ExecutionContext
  ): Promise<Result<NotificationResult>>;

  schedule(
    input: ScheduledNotificationInput,
    context: ExecutionContext
  ): Promise<Result<TaskDefinition>>;
}

77. Data Runtime Contract

export interface DataRuntime extends DevOSRuntime {
  query<T>(
    input: QueryInput,
    context: RuntimeContext
  ): Promise<Result<QueryResult<T>>>;

  aggregate<T>(
    input: AggregateInput,
    context: RuntimeContext
  ): Promise<Result<T>>;

  transaction<T>(
    operation: DataTransaction<T>,
    context: ExecutionContext
  ): Promise<Result<T>>;
}

78. Write Rule

Data Runtime 可以执行数据库写操作。

但业务模块:

不得直接调用 DataRuntime.write()

业务 mutation:

Action
 ↓
Action Runtime
 ↓
Data Runtime

这样才能统一:

permission
audit
event
idempotency
observability

79. Query Rule

读取:

Resource
 ↓
Query
 ↓
Data Runtime

查询必须自动处理:

permission
scope
field access
pagination
sorting
filter validation

80. Queue Runtime Contract

export interface QueueRuntime extends DevOSRuntime {
  enqueue(
    job: JobDefinition,
    context: RuntimeContext
  ): Promise<Result<string>>;

  dequeue(
    input: QueueDequeueInput,
    context: RuntimeContext
  ): Promise<Result<JobDefinition | null>>;

  acknowledge(
    jobId: string,
    context: RuntimeContext
  ): Promise<Result<void>>;

  retry(
    jobId: string,
    context: RuntimeContext
  ): Promise<Result<void>>;
}

81. Worker Runtime Contract

export interface WorkerRuntime extends DevOSRuntime {
  register(
    worker: WorkerDefinition
  ): Promise<void>;

  drain(
    workerId: string,
    context: RuntimeContext
  ): Promise<Result<void>>;

  execute(
    job: JobDefinition,
    context: ExecutionContext
  ): Promise<Result<ExecutionRecord>>;
}

Worker 最终:

Action Runtime

82. Scheduler Runtime Contract

Scheduler 不直接执行业务。

正确:

Schedule
 ↓
Task
 ↓
Job
 ↓
Queue

Contract:

export interface SchedulerRuntime extends DevOSRuntime {
  schedule(
    input: ScheduleInput,
    context: ExecutionContext
  ): Promise<Result<Schedule>>;

  unschedule(
    scheduleId: string,
    context: ExecutionContext
  ): Promise<Result<void>>;
}

83. Runtime Adapter

旧代码迁移允许:

export interface RuntimeAdapter<Legacy, Modern> {
  canHandle(input: Legacy): boolean;

  adapt(input: Legacy): Modern;
}

Adapter:

Legacy
 ↓
Adapter
 ↓
DevOS Contract

不能永久成为第二 Runtime。


84. Runtime Facade

复杂 Runtime 可以提供 Facade:

export interface RuntimeFacade {
  readonly runtime: DevOSRuntime;
}

Facade 只负责:

API simplification

不能重新实现:

execution
permission
queue
event

85. Runtime Composition

Runtime 可以调用 Runtime。

但是依赖必须明确。

例如:

Agent Runtime
 ↓
Capability Runtime
 ↓
Action Runtime
 ↓
Data Runtime

合法。


86. Forbidden Runtime Cycles

禁止:

Action
 ↓
Agent
 ↓
Action

或者:

Task
 ↓
Event
 ↓
Task
 ↓
Event

如果业务确实需要:

Event → Task

必须通过:

event trigger policy

避免无限循环。


87. Runtime Dependency Graph

建议维护:

packages/contracts
       ↓
core
       ↓
identity / permission
       ↓
resource
       ↓
data
       ↓
action
       ↓
execution
       ↓
task
       ↓
event
       ↓
plugin / mcp / capability
       ↓
skill
       ↓
agent

88. Core Runtime Dependencies

Core Runtime 不允许依赖:

SEO
CRM
Content
DevOps
Business

89. Runtime Registration Lifecycle

系统启动:

Load Config
 ↓
Initialize Providers
 ↓
Initialize Runtimes
 ↓
Register Resources
 ↓
Register Actions
 ↓
Register Capabilities
 ↓
Register Plugins
 ↓
Start Workers
 ↓
Start Event Consumers
 ↓
READY

90. Registration Ordering

依赖必须先注册:

Contracts
 ↓
Provider
 ↓
Runtime
 ↓
Resource
 ↓
Action
 ↓
Capability
 ↓
Plugin
 ↓
Agent

91. Runtime Bootstrap

推荐:

interface RuntimeBootstrap {
  runtimes: DevOSRuntime[];

  providers: DevOSProvider[];

  resources: ResourceDefinition[];

  actions: ActionDefinition[];

  capabilities: CapabilityDefinition[];
}

92. Bootstrap Must Be Deterministic

同样的:

configuration
+
plugin versions
+
environment

应该得到相同:

runtime registry
resource registry
action registry
capability registry

93. No Hidden Runtime Registration

禁止:

constructor() {
  globalRegistry.register(...)
}

这会导致:

import order

决定系统行为。

应该显式:

bootstrap
 ↓
register

94. Runtime Registry Snapshot

系统应该能够输出:

{
  "runtimeVersion": "1.0.0",
  "runtimes": [],
  "providers": [],
  "resources": [],
  "actions": [],
  "capabilities": []
}

用于:

debug
diagnostics
upgrade
reproducibility

95. Runtime Contract Testing

所有 Runtime 必须测试:

Lifecycle
Context
Health
Error
Permission
Cancellation
Timeout
Observability
Version

96. Generic Runtime Contract Test

建议:

describeRuntimeContract(
  createRuntime,
  {
    id: "core.action",
    version: "1.0.0"
  }
);

测试:

✓ initialize
✓ start
✓ health
✓ stop
✓ dispose

97. Error Contract Test

所有 Runtime:

✓ machine-readable error
✓ error code
✓ category
✓ retryable
✓ safe message
✓ correlation ID
✓ no secret leakage

98. Cancellation Contract Test

所有长任务:

start
 ↓
AbortSignal
 ↓
operation stops
 ↓
no orphan work

99. Timeout Contract Test

测试:

Provider hangs
 ↓
timeout
 ↓
Abort
 ↓
Execution failed
 ↓
correct error

100. Permission Contract Test

至少:

authorized → PASS
unauthorized → DENY
wrong organization → DENY
wrong project → DENY
wrong environment → DENY

101. Observability Contract Test

执行一次 Runtime 后必须能够找到:

requestId
correlationId
runtime
actor
duration
result
error

102. Audit Contract Test

Mutation Runtime:

execute
 ↓
audit exists

Audit 至少包含:

actor
action
target
result
timestamp
correlation

103. Event Contract Test

需要事件的 Runtime:

execute
 ↓
event emitted

事件必须包含:

eventId
eventType
version
actor
correlationId
payload

104. Version Contract Test

测试:

Runtime version
Action version
Provider version
Contract version

是否可追踪。


105. Runtime Health Contract Test

测试:

healthy dependency
 ↓
healthy

failed dependency
 ↓
degraded/unhealthy

106. Provider Contract Testing

同一 Provider Contract:

S3
Local
MinIO

应该都可以运行:

StorageProviderContractTest

这样 Provider 可以替换。


107. Example Provider Contract

describeStorageProviderContract(
  () => createS3Provider()
);

describeStorageProviderContract(
  () => createLocalProvider()
);

108. Contract Compatibility

新版本 Provider:

Provider v2

必须通过:

Provider Contract v1

才能接入。

如果 Contract Breaking:

Contract v2

必须明确。


109. Runtime Contract Versioning

建议:

core.runtime@1
action.runtime@1
task.runtime@1
event.runtime@1
storage.runtime@1

Breaking change:

@1 → @2

非 breaking:

1.1

110. Backward Compatibility

尽可能:

new Runtime
支持 old Contract

通过 Adapter:

old contract
 ↓
adapter
 ↓
new runtime

111. Runtime API Surface

每个 Runtime 必须明确:

PUBLIC
INTERNAL
PRIVATE

例如:

public:
execute()

internal:
resolveProvider()

private:
buildQuery()

112. No Leaky Abstraction

禁止向业务层暴露:

Prisma Client
Redis Client
AWS SDK
OpenAI SDK
BullMQ Job

应该暴露:

DevOS Contract

113. Runtime Error Translation

Provider:

AWS Error

转换:

storage.provider.unavailable

数据库:

Prisma Error

转换:

data.database.unavailable

114. Runtime Event Translation

Provider-specific Event:

S3 ObjectCreated

可以转换:

storage.file.created

这样业务不依赖 S3。


115. Runtime Metadata

所有 Runtime 可以提供:

export interface RuntimeMetadata {
  id: string;
  name: string;
  description: string;

  version: string;
  contractVersion: string;

  capabilities: string[];

  dependencies: string[];

  providers?: string[];
}

116. Runtime Discovery

系统应该支持:

runtimeRegistry.list()

输出:

core.action
core.data
core.task
core.event
core.storage
core.search
core.plugin
core.agent

117. Runtime Diagnostics

建议:

devos runtime list
devos runtime inspect core.action
devos runtime health
devos runtime dependencies

118. Runtime Inspect

例如:

devos runtime inspect core.action

应该显示:

ID
Version
Contract Version
Status
Dependencies
Providers
Capabilities
Health
Metrics

不能显示:

secret values
private credentials

119. Runtime Metrics

每个 Runtime 至少记录:

runtime.calls
runtime.success
runtime.failure
runtime.duration
runtime.timeout
runtime.cancelled
runtime.retry

120. Runtime Cardinality

禁止将:

userId
taskId
executionId
requestId

作为无限 cardinality metric label。

这些应该进入:

Logs / Traces

而不是 Metrics。


121. Runtime Logging

日志必须包含:

runtime
requestId
correlationId
executionId
actor

但不包含:

secret
token
password
private key

122. Runtime Tracing

建议 Span:

devos.runtime.action
devos.runtime.data
devos.runtime.task
devos.runtime.event

嵌套:

Agent Span
 └── Action Runtime Span
      └── Data Runtime Span

123. Runtime Cost

可能产生费用的 Runtime:

Agent
Model
Search
Storage
External API
Browser
Compute

应支持:

interface UsageMetadata {
  tokens?: number;
  requests?: number;
  bytes?: number;
  durationMs?: number;
  estimatedCost?: number;
  currency?: string;
}

124. Budget Enforcement

Runtime 可以读取:

Agent Budget
Task Budget
Organization Budget
Project Budget

但 Budget Policy 应由:

Policy / Usage Runtime

统一控制。


125. Runtime Rate Limit

统一:

interface RateLimitPolicy {
  limit: number;
  windowMs: number;
  key: string;
}

例如:

organization
project
actor
provider
action

126. Concurrency

Runtime 可以声明:

interface ConcurrencyPolicy {
  maxConcurrent: number;

  key:
    | "global"
    | "organization"
    | "project"
    | "actor"
    | "resource"
    | "provider";
}

127. Resource Lock

需要独占资源时:

Runtime
 ↓
Lock Runtime
 ↓
execute
 ↓
release

例如:

production server
DNS zone
browser session
deployment

128. Runtime Transactions

涉及数据库事务:

Action Runtime
 ↓
Data Runtime.transaction()

Runtime 不应该自己:

BEGIN
COMMIT
ROLLBACK

除非它就是 Data Runtime。


129. Runtime Context Immutability

Context 原则上:

immutable

不要:

context.actor = anotherUser;

禁止权限上下文在执行过程中被偷偷修改。


130. Child Context

需要派生 Context:

const childContext =
  context.child({
    executionId
  });

必须:

继承 actor
继承 organization
继承 project
继承 environment
继承 correlation

不能提升权限。


131. Privilege Escalation Prevention

Child Context:

cannot change actor
cannot add permission
cannot change organization

除非经过:

explicit impersonation / delegation policy

132. Delegation

Agent 代表用户操作:

User
 ↓
Agent
 ↓
Action

Action Context:

actor.type = agent
actor.id = agentId

delegatedBy = userId

这样 Audit 能显示:

User → Agent → Action

133. Service Actor

系统任务:

Scheduler
Worker
Migration
System Cleanup

可以:

actor.type = system

或:

actor.type = service

但必须有明确:

service identity
permissions
audit

134. Runtime Isolation

Plugin Runtime 不意味着:

Plugin = unrestricted code

必须有:

permissions
capabilities
resource scopes
provider policies

135. Runtime Sandbox

如果未来支持不可信第三方 Plugin:

Plugin
 ↓
Sandbox
 ↓
DevOS Capability

而不是:

Plugin
 ↓
Node process
 ↓
everything

136. Runtime Security Boundary

安全边界必须至少存在于:

API
Action Runtime
Plugin Runtime
MCP Runtime
Agent Runtime
Storage Runtime
Secret Runtime

137. UI Is Not Security Boundary

前端:

hidden button

不能算权限。

真正:

Action Runtime
 ↓
Permission

138. Runtime Input Validation

所有 Runtime Public API:

schema validation

推荐:

Zod

139. Runtime Output Validation

重要边界也应该验证:

Provider output
Action output
MCP output
Agent structured output

避免:

unknown external data

直接进入系统。


140. Structured Agent Output

Agent 必须优先:

JSON Schema / Zod

例如:

const PlanSchema = z.object({
  steps: z.array(
    z.object({
      actionId: z.string(),
      reason: z.string()
    })
  )
});

141. Runtime Serialization

跨:

Process
Queue
Worker
Event
MCP
Task

的数据必须:

JSON-safe / schema-defined

禁止直接传:

class instance
database connection
function
socket
secret object

142. Runtime Boundary

跨 Runtime:

Data

而不是:

live mutable object

143. Runtime State

Runtime 内存状态:

ephemeral

如果必须持久化:

Resource
Task
Execution
Event
Config
Database

不要偷偷使用:

global Map

作为系统事实来源。


144. Source of Truth

统一原则:

Database
    = durable source of truth

Redis
    = coordination / cache / queue / ephemeral state

Search Index
    = derived state

Event Store
    = event history

Object Storage
    = binary source of truth

Runtime memory
    = ephemeral state

145. Cache Rule

Runtime 不得把 Cache 当成 Source of Truth。

DB
 ↓
Cache

不是:

Cache
 ↓
DB

除非明确 Write-back architecture。


146. Runtime Rebuildability

任何 Runtime:

restart

后应该能够:

recover
reinitialize
resume

不能依赖:

memory state

才能正常运行。


147. Runtime Crash Recovery

Worker / Queue / Task:

crash
 ↓
lease expires
 ↓
job requeued
 ↓
retry

148. Event Crash Recovery

Event Handler:

event
 ↓
handler crash
 ↓
delivery retry
 ↓
DLQ

149. Storage Crash Recovery

Upload:

upload session
 ↓
disconnect
 ↓
resume

不能要求:

restart
 ↓
restart from zero

150. Agent Crash Recovery

Agent:

Agent Run
 ↓
crash

必须可以:

resume

或者:

fail safely

而不是丢失整个状态。


151. Runtime Recovery Contract

需要恢复的 Runtime 可以实现:

interface RecoverableRuntime extends DevOSRuntime {
  recover(
    context: RuntimeContext
  ): Promise<Result<RecoveryReport>>;
}

152. Runtime Maintenance

支持:

interface MaintainableRuntime {
  maintenance(
    context: RuntimeContext
  ): Promise<Result<MaintenanceReport>>;
}

例如:

reconcile
cleanup
rebuild
repair

153. Reconciliation

需要长期一致性的 Runtime 应支持:

Source of Truth
 ↓
Reconciliation
 ↓
Derived State

例如:

DB
 ↓
Search Index

或者:

DB
 ↓
Queue

154. Runtime Reconciliation Must Be Idempotent

重复执行:

reconcile()
reconcile()
reconcile()

不应该破坏数据。


155. Runtime Contract Documentation

每个 Runtime package 必须包含:

README.md
CONTRACT.md

CONTRACT.md 至少包含:

Purpose
Public API
Context
Dependencies
Providers
Errors
Events
Permissions
Lifecycle
Tests
Limitations

156. Runtime README Template

# Action Runtime

## Purpose

## Responsibilities

## Non-responsibilities

## Public API

## Context

## Dependencies

## Providers

## Errors

## Events

## Permissions

## Lifecycle

## Observability

## Tests

157. Runtime Non-responsibilities

这是防止 Runtime 膨胀的关键。

例如:

Action Runtime

负责:

Action execution

不负责:

Queue storage
Agent planning
UI rendering
Database schema
Notification delivery

158. Runtime Ownership Matrix

必须维护:

docs/RUNTIME_OWNERSHIP.md

示例:

Responsibility Owner
Action execution Action Runtime
DB access Data Runtime
Async task Task Runtime
Queue Queue Runtime
Event Event Runtime
File Storage Runtime
Search Search Runtime
Secret Secret Runtime
Agent planning Agent Runtime
Plugin lifecycle Plugin Runtime
Capability discovery Capability Runtime

159. Zcode Runtime Creation Rule

Zcode 想新增 Runtime 时必须回答:

1. 为什么现有 Runtime 不能承担?
2. 新 Runtime 的唯一职责是什么?
3. 谁调用它?
4. 谁拥有它的数据?
5. 它依赖哪些 Runtime?
6. 它是否会重复现有 Runtime?
7. 为什么不能使用 Provider?

如果无法回答:

DO NOT CREATE RUNTIME

160. New Runtime Approval

默认:

architectureChanges = 0

新增核心 Runtime:

必须 ADR

除非它已经在:

01–23

中明确规定。


161. Runtime vs Service Decision

遇到新模块:

应该创建 Runtime?
还是 Service?

优先判断:

Runtime

满足:

跨多个模块复用
生命周期
Provider
统一 Contract
独立健康状态
独立权限
独立执行模型

Service

满足:

局部业务逻辑
Domain-specific
不需要独立生命周期
不需要 Provider abstraction

162. Runtime vs Module

Runtime:

平台能力

Module:

业务能力

例如:

Search Runtime

是平台。

SEO Module

是业务。


163. Runtime vs Plugin

Plugin:

可安装扩展

Runtime:

平台执行机制

Plugin 使用 Runtime。

通常不是反过来。


164. Runtime vs Provider

Runtime:

What the platform does

Provider:

How a concrete infrastructure implementation does it

例如:

Storage Runtime

而:

S3 Provider
Local Provider

是实现。


165. Runtime vs Action

Action:

一个具体可执行能力

Runtime:

执行 Action 的统一机制

例如:

seo.website.scan

是 Action。

Action Runtime

执行它。


166. Runtime vs Workflow

Workflow:

多个 Action 的固定组合

Runtime:

执行基础机制

167. Runtime vs Agent

Agent:

动态决定做什么

Runtime:

保证怎么安全执行

168. Runtime Contract Golden Path

任何执行:

Request
 ↓
RuntimeContext
 ↓
Permission
 ↓
Validation
 ↓
Policy
 ↓
Runtime
 ↓
Provider
 ↓
Result
 ↓
Audit
 ↓
Event
 ↓
Observability

169. Unified Execution Envelope

建议所有 Runtime Execution 使用:

export interface RuntimeExecutionEnvelope<I> {
  executionId: string;

  runtimeId: string;
  runtimeVersion: string;

  contractVersion: string;

  input: I;

  context: ExecutionContext;

  policy?: RuntimePolicy;
}

170. Unified Execution Result

export interface RuntimeExecutionResult<O> {
  executionId: string;

  success: boolean;

  output?: O;

  error?: DevOSError;

  startedAt: string;
  completedAt?: string;

  durationMs?: number;

  usage?: UsageMetadata;
}

171. Execution Traceability

任何执行必须能回答:

Who?
What?
Where?
When?
Why?
How?
Result?
Cost?
Version?

即:

actor
action
resource
timestamp
reason
runtime
result
usage
versions

172. Runtime Contract Checklist

新 Runtime:

[ ] Common Runtime Contract
[ ] Lifecycle
[ ] Context
[ ] Result
[ ] Error
[ ] Registry
[ ] Provider
[ ] Permission
[ ] Scope
[ ] Config
[ ] Secret
[ ] Audit
[ ] Event
[ ] Observability
[ ] Health
[ ] Version
[ ] Timeout
[ ] Cancellation
[ ] Retry
[ ] Idempotency
[ ] Contract Tests

不适用的项目必须明确:

N/A — reason

不能静默省略。


173. Zcode Implementation Sequence

Zcode 实现 Runtime 时:

1. Contract
2. Types
3. Registry
4. Context
5. Error
6. Lifecycle
7. Minimal Implementation
8. Provider
9. Permission
10. Audit
11. Event
12. Observability
13. Contract Tests
14. Integration Test
15. CLI / Debug
16. Documentation

174. Do Not Start With UI

错误:

UI
 ↓
API
 ↓
Service

正确:

Contract
 ↓
Runtime
 ↓
Action/API
 ↓
UI

175. Do Not Start With Provider

错误:

S3 implementation
 ↓
Storage Runtime

正确:

Storage Contract
 ↓
Storage Runtime
 ↓
Storage Provider Contract
 ↓
S3

176. Minimal Runtime First

第一版 Runtime 只需要:

Contract
Lifecycle
Core operation
Error
Permission
Test

然后再增加:

retry
cache
provider failover
reconciliation
advanced performance

177. Runtime Evolution

建议:

V1
Core Contract

V1.1
Observability

V1.2
Retry

V1.3
Advanced Provider

V2
Breaking Contract

不要每次需求都:

Runtime V2
Runtime V3
Runtime V4

178. Backward-compatible Extension

优先:

optional field
optional capability
new provider
new event
new action version

避免:

breaking interface

179. Runtime Contract Compatibility Matrix

建议维护:

docs/RUNTIME_COMPATIBILITY.md

例如:

Runtime Contract Provider Status
Action v1 Core Stable
Storage v1 S3 Stable
Storage v1 Local Stable
Search v1 PostgreSQL Stable
Event v1 PostgreSQL/Redis Stable

180. Final Runtime Architecture

最终:

                         ┌──────────────┐
                         │   Contract   │
                         └──────┬───────┘
                                │
                         ┌──────▼───────┐
                         │    Runtime   │
                         └──────┬───────┘
                                │
                 ┌──────────────┼──────────────┐
                 ▼              ▼              ▼
            Permission       Policy        Context
                 │              │              │
                 └──────────────┼──────────────┘
                                ▼
                         ┌──────────────┐
                         │   Provider   │
                         └──────┬───────┘
                                │
                         ┌──────▼───────┐
                         │ Infrastructure│
                         └──────────────┘

执行之后:

Runtime
  ↓
Result
  ├── Audit
  ├── Event
  ├── Metrics
  ├── Trace
  └── Usage

181. DevOS Runtime Stack

完整结构:

┌─────────────────────────────────────┐
│              UI / API               │
├─────────────────────────────────────┤
│       Agent / Plugin / MCP          │
├─────────────────────────────────────┤
│       Capability / Skill            │
├─────────────────────────────────────┤
│        Action / Workflow            │
├─────────────────────────────────────┤
│         Runtime Contracts           │
├─────────────────────────────────────┤
│          Runtime Layer              │
├─────────────────────────────────────┤
│       Provider Abstraction          │
├─────────────────────────────────────┤
│ PostgreSQL / Redis / Object Storage │
│ External APIs / Model Providers     │
└─────────────────────────────────────┘

182. Required Contract Package

最终 Zcode 应形成:

packages/contracts/

建议:

packages/contracts/
├── runtime/
│   ├── context.ts
│   ├── result.ts
│   ├── error.ts
│   ├── lifecycle.ts
│   ├── health.ts
│   ├── version.ts
│   ├── registry.ts
│   ├── provider.ts
│   ├── policy.ts
│   ├── permission.ts
│   ├── audit.ts
│   ├── observability.ts
│   └── execution.ts
│
├── resource/
├── action/
├── execution/
├── task/
├── job/
├── event/
├── storage/
├── search/
├── config/
├── plugin/
├── mcp/
├── capability/
├── skill/
├── agent/
├── workflow/
└── notification/

183. Contract Package Rules

packages/contracts:

允许:
Type
Interface
Schema
Enum
Error Definition
Contract

禁止:
Database
Redis
HTTP Server
Business Logic
Provider SDK
Filesystem

184. Contract Must Be Lightweight

不要让:

packages/contracts

最终变成:

God Package

它应该只描述:

WHAT

而不是:

HOW

185. Runtime Implementation Packages

例如:

packages/contracts/action
        ↓
packages/action
packages/contracts/storage
        ↓
packages/storage
packages/contracts/agent
        ↓
packages/agent

186. SDK Boundary

外部 Plugin/MCP/Project 不应该直接依赖:

internal runtime implementation

而应该:

DevOS SDK
 ↓
Public Contract
 ↓
DevOS Runtime

187. Public SDK

未来:

packages/sdk/

提供:

defineResource()
defineAction()
defineSkill()
definePlugin()
defineCapability()
defineProvider()

例如:

export default definePlugin({
  id: "seo",
  version: "1.0.0",

  resources: [],
  actions: [],
  skills: [],
  ui: []
});

188. SDK Must Not Expose Internals

Plugin SDK 不应该暴露:

Prisma
Redis
internal queue
internal event store
secret DB

只暴露:

DevOS Contracts
Capability APIs
Runtime APIs

189. Contract Test SDK

建议提供:

packages/sdk/testing/

例如:

definePluginContractTest(plugin);

defineActionContractTest(action);

defineStorageProviderContractTest(provider);

190. Developer Experience

开发者最终应该可以:

devos create plugin my-plugin

得到:

manifest
resource
action
skill
ui
tests

并自动符合 Runtime Contract。


191. Automated Architecture Checks

CI 必须检查:

Contract imports implementation?
Business imports provider?
UI imports DB?
Agent imports Redis?
Plugin imports internal runtime?
Duplicate Runtime?

192. Dependency Rule Summary

contracts
   ↑
runtime
   ↑
provider
   ↑
module
   ↑
app

允许:

higher layer → lower layer

禁止:

lower layer → higher layer

193. Final Runtime Contract Rules

1. Every Runtime has one Contract.
2. Every Runtime has one Owner.
3. Every Runtime has one Registry.
4. Every Runtime has one Lifecycle.
5. Every Runtime uses RuntimeContext.
6. Every Runtime returns Result.
7. Every Runtime uses DevOSError.
8. Every Runtime supports Health.
9. Every Runtime has Version.
10. Every Runtime has Observability.
11. Every Runtime respects Permission.
12. Every Runtime respects Scope.
13. Every external Provider is abstracted.
14. Every long-running operation supports cancellation.
15. Every retryable operation declares retryability.
16. Every side effect considers idempotency.
17. Every mutation supports Audit.
18. Every durable state change can emit Event.
19. No Runtime duplicates another Runtime.
20. No Runtime exposes infrastructure internals.

194. Zcode Absolute Rules

当 Zcode 实现 Runtime 时:

❌ 不允许自己重新定义 Context
❌ 不允许自己重新定义 Error
❌ 不允许自己重新定义 Result
❌ 不允许自己重新定义 Registry
❌ 不允许自己重新定义 Provider 基础接口
❌ 不允许自己重新定义 Permission
❌ 不允许自己重新定义 Audit
❌ 不允许自己重新定义 Observability

必须复用:

packages/contracts/runtime

195. Runtime Creation Decision Tree

Zcode 遇到新需求:

          新需求
             │
             ▼
     已有 Runtime 能做?
        │          │
       YES         NO
        │           │
        ▼           ▼
      复用       Provider 能解决?
                    │       │
                   YES      NO
                    │        │
                    ▼        ▼
                 Provider   新 Runtime?
                              │
                         ┌────┴────┐
                        YES       NO
                         │         │
                         ▼         ▼
                       ADR      Module/
                                Service

196. Runtime Creation Rule

只有满足:

平台级
跨模块
长期存在
独立生命周期
独立 Contract
独立 Health
独立 Policy

才应该创建新的 Runtime。


197. Final Integration Model

最终所有平台能力都必须能够组合:

Resource
      ↓
Action
      ↓
Runtime Contract
      ↓
Runtime
      ↓
Provider
      ↓
Infrastructure

Agent:

Goal
 ↓
Capability
 ↓
Skill
 ↓
Action
 ↓
Runtime

Plugin:

Manifest
 ↓
Resource
 ↓
Action
 ↓
Capability
 ↓
Runtime

MCP:

MCP
 ↓
Capability
 ↓
Action
 ↓
Runtime

UI:

UI
 ↓
API / Action
 ↓
Runtime

198. The One Runtime Principle

DevOS 最重要的基础设施原则:

同一种平台能力,只允许存在一个正式 Runtime。

可以存在:

多个 Provider
多个 Adapter
多个 Client
多个 UI
多个 Plugin
多个 MCP Server
多个 Skill
多个 Agent Profile

但是:

Action Execution
Task Execution
Event Processing
Storage
Search
Secret
Plugin Lifecycle
Agent Execution

不能因为不同业务模块而各自重新实现。


199. The Contract Principle

第二条原则:

Runtime 可以有不同实现,但必须共享稳定 Contract。

例如:

Storage Runtime
 ├── Local Provider
 ├── S3 Provider
 ├── MinIO Provider
 └── Future Provider

全部实现:

StorageProviderContract

200. The Provider Principle

第三条原则:

Runtime 定义能力,Provider 定义具体基础设施实现。

因此:

Storage Runtime ≠ S3
Search Runtime ≠ Elasticsearch
Model Runtime ≠ OpenAI
Queue Runtime ≠ Redis
Event Runtime ≠ Redis

201. The Execution Principle

第四条原则:

Contract 描述能力,Runtime 保证执行,Provider 提供实现。

完整链:

Contract
 ↓
Runtime
 ↓
Policy
 ↓
Permission
 ↓
Provider
 ↓
Infrastructure
 ↓
Result

202. The Observability Principle

第五条原则:

Runtime 执行不是黑盒。

每次重要执行必须可以追踪:

Actor
Request
Correlation
Runtime
Version
Action
Provider
Execution
Task
Job
Result
Error
Cost
Audit
Event

203. The Security Principle

第六条原则:

Runtime Contract 是安全边界的一部分。

不能因为:

Plugin
Agent
MCP
Worker
CLI
Internal Service

就绕过:

Permission
Scope
Policy
Audit

204. The Upgrade Principle

第七条原则:

Contract 稳定性决定 DevOS 可升级性。

升级:

Runtime
Provider
Plugin
MCP
Agent
Project

都应该基于:

Contract Version
+
Compatibility

而不是依赖:

“当前代码刚好能运行”

205. Final Golden Rule

                  DEVOS CONTRACTS
                         │
        ┌────────────────┼────────────────┐
        ▼                ▼                ▼
     Context           Result           Error
        │                │                │
        └────────────────┼────────────────┘
                         ▼
                    RUNTIME
                         │
        ┌────────────────┼────────────────┐
        ▼                ▼                ▼
   Permission         Policy         Observability
        │                │                │
        └────────────────┼────────────────┘
                         ▼
                     PROVIDER
                         │
                         ▼
                  INFRASTRUCTURE
                         │
                         ▼
                       RESULT
                         │
             ┌───────────┼───────────┐
             ▼           ▼           ▼
           AUDIT       EVENT       TRACE

最终原则:

DevOS 不是一堆 Runtime 的集合。

DevOS 是一套拥有统一 Contract 的 Runtime Platform。

Runtime 负责执行,Provider 负责实现,Contract 负责稳定边界,Policy 负责约束,Permission 负责授权,Audit 负责追踪,Event 负责传播,Observability 负责解释系统发生了什么。

Zcode 不得重新发明这些边界。

所有新的 Runtime、Plugin、MCP、Skill、Agent、Module 和 Project,都必须建立在这套统一 Contract 之上。