Files
Agentswarm/scripts/test-swarm-dispatch.py
T
Songhaoz666andClaude Opus 4.8 f281370209 去中心化蜂群重构:从 Master 中心化切换为播种+自组织(唯一行为)
把本仓从「Master 分解→派发→单评审」重构为去中心化自组织蜂群,并设为唯一行为
(本仓即 swarm 运行时,模式选择在仓外,无 ENABLE_swarm 开关)。依据:heicodeDocs 弱中心
定义 + 蜂群文章(stigmergy)+ OpenAI Swarm(handoff)。

流程(全部无条件生效):
- 播种 build_seed_task_specs(不主控分解)→ 自选 swarm_dispatch(能力+τ+负载+预算,唯一派发)
  → 自主分解 task_proposal(autonomous_tasks)→ 竞争/接管 task_bid/yield/takeover(task_competition)
  → 同伴交叉评审 ≥2 评审者(cross_review,取代单 critic)→ 收敛 ConvergenceReport+termination_reason
  (convergence)→ 守卫 guard.diagnose(检测无法运作并列原因)。

删除:planner 主控分解、贪心/ACO/scored 派发与 scored_matchmake、单 critic 评审环、
全部 ENABLE_* swarm 构建开关。master_agent.synthesize 作为汇总工具保留。

测试:test-workflow-e2e 改写为真实 swarm 全流程;test-merge-smoke 改为 seeder/cross-review;
新增 test-swarm-{seed,dispatch,autonomous,competition,cross-review,convergence,guard} + 模块单测;
CI 同步。本地 18 套全绿。

影响范围:agent_swarm(orchestrator + 新模块 + 测试 + docs + CI)。不改 Manager↔Swarm 事件契约
(新事件均为运行时内部状态/遥测,不进 HM 注册表);不影响 Client/计费/密钥/审计/发布链路。
无新增长期开关。

诚实边界:不动 benchmark 验收(G_E 仍需真实 run,#13);convergence 暂为解释性(不强制覆盖
run.status);前端可见状态为跨端(#18);「去中心化是否更优」未证(需 Group C)。

#6 的 DoD(Path B 决策 + 定位文档)本 PR 已满足并实现 Path B → 关闭 #6。
#7/#8/#11/#12 的运行时机制已落地(事件 + e2e),但其 DoD 含前端可见状态(跨端 #18)与
多 Agent 回放,故以 Refs 链接、不自动关闭,留维护者在前端/验收就绪后关闭。

Closes #6
Refs #7
Refs #8
Refs #11
Refs #12
Refs #18

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-10 16:11:47 +08:00

108 lines
4.5 KiB
Python

"""Integration test for decentralized-rework P6: pheromone-driven agent self-selection.
Each idle agent perceives the eligible ready tasks and self-selects the best fit. With capability
and load equal, the differentiator is the pheromone trail (τ): an agent self-selects the role it
has historically succeeded at. Hermetic, no model key.
Run from agent_swarm_v6 (install deps first — needs fakeredis):
pip install -r orchestrator/requirements.txt -r agent/requirements.txt
REDIS_FAKE=1 ENABLE_SWARM_DISPATCH=1 python scripts/test-swarm-dispatch.py
"""
import asyncio
import os
import sys
from pathlib import Path
os.environ["REDIS_FAKE"] = "1"
os.environ["ENABLE_SWARM_DISPATCH"] = "1"
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from orchestrator.redis_client import redis_client
from orchestrator import swarm_runtime as sr_mod
from orchestrator.swarm_runtime import swarm_runtime
from orchestrator.task_queue import task_queue
from orchestrator.agent_registry import agent_registry
from orchestrator.decision_engine import decision_engine
from orchestrator import main as orch
failures = []
def check(name, cond):
print(("PASS" if cond else "FAIL"), "-", name)
if not cond:
failures.append(name)
async def _noop(self, *a, **k):
return None
async def ready_task(run, role):
t = await task_queue.create_task(task_id=f"{run.swarm_id}-t-{role}", description=role,
agent_role=role, required_capabilities=["python"], enqueue=True)
await swarm_runtime.attach_task(run, t.task_id)
return t
async def fresh_run(label):
body = {"mode": "swarm", "requirement": {"objective": "self-select test"},
"callback": {"url": "http://127.0.0.1:9/cb", "subscribed_events": []},
"metadata": {"manager_deployment_id": label}}
run, _ = await swarm_runtime.get_or_create_run(body=body, idempotency_key=None, correlation_id=label)
return run
async def main():
await redis_client.connect()
sr_mod.SwarmRuntime._post_callback = _noop
# Build pheromone profiles: X strong at implementation, Y strong at testing.
for _ in range(10):
await decision_engine.deposit(agent_role="implementation", agent_id="agent-X", success=True)
await decision_engine.deposit(agent_role="testing", agent_id="agent-X", success=False)
await decision_engine.deposit(agent_role="testing", agent_id="agent-Y", success=True)
await decision_engine.deposit(agent_role="implementation", agent_id="agent-Y", success=False)
# --- Run A: agent-X with BOTH tasks available self-selects its high-τ role (implementation) ---
await agent_registry.register_agent("agent-X", ["python"])
runA = await fresh_run("m-selA")
await ready_task(runA, "implementation")
await ready_task(runA, "testing")
x = next(a for a in await agent_registry.get_idle_agents() if a.agent_id == "agent-X")
assigned_a = await orch.swarm_dispatch([x])
check("agent-X self-selected its high-τ role (implementation)",
assigned_a == [("agent-X", f"{runA.swarm_id}-t-implementation")])
runA_r = await swarm_runtime.get_run(runA.swarm_id)
check("self-selection recorded an explainable dispatch decision",
bool(runA_r.dispatch_decisions)
and runA_r.dispatch_decisions[-1]["chosen_task_id"] == f"{runA.swarm_id}-t-implementation")
# --- Run B: agent-Y with BOTH tasks available self-selects its high-τ role (testing) ---
await agent_registry.register_agent("agent-Y", ["python"])
runB = await fresh_run("m-selB")
await ready_task(runB, "implementation")
await ready_task(runB, "testing")
y = next(a for a in await agent_registry.get_idle_agents() if a.agent_id == "agent-Y")
assigned_b = await orch.swarm_dispatch([y])
check("agent-Y self-selected its high-τ role (testing)",
assigned_b == [("agent-Y", f"{runB.swarm_id}-t-testing")])
# --- capability gate still holds: an agent lacking caps self-selects nothing ---
await agent_registry.register_agent("agent-Z", ["rust"])
runC = await fresh_run("m-selC")
await ready_task(runC, "implementation") # requires python
z = next(a for a in await agent_registry.get_idle_agents() if a.agent_id == "agent-Z")
assigned_c = await orch.swarm_dispatch([z])
check("incapable agent self-selects nothing", assigned_c == [])
print()
if failures:
print(f"{len(failures)} self-selection (P6) check(s) FAILED: {failures}")
sys.exit(1)
print("all swarm self-selection (P6) checks passed")
if __name__ == "__main__":
asyncio.run(main())