@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.
- package/README.md +169 -42
- package/dist/adapters/claude-code.js +23 -4
- package/dist/adapters/codex-cli.js +1 -1
- package/dist/adapters/cursor.js +4 -2
- package/dist/adapters/index.js +3 -0
- package/dist/adapters/kiro.js +361 -0
- package/dist/core/apply.js +161 -46
- package/dist/core/behaviour-hooks.js +7 -7
- package/dist/core/codecs/kiro-hooks-json.js +76 -0
- package/dist/core/doctor.js +27 -9
- package/dist/core/effective-settings.js +10 -0
- package/dist/core/entry-script.js +90 -0
- package/dist/core/git-bash.js +40 -0
- package/dist/core/install-hooks.js +126 -43
- package/dist/core/interview.js +114 -16
- package/dist/core/markers.js +678 -140
- package/dist/core/remove.js +67 -0
- package/dist/core/settings.js +32 -6
- package/dist/core/skills.js +47 -1
- package/dist/core/status.js +2 -1
- package/dist/core/wizard.js +64 -3
- package/dist/main.js +28 -9
- package/hooks/cursor-otlp.mjs +4 -27
- package/hooks/github-pr-marker.mjs +35 -22
- package/hooks/glab-mr-marker.mjs +795 -0
- package/hooks/jira-ticket-marker.mjs +27 -15
- package/hooks/kiro-otlp.mjs +570 -0
- package/hooks/linear-ticket-marker.mjs +27 -15
- package/hooks/mainwave-hook-node.mjs +42 -0
- package/hooks/mainwave-hook.mjs +301 -0
- package/hooks/marker-core.mjs +368 -41
- 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 +49 -0
- package/hooks/vocabulary.mjs +188 -0
- package/package.json +5 -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-setup/SKILL.md +47 -12
|
@@ -40,7 +40,7 @@ export const collectBehaviourHookIssues = async (cap, currentVersion, scan = sca
|
|
|
40
40
|
if (s.status === 'error') {
|
|
41
41
|
issues.push({
|
|
42
42
|
level: 'warn',
|
|
43
|
-
message:
|
|
43
|
+
message: `${cap.toolName} hooks file could not be parsed: ${s.path} — ${s.error ?? 'invalid JSON'}.`,
|
|
44
44
|
});
|
|
45
45
|
}
|
|
46
46
|
}
|
|
@@ -48,7 +48,7 @@ export const collectBehaviourHookIssues = async (cap, currentVersion, scan = sca
|
|
|
48
48
|
if (present.length === 0) {
|
|
49
49
|
issues.push({
|
|
50
50
|
level: 'info',
|
|
51
|
-
message:
|
|
51
|
+
message: `${cap.toolName} behaviour hook is not registered in any hooks file layer — re-run \`${cap.setupCommand}\` to enable it.`,
|
|
52
52
|
});
|
|
53
53
|
return issues;
|
|
54
54
|
}
|
|
@@ -58,8 +58,8 @@ export const collectBehaviourHookIssues = async (cap, currentVersion, scan = sca
|
|
|
58
58
|
if (version !== undefined && version !== currentVersion) {
|
|
59
59
|
issues.push({
|
|
60
60
|
level: 'warn',
|
|
61
|
-
message:
|
|
62
|
-
|
|
61
|
+
message: `${cap.toolName} hook in ${s.path} was written by @mainwave/cli@${version}; you are running ${currentVersion}. ` +
|
|
62
|
+
`Re-run \`${cap.setupCommand}\` to refresh it — a stale registration can silently stop emitting.`,
|
|
63
63
|
});
|
|
64
64
|
}
|
|
65
65
|
const script = scriptPathFromCommand(command);
|
|
@@ -70,13 +70,13 @@ export const collectBehaviourHookIssues = async (cap, currentVersion, scan = sca
|
|
|
70
70
|
catch {
|
|
71
71
|
issues.push({
|
|
72
72
|
level: 'error',
|
|
73
|
-
message:
|
|
73
|
+
message: `${cap.toolName} hook script is missing: ${script} — the hook no-ops silently (fail-open). Re-run \`${cap.setupCommand}\`.`,
|
|
74
74
|
});
|
|
75
75
|
}
|
|
76
76
|
if (basename(script) !== cap.script) {
|
|
77
77
|
issues.push({
|
|
78
78
|
level: 'warn',
|
|
79
|
-
message:
|
|
79
|
+
message: `${cap.toolName} hook in ${s.path} points at ${basename(script)}, not the expected ${cap.script}. ` +
|
|
80
80
|
'Re-run setup to refresh the registration.',
|
|
81
81
|
});
|
|
82
82
|
}
|
|
@@ -85,7 +85,7 @@ export const collectBehaviourHookIssues = async (cap, currentVersion, scan = sca
|
|
|
85
85
|
if (s.layerId === 'managed') {
|
|
86
86
|
issues.push({
|
|
87
87
|
level: 'info',
|
|
88
|
-
message:
|
|
88
|
+
message: `${cap.toolName} behaviour hook is pinned by managed/enterprise settings (${s.path}) — it applies to every user on this machine and can't be changed without admin access.`,
|
|
89
89
|
});
|
|
90
90
|
}
|
|
91
91
|
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { commandOwnership } from '../markers.js';
|
|
2
|
+
export const KIRO_HOOK_TIMEOUT_SECONDS = 10;
|
|
3
|
+
export const kiroHookName = (trigger) => `Mainwave: ${trigger}`;
|
|
4
|
+
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
5
|
+
const isCommandEntry = (v) => isPlainObject(v) &&
|
|
6
|
+
typeof v.trigger === 'string' &&
|
|
7
|
+
isPlainObject(v.action) &&
|
|
8
|
+
typeof v.action.command === 'string';
|
|
9
|
+
const isOwned = (v) => isCommandEntry(v) && commandOwnership(v.action.command) !== null;
|
|
10
|
+
const triggerOfKey = (key) => key.startsWith('hooks.') ? key.slice('hooks.'.length) : undefined;
|
|
11
|
+
const parse = (body, path) => {
|
|
12
|
+
let parsed;
|
|
13
|
+
try {
|
|
14
|
+
parsed = JSON.parse(body);
|
|
15
|
+
}
|
|
16
|
+
catch (err) {
|
|
17
|
+
throw new Error(`failed to parse ${path} as JSON: ${err.message}`);
|
|
18
|
+
}
|
|
19
|
+
if (!isPlainObject(parsed)) {
|
|
20
|
+
throw new Error(`${path}: expected a JSON object at the top level`);
|
|
21
|
+
}
|
|
22
|
+
return parsed;
|
|
23
|
+
};
|
|
24
|
+
const serialize = (doc) => {
|
|
25
|
+
if (!isPlainObject(doc))
|
|
26
|
+
throw new Error('expected a Kiro hooks document');
|
|
27
|
+
return JSON.stringify(doc, null, 2) + '\n';
|
|
28
|
+
};
|
|
29
|
+
const empty = () => ({ version: 'v1', hooks: [] });
|
|
30
|
+
const hooksOf = (doc) => {
|
|
31
|
+
if (doc.hooks === undefined)
|
|
32
|
+
return [];
|
|
33
|
+
if (!Array.isArray(doc.hooks))
|
|
34
|
+
throw new Error('Kiro hooks file: `hooks` is not an array');
|
|
35
|
+
return doc.hooks;
|
|
36
|
+
};
|
|
37
|
+
const readEnv = (doc) => {
|
|
38
|
+
if (!isPlainObject(doc))
|
|
39
|
+
throw new Error('expected a Kiro hooks document');
|
|
40
|
+
const out = {};
|
|
41
|
+
for (const entry of hooksOf(doc)) {
|
|
42
|
+
if (isOwned(entry) && !(`hooks.${entry.trigger}` in out)) {
|
|
43
|
+
out[`hooks.${entry.trigger}`] = entry.action.command;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return out;
|
|
47
|
+
};
|
|
48
|
+
const applyEnv = (doc, newEnv, _managedKeys) => {
|
|
49
|
+
const base = isPlainObject(doc) ? structuredClone(doc) : {};
|
|
50
|
+
base.version = typeof base.version === 'string' ? base.version : 'v1';
|
|
51
|
+
const kept = hooksOf(base).filter((e) => !isOwned(e));
|
|
52
|
+
const ours = Object.entries(newEnv).flatMap(([key, command]) => {
|
|
53
|
+
const trigger = triggerOfKey(key);
|
|
54
|
+
return trigger === undefined
|
|
55
|
+
? []
|
|
56
|
+
: [
|
|
57
|
+
{
|
|
58
|
+
name: kiroHookName(trigger),
|
|
59
|
+
trigger,
|
|
60
|
+
action: { type: 'command', command },
|
|
61
|
+
timeout: KIRO_HOOK_TIMEOUT_SECONDS,
|
|
62
|
+
enabled: true,
|
|
63
|
+
},
|
|
64
|
+
];
|
|
65
|
+
});
|
|
66
|
+
base.hooks = [...kept, ...ours];
|
|
67
|
+
return base;
|
|
68
|
+
};
|
|
69
|
+
export const kiroHooksJsonCodec = {
|
|
70
|
+
format: 'json',
|
|
71
|
+
parse,
|
|
72
|
+
serialize,
|
|
73
|
+
empty,
|
|
74
|
+
readEnv,
|
|
75
|
+
applyEnv,
|
|
76
|
+
};
|
package/dist/core/doctor.js
CHANGED
|
@@ -7,9 +7,9 @@ import { ValidateError } from './errors.js';
|
|
|
7
7
|
import { color, maskForDisplay } from './format.js';
|
|
8
8
|
import { collectBehaviourHookIssues } from './behaviour-hooks.js';
|
|
9
9
|
import { isManagedIdentityConfig, isManagedLayer, policyState } from './layer-policy.js';
|
|
10
|
-
import { collectMarkerIssues, readPackagedMatchers, scanForMarkers } from './markers.js';
|
|
10
|
+
import { collectMarkerIssues, DEFAULT_MARKER_TOOL, managedHooksDir, matchersForTool, readPackagedMatchers, scanForMarkers, } from './markers.js';
|
|
11
11
|
import { readExistingEnv } from './settings.js';
|
|
12
|
-
import { teamUcidStanding } from './apply.js';
|
|
12
|
+
import { hookShellMissingFor, teamUcidStanding } from './apply.js';
|
|
13
13
|
import { adapterEffective, primaryCarries } from './status.js';
|
|
14
14
|
import { readSettings } from './store.js';
|
|
15
15
|
import { emitJson } from './ui.js';
|
|
@@ -72,7 +72,7 @@ const renderEffectiveEnv = (effective, adapter) => {
|
|
|
72
72
|
};
|
|
73
73
|
const collectEnvFileTargets = (adapter) => {
|
|
74
74
|
const targets = [];
|
|
75
|
-
if (adapter.codec.format === 'env') {
|
|
75
|
+
if (adapter.codec.format === 'env' && !adapter.hookReadsConfigFile) {
|
|
76
76
|
targets.push({
|
|
77
77
|
label: 'Primary',
|
|
78
78
|
path: adapter.paths.global,
|
|
@@ -463,6 +463,28 @@ const renderChecks = (issues) => {
|
|
|
463
463
|
console.log(`${prefix} ${issue.message}`);
|
|
464
464
|
}
|
|
465
465
|
};
|
|
466
|
+
const markerMatchers = (adapter, matchers) => matchersForTool(matchers, adapter.markers?.runtimeTool ?? DEFAULT_MARKER_TOOL);
|
|
467
|
+
const hookChoices = async (adapter) => {
|
|
468
|
+
const { hooks } = await readSettings();
|
|
469
|
+
return { markers: hooks?.markers?.[adapter.name] ?? true };
|
|
470
|
+
};
|
|
471
|
+
const markerLayers = async (adapter) => {
|
|
472
|
+
const hooksFile = adapter.markers?.hooksFile;
|
|
473
|
+
if (hooksFile === undefined)
|
|
474
|
+
return activeHierarchy(adapter);
|
|
475
|
+
return [
|
|
476
|
+
...(hooksFile.localPath
|
|
477
|
+
? [{ id: 'project', label: 'Project hooks file', path: hooksFile.localPath, kind: 'file' }]
|
|
478
|
+
: []),
|
|
479
|
+
{ id: 'user', label: 'User hooks file', path: hooksFile.path, kind: 'file' },
|
|
480
|
+
];
|
|
481
|
+
};
|
|
482
|
+
const markerIssuesFor = async (adapter, effective) => adapter.markers
|
|
483
|
+
? collectMarkerIssues(await scanForMarkers(await markerLayers(adapter)), VERSION, markerMatchers(adapter, await readPackagedMatchers()), await skippedMarkerScans(effective), await hookChoices(adapter), adapter.markers.runtimeTool ?? DEFAULT_MARKER_TOOL, {
|
|
484
|
+
managedDir: managedHooksDir(),
|
|
485
|
+
hookShellMissing: await hookShellMissingFor(adapter, () => flattenEffective(effective)),
|
|
486
|
+
})
|
|
487
|
+
: [];
|
|
466
488
|
const skippedMarkerScans = async (effective) => {
|
|
467
489
|
const out = [];
|
|
468
490
|
for (const { layer, reason } of effective.skipped ?? []) {
|
|
@@ -536,9 +558,7 @@ export const runDoctor = async (adapter, options = {}) => {
|
|
|
536
558
|
console.log();
|
|
537
559
|
const issues = collectIssues(effective, adapter, await attributionContext(adapter, effective));
|
|
538
560
|
const shellEnvIssues = await checkShellEnv(adapter);
|
|
539
|
-
const markerIssues = adapter
|
|
540
|
-
? await collectMarkerIssues(await scanForMarkers(await activeHierarchy(adapter)), VERSION, await readPackagedMatchers(), await skippedMarkerScans(effective))
|
|
541
|
-
: [];
|
|
561
|
+
const markerIssues = await markerIssuesFor(adapter, effective);
|
|
542
562
|
const behaviourHookIssues = adapter.behaviourHooks
|
|
543
563
|
? await collectBehaviourHookIssues(adapter.behaviourHooks, VERSION)
|
|
544
564
|
: [];
|
|
@@ -564,9 +584,7 @@ const runDoctorJson = async (adapter, options) => {
|
|
|
564
584
|
const issues = [
|
|
565
585
|
...collectIssues(effective, adapter, await attributionContext(adapter, effective)),
|
|
566
586
|
...(await checkShellEnv(adapter)),
|
|
567
|
-
...(adapter
|
|
568
|
-
? await collectMarkerIssues(await scanForMarkers(await activeHierarchy(adapter)), VERSION, await readPackagedMatchers(), await skippedMarkerScans(effective))
|
|
569
|
-
: []),
|
|
587
|
+
...(await markerIssuesFor(adapter, effective)),
|
|
570
588
|
...(adapter.behaviourHooks
|
|
571
589
|
? await collectBehaviourHookIssues(adapter.behaviourHooks, VERSION)
|
|
572
590
|
: []),
|
|
@@ -109,6 +109,16 @@ export const flattenEffective = (effective) => {
|
|
|
109
109
|
}
|
|
110
110
|
return out;
|
|
111
111
|
};
|
|
112
|
+
export const effectiveEnv = async (adapter, userEnv) => {
|
|
113
|
+
const effective = await computeEffective(adapter);
|
|
114
|
+
if (userEnv === undefined)
|
|
115
|
+
return flattenEffective(effective);
|
|
116
|
+
const written = resolve(adapter.paths.global);
|
|
117
|
+
const scans = effective.scans.map((scan) => resolve(scan.path) === written
|
|
118
|
+
? { ...scan, status: 'present', env: { ...userEnv } }
|
|
119
|
+
: scan);
|
|
120
|
+
return flattenEffective(effectiveFrom(adapter, scans));
|
|
121
|
+
};
|
|
112
122
|
export const nativeIdentityReason = async (adapter, effective) => {
|
|
113
123
|
if (!adapter.nativeIdentityAbsent)
|
|
114
124
|
return undefined;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
export const HOOK_ENTRY_SCRIPT = 'mainwave-hook.sh';
|
|
2
|
+
export const HOOK_DISPATCHER_SCRIPT = 'mainwave-hook.mjs';
|
|
3
|
+
export const HOOK_NODE_ENTRY_SCRIPT = 'mainwave-hook-node.mjs';
|
|
4
|
+
export const ORG_DELIVERED_MARK = 'org-delivered';
|
|
5
|
+
export const HOOK_ENTRY_MARK = 'mainwave hook entry v2';
|
|
6
|
+
export const ENTRY_HOSTS = ['claude-code', 'codex'];
|
|
7
|
+
export const CODEX_BASH_FILTER = ['*pr*create*', '*mr*create*', '*mr*new*', '*merge_requests*'];
|
|
8
|
+
export const entryRouteKey = ({ host, event, route }) => `${host}/${event}/${route ?? ''}`;
|
|
9
|
+
const SAFE_TOKEN = /^[A-Za-z0-9._+-]+$/;
|
|
10
|
+
const shQuote = (value) => `'${value.replace(/'/g, `'\\''`)}'`;
|
|
11
|
+
export const renderHookEntry = ({ versionId, version, nodePath, routes, }) => {
|
|
12
|
+
for (const r of routes) {
|
|
13
|
+
for (const part of [r.host, r.event, r.route ?? 'x', r.optOut]) {
|
|
14
|
+
if (!SAFE_TOKEN.test(part))
|
|
15
|
+
throw new Error(`hook entry: unsafe route token ${part}`);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
if (!SAFE_TOKEN.test(versionId))
|
|
19
|
+
throw new Error(`hook entry: unsafe release id ${versionId}`);
|
|
20
|
+
const byOptOut = new Map();
|
|
21
|
+
for (const r of routes) {
|
|
22
|
+
byOptOut.set(r.optOut, [...(byOptOut.get(r.optOut) ?? []), entryRouteKey(r)]);
|
|
23
|
+
}
|
|
24
|
+
const arms = [...byOptOut].map(([optOut, keys]) => ` ${keys.join('|')}) k=${optOut} ;;`);
|
|
25
|
+
const codexBash = routes.some((r) => entryRouteKey(r) === 'codex/PostToolUse/bash');
|
|
26
|
+
const lines = [
|
|
27
|
+
'#!/bin/sh',
|
|
28
|
+
`# ${HOOK_ENTRY_MARK}`,
|
|
29
|
+
'#',
|
|
30
|
+
`# Generated by mainwave-cli ${version.replace(/[^A-Za-z0-9._+-]/g, '_')}; replaced whole by the next`,
|
|
31
|
+
'# release. Every Mainwave hook group runs it as',
|
|
32
|
+
'# sh mainwave-hook.sh <host> <Event> [<route>]',
|
|
33
|
+
"# and it runs that release's Node dispatcher. It prints nothing, never",
|
|
34
|
+
'# blocks, and exits 0.',
|
|
35
|
+
'main() {',
|
|
36
|
+
' exec >/dev/null 2>&1',
|
|
37
|
+
` V=${shQuote(versionId)}`,
|
|
38
|
+
` N=${shQuote(nodePath)}`,
|
|
39
|
+
' d=${0%/*}',
|
|
40
|
+
` js="$d/versions/$V/${HOOK_DISPATCHER_SCRIPT}"`,
|
|
41
|
+
' [ -f "$js" ] || return 0',
|
|
42
|
+
' r=$3',
|
|
43
|
+
' case "$r" in -*) r= ;; esac',
|
|
44
|
+
' k=',
|
|
45
|
+
' case "$1/$2/$r" in',
|
|
46
|
+
...arms,
|
|
47
|
+
' *) return 0 ;;',
|
|
48
|
+
' esac',
|
|
49
|
+
` [ -f "\${d%/*}/off/$1/$k" ] && [ ! -f "$d/${ORG_DELIVERED_MARK}" ] && return 0`,
|
|
50
|
+
' n=node',
|
|
51
|
+
' command -v node >/dev/null 2>&1 || n=$N',
|
|
52
|
+
...(codexBash
|
|
53
|
+
? [
|
|
54
|
+
' if [ "$1/$2/$r" = codex/PostToolUse/bash ]; then',
|
|
55
|
+
' in=$(cat)',
|
|
56
|
+
' case "$in" in',
|
|
57
|
+
` ${CODEX_BASH_FILTER.join('|')}) ;;`,
|
|
58
|
+
' *) return 0 ;;',
|
|
59
|
+
' esac',
|
|
60
|
+
' printf \'%s\' "$in" | "$n" "$js" "$@"',
|
|
61
|
+
' return 0',
|
|
62
|
+
' fi',
|
|
63
|
+
]
|
|
64
|
+
: []),
|
|
65
|
+
' "$n" "$js" "$@"',
|
|
66
|
+
' return 0',
|
|
67
|
+
'}',
|
|
68
|
+
'main "$@"',
|
|
69
|
+
'exit 0',
|
|
70
|
+
];
|
|
71
|
+
return `${lines.join('\n')}\n`;
|
|
72
|
+
};
|
|
73
|
+
export const entryVersionId = (text) => {
|
|
74
|
+
if (!text.includes(HOOK_ENTRY_MARK))
|
|
75
|
+
return undefined;
|
|
76
|
+
const m = /^\s*V='([A-Za-z0-9._+-]+)'$/m.exec(text);
|
|
77
|
+
return m?.[1];
|
|
78
|
+
};
|
|
79
|
+
export const entryCommand = (host, event, route) => `f="$HOME/.mainwave/hooks/managed/${HOOK_ENTRY_SCRIPT}"; [ -f "$f" ] && exec sh "$f" ${host} ${event}${route === undefined ? '' : ` ${route}`}; exit 0`;
|
|
80
|
+
export const nodeEntryCommand = (nodeEntryPath, host, event, route) => `(if exist "${nodeEntryPath}" node "${nodeEntryPath}" ${host} ${event}${route === undefined ? '' : ` ${route}`}) & exit /b 0`;
|
|
81
|
+
export const parseEntryCommand = (command) => {
|
|
82
|
+
const m = new RegExp(`${HOOK_ENTRY_SCRIPT.replace('.', '\\.')}"; \\[ -f "\\$f" \\] && exec sh "\\$f" ([A-Za-z0-9_-]+) ([A-Za-z]+)(?: ([A-Za-z0-9_-]+))?; exit 0`).exec(command);
|
|
83
|
+
if (!m) {
|
|
84
|
+
const loose = new RegExp(`(?:${HOOK_ENTRY_SCRIPT.replace('.', '\\.')}|${HOOK_NODE_ENTRY_SCRIPT.replace('.', '\\.')})"?\\s+([A-Za-z0-9_-]+)\\s+([A-Za-z]+)(?:\\s+([A-Za-z0-9_-]+))?`).exec(command);
|
|
85
|
+
if (!loose)
|
|
86
|
+
return undefined;
|
|
87
|
+
return { host: loose[1], event: loose[2], ...(loose[3] ? { route: loose[3] } : {}) };
|
|
88
|
+
}
|
|
89
|
+
return { host: m[1], event: m[2], ...(m[3] ? { route: m[3] } : {}) };
|
|
90
|
+
};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { win32 } from 'node:path';
|
|
3
|
+
const BASH_NAMES = new Set(['bash.exe', 'sh.exe', 'bash', 'sh']);
|
|
4
|
+
const DEFAULT_GIT_BASH = [
|
|
5
|
+
'C:\\Program Files\\Git\\bin\\bash.exe',
|
|
6
|
+
'C:\\Program Files (x86)\\Git\\bin\\bash.exe',
|
|
7
|
+
];
|
|
8
|
+
const gitOnPath = (env, exists) => {
|
|
9
|
+
const key = Object.keys(env).find((k) => k.toUpperCase() === 'PATH');
|
|
10
|
+
for (const dir of (key ? (env[key] ?? '') : '').split(win32.delimiter)) {
|
|
11
|
+
if (!dir)
|
|
12
|
+
continue;
|
|
13
|
+
for (const name of ['git.exe', 'git.cmd', 'git']) {
|
|
14
|
+
const candidate = win32.join(dir, name);
|
|
15
|
+
if (exists(candidate))
|
|
16
|
+
return candidate;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
return undefined;
|
|
20
|
+
};
|
|
21
|
+
export const findGitBash = (env, exists = existsSync) => {
|
|
22
|
+
const configured = env.CLAUDE_CODE_GIT_BASH_PATH?.trim();
|
|
23
|
+
if (configured &&
|
|
24
|
+
BASH_NAMES.has(win32.basename(configured).toLowerCase()) &&
|
|
25
|
+
exists(configured)) {
|
|
26
|
+
return configured;
|
|
27
|
+
}
|
|
28
|
+
const installed = DEFAULT_GIT_BASH.find(exists);
|
|
29
|
+
if (installed !== undefined)
|
|
30
|
+
return installed;
|
|
31
|
+
const git = gitOnPath(env, exists);
|
|
32
|
+
if (git === undefined)
|
|
33
|
+
return undefined;
|
|
34
|
+
const bash = win32.join(git, '..', '..', 'bin', 'bash.exe');
|
|
35
|
+
return exists(bash) ? bash : undefined;
|
|
36
|
+
};
|
|
37
|
+
export const claudeHookShellMissing = (env, plat = process.platform, exists = existsSync) => plat === 'win32' && findGitBash(env, exists) === undefined;
|
|
38
|
+
export const GIT_BASH_MISSING_REASON = "Git Bash isn't installed, so Claude Code runs hook commands in PowerShell, where the Mainwave hook commands can't run";
|
|
39
|
+
export const GIT_BASH_FIX = 'Install Git for Windows (https://git-scm.com/downloads/win), or set CLAUDE_CODE_GIT_BASH_PATH to your bash.exe, ' +
|
|
40
|
+
'then re-run `mainwave-cli setup claude-code`.';
|
|
@@ -1,58 +1,72 @@
|
|
|
1
|
-
import { basename } from 'node:path';
|
|
1
|
+
import { basename, dirname, isAbsolute, resolve } from 'node:path';
|
|
2
|
+
import { claudeConfigDir } from '../adapters/claude-code.js';
|
|
2
3
|
import { hasPath } from './detect.js';
|
|
3
4
|
import { activeHierarchy } from './effective-settings.js';
|
|
4
5
|
import { isManagedLayer } from './layer-policy.js';
|
|
5
|
-
import {
|
|
6
|
+
import { bootstrapGroup, buildHookGroups, DEFAULT_MARKER_TOOL, groupEvent, isBootstrapCommand, isDelivered, managedDeliversEntry, managedHooksDir, managedMarkerDeliveries, matchersForTool, packagedHooksDir, prepareMarkersFile, readPackagedMatchers, scanForMarkers, syncManagedHooks, syncOrgDelivered, userHookGroups, } from './markers.js';
|
|
6
7
|
import { applyUpdate } from './settings.js';
|
|
8
|
+
import { readSettings } from './store.js';
|
|
7
9
|
import { VERSION } from './version.js';
|
|
8
|
-
const
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
},
|
|
21
|
-
],
|
|
22
|
-
PostToolUse: matchers.map((m) => ({
|
|
23
|
-
matcher: m.matcher,
|
|
24
|
-
hooks: [
|
|
25
|
-
{
|
|
26
|
-
type: 'command',
|
|
27
|
-
command: buildHookCommand(`${PAYLOAD_HOOKS_DIR}/${m.hook}`, PAYLOAD_CLI_SPEC, 'darwin'),
|
|
28
|
-
timeout: 5,
|
|
29
|
-
},
|
|
30
|
-
],
|
|
31
|
-
})),
|
|
32
|
-
});
|
|
10
|
+
export const PAYLOAD_EVENTS = [
|
|
11
|
+
'SessionStart',
|
|
12
|
+
'UserPromptSubmit',
|
|
13
|
+
'PostToolUse',
|
|
14
|
+
'StopFailure',
|
|
15
|
+
];
|
|
16
|
+
const payloadGroup = ({ event: _event, ...group }) => group;
|
|
17
|
+
export const managedPayloadHooks = (matchers) => {
|
|
18
|
+
const groups = [bootstrapGroup(), ...buildHookGroups(matchersForTool(matchers), 'claude-code')];
|
|
19
|
+
const under = (event) => groups.filter((g) => groupEvent(g) === event).map(payloadGroup);
|
|
20
|
+
return Object.fromEntries(PAYLOAD_EVENTS.map((e) => [e, under(e)]));
|
|
21
|
+
};
|
|
33
22
|
const defaultPaths = () => ({
|
|
34
23
|
srcDir: packagedHooksDir(),
|
|
35
24
|
destDir: managedHooksDir(),
|
|
36
25
|
});
|
|
37
26
|
export const installHooks = async (adapter, paths = defaultPaths()) => {
|
|
38
|
-
const
|
|
39
|
-
const updated = await syncManagedHooks(
|
|
40
|
-
|
|
41
|
-
|
|
27
|
+
const all = await readPackagedMatchers(paths.srcDir);
|
|
28
|
+
const updated = await syncManagedHooks(all, paths.srcDir, paths.destDir, paths.version ?? VERSION, paths.nodePath);
|
|
29
|
+
if (adapter === undefined) {
|
|
30
|
+
return {
|
|
31
|
+
updated,
|
|
32
|
+
destDir: paths.destDir,
|
|
33
|
+
managedDelivers: false,
|
|
34
|
+
removedFromUser: 0,
|
|
35
|
+
addedToUser: 0,
|
|
36
|
+
userSettings: undefined,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
const scans = await scanForMarkers((await activeHierarchy(adapter)).filter(isManagedLayer));
|
|
40
|
+
const delivered = managedMarkerDeliveries(scans);
|
|
41
|
+
await syncOrgDelivered(managedDeliversEntry(scans), dirname(adapter.paths.global), paths.destDir);
|
|
42
42
|
const managedDelivers = delivered.size > 0;
|
|
43
|
+
const stored = paths.stored ?? (await readSettings().catch(() => ({}))).hooks ?? {};
|
|
43
44
|
const userSettings = adapter.paths.global;
|
|
45
|
+
const disclosed = stored.events?.[adapter.name]?.[userSettings];
|
|
44
46
|
let removedFromUser = 0;
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
47
|
+
let addedToUser = 0;
|
|
48
|
+
if ((managedDelivers || disclosed !== undefined) && hasPath(userSettings)) {
|
|
49
|
+
const groups = disclosed === undefined
|
|
50
|
+
? []
|
|
51
|
+
: userHookGroups(matchersForTool(all, DEFAULT_MARKER_TOOL), { markers: stored.markers?.[adapter.name] ?? true }, delivered, DEFAULT_MARKER_TOOL).filter((g) => disclosed.includes(groupEvent(g)));
|
|
52
|
+
const { update, plan } = await prepareMarkersFile(userSettings, adapter.codec, groups, 0o600, (ownership, group) => ownership === 'cli' &&
|
|
53
|
+
((!isBootstrapCommand(group.command) &&
|
|
54
|
+
isDelivered(delivered, group.event, group.command)) ||
|
|
55
|
+
(disclosed?.includes(group.event) ?? false)));
|
|
50
56
|
if (plan.changed) {
|
|
51
57
|
await applyUpdate(update);
|
|
52
58
|
removedFromUser = plan.removed.length;
|
|
59
|
+
addedToUser = plan.added.length;
|
|
53
60
|
}
|
|
54
61
|
}
|
|
55
|
-
return {
|
|
62
|
+
return {
|
|
63
|
+
updated,
|
|
64
|
+
destDir: paths.destDir,
|
|
65
|
+
managedDelivers,
|
|
66
|
+
removedFromUser,
|
|
67
|
+
addedToUser,
|
|
68
|
+
userSettings,
|
|
69
|
+
};
|
|
56
70
|
};
|
|
57
71
|
export const runInstallHooks = async (adapter, options = {}, paths) => {
|
|
58
72
|
let result;
|
|
@@ -68,14 +82,83 @@ export const runInstallHooks = async (adapter, options = {}, paths) => {
|
|
|
68
82
|
return 0;
|
|
69
83
|
const dest = result.destDir;
|
|
70
84
|
console.log(result.updated.length > 0
|
|
71
|
-
? `Installed
|
|
72
|
-
: `
|
|
73
|
-
if (result.
|
|
74
|
-
console.log(
|
|
75
|
-
'
|
|
85
|
+
? `Installed Mainwave hook scripts in ${dest}: ${result.updated.join(', ')}`
|
|
86
|
+
: `Mainwave hook scripts in ${dest} are already current.`);
|
|
87
|
+
if (result.userSettings === undefined) {
|
|
88
|
+
console.log("CLAUDE_CODE_SUBPROCESS_ENV_SCRUB hid this session's CLAUDE_CONFIG_DIR and the hook input " +
|
|
89
|
+
"didn't name it, so no Claude config dir's settings were changed.");
|
|
90
|
+
}
|
|
91
|
+
else if (result.removedFromUser > 0 || result.addedToUser > 0) {
|
|
92
|
+
console.log(`Updated the Mainwave hooks in ${result.userSettings}` +
|
|
93
|
+
(result.removedFromUser > 0 && result.managedDelivers
|
|
94
|
+
? ' — your managed settings deliver some of them now.'
|
|
95
|
+
: '.'));
|
|
76
96
|
}
|
|
77
97
|
else if (!result.managedDelivers) {
|
|
78
|
-
console.log('No managed settings deliver the
|
|
98
|
+
console.log('No managed settings deliver the Mainwave hooks, so your user settings were left as they are.');
|
|
79
99
|
}
|
|
80
100
|
return 0;
|
|
81
101
|
};
|
|
102
|
+
const HOOK_INPUT_CAP = 1024 * 1024;
|
|
103
|
+
const HOOK_INPUT_WAIT_MS = 2000;
|
|
104
|
+
const TRUTHY = new Set(['1', 'true', 'yes', 'on']);
|
|
105
|
+
export const readHookInput = (stream, cap = HOOK_INPUT_CAP, ms = HOOK_INPUT_WAIT_MS) => new Promise((done) => {
|
|
106
|
+
if (stream.isTTY) {
|
|
107
|
+
done(undefined);
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
const chunks = [];
|
|
111
|
+
let size = 0;
|
|
112
|
+
let settled = false;
|
|
113
|
+
const finish = (value, stop = false) => {
|
|
114
|
+
if (settled)
|
|
115
|
+
return;
|
|
116
|
+
settled = true;
|
|
117
|
+
clearTimeout(timer);
|
|
118
|
+
stream.off('data', onData);
|
|
119
|
+
stream.off('end', onEnd);
|
|
120
|
+
stream.off('error', onError);
|
|
121
|
+
if (stop)
|
|
122
|
+
stream.destroy();
|
|
123
|
+
done(value);
|
|
124
|
+
};
|
|
125
|
+
const onData = (chunk) => {
|
|
126
|
+
const buf = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
|
|
127
|
+
size += buf.length;
|
|
128
|
+
if (size > cap)
|
|
129
|
+
finish(undefined, true);
|
|
130
|
+
else
|
|
131
|
+
chunks.push(buf);
|
|
132
|
+
};
|
|
133
|
+
const onEnd = () => {
|
|
134
|
+
try {
|
|
135
|
+
finish(JSON.parse(Buffer.concat(chunks).toString('utf8')));
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
finish(undefined);
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
const onError = () => finish(undefined);
|
|
142
|
+
const timer = setTimeout(() => finish(undefined, true), ms);
|
|
143
|
+
stream.on('data', onData);
|
|
144
|
+
stream.on('end', onEnd);
|
|
145
|
+
stream.on('error', onError);
|
|
146
|
+
});
|
|
147
|
+
export const configDirFromTranscript = (transcriptPath) => {
|
|
148
|
+
if (typeof transcriptPath !== 'string' || !isAbsolute(transcriptPath))
|
|
149
|
+
return undefined;
|
|
150
|
+
if (!transcriptPath.endsWith('.jsonl'))
|
|
151
|
+
return undefined;
|
|
152
|
+
const projects = dirname(dirname(transcriptPath));
|
|
153
|
+
return basename(projects) === 'projects' ? resolve(dirname(projects)) : undefined;
|
|
154
|
+
};
|
|
155
|
+
export const sessionConfigDir = async (env = process.env, stdin = process.stdin) => {
|
|
156
|
+
const scrubbed = TRUTHY.has((env.CLAUDE_CODE_SUBPROCESS_ENV_SCRUB ?? '').trim().toLowerCase());
|
|
157
|
+
if (!scrubbed || env.CLAUDE_CONFIG_DIR?.trim() || stdin.isTTY)
|
|
158
|
+
return claudeConfigDir(env);
|
|
159
|
+
const input = await readHookInput(stdin);
|
|
160
|
+
const transcript = input !== null && typeof input === 'object'
|
|
161
|
+
? input.transcript_path
|
|
162
|
+
: undefined;
|
|
163
|
+
return configDirFromTranscript(transcript);
|
|
164
|
+
};
|