Files
Agentswarm/scripts/test-swarm-convergence.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

95 lines
4.1 KiB
Python

"""Integration test for the decentralized-rework P1: convergence wired into run completion (#12).
Boots the in-memory store, drives a run to a terminal state via refresh_swarm_run_status with the
convergence report enabled, and asserts a ConvergenceReport with a termination_reason is stored on
the run (shadow adoption — it does NOT override run.status). 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_CONVERGENCE_REPORT=1 python scripts/test-swarm-convergence.py
"""
import asyncio
import json
import os
import sys
from pathlib import Path
os.environ["REDIS_FAKE"] = "1"
os.environ["ENABLE_CONVERGENCE_REPORT"] = "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, TaskStatus
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 add_task(run, task_id, status, *, cost=0.0, depends_on=None):
t = await task_queue.create_task(task_id=task_id, description=task_id,
agent_role=task_id.split("-")[-1],
depends_on=depends_on or [], enqueue=False)
t.status = status
t.result = json.dumps({"usage": {"model_cost_usd": cost}})
await task_queue._save_task(t)
await swarm_runtime.attach_task(run, t.task_id)
return t
async def main():
await redis_client.connect()
sr_mod.SwarmRuntime._post_callback = _noop
# --- 1. all tasks completed → CONVERGED / tasks_completed ---
body = {"mode": "swarm", "requirement": {"objective": "converge test"},
"callback": {"url": "http://127.0.0.1:9/cb", "subscribed_events": []},
"metadata": {"manager_deployment_id": "m-conv"}}
run, _ = await swarm_runtime.get_or_create_run(body=body, idempotency_key=None, correlation_id="c1")
await add_task(run, "t-implementation", TaskStatus.COMPLETED)
await add_task(run, "t-testing", TaskStatus.COMPLETED, depends_on=["t-implementation"])
await orch.refresh_swarm_run_status(run)
refreshed = await swarm_runtime.get_run(run.swarm_id)
conv = refreshed.metadata.get("convergence")
check("convergence report stored on run", isinstance(conv, dict) and bool(conv))
check("run is completed (shadow: status unchanged by report)", refreshed.status == "completed")
check("status CONVERGED", conv and conv["status"] == "converged")
check("termination_reason = tasks_completed", conv and conv["termination_reason"] == "tasks_completed")
check("consensus 100 (no conflicts)", conv and conv["consensus_score"] == 100.0)
# --- 2. a dependency inconsistency surfaces as a conflict + unresolved risk → BLOCKED ---
body2 = {**body, "metadata": {"manager_deployment_id": "m-conv2"}}
run2, _ = await swarm_runtime.get_or_create_run(body=body2, idempotency_key=None, correlation_id="c2")
# child COMPLETED but its dependency FAILED → dependency_inconsistency
await add_task(run2, "dep-implementation", TaskStatus.FAILED)
await add_task(run2, "child-testing", TaskStatus.COMPLETED, depends_on=["dep-implementation"])
await orch.refresh_swarm_run_status(run2)
r2 = await swarm_runtime.get_run(run2.swarm_id)
conv2 = r2.metadata.get("convergence")
check("conflict detected (dependency inconsistency)",
conv2 and any(c["type"] == "dependency_inconsistency" for c in conv2["conflicts"]))
check("unresolved risk → termination_reason risk_blocked",
conv2 and conv2["termination_reason"] == "risk_blocked")
print()
if failures:
print(f"{len(failures)} convergence-wiring check(s) FAILED: {failures}")
sys.exit(1)
print("all swarm convergence-wiring (P1) checks passed")
if __name__ == "__main__":
asyncio.run(main())