From a49126b929f20d6b62e2b5d3779d6d1612b2dd50 Mon Sep 17 00:00:00 2001 From: Saim Shafique Date: Mon, 9 Nov 2026 06:38:31 +0500 Subject: [PATCH 1/4] fix(agent-context): save ai_skills before re-registering extensions on init --force `specify init --here --force` into a skills-mode agent re-registered installed extensions before init-options.json recorded ai_skills, so the extension manager rendered command files instead of SKILL.md files. Save the init options right after setup() and before the force re-registration; the block moved verbatim and all its inputs are already resolved at that point. Fixes #5321 --- src/specify_cli/command_init.py | 41 ++++++++++-------- tests/specify_cli/test_command_init.py | 58 ++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 18 deletions(-) diff --git a/src/specify_cli/command_init.py b/src/specify_cli/command_init.py index fb09c74fb2..6271bbdd78 100644 --- a/src/specify_cli/command_init.py +++ b/src/specify_cli/command_init.py @@ -739,6 +739,29 @@ def init( ) manifest.save() + # Save the init options before the force re-registration + # below: extension registration reads the saved ai / + # ai_skills options to decide skill vs command rendering, + # so a skills-mode re-init must record ai_skills first + # (#5321). All inputs here are already resolved. + init_opts = { + **previous_init_options, + "ai": selected_ai, + "integration": resolved_integration.key, + "here": here, + "script": selected_script, + "feature_numbering": previous_init_options.get("feature_numbering", "sequential"), + "speckit_version": get_speckit_version(), + "allow_symlinks": allow_symlinks, + } + if resolved_integration.is_skills_mode( + integration_parsed_options or None, project_root=project_path + ): + init_opts["ai_skills"] = True + else: + init_opts.pop("ai_skills", None) + save_init_options(project_path, init_opts) + if force: from .integrations._helpers import ( _register_extensions_for_agent, @@ -858,24 +881,6 @@ def init( sanitized_wf = str(wf_err).replace("\n", " ").strip() tracker.error("workflow", f"install failed: {sanitized_wf[:120]}") - init_opts = { - **previous_init_options, - "ai": selected_ai, - "integration": resolved_integration.key, - "here": here, - "script": selected_script, - "feature_numbering": previous_init_options.get("feature_numbering", "sequential"), - "speckit_version": get_speckit_version(), - "allow_symlinks": allow_symlinks, - } - if resolved_integration.is_skills_mode( - integration_parsed_options or None, project_root=project_path - ): - init_opts["ai_skills"] = True - else: - init_opts.pop("ai_skills", None) - save_init_options(project_path, init_opts) - ensure_executable_scripts(project_path, tracker=tracker) if preset: diff --git a/tests/specify_cli/test_command_init.py b/tests/specify_cli/test_command_init.py index 4d2c4cd3b5..edeb1d2df6 100644 --- a/tests/specify_cli/test_command_init.py +++ b/tests/specify_cli/test_command_init.py @@ -376,3 +376,61 @@ def setup_with_recovered_file(self, project_root, manifest, *args, **kwargs): assert result.exit_code == 0, result.output assert IntegrationManifest.load("codex", project).is_recovered(rel) + + +def test_init_force_registers_extensions_as_skills_in_skills_mode(tmp_path, monkeypatch): + """Force re-init into a skills-mode agent must register extensions as skills (#5321). + + The force re-registration reads the saved ai / ai_skills init options to + decide skill vs command rendering. Before the fix it ran before those + options were saved, so a skills-mode re-init wrote command files for the + extension instead of SKILL.md files. + """ + from specify_cli.extensions import ExtensionManager + + result = _init(tmp_path, "proj") + assert result.exit_code == 0, _strip(result.stdout) + project = tmp_path / "proj" + + ext_dir = tmp_path / "test-ext" + (ext_dir / "commands").mkdir(parents=True) + (ext_dir / "extension.yml").write_text( + "schema_version: '1.0'\n" + "extension:\n" + " id: test-ext\n" + " name: Test Extension\n" + " version: 1.0.0\n" + " description: A test extension for skill registration\n" + "requires:\n" + " speckit_version: '>=0.1.0'\n" + "provides:\n" + " commands:\n" + " - name: speckit.test-ext.hello\n" + " file: commands/hello.md\n" + " description: Test hello command\n", + encoding="utf-8", + ) + (ext_dir / "commands" / "hello.md").write_text( + "---\n" + "description: \"Test hello command\"\n" + "---\n" + "\n" + "# Hello Command\n" + "\n" + "Run this to say hello.\n" + "$ARGUMENTS\n", + encoding="utf-8", + ) + ExtensionManager(project).install_from_directory( + ext_dir, "0.1.0", register_commands=False + ) + + monkeypatch.chdir(project) + result = CliRunner().invoke(app, [ + "init", "--here", "--force", "--integration", "copilot", + "--script", "sh", "--non-interactive", "--ignore-agent-tools", "--offline", + ]) + assert result.exit_code == 0, _strip(result.stdout) + + assert (project / ".github" / "skills" / "speckit-test-ext-hello" / "SKILL.md").is_file() + assert not (project / ".github" / "agents" / "speckit.test-ext.hello.agent.md").exists() From 56b903c814dd3725eeced2bcba7e8f47df8b7816 Mon Sep 17 00:00:00 2001 From: Saim Shafique Date: Mon, 9 Nov 2026 02:54:57 +0000 Subject: [PATCH 2/4] fix(extensions): reject symlinked skill destinations on forced registration Forced extension skill registration bypasses the pre-existing-directory guards, so a skill directory that is a symlink to a location outside the project would receive the generated SKILL.md. Validate the skill destination against its trusted root before any write, reusing the shared-infrastructure check that already guards skill removal, and skip destinations outside any trusted root. Adds a regression test: a forced re-init with a symlinked extension skill directory writes nothing outside the project. --- src/specify_cli/extensions/__init__.py | 15 ++++++ tests/specify_cli/test_command_init.py | 66 ++++++++++++++++++++++++++ 2 files changed, 81 insertions(+) diff --git a/src/specify_cli/extensions/__init__.py b/src/specify_cli/extensions/__init__.py index c66ecaa65f..3c2bef5876 100644 --- a/src/specify_cli/extensions/__init__.py +++ b/src/specify_cli/extensions/__init__.py @@ -1625,6 +1625,21 @@ def _replacement(match: re.Match[str]) -> str: skill_dir_preexists = ( skill_subdir.exists() or skill_subdir.is_symlink() ) + # Reject symlinked skill destinations before any write. The + # skills root itself is validated, but a symlinked per-skill + # directory would redirect SKILL.md outside the project, and + # the force path bypasses the pre-existing-directory guards + # below. Mirrors _find_extension_skill_dirs, which applies + # the same validation before removal. + from ..shared_infra import _validate_safe_shared_directory + + trusted_root = self._extension_skill_trusted_root(skills_dir) + if trusted_root is None: + continue + try: + _validate_safe_shared_directory(trusted_root, skill_subdir) + except (OSError, ValueError): + continue CommandRegistrar._ensure_inside(cache_file, cache_root) if selected_ai == "generic" and skill_dir_preexists: metadata = self.registry.get(manifest.id) or {} diff --git a/tests/specify_cli/test_command_init.py b/tests/specify_cli/test_command_init.py index edeb1d2df6..90321141a0 100644 --- a/tests/specify_cli/test_command_init.py +++ b/tests/specify_cli/test_command_init.py @@ -434,3 +434,69 @@ def test_init_force_registers_extensions_as_skills_in_skills_mode(tmp_path, monk assert (project / ".github" / "skills" / "speckit-test-ext-hello" / "SKILL.md").is_file() assert not (project / ".github" / "agents" / "speckit.test-ext.hello.agent.md").exists() + + +def test_init_force_rejects_symlinked_extension_skill_destination(tmp_path, monkeypatch): + """Force re-init must not write SKILL.md through a symlinked skill dir (#5323). + + With force=True the pre-existing-directory guards in + ``_register_extension_skills`` are bypassed, so a skill directory that + is a symlink to a location outside the project would receive the + generated SKILL.md. The destination must be rejected before any write. + """ + from specify_cli.extensions import ExtensionManager + + result = _init(tmp_path, "proj") + assert result.exit_code == 0, _strip(result.stdout) + project = tmp_path / "proj" + + ext_dir = tmp_path / "test-ext" + (ext_dir / "commands").mkdir(parents=True) + (ext_dir / "extension.yml").write_text( + "schema_version: '1.0'\n" + "extension:\n" + " id: test-ext\n" + " name: Test Extension\n" + " version: 1.0.0\n" + " description: A test extension for skill registration\n" + "requires:\n" + " speckit_version: '>=0.1.0'\n" + "provides:\n" + " commands:\n" + " - name: speckit.test-ext.hello\n" + " file: commands/hello.md\n" + " description: Test hello command\n", + encoding="utf-8", + ) + (ext_dir / "commands" / "hello.md").write_text( + "---\n" + "description: \"Test hello command\"\n" + "---\n" + "\n" + "# Hello Command\n" + "\n" + "Run this to say hello.\n" + "$ARGUMENTS\n", + encoding="utf-8", + ) + ExtensionManager(project).install_from_directory( + ext_dir, "0.1.0", register_commands=False + ) + + # Plant a symlink where the extension skill would be written, pointing + # outside the project. + outside = tmp_path / "outside" + outside.mkdir() + skill_subdir = project / ".github" / "skills" / "speckit-test-ext-hello" + skill_subdir.parent.mkdir(parents=True, exist_ok=True) + os.symlink(outside, skill_subdir, target_is_directory=True) + + monkeypatch.chdir(project) + result = CliRunner().invoke(app, [ + "init", "--here", "--force", "--integration", "copilot", + "--script", "sh", "--non-interactive", "--ignore-agent-tools", "--offline", + ]) + assert result.exit_code == 0, _strip(result.stdout) + + assert not (outside / "SKILL.md").exists() + assert skill_subdir.is_symlink() From 7d09da6a10cfa28bc7bbd2758de476eccd970866 Mon Sep 17 00:00:00 2001 From: Saim Shafique Date: Mon, 9 Nov 2026 03:26:16 +0000 Subject: [PATCH 3/4] fix(extensions): normalize relative skill paths and guard hard-linked SKILL.md on forced registration Copilot review on #5323 found three follow-ups to the symlinked-destination fix: relative project roots failed trusted-root validation and silently skipped skills, an existing hard-linked SKILL.md was rewritten in place, and the symlink regression test failed on Windows without symlink privileges. --- src/specify_cli/extensions/__init__.py | 18 +++- tests/specify_cli/test_command_init.py | 127 ++++++++++++++++++++++++- 2 files changed, 143 insertions(+), 2 deletions(-) diff --git a/src/specify_cli/extensions/__init__.py b/src/specify_cli/extensions/__init__.py index 3c2bef5876..a35aad97a6 100644 --- a/src/specify_cli/extensions/__init__.py +++ b/src/specify_cli/extensions/__init__.py @@ -1637,7 +1637,13 @@ def _replacement(match: re.Match[str]) -> str: if trusted_root is None: continue try: - _validate_safe_shared_directory(trusted_root, skill_subdir) + # Normalize relative destinations before validation: the + # trusted root is absolute, so a relative skill path (for + # example with ExtensionManager(Path("."))) would fail the + # containment check and the skill would be silently skipped. + _validate_safe_shared_directory( + trusted_root, Path(os.path.abspath(skill_subdir)) + ) except (OSError, ValueError): continue CommandRegistrar._ensure_inside(cache_file, cache_root) @@ -1726,6 +1732,16 @@ def _replacement(match: re.Match[str]) -> str: ): skill_content = integration.post_process_skill_content(skill_content) + # A hard-linked SKILL.md shares its inode with other paths, so + # writing it in place would change every linked copy. Drop our + # link first so the write below creates a fresh file instead. + if skill_file.is_file() and not skill_file.is_symlink(): + try: + if skill_file.stat().st_nlink > 1: + unlink(skill_file) + except OSError: + pass # best effort; the write below still proceeds + if use_dev_symlink: try: cache_file.parent.mkdir(parents=True, exist_ok=True) diff --git a/tests/specify_cli/test_command_init.py b/tests/specify_cli/test_command_init.py index 90321141a0..a1305005bb 100644 --- a/tests/specify_cli/test_command_init.py +++ b/tests/specify_cli/test_command_init.py @@ -436,6 +436,40 @@ def test_init_force_registers_extensions_as_skills_in_skills_mode(tmp_path, monk assert not (project / ".github" / "agents" / "speckit.test-ext.hello.agent.md").exists() +def _create_test_extension(tmp_path: Path) -> Path: + """Create a minimal extension dir with one hello command.""" + ext_dir = tmp_path / "test-ext" + (ext_dir / "commands").mkdir(parents=True) + (ext_dir / "extension.yml").write_text( + "schema_version: '1.0'\n" + "extension:\n" + " id: test-ext\n" + " name: Test Extension\n" + " version: 1.0.0\n" + " description: A test extension for skill registration\n" + "requires:\n" + " speckit_version: '>=0.1.0'\n" + "provides:\n" + " commands:\n" + " - name: speckit.test-ext.hello\n" + " file: commands/hello.md\n" + " description: Test hello command\n", + encoding="utf-8", + ) + (ext_dir / "commands" / "hello.md").write_text( + "---\n" + "description: \"Test hello command\"\n" + "---\n" + "\n" + "# Hello Command\n" + "\n" + "Run this to say hello.\n" + "$ARGUMENTS\n", + encoding="utf-8", + ) + return ext_dir + + def test_init_force_rejects_symlinked_extension_skill_destination(tmp_path, monkeypatch): """Force re-init must not write SKILL.md through a symlinked skill dir (#5323). @@ -489,7 +523,10 @@ def test_init_force_rejects_symlinked_extension_skill_destination(tmp_path, monk outside.mkdir() skill_subdir = project / ".github" / "skills" / "speckit-test-ext-hello" skill_subdir.parent.mkdir(parents=True, exist_ok=True) - os.symlink(outside, skill_subdir, target_is_directory=True) + try: + os.symlink(outside, skill_subdir, target_is_directory=True) + except OSError: + pytest.skip("Current platform/user cannot create directory symlinks") monkeypatch.chdir(project) result = CliRunner().invoke(app, [ @@ -500,3 +537,91 @@ def test_init_force_rejects_symlinked_extension_skill_destination(tmp_path, monk assert not (outside / "SKILL.md").exists() assert skill_subdir.is_symlink() + + +def test_relative_project_root_still_registers_extension_skills(tmp_path, monkeypatch): + """Extension skills must register when the project root is relative (#5323). + + With ExtensionManager(Path(".")), the skills directory is relative + while _extension_skill_trusted_root() returns an absolute root, so + the trusted-root validation rejected every normal destination and + the handler silently skipped the skill. Relative roots must be + normalized before validation. + """ + from specify_cli.extensions import ExtensionManager + + result = _init(tmp_path, "proj") + assert result.exit_code == 0, _strip(result.stdout) + project = tmp_path / "proj" + + ext_dir = _create_test_extension(tmp_path) + + # Switch the saved options to copilot (skills mode) first, mirroring + # the #5321 force re-init path; no extension is installed yet. + monkeypatch.chdir(project) + result = CliRunner().invoke(app, [ + "init", "--here", "--force", "--integration", "copilot", + "--script", "sh", "--non-interactive", "--ignore-agent-tools", "--offline", + ]) + assert result.exit_code == 0, _strip(result.stdout) + + manager = ExtensionManager(Path(".")) + manager.install_from_directory(ext_dir, "0.1.0", register_commands=False) + + assert (project / ".github" / "skills" / "speckit-test-ext-hello" / "SKILL.md").is_file() + + +def test_init_force_does_not_modify_hard_linked_skill_file(tmp_path, monkeypatch): + """Force re-init must not write SKILL.md in place through a hard link (#5323). + + A hard-linked SKILL.md shares its inode with other paths, so writing + it in place would change every linked copy. Forced registration must + replace the file without modifying the shared data. + """ + from specify_cli.extensions import ExtensionManager + + result = _init(tmp_path, "proj") + assert result.exit_code == 0, _strip(result.stdout) + project = tmp_path / "proj" + + ext_dir = _create_test_extension(tmp_path) + + # Switch the saved options to copilot (skills mode) first, mirroring + # the #5321 force re-init path, so installation registers the skill + # under .github/skills. + monkeypatch.chdir(project) + result = CliRunner().invoke(app, [ + "init", "--here", "--force", "--integration", "copilot", + "--script", "sh", "--non-interactive", "--ignore-agent-tools", "--offline", + ]) + assert result.exit_code == 0, _strip(result.stdout) + + ExtensionManager(project).install_from_directory( + ext_dir, "0.1.0", register_commands=False + ) + + # Pre-create the skill file with known content and hard-link it + # outside the project. + skill_file = project / ".github" / "skills" / "speckit-test-ext-hello" / "SKILL.md" + assert skill_file.is_file() + old_content = "---\nold: content\n---\n\n# Old Skill\n" + skill_file.write_text(old_content, encoding="utf-8") + outside = tmp_path / "outside" + outside.mkdir() + outside_link = outside / "SKILL.md" + try: + os.link(skill_file, outside_link) + except OSError: + pytest.skip("Current platform/user cannot create hard links") + + result = CliRunner().invoke(app, [ + "init", "--here", "--force", "--integration", "copilot", + "--script", "sh", "--non-interactive", "--ignore-agent-tools", "--offline", + ]) + assert result.exit_code == 0, _strip(result.stdout) + + # The linked copy outside the project must be untouched... + assert outside_link.read_text(encoding="utf-8") == old_content + # ...while the project's skill was regenerated. + assert skill_file.read_text(encoding="utf-8") != old_content + assert skill_file.is_file() and not skill_file.is_symlink() From ae748e5da6c6905f13166061eef0672b63ab9bc9 Mon Sep 17 00:00:00 2001 From: Saim Shafique Date: Mon, 9 Nov 2026 15:22:27 +0000 Subject: [PATCH 4/4] fix(extensions): skip hard-linked skill when detach fails on forced registration A failed hard-link detach still fell through to the in-place write, so a writable SKILL.md in a non-writable directory was overwritten through the surviving link and every linked copy changed. Skip the skill instead and leave the file untouched; the init itself still succeeds. Adds a regression test that fails the detach and checks both the linked copy outside the project and the project skill keep their old content. --- src/specify_cli/extensions/__init__.py | 6 ++- tests/specify_cli/test_command_init.py | 71 ++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 1 deletion(-) diff --git a/src/specify_cli/extensions/__init__.py b/src/specify_cli/extensions/__init__.py index a35aad97a6..cb9f79d96a 100644 --- a/src/specify_cli/extensions/__init__.py +++ b/src/specify_cli/extensions/__init__.py @@ -1740,7 +1740,11 @@ def _replacement(match: re.Match[str]) -> str: if skill_file.stat().st_nlink > 1: unlink(skill_file) except OSError: - pass # best effort; the write below still proceeds + # The detach failed (for example, the file lives in a + # non-writable directory), so writing in place would + # modify every hard-linked copy. Skip this skill + # instead of writing through the link. + continue if use_dev_symlink: try: diff --git a/tests/specify_cli/test_command_init.py b/tests/specify_cli/test_command_init.py index a1305005bb..832948841a 100644 --- a/tests/specify_cli/test_command_init.py +++ b/tests/specify_cli/test_command_init.py @@ -625,3 +625,74 @@ def test_init_force_does_not_modify_hard_linked_skill_file(tmp_path, monkeypatch # ...while the project's skill was regenerated. assert skill_file.read_text(encoding="utf-8") != old_content assert skill_file.is_file() and not skill_file.is_symlink() + + +def test_init_force_skips_hard_linked_skill_when_detach_fails(tmp_path, monkeypatch): + """Force re-init must skip a hard-linked SKILL.md it cannot detach (#5323). + + If dropping the hard link raises OSError (for example, the file lives + in a non-writable directory), writing in place would modify every + linked copy, so the skill must be skipped instead of written. The + init itself still succeeds. + """ + from specify_cli.extensions import ExtensionManager + + result = _init(tmp_path, "proj") + assert result.exit_code == 0, _strip(result.stdout) + project = tmp_path / "proj" + + ext_dir = _create_test_extension(tmp_path) + + # Switch the saved options to copilot (skills mode) first, mirroring + # the #5321 force re-init path, so installation registers the skill + # under .github/skills. + monkeypatch.chdir(project) + result = CliRunner().invoke(app, [ + "init", "--here", "--force", "--integration", "copilot", + "--script", "sh", "--non-interactive", "--ignore-agent-tools", "--offline", + ]) + assert result.exit_code == 0, _strip(result.stdout) + + ExtensionManager(project).install_from_directory( + ext_dir, "0.1.0", register_commands=False + ) + + # Pre-create the skill file with known content and hard-link it + # outside the project. + skill_file = project / ".github" / "skills" / "speckit-test-ext-hello" / "SKILL.md" + assert skill_file.is_file() + old_content = "---\nold: content\n---\n\n# Old Skill\n" + skill_file.write_text(old_content, encoding="utf-8") + outside = tmp_path / "outside" + outside.mkdir() + outside_link = outside / "SKILL.md" + try: + os.link(skill_file, outside_link) + except OSError: + pytest.skip("Current platform/user cannot create hard links") + + # Make only this skill's detach fail, mirroring an unlink denied by + # the directory permissions; every other unlink still works. + import specify_cli.integrations._file_changes as file_changes + + real_unlink = file_changes.unlink + + def _fail_skill_detach(path, *, missing_ok=False): + if os.fspath(path) == os.fspath(skill_file): + raise OSError("cannot unlink hard-linked skill file") + return real_unlink(path, missing_ok=missing_ok) + + monkeypatch.setattr(file_changes, "unlink", _fail_skill_detach) + + result = CliRunner().invoke(app, [ + "init", "--here", "--force", "--integration", "copilot", + "--script", "sh", "--non-interactive", "--ignore-agent-tools", "--offline", + ]) + assert result.exit_code == 0, _strip(result.stdout) + + # The linked copy outside the project must be untouched... + assert outside_link.read_text(encoding="utf-8") == old_content + # ...and the project's skill must be left as it was, not overwritten + # in place through the surviving hard link. + assert skill_file.read_text(encoding="utf-8") == old_content + assert skill_file.stat().st_nlink > 1