Files
devos/Docs/DevOS-Platform-v2/02_CORE_ARCHITECTURE.md — DevOS Core 核心架构.md
phptits b1f17cf637 v2 platform foundation (docs 01/02/03): Action Runtime + Registry + unified API
- v2 foundation: ActionResult/DevError/ActorContext/ResourceRef/Execution types
- ActionRegistry + ResourceRegistry (namespaced types, FAIL FAST on duplicates)
- ActionRuntime pipeline: validate -> authorize -> middleware -> handler ->
  output validation -> audit -> event -> execution persisted (devos_action_executions)
- Legacy bridge: v1 services registered as devops.*/core.* resources & actions (47 actions, 9 resources)
- Unified Action API: POST /api/v2/actions/:actionId, GET discovery (actions/resources)
- 10 v2 unit tests (registry fail-fast, validation, authz, failure audit, events)
2026-09-10 21:09:44 +00:00

23 KiB
Raw Permalink Blame History

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 的设计目标:

Stable
Reusable
Predictable
Secure
Minimal
Business-Agnostic

2. Core 的核心原则

必须遵循:

Core 提供能力,不提供业务。

例如:

允许:

User
Organization
Role
Permission
Resource
Action
Event
Task
Job
File
Storage
Notification
Audit
Settings

禁止:

SEOKeyword
Backlink
CRMLead
Invoice
ProductOrder
Campaign
Article
WebsiteSEOScore

这些属于 Application / Plugin。


3. Core 模块总览

DevOS Core 第一阶段包含:

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:

Auth
User
Organization
Permission
Resource
Action
Event
Task
Job
File
Storage
Notification
Audit
Settings

但不应该出现:

UserNameService
UserAvatarService
UserPreferenceService
UserEmailService

除非存在明确的独立生命周期和依赖边界。


5. Core 分层

Core 内部继续分为:

Foundation
Domain
Application
Infrastructure

结构:

┌─────────────────────────────┐
│        Application          │
│     API / Command / Query   │
├─────────────────────────────┤
│           Domain            │
│ Identity / Auth / Resource  │
├─────────────────────────────┤
│        Foundation           │
│ Types / Errors / Events     │
├─────────────────────────────┤
│       Infrastructure        │
│ DB / Redis / Storage / Queue│
└─────────────────────────────┘

6. Foundation

Foundation 是最底层。

不得依赖:

Application
Plugin
MCP
Agent
具体业务

包含:

types
errors
result
ids
time
events
validation
contracts

例如:

type ID = string

interface Entity {
  id: ID
  createdAt: Date
  updatedAt: Date
}

7. Domain

Domain 定义 Core 的核心对象。

例如:

User
Organization
Role
Permission
Resource
Action
Task
Job
Event
File
Notification
AuditLog

Domain 不直接操作:

PostgreSQL
Redis
S3
HTTP
Filesystem

通过 Repository / Port 抽象访问。


8. Infrastructure

Infrastructure 实现具体技术。

例如:

PostgresUserRepository
RedisEventBus
S3Storage
BullMQJobQueue

Application / Domain 不应该依赖这些具体实现。

推荐:

Domain
   ↓
Interface
   ↓
Infrastructure

而不是:

Domain
   ↓
Prisma

9. Identity

Identity 是用户身份基础设施。

包含:

User
Account
Identity
Session
ServiceAccount
AgentIdentity

10. User

User 是 DevOS 全局用户。

用户模型最少包含:

interface User {
  id: string
  email?: string
  username?: string

  displayName?: string
  avatarUrl?: string

  status: UserStatus

  createdAt: Date
  updatedAt: Date
}

禁止 App 自己创建第二套 User。


11. Organization

DevOS 应默认支持多组织。

结构:

User
 │
 ├── Organization A
 │
 └── Organization B

Membership:

interface Membership {
  userId: string
  organizationId: string

  roles: string[]

  status: MembershipStatus
}

这使未来可以支持:

Personal Workspace
Team
Company
Agency
Client Workspace

12. Auth

Auth 负责:

Authentication
Session
Login
Logout
Credential Verification
OAuth
OIDC
API Key

Auth 不负责:

业务 Permission
SEO Permission
Plugin Permission

这些由 Authorization 负责。


13. Authentication Provider

Auth 应采用 Provider 模型:

AuthProvider
├── Password
├── OAuth
├── OIDC
├── SSO
└── APIKey

统一:

interface AuthProvider {
  id: string

  authenticate(input: unknown): Promise<AuthResult>

  revoke(sessionId: string): Promise<void>
}

这样未来增加:

Google
GitHub
Microsoft
Apple
OIDC
SAML

不需要修改 Core Auth 主体。


14. Authorization

Authorization 负责:

Role
Permission
Policy
Scope
Access Check

核心接口:

interface AuthorizationService {
  check(input: AuthorizationRequest): Promise<boolean>

  require(input: AuthorizationRequest): Promise<void>
}

15. Role

Role 是 Permission 的集合。

例如:

Admin
Manager
Editor
Viewer
Agent

Role 不应该直接绑定具体页面。

错误:

Admin -> /settings

正确:

Admin
 ↓
permission
 ↓
resource.action

16. Permission

Permission 格式:

<resource>.<action>

例如:

user.read
user.update

project.read
project.create
project.update
project.delete

App 可以扩展:

seo.website.read
seo.website.scan
seo.website.publish

17. Scope

Permission 还必须支持 Scope。

例如:

global
organization
project
resource
owner

示例:

project.update
scope = organization

表示用户只能修改当前 Organization 下的 Project。


18. Resource

Resource 是 Core 最重要的抽象之一。

Core 提供:

Resource Registry
Resource Metadata
Resource Reference
Resource Permissions
Resource Actions

但具体业务 Resource 由 App 注册。

Core 自身只注册:

User
Organization
Role
Permission
Task
Job
File

19. Resource Reference

统一 Resource Reference:

interface ResourceRef {
  type: string
  id: string
}

例如:

{
  "type": "seo.website",
  "id": "website_123"
}

任何系统都可以引用:

Task
Event
Audit
Notification
Action
Agent
Workflow

20. Action

Action 是 Core 与 Runtime 的连接点。

Core 提供:

Action Registry
Action Validation
Action Authorization
Action Execution Context
Action Audit
Action Event

Action 不应该绑定 HTTP。

错误:

scanWebsite(req, res)

正确:

scanWebsite.execute(context, input)

HTTP、MCP、Agent、CLI 都调用相同 Action。


21. Action Context

统一 Action Context:

interface ActionContext {
  requestId: string
  executionId: string

  actor: ActorContext

  organizationId?: string

  permissions: string[]

  metadata?: Record<string, unknown>
}

Actor:

type ActorContext =
  | UserActor
  | AgentActor
  | ServiceActor
  | SystemActor

22. Event

Core 提供 Event Bus。

接口:

interface EventBus {
  publish(event: DevEvent): Promise<void>

  subscribe(
    eventType: string,
    handler: EventHandler
  ): Unsubscribe
}

Event 可以:

persist
publish
subscribe
retry
replay

23. Event 与 Action

Action 成功执行后可以产生 Event。

例如:

seo.website.scan
        ↓
Action
        ↓
success
        ↓
seo.website.scan.completed

Core 不关心:

SEO

它只负责:

Action → Event

24. Task

Task 是用户可见的工作对象。

例如:

Review Article
Verify Website
Fix Broken Links

Task 模型:

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 是后台执行单元。

例如:

crawl
sync
embedding
report generation

Job 与 Task 不等价。

Task = Work Item
Job  = Execution Unit

26. Job Queue

Core 提供 Queue Contract:

interface JobQueue {
  dispatch<T>(
    name: string,
    payload: T,
    options?: JobOptions
  ): Promise<JobRef>
}

Infrastructure 决定实际实现:

Redis
BullMQ
RabbitMQ
SQS
Database Queue

Application 不直接依赖 Queue Provider。


27. File

File 是平台级资源。

统一 File API:

interface FileService {
  create(input: CreateFileInput): Promise<FileRef>

  get(id: string): Promise<FileRef>

  delete(id: string): Promise<void>

  getUrl(id: string): Promise<string>
}

App 不直接操作:

S3 SDK
filesystem
R2 SDK

28. Storage

Storage Provider:

LocalStorage
S3Storage
R2Storage
MinIOStorage

统一接口:

interface StorageProvider {
  put(input: StoragePutInput): Promise<StorageObject>
  get(key: string): Promise<ReadableStream>
  delete(key: string): Promise<void>
  exists(key: string): Promise<boolean>
}

29. Notification

Notification 是 Core Service。

支持:

in-app
email
webhook
push

但具体 Provider 属于 Extension。

例如:

Email Provider
Slack Provider
Discord Provider

可以实现为 Plugin。


30. Audit

Audit 是强制能力。

以下操作必须支持 Audit:

Authentication
Authorization changes
Permission changes
Sensitive Action
Plugin install
Plugin enable
Plugin disable
Settings changes
API key creation
Agent execution

Audit:

interface AuditRecord {
  id: string

  actor: ActorRef

  action: string

  resource?: ResourceRef

  result: 'success' | 'failure'

  metadata?: Record<string, unknown>

  createdAt: Date
}

31. Settings

Settings 分层:

System
Organization
User
App
Plugin

Key 示例:

system.locale
organization.timezone
user.theme
seo.crawler.concurrency
plugin.github.token

权限必须作用于 Settings。


32. Config

Config 与 Settings 必须区分。

Config:

Environment / Deployment

例如:

DATABASE_URL
REDIS_URL
STORAGE_ENDPOINT

Settings:

Runtime / User configurable

例如:

theme
timezone
crawler concurrency

禁止把 Secret 全部存入 Settings。


33. Secret

Secret 必须独立处理。

例如:

API Keys
OAuth Client Secret
Webhook Secret
Cloud Credentials
MCP Credentials

统一:

interface SecretStore {
  get(key: string): Promise<string | undefined>

  set(key: string, value: string): Promise<void>

  delete(key: string): Promise<void>
}

生产环境优先:

Vault
Cloud Secret Manager
Environment Secret
Encrypted Database

34. Search

Search 只定义抽象:

interface SearchService {
  index(input: SearchDocument): Promise<void>

  search(input: SearchQuery): Promise<SearchResult>

  remove(index: string, id: string): Promise<void>
}

可以替换:

PostgreSQL
Meilisearch
OpenSearch
Elasticsearch

35. Logging

统一 Logger:

logger.info()
logger.warn()
logger.error()
logger.debug()

必须自动附带:

requestId
executionId
organizationId
actorId

如果存在。


36. Health

统一:

/health
/health/live
/health/ready

检查:

Database
Redis
Storage
Queue
External Dependencies

37. Error Model

所有 Core / Runtime / App 错误必须遵循统一 Error Contract。

interface DevError {
  code: string

  message: string

  status?: number

  details?: unknown

  cause?: unknown

  requestId?: string
}

例如:

AUTH_REQUIRED
PERMISSION_DENIED
RESOURCE_NOT_FOUND
ACTION_NOT_FOUND
ACTION_INVALID
PLUGIN_NOT_FOUND
PLUGIN_DISABLED

禁止每个 App 自定义完全不同的错误格式。


38. Validation

统一 Schema Validation。

推荐:

Zod

Action:

inputSchema
outputSchema

必须在 Runtime 中验证。

流程:

Input
 ↓
Schema Validation
 ↓
Authorization
 ↓
Action
 ↓
Output Validation

39. API Layer

API Layer 不是 Core Business Logic。

它只是 Adapter。

例如:

REST Adapter
RPC Adapter
MCP Adapter
CLI Adapter
Agent Adapter

全部最终:

Adapter
 ↓
Action Runtime
 ↓
Core / App

40. Core Dependency Rule

严格规定:

Foundation
   ↑
Domain
   ↑
Application
   ↑
Adapters

实际依赖方向:

Adapters
   ↓
Application
   ↓
Domain
   ↓
Foundation

Infrastructure 通过 Interface 接入。


41. 禁止依赖

Core 禁止:

Core → SEO
Core → CRM
Core → DevOps
Core → Plugin
Core → MCP
Core → Skill
Core → Agent

反过来允许:

SEO → Core
CRM → Core
Plugin → Core
MCP → Runtime
Skill → Runtime
Agent → Runtime

42. 推荐目录结构

最终 Core package:

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 独立:

packages/infrastructure/
│
├── postgres/
├── redis/
├── storage/
├── queue/
├── search/
├── mail/
├── secrets/
└── logging/

这样未来可以替换 Provider。


44. Repository Pattern

推荐:

interface UserRepository {
  findById(id: string): Promise<User | null>

  findByEmail(email: string): Promise<User | null>

  create(user: User): Promise<User>

  update(user: User): Promise<User>

  delete(id: string): Promise<void>
}

PostgreSQL:

class PostgresUserRepository
  implements UserRepository

Domain 不知道 Prisma。


45. Prisma 使用原则

如果当前 DevOS 使用 Prisma:

可以继续使用。

但:

Prisma

属于 Infrastructure。

禁止:

import { PrismaClient } from '@prisma/client'

出现在:

Domain
Action Definition
Plugin SDK
Application Business Logic

应该只出现在 Repository / Infrastructure。


46. Database Boundary

数据库分为:

Core Tables
App Tables
Plugin Tables

逻辑结构:

PostgreSQL
│
├── devos_core
│
├── app_seo
│
├── app_devops
│
└── plugin_xxx

实际是否使用 PostgreSQL Schema 或 Table Prefix,可以由实现阶段决定。

但是逻辑边界必须存在。


47. Core Table 原则

Core 表只能存:

Platform State

例如:

users
organizations
memberships
roles
permissions
sessions
events
tasks
jobs
files
audit_logs
settings

Core 不允许出现:

keywords
backlinks
articles
servers
deployments
orders

48. Dependency Injection

Core Service 不应该自己 new Infrastructure。

错误:

const prisma = new PrismaClient()

正确:

class UserService {
  constructor(
    private users: UserRepository
  ) {}
}

Application Bootstrap 负责组装:

Repository
 ↓
Service
 ↓
Runtime

49. Bootstrap

DevOS 启动过程:

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。

例如:

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 分两级:

Public
Internal

Public:

@devos/core/user
@devos/core/resource
@devos/core/action
@devos/core/events

Internal:

@devos/core/internal/*

Plugin 不得依赖 Internal API。


52. Versioning

Core 必须使用 Semantic Versioning:

MAJOR.MINOR.PATCH

例如:

2.0.0
2.1.0
2.1.1

原则:

PATCH
Bug Fix

MINOR
Backward Compatible Feature

MAJOR
Breaking Change

53. Core API Stability

一旦某个接口进入:

Public API

就必须考虑:

Backward Compatibility
Migration
Deprecation
Documentation

禁止随意修改。


54. Extension Contract

App / Plugin 只能通过:

SDK

使用 DevOS。

例如:

import {
  defineResource,
  defineAction,
  definePlugin
} from '@devos/sdk'

而不是:

import {
  InternalContainer,
  PrismaClient,
  InternalEventBus
} from '@devos/core/internal'

55. Core 的“瘦身原则”

如果一个能力满足:

只有某个 App 使用

默认不进入 Core。

如果:

多个 App 都需要

可以考虑 Runtime / Shared Package。

如果:

几乎所有 App 都需要

才考虑 Core。

决策:

One App
   ↓
App

Several Apps
   ↓
Shared Package / Runtime

Almost Everything
   ↓
Core

56. Shared Package 与 Core 的区别

不要把所有公共代码都塞入 Core。

例如:

@devos/date-utils
@devos/http-client
@devos/crypto

属于 Shared Libraries。

Core 是:

平台业务基础能力。

不是:

所有公共 TypeScript 工具的垃圾桶。


57. Core Migration Strategy

现有 DevOS 不允许直接“大爆炸重写”。

采用:

Current DevOS
      ↓
Identify Core Candidates
      ↓
Extract Interfaces
      ↓
Extract Services
      ↓
Move Infrastructure
      ↓
Introduce Runtime
      ↓
Convert Existing Features
      ↓
Remove Duplicates

58. Migration Priority

第一批:

Auth
User
Organization
Permission
Role
Settings

第二批:

Resource
Action
Event
Task
Job

第三批:

File
Storage
Notification
Audit
Search

第四批:

Runtime
Plugin
MCP
Skill
Agent

59. 旧代码处理原则

旧代码如果功能正常:

不要立即删除。

先:

Wrap
Adapter
Migrate
Deprecate
Remove

例如:

LegacyPermissionService
        ↓
PermissionAdapter
        ↓
AuthorizationService

稳定后再删除 Legacy 实现。


60. Core Acceptance Criteria

Core v2 必须满足:

A

新 App 可以直接使用:

Auth
User
Organization
Permission
Settings

无需复制代码。

B

新 App 可以注册:

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 模型

最终:

                         DevOS Core
                              │
       ┌──────────────┬───────┼──────────┬──────────────┐
       │              │       │          │              │
    Identity      Authorization Resource Action       Event
       │              │       │          │              │
       └──────────────┴───────┼──────────┴──────────────┘
                              │
                    ┌─────────┼─────────┐
                    │         │         │
                  Task       Job       Audit
                    │         │         │
                    └─────────┼─────────┘
                              │
                     Infrastructure
                              │
              ┌───────────────┼───────────────┐
              │               │               │
          PostgreSQL         Redis          Storage

62. Core 最终职责

DevOS Core 只回答以下问题:

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. 下一文档

下一份:

03_RESOURCE_ACTION_MODEL.md

将详细定义 DevOS 最核心的:

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 能不能真正成为“平台”的关键。