Skip to content

fix(hooks): anchor POSIX user-scope hook commands to $HOME - #2944

Merged
Daniel Meppiel (danielmeppiel) merged 14 commits into
microsoft:mainfrom
Bronyal-lzx:fix/posix-user-hook-home-anchor
Nov 12, 2026
Merged

Daniel Meppiel (danielmeppiel) merged 14 commits into
microsoft:mainfrom
Bronyal-lzx:fix/posix-user-hook-home-anchor

Conversation

@Bronyal-lzx

@Bronyal-lzx lzx (Bronyal-lzx) commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

fix(hooks): anchor POSIX user-scope hook commands to $HOME

TL;DR

User-scope installs (apm install -g) expanded the installing machine's home
directory into merged hook commands, so a ~/.claude/settings.json kept in a
dotfiles repo differed on every host and hand-normalizing it was undone by the
next install. On POSIX hosts the rewritten path is now anchored to $HOME,
which the invoking shell expands, so cwd-independence is unchanged. Windows
keeps absolute paths, and so do single-quoted references and a dynamic target
root outside the home directory.

Note

Fixes #2821. Only the form of the user-scope path changes; the merge,
ownership, and cleanup behavior is untouched.

Problem (WHY)

Why these matter: the absolute rewrite itself is required — hook commands
resolve against the working directory, not against the settings file:

"The absolute rewrite itself is right (#1310 / #1354: hook commands resolve
against the cwd, not the settings file) ... The ask is only about how
user-scope paths are anchored on POSIX targets."
— #2821

The repo's own authoring guidance says the same thing about tracked files:

"Script paths. Use ${PLUGIN_ROOT} ... Plain absolute paths break on
consumers' machines."
— hooks-and-commands.md

Approach (WHAT)

# Fix (and why, if non-obvious)
1 In the deploy_root branch (populated for user scope only), emit $HOME/<path-relative-to-deploy-root> instead of str((deploy_root / target_rel).resolve()). The deploy root is Path.home() for user scope, so the substitution is exact rather than heuristic.
2 Substitute only when relative_to(deploy_root) succeeds. A target root that resolves outside the deploy root — CLAUDE_CONFIG_DIR pointing elsewhere — keeps the previous absolute path instead of gaining a $HOME prefix that would point at the wrong location.
3 Gate the behavior on one module constant (_POSIX_USER_HOOK_PATHS = os.name != "nt") so Windows keeps the current form and tests can drive both branches deterministically.
4 Keep quoting exactly as it was. The deploy root branch never consulted path_is_quoted before, and it still does not, so no command string changes shape beyond its prefix.
5 Update the three test layers that encoded the old contract, rather than adding a parallel expectation set: the unit hook suite, the in-process install-dispatch suite, and the real-CLI lifecycle contract.
6 Anchor only when the reference is unquoted or double-quoted. A shell expands $HOME outside single quotes only, so a single-quoted reference keeps the previous absolute form instead of handing the target a literal '$HOME/…' path. The existing quote detection now reports the quote character rather than a boolean (_wrapping_quote), which is the whole cost of this guard.

Implementation (HOW)

Diff for line-level evidence:
https://github.com/microsoft/apm/pull/2944/files

Trade-offs

  • Chose $HOME over leaving the absolute path and documenting a dotfiles workaround. Rejected: telling users to post-process a file APM owns — the rewrite would still lose on the next install, as [FEATURE] Anchor user-scope hook commands to $HOME on POSIX targets so ~/.claude/settings.json stays portable across machines #2821 reports.
  • Chose to keep Windows absolute. Rejected: a Windows variable form (%USERPROFILE%) in this PR, because its cmd/PowerShell semantics differ and Project-scope hook path rewriting produces cwd-dependent commands on Windows (Claude Code target) #2408 shows cwd handling is already special there.
  • Chose absolute for a dynamic root outside the home directory. Rejected: writing $HOME/... there, which would resolve to a path that does not contain the deployed script.
  • Chose absolute for a single-quoted reference. Rejected: rewriting the surrounding single quotes into double quotes, which would widen this PR into a quote-normalization change for a shape the repo's own examples do not use — and the failure mode of getting it wrong is a hook that silently never runs.
  • Chose target-agnostic anchoring on POSIX, because _project_scoped_command_path is shared by every merge-based target. Rejected: restricting to claude/codex without maintainer input — it is a one-line condition if you prefer that.
  • Chose no mermaid diagram. Rejected: a decorative flowchart for a one-line prefix substitution; the repo requires every block to be validated with mmdc, which is not available in this environment, so an unvalidated diagram would be worse than none.

Benefits

  1. A user-scope settings file tracked in a dotfiles repo now holds the same hook entries on macOS and Linux, whatever the username or home path.
  2. Re-running apm install -g on such a repo produces no diff instead of rewriting every hook entry.
  3. Renaming a user or moving a home directory no longer invalidates user-scope hook commands.
  4. Containment is stricter, not looser: a path resolving outside the deploy root can no longer be rewritten at all.
  5. Windows users observe no change in generated commands.

Validation

pytest tests/unit/integration/test_hook_integrator.py -q -n0

188 passed in 2.82s

pytest tests/integration/test_hook_js_sidecar_lifecycle_contract.py -q -n0 — real CLI, locally built apm binary, isolated HOME:

5 passed in 71.30s

ruff check src/ tests/ and ruff format --check src/ tests/ (both must be silent in CI):

All checks passed!
1768 files already formatted

Baseline comparison, because this machine cannot run the full CI matrix:

Full unit suite and lifecycle-smoke selection, branch vs. an untouched baseline checkout using the same binary
tests/unit + tests/test_console.py
  branch:   118 failed, 22183 passed
  baseline: 118 failed, 22181 passed
  -> candidate-only failures: none; failure sets identical. The branch collects
     exactly the 2 tests added here.

pytest -m 'lifecycle_smoke and not lifecycle_merge_group' tests/integration
  branch:   166 passed, 14 failed
  baseline: 165 passed, 15 failed
  -> candidate-only failures: none. The single baseline-only failure is the
     global hook lifecycle contract, which fails on that checkout because it
     still expects an absolute path while the shared binary already writes
     $HOME -- the control that shows this diff is what changes the behavior.

Every failure on both sides is a pre-existing environment limitation here:
no gh CLI, no pwsh, sandboxed pty allocation, and network-dependent
contracts.

Scenario Evidence

# Scenario (user promise) Principle(s) Test(s) proving it Type
1 Install a hook package with apm install -g on a POSIX host — the tracked settings file holds a $HOME-anchored command instead of the installing host's prefix (regression trap for #2821) Portability by manifest tests/unit/integration/test_hook_integrator.py::TestClaudeIntegration::test_user_scope_writes_portable_home_hook_paths unit
2 Install globally, then run the hook from an unrelated working directory — it still executes DevX (pragmatic as npm), Multi-harness support tests/integration/test_hook_js_sidecar_lifecycle_contract.py::test_required_global_copilot_sidecar_lifecycle e2e
3 Reinstall the same package globally — hook entries converge instead of duplicating, and apm uninstall --global removes exactly the package-owned files DevX (pragmatic as npm) tests/integration/test_hook_js_sidecar_lifecycle_contract.py::test_required_global_copilot_sidecar_lifecycle e2e
4 Install the same package at user scope for Copilot and Kiro — both targets get the anchored command Multi-harness support, Portability by manifest tests/integration/test_hook_integrator_copilot_casing_e2e.py::test_copilot_install_scope_controls_script_paths[True], ::test_kiro_install_scope_controls_script_paths[True] integration
5 Install globally on Windows — the generated command keeps its previous absolute form Multi-harness support tests/unit/integration/test_hook_integrator.py::TestIssue1007Fixes::test_rewrite_command_deploy_root_keeps_windows_absolute_path unit
6 Point CLAUDE_CONFIG_DIR outside the home directory — the command is never rewritten into a wrong $HOME path Secure by default, Portability by manifest tests/unit/integration/test_hook_integrator.py::TestIssue1007Fixes::test_rewrite_command_dynamic_root_outside_home_stays_absolute unit
7 Write a hook command with a single-quoted plugin-root reference — the emitted command stays executable instead of containing a literal $HOME DevX (pragmatic as npm), Multi-harness support tests/unit/integration/test_hook_integrator.py::TestIssue1007Fixes::test_rewrite_command_single_quoted_reference_stays_absolute unit

How to test

  • uv run --extra dev pytest tests/unit/integration/test_hook_integrator.py -q -n0 → 188 passed, including the three boundary cases (Windows, single-quoted reference, root outside home).
  • uv run --extra dev pytest tests/integration/test_hook_integrator_copilot_casing_e2e.py -q -n0 → passes for both user_scope parametrizations of Copilot and Kiro.
  • Build the CLI (scripts/build-binary.sh) and run APM_BINARY_PATH=… APM_E2E_TESTS=1 uv run --extra dev pytest tests/integration/test_hook_js_sidecar_lifecycle_contract.py -q -n0 → 5 passed.
  • uv run --extra dev ruff check src/ tests/ && uv run --extra dev ruff format --check src/ tests/ → both silent.
  • Spot-check the artifact: HOME=/tmp/scratch apm install --global --target claude <pkg> then grep -o '\$HOME[^"]*' /tmp/scratch/.claude/settings.json → prints $HOME/.claude/hooks/… and never /tmp/scratch/....

Review feedback addressed

Responding to the Copilot review on 6331f22:

  • [critical] Single-quoted references (hook_integrator.py:613) — correct, and this was a regression I introduced, not a pre-existing one: the previous absolute form worked inside any quoting. node '${CLAUDE_PLUGIN_ROOT}/hooks/run.mjs' produced node '$HOME/.claude/hooks/…', where the shell expands nothing. Anchoring now requires an unquoted or double-quoted reference; the quote character is threaded through instead of a boolean, and a regression test asserts the single-quoted form stays absolute and executable.
  • [nit] CHANGELOG entry missing the PR reference — fixed: the entry now ends with (#2944).
  • [nit] packages/apm-guide/.apm/skills/apm-usage/package-authoring.md still documents absolute paths — fixed: that resource now describes the $HOME anchor and its three exceptions.
  • [suppressed] Absolute root outside home + bundle copying (hook_integrator.py:605) — verified as pre-existing rather than introduced here. On an untouched main checkout, the same input produces the same absolute command and the same absolute copy target from this branch, so the ensure_path_within rejection in copy_deployed_hook_bundle is independent of this diff. This PR neither touches hook_bundle.py nor changes that path's behavior; happy to file or take a follow-up that supports an absolute root end to end.

Type of change

  • Bug fix
  • New feature
  • Documentation
  • Maintenance / refactor

Testing

  • Tested locally
  • All existing tests pass
  • Added tests for new functionality (if applicable)

Spec conformance (OpenAPM v0.1)

  • N/A — this PR does not change OpenAPM-observable behaviour.

The Mode B detector counts substantive added lines under src/apm_cli/integration/;
this diff is at 22, above the 20-line threshold, so it carries the documented
waiver rather than a spec citation. No existing req-XXX covers user-scope
hook anchoring, and inventing one for a path-spelling change would put
implementation detail into the spec:

apm-spec-waiver: user-scope hook anchoring changes path spelling only, adding no new OpenAPM requirement

If you would rather make user-scope anchoring normative, I am happy to add the
anchor + manifest row + conformance test instead and drop the waiver.


Maintainer reshape (2026-11-12, per the apm-scope:v1 record on #2821)

Maintainers reshaped this branch to the approved scope; lzx (@Bronyal-lzx)'s commits are preserved and every maintainer commit carries a Co-authored-by trailer. The host-OS gate described above is replaced:

  • Capability, not host OS. TargetProfile.user_hook_home_reference (UserHookHomeReference in src/apm_cli/integration/targets.py) declares, per harness, which command fields run through a POSIX shell. $HOME anchoring is enabled only where current official docs say so; everything else keeps today's absolute paths.
Harness Anchored field(s) Evidence
Claude Code shell-form command (not args exec form, not shell: "powershell") https://code.claude.com/docs/en/hooks ("passed to a shell: sh -c on macOS and Linux")
Copilot CLI bash (user hooks in ~/.copilot/hooks/) https://docs.github.com/en/copilot/reference/hooks-reference ("Shell command for Unix"; command is copied to PowerShell too)
Gemini CLI command https://geminicli.com/docs/hooks/reference/ ("The shell command to execute")
Kiro command actions from command/bash https://kiro.dev/docs/hooks/actions/ ("run a shell command"; CLI V3 loads ~/.kiro/hooks/)
Cursor, Codex, Windsurf none (absolute) no explicit POSIX shell statement (https://cursor.com/docs/hooks, https://developers.openai.com/codex/hooks); ~/.codeium/windsurf/hooks.json is no longer in the official docs
  • Windows hosts, single-quoted references, exec form and config roots outside the home directory stay absolute. References are now replaced positionally, so mixed quoting is safe.
  • Reinstalling over an absolute-path install migrates entries in place (APM ownership kept, no duplicates); a two-home round trip produces no diff.
  • Single owner + dual guardrail: static rule mutation_writes.user_hook_home_reference, tests/integration/test_architecture_user_hook_home_reference.py, and a MutationCase.
  • Tests: tests/unit/integration/test_user_hook_home_reference.py, and installed-CLI tests/integration/test_user_hook_home_reference_lifecycle.py (Claude/Copilot/Gemini/Kiro: $HOME form, run via sh -c from another cwd, migration, two-home round trip; Claude exec form and Cursor stay absolute).
  • Docs: per-harness table in hooks-and-commands.md, apm-usage guide, targets matrix link, CHANGELOG.

Closes #2821

User-scope installs expanded the installing host's home directory into the
merged hook `command` entries, so a `~/.claude/settings.json` kept in a
dotfiles repo differed on every machine it was synced to -- and a manually
normalized file was rewritten back on the next `apm install -g`.

On POSIX hosts, anchor the rewritten path to `$HOME` when the deployed
script lives under the deploy root. Hooks run through a shell, which
expands `$HOME` at invocation time, so the microsoft#1310 / microsoft#1354 cwd-independence
is preserved while the merged file becomes host-independent. Windows
keeps the absolute form, and a dynamic target root outside the home
directory (for example CLAUDE_CONFIG_DIR) stays absolute too.

The idempotent upsert already strips prior entries through their
`_apm_source` ownership marker rather than by comparing command strings,
so a reinstall converges on the anchored form without duplicating hooks.

Fixes microsoft#2821

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Critical and moderate implementation issues remain, along with documentation and changelog follow-ups.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

This PR anchors POSIX user-scope hook commands to $HOME, preserving absolute paths for Windows and external roots.

Changes:

  • Updates hook rewriting and scope propagation.
  • Adds unit and lifecycle coverage.
  • Updates documentation and changelog entries.
  • Outstanding fixes remain for quoted $HOME expansion and external-root bundle copying.
File summaries
File Summary
tests/unit/integration/test_hook_integrator.py Tests path rewriting across platforms and roots.
tests/integration/test_hook_js_sidecar_lifecycle_contract.py Covers $HOME expansion during lifecycle execution.
tests/integration/test_hook_integrator_copilot_casing_e2e.py Tests scoped Copilot and Kiro paths.
src/apm_cli/integration/hook_integrator.py Implements $HOME-anchored paths; critical (2 votes) single-quote expansion and moderate (1 vote) external-root bundle-copy issues remain.
src/apm_cli/install/services.py Updates user-scope hook handling.
docs/src/content/docs/reference/targets-matrix.md Documents target path behavior.
docs/src/content/docs/producer/author-primitives/hooks-and-commands.md Documents portable hook paths; usage skill documentation also needs updating (nit, 3 votes).
CHANGELOG.md Records the fix; PR number should be appended (nit, 3 votes).
Review details

Suppressed comments (1)

src/apm_cli/integration/hook_integrator.py:605

  • When CLAUDE_CONFIG_DIR is an absolute path outside HOME, root_dir and each target_rel are absolute. This branch returns an absolute command, but copy_deployed_hook_bundle later calls ensure_path_within(target_file, project_root) for that same target (hook_bundle.py:201-203), which rejects the script outside HOME; a real global install containing a hook therefore fails. Support the absolute root through bundle copying and manifest bookkeeping as well, or do not advertise this case as supported.
                    # A dynamic target root such as CLAUDE_CONFIG_DIR may live
                    # outside the deploy root. Keep that explicit absolute path
                    # rather than emitting a misleading $HOME-relative command.
  • Files reviewed: 8/8 changed files
  • Comments generated: 3
  • Review effort level: Lite

💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread CHANGELOG.md Resolved
@Bronyal-lzx lzx (Bronyal-lzx) changed the title fix: anchor POSIX user-scope hook commands to $HOME fix(hooks): anchor POSIX user-scope hook commands to $HOME Sep 11, 2026
@Bronyal-lzx

Copy link
Copy Markdown
Contributor Author

@microsoft-github-policy-service agree

Review feedback on microsoft#2944: a shell expands $HOME outside single quotes
only, so anchoring a single-quoted reference turned
`node '${CLAUDE_PLUGIN_ROOT}/hooks/run.mjs'` into a literal
'$HOME/.claude/hooks/...' path the target would never expand. Thread the
quote character through instead of a boolean and anchor only for
unquoted or double-quoted references.

Also sync the shipped apm-guide package-authoring resource and the
CHANGELOG PR reference.
@Bronyal-lzx

Copy link
Copy Markdown
Contributor Author

Thanks for the review — all three items are addressed in b8afdbd, and I checked the fourth.

Single-quoted references (critical). Confirmed, and it was a regression I introduced rather than pre-existing behavior: the old absolute form worked under any quoting, while node '${CLAUDE_PLUGIN_ROOT}/hooks/run.mjs' became node '$HOME/.claude/hooks/…', where the shell expands nothing. Anchoring now happens only for unquoted or double-quoted references, so the quote character is threaded through instead of a boolean. Regression test added: test_rewrite_command_single_quoted_reference_stays_absolute.

CHANGELOG PR reference. Fixed — the entry now ends with (#2944).

apm-guide resource. Fixed — packages/apm-guide/.apm/skills/apm-usage/package-authoring.md now documents the $HOME anchor and its three exceptions: Windows, single-quoted references, and a dynamic target root outside the home directory.

Absolute root outside HOME and bundle copying (suppressed comment). Verified as independent of this diff: on an untouched main checkout, the same input produces the same absolute command and the same absolute copy target, so the ensure_path_within rejection in copy_deployed_hook_bundle predates this PR. This change neither touches hook_bundle.py nor alters that path's behavior, so I left it alone rather than widening the scope — happy to open a follow-up for end-to-end support of an absolute root if that is wanted.

Local re-run after the fix: 195 passed (hook unit suite plus the in-process install-dispatch suite), 5 passed (real-CLI lifecycle contract against a rebuilt binary), ruff clean. The Mode B substantive-line count for this diff is now 22, above the 20-line threshold, so the PR body carries the documented apm-spec-waiver instead of a spec citation.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Three unresolved moderate findings remain involving repeated mixed-quote replacements and lifecycle shell-expansion coverage.

Review details

Suppressed comments (3)

src/apm_cli/integration/hook_integrator.py:699

  • The quote policy is computed for the current match, but this global replacement rewrites every identical reference in the command. For example, bash "${CLAUDE_PLUGIN_ROOT}/hooks/run.sh" && bash '${CLAUDE_PLUGIN_ROOT}/hooks/run.sh' makes the second occurrence $HOME/... inside single quotes, where it is literal and the hook fails. Replace only the current occurrence (for example with count=1, while processing matches in order) so each reference keeps its own quote semantics.
                    _wrapping_quote(command, match),
                )
                new_command = new_command.replace(full_var, resolved_cmd)

src/apm_cli/integration/hook_integrator.py:749

  • The same global replacement issue applies to repeated relative references with mixed quoting. If an unquoted/double-quoted ./hooks/run.sh appears before a single-quoted copy, this replaces both with $HOME/..., leaving the latter as a literal path and breaking that hook. Limit the replacement to the current match so the single-quoted occurrence remains absolute.
                    _wrapping_quote(command, match),
                )
                new_command = new_command.replace(rel_ref, resolved_cmd)

tests/integration/test_hook_js_sidecar_lifecycle_contract.py:731

  • This lifecycle test replaces $HOME in the parsed argv before invoking the hook, so it never exercises the shell expansion that makes the new representation executable. A regression that writes a literal $HOME path or invokes this command without a shell would still pass here; run the generated command through the same POSIX shell with the isolated HOME (and keep a platform-appropriate direct invocation for Windows) so this contract is actually covered.
    hook_argv = [arg.replace("$HOME", str(scenario.isolated.home)) for arg in command[1:]]
  • Files reviewed: 9/9 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

@sergio-sisternes-epam

Sergio Sisternes (sergio-sisternes-epam) commented Sep 18, 2026 •

Copy link
Copy Markdown
Collaborator

PR triage recommendation

needs-issue

Recommendation only, not merge or scope approval. A responsible
human maintainer must approve. Labels, automated advice, and
silence are not approval.

Linked issue

#2821 (open). Labels: theme/portability, area/multi-target,
type/feature, triage/recommended. Not labelled status/accepted.
A maintainer withdrew prior acceptance on 2026-09-12 as part of
APM's contribution reset
(#2821 (comment)).

Proposed classification

theme/portability, area/multi-target, type/feature
(aligned with #2821; PR had no labels).

CODEOWNERS: Daniel Meppiel (@danielmeppiel), Sergio Sisternes (@sergio-sisternes-epam).

Suggested next action

Wait for a responsible human maintainer to record bounded scope
and status/accepted on #2821 before this implementation is
invited.

Thank you for contributing this pull request. APM starts with an
issue, not an implementation
(https://github.com/microsoft/apm/blob/main/CONTRIBUTING.md).
This PR already links #2821, but that issue is not currently
labelled status/accepted. A maintainer withdrew prior acceptance
on 2026-09-12 as part of a contribution reset. Please wait for a
responsible human maintainer to review and accept the scope on
#2821 first. This PR is labelled status/deferred until that
happens.


Generated by autopilot-pr-triage-worker. This comment is AI-generated and may contain errors.

@sergio-sisternes-epam Sergio Sisternes (sergio-sisternes-epam) added triage/recommended Automated advice completed; not human scope approval. status/deferred Not invited for implementation now; no release commitment. theme/portability area/multi-target Multi-target deploy spec, target directory creation, agent surface routing. type/feature New capability, new flag, new primitive. labels Sep 18, 2026
@danielmeppiel Daniel Meppiel (danielmeppiel) removed the status/deferred Not invited for implementation now; no release commitment. label Nov 12, 2026
@danielmeppiel

Copy link
Copy Markdown
Collaborator

Update (Daniel Meppiel (@danielmeppiel), 2026-11-12): to ship this sooner, maintainers will reshape this PR to the recorded scope now rather than waiting until 11-14. We will push to this branch where permitted, or otherwise open a successor PR that preserves your commits and authorship. Thank you for the contribution; your review of the reshaped version is welcome.


Posted with AI assistance on behalf of Daniel Meppiel (@danielmeppiel).

Reshapes microsoft#2944 to the approved microsoft#2821 scope. Whether a user-scope hook
command may use $HOME is now a per-harness capability on TargetProfile
(UserHookHomeReference) instead of a host-OS gate. It is enabled only
where the harness's current official docs state the command runs in a
POSIX shell: Claude Code shell-form command, Copilot CLI bash, Gemini CLI
command and Kiro command actions. Cursor, Codex and Windsurf, exec form
(args), shell: powershell, Copilot's cross-platform command, Windows
hosts, single-quoted references and roots outside home keep absolute
paths.

Each reference is now replaced at its own position, so repeated
references with mixed quoting keep their own policy (Copilot review on
hook_integrator.py:699/749). The global Copilot lifecycle contract now
runs the hook through sh -c. New installed-CLI tests cover each enabled
harness, in-place migration from absolute entries and a two-home round
trip.

apm-spec-waiver: user-scope hook path spelling only; no OpenAPM-observable requirement changes

Co-authored-by: Bronyal-lzx <[email protected]>
Co-authored-by: Copilot App <[email protected]>
TargetProfile.user_hook_home_reference becomes a canonical decision on
the existing targets.py owner record. The new static rule requires hook
rewriters to resolve the capability and call reference_for, and rejects
host-OS gates or hard-coded $HOME in hook_integrator.py and
kiro_hook_integrator.py. Adds the mutation matrix case and a dedicated
architecture test.

Co-authored-by: Bronyal-lzx <[email protected]>
Co-authored-by: Copilot App <[email protected]>
Replaces the POSIX-host description with the per-harness table, keeps
the absolute-path exceptions, and moves the changelog entry into
Unreleased with contributor credit (Copilot review on the apm-guide
package-authoring resource).

Co-authored-by: Bronyal-lzx <[email protected]>
Co-authored-by: Copilot App <[email protected]>
hook_integrator.py sits at the 2100-line CI guard after merging main, so
the anchoring decision moves fully into UserHookHomeReference: anchor()
spells the path and for_handler() drops exec-form (args) handlers. The
quote and splice helpers join the hook command parsing module, and the
rewriter binds its per-command arguments once. The static guard, the
mutation case and the architecture test follow the new owner API.

Co-authored-by: Bronyal-lzx <[email protected]>
Co-authored-by: Copilot App <[email protected]>
The frozen semantic rule inventory must list
mutation_writes.user_hook_home_reference (CI Build & Test Shard 2).

Co-authored-by: Bronyal-lzx <[email protected]>
Co-authored-by: Copilot App <[email protected]>
- splice_references rejects overlapping edits instead of garbling output
  (python-architect, supply-chain-security-expert), with a unit trap.
- Docs: HOME-mismatch caution admonition (devx-ux-expert), clearer
  Copilot row and POSIX wording, targets-matrix links to the single
  per-harness rule (doc-writer), shorter CHANGELOG entry.
- Installed-CLI lifecycle adds a Claude exec-form (args) case that must
  stay absolute (test-coverage-expert).

Co-authored-by: Bronyal-lzx <[email protected]>
Co-authored-by: Copilot App <[email protected]>
@danielmeppiel

Copy link
Copy Markdown
Collaborator

APM Review Panel: ship_with_followups

User-scope hook commands now use $HOME paths, so they work across machines. This applies only to harnesses whose official docs confirm they run the command in a shell.

panel-mode=full; personas=python-architect,test-coverage-expert,doc-writer,devx-ux-expert,supply-chain-security-expert,apm-ceo

cc lzx (@Bronyal-lzx) Daniel Meppiel (@danielmeppiel) Sergio Sisternes (@sergio-sisternes-epam) -- a fresh advisory pass is ready for your review.

The panel found no blocking issues. Each harness's evidence (does it run hook commands through a shell?) lives on TargetProfile as a frozen UserHookHomeReference capability. The hook rewriter checks the harness's documented behavior instead of the host OS. The contributor's commits are preserved and credited; the maintainer reshape happened on the same branch.

python-architect and supply-chain-security-expert independently flagged that splice_references accepted overlapping spans. test-coverage-expert confirmed that every "Done when" item has a regression trap at integration or e2e level. All five in-scope follow-ups below are already folded at this head.

Aligned with:

  • Portable by manifest: one install works on another machine with a different home directory.
  • Secure by default: unverified harnesses, exec form, single quotes and custom roots keep absolute paths.
  • Governed by policy: a single owner plus a static guard and 8 architecture mutations.
  • Multi-harness: 4 harnesses enabled with a cited source each; 3 stay absolute pending docs.
  • Pragmatic as npm: no new flags; migration happens in place on reinstall.

Panel summary

Persona B R N Takeaway
Python Architect 0 0 2 Single-owner discipline is clean: UserHookHomeReference owns all anchoring decisions and rewriters delegate. The positional splice fixes mixed quoting.
Test Coverage Expert 0 0 1 Every "Done when" item has a regression trap. Real-CLI lifecycle covers migration and a two-home round trip, plus 8 architecture mutation guards.
Doc Writer 0 1 2 Docs match targets.py for all four enabled harnesses and every exception. Only polish remains.
DevX UX Expert 0 1 1 Anchoring is driven by per-harness evidence. Make the HOME-mismatch failure more visible.
Supply Chain Security Expert 0 0 1 No new escalation from $HOME anchoring. Containment, quoting and ownership are correct.

B = blocking-severity findings, R = recommended, N = nits.
Counts are signal strength, not gates. The maintainer ships.

Top 4 follow-ups

  1. [Python Architect + Supply Chain Security Expert] splice_references now rejects overlapping spans -- folded in 15bc65c with a unit trap.
  2. [DevX UX Expert] The HOME-mismatch caveat is now a :::caution block that names the symptom -- folded in 15bc65c.
  3. [Doc Writer] targets-matrix now links to the per-harness rule instead of restating it -- folded in 15bc65c.
  4. [DevX UX Expert] Clearer Copilot table row and POSIX wording; shorter CHANGELOG entry -- folded in 15bc65c.

Architecture

classDiagram
    direction LR
    class TargetProfile {
        <<ValueObject>>
        +root_dir str
        +user_hook_home_reference UserHookHomeReference | None
        +for_scope(user_scope) TargetProfile | None
    }
    class UserHookHomeReference {
        <<Strategy>>
        +shell_selectors tuple
        +evidence str
        +reference str
        +for_handler(handler) UserHookHomeReference | None
        +reference_for(selector, quote) str | None
        +anchor(path, selector, quote) str
    }
    class HookIntegrator {
        -_home_reference_for_hook_rewrite(target, user_scope)
        -_rewrite_hooks_data()
        -_rewrite_command_for_target()
        -_project_scoped_command_path()
    }
    class KiroHookIntegrator {
        +integrate_kiro_hooks()
    }
    TargetProfile *-- UserHookHomeReference : optional capability
    HookIntegrator ..> UserHookHomeReference : for_handler and anchor
    KiroHookIntegrator ..> HookIntegrator : shared helper
    class TargetProfile:::touched
    class UserHookHomeReference:::touched
    class HookIntegrator:::touched
    class KiroHookIntegrator:::touched
    classDef touched fill:#fff3b0,stroke:#d47600
Loading
flowchart TD
    A["apm install -g"] --> B["TargetProfile.for_scope(user_scope=True)"]
    B --> E["_home_reference_for_hook_rewrite"]
    E --> G{"for_handler: exec form (args)?"}
    G -->|yes| M["absolute path"]
    G -->|no| K["anchor(path, field, quote)"]
    K --> L{"shell field, not single-quoted, POSIX host?"}
    L -->|no| M
    L -->|yes| N{"path under home?"}
    N -->|no: custom root| M
    N -->|yes| O["$HOME/relative"]
Loading

Recommendation

The panel recommends shipping: there are no blocking findings, no failing tests and no new security exposure. The convergent follow-up was the splice_references overlap guard, and all follow-ups are folded at this head. CI is green and the PR is ready for maintainer review.

Folded in this run

  • (copilot) Each plugin-root or relative reference is replaced at its own position, so repeated references keep their own quote policy -- resolved in 2b6c2b0.
  • (copilot) The global Copilot lifecycle contract now runs the bash command through sh -c -- resolved in 2b6c2b0.
  • (copilot) The apm-usage guide describes the per-harness rule -- resolved in bfb5a9b.
  • (panel) Scope reshape: the per-harness UserHookHomeReference capability replaces the host-OS gate. It is enabled only for harnesses whose docs verify shell execution (source table in the PR body) -- resolved in 2b6c2b0 and 635a155.
  • (panel) New-owner dual guardrail: registry guard, static rule, architecture test, MutationCase and the frozen rule inventory -- resolved in 311d935 and fc3ee71.
  • (panel) Overlap guard, caution admonition, docs link and wording, and a Claude exec-form lifecycle case -- resolved in 15bc65c.

Copilot signals reviewed

  • src/apm_cli/integration/hook_integrator.py:625 -- LEGIT: single-quoted $HOME is never expanded; references inside single quotes stay absolute (resolved in b8afdbd).
  • CHANGELOG.md -- LEGIT: the entry needed the PR number; now under Unreleased with credit (resolved in bfb5a9b).
  • docs/.../hooks-and-commands.md:292 -- LEGIT: the apm-usage guide had drifted (resolved in bfb5a9b).
  • src/apm_cli/integration/hook_integrator.py:699 and :749 -- LEGIT: global replace applied one quote policy to every occurrence; now replaced by position (resolved in 2b6c2b0).
  • tests/integration/test_hook_js_sidecar_lifecycle_contract.py:731 -- LEGIT: the test skipped shell expansion; now runs through sh -c (resolved in 2b6c2b0).
  • src/apm_cli/integration/hook_integrator.py:605 -- NOT-LEGIT for this PR: rejecting the bundle copy for a CLAUDE_CONFIG_DIR outside HOME predates this change. The approved scope keeps custom roots absolute and unchanged.

Regression-trap evidence (mutation-break gate)

  • tests/unit/integration/test_user_hook_home_reference.py -- removed each of these in turn: capability lookup, exec-form check, single-quote check, field selectors, home containment, overlap guard. Each removal made tests fail; guards restored.
  • tests/integration/test_user_hook_home_reference_lifecycle.py::...[claude] -- with the capability ignored, the test failed; restored.
  • tests/integration/test_architecture_user_hook_home_reference.py plus the owner MutationCase -- with the static rule gutted, 7 tests failed; restored.

Lint contract

The full CI lint mirror is silent at fe6c0d2:

  • ruff check and format (src, tests, architecture linter)
  • pylint R0801
  • lint-auth-signals
  • lint-architecture-boundaries
  • 2100-line guard (hook_integrator.py is 2098 lines)

CI

All checks at fe6c0d2 pass: 23 success, 2 neutral, 1 skipped, including Lifecycle Smoke, Windows compatibility, Spec conformance and the required-checks rollup. license/cla passes. This took 1 CI fix iteration: the frozen architecture rule inventory needed the new rule.

Mergeability status

PR head SHA CEO stance iters folds defers Copilot rounds CI mergeable mergeStateStatus notes
#2944 fe6c0d2 ship_with_followups 1 11 0 1 green MERGEABLE BLOCKED pending required review
Full per-persona findings

Python Architect

  • [nit] splice_references should defensively assert non-overlapping edits at src/apm_cli/integration/hook_command_paths.py:105 -- folded (raises ValueError).
  • [nit] Strategy + ValueObject + dual guardrail are well applied; no further abstraction needed.

Test Coverage Expert

  • [nit] The lifecycle parametrize had no exec-form case -- folded as the claude-exec-form lifecycle case.

Doc Writer

  • [recommended] Per-harness rule restated in targets-matrix.md -- folded (link instead).
  • [nit] "no documented POSIX shell execution" wording -- folded.
  • [nit] CHANGELOG entry length -- folded (trimmed).

DevX UX Expert

  • [recommended] The HOME-mismatch caveat was buried -- folded as a :::caution block.
  • [nit] Copilot table row ambiguity -- folded.

Supply Chain Security Expert

  • [nit] splice_references silently accepted overlapping spans -- folded.

This panel is advisory. It does not block merge. Re-apply the
panel-review label after addressing feedback to re-run.


Generated by autopilot-pr-merge-worker. This comment is AI-generated and may contain errors.

Bring PR microsoft#2944 up to date with main 90e76bf. Both overlapping
files merged keeping both intents: CHANGELOG.md keeps main's microsoft#3630
entry alongside this PR's microsoft#2944 entry under Unreleased/Fixed, and
test_architecture_owner_rule_mutations.py keeps main's updated
github_downloader intent plus this PR's user-hook-home-reference case.

Co-authored-by: Copilot App <[email protected]>
@danielmeppiel

Copy link
Copy Markdown
Collaborator

Merged current main into this branch at 90e76bf -> f6ba150 (merge-of-main fallback; branch history already carries merge-from-main commits, so no force push was needed).

Overlapping paths merged (faithful merge of both intents; git resolved them without textual conflict):

No regression-trap test from this PR was changed by the merge.

Lint contract: ruff check and ruff format --check (src/ tests/ and linter scripts) silent, pylint R0801 10.00/10, lint-auth-signals.sh and lint-architecture-boundaries.sh exit 0, no src file over 2100 lines.

Targeted functional tests re-run at f6ba150: test_user_hook_home_reference (26), test_user_root_context (24), test_hook_integrator (188), copilot casing e2e (7), user-hook home reference lifecycle + global copilot sidecar contract (7), architecture user-hook home reference (9) -- all passed. CI at f6ba150: 22 pass, 2 skipping, 0 failing.

Post-push mergeability: gh pr view --json mergeStateStatus,mergeable reports BLOCKED / MERGEABLE (BLOCKED reflects the repo ruleset: code-owner review + merge queue). Push used git push https://github.com/Bronyal-lzx/apm.git HEAD:refs/heads/fix/posix-user-hook-home-anchor (plain fast-forward, never --force).

Ready for maintainer review.


This comment was generated by an AI agent on behalf of the maintainers. It may contain mistakes; please verify before acting on it.

@danielmeppiel
Daniel Meppiel (danielmeppiel) merged commit 0b076ef into microsoft:main Nov 12, 2026
24 checks passed
Daniel Meppiel (danielmeppiel) added a commit that referenced this pull request Nov 12, 2026
Resolve hook_integrator.py: keep #2944's _DOT_NAMED_HOOK_ROOTS and drop
the retired _filter_hook_files_for_target seam (filename routing is
removed by this PR).

Co-authored-by: Copilot App <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/multi-target Multi-target deploy spec, target directory creation, agent surface routing. triage/recommended Automated advice completed; not human scope approval. type/feature New capability, new flag, new primitive.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEATURE] Anchor user-scope hook commands to $HOME on POSIX targets so ~/.claude/settings.json stays portable across machines

4 participants