# DevOS Deployment / Environment / Configuration Runtime > Document: 13 > Status: Required > Audience: Zcode / DevOS Core Team > Purpose: 定义 DevOS 的部署、环境、配置、Secrets、Runtime Profile 与基础设施运行模型 > Depends On: > - 03_RESOURCE_ACTION_MODEL.md > - 06_MCP_SKILL_AGENT_RUNTIME.md > - 09_TASK_JOB_QUEUE_RUNTIME.md > - 12_MIGRATION_VERSIONING_COMPATIBILITY.md --- # 1. Goals DevOS 不能只定义业务 Runtime。 它必须能够回答: - DevOS 当前运行在哪个环境? - 当前是什么版本? - 当前连接哪个数据库? - Redis 在哪里? - 当前启用了哪些 Plugin? - 当前 Worker 有多少? - 当前 Agent 使用什么 Model? - 哪些配置属于公开配置? - 哪些配置属于 Secret? - Plugin 的配置如何保存? - 不同环境如何隔离? - Docker / Kubernetes / VM / Bare Metal 如何部署? - 如何启动 API? - 如何启动 Worker? - 如何执行 Migration? - 如何进行健康检查? - 如何优雅关闭? - 如何进行升级? - 如何进行回滚? - 如何发现配置错误? 因此 DevOS 必须增加: ```text Deployment Runtime Environment Runtime Configuration Runtime Secret Runtime Runtime Profile Health Runtime Bootstrap Runtime Shutdown Runtime ```` --- # 2. Architecture 整体架构: ```text DevOS │ ┌─────────────┴─────────────┐ │ │ Application Runtime Infrastructure Runtime │ │ ┌─────┼─────┐ ┌───────┼────────┐ │ │ │ │ │ │ API Worker Agent Config Secret Health │ │ │ │ │ │ └─────┴─────┘ └───────┼────────┘ │ Environment Runtime │ ┌───────────────┼───────────────┐ │ │ │ Local Staging Production │ │ │ PostgreSQL PostgreSQL PostgreSQL Redis Redis Redis Storage Storage Storage ``` DevOS Runtime 不应该直接读取: ```text process.env.XYZ ``` 业务代码也不应该直接: ```text process.env.OPENAI_API_KEY process.env.DATABASE_URL process.env.REDIS_URL ``` 所有配置必须经过: ```text Configuration Runtime ``` 统一解析。 --- # 3. Core Concepts DevOS 定义以下概念: ```text Environment Runtime Profile Configuration Secret Configuration Source Configuration Schema Configuration Snapshot Deployment Instance Service Health Check ``` 关系: ```text Environment │ ├── Configuration ├── Secrets ├── Runtime Profile ├── Deployments │ └── Instances │ ├── API ├── Worker ├── Scheduler └── Agent ``` --- # 4. Environment Environment 表示一个完整运行环境。 例如: ```text local development test staging production ``` 推荐默认: ```text local development staging production ``` Environment 是 Resource: ```text core.environment ``` --- # 5. Environment Interface ```ts export interface Environment { id: string organizationId?: string key: string name: string description?: string type: | 'local' | 'development' | 'test' | 'staging' | 'production' | 'custom' status: | 'active' | 'inactive' | 'maintenance' isProduction: boolean configVersion: number runtimeVersion: string metadata?: Record createdAt: Date updatedAt: Date } ``` --- # 6. Environment Isolation 不同 Environment 必须严格隔离。 至少隔离: ```text Database Redis Object Storage Secrets Queues Task Job Execution Logs Artifacts Plugin Configuration Agent Memory External Credentials ``` 禁止: ```text production Task ↓ staging Queue ``` 禁止: ```text production Secret ↓ development Runtime ``` 除非显式配置并通过 Policy。 --- # 7. Runtime Profile Runtime Profile 描述某个 DevOS 实例应该运行什么。 例如: ```text api worker scheduler agent all-in-one ``` 定义: ```ts export interface RuntimeProfile { id: string key: string name: string services: RuntimeService[] environment: string configOverrides?: Record metadata?: Record } ``` --- # 8. Runtime Service ```ts export type RuntimeServiceType = | 'api' | 'worker' | 'scheduler' | 'agent' | 'event-consumer' | 'mcp' | 'plugin-host' | 'migration' ``` ```ts export interface RuntimeService { id: string type: RuntimeServiceType enabled: boolean replicas?: number concurrency?: number queues?: string[] capabilities?: string[] resources?: { cpu?: string memory?: string } metadata?: Record } ``` --- # 9. Default Runtime Profiles DevOS 必须提供: ## 9.1 all-in-one 适合: ```text 个人开发 小型部署 Demo 单机服务器 ``` 运行: ```text API Worker Scheduler Agent MCP ``` --- ## 9.2 api 只运行: ```text API ``` --- ## 9.3 worker 运行: ```text Worker Task Job Queue ``` --- ## 9.4 scheduler 运行: ```text Scheduler Event Trigger Webhook Trigger ``` --- ## 9.5 agent 运行: ```text Agent Runtime Agent Scheduler Agent Execution ``` --- # 10. Configuration Runtime 配置必须统一进入: ```text ConfigurationRuntime ``` 接口: ```ts export interface ConfigurationRuntime { get( key: string, options?: ConfigurationGetOptions ): T getOrThrow( key: string, options?: ConfigurationGetOptions ): T has(key: string): boolean resolve(): Promise validate(): Promise reload(): Promise version(): number } ``` --- # 11. Configuration Sources 支持: ```text 1. Built-in Defaults 2. Configuration File 3. Environment Variables 4. Database 5. Secret Manager 6. Plugin Configuration 7. Environment Configuration 8. Runtime Overrides ``` 优先级: ```text Runtime Override ↓ Secret Manager ↓ Environment Configuration ↓ Plugin Configuration ↓ Environment Variables ↓ Configuration File ↓ Built-in Default ``` 但 Secret 不应该简单等价于普通 Configuration。 --- # 12. Configuration Schema 每个配置必须声明 Schema。 例如: ```ts export interface ConfigurationDefinition { key: string description?: string schema: unknown defaultValue?: T required?: boolean secret?: boolean readonly?: boolean reloadable?: boolean sensitive?: boolean scope: | 'system' | 'environment' | 'organization' | 'project' | 'plugin' | 'user' validator?: ( value: T ) => Promise | void } ``` 推荐: ```text Zod ``` 例如: ```ts const config = defineConfig({ key: 'redis.url', schema: z.string().url(), required: true, secret: true, scope: 'environment' }) ``` --- # 13. Configuration Namespace 配置必须使用 Namespace。 例如: ```text core.database.url core.redis.url core.http.port core.http.host core.storage.provider core.storage.bucket core.agent.defaultModel core.agent.maxIterations core.queue.defaultConcurrency core.scheduler.enabled ``` Plugin: ```text plugin.github.token plugin.github.apiUrl plugin.openai.apiKey plugin.openai.defaultModel plugin.seo.defaultTimeout ``` 禁止 Plugin 使用: ```text DATABASE_URL REDIS_URL OPENAI_KEY ``` 作为业务代码内部 API。 --- # 14. Environment Variables Environment Variables 可以作为 Configuration Source。 例如: ```text DEVOS_CORE_HTTP_PORT=3000 DEVOS_CORE_DATABASE_URL=... DEVOS_CORE_REDIS_URL=... DEVOS_PLUGIN_OPENAI_API_KEY=... ``` 映射: ```text DEVOS_CORE_HTTP_PORT ↓ core.http.port ``` 规则: ```text DEVOS_ namespace key ``` 推荐转换: ```text . → _ ``` 例如: ```text core.database.url ``` 变成: ```text DEVOS_CORE_DATABASE_URL ``` --- # 15. Secret Runtime Secret 必须独立于普通 Configuration。 定义: ```ts export interface SecretReference { id: string key: string provider: | 'database' | 'env' | 'vault' | 'external' | 'custom' version?: string metadata?: Record } ``` 代码中: ```ts const token = await secrets.get( 'plugin.github.token' ) ``` 禁止: ```ts console.log(token) ``` --- # 16. Secret Storage DevOS 最少支持: ```text env database-encrypted external ``` 未来支持: ```text HashiCorp Vault AWS Secrets Manager GCP Secret Manager Azure Key Vault Kubernetes Secrets ``` 但是: ```text SecretProvider ``` 必须抽象。 ```ts export interface SecretProvider { get( key: string, context: SecretContext ): Promise set( key: string, value: string, context: SecretContext ): Promise delete( key: string, context: SecretContext ): Promise exists( key: string, context: SecretContext ): Promise } ``` --- # 17. Secret Encryption 如果使用 Database 保存 Secret: 必须: ```text Encryption at Rest ``` 禁止明文保存: ```text apiKey password accessToken refreshToken privateKey webhookSecret cookie sessionSecret ``` 数据库保存: ```text ciphertext keyVersion algorithm createdAt updatedAt ``` --- # 18. Secret Redaction 日志系统必须自动隐藏: ```text API Key Token Password Cookie Authorization Private Key Secret ``` 例如: ```text Authorization: Bearer sk-xxxx ``` 必须变成: ```text Authorization: Bearer [REDACTED] ``` --- # 19. Configuration Snapshot 每次 Runtime 启动都生成: ```ts export interface ConfigurationSnapshot { id: string environmentId: string version: number values: Record secretKeys: string[] checksum: string createdAt: Date } ``` 注意: ```text Snapshot 中不能保存 Secret 明文。 ``` 只保存: ```text secretKeys secret references ``` --- # 20. Runtime Reproducibility 每一个: ```text Task Job Execution AgentRun ``` 都应该记录: ```text environmentId configVersion runtimeVersion plugin versions ``` 这样可以回答: > 为什么这个任务昨天成功,今天失败? 可以定位: ```text Runtime Version + Configuration Version + Plugin Version + Action Version + Model Version ``` --- # 21. Configuration Versioning 配置必须有版本。 ```ts export interface ConfigurationVersion { version: number environmentId: string checksum: string createdBy: string createdAt: Date changes: ConfigurationChange[] } ``` ```ts export interface ConfigurationChange { key: string oldValue?: unknown newValue?: unknown changedBy: string reason?: string } ``` Secret 的值不能出现在: ```text oldValue newValue logs audit message ``` 只能: ```text changed: true ``` --- # 22. Configuration Change Flow 配置修改: ```text User ↓ Configuration UI ↓ Configuration Action ↓ Authorization ↓ Validation ↓ Configuration Runtime ↓ New Configuration Version ↓ Audit Event ↓ Reload / Restart ``` 不能: ```text UI ↓ 直接修改 DB ``` --- # 23. Configuration Actions Configuration 是 Resource。 ```text core.configuration ``` Actions: ```text core.configuration.get core.configuration.list core.configuration.set core.configuration.update core.configuration.validate core.configuration.reload core.configuration.rollback core.configuration.diff ``` Secret: ```text core.secret.list core.secret.getMetadata core.secret.set core.secret.rotate core.secret.delete ``` 注意: ```text core.secret.get ``` 默认禁止。 UI 也不应该直接展示 Secret 原文。 --- # 24. Plugin Configuration Plugin Manifest 可以声明: ```ts export interface PluginConfigDefinition { key: string schema: unknown defaultValue?: unknown required?: boolean secret?: boolean reloadable?: boolean } ``` 例如: ```ts const plugin: PluginManifest = { id: 'github', config: [ { key: 'apiUrl', schema: z.string().url(), defaultValue: 'https://api.github.com' }, { key: 'token', schema: z.string(), required: true, secret: true } ] } ``` 安装 Plugin 后: ```text Plugin ↓ Manifest ↓ Configuration Registry ↓ Configuration UI ``` 自动出现: ```text Settings └── Plugins └── GitHub ├── General ├── Credentials └── Advanced ``` --- # 25. Dynamic Configuration UI Configuration Schema 应该能够驱动 UI。 例如: ```ts { key: 'core.agent.maxIterations', type: 'number', min: 1, max: 100 } ``` UI 自动生成: ```text Max Iterations [ 20 ] ``` Secret: ```text OpenAI API Key [ ************** ] ``` Boolean: ```text Enable Scheduler [ ON ] ``` Enum: ```text Default Model [ GPT ... ▼ ] ``` --- # 26. Configuration Field Metadata 支持: ```ts interface ConfigurationUI { label?: string description?: string group?: string order?: number component?: | 'text' | 'password' | 'number' | 'boolean' | 'select' | 'textarea' | 'json' | 'code' hidden?: boolean advanced?: boolean } ``` --- # 27. Health Runtime DevOS 必须提供统一 Health Runtime。 ```ts export interface HealthCheck { id: string name: string type: | 'liveness' | 'readiness' | 'startup' | 'dependency' check( context: HealthContext ): Promise } ``` --- # 28. Health Result ```ts export interface HealthResult { status: | 'healthy' | 'degraded' | 'unhealthy' latencyMs?: number message?: string details?: Record } ``` --- # 29. Health Checks 至少检查: ```text Application Database Redis Queue Storage Plugin Runtime MCP Runtime Agent Runtime Worker Scheduler Configuration Migration ``` 例如: ```text GET /health ``` 返回: ```json { "status": "healthy" } ``` --- # 30. Liveness Liveness 只回答: > 进程是否还活着? 不能依赖: ```text Database Redis External API ``` 例如: ```text GET /health/live ``` --- # 31. Readiness Readiness 回答: > 当前实例是否可以接受请求? 检查: ```text Database Redis Configuration Migration Required Plugins ``` 例如: ```text GET /health/ready ``` --- # 32. Startup Startup 检查: ```text Configuration loaded Database connected Migration completed Required services initialized Plugin registry initialized ``` --- # 33. Dependency Health 每一个 Plugin 可以注册: ```ts plugin.health.register(...) ``` 例如: ```text GitHub API: healthy OpenAI API: healthy Cloudflare API: degraded ``` 但是: ```text Plugin API unhealthy ``` 不应该直接导致: ```text DevOS Core unhealthy ``` 除非 Plugin 被标记: ```text required: true ``` --- # 34. Bootstrap Runtime DevOS 启动必须经过统一 Bootstrap。 ```text Process Start ↓ Load Environment ↓ Load Configuration ↓ Validate Configuration ↓ Initialize Logger ↓ Initialize Database ↓ Check Migration ↓ Initialize Redis ↓ Initialize Event Bus ↓ Initialize Resource Registry ↓ Initialize Action Registry ↓ Initialize Plugin Runtime ↓ Initialize MCP Runtime ↓ Initialize Skill Registry ↓ Initialize Agent Runtime ↓ Initialize Task Runtime ↓ Initialize Scheduler ↓ Register Health Checks ↓ Ready ``` --- # 35. Bootstrap Phase 定义: ```ts export type BootstrapPhase = | 'config' | 'logging' | 'database' | 'migration' | 'redis' | 'events' | 'resources' | 'actions' | 'plugins' | 'mcp' | 'skills' | 'agents' | 'tasks' | 'scheduler' | 'health' | 'ready' ``` --- # 36. Bootstrap Module ```ts export interface BootstrapModule { id: string phase: BootstrapPhase priority?: number dependsOn?: string[] initialize( context: BootstrapContext ): Promise shutdown?( context: ShutdownContext ): Promise } ``` --- # 37. Plugin Bootstrap Plugin 必须支持: ```ts export interface PluginRuntime { initialize(): Promise activate(): Promise deactivate(): Promise health(): Promise } ``` 生命周期: ```text installed ↓ configured ↓ initializing ↓ active ↓ deactivating ↓ inactive ``` 异常: ```text failed ``` --- # 38. Graceful Shutdown DevOS 不能直接: ```text process.exit() ``` 正常关闭: ```text SIGTERM ↓ Mark Instance Draining ↓ Stop Accepting New Requests ↓ Stop Scheduler ↓ Stop Creating New Jobs ↓ Worker Drain ↓ Wait Running Jobs ↓ Close MCP Connections ↓ Close Plugin Runtime ↓ Close Redis ↓ Close Database ↓ Flush Logs ↓ Exit ``` --- # 39. Worker Drain Worker 收到 shutdown: ```text busy jobs ``` 继续执行。 新 Job: ```text 不再领取 ``` 最终: ```text busy = 0 ``` 才退出。 如果超过: ```text shutdownTimeout ``` 进入: ```text forced shutdown ``` --- # 40. Runtime Instance DevOS 运行实例: ```ts export interface RuntimeInstance { id: string environmentId: string serviceType: RuntimeServiceType hostname?: string version: string status: | 'starting' | 'ready' | 'draining' | 'stopped' | 'unhealthy' startedAt: Date lastHeartbeatAt?: Date metadata?: Record } ``` --- # 41. Instance Heartbeat API / Worker / Scheduler 都必须发送: ```text heartbeat ``` 例如: ```text runtime.instance.heartbeat ``` 用于: ```text Instance Discovery Worker Discovery Health Monitoring Auto Recovery ``` --- # 42. Deployment Deployment 表示一次部署行为。 ```ts export interface Deployment { id: string environmentId: string version: string status: | 'pending' | 'deploying' | 'healthy' | 'failed' | 'rolled_back' configVersion: number startedAt?: Date completedAt?: Date error?: unknown metadata?: Record } ``` Deployment 是 Resource: ```text core.deployment ``` --- # 43. Deployment Actions ```text core.deployment.create core.deployment.start core.deployment.stop core.deployment.restart core.deployment.rollback core.deployment.health core.deployment.scale ``` --- # 44. Deployment Must Use Task Runtime 部署不是: ```text Controller ↓ shell exec ``` 必须: ```text Deployment Action ↓ Task ↓ Jobs ↓ Worker ↓ Deployment Actions ``` 例如: ```text deploy ├── validate config ├── database migration ├── deploy api ├── deploy worker ├── health check └── finalize ``` --- # 45. Deployment State Machine ```text pending ↓ validating ↓ deploying ↓ migrating ↓ starting ↓ health_check ↓ healthy ``` 失败: ```text deploying ↓ failed ↓ rollback ↓ rolled_back ``` --- # 46. Docker Support DevOS 必须提供官方 Docker 部署方式。 至少: ```text devos-api devos-worker devos-scheduler devos-agent ``` 以及: ```text postgres redis ``` 开发环境可以: ```text docker compose up ``` --- # 47. Docker Compose 推荐结构: ```text deploy/ └── docker/ ├── docker-compose.yml ├── docker-compose.dev.yml ├── docker-compose.prod.yml ├── .env.example └── README.md ``` --- # 48. Production Architecture 生产环境推荐: ```text Load Balancer │ ┌────────┴────────┐ │ │ API 1 API 2 │ │ └────────┬────────┘ │ PostgreSQL │ Redis │ ┌────────────┼────────────┐ │ │ │ Worker 1 Worker 2 Worker N │ │ │ └────────────┼────────────┘ │ Scheduler │ Agent ``` --- # 49. Kubernetes Kubernetes 不是 DevOS Core 的必选依赖。 必须提供: ```text Deployment Service ConfigMap Secret Job CronJob ``` 对应模板。 目录: ```text deploy/ └── kubernetes/ ├── namespace.yaml ├── api.yaml ├── worker.yaml ├── scheduler.yaml ├── agent.yaml ├── configmap.yaml ├── secret.example.yaml └── kustomization.yaml ``` --- # 50. Kubernetes Runtime Worker: ```text Deployment ``` Scheduler: ```text Deployment replicas = 1 ``` Migration: ```text Job ``` 不要让: ```text 每个 API Pod ``` 同时执行 Migration。 --- # 51. Migration Lock 结合: ```text 12_MIGRATION_VERSIONING_COMPATIBILITY.md ``` Migration 必须有: ```text distributed lock ``` 确保: ```text API 1 API 2 Worker 1 Worker 2 ``` 不会同时执行 migration。 --- # 52. Storage Runtime DevOS 需要统一 Storage API。 ```ts export interface StorageProvider { put( key: string, data: Buffer | Uint8Array | NodeJS.ReadableStream, options?: StoragePutOptions ): Promise get( key: string ): Promise delete( key: string ): Promise exists( key: string ): Promise getSignedUrl?( key: string, options?: SignedUrlOptions ): Promise } ``` 支持: ```text local filesystem S3 MinIO Cloudflare R2 ``` --- # 53. Artifact Runtime Task / Job / Agent / Plugin 产生的文件不能直接散落: ```text /tmp ``` 必须进入: ```text Artifact Runtime ``` 例如: ```text core.artifact ``` ```ts export interface Artifact { id: string taskId?: string jobId?: string executionId?: string name: string mimeType: string size: number storageKey: string checksum?: string createdAt: Date } ``` --- # 54. Temporary Files 允许: ```text /tmp/devos/* ``` 但: ```text 临时文件 ≠ Artifact ``` Task 完成后: ```text cleanup ``` Artifact 必须持久化。 --- # 55. Runtime Paths 统一: ```text DEVOS_DATA_DIR DEVOS_CACHE_DIR DEVOS_TEMP_DIR DEVOS_LOG_DIR DEVOS_ARTIFACT_DIR ``` 例如: ```text /data/devos /data/devos/cache /data/devos/tmp /data/devos/logs /data/devos/artifacts ``` 业务代码禁止自行: ```ts '/tmp/foo' ``` 必须: ```ts runtime.paths.temp(...) ``` --- # 56. Runtime Paths API ```ts export interface RuntimePaths { data(): string cache(): string temp(): string logs(): string artifacts(): string plugin(id: string): string } ``` --- # 57. External Service Runtime 所有外部服务必须通过 Provider。 例如: ```text EmailProvider StorageProvider ModelProvider BrowserProvider DNSProvider CloudProvider GitProvider SearchProvider ``` 不要: ```text Action ↓ 直接 fetch("https://api.xxx.com") ``` 应该: ```text Action ↓ Provider ↓ External API ``` --- # 58. Provider Registry ```ts export interface ProviderRegistry { register( type: string, id: string, provider: T ): void get( type: string, id?: string ): T list( type: string ): ProviderInfo[] } ``` 例如: ```text model.openai model.anthropic storage.s3 storage.minio email.smtp git.github git.gitlab ``` --- # 59. External Credentials Provider Credentials 必须进入: ```text Secret Runtime ``` 例如: ```text provider.github.token provider.cloudflare.apiToken provider.openai.apiKey ``` 而不是: ```text plugin.github.githubToken ``` 如果 Credential 属于 Plugin,则 Plugin 可以拥有: ```text plugin.github.credentials ``` 但底层仍然使用: ```text Secret Runtime ``` --- # 60. Runtime Capability Discovery Runtime 必须能够告诉 Agent: ```text 当前环境有哪些能力? ``` 例如: ```text PostgreSQL available Redis available GitHub available OpenAI available Browser available Storage available ``` 但: ```text secret value ``` 绝对不能进入 Capability Discovery。 --- # 61. Configuration Policy 配置必须支持 Policy。 例如: ```ts export interface ConfigurationPolicy { key: string writableBy: | 'system' | 'admin' | 'owner' productionEditable: boolean requiresApproval?: boolean immutable?: boolean } ``` 例如: ```text production.database.url ``` 可以: ```text immutable = true ``` 或者: ```text requiresApproval = true ``` --- # 62. Production Safety Production 环境默认: ```text dangerous configuration ``` 必须更加严格。 例如: ```text Database URL Storage Bucket Queue Prefix Encryption Key Authentication Secret ``` 不能普通管理员随意修改。 --- # 63. Configuration Rollback 配置必须支持: ```text Version 1 Version 2 Version 3 ``` 可以: ```text rollback Version 2 ``` 流程: ```text User ↓ configuration.rollback ↓ Authorization ↓ Compatibility Check ↓ Diff ↓ Approval ↓ Create Version 4 ↓ Apply ↓ Health Check ``` 注意: ```text Rollback 不删除 Version 3。 ``` 而是创建: ```text Version 4 ``` 内容等于: ```text Version 2 ``` 这样审计历史完整。 --- # 64. Dynamic Reload 配置定义: ```text reloadable: true ``` 才允许热更新。 例如: ```text log.level agent.defaultModel worker.concurrency ``` 不适合热更新: ```text database.url encryption.masterKey runtime.port ``` 修改这些配置: ```text restart required ``` --- # 65. Reload Flow ```text Configuration Update ↓ Validate ↓ Create Version ↓ Apply ↓ Notify Config Event ↓ Runtime Modules ↓ reload() ``` Event: ```text core.configuration.changed ``` --- # 66. Configuration Event ```ts interface ConfigurationChangedEvent { environmentId: string version: number changedKeys: string[] reloadableKeys: string[] restartRequiredKeys: string[] actorId: string timestamp: Date } ``` 禁止事件包含: ```text secret value ``` --- # 67. Configuration Cache Configuration Runtime 可以缓存: ```text Resolved Configuration ``` 但是 Secret: ```text 短生命周期缓存 ``` 并且: ```text never log never serialize to event ``` --- # 68. Environment Context 所有 ActionContext 必须能够获取: ```ts interface EnvironmentContext { environmentId: string environmentType: string isProduction: boolean configVersion: number runtimeVersion: string } ``` Action: ```ts ctx.environment ``` --- # 69. Production Action Policy 结合: ```text 03_RESOURCE_ACTION_MODEL.md ``` Action 可以声明: ```ts interface ActionDefinition { // existing fields... environments?: { allow?: string[] deny?: string[] } production?: { allowed: boolean requiresApproval?: boolean } } ``` 例如: ```text server.delete ``` 默认: ```text production.allowed = false ``` --- # 70. Deployment + Agent Agent 可以提出: ```text 部署新版本 ``` 但不能绕过: ```text Deployment Action Approval Policy Task Runtime ``` 流程: ```text Agent Goal ↓ Skill ↓ Deployment Capability ↓ Plan ↓ Approval ↓ Task ↓ Jobs ↓ Deployment Action ↓ Health Check ``` --- # 71. Agent Production Guard Agent 在 production 执行: ```text deployment database migration server delete DNS change credential rotation ``` 必须根据 Policy: ```text allow deny approval_required ``` Agent 不能自行改变 Policy。 --- # 72. CLI 增加: ```bash devos env list devos env get production devos config list devos config get core.agent.defaultModel devos config set core.agent.defaultModel xxx devos config validate devos config diff devos config rollback devos secret list devos secret set devos secret rotate devos health devos health live devos health ready devos runtime status devos runtime instances devos deployment list devos deployment deploy devos deployment rollback ``` Secret CLI 默认: ```text 不打印 Secret value ``` --- # 73. API Environment: ```text GET /api/environments GET /api/environments/:id POST /api/environments PATCH /api/environments/:id DELETE /api/environments/:id ``` Configuration: ```text GET /api/config GET /api/config/:key PATCH /api/config/:key POST /api/config/validate POST /api/config/reload GET /api/config/versions GET /api/config/diff POST /api/config/rollback ``` Health: ```text GET /health GET /health/live GET /health/ready GET /health/startup ``` Runtime: ```text GET /api/runtime GET /api/runtime/instances GET /api/runtime/instances/:id ``` Deployment: ```text GET /api/deployments POST /api/deployments GET /api/deployments/:id POST /api/deployments/:id/start POST /api/deployments/:id/rollback ``` --- # 74. UI DevOS Settings 增加: ```text Settings ├── General ├── Environment ├── Configuration ├── Secrets ├── Runtime ├── Providers ├── Storage ├── Health └── Deployments ``` Environment: ```text Development Staging Production ``` 点击进入: ```text Overview Configuration Secrets Services Instances Health Deployments Activity ``` --- # 75. Configuration UI 页面: ```text Configuration ``` 支持: ```text Search Filter Namespace Environment Modified Secret Restart Required ``` 字段: ```text Key Value Source Version Last Modified Status ``` Secret: ```text ******** ``` 绝不能默认显示: ```text plaintext ``` --- # 76. Runtime Dashboard 显示: ```text API Worker Scheduler Agent MCP ``` 例如: ```text API ● Healthy Version: 1.4.2 Uptime: 4d 12h Worker ● Healthy Workers: 8 Running Jobs: 21 Scheduler ● Healthy Schedules: 42 Agent ● Healthy Running: 3 ``` --- # 77. Health Dashboard 显示: ```text Core Database Redis Storage Queue Workers Scheduler Plugins MCP Agent ``` 状态: ```text Healthy Degraded Unhealthy ``` 支持点击进入详细信息。 --- # 78. Deployment Dashboard 显示: ```text Current Version Previous Version Config Version Plugin Versions Deployment Status Health ``` Timeline: ```text 22:01 Validate 22:02 Migration 22:03 API started 22:04 Worker started 22:04 Health check 22:05 Healthy ``` --- # 79. Database Model 至少增加: ```text environments runtime_profiles runtime_instances configuration_definitions configuration_values configuration_versions configuration_changes secret_references deployments health_checks health_results ``` 建议: ```text configuration_values ``` 不要直接保存所有 Secret。 --- # 80. Configuration Value Model ```ts interface ConfigurationValue { id: string environmentId: string key: string value?: unknown secretRefId?: string source: | 'default' | 'file' | 'env' | 'database' | 'secret' | 'runtime' version: number createdAt: Date updatedAt: Date } ``` --- # 81. Multi-Tenant Isolation 如果 DevOS 支持 Organization: ```text System Configuration Organization Configuration Project Configuration User Configuration ``` 优先级: ```text User ↓ Project ↓ Organization ↓ Environment ↓ System ↓ Default ``` 但: ```text Security Configuration Encryption Configuration Database Configuration ``` 不能被普通 Project/User 覆盖。 --- # 82. Configuration Resolution 最终: ```ts resolve( key, context ) ``` 例如: ```ts config.get( 'agent.defaultModel', { organizationId, projectId, environmentId } ) ``` 解析: ```text User ↓ Project ↓ Organization ↓ Environment ↓ System ↓ Default ``` 返回最终值。 --- # 83. Configuration Explain 必须提供: ```text config.explain(key) ``` 例如: ```text agent.defaultModel Resolved Value: gpt-x Source: organization Environment: production Version: 42 Overrides: system = xxx environment = xxx organization = gpt-x ``` Secret: ```text Value: [REDACTED] ``` --- # 84. Why Configuration Explain Is Important 当用户问: > 为什么生产环境使用了这个 Model? DevOS 必须可以回答: ```text Value Source Version Environment Override Changed By Changed At ``` 而不是: ```text 不知道 ``` --- # 85. Local Development 提供: ```bash devos dev ``` 自动: ```text start postgres start redis start api start worker start scheduler ``` 或者: ```bash devos dev api devos dev worker ``` --- # 86. Bootstrap CLI 提供: ```bash devos init ``` 完成: ```text create config create .env check dependencies initialize database run migration create default admin create default environment ``` --- # 87. Environment Initialization 首次启动: ```text No Environment ↓ Create local ↓ Generate Runtime Config ↓ Initialize Database ↓ Install Core Plugins ↓ Create Default Organization ↓ Ready ``` 生产环境禁止自动创建: ```text random admin password ``` 必须显式初始化。 --- # 88. Docker Environment `.env.example`: ```text DEVOS_ENV=development DEVOS_CORE_HTTP_HOST=0.0.0.0 DEVOS_CORE_HTTP_PORT=3000 DEVOS_CORE_DATABASE_URL= DEVOS_CORE_REDIS_URL= DEVOS_CORE_STORAGE_PROVIDER=local DEVOS_CORE_STORAGE_PATH=/data/devos DEVOS_CORE_LOG_LEVEL=info ``` 不要提交: ```text .env .env.production secret files private keys ``` --- # 89. Security Rules 必须禁止: ```text Secret in Git Secret in logs Secret in Task input Secret in Agent memory Secret in Event payload Secret in Audit payload Secret in Error message Secret in telemetry ``` 如果 Action Input 包含 Secret: 必须进行: ```text redaction ``` --- # 90. Agent Memory Security Agent Memory 不允许保存: ```text API keys passwords tokens cookies private keys session credentials ``` 即使 Agent: ```text 观察到 ``` 也必须: ```text redact before persistence ``` --- # 91. Error Sanitization External API 返回: ```text authorization token ``` 不能直接: ```ts throw new Error(response.text) ``` 必须: ```ts sanitizeExternalError() ``` --- # 92. Configuration Validation 启动时: ```text Configuration ↓ Schema Validation ↓ Cross-field Validation ↓ Dependency Validation ``` 例如: ```text storage.provider = s3 ``` 则必须: ```text s3.endpoint s3.bucket s3.region credentials ``` 全部满足。 --- # 93. Configuration Dependency 配置定义支持: ```ts dependsOn?: string[] ``` 以及: ```ts validate?: ( config: ResolvedConfiguration ) => Promise ``` --- # 94. Fail Fast 以下配置错误: ```text Database URL missing Encryption key invalid Redis URL invalid Required Plugin configuration missing ``` Production: ```text 启动失败 ``` 不能: ```text 启动后部分功能坏掉 ``` 除非明确标记: ```text optional ``` --- # 95. Optional Dependencies Plugin 可以定义: ```ts dependencies: { required: [], optional: [] } ``` 例如: ```text SEO Plugin required: database optional: browser github ``` 没有 Browser: ```text SEO Plugin 仍然可以启动 ``` 但: ```text browser-dependent capabilities ``` 标记: ```text unavailable ``` --- # 96. Capability Availability Capability Registry 必须知道: ```ts interface CapabilityAvailability { available: boolean reason?: string requiredConfiguration?: string[] requiredProvider?: string[] health?: HealthResult } ``` 这样 Agent 不会尝试: ```text 调用不可用 Capability ``` --- # 97. Runtime Dependency Graph DevOS 启动前可以构建: ```text API ├── Config ├── Database ├── Resource ├── Action └── Plugin Worker ├── Config ├── Redis ├── Queue └── Action Agent ├── Model Provider ├── Capability Registry └── Task Runtime ``` 如果依赖不可用: ```text Runtime Profile ``` 应报告明确原因。 --- # 98. Observability Runtime 必须输出: ```text Logs Metrics Traces Health Audit Events ``` 每一个 Instance: ```text instanceId environmentId runtimeVersion ``` 都应该进入 Observability Context。 --- # 99. Metrics 至少: ```text devos_runtime_instances devos_config_reload_total devos_config_validation_failures_total devos_health_check_total devos_deployment_total devos_deployment_duration devos_worker_active devos_worker_capacity devos_queue_depth ``` --- # 100. Events 至少: ```text core.environment.created core.environment.updated core.configuration.changed core.configuration.reloaded core.configuration.rollback core.secret.created core.secret.rotated core.secret.deleted core.runtime.started core.runtime.ready core.runtime.draining core.runtime.stopped core.deployment.started core.deployment.completed core.deployment.failed core.deployment.rollback core.health.degraded core.health.recovered ``` --- # 101. Audit 所有: ```text Configuration Change Secret Change Environment Change Deployment Rollback Runtime Control ``` 都必须 Audit。 例如: ```text User ↓ configuration.set ↓ key=agent.defaultModel ↓ environment=production ↓ version=42 ``` Secret: ```text key=provider.openai.apiKey changed=true ``` 而不是: ```text newValue=sk-xxxx ``` --- # 102. Resource Registry Integration 新增: ```text core.environment core.configuration core.configurationVersion core.secret core.runtimeInstance core.deployment core.artifact ``` 全部注册到: ```text Resource Registry ``` --- # 103. Action Runtime Integration 所有操作: ```text Environment Configuration Secret Runtime Deployment Artifact ``` 必须: ```text Action Runtime ``` 执行。 禁止: ```text Controller → Prisma UI → API → Prisma Plugin → Prisma Agent → Prisma ``` --- # 104. Task Runtime Integration 长任务: ```text Deployment Configuration Migration Artifact Cleanup Environment Provision ``` 必须: ```text Task → Job → Worker ``` 例如: ```text Deployment Task ├── validate ├── migrate ├── restart ├── health check └── finalize ``` --- # 105. Plugin Integration Plugin 可以声明: ```ts interface PluginManifest { // existing... configuration?: ConfigurationDefinition[] secrets?: SecretDefinition[] providers?: ProviderDefinition[] healthChecks?: HealthCheckDefinition[] runtimeServices?: RuntimeService[] deploymentHooks?: DeploymentHook[] } ``` 这样 Plugin 能真正成为: ```text 可安装 Runtime Extension ``` --- # 106. Plugin UI Plugin 可以注册: ```text Settings Dashboard Health Configuration Credentials Runtime ``` 例如: ```text Plugins └── GitHub ├── Overview ├── Configuration ├── Credentials ├── Health └── Usage ``` --- # 107. MCP Integration MCP Server 的配置: ```text mcp.github.endpoint mcp.github.auth mcp.github.timeout ``` 必须通过: ```text Configuration Runtime Secret Runtime ``` MCP Runtime 不允许自行: ```text process.env ``` 获取业务 Secret。 --- # 108. MCP Health 每个 MCP Server: ```text connected degraded disconnected error ``` Agent Capability Discovery 必须过滤: ```text disconnected ``` 的 MCP Capability。 --- # 109. Agent Model Provider Agent 使用: ```text ModelProvider ``` 配置: ```text agent.defaultModel agent.fallbackModel agent.maxTokens agent.temperature ``` Credential: ```text provider.openai.apiKey ``` 进入: ```text Secret Runtime ``` --- # 110. Environment-Specific Model Policy 例如: ```text development cheap model staging standard model production production model ``` Agent Runtime: ```ts modelProvider.resolve({ environmentId, agentProfileId }) ``` --- # 111. Production Freeze 支持: ```text Environment Freeze ``` 例如: ```text production ``` 进入: ```text frozen ``` 期间禁止: ```text configuration change plugin upgrade deployment migration ``` 除非: ```text override + approval ``` --- # 112. Environment Maintenance Environment 支持: ```text active maintenance inactive ``` Maintenance: ```text API ↓ 正常读取 ``` 但是: ```text 新 Deployment 新 Agent Run 危险 Action ``` 默认禁止。 --- # 113. Environment Actions ```text core.environment.create core.environment.update core.environment.activate core.environment.deactivate core.environment.maintenance core.environment.freeze core.environment.unfreeze ``` --- # 114. Production Approval 结合 Agent / Action / Deployment: ```text Dangerous Action ↓ Policy ↓ requiresApproval ↓ Approval Resource ↓ Human Approval ↓ Task ``` 禁止: ```text Agent ↓ production deployment ``` 直接成功。 --- # 115. Disaster Recovery DevOS 必须定义: ```text Database Backup Configuration Backup Secret Backup Artifact Backup Plugin Lock ``` 至少能够恢复: ```text Database + Configuration Version + Plugin Versions + Runtime Version ``` --- # 116. Backup Resource ```text core.backup ``` ```ts interface Backup { id: string environmentId: string type: | 'database' | 'configuration' | 'artifact' | 'full' status: | 'pending' | 'running' | 'completed' | 'failed' storageKey: string checksum?: string createdAt: Date } ``` --- # 117. Backup Policy 支持: ```text daily weekly monthly before deployment before migration ``` 生产环境: ```text deployment ↓ backup ↓ migration ``` --- # 118. Recovery Recovery 必须使用 Task Runtime: ```text Recovery Task ├── validate backup ├── restore database ├── restore configuration ├── restore artifacts ├── restore plugin versions ├── health check └── finalize ``` --- # 119. Filesystem Boundary 禁止业务代码直接操作: ```text fs.writeFile('/etc/...') ``` 必须使用: ```text RuntimePaths StorageRuntime ArtifactRuntime ``` 只有明确标记的 Infrastructure Action 可以操作系统资源。 --- # 120. Shell Boundary DevOS Core 禁止业务代码随意: ```ts exec() spawn() ``` 需要系统命令时: ```text CommandRuntime ``` 统一执行。 ```ts interface CommandRuntime { execute( command: string, args: string[], options?: CommandOptions ): Promise } ``` 必须: ```text allowlist timeout cwd environment isolation stdout limit stderr limit audit ``` --- # 121. Command Security 禁止: ```text shell=true ``` 作为默认行为。 参数必须: ```text argv array ``` 例如: ```ts execute( 'git', ['clone', url, target] ) ``` 而不是: ```ts execute(`git clone ${url} ${target}`) ``` --- # 122. Container Runtime 未来支持: ```text Docker Podman Kubernetes ``` 抽象: ```ts interface ContainerRuntime { create(...) start(...) stop(...) restart(...) remove(...) logs(...) inspect(...) } ``` Plugin 可以使用: ```text container provider ``` 但不能绕过: ```text Policy Audit Task Runtime ``` --- # 123. Infrastructure Provider 统一: ```text InfrastructureProvider ``` 未来: ```text AWS Cloudflare DigitalOcean Hetzner GCP Azure Kubernetes Docker SSH ``` 例如: ```ts interface ServerProvider { listServers(): Promise createServer(input): Promise deleteServer(id): Promise rebootServer(id): Promise } ``` 这些能力最终应该成为: ```text Plugin Capability ``` 而不是 DevOS Core 硬编码。 --- # 124. Core vs Plugin Boundary DevOS Core 负责: ```text Configuration Environment Secret Runtime Health Deployment abstraction Storage abstraction Provider abstraction ``` 具体服务: ```text AWS Cloudflare GitHub GitLab OpenAI Browser SSH Docker ``` 应该: ```text Plugin ``` 提供。 --- # 125. Project Configuration 未来支持 Project: ```text Organization ├── Project A │ └── Environment │ ├── dev │ ├── staging │ └── production │ └── Project B ``` Configuration Scope: ```text system organization project environment user ``` --- # 126. Configuration Context 统一: ```ts interface ConfigurationContext { environmentId?: string organizationId?: string projectId?: string userId?: string } ``` --- # 127. Runtime Context 统一: ```ts interface RuntimeContext { runtimeInstanceId: string environmentId: string serviceType: RuntimeServiceType runtimeVersion: string configVersion: number shutdownSignal: AbortSignal } ``` --- # 128. Package Structure Zcode 必须增加: ```text packages/ ├── config/ ├── secret/ ├── environment/ ├── runtime/ ├── health/ ├── deployment/ ├── storage/ ├── artifact/ ├── provider/ └── command/ ``` 建议: ```text packages/runtime/ ├── bootstrap/ ├── shutdown/ ├── instance/ ├── profile/ ├── paths/ └── context/ ``` --- # 129. Config Package ```text packages/config/ ├── config-runtime.ts ├── config-registry.ts ├── config-resolver.ts ├── config-validator.ts ├── config-schema.ts ├── config-version.ts ├── config-store.ts ├── config-source.ts ├── config-redactor.ts └── index.ts ``` --- # 130. Secret Package ```text packages/secret/ ├── secret-runtime.ts ├── secret-provider.ts ├── secret-store.ts ├── secret-encryption.ts ├── secret-redactor.ts ├── secret-context.ts └── index.ts ``` --- # 131. Environment Package ```text packages/environment/ ├── environment-resource.ts ├── environment-service.ts ├── environment-policy.ts ├── environment-context.ts └── index.ts ``` --- # 132. Health Package ```text packages/health/ ├── health-runtime.ts ├── health-check.ts ├── health-registry.ts ├── health-result.ts └── index.ts ``` --- # 133. Deployment Package ```text packages/deployment/ ├── deployment-resource.ts ├── deployment-service.ts ├── deployment-runner.ts ├── deployment-policy.ts ├── deployment-plan.ts └── index.ts ``` --- # 134. Provider Package ```text packages/provider/ ├── provider-registry.ts ├── provider-runtime.ts ├── model/ ├── storage/ ├── email/ ├── git/ ├── cloud/ ├── browser/ └── index.ts ``` --- # 135. Command Package ```text packages/command/ ├── command-runtime.ts ├── command-policy.ts ├── command-parser.ts ├── command-result.ts └── index.ts ``` --- # 136. Testing 必须增加: ```text unit tests integration tests runtime tests deployment tests security tests configuration tests ``` --- # 137. Configuration Tests 必须测试: ```text default resolution environment resolution organization override project override user override schema validation required config optional config secret config config version config diff config rollback reloadable config restart-required config ``` --- # 138. Secret Tests 必须测试: ```text encryption decryption rotation redaction access policy audit no plaintext logs no plaintext events no plaintext Agent memory ``` --- # 139. Environment Tests 测试: ```text environment isolation production policy maintenance mode freeze activate deactivate ``` --- # 140. Runtime Tests 测试: ```text bootstrap order dependency resolution health readiness shutdown worker drain heartbeat instance registration ``` --- # 141. Deployment Tests 测试: ```text deployment plan migration health check failure rollback backup configuration version plugin version runtime version ``` --- # 142. Security Tests 必须专门测试: ```text Agent cannot access secret Plugin cannot access unrelated secret User cannot access production config Project cannot override system security config MCP cannot bypass policy Action cannot bypass environment policy ``` --- # 143. Acceptance Criteria 完成本 Document 后必须满足: ## Environment ```text [ ] Environment Resource [ ] Environment isolation [ ] Environment policy [ ] Maintenance [ ] Freeze ``` ## Configuration ```text [ ] Configuration Registry [ ] Configuration Runtime [ ] Configuration Schema [ ] Configuration Resolution [ ] Configuration Version [ ] Configuration Diff [ ] Configuration Rollback [ ] Configuration Explain [ ] Configuration Reload ``` ## Secret ```text [ ] Secret Runtime [ ] Secret Provider [ ] Encryption [ ] Rotation [ ] Redaction [ ] Audit ``` ## Runtime ```text [ ] Bootstrap [ ] Shutdown [ ] Runtime Profile [ ] Runtime Instance [ ] Heartbeat [ ] Health [ ] Liveness [ ] Readiness ``` ## Deployment ```text [ ] Deployment Resource [ ] Deployment Task [ ] Deployment Job [ ] Migration [ ] Health Check [ ] Rollback [ ] Backup ``` ## Infrastructure ```text [ ] Storage Runtime [ ] Artifact Runtime [ ] Provider Registry [ ] Command Runtime [ ] Container Runtime abstraction ``` ## Integration ```text [ ] Action Runtime [ ] Task Runtime [ ] Agent Runtime [ ] Plugin Runtime [ ] MCP Runtime [ ] Capability Registry [ ] Audit [ ] Event [ ] Observability ``` --- # 144. Zcode Implementation Rules ## Rule 1 禁止业务代码直接读取: ```text process.env ``` 必须: ```text ConfigurationRuntime ``` --- ## Rule 2 禁止业务代码直接读取 Secret。 必须: ```text SecretRuntime ``` --- ## Rule 3 禁止 Secret 出现在: ```text Log Event Audit Task Input Agent Memory Error Metric Trace ``` --- ## Rule 4 禁止 Controller 直接: ```text Prisma Redis fs exec fetch ``` 必须通过: ```text Resource Action Runtime Provider ``` --- ## Rule 5 部署必须: ```text Task → Job → Worker ``` --- ## Rule 6 Migration 必须: ```text Migration Runtime + Distributed Lock ``` --- ## Rule 7 所有 Runtime Instance 必须: ```text register heartbeat health shutdown ``` --- ## Rule 8 Production 必须拥有更严格的: ```text Policy Approval Audit Backup Rollback ``` --- ## Rule 9 Plugin 可以扩展: ```text Configuration Secret Provider Health Runtime Service UI ``` 但不能修改: ```text DevOS Core Security Boundary ``` --- ## Rule 10 Agent 不得绕过: ```text Environment Policy Configuration Policy Secret Policy Action Policy Deployment Policy ``` --- # 145. Golden Rule DevOS 的 Infrastructure Runtime 必须遵循: ```text Environment ↓ Configuration ↓ Secret ↓ Runtime ↓ Provider ↓ Health ↓ Deployment ``` 业务执行必须继续遵循: ```text Goal ↓ Agent ↓ Skill ↓ Capability ↓ Task ↓ Job ↓ Action ↓ Action Runtime ↓ Execution ``` 最终 DevOS 的完整运行模型: ```text DevOS │ ┌──────────────────┼──────────────────┐ │ │ │ Runtime Application Agent │ │ │ Environment Resource Goal Configuration Action │ Secret Event Skill Provider │ │ Health └──────────┬─────────┘ Deployment │ │ Capability │ │ └──────────────┬────────────┘ │ Action Runtime │ Task │ Job │ Worker │ Execution │ Event │ Observation ``` --- # 146. Final Principle DevOS 不应该让每一个新项目重新解决: ```text .env Secrets Docker Redis Postgres Worker Scheduler Health Deployment Migration Storage Providers Configuration Runtime ``` 这些应该全部成为: ```text DevOS Platform ``` 而业务项目只需要: ```text Resource Action Event Plugin Skill Agent UI ``` 例如一个新的 SEO 应用: ```text DevOS Core + SEO Plugin + SEO Skills + SEO Agents ``` 而不是重新建立: ```text SEO Backend SEO Queue SEO Worker SEO Config SEO Secrets SEO Scheduler SEO Deployment SEO Agent Runtime ``` **DevOS 的目标是让“业务项目”只负责业务,让“平台”负责运行。** 这一篇完成后,DevOS 的基础设施边界就比较完整了:**03 Resource/Action → 06 Agent/MCP/Skill → 09 Task/Job → 12 Version/Migration → 13 Deployment/Environment/Config**。