diff --git a/CHANGELOG.md b/CHANGELOG.md index 6bf6ae5437..2c5224a74a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `apm update` against private Azure DevOps deps no longer fails on Windows with a misleading "az present but not logged in" diagnostic when the user IS signed in via `az login`. Root cause: Python's `subprocess.run(["az", ...])` -> `CreateProcessW` does not honor `PATHEXT` for non-`.exe` executables, so the Windows `az.cmd` wrapper could not be invoked even though `shutil.which("az")` resolved it. `AzureCliBearerProvider` now resolves the `az` binary via `shutil.which` once at construction and passes the absolute path to every subprocess call. As a defense-in-depth measure, the ADO `--update` preflight probe no longer strips `GIT_CONFIG_GLOBAL` / `GIT_CONFIG_NOSYSTEM` / `GIT_ASKPASS`, so Git Credential Manager can answer for Entra-cached ADO credentials whenever bearer acquisition is unavailable for any reason (sandbox, proxy, future PATH quirks). The actual clone path keeps its full gitconfig isolation. (#1430) - Root `.apm` hooks no longer duplicate after renaming the project directory or using git worktrees; Claude, Codex, Cursor, Gemini, and Windsurf hook configs stay idempotent across checkouts. The hook source-id is now derived from `apm.yml`'s `name` field instead of `install_path.name`, and `apm install` silently heals stale same-content entries from prior checkout basenames. Copilot is unaffected (its hooks live in per-file namespaces under `.github/hooks/`, not a shared merged config). (#1392, closes #1329) +- `apm install` (project-scope) keeps hook `command` paths repo-relative again, so checked-in `.claude/settings.json`, `.codex/hooks.json`, and equivalents stay portable across clones, contributors, and CI runners; user-scope (`apm install -g`) still writes absolute paths (#1310 / #1354 preserved). Re-run `apm install` on existing repos to rewrite any committed absolutized configs back to repo-relative paths. (#1394) ## [0.14.1] - 2026-05-20 diff --git a/docs/src/content/docs/producer/author-primitives/hooks-and-commands.md b/docs/src/content/docs/producer/author-primitives/hooks-and-commands.md index a2a415a15a..da01dadca9 100644 --- a/docs/src/content/docs/producer/author-primitives/hooks-and-commands.md +++ b/docs/src/content/docs/producer/author-primitives/hooks-and-commands.md @@ -151,13 +151,17 @@ agent a procedure" fits a skill -- and reaches every harness. - **Script paths.** Use `${PLUGIN_ROOT}` (or the harness-specific alias) for scripts that ship inside the package. Plain absolute paths break on consumers' machines. -- **Claude target path resolution.** When installing for the Claude - target, `apm install` rewrites `${PLUGIN_ROOT}` and relative `./` - references to absolute paths so Claude Code can execute scripts - regardless of the working directory. Scripts that are missing at - install time are replaced with their expected absolute path and a - warning is emitted — the hook is written, but the script will fail - at runtime until the file is present. +- **Hook script path resolution.** `apm install -g` (user-scope) + rewrites `${PLUGIN_ROOT}` and relative `./` references to absolute + paths so Claude Code can execute scripts regardless of the working + directory. Project-scope `apm install` (no `-g`) keeps `command` + paths repo-relative so checked-in configs stay portable across + clones, contributors, and CI. Either way, if a referenced script + is missing at install time the installer emits a warning -- in + user-scope the unexpanded variable is rewritten to the absolute + source path so the hook fails loudly at runtime; in project-scope + the variable is left in place so the deployed config never embeds + the installer's machine-local prefix. - **Same `.prompt.md` is two primitives.** A single `.apm/prompts/foo.prompt.md` becomes Copilot's prompt and Claude's `/foo` command in the same install. Name files with both surfaces diff --git a/src/apm_cli/install/services.py b/src/apm_cli/install/services.py index 25204a3d40..1b62e22bae 100644 --- a/src/apm_cli/install/services.py +++ b/src/apm_cli/install/services.py @@ -135,6 +135,8 @@ def integrate_package_primitives( """ from apm_cli.integration.dispatch import get_dispatch_table + from ..core.scope import InstallScope + _dispatch = get_dispatch_table() result = { "prompts": 0, @@ -265,14 +267,23 @@ def _format_target_collapse(paths: list[str], verbose: bool) -> tuple[str, list[ _mapping = _target.primitives.get(_prim_name) if _mapping is None: continue + _call_kwargs: dict[str, Any] = { + "force": force, + "managed_files": managed_files, + "diagnostics": diagnostics, + "scope": scope, + } + # Hook integrator alone needs the scope signal: project-scope + # deploys keep ``command`` paths repo-relative (#1394), user-scope + # deploys absolutize them (#1310 / #1354). Sibling integrators + # don't accept this kwarg, so include it only for hooks. + if _prim_name == "hooks": + _call_kwargs["user_scope"] = scope is InstallScope.USER _int_result = getattr(_integrator, _entry.integrate_method)( _target, package_info, project_root, - force=force, - managed_files=managed_files, - diagnostics=diagnostics, - scope=scope, + **_call_kwargs, ) result["links_resolved"] += _int_result.links_resolved for tp in _int_result.target_paths: diff --git a/src/apm_cli/integration/hook_integrator.py b/src/apm_cli/integration/hook_integrator.py index 0bf2586d31..1f62b89dc1 100644 --- a/src/apm_cli/integration/hook_integrator.py +++ b/src/apm_cli/integration/hook_integrator.py @@ -447,11 +447,17 @@ def _rewrite_command_for_target( else target_rel ) new_command = new_command.replace(full_var, resolved_cmd) - elif deploy_root is not None: - # File absent: resolve to absolute source path so Claude Code - # gets a clear "file not found" rather than an unexpanded variable. + else: + # File absent: always warn so a misconfigured hook is never + # silently deployed. For user-scope (deploy_root set) also + # rewrite the unexpanded variable to an absolute source path + # so the target surfaces a clear "file not found". For + # project-scope (deploy_root is None) leave the variable in + # place -- rewriting to an absolute path would re-introduce + # the #1394 portability regression in committed configs. _rich_warning(f"Hook script not found: {source_file}") - new_command = new_command.replace(full_var, str(source_file)) + if deploy_root is not None: + new_command = new_command.replace(full_var, str(source_file)) # Handle relative ./path and .\path references (safe to run after # ${CLAUDE_PLUGIN_ROOT} substitution since replacements produce paths @@ -479,11 +485,12 @@ def _rewrite_command_for_target( else target_rel ) new_command = new_command.replace(rel_ref, resolved_cmd) - elif deploy_root is not None: - # File absent: resolve to absolute source path so the target - # gets a clear "file not found" rather than a bare relative ref. + else: + # File absent: always warn (see ${PLUGIN_ROOT} branch above + # for the project-scope vs user-scope rationale). _rich_warning(f"Hook script not found: {source_file}") - new_command = new_command.replace(rel_ref, str(source_file)) + if deploy_root is not None: + new_command = new_command.replace(rel_ref, str(source_file)) return new_command, scripts_to_copy @@ -988,6 +995,7 @@ def _integrate_merged_hooks( managed_files: set = None, # noqa: RUF013 diagnostics=None, target=None, + user_scope: bool = False, ) -> HookIntegrationResult: """Integrate hooks by merging into a target-specific JSON config. @@ -1009,6 +1017,19 @@ def _integrate_merged_hooks( if config.require_dir and not target_dir.exists(): return _empty + # Absolutize hook commands only for user-scope deploys. Claude + # Code (and the Codex/Cursor/Gemini equivalents) reads + # ``~/.claude/settings.json`` without a fixed cwd and does not + # expand ``${CLAUDE_PLUGIN_ROOT}`` in that file (see #1310 / #1354), + # so user-scope deploys must write absolute paths. Project-scope + # ``/.claude/settings.json`` is typically checked in and runs + # with cwd at the repo root, where repo-relative paths resolve + # correctly -- baking absolute machine paths into checked-in config + # breaks portability across clones, contributors, and CI (#1394). + # ``user_scope`` is threaded from the caller's ``InstallScope`` so + # the gate is explicit rather than inferred from deploy-root shape. + _deploy_root_for_rewrite = project_root if user_scope else None + hook_files = self.find_hook_files(package_info.install_path) hook_files = _filter_hook_files_for_target(hook_files, config.target_key) if not hook_files: @@ -1079,7 +1100,7 @@ def _integrate_merged_hooks( config.target_key, hook_file_dir=hook_file.parent, root_dir=root_dir, - deploy_root=project_root, + deploy_root=_deploy_root_for_rewrite, ) # Merge hooks into config (additive) @@ -1283,6 +1304,8 @@ def integrate_package_hooks_claude( force: bool = False, managed_files: set = None, # noqa: RUF013 diagnostics=None, + *, + user_scope: bool = False, ) -> HookIntegrationResult: """Integrate hooks into .claude/settings.json. @@ -1295,6 +1318,7 @@ def integrate_package_hooks_claude( force=force, managed_files=managed_files, diagnostics=diagnostics, + user_scope=user_scope, ) def integrate_package_hooks_cursor( @@ -1304,6 +1328,8 @@ def integrate_package_hooks_cursor( force: bool = False, managed_files: set = None, # noqa: RUF013 diagnostics=None, + *, + user_scope: bool = False, ) -> HookIntegrationResult: """Integrate hooks into .cursor/hooks.json. @@ -1316,6 +1342,7 @@ def integrate_package_hooks_cursor( force=force, managed_files=managed_files, diagnostics=diagnostics, + user_scope=user_scope, ) def integrate_package_hooks_codex( @@ -1325,6 +1352,8 @@ def integrate_package_hooks_codex( force: bool = False, managed_files: set = None, # noqa: RUF013 diagnostics=None, + *, + user_scope: bool = False, ) -> HookIntegrationResult: """Integrate hooks into .codex/hooks.json. @@ -1337,6 +1366,7 @@ def integrate_package_hooks_codex( force=force, managed_files=managed_files, diagnostics=diagnostics, + user_scope=user_scope, ) # ------------------------------------------------------------------ @@ -1353,12 +1383,19 @@ def integrate_hooks_for_target( managed_files: set = None, # noqa: RUF013 diagnostics=None, scope=None, + user_scope: bool = False, ) -> "HookIntegrationResult": """Integrate hooks for a single *target*. Copilot uses individual JSON files (genuinely different pattern). All other merge-based targets are dispatched via the ``_MERGE_HOOK_TARGETS`` registry. + + ``user_scope`` controls whether merged-hook ``command`` paths are + rewritten to absolute paths (required when deploying to + ``~/.claude/settings.json`` -- see #1310 / #1354) or left + repo-relative so checked-in project-scope configs stay portable + across clones, contributors, and CI runners (#1394). """ if target.name == "copilot": return self.integrate_package_hooks( @@ -1380,6 +1417,7 @@ def integrate_hooks_for_target( managed_files=managed_files, diagnostics=diagnostics, target=target, + user_scope=user_scope, ) return HookIntegrationResult( diff --git a/tests/unit/install/test_services_hook_scope.py b/tests/unit/install/test_services_hook_scope.py new file mode 100644 index 0000000000..cd3aef4d2e --- /dev/null +++ b/tests/unit/install/test_services_hook_scope.py @@ -0,0 +1,221 @@ +"""Services-tier regression trap for the hook ``user_scope`` dispatch (#1394). + +The fix for #1394 hinges on a single line in +``apm_cli.install.services.integrate_package_primitives``: + + if _prim_name == "hooks": + _call_kwargs["user_scope"] = scope is InstallScope.USER + +``test_hook_integrator.py`` exercises ``HookIntegrator`` directly, +which proves the integrator honours ``user_scope=True/False`` but +does NOT prove the services-tier dispatch translates ``InstallScope`` +to that boolean correctly. A future refactor that swapped the +``InstallScope`` constants, dropped the kwarg, or moved hook +dispatch to a different branch would silently restore the +portability regression with no failing test. + +These tests close that gap by calling +``integrate_package_primitives`` through the production boundary +with a mocked ``hook_integrator`` and asserting the dispatched +``user_scope`` kwarg matches the supplied ``InstallScope``. +""" + +from __future__ import annotations + +from dataclasses import replace +from pathlib import Path +from typing import Any +from unittest.mock import MagicMock + +import pytest + +from apm_cli.core.scope import InstallScope +from apm_cli.install.services import integrate_package_primitives +from apm_cli.integration.base_integrator import IntegrationResult +from apm_cli.integration.targets import KNOWN_TARGETS +from apm_cli.utils.diagnostics import DiagnosticCollector + + +@pytest.fixture(autouse=True) +def _reset_config_cache() -> Any: + """Match the isolation pattern of tests/unit/install/test_services.py.""" + from apm_cli.config import _invalidate_config_cache + + _invalidate_config_cache() + yield + _invalidate_config_cache() + + +def _claude_hooks_only_target() -> Any: + """Return a Claude TargetProfile whose only primitive is ``hooks``. + + Keeping the dispatch surface to a single primitive guarantees the + mocked ``hook_integrator`` is invoked exactly once, so the asserted + ``user_scope`` kwarg is unambiguous. + """ + claude = KNOWN_TARGETS["claude"] + return replace(claude, primitives={"hooks": claude.primitives["hooks"]}) + + +def _make_integrator_returning_empty() -> MagicMock: + """Mock integrator that returns a real IntegrationResult. + + ``integrate_package_primitives`` reads ``files_integrated``, + ``target_paths``, and ``links_resolved`` from the result; a real + dataclass keeps assertions on those fields meaningful without + leaking MagicMock auto-attribute behaviour into the counters. + """ + integrator = MagicMock(name="hook_integrator") + integrator.integrate_hooks_for_target.return_value = IntegrationResult( + files_integrated=0, + files_updated=0, + files_skipped=0, + target_paths=[], + links_resolved=0, + ) + return integrator + + +def _make_skill_integrator() -> MagicMock: + """Mock skill integrator returning a real IntegrationResult. + + ``integrate_package_primitives`` inspects ``sub_skills_promoted``, + ``skill_created``, and ``target_paths`` on the skill result; a real + dataclass keeps those reads typed (vs MagicMock auto-attribute). + """ + skill = MagicMock(name="skill_integrator") + skill.integrate_package_skill.return_value = IntegrationResult( + files_integrated=0, + files_updated=0, + files_skipped=0, + target_paths=[], + links_resolved=0, + ) + return skill + + +def _call(scope: InstallScope, project_root: Path) -> MagicMock: + """Invoke ``integrate_package_primitives`` and return the hook integrator mock.""" + hook_integrator = _make_integrator_returning_empty() + package_info = MagicMock(name="package_info") + package_info.install_path = project_root + integrate_package_primitives( + package_info, + project_root, + targets=[_claude_hooks_only_target()], + prompt_integrator=MagicMock(), + agent_integrator=MagicMock(), + skill_integrator=_make_skill_integrator(), + instruction_integrator=MagicMock(), + command_integrator=MagicMock(), + hook_integrator=hook_integrator, + force=False, + managed_files=None, + diagnostics=DiagnosticCollector(), + scope=scope, + ) + return hook_integrator + + +def test_user_scope_dispatches_user_scope_true(tmp_path: Path) -> None: + """``InstallScope.USER`` must reach the hook integrator as ``user_scope=True``. + + Regression trap for the production wiring at + ``services.py`` ~L258. A constant swap that mapped USER to + ``user_scope=False`` would silently restore #1394 -- this test + fails first. + """ + hook_integrator = _call(InstallScope.USER, tmp_path) + + hook_integrator.integrate_hooks_for_target.assert_called_once() + kwargs = hook_integrator.integrate_hooks_for_target.call_args.kwargs + assert kwargs.get("user_scope") is True, ( + "InstallScope.USER must dispatch user_scope=True so user-scope " + f"hook commands stay absolute (#1310/#1354); got kwargs={kwargs!r}" + ) + + +def test_project_scope_dispatches_user_scope_false(tmp_path: Path) -> None: + """``InstallScope.PROJECT`` must reach the hook integrator as ``user_scope=False``. + + Regression trap for #1394: project-scope hooks MUST stay + repo-relative so committed configs are portable across clones / CI. + """ + hook_integrator = _call(InstallScope.PROJECT, tmp_path) + + hook_integrator.integrate_hooks_for_target.assert_called_once() + kwargs = hook_integrator.integrate_hooks_for_target.call_args.kwargs + assert kwargs.get("user_scope") is False, ( + "InstallScope.PROJECT must dispatch user_scope=False so committed " + f"hook configs stay portable (#1394); got kwargs={kwargs!r}" + ) + + +def test_scope_none_defaults_user_scope_false(tmp_path: Path) -> None: + """``scope=None`` (legacy call sites) must default to the safe project-scope path. + + The fix's invariant: anything that is not unambiguously + ``InstallScope.USER`` must NOT absolutize hook commands. A future + refactor that flipped this default to ``True`` would re-introduce + #1394 for every legacy call site at once. + """ + hook_integrator = _call(None, tmp_path) # type: ignore[arg-type] + + hook_integrator.integrate_hooks_for_target.assert_called_once() + kwargs = hook_integrator.integrate_hooks_for_target.call_args.kwargs + assert kwargs.get("user_scope") is False, ( + "scope=None must default to user_scope=False to preserve #1394 " + f"safety for legacy call sites; got kwargs={kwargs!r}" + ) + + +def test_non_hook_integrators_never_receive_user_scope(tmp_path: Path) -> None: + """Sibling integrators do not accept ``user_scope`` -- the kwarg must be hook-only. + + Threading ``user_scope`` into prompt/agent/command/instruction + integrators would raise ``TypeError`` at runtime. This test + locks the per-primitive gate so a refactor that hoists the kwarg + above the ``if _prim_name == "hooks":`` check fails loudly. + """ + claude = KNOWN_TARGETS["claude"] + # Use a target that exposes BOTH hooks and a non-hook primitive + # (commands) so the dispatch loop runs for both. + target = replace( + claude, + primitives={ + "hooks": claude.primitives["hooks"], + "commands": claude.primitives["commands"], + }, + ) + command_integrator = MagicMock(name="command_integrator") + command_integrator.integrate_commands_for_target.return_value = IntegrationResult( + files_integrated=0, + files_updated=0, + files_skipped=0, + target_paths=[], + links_resolved=0, + ) + hook_integrator = _make_integrator_returning_empty() + package_info = MagicMock(name="package_info") + package_info.install_path = tmp_path + integrate_package_primitives( + package_info, + tmp_path, + targets=[target], + prompt_integrator=MagicMock(), + agent_integrator=MagicMock(), + skill_integrator=_make_skill_integrator(), + instruction_integrator=MagicMock(), + command_integrator=command_integrator, + hook_integrator=hook_integrator, + force=False, + managed_files=None, + diagnostics=DiagnosticCollector(), + scope=InstallScope.USER, + ) + + command_integrator.integrate_commands_for_target.assert_called_once() + cmd_kwargs = command_integrator.integrate_commands_for_target.call_args.kwargs + assert "user_scope" not in cmd_kwargs, ( + f"Non-hook integrators must not receive the user_scope kwarg; got kwargs={cmd_kwargs!r}" + ) diff --git a/tests/unit/integration/test_hook_integrator.py b/tests/unit/integration/test_hook_integrator.py index 0029c2962f..be51e08301 100644 --- a/tests/unit/integration/test_hook_integrator.py +++ b/tests/unit/integration/test_hook_integrator.py @@ -763,12 +763,13 @@ def extract_commands(text: str) -> set: assert all("_apm_source" not in e for e in stop) return {h["command"] for entry in stop for h in entry["hooks"]} - # Commands are now absolute paths (deploy_root=project_root is threaded - # through _integrate_merged_hooks so Claude Code never sees an unexpanded - # ${CLAUDE_PLUGIN_ROOT} variable). Assert on the absolute form. + # Project-scope writes repo-relative paths so checked-in + # settings.json stays portable across clones / CI (#1394). + # User-scope deploys (project_root == ~) still absolutize via + # _rewrite_command_for_target's deploy_root branch -- see #1354. assert extract_commands(first) == { - str((temp_project / ".claude/hooks/multi-stop-pkg/hooks/stop-a.sh").resolve()), - str((temp_project / ".claude/hooks/multi-stop-pkg/hooks/stop-b.sh").resolve()), + ".claude/hooks/multi-stop-pkg/hooks/stop-a.sh", + ".claude/hooks/multi-stop-pkg/hooks/stop-b.sh", } # Verify sidecar has the ownership info @@ -782,6 +783,99 @@ def extract_commands(text: str) -> set: assert settings_path.read_text() == first + def test_project_scope_writes_relative_hook_paths(self, temp_project): + """Project-scope (.claude/settings.json checked into the repo) must keep + repo-relative hook commands so the generated config is portable across + clones / contributors / CI runners (#1394). + + Regression: #1354 unconditionally threaded deploy_root=project_root to + absolutize commands -- correct for user-scope (~/.claude/settings.json, + which #1310 was about) but wrong for project-scope, where it baked the + installer's machine-local absolute prefix into the committed JSON. + """ + pkg_dir = temp_project / "scope-pkg" + hooks_dir = pkg_dir / "hooks" + hooks_dir.mkdir(parents=True, exist_ok=True) + (hooks_dir / "hooks.json").write_text( + json.dumps( + { + "hooks": { + "Stop": [ + { + "hooks": [ + { + "type": "command", + "command": "${CLAUDE_PLUGIN_ROOT}/hooks/stop.sh", + } + ] + } + ] + } + } + ) + ) + (hooks_dir / "stop.sh").write_text("#!/bin/bash\nexit 0") + + pkg_info = _make_package_info(pkg_dir, "scope-pkg") + integrator = HookIntegrator() + integrator.integrate_package_hooks_claude(pkg_info, temp_project) + + settings = json.loads((temp_project / ".claude" / "settings.json").read_text()) + cmd = settings["hooks"]["Stop"][0]["hooks"][0]["command"] + assert cmd == ".claude/hooks/scope-pkg/hooks/stop.sh", ( + f"Project-scope command must be repo-relative; got {cmd!r}" + ) + assert not Path(cmd).is_absolute(), ( + f"Project-scope command must not be absolute; got {cmd!r}" + ) + assert str(temp_project) not in cmd, ( + f"Project-scope command must not embed the installer's absolute prefix; got {cmd!r}" + ) + + def test_user_scope_still_writes_absolute_hook_paths(self, temp_project): + """User-scope deploys must still absolutize hook commands -- + ``~/.claude/settings.json`` runs without a fixed cwd, so relative + paths cannot resolve (#1310 / #1354). + + ``user_scope=True`` is the explicit signal the production dispatch + (``services.integrate_package_primitives``) computes from the + ``InstallScope`` enum, kept independent of deploy-root layout in + ``core/scope.py``. + """ + pkg_dir = temp_project / "scope-pkg" + hooks_dir = pkg_dir / "hooks" + hooks_dir.mkdir(parents=True, exist_ok=True) + (hooks_dir / "hooks.json").write_text( + json.dumps( + { + "hooks": { + "Stop": [ + { + "hooks": [ + { + "type": "command", + "command": "${CLAUDE_PLUGIN_ROOT}/hooks/stop.sh", + } + ] + } + ] + } + } + ) + ) + (hooks_dir / "stop.sh").write_text("#!/bin/bash\nexit 0") + + pkg_info = _make_package_info(pkg_dir, "scope-pkg") + integrator = HookIntegrator() + integrator.integrate_package_hooks_claude(pkg_info, temp_project, user_scope=True) + + settings = json.loads((temp_project / ".claude" / "settings.json").read_text()) + cmd = settings["hooks"]["Stop"][0]["hooks"][0]["command"] + assert Path(cmd).is_absolute(), f"User-scope command must be absolute; got {cmd!r}" + assert cmd == str( + (temp_project / ".claude" / "hooks" / "scope-pkg" / "hooks" / "stop.sh").resolve() + ) + def test_no_hooks_returns_empty_result(self, temp_project): """Test Claude integration with no hook files returns empty result.""" pkg_dir = temp_project / "pkg" @@ -2450,6 +2544,37 @@ def test_codex_hooks_not_deployed_without_codex_dir(self): assert result.files_integrated == 0 + def test_codex_project_scope_keeps_relative_hook_paths(self): + """Project-scope .codex/hooks.json must stay portable (#1394). + + Mirrors the Claude regression test for the Codex target so the + shared _integrate_merged_hooks scope check is asserted from both + public entry points. + """ + hook_data = { + "hooks": { + "SessionStart": [ + {"type": "command", "command": "${CURSOR_PLUGIN_ROOT}/hooks/run.sh"} + ] + } + } + pi = self._make_package_info(hook_data=hook_data) + # ${CURSOR_PLUGIN_ROOT}/hooks/run.sh resolves under package root. + scripts_dir = pi.install_path / "hooks" + scripts_dir.mkdir(parents=True, exist_ok=True) + (scripts_dir / "run.sh").write_text("#!/bin/bash\nexit 0") + + integrator = HookIntegrator() + integrator.integrate_package_hooks_codex(pi, self.root) + + data = json.loads((self.root / ".codex" / "hooks.json").read_text()) + cmd = data["hooks"]["SessionStart"][0]["command"] + assert cmd == ".codex/hooks/test-pkg/hooks/run.sh", ( + f"Project-scope Codex command must be repo-relative; got {cmd!r}" + ) + assert not Path(cmd).is_absolute() + assert str(self.root) not in cmd + # --- Gemini hook integration tests ----------------------------------------------- @@ -3484,6 +3609,88 @@ def test_rewrite_command_nonexistent_script_with_deploy_root(self, tmp_path: Pat assert "missing.sh" in cmd, "Command must contain the script name" assert Path(cmd).is_absolute(), "Command must be an absolute path (the source file)" + def test_rewrite_command_missing_script_warns_in_both_scopes( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """Missing hook scripts must emit a warning regardless of scope (#1394 follow-up). + + Pre-fix, project-scope (deploy_root=None) silently left + ``${CLAUDE_PLUGIN_ROOT}/...`` unexpanded with zero diagnostic + output, so a misconfigured hook reached the deployed config + without any signal. Both scopes must now warn. + """ + from apm_cli.integration import hook_integrator as hi_mod + + warnings: list[str] = [] + monkeypatch.setattr(hi_mod, "_rich_warning", lambda msg: warnings.append(msg)) + + pkg_dir = tmp_path / "pkg" + pkg_dir.mkdir(parents=True, exist_ok=True) + integrator = HookIntegrator() + + # Project-scope (deploy_root=None): must warn, command must keep + # the unexpanded variable so we never bake an absolute source + # prefix into committed configs (#1394). + cmd_project, _ = integrator._rewrite_command_for_target( + "${CLAUDE_PLUGIN_ROOT}/hooks/missing.sh", + pkg_dir, + "my-pkg", + "claude", + deploy_root=None, + ) + assert "${CLAUDE_PLUGIN_ROOT}" in cmd_project, ( + "Project-scope must leave the variable unexpanded so committed " + f"configs stay portable; got {cmd_project!r}" + ) + assert len(warnings) == 1 and "Hook script not found" in warnings[0], ( + f"Project-scope must emit exactly one missing-script warning; got {warnings!r}" + ) + + # User-scope (deploy_root set): must warn AND rewrite to the + # absolute source path so the target surfaces a clear runtime + # failure (preserves #1310 / #1354 behaviour). + cmd_user, _ = integrator._rewrite_command_for_target( + "${CLAUDE_PLUGIN_ROOT}/hooks/missing.sh", + pkg_dir, + "my-pkg", + "claude", + deploy_root=tmp_path / "fake-home", + ) + assert "${CLAUDE_PLUGIN_ROOT}" not in cmd_user, ( + f"User-scope must resolve the variable; got {cmd_user!r}" + ) + assert Path(cmd_user).is_absolute() + assert len(warnings) == 2, ( + f"User-scope must emit a second missing-script warning; got {warnings!r}" + ) + + def test_rewrite_command_missing_relative_script_warns_in_project_scope( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """The ``./path`` branch must also warn for project-scope missing scripts.""" + from apm_cli.integration import hook_integrator as hi_mod + + warnings: list[str] = [] + monkeypatch.setattr(hi_mod, "_rich_warning", lambda msg: warnings.append(msg)) + + pkg_dir = tmp_path / "pkg" + pkg_dir.mkdir(parents=True, exist_ok=True) + integrator = HookIntegrator() + + cmd, _ = integrator._rewrite_command_for_target( + "./hooks/missing.sh", + pkg_dir, + "my-pkg", + "claude", + deploy_root=None, + ) + # Variable / relative ref stays in place under project-scope so + # the committed config never embeds an absolute prefix. + assert "./hooks/missing.sh" in cmd + assert len(warnings) == 1 and "Hook script not found" in warnings[0], ( + f"Project-scope must warn for the ./path branch too; got {warnings!r}" + ) + # ------------------------------------------------------------------ # Group C: Event normalisation for Claude # ------------------------------------------------------------------