# DevOS Platform v2 ## 02 — Core Architecture Specification **Document Version:** 2.0 **Status:** Architecture Specification **Parent Document:** `01_ARCHITECTURE.md` **Target:** DevOS Platform v2 **Implementation Target:** Zcode / AI Coding Agent --- # 1. Core 定义 DevOS Core 是整个 DevOS Platform 的稳定基础层。 Core 的职责是提供所有 Application、Plugin、MCP、Skill、Agent 都可能依赖的通用能力。 Core 不属于任何业务领域。 Core 的设计目标: ```text Stable Reusable Predictable Secure Minimal Business-Agnostic ``` --- # 2. Core 的核心原则 必须遵循: > Core 提供能力,不提供业务。 例如: 允许: ```text User Organization Role Permission Resource Action Event Task Job File Storage Notification Audit Settings ``` 禁止: ```text SEOKeyword Backlink CRMLead Invoice ProductOrder Campaign Article WebsiteSEOScore ``` 这些属于 Application / Plugin。 --- # 3. Core 模块总览 DevOS Core 第一阶段包含: ```text core/ ├── identity/ ├── organization/ ├── auth/ ├── authorization/ ├── resource/ ├── action/ ├── event/ ├── task/ ├── job/ ├── file/ ├── storage/ ├── notification/ ├── audit/ ├── settings/ ├── search/ ├── api/ ├── error/ ├── validation/ ├── logging/ ├── health/ └── config/ ``` --- # 4. Core 不应该过度拆分 不要为了“模块化”而产生数十个没有实际边界的 package。 以下内容可以属于 Core: ```text Auth User Organization Permission Resource Action Event Task Job File Storage Notification Audit Settings ``` 但不应该出现: ```text UserNameService UserAvatarService UserPreferenceService UserEmailService ``` 除非存在明确的独立生命周期和依赖边界。 --- # 5. Core 分层 Core 内部继续分为: ```text Foundation Domain Application Infrastructure ``` 结构: ```text ┌─────────────────────────────┐ │ Application │ │ API / Command / Query │ ├─────────────────────────────┤ │ Domain │ │ Identity / Auth / Resource │ ├─────────────────────────────┤ │ Foundation │ │ Types / Errors / Events │ ├─────────────────────────────┤ │ Infrastructure │ │ DB / Redis / Storage / Queue│ └─────────────────────────────┘ ``` --- # 6. Foundation Foundation 是最底层。 不得依赖: ```text Application Plugin MCP Agent 具体业务 ``` 包含: ```text types errors result ids time events validation contracts ``` 例如: ```ts type ID = string interface Entity { id: ID createdAt: Date updatedAt: Date } ``` --- # 7. Domain Domain 定义 Core 的核心对象。 例如: ```text User Organization Role Permission Resource Action Task Job Event File Notification AuditLog ``` Domain 不直接操作: ```text PostgreSQL Redis S3 HTTP Filesystem ``` 通过 Repository / Port 抽象访问。 --- # 8. Infrastructure Infrastructure 实现具体技术。 例如: ```text PostgresUserRepository RedisEventBus S3Storage BullMQJobQueue ``` Application / Domain 不应该依赖这些具体实现。 推荐: ```text Domain ↓ Interface ↓ Infrastructure ``` 而不是: ```text Domain ↓ Prisma ``` --- # 9. Identity Identity 是用户身份基础设施。 包含: ```text User Account Identity Session ServiceAccount AgentIdentity ``` --- # 10. User User 是 DevOS 全局用户。 用户模型最少包含: ```ts interface User { id: string email?: string username?: string displayName?: string avatarUrl?: string status: UserStatus createdAt: Date updatedAt: Date } ``` 禁止 App 自己创建第二套 User。 --- # 11. Organization DevOS 应默认支持多组织。 结构: ```text User │ ├── Organization A │ └── Organization B ``` Membership: ```ts interface Membership { userId: string organizationId: string roles: string[] status: MembershipStatus } ``` 这使未来可以支持: ```text Personal Workspace Team Company Agency Client Workspace ``` --- # 12. Auth Auth 负责: ```text Authentication Session Login Logout Credential Verification OAuth OIDC API Key ``` Auth 不负责: ```text 业务 Permission SEO Permission Plugin Permission ``` 这些由 Authorization 负责。 --- # 13. Authentication Provider Auth 应采用 Provider 模型: ```text AuthProvider ├── Password ├── OAuth ├── OIDC ├── SSO └── APIKey ``` 统一: ```ts interface AuthProvider { id: string authenticate(input: unknown): Promise revoke(sessionId: string): Promise } ``` 这样未来增加: ```text Google GitHub Microsoft Apple OIDC SAML ``` 不需要修改 Core Auth 主体。 --- # 14. Authorization Authorization 负责: ```text Role Permission Policy Scope Access Check ``` 核心接口: ```ts interface AuthorizationService { check(input: AuthorizationRequest): Promise require(input: AuthorizationRequest): Promise } ``` --- # 15. Role Role 是 Permission 的集合。 例如: ```text Admin Manager Editor Viewer Agent ``` Role 不应该直接绑定具体页面。 错误: ```text Admin -> /settings ``` 正确: ```text Admin ↓ permission ↓ resource.action ``` --- # 16. Permission Permission 格式: ```text . ``` 例如: ```text user.read user.update project.read project.create project.update project.delete ``` App 可以扩展: ```text seo.website.read seo.website.scan seo.website.publish ``` --- # 17. Scope Permission 还必须支持 Scope。 例如: ```text global organization project resource owner ``` 示例: ```text project.update scope = organization ``` 表示用户只能修改当前 Organization 下的 Project。 --- # 18. Resource Resource 是 Core 最重要的抽象之一。 Core 提供: ```text Resource Registry Resource Metadata Resource Reference Resource Permissions Resource Actions ``` 但具体业务 Resource 由 App 注册。 Core 自身只注册: ```text User Organization Role Permission Task Job File ``` --- # 19. Resource Reference 统一 Resource Reference: ```ts interface ResourceRef { type: string id: string } ``` 例如: ```json { "type": "seo.website", "id": "website_123" } ``` 任何系统都可以引用: ```text Task Event Audit Notification Action Agent Workflow ``` --- # 20. Action Action 是 Core 与 Runtime 的连接点。 Core 提供: ```text Action Registry Action Validation Action Authorization Action Execution Context Action Audit Action Event ``` Action 不应该绑定 HTTP。 错误: ```ts scanWebsite(req, res) ``` 正确: ```ts scanWebsite.execute(context, input) ``` HTTP、MCP、Agent、CLI 都调用相同 Action。 --- # 21. Action Context 统一 Action Context: ```ts interface ActionContext { requestId: string executionId: string actor: ActorContext organizationId?: string permissions: string[] metadata?: Record } ``` Actor: ```ts type ActorContext = | UserActor | AgentActor | ServiceActor | SystemActor ``` --- # 22. Event Core 提供 Event Bus。 接口: ```ts interface EventBus { publish(event: DevEvent): Promise subscribe( eventType: string, handler: EventHandler ): Unsubscribe } ``` Event 可以: ```text persist publish subscribe retry replay ``` --- # 23. Event 与 Action Action 成功执行后可以产生 Event。 例如: ```text seo.website.scan ↓ Action ↓ success ↓ seo.website.scan.completed ``` Core 不关心: ```text SEO ``` 它只负责: ```text Action → Event ``` --- # 24. Task Task 是用户可见的工作对象。 例如: ```text Review Article Verify Website Fix Broken Links ``` Task 模型: ```ts interface Task { id: string title: string description?: string status: TaskStatus assigneeId?: string organizationId?: string resource?: ResourceRef createdBy: ActorRef createdAt: Date updatedAt: Date } ``` --- # 25. Job Job 是后台执行单元。 例如: ```text crawl sync embedding report generation ``` Job 与 Task 不等价。 ```text Task = Work Item Job = Execution Unit ``` --- # 26. Job Queue Core 提供 Queue Contract: ```ts interface JobQueue { dispatch( name: string, payload: T, options?: JobOptions ): Promise } ``` Infrastructure 决定实际实现: ```text Redis BullMQ RabbitMQ SQS Database Queue ``` Application 不直接依赖 Queue Provider。 --- # 27. File File 是平台级资源。 统一 File API: ```ts interface FileService { create(input: CreateFileInput): Promise get(id: string): Promise delete(id: string): Promise getUrl(id: string): Promise } ``` App 不直接操作: ```text S3 SDK filesystem R2 SDK ``` --- # 28. Storage Storage Provider: ```text LocalStorage S3Storage R2Storage MinIOStorage ``` 统一接口: ```ts interface StorageProvider { put(input: StoragePutInput): Promise get(key: string): Promise delete(key: string): Promise exists(key: string): Promise } ``` --- # 29. Notification Notification 是 Core Service。 支持: ```text in-app email webhook push ``` 但具体 Provider 属于 Extension。 例如: ```text Email Provider Slack Provider Discord Provider ``` 可以实现为 Plugin。 --- # 30. Audit Audit 是强制能力。 以下操作必须支持 Audit: ```text Authentication Authorization changes Permission changes Sensitive Action Plugin install Plugin enable Plugin disable Settings changes API key creation Agent execution ``` Audit: ```ts interface AuditRecord { id: string actor: ActorRef action: string resource?: ResourceRef result: 'success' | 'failure' metadata?: Record createdAt: Date } ``` --- # 31. Settings Settings 分层: ```text System Organization User App Plugin ``` Key 示例: ```text system.locale organization.timezone user.theme seo.crawler.concurrency plugin.github.token ``` 权限必须作用于 Settings。 --- # 32. Config Config 与 Settings 必须区分。 Config: ```text Environment / Deployment ``` 例如: ```text DATABASE_URL REDIS_URL STORAGE_ENDPOINT ``` Settings: ```text Runtime / User configurable ``` 例如: ```text theme timezone crawler concurrency ``` 禁止把 Secret 全部存入 Settings。 --- # 33. Secret Secret 必须独立处理。 例如: ```text API Keys OAuth Client Secret Webhook Secret Cloud Credentials MCP Credentials ``` 统一: ```ts interface SecretStore { get(key: string): Promise set(key: string, value: string): Promise delete(key: string): Promise } ``` 生产环境优先: ```text Vault Cloud Secret Manager Environment Secret Encrypted Database ``` --- # 34. Search Search 只定义抽象: ```ts interface SearchService { index(input: SearchDocument): Promise search(input: SearchQuery): Promise remove(index: string, id: string): Promise } ``` 可以替换: ```text PostgreSQL Meilisearch OpenSearch Elasticsearch ``` --- # 35. Logging 统一 Logger: ```ts logger.info() logger.warn() logger.error() logger.debug() ``` 必须自动附带: ```text requestId executionId organizationId actorId ``` 如果存在。 --- # 36. Health 统一: ```text /health /health/live /health/ready ``` 检查: ```text Database Redis Storage Queue External Dependencies ``` --- # 37. Error Model 所有 Core / Runtime / App 错误必须遵循统一 Error Contract。 ```ts interface DevError { code: string message: string status?: number details?: unknown cause?: unknown requestId?: string } ``` 例如: ```text AUTH_REQUIRED PERMISSION_DENIED RESOURCE_NOT_FOUND ACTION_NOT_FOUND ACTION_INVALID PLUGIN_NOT_FOUND PLUGIN_DISABLED ``` 禁止每个 App 自定义完全不同的错误格式。 --- # 38. Validation 统一 Schema Validation。 推荐: ```text Zod ``` Action: ```ts inputSchema outputSchema ``` 必须在 Runtime 中验证。 流程: ```text Input ↓ Schema Validation ↓ Authorization ↓ Action ↓ Output Validation ``` --- # 39. API Layer API Layer 不是 Core Business Logic。 它只是 Adapter。 例如: ```text REST Adapter RPC Adapter MCP Adapter CLI Adapter Agent Adapter ``` 全部最终: ```text Adapter ↓ Action Runtime ↓ Core / App ``` --- # 40. Core Dependency Rule 严格规定: ```text Foundation ↑ Domain ↑ Application ↑ Adapters ``` 实际依赖方向: ```text Adapters ↓ Application ↓ Domain ↓ Foundation ``` Infrastructure 通过 Interface 接入。 --- # 41. 禁止依赖 Core 禁止: ```text Core → SEO Core → CRM Core → DevOps Core → Plugin Core → MCP Core → Skill Core → Agent ``` 反过来允许: ```text SEO → Core CRM → Core Plugin → Core MCP → Runtime Skill → Runtime Agent → Runtime ``` --- # 42. 推荐目录结构 最终 Core package: ```text packages/core/ │ ├── src/ │ │ │ ├── foundation/ │ │ ├── types/ │ │ ├── errors/ │ │ ├── ids/ │ │ ├── result/ │ │ └── validation/ │ │ │ ├── identity/ │ │ │ ├── organization/ │ │ │ ├── auth/ │ │ │ ├── authorization/ │ │ │ ├── resource/ │ │ │ ├── action/ │ │ │ ├── event/ │ │ │ ├── task/ │ │ │ ├── job/ │ │ │ ├── file/ │ │ │ ├── storage/ │ │ │ ├── notification/ │ │ │ ├── audit/ │ │ │ ├── settings/ │ │ │ ├── search/ │ │ │ ├── config/ │ │ │ ├── logging/ │ │ │ └── health/ │ ├── package.json └── tsconfig.json ``` --- # 43. Infrastructure Package Infrastructure 独立: ```text packages/infrastructure/ │ ├── postgres/ ├── redis/ ├── storage/ ├── queue/ ├── search/ ├── mail/ ├── secrets/ └── logging/ ``` 这样未来可以替换 Provider。 --- # 44. Repository Pattern 推荐: ```ts interface UserRepository { findById(id: string): Promise findByEmail(email: string): Promise create(user: User): Promise update(user: User): Promise delete(id: string): Promise } ``` PostgreSQL: ```ts class PostgresUserRepository implements UserRepository ``` Domain 不知道 Prisma。 --- # 45. Prisma 使用原则 如果当前 DevOS 使用 Prisma: 可以继续使用。 但: ```text Prisma ``` 属于 Infrastructure。 禁止: ```ts import { PrismaClient } from '@prisma/client' ``` 出现在: ```text Domain Action Definition Plugin SDK Application Business Logic ``` 应该只出现在 Repository / Infrastructure。 --- # 46. Database Boundary 数据库分为: ```text Core Tables App Tables Plugin Tables ``` 逻辑结构: ```text PostgreSQL │ ├── devos_core │ ├── app_seo │ ├── app_devops │ └── plugin_xxx ``` 实际是否使用 PostgreSQL Schema 或 Table Prefix,可以由实现阶段决定。 但是逻辑边界必须存在。 --- # 47. Core Table 原则 Core 表只能存: ```text Platform State ``` 例如: ```text users organizations memberships roles permissions sessions events tasks jobs files audit_logs settings ``` Core 不允许出现: ```text keywords backlinks articles servers deployments orders ``` --- # 48. Dependency Injection Core Service 不应该自己 new Infrastructure。 错误: ```ts const prisma = new PrismaClient() ``` 正确: ```ts class UserService { constructor( private users: UserRepository ) {} } ``` Application Bootstrap 负责组装: ```text Repository ↓ Service ↓ Runtime ``` --- # 49. Bootstrap DevOS 启动过程: ```text Load Config ↓ Initialize Infrastructure ↓ Initialize Core ↓ Register Core Services ↓ Initialize Runtime ↓ Discover Apps ↓ Discover Plugins ↓ Register Extensions ↓ Start HTTP ↓ Start Worker ``` --- # 50. Core Service Registry 需要统一 Service Registry。 例如: ```ts container.register( 'userRepository', userRepository ) container.register( 'authorization', authorizationService ) container.register( 'eventBus', eventBus ) ``` Plugin / App 只能访问公开的 SDK Contract。 不要直接访问 Container 内部实现。 --- # 51. Public API vs Internal API Core API 分两级: ```text Public Internal ``` Public: ```text @devos/core/user @devos/core/resource @devos/core/action @devos/core/events ``` Internal: ```text @devos/core/internal/* ``` Plugin 不得依赖 Internal API。 --- # 52. Versioning Core 必须使用 Semantic Versioning: ```text MAJOR.MINOR.PATCH ``` 例如: ```text 2.0.0 2.1.0 2.1.1 ``` 原则: ```text PATCH Bug Fix MINOR Backward Compatible Feature MAJOR Breaking Change ``` --- # 53. Core API Stability 一旦某个接口进入: ```text Public API ``` 就必须考虑: ```text Backward Compatibility Migration Deprecation Documentation ``` 禁止随意修改。 --- # 54. Extension Contract App / Plugin 只能通过: ```text SDK ``` 使用 DevOS。 例如: ```ts import { defineResource, defineAction, definePlugin } from '@devos/sdk' ``` 而不是: ```ts import { InternalContainer, PrismaClient, InternalEventBus } from '@devos/core/internal' ``` --- # 55. Core 的“瘦身原则” 如果一个能力满足: ```text 只有某个 App 使用 ``` 默认不进入 Core。 如果: ```text 多个 App 都需要 ``` 可以考虑 Runtime / Shared Package。 如果: ```text 几乎所有 App 都需要 ``` 才考虑 Core。 决策: ```text One App ↓ App Several Apps ↓ Shared Package / Runtime Almost Everything ↓ Core ``` --- # 56. Shared Package 与 Core 的区别 不要把所有公共代码都塞入 Core。 例如: ```text @devos/date-utils @devos/http-client @devos/crypto ``` 属于 Shared Libraries。 Core 是: > 平台业务基础能力。 不是: > 所有公共 TypeScript 工具的垃圾桶。 --- # 57. Core Migration Strategy 现有 DevOS 不允许直接“大爆炸重写”。 采用: ```text Current DevOS ↓ Identify Core Candidates ↓ Extract Interfaces ↓ Extract Services ↓ Move Infrastructure ↓ Introduce Runtime ↓ Convert Existing Features ↓ Remove Duplicates ``` --- # 58. Migration Priority 第一批: ```text Auth User Organization Permission Role Settings ``` 第二批: ```text Resource Action Event Task Job ``` 第三批: ```text File Storage Notification Audit Search ``` 第四批: ```text Runtime Plugin MCP Skill Agent ``` --- # 59. 旧代码处理原则 旧代码如果功能正常: 不要立即删除。 先: ```text Wrap Adapter Migrate Deprecate Remove ``` 例如: ```text LegacyPermissionService ↓ PermissionAdapter ↓ AuthorizationService ``` 稳定后再删除 Legacy 实现。 --- # 60. Core Acceptance Criteria Core v2 必须满足: ### A 新 App 可以直接使用: ```text Auth User Organization Permission Settings ``` 无需复制代码。 ### B 新 App 可以注册: ```text Resource Action Event Task ``` ### C Agent / MCP / UI 可以调用相同 Action。 ### D Core 不依赖任何业务 App。 ### E Core 不直接依赖具体数据库 Provider。 ### F Core 不直接依赖具体 Storage Provider。 ### G Plugin 不需要访问 Core Internal API。 ### H 所有敏感操作都可以 Audit。 ### I 所有异步执行都可以进入统一 Job Runtime。 --- # 61. 最终 Core 模型 最终: ```text DevOS Core │ ┌──────────────┬───────┼──────────┬──────────────┐ │ │ │ │ │ Identity Authorization Resource Action Event │ │ │ │ │ └──────────────┴───────┼──────────┴──────────────┘ │ ┌─────────┼─────────┐ │ │ │ Task Job Audit │ │ │ └─────────┼─────────┘ │ Infrastructure │ ┌───────────────┼───────────────┐ │ │ │ PostgreSQL Redis Storage ``` --- # 62. Core 最终职责 DevOS Core 只回答以下问题: ```text Who are you? 你是谁? Where do you belong? 你属于哪个组织? What can you access? 你可以访问什么? What resource exists? 系统里有什么资源? What action can be executed? 可以执行什么操作? Who executed it? 谁执行了它? What happened? 发生了什么? What work is running? 当前有什么工作? Where is the data stored? 数据在哪里? How is the system configured? 系统如何配置? ``` 业务问题交给 App。 --- # 63. 一句话架构原则 DevOS Core 必须做到: > **足够强大,让新 App 不需要重复造基础设施;足够克制,让任何业务都不能污染 Core。** --- # 64. 下一文档 下一份: ```text 03_RESOURCE_ACTION_MODEL.md ``` 将详细定义 DevOS 最核心的: ```text Resource Resource Definition Resource Registry Action Action Definition Action Context Action Permission Action Validation Action Execution Action Result Action Error Action Event Action Audit Action Middleware Action Transaction Action Idempotency Action Retry Action Async Execution ``` 尤其会解决一个非常重要的问题: > **以后 UI、REST API、CLI、MCP、Skill、Agent,到底如何全部调用同一个 Action,而不是重新实现五套业务逻辑。** 这是 DevOS 能不能真正成为“平台”的关键。