Skip to content

The agent that grows with you

fix(skills): publish and read the (map, platform) pair under one lock

Jeff Mettel22f66de638ae
diff --git a/agent/skill_commands.py b/agent/skill_commands.py
index 4169e54fe48..f1e42e69023 100644
--- a/agent/skill_commands.py
+++ b/agent/skill_commands.py
@@ -8,6 +8,7 @@ import json
import logging
import os
import re
+import threading
from pathlib import Path
from typing import Any, Dict, Optional
@@ -24,6 +25,10 @@ logger = logging.getLogger(__name__)
_skill_commands: Dict[str, Dict[str, Any]] = {}
_skill_commands_platform: Optional[str] = None
_skill_commands_home: Optional[str] = None
+# Guards the (map, platform-tag, home-tag) triple so publication and the
+# freshness lookup always see a consistent snapshot. Scanning itself stays
+# outside this lock.
+_publish_lock = threading.Lock()
# Patterns for sanitizing skill names into clean hyphen-separated slugs.
_SKILL_INVALID_CHARS = re.compile(r"[^a-z0-9-]")
_SKILL_MULTI_HYPHEN = re.compile(r"-{2,}")
@@ -423,9 +428,15 @@ def scan_skill_commands() -> Dict[str, Dict[str, Any]]:
Dict mapping "/skill-name" to {name, description, skill_md_path, skill_dir}.
"""
global _skill_commands, _skill_commands_platform, _skill_commands_home
- _skill_commands_platform = _resolve_skill_commands_platform()
- _skill_commands_home = _resolve_skill_commands_home()
- _skill_commands = {}
+ platform = _resolve_skill_commands_platform()
+ home = _resolve_skill_commands_home()
+ # Build into a local map and publish once, at the end. Writing straight
+ # into the global made a scan's partial results visible to everything
+ # else in the process: a second, overlapping scan deduped against its own
+ # (empty) ``seen_names`` but collided against the first scan's already-
+ # published slugs, logging one bogus "already claimed" warning per skill —
+ # each naming the same skill as its own incumbent (#74574).
+ commands: Dict[str, Dict[str, Any]] = {}
try:
from tools.skills_tool import SKILLS_DIR, _parse_frontmatter, skill_matches_platform, skill_matches_environment, _get_disabled_skill_names
from agent.skill_utils import (
@@ -505,14 +516,14 @@ def scan_skill_commands() -> Dict[str, Dict[str, Any]]:
# slug (e.g. "git_helper" vs "git-helper"). First-wins
# preserves local-before-external precedence.
cmd_key = f"/{cmd_name}"
- if cmd_key in _skill_commands:
+ if cmd_key in commands:
logger.warning(
"Skill %r maps to slash command %s already claimed "
"by %r; keeping the first and skipping this one.",
- name, cmd_key, _skill_commands[cmd_key]["name"],
+ name, cmd_key, commands[cmd_key]["name"],
)
continue
- _skill_commands[cmd_key] = {
+ commands[cmd_key] = {
"name": name,
"description": description or f"Invoke the {name} skill",
"skill_md_path": str(skill_md),
@@ -522,7 +533,18 @@ def scan_skill_commands() -> Dict[str, Dict[str, Any]]:
continue
except Exception:
pass
- return _skill_commands
+ # Publish the finished map and the platform/home it was scanned for as
+ # ONE step. Bare assignments are not atomic together: a reader landing
+ # between them sees the NEW map still carrying the OLD platform tag, and
+ # if that stale tag happens to match its own platform it accepts the map
+ # without rescanning — serving another platform's disabled-skill view,
+ # exactly the leak #14536 closed. Only the publish/lookup pair is locked;
+ # the scan above (file I/O, deferred imports) stays outside it.
+ with _publish_lock:
+ _skill_commands = commands
+ _skill_commands_platform = platform
+ _skill_commands_home = home
+ return commands
def get_skill_commands() -> Dict[str, Dict[str, Any]]:
@@ -534,13 +556,22 @@ def get_skill_commands() -> Dict[str, Dict[str, Any]]:
active profile's Hermes home changes (e.g. Desktop switching profiles
mid-session) so each profile sees its own ``skills.external_dirs`` (#88023).
"""
- if (
- not _skill_commands
- or _skill_commands_platform != _resolve_skill_commands_platform()
- or _skill_commands_home != _resolve_skill_commands_home()
- ):
- scan_skill_commands()
- return _skill_commands
+ current_platform = _resolve_skill_commands_platform()
+ current_home = _resolve_skill_commands_home()
+ # Read the map and its tags under the same lock that publishes them, so
+ # the freshness decision is made against a consistent snapshot.
+ with _publish_lock:
+ commands = _skill_commands
+ is_fresh = (
+ bool(commands)
+ and _skill_commands_platform == current_platform
+ and _skill_commands_home == current_home
+ )
+ if is_fresh:
+ return commands
+ # Scan outside the lock — it does file I/O and deferred imports, and
+ # concurrent scans are already safe (each builds its own map).
+ return scan_skill_commands()
def reload_skills() -> Dict[str, Any]:
diff --git a/tests/agent/test_skill_commands.py b/tests/agent/test_skill_commands.py
index 737a916df83..c6f016aee5b 100644
--- a/tests/agent/test_skill_commands.py
+++ b/tests/agent/test_skill_commands.py
@@ -348,6 +348,140 @@ class TestScanSkillCommands:
scan_skill_commands()
assert any("already claimed" in r.message for r in caplog.records)
+ # -- concurrent scans (#74574) ------------------------------------------
+
+ def test_concurrent_scans_do_not_report_skills_as_claiming_themselves(
+ self, tmp_path, caplog
+ ):
+ """Two overlapping scans must not see each other's partial results.
+
+ ``scan_skill_commands`` published into a module-global dict while it
+ built, but deduped against a *local* ``seen_names``. A second scan
+ starting mid-flight therefore found every slug already present and
+ logged one "already claimed" warning per skill — each naming the very
+ same skill as the incumbent. A gateway serving several platforms hits
+ this on startup, flooding errors.log with one line per installed skill.
+ """
+ import logging as _logging
+ import threading
+
+ import tools.skills_tool as _skills_tool
+
+ skill_count = 5
+ for index in range(skill_count):
+ _make_skill(tmp_path, f"skill-{index}")
+
+ real_parse = _skills_tool._parse_frontmatter
+ parked = threading.Event()
+ other_scan_finished = threading.Event()
+ already_parked = threading.local()
+
+ def parking_parse(content):
+ # Park the background scan once, before it has published anything,
+ # so the foreground scan runs to completion underneath it.
+ if (
+ threading.current_thread().name == "parked-scan"
+ and not getattr(already_parked, "done", False)
+ ):
+ already_parked.done = True
+ parked.set()
+ other_scan_finished.wait(timeout=10)
+ return real_parse(content)
+
+ with patch("tools.skills_tool.SKILLS_DIR", tmp_path), patch(
+ "tools.skills_tool._parse_frontmatter", parking_parse
+ ):
+ with caplog.at_level(_logging.WARNING, logger="agent.skill_commands"):
+ background = threading.Thread(
+ target=scan_skill_commands, name="parked-scan", daemon=True
+ )
+ background.start()
+ assert parked.wait(timeout=10), "background scan never parked"
+
+ foreground = scan_skill_commands()
+
+ other_scan_finished.set()
+ background.join(timeout=10)
+ assert not background.is_alive()
+
+ collisions = [r for r in caplog.records if "already claimed" in r.message]
+ assert collisions == [], (
+ "overlapping scans reported self-collisions: "
+ f"{[r.getMessage() for r in collisions]}"
+ )
+ # Both scans still produce the full, correct map.
+ assert len(foreground) == skill_count
+ assert foreground["/skill-0"]["name"] == "skill-0"
+
+ def test_publication_and_lookup_share_one_lock(self, tmp_path):
+ """A reader must not land between the map and platform-tag writes.
+
+ They are two separate global assignments. A reader in between sees the
+ NEW map still carrying the OLD platform tag; if that stale tag matches
+ its own platform it accepts the map without rescanning and serves
+ another platform's disabled-skill view — the leak #14536 closed.
+ Holding the publish lock must therefore block a reader outright.
+ """
+ import threading
+
+ import agent.skill_commands as skill_commands_module
+ from agent.skill_commands import get_skill_commands
+
+ _make_skill(tmp_path, "shared")
+
+ with patch("tools.skills_tool.SKILLS_DIR", tmp_path):
+ scan_skill_commands()
+
+ done = threading.Event()
+
+ def _read():
+ with patch("tools.skills_tool.SKILLS_DIR", tmp_path):
+ get_skill_commands()
+ done.set()
+
+ with skill_commands_module._publish_lock:
+ reader = threading.Thread(target=_read, daemon=True)
+ reader.start()
+ # The reader must be unable to complete its freshness lookup
+ # while publication is in progress.
+ assert not done.wait(timeout=0.5), (
+ "get_skill_commands read the (map, platform) pair without "
+ "the publish lock"
+ )
+
+ assert done.wait(timeout=10), "reader did not finish after release"
+ reader.join(timeout=10)
+
+ def test_scan_never_publishes_a_partially_built_map(self, tmp_path):
+ """A reader during a scan sees the previous map, never a half-built one."""
+ import threading
+
+ import agent.skill_commands as skill_commands_module
+ import tools.skills_tool as _skills_tool
+
+ skill_count = 5
+ for index in range(skill_count):
+ _make_skill(tmp_path, f"skill-{index}")
+
+ with patch("tools.skills_tool.SKILLS_DIR", tmp_path):
+ scan_skill_commands()
+
+ real_parse = _skills_tool._parse_frontmatter
+ observed_sizes = []
+
+ def observing_parse(content):
+ observed_sizes.append(len(skill_commands_module._skill_commands))
+ return real_parse(content)
+
+ with patch("tools.skills_tool.SKILLS_DIR", tmp_path), patch(
+ "tools.skills_tool._parse_frontmatter", observing_parse
+ ):
+ scan_skill_commands()
+
+ # Every mid-scan observation shows the complete previous map, never a
+ # partial one growing from 0.
+ assert observed_sizes == [skill_count] * skill_count
+
class TestResolveSkillCommandKey:
"""Telegram bot-command names disallow hyphens, so the menu registers