@mainwave/cli 0.7.1 → 0.9.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 +141 -42
- package/dist/adapters/claude-code.js +33 -7
- package/dist/adapters/claude-desktop.js +0 -1
- package/dist/adapters/codex-cli.js +1 -2
- package/dist/adapters/copilot-chat.js +0 -1
- package/dist/adapters/copilot-cli.js +0 -1
- package/dist/adapters/cursor-enterprise.js +0 -1
- package/dist/adapters/cursor.js +15 -4
- package/dist/adapters/index.js +0 -1
- package/dist/adapters/types.js +0 -1
- package/dist/api/index.js +0 -1
- package/dist/api/types.gen.js +0 -1
- package/dist/cli.js +0 -1
- package/dist/core/apply.js +151 -42
- package/dist/core/auth-commands.js +0 -1
- package/dist/core/behaviour-hooks.js +0 -1
- package/dist/core/browser.js +0 -1
- package/dist/core/codecs/cursor-hooks-json.js +0 -1
- package/dist/core/codecs/env-file.js +0 -1
- package/dist/core/codecs/json-env.js +0 -1
- package/dist/core/codecs/json-flat.js +0 -1
- package/dist/core/codecs/json-managed.js +0 -1
- package/dist/core/codecs/toml-otel.js +0 -1
- package/dist/core/codecs/types.js +0 -1
- package/dist/core/detect.js +0 -1
- package/dist/core/device-login.js +0 -1
- package/dist/core/doctor.js +45 -9
- package/dist/core/edit.js +9 -5
- package/dist/core/effective-settings.js +71 -20
- package/dist/core/entry-script.js +90 -0
- package/dist/core/env-command.js +0 -1
- package/dist/core/errors.js +0 -1
- package/dist/core/flags.js +0 -1
- package/dist/core/format.js +0 -1
- package/dist/core/git-bash.js +40 -0
- package/dist/core/git.js +0 -1
- package/dist/core/headers.js +0 -1
- package/dist/core/install-hooks.js +127 -44
- package/dist/core/interview.js +53 -4
- package/dist/core/keys.js +0 -1
- package/dist/core/layer-policy.js +2 -1
- package/dist/core/markers.js +826 -133
- package/dist/core/pinned-use-case.js +0 -1
- package/dist/core/platform.js +0 -1
- package/dist/core/post-setup.js +0 -1
- package/dist/core/prompts.js +0 -1
- package/dist/core/settings.js +32 -8
- package/dist/core/skills.js +5 -2
- package/dist/core/status.js +7 -5
- package/dist/core/store.js +0 -1
- package/dist/core/tty.js +0 -1
- package/dist/core/ucid.js +0 -1
- package/dist/core/ui.js +0 -1
- package/dist/core/use-case.js +0 -1
- package/dist/core/validate.js +0 -1
- package/dist/core/verify.js +0 -1
- package/dist/core/version.js +0 -1
- package/dist/core/wizard.js +49 -8
- package/dist/main.js +16 -10
- package/hooks/cursor-otlp.mjs +13 -15
- package/hooks/github-pr-marker.mjs +55 -31
- package/hooks/glab-mr-marker.mjs +795 -0
- package/hooks/jira-ticket-marker.mjs +35 -23
- package/hooks/linear-ticket-marker.mjs +35 -21
- package/hooks/mainwave-hook-node.mjs +42 -0
- package/hooks/mainwave-hook.mjs +301 -0
- package/hooks/managed-entry.mjs +42 -0
- package/hooks/marker-core.mjs +389 -62
- package/hooks/matchers.json +82 -6
- package/hooks/plan-snapshot.mjs +529 -0
- package/hooks/stop-failure.mjs +43 -0
- package/hooks/vocabulary.d.mts +48 -0
- package/hooks/vocabulary.mjs +181 -0
- package/package.json +6 -5
- package/skills/mainwave-instrument/SKILL.md +21 -7
- package/skills/mainwave-instrument/reference/api.md +29 -10
- package/skills/mainwave-instrument/reference/frameworks.md +3 -3
- package/skills/mainwave-instrument/reference/troubleshooting.md +12 -5
- package/skills/mainwave-instrument-node/SKILL.md +420 -0
- package/skills/mainwave-instrument-node/reference/api.md +96 -0
- package/skills/mainwave-instrument-node/reference/frameworks.md +82 -0
- package/skills/mainwave-instrument-node/reference/troubleshooting.md +152 -0
- package/skills/mainwave-setup/SKILL.md +47 -12
- package/dist/adapters/claude-code.js.map +0 -1
- package/dist/adapters/claude-desktop.js.map +0 -1
- package/dist/adapters/codex-cli.js.map +0 -1
- package/dist/adapters/copilot-chat.js.map +0 -1
- package/dist/adapters/copilot-cli.js.map +0 -1
- package/dist/adapters/cursor-enterprise.js.map +0 -1
- package/dist/adapters/cursor.js.map +0 -1
- package/dist/adapters/index.js.map +0 -1
- package/dist/adapters/types.js.map +0 -1
- package/dist/api/index.js.map +0 -1
- package/dist/api/types.gen.js.map +0 -1
- package/dist/cli.js.map +0 -1
- package/dist/core/apply.js.map +0 -1
- package/dist/core/auth-commands.js.map +0 -1
- package/dist/core/behaviour-hooks.js.map +0 -1
- package/dist/core/browser.js.map +0 -1
- package/dist/core/codecs/cursor-hooks-json.js.map +0 -1
- package/dist/core/codecs/env-file.js.map +0 -1
- package/dist/core/codecs/json-env.js.map +0 -1
- package/dist/core/codecs/json-flat.js.map +0 -1
- package/dist/core/codecs/json-managed.js.map +0 -1
- package/dist/core/codecs/toml-otel.js.map +0 -1
- package/dist/core/codecs/types.js.map +0 -1
- package/dist/core/detect.js.map +0 -1
- package/dist/core/device-login.js.map +0 -1
- package/dist/core/doctor.js.map +0 -1
- package/dist/core/edit.js.map +0 -1
- package/dist/core/effective-settings.js.map +0 -1
- package/dist/core/env-command.js.map +0 -1
- package/dist/core/errors.js.map +0 -1
- package/dist/core/flags.js.map +0 -1
- package/dist/core/format.js.map +0 -1
- package/dist/core/git.js.map +0 -1
- package/dist/core/headers.js.map +0 -1
- package/dist/core/install-hooks.js.map +0 -1
- package/dist/core/interview.js.map +0 -1
- package/dist/core/keys.js.map +0 -1
- package/dist/core/layer-policy.js.map +0 -1
- package/dist/core/markers.js.map +0 -1
- package/dist/core/pinned-use-case.js.map +0 -1
- package/dist/core/platform.js.map +0 -1
- package/dist/core/post-setup.js.map +0 -1
- package/dist/core/prompts.js.map +0 -1
- package/dist/core/settings.js.map +0 -1
- package/dist/core/skills.js.map +0 -1
- package/dist/core/status.js.map +0 -1
- package/dist/core/store.js.map +0 -1
- package/dist/core/tty.js.map +0 -1
- package/dist/core/ucid.js.map +0 -1
- package/dist/core/ui.js.map +0 -1
- package/dist/core/use-case.js.map +0 -1
- package/dist/core/validate.js.map +0 -1
- package/dist/core/verify.js.map +0 -1
- package/dist/core/version.js.map +0 -1
- package/dist/core/wizard.js.map +0 -1
- package/dist/main.js.map +0 -1
package/dist/core/markers.js
CHANGED
|
@@ -1,24 +1,54 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
1
2
|
import { existsSync, promises as fs } from 'node:fs';
|
|
2
3
|
import { homedir } from 'node:os';
|
|
3
|
-
import { basename, join, resolve } from 'node:path';
|
|
4
|
+
import { basename, dirname, join, resolve, win32 } from 'node:path';
|
|
4
5
|
import { fileURLToPath } from 'node:url';
|
|
5
6
|
import { dropInNames } from './effective-settings.js';
|
|
6
|
-
import {
|
|
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';
|
|
9
|
+
import { isManagedLayer, isPolicyKey } from './layer-policy.js';
|
|
7
10
|
export const MANAGED_BY = '--managed-by @mainwave/cli';
|
|
8
11
|
export const PAYLOAD_CLI_SPEC = 'latest';
|
|
9
12
|
const OWNED_CLI_MARKERS = [MANAGED_BY, '.mainwave/hooks', '.mainwave\\hooks'];
|
|
13
|
+
const BOOTSTRAP_RE = /@mainwave\/cli@\S+ install-hooks\b/;
|
|
10
14
|
const OWNED_INTERNAL_MARKERS = [
|
|
11
15
|
'clients/cli/hooks',
|
|
12
16
|
'claude-managed-settings/hooks',
|
|
13
17
|
'mainwave-hooks',
|
|
14
18
|
];
|
|
15
19
|
export const commandOwnership = (command) => {
|
|
16
|
-
if (OWNED_CLI_MARKERS.some((m) => command.includes(m)))
|
|
20
|
+
if (OWNED_CLI_MARKERS.some((m) => command.includes(m)) || BOOTSTRAP_RE.test(command)) {
|
|
17
21
|
return 'cli';
|
|
22
|
+
}
|
|
18
23
|
if (OWNED_INTERNAL_MARKERS.some((m) => command.includes(m)))
|
|
19
24
|
return 'internal';
|
|
20
25
|
return null;
|
|
21
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';
|
|
22
52
|
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
23
53
|
export const packagedHooksDir = () => fileURLToPath(new URL('../../hooks/', import.meta.url));
|
|
24
54
|
export const installedHooksDir = () => join(homedir(), '.mainwave', 'hooks');
|
|
@@ -35,21 +65,84 @@ export const shellHome = (plat = process.platform, env = process.env, dirExists
|
|
|
35
65
|
};
|
|
36
66
|
export const installHooksCommand = (version, { quiet = true } = {}) => `cd "$HOME" && npx -y --registry=https://registry.npmjs.org ` +
|
|
37
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-]*$/;
|
|
38
77
|
export const readPackagedMatchers = async (dir = packagedHooksDir()) => {
|
|
39
78
|
const raw = JSON.parse(await fs.readFile(join(dir, 'matchers.json'), 'utf8'));
|
|
40
79
|
if (!Array.isArray(raw))
|
|
41
80
|
throw new Error('matchers.json: expected a top-level array');
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
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`);
|
|
109
|
+
}
|
|
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"`);
|
|
45
122
|
}
|
|
46
|
-
|
|
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
|
+
};
|
|
47
139
|
});
|
|
48
140
|
};
|
|
141
|
+
const SHARED_HOOK_MODULES = ['marker-core.mjs', 'vocabulary.mjs', HOOK_DISPATCHER_SCRIPT];
|
|
142
|
+
export const featureModule = (feature) => `${feature}.mjs`;
|
|
49
143
|
export const hookScriptFiles = (matchers) => [
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
...matchers.map((m) => m.hook),
|
|
144
|
+
...SHARED_HOOK_MODULES,
|
|
145
|
+
...new Set(matchers.flatMap((m) => m.features.map(featureModule))),
|
|
53
146
|
];
|
|
54
147
|
export const copyHookScripts = async (files, srcDir = packagedHooksDir(), destDir = installedHooksDir()) => {
|
|
55
148
|
await fs.mkdir(destDir, { recursive: true });
|
|
@@ -61,48 +154,319 @@ export const copyHookScripts = async (files, srcDir = packagedHooksDir(), destDi
|
|
|
61
154
|
}
|
|
62
155
|
return destDir;
|
|
63
156
|
};
|
|
64
|
-
export const
|
|
65
|
-
|
|
157
|
+
export const MANAGED_POINTER = 'current.json';
|
|
158
|
+
export const MANAGED_VERSIONS_DIR = 'versions';
|
|
159
|
+
export const MANAGED_ENTRY_SCRIPT = 'managed-entry.mjs';
|
|
160
|
+
const MANAGED_ENTRY_MARK = 'mainwave managed hook entry';
|
|
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);
|
|
176
|
+
const VERSION_DIR_RE = /^[A-Za-z0-9][A-Za-z0-9._+-]*$/;
|
|
177
|
+
const versionDirName = (version, files, bodies) => {
|
|
178
|
+
const hash = createHash('sha256');
|
|
179
|
+
files.forEach((f, i) => hash.update(f).update('\0').update(bodies[i]).update('\0'));
|
|
180
|
+
const safe = version.replace(/[^A-Za-z0-9._+-]/g, '_').replace(/^[^A-Za-z0-9]+/, '');
|
|
181
|
+
return `${safe || 'v'}-${hash.digest('hex').slice(0, 12)}`;
|
|
182
|
+
};
|
|
183
|
+
const holdsFiles = async (dir, files, bodies) => {
|
|
184
|
+
for (const [i, f] of files.entries()) {
|
|
185
|
+
const current = await fs.readFile(join(dir, f)).catch(() => null);
|
|
186
|
+
if (current === null || !current.equals(bodies[i]))
|
|
187
|
+
return false;
|
|
188
|
+
}
|
|
189
|
+
return true;
|
|
190
|
+
};
|
|
191
|
+
const writeAtomic = async (path, body, mode = 0o644) => {
|
|
192
|
+
const tmp = `${path}.tmp.${process.pid}.${Math.random().toString(36).slice(2)}`;
|
|
193
|
+
await fs.writeFile(tmp, body, { mode });
|
|
194
|
+
await fs.rename(tmp, path);
|
|
195
|
+
};
|
|
196
|
+
export const readManagedPointer = async (destDir) => {
|
|
197
|
+
try {
|
|
198
|
+
const { dir } = JSON.parse(await fs.readFile(join(destDir, MANAGED_POINTER), 'utf8'));
|
|
199
|
+
return typeof dir === 'string' && VERSION_DIR_RE.test(dir) ? dir : undefined;
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
return undefined;
|
|
203
|
+
}
|
|
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
|
+
};
|
|
209
|
+
export const stageManagedVersion = async (files, srcDir, destDir, version) => {
|
|
210
|
+
const bodies = await Promise.all(files.map((f) => fs.readFile(join(srcDir, f))));
|
|
211
|
+
const id = versionDirName(version, files, bodies);
|
|
212
|
+
const versionsDir = join(destDir, MANAGED_VERSIONS_DIR);
|
|
213
|
+
await fs.mkdir(versionsDir, { recursive: true });
|
|
214
|
+
const final = join(versionsDir, id);
|
|
215
|
+
const staged = { id, version, files, bodies };
|
|
216
|
+
if (await holdsFiles(final, files, bodies)) {
|
|
217
|
+
if ((await readManagedPointer(destDir)) !== id || (await readEntryVersion(destDir)) !== id) {
|
|
218
|
+
const now = new Date();
|
|
219
|
+
await fs.utimes(final, now, now).catch(() => undefined);
|
|
220
|
+
}
|
|
221
|
+
return { ...staged, written: false };
|
|
222
|
+
}
|
|
223
|
+
const tmp = await fs.mkdtemp(join(versionsDir, `.staging-${id}-`));
|
|
224
|
+
try {
|
|
225
|
+
for (const [i, f] of files.entries()) {
|
|
226
|
+
await fs.writeFile(join(tmp, f), bodies[i], { mode: 0o644 });
|
|
227
|
+
}
|
|
228
|
+
await fs.chmod(tmp, 0o755);
|
|
229
|
+
try {
|
|
230
|
+
await fs.rename(tmp, final);
|
|
231
|
+
}
|
|
232
|
+
catch (err) {
|
|
233
|
+
if (await holdsFiles(final, files, bodies)) {
|
|
234
|
+
await fs.rm(tmp, { recursive: true, force: true });
|
|
235
|
+
return { ...staged, written: false };
|
|
236
|
+
}
|
|
237
|
+
if (!(await moveAside(versionsDir, id)))
|
|
238
|
+
throw err;
|
|
239
|
+
await fs.rename(tmp, final);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
catch (err) {
|
|
243
|
+
await fs.rm(tmp, { recursive: true, force: true });
|
|
244
|
+
if (await holdsFiles(final, files, bodies))
|
|
245
|
+
return { ...staged, written: false };
|
|
246
|
+
throw err;
|
|
247
|
+
}
|
|
248
|
+
return { ...staged, written: true };
|
|
249
|
+
};
|
|
250
|
+
const moveAside = async (versionsDir, id) => {
|
|
251
|
+
const aside = join(versionsDir, `.stale-${id}-${Math.random().toString(36).slice(2)}`);
|
|
252
|
+
try {
|
|
253
|
+
await fs.rename(join(versionsDir, id), aside);
|
|
254
|
+
}
|
|
255
|
+
catch (err) {
|
|
256
|
+
return isMissing(err);
|
|
257
|
+
}
|
|
258
|
+
const now = new Date();
|
|
259
|
+
await fs.utimes(aside, now, now).catch(() => undefined);
|
|
260
|
+
return true;
|
|
261
|
+
};
|
|
262
|
+
const isMissing = (err) => err?.code === 'ENOENT';
|
|
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
|
+
};
|
|
300
|
+
export const commitManagedVersion = async (staged, hookNames, srcDir, destDir) => {
|
|
66
301
|
const updated = [];
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
302
|
+
const previous = await readManagedPointer(destDir);
|
|
303
|
+
if (previous !== staged.id) {
|
|
304
|
+
await writeAtomic(join(destDir, MANAGED_POINTER), `${JSON.stringify({ dir: staged.id, version: staged.version })}\n`);
|
|
305
|
+
updated.push(MANAGED_POINTER);
|
|
306
|
+
await retire(destDir, previous, staged.id);
|
|
307
|
+
}
|
|
308
|
+
const entry = await fs.readFile(join(srcDir, MANAGED_ENTRY_SCRIPT));
|
|
309
|
+
for (const name of hookNames) {
|
|
310
|
+
const current = await fs.readFile(join(destDir, name)).catch(() => null);
|
|
311
|
+
if (current !== null && current.equals(entry))
|
|
71
312
|
continue;
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
await fs.rename(tmp, join(destDir, f));
|
|
75
|
-
updated.push(f);
|
|
313
|
+
await writeAtomic(join(destDir, name), entry);
|
|
314
|
+
updated.push(name);
|
|
76
315
|
}
|
|
77
316
|
return updated;
|
|
78
317
|
};
|
|
79
|
-
|
|
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
|
+
};
|
|
329
|
+
const pruneManagedVersions = async (destDir, keep) => {
|
|
330
|
+
const versionsDir = join(destDir, MANAGED_VERSIONS_DIR);
|
|
331
|
+
const named = async () => new Set([await readManagedPointer(destDir), await readEntryVersion(destDir)]);
|
|
332
|
+
const current = await named();
|
|
333
|
+
const entries = await fs.readdir(versionsDir).catch(() => []);
|
|
334
|
+
const now = Date.now();
|
|
335
|
+
for (const name of entries) {
|
|
336
|
+
if (current.has(name) || name === keep)
|
|
337
|
+
continue;
|
|
338
|
+
const path = join(versionsDir, name);
|
|
339
|
+
const stat = await fs.stat(path).catch(() => null);
|
|
340
|
+
if (stat === null || now - stat.mtimeMs < RETIRED_GRACE_MS)
|
|
341
|
+
continue;
|
|
342
|
+
if ((await named()).has(name))
|
|
343
|
+
continue;
|
|
344
|
+
await fs.rm(path, { recursive: true, force: true }).catch(() => undefined);
|
|
345
|
+
}
|
|
346
|
+
};
|
|
347
|
+
export const syncManagedHooks = async (matchers, srcDir, destDir, version, nodePath = process.execPath) => {
|
|
348
|
+
const files = hookScriptFiles(matchers);
|
|
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
|
+
];
|
|
354
|
+
const staged = await stageManagedVersion(files, srcDir, destDir, version);
|
|
355
|
+
const updated = await commit(staged);
|
|
356
|
+
if (!(await stagedIntact(destDir, staged))) {
|
|
357
|
+
const again = await stageManagedVersion(files, srcDir, destDir, version);
|
|
358
|
+
updated.push(...(await commit(again)));
|
|
359
|
+
if (!(await stagedIntact(destDir, again))) {
|
|
360
|
+
throw new Error(`could not install a complete set of hook scripts in ${destDir}`);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
updated.push(...(await removeUnreleasedEntryPoints(destDir)));
|
|
364
|
+
await pruneManagedVersions(destDir, staged.id);
|
|
365
|
+
return [
|
|
366
|
+
...new Set([
|
|
367
|
+
...(staged.written ? files.map((f) => `${MANAGED_VERSIONS_DIR}/${staged.id}/${f}`) : []),
|
|
368
|
+
...updated,
|
|
369
|
+
]),
|
|
370
|
+
];
|
|
371
|
+
};
|
|
372
|
+
export const resolveManagedScript = async (script) => {
|
|
373
|
+
const body = await fs.readFile(script, 'utf8').catch(() => null);
|
|
374
|
+
if (body === null)
|
|
375
|
+
return undefined;
|
|
376
|
+
if (!body.includes(MANAGED_ENTRY_MARK))
|
|
377
|
+
return script;
|
|
378
|
+
const dir = await readManagedPointer(dirname(script));
|
|
379
|
+
if (dir === undefined)
|
|
380
|
+
return undefined;
|
|
381
|
+
const target = join(dirname(script), MANAGED_VERSIONS_DIR, dir, basename(script));
|
|
382
|
+
return existsSync(target) ? target : undefined;
|
|
383
|
+
};
|
|
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) => {
|
|
80
421
|
const toolArg = runtimeTool ? ` --tool ${runtimeTool}` : '';
|
|
81
422
|
return plat === 'win32'
|
|
82
423
|
? `node "${scriptPath}" ${MANAGED_BY}@${version}${toolArg}`
|
|
83
424
|
: `f="${scriptPath}"; [ -f "$f" ] && exec node "$f" ${MANAGED_BY}@${version}${toolArg}; exit 0`;
|
|
84
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);
|
|
85
429
|
export const parseManagedByVersion = (command) => {
|
|
86
430
|
const re = new RegExp(`${MANAGED_BY.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')}@([^\\s;]+)`);
|
|
87
431
|
return re.exec(command)?.[1];
|
|
88
432
|
};
|
|
89
433
|
export const scriptPathFromCommand = (command) => {
|
|
90
|
-
const raw = /"([^"]+\.mjs)"/.exec(command)?.[1];
|
|
434
|
+
const raw = /"([^"]+\.(?:mjs|sh))"/.exec(command)?.[1];
|
|
91
435
|
if (raw === undefined)
|
|
92
436
|
return raw;
|
|
93
437
|
const m = /^(?:\$\{HOME\}|\$HOME)(?=\/)/.exec(raw);
|
|
94
438
|
return m ? shellHome() + raw.slice(m[0].length) : raw;
|
|
95
439
|
};
|
|
96
|
-
export const
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
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;
|
|
106
470
|
const groupOwnership = (group) => {
|
|
107
471
|
if (!isPlainObject(group) || !Array.isArray(group.hooks))
|
|
108
472
|
return null;
|
|
@@ -115,28 +479,44 @@ const groupOwnership = (group) => {
|
|
|
115
479
|
}
|
|
116
480
|
return null;
|
|
117
481
|
};
|
|
118
|
-
const ownedGroupInfo = (group, ownership) => {
|
|
482
|
+
const ownedGroupInfo = (group, ownership, event) => {
|
|
119
483
|
const hooks = Array.isArray(group.hooks) ? group.hooks : [];
|
|
120
484
|
const first = hooks.find((h) => isPlainObject(h) && typeof h.command === 'string');
|
|
121
485
|
return {
|
|
122
|
-
|
|
486
|
+
event,
|
|
487
|
+
matcher: typeof group.matcher === 'string' ? group.matcher : NO_MATCHER,
|
|
123
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,
|
|
124
492
|
ownership,
|
|
125
493
|
};
|
|
126
494
|
};
|
|
127
495
|
export const ownedGroupsInDoc = (doc) => {
|
|
128
|
-
if (!isPlainObject(doc) || !isPlainObject(doc.hooks)
|
|
496
|
+
if (!isPlainObject(doc) || !isPlainObject(doc.hooks))
|
|
129
497
|
return [];
|
|
130
|
-
}
|
|
131
498
|
const out = [];
|
|
132
|
-
for (const
|
|
133
|
-
const
|
|
134
|
-
if (
|
|
135
|
-
|
|
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
|
+
}
|
|
136
508
|
}
|
|
137
509
|
return out;
|
|
138
510
|
};
|
|
139
|
-
const
|
|
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;
|
|
140
520
|
export const planMarkers = (doc, groups, remove = () => true) => {
|
|
141
521
|
if (!isPlainObject(doc))
|
|
142
522
|
throw new Error('expected the settings document to be a JSON object');
|
|
@@ -145,38 +525,59 @@ export const planMarkers = (doc, groups, remove = () => true) => {
|
|
|
145
525
|
throw new Error('settings `hooks` is not an object — refusing to modify it');
|
|
146
526
|
}
|
|
147
527
|
const hooks = hooksVal ? { ...hooksVal } : {};
|
|
148
|
-
const
|
|
149
|
-
|
|
150
|
-
|
|
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) });
|
|
151
537
|
}
|
|
152
|
-
const
|
|
538
|
+
const writable = groups.filter((g) => !skipped.has(groupEvent(g)));
|
|
153
539
|
const before = [];
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
if (
|
|
157
|
-
|
|
158
|
-
const
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
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
|
+
}
|
|
175
564
|
}
|
|
176
|
-
const
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
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
|
+
};
|
|
180
581
|
};
|
|
181
582
|
export const prepareMarkersFile = async (path, codec, groups, mode = 0o600, remove) => {
|
|
182
583
|
let body;
|
|
@@ -199,32 +600,61 @@ export const prepareMarkersFile = async (path, codec, groups, mode = 0o600, remo
|
|
|
199
600
|
return { update, plan };
|
|
200
601
|
};
|
|
201
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)';
|
|
202
612
|
const script = scriptPathFromCommand(command);
|
|
203
613
|
const version = parseManagedByVersion(command);
|
|
204
614
|
if (script)
|
|
205
615
|
return `${basename(script)}${version ? ` (@mainwave/cli@${version})` : ''}`;
|
|
206
616
|
return command.length > 60 ? `${command.slice(0, 57)}...` : command;
|
|
207
617
|
};
|
|
618
|
+
const hookSlot = (event, matcher) => matcher === undefined ? `hooks.${event}` : `hooks.${event}[${matcher}]`;
|
|
208
619
|
export const describeMarkersPlan = (plan) => {
|
|
209
620
|
const lines = [];
|
|
210
621
|
for (const g of plan.added) {
|
|
211
622
|
const cmd = g.hooks[0]?.command ?? '';
|
|
212
|
-
|
|
623
|
+
const filter = g.hooks[0]?.if ? ` if ${g.hooks[0].if}` : '';
|
|
624
|
+
lines.push(`+ ${hookSlot(groupEvent(g), g.matcher)}${filter} → ${shortCommand(cmd)}`);
|
|
213
625
|
}
|
|
214
626
|
for (const g of plan.removed) {
|
|
215
627
|
const label = g.ownership === 'internal' ? ' [internal installer]' : '';
|
|
216
|
-
|
|
628
|
+
const matcher = effectiveMatcher(g.matcher) === NO_MATCHER ? undefined : g.matcher;
|
|
629
|
+
lines.push(`- ${hookSlot(g.event, matcher)} → ${shortCommand(g.command)}${label}`);
|
|
217
630
|
}
|
|
218
631
|
if (plan.unchanged > 0)
|
|
219
632
|
lines.push(` (${plan.unchanged} hook groups unchanged)`);
|
|
220
633
|
return lines;
|
|
221
634
|
};
|
|
222
|
-
export const
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
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'),
|
|
226
651
|
];
|
|
227
|
-
const
|
|
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
|
+
};
|
|
228
658
|
const managedLockValue = (v) => {
|
|
229
659
|
if (v === undefined || v === null)
|
|
230
660
|
return undefined;
|
|
@@ -258,7 +688,8 @@ export const scanForMarkers = async (layers) => {
|
|
|
258
688
|
layerId: layer.id,
|
|
259
689
|
label: layer.label ?? layer.id,
|
|
260
690
|
groups: ownedGroupsInDoc(doc),
|
|
261
|
-
|
|
691
|
+
malformedEvents: INSTALLED_HOOK_EVENTS.filter((e) => isPlainObject(doc.hooks) && doc.hooks[e] !== undefined && !Array.isArray(doc.hooks[e])),
|
|
692
|
+
hasPolicyKey: Object.keys(doc).some(isPolicyKey),
|
|
262
693
|
managed: isManagedLayer(layer),
|
|
263
694
|
managedSource: layer.managedSource,
|
|
264
695
|
mergeSources: doc.managedSourcesBehavior === 'merge',
|
|
@@ -309,12 +740,66 @@ export const hooksBlocked = (scans) => {
|
|
|
309
740
|
: undefined);
|
|
310
741
|
return { managed: managedOff, developer, managedOnly };
|
|
311
742
|
};
|
|
312
|
-
export const
|
|
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
|
|
313
770
|
.filter((g) => g.ownership === 'cli')
|
|
314
|
-
.
|
|
315
|
-
.
|
|
316
|
-
|
|
317
|
-
|
|
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() }) => {
|
|
318
803
|
const issues = [];
|
|
319
804
|
const active = new Set(activeManagedScans(scans));
|
|
320
805
|
const inEffect = scans.filter((s, i) => !(s.managed && !active.has(s)) &&
|
|
@@ -324,7 +809,7 @@ export const collectMarkerIssues = async (scans, currentVersion, matchers, skipp
|
|
|
324
809
|
const running = inEffect.filter((s) => (s.managed ? blocked.managed : blocked.developer) === undefined);
|
|
325
810
|
const cli = running.flatMap((s) => s.groups
|
|
326
811
|
.filter((g) => g.ownership === 'cli')
|
|
327
|
-
.map((g) => ({ ...g, managed: s.managed === true })));
|
|
812
|
+
.map((g) => ({ ...g, managed: s.managed === true, path: s.path })));
|
|
328
813
|
const internal = running
|
|
329
814
|
.filter((s) => s.groups.some((g) => g.ownership === 'internal'))
|
|
330
815
|
.map((s) => s.path);
|
|
@@ -332,7 +817,27 @@ export const collectMarkerIssues = async (scans, currentVersion, matchers, skipp
|
|
|
332
817
|
for (const scan of scans.filter((s) => s.managed && !active.has(s) && s.groups.length > 0)) {
|
|
333
818
|
issues.push({
|
|
334
819
|
level: 'info',
|
|
335
|
-
message: `${scan.label ?? scan.layerId} (${scan.path}) installs
|
|
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}`,
|
|
336
841
|
});
|
|
337
842
|
}
|
|
338
843
|
const skippedDelivery = skipped.find(({ scan }) => scan.groups.some((g) => g.ownership === 'cli'));
|
|
@@ -340,18 +845,20 @@ export const collectMarkerIssues = async (scans, currentVersion, matchers, skipp
|
|
|
340
845
|
const { scan, reason } = skippedDelivery;
|
|
341
846
|
issues.push({
|
|
342
847
|
level: 'warn',
|
|
343
|
-
message: `${scan.label ?? scan.layerId} (${scan.path}) delivers the
|
|
848
|
+
message: `${scan.label ?? scan.layerId} (${scan.path}) delivers the Mainwave hooks, but this ` +
|
|
344
849
|
`session doesn't read it: ${reason}. Markers aren't sent from sessions started this way.`,
|
|
345
850
|
});
|
|
346
851
|
return issues;
|
|
347
852
|
}
|
|
348
853
|
if (withCli.length === 0 && !installedInternal) {
|
|
854
|
+
if (noShell)
|
|
855
|
+
return issues;
|
|
349
856
|
issues.push({
|
|
350
857
|
level: 'info',
|
|
351
858
|
message: blocked.managedOnly
|
|
352
859
|
? "Ticket & PR markers are not configured, and your organization's managed settings run only " +
|
|
353
|
-
'hooks they deliver — ask your Claude admin to add the
|
|
354
|
-
:
|
|
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.`,
|
|
355
862
|
});
|
|
356
863
|
return issues;
|
|
357
864
|
}
|
|
@@ -359,38 +866,60 @@ export const collectMarkerIssues = async (scans, currentVersion, matchers, skipp
|
|
|
359
866
|
const count = scan.groups.filter((g) => g.ownership === 'cli').length;
|
|
360
867
|
issues.push({
|
|
361
868
|
level: 'info',
|
|
362
|
-
message: `
|
|
869
|
+
message: `Mainwave hooks (${count}) are installed in ${scan.label ?? scan.layerId}: ${scan.path}.`,
|
|
363
870
|
});
|
|
364
871
|
const reason = scan.managed ? blocked.managed : blocked.developer;
|
|
365
872
|
if (reason !== undefined) {
|
|
366
|
-
const delivered =
|
|
873
|
+
const delivered = managedMarkerDeliveries(scans);
|
|
367
874
|
const covered = blocked.managed === undefined &&
|
|
368
875
|
scan.groups
|
|
369
876
|
.filter((g) => g.ownership === 'cli')
|
|
370
|
-
.every((g) => delivered
|
|
877
|
+
.every((g) => isDelivered(delivered, g.event, g.command));
|
|
371
878
|
issues.push({
|
|
372
879
|
level: 'warn',
|
|
373
|
-
message: `Claude Code doesn't run the
|
|
880
|
+
message: `Claude Code doesn't run the Mainwave hooks in ${scan.path}: ${reason}.` +
|
|
374
881
|
(!scan.managed && blocked.managedOnly
|
|
375
882
|
? covered
|
|
376
|
-
? ' Your managed settings deliver the same
|
|
883
|
+
? ' Your managed settings deliver the same hooks, so this copy is unused.'
|
|
377
884
|
: ' Ask your Claude admin to deliver them through managed settings.'
|
|
378
885
|
: ''),
|
|
379
886
|
});
|
|
380
887
|
}
|
|
381
888
|
}
|
|
382
|
-
const
|
|
383
|
-
const commandsByScript = new Map();
|
|
889
|
+
const commandsByRoute = new Map();
|
|
384
890
|
for (const g of cli) {
|
|
385
|
-
const
|
|
386
|
-
|
|
387
|
-
|
|
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));
|
|
897
|
+
}
|
|
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
|
+
});
|
|
388
915
|
}
|
|
389
|
-
|
|
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) {
|
|
390
919
|
issues.push({
|
|
391
920
|
level: 'warn',
|
|
392
|
-
message: `
|
|
393
|
-
|
|
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 ` +
|
|
394
923
|
'organization delivers them through managed settings, `mainwave-cli install-hooks` removes the ' +
|
|
395
924
|
'user-level copy; remove any project-level copy by hand.',
|
|
396
925
|
});
|
|
@@ -404,61 +933,225 @@ export const collectMarkerIssues = async (scans, currentVersion, matchers, skipp
|
|
|
404
933
|
'and restart Claude Code — or re-run setup on that file.',
|
|
405
934
|
});
|
|
406
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;
|
|
407
940
|
for (const g of cli) {
|
|
408
|
-
const
|
|
409
|
-
if (
|
|
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);
|
|
963
|
+
issues.push({
|
|
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.`,
|
|
969
|
+
});
|
|
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 {
|
|
985
|
+
issues.push({
|
|
986
|
+
level: 'error',
|
|
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.'),
|
|
993
|
+
});
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
continue;
|
|
997
|
+
}
|
|
998
|
+
if (host !== 'codex' && g.async !== true) {
|
|
410
999
|
issues.push({
|
|
411
1000
|
level: 'warn',
|
|
412
|
-
message: `
|
|
413
|
-
|
|
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.'),
|
|
414
1004
|
});
|
|
415
1005
|
}
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
await fs.access(script);
|
|
420
|
-
}
|
|
421
|
-
catch {
|
|
1006
|
+
if (generation === 'bootstrap') {
|
|
1007
|
+
seenRoutes.add(BOOTSTRAP_KEY);
|
|
1008
|
+
if (g.command === installHooksCommand(PAYLOAD_CLI_SPEC)) {
|
|
422
1009
|
issues.push({
|
|
423
|
-
level: '
|
|
424
|
-
message: `
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
(process.platform === 'win32' ? 'in Git Bash run ' : 'run ') +
|
|
428
|
-
`\`${installHooksCommand(version ?? PAYLOAD_CLI_SPEC, { quiet: false })}\`.`
|
|
429
|
-
: '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.'),
|
|
430
1014
|
});
|
|
431
1015
|
}
|
|
432
|
-
|
|
433
|
-
if (expected && expected.matcher !== g.matcher) {
|
|
1016
|
+
if (effectiveMatcher(g.matcher) === NO_MATCHER) {
|
|
434
1017
|
issues.push({
|
|
435
1018
|
level: 'warn',
|
|
436
|
-
message: `
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
: '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.'),
|
|
440
1022
|
});
|
|
441
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
|
+
});
|
|
442
1093
|
}
|
|
443
1094
|
}
|
|
444
1095
|
if (cli.length > 0) {
|
|
445
1096
|
const activity = [];
|
|
446
1097
|
for (const lf of markerLogFiles()) {
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
activity.push(`${lf.label}: last activity ${
|
|
450
|
-
}
|
|
451
|
-
catch {
|
|
452
|
-
}
|
|
1098
|
+
const last = await lastLogActivity(lf);
|
|
1099
|
+
if (last)
|
|
1100
|
+
activity.push(`${lf.label}: last activity ${last.toISOString()}`);
|
|
453
1101
|
}
|
|
454
1102
|
issues.push({
|
|
455
1103
|
level: 'info',
|
|
456
1104
|
message: activity.length > 0
|
|
457
|
-
? `
|
|
458
|
-
: '
|
|
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). ' +
|
|
459
1107
|
'File a ticket or open a PR with `gh pr create`, then check the log and the use case activity.',
|
|
460
1108
|
});
|
|
461
1109
|
}
|
|
462
1110
|
return issues;
|
|
463
1111
|
};
|
|
464
|
-
|
|
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
|
+
};
|