# `18_CONFIGURATION_SECRET_ENVIRONMENT_RUNTIME.md` > Version: 1.0 > Status: Implementation Specification > Target: Zcode > Depends on: > > * `03_RESOURCE_ACTION_MODEL.md` > * `06_MCP_SKILL_AGENT_RUNTIME.md` > * `09_TASK_JOB_QUEUE_RUNTIME.md` > * `12_MIGRATION_VERSIONING_COMPATIBILITY.md` > * `14_DATA_QUERY_SEARCH_INDEX_RUNTIME.md` > * `15_FILE_ARTIFACT_STORAGE_RUNTIME.md` > * `16_EVENT_STREAMING_NOTIFICATION_REALTIME_RUNTIME.md` > * `17_OBSERVABILITY_AUDIT_LOGGING_RUNTIME.md` --- # 1. Document Purpose 本文件定义 DevOS 统一的: * Configuration Runtime * Environment Runtime * Secret Runtime * Provider Runtime * Credential Runtime * Variable Runtime * Configuration Schema * Configuration Version * Configuration Override * Configuration Validation * Configuration Resolution * Secret Rotation * Secret Reference * Environment Isolation 目标: > DevOS 中所有 Core、Plugin、MCP、Agent、Skill、Workflow、Task、Worker、Action、Storage、Search、Provider 都必须通过统一 Configuration Runtime 获取配置。 禁止各模块自己: ```text process.env .env config.json yaml Redis 数据库 Secret Manager ``` 随意读取配置。 --- # 2. Core Principle DevOS 必须明确区分: ```text Configuration Secret Environment Provider Credential Runtime Variable ``` 它们不是同一个东西。 --- # 3. Configuration Configuration: > 控制系统行为的普通配置。 例如: ```text task.defaultTimeout worker.concurrency search.defaultProvider seo.scan.timeout ui.theme ``` --- # 4. Secret Secret: > 不应该以明文暴露给普通用户、日志或 API 的敏感值。 例如: ```text API Key Access Token Password Private Key Webhook Secret Database Password OAuth Client Secret Encryption Key ``` --- # 5. Environment Environment: > 一组隔离的运行环境和配置上下文。 例如: ```text development staging production ``` 也可以是: ```text dev test preview prod ``` --- # 6. Provider Provider: > 某种外部能力的实现来源。 例如: ```text LLM Provider Storage Provider Search Provider Email Provider DNS Provider Git Provider Browser Provider ``` 例如: ```text OpenAI Anthropic AWS S3 Cloudflare GitHub SMTP ``` --- # 7. Credential Credential: > Provider 所需要的认证信息。 例如: ```text GitHub Credential AWS Credential OpenAI Credential Cloudflare Credential SMTP Credential ``` --- # 8. Runtime Variable Runtime Variable: > 执行过程中临时产生或注入的变量。 例如: ```text TASK_ID EXECUTION_ID PROJECT_ID ARTIFACT_ID ``` Runtime Variable 不应该持久化成普通 Configuration。 --- # 9. Architecture ```text Configuration Runtime │ ┌───────────────────┼───────────────────┐ │ │ │ Configuration Environment Secret │ │ │ └───────────────────┼───────────────────┘ │ Resolution │ ┌───────────────────┼───────────────────┐ │ │ │ Provider Credential Runtime Variable │ │ │ └───────────────────┼───────────────────┘ ↓ Runtime Context ↓ ┌───────────────────┼───────────────────┐ ↓ ↓ ↓ Action Plugin Agent ↓ ↓ ↓ Task Worker Workflow ``` --- # 10. Configuration Hierarchy DevOS 配置支持多层覆盖: ```text Global ↓ Organization ↓ Project ↓ Environment ↓ Plugin ↓ Resource ↓ Runtime ``` 例如: ```text global.timeout = 30s project.timeout = 60s production.timeout = 90s ``` 最终: ```text production ↓ 90s ``` --- # 11. Configuration Precedence 必须定义稳定优先级: ```text Runtime Override > Resource Override > Plugin Environment > Environment > Project > Organization > Global > Default ``` --- # 12. Configuration Definition ```ts export interface ConfigDefinition { key: string namespace: string description?: string schema: unknown defaultValue?: T required?: boolean sensitive?: boolean mutable?: boolean restartRequired?: boolean scope: | 'global' | 'organization' | 'project' | 'environment' | 'plugin' | 'resource' } ``` --- # 13. Configuration Value ```ts export interface ConfigValue { key: string value: unknown scope: ConfigScope scopeId?: string version: number updatedAt: string updatedBy?: string metadata?: Record } ``` --- # 14. Configuration Scope ```ts export type ConfigScope = | 'global' | 'organization' | 'project' | 'environment' | 'plugin' | 'resource' ``` --- # 15. Configuration Runtime ```ts export interface ConfigRuntime { get( key: string, context: ConfigContext ): Promise require( key: string, context: ConfigContext ): Promise set( key: string, value: unknown, context: ConfigContext ): Promise delete( key: string, context: ConfigContext ): Promise resolve( context: ConfigContext ): Promise validate( key: string, value: unknown ): Promise } ``` --- # 16. Config Context ```ts export interface ConfigContext { organizationId?: string projectId?: string environmentId?: string pluginId?: string resourceType?: string resourceId?: string actorId?: string actorType?: 'user' | 'agent' | 'service' | 'system' runtimeVariables?: Record } ``` --- # 17. Configuration Resolution 调用: ```ts config.get( 'seo.scan.timeout', context ) ``` Runtime: ```text Default ↓ Global ↓ Organization ↓ Project ↓ Environment ↓ Plugin ↓ Resource ↓ Runtime Override ↓ Final Value ``` --- # 18. Resolved Configuration ```ts export interface ResolvedConfig { values: Record sources: Record< string, ConfigSource > version: number resolvedAt: string } ``` --- # 19. Config Source ```ts export interface ConfigSource { scope: ConfigScope scopeId?: string version: number updatedAt?: string } ``` 这样 UI 可以告诉用户: ```text seo.scan.timeout = 90s Source: Production Environment ``` --- # 20. Configuration Schema 配置必须拥有 Schema。 推荐: ```text Zod ``` 例如: ```ts const schema = z.object({ timeout: z.number().min(1).max(3600), concurrency: z.number().min(1).max(100), }) ``` --- # 21. Configuration Validation 设置配置时: ```text Input ↓ Schema Validation ↓ Policy Validation ↓ Permission ↓ Save ↓ Audit ↓ Event ``` 非法配置不得进入数据库。 --- # 22. Configuration Type 至少支持: ```text string number boolean enum array object json duration url hostname port cron resource reference provider reference secret reference ``` --- # 23. Configuration UI Metadata ```ts export interface ConfigUI { label: string description?: string component: | 'text' | 'password' | 'number' | 'switch' | 'select' | 'multi-select' | 'textarea' | 'json' | 'cron' | 'provider' | 'credential' hidden?: boolean readonly?: boolean advanced?: boolean } ``` --- # 24. Secret Runtime 定义: ```ts export interface SecretRuntime { create( input: CreateSecretInput ): Promise get( ref: SecretReference, context: SecretContext ): Promise rotate( ref: SecretReference, context: SecretContext ): Promise revoke( ref: SecretReference, context: SecretContext ): Promise delete( ref: SecretReference, context: SecretContext ): Promise } ``` --- # 25. Secret Reference 业务系统绝对不要保存: ```text apiKey = "sk-xxxxx" ``` 应该保存: ```json { "secretRef": "secret://openai/default" } ``` --- # 26. Secret Reference Interface ```ts export interface SecretReference { id: string namespace: string name: string version?: number provider: string } ``` 例如: ```text secret://openai/default secret://github/production secret://cloudflare/main ``` --- # 27. Secret Value ```ts export interface SecretValue { value: string version: number expiresAt?: string metadata?: Record } ``` Secret Value: > 只允许在需要执行时短暂进入内存。 --- # 28. Secret Storage 推荐抽象: ```ts export interface SecretProvider { put( ref: SecretReference, value: string ): Promise get( ref: SecretReference ): Promise delete( ref: SecretReference ): Promise rotate?( ref: SecretReference, value: string ): Promise } ``` 支持: ```text Local encrypted storage Vault AWS Secrets Manager GCP Secret Manager Azure Key Vault Kubernetes Secrets ``` --- # 29. Default Secret Provider DevOS 默认可以提供: ```text PostgreSQL encrypted secret storage ``` 但必须: ```text encryption at rest ``` 并且: ```text secret value ≠ normal database field ``` --- # 30. Encryption Secret 必须加密。 推荐: ```text Envelope Encryption ``` 结构: ```text Master Key ↓ Data Encryption Key ↓ Secret ``` Master Key 不存数据库明文。 --- # 31. Secret Access 读取 Secret 必须: ```text Authentication ↓ Permission ↓ Scope ↓ Policy ↓ Audit ↓ Secret Provider ``` --- # 32. Secret Access Audit 读取 Secret 必须产生 Audit: ```text actor: user_123 operation: secret.read secret: openai/default result: success ``` 但: > Audit 中绝对不能记录 Secret Value。 --- # 33. Secret Redaction Secret 即使被传入: ```text Log Error Trace Event Audit ``` 也必须自动: ```text [REDACTED] ``` 与 `17` 的 Redaction Runtime 集成。 --- # 34. Secret Rotation Secret 生命周期: ```text active ↓ rotation_pending ↓ rotating ↓ active_new_version ↓ revoked_old_version ``` --- # 35. Secret Version ```ts export interface SecretVersion { version: number createdAt: string expiresAt?: string status: | 'active' | 'expired' | 'revoked' createdBy?: string } ``` --- # 36. Zero Downtime Rotation Rotation 不应该: ```text delete old ↓ create new ``` 而应该: ```text new secret ↓ test ↓ activate ↓ switch consumers ↓ revoke old ``` --- # 37. Credential Runtime Credential 是 Secret 的业务封装。 例如: ```ts export interface Credential { id: string name: string providerId: string type: string secretRefs: SecretReference[] organizationId?: string projectId?: string environmentId?: string status: | 'active' | 'invalid' | 'expired' | 'revoked' metadata?: Record } ``` --- # 38. Provider Runtime ```ts export interface ProviderDefinition { id: string type: string name: string capabilities: string[] configSchema: unknown credentialSchema?: unknown healthCheck?: string } ``` --- # 39. Provider Example 例如 LLM: ```text provider.openai provider.anthropic provider.google ``` 统一: ```ts interface LLMProvider { generate(input: LLMInput): Promise } ``` --- # 40. Provider Resolution Agent 不应该写: ```ts new OpenAI() ``` 而应该: ```ts provider.resolve( 'llm', context ) ``` Runtime 决定: ```text Project Provider ↓ Environment Provider ↓ Default Provider ``` --- # 41. Provider Failover 可以配置: ```text Primary: OpenAI Fallback: Anthropic Fallback: Google ``` Runtime: ```text OpenAI ↓ failure Anthropic ↓ failure Google ``` 必须记录: ```text provider selected provider failed provider fallback ``` --- # 42. Provider Policy Provider 可以受到: ```text organization policy project policy environment policy agent policy ``` 限制。 例如: ```text Production Agent 只能使用: OpenAI Anthropic 禁止: Unknown Provider ``` --- # 43. Provider Health Provider 必须注册: ```text health check latency error rate rate limit quota ``` 与: ```text 17_OBSERVABILITY_AUDIT_LOGGING_RUNTIME.md ``` 集成。 --- # 44. Environment Resource 建议: ```text core.environment ``` 定义: ```ts export interface Environment { id: string name: string key: string type: | 'development' | 'test' | 'staging' | 'production' | 'preview' | 'custom' organizationId: string projectId?: string status: | 'active' | 'disabled' | 'archived' metadata?: Record } ``` --- # 45. Environment Isolation 环境必须隔离: ```text Development ≠ Production ``` 尤其: ```text Secrets Database Storage Queue Providers Credentials ``` --- # 46. Environment Context 所有执行都应该知道: ```text environmentId ``` 例如: ```ts interface ActionContext { environmentId?: string } ``` 这样: ```text Action ↓ Environment ↓ Configuration ↓ Credential ↓ Provider ``` 全部一致。 --- # 47. Production Protection Production 必须拥有额外 Policy。 例如: ```text production: requireApproval: - server.delete - database.delete - deployment.rollback forbidden: - test.provider ``` --- # 48. Environment Variables DevOS 可以读取系统环境变量: ```text process.env ``` 但是: > 只能由 Configuration Runtime 在启动阶段读取。 业务代码禁止直接: ```ts process.env.OPENAI_API_KEY ``` --- # 49. Bootstrap Configuration 启动阶段: ```text OS Environment ↓ Bootstrap Config ↓ Configuration Runtime ↓ Application Runtime ``` 例如: ```text DATABASE_URL REDIS_URL DEVOS_MASTER_KEY ``` 属于: ```text bootstrap secrets/config ``` --- # 50. Bootstrap vs Runtime Config Bootstrap: > 系统启动所必需。 Runtime: > 系统运行期间可动态修改。 例如: ```text DATABASE_URL ``` 通常 Bootstrap。 而: ```text worker.concurrency ``` 可以 Runtime Config。 --- # 51. Dynamic Configuration 支持动态修改: ```text worker.concurrency logging.level alert.threshold search.provider agent.maxIterations ``` 修改后: ```text validate ↓ persist ↓ publish config.changed ↓ runtime refresh ``` --- # 52. Configuration Event 与 `16` 集成: ```text config.created config.updated config.deleted config.reset config.reloaded secret.created secret.rotated secret.revoked credential.created credential.updated credential.revoked provider.created provider.updated provider.health_changed environment.created environment.updated environment.archived ``` --- # 53. Configuration Version 每次修改: ```text version++ ``` 例如: ```text v1 ↓ v2 ↓ v3 ``` 不能覆盖历史记录而无法追踪。 --- # 54. Configuration History 必须可以查询: ```text 谁改的? 什么时候改的? 改了什么? 为什么? 从什么值? 改成什么? ``` 例如: ```text worker.concurrency v12: 4 v13: 8 Actor: admin Reason: Increase production throughput ``` --- # 55. Configuration Audit 所有重要配置变更必须 Audit: ```text config.update config.delete config.reset secret.create secret.rotate secret.revoke credential.update provider.update environment.update ``` --- # 56. Configuration Rollback 支持: ```text current v13 ↓ rollback ↓ v12 ``` 但是实际上应该创建: ```text v14 ``` 内容等于: ```text v12 ``` 而不是修改历史。 --- # 57. Configuration Lock 某些配置可以锁定: ```ts export interface ConfigLock { key: string scope: ConfigScope scopeId?: string reason?: string lockedBy?: string } ``` 例如: ```text production.database.url ``` 禁止普通用户修改。 --- # 58. Configuration Policy 配置修改必须经过: ```text Permission ↓ Policy ↓ Validation ↓ Approval if required ↓ Write ``` --- # 59. Sensitive Configuration `ConfigDefinition`: ```ts sensitive: true ``` 例如: ```text smtp.password provider.apiKey database.password ``` UI 只能显示: ```text •••••••• ``` --- # 60. Secret vs Sensitive Config 必须区分: ```text sensitive config ``` 与: ```text secret ``` 例如: ```text logging.redaction.enabled = true ``` 可以是: ```text sensitive = false ``` 而: ```text openai.apiKey ``` 必须: ```text secret ``` --- # 61. No Secret in Config DB 禁止: ```json { "openai.apiKey": "sk-xxx" } ``` 应该: ```json { "openai.apiKey": { "secretRef": "secret://openai/default" } } ``` --- # 62. Provider Credential Binding 例如: ```text Provider: OpenAI Credential: openai-production Secret: secret://openai/production ``` 关系: ```text Provider ↓ Credential ↓ Secret ``` --- # 63. Credential Selection Runtime 根据: ```text organization project environment provider policy ``` 选择 Credential。 例如: ```text production ↓ OpenAI Provider ↓ openai-production credential ``` 而: ```text development ↓ OpenAI Provider ↓ openai-development credential ``` --- # 64. Configuration Resolver ```ts export interface ConfigResolver { resolve( key: string, context: ConfigContext ): Promise } ``` 解析过程: ```text Schema ↓ Defaults ↓ Scope values ↓ Overrides ↓ References ↓ Secrets ↓ Runtime Variables ↓ Validation ↓ Final Value ``` --- # 65. Secret Reference Resolution 例如配置: ```json { "apiKey": { "secretRef": "secret://github/production" } } ``` 最终: ```text Config Resolver ↓ Secret Runtime ↓ Secret Provider ↓ memory only ``` 绝对不要把解析后的 Secret 再持久化。 --- # 66. Runtime Context Action 执行时: ```ts export interface RuntimeConfigContext { config: ResolvedConfig providers: ProviderContext credentials: CredentialContext environment: Environment variables: Record } ``` --- # 67. Action Integration Action: ```ts async execute(input, ctx) { const timeout = await ctx.config.get( 'seo.scan.timeout' ) const provider = await ctx.providers.resolve( 'search' ) } ``` Action 不需要: ```text process.env database.config secret table ``` --- # 68. Agent Integration Agent 可以读取: ```text agent.model agent.maxIterations agent.maxTokens agent.temperature ``` 但必须经过: ```text Agent Policy ↓ Configuration Runtime ``` Agent 不能自己修改: ```text production secrets ``` --- # 69. Skill Integration Skill Manifest 可以声明: ```ts interface SkillConfigRequirement { key: string required: boolean description: string } ``` 例如: ```text seo.content-generation requires: llm.provider llm.model ``` Runtime 自动检查。 --- # 70. Plugin Configuration Plugin Manifest: ```ts interface PluginManifest { id: string config?: ConfigDefinition[] providers?: ProviderDefinition[] credentials?: CredentialDefinition[] } ``` Plugin 安装: ```text Plugin ↓ Config Definitions ↓ Provider Definitions ↓ Credential Definitions ↓ Registry ``` --- # 71. Plugin Settings Page Plugin 可以声明: ```text Settings ``` 例如: ```text SEO ├── General ├── Scan ├── Search Engine ├── AI ├── Credentials └── Advanced ``` 但 UI 使用: ```text DevOS Configuration UI ``` 而不是每个 Plugin 自己实现配置存储系统。 --- # 72. MCP Configuration MCP Server: ```text MCP Server ├── endpoint ├── transport ├── auth ├── timeout ├── credential └── enabled ``` 统一: ```text MCP Configuration Runtime ``` --- # 73. MCP Credential 例如: ```text MCP Server: github Credential: github-mcp-production Secret: secret://github/mcp-production ``` --- # 74. Workflow Configuration Workflow 可以使用: ```text ${project.id} ${environment.id} ${task.id} ${config.xxx} ${secret.xxx} ``` 但: ```text ${secret.xxx} ``` 只能在安全 Runtime Context 中解析。 --- # 75. Template Variables 定义: ```ts export interface VariableResolver { resolve( expression: string, context: RuntimeVariableContext ): Promise } ``` 例如: ```text ${task.id} ${project.name} ${environment.name} ``` --- # 76. Variable Security 禁止模板执行任意代码。 不能: ```text ${eval(...)} ``` 只能: ```text property lookup approved functions ``` --- # 77. Configuration Expression 可以支持: ```text ${config.seo.timeout} ${environment.name} ${project.id} ``` 但必须是: ```text sandboxed expression ``` --- # 78. Configuration Cache Configuration Runtime 可以缓存: ```text global organization project environment ``` 但是 Secret 缓存必须: ```text short TTL memory only never Redis plaintext ``` --- # 79. Configuration Invalidation 配置改变: ```text config.updated ↓ Event Runtime ↓ Config Cache invalidation ↓ Runtime refresh ``` --- # 80. Worker Configuration Worker 启动: ```text Bootstrap Config ↓ Environment ↓ Worker Config ↓ Provider Config ``` 动态配置: ```text worker.concurrency worker.queues worker.pollInterval ``` 可以热更新。 --- # 81. Scheduler Configuration Scheduler: ```text scheduler.enabled scheduler.maxConcurrent scheduler.pollInterval scheduler.misfirePolicy ``` 通过 Configuration Runtime。 --- # 82. Queue Configuration 例如: ```text queue.default.concurrency queue.ai.concurrency queue.browser.concurrency queue.retry.maxAttempts ``` 禁止 Queue Runtime 自己读取: ```text process.env ``` --- # 83. Database Configuration Database Bootstrap: ```text DATABASE_URL ``` 但是: ```text pool.max pool.timeout query.timeout ``` 可以由 Config Runtime 管理。 --- # 84. Storage Configuration 例如: ```text storage.defaultProvider storage.bucket storage.region storage.maxUploadSize storage.signedUrlTTL ``` Credential: ```text storage credential ``` 通过: ```text Credential Runtime ``` --- # 85. Search Configuration 例如: ```text search.defaultProvider search.semantic.enabled search.embeddingProvider search.maxResults ``` Provider: ```text PostgreSQL OpenSearch Meilisearch ``` --- # 86. Email Configuration 例如: ```text email.provider email.from email.replyTo ``` Credential: ```text SMTP password API key ``` 通过 Secret Runtime。 --- # 87. Environment Promotion 支持: ```text development ↓ staging ↓ production ``` 但: > Secret 不应该简单复制。 应该: ```text Config Promotion ``` 与: ```text Secret Binding ``` 分离。 --- # 88. Config Promotion 例如: ```text staging: seo.scan.timeout = 60 production: seo.scan.timeout = 60 ``` 可以 promote: ```text staging config ↓ production config ``` 但: ```text staging OpenAI key ``` 不能 promote。 生产环境重新绑定: ```text production credential ``` --- # 89. Environment Diff 必须提供: ```text dev vs staging staging vs production ``` 配置 Diff: ```text worker.concurrency dev: 2 prod: 16 seo.scan.timeout dev: 30 prod: 90 ``` Secret: ```text production secret differs ``` 只显示: ```text configured ``` 不能显示值。 --- # 90. Environment Import / Export 允许导出: ```text configuration definitions configuration values provider definitions credential references ``` 不允许导出: ```text secret values ``` --- # 91. Configuration Bundle 可以生成: ```text configuration bundle ``` 通过: ```text Artifact Runtime ``` 保存。 内容: ```text config.json providers.json credentials.json environment.json ``` Secret: ```text secret references only ``` --- # 92. Configuration Migration 与 `12` 集成。 例如: ```text v1: llm.provider v2: llm.defaultProvider ``` Migration: ```text llm.provider ↓ llm.defaultProvider ``` --- # 93. Configuration Schema Version 每个 Config Definition 可以: ```ts interface ConfigDefinition { key: string schemaVersion: number } ``` 升级: ```text schema v1 ↓ migration ↓ schema v2 ``` --- # 94. Plugin Upgrade Plugin 升级: ```text Plugin v1 ↓ Config compatibility check ↓ Config migration ↓ Secret compatibility ↓ Provider compatibility ↓ Plugin v2 ``` --- # 95. Configuration Validation During Upgrade 升级前必须检查: ```text required configs schema changes removed configs renamed configs provider changes credential changes secret changes ``` 如果: ```text breaking ``` 必须进入: ```text UpgradePlan ``` --- # 96. Configuration Snapshot 每次 Task/Execution 开始时,可以记录: ```ts interface ConfigurationSnapshot { id: string createdAt: string platformVersion: string configVersion: number environmentId?: string valuesHash: string } ``` 不一定保存全部 Secret。 --- # 97. Reproducibility 结合 `12`: 每个 Execution 应该知道: ```text runtimeVersion pluginVersion actionVersion skillVersion mcpVersion configurationVersion environmentId ``` 这样才能回答: > 为什么昨天这个 Action 成功,今天失败? --- # 98. Configuration Hash 生成: ```text SHA-256 ``` 例如: ```text configHash: a9c7... ``` Execution 记录: ```text configurationHash ``` Secret Value 不进入 Hash。 可以记录: ```text secretRef secretVersion ``` --- # 99. Secret Version Binding 高可靠执行可以锁定: ```text secret://openai/prod version = 7 ``` 这样: ```text Execution ``` 不会因为 Secret Rotation 导致执行中途变化。 --- # 100. Task Configuration Snapshot Task: ```text Task ↓ Configuration Snapshot ↓ Jobs ``` 批量 Task 的所有 Job 默认使用: ```text Task configuration context ``` 这样不会出现: ```text Job 1 → config v10 Job 2 → config v11 Job 3 → config v12 ``` 除非明确允许动态配置。 --- # 101. Dynamic vs Pinned Configuration 配置可以: ```text dynamic pinned ``` Dynamic: ```text 每次读取最新配置 ``` Pinned: ```text Task 创建时锁定版本 ``` 生产任务推荐: ```text pinned ``` --- # 102. Agent Configuration Agent Run 应记录: ```text model provider temperature maxTokens maxIterations budget configurationVersion ``` 如果 Agent 中途改变配置: ```text replan ``` 并记录原因。 --- # 103. Configuration Permissions 建议: ```text config.read config.create config.update config.delete config.rollback config.export ``` Secret: ```text secret.read secret.create secret.rotate secret.revoke secret.delete ``` Provider: ```text provider.read provider.create provider.update provider.delete provider.test ``` Environment: ```text environment.read environment.create environment.update environment.archive ``` --- # 104. Secret Read Policy Secret 权限应该比 Config 更严格。 例如: ```text config.read ``` 允许: ```text OpenAI credential = configured ``` 但: ```text secret.read ``` 才允许: ```text 实际读取 Secret ``` --- # 105. Secret Access Without Exposure Provider Action 最好: ```text Provider Runtime ↓ Secret Runtime ↓ Provider SDK ``` 而不是: ```text Agent ↓ Secret Value ``` Agent 通常只需要: ```text credentialId ``` --- # 106. Provider Test Action 提供: ```text provider.test ``` 例如: ```text provider.openai.test provider.github.test provider.cloudflare.test ``` 流程: ```text Provider ↓ Credential ↓ Secret ↓ Health/Test ↓ Result ``` 完整走: ```text Action Runtime ``` --- # 107. Secret Rotation Task Rotation 如果复杂: ```text Secret Rotate ↓ Task ↓ Job ↓ Worker ↓ Provider ↓ Validation ↓ Activate ↓ Audit ``` 不要在 HTTP 请求中执行长时间 Rotation。 --- # 108. Environment Lifecycle ```text creating ↓ active ↓ disabled ↓ archived ``` 删除 Environment 默认不允许直接物理删除。 推荐: ```text archive ``` --- # 109. Environment Delete Protection Production: ```text delete ``` 必须: ```text approval ``` 甚至默认: ```text forbidden ``` --- # 110. Environment Resource Scope 所有 Resource 可以绑定: ```text environmentId ``` 例如: ```text core.server core.database core.storage seo.website ``` 从而支持: ```text production resource staging resource ``` 隔离。 --- # 111. Environment-aware Search Search Runtime 自动加入: ```text environmentId ``` 例如: ```text Search production servers ``` 不能返回: ```text development servers ``` 除非权限允许跨 Environment。 --- # 112. Environment-aware Storage Artifact: ```text environmentId ``` File: ```text environmentId ``` Storage Policy 可以要求: ```text production artifacts ``` 存储在: ```text production bucket ``` --- # 113. Environment-aware Queue 可以: ```text production queue staging queue ``` 例如: ```text queue.production.ai queue.staging.ai ``` 防止: ```text staging job ``` 跑到: ```text production worker ``` --- # 114. Worker Environment Binding Worker: ```ts interface Worker { environmentIds?: string[] capabilities: string[] } ``` Worker 只能领取允许 Environment 的 Job。 --- # 115. Provider Environment Binding Provider Credential: ```text environmentId ``` 例如: ```text OpenAI Production OpenAI Staging ``` 不能混用。 --- # 116. Configuration Registry 建立: ```text Configuration Registry ``` 负责: ```text definitions schemas defaults scope validation UI metadata version migration ``` --- # 117. Secret Registry 负责: ```text secret metadata references versions provider scope rotation expiration ``` 不负责: ```text business configuration ``` --- # 118. Provider Registry 负责: ```text provider definitions provider implementations capabilities configuration schema credential schema health ``` --- # 119. Environment Registry 负责: ```text environment definitions status scope configuration binding provider binding storage binding queue binding ``` --- # 120. Runtime Resolution Chain 完整: ```text Execution ↓ Environment ↓ Config Resolver ↓ Configuration ↓ Provider Resolver ↓ Credential Resolver ↓ Secret Runtime ↓ External Provider ``` --- # 121. Unified Example 例如: ```text Agent: “扫描网站 a.com” ``` Agent: ```text seo.website.scan ``` Action Runtime: ```text Action ↓ Environment = production ↓ Config: seo.scan.timeout = 90 ↓ Provider: search.google ↓ Credential: google-search-console-production ↓ Secret: secret://google/search-console/prod ↓ Execution ``` 整个过程: ```text Audit Log Trace Metric Usage Cost Event ``` 都自动生成。 --- # 122. Configuration UI DevOS Settings: ```text Settings ├── General ├── Organizations ├── Projects ├── Environments ├── Configuration ├── Secrets ├── Credentials ├── Providers └── Runtime ``` --- # 123. Configuration UI Detail 配置页面: ```text Configuration ├── Global ├── Organization ├── Project ├── Environment ├── Plugin └── Resource ``` 支持: ```text Search Filter Edit Reset History Diff Rollback Lock Export ``` --- # 124. Secret UI Secret 页面: ```text Secrets ├── Active ├── Expiring ├── Expired ├── Revoked └── Rotation ``` 显示: ```text OpenAI Production Status: Active Version: 7 Expires: ... ``` 不显示: ```text secret value ``` --- # 125. Credential UI ```text Credentials ├── OpenAI Production ├── GitHub Production ├── Cloudflare Production └── SMTP Production ``` 操作: ```text Test Rotate Revoke Edit View Usage View Audit ``` --- # 126. Provider UI ```text Providers ├── LLM ├── Search ├── Storage ├── Git ├── DNS ├── Email └── Browser ``` 显示: ```text Provider Status Health Latency Credential Environment Usage Cost ``` --- # 127. Environment UI ```text Environments Development Active Staging Active Production Active ``` 点击: ```text Production ``` 显示: ```text Configuration Providers Credentials Resources Workers Queues Tasks Health Usage Cost ``` --- # 128. Environment Diff UI 例如: ```text Production vs Staging worker.concurrency Production: 16 Staging: 4 search.provider Production: google Staging: bing openai credential Production: configured Staging: configured ``` Secret: ```text Never show values. ``` --- # 129. API Configuration: ```http GET /api/config GET /api/config/:key POST /api/config PUT /api/config/:key DELETE /api/config/:key GET /api/config/history POST /api/config/rollback ``` Secrets: ```http GET /api/secrets POST /api/secrets POST /api/secrets/:id/rotate POST /api/secrets/:id/revoke DELETE /api/secrets/:id ``` Credentials: ```http GET /api/credentials POST /api/credentials PUT /api/credentials/:id POST /api/credentials/:id/test POST /api/credentials/:id/rotate POST /api/credentials/:id/revoke ``` --- # 130. Environment API ```http GET /api/environments POST /api/environments GET /api/environments/:id PUT /api/environments/:id POST /api/environments/:id/disable POST /api/environments/:id/archive GET /api/environments/:id/config GET /api/environments/:id/diff ``` --- # 131. Provider API ```http GET /api/providers GET /api/providers/:id POST /api/providers PUT /api/providers/:id DELETE /api/providers/:id POST /api/providers/:id/test GET /api/providers/:id/health ``` --- # 132. CLI ```bash devos config list devos config get seo.scan.timeout devos config set seo.scan.timeout 90 devos config history seo.scan.timeout devos config rollback seo.scan.timeout 12 devos secrets list devos secrets rotate openai-production devos secrets revoke old-key devos credentials list devos credentials test openai-production devos providers list devos providers test openai devos environments list devos environments diff staging production ``` --- # 133. CLI Security CLI: ```text devos secrets get ``` 默认: ```text 禁止 ``` 除非明确拥有: ```text secret.read ``` 即使允许,也应该: ```text explicit confirmation ``` 避免: ```text shell history ``` 记录 Secret。 --- # 134. Logging Integration 禁止: ```ts logger.info('credential', credential) ``` 因为可能泄漏 Secret。 必须: ```ts logger.info('credential resolved', { credentialId: credential.id, providerId: credential.providerId, }) ``` --- # 135. Error Integration 错误: ```text SecretProviderError ``` 允许: ```text code provider secretRef ``` 但不能: ```text secret value ``` --- # 136. Audit Integration Config 修改: ```text config.update ``` Secret: ```text secret.rotate ``` Provider: ```text provider.update ``` Environment: ```text environment.update ``` 全部进入: ```text Audit Runtime ``` --- # 137. Observability Integration Metrics: ```text config_read_total config_update_total secret_access_total secret_rotation_total provider_request_total provider_failure_total credential_test_total ``` Tracing: ```text config.resolve secret.resolve provider.resolve credential.resolve ``` --- # 138. Security Events 与 Event Runtime 集成: ```text security.secret.accessed security.secret.rotated security.secret.revoked security.credential.created security.credential.revoked security.config.changed security.environment.changed ``` --- # 139. Package Structure 建议: ```text packages/ ├── config/ │ ├── runtime/ │ ├── registry/ │ ├── resolver/ │ ├── schema/ │ ├── validation/ │ └── migration/ │ ├── secret/ │ ├── runtime/ │ ├── providers/ │ ├── encryption/ │ ├── rotation/ │ └── policy/ │ ├── credential/ │ ├── runtime/ │ ├── registry/ │ └── providers/ │ ├── provider/ │ ├── runtime/ │ ├── registry/ │ ├── resolver/ │ └── health/ │ └── environment/ ├── runtime/ ├── registry/ └── policy/ ``` --- # 140. NestJS Structure ```text src/ ├── config/ │ ├── config.module.ts │ ├── runtime/ │ ├── registry/ │ ├── resolver/ │ ├── controllers/ │ └── repositories/ │ ├── secret/ │ ├── secret.module.ts │ ├── runtime/ │ ├── providers/ │ ├── encryption/ │ └── repositories/ │ ├── credential/ │ ├── credential.module.ts │ ├── runtime/ │ └── repositories/ │ ├── provider/ │ ├── provider.module.ts │ ├── runtime/ │ ├── registry/ │ └── health/ │ └── environment/ ├── environment.module.ts ├── runtime/ └── repositories/ ``` --- # 141. Database Tables 建议: ```text config_definitions config_values config_versions config_locks environments providers provider_bindings credentials credential_bindings secrets secret_versions configuration_snapshots ``` --- # 142. `config_values` 核心: ```text id definition_id key scope scope_id value_json version created_at updated_at updated_by ``` 敏感值不能直接放这里。 --- # 143. `secrets` 核心: ```text id namespace name provider organization_id project_id environment_id current_version status expires_at created_at created_by ``` Secret Value: > 不作为普通业务 JSON 返回。 --- # 144. `secret_versions` ```text id secret_id version encrypted_value status created_at expires_at revoked_at ``` 加密后的 Value。 --- # 145. `credentials` ```text id name provider_id organization_id project_id environment_id status metadata_json created_at updated_at ``` 关联: ```text credential_secret_refs ``` --- # 146. `providers` ```text id type name version status config_json capabilities_json created_at updated_at ``` --- # 147. `environments` ```text id organization_id project_id name key type status created_at updated_at ``` --- # 148. Secret Encryption Requirements Zcode 必须: ```text [ ] Secret never stored plaintext [ ] Secret never returned by generic API [ ] Secret never logged [ ] Secret never included in Event payload [ ] Secret never included in Audit [ ] Secret never included in Trace attributes [ ] Secret never included in Error message [ ] Secret never included in configuration export ``` --- # 149. Configuration Security Requirements 必须: ```text [ ] RBAC [ ] Scope policy [ ] Validation [ ] Audit [ ] Versioning [ ] Rollback [ ] Lock [ ] Redaction [ ] Multi-tenant isolation ``` --- # 150. Testing 至少测试: ```text Configuration Resolution Configuration Precedence Configuration Validation Configuration Version Configuration Rollback Configuration Lock Secret Encryption Secret Access Secret Rotation Secret Revocation Secret Redaction Credential Binding Provider Resolution Provider Failover Environment Isolation Environment Promotion Agent Plugin MCP Task Job Worker Action ``` --- # 151. Configuration Precedence Test 输入: ```text Default = 10 Global = 20 Organization = 30 Project = 40 Environment = 50 Plugin = 60 Resource = 70 Runtime = 80 ``` 最终必须: ```text 80 ``` --- # 152. Configuration Rollback Test ```text v1 = 10 v2 = 20 v3 = 30 ``` Rollback v3 → v1。 必须产生: ```text v4 = 10 ``` 而不是: ```text delete v2 delete v3 ``` --- # 153. Secret Rotation Test ```text Secret v1 active ↓ create v2 ↓ validate v2 ↓ activate v2 ↓ revoke v1 ``` 验证: ```text v1 revoked v2 active ``` --- # 154. Secret Leak Test 模拟: ```text logger error trace audit event diagnostic ``` 都不能出现 Secret Value。 --- # 155. Environment Isolation Test ```text Production ``` 不能读取: ```text Staging Secret ``` 除非明确 Policy 允许。 --- # 156. Worker Environment Test ```text production job ``` 不能被: ```text staging worker ``` 领取。 --- # 157. Provider Credential Test ```text Production OpenAI Provider ``` 只能使用: ```text Production Credential ``` 不能自动 fallback 到: ```text Development Credential ``` --- # 158. Agent Security Test Agent: ```text read production secret ``` 如果没有: ```text secret.read ``` 必须: ```text DENIED ``` Agent 不能通过: ```text MCP Plugin Workflow Action ``` 绕过。 --- # 159. Plugin Security Test Plugin 尝试: ```ts process.env.OPENAI_API_KEY ``` 架构层面应该: > 不依赖该机制获取运行时 Secret。 Plugin 必须使用: ```text Credential Runtime ``` --- # 160. MCP Security Test MCP Tool: ```text get_secret ``` 不应该默认暴露。 MCP 应该使用: ```text Provider / Credential Capability ``` 完成外部调用,而不是把 Secret 交给 Agent。 --- # 161. Dynamic Config Test 修改: ```text worker.concurrency ``` 验证: ```text Config Update ↓ Event ↓ Cache Invalidation ↓ Worker Reload ``` 无需重启。 --- # 162. Configuration Failure 如果 Configuration Runtime 暂时不可用: ```text cached config ``` 可以根据配置策略继续。 但: ```text security critical config ``` 不能使用不确定的旧值。 --- # 163. Secret Provider Failure 如果 Secret Provider 无法访问: ```text Action ↓ Secret resolve ↓ failure ``` 必须: ```text Action failed ``` 而不能: ```text 使用空 Secret ``` --- # 164. Provider Failure Provider 失败: ```text Primary Provider ↓ Retry Policy ↓ Fallback Provider ``` 但必须满足: ```text Policy Compatibility Credential availability ``` --- # 165. Configuration Export Security Export: ```text config providers credentials metadata environment ``` 不允许: ```text secret values ``` --- # 166. Environment Promotion Test 测试: ```text staging config ↓ production ``` 验证: ```text configuration promoted secret not promoted credential rebound environmentId changed audit generated ``` --- # 167. Acceptance Criteria Zcode 完成后: ### Configuration ```text [ ] Config Registry [ ] Config Schema [ ] Config Runtime [ ] Scope [ ] Precedence [ ] Validation [ ] Version [ ] History [ ] Rollback [ ] Lock [ ] Dynamic Reload ``` ### Secret ```text [ ] Secret Runtime [ ] Encryption [ ] Secret Provider [ ] Reference [ ] Version [ ] Rotation [ ] Revocation [ ] Expiration [ ] Redaction ``` ### Credential ```text [ ] Credential Registry [ ] Provider Binding [ ] Environment Binding [ ] Test [ ] Rotation [ ] Revocation ``` ### Provider ```text [ ] Provider Registry [ ] Provider Resolver [ ] Health [ ] Failover [ ] Policy ``` ### Environment ```text [ ] Environment Resource [ ] Isolation [ ] Promotion [ ] Diff [ ] Environment Policy ``` --- # 168. Final Integration Acceptance 必须验证: ```text User ↓ Agent ↓ Skill ↓ Capability ↓ Action ↓ Environment ↓ Config Runtime ↓ Provider Runtime ↓ Credential Runtime ↓ Secret Runtime ↓ External Provider ↓ Execution ``` 并且自动关联: ```text Audit Log Metric Trace Usage Cost Event ``` --- # 169. Zcode Golden Rules ## Rule 1 禁止业务代码: ```ts process.env.X ``` 直接读取 Runtime Configuration。 --- ## Rule 2 禁止业务代码: ```ts database.query(config) ``` 自行读取配置表。 必须: ```text Config Runtime ``` --- ## Rule 3 禁止: ```text Plugin → Secret DB ``` 必须: ```text Plugin ↓ Credential Runtime ↓ Secret Runtime ``` --- ## Rule 4 禁止: ```text Agent → Secret Value ``` 除非明确 Permission + Policy + Action。 --- ## Rule 5 禁止: ```text MCP → Secret Store ``` MCP 必须通过: ```text Capability ↓ Action Runtime ↓ Credential / Provider Runtime ``` --- ## Rule 6 禁止: ```text Plugin → process.env ``` 获取业务级 API Key。 --- ## Rule 7 禁止: ```text Plugin ↓ 自己实现 config.json ``` 必须注册: ```text ConfigDefinition ``` 到 DevOS Configuration Registry。 --- ## Rule 8 禁止: ```text Plugin ↓ 自己实现 Secret Manager ``` 必须使用: ```text Secret Runtime ``` --- ## Rule 9 Production Environment 必须拥有: ```text 额外权限 额外 Policy Approval Audit Isolation ``` --- ## Rule 10 所有配置修改必须能够回答: ```text 谁? 什么时候? 改了什么? 为什么? 从哪里改? 改之前是什么? 改之后是什么? ``` --- # 170. Final Architecture 完成 18 后: ```text DEVOS │ ┌──────────────────┼──────────────────┐ │ │ │ Resource Action Data │ │ │ └──────────────────┼──────────────────┘ │ Task / Job │ Execution │ ┌─────────────┼─────────────┐ │ │ │ Config Provider Environment │ │ │ Resolver Resolver Scope │ │ │ Credential ──────┤ │ │ │ │ Secret │ │ │ │ │ └─────────────┼─────────────┘ │ External Capability │ ┌────────────────┼────────────────┐ │ │ │ MCP Plugin Agent │ │ │ └────────────────┼────────────────┘ │ Observability │ ┌──────────────────┼──────────────────┐ │ │ │ Log Trace Audit │ │ │ Metric Error Usage │ │ │ └──────────────────┼──────────────────┘ │ Event Runtime ``` --- # 171. DevOS Configuration Golden Rule 最终规则: ```text Configuration ↓ Configuration Runtime ↓ Environment Resolution ↓ Provider Resolution ↓ Credential Resolution ↓ Secret Resolution ↓ Runtime Context ↓ Action ↓ Execution ``` **业务代码不应该知道 Secret 存在哪里。** **Plugin 不应该知道配置存在哪里。** **Agent 不应该知道 Provider Credential 存在哪里。** **MCP 不应该接触 Secret Store。** **Worker 不应该直接读取 `.env`。** 所有这些都应该由: ```text DevOS Runtime ``` 统一解决。 > **Configuration 决定系统怎么运行,Environment 决定在哪运行,Provider 决定使用谁,Credential 决定以什么身份访问,Secret 决定敏感凭证是什么;而这些都必须通过统一 Runtime 解析。**