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: 团队技能链接同步移出事件循环,原生 junction 替代 mklink 子进程

ZhouRZa8b29e468a5f
diff --git a/jiuwenswarm/agents/harness/team/team_manager.py b/jiuwenswarm/agents/harness/team/team_manager.py
index 949291572a..315afe46b7 100644
--- a/jiuwenswarm/agents/harness/team/team_manager.py
+++ b/jiuwenswarm/agents/harness/team/team_manager.py
@@ -56,7 +56,7 @@ from jiuwenswarm.agents.harness.team.distributed_runtime import (
from jiuwenswarm.agents.harness.team.handlers.team_monitor_handler import TeamMonitorHandler
from jiuwenswarm.agents.harness.team import kv_cache_hooks
from jiuwenswarm.agents.harness.team.remote_member_bootstrap import release_a2x_reservations_for_session
-from jiuwenswarm.agents.harness.team.team_skill_links import sync_skill_dir_links
+from jiuwenswarm.agents.harness.team.team_skill_links import offload_link_sync, sync_skill_dir_links
from jiuwenswarm.common.config import (
get_config,
get_default_models,
@@ -1342,8 +1342,17 @@ class TeamManager:
)
@staticmethod
- def _initialize_team_shared_skill_links(spec: TeamAgentSpec) -> None:
- """Initialize team shared skill links from the global skill root."""
+ async def _initialize_team_shared_skill_links(spec: TeamAgentSpec) -> None:
+ """Initialize team shared skill links from the global skill root.
+
+ The sync is filesystem-heavy - one lstat per global skill entry plus one
+ link creation per new skill - and runs once per team on the first
+ request. It must not run inline on the event loop: on 2026-09-18 a
+ machine where each ``cmd.exe`` junction creation cost about a second
+ stalled the loop for 268s (BUG20260918365771). It also must complete
+ before the first team turn starts, so callers await it rather than
+ fire-and-forget.
+ """
global_skills_dir = get_agent_skills_dir()
if not global_skills_dir.exists():
logger.warning("[TeamManager] global_skills_dir does not exist: %s", global_skills_dir)
@@ -1357,8 +1366,11 @@ class TeamManager:
team_shared_skills_dir = Path(ws_path) / "skills"
- team_shared_skills_dir.mkdir(parents=True, exist_ok=True)
- sync_skill_dir_links(global_skills_dir, team_shared_skills_dir)
+ def _sync() -> None:
+ team_shared_skills_dir.mkdir(parents=True, exist_ok=True)
+ sync_skill_dir_links(global_skills_dir, team_shared_skills_dir)
+
+ await asyncio.to_thread(_sync)
logger.info("[TeamManager] Initialized team shared skill links: %s", team_shared_skills_dir)
@@ -1371,13 +1383,13 @@ class TeamManager:
return Path(ws_path) / "skills"
@staticmethod
- def ensure_team_shared_skills_initialized(spec: TeamAgentSpec) -> None:
+ async def ensure_team_shared_skills_initialized(spec: TeamAgentSpec) -> None:
"""Ensure team shared skills are available in the team workspace."""
- TeamManager._initialize_team_shared_skill_links(spec)
+ await TeamManager._initialize_team_shared_skill_links(spec)
- def ensure_team_shared_skills_ready_for_session(self, session_id: str, spec: TeamAgentSpec) -> None:
+ async def ensure_team_shared_skills_ready_for_session(self, session_id: str, spec: TeamAgentSpec) -> None:
"""Ensure team shared skills are initialized and registered for refresh."""
- self.ensure_team_shared_skills_initialized(spec)
+ await self.ensure_team_shared_skills_initialized(spec)
self.register_team_shared_skill_link_target(
session_id,
self._resolve_team_shared_skills_dir(spec),
@@ -1388,7 +1400,12 @@ class TeamManager:
self._team_shared_skill_link_targets[session_id] = target
def refresh_team_shared_skill_links(self, session_id: str) -> bool:
- """Refresh team shared skill links from global skills."""
+ """Refresh team shared skill links from global skills.
+
+ The sync is offloaded to a worker thread when this runs on the event
+ loop (rail refresh callbacks are sync callables invoked there); see
+ ``offload_link_sync``.
+ """
target = self._team_shared_skill_link_targets.get(session_id)
if target is None:
logger.debug("[TeamManager] no team shared skill link target for session_id=%s", session_id)
@@ -1397,7 +1414,7 @@ class TeamManager:
if not global_skills_dir.exists():
logger.warning("[TeamManager] global_skills_dir does not exist: %s", global_skills_dir)
return False
- sync_skill_dir_links(global_skills_dir, target)
+ offload_link_sync(global_skills_dir, target)
logger.info("[TeamManager] Refreshed team shared skill links: session_id=%s target=%s", session_id, target)
return True
@@ -1463,7 +1480,7 @@ class TeamManager:
team_agent.channel_id = bootstrap.channel_id # 记录 channel,供 _destroy_other_sessions 按 channel 隔离
self._team_agents[session_id] = team_agent
# After build, initialize team shared skill links.
- self.ensure_team_shared_skills_ready_for_session(session_id, spec)
+ await self.ensure_team_shared_skills_ready_for_session(session_id, spec)
if self._is_distributed_mode(config_base):
try:
diff --git a/jiuwenswarm/agents/harness/team/team_skill_links.py b/jiuwenswarm/agents/harness/team/team_skill_links.py
index 04ef779bf5..ddd36fbc44 100644
--- a/jiuwenswarm/agents/harness/team/team_skill_links.py
+++ b/jiuwenswarm/agents/harness/team/team_skill_links.py
@@ -4,6 +4,7 @@
from __future__ import annotations
+import asyncio
import logging
import os
import shutil
@@ -21,6 +22,11 @@ except ImportError: # pragma: no cover - unavailable outside Windows
else:
ERROR_PRIVILEGE_NOT_HELD = winerror.ERROR_PRIVILEGE_NOT_HELD
+try:
+ import _winapi
+except ImportError: # pragma: no cover - Windows-only builtin module
+ _winapi = None
+
def is_valid_skill_dir(path: Path) -> bool:
"""Return whether the path points to a valid skill directory."""
@@ -158,7 +164,30 @@ def _copy_skill_directory(target_path: Path, link_path: Path) -> None:
def _create_windows_junction(target_path: Path, link_path: Path) -> None:
- """Create a directory junction using ``mklink /J`` on Windows."""
+ """Create a directory junction on Windows.
+
+ Prefers the native ``_winapi.CreateJunction``: no subprocess, sub-millisecond
+ per link, and immune to localized ``cmd.exe`` output encoding. The 2026-09-18
+ incident stalled an event loop for 268s because 273 junctions were created
+ serially through ``cmd.exe`` (about 1s of process-creation overhead each on
+ that machine), and the same call crashed a subprocess reader thread with
+ ``UnicodeDecodeError`` on Chinese Windows (GBK output vs UTF-8 decoding).
+
+ The ``cmd.exe /c mklink /J`` fallback only runs when the private API is
+ unavailable or rejected the creation. Its output is decoded with the ANSI
+ code page (``mbcs``) and undecodable bytes are replaced, so localized output
+ can neither crash the reader thread nor raise while decoding.
+ """
+ create_junction = getattr(_winapi, "CreateJunction", None) if _winapi is not None else None
+ if create_junction is not None:
+ try:
+ create_junction(str(target_path), str(link_path))
+ return
+ except OSError:
+ if path_exists_or_link(link_path):
+ raise
+ # Fall through to cmd.exe, which reports a descriptive error for
+ # cases the native call rejected (e.g. a missing target).
cmd_path = os.path.join(
os.environ.get("SystemRoot", r"C:\Windows"),
"System32",
@@ -167,10 +196,41 @@ def _create_windows_junction(target_path: Path, link_path: Path) -> None:
result = subprocess.run(
[cmd_path, "/c", "mklink", "/J", str(link_path), str(target_path)],
capture_output=True,
- text=True,
check=False,
shell=False,
+ encoding="mbcs" if sys.platform == "win32" else "utf-8",
+ errors="replace",
)
if result.returncode != 0:
error_output = result.stderr.strip() or result.stdout.strip()
raise OSError(f"Failed to create junction {link_path} -> {target_path}: {error_output}")
+
+
+def offload_link_sync(source: Path, target: Path) -> object | None:
+ """Sync skill links without blocking a running event loop.
+
+ Link sync is filesystem-heavy: one lstat per source entry plus one link
+ creation per new skill. Sync refresh callbacks (rail hooks, tool hooks)
+ are invoked on the event loop thread, where running inline would stall the
+ loop - the 2026-09-18 incident stalled one for 268s this way. When a loop
+ is running on the calling thread the sync is scheduled on the default
+ executor and the executor future is returned (callers may await it;
+ failures are logged via a done callback). On threads without a running
+ loop the sync runs inline and None is returned, preserving synchronous
+ completion semantics.
+ """
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError:
+ sync_skill_dir_links(source, target)
+ return None
+
+ pending = loop.run_in_executor(None, sync_skill_dir_links, source, target)
+
+ def _log_failure(fut: object) -> None:
+ exc = getattr(fut, "exception", lambda: None)()
+ if exc is not None:
+ logger.error("[TeamSkillLinks] offloaded skill link sync failed: %s", exc)
+
+ pending.add_done_callback(_log_failure)
+ return pending
diff --git a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py
index 4e23990c6b..77ca183949 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py
@@ -5,6 +5,7 @@
from __future__ import annotations
import asyncio
+import inspect
import logging
import os
import re
@@ -2027,7 +2028,13 @@ async def process_team_message_stream(
ensure_ready = getattr(team_manager, "ensure_team_shared_skills_ready_for_session", None)
shared_skills_ready_prepared = False
if is_first_request and callable(ensure_ready):
- ensure_ready(session_id, team_spec)
+ # The manager is a duck-typed extension point: implementations may be
+ # sync (older/embedded variants) or async (the link sync now runs via
+ # asyncio.to_thread so it cannot stall the loop - BUG20260918365771).
+ # Support both signatures here.
+ ensure_ready_result = ensure_ready(session_id, team_spec)
+ if inspect.isawaitable(ensure_ready_result):
+ await ensure_ready_result
shared_skills_ready_prepared = True
slash_result = await _handle_team_slash_command(
@@ -2351,7 +2358,9 @@ async def process_team_message_stream(
if is_first_request:
if callable(ensure_ready) and not shared_skills_ready_prepared:
- ensure_ready(session_id, team_spec)
+ ensure_ready_result = ensure_ready(session_id, team_spec)
+ if inspect.isawaitable(ensure_ready_result):
+ await ensure_ready_result
shared_skills_ready_prepared = True
request_queue = await _start_team_stream_round(
channel_id=channel_id,
diff --git a/tests/unit_tests/agentserver/test_team_manager_registry.py b/tests/unit_tests/agentserver/test_team_manager_registry.py
index 497b3a56e7..46c49d87e3 100644
--- a/tests/unit_tests/agentserver/test_team_manager_registry.py
+++ b/tests/unit_tests/agentserver/test_team_manager_registry.py
@@ -429,10 +429,13 @@ async def test_team_manager_keeps_single_session_per_channel(monkeypatch: pytest
monkeypatch.setattr(TeamManager, "_load_team_spec", staticmethod(fake_load_team_spec))
# Mock _initialize_team_shared_skill_links to avoid file operations
+ async def _noop_init_links(_spec):
+ return None
+
monkeypatch.setattr(
TeamManager,
"_initialize_team_shared_skill_links",
- staticmethod(lambda spec: None),
+ staticmethod(_noop_init_links),
)
# Provider assembly is covered by the swarm suite; stub it so this
# session-management test runs on the minimal fake spec.
@@ -486,10 +489,13 @@ async def test_create_team_does_not_run_global_runtime_cleanup(monkeypatch: pyte
monkeypatch.setattr(TeamManager, "_load_team_spec", staticmethod(fake_load_team_spec))
# Mock _initialize_team_shared_skill_links to avoid file operations
+ async def _noop_init_links(_spec):
+ return None
+
monkeypatch.setattr(
TeamManager,
"_initialize_team_shared_skill_links",
- staticmethod(lambda spec: None),
+ staticmethod(_noop_init_links),
)
# Provider assembly is covered by the swarm suite; stub it so this
# session-management test runs on the minimal fake spec.
@@ -526,10 +532,13 @@ async def test_create_team_appends_session_id_to_team_name(monkeypatch: pytest.M
return SimpleNamespace()
monkeypatch.setattr(TeamManager, "_load_team_spec", staticmethod(lambda _session_id: _Spec()))
+ async def _noop_init_links(_spec):
+ return None
+
monkeypatch.setattr(
TeamManager,
"_initialize_team_shared_skill_links",
- staticmethod(lambda spec: None),
+ staticmethod(_noop_init_links),
)
# Provider assembly is covered by the swarm suite; stub it so this
# session-management test runs on the minimal fake spec.
@@ -565,11 +574,14 @@ async def test_create_team_appends_session_id_to_web_team_name(monkeypatch: pyte
created_team_names.append(self.team_name)
return SimpleNamespace()
+ async def _noop_init_links(_spec):
+ return None
+
monkeypatch.setattr(TeamManager, "_load_team_spec", staticmethod(lambda _session_id: _Spec()))
monkeypatch.setattr(
TeamManager,
"_initialize_team_shared_skill_links",
- staticmethod(lambda spec: None),
+ staticmethod(_noop_init_links),
)
# Provider assembly is covered by the swarm suite; stub it so this
# session-management test runs on the minimal fake spec.
@@ -2057,10 +2069,13 @@ async def test_create_team_passes_sessions_root_to_load_session_team_spec(
"jiuwenswarm.common.config.get_config",
lambda: {},
)
+ async def _noop_ensure_ready(self, session_id, spec):
+ return None
+
monkeypatch.setattr(
TeamManager,
"ensure_team_shared_skills_ready_for_session",
- lambda self, session_id, spec: None,
+ _noop_ensure_ready,
)
monkeypatch.setattr(
TeamManager,
diff --git a/tests/unit_tests/agentserver/test_team_shared_skills.py b/tests/unit_tests/agentserver/test_team_shared_skills.py
index cbb712f74a..0872158dfd 100644
--- a/tests/unit_tests/agentserver/test_team_shared_skills.py
+++ b/tests/unit_tests/agentserver/test_team_shared_skills.py
@@ -25,7 +25,24 @@ def _assert_link_points_to(path: Path, target: Path) -> None:
assert path.resolve() == target.resolve()
-def test_ensure_team_shared_skills_initialized_links_global_skills(tmp_path, monkeypatch):
+def inline_link_sync(monkeypatch):
+ """Run link sync inline even inside a running loop, for deterministic tests.
+
+ Production offloads the sync to a worker thread when called on the event
+ loop (BUG20260918365771); asserting immediately after a refresh call would
+ then race the executor thread.
+ """
+ from jiuwenswarm.agents.harness.team import team_skill_links
+
+ monkeypatch.setattr(
+ "jiuwenswarm.agents.harness.team.team_manager.offload_link_sync",
+ lambda source, target: team_skill_links.sync_skill_dir_links(source, target),
+ )
+
+
+async def test_ensure_team_shared_skills_initialized_links_global_skills(tmp_path, monkeypatch):
"""Global skills should be linked to team shared directory via the public helper."""
# Create global skills directory
global_skills_dir = tmp_path / "global_skills"
@@ -58,7 +75,7 @@ def test_ensure_team_shared_skills_initialized_links_global_skills(tmp_path, mon
)
manager = TeamManager()
- manager.ensure_team_shared_skills_initialized(spec)
+ await manager.ensure_team_shared_skills_initialized(spec)
# The skills root stays a normal directory; individual skills are linked.
assert team_shared_skills.is_dir()
@@ -68,7 +85,8 @@ def test_ensure_team_shared_skills_initialized_links_global_skills(tmp_path, mon
assert not (team_shared_skills / "skills_state.json").exists()
-def test_existing_skill_entry_is_not_replaced(tmp_path, monkeypatch):
+async def test_existing_skill_entry_is_not_replaced(tmp_path, monkeypatch):
"""Existing skill entries should be left untouched."""
global_skills_dir = tmp_path / "global_skills"
global_skills_dir.mkdir(parents=True)
@@ -97,7 +115,7 @@ def test_existing_skill_entry_is_not_replaced(tmp_path, monkeypatch):
)
manager = TeamManager()
- manager.ensure_team_shared_skills_initialized(spec)
+ await manager.ensure_team_shared_skills_initialized(spec)
assert (team_shared_skills / "skill-a").resolve() == existing_skill.resolve()
assert "existing-skill-a" in (team_shared_skills / "skill-a" / "SKILL.md").read_text(encoding="utf-8")
@@ -131,7 +149,8 @@ def test_refresh_team_shared_skill_links_adds_new_global_skill(tmp_path, monkeyp
_assert_link_points_to(team_shared_skills / "skill-b", skill_b)
-def test_ensure_team_shared_skills_ready_for_session_registers_refresh_target(tmp_path, monkeypatch):
+async def test_ensure_team_shared_skills_ready_for_session_registers_refresh_target(tmp_path, monkeypatch, inline_link_sync):
"""Session readiness should initialize links and register the refresh target."""
global_skills_dir = tmp_path / "global_skills"
global_skills_dir.mkdir(parents=True)
@@ -154,7 +173,7 @@ def test_ensure_team_shared_skills_ready_for_session_registers_refresh_target(tm
)
manager = TeamManager()
- manager.ensure_team_shared_skills_ready_for_session("sess-1", spec)
+ await manager.ensure_team_shared_skills_ready_for_session("sess-1", spec)
team_shared_skills = team_workspace / "skills"
_assert_link_points_to(team_shared_skills / "skill-a", skill_a)
diff --git a/tests/unit_tests/agentserver/test_team_skill_links.py b/tests/unit_tests/agentserver/test_team_skill_links.py
new file mode 100644
index 0000000000..2ef21ecd9a
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_team_skill_links.py
@@ -0,0 +1,225 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Unit tests for team skill link creation and event-loop-safe offloading."""
+
+# pylint: disable=protected-access
+
+import asyncio
+import contextlib
+import os
+import stat
+import sys
+from pathlib import Path
+
+import pytest
+
+from jiuwenswarm.agents.harness.team import team_skill_links
+from jiuwenswarm.agents.harness.team.team_skill_links import (
+ _create_windows_junction,
+ ensure_skill_dir_links,
+ link_skill_dir,
+ offload_link_sync,
+)
+
+
+def _make_skill(root: Path, name: str) -> Path:
+ skill_dir = root / name
+ skill_dir.mkdir(parents=True)
+ (skill_dir / "SKILL.md").write_text(f"---\nname: {name}\n---\n", encoding="utf-8")
+ return skill_dir
+
+
+def _assert_link_resolves(link: Path, target: Path) -> None:
+ """Assert the link exists and resolves to the expected target.
+
+ On Windows ``link_skill_dir`` produces a junction (reparse point); on
+ other platforms it falls through to a plain ``os.symlink`` symlink, so
+ the shape assertion is platform-specific while the resolution assertion
+ is shared.
+ """
+ assert os.path.lexists(link)
+ if sys.platform == "win32":
+ attributes = os.lstat(link).st_file_attributes
+ assert attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT
+ else:
+ assert os.path.islink(link)
+ assert link.resolve() == target.resolve()
+
+
+_winapi_create_junction = getattr(getattr(team_skill_links, "_winapi", None), "CreateJunction", None)
+
+requires_native_create_junction = pytest.mark.skipif(
+ sys.platform != "win32" or _winapi_create_junction is None,
+ reason="requires _winapi.CreateJunction on Windows",
+)
+requires_windows = pytest.mark.skipif(sys.platform != "win32", reason="Windows junctions")
+
+
+@requires_native_create_junction
+def test_create_windows_junction_native_avoids_subprocess(tmp_path, monkeypatch):
+ """The native path creates a reparse-point junction without spawning cmd.exe."""
+ spawned = []
+
+ original_run = team_skill_links.subprocess.run
+
+ def _spy_run(*args, **kwargs):
+ spawned.append(args)
+ return original_run(*args, **kwargs)
+
+ monkeypatch.setattr(team_skill_links.subprocess, "run", _spy_run)
+ target = _make_skill(tmp_path, "skill-a")
+ link = tmp_path / "link"
+
+ _create_windows_junction(target, link)
+
+ _assert_link_resolves(link, target)
+ assert not spawned, "native junction creation must not spawn cmd.exe"
+
+
+@requires_windows
+def test_cmd_fallback_creates_junction_when_winapi_unavailable(tmp_path, monkeypatch):
+ """Without the private API the cmd.exe fallback still creates a working junction."""
+ monkeypatch.setattr(team_skill_links, "_winapi", None)
+ target = _make_skill(tmp_path, "skill-a")
+ link = tmp_path / "link"
+
+ _create_windows_junction(target, link)
+
+ _assert_link_resolves(link, target)
+
+
+def test_cmd_fallback_passes_decoding_options(monkeypatch, tmp_path):
+ """The fallback decodes localized cmd.exe output instead of crashing (9-18 incident)."""
+ captured = {}
+
+ def _fake_run(cmd, **kwargs):
+ captured["cmd"] = cmd
+ captured["kwargs"] = kwargs
+ return type(
+ "_Completed",
+ (),
+ {"returncode": 0, "stdout": "创建的联接", "stderr": ""},
+ )()
+
+ monkeypatch.setattr(team_skill_links, "_winapi", None)
+ monkeypatch.setattr(team_skill_links.subprocess, "run", _fake_run)
+ target = _make_skill(tmp_path, "skill-a")
+ link = tmp_path / "link"
+
+ _create_windows_junction(target, link)
+
+ assert captured["kwargs"]["errors"] == "replace"
+ assert captured["kwargs"]["capture_output"] is True
+ if sys.platform == "win32":
+ assert captured["kwargs"]["encoding"] == "mbcs"
+ else:
+ assert captured["kwargs"]["encoding"] == "utf-8"
+ assert captured["cmd"][1:3] == ["/c", "mklink"]
+
+
+def test_cmd_failure_raises_oserror_not_decode_error(monkeypatch, tmp_path):
+ """A failing localized mklink raises OSError with readable text, never UnicodeDecodeError."""
+ localized_error = "系统找不到指定的文件。"
+
+ def _fake_run(cmd, **kwargs):
+ return type(
+ "_Completed",
+ (),
+ {"returncode": 1, "stdout": "", "stderr": localized_error},
+ )()
+
+ monkeypatch.setattr(team_skill_links, "_winapi", None)
+ monkeypatch.setattr(team_skill_links.subprocess, "run", _fake_run)
+ target = _make_skill(tmp_path, "skill-a")
+ link = tmp_path / "link"
+
+ with pytest.raises(OSError) as excinfo:
+ _create_windows_junction(target, link)
+
+ assert not isinstance(excinfo.value, UnicodeDecodeError)
+ assert localized_error in str(excinfo.value)
+
+
+@requires_windows
+def test_native_rejection_falls_back_to_cmd_exe(tmp_path, monkeypatch):
+ """When the native call rejects the creation, the cmd.exe fallback still creates the junction."""
+
+ def _reject(_src, _dst):
+ raise OSError("native rejected")
+
+ monkeypatch.setattr(team_skill_links._winapi, "CreateJunction", _reject)
+ target = _make_skill(tmp_path, "skill-a")
+ link = tmp_path / "link"
+
+ _create_windows_junction(target, link)
+
+ _assert_link_resolves(link, target)
+
+
+def test_link_skill_dir_is_idempotent(tmp_path):
+ """Linking twice keeps a single working link and never raises."""
+ target = _make_skill(tmp_path, "skill-a")
+ link = tmp_path / "link"
+
+ link_skill_dir(target, link)
+ link_skill_dir(target, link)
+
+ _assert_link_resolves(link, target)
+
+
+def test_ensure_skill_dir_links_skips_existing_entries(tmp_path):
+ """Pre-existing target entries are left untouched (regression)."""
+ source = tmp_path / "global_skills"
+ _make_skill(source, "skill-a")
+ _make_skill(source, "skill-b")
+ target = tmp_path / "team_skills"
+ target.mkdir()
+ ordinary = target / "skill-a"
+ ordinary.mkdir()
+ (ordinary / "SKILL.md").write_text("---\nname: ordinary\n---\n", encoding="utf-8")
+
+ ensure_skill_dir_links(source, target)
+
+ assert (ordinary / "SKILL.md").read_text(encoding="utf-8") == "---\nname: ordinary\n---\n"
+ _assert_link_resolves(target / "skill-b", source / "skill-b")
+
+
+def test_offload_link_sync_runs_inline_without_running_loop(tmp_path):
+ """Without a running loop the sync completes synchronously and returns None."""
+ source = tmp_path / "global_skills"
+ _make_skill(source, "skill-a")
+ target = tmp_path / "team_skills"
+
+ result = offload_link_sync(source, target)
+
+ assert result is None
+ _assert_link_resolves(target / "skill-a", source / "skill-a")
+
+
+async def test_offload_link_sync_schedules_on_running_loop_and_keeps_loop_responsive(tmp_path):
+ """On the event loop the sync runs in a worker thread while the loop keeps ticking."""
+ source = tmp_path / "global_skills"
+ _make_skill(source, "skill-a")
+ target = tmp_path / "team_skills"
+
+ ticks = 0
+
+ async def _heartbeat():
+ nonlocal ticks
+ while True:
+ ticks += 1
+ await asyncio.sleep(0)
+
+ heartbeat = asyncio.create_task(_heartbeat())
+ try:
+ pending = offload_link_sync(source, target)
+ assert pending is not None, "a running loop must offload instead of running inline"
+ await pending
+ finally:
+ heartbeat.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await heartbeat
+
+ assert ticks >= 1, "event loop must stay responsive while the sync runs off thread"
+ _assert_link_resolves(target / "skill-a", source / "skill-a")