@mainwave/cli 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +169 -42
  2. package/dist/adapters/claude-code.js +23 -4
  3. package/dist/adapters/codex-cli.js +1 -1
  4. package/dist/adapters/cursor.js +4 -2
  5. package/dist/adapters/index.js +3 -0
  6. package/dist/adapters/kiro.js +361 -0
  7. package/dist/core/apply.js +161 -46
  8. package/dist/core/behaviour-hooks.js +7 -7
  9. package/dist/core/codecs/kiro-hooks-json.js +76 -0
  10. package/dist/core/doctor.js +27 -9
  11. package/dist/core/effective-settings.js +10 -0
  12. package/dist/core/entry-script.js +90 -0
  13. package/dist/core/git-bash.js +40 -0
  14. package/dist/core/install-hooks.js +126 -43
  15. package/dist/core/interview.js +114 -16
  16. package/dist/core/markers.js +678 -140
  17. package/dist/core/remove.js +67 -0
  18. package/dist/core/settings.js +32 -6
  19. package/dist/core/skills.js +47 -1
  20. package/dist/core/status.js +2 -1
  21. package/dist/core/wizard.js +64 -3
  22. package/dist/main.js +28 -9
  23. package/hooks/cursor-otlp.mjs +4 -27
  24. package/hooks/github-pr-marker.mjs +35 -22
  25. package/hooks/glab-mr-marker.mjs +795 -0
  26. package/hooks/jira-ticket-marker.mjs +27 -15
  27. package/hooks/kiro-otlp.mjs +570 -0
  28. package/hooks/linear-ticket-marker.mjs +27 -15
  29. package/hooks/mainwave-hook-node.mjs +42 -0
  30. package/hooks/mainwave-hook.mjs +301 -0
  31. package/hooks/marker-core.mjs +368 -41
  32. package/hooks/matchers.json +82 -6
  33. package/hooks/plan-snapshot.mjs +529 -0
  34. package/hooks/stop-failure.mjs +43 -0
  35. package/hooks/vocabulary.d.mts +49 -0
  36. package/hooks/vocabulary.mjs +188 -0
  37. package/package.json +5 -5
  38. package/skills/mainwave-instrument/SKILL.md +21 -7
  39. package/skills/mainwave-instrument/reference/api.md +29 -10
  40. package/skills/mainwave-instrument/reference/frameworks.md +3 -3
  41. package/skills/mainwave-instrument/reference/troubleshooting.md +12 -5
  42. package/skills/mainwave-setup/SKILL.md +47 -12
@@ -1,5 +1,8 @@
1
1
  #!/usr/bin/env node
2
- // Claude Code PostToolUse hook for Linear issue saves.
2
+ // The Linear ticket marker: a PostToolUse feature of the Mainwave hook
3
+ // dispatcher (mainwave-hook.mjs) for Linear issue saves. It also still runs on
4
+ // its own (§ the main at the bottom), because hook settings pasted before the
5
+ // dispatcher name this file.
3
6
  //
4
7
  // Matches any Linear MCP's issue-save tool. The tool name is `save_issue` on both
5
8
  // integrations seen so far; what differs is the server prefix (`mcp__linear__` vs
@@ -70,7 +73,7 @@ export {
70
73
  toolOutput,
71
74
  } from './marker-core.mjs'
72
75
 
73
- const log = markerLog(process.argv, '.mainwave-ticket-marker.log')
76
+ const LOG_NAME = 'ticket-marker.log'
74
77
 
75
78
  // A source tag the collector does NOT classify as a coding agent, and a service
76
79
  // name outside its coding-agent `service.name` allow-list, so the marker lands
@@ -240,15 +243,13 @@ export const buildTracePayload = ({
240
243
  nowNs,
241
244
  })
242
245
 
243
- const main = async () => {
244
- let payload
245
- try {
246
- payload = JSON.parse(await readStdin())
247
- } catch {
248
- log('skip: no parseable hook payload')
249
- return
250
- }
251
-
246
+ /**
247
+ * The feature: one marker span for the saved issue, or a logged skip when the
248
+ * output names none. `ctx.argv` carries the hook command's flags (and
249
+ * `--tool <host>` under the dispatcher); `ctx.emit` posts.
250
+ */
251
+ export const handle = async (payload, { argv = process.argv, emit = emitMarker } = {}) => {
252
+ const log = markerLog(argv, LOG_NAME)
252
253
  const output = toolOutput(payload)
253
254
  const issueKey = extractIssueKey(output)
254
255
  if (!issueKey) {
@@ -260,8 +261,8 @@ const main = async () => {
260
261
  const op = detectOp(payload.tool_name, payload.tool_input)
261
262
 
262
263
  const projectDir = markerProjectDir(payload)
263
- const tool = markerTool(process.argv)
264
- const managedDir = markerManagedDir(process.argv)
264
+ const tool = markerTool(argv)
265
+ const managedDir = markerManagedDir(argv)
265
266
  const env = markerSessionEnv(tool, payload)
266
267
  const { endpoint, bearer, resourceAttrs } = loadOtelConfig(projectDir, env, tool, managedDir)
267
268
  log(
@@ -292,7 +293,18 @@ const main = async () => {
292
293
  callContext: markerCallContext(tool, payload),
293
294
  nowNs: BigInt(Date.now()) * 1_000_000n,
294
295
  })
295
- await emitMarker({ endpoint, bearer, body, label: issueKey, log })
296
+ await emit({ endpoint, bearer, body, label: issueKey, log })
297
+ }
298
+
299
+ const main = async () => {
300
+ let payload
301
+ try {
302
+ payload = JSON.parse(await readStdin())
303
+ } catch {
304
+ markerLog(process.argv, LOG_NAME)('skip: no parseable hook payload')
305
+ return
306
+ }
307
+ await handle(payload)
296
308
  }
297
309
 
298
310
  // Run the IO path only when executed directly, so tests can import the pure fns.
@@ -300,6 +312,6 @@ const main = async () => {
300
312
  // file URL (e.g. the space in the managed install dir "/Library/Application
301
313
  // Support/…") still matches import.meta.url — a raw `file://${argv[1]}` template
302
314
  // keeps the literal space, never matches, and silently skips main().
303
- if (import.meta.url === pathToFileURL(process.argv[1]).href) {
315
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
304
316
  await main()
305
317
  }
@@ -0,0 +1,42 @@
1
+ #!/usr/bin/env node
2
+ // mainwave hook node entry
3
+ //
4
+ // The Node twin of the shell entry `mainwave-hook.sh` beside it, for a host
5
+ // that runs hook commands through cmd.exe instead of a POSIX shell (Codex on
6
+ // Windows): `node "<this file>" <host> <Event> [<route>]`. It holds no hook
7
+ // logic. It reads the release directory the shell entry names and runs that
8
+ // release's dispatcher with the same arguments, the hook input left on stdin
9
+ // for it. The dispatcher checks the developer's opt-outs itself.
10
+ //
11
+ // Prints nothing and fails open: a missing or foreign shell entry, or a release
12
+ // that isn't installed, ends it without sending anything.
13
+
14
+ import { readFileSync, realpathSync } from 'node:fs'
15
+ import { dirname, join } from 'node:path'
16
+ import { fileURLToPath, pathToFileURL } from 'node:url'
17
+
18
+ const VERSION_DIR_RE = /^[A-Za-z0-9][A-Za-z0-9._+-]*$/
19
+
20
+ const here = fileURLToPath(import.meta.url)
21
+
22
+ /** The release directory the shell entry names (its `V='<release>'` line), or
23
+ * `undefined` when it names none. */
24
+ const release = () => {
25
+ const text = readFileSync(join(dirname(here), 'mainwave-hook.sh'), 'utf8')
26
+ if (!text.includes('mainwave hook entry v2')) return undefined
27
+ const id = /^\s*V='([^']*)'$/m.exec(text)?.[1]
28
+ return id !== undefined && VERSION_DIR_RE.test(id) ? id : undefined
29
+ }
30
+
31
+ try {
32
+ const id = release()
33
+ if (id !== undefined) {
34
+ const script = realpathSync(join(dirname(here), 'versions', id, 'mainwave-hook.mjs'))
35
+ // The dispatcher runs its main only when it is the process's entry point,
36
+ // which it checks against argv[1].
37
+ process.argv[1] = script
38
+ await import(pathToFileURL(script).href)
39
+ }
40
+ } catch {
41
+ // fail open — telemetry never blocks the session
42
+ }
@@ -0,0 +1,301 @@
1
+ #!/usr/bin/env node
2
+ // The Node half of the Mainwave hook entry. Every Mainwave hook group runs
3
+ // `mainwave-hook.sh <host> <Event> [<route>]`, which runs this file from the
4
+ // release directory it names, with the same arguments and the hook input on
5
+ // stdin. This file:
6
+ //
7
+ // - reads the hook input once, at most MAX_INPUT_BYTES, and parses it;
8
+ // - requires the input's `hook_event_name` to be the event its arguments name
9
+ // (Codex inputs may omit it);
10
+ // - looks up the features registered for `<host> <Event> [<route>]` (§ ROUTES)
11
+ // and skips any the developer turned off (§ isOptedOut), unless the
12
+ // organization's managed settings deliver this hook — then they can't;
13
+ // - runs each feature's `handle(input, ctx)` under the feature's own time cap
14
+ // (§ FEATURES), all of them under a global watchdog (§ WATCHDOG_MS);
15
+ // - posts only the span names and attribute keys the feature is bound to
16
+ // (vocabulary FEATURE_EMITS): anything else is dropped before it is sent.
17
+ //
18
+ // It prints nothing, never blocks a session (every group is async), and exits
19
+ // 0 whatever happens. It never logs or forwards the prompt, the tool input or
20
+ // the tool output; a feature reads only the fields it documents. Its own log
21
+ // (`~/.mainwave/logs/hook.log`, or `--log-file`) records only the event, route,
22
+ // feature and an outcome code.
23
+
24
+ import { existsSync, readFileSync, realpathSync } from 'node:fs'
25
+ import { homedir } from 'node:os'
26
+ import { basename, dirname, join } from 'node:path'
27
+ import { fileURLToPath, pathToFileURL } from 'node:url'
28
+
29
+ import {
30
+ emitMarker,
31
+ markerLog,
32
+ markerManagedDir,
33
+ markerProjectDir,
34
+ markerSessionEnv,
35
+ readStdinCapped,
36
+ selectedManagedPaths,
37
+ sessionBypassesServer,
38
+ } from './marker-core.mjs'
39
+ import { COMMON_SPAN_KEYS, FEATURE_EMITS } from './vocabulary.mjs'
40
+
41
+ /** Hook input larger than this is skipped unread. */
42
+ export const MAX_INPUT_BYTES = 8 * 1024 * 1024
43
+
44
+ /** The whole run's bound: past it the process exits 0, whatever is pending. */
45
+ export const WATCHDOG_MS = 9000
46
+
47
+ /**
48
+ * Every feature the dispatcher can run: its module (beside this file), the
49
+ * most it may take, and which of the developer's choices turns it off: every
50
+ * feature follows `markers` (`--no-markers` installs no Mainwave hooks).
51
+ *
52
+ * Caps are each feature's own worst case plus 250 ms: the plan snapshot's
53
+ * 4 s send; the PR marker's 5 s `gh pr view` and 3 s post; the MR marker's
54
+ * 2.5 s lookup and 1.5 s post; the ticket markers' and the StopFailure
55
+ * span's 3 s post.
56
+ */
57
+ export const FEATURES = Object.freeze({
58
+ 'plan-snapshot': { module: 'plan-snapshot.mjs', capMs: 4250, optOut: 'markers' },
59
+ 'github-pr-marker': { module: 'github-pr-marker.mjs', capMs: 8250, optOut: 'markers' },
60
+ 'glab-mr-marker': { module: 'glab-mr-marker.mjs', capMs: 4250, optOut: 'markers' },
61
+ 'linear-ticket-marker': { module: 'linear-ticket-marker.mjs', capMs: 3250, optOut: 'markers' },
62
+ 'jira-ticket-marker': { module: 'jira-ticket-marker.mjs', capMs: 3250, optOut: 'markers' },
63
+ 'stop-failure': { module: 'stop-failure.mjs', capMs: 3250, optOut: 'markers' },
64
+ })
65
+
66
+ /**
67
+ * `<host> <Event>[ <route>]` → the features that run there. Mirrors the
68
+ * packaged matchers.json (a test holds the two together). Codex has no `if`
69
+ * filter, so its one Bash route runs both pull-request markers, which each
70
+ * check the command themselves.
71
+ */
72
+ export const ROUTES = Object.freeze({
73
+ 'claude-code UserPromptSubmit': ['plan-snapshot'],
74
+ 'claude-code PostToolUse gh': ['github-pr-marker'],
75
+ 'claude-code PostToolUse glab': ['glab-mr-marker'],
76
+ 'claude-code PostToolUse linear': ['linear-ticket-marker'],
77
+ 'claude-code PostToolUse jira': ['jira-ticket-marker'],
78
+ 'claude-code StopFailure': ['stop-failure'],
79
+ 'codex PostToolUse bash': ['github-pr-marker', 'glab-mr-marker'],
80
+ 'codex PostToolUse linear': ['linear-ticket-marker'],
81
+ 'codex PostToolUse jira': ['jira-ticket-marker'],
82
+ })
83
+
84
+ /** `<host> <Event>[ <route>]` from argv: the positional arguments after the
85
+ * script, a route being any third word that isn't a `--flag`. */
86
+ export const parseInvocation = (argv) => {
87
+ const [host, event, maybeRoute] = argv.slice(2)
88
+ const route = maybeRoute !== undefined && !maybeRoute.startsWith('-') ? maybeRoute : undefined
89
+ const positional = 2 + (route === undefined ? 2 : 3)
90
+ return { host, event, route, flags: argv.slice(positional) }
91
+ }
92
+
93
+ export const routeKey = (host, event, route) =>
94
+ route === undefined ? `${host} ${event}` : `${host} ${event} ${route}`
95
+
96
+ /** The features for an invocation, or `[]` for one this release doesn't know. */
97
+ export const featuresFor = (host, event, route) =>
98
+ Object.hasOwn(ROUTES, routeKey(host, event, route)) ? ROUTES[routeKey(host, event, route)] : []
99
+
100
+ /**
101
+ * The argv a feature reads its flags from: the trusted `--flag value` pairs
102
+ * the hook command passed (tests pass `--log-file`, `--managed-settings-dir`,
103
+ * `--gh-bin`), with the host as `--tool`, the selector the shared marker
104
+ * plumbing reads. Never the environment (§ marker-core `hookFlag`).
105
+ */
106
+ export const featureArgv = (argv, host, flags) => [argv[0], argv[1], '--tool', host, ...flags]
107
+
108
+ const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v)
109
+
110
+ /**
111
+ * The OTLP body with every span the feature isn't bound to removed, and every
112
+ * attribute on the rest that the feature doesn't bind (§ vocabulary
113
+ * FEATURE_EMITS, COMMON_SPAN_KEYS) dropped. Resource attributes are the
114
+ * developer's own configuration plus the source stamps, and pass as they are.
115
+ */
116
+ export const allowlistPayload = (body, feature) => {
117
+ const allow = FEATURE_EMITS[feature]
118
+ if (allow === undefined) return { resourceSpans: [] }
119
+ const keys = new Set([...COMMON_SPAN_KEYS, ...allow.keys])
120
+ const bound = (key) => keys.has(key) || allow.prefixes.some((p) => key.startsWith(p))
121
+ return {
122
+ resourceSpans: (body?.resourceSpans ?? []).map((rs) => ({
123
+ ...rs,
124
+ scopeSpans: (rs.scopeSpans ?? []).map((ss) => ({
125
+ ...ss,
126
+ spans: (ss.spans ?? [])
127
+ .filter((s) => allow.spans.includes(s.name))
128
+ .map((s) => ({ ...s, attributes: (s.attributes ?? []).filter((a) => bound(a?.key)) })),
129
+ })),
130
+ })),
131
+ }
132
+ }
133
+
134
+ /** Whether an OTLP body still carries a span after § allowlistPayload. */
135
+ const hasSpan = (body) =>
136
+ (body.resourceSpans ?? []).some((rs) => (rs.scopeSpans ?? []).some((ss) => ss.spans?.length))
137
+
138
+ const here = fileURLToPath(import.meta.url)
139
+
140
+ /**
141
+ * The hooks directory (`~/.mainwave/hooks`): four levels up when this file
142
+ * runs from a release directory (`<hooks>/managed/versions/<release>/`),
143
+ * else the home directory's — the same directory the shell entry reads its
144
+ * opt-out flags from.
145
+ */
146
+ export const hooksRoot = (file = here) => {
147
+ const versions = dirname(dirname(file))
148
+ return basename(versions) === 'versions'
149
+ ? dirname(dirname(versions))
150
+ : join(homedir(), '.mainwave', 'hooks')
151
+ }
152
+
153
+ /** The flag file that turns `optOut` off for `host`: `off/<host>/<optOut>`. */
154
+ export const optOutFlag = (root, host, optOut) => join(root, 'off', host, optOut)
155
+
156
+ /**
157
+ * Whether the managed settings Claude Code takes hooks from register this
158
+ * exact entry invocation. Those run whatever the developer chose, so a
159
+ * developer's opt-out can't remove them. Reads the same managed sources the
160
+ * markers resolve their collector from (`selectedManagedPaths`).
161
+ */
162
+ export const managedDeliversRoute = ({ host, event, route }, { projectDir, env, managedDir }) => {
163
+ if (host !== 'claude-code') return false
164
+ const bypassed = sessionBypassesServer(projectDir, env, undefined, undefined, managedDir)
165
+ const paths = selectedManagedPaths(env, undefined, undefined, managedDir, bypassed)
166
+ const want = route === undefined ? ` ${host} ${event};` : ` ${host} ${event} ${route};`
167
+ for (const path of paths) {
168
+ let doc
169
+ try {
170
+ doc = JSON.parse(readFileSync(path, 'utf8'))
171
+ } catch {
172
+ continue
173
+ }
174
+ const groups = isPlainObject(doc?.hooks) ? doc.hooks[event] : undefined
175
+ if (!Array.isArray(groups)) continue
176
+ for (const group of groups) {
177
+ for (const h of Array.isArray(group?.hooks) ? group.hooks : []) {
178
+ const command = typeof h?.command === 'string' ? h.command : ''
179
+ if (command.includes('mainwave-hook.sh') && command.includes(want)) return true
180
+ }
181
+ }
182
+ }
183
+ return false
184
+ }
185
+
186
+ /**
187
+ * Whether the developer turned this feature off: its flag file exists and the
188
+ * organization's managed settings don't deliver this hook themselves.
189
+ */
190
+ export const isOptedOut = (invocation, optOut, root, session) =>
191
+ existsSync(optOutFlag(root, invocation.host, optOut)) &&
192
+ !managedDeliversRoute(invocation, session)
193
+
194
+ /** Resolves after `ms`, without keeping the process alive. */
195
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms).unref())
196
+
197
+ /**
198
+ * Run the features for one invocation. Resolves when every feature has
199
+ * finished or hit its cap; never throws. `importFeature` loads a feature
200
+ * module and `capFor` gives its cap (tests swap both). Returns each feature's
201
+ * outcome, for the log.
202
+ */
203
+ export const dispatch = async (
204
+ argv,
205
+ text,
206
+ {
207
+ env = process.env,
208
+ root = hooksRoot(),
209
+ importFeature = (module) => import(pathToFileURL(join(dirname(here), module)).href),
210
+ capFor = (feature) => FEATURES[feature].capMs,
211
+ } = {},
212
+ ) => {
213
+ const invocation = parseInvocation(argv)
214
+ const { host, event, route, flags } = invocation
215
+ const features = featuresFor(host, event, route)
216
+ if (features.length === 0) return [{ outcome: 'unknown-route' }]
217
+ if (text === undefined) return [{ outcome: 'input-too-large' }]
218
+ let payload
219
+ try {
220
+ payload = JSON.parse(text)
221
+ } catch {
222
+ return [{ outcome: 'unparseable-input' }]
223
+ }
224
+ if (!isPlainObject(payload)) return [{ outcome: 'unparseable-input' }]
225
+ const named = payload.hook_event_name
226
+ // Codex's input shape mirrors Claude Code's, but whether it names the event
227
+ // isn't documented, so only a different name is refused there.
228
+ if (named !== event && !(host === 'codex' && named === undefined)) {
229
+ return [{ outcome: 'event-mismatch' }]
230
+ }
231
+ const hookArgv = featureArgv(argv, host, flags)
232
+ // The env every feature resolves its settings from: under the credential
233
+ // scrub, the session's own config dir is put back from the input, so the
234
+ // org-delivery check reads the managed settings this session runs on.
235
+ const sessionEnv = markerSessionEnv(host, payload, env)
236
+ const session = {
237
+ projectDir: markerProjectDir(payload, sessionEnv),
238
+ env: sessionEnv,
239
+ managedDir: markerManagedDir(hookArgv),
240
+ }
241
+ return Promise.all(
242
+ features.map(async (feature) => {
243
+ const spec = FEATURES[feature]
244
+ try {
245
+ if (isOptedOut(invocation, spec.optOut, root, session)) {
246
+ return { feature, outcome: 'opted-out' }
247
+ }
248
+ const mod = await importFeature(spec.module)
249
+ // Only what the feature is bound to is ever posted.
250
+ const emit = (args) => {
251
+ const body = allowlistPayload(args.body, feature)
252
+ return hasSpan(body) ? emitMarker({ ...args, body }) : Promise.resolve(undefined)
253
+ }
254
+ const run = Promise.resolve(mod.handle(payload, { argv: hookArgv, emit })).then(
255
+ () => 'done',
256
+ () => 'failed',
257
+ )
258
+ const outcome = await Promise.race([run, sleep(capFor(feature)).then(() => 'timeout')])
259
+ return { feature, outcome }
260
+ } catch {
261
+ return { feature, outcome: 'failed' }
262
+ }
263
+ }),
264
+ )
265
+ }
266
+
267
+ const main = async () => {
268
+ // Nothing may hold a session's hook past this, whatever a feature awaits.
269
+ setTimeout(() => process.exit(0), WATCHDOG_MS).unref()
270
+ const { host, event, route } = parseInvocation(process.argv)
271
+ const log = markerLog(process.argv, 'hook.log')
272
+ if (featuresFor(host, event, route).length === 0) return
273
+ const text = await readStdinCapped(MAX_INPUT_BYTES)
274
+ const outcomes = await dispatch(process.argv, text)
275
+ // Only what someone diagnoses: never a feature that ran to completion or was
276
+ // turned off, and never anything from the input.
277
+ for (const { feature, outcome } of outcomes) {
278
+ if (outcome === 'done' || outcome === 'opted-out') continue
279
+ log(`${routeKey(host, event, route)}${feature ? ` ${feature}` : ''}: ${outcome}`)
280
+ }
281
+ }
282
+
283
+ /** Whether this file is the process's entry point. By real path: Node runs the
284
+ * main module from its real path, and a home directory reached through a
285
+ * symlink (macOS `/var` → `/private/var`) would otherwise never match. */
286
+ const isMain = () => {
287
+ try {
288
+ return realpathSync(process.argv[1]) === realpathSync(here)
289
+ } catch {
290
+ return false
291
+ }
292
+ }
293
+
294
+ if (process.argv[1] && isMain()) {
295
+ try {
296
+ await main()
297
+ } catch {
298
+ // fail open — telemetry never blocks the session
299
+ }
300
+ process.exit(0)
301
+ }