Skip to content
Open
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
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
5 changes: 5 additions & 0 deletions design/extension.md
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,11 @@ renders primary names and aliases, so integrations whose native command format
is `SKILL.md` create separate primary and alias skill directories. Non-generic
native registration writes its selected destination and may replace an
existing file; the generic integration applies its ownership checks first.
For native `SKILL.md` integrations, `registered_commands` records the primary
and alias names. The primary skill name is also refreshed by the shared
extension-skill renderer; aliases retain their alias-specific frontmatter and
receive the integration's skill post-processing. Refresh uses an ownership
allowlist so unrelated user skills remain protected.

Command-backed integrations configured to use skills take a separate
supplemental path. That path renders only primary commands as
Expand Down
10 changes: 8 additions & 2 deletions docs/extensions/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -280,8 +280,14 @@ is_installed = registry.is_installed(extension_id: str) # bool
}
```

`registered_commands` maps integration keys to registered command names;
`registered_skills` records supplemental skill names. The installer stores
`registered_commands` maps integration keys to registered command names,
including aliases emitted by native command registration. For native
`SKILL.md` integrations, registration creates separate primary and alias
skill files and applies integration-specific skill post-processing to each.
`registered_skills` records skills written by the shared extension-skill
renderer (primary command names only); its refresh allowlist is limited to
outputs owned by that registration, preserving unrelated user skills. The
installer stores
`"local"` as raw local provenance, or a catalog object as shown above.
The CLI's normalized `--json` output uses a separate
[public source shape](cli.md#list-installed-extensions).
Expand Down
15 changes: 10 additions & 5 deletions src/specify_cli/agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -883,12 +883,10 @@ def register_commands(

# -- Post-process for non-skills agents -----------------------
_integration = None
if agent_config["extension"] != "/SKILL.md":
from specify_cli.integrations import ( # noqa: PLC0415
get_integration,
)
from specify_cli.integrations import get_integration # noqa: PLC0415

_integration = get_integration(agent_name)
_integration = get_integration(agent_name)
if agent_config["extension"] != "/SKILL.md":
if _integration is not None:
output = _integration.post_process_command_content(output)

Expand Down Expand Up @@ -977,6 +975,13 @@ def register_commands(
version=version,
)

if (
agent_config["extension"] == "/SKILL.md"
and _integration is not None
and hasattr(_integration, "post_process_skill_content")
):
alias_output = _integration.post_process_skill_content(alias_output)

Comment thread
Copilot marked this conversation as resolved.
Resolved
alias_file = (
commands_dir / f"{alias_output_name}{agent_config['extension']}"
)
Expand Down
53 changes: 44 additions & 9 deletions src/specify_cli/extensions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1524,6 +1524,7 @@ def _register_extension_skills(
extension_dir: Path,
link_outputs: bool = False,
force: bool = False,
force_names: Set[str] | None = None,
) -> List[str]:
"""Generate SKILL.md files for extension commands as agent skills.

Expand All @@ -1538,10 +1539,11 @@ def _register_extension_skills(
link_outputs: If True, create dev-mode symlinks for rendered
skill files when supported by the OS.
force: If True, overwrite existing SKILL.md files even when they
are not dev-mode symlinks. Use in the upgrade path, where
``setup()`` has just freshly regenerated core-template skill
files and the skip guard would otherwise prevent extension
content from being layered on top.
are not dev-mode symlinks. Use only when the caller has
established ownership of the existing outputs or has freshly
regenerated them as part of an upgrade.
force_names: Optional allowlist of skill names for ``force``.
Other existing skills remain protected from overwrites.

Returns:
List of skill names that were created (for registry storage).
Expand Down Expand Up @@ -1615,6 +1617,7 @@ def _replacement(match: re.Match[str]) -> str:
# Derive skill name from command name using the same hyphenated
# convention as hook rendering and preset skill registration.
skill_name = self._skill_name_for_command(cmd_name)
force_skill = force and (force_names is None or skill_name in force_names)

# Check if skill already exists before creating the directory
skill_subdir = skills_dir / skill_name
Expand All @@ -1641,9 +1644,9 @@ def _replacement(match: re.Match[str]) -> str:
# to be refreshed on a subsequent dev install. In the upgrade
# path (force=True) the file was just written by setup(), so
# overwriting it with the composed extension content is correct.
if not is_expected_dev_symlink and not force:
if not is_expected_dev_symlink and not force_skill:
continue
elif skill_dir_preexists and not force:
elif skill_dir_preexists and not force_skill:
# Never add files to a pre-existing user directory. Without a
# verifiable SKILL.md ownership marker, rollback/removal cannot
# distinguish our output from unrelated user artifacts.
Expand All @@ -1669,6 +1672,10 @@ def _replacement(match: re.Match[str]) -> str:
frontmatter = registrar._adjust_script_paths(
frontmatter, extension_id=manifest.id
)
if integration is not None:
frontmatter, body = integration.process_registered_command(
frontmatter, body, source_id=manifest.id
)
Comment on lines +1731 to +1734
# Mirror the register_commands() rewrite (#2101): resolve
# extension-relative subdir references (agents/, knowledge-base/,
# etc.) to their installed .specify/extensions/<id>/ location
Expand Down Expand Up @@ -3061,9 +3068,28 @@ def rollback_generic_registration() -> None:

# Auto-register extension commands as agent skills when skills mode
# was used during project initialisation (feature parity).
registered_skills = self._register_extension_skills(
manifest, dest_dir, link_outputs=link_commands
# Native integration registration can write the primary SKILL.md
# before the shared renderer runs. Refresh only names whose command
# artifacts this install actually registered, so fresh installs and
# updates produce the same content without overwriting unrelated
# user skills. Keep this in the shared install path so every source
# (local, catalog, or update archive) gets identical bookkeeping.
native_skill_names = {
self._skill_name_for_command(command_name)
for command_names in registered_commands.values()
for command_name in self._valid_name_list(command_names)
}
Comment thread
Copilot marked this conversation as resolved.
Resolved
rendered_skills = self._register_extension_skills(
manifest,
dest_dir,
link_outputs=link_commands,
force=bool(native_skill_names),
force_names=native_skill_names,
Comment on lines +3270 to +3271
Comment thread
Copilot marked this conversation as resolved.
Resolved
Comment on lines +3270 to +3271
)
# Record every file rendered here as extension-owned. Native
# command registration also tracks primary skills, while this
# ownership marker lets removal safely verify the rendered content.
registered_skills = list(dict.fromkeys(rendered_skills))
if register_commands and generic_active and manifest.commands:
expected = set(names)
actual = set(
Expand Down Expand Up @@ -4000,8 +4026,17 @@ def register_enabled_extensions_for_agent(self, agent_name: str, *, force: bool
# #2948 callers only pass the active agent anyway).
if agent_name == active_agent:
try:
registered_skill_names = {
self._skill_name_for_command(command_name)
for command_name in self._valid_name_list(registered)
}
registered_skills = self._register_extension_skills(
manifest, ext_dir, force=force
manifest,
ext_dir,
force=force or bool(registered_skill_names),
force_names=(
None if force else registered_skill_names
),
)
if agent_name == "generic" and skills_mode_active:
registered_skills = self._complete_generic_refresh(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -551,7 +551,7 @@ def backup_extension_skills(skill_names, *, skills_dir=None):
manager.remove(extension_id, keep_config=True)

# 8. Install new version
_ = manager.install_from_zip(
manager.install_from_zip(
archive_path,
speckit_version,
catalog_name=update.catalog_name,
Expand Down
56 changes: 55 additions & 1 deletion tests/integrations/test_integration_generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
from specify_cli.integrations.manifest import IntegrationManifest
from specify_cli.integration_state import INTEGRATION_STATE_SCHEMA, write_integration_json
from specify_cli.extensions import ExtensionCatalog, ExtensionError, ExtensionManager, HookExecutor
from specify_cli import save_init_options
from specify_cli import app, save_init_options
from typer.testing import CliRunner


@pytest.fixture
Expand Down Expand Up @@ -64,6 +65,59 @@ def generic_project(tmp_path, *, skills=False, commands_dir=".custom/commands"):
return project


def test_generic_skills_update_rolls_back_when_command_source_is_missing(
tmp_path, generic_extension, monkeypatch,
):
"""Skills-mode updates retain source validation and restore old artifacts."""
project = generic_project(tmp_path, skills=True)
monkeypatch.chdir(project)
manager = ExtensionManager(project)
manager.install_from_directory(generic_extension, "1.0.0")
artifact = project / ".custom/commands/speckit-sample-run/SKILL.md"
original_artifact = artifact.read_bytes()
original_registry = manager.registry.get("sample")

updated_source = tmp_path / "updated-source"
shutil.copytree(generic_extension, updated_source)
manifest_path = updated_source / "extension.yml"
manifest = yaml.safe_load(manifest_path.read_text(encoding="utf-8"))
manifest["extension"]["version"] = "2.0.0"
manifest_path.write_text(yaml.safe_dump(manifest), encoding="utf-8")
(updated_source / "commands" / "run.md").unlink()
archive_path = tmp_path / "sample-update.zip"
with zipfile.ZipFile(archive_path, "w") as archive:
for path in updated_source.rglob("*"):
if path.is_file():
archive.write(path, path.relative_to(updated_source))

with (
patch.object(
ExtensionCatalog,
"get_extension_info",
return_value={
"id": "sample",
"name": "Sample",
"version": "2.0.0",
"_install_allowed": True,
},
),
patch.object(
ExtensionCatalog, "download_extension", return_value=archive_path
),
):
result = CliRunner().invoke(
app,
["extension", "update", "sample"],
input="y\n",
catch_exceptions=True,
)

assert result.exit_code == 1, result.output
assert "missing source" in result.output.lower()
assert ExtensionManager(project).registry.get("sample") == original_registry
assert artifact.read_bytes() == original_artifact


@pytest.mark.parametrize("skills", [False, True])
def test_generic_extension_lifecycle(tmp_path, generic_extension, skills):
project = generic_project(
Expand Down
57 changes: 55 additions & 2 deletions tests/specify_cli/extensions/test_command_add.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,60 @@ def test_add_dev_writes_codex_skills_as_files(self, extension_dir, project_dir):
content = skill_file.read_text(encoding="utf-8")
assert "name: speckit-test-ext-hello" in content
assert "metadata:" in content
assert "source: test-ext:commands/hello.md" in content
assert "source: extension:test-ext" in content

def test_add_dev_renders_claude_extension_skill_with_hook_output(
self, extension_dir, project_dir, monkeypatch
):
"""The actual add path records rendered Claude skills and hook output."""
from specify_cli.integrations import get_integration

init_options = project_dir / ".specify" / "init-options.json"
init_options.write_text(
json.dumps({"ai": "claude", "ai_skills": True, "script": "sh"}),
encoding="utf-8",
)
command_file = extension_dir / "commands" / "hello.md"
command_file.write_text(
command_file.read_text(encoding="utf-8")
+ "\n- For each executable hook, output the following command name.\n",
encoding="utf-8",
)

def process_registered_command(self, frontmatter, body, *, source_id):
updated = dict(frontmatter)
updated["description"] = f"[{source_id}] {frontmatter['description']}"
return updated, body + "\nHOOK-TRANSFORMED\n"

monkeypatch.setattr(
get_integration("claude").__class__,
"process_registered_command",
process_registered_command,
)
with patch.object(Path, "cwd", return_value=project_dir):
result = CliRunner().invoke(
app,
["extension", "add", str(extension_dir), "--dev"],
catch_exceptions=True,
)

assert result.exit_code == 0, result.output
skill_file = (
project_dir
/ ".claude"
/ "skills"
/ "speckit-test-ext-hello"
/ "SKILL.md"
)
content = skill_file.read_text(encoding="utf-8")
assert "source: extension:test-ext" in content
assert "user-invocable: true" in content
assert "disable-model-invocation: false" in content
assert "HOOK-TRANSFORMED" in content
assert "- For each executable hook, output the following command name." in content
assert "- When constructing command invocations from hook command names" in content
registry = ExtensionRegistry(project_dir / ".specify" / "extensions")
assert "speckit-test-ext-hello" in registry.get("test-ext")["registered_skills"]

def test_add_dev_replaces_existing_codex_skill_symlink(
self, extension_dir, project_dir, temp_dir
Expand Down Expand Up @@ -250,7 +303,7 @@ def test_add_dev_replaces_existing_codex_skill_symlink(
assert not skill_file.is_symlink()
content = skill_file.read_text(encoding="utf-8")
assert "name: speckit-test-ext-hello" in content
assert "source: test-ext:commands/hello.md" in content
assert "source: extension:test-ext" in content
assert cache_file.read_text(encoding="utf-8") == "old linked content"

def test_add_dev_falls_back_to_copy_when_windows_symlinks_unavailable(
Expand Down
Loading
Loading