@mainwave/cli 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +169 -42
  2. package/dist/adapters/claude-code.js +23 -4
  3. package/dist/adapters/codex-cli.js +1 -1
  4. package/dist/adapters/cursor.js +4 -2
  5. package/dist/adapters/index.js +3 -0
  6. package/dist/adapters/kiro.js +361 -0
  7. package/dist/core/apply.js +161 -46
  8. package/dist/core/behaviour-hooks.js +7 -7
  9. package/dist/core/codecs/kiro-hooks-json.js +76 -0
  10. package/dist/core/doctor.js +27 -9
  11. package/dist/core/effective-settings.js +10 -0
  12. package/dist/core/entry-script.js +90 -0
  13. package/dist/core/git-bash.js +40 -0
  14. package/dist/core/install-hooks.js +126 -43
  15. package/dist/core/interview.js +114 -16
  16. package/dist/core/markers.js +678 -140
  17. package/dist/core/remove.js +67 -0
  18. package/dist/core/settings.js +32 -6
  19. package/dist/core/skills.js +47 -1
  20. package/dist/core/status.js +2 -1
  21. package/dist/core/wizard.js +64 -3
  22. package/dist/main.js +28 -9
  23. package/hooks/cursor-otlp.mjs +4 -27
  24. package/hooks/github-pr-marker.mjs +35 -22
  25. package/hooks/glab-mr-marker.mjs +795 -0
  26. package/hooks/jira-ticket-marker.mjs +27 -15
  27. package/hooks/kiro-otlp.mjs +570 -0
  28. package/hooks/linear-ticket-marker.mjs +27 -15
  29. package/hooks/mainwave-hook-node.mjs +42 -0
  30. package/hooks/mainwave-hook.mjs +301 -0
  31. package/hooks/marker-core.mjs +368 -41
  32. package/hooks/matchers.json +82 -6
  33. package/hooks/plan-snapshot.mjs +529 -0
  34. package/hooks/stop-failure.mjs +43 -0
  35. package/hooks/vocabulary.d.mts +49 -0
  36. package/hooks/vocabulary.mjs +188 -0
  37. package/package.json +5 -5
  38. package/skills/mainwave-instrument/SKILL.md +21 -7
  39. package/skills/mainwave-instrument/reference/api.md +29 -10
  40. package/skills/mainwave-instrument/reference/frameworks.md +3 -3
  41. package/skills/mainwave-instrument/reference/troubleshooting.md +12 -5
  42. package/skills/mainwave-setup/SKILL.md +47 -12
@@ -1,25 +1,54 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { existsSync, promises as fs } from 'node:fs';
3
3
  import { homedir } from 'node:os';
4
- import { basename, dirname, join, resolve } from 'node:path';
4
+ import { basename, dirname, join, resolve, win32 } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { dropInNames } from './effective-settings.js';
7
+ import { GIT_BASH_FIX, GIT_BASH_MISSING_REASON } from './git-bash.js';
8
+ import { entryCommand, entryVersionId, HOOK_DISPATCHER_SCRIPT, HOOK_ENTRY_SCRIPT, HOOK_NODE_ENTRY_SCRIPT, nodeEntryCommand, ORG_DELIVERED_MARK, parseEntryCommand, renderHookEntry, } from './entry-script.js';
7
9
  import { isManagedLayer, isPolicyKey } from './layer-policy.js';
8
10
  export const MANAGED_BY = '--managed-by @mainwave/cli';
9
11
  export const PAYLOAD_CLI_SPEC = 'latest';
10
12
  const OWNED_CLI_MARKERS = [MANAGED_BY, '.mainwave/hooks', '.mainwave\\hooks'];
13
+ const BOOTSTRAP_RE = /@mainwave\/cli@\S+ install-hooks\b/;
11
14
  const OWNED_INTERNAL_MARKERS = [
12
15
  'clients/cli/hooks',
13
16
  'claude-managed-settings/hooks',
14
17
  'mainwave-hooks',
15
18
  ];
16
19
  export const commandOwnership = (command) => {
17
- if (OWNED_CLI_MARKERS.some((m) => command.includes(m)))
20
+ if (OWNED_CLI_MARKERS.some((m) => command.includes(m)) || BOOTSTRAP_RE.test(command)) {
18
21
  return 'cli';
22
+ }
19
23
  if (OWNED_INTERNAL_MARKERS.some((m) => command.includes(m)))
20
24
  return 'internal';
21
25
  return null;
22
26
  };
27
+ export const commandGeneration = (command) => command.includes(HOOK_ENTRY_SCRIPT) || command.includes(HOOK_NODE_ENTRY_SCRIPT)
28
+ ? 'entry'
29
+ : BOOTSTRAP_RE.test(command)
30
+ ? 'bootstrap'
31
+ : 'legacy';
32
+ export const INSTALLED_HOOK_EVENTS = [
33
+ 'SessionStart',
34
+ 'UserPromptSubmit',
35
+ 'PostToolUse',
36
+ 'StopFailure',
37
+ ];
38
+ export const MARKER_HOOK_EVENTS = INSTALLED_HOOK_EVENTS;
39
+ const ENTRY_EVENTS = [
40
+ 'UserPromptSubmit',
41
+ 'PostToolUse',
42
+ 'StopFailure',
43
+ ];
44
+ const MATCHER_EVENTS = new Set(['PostToolUse', 'SessionStart']);
45
+ const TOOL_EVENTS = new Set(['PostToolUse']);
46
+ export const NO_MATCHER = '(no matcher)';
47
+ export const DEFAULT_MARKER_TOOL = 'claude-code';
48
+ export const matchersForTool = (matchers, tool = DEFAULT_MARKER_TOOL) => matchers.filter((m) => m.hosts.includes(tool));
49
+ export const isPlanSnapshot = (m) => m.features.includes('plan-snapshot') || m.features.includes('stop-failure');
50
+ export const selectHookMatchers = (matchers, on) => (on.markers ? [...matchers] : []);
51
+ export const groupEvent = (group) => group.event ?? 'PostToolUse';
23
52
  const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
24
53
  export const packagedHooksDir = () => fileURLToPath(new URL('../../hooks/', import.meta.url));
25
54
  export const installedHooksDir = () => join(homedir(), '.mainwave', 'hooks');
@@ -36,21 +65,84 @@ export const shellHome = (plat = process.platform, env = process.env, dirExists
36
65
  };
37
66
  export const installHooksCommand = (version, { quiet = true } = {}) => `cd "$HOME" && npx -y --registry=https://registry.npmjs.org ` +
38
67
  `@mainwave/cli@${version} install-hooks${quiet ? ' --quiet' : ''}`;
68
+ export const bootstrapCommand = (version) => `{ ${installHooksCommand(version)}; } >/dev/null 2>&1; exit 0`;
69
+ export const BOOTSTRAP_MATCHER = 'startup|resume|fork';
70
+ export const BOOTSTRAP_KEY = 'SessionStart:bootstrap';
71
+ export const bootstrapGroup = () => ({
72
+ event: 'SessionStart',
73
+ matcher: BOOTSTRAP_MATCHER,
74
+ hooks: [{ type: 'command', command: bootstrapCommand(PAYLOAD_CLI_SPEC), async: true }],
75
+ });
76
+ const SAFE_ROUTE = /^[a-z][a-z0-9-]*$/;
39
77
  export const readPackagedMatchers = async (dir = packagedHooksDir()) => {
40
78
  const raw = JSON.parse(await fs.readFile(join(dir, 'matchers.json'), 'utf8'));
41
79
  if (!Array.isArray(raw))
42
80
  throw new Error('matchers.json: expected a top-level array');
43
- return raw.map((e) => {
44
- if (!isPlainObject(e) || typeof e.hook !== 'string' || typeof e.matcher !== 'string') {
45
- throw new Error('matchers.json: every entry needs string `hook` and `matcher` fields');
81
+ const seen = new Set();
82
+ return raw.map((e, i) => {
83
+ if (!isPlainObject(e))
84
+ throw new Error(`matchers.json: entry ${i} is not an object`);
85
+ const name = `entry ${i} (${String(e.event)}${e.route ? ` ${String(e.route)}` : ''})`;
86
+ for (const legacy of ['hook', 'events']) {
87
+ if (e[legacy] !== undefined) {
88
+ throw new Error(`matchers.json: ${name} uses \`${legacy}\`; name \`event\` and \`features\``);
89
+ }
90
+ }
91
+ if (!ENTRY_EVENTS.includes(e.event)) {
92
+ throw new Error(`matchers.json: ${name} has unsupported event (one of ${ENTRY_EVENTS.join(' / ')})`);
93
+ }
94
+ const event = e.event;
95
+ if (e.route !== undefined && (typeof e.route !== 'string' || !SAFE_ROUTE.test(e.route))) {
96
+ throw new Error(`matchers.json: ${name} \`route\` must be a lower-case word`);
97
+ }
98
+ if (e.matcher !== undefined && (typeof e.matcher !== 'string' || e.matcher === '')) {
99
+ throw new Error(`matchers.json: ${name} \`matcher\` must be a non-empty string`);
100
+ }
101
+ if (e.matcher !== undefined && !MATCHER_EVENTS.has(event)) {
102
+ throw new Error(`matchers.json: ${name} — ${event} takes no \`matcher\``);
103
+ }
104
+ if (event === 'PostToolUse' && e.matcher === undefined) {
105
+ throw new Error(`matchers.json: ${name} needs a \`matcher\``);
106
+ }
107
+ if (e.if !== undefined && (typeof e.if !== 'string' || !TOOL_EVENTS.has(event))) {
108
+ throw new Error(`matchers.json: ${name} — \`if\` is a string, on tool events only`);
46
109
  }
47
- return { hook: e.hook, matcher: e.matcher };
110
+ const strings = (key) => {
111
+ const v = e[key];
112
+ if (!Array.isArray(v) || v.length === 0 || !v.every((s) => typeof s === 'string' && s)) {
113
+ throw new Error(`matchers.json: ${name} \`${key}\` must be a non-empty array of strings`);
114
+ }
115
+ return v;
116
+ };
117
+ const features = strings('features');
118
+ const hosts = strings('hosts');
119
+ const dataClasses = strings('dataClasses');
120
+ if (e.optOut !== 'markers') {
121
+ throw new Error(`matchers.json: ${name} \`optOut\` must be "markers"`);
122
+ }
123
+ for (const host of hosts) {
124
+ const key = `${host} ${event} ${e.route ?? ''}`;
125
+ if (seen.has(key))
126
+ throw new Error(`matchers.json: ${name} repeats a route for ${host}`);
127
+ seen.add(key);
128
+ }
129
+ return {
130
+ event,
131
+ ...(typeof e.route === 'string' ? { route: e.route } : {}),
132
+ ...(typeof e.matcher === 'string' ? { matcher: e.matcher } : {}),
133
+ ...(typeof e.if === 'string' ? { if: e.if } : {}),
134
+ features,
135
+ optOut: e.optOut,
136
+ hosts,
137
+ dataClasses,
138
+ };
48
139
  });
49
140
  };
141
+ const SHARED_HOOK_MODULES = ['marker-core.mjs', 'vocabulary.mjs', HOOK_DISPATCHER_SCRIPT];
142
+ export const featureModule = (feature) => `${feature}.mjs`;
50
143
  export const hookScriptFiles = (matchers) => [
51
- 'marker-core.mjs',
52
- 'vocabulary.mjs',
53
- ...matchers.map((m) => m.hook),
144
+ ...SHARED_HOOK_MODULES,
145
+ ...new Set(matchers.flatMap((m) => m.features.map(featureModule))),
54
146
  ];
55
147
  export const copyHookScripts = async (files, srcDir = packagedHooksDir(), destDir = installedHooksDir()) => {
56
148
  await fs.mkdir(destDir, { recursive: true });
@@ -67,6 +159,20 @@ export const MANAGED_VERSIONS_DIR = 'versions';
67
159
  export const MANAGED_ENTRY_SCRIPT = 'managed-entry.mjs';
68
160
  const MANAGED_ENTRY_MARK = 'mainwave managed hook entry';
69
161
  const RETIRED_GRACE_MS = 10 * 60 * 1000;
162
+ export const LEGACY_ENTRY_NAMES = [
163
+ 'linear-ticket-marker.mjs',
164
+ 'github-pr-marker.mjs',
165
+ 'jira-ticket-marker.mjs',
166
+ ];
167
+ const NEVER_RELEASED_ENTRY_NAMES = ['glab-mr-marker.mjs', 'claude-plan-snapshot.mjs'];
168
+ const LEGACY_SCRIPT_ROUTES = {
169
+ 'linear-ticket-marker.mjs': { event: 'PostToolUse', route: 'linear' },
170
+ 'jira-ticket-marker.mjs': { event: 'PostToolUse', route: 'jira' },
171
+ 'github-pr-marker.mjs': { event: 'PostToolUse', route: 'gh' },
172
+ 'glab-mr-marker.mjs': { event: 'PostToolUse', route: 'glab' },
173
+ 'claude-plan-snapshot.mjs': { event: 'UserPromptSubmit' },
174
+ };
175
+ export const legacyScriptReleased = (name) => LEGACY_ENTRY_NAMES.includes(name);
70
176
  const VERSION_DIR_RE = /^[A-Za-z0-9][A-Za-z0-9._+-]*$/;
71
177
  const versionDirName = (version, files, bodies) => {
72
178
  const hash = createHash('sha256');
@@ -96,6 +202,10 @@ export const readManagedPointer = async (destDir) => {
96
202
  return undefined;
97
203
  }
98
204
  };
205
+ export const readEntryVersion = async (destDir) => {
206
+ const text = await fs.readFile(join(destDir, HOOK_ENTRY_SCRIPT), 'utf8').catch(() => null);
207
+ return text === null ? undefined : entryVersionId(text);
208
+ };
99
209
  export const stageManagedVersion = async (files, srcDir, destDir, version) => {
100
210
  const bodies = await Promise.all(files.map((f) => fs.readFile(join(srcDir, f))));
101
211
  const id = versionDirName(version, files, bodies);
@@ -104,7 +214,7 @@ export const stageManagedVersion = async (files, srcDir, destDir, version) => {
104
214
  const final = join(versionsDir, id);
105
215
  const staged = { id, version, files, bodies };
106
216
  if (await holdsFiles(final, files, bodies)) {
107
- if ((await readManagedPointer(destDir)) !== id) {
217
+ if ((await readManagedPointer(destDir)) !== id || (await readEntryVersion(destDir)) !== id) {
108
218
  const now = new Date();
109
219
  await fs.utimes(final, now, now).catch(() => undefined);
110
220
  }
@@ -151,18 +261,49 @@ const moveAside = async (versionsDir, id) => {
151
261
  };
152
262
  const isMissing = (err) => err?.code === 'ENOENT';
153
263
  const stagedIntact = async (destDir, staged) => holdsFiles(join(destDir, MANAGED_VERSIONS_DIR, staged.id), staged.files, staged.bodies);
264
+ const retire = async (destDir, id, keep) => {
265
+ if (id === undefined || id === keep)
266
+ return;
267
+ const now = new Date();
268
+ await fs.utimes(join(destDir, MANAGED_VERSIONS_DIR, id), now, now).catch(() => undefined);
269
+ };
270
+ export const writeHookEntry = async (staged, destDir, routes, nodePath = process.execPath) => {
271
+ const body = renderHookEntry({
272
+ versionId: staged.id,
273
+ version: staged.version,
274
+ nodePath,
275
+ routes: routes.flatMap((m) => m.hosts.map((host) => ({
276
+ host,
277
+ event: m.event,
278
+ ...(m.route !== undefined ? { route: m.route } : {}),
279
+ optOut: m.optOut,
280
+ }))),
281
+ });
282
+ const path = join(destDir, HOOK_ENTRY_SCRIPT);
283
+ const current = await fs.readFile(path, 'utf8').catch(() => null);
284
+ if (current === body)
285
+ return false;
286
+ const previous = current === null ? undefined : entryVersionId(current);
287
+ await writeAtomic(path, body);
288
+ await retire(destDir, previous, staged.id);
289
+ return true;
290
+ };
291
+ export const writeNodeEntry = async (srcDir, destDir) => {
292
+ const body = await fs.readFile(join(srcDir, HOOK_NODE_ENTRY_SCRIPT));
293
+ const path = join(destDir, HOOK_NODE_ENTRY_SCRIPT);
294
+ const current = await fs.readFile(path).catch(() => null);
295
+ if (current !== null && current.equals(body))
296
+ return false;
297
+ await writeAtomic(path, body);
298
+ return true;
299
+ };
154
300
  export const commitManagedVersion = async (staged, hookNames, srcDir, destDir) => {
155
301
  const updated = [];
156
302
  const previous = await readManagedPointer(destDir);
157
303
  if (previous !== staged.id) {
158
304
  await writeAtomic(join(destDir, MANAGED_POINTER), `${JSON.stringify({ dir: staged.id, version: staged.version })}\n`);
159
305
  updated.push(MANAGED_POINTER);
160
- if (previous !== undefined) {
161
- const now = new Date();
162
- await fs
163
- .utimes(join(destDir, MANAGED_VERSIONS_DIR, previous), now, now)
164
- .catch(() => undefined);
165
- }
306
+ await retire(destDir, previous, staged.id);
166
307
  }
167
308
  const entry = await fs.readFile(join(srcDir, MANAGED_ENTRY_SCRIPT));
168
309
  for (const name of hookNames) {
@@ -174,35 +315,52 @@ export const commitManagedVersion = async (staged, hookNames, srcDir, destDir) =
174
315
  }
175
316
  return updated;
176
317
  };
318
+ const removeUnreleasedEntryPoints = async (destDir) => {
319
+ const removed = [];
320
+ for (const name of NEVER_RELEASED_ENTRY_NAMES) {
321
+ const body = await fs.readFile(join(destDir, name), 'utf8').catch(() => null);
322
+ if (body === null || !body.includes(MANAGED_ENTRY_MARK))
323
+ continue;
324
+ await fs.rm(join(destDir, name), { force: true }).catch(() => undefined);
325
+ removed.push(name);
326
+ }
327
+ return removed;
328
+ };
177
329
  const pruneManagedVersions = async (destDir, keep) => {
178
330
  const versionsDir = join(destDir, MANAGED_VERSIONS_DIR);
179
- const current = await readManagedPointer(destDir);
331
+ const named = async () => new Set([await readManagedPointer(destDir), await readEntryVersion(destDir)]);
332
+ const current = await named();
180
333
  const entries = await fs.readdir(versionsDir).catch(() => []);
181
334
  const now = Date.now();
182
335
  for (const name of entries) {
183
- if (name === current || name === keep)
336
+ if (current.has(name) || name === keep)
184
337
  continue;
185
338
  const path = join(versionsDir, name);
186
339
  const stat = await fs.stat(path).catch(() => null);
187
340
  if (stat === null || now - stat.mtimeMs < RETIRED_GRACE_MS)
188
341
  continue;
189
- if ((await readManagedPointer(destDir)) === name)
342
+ if ((await named()).has(name))
190
343
  continue;
191
344
  await fs.rm(path, { recursive: true, force: true }).catch(() => undefined);
192
345
  }
193
346
  };
194
- export const syncManagedHooks = async (matchers, srcDir, destDir, version) => {
347
+ export const syncManagedHooks = async (matchers, srcDir, destDir, version, nodePath = process.execPath) => {
195
348
  const files = hookScriptFiles(matchers);
196
- const hookNames = matchers.map((m) => m.hook);
349
+ const commit = async (staged) => [
350
+ ...((await writeHookEntry(staged, destDir, matchers, nodePath)) ? [HOOK_ENTRY_SCRIPT] : []),
351
+ ...((await writeNodeEntry(srcDir, destDir)) ? [HOOK_NODE_ENTRY_SCRIPT] : []),
352
+ ...(await commitManagedVersion(staged, LEGACY_ENTRY_NAMES, srcDir, destDir)),
353
+ ];
197
354
  const staged = await stageManagedVersion(files, srcDir, destDir, version);
198
- const updated = await commitManagedVersion(staged, hookNames, srcDir, destDir);
355
+ const updated = await commit(staged);
199
356
  if (!(await stagedIntact(destDir, staged))) {
200
357
  const again = await stageManagedVersion(files, srcDir, destDir, version);
201
- updated.push(...(await commitManagedVersion(again, hookNames, srcDir, destDir)));
358
+ updated.push(...(await commit(again)));
202
359
  if (!(await stagedIntact(destDir, again))) {
203
360
  throw new Error(`could not install a complete set of hook scripts in ${destDir}`);
204
361
  }
205
362
  }
363
+ updated.push(...(await removeUnreleasedEntryPoints(destDir)));
206
364
  await pruneManagedVersions(destDir, staged.id);
207
365
  return [
208
366
  ...new Set([
@@ -223,33 +381,92 @@ export const resolveManagedScript = async (script) => {
223
381
  const target = join(dirname(script), MANAGED_VERSIONS_DIR, dir, basename(script));
224
382
  return existsSync(target) ? target : undefined;
225
383
  };
226
- export const buildHookCommand = (scriptPath, version, plat = process.platform, runtimeTool) => {
384
+ export const hooksRootDir = (managedDir = managedHooksDir()) => dirname(managedDir);
385
+ export const optOutFlagPath = (host, optOut, root = hooksRootDir()) => join(root, 'off', host, optOut);
386
+ export const writeOptOutFlags = async (host, on, root = hooksRootDir()) => {
387
+ for (const [optOut, enabled] of Object.entries(on)) {
388
+ if (enabled === undefined)
389
+ continue;
390
+ const path = optOutFlagPath(host, optOut, root);
391
+ if (enabled) {
392
+ await fs.rm(path, { force: true });
393
+ }
394
+ else {
395
+ await fs.mkdir(dirname(path), { recursive: true });
396
+ await fs.writeFile(path, '', { mode: 0o644 });
397
+ }
398
+ }
399
+ };
400
+ export const managedDeliversEntry = (scans) => activeManagedScans(scans).some((s) => s.groups.some((g) => g.ownership === 'cli' && commandGeneration(g.command) === 'entry'));
401
+ export const syncOrgDelivered = async (delivers, configDir, destDir = managedHooksDir()) => {
402
+ const path = join(destDir, ORG_DELIVERED_MARK);
403
+ const text = await fs.readFile(path, 'utf8').catch(() => undefined);
404
+ const lines = (text ?? '').split('\n').filter((l) => l !== '');
405
+ const next = delivers
406
+ ? lines.includes(configDir)
407
+ ? lines
408
+ : [...lines, configDir]
409
+ : lines.filter((l) => l !== configDir);
410
+ if (next.length === 0) {
411
+ await fs.rm(path, { force: true });
412
+ return false;
413
+ }
414
+ if (text === undefined || next !== lines) {
415
+ await fs.mkdir(destDir, { recursive: true });
416
+ await writeAtomic(path, `${next.join('\n')}\n`);
417
+ }
418
+ return true;
419
+ };
420
+ export const buildScriptHookCommand = (scriptPath, version, plat = process.platform, runtimeTool) => {
227
421
  const toolArg = runtimeTool ? ` --tool ${runtimeTool}` : '';
228
422
  return plat === 'win32'
229
423
  ? `node "${scriptPath}" ${MANAGED_BY}@${version}${toolArg}`
230
424
  : `f="${scriptPath}"; [ -f "$f" ] && exec node "$f" ${MANAGED_BY}@${version}${toolArg}; exit 0`;
231
425
  };
426
+ export const buildHookCommand = (host, event, route, plat = process.platform, managedDir = managedHooksDir()) => host === 'codex' && plat === 'win32'
427
+ ? nodeEntryCommand(win32.join(managedDir, HOOK_NODE_ENTRY_SCRIPT), host, event, route)
428
+ : entryCommand(host, event, route);
232
429
  export const parseManagedByVersion = (command) => {
233
430
  const re = new RegExp(`${MANAGED_BY.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')}@([^\\s;]+)`);
234
431
  return re.exec(command)?.[1];
235
432
  };
236
433
  export const scriptPathFromCommand = (command) => {
237
- const raw = /"([^"]+\.mjs)"/.exec(command)?.[1];
434
+ const raw = /"([^"]+\.(?:mjs|sh))"/.exec(command)?.[1];
238
435
  if (raw === undefined)
239
436
  return raw;
240
437
  const m = /^(?:\$\{HOME\}|\$HOME)(?=\/)/.exec(raw);
241
438
  return m ? shellHome() + raw.slice(m[0].length) : raw;
242
439
  };
243
- export const buildHookGroups = (matchers, version, hookDir = installedHooksDir(), plat = process.platform, runtimeTool) => matchers.map((m) => ({
244
- matcher: m.matcher,
245
- hooks: [
246
- {
247
- type: 'command',
248
- command: buildHookCommand(join(hookDir, m.hook), version, plat, runtimeTool),
249
- timeout: 5,
250
- },
251
- ],
252
- }));
440
+ export const hookShape = (host) => host === 'codex' ? { timeout: 5 } : { async: true };
441
+ const groupFor = (m, host) => {
442
+ const hook = {
443
+ type: 'command',
444
+ command: buildHookCommand(host, m.event, m.route),
445
+ ...hookShape(host),
446
+ };
447
+ if (m.if !== undefined && host !== 'codex')
448
+ hook.if = m.if;
449
+ return {
450
+ ...(m.event === 'PostToolUse' ? {} : { event: m.event }),
451
+ ...(m.matcher !== undefined ? { matcher: m.matcher } : {}),
452
+ hooks: [hook],
453
+ };
454
+ };
455
+ export const buildHookGroups = (matchers, host = DEFAULT_MARKER_TOOL) => matchers.map((m) => groupFor(m, host));
456
+ export const hostRunsBootstrap = (host) => host === DEFAULT_MARKER_TOOL;
457
+ export const userHookGroups = (hosted, on, delivered, host = DEFAULT_MARKER_TOOL) => {
458
+ const selected = selectHookMatchers(hosted, on);
459
+ const groups = [
460
+ ...(hostRunsBootstrap(host) && selected.length > 0 ? [bootstrapGroup()] : []),
461
+ ...buildHookGroups(selected, host),
462
+ ];
463
+ return groups.filter((g) => {
464
+ const command = g.hooks[0]?.command ?? '';
465
+ return isBootstrapCommand(command) || !isDelivered(delivered, groupEvent(g), command);
466
+ });
467
+ };
468
+ export const isBootstrapCommand = (command) => commandGeneration(command) === 'bootstrap';
469
+ const writtenGroup = ({ event: _event, ...group }) => group;
253
470
  const groupOwnership = (group) => {
254
471
  if (!isPlainObject(group) || !Array.isArray(group.hooks))
255
472
  return null;
@@ -262,28 +479,44 @@ const groupOwnership = (group) => {
262
479
  }
263
480
  return null;
264
481
  };
265
- const ownedGroupInfo = (group, ownership) => {
482
+ const ownedGroupInfo = (group, ownership, event) => {
266
483
  const hooks = Array.isArray(group.hooks) ? group.hooks : [];
267
484
  const first = hooks.find((h) => isPlainObject(h) && typeof h.command === 'string');
268
485
  return {
269
- matcher: typeof group.matcher === 'string' ? group.matcher : '(no matcher)',
486
+ event,
487
+ matcher: typeof group.matcher === 'string' ? group.matcher : NO_MATCHER,
270
488
  command: first?.command ?? '',
489
+ timeout: typeof first?.timeout === 'number' ? first.timeout : undefined,
490
+ async: first?.async === true ? true : undefined,
491
+ if: typeof first?.if === 'string' ? first.if : undefined,
271
492
  ownership,
272
493
  };
273
494
  };
274
495
  export const ownedGroupsInDoc = (doc) => {
275
- if (!isPlainObject(doc) || !isPlainObject(doc.hooks) || !Array.isArray(doc.hooks.PostToolUse)) {
496
+ if (!isPlainObject(doc) || !isPlainObject(doc.hooks))
276
497
  return [];
277
- }
278
498
  const out = [];
279
- for (const g of doc.hooks.PostToolUse) {
280
- const o = groupOwnership(g);
281
- if (o !== null && isPlainObject(g))
282
- out.push(ownedGroupInfo(g, o));
499
+ for (const event of MARKER_HOOK_EVENTS) {
500
+ const list = doc.hooks[event];
501
+ if (!Array.isArray(list))
502
+ continue;
503
+ for (const g of list) {
504
+ const o = groupOwnership(g);
505
+ if (o !== null && isPlainObject(g))
506
+ out.push(ownedGroupInfo(g, o, event));
507
+ }
283
508
  }
284
509
  return out;
285
510
  };
286
- const sameGroup = (before, after) => before.matcher === after.matcher && before.command === (after.hooks[0]?.command ?? '');
511
+ export const malformedEventMessage = (event) => `\`hooks.${event}\` in the settings file is not an array, so Mainwave left it untouched and installed no ${event} hook there. ` +
512
+ 'Fix or remove that value, then re-run setup.';
513
+ const effectiveMatcher = (matcher) => matcher === undefined || matcher === '' || matcher === '*' ? NO_MATCHER : matcher;
514
+ const sameGroup = (before, after) => before.event === groupEvent(after) &&
515
+ effectiveMatcher(before.matcher) === effectiveMatcher(after.matcher) &&
516
+ before.command === (after.hooks[0]?.command ?? '') &&
517
+ before.timeout === after.hooks[0]?.timeout &&
518
+ (before.async === true) === (after.hooks[0]?.async === true) &&
519
+ before.if === after.hooks[0]?.if;
287
520
  export const planMarkers = (doc, groups, remove = () => true) => {
288
521
  if (!isPlainObject(doc))
289
522
  throw new Error('expected the settings document to be a JSON object');
@@ -292,38 +525,59 @@ export const planMarkers = (doc, groups, remove = () => true) => {
292
525
  throw new Error('settings `hooks` is not an object — refusing to modify it');
293
526
  }
294
527
  const hooks = hooksVal ? { ...hooksVal } : {};
295
- const postVal = hooks.PostToolUse;
296
- if (postVal !== undefined && !Array.isArray(postVal)) {
297
- throw new Error('settings `hooks.PostToolUse` is not an array — refusing to modify it');
528
+ const written = new Set(groups.map(groupEvent));
529
+ const skipped = new Set();
530
+ const skippedEvents = [];
531
+ for (const event of MARKER_HOOK_EVENTS) {
532
+ if (hooks[event] === undefined || Array.isArray(hooks[event]))
533
+ continue;
534
+ skipped.add(event);
535
+ if (written.has(event))
536
+ skippedEvents.push({ event, message: malformedEventMessage(event) });
298
537
  }
299
- const post = postVal ? [...postVal] : [];
538
+ const writable = groups.filter((g) => !skipped.has(groupEvent(g)));
300
539
  const before = [];
301
- const kept = post.filter((g) => {
302
- const o = groupOwnership(g);
303
- if (o === null || !isPlainObject(g))
304
- return true;
305
- const info = ownedGroupInfo(g, o);
306
- if (!remove(o, info))
307
- return true;
308
- before.push(info);
309
- return false;
310
- });
311
- const nextPost = [...kept, ...groups];
312
- const next = { ...doc };
313
- if (nextPost.length > 0) {
314
- next.hooks = { ...hooks, PostToolUse: nextPost };
315
- }
316
- else {
317
- const { PostToolUse: _dropped, ...rest } = hooks;
318
- if (Object.keys(rest).length > 0)
319
- next.hooks = rest;
320
- else
321
- delete next.hooks;
540
+ let pruned = false;
541
+ for (const event of MARKER_HOOK_EVENTS) {
542
+ if (skipped.has(event))
543
+ continue;
544
+ const current = hooks[event];
545
+ let removedHere = 0;
546
+ const kept = (current ?? []).filter((g) => {
547
+ const o = groupOwnership(g);
548
+ if (o === null || !isPlainObject(g))
549
+ return true;
550
+ const info = ownedGroupInfo(g, o, event);
551
+ if (!remove(o, info))
552
+ return true;
553
+ before.push(info);
554
+ removedHere++;
555
+ return false;
556
+ });
557
+ const next = [...kept, ...writable.filter((g) => groupEvent(g) === event).map(writtenGroup)];
558
+ if (next.length > 0)
559
+ hooks[event] = next;
560
+ else if (removedHere > 0) {
561
+ delete hooks[event];
562
+ pruned = true;
563
+ }
322
564
  }
323
- const unchanged = before.filter((b) => groups.some((a) => sameGroup(b, a))).length;
324
- const removed = before.filter((b) => !groups.some((a) => sameGroup(b, a)));
325
- const added = groups.filter((a) => !before.some((b) => sameGroup(b, a)));
326
- return { next, removed, added, unchanged, changed: removed.length > 0 || added.length > 0 };
565
+ const next = { ...doc };
566
+ if (Object.keys(hooks).length > 0 || (hooksVal !== undefined && !pruned))
567
+ next.hooks = hooks;
568
+ else
569
+ delete next.hooks;
570
+ const unchanged = before.filter((b) => writable.some((a) => sameGroup(b, a))).length;
571
+ const removed = before.filter((b) => !writable.some((a) => sameGroup(b, a)));
572
+ const added = writable.filter((a) => !before.some((b) => sameGroup(b, a)));
573
+ return {
574
+ next,
575
+ removed,
576
+ added,
577
+ unchanged,
578
+ changed: removed.length > 0 || added.length > 0,
579
+ skipped: skippedEvents,
580
+ };
327
581
  };
328
582
  export const prepareMarkersFile = async (path, codec, groups, mode = 0o600, remove) => {
329
583
  let body;
@@ -346,31 +600,61 @@ export const prepareMarkersFile = async (path, codec, groups, mode = 0o600, remo
346
600
  return { update, plan };
347
601
  };
348
602
  const shortCommand = (command) => {
603
+ const entry = parseEntryCommand(command);
604
+ if (entry) {
605
+ const file = command.includes(HOOK_NODE_ENTRY_SCRIPT)
606
+ ? HOOK_NODE_ENTRY_SCRIPT
607
+ : HOOK_ENTRY_SCRIPT;
608
+ return `${file} ${entry.host} ${entry.event}${entry.route ? ` ${entry.route}` : ''}`;
609
+ }
610
+ if (commandGeneration(command) === 'bootstrap')
611
+ return 'install-hooks (session start)';
349
612
  const script = scriptPathFromCommand(command);
350
613
  const version = parseManagedByVersion(command);
351
614
  if (script)
352
615
  return `${basename(script)}${version ? ` (@mainwave/cli@${version})` : ''}`;
353
616
  return command.length > 60 ? `${command.slice(0, 57)}...` : command;
354
617
  };
618
+ const hookSlot = (event, matcher) => matcher === undefined ? `hooks.${event}` : `hooks.${event}[${matcher}]`;
355
619
  export const describeMarkersPlan = (plan) => {
356
620
  const lines = [];
357
621
  for (const g of plan.added) {
358
622
  const cmd = g.hooks[0]?.command ?? '';
359
- lines.push(`+ hooks.PostToolUse[${g.matcher}] → ${shortCommand(cmd)}`);
623
+ const filter = g.hooks[0]?.if ? ` if ${g.hooks[0].if}` : '';
624
+ lines.push(`+ ${hookSlot(groupEvent(g), g.matcher)}${filter} → ${shortCommand(cmd)}`);
360
625
  }
361
626
  for (const g of plan.removed) {
362
627
  const label = g.ownership === 'internal' ? ' [internal installer]' : '';
363
- lines.push(`- hooks.PostToolUse[${g.matcher}] → ${shortCommand(g.command)}${label}`);
628
+ const matcher = effectiveMatcher(g.matcher) === NO_MATCHER ? undefined : g.matcher;
629
+ lines.push(`- ${hookSlot(g.event, matcher)} → ${shortCommand(g.command)}${label}`);
364
630
  }
365
631
  if (plan.unchanged > 0)
366
632
  lines.push(` (${plan.unchanged} hook groups unchanged)`);
367
633
  return lines;
368
634
  };
369
- export const markerLogFiles = () => [
370
- { label: 'Linear tickets', path: join(homedir(), '.mainwave-ticket-marker.log') },
371
- { label: 'Jira tickets', path: join(homedir(), '.mainwave-jira-ticket-marker.log') },
372
- { label: 'PRs', path: join(homedir(), '.mainwave-pr-marker.log') },
635
+ export const hookLogDir = (home = homedir()) => join(home, '.mainwave', 'logs');
636
+ const logFile = (home, label, name, legacyName) => ({
637
+ label,
638
+ path: join(hookLogDir(home), name),
639
+ legacyPath: join(home, legacyName),
640
+ });
641
+ export const markerLogFiles = (home = homedir()) => [
642
+ logFile(home, 'Linear tickets', 'ticket-marker.log', '.mainwave-ticket-marker.log'),
643
+ logFile(home, 'Jira tickets', 'jira-ticket-marker.log', '.mainwave-jira-ticket-marker.log'),
644
+ logFile(home, 'PRs', 'pr-marker.log', '.mainwave-pr-marker.log'),
645
+ logFile(home, 'GitLab MRs', 'glab-mr-marker.log', '.mainwave-glab-mr-marker.log'),
646
+ {
647
+ ...logFile(home, 'Claude plan snapshots', 'plan-snapshot.log', '.mainwave-plan-snapshot.log.ok'),
648
+ activityPath: join(hookLogDir(home), 'plan-snapshot.log.ok'),
649
+ },
650
+ logFile(home, 'Claude turn errors', 'claude-events.log', '.mainwave-claude-events.log'),
373
651
  ];
652
+ export const lastLogActivity = async (lf) => {
653
+ const times = await Promise.all([lf.activityPath ?? lf.path, lf.legacyPath].map((p) => fs.stat(p).then((s) => s.mtime, () => undefined)));
654
+ return times
655
+ .filter((t) => t !== undefined)
656
+ .sort((a, b) => b.getTime() - a.getTime())[0];
657
+ };
374
658
  const managedLockValue = (v) => {
375
659
  if (v === undefined || v === null)
376
660
  return undefined;
@@ -404,6 +688,7 @@ export const scanForMarkers = async (layers) => {
404
688
  layerId: layer.id,
405
689
  label: layer.label ?? layer.id,
406
690
  groups: ownedGroupsInDoc(doc),
691
+ malformedEvents: INSTALLED_HOOK_EVENTS.filter((e) => isPlainObject(doc.hooks) && doc.hooks[e] !== undefined && !Array.isArray(doc.hooks[e])),
407
692
  hasPolicyKey: Object.keys(doc).some(isPolicyKey),
408
693
  managed: isManagedLayer(layer),
409
694
  managedSource: layer.managedSource,
@@ -455,12 +740,66 @@ export const hooksBlocked = (scans) => {
455
740
  : undefined);
456
741
  return { managed: managedOff, developer, managedOnly };
457
742
  };
458
- export const managedMarkerScripts = (scans) => new Set(activeManagedScans(scans).flatMap((s) => s.groups
743
+ export const deliveryKey = (event, route) => route === undefined ? event : `${event}:${route}`;
744
+ export const routeKeyOf = (command, host = DEFAULT_MARKER_TOOL) => {
745
+ const generation = commandGeneration(command);
746
+ if (generation === 'bootstrap')
747
+ return BOOTSTRAP_KEY;
748
+ if (generation === 'entry') {
749
+ const parsed = parseEntryCommand(command);
750
+ return parsed && parsed.host === host ? deliveryKey(parsed.event, parsed.route) : undefined;
751
+ }
752
+ const script = scriptPathFromCommand(command);
753
+ const legacy = script === undefined ? undefined : LEGACY_SCRIPT_ROUTES[basename(script)];
754
+ if (legacy === undefined)
755
+ return undefined;
756
+ if (host === 'codex' && (legacy.route === 'gh' || legacy.route === 'glab')) {
757
+ return deliveryKey(legacy.event, 'bash');
758
+ }
759
+ return deliveryKey(legacy.event, legacy.route);
760
+ };
761
+ export const legacyCommandSends = (command) => {
762
+ const script = scriptPathFromCommand(command);
763
+ return script !== undefined && legacyScriptReleased(basename(script));
764
+ };
765
+ export const isDelivered = (delivered, _event, command) => {
766
+ const key = routeKeyOf(command);
767
+ return key !== undefined && delivered.has(key);
768
+ };
769
+ export const managedMarkerDeliveries = (scans) => new Set(activeManagedScans(scans).flatMap((s) => s.groups
459
770
  .filter((g) => g.ownership === 'cli')
460
- .map((g) => scriptPathFromCommand(g.command))
461
- .filter((p) => p !== undefined)
462
- .map((p) => basename(p))));
463
- export const collectMarkerIssues = async (scans, currentVersion, matchers, skipped = []) => {
771
+ .filter((g) => commandGeneration(g.command) !== 'legacy' || legacyCommandSends(g.command))
772
+ .flatMap((g) => {
773
+ const key = routeKeyOf(g.command);
774
+ return key === undefined ? [] : [key];
775
+ })));
776
+ export const scanRoutes = (scan, host = DEFAULT_MARKER_TOOL) => [
777
+ ...new Set(scan.groups
778
+ .filter((g) => g.ownership === 'cli')
779
+ .filter((g) => commandGeneration(g.command) !== 'legacy' || legacyCommandSends(g.command))
780
+ .flatMap((g) => {
781
+ const key = routeKeyOf(g.command, host);
782
+ return key === undefined ? [] : [key];
783
+ })),
784
+ ];
785
+ export const isPlanSnapshotRoute = (key) => key === 'UserPromptSubmit' || key === 'StopFailure';
786
+ const PLAN_SNAPSHOT_KEY = deliveryKey('UserPromptSubmit');
787
+ export const managedDeliversPlanSnapshot = (scans) => managedMarkerDeliveries(scans).has(PLAN_SNAPSHOT_KEY);
788
+ export const routeLabel = (key) => {
789
+ const labels = {
790
+ [BOOTSTRAP_KEY]: 'the session-start refresh (install-hooks)',
791
+ UserPromptSubmit: 'the Claude plan snapshot',
792
+ 'PostToolUse:gh': 'the GitHub PR marker',
793
+ 'PostToolUse:glab': 'the GitLab MR marker',
794
+ 'PostToolUse:bash': 'the PR and MR markers',
795
+ 'PostToolUse:linear': 'the Linear ticket marker',
796
+ 'PostToolUse:jira': 'the Jira ticket marker',
797
+ StopFailure: 'the Claude turn-error span',
798
+ };
799
+ return labels[key] ?? key;
800
+ };
801
+ const pasteFix = "It comes from your organization's managed settings: ask your Claude admin to paste the current payload from Mainwave's Org-wide setup.";
802
+ export const collectMarkerIssues = async (scans, currentVersion, matchers, skipped = [], choices = { markers: true }, host = DEFAULT_MARKER_TOOL, layout = { managedDir: managedHooksDir() }) => {
464
803
  const issues = [];
465
804
  const active = new Set(activeManagedScans(scans));
466
805
  const inEffect = scans.filter((s, i) => !(s.managed && !active.has(s)) &&
@@ -470,7 +809,7 @@ export const collectMarkerIssues = async (scans, currentVersion, matchers, skipp
470
809
  const running = inEffect.filter((s) => (s.managed ? blocked.managed : blocked.developer) === undefined);
471
810
  const cli = running.flatMap((s) => s.groups
472
811
  .filter((g) => g.ownership === 'cli')
473
- .map((g) => ({ ...g, managed: s.managed === true })));
812
+ .map((g) => ({ ...g, managed: s.managed === true, path: s.path })));
474
813
  const internal = running
475
814
  .filter((s) => s.groups.some((g) => g.ownership === 'internal'))
476
815
  .map((s) => s.path);
@@ -478,7 +817,27 @@ export const collectMarkerIssues = async (scans, currentVersion, matchers, skipp
478
817
  for (const scan of scans.filter((s) => s.managed && !active.has(s) && s.groups.length > 0)) {
479
818
  issues.push({
480
819
  level: 'info',
481
- message: `${scan.label ?? scan.layerId} (${scan.path}) installs marker hooks, but Claude Code ignores it while another managed source is in effect.`,
820
+ message: `${scan.label ?? scan.layerId} (${scan.path}) installs Mainwave hooks, but Claude Code ignores it while another managed source is in effect.`,
821
+ });
822
+ }
823
+ const selected = selectHookMatchers(matchers, choices);
824
+ const installed = new Set([
825
+ ...selected.map((m) => m.event),
826
+ ...(hostRunsBootstrap(host) && selected.length > 0 ? ['SessionStart'] : []),
827
+ ]);
828
+ for (const scan of scans.filter((s) => active.has(s) || !s.managed)) {
829
+ for (const event of (scan.malformedEvents ?? []).filter((e) => installed.has(e))) {
830
+ issues.push({
831
+ level: 'warn',
832
+ message: `${scan.label ?? scan.layerId} (${scan.path}): ${malformedEventMessage(event)}`,
833
+ });
834
+ }
835
+ }
836
+ const noShell = host === DEFAULT_MARKER_TOOL && layout.hookShellMissing === true;
837
+ if (noShell) {
838
+ issues.push({
839
+ level: 'error',
840
+ message: `${GIT_BASH_MISSING_REASON}. ${GIT_BASH_FIX}`,
482
841
  });
483
842
  }
484
843
  const skippedDelivery = skipped.find(({ scan }) => scan.groups.some((g) => g.ownership === 'cli'));
@@ -486,18 +845,20 @@ export const collectMarkerIssues = async (scans, currentVersion, matchers, skipp
486
845
  const { scan, reason } = skippedDelivery;
487
846
  issues.push({
488
847
  level: 'warn',
489
- message: `${scan.label ?? scan.layerId} (${scan.path}) delivers the ticket & PR marker hooks, but this ` +
848
+ message: `${scan.label ?? scan.layerId} (${scan.path}) delivers the Mainwave hooks, but this ` +
490
849
  `session doesn't read it: ${reason}. Markers aren't sent from sessions started this way.`,
491
850
  });
492
851
  return issues;
493
852
  }
494
853
  if (withCli.length === 0 && !installedInternal) {
854
+ if (noShell)
855
+ return issues;
495
856
  issues.push({
496
857
  level: 'info',
497
858
  message: blocked.managedOnly
498
859
  ? "Ticket & PR markers are not configured, and your organization's managed settings run only " +
499
- 'hooks they deliver — ask your Claude admin to add the marker hooks to them.'
500
- : 'Ticket & PR markers are not configured — re-run `mainwave-cli setup claude-code` to enable them.',
860
+ 'hooks they deliver — ask your Claude admin to add the Mainwave hooks to them.'
861
+ : `Ticket & PR markers are not configured — re-run \`mainwave-cli setup ${host === 'codex' ? 'codex' : 'claude-code'}\` to enable them.`,
501
862
  });
502
863
  return issues;
503
864
  }
@@ -505,38 +866,60 @@ export const collectMarkerIssues = async (scans, currentVersion, matchers, skipp
505
866
  const count = scan.groups.filter((g) => g.ownership === 'cli').length;
506
867
  issues.push({
507
868
  level: 'info',
508
- message: `Marker hooks (${count}) are installed in ${scan.label ?? scan.layerId}: ${scan.path}.`,
869
+ message: `Mainwave hooks (${count}) are installed in ${scan.label ?? scan.layerId}: ${scan.path}.`,
509
870
  });
510
871
  const reason = scan.managed ? blocked.managed : blocked.developer;
511
872
  if (reason !== undefined) {
512
- const delivered = managedMarkerScripts(scans);
873
+ const delivered = managedMarkerDeliveries(scans);
513
874
  const covered = blocked.managed === undefined &&
514
875
  scan.groups
515
876
  .filter((g) => g.ownership === 'cli')
516
- .every((g) => delivered.has(basename(scriptPathFromCommand(g.command) ?? g.command)));
877
+ .every((g) => isDelivered(delivered, g.event, g.command));
517
878
  issues.push({
518
879
  level: 'warn',
519
- message: `Claude Code doesn't run the marker hooks in ${scan.path}: ${reason}.` +
880
+ message: `Claude Code doesn't run the Mainwave hooks in ${scan.path}: ${reason}.` +
520
881
  (!scan.managed && blocked.managedOnly
521
882
  ? covered
522
- ? ' Your managed settings deliver the same marker hooks, so this copy is unused.'
883
+ ? ' Your managed settings deliver the same hooks, so this copy is unused.'
523
884
  : ' Ask your Claude admin to deliver them through managed settings.'
524
885
  : ''),
525
886
  });
526
887
  }
527
888
  }
528
- const runningWithCli = running.filter((s) => s.groups.some((g) => g.ownership === 'cli'));
529
- const commandsByScript = new Map();
889
+ const commandsByRoute = new Map();
530
890
  for (const g of cli) {
531
- const script = scriptPathFromCommand(g.command);
532
- const name = script === undefined ? g.command : basename(script);
533
- commandsByScript.set(name, (commandsByScript.get(name) ?? new Set()).add(g.command));
891
+ const key = routeKeyOf(g.command, host);
892
+ if (key === undefined || key === BOOTSTRAP_KEY)
893
+ continue;
894
+ if (commandGeneration(g.command) === 'legacy' && !legacyCommandSends(g.command))
895
+ continue;
896
+ commandsByRoute.set(key, (commandsByRoute.get(key) ?? new Set()).add(g.command));
534
897
  }
535
- if (runningWithCli.length > 1 && [...commandsByScript.values()].some((c) => c.size > 1)) {
898
+ const duplicated = [...commandsByRoute].filter(([, c]) => c.size > 1);
899
+ const generations = (commands) => new Set([...commands].map(commandGeneration));
900
+ const bothGenerations = duplicated.filter(([, c]) => {
901
+ const gens = generations(c);
902
+ return gens.has('legacy') && gens.has('entry');
903
+ });
904
+ if (bothGenerations.length > 0) {
905
+ const files = [
906
+ ...new Set(cli.filter((g) => commandGeneration(g.command) === 'legacy').map((g) => g.path)),
907
+ ];
908
+ issues.push({
909
+ level: 'warn',
910
+ message: `Both generations of the Mainwave hooks are installed: the first-generation per-script hooks (${files.join(', ')}) ` +
911
+ `and the current mainwave-hook.sh entry, so ${bothGenerations.map(([k]) => routeLabel(k)).join(', ')} send twice. ` +
912
+ 'Remove the first-generation groups: a managed copy means your Claude admin merged the current payload into ' +
913
+ 'the old one instead of replacing it — ask them to replace it; a user copy goes when you re-run setup.',
914
+ });
915
+ }
916
+ const sameGeneration = duplicated.filter(([k]) => !bothGenerations.some(([b]) => b === k));
917
+ const runningWithCli = running.filter((s) => s.groups.some((g) => g.ownership === 'cli'));
918
+ if (runningWithCli.length > 1 && sameGeneration.length > 0) {
536
919
  issues.push({
537
920
  level: 'warn',
538
- message: `Marker hooks are installed in more than one settings file (${runningWithCli.map((s) => s.path).join(', ')}) ` +
539
- 'with different commands, so every ticket and PR sends a marker once per file. Keep one: when your ' +
921
+ message: `Mainwave hooks are installed in more than one settings file (${runningWithCli.map((s) => s.path).join(', ')}) ` +
922
+ `with different commands, so ${sameGeneration.map(([k]) => routeLabel(k)).join(', ')} send once per file. Keep one: when your ` +
540
923
  'organization delivers them through managed settings, `mainwave-cli install-hooks` removes the ' +
541
924
  'user-level copy; remove any project-level copy by hand.',
542
925
  });
@@ -550,70 +933,225 @@ export const collectMarkerIssues = async (scans, currentVersion, matchers, skipp
550
933
  'and restart Claude Code — or re-run setup on that file.',
551
934
  });
552
935
  }
936
+ const fixFor = (managed, user) => (managed ? pasteFix : user);
937
+ const byKey = new Map(matchers.map((m) => [deliveryKey(m.event, m.route), m]));
938
+ const seenRoutes = new Set();
939
+ let entryChecked = false;
553
940
  for (const g of cli) {
554
- const version = parseManagedByVersion(g.command);
555
- if (!g.managed && version !== undefined && /^\d/.test(version) && version !== currentVersion) {
941
+ const generation = commandGeneration(g.command);
942
+ if (generation === 'legacy') {
943
+ const script = scriptPathFromCommand(g.command);
944
+ const name = script === undefined ? g.command : basename(script);
945
+ if (g.event === 'PostToolUse' && effectiveMatcher(g.matcher) === NO_MATCHER) {
946
+ issues.push({
947
+ level: 'warn',
948
+ message: `The first-generation Mainwave hook ${name} in ${g.path} has no matcher, so it runs on every tool call. ` +
949
+ fixFor(g.managed, 'Re-run setup to replace it.'),
950
+ });
951
+ }
952
+ if (!legacyCommandSends(g.command)) {
953
+ issues.push({
954
+ level: 'warn',
955
+ message: `A first-generation Mainwave hook (${name}, ${g.event}) in ${g.path} runs a script no release installs, so it sends nothing. ` +
956
+ fixFor(g.managed, 'Re-run setup to replace it.'),
957
+ });
958
+ continue;
959
+ }
960
+ const legacyKey = routeKeyOf(g.command, host);
961
+ if (legacyKey !== undefined)
962
+ seenRoutes.add(legacyKey);
556
963
  issues.push({
557
- level: 'warn',
558
- message: `Marker hook [${g.matcher}] was written by @mainwave/cli@${version}; you are running ${currentVersion}. ` +
559
- 'Re-run setup to refresh the hook scripts and matching rules — a stale rule silently stops emitting.',
964
+ level: g.managed ? 'info' : 'warn',
965
+ message: g.managed
966
+ ? `Your organization's managed settings still run the first-generation ${name} hook (one synchronous Node per matching tool call). ` +
967
+ "It keeps working; the current payload from Mainwave's Org-wide setup runs every Mainwave hook in the background. Ask your Claude admin to paste it."
968
+ : `${name} (${g.event}) in ${g.path} is a first-generation Mainwave hook. Re-run setup to move to the current hook entry.`,
560
969
  });
561
- }
562
- const script = scriptPathFromCommand(g.command);
563
- if (script !== undefined) {
564
- try {
565
- await fs.access(script);
566
- if (g.managed && (await resolveManagedScript(script)) === undefined) {
970
+ if (script !== undefined) {
971
+ try {
972
+ await fs.access(script);
973
+ if (g.managed && (await resolveManagedScript(script)) === undefined) {
974
+ issues.push({
975
+ level: 'error',
976
+ message: `Marker hook ${basename(script)} in ${dirname(script)} names no installed release ` +
977
+ `(${MANAGED_POINTER} is missing, or its release lacks the script), so it sends nothing. ` +
978
+ 'Start a new Claude Code session, or ' +
979
+ (process.platform === 'win32' ? 'in Git Bash run ' : 'run ') +
980
+ `\`${installHooksCommand(PAYLOAD_CLI_SPEC, { quiet: false })}\`.`,
981
+ });
982
+ }
983
+ }
984
+ catch {
567
985
  issues.push({
568
986
  level: 'error',
569
- message: `Marker hook ${basename(script)} in ${dirname(script)} names no installed release ` +
570
- `(${MANAGED_POINTER} is missing, or its release lacks the script), so it sends nothing. ` +
571
- 'Start a new Claude Code session, or ' +
572
- (process.platform === 'win32' ? 'in Git Bash run ' : 'run ') +
573
- `\`${installHooksCommand(version ?? PAYLOAD_CLI_SPEC, { quiet: false })}\`.`,
987
+ message: `Marker hook script is missing: ${script} — the hook no-ops silently (fail-open). ` +
988
+ (g.managed
989
+ ? 'Start a new Claude Code session (the managed settings install it at startup), or ' +
990
+ (process.platform === 'win32' ? 'in Git Bash run ' : 'run ') +
991
+ `\`${installHooksCommand(PAYLOAD_CLI_SPEC, { quiet: false })}\`.`
992
+ : 'Re-run setup.'),
574
993
  });
575
994
  }
576
995
  }
577
- catch {
996
+ continue;
997
+ }
998
+ if (host !== 'codex' && g.async !== true) {
999
+ issues.push({
1000
+ level: 'warn',
1001
+ message: `The Mainwave hook ${shortCommand(g.command)} under ${g.event} in ${g.path} is not async, so ` +
1002
+ `Claude Code waits for it on every ${g.event === 'PostToolUse' ? 'matching tool call' : g.event}. ` +
1003
+ fixFor(g.managed, 'Re-run setup to rewrite it.'),
1004
+ });
1005
+ }
1006
+ if (generation === 'bootstrap') {
1007
+ seenRoutes.add(BOOTSTRAP_KEY);
1008
+ if (g.command === installHooksCommand(PAYLOAD_CLI_SPEC)) {
578
1009
  issues.push({
579
- level: 'error',
580
- message: `Marker hook script is missing: ${script} — the entry no-ops silently (fail-open). ` +
581
- (g.managed
582
- ? 'Start a new Claude Code session (the managed settings install it at startup), or ' +
583
- (process.platform === 'win32' ? 'in Git Bash run ' : 'run ') +
584
- `\`${installHooksCommand(version ?? PAYLOAD_CLI_SPEC, { quiet: false })}\`.`
585
- : 'Re-run setup.'),
1010
+ level: 'info',
1011
+ message: `The Mainwave session-start refresh in ${g.path} is an earlier form that reports npm's error ` +
1012
+ 'as a failed hook when the npm registry is unreachable; the current one stays silent. ' +
1013
+ fixFor(g.managed, 'Re-run setup to rewrite it.'),
586
1014
  });
587
1015
  }
588
- const expected = matchers.find((m) => script.endsWith(m.hook));
589
- if (expected && expected.matcher !== g.matcher) {
1016
+ if (effectiveMatcher(g.matcher) === NO_MATCHER) {
590
1017
  issues.push({
591
1018
  level: 'warn',
592
- message: `Marker hook for ${basename(script)} has matcher \`${g.matcher}\` but this CLI ships \`${expected.matcher}\`. ` +
593
- (g.managed
594
- ? "It comes from your organization's managed settings: ask your Claude admin to paste the current payload from Mainwave's Org-wide setup."
595
- : 'Re-run setup — the stale matcher may no longer match the tools in use.'),
1019
+ message: `The Mainwave session-start refresh in ${g.path} has no matcher, so it runs npx on every SessionStart, ` +
1020
+ `/clear and compaction included. This CLI ships \`${BOOTSTRAP_MATCHER}\`. ` +
1021
+ fixFor(g.managed, 'Re-run setup to rewrite it.'),
596
1022
  });
597
1023
  }
1024
+ continue;
1025
+ }
1026
+ const parsed = parseEntryCommand(g.command);
1027
+ if (parsed === undefined || parsed.host !== host)
1028
+ continue;
1029
+ const key = deliveryKey(parsed.event, parsed.route);
1030
+ seenRoutes.add(key);
1031
+ if (parsed.event !== g.event) {
1032
+ issues.push({
1033
+ level: 'warn',
1034
+ message: `The Mainwave hook for ${parsed.event}${parsed.route ? ` ${parsed.route}` : ''} is registered under ${g.event} in ${g.path}, ` +
1035
+ `so it runs on ${g.event} and its feature finds nothing to do. ` +
1036
+ fixFor(g.managed, 'Re-run setup.'),
1037
+ });
1038
+ continue;
1039
+ }
1040
+ const expected = byKey.get(key);
1041
+ if (expected === undefined) {
1042
+ issues.push({
1043
+ level: 'info',
1044
+ message: `${g.path} runs Mainwave hook route ${parsed.event}${parsed.route ? ` ${parsed.route}` : ''}, which this CLI doesn't ship; the entry exits without sending anything.`,
1045
+ });
1046
+ continue;
1047
+ }
1048
+ if (expected.matcher !== undefined && effectiveMatcher(g.matcher) === NO_MATCHER) {
1049
+ issues.push({
1050
+ level: 'warn',
1051
+ message: `The Mainwave hook for ${routeLabel(key)} in ${g.path} has no matcher, so it runs on every ${g.event === 'PostToolUse' ? 'tool call' : g.event}. ` +
1052
+ `This CLI ships \`${expected.matcher}\`. ` +
1053
+ fixFor(g.managed, 'Re-run setup to rewrite it.'),
1054
+ });
1055
+ }
1056
+ else if (effectiveMatcher(expected.matcher) !== effectiveMatcher(g.matcher)) {
1057
+ issues.push({
1058
+ level: 'warn',
1059
+ message: `The Mainwave hook for ${routeLabel(key)} has matcher \`${g.matcher}\` but this CLI ships \`${expected.matcher ?? NO_MATCHER}\`. ` +
1060
+ fixFor(g.managed, 'Re-run setup — the stale matcher may no longer match the tools in use.'),
1061
+ });
1062
+ }
1063
+ if (host !== 'codex' && expected.if !== undefined && g.if !== expected.if) {
1064
+ issues.push({
1065
+ level: 'warn',
1066
+ message: g.if === undefined
1067
+ ? `The Mainwave hook for ${routeLabel(key)} in ${g.path} has no \`if\` filter, so Claude Code starts it for every ${g.matcher} call. ` +
1068
+ `This CLI ships \`if: ${expected.if}\`. ` +
1069
+ fixFor(g.managed, 'Re-run setup to rewrite it.')
1070
+ : `The Mainwave hook for ${routeLabel(key)} has \`if: ${g.if}\` but this CLI ships \`if: ${expected.if}\`. ` +
1071
+ fixFor(g.managed, 'Re-run setup to rewrite it.'),
1072
+ });
1073
+ }
1074
+ if (!entryChecked) {
1075
+ entryChecked = true;
1076
+ const nodeEntry = cli.some((c) => c.command.includes(HOOK_NODE_ENTRY_SCRIPT));
1077
+ issues.push(...(await entryIssues(layout.managedDir, matchers, g.managed, nodeEntry)));
1078
+ }
1079
+ }
1080
+ const anyCurrent = cli.some((g) => commandGeneration(g.command) === 'entry');
1081
+ if (anyCurrent) {
1082
+ const managedCurrent = cli.some((g) => g.managed && commandGeneration(g.command) === 'entry');
1083
+ const wanted = managedCurrent ? matchers : selected;
1084
+ const missing = wanted.filter((m) => !seenRoutes.has(deliveryKey(m.event, m.route)));
1085
+ if (missing.length > 0) {
1086
+ issues.push({
1087
+ level: managedCurrent ? 'info' : 'warn',
1088
+ message: `No Mainwave hook runs ${missing.map((m) => routeLabel(deliveryKey(m.event, m.route))).join(', ')}, which this CLI ships. ` +
1089
+ (managedCurrent
1090
+ ? "Your organization's payload predates them: ask your Claude admin to paste the current payload from Mainwave's Org-wide setup."
1091
+ : 'Re-run setup to add them.'),
1092
+ });
598
1093
  }
599
1094
  }
600
1095
  if (cli.length > 0) {
601
1096
  const activity = [];
602
1097
  for (const lf of markerLogFiles()) {
603
- try {
604
- const stat = await fs.stat(lf.path);
605
- activity.push(`${lf.label}: last activity ${stat.mtime.toISOString()}`);
606
- }
607
- catch {
608
- }
1098
+ const last = await lastLogActivity(lf);
1099
+ if (last)
1100
+ activity.push(`${lf.label}: last activity ${last.toISOString()}`);
609
1101
  }
610
1102
  issues.push({
611
1103
  level: 'info',
612
1104
  message: activity.length > 0
613
- ? `Marker hook activity — ${activity.join('; ')}.`
614
- : 'Markers are configured but no hook activity is recorded yet (~/.mainwave-*-marker.log). ' +
1105
+ ? `Mainwave hook activity — ${activity.join('; ')}.`
1106
+ : 'Mainwave hooks are configured but no hook activity is recorded yet (~/.mainwave/logs/*-marker.log; for plan snapshots, ~/.mainwave/logs/plan-snapshot.log.ok). ' +
615
1107
  'File a ticket or open a PR with `gh pr create`, then check the log and the use case activity.',
616
1108
  });
617
1109
  }
618
1110
  return issues;
619
1111
  };
1112
+ export const entryIssues = async (managedDir, matchers, managed, nodeEntry = false) => {
1113
+ const entry = join(managedDir, HOOK_ENTRY_SCRIPT);
1114
+ const fix = managed
1115
+ ? 'Start a new Claude Code session (the managed settings install it at startup), or ' +
1116
+ (process.platform === 'win32' ? 'in Git Bash run ' : 'run ') +
1117
+ `\`${installHooksCommand(PAYLOAD_CLI_SPEC, { quiet: false })}\`.`
1118
+ : 'Re-run setup.';
1119
+ const text = await fs.readFile(entry, 'utf8').catch(() => null);
1120
+ if (text === null) {
1121
+ return [
1122
+ {
1123
+ level: 'error',
1124
+ message: `The Mainwave hook entry is not installed (${entry}), so every Mainwave hook exits without sending anything. ${fix}`,
1125
+ },
1126
+ ];
1127
+ }
1128
+ const id = entryVersionId(text);
1129
+ const release = id === undefined ? undefined : join(managedDir, MANAGED_VERSIONS_DIR, id);
1130
+ if (release === undefined || !existsSync(join(release, HOOK_DISPATCHER_SCRIPT))) {
1131
+ return [
1132
+ {
1133
+ level: 'error',
1134
+ message: `The Mainwave hook entry (${entry}) names ${id === undefined ? 'no release' : `release ${id}, which is not installed`}, so every Mainwave hook exits without sending anything. ${fix}`,
1135
+ },
1136
+ ];
1137
+ }
1138
+ const missing = hookScriptFiles(matchers).filter((f) => !existsSync(join(release, f)));
1139
+ if (missing.length > 0) {
1140
+ return [
1141
+ {
1142
+ level: 'error',
1143
+ message: `Release ${id} of the Mainwave hooks lacks ${missing.join(', ')}, so the hooks that need ${missing.length === 1 ? 'it' : 'them'} send nothing. ${fix}`,
1144
+ },
1145
+ ];
1146
+ }
1147
+ const node = join(managedDir, HOOK_NODE_ENTRY_SCRIPT);
1148
+ if (nodeEntry && !existsSync(node)) {
1149
+ return [
1150
+ {
1151
+ level: 'error',
1152
+ message: `The Mainwave hooks' Node entry is not installed (${node}), so every hook that runs it fails without sending anything. ${fix}`,
1153
+ },
1154
+ ];
1155
+ }
1156
+ return [{ level: 'info', message: `Mainwave hook entry: ${entry} runs release ${id}.` }];
1157
+ };