@lilmgenius/win-hooks 1.15.0 → 1.15.2

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
@@ -57,6 +57,7 @@ You installed a plugin. It works fine for everyone on a Mac. On your machine it
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
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 |
60
+ | win-hooks' own hooks fail in sessions opened before its update, and `patch` says healthy | The update removed the version those sessions run from; win-hooks now remembers it and puts it back |
60
61
 
61
62
  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.
62
63
 
@@ -79,4 +80,4 @@ win-hooks runs entirely on your machine and sends nothing anywhere. No telemetry
79
80
 
80
81
  ## License
81
82
 
82
- [MIT](LICENSE). How it works, and every failure mode it handles: [`AGENTS.md`](AGENTS.md).
83
+ [MIT](LICENSE). See the [architecture map](AGENTS.md#architecture) and [catalogue of failure modes](AGENTS.md#known-edge-cases--scenarios).
package/bin/win-hooks.mjs CHANGED
@@ -105,11 +105,22 @@ function statusOf(id) {
105
105
  return report(state) + heartbeat(state);
106
106
  }
107
107
 
108
- function healthy({ incompatible, issues, settings }) {
109
- return !incompatible.length && !issues.length && !settings.length;
108
+ // A root an open session runs from and cannot find is a broken session, even
109
+ // though no hook file is wrong (CASE-36). A restored one is working, and is
110
+ // listed so a person can see why a version directory holds only links.
111
+ function brokenRoots(roots = []) {
112
+ return roots.filter((r) => r.state !== 'restored');
110
113
  }
111
114
 
112
- function report({ host, plugins, incompatible, issues, settings }, heading) {
115
+ function healthy({ incompatible, issues, settings, roots }) {
116
+ return !incompatible.length && !issues.length && !settings.length && !brokenRoots(roots).length;
117
+ }
118
+
119
+ function rootName(r) {
120
+ return r.plugin + '/' + r.version + ' (' + r.marketplace + ')';
121
+ }
122
+
123
+ function report({ host, plugins, incompatible, issues, settings, roots = [] }, heading) {
113
124
  const title = '# ' + host.label + (heading ? ' ' + heading : '')
114
125
  + ' - ' + plugins.length + ' hook file(s) scanned';
115
126
  const lines = [title];
@@ -120,12 +131,17 @@ function report({ host, plugins, incompatible, issues, settings }, heading) {
120
131
  ...incompatible.map((i) => ['incompatible', i.id + ' [' + i.event + ']', i.command]),
121
132
  ...issues.map((i) => [i.type, i.plugin, i.detail]),
122
133
  ...settings.map((s) => [s.type, s.path, s.to]),
134
+ ...brokenRoots(roots).map((r) => [r.state + ' root', rootName(r),
135
+ (r.state === 'missing' ? 'removed' : 'emptied') + ' while a session may still run from it; '
136
+ + r.currentVersion + ' is installed']),
123
137
  ];
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
- }
128
- if (lines.length === 1) lines.push(' healthy - every hook is Windows-compatible');
138
+ const info = roots.filter((r) => r.state === 'restored')
139
+ .map((r) => ['restored root', rootName(r), 'links to ' + r.currentVersion + ' for the sessions still running from it']);
140
+ const width = Math.max(0, ...[...rows, ...info].map(([type]) => type.length));
141
+ const line = ([type, subject, detail]) => ' ' + type.padEnd(width) + ' ' + subject + ' ' + detail;
142
+ lines.push(...rows.map(line));
143
+ if (!rows.length) lines.push(' healthy - every hook is Windows-compatible');
144
+ lines.push(...info.map(line));
129
145
  return lines.join('\n');
130
146
  }
131
147
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lilmgenius/win-hooks",
3
- "version": "1.15.0",
3
+ "version": "1.15.2",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
package/src/heal.mjs CHANGED
@@ -15,7 +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
+ import { recordRoot, restoreStaleRoots, staleRoots } from './stale.mjs';
19
19
  import { verify } from './verify.mjs';
20
20
 
21
21
  const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
@@ -85,8 +85,11 @@ export function heal(hostId, { changedOnly = false } = {}) {
85
85
  const host = HOSTS[hostId];
86
86
  const started = Date.now();
87
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) : [];
88
+ // guard watches, and the sessions it broke are waiting on this prompt. The
89
+ // root this heal runs from is noted first, so the heal that runs after the
90
+ // next upgrade knows to put it back (CASE-36).
91
+ recordRoot(host, ROOT);
92
+ const restored = restoreStaleRoots(host);
90
93
  if (changedOnly && unchanged(host)) {
91
94
  if (!restored.length) return null;
92
95
  record(host, { dur: (Date.now() - started) + 'ms', restored: restored.length });
@@ -123,6 +126,7 @@ export function inspect(hostId) {
123
126
  incompatible: findIncompatible(host, plugins),
124
127
  issues: verify(host, { templateCmd: TEMPLATE_CMD, plugins }).issues,
125
128
  settings: fixSettings(host.settingsFile),
129
+ roots: staleRoots(host),
126
130
  log: readLog(host),
127
131
  };
128
132
  }
package/src/hosts.mjs CHANGED
@@ -61,6 +61,10 @@ const claude = {
61
61
  // Files that change when the plugin set does. The per-prompt guard stats
62
62
  // these to rule out work without enumerating anything (CASE-26).
63
63
  registry: [join(HOME, '.claude/plugins/installed_plugins.json'), join(HOME, '.claude/settings.json')],
64
+ // One directory per installed plugin version, and what marks one installed
65
+ // (CASE-36).
66
+ cacheDir: join(HOME, '.claude/plugins/cache'),
67
+ manifestDir: '.claude-plugin',
64
68
  listPlugins: listClaudePlugins,
65
69
  // Claude replaces the command outright, so an already-patched hook is one
66
70
  // that already points at our dispatcher - which isIncompatible sees as a .cmd.
@@ -121,8 +125,10 @@ const codex = {
121
125
  // Codex records every install, removal, enable, and marketplace update in
122
126
  // config.toml, so one stat covers the whole plugin set.
123
127
  registry: [join(HOME, '.codex/config.toml')],
124
- // Where Codex keeps one directory per installed plugin version (CASE-35).
128
+ // Where Codex keeps one directory per installed plugin version, and what
129
+ // marks one installed (CASE-35, CASE-36).
125
130
  cacheDir: join(HOME, '.codex/plugins/cache'),
131
+ manifestDir: '.codex-plugin',
126
132
  listPlugins: listCodexPlugins,
127
133
  // A hook that already carries commandWindows is patched; leave the portable
128
134
  // command alone so it still runs natively on macOS and Linux.
package/src/rules.mjs CHANGED
@@ -2,7 +2,7 @@
2
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
- // is plumbing. Each rule maps to a CASE in AGENTS.md.
5
+ // is plumbing. Each rule maps to a CASE in docs/cases/.
6
6
 
7
7
  import { join } from 'node:path';
8
8
  import { readJson, resolvePython, writeJson } from './env.mjs';
package/src/stale.mjs CHANGED
@@ -1,25 +1,38 @@
1
- // Version directories a live Codex session still runs from (CASE-35).
1
+ // Version directories a live session still runs from (CASE-35, CASE-36).
2
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
3
+ // A host resolves the plugin root variable into a versioned cache path once,
4
+ // when a session loads its hooks, and never again. An upgrade run by any other
5
+ // process installs the next version beside it and deletes the old one, so
6
+ // every hook of every session already open fails from then on: Codex reports
7
+ // `hook exited with code 1` and shows nothing else (openai/codex#31383).
8
+ //
9
+ // Two shapes of the same gap. On Windows the deletion usually stops short of
9
10
  // 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
+ // it, and that leftover empty directory is the one place those sessions look
12
+ // (CASE-35). When nothing held it the directory is gone whole, and its name
13
+ // survives only where win-hooks wrote it down: every heal records the root it
14
+ // runs from, so the heal and patch that run next from the new version know
15
+ // which root to put back (CASE-36).
11
16
  //
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.
17
+ // The repair links each directory of the newest installed version into the
18
+ // old root with a junction, so the old sessions run the new code until they
19
+ // end. Nothing real is touched: a directory holding any real file or
20
+ // directory is either a whole older version or an install in progress, and
21
+ // the restored root gets no manifest directory, so it never reads as an
22
+ // installed version. Removing a junction does not follow it.
18
23
 
19
- import { existsSync, lstatSync, mkdirSync, readdirSync, readlinkSync, statSync, symlinkSync, unlinkSync } from 'node:fs';
20
- import { join, resolve } from 'node:path';
24
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, renameSync, statSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs';
25
+ import { dirname, join, relative, resolve } from 'node:path';
26
+ import { toPosix } from './env.mjs';
21
27
 
22
- const MANIFEST_DIR = '.codex-plugin';
28
+ // A record outlives the last heal from its root by 7 days. Every prompt of a
29
+ // session running from a root re-records it, so a record only lapses once its
30
+ // session has gone a week without a prompt from the real root (idle, or
31
+ // already running restored, since node resolves the junctions to the installed
32
+ // root) - longer than a session left open over a long weekend, the longest
33
+ // idle gap seen for an open session (CASE-35's ran overnight).
34
+ export const RECORD_TTL_MS = 7 * 24 * 60 * 60 * 1000;
35
+ const RECORDS = 'roots.json';
23
36
 
24
37
  const lstatOf = (path) => {
25
38
  try {
@@ -43,10 +56,10 @@ const isRealDir = (path) => {
43
56
  };
44
57
 
45
58
  // 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'));
59
+ const isInstalled = (root, manifest) => isRealDir(join(root, manifest)) && existsSync(join(root, manifest, 'plugin.json'));
47
60
 
48
61
  // Empty, or holding nothing but links: what an upgrade left of a version.
49
- const isEmptied = (root) => isRealDir(root) && !isInstalled(root)
62
+ const isEmptied = (root, manifest) => isRealDir(root) && !isInstalled(root, manifest)
50
63
  && childNames(root).every((name) => lstatOf(join(root, name))?.isSymbolicLink());
51
64
 
52
65
  const samePath = (a, b) => {
@@ -54,6 +67,14 @@ const samePath = (a, b) => {
54
67
  return norm(a) === norm(b);
55
68
  };
56
69
 
70
+ const linkedTo = (link, target) => {
71
+ try {
72
+ return lstatOf(link)?.isSymbolicLink() && samePath(readlinkSync(link), target);
73
+ } catch {
74
+ return false;
75
+ }
76
+ };
77
+
57
78
  // Point `link` at `target`; returns whether anything changed.
58
79
  function linkTo(link, target) {
59
80
  const st = lstatOf(link);
@@ -66,34 +87,117 @@ function linkTo(link, target) {
66
87
  return true;
67
88
  }
68
89
 
69
- // The version Codex installed last. Codex copies files with their source
90
+ // The version a host installed last. Both hosts copy files with their source
70
91
  // 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;
92
+ function newestInstalled(base, manifest) {
93
+ return childNames(base).filter((name) => !name.startsWith('.')).map((name) => join(base, name))
94
+ .filter((root) => isInstalled(root, manifest))
95
+ .map((root) => ({ root, born: statSync(root).birthtimeMs }))
96
+ .sort((a, b) => b.born - a.born)[0]?.root;
97
+ }
85
98
 
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
- }
99
+ const linkable = (current, manifest) =>
100
+ childNames(current).filter((name) => name !== manifest && isRealDir(join(current, name)));
101
+
102
+ // Where a root sits in a host's cache: <marketplace>/<plugin>/<version>.
103
+ function placeOf(host, root) {
104
+ if (!host.cacheDir) return null;
105
+ const parts = toPosix(relative(host.cacheDir, root)).split('/');
106
+ if (parts.length !== 3 || parts.some((p) => !p || p === '..')) return null;
107
+ const [marketplace, plugin, version] = parts;
108
+ return { marketplace, plugin, version, base: dirname(resolve(root)) };
109
+ }
110
+
111
+ // -- Records -----------------------------------------------------------
112
+
113
+ const recordsFile = (host) => join(host.stateDir, RECORDS);
114
+
115
+ // Unexpired records: root path -> ISO time of the last heal from it.
116
+ function readRecords(host, now) {
117
+ let data;
118
+ try {
119
+ data = JSON.parse(readFileSync(recordsFile(host), 'utf8'));
120
+ } catch {
121
+ return {};
122
+ }
123
+ return Object.fromEntries(Object.entries(data || {}).filter(([, at]) => {
124
+ const age = now - Date.parse(at);
125
+ return age >= 0 && age < RECORD_TTL_MS;
126
+ }));
127
+ }
128
+
129
+ // Note the root a heal of this host runs from, when it is a version in that
130
+ // host's cache - a checkout run by hand is nobody's session root. Written
131
+ // through a rename, so a concurrent heal never reads half a file; two heals
132
+ // racing can drop one entry, which that session's next prompt writes back.
133
+ export function recordRoot(host, root, now = Date.now()) {
134
+ if (!placeOf(host, root)) return;
135
+ try {
136
+ const records = readRecords(host, now);
137
+ records[toPosix(resolve(root))] = new Date(now).toISOString();
138
+ mkdirSync(host.stateDir, { recursive: true });
139
+ const tmp = recordsFile(host) + '.' + process.pid;
140
+ writeFileSync(tmp, JSON.stringify(records, null, 2) + '\n');
141
+ renameSync(tmp, recordsFile(host));
142
+ } catch { /* a missing record costs a restart, never a session */ }
143
+ }
144
+
145
+ // -- Finding and restoring ---------------------------------------------
146
+
147
+ // Every root a live session may still run from that does not hold a working
148
+ // copy, plus the ones already restored. `state` is `missing` (removed whole,
149
+ // known from a record), `emptied` (left on disk with no working links), or
150
+ // `restored`. Reads only: `status` reports from this.
151
+ export function staleRoots(host, now = Date.now()) {
152
+ const manifest = host.manifestDir;
153
+ if (!host.cacheDir || !manifest) return [];
154
+ const found = new Map();
155
+ const add = (root, current, state) => {
156
+ const place = placeOf(host, root);
157
+ const key = toPosix(resolve(root)).toLowerCase();
158
+ if (!place || found.has(key)) return;
159
+ found.set(key, { ...place, root, current, currentVersion: current.slice(place.base.length + 1), state });
160
+ };
161
+
162
+ for (const marketplace of childNames(host.cacheDir)) {
163
+ for (const plugin of childNames(join(host.cacheDir, marketplace))) {
164
+ const base = join(host.cacheDir, marketplace, plugin);
165
+ const current = newestInstalled(base, manifest);
166
+ if (!current) continue;
167
+ for (const name of childNames(base).filter((n) => !n.startsWith('.'))) {
168
+ const root = join(base, name);
169
+ if (!isEmptied(root, manifest)) continue;
170
+ const whole = linkable(current, manifest).every((n) => linkedTo(join(root, n), join(current, n)));
171
+ add(root, current, whole ? 'restored' : 'emptied');
94
172
  }
95
173
  }
96
174
  }
97
- return restored;
175
+
176
+ // Only a version of a plugin still installed is restored: an uninstall
177
+ // leaves nothing newer to run.
178
+ for (const root of Object.keys(readRecords(host, now))) {
179
+ const place = placeOf(host, root);
180
+ if (!place || lstatOf(root)) continue;
181
+ const current = newestInstalled(place.base, manifest);
182
+ if (current) add(resolve(root), current, 'missing');
183
+ }
184
+ return [...found.values()];
98
185
  }
99
186
 
187
+ // Restore every root staleRoots finds broken; returns one line per root.
188
+ export function restoreStaleRoots(host, now = Date.now()) {
189
+ const lines = [];
190
+ for (const s of staleRoots(host, now)) {
191
+ if (s.state === 'restored') continue;
192
+ try {
193
+ mkdirSync(s.root, { recursive: true });
194
+ for (const name of linkable(s.current, host.manifestDir)) linkTo(join(s.root, name), join(s.current, name));
195
+ } catch (e) {
196
+ lines.push('could not restore ' + s.plugin + '/' + s.version + ' - ' + e.message);
197
+ continue;
198
+ }
199
+ lines.push((s.state === 'missing' ? 'restored removed root ' : 'relinked ') + s.plugin + '/' + s.version
200
+ + ' to ' + s.currentVersion + ' for the sessions still running from it (' + s.marketplace + ')');
201
+ }
202
+ return lines;
203
+ }