@lilmgenius/win-hooks 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,147 @@
1
+ #!/bin/bash
2
+ # win-hooks: fix-bare-commands
3
+ # Rewrites bare interpreter commands (node, python, python3, npx, npm) in
4
+ # ~/.claude/settings.json hook commands to quoted absolute paths.
5
+ #
6
+ # Fixes errors like "지정된 경로를 찾을 수 없습니다" / "The system cannot find
7
+ # the path specified" that occur when Claude Code launches a hook via cmd.exe
8
+ # and cmd's PATH doesn't contain the bare interpreter — even though bash does.
9
+ #
10
+ # Requires: node (guaranteed by Claude Code), cygpath (Git Bash built-in)
11
+ #
12
+ # Usage: fix-bare-commands [--dry-run]
13
+ # --dry-run: show what would change without modifying files
14
+ #
15
+ # Output: tab-separated lines to stdout:
16
+ # location\told_command\tnew_command
17
+ #
18
+ # Exit code: 0 = success or nothing to fix, 1 = error
19
+
20
+ set -uo pipefail
21
+
22
+ DRY_RUN=false
23
+ [[ "${1:-}" == "--dry-run" ]] && DRY_RUN=true
24
+
25
+ SETTINGS="${HOME}/.claude/settings.json"
26
+ [[ ! -f "$SETTINGS" ]] && exit 0
27
+
28
+ if ! command -v node &>/dev/null; then
29
+ echo "win-hooks: node not found, cannot fix bare commands" >&2
30
+ exit 1
31
+ fi
32
+
33
+ # Resolve a bare command to a Windows-compatible absolute path.
34
+ # Echoes empty string if not resolvable or target file doesn't exist.
35
+ resolve_cmd() {
36
+ local name="$1"
37
+ local p
38
+ p=$(command -v "$name" 2>/dev/null) || return 0
39
+ # Must be a real path (not a shell builtin/alias).
40
+ [[ -z "$p" || "$p" != /* ]] && return 0
41
+ # For python/python3, reject a non-functional interpreter (dead Microsoft
42
+ # Store App Execution Alias stub) by actually running it — location-agnostic,
43
+ # so a real Store-installed Python is kept while the dead stub is dropped.
44
+ # Returning empty lets python3 fall back to the resolved python (CASE-09).
45
+ case "$name" in
46
+ python|python3) "$name" -c "" >/dev/null 2>&1 || return 0 ;;
47
+ esac
48
+ # Convert /c/Foo/bar to C:/Foo/bar; cygpath -m also auto-appends .exe when appropriate.
49
+ if command -v cygpath &>/dev/null; then
50
+ p=$(cygpath -m "$p" 2>/dev/null) || return 0
51
+ fi
52
+ # Defensive: ensure resolved file actually exists.
53
+ if [[ ! -f "$p" ]]; then
54
+ if [[ -f "${p}.exe" ]]; then
55
+ p="${p}.exe"
56
+ else
57
+ return 0
58
+ fi
59
+ fi
60
+ printf '%s' "$p"
61
+ }
62
+
63
+ NODE_PATH_RESOLVED=$(resolve_cmd node)
64
+ PYTHON_PATH_RESOLVED=$(resolve_cmd python)
65
+ PYTHON3_PATH_RESOLVED=$(resolve_cmd python3)
66
+ [[ -z "$PYTHON3_PATH_RESOLVED" ]] && PYTHON3_PATH_RESOLVED="$PYTHON_PATH_RESOLVED"
67
+ NPX_PATH_RESOLVED=$(resolve_cmd npx)
68
+ NPM_PATH_RESOLVED=$(resolve_cmd npm)
69
+
70
+ export WH_NODE="$NODE_PATH_RESOLVED"
71
+ export WH_PYTHON="$PYTHON_PATH_RESOLVED"
72
+ export WH_PYTHON3="$PYTHON3_PATH_RESOLVED"
73
+ export WH_NPX="$NPX_PATH_RESOLVED"
74
+ export WH_NPM="$NPM_PATH_RESOLVED"
75
+ export WH_DRY_RUN="$DRY_RUN"
76
+
77
+ node - "$SETTINGS" << 'JSEOF'
78
+ const fs = require('fs');
79
+ const settingsPath = process.argv[2];
80
+ const dryRun = process.env.WH_DRY_RUN === 'true';
81
+
82
+ const resolvers = {
83
+ node: process.env.WH_NODE || '',
84
+ python: process.env.WH_PYTHON || '',
85
+ python3: process.env.WH_PYTHON3 || '',
86
+ npx: process.env.WH_NPX || '',
87
+ npm: process.env.WH_NPM || '',
88
+ };
89
+
90
+ const raw = fs.readFileSync(settingsPath, 'utf8').replace(/^\uFEFF/, '');
91
+ let data;
92
+ try {
93
+ data = JSON.parse(raw);
94
+ } catch (e) {
95
+ process.stderr.write('win-hooks: settings.json parse error: ' + e.message + '\n');
96
+ process.exit(1);
97
+ }
98
+
99
+ if (!data.hooks) process.exit(0);
100
+
101
+ const changes = [];
102
+ // Match a leading bare interpreter followed by whitespace or end-of-string.
103
+ // Interpreters with paths (./node, /usr/bin/node, C:/.../node.exe) won't match.
104
+ const BARE_RE = /^(node|python3|python|npx|npm)(\s|$)/;
105
+
106
+ function walk(obj, loc) {
107
+ if (Array.isArray(obj)) {
108
+ obj.forEach((item, i) => walk(item, loc + '[' + i + ']'));
109
+ } else if (obj && typeof obj === 'object') {
110
+ if (typeof obj.command === 'string') {
111
+ const m = obj.command.match(BARE_RE);
112
+ if (m) {
113
+ const name = m[1];
114
+ const abs = resolvers[name];
115
+ if (abs) {
116
+ const rest = obj.command.slice(name.length);
117
+ const fixed = '"' + abs + '"' + rest;
118
+ changes.push({ loc, old: obj.command, fixed });
119
+ if (!dryRun) obj.command = fixed;
120
+ }
121
+ }
122
+ }
123
+ for (const [k, v] of Object.entries(obj)) {
124
+ walk(v, loc + '.' + k);
125
+ }
126
+ }
127
+ }
128
+
129
+ walk(data.hooks, 'hooks');
130
+
131
+ if (changes.length === 0) process.exit(0);
132
+
133
+ for (const c of changes) {
134
+ console.log(c.loc + '\t' + c.old + '\t' + c.fixed);
135
+ }
136
+
137
+ if (!dryRun) {
138
+ const bakPath = settingsPath + '.winhooks.bak';
139
+ if (!fs.existsSync(bakPath)) {
140
+ fs.copyFileSync(settingsPath, bakPath);
141
+ }
142
+ fs.writeFileSync(settingsPath, JSON.stringify(data, null, 2) + '\n');
143
+ process.stderr.write('win-hooks: fixed ' + changes.length + ' bare command(s) in settings.json\n');
144
+ } else {
145
+ process.stderr.write('win-hooks: would fix ' + changes.length + ' bare command(s) (dry-run)\n');
146
+ }
147
+ JSEOF
@@ -0,0 +1,132 @@
1
+ #!/bin/bash
2
+ # win-hooks: scripts/lib/plugins.sh
3
+ # Shared plugin-enumeration and encoding helpers (SSOT — see CLAUDE.md
4
+ # Work Principles). Sourced by find-incompatible, verify, apply-patches, and
5
+ # reheal so the "how do we read installed_plugins.json / strip BOM / resolve
6
+ # a working Python / validate JSON" logic lives in exactly one place instead
7
+ # of drifting across four copies.
8
+ #
9
+ # Not standalone: relies on the caller's `set -[eu]` and does not itself set
10
+ # any shell options.
11
+
12
+ # Strip a UTF-8 BOM (EF BB BF) from stdin, if present.
13
+ wh_strip_bom() { sed '1s/^\xEF\xBB\xBF//'; }
14
+
15
+ # Un-escape a hook command as it appears in scanner output, where JSON string
16
+ # quoting is preserved (`\"` for a literal quote). Turns the stored form back
17
+ # into the shell command the hook actually runs, so path/interpreter parsing
18
+ # sees real quotes. Shared by apply-patches (Claude) and the codex-* scripts.
19
+ wh_decode_json_command() { printf '%s' "$1" | sed 's/\\"/"/g'; }
20
+
21
+ # Parse installed_plugins.json (v1 or v2 format) at the given path.
22
+ # Output: plugin_name\tinstall_path (backslashes collapsed to forward slashes).
23
+ # v2 wraps plugins under {"version":2,"plugins":{"name@source":[{...}]}} —
24
+ # both formats key each installPath under a preceding quoted "name": [ line,
25
+ # so a single awk pass handles both (CASE-06).
26
+ wh_parse_plugins() {
27
+ local installed="$1"
28
+ [[ -f "$installed" ]] || return 0
29
+ wh_strip_bom < "$installed" | awk '
30
+ /": \[/ {
31
+ sub(/^[[:space:]]*"/, "")
32
+ sub(/".*/, "")
33
+ plugin = $0
34
+ next
35
+ }
36
+ /"installPath"/ {
37
+ sub(/.*"installPath"[[:space:]]*:[[:space:]]*"/, "")
38
+ sub(/".*/, "")
39
+ path = $0
40
+ if (plugin != "" && path != "") print plugin "\t" path
41
+ }
42
+ ' | sed 's/[\\][\\]*/\//g'
43
+ }
44
+
45
+ # Iterate installed plugins that ship a hooks/hooks.json, skipping win-hooks
46
+ # itself (it self-edits its own hooks.json timeout at SessionStart — CASE-25 —
47
+ # which would otherwise cause callers like `reheal` to re-trigger on their own
48
+ # write).
49
+ # Output: plugin_name\tinstall_path\thooks_file
50
+ wh_each_plugin_hooksjson() {
51
+ local installed="$1"
52
+ wh_parse_plugins "$installed" | while IFS=$'\t' read -r plugin install_path; do
53
+ [[ "$plugin" == *"win-hooks"* ]] && continue
54
+ local hooks_file="${install_path}/hooks/hooks.json"
55
+ [[ -f "$hooks_file" ]] || continue
56
+ printf '%s\t%s\t%s\n' "$plugin" "$install_path" "$hooks_file"
57
+ done
58
+ }
59
+
60
+ # Resolve a working Python to an absolute path via a functional probe
61
+ # (`"$py" -c ""` exits 0), not a path heuristic — accepts any real
62
+ # Store/conda/python.org interpreter and rejects only a dead Microsoft Store
63
+ # App Execution Alias stub, wherever it lives (CASE-09). Prints nothing and
64
+ # returns non-zero if no Python works.
65
+ wh_resolve_python() {
66
+ local _py _p
67
+ for _py in python3 python py; do
68
+ command -v "$_py" >/dev/null 2>&1 || continue
69
+ "$_py" -c "" >/dev/null 2>&1 || continue
70
+ _p=$(command -v "$_py")
71
+ command -v cygpath >/dev/null 2>&1 && _p=$(cygpath -m "$_p" 2>/dev/null || printf '%s' "$_p")
72
+ [[ -f "$_p" ]] || { [[ -f "${_p}.exe" ]] && _p="${_p}.exe"; }
73
+ printf '%s' "$_p"
74
+ return 0
75
+ done
76
+ return 1
77
+ }
78
+
79
+ # Print a wrapper-body script that execs the plugin-root script <rel> under the
80
+ # right runtime for <interp>: a resolved absolute Python for python/python3
81
+ # (CASE-09 — bare python3 may be a dead Store stub, or a different interpreter
82
+ # under cmd.exe dispatch), bash for .sh/bash/sh, else the script directly. A
83
+ # graceful exit-0 no-op when a python hook has no working interpreter. Shared by
84
+ # the Codex patcher (generate_wrapper) and verifier (create_wrapper_body) so
85
+ # their wrapper bodies cannot drift (see the CASE-09-parity regression).
86
+ wh_wrapper_exec_body() {
87
+ local rel="$1" interp="$2" _py
88
+ if [[ "$interp" == "python3" || "$interp" == "python" ]]; then
89
+ _py=$(wh_resolve_python || true)
90
+ if [[ -n "$_py" ]]; then
91
+ printf '#!/bin/bash\nSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"\nPLUGIN_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"\nexec "%s" "$PLUGIN_ROOT/%s" "$@"\n' "$_py" "$rel"
92
+ else
93
+ printf '#!/bin/bash\n# win-hooks: no working Python found; graceful no-op\nexit 0\n'
94
+ fi
95
+ elif [[ "$rel" == *.sh || "$interp" == "bash" || "$interp" == "sh" ]]; then
96
+ printf '#!/bin/bash\nSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"\nPLUGIN_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"\nexec bash "$PLUGIN_ROOT/%s" "$@"\n' "$rel"
97
+ else
98
+ printf '#!/bin/bash\nSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"\nPLUGIN_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"\nexec "$PLUGIN_ROOT/%s" "$@"\n' "$rel"
99
+ fi
100
+ }
101
+
102
+ # Validate that a file contains valid JSON. Fallback chain: node (guaranteed
103
+ # by Claude Code) -> powershell (Windows built-in) -> skip (no validator
104
+ # available, treated as valid so a missing runtime never blocks patching).
105
+ # Returns 0 if valid or unverifiable, 1 if invalid; prints an error message
106
+ # describing the failure on stdout+stderr (merged, per caller's `2>&1`).
107
+ wh_validate_json() {
108
+ local file="$1"
109
+ if command -v node &>/dev/null; then
110
+ node -e "
111
+ try {
112
+ const fs = require('fs');
113
+ let t = fs.readFileSync(process.argv[1],'utf8').replace(/^\uFEFF/,'');
114
+ JSON.parse(t);
115
+ } catch(e) {
116
+ process.stderr.write('JSON invalid: ' + e.message + '\n');
117
+ process.exit(1);
118
+ }
119
+ " "$file" 2>&1
120
+ return $?
121
+ fi
122
+ if command -v powershell.exe &>/dev/null; then
123
+ local ps_path
124
+ ps_path=$(cygpath -w "$file" 2>/dev/null || echo "$file")
125
+ powershell.exe -NoProfile -Command "
126
+ try { Get-Content -Raw -Encoding UTF8 '$ps_path' | ConvertFrom-Json | Out-Null }
127
+ catch { Write-Error \$_.Exception.Message; exit 1 }
128
+ " 2>&1
129
+ return $?
130
+ fi
131
+ return 0
132
+ }
@@ -0,0 +1,42 @@
1
+ #!/usr/bin/env node
2
+ // win-hooks: scripts/sync-version
3
+ // Single source of truth for the version = package.json "version". Propagates
4
+ // it into the plugin manifests so the four copies never drift (win-hooks' own
5
+ // SSOT principle — see CLAUDE.md Conventions).
6
+ //
7
+ // node scripts/sync-version write package.json's version into the manifests
8
+ // node scripts/sync-version --check exit 1 if any manifest disagrees (used by test/run.sh)
9
+
10
+ import { readFileSync, writeFileSync } from 'node:fs';
11
+ import { fileURLToPath } from 'node:url';
12
+ import { dirname, join } from 'node:path';
13
+
14
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
15
+ const check = process.argv.includes('--check');
16
+ const version = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')).version;
17
+
18
+ // Each target: file path + how to read/set its version (marketplace nests it).
19
+ const targets = [
20
+ { rel: '.claude-plugin/plugin.json', get: (d) => d.version, set: (d, v) => { d.version = v; } },
21
+ { rel: '.codex-plugin/plugin.json', get: (d) => d.version, set: (d, v) => { d.version = v; } },
22
+ { rel: '.claude-plugin/marketplace.json', get: (d) => d.plugins?.[0]?.version, set: (d, v) => { d.plugins[0].version = v; } },
23
+ ];
24
+
25
+ let drift = 0;
26
+ for (const t of targets) {
27
+ const path = join(ROOT, t.rel);
28
+ const data = JSON.parse(readFileSync(path, 'utf8'));
29
+ const current = t.get(data);
30
+ if (current === version) continue;
31
+ if (check) {
32
+ console.error(`version drift: ${t.rel} is ${current}, package.json is ${version}`);
33
+ drift++;
34
+ continue;
35
+ }
36
+ t.set(data, version);
37
+ writeFileSync(path, JSON.stringify(data, null, 2) + '\n');
38
+ console.log(`synced ${t.rel} -> ${version}`);
39
+ }
40
+
41
+ if (check && drift) process.exit(1);
42
+ if (check) console.log(`version ${version} is in sync across all manifests`);
package/scripts/verify ADDED
@@ -0,0 +1,334 @@
1
+ #!/bin/bash
2
+ # win-hooks: verify
3
+ # Post-patch health check for all installed plugins' hooks.
4
+ # Detects: invalid JSON, BOM, CRLF, missing wrappers, broken references.
5
+ #
6
+ # Dependencies: only coreutils (od, sed, grep, awk) + Git Bash.
7
+ # JSON validation uses fallback chain: node (guaranteed) -> powershell -> skip.
8
+ #
9
+ # Output: tab-separated lines to stdout:
10
+ # plugin\tinstall_path\tissue_type\tdetail
11
+ #
12
+ # Issue types:
13
+ # bom — UTF-8 BOM (EF BB BF) in any hook file (hooks/, _hooks/, or
14
+ # any file referenced from hooks.json via ${CLAUDE_PLUGIN_ROOT}/...)
15
+ # json_invalid — hooks.json is not valid JSON
16
+ # json_crlf — hooks.json contains CRLF line endings
17
+ # wrapper_missing — hooks.json references a _hooks/ wrapper that doesn't exist
18
+ # (--fix recreates it: passthrough `exec bash "$@"` when the
19
+ # patched command forwards the real target, else regenerated
20
+ # from hooks.json.bak — bash path-bake or probed-python bake)
21
+ # wrapper_broken — _hooks/ wrapper execs a bogus ${PLUGIN_ROOT}/<interpreter>
22
+ # target (path extraction grabbed the interpreter, not the
23
+ # script); fails with bash: .../bash: No such file or directory
24
+ # cmd_missing — _hooks/run-hook.cmd is missing but hooks.json references it
25
+ # recursive_wrapper — bash wrapper (.py/.js) calls python3/node on itself
26
+ # python3_stub — a hook invokes bare python3/python but it resolves to a
27
+ # Microsoft Store App Execution Alias stub (or is missing)
28
+ # backslash_path — settings.json hook command contains Windows backslash paths
29
+ # bare_command — settings.json hook command uses bare interpreter not resolvable by cmd.exe
30
+ #
31
+ # Exit code: number of issues found (0 = healthy, capped at 125)
32
+ #
33
+ # Usage: verify [--fix]
34
+ # --fix: auto-repair BOM/CRLF, broken/missing wrappers, and recursive wrappers in-place
35
+
36
+ set -uo pipefail
37
+
38
+ FIX_MODE=false
39
+ [[ "${1:-}" == "--fix" ]] && FIX_MODE=true
40
+
41
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
42
+ LIB="${SCRIPT_DIR}/lib/plugins.sh"
43
+ if [[ ! -f "$LIB" ]]; then
44
+ echo "win-hooks: shared lib not found: $LIB" >&2
45
+ exit 1
46
+ fi
47
+ source "$LIB"
48
+
49
+ INSTALLED="${HOME}/.claude/plugins/installed_plugins.json"
50
+ [[ ! -f "$INSTALLED" ]] && exit 0
51
+
52
+ ISSUES_FILE=$(mktemp)
53
+ trap 'rm -f "$ISSUES_FILE"' EXIT
54
+
55
+ # ── Helpers ────────────────────────────────────────────────────────
56
+
57
+ add_issue() {
58
+ local plugin="$1" path="$2" type="$3" detail="$4"
59
+ printf '%s\t%s\t%s\t%s\n' "$plugin" "$path" "$type" "$detail" >> "$ISSUES_FILE"
60
+ printf '%s\t%s\t%s\t%s\n' "$plugin" "$path" "$type" "$detail"
61
+ }
62
+
63
+ # ── Checks ─────────────────────────────────────────────────────────
64
+
65
+ check_bom() {
66
+ local plugin="$1" install_path="$2"
67
+ local hooks_file="${install_path}/hooks/hooks.json"
68
+ local file_list f bom rel
69
+
70
+ # Build deduped file list: standard hook dirs + every file the hooks.json
71
+ # references via ${CLAUDE_PLUGIN_ROOT}/... (catches wrappers in nonstandard
72
+ # subdirs like scripts/, bin/, etc.).
73
+ file_list=$({
74
+ for dir in "${install_path}/hooks" "${install_path}/_hooks"; do
75
+ [[ -d "$dir" ]] || continue
76
+ find "$dir" -maxdepth 1 -type f 2>/dev/null
77
+ done
78
+ if [[ -f "$hooks_file" ]]; then
79
+ grep -oE '\$\{CLAUDE_PLUGIN_ROOT\}/[A-Za-z0-9_./-]+' "$hooks_file" 2>/dev/null \
80
+ | sed "s|\${CLAUDE_PLUGIN_ROOT}|${install_path}|"
81
+ fi
82
+ } | sort -u)
83
+
84
+ while IFS= read -r f; do
85
+ [[ -z "$f" ]] && continue
86
+ [[ -f "$f" ]] || continue
87
+ case "$f" in *.json.bak|*.tmp) continue ;; esac
88
+ bom=$(od -A n -t x1 -N 3 "$f" 2>/dev/null | tr -d ' \n')
89
+ [[ "$bom" != "efbbbf" ]] && continue
90
+ rel="${f#$install_path/}"
91
+ add_issue "$plugin" "$install_path" "bom" "$rel"
92
+ if $FIX_MODE; then
93
+ tail -c +4 "$f" > "${f}.tmp" && mv "${f}.tmp" "$f"
94
+ echo " FIXED: stripped BOM from $rel" >&2
95
+ fi
96
+ done <<< "$file_list"
97
+ }
98
+
99
+ check_crlf() {
100
+ local plugin="$1" install_path="$2" hooks_file="$3"
101
+ if od -c "$hooks_file" 2>/dev/null | grep -q '\\r \\n'; then
102
+ add_issue "$plugin" "$install_path" "json_crlf" "CRLF line endings detected"
103
+ if $FIX_MODE; then
104
+ sed -i 's/\r$//' "$hooks_file" 2>/dev/null || {
105
+ sed 's/\r$//' "$hooks_file" > "${hooks_file}.tmp" && mv "${hooks_file}.tmp" "$hooks_file"
106
+ }
107
+ echo " FIXED: normalized CRLF in $hooks_file" >&2
108
+ fi
109
+ fi
110
+ }
111
+
112
+ check_json_valid() {
113
+ local plugin="$1" install_path="$2" hooks_file="$3"
114
+ local err
115
+ err=$(wh_validate_json "$hooks_file" 2>&1) || {
116
+ add_issue "$plugin" "$install_path" "json_invalid" "$err"
117
+ return 1
118
+ }
119
+ return 0
120
+ }
121
+
122
+ # Recreate a wrapper that hooks.json references but that is missing from _hooks/.
123
+ # Two cases:
124
+ # 1. The patched command forwards the real ${CLAUDE_PLUGIN_ROOT}/... target as a
125
+ # trailing arg (older patch form). run-hook.cmd passes it through as "$@", so
126
+ # the correct body is `exec bash "$@"`.
127
+ # 2. The path is baked into the wrapper body (current patch form, no trailing
128
+ # target). Recover the original command from hooks.json.bak by matching the
129
+ # generated wrapper name, then regenerate the body — probed-python bake for
130
+ # python/python3 hooks, else a bash/direct path bake (mirrors apply-patches).
131
+ recreate_missing_wrapper() {
132
+ local install_path="$1" hooks_file="$2" wrapper="$3" rest="$4"
133
+ local target="${install_path}/_hooks/${wrapper}"
134
+
135
+ # Case 1: real target forwarded as an argument.
136
+ if printf '%s' "$rest" | grep -q 'CLAUDE_PLUGIN_ROOT'; then
137
+ printf '#!/bin/bash\n# win-hooks: recreated — exec the real target passed by run-hook.cmd\nexec bash "$@"\n' > "$target"
138
+ echo " FIXED: recreated missing wrapper _hooks/${wrapper} (passthrough)" >&2
139
+ return 0
140
+ fi
141
+
142
+ # Case 2: path baked in body — recover original command from .bak.
143
+ local bak="${hooks_file}.bak" rawcmd="" relpath interp py b p l
144
+ if [[ ! -f "$bak" ]]; then
145
+ echo " WARN: cannot recreate _hooks/${wrapper} — no hooks.json.bak" >&2
146
+ return 1
147
+ fi
148
+ while IFS= read -r l; do
149
+ p=$(printf '%s' "$l" | grep -oE '\$\{CLAUDE_PLUGIN_ROOT\}/[A-Za-z0-9_./-]+' | head -1)
150
+ [[ -z "$p" ]] && continue
151
+ b=$(basename "$p"); b="${b%.*}"; b="${b//_/-}"
152
+ if [[ "$b" == "$wrapper" ]]; then rawcmd="$l"; break; fi
153
+ done < <(grep -E '"command"' "$bak" 2>/dev/null)
154
+ if [[ -z "$rawcmd" ]]; then
155
+ echo " WARN: cannot map _hooks/${wrapper} to a hooks.json.bak command" >&2
156
+ return 1
157
+ fi
158
+ relpath=$(printf '%s' "$rawcmd" | grep -oE '\$\{CLAUDE_PLUGIN_ROOT\}/[A-Za-z0-9_./-]+' | head -1 | sed 's|.*${CLAUDE_PLUGIN_ROOT}/||')
159
+ interp=$(printf '%s' "$rawcmd" | sed -E 's/.*"command"[[:space:]]*:[[:space:]]*"//' | awk '{print $1}' | tr -d '\\"')
160
+ if [[ "$interp" == "python3" || "$interp" == "python" ]]; then
161
+ py=$(wh_resolve_python)
162
+ if [[ -n "$py" ]]; then
163
+ printf '#!/bin/bash\nSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"\nPLUGIN_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"\nexec "%s" "$PLUGIN_ROOT/%s" "$@"\n' "$py" "$relpath" > "$target"
164
+ else
165
+ printf '#!/bin/bash\n# win-hooks: no working Python found — graceful no-op\nexit 0\n' > "$target"
166
+ fi
167
+ elif [[ "$relpath" == *.sh || "$interp" == "bash" || "$interp" == "sh" ]]; then
168
+ printf '#!/bin/bash\nSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"\nPLUGIN_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"\nexec bash "$PLUGIN_ROOT/%s" "$@"\n' "$relpath" > "$target"
169
+ else
170
+ printf '#!/bin/bash\nSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"\nPLUGIN_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"\nexec "$PLUGIN_ROOT/%s" "$@"\n' "$relpath" > "$target"
171
+ fi
172
+ echo " FIXED: recreated missing wrapper _hooks/${wrapper} (regenerated from .bak)" >&2
173
+ }
174
+
175
+ check_wrappers() {
176
+ local plugin="$1" install_path="$2" hooks_file="$3"
177
+ local hooks_dir="${install_path}/_hooks"
178
+ # Each patched command looks like:
179
+ # "\"${CLAUDE_PLUGIN_ROOT}/_hooks/run-hook.cmd\" <wrapper> [<trailing target>]"
180
+ # The escaped \" right after run-hook.cmd defeated an [^"]* grab (it stopped at
181
+ # that quote, losing the wrapper name), so wrapper_missing never fired for the
182
+ # normal patched form. Parse per line: strip up to run-hook.cmd plus the escaped
183
+ # quote/space, then take the first token as the wrapper name.
184
+ # Require the _hooks/ segment so we only manage win-hooks-created wrappers — a
185
+ # plugin that ships its own polyglot at hooks/run-hook.cmd (e.g. superpowers)
186
+ # must NOT be flagged.
187
+ grep -E '_hooks/run-hook\.cmd' "$hooks_file" 2>/dev/null | while IFS= read -r line; do
188
+ local rest wrapper
189
+ rest=$(printf '%s' "$line" | sed -E 's/.*run-hook\.cmd//; s/^[\\"]*[[:space:]]*//')
190
+ wrapper=$(printf '%s' "$rest" | awk '{print $1}' | sed 's/[\\"].*//')
191
+ [[ -z "$wrapper" ]] && continue
192
+
193
+ if [[ ! -f "${hooks_dir}/run-hook.cmd" ]]; then
194
+ add_issue "$plugin" "$install_path" "cmd_missing" "_hooks/run-hook.cmd not found"
195
+ fi
196
+ if [[ ! -f "${hooks_dir}/${wrapper}" ]]; then
197
+ add_issue "$plugin" "$install_path" "wrapper_missing" "_hooks/${wrapper} not found"
198
+ if $FIX_MODE; then
199
+ recreate_missing_wrapper "$install_path" "$hooks_file" "$wrapper" "$rest"
200
+ fi
201
+ fi
202
+ done
203
+ }
204
+
205
+ check_recursive_wrapper() {
206
+ local plugin="$1" install_path="$2"
207
+ for dir in "${install_path}/hooks" "${install_path}/_hooks"; do
208
+ [[ ! -d "$dir" ]] && continue
209
+ for f in "$dir"/*.py "$dir"/*.js; do
210
+ [[ ! -f "$f" ]] && continue
211
+ # Check if it's actually a bash script (not real Python/JS)
212
+ local first_line
213
+ first_line=$(head -c 64 "$f" | tr -d '\r' | sed 's/^\xEF\xBB\xBF//' | head -1)
214
+ [[ "$first_line" != "#!/bin/bash"* && "$first_line" != "#!/usr/bin/env bash"* ]] && continue
215
+ # Check if the script calls python3/node on the same filename
216
+ local base
217
+ base=$(basename "$f")
218
+ if grep -qE "(python3?|node)[[:space:]].*${base}" "$f" 2>/dev/null; then
219
+ add_issue "$plugin" "$install_path" "recursive_wrapper" "${base} calls interpreter on itself"
220
+ if $FIX_MODE; then
221
+ printf '#!/bin/bash\n# win-hooks: disabled — bash wrapper called interpreter on itself\nexit 0\n' > "$f"
222
+ echo " FIXED: disabled recursive wrapper ${base}" >&2
223
+ fi
224
+ fi
225
+ done
226
+ done
227
+ }
228
+
229
+ # Detect _hooks/ wrappers that exec a bogus single-segment ${PLUGIN_ROOT}/<X>
230
+ # target. Caused by an older apply-patches grabbing the interpreter (e.g. `bash`)
231
+ # from a command like `bash ${CLAUDE_PLUGIN_ROOT}/x.sh` as the script path, so the
232
+ # wrapper runs `exec bash "$PLUGIN_ROOT/bash"` — a file that does not exist. Symptom:
233
+ # `bash: .../<plugin>/<ver>/bash: No such file or directory`. The real target is
234
+ # still passed as $@ by run-hook.cmd, so repair = exec that instead.
235
+ check_wrapper_bodies() {
236
+ local plugin="$1" install_path="$2"
237
+ local dir="${install_path}/_hooks"
238
+ [[ -d "$dir" ]] || return 0
239
+ local f base seg rel
240
+ for f in "$dir"/*; do
241
+ [[ -f "$f" ]] || continue
242
+ base=$(basename "$f")
243
+ [[ "$base" == "run-hook.cmd" ]] && continue
244
+ # Broken wrapper from JSON-escaped quote leakage:
245
+ # bash \"$CLAUDE_PLUGIN_ROOT\"/hooks/x.sh
246
+ # The backslashes make the quotes literal, so bash tries to open a path
247
+ # containing quote characters. Regenerate it as the normal path-baked body.
248
+ rel=$(sed -nE 's#.*\\"\$CLAUDE_PLUGIN_ROOT\\"/([A-Za-z0-9_./-]+).*#\1#p' "$f" 2>/dev/null | head -1)
249
+ if [[ -n "$rel" ]]; then
250
+ add_issue "$plugin" "$install_path" "wrapper_broken" "_hooks/${base} contains literal escaped quotes around CLAUDE_PLUGIN_ROOT"
251
+ if $FIX_MODE; then
252
+ if [[ "$rel" == *.sh ]]; then
253
+ printf '#!/bin/bash\nSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"\nPLUGIN_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"\nexec bash "$PLUGIN_ROOT/%s" "$@"\n' "$rel" > "$f"
254
+ else
255
+ printf '#!/bin/bash\nSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"\nPLUGIN_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"\nexec "$PLUGIN_ROOT/%s" "$@"\n' "$rel" > "$f"
256
+ fi
257
+ echo " FIXED: repaired escaped-quote wrapper _hooks/${base}" >&2
258
+ fi
259
+ continue
260
+ fi
261
+ # Bogus target = a single path segment (no slash) right after $PLUGIN_ROOT/.
262
+ seg=$(grep -oE 'exec ([^ "]+ )?"\$PLUGIN_ROOT/[^"/]+"' "$f" 2>/dev/null | head -1 \
263
+ | sed -E 's#.*\$PLUGIN_ROOT/([^"/]+)".*#\1#')
264
+ [[ -z "$seg" ]] && continue
265
+ # Broken if that segment is a bare interpreter name, or the file is absent.
266
+ if [[ "$seg" =~ ^(bash|sh|python3?|node|npx|npm)$ ]] || [[ ! -e "${install_path}/${seg}" ]]; then
267
+ add_issue "$plugin" "$install_path" "wrapper_broken" "_hooks/${base} execs nonexistent \$PLUGIN_ROOT/${seg}"
268
+ if $FIX_MODE; then
269
+ printf '#!/bin/bash\n# win-hooks: repaired — exec the real target passed by run-hook.cmd\nexec bash "$@"\n' > "$f"
270
+ echo " FIXED: repaired broken wrapper _hooks/${base}" >&2
271
+ fi
272
+ fi
273
+ done
274
+ }
275
+
276
+ # Detect an unwrapped hook that invokes a bare python3/python interpreter for
277
+ # which NO working Python exists. apply-patches normally wraps such hooks (and
278
+ # the wrapper falls back across python3/python/py), so this only fires for an
279
+ # unpatched hook on a machine with no usable interpreter — e.g. python3 is only
280
+ # a dead Microsoft Store App Execution Alias stub and there is no other Python.
281
+ # Detection uses a functional probe (`-c ""`), not a path heuristic, so a real
282
+ # Store-installed Python is not misreported.
283
+ check_python3_stub() {
284
+ local plugin="$1" install_path="$2" hooks_file="$3"
285
+ # Does any (still-bare) hook command start with python3/python?
286
+ grep -qE '"command":[[:space:]]*"python3?[[:space:]]' "$hooks_file" 2>/dev/null || return 0
287
+ local _py
288
+ for _py in python3 python py; do
289
+ command -v "$_py" >/dev/null 2>&1 && "$_py" -c "" >/dev/null 2>&1 && return 0
290
+ done
291
+ add_issue "$plugin" "$install_path" "python3_stub" "hook uses python but no working python3/python/py is available"
292
+ }
293
+
294
+ # ── Main scan ──────────────────────────────────────────────────────
295
+
296
+ while IFS=$'\t' read -r plugin install_path hooks_file; do
297
+ # Run checks (fix BOM/CRLF before JSON validation)
298
+ check_bom "$plugin" "$install_path"
299
+ check_crlf "$plugin" "$install_path" "$hooks_file"
300
+ check_recursive_wrapper "$plugin" "$install_path"
301
+ check_wrapper_bodies "$plugin" "$install_path"
302
+ check_python3_stub "$plugin" "$install_path" "$hooks_file"
303
+ if check_json_valid "$plugin" "$install_path" "$hooks_file"; then
304
+ check_wrappers "$plugin" "$install_path" "$hooks_file"
305
+ fi
306
+ done < <(wh_each_plugin_hooksjson "$INSTALLED")
307
+
308
+ # ── Check settings.json for backslash paths and bare commands ─────
309
+
310
+ SETTINGS="${HOME}/.claude/settings.json"
311
+ if [[ -f "$SETTINGS" ]] && command -v node &>/dev/null; then
312
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
313
+ if [[ -f "${SCRIPT_DIR}/fix-backslash-paths" ]]; then
314
+ bash "${SCRIPT_DIR}/fix-backslash-paths" --dry-run 2>/dev/null | while IFS=$'\t' read -r location old_cmd new_cmd; do
315
+ add_issue "settings.json" "$SETTINGS" "backslash_path" "${location}: ${old_cmd}"
316
+ done
317
+ fi
318
+ if [[ -f "${SCRIPT_DIR}/fix-bare-commands" ]]; then
319
+ bash "${SCRIPT_DIR}/fix-bare-commands" --dry-run 2>/dev/null | while IFS=$'\t' read -r location old_cmd new_cmd; do
320
+ add_issue "settings.json" "$SETTINGS" "bare_command" "${location}: ${old_cmd}"
321
+ done
322
+ fi
323
+ fi
324
+
325
+ # ── Summary ────────────────────────────────────────────────────────
326
+
327
+ issues=$(wc -l < "$ISSUES_FILE" | tr -d ' ')
328
+ if [[ "$issues" -eq 0 ]]; then
329
+ echo "win-hooks verify: all plugins healthy" >&2
330
+ else
331
+ echo "win-hooks verify: $issues issue(s) found" >&2
332
+ fi
333
+
334
+ exit $(( issues > 125 ? 125 : issues ))