Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix(team): 有 entity 缺 binding 时从 entity 补写 binding

openJiuwen-bot636767adc9c6
diff --git a/jiuwenswarm/server/handlers/team.py b/jiuwenswarm/server/handlers/team.py
index 24bf4cb587..2c32a91a50 100644
--- a/jiuwenswarm/server/handlers/team.py
+++ b/jiuwenswarm/server/handlers/team.py
@@ -56,6 +56,7 @@ def _create_team_binding_from_template(
team_name: str,
template_id: str,
config_base: dict[str, Any],
+ heal: bool = False,
) -> Any:
from jiuwenswarm.agents.harness.team import (
get_team_template_snapshot,
@@ -63,12 +64,36 @@ def _create_team_binding_from_template(
)
from jiuwenswarm.server.runtime.team_binding_store import (
TeamBindingStoreError,
+ ensure_binding_for_entity,
get_team_binding_store,
validate_team_name,
)
from jiuwenswarm.server.runtime.team_entity_store import ensure_team_entity, get_team_entity_store
normalized_name = validate_team_name(team_name)
+ entity_store = get_team_entity_store()
+ binding_store = get_team_binding_store()
+
+ # Upgrade heal (opt-in): entity without binding is otherwise an unrecoverable
+ # dead state. Only explicit create (heal=True) may backfill; generate/auto
+ # create keep CONFLICT so name-allocation retries stay "always new team".
+ if entity_store.exists(normalized_name):
+ existing_binding = binding_store.get(normalized_name)
+ if existing_binding is not None or not heal:
+ raise TeamBindingStoreError("team_name already exists", code="CONFLICT")
+ entity = entity_store.get(normalized_name)
+ if entity is None:
+ raise TeamBindingStoreError("team entity config missing", code="NOT_FOUND")
+ binding = ensure_binding_for_entity(entity, store=binding_store)
+ if binding is None:
+ raise TeamBindingStoreError("team entity config missing", code="NOT_FOUND")
+ logger.info(
+ "[AgentWebSocketServer] healed missing team binding from entity: team_name=%s template_id=%s",
+ binding.team_name,
+ binding.template_id,
+ )
+ return binding
+
template_ids = {
str(item.get("template_id") or "")
for item in list_team_template_summaries(config_base)
@@ -76,11 +101,7 @@ def _create_team_binding_from_template(
if template_id not in template_ids:
raise TeamBindingStoreError("template_id not found", code="NOT_FOUND")
- entity_store = get_team_entity_store()
- if entity_store.exists(normalized_name):
- raise TeamBindingStoreError("team_name already exists", code="CONFLICT")
template_snapshot = get_team_template_snapshot(config_base, template_id=template_id)
- binding_store = get_team_binding_store()
binding = binding_store.create(team_name=normalized_name, template_id=template_id)
try:
entity = ensure_team_entity(
@@ -364,6 +385,7 @@ async def handle_team_binding_create(ctx: RequestContext) -> None:
team_name=team_name,
template_id=template_id,
config_base=config_base,
+ heal=True,
)
resp = AgentResponse(
request_id=request.request_id,
diff --git a/jiuwenswarm/server/runtime/team_binding_store.py b/jiuwenswarm/server/runtime/team_binding_store.py
index 9bd75ddd93..29b1c152e7 100644
--- a/jiuwenswarm/server/runtime/team_binding_store.py
+++ b/jiuwenswarm/server/runtime/team_binding_store.py
@@ -157,6 +157,7 @@ class TeamBindingStore:
template_id: str,
template_snapshot: dict[str, Any] | None = None,
legacy: bool = False,
+ created_at: float | None = None,
) -> TeamBinding:
normalized_name = validate_team_name(team_name)
normalized_template = str(template_id or "").strip()
@@ -164,6 +165,11 @@ class TeamBindingStore:
raise TeamBindingStoreError("template_id is required", code="BAD_REQUEST")
now = time.time()
+ created = (
+ float(created_at)
+ if isinstance(created_at, (int, float)) and float(created_at) > 0
+ else now
+ )
with self._lock:
data = self._read_unlocked()
if normalized_name in data:
@@ -171,7 +177,7 @@ class TeamBindingStore:
binding = TeamBinding(
team_name=normalized_name,
template_id=normalized_template,
- created_at=now,
+ created_at=created,
updated_at=now,
legacy=legacy,
template_snapshot=deepcopy(template_snapshot) if isinstance(template_snapshot, dict) else None,
@@ -325,3 +331,46 @@ def get_team_binding_store() -> TeamBindingStore:
if _DEFAULT_STORE is None:
_DEFAULT_STORE = TeamBindingStore()
return _DEFAULT_STORE
+
+
+def ensure_binding_for_entity(
+ entity: Any,
+ *,
+ store: TeamBindingStore | None = None,
+) -> TeamBinding | None:
+ """Backfill a binding from a persisted team entity when one is missing.
+
+ Heals the upgrade dead-state ``entity ∧ ¬binding``. Session linkage stays
+ empty until ``bind_session``; identity and template come from the entity.
+
+ The written binding is a normal (non-legacy) entry so ``team.bindings.list``
+ can enrich from the existing entity and keep the team selectable.
+ """
+ team_name = str(getattr(entity, "team_name", "") or "").strip()
+ template_id = str(getattr(entity, "template_id", "") or "").strip()
+ if not team_name or not template_id:
+ return None
+
+ binding_store = store or get_team_binding_store()
+ existing = binding_store.get(team_name)
+ if existing is not None:
+ return existing
+
+ template_snapshot = getattr(entity, "template_snapshot", None)
+ created_at = getattr(entity, "created_at", None)
+ try:
+ return binding_store.create(
+ team_name=team_name,
+ template_id=template_id,
+ template_snapshot=(
+ deepcopy(template_snapshot) if isinstance(template_snapshot, dict) else None
+ ),
+ created_at=float(created_at) if isinstance(created_at, (int, float)) else None,
+ )
+ except TeamBindingStoreError as exc:
+ if exc.code != "CONFLICT":
+ raise
+ raced = binding_store.get(team_name)
+ if raced is not None:
+ return raced
+ raise
diff --git a/tests/unit_tests/agentserver/test_agentserver_acp.py b/tests/unit_tests/agentserver/test_agentserver_acp.py
index 6244ba22e5..b0aa702677 100644
--- a/tests/unit_tests/agentserver/test_agentserver_acp.py
+++ b/tests/unit_tests/agentserver/test_agentserver_acp.py
@@ -1236,6 +1236,140 @@ async def test_handle_team_binding_create_persists_team_entity(monkeypatch, tmp_
assert entity.template_snapshot["leader"]["member_name"] == "lead_1"
+async def test_handle_team_binding_create_heals_entity_without_binding(monkeypatch, tmp_path):
+ from jiuwenswarm.server.runtime.team_binding_store import TeamBindingStore
+ from jiuwenswarm.server.runtime.team_entity_store import TeamEntityStore
+
+ server = AgentWebSocketServerHarness()
+ fake_ws = FakeWebSocket()
+ binding_store = TeamBindingStore(tmp_path / "teams" / "bindings.json")
+ entity_store = TeamEntityStore(tmp_path / ".agent_teams")
+ entity_store.write(
+ team_name="oc_team_legacy",
+ template_id="oc_team_legacy",
+ template_snapshot={
+ "team_name": "oc_team_legacy",
+ "leader": {"member_name": "lead"},
+ },
+ created_at=42.0,
+ )
+
+ patch_shared_name(monkeypatch, "get_config", lambda: {"modes": {"team": {}}})
+ patch_shared_name(monkeypatch, "encode_agent_response_for_wire", fake_encode_agent_response_for_wire)
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.team_binding_store.get_team_binding_store",
+ lambda: binding_store,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.team_entity_store.get_team_entity_store",
+ lambda: entity_store,
+ )
+
+ request = AgentRequest(
+ request_id="req-team-binding-heal",
+ channel_id="officeclaw",
+ req_method=ReqMethod.TEAM_BINDING_CREATE,
+ params={"team_name": "oc_team_legacy", "template_id": "oc_team_legacy"},
+ )
+
+ await server.handle_team_binding_create_for_test(fake_ws, request, asyncio.Lock())
+
+ binding = binding_store.get("oc_team_legacy")
+ assert fake_ws.sent[0]["ok"] is True
+ assert binding is not None
+ assert binding.template_id == "oc_team_legacy"
+ assert binding.created_at == 42.0
+ assert binding.legacy is False
+ assert binding.session_ids == ()
+ # Entity must stay intact; heal only backfills binding.
+ entity = entity_store.get("oc_team_legacy")
+ assert entity is not None
+ assert entity.created_at == 42.0
+
+
+def test_create_team_binding_without_heal_conflicts_on_entity_only(monkeypatch, tmp_path):
+ """Generate/auto-create must not adopt a dead-state entity (heal defaults off)."""
+ from jiuwenswarm.server.handlers import team as team_handlers
+ from jiuwenswarm.server.runtime.team_binding_store import (
+ TeamBindingStore,
+ TeamBindingStoreError,
+ )
+ from jiuwenswarm.server.runtime.team_entity_store import TeamEntityStore
+
+ binding_store = TeamBindingStore(tmp_path / "teams" / "bindings.json")
+ entity_store = TeamEntityStore(tmp_path / ".agent_teams")
+ entity_store.write(
+ team_name="semantic_name",
+ template_id="semantic_name",
+ template_snapshot={
+ "team_name": "semantic_name",
+ "leader": {"member_name": "lead"},
+ },
+ created_at=42.0,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.team_binding_store.get_team_binding_store",
+ lambda: binding_store,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.team_entity_store.get_team_entity_store",
+ lambda: entity_store,
+ )
+
+ with pytest.raises(TeamBindingStoreError) as exc_info:
+ team_handlers._create_team_binding_from_template(
+ team_name="semantic_name",
+ template_id="research",
+ config_base={"modes": {"team": {"research": {"team_name": "t"}}}},
+ heal=False,
+ )
+
+ assert exc_info.value.code == "CONFLICT"
+ assert binding_store.get("semantic_name") is None
+
+
+async def test_handle_team_binding_create_still_conflicts_when_binding_exists(monkeypatch, tmp_path):
+ from jiuwenswarm.server.runtime.team_binding_store import TeamBindingStore
+ from jiuwenswarm.server.runtime.team_entity_store import TeamEntityStore
+
+ server = AgentWebSocketServerHarness()
+ fake_ws = FakeWebSocket()
+ binding_store = TeamBindingStore(tmp_path / "teams" / "bindings.json")
+ entity_store = TeamEntityStore(tmp_path / ".agent_teams")
+ entity_store.write(
+ team_name="research_team",
+ template_id="research",
+ template_snapshot={"team_name": "research_team", "leader": {"member_name": "lead"}},
+ created_at=42.0,
+ )
+ binding_store.create(team_name="research_team", template_id="research", created_at=42.0)
+
+ patch_shared_name(monkeypatch, "get_config", lambda: {"modes": {"team": {}}})
+ patch_shared_name(monkeypatch, "encode_agent_response_for_wire", fake_encode_agent_response_for_wire)
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.team_binding_store.get_team_binding_store",
+ lambda: binding_store,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.team_entity_store.get_team_entity_store",
+ lambda: entity_store,
+ )
+
+ request = AgentRequest(
+ request_id="req-team-binding-conflict",
+ channel_id="web",
+ req_method=ReqMethod.TEAM_BINDING_CREATE,
+ params={"team_name": "research_team", "template_id": "research"},
+ )
+
+ await server.handle_team_binding_create_for_test(fake_ws, request, asyncio.Lock())
+
+ assert fake_ws.sent[0]["ok"] is False
+ assert fake_ws.sent[0]["payload"]["code"] == "CONFLICT"
+
+
@pytest.mark.asyncio
async def test_handle_team_binding_create_uses_officeclaw_tenant_catalog(monkeypatch, tmp_path):
from jiuwenswarm.server.runtime.team_binding_store import TeamBindingStore
diff --git a/tests/unit_tests/agentserver/test_team_binding_store.py b/tests/unit_tests/agentserver/test_team_binding_store.py
index 082e3d2253..c1835053ea 100644
--- a/tests/unit_tests/agentserver/test_team_binding_store.py
+++ b/tests/unit_tests/agentserver/test_team_binding_store.py
@@ -6,6 +6,7 @@ from __future__ import annotations
import json
import threading
+from types import SimpleNamespace
import pytest
@@ -13,6 +14,7 @@ from jiuwenswarm.server.runtime import team_binding_store as team_binding_store_
from jiuwenswarm.server.runtime.team_binding_store import (
TeamBindingStore,
TeamBindingStoreError,
+ ensure_binding_for_entity,
)
@@ -217,3 +219,58 @@ def test_team_binding_store_concurrent_create_keeps_valid_json(tmp_path) -> None
assert {binding.team_name for binding in store.list()} == {
f"team_{index}" for index in range(12)
}
+
+
+def test_ensure_binding_for_entity_creates_normal_binding(tmp_path) -> None:
+ store = TeamBindingStore(tmp_path / "bindings.json")
+ entity = SimpleNamespace(
+ team_name="healed_team",
+ template_id="healed_team",
+ created_at=123.0,
+ template_snapshot={"leader": {"member_name": "lead"}},
+ )
+
+ binding = ensure_binding_for_entity(entity, store=store)
+
+ assert binding is not None
+ assert binding.team_name == "healed_team"
+ assert binding.template_id == "healed_team"
+ assert binding.created_at == 123.0
+ assert binding.legacy is False
+ assert binding.session_ids == ()
+ # In-memory create keeps the snapshot; bindings.json intentionally omits it.
+ assert binding.template_snapshot == {"leader": {"member_name": "lead"}}
+ reloaded = store.get("healed_team")
+ assert reloaded is not None
+ assert reloaded.team_name == "healed_team"
+ assert reloaded.template_id == "healed_team"
+ assert reloaded.created_at == 123.0
+ assert reloaded.legacy is False
+ assert reloaded.session_ids == ()
+
+
+def test_ensure_binding_for_entity_is_idempotent(tmp_path) -> None:
+ store = TeamBindingStore(tmp_path / "bindings.json")
+ entity = SimpleNamespace(
+ team_name="healed_team",
+ template_id="healed_team",
+ created_at=123.0,
+ template_snapshot={"leader": {"member_name": "lead"}},
+ )
+ first = ensure_binding_for_entity(entity, store=store)
+ store.bind_session(team_name="healed_team", session_id="sess-a")
+
+ second = ensure_binding_for_entity(entity, store=store)
+
+ assert first is not None
+ assert second is not None
+ assert second.session_ids == ("sess-a",)
+ assert second.template_id == "healed_team"
+
+
+def test_ensure_binding_for_entity_returns_none_without_identity(tmp_path) -> None:
+ store = TeamBindingStore(tmp_path / "bindings.json")
+
+ assert ensure_binding_for_entity(SimpleNamespace(team_name="", template_id="t"), store=store) is None
+ assert ensure_binding_for_entity(SimpleNamespace(team_name="t", template_id=""), store=store) is None
+ assert store.list() == []