Octopus 架构分析
基于代码目录结构、模块依赖、调用链路和门禁检查的架构全景分析。
1. 三层分层架构(Three-Layer Architecture)
Octopus 采用严格的三层单向依赖架构,由 52 个 Gate 门禁编译时强制执行。
┌─────────────────────────────────────────────┐
│ Layer 3: Products (CLI/TUI/Web/Desktop/Mobile) │
│ ↓ 仅依赖 shared + kernel contracts │
├─────────────────────────────────────────────┤
│ Layer 2: products/shared (Server + Adapters) │
│ ↓ 仅依赖 kernel contracts │
├─────────────────────────────────────────────┤
│ Layer 1: kernel (Contracts + Domains + Ports) │
│ ↓ 无外部依赖,纯 Python,零 I/O │
└─────────────────────────────────────────────┘
代码证据
- 层级定义:
ARCHITECTURE_OVERVIEW.md— 单页冻结文档 - 强制执行:
kernel/ops/gates.py—gate_kernel_purity()禁止 kernel 中出现 I/O 相关导入 - 边界规则:
products/shared/docs/PLACEMENT_RULES.md— 三层放置规则 - Capability 包边界:
server/shared/capability_base/gate_validator.py— Gate 6Boundary Clarity禁止包导入 kernel 运行时
gate_kernel_purity 禁止列表
禁止词: system, teams, slack, email, web, ui, bridge, requests, discord, telegram
禁止 I/O 模式: open, subprocess, httpx, requests, urllib, sqlite3, os.environ
禁止框架: fastapi, flask, uvicorn
2. Kernel 内部架构
2.1 Contracts(契约层)— 552 个冻结数据类
所有跨层通信的数据结构均定义为 @dataclass(frozen=True),不可变、可序列化、可比较。
代码位置: kernel/contracts/ — 99 个文件
核心契约族:
| 契约文件 | 冻结类数量 | 覆盖领域 |
|---|---|---|
screen_os.py | 46 | GUI 感知与操作 |
linkage.py | 29 | 计划图与执行连接 |
skill_maturity.py | 15 | 技能成熟度评估 |
capability_family.py | ~10 | 能力族分类 |
semantic_state.py | 8 | 语义状态平面 |
autonomous_ops.py | 13 | 自主运维 |
org_intelligence.py | 10 | 组织智能 |
2.2 Domains(域逻辑层)— 45+ 纯函数模块
无状态、无 I/O 的纯业务逻辑,接收契约输入、返回契约输出。
按职责分组:
AI/认知层 (10 domains)
├── causal_reasoning/ # 因果图推理
├── constraint_solver/ # AC-3 约束求解
├── metacognition/ # 元认知自省
├── perception/ # 多模态感知
├── tool_reasoning/ # 工具组合推理
├── negotiation/ # 多 Agent 协商
├── cerebellum/ # 技能精炼
├── occupational_reasoning/ # 职业推理
├── world_model/ # 世界模型
└── goal_synthesis/ # 目标综合
学习/进化层 (7 domains)
├── capability_learning/ # 15 个子模块(核心学习管线)
├── skill_learning/ # 技能蒸馏
├── capability_evolution/ # 能力进化
├── intent_genesis/ # 意图生成
├── curiosity_engine/ # 好奇心引擎
├── operational_learning/ # 运维学习
└── learning_lab/ # 实验沙盒
知识/记忆层 (6 domains)
├── docset/ # 11 子模块(BM25、分块、混合搜索等)
├── rag/ # 检索增强生成
├── memory/ # 追加式记忆
├── filesystem_knowledge/ # 文件系统图
├── linux_command_kg/ # 命令知识图
└── knowledge_replay/ # 知识回放
运维层 (8 domains)
├── screen_os/ # 29 子模块(GUI 感知与操作)
├── system_tools/ # 系统工具
├── system_governor/ # 系统治理
├── resource_manager/ # 资源管理
├── safe_cleanup/ # 安全清理
├── communication_os/ # 通信路由
├── network_os/ # 网络模型
└── executor_service/ # 执行服务
2.3 Ports(端口层)— 34 个 Protocol 接口
定义所有 I/O 边界的抽象协议,kernel 不实现,由 shared 层注入。
代码位置: kernel/ports/interfaces.py 第 40-191 行
核心端口矩阵:
| 端口类别 | 端口 | Protocol 方法 |
|---|---|---|
| 运行时 | ConfigPort | get(key, default) |
| 运行时 | ClockPort | now_iso(), is_deterministic_source() |
| 运行时 | RandomPort | randint(low, high) |
| 存储 | StatePort | get/put(namespace, key, value) |
| 存储 | MemoryPort | append-only 记忆 |
| 存储 | KnowledgePort | 知识库 CRUD |
| 证据 | EvidenceStorePort | put_manifest/get_manifest |
| 执行 | CommandExecPort | run(argv) |
| 网络 | ApiPort | HTTP 出站 |
| LLM | LLMProviderPort | complete(model, prompt) |
| 感知 | ScreenPort | capture_snapshot(), execute_action() |
| 感知 | VisionPort | 图像分析 |
| 感知 | AudioPort | 音频处理 |
| 安全 | SafetyPort | 安全验证 |
| 安全 | SecretVaultPort | 凭据存取 |
| 协调 | ConsensusPort | 多 Agent 共识 |
REQUIRED_PORTS(46 个必需端口): kernel/ops/gates.py 第 59-118 行
2.4 Runtime(运行时)— Worker Loop + 12 Mixin
代码位置: kernel/runtime/worker_loop.py
class KernelWorkerLoop(
BrainLearningMixin, # _wl_brain_learning.py
CommunicationMixin, # _wl_communication.py
EnterpriseGovMixin, # _wl_enterprise_gov.py
GoalSynthesisMixin, # _wl_goal_synthesis.py
MemoryKbMixin, # _wl_memory_kb.py
LlmRoutingMixin, # _wl_llm_routing.py
ModeDispatchMixin, # _wl_mode_dispatch.py
ResourceOrchestrationMixin, # _wl_resource_orchestration.py
PerceptionMixin, # _wl_perception.py
SafetyMonitoringMixin, # _wl_safety.py
MetacognitionMixin, # _wl_metacognition.py
ToolReasoningMixin, # _wl_tool_reasoning.py
):
pass
Tick 循环输出:
@dataclass(frozen=True)
class TickResult:
processed: int # 本轮处理的队列项
queued: int # 排入下轮的项
dead: int # 死信项
next_wake_ms: int | None # 下次唤醒间隔
3. Server/Shared 层架构
3.1 HTTP 路由(28 模块 × 546 端点)
代码位置: server/shared/adapters/http/routes_core.py 组装所有子路由
| 路由模块 | 前缀 | 端点数 | 核心职责 |
|---|---|---|---|
_routes_health.py | /health, /intent, /runs | ~18 | 健康检查、意图提交 |
_routes_skills.py | /api/skills/* | ~53 | 技能生命周期 |
_routes_analytics.py | /api/self-goal/*, /api/cerebellum/* | ~63 | 认知分析 |
_routes_msp.py | /api/msp/* | ~20 | 告警、工单、SLA |
_routes_capability_registry.py | /api/capability-registry/* | ~14 | 能力注册表 |
_routes_screen_governance.py | /api/screen-governance/* | ~34 | 屏幕治理 |
_routes_cloud.py | /api/cloud/* | ~15 | AWS/Azure 操作 |
_routes_devops.py | /api/dev/* | ~12 | Git/CI/CD |
_routes_finance.py | /api/finance/* | ~10 | 财务管理 |
| 其他 18 个模块 | 各异 | ~307 | 办公、生活、连接器等 |
3.2 Dispatch Router(核心调度器)
代码位置: server/shared/ports_impl/dispatch_router.py — 561 行
三种传输通道:
PlanStep
│
├── SYSTEM 传输 → exec_subprocess.py → CLI/Shell 执行
├── API 传输 → api_caller.py → httpx HTTP 调用
└── INTERNAL 传输 → Python handler 直接调用
调度流程(三阶段):
① Credential Preflight — 检查 {{cred://...}} 引用是否可解析
② Credential Inject — 将密文注入请求参数
③ Execute — 通过对应传输通道执行
④ Normalize — 统一输出格式(tool_name, outputs, error_code, retryable 等)
断路器: 每个 Skill 独立维护 CLOSED → OPEN → HALF_OPEN 状态机。
结果反馈: outcome_sink 回调将执行结果反馈到 Bayesian 信念存储。
3.3 Port 实现矩阵(45+ 适配器)
| 实现文件 | 实现的 Port | 底层技术 |
|---|---|---|
dispatch_router.py | DispatchPort | httpx + subprocess |
secret_vault_sqlite.py | SecretVaultPort | SQLite |
memory_sqlite.py | MemoryPort | SQLite |
knowledge_store_sqlite.py | KnowledgePort | SQLite |
vector_store_faiss.py | VectorStorePort | FAISS |
vector_store_qdrant.py | VectorStorePort | Qdrant |
llm_provider.py | LLMProviderPort | OpenAI SDK |
embedding_local.py | EmbeddingPort | sentence-transformers |
screen_playwright.py | ScreenPort | Playwright |
screen_desktop/ | ScreenPort | pyautogui/UIA |
screen_mobile/ | ScreenPort | Appium |
evidence_fs.py | EvidenceStorePort | 文件系统 |
event_bus_inmem.py | EventSinkPort | 内存 |
file_operations.py | StoragePort | 文件系统 |
exec_subprocess.py | CommandExecPort | subprocess |
4. Capability 生态系统架构
4.1 六层能力架构
代码证据: docs/tranche5/CAPABILITY_ECOSYSTEM_MASTER_MAP.md
L6 产品界面 Chat │ WebUI │ Workflow │ Replay
L5 编排层 Planning │ Dispatch │ Recovery │ Replay
L4 能力层 11 族 × 39 首批包 = 编码、搜索、知识、数据库、浏览器、商业、云、网络、通信、身份、文档
L3 语义状态 8 域: resource │ artifact │ external │ knowledge │ execution │ policy │ evidence │ intent
L2 治理层 Policy │ Quota │ Risk │ Approval │ Audit │ Trace │ Circuit
L1 传输层 Internal │ System │ MCP │ HTTP │ SDK │ Browser │ DB
4.2 Capability 包结构(每包 7 个必须文件)
capability_id/
├── manifest.json # 元数据(family, transport_hints, risk_tier, tools)
├── handler.py # 执行逻辑(继承 BaseHandler)
├── policy.py # 授权策略
├── audit.py # 审计记录
├── quota.py # 配额/限流
├── normalizer.py # 输出标准化
├── state_mapper.py # 语义状态映射
└── tests/
└── test_package.py
4.3 六重门禁验证
代码位置: server/shared/capability_base/gate_validator.py — 250 行
| 门禁 | 检查内容 |
|---|---|
| Gate 1: Package Completeness | 7 个必需文件齐全 |
| Gate 2: Dispatch Compatibility | transport_hints 合法,handler 可导入 |
| Gate 3: Semantic State Outputs | state_outputs 非空,遵循 8 域前缀 |
| Gate 4: Replay Readiness | audit.py 存在,evidence_tags 已声明 |
| Gate 5: Mutation Governance | 写操作需 approval + risk_tier ≥ MEDIUM |
| Gate 6: Boundary Clarity | 不导入 kernel 运行时,仅 contracts.* |
5. Agent 循环架构
生产节点调用链
octopus-planner.timer (每小时触发)
│
▼
Planner → 生成任务 → Redis Queue
│
▼
octopus-worker (持久守护进程)
│
▼
Worker Loop (12 Mixin)
│
├── Intent 解析
├── Plan 生成(PlanGraph)
├── Gate 检查(52 门禁)
├── Capability Grant 授权
├── Dispatch Router 分发
│ ├── SYSTEM → Shell 执行
│ ├── API → httpx 调用
│ └── INTERNAL → Python 处理
├── Evidence 记录
└── Feedback → Bayesian 信念更新
│
▼
Evidence Store (state/evidence/run-{id}/)
├── replay.jsonl
├── manifest.json
└── brain_learning_report.json
systemd 服务矩阵
| 服务 | 端口 | 职责 |
|---|---|---|
| octopus-kernel | :9071 | Kernel 核心 |
| octopus-http | :8000 | HTTP API |
| caddy | :80/:443 | 反向代理 + TLS |
| redis | :6379 | 任务队列 |
| prometheus | :9090 | 指标采集 |
| node-exporter | :9100 | 主机指标 |
| grafana | :3000 | 指标仪表盘 |
| octopus-worker | — | 任务执行守护进程 |
| octopus-planner.timer | — | 定时计划器 |
6. 数据流架构
6.1 Intent → Result 完整链路
用户输入 (CLI/TUI/Web/Mobile)
│
▼ POST /api/intent
HTTP Server (FastAPI)
│
▼ Intent 契约
Kernel Worker Loop
│
├── ① LLM Routing Mixin → 选择模型
├── ② Plan Generation → PlanGraph (DAG)
├── ③ Gate Validation → 52 检查
├── ④ Capability Grant → 授权判定
├── ⑤ Dispatch → 三通道执行
├── ⑥ Result Normalization → 统一输出
├── ⑦ Evidence Recording → 证据链
└── ⑧ Feedback → 信念更新
│
▼ Result 契约
HTTP Response / SSE Stream
│
▼
客户端渲染 (表格/图表/卡片/Markdown)
6.2 Capability 学习链路(6 步管线)
外部源 (GitHub/npm/PyPI/Docker/OpenAPI)
│
▼ ① Ingest
Source Validator → LearningSource 契约
│
▼ ② Classify
Classification Engine → ResourceClassification
│
▼ ③ Extract
Extraction Validator → ExtractedCapability
│
▼ ④ Risk Evaluate
Risk Evaluator → ExternalRiskProfile (分值/等级)
│
▼ ⑤ Verify
Verifier → 沙盒执行验证
│
▼ ⑥ Assimilate
Assimilation Policy → shadow 模式注册
│
▼
Registry (origin=shadow) → Bayesian 监控 → 自动晋升/降级
7. 52 Gate 门禁架构
代码位置: kernel/ops/gates.py — 2000+ 行
门禁分类
| 类别 | 数量 | 核心门禁 |
|---|---|---|
| 架构纯净 | 6 | purity, skeleton, no_io, no_env, determinism, plugin_allowlist |
| API 合规 | 5 | public_api_surface, ports_completeness, domain_skeleton, wave0, wave1 |
| 契约冻结 | 8 | linkage_spec, transport_no_fork, rpc_spec, os_store, freeze_lock |
| 记忆安全 | 8 | append_only, write_audited, revoke_audited, app_isolation |
| 知识合规 | 5 | kb_ref_in_evidence, kb_no_content, observability |
| 域基础 | 15 | 每个核心域的基础验证 |
| 策略容错 | 5 | queue_foundation, cache_audit, version_stability |
运行方式
# 运行全部门禁
python3 -m ops.gates all
# 运行单个门禁
python3 -m ops.gates gate_kernel_purity
8. Role-Based 架构
角色定义模板(5 文件)
代码位置: roles/ — 46+ 角色目录
每个角色由 5 个 YAML 文件定义:
| 文件 | 内容 |
|---|---|
product.yaml | 身份、使命、核心职责、排除范围 |
drives.yaml | 行为驱动(触发器 + 目标) |
metrics.yaml | 质量信号(成功率、延迟、回滚率) |
surfaces.yaml | 可观察/可操作/可学习/禁止列表 |
policies.yaml | 安全红线、自治策略、学习事件日志 |
自治四阶段
observe → experiment → promote → expand
│ │ │ │
│ │ │ └── 扩展到新场景
│ │ └── 验证后提升为标准操作
│ └── 在 shadow 模式实验
└── 仅观察,不行动
架构全景图
┌─────────────────────────────────────────────────────────────┐
│ Product Surfaces │
│ CLI TUI Web Console Desktop Mobile │
│ (argparse) (Textual) (React/Vite) (Tauri) (Expo/RN) │
├─────────────────────────────────────────────────────────────┤
│ HTTP + Auth Layer │
│ FastAPI │ 28 Routes │ 546 Endpoints │ Bearer Token │ SSE │
├─────────────────────────────────────────────────────────────┤
│ Dispatch Router │
│ SYSTEM(CLI) │ API(httpx) │ INTERNAL(Python) │
│ Circuit Breaker │ Credential Inject │ Outcome Sink │
├─────────────────────────────────────────────────────────────┤
│ Capability Ecosystem (L4) │
│ 11 Families │ 61 Packages │ 6 Gates │ Governance Quartet │
├─────────────────────────────────────────────────────────────┤
│ Semantic State (L3) │
│ 8 Domains: resource│artifact│external│knowledge│... │
│ 5 Fact Types: observed│derived│inferred│declared│reconciled │
├─────────────────────────────────────────────────────────────┤
│ Kernel Runtime │
│ Worker Loop │ 12 Mixins │ Queue Engine │ Tick/Wake │
│ 552 Frozen Contracts │ 45+ Pure Domains │ 34 Ports │
├─────────────────────────────────────────────────────────────┤
│ Infrastructure │
│ Redis │ SQLite │ FAISS │ systemd │ Docker │ 58 MCP Servers │
└─────────────────────────────────────────────────────────────┘