devnomad-byte/holobiont

★ 1Forks 0TypeScriptGitHub ↗Compare

README

Holobiont

多物种竞争与跨尺度信息素路由的群体智能协同编排框架

Production-grade TypeScript implementation of the paper "Multi-Species Competition and Cross-Scale Pheromone Routing for Swarm Intelligence Collaborative Orchestration".

Holobiont 是一个基于生物学约束理论的多智能体编排系统,融合三层自相似信息素路由与多物种达尔文式竞争:以统一的信息素方程在元层(任务类型→物种)、应用层(任务实例→种群实例)、智能体层(子任务→智能体实例)三个尺度上自相似工作,五种仿生算法物种(ACO/ABC/FA/SSO/DBO)在共享信息素协议下通过实际表现争夺任务处理权。


目录


架构概览

┌─────────────────────────────────────────────────────┐
│                    CLI + TUI                         │
│  holobiont run | eval | viz | config                 │
├─────────────────────────────────────────────────────┤
│  eval/              │  firewall/      │  experience/ │
│  Benchmarks         │  Backpressure   │  Dual-trace  │
│  Metrics (SSI)      │  Bulkhead       │  Fossil Rec  │
│  Experiment runner  │  Object Pool    │  Cold-start  │
├─────────────────────────────────────────────────────┤
│  colony/                                              │
│  Queen + Heartbeat + Succession (Σ Q_t election)      │
│  Agent lifecycle: Spawn→Nomad→Die→Precipitate         │
│  Species competition (Algorithm 1, Q/2 tie-break)     │
│  Constraint layer + Cross-scale coupling (Eq 3/4)     │
│  Epigenetic traits (5 traits + θ_low/θ_high)          │
│  Drift monitor + 7 ecological patterns + Lifecycle    │
├─────────────────────────────────────────────────────┤
│  species/                                             │
│  ACO: multi-ant path exploration (4 LLM calls)        │
│  ABC: scout/employed/onlooker (4 calls)               │
│  FA:  brightness attraction (7 calls)                 │
│  SSO: vibration mesh (7 calls)                        │
│  DBO: 5-behavior cycle (5 calls)                      │
├─────────────────────────────────────────────────────┤
│  core/                                                │
│  Pheromone bus (Eq 1) + Equation engine (Eq 1-4)      │
│  ThreeScaleMatrix (meta/app/agent 3-tier τ)           │
│  Provider (Anthropic SDK + custom baseURL for GLM)    │
│  Worker threads bridge + Trace writer                 │
└─────────────────────────────────────────────────────┘

快速开始

环境要求

  • Node.js ≥ 22.0.0(推荐 24.x)
  • pnpm ≥ 9.x
  • Windows / macOS / Linux(开发环境为 Windows 10)

安装

# 1. 克隆代码
git clone https://github.com/devnomad-byte/holobiont holobiont
cd holobiont

# 2. 安装依赖(pnpm workspaces 会自动 link 内部包)
pnpm install

# 3. 构建所有 packages
pnpm build

配置 LLM Provider

复制配置模板并填入你的 API 凭证:

cp experiments/config.example.json experiments/config.json

然后编辑 experiments/config.json:

{
  "runId": "run-YYYY-MM-DD",
  "provider": {
    "baseURL": "https://open.bigmodel.cn/api/anthropic",
    "authToken": "<YOUR_TOKEN>",
    "model": "glm-5.2",
    "maxTokens": 600
  },
  "judge": {
    "baseURL": "https://open.bigmodel.cn/api/anthropic",
    "authToken": "<YOUR_TOKEN>",
    "model": "glm-5.2",
    "maxTokens": 300,
    "panelSize": 3
  },
  "routing": {
    "rho": 0.1,
    "alpha": 1.0,
    "beta": 2.0,
    "initialTau": 0.3,
    "nonNicheTau": 0.1,
    "tauDeltaFactor": 0.3
  }
}

支持的 Provider:本框架通过 Anthropic SDK 调用,任何兼容 Anthropic 协议的端点都可用。只需配置 baseURL + authToken + 对应 provider 文档中列出的模型名。常见选项:

Provider baseURL 示例 model
智谱 BigModel https://open.bigmodel.cn/api/anthropic glm-5.2, glm-4.6, glm-4-flash 等
Anthropic 官方 https://api.anthropic.com claude-sonnet-4-6, claude-opus-4-6 等
DeepSeek https://api.deepseek.com/anthropic deepseek-chat, deepseek-reasoner 等

模型名请查阅对应 provider 的官方文档;本框架不对模型名做校验,遇到 4xx 错误时请核对 provider 文档。

验证安装

# 跑单元测试(不需要 API key)
pnpm test

# 3 任务冒烟(需要 API key)
pnpm experiment:smoke:full

配置

experiments/config.json 完整字段说明:

字段 类型 默认 说明
runId string — 本次运行标识符,结果文件以此为前缀
provider.baseURL string — LLM API 端点
provider.authToken string — API key
provider.model string — 模型名(如 glm-5.2)
provider.maxTokens number 600 单次生成 max tokens
judge.panelSize number 3 Agent-as-a-Judge 裁判数
routing.rho number 0.1 Meta 层蒸发率
routing.alpha number 1.0 Eq 2 信息素指数
routing.beta number 2.0 Eq 2 启发值指数
routing.initialTau number 0.3 生态位匹配物种的初始 τ
routing.nonNicheTau number 0.1 非匹配物种的初始 τ
routing.tauDeltaFactor number 0.3 Eq 1 Δτ 乘数
experiment.interTaskDelayMs number 500 任务间延迟(毫秒)
output.dir string ./results 输出目录

运行实验

完整集成实验(推荐)

# 3 任务冒烟(验证所有机制正常,约 3-5 分钟)
SMOKE=1 npx tsx experiments/holobiont-full.ts

# 全量 40 任务(约 30-40 分钟,消耗约 300-500K tokens)
npx tsx experiments/holobiont-full.ts

这个入口集成所有 §2-§4 机制:三尺度 τ 矩阵、五物种编排、Algorithm 1、表观遗传、蜂后心跳、三防火墙、漂移检测、双痕迹记忆、Colony lifecycle、7 生态交互。

简化实验(仅 Meta 层竞争)

# 3 任务冒烟
SMOKE=1 npx tsx experiments/species-competition.ts

# 全量 40 任务
pnpm experiment

这是早期实现的简化版本,只跑 Meta 层竞争(不含三尺度耦合、表观遗传、防火墙等)。用于快速验证 §4.2 Algorithm 1。

基线对比

# Single-Agent + Random Routing 两个基线
npx tsx experiments/baselines.ts

其他验证脚本

# 三尺度矩阵隔离演示(不调 LLM)
npx tsx experiments/scale-matrix-smoke.ts

# 五物种编排策略单独测试(调真实 LLM)
npx tsx experiments/species-smoke.ts

运行测试

# 所有包的单元测试
pnpm test

# 单独跑某包
pnpm --filter @holobiont/core test
pnpm --filter @holobiont/colony test
pnpm --filter @holobiont/species test
pnpm --filter @holobiont/experience test
pnpm --filter @holobiont/firewall test

# 持续监听模式
pnpm --filter @holobiont/core test:watch

测试覆盖:60+ 单元测试覆盖所有 §2-§4 机制(方程、数据结构、物种编排、表观遗传、选举、漂移、双痕迹、知识体系、生态交互)。


项目结构

holobiont/
├── README.md                    # 本文档
├── package.json                 # workspace 根配置
├── pnpm-workspace.yaml          # pnpm workspace 声明
├── tsconfig.base.json           # 共享 TS 配置(NodeNext, strict)
├── eslint.config.mjs            # Alibaba f2e-spec ESLint 配置
│
├── packages/                    # 7 个 workspace 包
│   ├── core/                    # 基础层:类型、方程、PheromoneBus、Provider
│   │   └── src/
│   │       ├── types.ts         # 品牌 types + PheromoneType/Scale 枚举
│   │       ├── equation-engine.ts  # Eq 1/2/3/4 纯函数
│   │       ├── scale-matrix.ts  # ThreeScaleMatrix 类(三层 τ + 跨尺度耦合)
│   │       ├── pheromone-bus.ts # EventEmitter + Eq 1 衰减
│   │       ├── provider.ts      # Anthropic SDK + 自定义 baseURL
│   │       └── trace.ts         # JSONL trace writer
│   │
│   ├── colony/                  # 编排核心:Queen、生命周期、竞争、表观、漂移
│   │   └── src/
│   │       ├── competition.ts       # Algorithm 1: routeCompetition + depositCompetitionSignals
│   │       ├── queen.ts             # Queen + heartbeat + spawnAgent
│   │       ├── succession.ts        # §4.4 累积适应度选举
│   │       ├── epigenetic-activation.ts  # §4.3 selectTraits + injectTraitPrompts
│   │       ├── drift-monitor.ts     # §4.7 漂移监控
│   │       ├── ecological.ts        # §3 末尾 7 生态模式 + Colony lifecycle
│   │       ├── agent-lifecycle.ts   # Spawn→Nomad→Die→Precipitate
│   │       ├── constraint-layer.ts  # 5 不可变约束
│   │       ├── blueprint.ts         # §4.6 WorkingBlueprint + 5 性状
│   │       ├── message-protocol.ts  # QueenMessage / AgentMessage discriminated union
│   │       └── worker-pool.ts       # worker_threads 池
│   │
│   ├── species/                 # 五物种 LLM 编排策略
│   │   └── src/
│   │       ├── orchestrator.ts      # SpeciesOrchestrator 接口 + 共享类型
│   │       ├── aco/orchestrator.ts  # 多蚂蚁路径(4 calls)
│   │       ├── abc/orchestrator.ts  # 侦察/工蜂/观察(4 calls)
│   │       ├── fa/orchestrator.ts   # 亮度吸引(7 calls)
│   │       ├── sso/orchestrator.ts  # 振动网格(7 calls)
│   │       ├── dbo/orchestrator.ts  # 5 行为循环(5 calls)
│   │       └── registry.ts          # 物种注册表
│   │
│   ├── experience/              # 自演化记忆
│   │   └── src/
│   │       ├── engram-store.ts      # 快痕迹存储
│   │       ├── dual-trace.ts        # §4.7 双痕迹(快 engram + 慢 τ Q-gated)
│   │       ├── cosine-similarity.ts # §4.7 漂移相似度
│   │       ├── cold-start.ts        # 冷启动播种
│   │       ├── consolidation.ts     # Q-gated 固化
│   │       ├── fossil-store.ts      # §4.6 DNA→RNA→Protein→Fossil
│   │       └── checkpoint.ts        # 蜂后继任检查点
│   │
│   ├── firewall/                # 资源管理
│   │   └── src/
│   │       ├── backpressure.ts      # AIMD 背压(θ_high=0.85, θ_low=0.60)
│   │       ├── bulkhead.ts          # 物种配额舱壁
│   │       └── object-pool.ts       # DBO 对象池
│   │
│   ├── cli/                     # Commander.js + Ink TUI(基础骨架)
│   └── eval/                    # 评测工具(基础骨架)
│
└── experiments/                 # 实验脚本(不在 workspace 包内)
    ├── config.example.json      # 配置模板(克隆后复制为 config.json 并填 API key)
    ├── config.json              # 本地配置(已 gitignore,不上传)
    ├── holobiont-full.ts        # ★ 完整集成实验入口(所有 §2-§4 机制)
    ├── species-competition.ts   # 简化实验(仅 §4.2 Algorithm 1)
    ├── baselines.ts             # Single-Agent + Random 基线
    ├── species-smoke.ts         # 5 物种编排策略单独冒烟
    ├── scale-matrix-smoke.ts    # 三尺度矩阵隔离演示
    └── results/                 # 输出目录(按 runId 分子目录)
        └── <runId>-full/
            ├── summary.json     # ★ 论文 §5 数据来源
            ├── trace.jsonl      # 全量 trace(每事件一行)
            ├── quality.json     # 每任务每物种 quality
            ├── tau-meta.json    # Meta 层 τ 矩阵最终态
            ├── tau-app.json     # Application 层
            └── tau-agent.json   # Agent 层

核心概念

三尺度自相似 τ 矩阵(§2)

tauMeta[taskType][species]           // 战略层:物种对任务类型的适配
tauApp[taskInstance][swarmInstance]  // 战术层:种群实例对任务实例的适配
tauAgent[subtask][agentInstance]     // 操作层:智能体实例对子任务的适配

三层使用同一个 Eq 1(τ(t+1) = (1-ρ)·τ(t) + Δτ),仅 ρ 不同:

  • Meta: ρ=0.1(慢,长期战略记忆)
  • App: ρ=0.3(中)
  • Agent: ρ=0.5(快,快速适应当前任务)

跨尺度耦合:

  • Eq 3 自底向上:子层 Δτ 均值聚合到父层(aggregateAgentToApp, aggregateAppToMeta)
  • Eq 4 自顶向下:父层 τ 归一化后偏置子层 η(biasAppEta, biasAgentEta)

五物种 LLM 编排策略(§3)

每个物种用不同方式组织 LLM 调用:

物种 算法 LLM 调用数 生态位
s-aco ACO 多蚂蚁路径 4(3 子任务 + 1 校对) code, security
s-abc ABC 侦察/工蜂/观察 4(1+2+1) data, code
s-fa FA 亮度吸引 7(3 候选 + 1 判 + 2 变种 + 1 最终) design, data
s-sso SSO 振动网格 7(3 r1 + 3 r2 + 1 合并) security, code
s-dbo DBO 5 行为循环 5(滚球/跳舞/觅食/偷窃/繁殖) data, design

Route-then-Orchestrate 模式(默认):Meta 层 Eq 2 先选胜者物种 → 只有胜者的 orchestrate 被调用。

Algorithm 1 多物种竞争路由(§4.2)

Step 1: 信号比例沉积到竞争总线(depositCompetitionSignals)
Step 2: Eq 2 选胜者;若平局 → Q = Q/2(qualityMultiplier = 0.5)
Step 3: 胜者强化 Δτ = Q × multiplier × factor;败者纯蒸发
Step 4: 蜂后生成胜者物种(受背压门控)

表观遗传性状系统(§4.3)

5 性状(colony_deliberation, test_driven_foraging, systematic_pathfinding, colony_review, verification_ritual)按浓度依赖激活:

concentration < θ_low  → 激活度 = 0
concentration > θ_high → 激活度 = 1.0
介于之间                → 线性插值

激活的性状作为 prompt 前缀注入到 system prompt(injectTraitPrompts,固定 1x 不重复)。

蜂后继任协议(§4.4)

  • 心跳:每 5 秒发 queen.alive(浓度=1.0)
  • 空位期:τ(queen.alive) < 0.1 时进入 interregnum
  • 选举:electSuccessor() 按 f(i) = Σ Q_t 排序所有活智能体
  • 兜底:零候选时提升永久身份 queen-emeritus

知识体系(§4.6)

DNA (MasterGenome)  →  RNA (WorkingBlueprint)  →  Protein (AgentProtein)  →  Fossil Record
   设计时固定           spawn 时转录                运行时累积行为             死亡时沉淀

变异(colony-D12):仅 Statary 阶段触发;累积 ≥10 条 Fossil 后,若均值 < 历史 × 0.8 则提议 MutationDelta。


输出文件

每次完整实验写入 experiments/results/<runId>-full/:

summary.json(论文 §5 数据来源)

以下为字段说明(数值为示例,实际值见 experiments/results/run-2026-06-22-glm52-full/summary.json):

{
  "runId": "run-2026-06-22-glm52-full",
  "totals": {
    "tasksRun": 40,
    "generationTokens": 520000,
    "avgTokensPerTask": 13000,
    "avgLatencyMsPerTask": 50000,
    "heartbeatCount": 400,
    "queenKilled": true
  },
  "qualityByType": {
    "code":     { "avg": 0.40, "best": 0.85, "n": 10 },
    "data":     { "avg": 0.45, "best": 0.90, "n": 10 },
    "design":   { "avg": 0.35, "best": 0.75, "n": 10 },
    "security": { "avg": 0.38, "best": 0.80, "n": 10 }
  },
  "ssiByType": { "code": 1.0, "data": 1.0, ... },
  "ssiByTypeExcludingTieBreak": { ... },
  "tieBreakRate": 0.10,
  "earlyTieBreakRate": 1.0,
  "lateTieBreakRate": 0.0,
  "finalTauMeta": { ... },
  "fitnessRecords": [ ... ],
  "fossilCount": 40,
  "lifecyclePhase": "statary"
}

trace.jsonl(全量事件流,~1000+ 行)

每事件一行 JSON,含 seq, ts, runId, taskId, kind, payload。事件种类:

类别 kind
任务 task-start, task-end
路由 meta-routing, signal-deposit
方程 eq1-evaporation, eq3-aggregation, eq4-bias
物种 species-orchestrate
评估 judge-score
蜂后 queen-death-injected, succession-event
表观 trait-activation
防火墙 firewall-backpressure
漂移 drift-check
记忆 engram-write, fossil-record
Lifecycle phase, phase-transition

τ 矩阵文件

  • tau-meta.json — Meta 层(4 任务类型 × 5 物种)
  • tau-app.json — Application 层(任务实例 × 种群实例)
  • tau-agent.json — Agent 层(子任务 × 智能体实例)

quality.json

每行一条评分记录:{ taskId, taskType, species, quality, judges }


论文对应表

论文章节 实现代码
§2.1 元优化方程 Eq 1 packages/core/src/equation-engine.ts:updatePheromone()
§2.1 选择概率 Eq 2 packages/core/src/equation-engine.ts:selectProbability()
§2.3 自底向上 Eq 3 packages/core/src/equation-engine.ts:aggregateDelta() + scale-matrix.ts:aggregateAgentToApp/aggregateAppToMeta
§2.3 自顶向下 Eq 4 packages/core/src/equation-engine.ts:biasHeuristic() + scale-matrix.ts:biasAppEta/biasAgentEta
§2 三尺度 τ 矩阵 packages/core/src/scale-matrix.ts:ThreeScaleMatrix
§3 五物种算法 packages/species/src/{aco,abc,fa,sso,dbo}/orchestrator.ts
§4.1 双层面架构 packages/colony/src/constraint-layer.ts
§4.2 Algorithm 1 packages/colony/src/competition.ts:routeCompetition + depositCompetitionSignals
§4.3 表观遗传性状 packages/colony/src/epigenetic-activation.ts
§4.4 蜂后继任 packages/colony/src/queen.ts + succession.ts
§4.5 三防火墙 packages/firewall/src/{backpressure,bulkhead,object-pool}.ts
§4.6 知识体系 packages/experience/src/fossil-store.ts
§4.7 漂移检测 packages/colony/src/drift-monitor.ts + packages/experience/src/cosine-similarity.ts
§4.7 双痕迹记忆 packages/experience/src/dual-trace.ts
§5 实验 experiments/holobiont-full.ts
§5 SSI 指标 实验脚本内 computeSSI() 函数

故障排查

ERR_PACKAGE_PATH_NOT_EXPORTED

症状:tsx experiments/... 报错 No "exports" main defined in @holobiont/core

原因:workspace 包未正确 link 到根 node_modules。

修复:

pnpm install   # 重新 link

如果根 package.json 缺少 dependencies 字段(旧版本),手动添加:

"dependencies": {
  "@holobiont/core": "workspace:*",
  "@holobiont/colony": "workspace:*",
  "@holobiont/experience": "workspace:*"
}

[1211] 模型不存在 / model not found

症状:API 返回模型不存在错误(HTTP 4xx)

原因:config.json 的 model 字段与 provider 不匹配。

修复:查阅对应 provider 的官方文档,使用其支持的模型名(每家 provider 的命名规则不同,本框架不做模型名校验)。

PROVIDER_API_FAILURE 4xx/5xx

症状:所有 LLM 调用失败

可能原因:

  1. API key 错或过期(检查 config.json:authToken)
  2. 模型名错(见上一条)
  3. baseURL 拼写错误

修复:核对 config.json 三字段(baseURL / authToken / model)与 provider 官方文档一致。provider.ts 会自动对非 api.anthropic.com 端点跳过 thinking: disabled 字段,避免协议不兼容。

单元测试失败

# 单独跑某测试文件查看详情
pnpm --filter @holobiont/colony test -- --run src/__tests__/competition.test.ts

实验运行慢

预期耗时:

  • 3 任务冒烟(SMOKE=1):3-5 分钟
  • 40 任务全量:30-40 分钟

预期 token 消耗:

  • 3 任务:~20K
  • 40 任务:~400-500K

如果明显超出预期,检查:

  1. 是否所有 5 物种都被路由过(不应该一物种独占)
  2. 平局率是否过高(routing 没学到)
  3. 是否触发了故障注入(task 20 后会杀蜂后,选举会消耗时间)

开发指南

代码风格

  • ESLint:eslint-config-ali v16+(Alibaba f2e-spec)
  • Prettier:与 ESLint 集成
  • TypeScript:strict: true,禁用 any
  • 命名:文件 kebab-case(pheromone-bus.ts),类 PascalCase(PheromoneBus),函数/变量 camelCase(emitPheromone),常量 UPPER_SNAKE_CASE(DEFAULT_RHO)
  • 导出函数 必须有 JSDoc(@param + @returns)

添加新物种

  1. 在 packages/species/src/<new-species>/orchestrator.ts 实现 SpeciesOrchestrator 接口
  2. 决定该物种的 LLM 编排模式(X calls,特定 prompt 模式)
  3. 在 packages/species/src/__tests__/<new-species>-orchestrator.test.ts 写 mock provider 测试
  4. 在 packages/species/src/index.ts 导出
  5. 在实验脚本 ORCHESTRATORS 数组加入

相关文档


License

MIT License. See LICENSE.

Citation

@article{qi2026holobiont,
  title={Multi-Species Competition and Cross-Scale Pheromone Routing
         for Swarm Intelligence Collaborative Orchestration},
  author={Qi, Jianchun and Lin, Feng},
  journal={Application Research of Computers},
  year={2026},
  note={Under review}
}

Contributors

devnomad-byte

Issues