@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.
Files changed (139) hide show
  1. package/README.md +141 -42
  2. package/dist/adapters/claude-code.js +33 -7
  3. package/dist/adapters/claude-desktop.js +0 -1
  4. package/dist/adapters/codex-cli.js +1 -2
  5. package/dist/adapters/copilot-chat.js +0 -1
  6. package/dist/adapters/copilot-cli.js +0 -1
  7. package/dist/adapters/cursor-enterprise.js +0 -1
  8. package/dist/adapters/cursor.js +15 -4
  9. package/dist/adapters/index.js +0 -1
  10. package/dist/adapters/types.js +0 -1
  11. package/dist/api/index.js +0 -1
  12. package/dist/api/types.gen.js +0 -1
  13. package/dist/cli.js +0 -1
  14. package/dist/core/apply.js +151 -42
  15. package/dist/core/auth-commands.js +0 -1
  16. package/dist/core/behaviour-hooks.js +0 -1
  17. package/dist/core/browser.js +0 -1
  18. package/dist/core/codecs/cursor-hooks-json.js +0 -1
  19. package/dist/core/codecs/env-file.js +0 -1
  20. package/dist/core/codecs/json-env.js +0 -1
  21. package/dist/core/codecs/json-flat.js +0 -1
  22. package/dist/core/codecs/json-managed.js +0 -1
  23. package/dist/core/codecs/toml-otel.js +0 -1
  24. package/dist/core/codecs/types.js +0 -1
  25. package/dist/core/detect.js +0 -1
  26. package/dist/core/device-login.js +0 -1
  27. package/dist/core/doctor.js +45 -9
  28. package/dist/core/edit.js +9 -5
  29. package/dist/core/effective-settings.js +71 -20
  30. package/dist/core/entry-script.js +90 -0
  31. package/dist/core/env-command.js +0 -1
  32. package/dist/core/errors.js +0 -1
  33. package/dist/core/flags.js +0 -1
  34. package/dist/core/format.js +0 -1
  35. package/dist/core/git-bash.js +40 -0
  36. package/dist/core/git.js +0 -1
  37. package/dist/core/headers.js +0 -1
  38. package/dist/core/install-hooks.js +127 -44
  39. package/dist/core/interview.js +53 -4
  40. package/dist/core/keys.js +0 -1
  41. package/dist/core/layer-policy.js +2 -1
  42. package/dist/core/markers.js +826 -133
  43. package/dist/core/pinned-use-case.js +0 -1
  44. package/dist/core/platform.js +0 -1
  45. package/dist/core/post-setup.js +0 -1
  46. package/dist/core/prompts.js +0 -1
  47. package/dist/core/settings.js +32 -8
  48. package/dist/core/skills.js +5 -2
  49. package/dist/core/status.js +7 -5
  50. package/dist/core/store.js +0 -1
  51. package/dist/core/tty.js +0 -1
  52. package/dist/core/ucid.js +0 -1
  53. package/dist/core/ui.js +0 -1
  54. package/dist/core/use-case.js +0 -1
  55. package/dist/core/validate.js +0 -1
  56. package/dist/core/verify.js +0 -1
  57. package/dist/core/version.js +0 -1
  58. package/dist/core/wizard.js +49 -8
  59. package/dist/main.js +16 -10
  60. package/hooks/cursor-otlp.mjs +13 -15
  61. package/hooks/github-pr-marker.mjs +55 -31
  62. package/hooks/glab-mr-marker.mjs +795 -0
  63. package/hooks/jira-ticket-marker.mjs +35 -23
  64. package/hooks/linear-ticket-marker.mjs +35 -21
  65. package/hooks/mainwave-hook-node.mjs +42 -0
  66. package/hooks/mainwave-hook.mjs +301 -0
  67. package/hooks/managed-entry.mjs +42 -0
  68. package/hooks/marker-core.mjs +389 -62
  69. package/hooks/matchers.json +82 -6
  70. package/hooks/plan-snapshot.mjs +529 -0
  71. package/hooks/stop-failure.mjs +43 -0
  72. package/hooks/vocabulary.d.mts +48 -0
  73. package/hooks/vocabulary.mjs +181 -0
  74. package/package.json +6 -5
  75. package/skills/mainwave-instrument/SKILL.md +21 -7
  76. package/skills/mainwave-instrument/reference/api.md +29 -10
  77. package/skills/mainwave-instrument/reference/frameworks.md +3 -3
  78. package/skills/mainwave-instrument/reference/troubleshooting.md +12 -5
  79. package/skills/mainwave-instrument-node/SKILL.md +420 -0
  80. package/skills/mainwave-instrument-node/reference/api.md +96 -0
  81. package/skills/mainwave-instrument-node/reference/frameworks.md +82 -0
  82. package/skills/mainwave-instrument-node/reference/troubleshooting.md +152 -0
  83. package/skills/mainwave-setup/SKILL.md +47 -12
  84. package/dist/adapters/claude-code.js.map +0 -1
  85. package/dist/adapters/claude-desktop.js.map +0 -1
  86. package/dist/adapters/codex-cli.js.map +0 -1
  87. package/dist/adapters/copilot-chat.js.map +0 -1
  88. package/dist/adapters/copilot-cli.js.map +0 -1
  89. package/dist/adapters/cursor-enterprise.js.map +0 -1
  90. package/dist/adapters/cursor.js.map +0 -1
  91. package/dist/adapters/index.js.map +0 -1
  92. package/dist/adapters/types.js.map +0 -1
  93. package/dist/api/index.js.map +0 -1
  94. package/dist/api/types.gen.js.map +0 -1
  95. package/dist/cli.js.map +0 -1
  96. package/dist/core/apply.js.map +0 -1
  97. package/dist/core/auth-commands.js.map +0 -1
  98. package/dist/core/behaviour-hooks.js.map +0 -1
  99. package/dist/core/browser.js.map +0 -1
  100. package/dist/core/codecs/cursor-hooks-json.js.map +0 -1
  101. package/dist/core/codecs/env-file.js.map +0 -1
  102. package/dist/core/codecs/json-env.js.map +0 -1
  103. package/dist/core/codecs/json-flat.js.map +0 -1
  104. package/dist/core/codecs/json-managed.js.map +0 -1
  105. package/dist/core/codecs/toml-otel.js.map +0 -1
  106. package/dist/core/codecs/types.js.map +0 -1
  107. package/dist/core/detect.js.map +0 -1
  108. package/dist/core/device-login.js.map +0 -1
  109. package/dist/core/doctor.js.map +0 -1
  110. package/dist/core/edit.js.map +0 -1
  111. package/dist/core/effective-settings.js.map +0 -1
  112. package/dist/core/env-command.js.map +0 -1
  113. package/dist/core/errors.js.map +0 -1
  114. package/dist/core/flags.js.map +0 -1
  115. package/dist/core/format.js.map +0 -1
  116. package/dist/core/git.js.map +0 -1
  117. package/dist/core/headers.js.map +0 -1
  118. package/dist/core/install-hooks.js.map +0 -1
  119. package/dist/core/interview.js.map +0 -1
  120. package/dist/core/keys.js.map +0 -1
  121. package/dist/core/layer-policy.js.map +0 -1
  122. package/dist/core/markers.js.map +0 -1
  123. package/dist/core/pinned-use-case.js.map +0 -1
  124. package/dist/core/platform.js.map +0 -1
  125. package/dist/core/post-setup.js.map +0 -1
  126. package/dist/core/prompts.js.map +0 -1
  127. package/dist/core/settings.js.map +0 -1
  128. package/dist/core/skills.js.map +0 -1
  129. package/dist/core/status.js.map +0 -1
  130. package/dist/core/store.js.map +0 -1
  131. package/dist/core/tty.js.map +0 -1
  132. package/dist/core/ucid.js.map +0 -1
  133. package/dist/core/ui.js.map +0 -1
  134. package/dist/core/use-case.js.map +0 -1
  135. package/dist/core/validate.js.map +0 -1
  136. package/dist/core/verify.js.map +0 -1
  137. package/dist/core/version.js.map +0 -1
  138. package/dist/core/wizard.js.map +0 -1
  139. package/dist/main.js.map +0 -1
@@ -0,0 +1,795 @@
1
+ #!/usr/bin/env node
2
+ // The GitLab merge-request marker: a PostToolUse feature of the Mainwave hook
3
+ // dispatcher (mainwave-hook.mjs) for merge requests opened with the `glab` CLI.
4
+ // It also runs on its own (§ the main at the bottom), the way the other
5
+ // markers do.
6
+ //
7
+ // The GitLab connector lists merge requests from the API, but nothing says which
8
+ // ones an AI session opened. This hook runs after each Bash tool call, and when
9
+ // the command opened a merge request it reads the MR out of the tool *result*
10
+ // (stdout) and emits one small OTLP marker span, the GitLab analogue of the
11
+ // GitHub PR marker. Two commands open a merge request:
12
+ //
13
+ // glab mr create ... stdout ends with the MR's web URL
14
+ // glab api projects/<id>/merge_requests a POST; stdout is the MR as JSON
15
+ //
16
+ // A marker carries the MR's iid under vcs.change.id and an instance-namespaced
17
+ // project id under vcs.repository.id (`<instance>:<project id>`). GitLab ids are
18
+ // per instance, so two instances share one integer space; the instance is the
19
+ // host of the MR's own web URL, lowercased, with the scheme's default port
20
+ // dropped and any other port kept. The connector derives the same string from
21
+ // the project URLs it lists, whatever alias the operator typed for the host. A
22
+ // project id survives a rename or a move between groups where the URL does not,
23
+ // which is why the coverage join prefers it.
24
+ //
25
+ // The ids come from the API response when there is one (`glab api`), else from
26
+ // `glab mr view <iid> -R <project url> -F json`. That lookup runs only for a host
27
+ // glab is already set up for (the URL came from tool output, and glab would send
28
+ // the user's token to whatever host it names), and its answer is used only if it
29
+ // describes the URL the hook extracted. If the lookup is skipped or fails the
30
+ // marker still emits with the URL and iid but no repository id, and the coverage
31
+ // join falls back to matching the URL.
32
+ //
33
+ // Shared OTLP plumbing lives in ./marker-core.mjs. Privacy: emits the MR url, iid,
34
+ // project id, title and the changed-file count when GitLab has one, never diff
35
+ // contents or the description. Claude Code runs it only for a Bash command that
36
+ // starts with `glab` (the hook group's `if` filter; Codex, which has no such
37
+ // filter, runs it behind a substring check in the shell entry); it returns
38
+ // immediately (no log, no network) for anything that is not a glab MR creation,
39
+ // and fails open and fast otherwise, so it can never block or slow the session.
40
+
41
+ import { execFile } from 'node:child_process'
42
+ import { existsSync, readFileSync } from 'node:fs'
43
+ import { tmpdir, userInfo } from 'node:os'
44
+ import { join } from 'node:path'
45
+ import { pathToFileURL } from 'node:url'
46
+
47
+ import {
48
+ buildMarkerPayload,
49
+ markerOauthAccount,
50
+ markerSessionEnv,
51
+ emitMarker,
52
+ hookFlag,
53
+ loadOtelConfig,
54
+ markerCallContext,
55
+ markerHostSource,
56
+ markerManagedDir,
57
+ markerProjectDir,
58
+ markerTool,
59
+ markerLog,
60
+ payloadShape,
61
+ readStdin,
62
+ toolOutput,
63
+ } from './marker-core.mjs'
64
+ import {
65
+ ATTR_VCS_CHANGE_FILES_CHANGED,
66
+ ATTR_VCS_CHANGE_ID,
67
+ ATTR_VCS_CHANGE_TITLE,
68
+ ATTR_VCS_PROVIDER_NAME,
69
+ ATTR_VCS_REPOSITORY_ID,
70
+ ATTR_VCS_REPOSITORY_URL_FULL,
71
+ VCS_OPENED,
72
+ VCS_PROVIDER_GITLAB,
73
+ } from './vocabulary.mjs'
74
+
75
+ export { payloadShape, toolOutput } from './marker-core.mjs'
76
+
77
+ const LOG_NAME = 'glab-mr-marker.log'
78
+
79
+ // Non-coding source/service so the marker lands as an ordinary span and stays
80
+ // out of the coding-work segmentation, same as the other markers.
81
+ const MARKER_SOURCE = 'hook.gitlab'
82
+ const MARKER_SERVICE = 'mainwave.mr-hook'
83
+
84
+ // ── Reading the command ──────────────────────────────────────────────────────
85
+
86
+ /** Split a shell command into simple commands, each a list of words. Quotes and
87
+ * backslashes are honored so a separator inside a quoted string (a commit
88
+ * message, a `-f description="a; b"`) does not split. Not a shell: no
89
+ * substitution, and a heredoc body is tokenized as if it were commands (harmless
90
+ * unless the output also holds a merge request URL); good enough to decide what
91
+ * a command's first words and flags are. */
92
+ export const shellSegments = (command) => {
93
+ const segments = []
94
+ let words = []
95
+ let word = ''
96
+ let inWord = false
97
+ let quote = ''
98
+ const endWord = () => {
99
+ if (inWord) words.push(word)
100
+ word = ''
101
+ inWord = false
102
+ }
103
+ const endSegment = () => {
104
+ endWord()
105
+ if (words.length) segments.push(words)
106
+ words = []
107
+ }
108
+ const s = command ?? ''
109
+ for (let i = 0; i < s.length; i++) {
110
+ const c = s[i]
111
+ if (quote) {
112
+ if (c === quote) quote = ''
113
+ else if (c === '\\' && quote === '"' && i + 1 < s.length) word += s[++i]
114
+ else word += c
115
+ } else if (c === "'" || c === '"') {
116
+ quote = c
117
+ inWord = true
118
+ } else if (c === '\\' && i + 1 < s.length) {
119
+ word += s[++i]
120
+ inWord = true
121
+ } else if (c === '&' || c === '|' || c === ';' || c === '\n' || c === '(' || c === ')') {
122
+ // `&&`, `||`, `|`, `;`, newline, a lone `&` and the parentheses of a
123
+ // subshell or `$(...)` all end a command.
124
+ endSegment()
125
+ } else if (c === ' ' || c === '\t' || c === '\r') {
126
+ endWord()
127
+ } else {
128
+ word += c
129
+ inWord = true
130
+ }
131
+ }
132
+ endSegment()
133
+ return segments
134
+ }
135
+
136
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/
137
+
138
+ // Words that may precede the glab binary at a command position without changing
139
+ // what runs: `env GITLAB_HOST=h glab ...`, `time glab ...`, `command glab ...`,
140
+ // `sudo -u bob glab ...`, `if glab mr create; then ...`. Each maps to the flags
141
+ // that take a value, which are skipped with it.
142
+ const WRAPPER_VALUE_FLAGS = {
143
+ env: new Set(['-u', '--unset', '-C', '--chdir']),
144
+ sudo: new Set(['-u', '-g', '-U', '-C', '-D', '-R', '-p', '-h', '-T']),
145
+ time: new Set(['-f', '-o']),
146
+ command: new Set(),
147
+ nohup: new Set(),
148
+ exec: new Set(['-a']),
149
+ '{': new Set(),
150
+ '!': new Set(),
151
+ if: new Set(),
152
+ then: new Set(),
153
+ else: new Set(),
154
+ elif: new Set(),
155
+ do: new Set(),
156
+ while: new Set(),
157
+ until: new Set(),
158
+ }
159
+
160
+ /** The words of a segment after leading `VAR=value` assignments and wrapper
161
+ * words (with the flags and assignments that follow a wrapper), when what
162
+ * follows is the glab binary (`glab` or any path ending in it). Self-managed
163
+ * users routinely write `GITLAB_HOST=git.example.com glab mr create`. */
164
+ const glabWords = (segment) => {
165
+ let i = 0
166
+ for (;;) {
167
+ const w = segment[i]
168
+ if (w === undefined) return undefined
169
+ if (ASSIGNMENT.test(w)) {
170
+ i++
171
+ continue
172
+ }
173
+ const valueFlags = Object.hasOwn(WRAPPER_VALUE_FLAGS, w) ? WRAPPER_VALUE_FLAGS[w] : undefined
174
+ if (!valueFlags) break
175
+ i++
176
+ // Flags of a wrapper (`env -i`, `time -p`, `sudo -u bob`) are skipped with it.
177
+ while (segment[i]?.startsWith('-')) {
178
+ i += valueFlags.has(segment[i]) ? 2 : 1
179
+ }
180
+ }
181
+ const bin = segment[i]
182
+ if (!bin || !/(^|\/)glab(\.exe)?$/.test(bin)) return undefined
183
+ return segment.slice(i + 1)
184
+ }
185
+
186
+ // `glab api` flags that take a value, and the ones that put a body on the
187
+ // request. Measured against glab 1.120.0: with no `--method`, any of
188
+ // -f/--raw-field, -F/--field, --form or --input turns the request into a POST,
189
+ // and an explicit -X/--method wins in both directions (`-X GET -f a=b` is a GET
190
+ // with a query string).
191
+ const API_VALUE_FLAGS = new Set([
192
+ '-X',
193
+ '--method',
194
+ '-f',
195
+ '--raw-field',
196
+ '-F',
197
+ '--field',
198
+ '--form',
199
+ '--input',
200
+ '-H',
201
+ '--header',
202
+ '--hostname',
203
+ '--output',
204
+ ])
205
+ const API_BODY_FLAGS = new Set(['-f', '--raw-field', '-F', '--field', '--form', '--input'])
206
+
207
+ /** `{endpoint, method}` of a `glab api` invocation's words (after `api`):
208
+ * the first positional argument, and the HTTP method glab will use. */
209
+ export const parseApiCall = (words) => {
210
+ let endpoint
211
+ let explicit
212
+ let body = false
213
+ for (let i = 0; i < words.length; i++) {
214
+ const w = words[i]
215
+ if (!w.startsWith('-') || w === '-') {
216
+ endpoint ??= w
217
+ continue
218
+ }
219
+ let flag = w
220
+ let value
221
+ const eq = w.indexOf('=')
222
+ if (w.startsWith('--') && eq !== -1) {
223
+ flag = w.slice(0, eq)
224
+ value = w.slice(eq + 1)
225
+ } else if (/^-[XfFH]./.test(w)) {
226
+ // -XPOST, -ftitle=x: the value is glued to the short flag.
227
+ flag = w.slice(0, 2)
228
+ value = w.slice(2)
229
+ }
230
+ if (API_VALUE_FLAGS.has(flag)) {
231
+ value ??= words[++i]
232
+ if (flag === '-X' || flag === '--method') explicit = (value ?? '').toUpperCase()
233
+ if (API_BODY_FLAGS.has(flag)) body = true
234
+ }
235
+ }
236
+ return { endpoint, method: explicit ?? (body ? 'POST' : 'GET') }
237
+ }
238
+
239
+ // `projects/<id or url-encoded path>/merge_requests`, ending there: the create
240
+ // endpoint. Deeper paths (`.../merge_requests/7/notes`, `/approve`) act on an
241
+ // existing MR and open nothing. A leading `/` and an `api/v4/` prefix are both
242
+ // accepted by glab, and a query string does not change the resource.
243
+ const API_CREATE_ENDPOINT = /^\/?(?:api\/v4\/)?projects\/[^/?#]+\/merge_requests\/?(?:[?#].*)?$/
244
+
245
+ /** What a Bash command asks glab to do, or undefined when it opens no merge
246
+ * request. `{kind: 'create', title}` for `glab mr create` (alias `new`) at a
247
+ * command position, `{kind: 'api'}` for a POST of `glab api` to the project's
248
+ * merge_requests endpoint. A GET, an unrelated endpoint, `glab mr view`, or the
249
+ * words appearing inside a quoted string all return undefined. */
250
+ export const classifyGlabCommand = (command) => {
251
+ for (const segment of shellSegments(command)) {
252
+ const words = glabWords(segment)
253
+ if (!words) continue
254
+ // `glab mr create --help` prints usage and creates nothing.
255
+ if (words.includes('--help') || words.includes('-h')) continue
256
+ if (words[0] === 'mr' && (words[1] === 'create' || words[1] === 'new')) {
257
+ return { kind: 'create', title: extractMrTitle(words.slice(2)) }
258
+ }
259
+ if (words[0] === 'api') {
260
+ const { endpoint, method } = parseApiCall(words.slice(1))
261
+ if (method === 'POST' && endpoint && API_CREATE_ENDPOINT.test(endpoint)) {
262
+ return { kind: 'api', title: extractApiTitle(words.slice(1)) }
263
+ }
264
+ }
265
+ }
266
+ return undefined
267
+ }
268
+
269
+ /** True when a Bash command opens a merge request through glab. */
270
+ export const isGlabMrCreate = (command) => classifyGlabCommand(command) !== undefined
271
+
272
+ /** The `--title` / `-t` value of a `glab mr create` command's flags. */
273
+ export const extractMrTitle = (words) => {
274
+ for (let i = 0; i < words.length; i++) {
275
+ const w = words[i]
276
+ if (w === '--title' || w === '-t') return words[i + 1]
277
+ if (w.startsWith('--title=')) return w.slice('--title='.length)
278
+ if (/^-t.+/.test(w) && !w.startsWith('--')) return w.slice(2)
279
+ }
280
+ return undefined
281
+ }
282
+
283
+ /** The `title=` field of a `glab api` call, from -f/-F/--field/--raw-field. */
284
+ const extractApiTitle = (words) => {
285
+ for (let i = 0; i < words.length; i++) {
286
+ const w = words[i]
287
+ const value = /^(-f|-F|--field|--raw-field)$/.test(w)
288
+ ? words[i + 1]
289
+ : /^--(?:raw-)?field=/.test(w)
290
+ ? w.slice(w.indexOf('=') + 1)
291
+ : undefined
292
+ if (value?.startsWith('title=')) return value.slice('title='.length)
293
+ }
294
+ return undefined
295
+ }
296
+
297
+ // ── Reading the result ───────────────────────────────────────────────────────
298
+
299
+ // Hook budget. The installers kill a marker hook at 5 s, so the glab lookup (one
300
+ // process that makes two sequential requests) and the emit share a deadline
301
+ // rather than each taking its own: a slow instance costs the ids, never the
302
+ // marker.
303
+ export const LOOKUP_TIMEOUT_MS = 2500
304
+ export const EMIT_TIMEOUT_MS = 1500
305
+
306
+ const MR_URL =
307
+ /https?:\/\/[A-Za-z0-9.-]+(?::\d+)?(?:\/[\w.~%+-]+)+?\/(?:-\/)?merge_requests\/(\d+)(?![\w/])/g
308
+ const MR_URL_LINE = new RegExp(`^${MR_URL.source}$`)
309
+ const ANCHOR = /^\s*Creating merge request for \S+ into \S+ in \S+\s*$/
310
+ // Terminal colour codes glab may print around the MR line.
311
+ const ANSI = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*[A-Za-z]`, 'g')
312
+
313
+ const parseMrUrl = (m) => {
314
+ let url = m[0]
315
+ try {
316
+ // Canonical form: lowercase host, default port dropped, so the URL fallback
317
+ // in the coverage join sees the same string the connector stores.
318
+ url = new URL(url).href
319
+ } catch {
320
+ // keep the matched text
321
+ }
322
+ return { url, iid: m[1], projectUrl: url.replace(/\/(?:-\/)?merge_requests\/\d+$/, '') }
323
+ }
324
+
325
+ /** The project path of an MR URL (`group/sub/project`), lowercased and decoded. */
326
+ const projectPathOf = (url) => {
327
+ try {
328
+ return decodeURIComponent(
329
+ new URL(url).pathname.replace(/\/(?:-\/)?merge_requests\/\d+$/, '').replace(/^\//, ''),
330
+ ).toLowerCase()
331
+ } catch {
332
+ return undefined
333
+ }
334
+ }
335
+
336
+ /** The merge request glab itself created, from the text it printed: `{url, iid,
337
+ * projectUrl}`. Verified against glab 1.120.0: `glab mr create` prints
338
+ * `Creating merge request for <source> into <target> in <group/project>` (to
339
+ * stderr) and then the MR's web URL on its own line (to stdout). The first line
340
+ * is the anchor: the URL taken is the first MR URL after it, alone on its line,
341
+ * whose project path equals `<group/project>`. Two anchors naming distinct MRs
342
+ * yield none. A URL anywhere else in the output belongs to
343
+ * something else (a commit subject that cites another MR, `git push`'s `remote:
344
+ * View merge request` line, text from a file the command also printed) and is
345
+ * never taken; `remote:` lines are dropped outright. If the anchor is present
346
+ * and no such URL follows it, there is no result. With no anchor (the stdout
347
+ * alone, or a `| jq -r .web_url` pipe leaving a bare URL) a URL is taken only
348
+ * when it is the single distinct MR URL in the output. Returns undefined
349
+ * otherwise (a `--web` create, a dry run, a failure).
350
+ *
351
+ * The host may be any self-managed instance, with a port, and the project path
352
+ * any number of groups deep; the `/-/` before `merge_requests` is optional for
353
+ * old instances. Hosts outside `[A-Za-z0-9.-]` (IDN, `user@host`, IPv6
354
+ * literals) are not recognized. A GitLab installed under a relative URL root
355
+ * (https://host/gitlab/...) puts the root in the URL's path but not in the
356
+ * anchor's, so such a create has no result. */
357
+ export const extractMrUrl = (text) => {
358
+ const lines = String(text ?? '')
359
+ .replace(ANSI, '')
360
+ .split(/\r?\n/)
361
+ .filter((l) => !/^\s*remote:/i.test(l))
362
+ // glab prints the URL alone on its line; a URL inside other text is not glab's.
363
+ const urlOn = (line) => {
364
+ const m = line.trim().match(MR_URL_LINE)
365
+ return m ? parseMrUrl(m) : undefined
366
+ }
367
+ const anchors = []
368
+ lines.forEach((l, i) => {
369
+ if (ANCHOR.test(l)) anchors.push(i)
370
+ })
371
+ if (anchors.length > 0) {
372
+ const pairs = new Map()
373
+ anchors.forEach((at, n) => {
374
+ const path = lines[at].trim().split(/\s+/).pop().toLowerCase()
375
+ for (const line of lines.slice(at + 1, anchors[n + 1] ?? lines.length)) {
376
+ const u = urlOn(line)
377
+ if (u && projectPathOf(u.url) === path) {
378
+ pairs.set(u.url, u)
379
+ break
380
+ }
381
+ }
382
+ })
383
+ // More than one distinct created MR in the output: text the command printed
384
+ // may hold a look-alike, so none can be attributed.
385
+ return pairs.size === 1 ? [...pairs.values()][0] : undefined
386
+ }
387
+ const all = lines.map(urlOn).filter(Boolean)
388
+ return new Set(all.map((u) => u.url)).size === 1 ? all[0] : undefined
389
+ }
390
+
391
+ /** The text(s) of a Bash tool result. Claude Code sends `{stdout, stderr,
392
+ * interrupted, isImage}`; older payloads and the tests also send a bare string.
393
+ * Claude Code usually merges the shell's stderr into stdout, but where the
394
+ * streams are separate glab prints its `Creating merge request …` line to stderr
395
+ * and the URL to stdout, so with both present the first candidate is stderr then
396
+ * stdout's last line, followed by each alone. */
397
+ export const outputTexts = (output) => {
398
+ if (typeof output === 'string') return output ? [output] : []
399
+ if (output && typeof output === 'object') {
400
+ const out = typeof output.stdout === 'string' ? output.stdout : ''
401
+ const err = typeof output.stderr === 'string' ? output.stderr : ''
402
+ // glab's URL is the last thing it prints, so with separate streams only
403
+ // stdout's last line is paired with the stderr anchor; earlier stdout is the
404
+ // command's other output.
405
+ const last = out.trimEnd().split('\n').pop()
406
+ const texts = out && err ? [`${err}\n${last}`, out, err] : [out || err].filter(Boolean)
407
+ return texts.length ? texts : [JSON.stringify(output)]
408
+ }
409
+ return []
410
+ }
411
+
412
+ // ── Which hosts the lookup may contact ───────────────────────────────────────
413
+
414
+ /** The home directory of the user running the hook, from the account database
415
+ * rather than `HOME`: a repository's project settings `env` reaches the hook, and
416
+ * `HOME` is how it would point glab's config at a file it wrote. */
417
+ const accountHome = () => {
418
+ try {
419
+ return userInfo().homedir
420
+ } catch {
421
+ return undefined
422
+ }
423
+ }
424
+
425
+ /** The directory glab 1.120.0 reads its config from, resolved the way glab does
426
+ * but without its environment overrides (`GLAB_CONFIG_DIR`, `XDG_CONFIG_HOME`,
427
+ * `AppData`), each of which a repository could set: the legacy
428
+ * `<home>/.config/glab-cli` when its `config.yml` exists, else the platform
429
+ * default: `<home>/Library/Application Support/glab-cli` on macOS,
430
+ * `<home>/AppData/Roaming/glab-cli` on Windows, `<home>/.config/glab-cli`
431
+ * elsewhere. A user who relocates the config with those variables gets markers
432
+ * without ids (the URL fallback). */
433
+ export const glabConfigDir = ({ home = accountHome(), platform = process.platform } = {}) => {
434
+ if (!home) return undefined
435
+ const legacy = join(home, '.config', 'glab-cli')
436
+ if (existsSync(join(legacy, 'config.yml'))) return legacy
437
+ if (platform === 'darwin') return join(home, 'Library', 'Application Support', 'glab-cli')
438
+ if (platform === 'win32') return join(home, 'AppData', 'Roaming', 'glab-cli')
439
+ return legacy
440
+ }
441
+
442
+ /** The hosts glab is set up for: gitlab.com and the `hosts:` keys of the config
443
+ * file in `configDir` (read as keys only, so no token is ever held). The lookup
444
+ * runs glab with the user's credentials, and glab sends a token to whatever host
445
+ * `-R` names, so a URL taken from tool output must never reach a host the user
446
+ * has not already chosen. Nothing here comes from the environment, which a
447
+ * repository's project settings can set. */
448
+ export const glabKnownHosts = ({ configDir } = {}) => {
449
+ const hosts = new Set(['gitlab.com'])
450
+ let text = ''
451
+ try {
452
+ if (configDir) text = readFileSync(join(configDir, 'config.yml'), 'utf8')
453
+ } catch {
454
+ return hosts
455
+ }
456
+ let inHosts = false
457
+ let indent
458
+ for (const line of text.split(/\r?\n/)) {
459
+ if (/^hosts:\s*(#.*)?$/.test(line)) {
460
+ inHosts = true
461
+ continue
462
+ }
463
+ if (!inHosts) continue
464
+ if (/^\S/.test(line)) {
465
+ inHosts = false
466
+ continue
467
+ }
468
+ const m = line.match(/^( +)(["']?)([^\s"':]+(?::\d+)?)\2:\s*(#.*)?$/)
469
+ if (!m) continue
470
+ indent ??= m[1].length
471
+ if (m[1].length === indent) hosts.add(m[3].toLowerCase())
472
+ }
473
+ return hosts
474
+ }
475
+
476
+ // What may reach the glab child. Everything glab reads that picks a destination or
477
+ // a protocol (`GITLAB_API_HOST`, `GLAB_API_PROTOCOL`, `API_PROTOCOL`,
478
+ // `GLAB_CONFIG_DIR`, `GITLAB_HOST`, proxy and TLS variables) is a way for a
479
+ // repository's project settings `env` to send the user's token somewhere the host
480
+ // check never saw, so the child gets these and nothing else. The tokens pass
481
+ // through: a token a repository supplies authenticates only that identity, and
482
+ // the host is now the vetted one.
483
+ const PASSTHROUGH_ENV = [
484
+ 'PATH',
485
+ 'GITLAB_TOKEN',
486
+ 'GITLAB_ACCESS_TOKEN',
487
+ 'USER',
488
+ 'LOGNAME',
489
+ 'TMPDIR',
490
+ 'LANG',
491
+ 'LC_ALL',
492
+ 'DBUS_SESSION_BUS_ADDRESS',
493
+ // Windows needs these to start a process at all; none picks a destination.
494
+ 'SystemRoot',
495
+ 'WINDIR',
496
+ 'COMSPEC',
497
+ 'PATHEXT',
498
+ ]
499
+
500
+ /** The environment for the `glab mr view` child: the pass-through names above,
501
+ * plus values the hook sets itself. `HOME` is the account's home and
502
+ * `GLAB_CONFIG_DIR` the directory the host check read, so glab and the check
503
+ * read one file. */
504
+ export const lookupEnv = ({ home, configDir, source = process.env }) => {
505
+ const env = {}
506
+ for (const k of PASSTHROUGH_ENV) if (source[k] !== undefined) env[k] = source[k]
507
+ if (home) env.HOME = home
508
+ if (configDir) env.GLAB_CONFIG_DIR = configDir
509
+ env.GLAB_NO_PROMPT = '1'
510
+ env.GLAB_SEND_TELEMETRY = '0'
511
+ return env
512
+ }
513
+
514
+ /** The instance part of `vcs.repository.id`: the URL's host, lowercased, with
515
+ * the scheme's default port (443 for https, 80 for http) removed and any other
516
+ * port kept. This is the WHATWG `URL.host` serialization. Undefined for a
517
+ * string that is not an absolute URL. */
518
+ export const instanceOf = (url) => {
519
+ try {
520
+ return new URL(url).host.toLowerCase() || undefined
521
+ } catch {
522
+ return undefined
523
+ }
524
+ }
525
+
526
+ /** `<instance>:<project id>`, or undefined unless the project id is a positive
527
+ * integer and the URL names an instance. */
528
+ export const namespacedRepositoryId = (url, projectId) => {
529
+ const instance = instanceOf(url)
530
+ const id =
531
+ typeof projectId === 'string' && /^\d+$/.test(projectId) ? Number(projectId) : projectId
532
+ return instance && Number.isInteger(id) && id > 0 ? `${instance}:${id}` : undefined
533
+ }
534
+
535
+ /** The title without GitLab's draft marker. GitLab derives "draft" from the
536
+ * title prefix (`Draft:`, `[Draft]`, `(Draft)`, case-insensitive), and `glab mr
537
+ * create --draft` adds one, so the marker's title would otherwise differ from
538
+ * the connector's. */
539
+ export const stripDraftPrefix = (title) => {
540
+ if (typeof title !== 'string') return undefined
541
+ const stripped = title.replace(/^\s*(?:(?:\[draft\]|\(draft\)|draft:)\s*)+/i, '').trim()
542
+ return stripped || undefined
543
+ }
544
+
545
+ /** The MR fields a marker reads from `glab mr view -F json` stdout or a `glab
546
+ * api` response body: `{iid, projectId, title, webUrl, filesChanged}`, each
547
+ * undefined when missing or the wrong type. Never throws. `changes_count` is
548
+ * a string that reads "1000+" past the cap and is null while GitLab is still
549
+ * computing the diff; only a plain integer is taken. */
550
+ export const parseMrJson = (stdout) => {
551
+ let json
552
+ try {
553
+ json = JSON.parse(stdout)
554
+ } catch {
555
+ return {}
556
+ }
557
+ if (!json || typeof json !== 'object' || Array.isArray(json)) return {}
558
+ const int = (v) =>
559
+ Number.isInteger(v) ? v : typeof v === 'string' && /^\d+$/.test(v) ? Number(v) : undefined
560
+ return {
561
+ iid: int(json.iid),
562
+ projectId: int(json.project_id),
563
+ title: typeof json.title === 'string' ? json.title : undefined,
564
+ webUrl: typeof json.web_url === 'string' ? json.web_url : undefined,
565
+ filesChanged: int(json.changes_count),
566
+ }
567
+ }
568
+
569
+ const sameUrl = (a, b) => {
570
+ try {
571
+ return new URL(a).href.replace(/\/$/, '') === new URL(b).href.replace(/\/$/, '')
572
+ } catch {
573
+ return false
574
+ }
575
+ }
576
+
577
+ /**
578
+ * The MR's ids and title via `glab mr view <iid> -R <project url> -F json`.
579
+ * Fail-open: resolves `{reason}` on any error (glab absent, unauthenticated, the
580
+ * host unreachable, timeout, bad output) so a marker still emits without ids; it
581
+ * never blocks the session. `reason` is a value-free word for the local log. The
582
+ * result is trusted only if the MR it returns has the URL the hook extracted;
583
+ * otherwise `{reason: 'url-mismatch'}`. `bin` replaces `glab`; `main` takes it
584
+ * only from the hook's own `--glab-bin` flag (tests pass a stub), never from a
585
+ * variable naming the binary, because a repository's project settings `env`
586
+ * reaches the hook and this runs with the repository as its working directory.
587
+ * `-R` names the project by URL, so the lookup does not depend on what remote the
588
+ * working directory has; the caller has already checked the host and supplies the
589
+ * allowlisted `env` (`lookupEnv`).
590
+ */
591
+ export const fetchMrDetails = (
592
+ { iid, projectUrl, url },
593
+ { cwd, bin = 'glab', timeoutMs = LOOKUP_TIMEOUT_MS, env } = {},
594
+ ) =>
595
+ new Promise((resolve) => {
596
+ if (!iid || !projectUrl) return resolve({ reason: 'no-target' })
597
+ execFile(
598
+ bin,
599
+ ['mr', 'view', String(iid), '-R', projectUrl, '-F', 'json'],
600
+ { cwd, timeout: timeoutMs, windowsHide: true, env },
601
+ (err, stdout) => {
602
+ if (err) {
603
+ const reason =
604
+ err.code === 'ENOENT' ? 'glab-missing' : err.killed ? 'timeout' : `exit-${err.code}`
605
+ return resolve({ reason })
606
+ }
607
+ const mr = parseMrJson(stdout)
608
+ if (!mr.webUrl) return resolve({ reason: 'unparseable' })
609
+ resolve(sameUrl(mr.webUrl, url) ? mr : { reason: 'url-mismatch' })
610
+ },
611
+ )
612
+ })
613
+
614
+ // ── Building the marker ──────────────────────────────────────────────────────
615
+
616
+ /** Build the OTLP/JSON payload for one MR-marker span: the typed
617
+ * `vcs.change.opened` event, since a `glab mr create` only ever opens. The MR
618
+ * url lands under vcs.repository.url.full, the iid under vcs.change.id, and the
619
+ * namespaced project id under vcs.repository.id. The span self-declares
620
+ * `mainwave.source = hook.gitlab`. Absent values (undefined) drop out via
621
+ * buildMarkerPayload's empty-value filter. */
622
+ export const buildMrPayload = ({
623
+ url,
624
+ iid,
625
+ repositoryId,
626
+ title,
627
+ filesChanged,
628
+ sessionId,
629
+ userEmail,
630
+ userAccountUuid,
631
+ resourceAttrs,
632
+ hostSource,
633
+ callContext,
634
+ nowNs,
635
+ }) =>
636
+ buildMarkerPayload({
637
+ spanName: VCS_OPENED,
638
+ scopeName: 'mainwave.glab-mr-marker',
639
+ attributes: {
640
+ [ATTR_VCS_REPOSITORY_URL_FULL]: url,
641
+ [ATTR_VCS_CHANGE_ID]: iid,
642
+ [ATTR_VCS_PROVIDER_NAME]: VCS_PROVIDER_GITLAB,
643
+ [ATTR_VCS_REPOSITORY_ID]: repositoryId,
644
+ [ATTR_VCS_CHANGE_TITLE]: title,
645
+ [ATTR_VCS_CHANGE_FILES_CHANGED]: filesChanged,
646
+ },
647
+ sessionId,
648
+ userEmail,
649
+ userAccountUuid,
650
+ resourceAttrs,
651
+ source: MARKER_SOURCE,
652
+ service: MARKER_SERVICE,
653
+ hostSource,
654
+ callContext,
655
+ nowNs,
656
+ })
657
+
658
+ /** A `glab api` POST response is the created MR itself: parse it as JSON, from
659
+ * the whole text or the first `{` to the last `}`. Returns the parsed fields when
660
+ * it is an MR with a web_url; otherwise `{}` (a jq-filtered pipe, an error body). */
661
+ export const mrFromApiResult = (text) => {
662
+ const direct = parseMrJson(text)
663
+ if (direct.webUrl) return direct
664
+ const start = text.indexOf('{')
665
+ const end = text.lastIndexOf('}')
666
+ return start !== -1 && end > start ? parseMrJson(text.slice(start, end + 1)) : {}
667
+ }
668
+
669
+ const firstOf = (texts, read) => {
670
+ for (const t of texts) {
671
+ const found = read(t)
672
+ if (found) return found
673
+ }
674
+ return undefined
675
+ }
676
+
677
+ /**
678
+ * The feature: one marker span when the Bash command opened a merge request,
679
+ * else nothing. `ctx.argv` carries the hook command's flags (and
680
+ * `--tool <host>` under the dispatcher); `ctx.emit` posts.
681
+ */
682
+ export const handle = async (payload, { argv = process.argv, emit = emitMarker } = {}) => {
683
+ // Cheap guard first: bail with no log and no work unless the command could
684
+ // have opened a merge request.
685
+ const command = payload?.tool_input?.command
686
+ const call = classifyGlabCommand(command)
687
+ if (!call) return
688
+ const log = markerLog(argv, LOG_NAME)
689
+
690
+ const texts = outputTexts(toolOutput(payload))
691
+ let api = {}
692
+ let mr
693
+ if (call.kind === 'api') {
694
+ const parsed = firstOf(texts, (t) => {
695
+ const a = mrFromApiResult(t)
696
+ return a.webUrl ? a : undefined
697
+ })
698
+ if (parsed) {
699
+ api = parsed
700
+ mr = extractMrUrl(parsed.webUrl)
701
+ }
702
+ }
703
+ // `glab mr create`, and a `glab api` POST whose JSON was filtered away.
704
+ mr ??= firstOf(texts, extractMrUrl)
705
+ if (!mr) {
706
+ log(`skip: no merge request url in tool output (${payloadShape(payload)})`)
707
+ return
708
+ }
709
+
710
+ const projectDir = markerProjectDir(payload)
711
+ const tool = markerTool(argv)
712
+ const managedDir = markerManagedDir(argv)
713
+ const env = markerSessionEnv(tool, payload)
714
+ const { endpoint, bearer, resourceAttrs } = loadOtelConfig(projectDir, env, tool, managedDir)
715
+ log(
716
+ `mr=${mr.iid} endpoint=${endpoint ? 'set' : 'MISSING'} ` +
717
+ `bearer=${bearer ? 'set' : 'MISSING'} ucid=${resourceAttrs['mainwave.ucid'] || 'MISSING'}`,
718
+ )
719
+ if (!endpoint || !bearer) {
720
+ log('skip: collector endpoint/bearer not found in settings or env')
721
+ return
722
+ }
723
+ // Read only once the emit is certain: `.claude.json` can run to megabytes.
724
+ const { email: userEmail, accountUuid: userAccountUuid } = markerOauthAccount(tool, {
725
+ cwd: projectDir,
726
+ env,
727
+ managedDir,
728
+ })
729
+
730
+ // A `glab api` response already carries the ids. Otherwise ask glab once, but
731
+ // only for a host glab is set up for: the URL came from tool output, and glab
732
+ // would send the user's token to whatever host it names. Best-effort: the
733
+ // marker still emits with the link and iid if the lookup is skipped or fails,
734
+ // and then carries no repository id.
735
+ let details = api
736
+ let lookup = 'response'
737
+ if (api.projectId === undefined) {
738
+ const home = hookFlag(argv, '--glab-home') || accountHome()
739
+ const configDir = hookFlag(argv, '--glab-config-dir') || glabConfigDir({ home })
740
+ const known = glabKnownHosts({ configDir })
741
+ if (!known.has(instanceOf(mr.url))) {
742
+ details = {}
743
+ lookup = 'host-not-configured'
744
+ } else {
745
+ details = await fetchMrDetails(mr, {
746
+ // Not the repository: glab reads `.git/glab-cli/config.yml` from its cwd,
747
+ // and a file the repository wrote there (mode 644) makes glab exit.
748
+ cwd: home || tmpdir(),
749
+ bin: hookFlag(argv, '--glab-bin'),
750
+ timeoutMs: Number(hookFlag(argv, '--lookup-timeout-ms')) || LOOKUP_TIMEOUT_MS,
751
+ env: lookupEnv({ home, configDir }),
752
+ })
753
+ lookup = details.reason ?? 'ok'
754
+ }
755
+ }
756
+ const repositoryId = namespacedRepositoryId(mr.url, details.projectId)
757
+ log(
758
+ `ids lookup=${lookup} repository_id=${repositoryId ? 'set' : 'na'} ` +
759
+ `files_changed=${details.filesChanged ?? 'na'}`,
760
+ )
761
+
762
+ const body = buildMrPayload({
763
+ url: mr.url,
764
+ iid: mr.iid,
765
+ repositoryId,
766
+ title: stripDraftPrefix(details.title ?? api.title ?? call.title),
767
+ filesChanged: details.filesChanged,
768
+ sessionId: payload.session_id,
769
+ userEmail,
770
+ userAccountUuid,
771
+ resourceAttrs,
772
+ hostSource: markerHostSource(tool),
773
+ callContext: markerCallContext(tool, payload),
774
+ nowNs: BigInt(Date.now()) * 1_000_000n,
775
+ })
776
+ await emit({ endpoint, bearer, body, label: `!${mr.iid}`, log, timeoutMs: EMIT_TIMEOUT_MS })
777
+ }
778
+
779
+ const main = async () => {
780
+ let payload
781
+ try {
782
+ payload = JSON.parse(await readStdin())
783
+ } catch {
784
+ return // stay silent for anything we can't read
785
+ }
786
+ await handle(payload)
787
+ }
788
+
789
+ // Run the IO path only when executed directly, so tests can import the pure fns.
790
+ // pathToFileURL, not a `file://${argv[1]}` template: a script path with a space
791
+ // (the managed install dir "/Library/Application Support/...") percent-encodes in
792
+ // import.meta.url and a raw template would never match, silently skipping main().
793
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
794
+ await main()
795
+ }