Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 3 additions & 6 deletions src/specify_cli/presets/_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
_write_shared_bytes,
_write_shared_text,
)
from ._manager_commands import _PresetCommandMethods
from ._manager_commands import _PresetCommandMethods, _preset_command_names
from ._manager_skills import _PresetSkillMethods
from ._manifest import (
PresetCompatibilityError,
Expand Down Expand Up @@ -478,11 +478,7 @@ def install_from_directory(

# Reconcile all affected commands from the full priority stack so that
# install order doesn't determine the winning command file.
cmd_names = [
t["name"]
for t in manifest.templates
if t.get("type") == "command"
]
cmd_names = _preset_command_names(dest_dir, manifest)
if cmd_names:
try:
self._reconcile_composed_commands(cmd_names)
Expand Down Expand Up @@ -767,6 +763,7 @@ def remove(self, pack_id: str) -> bool:
manifest_path = pack_dir / "preset.yml"
if manifest_path.exists():
try:
removed_cmd_names.update(_preset_command_names(pack_dir))
manifest = PresetManifest(manifest_path)
for tmpl in manifest.templates:
if (
Expand Down
132 changes: 95 additions & 37 deletions src/specify_cli/presets/_manager_commands.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Agent command registration and reconciliation for installed presets."""

import copy
import re
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set

Expand All @@ -15,7 +16,10 @@
resolve_active_agent_for_registration,
)
from ..extensions import ExtensionRegistry
from ..integrations._file_changes import write_text as _write_text
from ..shared_infra import (
_ensure_safe_shared_directory,
_write_shared_text,
)
from ._manifest import PresetManifest
from ._resolver import PresetResolver

Expand Down Expand Up @@ -89,6 +93,32 @@ def _substitute_core_template(
return body.replace("{CORE_TEMPLATE}", core_body), core_frontmatter


def _preset_command_names(
preset_dir: Path, manifest: PresetManifest | None = None
) -> list[str]:
"""Return declared and convention-based command names for an installed preset."""
manifest = manifest or PresetManifest(preset_dir / "preset.yml")
command_templates = [
template
for template in manifest.templates
if template.get("type") == "command"
]
names = [template["name"] for template in command_templates]
declared_files = {
(preset_dir / template["file"]).resolve()
for template in command_templates
if isinstance(template.get("file"), str)
}
convention_dir = preset_dir / "commands"
if convention_dir.is_dir():
for path in convention_dir.glob("*.md"):
if path.resolve() in declared_files:
continue
if re.fullmatch(r"[a-z0-9-]+(?:\.[a-z0-9-]+)*", path.stem):
names.append(path.stem)
return list(dict.fromkeys(names))


class _PresetCommandMethods:
"""Command artifact methods shared through PresetManager's lifecycle state."""

Expand Down Expand Up @@ -148,9 +178,11 @@ def _register_commands(
if composed is not None:
if composed_dir is None:
composed_dir = preset_dir / ".composed"
composed_dir.mkdir(parents=True, exist_ok=True)
_ensure_safe_shared_directory(
self.project_root, composed_dir
)
composed_file = composed_dir / f"{cmd['name']}.md"
_write_text(composed_file, composed, encoding="utf-8")
_write_shared_text(self.project_root, composed_file, composed)
commands_to_register.append({
**cmd,
"file": f".composed/{cmd['name']}.md",
Expand Down Expand Up @@ -994,6 +1026,30 @@ def record_written(written: Dict[str, List[str]]) -> None:
# repeated filesystem reads for each command name.
presets_by_priority = list(self.registry.list_by_priority())

def preset_template_for_path(
pack_id: str, pack_dir: Path, path: Path, cmd_name: str
) -> tuple[str, Dict[str, Any]] | None:
manifest = resolver._get_manifest(pack_dir)
if manifest:
for template in manifest.templates:
if (
template.get("name") == cmd_name
and template.get("type") == "command"
):
return manifest.id, template

if (
path.parent == pack_dir / "commands"
and path.stem == cmd_name
and re.fullmatch(r"[a-z0-9-]+(?:\.[a-z0-9-]+)*", cmd_name)
):
return pack_id, {
"name": cmd_name,
"type": "command",
"file": path.relative_to(pack_dir).as_posix(),
}
return None

for cmd_name in command_names:
layers = resolver.collect_all_layers(cmd_name, "command")
if not layers:
Expand All @@ -1014,18 +1070,18 @@ def record_written(written: Dict[str, List[str]]) -> None:
for pack_id, _meta in presets_by_priority:
pack_dir = self.presets_dir / pack_id
if top_path.is_relative_to(pack_dir):
manifest = resolver._get_manifest(pack_dir)
if manifest:
for tmpl in manifest.templates:
if tmpl.get("name") == cmd_name and tmpl.get("type") == "command":
written = self._register_for_non_skill_agents(
registrar, [tmpl], manifest.id, pack_dir,
only_agent=only_agent, extra_agents=extra_agents,
)
record_written(written)
self._merge_pack_registered_commands(manifest.id, written)
registered = True
break
owned_template = preset_template_for_path(
pack_id, pack_dir, top_path, cmd_name
)
if owned_template:
owner_id, tmpl = owned_template
written = self._register_for_non_skill_agents(
registrar, [tmpl], owner_id, pack_dir,
only_agent=only_agent, extra_agents=extra_agents,
)
record_written(written)
self._merge_pack_registered_commands(owner_id, written)
Comment on lines +1082 to +1083
registered = True
break
if not registered:
# Top layer is a non-preset source (extension, core, or
Expand Down Expand Up @@ -1121,39 +1177,41 @@ def record_written(written: Dict[str, List[str]]) -> None:
)
continue

# Write to the highest-priority preset's .composed dir
# Write to the winning preset's .composed dir when the
# convention-only command has no manifest entry. Tracking the
# registration there lets preset removal clean it up later.
registered = False
for pack_id, _meta in presets_by_priority:
pack_dir = self.presets_dir / pack_id
manifest = resolver._get_manifest(pack_dir)
if not manifest:
if not layers[0]["path"].is_relative_to(pack_dir):
continue
for tmpl in manifest.templates:
if tmpl.get("name") == cmd_name and tmpl.get("type") == "command":
composed_dir = pack_dir / ".composed"
composed_dir.mkdir(parents=True, exist_ok=True)
composed_file = composed_dir / f"{cmd_name}.md"
_write_text(composed_file, composed, encoding="utf-8")
written = self._register_for_non_skill_agents(
registrar,
[{**tmpl, "file": f".composed/{cmd_name}.md"}],
manifest.id, pack_dir,
only_agent=only_agent, extra_agents=extra_agents,
)
record_written(written)
self._merge_pack_registered_commands(manifest.id, written)
registered = True
break
else:
owned_template = preset_template_for_path(
pack_id, pack_dir, layers[0]["path"], cmd_name
Comment on lines +1186 to +1189
)
if not owned_template:
continue
owner_id, tmpl = owned_template
composed_dir = pack_dir / ".composed"
_ensure_safe_shared_directory(self.project_root, composed_dir)
composed_file = composed_dir / f"{cmd_name}.md"
_write_shared_text(self.project_root, composed_file, composed)
written = self._register_for_non_skill_agents(
registrar,
[{**tmpl, "file": f".composed/{cmd_name}.md"}],
owner_id, pack_dir,
only_agent=only_agent, extra_agents=extra_agents,
)
record_written(written)
self._merge_pack_registered_commands(owner_id, written)
registered = True
break
if not registered:
# No preset owns this composed command — write to a
# shared .composed dir and register from the top layer.
shared_composed = self.presets_dir / ".composed"
shared_composed.mkdir(parents=True, exist_ok=True)
_ensure_safe_shared_directory(self.project_root, shared_composed)
composed_file = shared_composed / f"{cmd_name}.md"
_write_text(composed_file, composed, encoding="utf-8")
_write_shared_text(self.project_root, composed_file, composed)
source = layers[0]["source"]
if source.startswith("extension:"):
source_id = source.split(":", 1)[1].split(" ", 1)[0]
Expand Down
54 changes: 50 additions & 4 deletions src/specify_cli/presets/_manager_skills.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import copy
import os
import re
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set, Union

Expand Down Expand Up @@ -29,9 +30,15 @@ class _FilteredManifest:
that aren't being reconciled.
"""

def __init__(self, manifest: "PresetManifest", cmd_names: set):
def __init__(
self,
manifest: "PresetManifest",
cmd_names: set,
convention_templates: Optional[List[Dict[str, Any]]] = None,
):
self._manifest = manifest
self._cmd_names = cmd_names
self._convention_templates = convention_templates or []

def __getattr__(self, name: str):
return getattr(self._manifest, name)
Expand All @@ -41,7 +48,7 @@ def templates(self) -> List[Dict[str, Any]]:
return [
t for t in self._manifest.templates
if t.get("name") in self._cmd_names
]
] + self._convention_templates

def _merge_pack_registered_skills(
self, pack_id: str, written: Optional[Dict[str, List[str]]]
Expand Down Expand Up @@ -140,7 +147,6 @@ def _reconcile_skills(
active_ai = init_opts.get("ai") if isinstance(init_opts, dict) else None
if not isinstance(active_ai, str) or not active_ai:
active_ai = None

# Cache registry once to avoid repeated filesystem reads
presets_by_priority = list(self.registry.list_by_priority())

Expand All @@ -153,6 +159,17 @@ def _reconcile_skills(
non_preset_skills: List[tuple] = []
managed_skill_names: set = set()
reconciled_skill_commands: set[str] = set()
if active_skills_dir and active_ai and is_ai_skills_enabled(init_opts):
# The active skills-mode directory may already contain a core
# skill that a convention-only preset overrides. Admit only
# existing active skill directories that no preset has recorded
# yet; historical directories remain limited to tracked names.
for cmd_name in command_names:
managed_skill_names.update(
skill_name
for skill_name in self._skill_names_for_command(cmd_name)
if (active_skills_dir / skill_name).is_dir()
)

for cmd_name in command_names:
layers = resolver.collect_all_layers(cmd_name, "command")
Expand Down Expand Up @@ -337,7 +354,36 @@ def apply_to_dir(
except PresetValidationError:
continue
cmds_set = set(dir_cmds)
filtered_manifest = self._FilteredManifest(manifest, cmds_set)
convention_templates = []
for cmd_name in dir_cmds:
if any(
template.get("name") == cmd_name
and template.get("type") == "command"
for template in manifest.templates
):
continue
layers = resolver.collect_all_layers(cmd_name, "command")
if not layers:
continue
source_path = layers[0]["path"]
if (
source_path.is_relative_to(pack_dir)
and source_path.parent == pack_dir / "commands"
and source_path.stem == cmd_name
and re.fullmatch(
r"[a-z0-9-]+(?:\.[a-z0-9-]+)*", cmd_name
)
):
convention_templates.append(
{
"name": cmd_name,
"type": "command",
"file": source_path.relative_to(pack_dir).as_posix(),
}
Comment on lines +377 to +382
)
filtered_manifest = self._FilteredManifest(
manifest, cmds_set, convention_templates
)
# Not dead code: _register_skills only *overwrites* skill
# subdirectories that already exist (plus brand-new ones for
# the active ai_skills agent). For a restore into a
Expand Down
24 changes: 24 additions & 0 deletions src/specify_cli/presets/command_set_priority.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,30 @@ def preset_set_priority(

# Update priority
manager.registry.update(preset_id, {"priority": priority})

# Disabled presets are deliberately excluded from resolution. Updating
# their priority must not rewrite files still owned by the active stack.
# A priority change can change the winning command or skill layer just as
# install and removal do, so rematerialize artifacts provided by this
# preset from the full priority stack.
if metadata.get("enabled", True) is not False:
try:
from ._manager_commands import _preset_command_names

preset_dir = manager.presets_dir / preset_id
command_names = _preset_command_names(preset_dir)
if command_names:
manager._reconcile_composed_commands(command_names)
manager._reconcile_skills(command_names)
Comment on lines +73 to +75
except Exception as exc: # noqa: BLE001 - lifecycle reconciliation is best-effort
import warnings

warnings.warn(
f"Post-priority reconciliation failed for {preset_id}: {exc}. "
"Agent command files may not reflect the current priority stack.",
stacklevel=2,
)

manager.reconcile_constitution(
f"Failed to reconcile constitution after changing priority for preset {preset_id}"
)
Expand Down
Loading