# 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 后续会存在: ```text 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 自己设计: ```text Context Result Error Registry Lifecycle Health Version Provider ``` 最终会变成: ```text Runtime A ├── AContext ├── AResult ├── AError └── ARegistry Runtime B ├── BContext ├── BResult ├── BError └── BRegistry Runtime C ├── CContext ├── CResult ├── CError └── CRegistry ``` 这种设计会导致: ```text 类型无法复用 错误无法统一 日志无法统一 权限无法统一 Agent 无法统一调用 Plugin 无法统一接入 测试无法统一 ``` 因此 DevOS 必须采用: > **Common Runtime Contract + Runtime-specific Extension** --- # 2. Core Principle 所有 Runtime: ```text Common Contract ↓ Runtime Contract ↓ Provider / Implementation ``` 例如: ```text RuntimeContract ↓ ActionRuntimeContract ↓ ActionRuntimeImpl ``` 或者: ```text RuntimeContract ↓ StorageRuntimeContract ↓ S3StorageProvider ``` --- # 3. Runtime Contract Layers 统一分为五层: ```text Layer 1 Common Types Layer 2 Runtime Lifecycle Layer 3 Runtime Context Layer 4 Runtime-specific Contract Layer 5 Provider / Implementation ``` 结构: ```text ┌──────────────────────────────┐ │ Runtime-specific Contract │ ├──────────────────────────────┤ │ Common Runtime Contract │ ├──────────────────────────────┤ │ Context / Result / Error │ ├──────────────────────────────┤ │ Registry / Lifecycle │ ├──────────────────────────────┤ │ Provider / Implementation │ └──────────────────────────────┘ ``` --- # 4. Package Ownership 统一 Contract 应放在: ```text packages/contracts/ ``` 建议: ```text 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: ```text packages/contracts ``` 不得依赖: ```text Action Runtime Task Runtime Plugin Agent SEO DevOps Business Modules UI ``` 正确: ```text contracts ↑ runtime ↑ modules ↑ apps ``` --- # 6. Common Runtime Interface 所有 Runtime 必须实现: ```ts export interface DevOSRuntime { readonly id: string; readonly version: string; readonly status: RuntimeStatus; initialize(context: RuntimeInitContext): Promise; start(context: RuntimeStartContext): Promise; stop(context: RuntimeStopContext): Promise; health(context: RuntimeHealthContext): Promise; dispose(context: RuntimeDisposeContext): Promise; } ``` --- # 7. Runtime Status 统一: ```ts export type RuntimeStatus = | "created" | "initializing" | "ready" | "starting" | "running" | "degraded" | "draining" | "stopping" | "stopped" | "failed"; ``` 生命周期: ```text created ↓ initializing ↓ ready ↓ starting ↓ running ↓ draining ↓ stopping ↓ stopped ``` 异常: ```text initializing → failed starting → failed running → degraded ``` --- # 8. Runtime Lifecycle Rules Runtime: ```text initialize() ``` 负责: ```text 配置加载 依赖解析 Schema 验证 Provider 准备 内部状态初始化 ``` 不得在: ```text initialize() ``` 中偷偷执行: ```text 业务操作 数据库大规模迁移 用户请求 Agent Task ``` --- # 9. Start ```ts start() ``` 负责: ```text 启动监听器 Worker Queue consumer Event subscriber Realtime connections ``` --- # 10. Stop Runtime 必须支持 graceful shutdown: ```text stop() ↓ stop accepting new work ↓ drain active work ↓ flush buffers ↓ close connections ↓ stopped ``` --- # 11. Dispose ```ts dispose() ``` 负责释放: ```text memory provider connections timers listeners subscriptions ``` --- # 12. Runtime Context 所有 Runtime Context 必须包含: ```ts export interface RuntimeContext { requestId: string; correlationId: string; actor: ActorContext; organizationId?: string; projectId?: string; environmentId?: string; locale?: string; timezone?: string; signal?: AbortSignal; metadata?: Record; } ``` --- # 13. Actor Context 统一: ```ts export type ActorType = | "user" | "agent" | "service" | "system"; ``` ```ts export interface ActorContext { id: string; type: ActorType; sessionId?: string; roles?: string[]; permissions?: string[]; metadata?: Record; } ``` --- # 14. Never Create Different Actor Models 禁止: ```text UserContext AgentContext PluginContext MCPContext TaskContext ``` 各自完全独立。 可以扩展: ```ts interface AgentRuntimeContext extends RuntimeContext { agentRunId: string; } ``` 但必须继承: ```text RuntimeContext ``` --- # 15. Execution Context 需要执行具体操作时: ```ts export interface ExecutionContext extends RuntimeContext { executionId: string; taskId?: string; jobId?: string; actionId?: string; actionVersion?: string; } ``` --- # 16. Common Result 统一 Result: ```ts export type Result = | { success: true; data: T; metadata?: ResultMetadata; } | { success: false; error: E; metadata?: ResultMetadata; }; ``` --- # 17. Result Metadata ```ts 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 错误: ```ts return openaiResponse; ``` 或者: ```ts return awsSdkResponse; ``` 应该: ```text Provider ↓ Adapter ↓ DevOS Contract ``` 这样业务层不依赖 Provider。 --- # 19. Common Error 统一: ```ts export interface DevOSError { code: string; message: string; category: ErrorCategory; retryable: boolean; severity: ErrorSeverity; safeMessage?: string; details?: Record; cause?: unknown; fingerprint?: string; requestId?: string; correlationId?: string; executionId?: string; } ``` --- # 20. Error Categories 统一: ```ts 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 ```ts export type ErrorSeverity = | "info" | "warning" | "error" | "critical"; ``` --- # 22. Error Code Naming 推荐: ```text .. ``` 例如: ```text 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 不要: ```ts throw new Error("Something went wrong"); ``` 应该: ```ts 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 以下字段绝对不能自动进入: ```text Error Log Audit Event Trace Result ``` 包括: ```text password apiKey token secret privateKey credentialValue sessionToken ``` 必须: ```text redact ``` --- # 25. Error Serialization 统一: ```ts export interface SerializedError { code: string; category: ErrorCategory; retryable: boolean; severity: ErrorSeverity; safeMessage: string; requestId?: string; correlationId?: string; executionId?: string; } ``` 内部: ```text details cause stack ``` 不应该默认返回客户端。 --- # 26. Runtime Registry 统一 Registry: ```ts export interface RuntimeRegistry { register(runtime: T): Promise | void; unregister(id: string): Promise | void; get(id: string): T | undefined; has(id: string): boolean; list(): T[]; health(): Promise; } ``` --- # 27. Registry Rules Registry: ```text register discover resolve health unregister ``` 不得承担: ```text business logic execution logic database workflow ``` --- # 28. Duplicate Registration 默认禁止: ```text register("action") register("action") ``` 除非明确: ```text replace ``` 且必须: ```text permission version compatibility ``` --- # 29. Runtime ID Runtime ID: ```text core.action core.task core.event core.storage core.search core.plugin core.agent ``` Plugin Runtime: ```text plugin. ``` 但 Plugin 业务 Runtime 仍然不能取代 Core Runtime。 --- # 30. Runtime Version 必须: ```ts interface RuntimeVersion { major: number; minor: number; patch: number; } ``` 推荐 SemVer。 --- # 31. Contract Version Runtime Version 与 Contract Version 分离。 例如: ```text Runtime: action-runtime 2.4.1 Contract: action-contract 1 ``` 这样 Provider 可以独立升级。 --- # 32. Compatibility 统一: ```ts export interface CompatibilityResult { compatible: boolean; issues: CompatibilityIssue[]; warnings: CompatibilityIssue[]; } ``` --- # 33. Runtime Health 统一: ```ts 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 ```ts export interface RuntimeDependencyHealth { id: string; status: | "healthy" | "degraded" | "unhealthy" | "unknown"; latencyMs?: number; message?: string; } ``` --- # 35. Runtime Provider Contract 所有可替换基础设施使用 Provider。 ```ts export interface DevOSProvider { readonly id: string; readonly type: string; readonly version: string; initialize(context: ProviderContext): Promise; health(context: ProviderContext): Promise; dispose(context: ProviderContext): Promise; } ``` --- # 36. Provider Context ```ts export interface ProviderContext extends RuntimeContext { providerId: string; configuration: Record; } ``` 敏感数据: ```text 不得直接塞入 configuration ``` 应通过: ```text Credential / Secret Runtime ``` 解析。 --- # 37. Provider Resolution 统一: ```text Runtime ↓ Provider Registry ↓ Provider Resolver ↓ Provider ``` 例如: ```text Storage Runtime ↓ Storage Provider Registry ↓ S3 Provider ``` --- # 38. Provider Failover Provider 支持: ```text primary ↓ health check ↓ fallback ``` 但: > Failover 必须由 Runtime Policy 控制。 业务代码不能: ```ts if (s3Failed) { useLocalFs(); } ``` --- # 39. Runtime Policy 统一: ```ts export interface RuntimePolicy { timeoutMs?: number; maxConcurrency?: number; retry?: RetryPolicy; rateLimit?: RateLimitPolicy; requireApproval?: boolean; allowedProviders?: string[]; deniedProviders?: string[]; } ``` --- # 40. Retry Policy ```ts export interface RetryPolicy { enabled: boolean; maxAttempts: number; strategy: | "fixed" | "linear" | "exponential"; initialDelayMs?: number; maxDelayMs?: number; jitter?: boolean; } ``` --- # 41. Runtime Execution 需要执行操作的 Runtime 应统一: ```ts export interface RuntimeExecutor { execute( input: I, context: ExecutionContext ): Promise>; } ``` --- # 42. Cancellation 所有可能长时间运行的操作: ```ts context.signal ``` 必须被支持。 例如: ```ts if (context.signal?.aborted) { throw cancelledError(); } ``` --- # 43. Timeout Runtime 不应该无限等待 Provider。 必须支持: ```text Runtime Policy ↓ Timeout ↓ AbortSignal ↓ Execution cancelled / failed ``` --- # 44. Idempotency 涉及副作用的 Runtime 必须支持: ```ts export interface IdempotencyContext { key: string; scope: string; ttlSeconds?: number; } ``` 例如: ```text action execution payment file upload webhook notification job ``` --- # 45. Audit Contract 涉及: ```text security permission data mutation external side effect ``` 必须支持 Audit。 ```ts export interface AuditContext { actor: ActorContext; action?: string; resourceType?: string; resourceId?: string; reason?: string; before?: unknown; after?: unknown; approvalId?: string; } ``` --- # 46. Event Contract Runtime 产生事件必须遵循统一: ```ts export interface DevOSEvent { 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。 统一使用: ```ts export interface RuntimeObservability { logger: DevOSLogger; metrics: DevOSMetrics; tracer: DevOSTracer; } ``` --- # 48. Logger ```ts 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 ```ts export interface LogContext { requestId?: string; correlationId?: string; executionId?: string; taskId?: string; jobId?: string; runtime?: string; action?: string; actorId?: string; metadata?: Record; } ``` --- # 50. Metrics Contract ```ts export interface DevOSMetrics { counter( name: string, value?: number, labels?: Record ): void; gauge( name: string, value: number, labels?: Record ): void; histogram( name: string, value: number, labels?: Record ): void; } ``` --- # 51. Trace Contract ```ts export interface DevOSTracer { startSpan( name: string, context?: TraceContext ): TraceSpan; } ``` 实现优先: ```text OpenTelemetry ``` 但业务 Runtime 依赖: ```text DevOSTracer ``` 而不是直接依赖 OpenTelemetry API。 --- # 52. Permission Contract 所有 Runtime 操作都应该能够检查: ```ts export interface PermissionChecker { check( permission: string, context: RuntimeContext, resource?: ResourceScope ): Promise; } ``` --- # 53. Permission Result ```ts export interface PermissionResult { allowed: boolean; reason?: string; matchedPolicies?: string[]; scope?: ResourceScope; } ``` --- # 54. Scope Contract ```ts export interface ResourceScope { organizationId?: string; projectId?: string; environmentId?: string; resourceType?: string; resourceId?: string; } ``` --- # 55. Runtime Authorization Rule Runtime 不应该只检查: ```text permission === true ``` 至少: ```text Actor ↓ Permission ↓ Resource ↓ Scope ↓ Policy ``` --- # 56. Configuration Contract Runtime 配置必须声明: ```ts export interface RuntimeConfigDefinition { runtimeId: string; schema: unknown; defaults?: Record; reloadable?: boolean; } ``` 实际值来自: ```text Configuration Runtime ``` 而不是 Runtime 自己从: ```text process.env ``` 读取。 --- # 57. Secret Contract Runtime 如果需要 Secret: ```ts export interface SecretReference { type: "secret"; id: string; } ``` Runtime 请求: ```text Secret Runtime ``` 而不是: ```ts process.env.API_KEY ``` --- # 58. Resource Contract Runtime 创建 Resource 时: ```ts 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 统一: ```ts export interface ActionDefinition { 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; } ``` --- # 60. Action Registration ```ts interface ActionRegistry { register(action: ActionDefinition): void; get(id: string, version?: string): ActionDefinition | undefined; list(): ActionDefinition[]; resolve( id: string, context: RuntimeContext ): Promise; } ``` --- # 61. Task Contract ```ts export interface TaskDefinition { id: string; type: string; name: string; actor: ActorContext; status: TaskStatus; input?: unknown; output?: unknown; progress?: TaskProgress; } ``` --- # 62. Job Contract ```ts export interface JobDefinition { id: string; taskId: string; actionId: string; actionVersion: string; input: unknown; attempts: number; maxAttempts: number; status: JobStatus; } ``` --- # 63. Execution Contract ```ts 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 ```ts export interface EventRuntime extends DevOSRuntime { publish( event: DevOSEvent, context: RuntimeContext ): Promise>; subscribe( subscription: EventSubscription, context: RuntimeContext ): Promise>; unsubscribe( subscriptionId: string, context: RuntimeContext ): Promise>; replay( request: EventReplayRequest, context: RuntimeContext ): Promise>; } ``` --- # 65. Storage Runtime Contract ```ts export interface StorageRuntime extends DevOSRuntime { upload( input: StorageUploadInput, context: ExecutionContext ): Promise>; download( input: StorageDownloadInput, context: ExecutionContext ): Promise>; delete( input: StorageDeleteInput, context: ExecutionContext ): Promise>; getMetadata( input: StorageMetadataInput, context: RuntimeContext ): Promise>; } ``` --- # 66. Search Runtime Contract ```ts export interface SearchRuntime extends DevOSRuntime { search( input: SearchInput, context: RuntimeContext ): Promise>; index( input: IndexInput, context: ExecutionContext ): Promise>; rebuild( input: RebuildIndexInput, context: ExecutionContext ): Promise>; } ``` --- # 67. Configuration Runtime Contract ```ts export interface ConfigurationRuntime extends DevOSRuntime { resolve( input: ResolveConfigInput, context: RuntimeContext ): Promise>; set( input: SetConfigInput, context: ExecutionContext ): Promise>; rollback( input: RollbackConfigInput, context: ExecutionContext ): Promise>; } ``` --- # 68. Secret Runtime Contract ```ts export interface SecretRuntime extends DevOSRuntime { create( input: CreateSecretInput, context: ExecutionContext ): Promise>; resolve( reference: SecretReference, context: RuntimeContext ): Promise>; rotate( input: RotateSecretInput, context: ExecutionContext ): Promise>; revoke( input: RevokeSecretInput, context: ExecutionContext ): Promise>; } ``` `SecretValue`: ```ts interface SecretValue { value: string; } ``` 只允许在: ```text secure runtime boundary ``` 短暂存在。 --- # 69. Plugin Runtime Contract ```ts export interface PluginRuntime extends DevOSRuntime { install( input: PluginInstallInput, context: ExecutionContext ): Promise>; enable( pluginId: string, context: ExecutionContext ): Promise>; disable( pluginId: string, context: ExecutionContext ): Promise>; upgrade( input: PluginUpgradeInput, context: ExecutionContext ): Promise>; uninstall( pluginId: string, context: ExecutionContext ): Promise>; } ``` --- # 70. Capability Runtime Contract ```ts export interface CapabilityRegistry { register( capability: CapabilityDefinition ): void; unregister( id: string ): void; get( id: string, version?: string ): CapabilityDefinition | undefined; search( input: CapabilitySearchInput, context: RuntimeContext ): Promise>; } ``` --- # 71. Agent Runtime Contract ```ts export interface AgentRuntime extends DevOSRuntime { createGoal( input: AgentGoalInput, context: RuntimeContext ): Promise>; run( goalId: string, context: ExecutionContext ): Promise>; cancel( runId: string, context: ExecutionContext ): Promise>; observe( runId: string, context: RuntimeContext ): Promise>; } ``` --- # 72. Agent Runtime Restrictions Agent Runtime: ```text 可以: Goal Plan Capability Discovery Action Task Observation Replan ``` 不能: ```text Direct DB Direct Redis Direct filesystem Direct Queue Direct Secret Store ``` --- # 73. MCP Runtime Contract ```ts export interface MCPRuntime extends DevOSRuntime { connect( input: MCPConnectionInput, context: RuntimeContext ): Promise>; discover( connectionId: string, context: RuntimeContext ): Promise>; invoke( input: MCPInvokeInput, context: ExecutionContext ): Promise>; disconnect( connectionId: string, context: RuntimeContext ): Promise>; } ``` --- # 74. MCP Invocation Rule 内部执行必须: ```text MCP ↓ Capability ↓ Permission ↓ Action Runtime ↓ Execution ``` --- # 75. Workflow Runtime Contract ```ts export interface WorkflowRuntime extends DevOSRuntime { validate( workflow: WorkflowDefinition, context: RuntimeContext ): Promise>; start( input: WorkflowStartInput, context: ExecutionContext ): Promise>; cancel( workflowRunId: string, context: ExecutionContext ): Promise>; } ``` Workflow 不应该重新实现: ```text Task Job Queue Action Event ``` 而应该组合这些 Runtime。 --- # 76. Notification Runtime Contract ```ts export interface NotificationRuntime extends DevOSRuntime { send( input: NotificationInput, context: ExecutionContext ): Promise>; schedule( input: ScheduledNotificationInput, context: ExecutionContext ): Promise>; } ``` --- # 77. Data Runtime Contract ```ts export interface DataRuntime extends DevOSRuntime { query( input: QueryInput, context: RuntimeContext ): Promise>>; aggregate( input: AggregateInput, context: RuntimeContext ): Promise>; transaction( operation: DataTransaction, context: ExecutionContext ): Promise>; } ``` --- # 78. Write Rule Data Runtime 可以执行数据库写操作。 但业务模块: ```text 不得直接调用 DataRuntime.write() ``` 业务 mutation: ```text Action ↓ Action Runtime ↓ Data Runtime ``` 这样才能统一: ```text permission audit event idempotency observability ``` --- # 79. Query Rule 读取: ```text Resource ↓ Query ↓ Data Runtime ``` 查询必须自动处理: ```text permission scope field access pagination sorting filter validation ``` --- # 80. Queue Runtime Contract ```ts export interface QueueRuntime extends DevOSRuntime { enqueue( job: JobDefinition, context: RuntimeContext ): Promise>; dequeue( input: QueueDequeueInput, context: RuntimeContext ): Promise>; acknowledge( jobId: string, context: RuntimeContext ): Promise>; retry( jobId: string, context: RuntimeContext ): Promise>; } ``` --- # 81. Worker Runtime Contract ```ts export interface WorkerRuntime extends DevOSRuntime { register( worker: WorkerDefinition ): Promise; drain( workerId: string, context: RuntimeContext ): Promise>; execute( job: JobDefinition, context: ExecutionContext ): Promise>; } ``` Worker 最终: ```text Action Runtime ``` --- # 82. Scheduler Runtime Contract Scheduler 不直接执行业务。 正确: ```text Schedule ↓ Task ↓ Job ↓ Queue ``` Contract: ```ts export interface SchedulerRuntime extends DevOSRuntime { schedule( input: ScheduleInput, context: ExecutionContext ): Promise>; unschedule( scheduleId: string, context: ExecutionContext ): Promise>; } ``` --- # 83. Runtime Adapter 旧代码迁移允许: ```ts export interface RuntimeAdapter { canHandle(input: Legacy): boolean; adapt(input: Legacy): Modern; } ``` Adapter: ```text Legacy ↓ Adapter ↓ DevOS Contract ``` 不能永久成为第二 Runtime。 --- # 84. Runtime Facade 复杂 Runtime 可以提供 Facade: ```ts export interface RuntimeFacade { readonly runtime: DevOSRuntime; } ``` Facade 只负责: ```text API simplification ``` 不能重新实现: ```text execution permission queue event ``` --- # 85. Runtime Composition Runtime 可以调用 Runtime。 但是依赖必须明确。 例如: ```text Agent Runtime ↓ Capability Runtime ↓ Action Runtime ↓ Data Runtime ``` 合法。 --- # 86. Forbidden Runtime Cycles 禁止: ```text Action ↓ Agent ↓ Action ``` 或者: ```text Task ↓ Event ↓ Task ↓ Event ``` 如果业务确实需要: ```text Event → Task ``` 必须通过: ```text event trigger policy ``` 避免无限循环。 --- # 87. Runtime Dependency Graph 建议维护: ```text packages/contracts ↓ core ↓ identity / permission ↓ resource ↓ data ↓ action ↓ execution ↓ task ↓ event ↓ plugin / mcp / capability ↓ skill ↓ agent ``` --- # 88. Core Runtime Dependencies Core Runtime 不允许依赖: ```text SEO CRM Content DevOps Business ``` --- # 89. Runtime Registration Lifecycle 系统启动: ```text Load Config ↓ Initialize Providers ↓ Initialize Runtimes ↓ Register Resources ↓ Register Actions ↓ Register Capabilities ↓ Register Plugins ↓ Start Workers ↓ Start Event Consumers ↓ READY ``` --- # 90. Registration Ordering 依赖必须先注册: ```text Contracts ↓ Provider ↓ Runtime ↓ Resource ↓ Action ↓ Capability ↓ Plugin ↓ Agent ``` --- # 91. Runtime Bootstrap 推荐: ```ts interface RuntimeBootstrap { runtimes: DevOSRuntime[]; providers: DevOSProvider[]; resources: ResourceDefinition[]; actions: ActionDefinition[]; capabilities: CapabilityDefinition[]; } ``` --- # 92. Bootstrap Must Be Deterministic 同样的: ```text configuration + plugin versions + environment ``` 应该得到相同: ```text runtime registry resource registry action registry capability registry ``` --- # 93. No Hidden Runtime Registration 禁止: ```ts constructor() { globalRegistry.register(...) } ``` 这会导致: ```text import order ``` 决定系统行为。 应该显式: ```text bootstrap ↓ register ``` --- # 94. Runtime Registry Snapshot 系统应该能够输出: ```json { "runtimeVersion": "1.0.0", "runtimes": [], "providers": [], "resources": [], "actions": [], "capabilities": [] } ``` 用于: ```text debug diagnostics upgrade reproducibility ``` --- # 95. Runtime Contract Testing 所有 Runtime 必须测试: ```text Lifecycle Context Health Error Permission Cancellation Timeout Observability Version ``` --- # 96. Generic Runtime Contract Test 建议: ```ts describeRuntimeContract( createRuntime, { id: "core.action", version: "1.0.0" } ); ``` 测试: ```text ✓ initialize ✓ start ✓ health ✓ stop ✓ dispose ``` --- # 97. Error Contract Test 所有 Runtime: ```text ✓ machine-readable error ✓ error code ✓ category ✓ retryable ✓ safe message ✓ correlation ID ✓ no secret leakage ``` --- # 98. Cancellation Contract Test 所有长任务: ```text start ↓ AbortSignal ↓ operation stops ↓ no orphan work ``` --- # 99. Timeout Contract Test 测试: ```text Provider hangs ↓ timeout ↓ Abort ↓ Execution failed ↓ correct error ``` --- # 100. Permission Contract Test 至少: ```text authorized → PASS unauthorized → DENY wrong organization → DENY wrong project → DENY wrong environment → DENY ``` --- # 101. Observability Contract Test 执行一次 Runtime 后必须能够找到: ```text requestId correlationId runtime actor duration result error ``` --- # 102. Audit Contract Test Mutation Runtime: ```text execute ↓ audit exists ``` Audit 至少包含: ```text actor action target result timestamp correlation ``` --- # 103. Event Contract Test 需要事件的 Runtime: ```text execute ↓ event emitted ``` 事件必须包含: ```text eventId eventType version actor correlationId payload ``` --- # 104. Version Contract Test 测试: ```text Runtime version Action version Provider version Contract version ``` 是否可追踪。 --- # 105. Runtime Health Contract Test 测试: ```text healthy dependency ↓ healthy failed dependency ↓ degraded/unhealthy ``` --- # 106. Provider Contract Testing 同一 Provider Contract: ```text S3 Local MinIO ``` 应该都可以运行: ```text StorageProviderContractTest ``` 这样 Provider 可以替换。 --- # 107. Example Provider Contract ```ts describeStorageProviderContract( () => createS3Provider() ); describeStorageProviderContract( () => createLocalProvider() ); ``` --- # 108. Contract Compatibility 新版本 Provider: ```text Provider v2 ``` 必须通过: ```text Provider Contract v1 ``` 才能接入。 如果 Contract Breaking: ```text Contract v2 ``` 必须明确。 --- # 109. Runtime Contract Versioning 建议: ```text core.runtime@1 action.runtime@1 task.runtime@1 event.runtime@1 storage.runtime@1 ``` Breaking change: ```text @1 → @2 ``` 非 breaking: ```text 1.1 ``` --- # 110. Backward Compatibility 尽可能: ```text new Runtime 支持 old Contract ``` 通过 Adapter: ```text old contract ↓ adapter ↓ new runtime ``` --- # 111. Runtime API Surface 每个 Runtime 必须明确: ```text PUBLIC INTERNAL PRIVATE ``` 例如: ```text public: execute() internal: resolveProvider() private: buildQuery() ``` --- # 112. No Leaky Abstraction 禁止向业务层暴露: ```text Prisma Client Redis Client AWS SDK OpenAI SDK BullMQ Job ``` 应该暴露: ```text DevOS Contract ``` --- # 113. Runtime Error Translation Provider: ```text AWS Error ``` 转换: ```text storage.provider.unavailable ``` 数据库: ```text Prisma Error ``` 转换: ```text data.database.unavailable ``` --- # 114. Runtime Event Translation Provider-specific Event: ```text S3 ObjectCreated ``` 可以转换: ```text storage.file.created ``` 这样业务不依赖 S3。 --- # 115. Runtime Metadata 所有 Runtime 可以提供: ```ts export interface RuntimeMetadata { id: string; name: string; description: string; version: string; contractVersion: string; capabilities: string[]; dependencies: string[]; providers?: string[]; } ``` --- # 116. Runtime Discovery 系统应该支持: ```ts runtimeRegistry.list() ``` 输出: ```text core.action core.data core.task core.event core.storage core.search core.plugin core.agent ``` --- # 117. Runtime Diagnostics 建议: ```bash devos runtime list devos runtime inspect core.action devos runtime health devos runtime dependencies ``` --- # 118. Runtime Inspect 例如: ```bash devos runtime inspect core.action ``` 应该显示: ```text ID Version Contract Version Status Dependencies Providers Capabilities Health Metrics ``` 不能显示: ```text secret values private credentials ``` --- # 119. Runtime Metrics 每个 Runtime 至少记录: ```text runtime.calls runtime.success runtime.failure runtime.duration runtime.timeout runtime.cancelled runtime.retry ``` --- # 120. Runtime Cardinality 禁止将: ```text userId taskId executionId requestId ``` 作为无限 cardinality metric label。 这些应该进入: ```text Logs / Traces ``` 而不是 Metrics。 --- # 121. Runtime Logging 日志必须包含: ```text runtime requestId correlationId executionId actor ``` 但不包含: ```text secret token password private key ``` --- # 122. Runtime Tracing 建议 Span: ```text devos.runtime.action devos.runtime.data devos.runtime.task devos.runtime.event ``` 嵌套: ```text Agent Span └── Action Runtime Span └── Data Runtime Span ``` --- # 123. Runtime Cost 可能产生费用的 Runtime: ```text Agent Model Search Storage External API Browser Compute ``` 应支持: ```ts interface UsageMetadata { tokens?: number; requests?: number; bytes?: number; durationMs?: number; estimatedCost?: number; currency?: string; } ``` --- # 124. Budget Enforcement Runtime 可以读取: ```text Agent Budget Task Budget Organization Budget Project Budget ``` 但 Budget Policy 应由: ```text Policy / Usage Runtime ``` 统一控制。 --- # 125. Runtime Rate Limit 统一: ```ts interface RateLimitPolicy { limit: number; windowMs: number; key: string; } ``` 例如: ```text organization project actor provider action ``` --- # 126. Concurrency Runtime 可以声明: ```ts interface ConcurrencyPolicy { maxConcurrent: number; key: | "global" | "organization" | "project" | "actor" | "resource" | "provider"; } ``` --- # 127. Resource Lock 需要独占资源时: ```text Runtime ↓ Lock Runtime ↓ execute ↓ release ``` 例如: ```text production server DNS zone browser session deployment ``` --- # 128. Runtime Transactions 涉及数据库事务: ```text Action Runtime ↓ Data Runtime.transaction() ``` Runtime 不应该自己: ```text BEGIN COMMIT ROLLBACK ``` 除非它就是 Data Runtime。 --- # 129. Runtime Context Immutability Context 原则上: ```text immutable ``` 不要: ```ts context.actor = anotherUser; ``` 禁止权限上下文在执行过程中被偷偷修改。 --- # 130. Child Context 需要派生 Context: ```ts const childContext = context.child({ executionId }); ``` 必须: ```text 继承 actor 继承 organization 继承 project 继承 environment 继承 correlation ``` 不能提升权限。 --- # 131. Privilege Escalation Prevention Child Context: ```text cannot change actor cannot add permission cannot change organization ``` 除非经过: ```text explicit impersonation / delegation policy ``` --- # 132. Delegation Agent 代表用户操作: ```text User ↓ Agent ↓ Action ``` Action Context: ```text actor.type = agent actor.id = agentId delegatedBy = userId ``` 这样 Audit 能显示: ```text User → Agent → Action ``` --- # 133. Service Actor 系统任务: ```text Scheduler Worker Migration System Cleanup ``` 可以: ```text actor.type = system ``` 或: ```text actor.type = service ``` 但必须有明确: ```text service identity permissions audit ``` --- # 134. Runtime Isolation Plugin Runtime 不意味着: ```text Plugin = unrestricted code ``` 必须有: ```text permissions capabilities resource scopes provider policies ``` --- # 135. Runtime Sandbox 如果未来支持不可信第三方 Plugin: ```text Plugin ↓ Sandbox ↓ DevOS Capability ``` 而不是: ```text Plugin ↓ Node process ↓ everything ``` --- # 136. Runtime Security Boundary 安全边界必须至少存在于: ```text API Action Runtime Plugin Runtime MCP Runtime Agent Runtime Storage Runtime Secret Runtime ``` --- # 137. UI Is Not Security Boundary 前端: ```text hidden button ``` 不能算权限。 真正: ```text Action Runtime ↓ Permission ``` --- # 138. Runtime Input Validation 所有 Runtime Public API: ```text schema validation ``` 推荐: ```text Zod ``` --- # 139. Runtime Output Validation 重要边界也应该验证: ```text Provider output Action output MCP output Agent structured output ``` 避免: ```text unknown external data ``` 直接进入系统。 --- # 140. Structured Agent Output Agent 必须优先: ```text JSON Schema / Zod ``` 例如: ```ts const PlanSchema = z.object({ steps: z.array( z.object({ actionId: z.string(), reason: z.string() }) ) }); ``` --- # 141. Runtime Serialization 跨: ```text Process Queue Worker Event MCP Task ``` 的数据必须: ```text JSON-safe / schema-defined ``` 禁止直接传: ```text class instance database connection function socket secret object ``` --- # 142. Runtime Boundary 跨 Runtime: ```text Data ``` 而不是: ```text live mutable object ``` --- # 143. Runtime State Runtime 内存状态: ```text ephemeral ``` 如果必须持久化: ```text Resource Task Execution Event Config Database ``` 不要偷偷使用: ```text global Map ``` 作为系统事实来源。 --- # 144. Source of Truth 统一原则: ```text 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。 ```text DB ↓ Cache ``` 不是: ```text Cache ↓ DB ``` 除非明确 Write-back architecture。 --- # 146. Runtime Rebuildability 任何 Runtime: ```text restart ``` 后应该能够: ```text recover reinitialize resume ``` 不能依赖: ```text memory state ``` 才能正常运行。 --- # 147. Runtime Crash Recovery Worker / Queue / Task: ```text crash ↓ lease expires ↓ job requeued ↓ retry ``` --- # 148. Event Crash Recovery Event Handler: ```text event ↓ handler crash ↓ delivery retry ↓ DLQ ``` --- # 149. Storage Crash Recovery Upload: ```text upload session ↓ disconnect ↓ resume ``` 不能要求: ```text restart ↓ restart from zero ``` --- # 150. Agent Crash Recovery Agent: ```text Agent Run ↓ crash ``` 必须可以: ```text resume ``` 或者: ```text fail safely ``` 而不是丢失整个状态。 --- # 151. Runtime Recovery Contract 需要恢复的 Runtime 可以实现: ```ts interface RecoverableRuntime extends DevOSRuntime { recover( context: RuntimeContext ): Promise>; } ``` --- # 152. Runtime Maintenance 支持: ```ts interface MaintainableRuntime { maintenance( context: RuntimeContext ): Promise>; } ``` 例如: ```text reconcile cleanup rebuild repair ``` --- # 153. Reconciliation 需要长期一致性的 Runtime 应支持: ```text Source of Truth ↓ Reconciliation ↓ Derived State ``` 例如: ```text DB ↓ Search Index ``` 或者: ```text DB ↓ Queue ``` --- # 154. Runtime Reconciliation Must Be Idempotent 重复执行: ```text reconcile() reconcile() reconcile() ``` 不应该破坏数据。 --- # 155. Runtime Contract Documentation 每个 Runtime package 必须包含: ```text README.md CONTRACT.md ``` `CONTRACT.md` 至少包含: ```text Purpose Public API Context Dependencies Providers Errors Events Permissions Lifecycle Tests Limitations ``` --- # 156. Runtime README Template ```md # Action Runtime ## Purpose ## Responsibilities ## Non-responsibilities ## Public API ## Context ## Dependencies ## Providers ## Errors ## Events ## Permissions ## Lifecycle ## Observability ## Tests ``` --- # 157. Runtime Non-responsibilities 这是防止 Runtime 膨胀的关键。 例如: ```text Action Runtime ``` 负责: ```text Action execution ``` 不负责: ```text Queue storage Agent planning UI rendering Database schema Notification delivery ``` --- # 158. Runtime Ownership Matrix 必须维护: ```text 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 时必须回答: ```text 1. 为什么现有 Runtime 不能承担? 2. 新 Runtime 的唯一职责是什么? 3. 谁调用它? 4. 谁拥有它的数据? 5. 它依赖哪些 Runtime? 6. 它是否会重复现有 Runtime? 7. 为什么不能使用 Provider? ``` 如果无法回答: ```text DO NOT CREATE RUNTIME ``` --- # 160. New Runtime Approval 默认: ```text architectureChanges = 0 ``` 新增核心 Runtime: ```text 必须 ADR ``` 除非它已经在: ```text 01–23 ``` 中明确规定。 --- # 161. Runtime vs Service Decision 遇到新模块: ```text 应该创建 Runtime? 还是 Service? ``` 优先判断: ### Runtime 满足: ```text 跨多个模块复用 生命周期 Provider 统一 Contract 独立健康状态 独立权限 独立执行模型 ``` ### Service 满足: ```text 局部业务逻辑 Domain-specific 不需要独立生命周期 不需要 Provider abstraction ``` --- # 162. Runtime vs Module Runtime: ```text 平台能力 ``` Module: ```text 业务能力 ``` 例如: ```text Search Runtime ``` 是平台。 ```text SEO Module ``` 是业务。 --- # 163. Runtime vs Plugin Plugin: ```text 可安装扩展 ``` Runtime: ```text 平台执行机制 ``` Plugin 使用 Runtime。 通常不是反过来。 --- # 164. Runtime vs Provider Runtime: ```text What the platform does ``` Provider: ```text How a concrete infrastructure implementation does it ``` 例如: ```text Storage Runtime ``` 而: ```text S3 Provider Local Provider ``` 是实现。 --- # 165. Runtime vs Action Action: ```text 一个具体可执行能力 ``` Runtime: ```text 执行 Action 的统一机制 ``` 例如: ```text seo.website.scan ``` 是 Action。 ```text Action Runtime ``` 执行它。 --- # 166. Runtime vs Workflow Workflow: ```text 多个 Action 的固定组合 ``` Runtime: ```text 执行基础机制 ``` --- # 167. Runtime vs Agent Agent: ```text 动态决定做什么 ``` Runtime: ```text 保证怎么安全执行 ``` --- # 168. Runtime Contract Golden Path 任何执行: ```text Request ↓ RuntimeContext ↓ Permission ↓ Validation ↓ Policy ↓ Runtime ↓ Provider ↓ Result ↓ Audit ↓ Event ↓ Observability ``` --- # 169. Unified Execution Envelope 建议所有 Runtime Execution 使用: ```ts export interface RuntimeExecutionEnvelope { executionId: string; runtimeId: string; runtimeVersion: string; contractVersion: string; input: I; context: ExecutionContext; policy?: RuntimePolicy; } ``` --- # 170. Unified Execution Result ```ts export interface RuntimeExecutionResult { executionId: string; success: boolean; output?: O; error?: DevOSError; startedAt: string; completedAt?: string; durationMs?: number; usage?: UsageMetadata; } ``` --- # 171. Execution Traceability 任何执行必须能回答: ```text Who? What? Where? When? Why? How? Result? Cost? Version? ``` 即: ```text actor action resource timestamp reason runtime result usage versions ``` --- # 172. Runtime Contract Checklist 新 Runtime: ```text [ ] Common Runtime Contract [ ] Lifecycle [ ] Context [ ] Result [ ] Error [ ] Registry [ ] Provider [ ] Permission [ ] Scope [ ] Config [ ] Secret [ ] Audit [ ] Event [ ] Observability [ ] Health [ ] Version [ ] Timeout [ ] Cancellation [ ] Retry [ ] Idempotency [ ] Contract Tests ``` 不适用的项目必须明确: ```text N/A — reason ``` 不能静默省略。 --- # 173. Zcode Implementation Sequence Zcode 实现 Runtime 时: ```text 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 错误: ```text UI ↓ API ↓ Service ``` 正确: ```text Contract ↓ Runtime ↓ Action/API ↓ UI ``` --- # 175. Do Not Start With Provider 错误: ```text S3 implementation ↓ Storage Runtime ``` 正确: ```text Storage Contract ↓ Storage Runtime ↓ Storage Provider Contract ↓ S3 ``` --- # 176. Minimal Runtime First 第一版 Runtime 只需要: ```text Contract Lifecycle Core operation Error Permission Test ``` 然后再增加: ```text retry cache provider failover reconciliation advanced performance ``` --- # 177. Runtime Evolution 建议: ```text V1 Core Contract V1.1 Observability V1.2 Retry V1.3 Advanced Provider V2 Breaking Contract ``` 不要每次需求都: ```text Runtime V2 Runtime V3 Runtime V4 ``` --- # 178. Backward-compatible Extension 优先: ```text optional field optional capability new provider new event new action version ``` 避免: ```text breaking interface ``` --- # 179. Runtime Contract Compatibility Matrix 建议维护: ```text 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 最终: ```text ┌──────────────┐ │ Contract │ └──────┬───────┘ │ ┌──────▼───────┐ │ Runtime │ └──────┬───────┘ │ ┌──────────────┼──────────────┐ ▼ ▼ ▼ Permission Policy Context │ │ │ └──────────────┼──────────────┘ ▼ ┌──────────────┐ │ Provider │ └──────┬───────┘ │ ┌──────▼───────┐ │ Infrastructure│ └──────────────┘ ``` 执行之后: ```text Runtime ↓ Result ├── Audit ├── Event ├── Metrics ├── Trace └── Usage ``` --- # 181. DevOS Runtime Stack 完整结构: ```text ┌─────────────────────────────────────┐ │ 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 应形成: ```text packages/contracts/ ``` 建议: ```text 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`: ```text 允许: Type Interface Schema Enum Error Definition Contract 禁止: Database Redis HTTP Server Business Logic Provider SDK Filesystem ``` --- # 184. Contract Must Be Lightweight 不要让: ```text packages/contracts ``` 最终变成: ```text God Package ``` 它应该只描述: ```text WHAT ``` 而不是: ```text HOW ``` --- # 185. Runtime Implementation Packages 例如: ```text packages/contracts/action ↓ packages/action ``` ```text packages/contracts/storage ↓ packages/storage ``` ```text packages/contracts/agent ↓ packages/agent ``` --- # 186. SDK Boundary 外部 Plugin/MCP/Project 不应该直接依赖: ```text internal runtime implementation ``` 而应该: ```text DevOS SDK ↓ Public Contract ↓ DevOS Runtime ``` --- # 187. Public SDK 未来: ```text packages/sdk/ ``` 提供: ```ts defineResource() defineAction() defineSkill() definePlugin() defineCapability() defineProvider() ``` 例如: ```ts export default definePlugin({ id: "seo", version: "1.0.0", resources: [], actions: [], skills: [], ui: [] }); ``` --- # 188. SDK Must Not Expose Internals Plugin SDK 不应该暴露: ```text Prisma Redis internal queue internal event store secret DB ``` 只暴露: ```text DevOS Contracts Capability APIs Runtime APIs ``` --- # 189. Contract Test SDK 建议提供: ```text packages/sdk/testing/ ``` 例如: ```ts definePluginContractTest(plugin); defineActionContractTest(action); defineStorageProviderContractTest(provider); ``` --- # 190. Developer Experience 开发者最终应该可以: ```bash devos create plugin my-plugin ``` 得到: ```text manifest resource action skill ui tests ``` 并自动符合 Runtime Contract。 --- # 191. Automated Architecture Checks CI 必须检查: ```text Contract imports implementation? Business imports provider? UI imports DB? Agent imports Redis? Plugin imports internal runtime? Duplicate Runtime? ``` --- # 192. Dependency Rule Summary ```text contracts ↑ runtime ↑ provider ↑ module ↑ app ``` 允许: ```text higher layer → lower layer ``` 禁止: ```text lower layer → higher layer ``` --- # 193. Final Runtime Contract Rules ```text 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 时: ```text ❌ 不允许自己重新定义 Context ❌ 不允许自己重新定义 Error ❌ 不允许自己重新定义 Result ❌ 不允许自己重新定义 Registry ❌ 不允许自己重新定义 Provider 基础接口 ❌ 不允许自己重新定义 Permission ❌ 不允许自己重新定义 Audit ❌ 不允许自己重新定义 Observability ``` 必须复用: ```text packages/contracts/runtime ``` --- # 195. Runtime Creation Decision Tree Zcode 遇到新需求: ```text 新需求 │ ▼ 已有 Runtime 能做? │ │ YES NO │ │ ▼ ▼ 复用 Provider 能解决? │ │ YES NO │ │ ▼ ▼ Provider 新 Runtime? │ ┌────┴────┐ YES NO │ │ ▼ ▼ ADR Module/ Service ``` --- # 196. Runtime Creation Rule 只有满足: ```text 平台级 跨模块 长期存在 独立生命周期 独立 Contract 独立 Health 独立 Policy ``` 才应该创建新的 Runtime。 --- # 197. Final Integration Model 最终所有平台能力都必须能够组合: ```text Resource ↓ Action ↓ Runtime Contract ↓ Runtime ↓ Provider ↓ Infrastructure ``` Agent: ```text Goal ↓ Capability ↓ Skill ↓ Action ↓ Runtime ``` Plugin: ```text Manifest ↓ Resource ↓ Action ↓ Capability ↓ Runtime ``` MCP: ```text MCP ↓ Capability ↓ Action ↓ Runtime ``` UI: ```text UI ↓ API / Action ↓ Runtime ``` --- # 198. The One Runtime Principle DevOS 最重要的基础设施原则: > **同一种平台能力,只允许存在一个正式 Runtime。** 可以存在: ```text 多个 Provider 多个 Adapter 多个 Client 多个 UI 多个 Plugin 多个 MCP Server 多个 Skill 多个 Agent Profile ``` 但是: ```text Action Execution Task Execution Event Processing Storage Search Secret Plugin Lifecycle Agent Execution ``` 不能因为不同业务模块而各自重新实现。 --- # 199. The Contract Principle 第二条原则: > **Runtime 可以有不同实现,但必须共享稳定 Contract。** 例如: ```text Storage Runtime ├── Local Provider ├── S3 Provider ├── MinIO Provider └── Future Provider ``` 全部实现: ```text StorageProviderContract ``` --- # 200. The Provider Principle 第三条原则: > **Runtime 定义能力,Provider 定义具体基础设施实现。** 因此: ```text Storage Runtime ≠ S3 Search Runtime ≠ Elasticsearch Model Runtime ≠ OpenAI Queue Runtime ≠ Redis Event Runtime ≠ Redis ``` --- # 201. The Execution Principle 第四条原则: > **Contract 描述能力,Runtime 保证执行,Provider 提供实现。** 完整链: ```text Contract ↓ Runtime ↓ Policy ↓ Permission ↓ Provider ↓ Infrastructure ↓ Result ``` --- # 202. The Observability Principle 第五条原则: > **Runtime 执行不是黑盒。** 每次重要执行必须可以追踪: ```text Actor Request Correlation Runtime Version Action Provider Execution Task Job Result Error Cost Audit Event ``` --- # 203. The Security Principle 第六条原则: > **Runtime Contract 是安全边界的一部分。** 不能因为: ```text Plugin Agent MCP Worker CLI Internal Service ``` 就绕过: ```text Permission Scope Policy Audit ``` --- # 204. The Upgrade Principle 第七条原则: > **Contract 稳定性决定 DevOS 可升级性。** 升级: ```text Runtime Provider Plugin MCP Agent Project ``` 都应该基于: ```text Contract Version + Compatibility ``` 而不是依赖: ```text “当前代码刚好能运行” ``` --- # 205. Final Golden Rule ```text 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 之上。**