@lilmgenius/win-hooks 1.13.0 → 1.15.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
 
@@ -56,12 +56,15 @@ You installed a plugin. It works fine for everyone on a Mac. On your machine it
56
56
  | `Python was not found; ... Microsoft Store` | Windows' fake `python3` placeholder shadowing your real one |
57
57
  | `JSON Parse error: Unrecognized token` | An invisible byte (BOM) at the top of a config file |
58
58
  | `Cannot find module 'C:\Users...'` | Backslashes in a path getting eaten before the hook runs |
59
+ | `hook exited with code 1` on every hook, in a Codex session that was fine an hour ago | Another Codex window updated the plugin and deleted the version this session was running |
59
60
 
60
61
  None of that is your fault. Almost every plugin is written and tested on macOS or Linux, so its hooks assume Unix tools that Windows does not have.
61
62
 
63
+ It also repairs the damage no error message shows you: CRLF line endings, a `hooks.json` no parser will read, and the patched hook entries themselves - one that went missing, one that calls an interpreter on itself, one aimed at a target that is gone, and files an older win-hooks left behind.
64
+
62
65
  ## How it stays fixed
63
66
 
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.
67
+ 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
68
 
66
69
  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
70
 
package/bin/win-hooks.mjs CHANGED
@@ -1,6 +1,6 @@
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
5
  // heal [host] silent repair; --changed-only skips when no plugin's hooks
6
6
  // changed since the last run (the near-free per-prompt guard);
@@ -68,7 +68,7 @@ function announcement({ host, scanned, patched, issues, fixes }) {
68
68
 
69
69
  function summarize({ host, patched, failed, settings, issues, fixes }) {
70
70
  const lines = [];
71
- 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(', ') + ')');
72
72
  for (const f of failed) lines.push('win-hooks: could not patch ' + f.plugin.id + ' - ' + f.error);
73
73
  if (settings.length) lines.push('win-hooks: repaired ' + settings.length + ' hook command(s) in ' + host.label + ' settings');
74
74
  for (const f of fixes) lines.push('win-hooks: ' + f);
@@ -114,9 +114,17 @@ function report({ host, plugins, incompatible, issues, settings }, heading) {
114
114
  + ' - ' + plugins.length + ' hook file(s) scanned';
115
115
  const lines = [title];
116
116
 
117
- for (const i of incompatible) lines.push(' incompatible ' + i.id + ' [' + i.event + '] ' + i.command);
118
- for (const i of issues) lines.push(' ' + i.type.padEnd(14) + i.plugin + ' ' + i.detail);
119
- 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
+ }
120
128
  if (lines.length === 1) lines.push(' healthy - every hook is Windows-compatible');
121
129
  return lines.join('\n');
122
130
  }
@@ -6,7 +6,7 @@
6
6
  "hooks": [
7
7
  {
8
8
  "type": "command",
9
- "command": "bash \"${PLUGIN_ROOT}/hooks/win-hooks\" heal codex --announce",
9
+ "command": "bash \"${PLUGIN_ROOT}/hooks/run-hook.cmd\" win-hooks heal codex --announce",
10
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"
@@ -19,7 +19,7 @@
19
19
  "hooks": [
20
20
  {
21
21
  "type": "command",
22
- "command": "bash \"${PLUGIN_ROOT}/hooks/win-hooks\" heal codex --changed-only",
22
+ "command": "bash \"${PLUGIN_ROOT}/hooks/run-hook.cmd\" win-hooks heal codex --changed-only",
23
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"
@@ -0,0 +1,3 @@
1
+ {
2
+ "win-hooks": { "exec": "node", "target": "bin/win-hooks.mjs" }
3
+ }
@@ -3,59 +3,49 @@
3
3
  REM The entry point every patched hook is dispatched through: one file that is
4
4
  REM valid batch AND valid bash at once, so Claude Code and Codex can each
5
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. Wrapper names are
6
+ REM it as a quoted here-doc and falls through to the tail. Hook names are
7
7
  REM extensionless because Claude Code prepends "bash" to any command containing
8
8
  REM .sh, which would undo the patch (CASE-07).
9
9
  REM
10
- REM Usage: run-hook.cmd <script-name> [args...]
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).
13
+ REM
14
+ REM Usage: run-hook.cmd <hook-name> [args...]
11
15
 
12
16
  if "%~1"=="" (
13
- echo run-hook.cmd: missing script name >&2
17
+ echo win-hooks: run-hook.cmd was given no hook name >&2
14
18
  exit /b 1
15
19
  )
16
20
 
17
- set "HOOK_DIR=%~dp0"
18
- set "WH_BASH="
19
-
20
- REM Explicit override first, for a portable, scoop, or winget Git install.
21
- if defined WH_BASH_EXE if exist "%WH_BASH_EXE%" set "WH_BASH=%WH_BASH_EXE%"
22
-
23
- REM Then Git for Windows, which is where it almost always is.
24
- if not defined WH_BASH if exist "C:\Program Files\Git\bin\bash.exe" set "WH_BASH=C:\Program Files\Git\bin\bash.exe"
25
- 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
-
27
- if defined WH_BASH goto :run
21
+ set "WH_NODE="
28
22
 
29
- REM Finally PATH (MSYS2, Cygwin, a nonstandard install), resolved by the FOR
30
- REM path-search modifier below - `where` costs a subprocess. Never name that
31
- REM modifier in a REM: cmd.exe expands it there too and the comment breaks.
32
- for %%I in (bash.exe) do set "WH_BASH=%%~$PATH:I"
33
- if not defined WH_BASH goto :nobash
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%"
34
25
 
35
- REM PATH bash is often C:\Windows\System32\bash.exe, the WSL launcher: it
36
- REM cannot open Windows paths yet still exits 0, so it would swallow every hook
37
- REM forever. A PATH candidate must prove it can see the script it is about to
38
- REM run (CASE-29); the paths above are known-good. The probe travels through
39
- REM the environment because WSL does not forward $0 the way a real bash does.
40
- set "WH_PROBE=%HOOK_DIR%%~1"
41
- "%WH_BASH%" -c "test -f \"$WH_PROBE\"" >nul 2>&1
42
- if errorlevel 1 goto :nobash
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
43
31
 
44
- :run
45
- REM %* would ignore the shift, so arguments are forwarded positionally. Eight
46
- REM is every hook win-hooks generates; a ninth would be silently dropped.
47
- "%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" %*
48
36
  exit /b %ERRORLEVEL%
49
37
 
50
- :nobash
38
+ :nonode
51
39
  REM Fail-safe: no repair, never a broken session - but say so, because a hook
52
40
  REM that does nothing quietly is the exact failure win-hooks exists to catch.
53
- echo run-hook.cmd: no bash that can run "%~1"; skipping >&2
41
+ echo win-hooks: no node found; skipping "%~1" >&2
54
42
  exit /b 0
55
43
  CMDBLOCK
56
44
 
57
- # bash: run the named script directly.
58
- SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
59
- SCRIPT_NAME="$1"
60
- shift
61
- 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.13.0",
3
+ "version": "1.15.0",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
package/src/heal.mjs CHANGED
@@ -15,6 +15,7 @@ import { newestMtime, readJson, writeJson, writeText } from './env.mjs';
15
15
  import { HOSTS } from './hosts.mjs';
16
16
  import { findIncompatible, patchAll } from './patch.mjs';
17
17
  import { fixSettings } from './settings.mjs';
18
+ import { restoreStaleRoots } from './stale.mjs';
18
19
  import { verify } from './verify.mjs';
19
20
 
20
21
  const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
@@ -83,12 +84,20 @@ const commit = (host, plugins) => {
83
84
  export function heal(hostId, { changedOnly = false } = {}) {
84
85
  const host = HOSTS[hostId];
85
86
  const started = Date.now();
86
- if (changedOnly && unchanged(host)) return null;
87
+ // Before the guard: an upgrade run by another process moves nothing the
88
+ // guard watches, and the sessions it broke are waiting on this prompt.
89
+ const restored = host.cacheDir ? restoreStaleRoots(host.cacheDir) : [];
90
+ if (changedOnly && unchanged(host)) {
91
+ if (!restored.length) return null;
92
+ record(host, { dur: (Date.now() - started) + 'ms', restored: restored.length });
93
+ return { host, scanned: 0, patched: [], failed: [], settings: [], issues: [], fixes: restored };
94
+ }
87
95
 
88
96
  const plugins = host.listPlugins();
89
97
  const { patched, failed } = patchAll(host, TEMPLATE_CMD, plugins);
90
98
  const settings = fixSettings(host.settingsFile, { fix: true });
91
99
  const { issues, fixes } = verify(host, { fix: true, templateCmd: TEMPLATE_CMD, plugins });
100
+ fixes.push(...restored);
92
101
 
93
102
  commit(host, plugins);
94
103
  record(host, {
@@ -98,6 +107,7 @@ export function heal(hostId, { changedOnly = false } = {}) {
98
107
  settings: settings.length,
99
108
  fixed: fixes.length,
100
109
  issues: issues.length,
110
+ restored: restored.length,
101
111
  });
102
112
 
103
113
  return { host, scanned: plugins.length, patched, failed, settings, issues, fixes };
@@ -111,7 +121,7 @@ export function inspect(hostId) {
111
121
  host,
112
122
  plugins,
113
123
  incompatible: findIncompatible(host, plugins),
114
- issues: verify(host, { plugins }).issues,
124
+ issues: verify(host, { templateCmd: TEMPLATE_CMD, plugins }).issues,
115
125
  settings: fixSettings(host.settingsFile),
116
126
  log: readLog(host),
117
127
  };
package/src/hosts.mjs CHANGED
@@ -1,10 +1,10 @@
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';
@@ -54,7 +54,7 @@ const claude = {
54
54
  id: 'claude',
55
55
  label: 'Claude Code',
56
56
  rootVar: 'CLAUDE_PLUGIN_ROOT',
57
- wrapperDir: '_hooks',
57
+ hookDir: '_hooks',
58
58
  bakSuffix: '.bak',
59
59
  stateDir: join(HOME, '.claude/win-hooks'),
60
60
  settingsFile: join(HOME, '.claude/settings.json'),
@@ -63,17 +63,17 @@ const claude = {
63
63
  registry: [join(HOME, '.claude/plugins/installed_plugins.json'), join(HOME, '.claude/settings.json')],
64
64
  listPlugins: listClaudePlugins,
65
65
  // Claude replaces the command outright, so an already-patched hook is one
66
- // 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.
67
67
  sourceCommand: (hook) => hook.command,
68
68
  patchedCommand: (hook) => hook.command,
69
69
  applyPatch: (hook, ref) => { hook.command = ref; },
70
70
  // The shells that may dispatch a command this host emits. Claude Code runs a
71
71
  // Windows hook command through cmd.exe, the one shell that also accepts a
72
72
  // quoted path in command position, so the reference below needs no prefix.
73
- // The CASE-31 gate executes wrapperRef under every shell named here.
73
+ // The CASE-31 gate executes hookRef under every shell named here.
74
74
  dispatchers: ['cmd'],
75
- wrapperRef: (wrapper, args) =>
76
- '"${CLAUDE_PLUGIN_ROOT}/_hooks/run-hook.cmd" ' + wrapper + (args ? ' ' + args : ''),
75
+ hookRef: (name, args) =>
76
+ '"${CLAUDE_PLUGIN_ROOT}/_hooks/run-hook.cmd" ' + name + (args ? ' ' + args : ''),
77
77
  };
78
78
 
79
79
  // ── Codex ─────────────────────────────────────────────────────────────
@@ -114,13 +114,15 @@ const codex = {
114
114
  id: 'codex',
115
115
  label: 'Codex',
116
116
  rootVar: 'PLUGIN_ROOT',
117
- wrapperDir: '_codex_hooks',
117
+ hookDir: '_codex_hooks',
118
118
  bakSuffix: '.codex-win-hooks.bak',
119
119
  stateDir: join(HOME, '.codex/win-hooks'),
120
120
  settingsFile: null,
121
121
  // Codex records every install, removal, enable, and marketplace update in
122
122
  // config.toml, so one stat covers the whole plugin set.
123
123
  registry: [join(HOME, '.codex/config.toml')],
124
+ // Where Codex keeps one directory per installed plugin version (CASE-35).
125
+ cacheDir: join(HOME, '.codex/plugins/cache'),
124
126
  listPlugins: listCodexPlugins,
125
127
  // A hook that already carries commandWindows is patched; leave the portable
126
128
  // command alone so it still runs natively on macOS and Linux.
@@ -130,10 +132,10 @@ const codex = {
130
132
  // Codex hands commandWindows to the session shell, which is cmd.exe or
131
133
  // PowerShell depending on how the session was started - so the reference has
132
134
  // to carry the CASE-31 prefix. The backslashes are for the cmd.exe that ends
133
- // up running the wrapper.
135
+ // up running the hook.
134
136
  dispatchers: ['cmd', 'powershell'],
135
- wrapperRef: (wrapper, args) =>
136
- DISPATCH_PREFIX + '"${PLUGIN_ROOT}\\_codex_hooks\\run-hook.cmd" ' + wrapper
137
+ hookRef: (name, args) =>
138
+ DISPATCH_PREFIX + '"${PLUGIN_ROOT}\\_codex_hooks\\run-hook.cmd" ' + name
137
139
  + (args ? ' ' + args : ''),
138
140
  };
139
141
 
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.
@@ -71,9 +72,13 @@ export const opensWithQuotedPath = (cmd) => /^["']/.test(decode(cmd).trim());
71
72
  export const isDispatchable = (cmd, dispatchers) =>
72
73
  !opensWithQuotedPath(cmd) || dispatchers.every((shell) => shell === 'cmd');
73
74
 
74
- // Wrapper filenames are extensionless, so Claude Code's Windows auto-detection
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
75
80
  // does not prepend "bash" to anything containing ".sh" (CASE-07).
76
- export function wrapperName(cmd, rootVar) {
81
+ export function hookName(cmd, rootVar) {
77
82
  const c = decode(cmd);
78
83
 
79
84
  // A keyed invocation names itself after its subject:
@@ -88,57 +93,69 @@ export function wrapperName(cmd, rootVar) {
88
93
  }
89
94
 
90
95
  const name = c.trim().split(/\s+/).slice(0, 3).join('-').replace(/[^A-Za-z0-9-]/g, '');
91
- return name || 'hook-wrapper';
96
+ return name || 'hook';
92
97
  }
93
98
 
94
- const PREAMBLE =
95
- '#!/bin/bash\n' +
96
- 'SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"\n' +
97
- 'PLUGIN_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"\n';
98
-
99
- export const passthroughBody = () =>
100
- '#!/bin/bash\n# win-hooks: exec the real target passed through by run-hook.cmd\nexec bash "$@"\n';
101
-
102
- export const disabledBody = (why) =>
103
- '#!/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
+ }
104
124
 
105
- // The wrapper body. Bash, because it has to exec .sh targets and inherits the
106
- // plugin-root convention every hook already relies on.
107
- export function wrapperBody(cmd, rootVar) {
125
+ // The descriptor that replaces one incompatible command.
126
+ export function hookEntry(cmd, rootVar) {
108
127
  const c = decode(cmd);
109
128
  const rel = relPath(c, rootVar);
110
129
  const h = head(c);
111
130
 
112
- if (rel) {
113
- if (/^python3?$/.test(h)) {
114
- // Resolved once at patch time, not per invocation: hot hooks such as
115
- // PreToolUse should not pay a second interpreter startup.
116
- const py = resolvePython();
117
- if (!py) return disabledBody('no working Python found at patch time');
118
- return PREAMBLE + 'exec "' + py + '" "$PLUGIN_ROOT/' + rel + '" "$@"\n';
119
- }
120
- if (/\.sh$/.test(rel) || /^(bash|sh)$/.test(h)) {
121
- return PREAMBLE + 'exec bash "$PLUGIN_ROOT/' + rel + '" "$@"\n';
122
- }
123
- return PREAMBLE + 'exec "$PLUGIN_ROOT/' + rel + '" "$@"\n';
124
- }
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() };
125
135
 
126
- // CASE-08: stay silent when the dependency is genuinely absent, rather than
127
- // failing the hook loudly on every single invocation.
128
- 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 };
129
144
  }
130
145
 
131
- // A wrapper body is "broken" when it execs a target that cannot exist: the
132
- // interpreter name captured instead of the script (exec "$PLUGIN_ROOT/bash"),
133
- // or a path that is simply absent. Symptom: bash: .../bash: No such file.
134
- export function brokenWrapperTarget(body, installPath, existsAt) {
135
- const escaped = body.match(/\\"\$(?:\{)?(?:CLAUDE_)?PLUGIN_ROOT(?:\})?\\"\/([A-Za-z0-9_./-]+)/);
136
- if (escaped) return { kind: 'escaped-quotes', rel: escaped[1] };
137
-
138
- const m = body.match(/exec (?:[^\s"]+ )?"\$PLUGIN_ROOT\/([^"]+)"/);
139
- if (!m) return null;
140
- 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;
141
152
  if (/^(bash|sh|python3?|node|npx|npm)$/.test(rel)) return { kind: 'interpreter', rel };
142
153
  if (!existsAt(installPath + '/' + rel)) return { kind: 'missing-target', rel };
143
154
  return null;
144
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/stale.mjs ADDED
@@ -0,0 +1,99 @@
1
+ // Version directories a live Codex session still runs from (CASE-35).
2
+ //
3
+ // Codex resolves ${PLUGIN_ROOT} into a versioned cache path once, when a
4
+ // session loads its hooks, and never again. A marketplace upgrade run by any
5
+ // other Codex process installs the next version beside it and deletes the old
6
+ // one, so every hook of every session already open fails from then on: the
7
+ // session's shell reports `hook exited with code 1` and Codex shows nothing
8
+ // else (openai/codex#31383). On Windows the deletion usually stops short of
9
+ // the directory itself, because a process the old session started still holds
10
+ // it, and that leftover empty directory is the one place those sessions look.
11
+ //
12
+ // The repair links each directory of the installed version into the emptied
13
+ // one with a junction, so the old sessions run the new code until they end.
14
+ // Nothing real is touched: a directory holding any real file or directory is
15
+ // either a whole older version or an install in progress, and the restored
16
+ // root gets no `.codex-plugin`, so it never reads as an installed version.
17
+ // Codex's own cleanup removes a junction without following it.
18
+
19
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readlinkSync, statSync, symlinkSync, unlinkSync } from 'node:fs';
20
+ import { join, resolve } from 'node:path';
21
+
22
+ const MANIFEST_DIR = '.codex-plugin';
23
+
24
+ const lstatOf = (path) => {
25
+ try {
26
+ return lstatSync(path);
27
+ } catch {
28
+ return null;
29
+ }
30
+ };
31
+
32
+ const childNames = (dir) => {
33
+ try {
34
+ return readdirSync(dir);
35
+ } catch {
36
+ return [];
37
+ }
38
+ };
39
+
40
+ const isRealDir = (path) => {
41
+ const st = lstatOf(path);
42
+ return Boolean(st && st.isDirectory() && !st.isSymbolicLink());
43
+ };
44
+
45
+ // An installed version: its manifest directory is real, not one of our links.
46
+ const isInstalled = (root) => isRealDir(join(root, MANIFEST_DIR)) && existsSync(join(root, MANIFEST_DIR, 'plugin.json'));
47
+
48
+ // Empty, or holding nothing but links: what an upgrade left of a version.
49
+ const isEmptied = (root) => isRealDir(root) && !isInstalled(root)
50
+ && childNames(root).every((name) => lstatOf(join(root, name))?.isSymbolicLink());
51
+
52
+ const samePath = (a, b) => {
53
+ const norm = (p) => resolve(String(p).replace(/^\\\\\?\\/, '')).replace(/[\\/]+$/, '').toLowerCase();
54
+ return norm(a) === norm(b);
55
+ };
56
+
57
+ // Point `link` at `target`; returns whether anything changed.
58
+ function linkTo(link, target) {
59
+ const st = lstatOf(link);
60
+ if (st && !st.isSymbolicLink()) return false;
61
+ if (st) {
62
+ if (samePath(readlinkSync(link), target)) return false;
63
+ unlinkSync(link);
64
+ }
65
+ symlinkSync(target, link, 'junction');
66
+ return true;
67
+ }
68
+
69
+ // The version Codex installed last. Codex copies files with their source
70
+ // times, so the directory's own creation time is the install time.
71
+ const newest = (roots) => roots
72
+ .map((root) => ({ root, born: statSync(root).birthtimeMs }))
73
+ .sort((a, b) => b.born - a.born)[0]?.root;
74
+
75
+ // Repair every emptied version under a Codex plugin cache; returns one line
76
+ // per version it relinked.
77
+ export function restoreStaleRoots(cacheDir) {
78
+ const restored = [];
79
+ for (const marketplace of childNames(cacheDir)) {
80
+ for (const plugin of childNames(join(cacheDir, marketplace))) {
81
+ const base = join(cacheDir, marketplace, plugin);
82
+ const versions = childNames(base).filter((name) => !name.startsWith('.')).map((name) => join(base, name));
83
+ const current = newest(versions.filter(isInstalled));
84
+ if (!current) continue;
85
+
86
+ for (const root of versions.filter(isEmptied)) {
87
+ const names = childNames(current).filter((name) => name !== MANIFEST_DIR && isRealDir(join(current, name)));
88
+ mkdirSync(root, { recursive: true });
89
+ const changed = names.filter((name) => linkTo(join(root, name), join(current, name)));
90
+ if (changed.length) {
91
+ restored.push('relinked ' + plugin + '/' + root.slice(base.length + 1) + ' to ' + current.slice(base.length + 1)
92
+ + ' for the sessions still running from it (' + marketplace + ')');
93
+ }
94
+ }
95
+ }
96
+ }
97
+ return restored;
98
+ }
99
+
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,8 +0,0 @@
1
- #!/bin/bash
2
- # The bridge from a hook dispatch to the engine. win-hooks reaches its own
3
- # engine exactly the way a patched plugin reaches its wrapper, so if this path
4
- # works here it works there.
5
- #
6
- # Fail-safe: a missing runtime means no repair, never a broken session.
7
- command -v node >/dev/null 2>&1 || exit 0
8
- exec node "$(cd "$(dirname "$0")/.." && pwd)/bin/win-hooks.mjs" "$@"