Skip to content

Commit f47e7aa

Browse files
committed
fix(presets): refresh a survivor skill left by command registration
For native skill agents command registration writes a composer's primary skill first, marked <id>:.composed/<command>.md, and the skills phase then replaces it with a preset:<id> one. When that phase fails during activation, the command registration is all there is: only registered_commands records it. Removing the base then refreshed or retired the alias but left the removed preset's text in the primary skill, because survivor ownership was read from registered_skills and the preset:<id> marker alone. Also read a native skill agent's registered_commands for the primary command, and accept the marker command registration writes for the command's own file, raw or composed. The skill then goes through the same refresh as any survivor-owned one. Assisted-by: Claude Code (model: Claude Mythos 5.2, autonomous)
1 parent 977a329 commit f47e7aa

2 files changed

Lines changed: 119 additions & 21 deletions

File tree

‎src/specify_cli/presets/_manager_skills.py‎

Lines changed: 59 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1052,13 +1052,21 @@ def _surviving_owned_skills(
10521052
still carries that preset's ``preset:<id>`` marker, as
10531053
``(skills_dir, agent, owner_id, command_name, skill_name)`` tuples.
10541054
1055+
For native skill agents command registration writes the same file
1056+
first, marked ``<id>:<file>``, and records it in
1057+
``registered_commands``. When the skills phase then fails, that is
1058+
all there is, so those records and that marker (for the command's own
1059+
file, raw or composed) count as well.
1060+
10551061
Several agents can record one physical directory (agy/codex/zed all
10561062
use ``.agents/skills``), so each file is returned once, with the
10571063
agent to render it: the active agent when it uses that directory,
10581064
otherwise the first recorded agent in sorted order, as
10591065
``_unregister_skills`` and the alias pass choose.
10601066
"""
10611067
registrar = self._command_registrar()
1068+
registrar._ensure_configs()
1069+
resolver = PresetResolver(self.project_root)
10621070
affected = {
10631071
name: cmd_name
10641072
for cmd_name in command_names
@@ -1073,28 +1081,54 @@ def _surviving_owned_skills(
10731081
recorded = self._infer_legacy_skill_provenance(
10741082
[n for n in recorded if isinstance(n, str)], pack_id, active_ai
10751083
)
1076-
if not isinstance(recorded, dict):
1077-
continue
1084+
recorded_commands = meta.get("registered_commands")
10781085
groups: Dict[Path, Dict[str, List[str]]] = {}
1079-
for agent, names in recorded.items():
1080-
if not isinstance(agent, str) or not isinstance(names, list):
1081-
continue
1082-
skills_dir = (
1083-
active_skills_dir
1084-
if agent == active_ai
1085-
else self._safe_skills_dir_for_agent(agent)
1086-
)
1087-
if skills_dir is None:
1088-
continue
1089-
group = groups.setdefault(skills_dir, {"agents": [], "names": []})
1090-
group["agents"].append(agent)
1091-
for name in names:
1092-
if (
1093-
isinstance(name, str)
1094-
and name in affected
1095-
and name not in group["names"]
1086+
for from_commands, records in (
1087+
(False, recorded if isinstance(recorded, dict) else {}),
1088+
(True, recorded_commands if isinstance(recorded_commands, dict) else {}),
1089+
):
1090+
for agent, names in records.items():
1091+
if not isinstance(agent, str) or not isinstance(names, list):
1092+
continue
1093+
agent_config = registrar.AGENT_CONFIGS.get(agent)
1094+
if from_commands and not (
1095+
agent_config and agent_config.get("extension") == "/SKILL.md"
10961096
):
1097-
group["names"].append(name)
1097+
continue
1098+
skills_dir = (
1099+
active_skills_dir
1100+
if agent == active_ai
1101+
else self._safe_skills_dir_for_agent(agent)
1102+
)
1103+
if skills_dir is None:
1104+
continue
1105+
group = groups.setdefault(skills_dir, {"agents": [], "names": []})
1106+
if agent not in group["agents"]:
1107+
group["agents"].append(agent)
1108+
for name in names:
1109+
if not isinstance(name, str):
1110+
continue
1111+
if from_commands:
1112+
# Only a primary command: aliases are reconciled
1113+
# by ``_reconcile_preset_aliases``.
1114+
output = registrar._compute_output_name(
1115+
agent, name, agent_config
1116+
)
1117+
if affected.get(output) != name:
1118+
continue
1119+
name = output
1120+
if name in affected and name not in group["names"]:
1121+
group["names"].append(name)
1122+
manifest = resolver._get_manifest(self.presets_dir / pack_id)
1123+
# {command_name: markers command registration writes for it}
1124+
command_sources: Dict[str, Set[str]] = {}
1125+
for tmpl in manifest.templates if manifest else []:
1126+
if tmpl.get("type") == "command" and isinstance(tmpl.get("name"), str):
1127+
sources = command_sources.setdefault(
1128+
tmpl["name"], {f"{pack_id}:.composed/{tmpl['name']}.md"}
1129+
)
1130+
if isinstance(tmpl.get("file"), str):
1131+
sources.add(f"{pack_id}:{tmpl['file']}")
10981132
for skills_dir, group in groups.items():
10991133
agents = group["agents"]
11001134
agent = (
@@ -1114,7 +1148,11 @@ def _surviving_owned_skills(
11141148
except (OSError, UnicodeDecodeError):
11151149
continue
11161150
metadata = registrar.parse_frontmatter(content)[0].get("metadata")
1117-
if isinstance(metadata, dict) and metadata.get("source") == f"preset:{pack_id}":
1151+
source = metadata.get("source") if isinstance(metadata, dict) else None
1152+
if source == f"preset:{pack_id}" or (
1153+
isinstance(source, str)
1154+
and source in command_sources.get(affected[name], ())
1155+
):
11181156
found.append((skills_dir, agent, pack_id, affected[name], name))
11191157
return found
11201158

‎tests/specify_cli/presets/test_manager_skills.py‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3165,6 +3165,66 @@ def test_shared_dir_outputs_use_active_renderer_when_only_another_agent_recorded
31653165
assert "Core custom body" in text and "Base preset body" not in text
31663166
assert "$speckit-plan" in text and "/speckit-plan" not in text
31673167

3168+
@pytest.mark.parametrize("core", [False, True], ids=["no-fallback", "core-fallback"])
3169+
@pytest.mark.parametrize("historical", [False, True], ids=["active", "historical"])
3170+
def test_remove_base_refreshes_survivor_skill_left_by_command_registration(
3171+
self, project_dir, temp_dir, monkeypatch, core, historical
3172+
):
3173+
"""The composer's skills phase fails while Codex is activated, so its
3174+
primary skill there is the composed command registration
3175+
(``<id>:.composed/<command>.md``) and only ``registered_commands``
3176+
records it. Removing the base must still recompose or retire that
3177+
skill, as it does the alias, instead of leaving the removed preset's
3178+
text in it."""
3179+
manager = self._install_custom_layers(
3180+
project_dir, temp_dir, core=core, alias=self._ALIAS
3181+
)
3182+
self._write_init_options(project_dir, ai="codex", ai_skills=True)
3183+
shared = project_dir / ".agents" / "skills"
3184+
shared.mkdir(parents=True)
3185+
original = manager._register_skills
3186+
3187+
def fail_composer(manifest, *args, **kwargs):
3188+
if manifest.id == "append-preset":
3189+
raise RuntimeError("simulated composer skills phase failure")
3190+
return original(manifest, *args, **kwargs)
3191+
3192+
with monkeypatch.context() as patch:
3193+
patch.setattr(manager, "_register_skills", fail_composer)
3194+
with pytest.warns(UserWarning, match="simulated composer skills phase"):
3195+
manager.register_enabled_presets_for_agent("codex")
3196+
skill = shared / "speckit-custom" / "SKILL.md"
3197+
alias = shared / "speckit-custom-short" / "SKILL.md"
3198+
for output in (skill, alias):
3199+
content = output.read_text(encoding="utf-8")
3200+
assert "source: append-preset:.composed/speckit.custom.md" in content
3201+
assert "Base preset body" in content
3202+
composer = manager.registry.get("append-preset")
3203+
assert "speckit.custom" in composer["registered_commands"]["codex"]
3204+
assert not composer["registered_skills"].get("codex")
3205+
if historical:
3206+
self._write_init_options(project_dir, ai="claude", ai_skills=True)
3207+
3208+
if core:
3209+
assert manager.remove("base-preset") is True
3210+
else:
3211+
with pytest.warns(UserWarning, match="no base layer"):
3212+
assert manager.remove("base-preset") is True
3213+
3214+
for output in (skill, alias):
3215+
if not core:
3216+
assert not output.exists()
3217+
continue
3218+
content = output.read_text(encoding="utf-8")
3219+
assert "Base preset body" not in content
3220+
assert "Core custom body" in content and "Appended body" in content
3221+
if core:
3222+
removed = skill.read_text(encoding="utf-8")
3223+
assert "source: preset:append-preset" in removed
3224+
self._write_init_options(project_dir, ai="codex", ai_skills=True)
3225+
manager.register_enabled_presets_for_agent("codex")
3226+
assert skill.read_text(encoding="utf-8") == removed
3227+
31683228
def test_alias_refresh_rewrites_the_same_file(self, project_dir, temp_dir):
31693229
"""The alias is refreshed in place, as command registration always
31703230
wrote it: the same inode keeps its owner, ACL and mode."""

0 commit comments

Comments
 (0)