@lilmgenius/win-hooks 1.12.0 → 1.14.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.
package/README.md CHANGED
@@ -42,7 +42,7 @@ npx @lilmgenius/win-hooks
42
42
 
43
43
  That's the whole setup. No config, no flags, nothing to remember.
44
44
 
45
- You need Windows 10/11 and [Git for Windows](https://git-scm.com/download/win). Node.js already comes with Claude Code and Codex.
45
+ You need Windows 10/11. Node.js already comes with Claude Code and Codex, and [Git for Windows](https://git-scm.com/download/win) is needed only for plugins whose hooks are shell scripts.
46
46
 
47
47
  ## What it fixes
48
48
 
@@ -61,9 +61,9 @@ None of that is your fault. Almost every plugin is written and tested on macOS o
61
61
 
62
62
  ## How it stays fixed
63
63
 
64
- win-hooks repairs your plugins at every session start, including ones you install later and ones that break again after an update. Repairs are written next to the original file, never on top of it, and anything already working is left alone.
64
+ win-hooks repairs your plugins at every session start, including ones you install later, ones that break again after an update, and ones an older win-hooks left behind. Repairs are written next to the original file, never on top of it, and anything already working is left alone.
65
65
 
66
- A healthy run is silent. To look anyway:
66
+ At the start of a session it says so in one line, so you can tell a clean run from a hook that never fired. To look closer:
67
67
 
68
68
  | Command | What it does |
69
69
  |---|---|
package/bin/win-hooks.mjs CHANGED
@@ -1,24 +1,24 @@
1
1
  #!/usr/bin/env node
2
2
  // win-hooks CLI - the single entry point. The plugin's own SessionStart and
3
- // UserPromptSubmit hooks land here too, via hooks/run-hook.cmd -> hooks/win-hooks.
3
+ // UserPromptSubmit hooks land here too, via hooks/run-hook.cmd -> hooks/run.mjs.
4
4
  //
5
- // win-hooks repair Claude Code and Codex plugin hooks
6
- // win-hooks heal [host] repair one host (claude | codex)
7
- // win-hooks status [host] report without changing anything
8
- // win-hooks patch [host] report, repair what is not healthy, prove the result
5
+ // heal [host] silent repair; --changed-only skips when no plugin's hooks
6
+ // changed since the last run (the near-free per-prompt guard);
7
+ // --announce speaks the result into the session (CASE-32)
8
+ // status [host] report, change nothing
9
+ // patch [host] report, repair what is not healthy, prove the result
9
10
  //
10
- // --changed-only skip when no plugin's hooks changed since the last run
11
- // (the per-prompt guard; near-free on the hot path)
12
- //
13
- // Progress goes to stderr, never stdout: these hooks run under Claude Code,
14
- // whose UserPromptSubmit stdout is injected into the model's context. `status`
15
- // and `patch` are the exception - a person asked for their output.
11
+ // Progress goes to stderr, never stdout: a UserPromptSubmit hook's stdout is
12
+ // injected into the model's context. `status`, `patch`, and an announced heal
13
+ // are the exceptions - a person asked for the first two, and the third is a
14
+ // session-start hook, whose stdout both hosts inject into the session as it
15
+ // stands (CASE-32).
16
16
 
17
17
  import { isWindows } from '../src/env.mjs';
18
18
  import { HOSTS } from '../src/hosts.mjs';
19
19
  import { heal, inspect } from '../src/heal.mjs';
20
20
 
21
- const USAGE = 'usage: win-hooks [heal|status|patch] [claude|codex] [--changed-only]';
21
+ const USAGE = 'usage: win-hooks [heal|status|patch] [claude|codex] [--changed-only] [--announce]';
22
22
 
23
23
  const args = process.argv.slice(2);
24
24
  const flags = new Set(args.filter((a) => a.startsWith('--')));
@@ -42,19 +42,33 @@ if (command !== 'heal') {
42
42
  process.exit(0);
43
43
  }
44
44
 
45
+ const announce = flags.has('--announce');
46
+
45
47
  for (const id of hostIds) {
46
48
  try {
47
49
  const result = heal(id, { changedOnly: flags.has('--changed-only') });
48
- if (result) for (const line of summarize(result)) console.error(line);
50
+ if (!result) continue;
51
+ const lines = summarize(result);
52
+ if (announce) lines.unshift(announcement(result));
53
+ for (const line of lines) (announce ? console.log : console.error)(line);
49
54
  } catch (e) {
50
55
  // One broken host must not take the session down with it.
51
56
  console.error('win-hooks: ' + HOSTS[id].label + ' repair failed - ' + e.message);
52
57
  }
53
58
  }
54
59
 
60
+ // One line a person can read at session start. A silent happy path is
61
+ // indistinguishable from a hook the host never dispatched, and the run log
62
+ // cannot separate them either, since a manual repair writes the same line
63
+ // (CASE-32). Said once per session, never per prompt.
64
+ function announcement({ host, scanned, patched, issues, fixes }) {
65
+ return 'win-hooks: ' + host.label + ' - ' + scanned + ' hook file(s) checked, '
66
+ + patched.length + ' repaired, ' + Math.max(issues.length - fixes.length, 0) + ' issue(s) open';
67
+ }
68
+
55
69
  function summarize({ host, patched, failed, settings, issues, fixes }) {
56
70
  const lines = [];
57
- for (const p of patched) lines.push('win-hooks: patched ' + p.plugin.id + ' (' + p.wrappers.join(', ') + ')');
71
+ for (const p of patched) lines.push('win-hooks: patched ' + p.plugin.id + ' (' + p.hooks.join(', ') + ')');
58
72
  for (const f of failed) lines.push('win-hooks: could not patch ' + f.plugin.id + ' - ' + f.error);
59
73
  if (settings.length) lines.push('win-hooks: repaired ' + settings.length + ' hook command(s) in ' + host.label + ' settings');
60
74
  for (const f of fixes) lines.push('win-hooks: ' + f);
@@ -66,10 +80,9 @@ function summarize({ host, patched, failed, settings, issues, fixes }) {
66
80
  return lines;
67
81
  }
68
82
 
69
- // Report, repair what is not healthy, then prove the result - one verb,
70
- // because nobody inspects hooks for their own sake. A healthy host leaves
71
- // nothing to decide, and a broken one was always going to be repaired, so
72
- // splitting the two only asks the user which one they needed.
83
+ // One verb, because nobody inspects hooks for their own sake: a healthy host
84
+ // leaves nothing to decide and a broken one was always going to be repaired,
85
+ // so splitting the two only asks the user which one they needed (CASE-30).
73
86
  function patchHost(id) {
74
87
  const before = inspect(id);
75
88
  if (healthy(before)) return report(before) + heartbeat(before);
@@ -101,9 +114,17 @@ function report({ host, plugins, incompatible, issues, settings }, heading) {
101
114
  + ' - ' + plugins.length + ' hook file(s) scanned';
102
115
  const lines = [title];
103
116
 
104
- for (const i of incompatible) lines.push(' incompatible ' + i.id + ' [' + i.event + '] ' + i.command);
105
- for (const i of issues) lines.push(' ' + i.type.padEnd(14) + i.plugin + ' ' + i.detail);
106
- for (const s of settings) lines.push(' ' + s.type.padEnd(14) + s.path + ' ' + s.to);
117
+ // The label column is measured, not guessed: a fixed width silently ran the
118
+ // longest issue types into the plugin name beside them.
119
+ const rows = [
120
+ ...incompatible.map((i) => ['incompatible', i.id + ' [' + i.event + ']', i.command]),
121
+ ...issues.map((i) => [i.type, i.plugin, i.detail]),
122
+ ...settings.map((s) => [s.type, s.path, s.to]),
123
+ ];
124
+ const width = Math.max(0, ...rows.map(([type]) => type.length));
125
+ for (const [type, subject, detail] of rows) {
126
+ lines.push(' ' + type.padEnd(width) + ' ' + subject + ' ' + detail);
127
+ }
107
128
  if (lines.length === 1) lines.push(' healthy - every hook is Windows-compatible');
108
129
  return lines.join('\n');
109
130
  }
@@ -6,8 +6,8 @@
6
6
  "hooks": [
7
7
  {
8
8
  "type": "command",
9
- "command": "bash \"${PLUGIN_ROOT}/hooks/win-hooks\" heal codex",
10
- "commandWindows": "\"${PLUGIN_ROOT}\\hooks\\run-hook.cmd\" win-hooks heal codex",
9
+ "command": "bash \"${PLUGIN_ROOT}/hooks/run-hook.cmd\" win-hooks heal codex --announce",
10
+ "commandWindows": "cmd /c \"${PLUGIN_ROOT}\\hooks\\run-hook.cmd\" win-hooks heal codex --announce",
11
11
  "timeout": 60,
12
12
  "statusMessage": "win-hooks: checking Codex plugin hooks"
13
13
  }
@@ -19,8 +19,8 @@
19
19
  "hooks": [
20
20
  {
21
21
  "type": "command",
22
- "command": "bash \"${PLUGIN_ROOT}/hooks/win-hooks\" heal codex --changed-only",
23
- "commandWindows": "\"${PLUGIN_ROOT}\\hooks\\run-hook.cmd\" win-hooks heal codex --changed-only",
22
+ "command": "bash \"${PLUGIN_ROOT}/hooks/run-hook.cmd\" win-hooks heal codex --changed-only",
23
+ "commandWindows": "cmd /c \"${PLUGIN_ROOT}\\hooks\\run-hook.cmd\" win-hooks heal codex --changed-only",
24
24
  "timeout": 20,
25
25
  "statusMessage": "win-hooks: checking changed Codex plugin hooks"
26
26
  }
package/hooks/hooks.json CHANGED
@@ -6,7 +6,7 @@
6
6
  "hooks": [
7
7
  {
8
8
  "type": "command",
9
- "command": "\"${CLAUDE_PLUGIN_ROOT}/hooks/run-hook.cmd\" win-hooks heal",
9
+ "command": "\"${CLAUDE_PLUGIN_ROOT}/hooks/run-hook.cmd\" win-hooks heal --announce",
10
10
  "timeout": 60
11
11
  }
12
12
  ]
@@ -0,0 +1,3 @@
1
+ {
2
+ "win-hooks": { "exec": "node", "target": "bin/win-hooks.mjs" }
3
+ }
@@ -1,66 +1,51 @@
1
1
  : << 'CMDBLOCK'
2
2
  @echo off
3
- REM The entry point every patched hook is dispatched through - a single file
4
- REM that is valid batch AND valid bash at once. cmd.exe runs the batch block
5
- REM below; bash treats it as a quoted here-doc and falls through to the tail.
3
+ REM The entry point every patched hook is dispatched through: one file that is
4
+ REM valid batch AND valid bash at once, so Claude Code and Codex can each
5
+ REM dispatch it their own way. cmd.exe runs the batch block below; bash treats
6
+ REM it as a quoted here-doc and falls through to the tail. Hook names are
7
+ REM extensionless because Claude Code prepends "bash" to any command containing
8
+ REM .sh, which would undo the patch (CASE-07).
6
9
  REM
7
- REM Why a polyglot: Claude Code and Codex each dispatch hooks differently, and
8
- REM the wrapper has to be reachable from both without shipping two files.
9
- REM Wrapper names are extensionless because Claude Code prepends "bash" to any
10
- REM command containing .sh on Windows, which would undo the patch (CASE-07).
10
+ REM Both halves do the same small thing: start node on run.mjs, which resolves
11
+ REM the named hook and runs it. Nothing here looks for bash any more - that
12
+ REM decision moved into run.mjs, where it is ordinary code (CASE-29).
11
13
  REM
12
- REM Usage: run-hook.cmd <script-name> [args...]
14
+ REM Usage: run-hook.cmd <hook-name> [args...]
13
15
 
14
16
  if "%~1"=="" (
15
- echo run-hook.cmd: missing script name >&2
17
+ echo win-hooks: run-hook.cmd was given no hook name >&2
16
18
  exit /b 1
17
19
  )
18
20
 
19
- set "HOOK_DIR=%~dp0"
20
- set "WH_BASH="
21
+ set "WH_NODE="
21
22
 
22
- REM Explicit override first: set WH_BASH_EXE when bash lives somewhere this
23
- REM does not already look, e.g. a portable, scoop, or winget Git install.
24
- if defined WH_BASH_EXE if exist "%WH_BASH_EXE%" set "WH_BASH=%WH_BASH_EXE%"
23
+ REM Explicit override first, for a portable or otherwise unusual node install.
24
+ if defined WH_NODE_EXE if exist "%WH_NODE_EXE%" set "WH_NODE=%WH_NODE_EXE%"
25
25
 
26
- REM Then Git for Windows, which is where it almost always is.
27
- if not defined WH_BASH if exist "C:\Program Files\Git\bin\bash.exe" set "WH_BASH=C:\Program Files\Git\bin\bash.exe"
28
- if not defined WH_BASH if exist "C:\Program Files (x86)\Git\bin\bash.exe" set "WH_BASH=C:\Program Files (x86)\Git\bin\bash.exe"
26
+ REM Then PATH, resolved by the FOR path-search modifier below, because `where`
27
+ REM costs a subprocess. Never name that modifier in a REM: cmd.exe expands it
28
+ REM there too and the comment breaks.
29
+ if not defined WH_NODE for %%I in (node.exe) do set "WH_NODE=%%~$PATH:I"
30
+ if not defined WH_NODE goto :nonode
29
31
 
30
- if defined WH_BASH goto :run
31
-
32
- REM Finally PATH (MSYS2, Cygwin, a nonstandard install). Resolved by the FOR
33
- REM path-search modifier below rather than by `where`, which costs a subprocess.
34
- REM That modifier must not be named in a REM: cmd.exe expands it there too, and
35
- REM a comment mentioning it is a syntax error.
36
- for %%I in (bash.exe) do set "WH_BASH=%%~$PATH:I"
37
- if not defined WH_BASH goto :nobash
38
-
39
- REM PATH bash is often C:\Windows\System32\bash.exe, the WSL launcher, which
40
- REM cannot open Windows paths and still exits 0 - it would swallow every hook
41
- REM forever. So the candidate has to prove it can see the script it is about to
42
- REM run (CASE-29). Only PATH is probed; the paths above are known-good. The
43
- REM path goes through the environment because bash would receive it as $0 and
44
- REM WSL's launcher does not forward $0 the way a real bash does.
45
- set "WH_PROBE=%HOOK_DIR%%~1"
46
- "%WH_BASH%" -c "test -f \"$WH_PROBE\"" >nul 2>&1
47
- if errorlevel 1 goto :nobash
48
-
49
- :run
50
- REM %* would ignore the shift, so arguments are forwarded positionally. Eight
51
- REM is every hook win-hooks generates; a ninth would be silently dropped.
52
- "%WH_BASH%" "%HOOK_DIR%%~1" %2 %3 %4 %5 %6 %7 %8 %9
32
+ REM %* forwards every argument, including the hook name run.mjs reads first.
33
+ REM The previous positional forwarding capped a hook at eight arguments because
34
+ REM cmd.exe's %* ignores shift; nothing shifts now, so the cap is gone (CASE-27).
35
+ "%WH_NODE%" "%~dp0run.mjs" %*
53
36
  exit /b %ERRORLEVEL%
54
37
 
55
- :nobash
38
+ :nonode
56
39
  REM Fail-safe: no repair, never a broken session - but say so, because a hook
57
40
  REM that does nothing quietly is the exact failure win-hooks exists to catch.
58
- echo run-hook.cmd: no bash that can run "%~1"; skipping >&2
41
+ echo win-hooks: no node found; skipping "%~1" >&2
59
42
  exit /b 0
60
43
  CMDBLOCK
61
44
 
62
- # bash: run the named script directly.
63
- SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
64
- SCRIPT_NAME="$1"
65
- shift
66
- exec bash "${SCRIPT_DIR}/${SCRIPT_NAME}" "$@"
45
+ # bash: the same dispatch, for Git Bash on Windows and for Codex's portable
46
+ # command on macOS and Linux.
47
+ command -v node >/dev/null 2>&1 || {
48
+ echo 'win-hooks: no node found; skipping' >&2
49
+ exit 0
50
+ }
51
+ exec node "$(cd "$(dirname "$0")" && pwd)/run.mjs" "$@"
package/hooks/run.mjs ADDED
@@ -0,0 +1,137 @@
1
+ // The dispatcher every patched hook lands in, one step after run-hook.cmd.
2
+ //
3
+ // This file is copied verbatim into each patched plugin's hook directory, so
4
+ // it must not import anything from src/: there is no src/ beside it there. The
5
+ // bash resolution and the descriptor shapes below are therefore deliberately a
6
+ // second copy of what src/env.mjs and src/rules.mjs own, rather than a shared
7
+ // import - the alternative is shipping the whole engine into every plugin that
8
+ // has one broken hook.
9
+ //
10
+ // Usage: node run.mjs <hook-name> [args...]
11
+
12
+ import { spawnSync } from 'node:child_process';
13
+ import { existsSync, readFileSync } from 'node:fs';
14
+ import { dirname, join } from 'node:path';
15
+ import { fileURLToPath } from 'node:url';
16
+
17
+ const HOOK_DIR = dirname(fileURLToPath(import.meta.url));
18
+ const PLUGIN_ROOT = dirname(HOOK_DIR);
19
+
20
+ const name = process.argv[2];
21
+ const args = process.argv.slice(3);
22
+
23
+ // Fail-safe everywhere below: a hook that cannot run must be a no-op, never a
24
+ // broken session. It still says so on stderr, because a hook that does nothing
25
+ // silently is the exact failure win-hooks exists to catch (CASE-29/32).
26
+ const skip = (why) => {
27
+ process.stderr.write('win-hooks: ' + why + '; skipping\n');
28
+ process.exit(0);
29
+ };
30
+
31
+ if (!name) skip('run.mjs was given no hook name');
32
+
33
+ // Known-good bash paths are trusted without a probe, so the common case costs
34
+ // no subprocess. Anything found on PATH has to prove itself first.
35
+ const KNOWN_BASH = [
36
+ process.env.WH_BASH_EXE,
37
+ 'C:/Program Files/Git/bin/bash.exe',
38
+ 'C:/Program Files (x86)/Git/bin/bash.exe',
39
+ ].filter(Boolean);
40
+
41
+ const toPosix = (p) => String(p || '').replace(/\\/g, '/');
42
+
43
+ // CASE-29: PATH bash on stock Windows is System32\bash.exe, the WSL launcher.
44
+ // It cannot open a Windows path and still exits 0, so it would swallow every
45
+ // hook forever. A candidate must prove it can see the file it is about to run.
46
+ // The path travels through the environment rather than as $0, because WSL
47
+ // reports $0 as /bin/bash and would pass a test it must fail.
48
+ const bashSees = (exe, target) => {
49
+ const r = spawnSync(exe, ['-c', 'test -f "$WH_PROBE"'], {
50
+ env: { ...process.env, WH_PROBE: toPosix(target) },
51
+ stdio: 'ignore',
52
+ windowsHide: true,
53
+ timeout: 10000,
54
+ });
55
+ return !r.error && r.status === 0;
56
+ };
57
+
58
+ // PATH is walked here rather than shelled out to `where.exe`, which would cost
59
+ // a subprocess and would itself have to be found on the PATH under test.
60
+ const pathDirs = () =>
61
+ String(process.env.PATH || '')
62
+ .split(';')
63
+ .map((d) => d.trim().replace(/^"|"$/g, ''))
64
+ .filter(Boolean);
65
+
66
+ const resolveBash = (target) => {
67
+ for (const exe of KNOWN_BASH) if (existsSync(exe)) return exe;
68
+ for (const dir of pathDirs()) {
69
+ const exe = join(dir, 'bash.exe');
70
+ if (existsSync(exe) && bashSees(exe, target)) return exe;
71
+ }
72
+ return null;
73
+ };
74
+
75
+ // Is this bare name executable from PATH? The same walk as resolveBash, but
76
+ // across PATHEXT, since a dependency may be a .cmd or .bat shim, not an .exe.
77
+ const onPath = (bin) => {
78
+ const exts = String(process.env.PATHEXT || '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean);
79
+ return pathDirs().some((d) => exts.some((ext) => existsSync(join(d, bin + ext))));
80
+ };
81
+
82
+ const readMap = () => {
83
+ const file = join(HOOK_DIR, 'hooks.map.json');
84
+ if (!existsSync(file)) return {};
85
+ try {
86
+ return JSON.parse(readFileSync(file, 'utf8').replace(/^\uFEFF/, ''));
87
+ } catch {
88
+ return {};
89
+ }
90
+ };
91
+
92
+ // A bash wrapper file sitting in this directory is an install patched before
93
+ // the map existed. Running it keeps that machine working until the next heal
94
+ // replaces it with an entry - which verify does, so this is a bridge, not a
95
+ // second supported layout.
96
+ const legacyWrapper = join(HOOK_DIR, name);
97
+ const entry = readMap()[name]
98
+ || (existsSync(legacyWrapper) ? { exec: 'bash', absoluteTarget: legacyWrapper } : null);
99
+
100
+ if (!entry) skip('no hook named "' + name + '" in ' + HOOK_DIR);
101
+
102
+ // A hook win-hooks could not make runnable at patch time - no working Python,
103
+ // say. Exiting 0 in silence is the point: it is a deliberate no-op, and a line
104
+ // per invocation would be noise in every session until the plugin updates.
105
+ if (entry.disabled) process.exit(0);
106
+
107
+ // CASE-08: an optional dependency that simply is not installed here. Re-checked
108
+ // every run rather than at patch time, so installing it later just starts
109
+ // working, and its absence never fails the hook.
110
+ if (entry.requires) {
111
+ if (!onPath(entry.requires)) process.exit(0);
112
+ // The command is run as written and the hook's own arguments are not
113
+ // appended: the entry already holds the whole original command line, so
114
+ // forwarding them too would duplicate every argument (CASE-10).
115
+ const dep = spawnSync(entry.command, { stdio: 'inherit', shell: true, windowsHide: true });
116
+ process.exit(dep.status === null ? 0 : dep.status);
117
+ }
118
+
119
+ const target = entry.absoluteTarget || join(PLUGIN_ROOT, entry.target);
120
+
121
+ // exec is an absolute interpreter path baked in at patch time (CASE-09), the
122
+ // literal "bash" when only a run-time search can find one, or absent when the
123
+ // target is handed to the OS to run on its own.
124
+ let exe = entry.exec;
125
+ // "node" means the one already running: run-hook.cmd found it, and reusing it
126
+ // keeps a hook on the same interpreter that dispatched it.
127
+ if (exe === 'node') exe = process.execPath;
128
+ else if (exe === 'bash') {
129
+ exe = resolveBash(target);
130
+ if (!exe) skip('no bash that can run "' + name + '"');
131
+ }
132
+
133
+ const r = spawnSync(exe || target, exe ? [target, ...args] : args, {
134
+ stdio: 'inherit',
135
+ windowsHide: true,
136
+ });
137
+ process.exit(r.status === null ? 0 : r.status);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lilmgenius/win-hooks",
3
- "version": "1.12.0",
3
+ "version": "1.14.0",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
package/src/heal.mjs CHANGED
@@ -1,11 +1,12 @@
1
1
  // Orchestration: the one code path every surface goes through - the plugin's
2
2
  // own hooks, the CLI, and the slash commands.
3
3
  //
4
- // Two rules govern this file. Nothing is ever written to stdout from a hook: a
5
- // UserPromptSubmit hook's stdout is injected into the model's context, so
6
- // progress chatter would silently poison every prompt. And an environmental
7
- // failure degrades to a no-op rather than breaking the session it exists to
8
- // protect.
4
+ // Two rules govern this file. It prints nothing itself: a UserPromptSubmit
5
+ // hook's stdout is injected into the model's context, so progress chatter
6
+ // would silently poison every prompt. The one place that is a feature rather
7
+ // than a hazard is session start, and only the CLI decides that, from
8
+ // --announce (CASE-32). And an environmental failure degrades to a no-op
9
+ // rather than breaking the session it exists to protect.
9
10
 
10
11
  import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
11
12
  import { join, dirname } from 'node:path';
@@ -99,7 +100,7 @@ export function heal(hostId, { changedOnly = false } = {}) {
99
100
  issues: issues.length,
100
101
  });
101
102
 
102
- return { host, patched, failed, settings, issues, fixes };
103
+ return { host, scanned: plugins.length, patched, failed, settings, issues, fixes };
103
104
  }
104
105
 
105
106
  // Report without touching anything.
@@ -110,7 +111,7 @@ export function inspect(hostId) {
110
111
  host,
111
112
  plugins,
112
113
  incompatible: findIncompatible(host, plugins),
113
- issues: verify(host, { plugins }).issues,
114
+ issues: verify(host, { templateCmd: TEMPLATE_CMD, plugins }).issues,
114
115
  settings: fixSettings(host.settingsFile),
115
116
  log: readLog(host),
116
117
  };
package/src/hosts.mjs CHANGED
@@ -1,15 +1,16 @@
1
1
  // Host descriptors.
2
2
  //
3
3
  // Claude Code and Codex differ in four ways: how plugins are enumerated, which
4
- // variable names the plugin root, where wrappers live, and how a patch is
4
+ // variable names the plugin root, where the hooks live, and how a patch is
5
5
  // recorded. Claude rewrites "command" in place; Codex adds a "commandWindows"
6
6
  // sibling so the portable command keeps working on macOS and Linux. Scanning,
7
- // wrapper generation, and verification are identical, so they are shared.
7
+ // descriptor generation, and verification are identical, so they are shared.
8
8
 
9
9
  import { spawnSync } from 'node:child_process';
10
10
  import { existsSync } from 'node:fs';
11
11
  import { join, resolve } from 'node:path';
12
12
  import { HOME, readJson, toPosix } from './env.mjs';
13
+ import { DISPATCH_PREFIX, opensWithQuotedPath } from './rules.mjs';
13
14
 
14
15
  // Both hosts use the same hooks.json shape:
15
16
  // { hooks: { <Event>: [ { hooks: [ { type: "command", command } ] } ] } }
@@ -53,7 +54,7 @@ const claude = {
53
54
  id: 'claude',
54
55
  label: 'Claude Code',
55
56
  rootVar: 'CLAUDE_PLUGIN_ROOT',
56
- wrapperDir: '_hooks',
57
+ hookDir: '_hooks',
57
58
  bakSuffix: '.bak',
58
59
  stateDir: join(HOME, '.claude/win-hooks'),
59
60
  settingsFile: join(HOME, '.claude/settings.json'),
@@ -62,12 +63,17 @@ const claude = {
62
63
  registry: [join(HOME, '.claude/plugins/installed_plugins.json'), join(HOME, '.claude/settings.json')],
63
64
  listPlugins: listClaudePlugins,
64
65
  // Claude replaces the command outright, so an already-patched hook is one
65
- // that already points at our wrapper - which isIncompatible sees as a .cmd.
66
+ // that already points at our dispatcher - which isIncompatible sees as a .cmd.
66
67
  sourceCommand: (hook) => hook.command,
67
68
  patchedCommand: (hook) => hook.command,
68
69
  applyPatch: (hook, ref) => { hook.command = ref; },
69
- wrapperRef: (wrapper, args) =>
70
- '"${CLAUDE_PLUGIN_ROOT}/_hooks/run-hook.cmd" ' + wrapper + (args ? ' ' + args : ''),
70
+ // The shells that may dispatch a command this host emits. Claude Code runs a
71
+ // Windows hook command through cmd.exe, the one shell that also accepts a
72
+ // quoted path in command position, so the reference below needs no prefix.
73
+ // The CASE-31 gate executes hookRef under every shell named here.
74
+ dispatchers: ['cmd'],
75
+ hookRef: (name, args) =>
76
+ '"${CLAUDE_PLUGIN_ROOT}/_hooks/run-hook.cmd" ' + name + (args ? ' ' + args : ''),
71
77
  };
72
78
 
73
79
  // ── Codex ─────────────────────────────────────────────────────────────
@@ -97,11 +103,18 @@ function listCodexPlugins() {
97
103
  });
98
104
  }
99
105
 
106
+ // A commandWindows this tool wrote before CASE-31 opens with a quoted path,
107
+ // which a PowerShell dispatcher cannot parse. It is ours to re-derive, so it
108
+ // counts as unpatched; a commandWindows a plugin author wrote is left alone.
109
+ const isStaleCodexPatch = (hook) =>
110
+ String(hook.commandWindows || '').replace(/\\/g, '/').includes('_codex_hooks/run-hook.cmd')
111
+ && opensWithQuotedPath(hook.commandWindows);
112
+
100
113
  const codex = {
101
114
  id: 'codex',
102
115
  label: 'Codex',
103
116
  rootVar: 'PLUGIN_ROOT',
104
- wrapperDir: '_codex_hooks',
117
+ hookDir: '_codex_hooks',
105
118
  bakSuffix: '.codex-win-hooks.bak',
106
119
  stateDir: join(HOME, '.codex/win-hooks'),
107
120
  settingsFile: null,
@@ -111,12 +124,17 @@ const codex = {
111
124
  listPlugins: listCodexPlugins,
112
125
  // A hook that already carries commandWindows is patched; leave the portable
113
126
  // command alone so it still runs natively on macOS and Linux.
114
- sourceCommand: (hook) => (hook.commandWindows ? null : hook.command),
127
+ sourceCommand: (hook) => (hook.commandWindows && !isStaleCodexPatch(hook) ? null : hook.command),
115
128
  patchedCommand: (hook) => hook.commandWindows,
116
129
  applyPatch: (hook, ref) => { hook.commandWindows = ref; },
117
- // Codex dispatches commandWindows through cmd.exe, which wants backslashes.
118
- wrapperRef: (wrapper, args) =>
119
- '"${PLUGIN_ROOT}\\_codex_hooks\\run-hook.cmd" ' + wrapper + (args ? ' ' + args : ''),
130
+ // Codex hands commandWindows to the session shell, which is cmd.exe or
131
+ // PowerShell depending on how the session was started - so the reference has
132
+ // to carry the CASE-31 prefix. The backslashes are for the cmd.exe that ends
133
+ // up running the hook.
134
+ dispatchers: ['cmd', 'powershell'],
135
+ hookRef: (name, args) =>
136
+ DISPATCH_PREFIX + '"${PLUGIN_ROOT}\\_codex_hooks\\run-hook.cmd" ' + name
137
+ + (args ? ' ' + args : ''),
120
138
  };
121
139
 
122
140
  export const HOSTS = { claude, codex };
package/src/patch.mjs CHANGED
@@ -4,15 +4,15 @@
4
4
  // JSON is parsed rather than pattern-matched, a malformed result is impossible
5
5
  // by construction - no write-then-validate-then-restore dance is needed.
6
6
 
7
- import { existsSync, mkdirSync, copyFileSync, readFileSync } from 'node:fs';
8
- import { join } from 'node:path';
9
- import { backupOnce, hasCommand, readJson, sanitize, writeJson, writeText } from './env.mjs';
7
+ import { mkdirSync, copyFileSync } from 'node:fs';
8
+ import { dirname, join } from 'node:path';
9
+ import { backupOnce, hasCommand, readJson, sanitize, writeJson } from './env.mjs';
10
10
  import { eachHook } from './hosts.mjs';
11
- import { isIncompatible, trailingArgs, wrapperBody, wrapperName } from './rules.mjs';
11
+ import { DISPATCHER_FILES, hookEntry, isIncompatible, readHookMap, trailingArgs, hookName, writeHookMap } from './rules.mjs';
12
12
 
13
13
  const scanOpts = (host) => ({ rootVar: host.rootVar, isInstalled: hasCommand });
14
14
 
15
- // Hooks in this plugin that still need a Windows wrapper.
15
+ // Hooks in this plugin that still need a Windows-safe replacement.
16
16
  function incompatibleHooks(host, plugin) {
17
17
  const { ok, data, error } = readJson(plugin.hooksFile);
18
18
  if (!ok) return { error };
@@ -30,38 +30,37 @@ function incompatibleHooks(host, plugin) {
30
30
  // overwhelmingly common case, which must stay cheap.
31
31
  function patchPlugin(host, plugin, templateCmd) {
32
32
  // BOM/CRLF are corruption in their own right (CASE-01/02/03); clear them
33
- // whether or not this plugin turns out to need a wrapper.
33
+ // whether or not this plugin turns out to need patching.
34
34
  sanitize(plugin.hooksFile);
35
35
  const { error, data, targets } = incompatibleHooks(host, plugin);
36
36
  if (error) return { plugin, error: 'hooks.json is not valid JSON: ' + error };
37
37
  if (!targets.length) return null;
38
38
 
39
- const wrapperDir = join(plugin.installPath, host.wrapperDir);
40
- mkdirSync(wrapperDir, { recursive: true });
39
+ const hookDir = join(plugin.installPath, host.hookDir);
40
+ mkdirSync(hookDir, { recursive: true });
41
41
 
42
- // Always refresh run-hook.cmd (CASE-27). It is win-hooks-owned infrastructure
43
- // users never edit, so template fixes must reach already-patched plugins.
44
- copyFileSync(templateCmd, join(wrapperDir, 'run-hook.cmd'));
42
+ // Always refresh the dispatcher (CASE-27). It is win-hooks-owned
43
+ // infrastructure users never edit, so template fixes must reach
44
+ // already-patched plugins - and both files move together, because the batch
45
+ // half does nothing except start the run.mjs beside it.
46
+ for (const name of DISPATCHER_FILES) {
47
+ copyFileSync(join(dirname(templateCmd), name), join(hookDir, name));
48
+ }
45
49
  backupOnce(plugin.hooksFile, host.bakSuffix);
46
50
 
47
- const wrappers = [];
51
+ // Merged, not overwritten: Codex declares one hooks.json per event, so this
52
+ // plugin's other events have already written their entries into this map.
53
+ const map = readHookMap(hookDir);
54
+ const hooks = [];
48
55
  for (const { hook, command } of targets) {
49
- const name = wrapperName(command, host.rootVar);
50
- const body = wrapperBody(command, host.rootVar);
51
- const file = join(wrapperDir, name);
52
-
53
- // Never clobber a file that is not one of ours.
54
- const existing = existsSync(file) ? readFileSync(file, 'utf8') : null;
55
- if (existing !== null && !existing.startsWith('#!/bin/bash')) continue;
56
- if (existing !== body) writeText(file, body);
57
-
58
- host.applyPatch(hook, host.wrapperRef(name, trailingArgs(command, host.rootVar)));
59
- wrappers.push(name);
56
+ const name = hookName(command, host.rootVar);
57
+ map[name] = hookEntry(command, host.rootVar);
58
+ host.applyPatch(hook, host.hookRef(name, trailingArgs(command, host.rootVar)));
59
+ hooks.push(name);
60
60
  }
61
- if (!wrappers.length) return null;
62
-
61
+ writeHookMap(hookDir, map);
63
62
  writeJson(plugin.hooksFile, data);
64
- return { plugin, wrappers };
63
+ return { plugin, hooks };
65
64
  }
66
65
 
67
66
  export function patchAll(host, templateCmd, plugins = host.listPlugins()) {
package/src/rules.mjs CHANGED
@@ -1,10 +1,11 @@
1
1
  // The domain knowledge: which hook commands break on Windows, what to name the
2
- // wrapper that replaces them, and what that wrapper contains.
2
+ // hook that replaces them, and what that hook's descriptor says.
3
3
  //
4
4
  // This is the one module worth reading to understand win-hooks; everything else
5
5
  // is plumbing. Each rule maps to a CASE in AGENTS.md.
6
6
 
7
- import { resolvePython } from './env.mjs';
7
+ import { join } from 'node:path';
8
+ import { readJson, resolvePython, writeJson } from './env.mjs';
8
9
 
9
10
  // Hook commands are stored JSON-escaped; recover the shell command as written.
10
11
  const decode = (cmd) => String(cmd || '').replace(/\\"/g, '"');
@@ -21,13 +22,13 @@ export function relPath(cmd, rootVar) {
21
22
  }
22
23
 
23
24
  // Arguments that follow the script path and must survive the rewrite. The path
24
- // itself is baked into the wrapper body, so re-appending it would be a bug.
25
+ // itself is part of the descriptor, so re-appending it would be a bug.
25
26
  export function trailingArgs(cmd, rootVar) {
26
27
  const re = new RegExp('.*"?\\$(?:\\{' + rootVar + '\\}|' + rootVar + ')"?/[A-Za-z0-9_./-]+');
27
28
  return decode(cmd).replace(re, '').replace(/^["\s]+|\s+$/g, '');
28
29
  }
29
30
 
30
- // Does this hook command need a Windows wrapper?
31
+ // Does this hook command need to be replaced on Windows?
31
32
  //
32
33
  // isInstalled is injected so the bare-binary rule stays testable, and so the
33
34
  // Codex lane can opt out of it.
@@ -56,9 +57,28 @@ export function isIncompatible(cmd, { rootVar, isInstalled = () => true } = {})
56
57
  return false;
57
58
  }
58
59
 
59
- // Wrapper filenames are extensionless, so Claude Code's Windows auto-detection
60
+ // CASE-31: the shell that dispatches a hook command is the host's choice, not
61
+ // ours. Every Windows shell runs a bare command name in command position, but
62
+ // only cmd.exe also accepts a quoted path there - PowerShell reads the leading
63
+ // quote as a string expression and rejects every argument after it. A command
64
+ // that has to survive an unknown dispatcher therefore opens with cmd /c, which
65
+ // is a command name under both and hands the quoted path to the cmd.exe that
66
+ // was wanted all along.
67
+ export const DISPATCH_PREFIX = 'cmd /c ';
68
+
69
+ export const opensWithQuotedPath = (cmd) => /^["']/.test(decode(cmd).trim());
70
+
71
+ // Would this command survive every shell the host might dispatch it through?
72
+ export const isDispatchable = (cmd, dispatchers) =>
73
+ !opensWithQuotedPath(cmd) || dispatchers.every((shell) => shell === 'cmd');
74
+
75
+ // The two halves of the dispatcher, copied into a hook directory from the
76
+ // shipped template and never generated per hook.
77
+ export const DISPATCHER_FILES = ['run-hook.cmd', 'run.mjs'];
78
+
79
+ // Hook names are extensionless, so Claude Code's Windows auto-detection
60
80
  // does not prepend "bash" to anything containing ".sh" (CASE-07).
61
- export function wrapperName(cmd, rootVar) {
81
+ export function hookName(cmd, rootVar) {
62
82
  const c = decode(cmd);
63
83
 
64
84
  // A keyed invocation names itself after its subject:
@@ -73,57 +93,69 @@ export function wrapperName(cmd, rootVar) {
73
93
  }
74
94
 
75
95
  const name = c.trim().split(/\s+/).slice(0, 3).join('-').replace(/[^A-Za-z0-9-]/g, '');
76
- return name || 'hook-wrapper';
96
+ return name || 'hook';
77
97
  }
78
98
 
79
- const PREAMBLE =
80
- '#!/bin/bash\n' +
81
- 'SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"\n' +
82
- 'PLUGIN_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"\n';
83
-
84
- export const passthroughBody = () =>
85
- '#!/bin/bash\n# win-hooks: exec the real target passed through by run-hook.cmd\nexec bash "$@"\n';
86
-
87
- export const disabledBody = (why) =>
88
- '#!/bin/bash\n# win-hooks: disabled - ' + why + '\nexit 0\n';
99
+ // Every patched hook is one JSON descriptor in this file, which run.mjs reads.
100
+ // It replaced a directory of generated bash scripts, and the three shapes below
101
+ // are the whole vocabulary - none of them is shell text:
102
+ //
103
+ // { disabled: why } win-hooks could not make this runnable
104
+ // { requires: bin, command: cmd } run cmd, but only if bin is on PATH
105
+ // { exec?: interp, target: rel } run target, under interp when one is named
106
+ export const MAP_FILE = 'hooks.map.json';
107
+
108
+ export const readHookMap = (dir) => {
109
+ const { ok, data } = readJson(join(dir, MAP_FILE));
110
+ return ok && data && typeof data === 'object' ? data : {};
111
+ };
112
+
113
+ export const writeHookMap = (dir, map) => writeJson(join(dir, MAP_FILE), map);
114
+
115
+ // CASE-34: what a hook directory may hold - the dispatchers, the map, and the
116
+ // pre-map wrappers run.mjs still bridges to, one per dispatched name the map
117
+ // does not define. Nothing can reach the rest: a name the map defines is served
118
+ // from the entry, and a name no hooks.json dispatches is never asked for.
119
+ export function orphanHookFiles(names, map, dispatched) {
120
+ const bridged = new Set(dispatched.filter((name) => !map[name]));
121
+ return names.filter((name) =>
122
+ !DISPATCHER_FILES.includes(name) && name !== MAP_FILE && !bridged.has(name));
123
+ }
89
124
 
90
- // The wrapper body. Bash, because it has to exec .sh targets and inherits the
91
- // plugin-root convention every hook already relies on.
92
- export function wrapperBody(cmd, rootVar) {
125
+ // The descriptor that replaces one incompatible command.
126
+ export function hookEntry(cmd, rootVar) {
93
127
  const c = decode(cmd);
94
128
  const rel = relPath(c, rootVar);
95
129
  const h = head(c);
96
130
 
97
- if (rel) {
98
- if (/^python3?$/.test(h)) {
99
- // Resolved once at patch time, not per invocation: hot hooks such as
100
- // PreToolUse should not pay a second interpreter startup.
101
- const py = resolvePython();
102
- if (!py) return disabledBody('no working Python found at patch time');
103
- return PREAMBLE + 'exec "' + py + '" "$PLUGIN_ROOT/' + rel + '" "$@"\n';
104
- }
105
- if (/\.sh$/.test(rel) || /^(bash|sh)$/.test(h)) {
106
- return PREAMBLE + 'exec bash "$PLUGIN_ROOT/' + rel + '" "$@"\n';
107
- }
108
- return PREAMBLE + 'exec "$PLUGIN_ROOT/' + rel + '" "$@"\n';
109
- }
131
+ // CASE-08: a bare dependency that is not installed here. The command is kept
132
+ // whole and re-checked at run time, so installing it later just starts
133
+ // working and its absence never fails the hook.
134
+ if (!rel) return { requires: h, command: c.trim() };
110
135
 
111
- // CASE-08: stay silent when the dependency is genuinely absent, rather than
112
- // failing the hook loudly on every single invocation.
113
- return '#!/bin/bash\nif ! command -v "' + h + '" >/dev/null 2>&1; then\n exit 0\nfi\n' + c.trim() + '\n';
136
+ if (/^python3?$/.test(h)) {
137
+ // Resolved once at patch time, not per invocation: hot hooks such as
138
+ // PreToolUse should not pay a second interpreter startup (CASE-09).
139
+ const py = resolvePython();
140
+ return py ? { exec: py, target: rel } : { disabled: 'no working Python found at patch time' };
141
+ }
142
+ if (/\.sh$/.test(rel) || /^(bash|sh)$/.test(h)) return { exec: 'bash', target: rel };
143
+ return { target: rel };
114
144
  }
115
145
 
116
- // A wrapper body is "broken" when it execs a target that cannot exist: the
117
- // interpreter name captured instead of the script (exec "$PLUGIN_ROOT/bash"),
118
- // or a path that is simply absent. Symptom: bash: .../bash: No such file.
119
- export function brokenWrapperTarget(body, installPath, existsAt) {
120
- const escaped = body.match(/\\"\$(?:\{)?(?:CLAUDE_)?PLUGIN_ROOT(?:\})?\\"\/([A-Za-z0-9_./-]+)/);
121
- if (escaped) return { kind: 'escaped-quotes', rel: escaped[1] };
122
-
123
- const m = body.match(/exec (?:[^\s"]+ )?"\$PLUGIN_ROOT\/([^"]+)"/);
124
- if (!m) return null;
125
- const rel = m[1];
146
+ // A descriptor is broken when its target cannot run: the interpreter name
147
+ // captured instead of the script - the awk-era CASE-24 defect, still reachable
148
+ // through a pre-map wrapper - or a target a plugin update took away.
149
+ export function brokenEntry(entry, installPath, existsAt) {
150
+ const rel = entry && entry.target;
151
+ if (!rel) return null;
126
152
  if (/^(bash|sh|python3?|node|npx|npm)$/.test(rel)) return { kind: 'interpreter', rel };
127
153
  if (!existsAt(installPath + '/' + rel)) return { kind: 'missing-target', rel };
128
154
  return null;
129
155
  }
156
+
157
+ // CASE-22: what a plugin script that runs an interpreter on itself is replaced
158
+ // with. One line, and a no-op under sh, python, and node alike - measured. The
159
+ // obvious "#!/bin/bash\nexit 0" is not it: that body is a SyntaxError under
160
+ // both interpreters the symptom names, so it left the hook just as broken.
161
+ export const NEUTRALIZED_SCRIPT = '#!/bin/sh\n';
package/src/settings.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  //
3
3
  // These hooks are dispatched through cmd.exe, whose environment is not Git
4
4
  // Bash's. Two things break as a result, and both are rewrites of the command
5
- // string rather than wrapper generation - so they live apart from the plugin
5
+ // string rather than a hook descriptor - so they live apart from the plugin
6
6
  // pipeline.
7
7
 
8
8
  import { existsSync } from 'node:fs';
package/src/verify.mjs CHANGED
@@ -3,11 +3,11 @@
3
3
  // The issue types below are a closed vocabulary, shared verbatim with
4
4
  // skills/patch/SKILL.md. Adding one means updating both.
5
5
 
6
- import { copyFileSync, existsSync, mkdirSync, readdirSync, statSync } from 'node:fs';
7
- import { join } from 'node:path';
6
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, rmSync, statSync } from 'node:fs';
7
+ import { dirname, join } from 'node:path';
8
8
  import { hasBom, hasCrlf, readJson, readText, resolvePython, sanitize, writeText } from './env.mjs';
9
9
  import { eachHook } from './hosts.mjs';
10
- import { brokenWrapperTarget, disabledBody, passthroughBody, relPath, wrapperBody, wrapperName } from './rules.mjs';
10
+ import { brokenEntry, DISPATCHER_FILES, hookEntry, MAP_FILE, NEUTRALIZED_SCRIPT, orphanHookFiles, readHookMap, relPath, hookName, writeHookMap } from './rules.mjs';
11
11
 
12
12
  const listFiles = (dir) => {
13
13
  try {
@@ -23,22 +23,38 @@ const readOrNull = (file) => {
23
23
  try { return readText(file); } catch { return null; }
24
24
  };
25
25
 
26
- // Recover the pre-patch command for a wrapper by replaying the naming rule over
27
- // the backups. That is what lets a deleted wrapper be rebuilt exactly (CASE-16).
28
- function originalCommandFor(host, hooksFiles, wrapper) {
26
+ // What one hooks file dispatches through win-hooks, as the argument text that
27
+ // follows run-hook.cmd: the hook name, plus whatever an older patch form
28
+ // forwarded after it. One rule, because the directory-level prune and the
29
+ // per-file entry check have to agree on which hooks are reachable.
30
+ function dispatchedArgs(host, data) {
31
+ const args = [];
32
+ for (const { hook } of eachHook(data)) {
33
+ const patched = String(host.patchedCommand(hook) || '').replace(/\\/g, '/');
34
+ if (!patched.includes(host.hookDir + '/run-hook.cmd')) continue;
35
+ args.push(patched.replace(/^.*run-hook\.cmd"?\s*/i, ''));
36
+ }
37
+ return args;
38
+ }
39
+
40
+ const hookNameOf = (rest) => (rest.match(/^"?([^"\s]+)/) || [])[1];
41
+
42
+ // Recover the pre-patch command for a hook by replaying the naming rule over
43
+ // the backups. That is what lets a deleted hook entry be rebuilt exactly (CASE-16).
44
+ function originalCommandFor(host, hooksFiles, name) {
29
45
  for (const file of hooksFiles) {
30
46
  const bak = readJson(file + host.bakSuffix);
31
47
  if (!bak.ok) continue;
32
48
  for (const { hook } of eachHook(bak.data)) {
33
49
  const command = hook.command;
34
- if (command && wrapperName(command, host.rootVar) === wrapper) return command;
50
+ if (command && hookName(command, host.rootVar) === name) return command;
35
51
  }
36
52
  }
37
53
  return null;
38
54
  }
39
55
 
40
56
  // Every file in one install whose encoding matters: the hook directories, plus
41
- // anything a hooks.json points at, so a wrapper parked in a nonstandard subdir
57
+ // anything a hooks.json points at, so a script parked in a nonstandard subdir
42
58
  // (scripts/) is not missed.
43
59
  function encodingCandidates(host, install, dirFiles) {
44
60
  const files = new Set([...install.hooksFiles, ...dirFiles]);
@@ -49,13 +65,11 @@ function encodingCandidates(host, install, dirFiles) {
49
65
  return [...files].filter((f) => !/\.bak$|\.tmp$/.test(f) && existsSync(f));
50
66
  }
51
67
 
52
- // Directory-level checks, run once per install tree. A Codex plugin declares
53
- // one hooks.json per event, so this is where re-scanning the same directory
54
- // dozens of times would otherwise come from.
68
+ // Directory-level checks, run once per install tree.
55
69
  function checkTree(host, install, report, repair) {
56
- const wrapperDir = join(install.path, host.wrapperDir);
70
+ const hookDir = join(install.path, host.hookDir);
57
71
  const rel = (file) => file.replace(install.path, '').replace(/^[\\/]/, '').replace(/\\/g, '/');
58
- const dirFiles = [...listFiles(join(install.path, 'hooks')), ...listFiles(wrapperDir)];
72
+ const dirFiles = [...listFiles(join(install.path, 'hooks')), ...listFiles(hookDir)];
59
73
 
60
74
  // ── Encoding (CASE-01/02/03) ──────────────────────────────────────
61
75
  for (const file of encodingCandidates(host, install, dirFiles)) {
@@ -70,82 +84,150 @@ function checkTree(host, install, report, repair) {
70
84
  repair(() => { sanitize(file); return 'normalized CRLF in ' + rel(file); });
71
85
  }
72
86
 
73
- // ── Wrapper bodies ────────────────────────────────────────────────
87
+ // ── CASE-22: a script that runs an interpreter on its own filename ───
88
+ // It recurses until the hook times out. Only bash files qualify: the symptom
89
+ // is a plugin shipping a shell script under a .py or .js name.
74
90
  for (const file of dirFiles) {
75
- const name = baseName(file);
76
- if (name === 'run-hook.cmd') continue;
77
91
  const body = readOrNull(file);
78
92
  if (body === null || !/^#!\/(bin\/bash|usr\/bin\/env bash)/.test(body)) continue;
79
-
80
- // CASE-22: a bash wrapper that invokes an interpreter on its own filename
81
- // recurses until the hook times out.
93
+ const name = baseName(file);
82
94
  const self = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
83
- if (new RegExp('(python3?|node)\\s+\\S*' + self).test(body)) {
84
- report('recursive_wrapper', name + ' calls an interpreter on itself');
85
- repair(() => {
86
- writeText(file, disabledBody('bash wrapper called an interpreter on itself'));
87
- return 'disabled recursive wrapper ' + name;
88
- });
89
- continue;
90
- }
95
+ if (!new RegExp('(python3?|node)\\s+\\S*' + self).test(body)) continue;
96
+ report('recursive_wrapper', name + ' calls an interpreter on itself');
97
+ repair(() => {
98
+ writeText(file, NEUTRALIZED_SCRIPT);
99
+ return 'neutralized recursive script ' + rel(file);
100
+ });
101
+ }
91
102
 
92
- // CASE-24: the wrapper execs a target that cannot exist.
93
- const broken = brokenWrapperTarget(body, install.path, existsSync);
103
+ // ── CASE-24: a hook descriptor whose target cannot run ──────────────
104
+ const map = readHookMap(hookDir);
105
+ for (const [name, entry] of Object.entries(map)) {
106
+ const broken = brokenEntry(entry, install.path, existsSync);
94
107
  if (!broken) continue;
95
- report('wrapper_broken', rel(file) + ' execs an invalid target: ' + broken.rel);
108
+ report('wrapper_broken', name + ' targets ' + broken.rel + ' (' + broken.kind + ')');
96
109
  repair(() => {
110
+ // Rebuilt from the pre-patch command, and disabled outright when even
111
+ // that points at something no longer on disk - reporting the same broken
112
+ // entry every session is not a repair.
97
113
  const original = originalCommandFor(host, install.hooksFiles, name);
98
- writeText(file, original ? wrapperBody(original, host.rootVar) : passthroughBody());
99
- return 'repaired wrapper ' + rel(file);
114
+ const rebuilt = original ? hookEntry(original, host.rootVar) : null;
115
+ map[name] = rebuilt && !brokenEntry(rebuilt, install.path, existsSync)
116
+ ? rebuilt
117
+ : { disabled: broken.rel + ' is not on disk' };
118
+ writeHookMap(hookDir, map);
119
+ return 'repaired hook entry ' + name;
120
+ });
121
+ }
122
+
123
+ // ── CASE-34: a file the pre-descriptor layout left behind ───────────
124
+ // Reachability is decided from every hooks file in the tree at once, and
125
+ // only when all of them parsed: an incomplete picture of what is dispatched
126
+ // would condemn a wrapper that is still the only way one hook runs.
127
+ const parsed = install.hooksFiles.map((file) => readJson(file));
128
+ if (!parsed.every((p) => p.ok)) return;
129
+ const dispatched = parsed
130
+ .flatMap((p) => dispatchedArgs(host, p.data))
131
+ .map(hookNameOf)
132
+ .filter(Boolean);
133
+
134
+ for (const name of orphanHookFiles(listFiles(hookDir).map(baseName), map, dispatched)) {
135
+ report('wrapper_orphan', name + ' is dispatched by nothing');
136
+ repair(() => {
137
+ const file = join(hookDir, name);
138
+ rmSync(file);
139
+ return 'removed leftover ' + rel(file);
100
140
  });
101
141
  }
102
142
  }
103
143
 
104
- // Per-hooks.json checks: is it parseable, and does every wrapper it names exist?
105
- function checkHooksFile(host, install, plugin, report, repair) {
106
- const wrapperDir = join(install.path, host.wrapperDir);
144
+ // The dispatcher is run-hook.cmd plus the run.mjs it starts, and present is not
145
+ // enough: a copy from an older release still execs the wrapper file the
146
+ // descriptor map replaced, and a fully compatible plugin never re-enters patch
147
+ // setup to be refreshed there (CASE-27). Contents compare through the
148
+ // normalizing read, so a BOM or CRLF stays one report, as corruption.
149
+ function checkDispatcher(host, hookDir, templateCmd, report, repair) {
150
+ for (const name of DISPATCHER_FILES) {
151
+ const target = join(hookDir, name);
152
+ const source = templateCmd ? join(dirname(templateCmd), name) : null;
153
+ const shipped = source ? readOrNull(source) : null;
154
+ const state = !existsSync(target) ? 'not found'
155
+ : shipped !== null && readOrNull(target) !== shipped ? 'is stale'
156
+ : null;
157
+ if (!state) continue;
158
+ report('cmd_missing', host.hookDir + '/' + name + ' ' + state);
159
+ if (!source) continue;
160
+ repair(() => {
161
+ mkdirSync(hookDir, { recursive: true });
162
+ copyFileSync(source, target);
163
+ return 'restored ' + host.hookDir + '/' + name;
164
+ });
165
+ }
166
+ }
167
+
168
+ // Per-hooks.json checks: is it parseable, and does every hook it names exist?
169
+ function checkHooksFile(host, install, plugin, templateCmd, report, repair) {
170
+ const hookDir = join(install.path, host.hookDir);
107
171
  const { ok, data, error } = readJson(plugin.hooksFile);
108
172
  if (!ok) return report('json_invalid', error);
109
173
 
110
- let needsRunHook = false;
111
174
  for (const { hook } of eachHook(data)) {
112
175
  // A python hook still running bare on a machine with no usable interpreter
113
176
  // can never succeed; say so rather than failing silently (CASE-09/21).
114
177
  if (/^python3?\s/.test(String(host.sourceCommand(hook) || '').trim()) && !resolvePython()) {
115
178
  report('python3_stub', 'hook uses python but no working interpreter is installed');
116
179
  }
180
+ }
117
181
 
118
- const patched = String(host.patchedCommand(hook) || '').replace(/\\/g, '/');
119
- if (!patched.includes(host.wrapperDir + '/run-hook.cmd')) continue;
120
- needsRunHook = true;
182
+ const dispatched = dispatchedArgs(host, data);
183
+ if (!dispatched.length) return;
184
+
185
+ // Before the entry repairs below, not after: they delete the legacy wrapper
186
+ // file that a stale dispatcher is still exec'ing, and a run that refreshed
187
+ // the dispatcher second would leave the plugin dead in the gap.
188
+ checkDispatcher(host, hookDir, templateCmd, report, repair);
121
189
 
122
- const rest = patched.replace(/^.*run-hook\.cmd"?\s*/i, '');
123
- const wrapper = (rest.match(/^"?([^"\s]+)/) || [])[1];
124
- if (!wrapper) { report('wrapper_missing', 'wrapper name is not parseable'); continue; }
125
- if (existsSync(join(wrapperDir, wrapper))) continue;
190
+ const map = readHookMap(hookDir);
191
+ for (const rest of dispatched) {
192
+ const name = hookNameOf(rest);
193
+ if (!name) { report('wrapper_missing', 'hook name is not parseable'); continue; }
194
+ if (map[name]) continue;
126
195
 
127
- report('wrapper_missing', host.wrapperDir + '/' + wrapper + ' not found');
196
+ report('wrapper_missing', MAP_FILE + ' has no entry for ' + name);
128
197
  repair(() => {
129
198
  // An older patch form forwarded the real target as a trailing argument;
130
- // run-hook.cmd passes it through, so a passthrough body is correct there.
199
+ // it was handed to bash, so that is the entry it becomes.
131
200
  const forwarded = relPath(rest, host.rootVar);
132
- const original = forwarded ? null : originalCommandFor(host, install.hooksFiles, wrapper);
133
- if (!forwarded && !original) return 'could not rebuild ' + wrapper + ' (no usable backup)';
134
- mkdirSync(wrapperDir, { recursive: true });
135
- writeText(join(wrapperDir, wrapper), forwarded ? passthroughBody() : wrapperBody(original, host.rootVar));
136
- return 'recreated missing wrapper ' + host.wrapperDir + '/' + wrapper;
201
+ const original = forwarded ? null : originalCommandFor(host, install.hooksFiles, name);
202
+ if (!forwarded && !original) return 'could not rebuild ' + name + ' (no usable backup)';
203
+ mkdirSync(hookDir, { recursive: true });
204
+ const merged = readHookMap(hookDir);
205
+ merged[name] = forwarded
206
+ ? { exec: 'bash', target: forwarded }
207
+ : hookEntry(original, host.rootVar);
208
+ writeHookMap(hookDir, merged);
209
+ // A pre-map wrapper file of the same name is now shadowed by the entry;
210
+ // dropping it keeps the fallback in run.mjs a migration bridge rather
211
+ // than a second supported layout.
212
+ const legacy = join(hookDir, name);
213
+ if ((readOrNull(legacy) || '').startsWith('#!/bin/bash')) rmSync(legacy);
214
+ return 'added hook entry ' + name;
137
215
  });
138
216
  }
217
+ }
139
218
 
140
- if (needsRunHook && !existsSync(join(wrapperDir, 'run-hook.cmd'))) {
141
- report('cmd_missing', host.wrapperDir + '/run-hook.cmd not found');
142
- repair((templateCmd) => {
143
- if (!templateCmd) return null;
144
- mkdirSync(wrapperDir, { recursive: true });
145
- copyFileSync(templateCmd, join(wrapperDir, 'run-hook.cmd'));
146
- return 'restored ' + host.wrapperDir + '/run-hook.cmd';
147
- });
219
+ // Codex declares one hooks.json per event, so many "plugins" share one install
220
+ // tree. Group them, or every directory-level check runs once per hooks file.
221
+ function byInstall(plugins) {
222
+ const trees = new Map();
223
+ for (const plugin of plugins) {
224
+ const tree = trees.get(plugin.installPath)
225
+ || { path: plugin.installPath, plugins: [], hooksFiles: [] };
226
+ tree.plugins.push(plugin);
227
+ tree.hooksFiles.push(plugin.hooksFile);
228
+ trees.set(plugin.installPath, tree);
148
229
  }
230
+ return [...trees.values()];
149
231
  }
150
232
 
151
233
  export function verify(host, { fix = false, templateCmd = null, plugins = host.listPlugins() } = {}) {
@@ -158,7 +240,7 @@ export function verify(host, { fix = false, templateCmd = null, plugins = host.l
158
240
  repair: (action) => {
159
241
  if (!fix) return;
160
242
  let done;
161
- try { done = action(templateCmd); } catch (e) { done = 'repair failed: ' + e.message; }
243
+ try { done = action(); } catch (e) { done = 'repair failed: ' + e.message; }
162
244
  if (done) fixes.push(done);
163
245
  },
164
246
  });
@@ -174,23 +256,9 @@ export function verify(host, { fix = false, templateCmd = null, plugins = host.l
174
256
 
175
257
  guard(install.plugins[0], (report, repair) => checkTree(host, install, report, repair));
176
258
  for (const plugin of install.plugins) {
177
- guard(plugin, (report, repair) => checkHooksFile(host, install, plugin, report, repair));
259
+ guard(plugin, (report, repair) => checkHooksFile(host, install, plugin, templateCmd, report, repair));
178
260
  }
179
261
  }
180
262
 
181
263
  return { issues, fixes };
182
264
  }
183
-
184
- // Codex declares one hooks.json per event, so many "plugins" share one install
185
- // tree. Group them, or every directory-level check runs once per hooks file.
186
- function byInstall(plugins) {
187
- const trees = new Map();
188
- for (const plugin of plugins) {
189
- const tree = trees.get(plugin.installPath)
190
- || { path: plugin.installPath, plugins: [], hooksFiles: [] };
191
- tree.plugins.push(plugin);
192
- tree.hooksFiles.push(plugin.hooksFile);
193
- trees.set(plugin.installPath, tree);
194
- }
195
- return [...trees.values()];
196
- }
package/hooks/win-hooks DELETED
@@ -1,10 +0,0 @@
1
- #!/bin/bash
2
- # The bridge from a hook dispatch to the engine.
3
- #
4
- # run-hook.cmd already knows how to find bash on Windows, so win-hooks reaches
5
- # its own engine exactly the way a patched plugin reaches its wrapper - if this
6
- # path works here, it works there.
7
- #
8
- # Fail-safe: a missing runtime means no repair, never a broken session.
9
- command -v node >/dev/null 2>&1 || exit 0
10
- exec node "$(cd "$(dirname "$0")/.." && pwd)/bin/win-hooks.mjs" "$@"