Skip to content

Commit 1930f89

Browse files
ZhiyaoWen999Zhiyao
andauthored
fix extension-local script path rewriting (github#3364)
Co-authored-by: Zhiyao <[email protected]>
1 parent 4bb5166 commit 1930f89

4 files changed

Lines changed: 158 additions & 14 deletions

File tree

‎src/specify_cli/agents.py‎

Lines changed: 47 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,9 @@ def render_frontmatter(fm: dict) -> str:
148148
)
149149
return f"---\n{yaml_str}---\n"
150150

151-
def _adjust_script_paths(self, frontmatter: dict) -> dict:
151+
def _adjust_script_paths(
152+
self, frontmatter: dict, extension_id: Optional[str] = None
153+
) -> dict:
152154
"""Normalize script paths in frontmatter to generated project locations.
153155
154156
Rewrites known repo-relative and top-level script paths under the
@@ -158,6 +160,7 @@ def _adjust_script_paths(self, frontmatter: dict) -> dict:
158160
159161
Args:
160162
frontmatter: Frontmatter dictionary
163+
extension_id: Extension id when rendering extension-owned commands.
161164
162165
Returns:
163166
Modified frontmatter with normalized project paths
@@ -168,11 +171,15 @@ def _adjust_script_paths(self, frontmatter: dict) -> dict:
168171
if isinstance(scripts, dict):
169172
for key, script_path in scripts.items():
170173
if isinstance(script_path, str):
171-
scripts[key] = self.rewrite_project_relative_paths(script_path)
174+
scripts[key] = self.rewrite_project_relative_paths(
175+
script_path, extension_id=extension_id
176+
)
172177
return frontmatter
173178

174179
@staticmethod
175-
def rewrite_project_relative_paths(text: str) -> str:
180+
def rewrite_project_relative_paths(
181+
text: str, extension_id: Optional[str] = None
182+
) -> str:
176183
"""Rewrite repo-relative paths to their generated project locations."""
177184
if not isinstance(text, str) or not text:
178185
return text
@@ -184,10 +191,18 @@ def rewrite_project_relative_paths(text: str) -> str:
184191
):
185192
text = text.replace(old, new)
186193

187-
# Only rewrite top-level style references so extension-local paths like
188-
# ".specify/extensions/<ext>/scripts/..." remain intact.
194+
# Only rewrite top-level style references so existing generated paths
195+
# like ".specify/extensions/<ext>/scripts/..." remain intact. When
196+
# rendering extension commands, top-level "scripts/" is extension-local.
197+
scripts_replacement = (
198+
f".specify/extensions/{extension_id}/scripts/"
199+
if extension_id
200+
else ".specify/scripts/"
201+
)
189202
text = re.sub(r'(^|[\s`"\'(])(?:\.?/)?memory/', r"\1.specify/memory/", text)
190-
text = re.sub(r'(^|[\s`"\'(])(?:\.?/)?scripts/', r"\1.specify/scripts/", text)
203+
text = re.sub(
204+
r'(^|[\s`"\'(])(?:\.?/)?scripts/', rf"\1{scripts_replacement}", text
205+
)
191206
text = re.sub(
192207
r'(^|[\s`"\'(])(?:\.?/)?templates/', r"\1.specify/templates/", text
193208
)
@@ -312,6 +327,7 @@ def render_skill_command(
312327
source_id: str,
313328
source_file: str,
314329
project_root: Path,
330+
extension_id: Optional[str] = None,
315331
) -> str:
316332
"""Render a command override as a SKILL.md file.
317333
@@ -331,7 +347,7 @@ def render_skill_command(
331347
agent_config = self.AGENT_CONFIGS.get(agent_name, {})
332348
if agent_config.get("extension") == "/SKILL.md":
333349
body = self.resolve_skill_placeholders(
334-
agent_name, frontmatter, body, project_root
350+
agent_name, frontmatter, body, project_root, extension_id=extension_id
335351
)
336352

337353
description = frontmatter.get(
@@ -393,7 +409,11 @@ def apply_argument_hint(
393409

394410
@staticmethod
395411
def resolve_skill_placeholders(
396-
agent_name: str, frontmatter: dict, body: str, project_root: Path
412+
agent_name: str,
413+
frontmatter: dict,
414+
body: str,
415+
project_root: Path,
416+
extension_id: Optional[str] = None,
397417
) -> str:
398418
"""Resolve script placeholders for skills-backed agents."""
399419
if not isinstance(frontmatter, dict):
@@ -433,7 +453,9 @@ def resolve_skill_placeholders(
433453

434454
body = body.replace("{ARGS}", "$ARGUMENTS").replace("__AGENT__", agent_name)
435455

436-
return CommandRegistrar.rewrite_project_relative_paths(body)
456+
return CommandRegistrar.rewrite_project_relative_paths(
457+
body, extension_id=extension_id
458+
)
437459

438460
def _convert_argument_placeholder(
439461
self, content: str, from_placeholder: str, to_placeholder: str
@@ -528,6 +550,7 @@ def register_commands(
528550
context_note: str = None,
529551
_resolved_dir: Path = None,
530552
link_outputs: bool = False,
553+
extension_id: Optional[str] = None,
531554
) -> List[str]:
532555
"""Register commands for a specific agent.
533556
@@ -545,6 +568,7 @@ def register_commands(
545568
link_outputs: If True, write rendered output to a source-local
546569
dev cache and symlink the agent command file to it. Falls back
547570
to a normal file write when symlinks are unavailable.
571+
extension_id: Extension id when rendering extension-owned commands.
548572
549573
Returns:
550574
List of registered command names
@@ -614,7 +638,9 @@ def register_commands(
614638
frontmatter[key] = core_frontmatter[key]
615639
frontmatter.pop("strategy", None)
616640

617-
frontmatter = self._adjust_script_paths(frontmatter)
641+
frontmatter = self._adjust_script_paths(
642+
frontmatter, extension_id=extension_id
643+
)
618644

619645
for key in agent_config.get("strip_frontmatter_keys", []):
620646
frontmatter.pop(key, None)
@@ -653,10 +679,11 @@ def register_commands(
653679
source_id,
654680
cmd_file,
655681
project_root,
682+
extension_id=extension_id,
656683
)
657684
elif agent_config["format"] == "markdown":
658685
body = self.resolve_skill_placeholders(
659-
agent_name, frontmatter, body, project_root
686+
agent_name, frontmatter, body, project_root, extension_id=extension_id
660687
)
661688
body = self._convert_argument_placeholder(
662689
body, "$ARGUMENTS", agent_config["args"]
@@ -666,7 +693,7 @@ def register_commands(
666693
)
667694
elif agent_config["format"] == "toml":
668695
body = self.resolve_skill_placeholders(
669-
agent_name, frontmatter, body, project_root
696+
agent_name, frontmatter, body, project_root, extension_id=extension_id
670697
)
671698
body = self._convert_argument_placeholder(
672699
body, "$ARGUMENTS", agent_config["args"]
@@ -721,6 +748,7 @@ def register_commands(
721748
source_id,
722749
cmd_file,
723750
project_root,
751+
extension_id=extension_id,
724752
)
725753
elif agent_config["format"] == "markdown":
726754
alias_output = self.render_markdown_command(
@@ -750,6 +778,7 @@ def register_commands(
750778
source_id,
751779
cmd_file,
752780
project_root,
781+
extension_id=extension_id,
753782
)
754783

755784
alias_file = (
@@ -881,6 +910,7 @@ def register_commands_for_all_agents(
881910
context_note: str = None,
882911
link_outputs: bool = False,
883912
create_missing_active_skills_dir: bool = False,
913+
extension_id: Optional[str] = None,
884914
) -> Dict[str, List[str]]:
885915
"""Register commands for all detected agents in the project.
886916
@@ -897,6 +927,7 @@ def register_commands_for_all_agents(
897927
Recovery requires active skills mode (or Kimi's existing native
898928
skills directory) and is skipped when safe resolution or
899929
creation fails.
930+
extension_id: Extension id when rendering extension-owned commands.
900931
901932
Returns:
902933
Dictionary mapping agent names to list of registered commands
@@ -999,6 +1030,7 @@ def register_commands_for_all_agents(
9991030
context_note=context_note,
10001031
_resolved_dir=agent_dir,
10011032
link_outputs=link_outputs,
1033+
extension_id=extension_id,
10021034
)
10031035
if registered:
10041036
results[agent_name] = registered
@@ -1023,6 +1055,7 @@ def register_commands_for_non_skill_agents(
10231055
project_root: Path,
10241056
context_note: Optional[str] = None,
10251057
link_outputs: bool = False,
1058+
extension_id: Optional[str] = None,
10261059
) -> Dict[str, List[str]]:
10271060
"""Register commands for all non-skill agents in the project.
10281061
@@ -1038,6 +1071,7 @@ def register_commands_for_non_skill_agents(
10381071
context_note: Custom context comment for markdown output
10391072
link_outputs: If True, create dev-mode symlinks for rendered
10401073
command files when supported by the OS.
1074+
extension_id: Extension id when rendering extension-owned commands.
10411075
10421076
Returns:
10431077
Dictionary mapping agent names to list of registered commands
@@ -1066,6 +1100,7 @@ def register_commands_for_non_skill_agents(
10661100
context_note=context_note,
10671101
_resolved_dir=agent_dir,
10681102
link_outputs=link_outputs,
1103+
extension_id=extension_id,
10691104
)
10701105
if registered:
10711106
results[agent_name] = registered

‎src/specify_cli/extensions/__init__.py‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1075,9 +1075,11 @@ def _register_extension_skills(
10751075
pass # best-effort cleanup
10761076
continue
10771077
frontmatter, body = registrar.parse_frontmatter(content)
1078-
frontmatter = registrar._adjust_script_paths(frontmatter)
1078+
frontmatter = registrar._adjust_script_paths(
1079+
frontmatter, extension_id=manifest.id
1080+
)
10791081
body = registrar.resolve_skill_placeholders(
1080-
selected_ai, frontmatter, body, self.project_root
1082+
selected_ai, frontmatter, body, self.project_root, extension_id=manifest.id
10811083
)
10821084

10831085
original_desc = frontmatter.get("description", "")
@@ -1958,6 +1960,7 @@ def register_commands_for_agent(
19581960
project_root,
19591961
context_note=context_note,
19601962
link_outputs=link_outputs,
1963+
extension_id=manifest.id,
19611964
)
19621965

19631966
def register_commands_for_all_agents(
@@ -1978,6 +1981,7 @@ def register_commands_for_all_agents(
19781981
context_note=context_note,
19791982
link_outputs=link_outputs,
19801983
create_missing_active_skills_dir=create_missing_active_skills_dir,
1984+
extension_id=manifest.id,
19811985
)
19821986

19831987
def unregister_commands(

‎tests/test_extension_skills.py‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -850,6 +850,67 @@ def test_skill_registration_resolves_script_placeholders(self, project_dir, temp
850850
assert ".specify/templates/checklist.md" in content
851851
assert ".specify/memory/constitution.md" in content
852852

853+
def test_skill_registration_uses_extension_local_script_paths(self, project_dir, temp_dir):
854+
"""Auto-registered skills should not rewrite extension scripts into core scripts."""
855+
_create_init_options(project_dir, ai="claude", ai_skills=True)
856+
skills_dir = _create_skills_dir(project_dir, ai="claude")
857+
858+
ext_dir = temp_dir / "scripted-ext"
859+
ext_dir.mkdir()
860+
manifest_data = {
861+
"schema_version": "1.0",
862+
"extension": {
863+
"id": "scripted-ext",
864+
"name": "Scripted Extension",
865+
"version": "1.0.0",
866+
"description": "Test",
867+
},
868+
"requires": {"speckit_version": ">=0.1.0"},
869+
"provides": {
870+
"commands": [
871+
{
872+
"name": "speckit.scripted-ext.check",
873+
"file": "commands/check.md",
874+
"description": "Scripted check command",
875+
}
876+
]
877+
},
878+
}
879+
with open(ext_dir / "extension.yml", "w") as f:
880+
yaml.safe_dump(manifest_data, f)
881+
882+
(ext_dir / "commands").mkdir()
883+
(ext_dir / "scripts" / "bash").mkdir(parents=True)
884+
(ext_dir / "scripts" / "bash" / "resolve-skill.sh").write_text(
885+
"#!/usr/bin/env bash\n"
886+
)
887+
(ext_dir / "scripts" / "bash" / "ensure-skills.sh").write_text(
888+
"#!/usr/bin/env bash\n"
889+
)
890+
(ext_dir / "commands" / "check.md").write_text(
891+
"---\n"
892+
"description: Scripted check command\n"
893+
"scripts:\n"
894+
' sh: scripts/bash/resolve-skill.sh "{ARGS}"\n'
895+
"---\n\n"
896+
"Run {SCRIPT}\n"
897+
"Then run scripts/bash/ensure-skills.sh.\n"
898+
)
899+
900+
manager = ExtensionManager(project_dir)
901+
manager.install_from_directory(ext_dir, "0.1.0", register_commands=False)
902+
903+
content = (skills_dir / "speckit-scripted-ext-check" / "SKILL.md").read_text()
904+
assert "{SCRIPT}" not in content
905+
assert "{ARGS}" not in content
906+
assert (
907+
'.specify/extensions/scripted-ext/scripts/bash/resolve-skill.sh "$ARGUMENTS"'
908+
in content
909+
)
910+
assert ".specify/extensions/scripted-ext/scripts/bash/ensure-skills.sh" in content
911+
assert ".specify/scripts/bash/resolve-skill.sh" not in content
912+
assert ".specify/scripts/bash/ensure-skills.sh" not in content
913+
853914
def test_missing_command_file_skipped(self, skills_project, temp_dir):
854915
"""Commands with missing source files should be skipped gracefully."""
855916
project_dir, skills_dir = skills_project

‎tests/test_extensions.py‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1147,10 +1147,12 @@ def fake_register_all(
11471147
context_note=None,
11481148
link_outputs=False,
11491149
create_missing_active_skills_dir=False,
1150+
extension_id=None,
11501151
):
11511152
captured["create_missing_active_skills_dir"] = (
11521153
create_missing_active_skills_dir
11531154
)
1155+
captured["extension_id"] = extension_id
11541156
return {}
11551157

11561158
monkeypatch.setattr(
@@ -1164,6 +1166,7 @@ def fake_register_all(
11641166
registrar.register_commands_for_all_agents(manifest, extension_dir, project_dir)
11651167

11661168
assert captured["create_missing_active_skills_dir"] is False
1169+
assert captured["extension_id"] == manifest.id
11671170

11681171
def test_install_duplicate(self, extension_dir, project_dir):
11691172
"""Test installing already installed extension."""
@@ -1695,6 +1698,29 @@ def test_adjust_script_paths_preserves_extension_local_paths(self):
16951698
assert adjusted["scripts"]["sh"] == ".specify/extensions/test-ext/scripts/setup.sh {ARGS}"
16961699
assert adjusted["scripts"]["ps"] == ".specify/scripts/powershell/setup-plan.ps1 {ARGS}"
16971700

1701+
def test_adjust_script_paths_rewrites_extension_top_level_scripts(self):
1702+
"""Extension command-local scripts should resolve under the installed extension."""
1703+
from specify_cli.agents import CommandRegistrar as AgentCommandRegistrar
1704+
1705+
registrar = AgentCommandRegistrar()
1706+
original = {
1707+
"scripts": {
1708+
"sh": "scripts/bash/resolve-skill.sh {ARGS}",
1709+
"ps": "../../scripts/powershell/setup-plan.ps1 -Json",
1710+
}
1711+
}
1712+
1713+
adjusted = registrar._adjust_script_paths(original, extension_id="test-ext")
1714+
1715+
assert (
1716+
adjusted["scripts"]["sh"]
1717+
== ".specify/extensions/test-ext/scripts/bash/resolve-skill.sh {ARGS}"
1718+
)
1719+
assert (
1720+
adjusted["scripts"]["ps"]
1721+
== ".specify/scripts/powershell/setup-plan.ps1 -Json"
1722+
)
1723+
16981724
def test_rewrite_project_relative_paths_preserves_extension_local_body_paths(self):
16991725
"""Body rewrites should preserve extension-local assets while fixing top-level refs."""
17001726
from specify_cli.agents import CommandRegistrar as AgentCommandRegistrar
@@ -1709,6 +1735,24 @@ def test_rewrite_project_relative_paths_preserves_extension_local_body_paths(sel
17091735
assert ".specify/extensions/test-ext/templates/spec.md" in rewritten
17101736
assert ".specify/scripts/bash/setup-plan.sh" in rewritten
17111737

1738+
def test_rewrite_project_relative_paths_uses_extension_context_for_scripts(self):
1739+
"""Extension source bodies treat top-level scripts/ as extension-local."""
1740+
from specify_cli.agents import CommandRegistrar as AgentCommandRegistrar
1741+
1742+
body = (
1743+
"Run scripts/bash/ensure-skills.sh\n"
1744+
"Fallback ../../scripts/bash/setup-plan.sh\n"
1745+
"Read templates/checklist.md\n"
1746+
)
1747+
1748+
rewritten = AgentCommandRegistrar.rewrite_project_relative_paths(
1749+
body, extension_id="test-ext"
1750+
)
1751+
1752+
assert ".specify/extensions/test-ext/scripts/bash/ensure-skills.sh" in rewritten
1753+
assert ".specify/scripts/bash/setup-plan.sh" in rewritten
1754+
assert ".specify/templates/checklist.md" in rewritten
1755+
17121756
def test_render_toml_command_handles_embedded_triple_double_quotes(self):
17131757
"""TOML renderer should stay valid when body includes triple double-quotes."""
17141758
from specify_cli.agents import CommandRegistrar as AgentCommandRegistrar

0 commit comments

Comments
 (0)