@mainwave/cli 0.9.0 → 0.11.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.
@@ -12,6 +12,7 @@ import { installSkillsPayload } from './skills.js';
12
12
  import { adapterEffective, attributionOf, primaryCarries } from './status.js';
13
13
  import { activeSession, readCredentials, readSettings, rememberKey, resolveEndpoints, updateSettings, } from './store.js';
14
14
  import { isInteractive } from './tty.js';
15
+ import { trimSlash } from './url.js';
15
16
  import { VERSION } from './version.js';
16
17
  import { emitJson, say, setJsonMode } from './ui.js';
17
18
  import { validateCollector } from './validate.js';
@@ -109,6 +110,10 @@ export const ucidRemovalNotice = (plan, onDisk) => onDisk !== undefined && plan.
109
110
  ? `${plan.adapter.displayName}: removing UCID ${onDisk} an earlier setup wrote; activity will ` +
110
111
  `now be attributed from your identity. Pass --ucid ${onDisk} to keep it.`
111
112
  : null;
113
+ export const ucidIgnoredNotice = (adapter, explicitUcid) => adapter.carriesNoUcid && explicitUcid !== undefined
114
+ ? `${adapter.displayName}: its hooks send no use-case id, so --ucid / --use-case don't apply; ` +
115
+ 'its activity is attributed from your email.'
116
+ : null;
112
117
  export const teamUcidNotice = (plan) => {
113
118
  const decision = plan.teamUcid;
114
119
  if (!decision)
@@ -230,6 +235,7 @@ export const redeemInviteToOverrides = async (token, apiUrl, options) => {
230
235
  rememberKeyAs: creds.key_label,
231
236
  collectorUrl: creds.collector_url,
232
237
  userEmail: creds.email,
238
+ userEmailFromInvite: true,
233
239
  };
234
240
  };
235
241
  export const runSetup = async (adapters, rawOptions = {}) => {
@@ -276,12 +282,14 @@ export const runSetup = async (adapters, rawOptions = {}) => {
276
282
  apiUrl: endpoints.apiUrl,
277
283
  });
278
284
  say('');
279
- const { url: collectorUrl, key: apiKey, identity, } = await validateWithRetry(interview.collectorUrl, interview.apiKey, interactive);
285
+ const { url: validatedUrl, key: apiKey, identity, } = await validateWithRetry(interview.collectorUrl, interview.apiKey, interactive);
286
+ const collectorUrl = trimSlash(validatedUrl);
280
287
  const answers = { ...interview, collectorUrl, apiKey };
281
288
  const plans = await Promise.all(adapters.map((adapter, i) => planAdapter(adapter, answers, {
282
289
  onDisk: prefills[i]?.values,
283
290
  storedUseCase: settings.useCase,
284
291
  unpin: options.skipUseCase === true,
292
+ pass: adapters.map((a) => a.name),
285
293
  })));
286
294
  for (const plan of plans)
287
295
  renderPlan(plan);
@@ -292,6 +300,11 @@ export const runSetup = async (adapters, rawOptions = {}) => {
292
300
  say('');
293
301
  say(color.yellow(note));
294
302
  }
303
+ const ignored = ucidIgnoredNotice(plan.adapter, answers.ucid);
304
+ if (ignored) {
305
+ say('');
306
+ say(color.yellow(ignored));
307
+ }
295
308
  const team = teamUcidNotice(plan);
296
309
  if (team) {
297
310
  say('');
@@ -323,7 +336,9 @@ export const runSetup = async (adapters, rawOptions = {}) => {
323
336
  createdAt: new Date().toISOString(),
324
337
  });
325
338
  }
326
- const developerPin = useCase && adapters.some((a) => !a.teamUcid) ? { ...useCase, pinned: true } : undefined;
339
+ const developerPin = useCase && adapters.some((a) => !a.teamUcid && !a.carriesNoUcid)
340
+ ? { ...useCase, pinned: true }
341
+ : undefined;
327
342
  const markerTools = plans.filter((p) => p.markersOn !== null);
328
343
  const hooks = { ...settings.hooks };
329
344
  if (markerTools.length > 0) {
@@ -342,6 +357,13 @@ export const runSetup = async (adapters, rawOptions = {}) => {
342
357
  { ...filesOf(p.adapter.name), [userHooksPath(p.adapter)]: [...p.hookEvents] },
343
358
  ])),
344
359
  };
360
+ hooks.routes = {
361
+ ...hooks.routes,
362
+ ...Object.fromEntries(markerTools.map((p) => [
363
+ p.adapter.name,
364
+ { ...hooks.routes?.[p.adapter.name], [userHooksPath(p.adapter)]: [...p.hookRoutes] },
365
+ ])),
366
+ };
345
367
  }
346
368
  await updateSettings({
347
369
  hooks,
@@ -350,7 +372,9 @@ export const runSetup = async (adapters, rawOptions = {}) => {
350
372
  orgId: identity.orgId ?? settings.orgId,
351
373
  useCase: options.skipUseCase ? null : developerPin,
352
374
  });
353
- const passPin = useCase ?? plans.find((p) => p.keptPin)?.keptPin;
375
+ const passPin = adapters.some((a) => !a.carriesNoUcid)
376
+ ? (useCase ?? plans.find((p) => p.keptPin)?.keptPin)
377
+ : undefined;
354
378
  for (const plan of plans) {
355
379
  if (plan.markersOn !== null) {
356
380
  await printMarkerCoexistenceNotes(plan.adapter, plan.primaryPath, plan.markersOn);
@@ -388,6 +412,7 @@ export const runSetup = async (adapters, rawOptions = {}) => {
388
412
  }, p.adapter),
389
413
  ]))),
390
414
  optIns: answers.optIns,
415
+ optInsByTool: Object.fromEntries(plans.map((p) => [p.adapter.name, p.input.optIns])),
391
416
  markers: answers.markers,
392
417
  ...planSnapshotReport(plans, await blockedSnapshots(plans)),
393
418
  verified,
package/dist/main.js CHANGED
@@ -13,6 +13,7 @@ import { runStatus } from './core/status.js';
13
13
  import { ensureTty, isInteractive } from './core/tty.js';
14
14
  import { VERSION } from './core/version.js';
15
15
  import { runVerify } from './core/verify.js';
16
+ import { runRemove } from './core/remove.js';
16
17
  import { runSetup, runSkillsOnly } from './core/wizard.js';
17
18
  export { VERSION };
18
19
  const printHelp = () => {
@@ -71,6 +72,8 @@ Setup flags (every prompt has one, so scripts and coding agents can drive it):
71
72
  --yes --json --no-verify --verify-timeout <seconds>
72
73
  --skills / --no-skills install the agent skills payload (default: ask, or on in scripts)
73
74
  --skills-only install only the skills, touching no telemetry config
75
+ --remove take this CLI's config for the named tools back off this
76
+ machine (Kiro: its hooks file entries and kiro.env)
74
77
  mainwave-cli --version print version
75
78
 
76
79
  Available adapters:
@@ -277,6 +280,15 @@ export const main = async (argv) => {
277
280
  named.push(resolved);
278
281
  }
279
282
  try {
283
+ if (flagBool(parsed, 'remove') === true) {
284
+ if (named.length === 0) {
285
+ throw new WizardAbort('--remove needs the tools to remove, e.g. `setup kiro-ide --remove`');
286
+ }
287
+ return await runRemove(named, {
288
+ yes: flagBool(parsed, 'yes') === true,
289
+ json: flagBool(parsed, 'json') === true,
290
+ });
291
+ }
280
292
  const opts = setupOptions(parsed);
281
293
  const targets = named.length > 0
282
294
  ? named
@@ -33,6 +33,7 @@ import {
33
33
  buildMarkerPayload,
34
34
  emitMarker,
35
35
  markerLog,
36
+ parseEnvFile,
36
37
  parseKv,
37
38
  readStdin,
38
39
  } from './marker-core.mjs'
@@ -51,32 +52,8 @@ const SERVICE_NAME = 'cursor'
51
52
  // Config resolution — the managed env file this script's OTLP target lives in.
52
53
  // ---------------------------------------------------------------------------
53
54
 
54
- /** Reverse of the env-file codec's double-quoting (KEY="value" with \\ \" \n). */
55
- const unquote = (raw) => {
56
- const v = raw.trim()
57
- if (v.startsWith('"') && v.endsWith('"') && v.length >= 2) {
58
- return v.slice(1, -1).replace(/\\n/g, '\n').replace(/\\"/g, '"').replace(/\\\\/g, '\\')
59
- }
60
- if (v.startsWith("'") && v.endsWith("'") && v.length >= 2) return v.slice(1, -1)
61
- return v
62
- }
63
-
64
- /** Parse a `KEY="value"` env file into a flat record; {} on any error. */
65
- export const parseEnvFile = (text) => {
66
- const out = {}
67
- for (const line of (text ?? '').split('\n')) {
68
- const trimmed = line.trim()
69
- if (trimmed === '' || trimmed.startsWith('#')) continue
70
- let rest = trimmed
71
- if (rest.startsWith('export ')) rest = rest.slice('export '.length).trimStart()
72
- const eq = rest.indexOf('=')
73
- if (eq < 0) continue
74
- const key = rest.slice(0, eq).trim()
75
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) continue
76
- out[key] = unquote(rest.slice(eq + 1))
77
- }
78
- return out
79
- }
55
+ // Re-exported: the parse moved to marker-core.mjs so the Kiro hook shares it.
56
+ export { parseEnvFile }
80
57
 
81
58
  const readFileSafe = (path) => {
82
59
  try {
@@ -0,0 +1,406 @@
1
+ #!/usr/bin/env node
2
+ // The git commit marker: a PostToolUse feature of the Mainwave hook dispatcher
3
+ // (mainwave-hook.mjs) for commits a coding agent makes with `git commit`.
4
+ //
5
+ // Nothing else records which commits an AI session made, or how many lines
6
+ // each one changed per file. This hook runs after each Bash tool call, and
7
+ // when the command ran `git commit` it reads the new commit's short name out
8
+ // of the tool result (git prints `[<branch> <sha>] <subject>` on success),
9
+ // asks git for that commit's numstat, and emits one `vcs.commit.created` span
10
+ // per commit carrying the full sha, the first parent, the totals and the
11
+ // per-file counts.
12
+ //
13
+ // The tool result is what proves the commit happened: a failed commit (nothing
14
+ // to commit, a rejected pre-commit hook, a bad message) prints no such line, so
15
+ // nothing is sent. Neither is anything for `git commit --quiet` or `--dry-run`,
16
+ // which print none either; that miss is accepted. The commit is looked up by
17
+ // the name git printed, not HEAD, so a command that commits twice, or moves
18
+ // HEAD after committing, still reports each commit it made. Git's answer is
19
+ // used only when its full name begins with the printed short name.
20
+ //
21
+ // Privacy: emits repository-relative paths, line counts and object names,
22
+ // never file contents, the diff or the commit message. A binary file (git
23
+ // prints `-` for both counts) counts as changed with 0 lines added and 0
24
+ // removed, and is flagged binary. Claude Code runs this only for a Bash
25
+ // command that starts with `git` (the hook group's `if` filter); it returns
26
+ // immediately, with no log and no work, for anything that isn't a commit, and
27
+ // fails open otherwise: git is given 5 s in all, and any error sends nothing.
28
+
29
+ import { execFile } from 'node:child_process'
30
+ import { isAbsolute, resolve } from 'node:path'
31
+
32
+ import {
33
+ buildMarkerPayload,
34
+ emitMarker,
35
+ hookFlag,
36
+ intAttr,
37
+ loadOtelConfig,
38
+ markerCallContext,
39
+ markerHostSource,
40
+ markerLog,
41
+ markerManagedDir,
42
+ markerOauthAccount,
43
+ markerProjectDir,
44
+ markerSessionEnv,
45
+ markerTool,
46
+ payloadShape,
47
+ toolOutput,
48
+ } from './marker-core.mjs'
49
+ import {
50
+ ATTR_VCS_COMMIT_FILE_IS_BINARY,
51
+ ATTR_VCS_COMMIT_FILE_LINES_ADDED,
52
+ ATTR_VCS_COMMIT_FILE_LINES_REMOVED,
53
+ ATTR_VCS_COMMIT_FILE_PATHS,
54
+ ATTR_VCS_COMMIT_FILES_CHANGED,
55
+ ATTR_VCS_COMMIT_LINES_ADDED,
56
+ ATTR_VCS_COMMIT_LINES_REMOVED,
57
+ ATTR_VCS_COMMIT_PARENT_COUNT,
58
+ ATTR_VCS_COMMIT_PARENT_SHA,
59
+ ATTR_VCS_COMMIT_SHA,
60
+ VCS_COMMIT_CREATED,
61
+ } from './vocabulary.mjs'
62
+
63
+ const LOG_NAME = 'git-commit-marker.log'
64
+
65
+ // Non-coding source/service so the marker lands as an ordinary span and stays
66
+ // out of the coding-work segmentation, as the other markers do. The vendor is
67
+ // git itself: a commit is local, whatever forge it is later pushed to.
68
+ const MARKER_SOURCE = 'hook.git'
69
+ const MARKER_SERVICE = 'mainwave.git-hook'
70
+
71
+ /** The most git may take, over every lookup one tool call makes. */
72
+ export const GIT_TIMEOUT_MS = 5000
73
+
74
+ /** The most commits one tool call reports. */
75
+ export const MAX_COMMITS = 20
76
+
77
+ /** The most files a span lists one by one. The totals always cover every
78
+ * file; past this the per-file lists stop, so their length says how many
79
+ * they hold. */
80
+ export const MAX_FILES = 2000
81
+
82
+ /** Past this many bytes of paths the per-file lists stop too, keeping the
83
+ * span far below the collector's per-attribute bound. */
84
+ export const MAX_PATH_BYTES = 128 * 1024
85
+
86
+ /** git's own output cap for one lookup (a commit touching many files). */
87
+ const MAX_GIT_OUTPUT_BYTES = 16 * 1024 * 1024
88
+
89
+ // A shell word: double-quoted, single-quoted, or bare.
90
+ const WORD = `(?:"[^"]*"|'[^']*'|[^\\s;&|()]+)`
91
+ // git's global options before the subcommand: `-C <dir>`, `-c <k=v>`, and
92
+ // `--flag` / `--flag=value` (`--no-pager`, `--git-dir=…`).
93
+ const GLOBAL_OPTS = `((?:\\s+-[Cc]\\s+${WORD}|\\s+--[A-Za-z-]+(?:=${WORD})?)*)`
94
+ // `git commit` at a command position: the start, after a separator, a
95
+ // subshell or command substitution opener, or a shell keyword; `VAR=value`
96
+ // prefixes allowed. `commit-tree` and `commit-graph` are other commands.
97
+ const GIT_COMMIT_RE = new RegExp(
98
+ `(?:^|&&|\\|\\||[;|\\n({]|\\$\\(|\\b(?:then|do|else)\\s)\\s*` +
99
+ `(?:[A-Za-z_][A-Za-z0-9_]*=${WORD}?\\s+)*` +
100
+ `git${GLOBAL_OPTS}\\s+commit(?![\\w-])`,
101
+ 'g',
102
+ )
103
+
104
+ const unquote = (w) => (/^(["']).*\1$/.test(w) ? w.slice(1, -1) : w)
105
+
106
+ /**
107
+ * Every `git commit` in a Bash command, each with the directory its `-C`
108
+ * options name (relative to the command's own directory), else undefined.
109
+ * Empty when the command runs no commit — the cheap guard every call meets.
110
+ */
111
+ export const findGitCommits = (command) => {
112
+ if (typeof command !== 'string' || !command.includes('commit')) return []
113
+ const out = []
114
+ for (const m of command.matchAll(GIT_COMMIT_RE)) {
115
+ const dirs = [...(m[1] ?? '').matchAll(new RegExp(`-C\\s+(${WORD})`, 'g'))].map((d) =>
116
+ unquote(d[1]),
117
+ )
118
+ out.push({ dir: dirs.length ? dirs.reduce((a, d) => (a ? resolve(a, d) : d)) : undefined })
119
+ }
120
+ return out
121
+ }
122
+
123
+ /** Whether a Bash command runs `git commit` at a command position. */
124
+ export const isGitCommit = (command) => findGitCommits(command).length > 0
125
+
126
+ // git's summary line for a new commit: `[main 1a2b3c4] subject`, also
127
+ // `[main (root-commit) 1a2b3c4]` and `[detached HEAD 1a2b3c4]`. The name is
128
+ // at least 7 hex digits (core.abbrev's floor), up to a SHA-256 name.
129
+ const COMMIT_LINE_RE = /^\[[^\n]*? ([0-9a-f]{7,64})\] /gm
130
+
131
+ /**
132
+ * The short names of the commits a tool result reports, in order, distinct.
133
+ * Reads a bare string or Claude Code's `{stdout, stderr}`; a result with no
134
+ * commit line (a failed or quiet commit) yields none.
135
+ */
136
+ export const commitsInOutput = (output) => {
137
+ const texts =
138
+ typeof output === 'string'
139
+ ? [output]
140
+ : output && typeof output === 'object'
141
+ ? [output.stdout, output.stderr].filter((t) => typeof t === 'string')
142
+ : []
143
+ const shas = []
144
+ for (const text of texts) {
145
+ for (const m of text.matchAll(COMMIT_LINE_RE)) {
146
+ if (!shas.includes(m[1])) shas.push(m[1])
147
+ }
148
+ }
149
+ return shas.slice(0, MAX_COMMITS)
150
+ }
151
+
152
+ /** A numstat count: an integer, or `-` for a binary file. */
153
+ const count = (raw) => (raw === '-' ? undefined : /^\d+$/.test(raw) ? Number(raw) : NaN)
154
+
155
+ /**
156
+ * Parse `git show -z --numstat --format=%H%n%P <sha>` output: the commit's
157
+ * name and parents, then one record per file. With `-z` a record is
158
+ * `<added>\t<removed>\t<path>\0`, or for a rename `<added>\t<removed>\t\0<old
159
+ * path>\0<new path>\0` (the new path is kept). A binary file's counts are
160
+ * `-`: it is kept with 0 and 0 and flagged. Returns undefined for anything
161
+ * that doesn't parse.
162
+ */
163
+ export const parseNumstat = (stdout) => {
164
+ if (typeof stdout !== 'string') return undefined
165
+ const headEnd = stdout.indexOf('\0')
166
+ if (headEnd === -1) return undefined
167
+ const [sha = '', parentLine = ''] = stdout.slice(0, headEnd).split('\n')
168
+ if (!/^[0-9a-f]{40}([0-9a-f]{24})?$/.test(sha)) return undefined
169
+ const parents = parentLine.split(' ').filter(Boolean)
170
+ if (!parents.every((p) => /^[0-9a-f]{40,64}$/.test(p))) return undefined
171
+ const tokens = stdout
172
+ .slice(headEnd + 1)
173
+ .replace(/^\n/, '')
174
+ .split('\0')
175
+ const files = []
176
+ for (let i = 0; i < tokens.length; i++) {
177
+ const token = tokens[i]
178
+ if (token === '') continue
179
+ const m = /^(-|\d+)\t(-|\d+)\t([\s\S]*)$/.exec(token)
180
+ if (!m) return undefined
181
+ let path = m[3]
182
+ if (path === '') {
183
+ // A rename or copy: the old path, then the new one.
184
+ path = tokens[i + 2]
185
+ i += 2
186
+ }
187
+ if (typeof path !== 'string' || path === '') return undefined
188
+ const added = count(m[1])
189
+ const removed = count(m[2])
190
+ if (Number.isNaN(added) || Number.isNaN(removed)) return undefined
191
+ const isBinary = added === undefined || removed === undefined
192
+ files.push({
193
+ path,
194
+ linesAdded: isBinary ? 0 : added,
195
+ linesRemoved: isBinary ? 0 : removed,
196
+ isBinary,
197
+ })
198
+ }
199
+ return { sha, parents, files }
200
+ }
201
+
202
+ /**
203
+ * One commit's numstat, from `git show` run in `cwd`. Resolves undefined on
204
+ * any failure (git absent, not a repository, unknown name, timeout, output
205
+ * that doesn't parse) and when git's full name doesn't begin with `shortSha`.
206
+ * `bin` replaces `git`; `handle` takes it only from the hook's own
207
+ * `--git-bin` flag (tests pass a stub), never from the environment.
208
+ */
209
+ export const fetchCommit = (shortSha, { cwd, bin = 'git', timeoutMs = GIT_TIMEOUT_MS } = {}) =>
210
+ new Promise((done) => {
211
+ if (!/^[0-9a-f]{7,64}$/.test(shortSha ?? '') || timeoutMs <= 0) return done(undefined)
212
+ try {
213
+ execFile(
214
+ bin,
215
+ [
216
+ '--no-pager',
217
+ // A repository's config can name a program git runs on index reads.
218
+ '-c',
219
+ 'core.fsmonitor=false',
220
+ 'show',
221
+ '--no-color',
222
+ '--no-ext-diff',
223
+ '--no-textconv',
224
+ '-z',
225
+ '--numstat',
226
+ '--format=%H%n%P',
227
+ shortSha,
228
+ '--',
229
+ ],
230
+ {
231
+ cwd,
232
+ timeout: timeoutMs,
233
+ maxBuffer: MAX_GIT_OUTPUT_BYTES,
234
+ windowsHide: true,
235
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: '0', GIT_TERMINAL_PROMPT: '0' },
236
+ },
237
+ (err, stdout) => {
238
+ if (err) return done(undefined)
239
+ const commit = parseNumstat(stdout)
240
+ done(commit && commit.sha.startsWith(shortSha) ? commit : undefined)
241
+ },
242
+ )
243
+ } catch {
244
+ done(undefined)
245
+ }
246
+ })
247
+
248
+ /** The span's attributes for one commit: the totals over every file, and the
249
+ * per-file lists up to § MAX_FILES files and § MAX_PATH_BYTES of paths. */
250
+ export const commitAttributes = ({ sha, parents, files }) => {
251
+ const listed = []
252
+ let pathBytes = 0
253
+ for (const f of files) {
254
+ pathBytes += Buffer.byteLength(f.path)
255
+ if (listed.length >= MAX_FILES || pathBytes > MAX_PATH_BYTES) break
256
+ listed.push(f)
257
+ }
258
+ const sum = (k) => files.reduce((n, f) => n + f[k], 0)
259
+ const array = (key, values) => ({ key, value: { arrayValue: { values } } })
260
+ return {
261
+ strings: {
262
+ [ATTR_VCS_COMMIT_SHA]: sha,
263
+ [ATTR_VCS_COMMIT_PARENT_SHA]: parents[0],
264
+ },
265
+ typed: [
266
+ intAttr(ATTR_VCS_COMMIT_PARENT_COUNT, parents.length),
267
+ intAttr(ATTR_VCS_COMMIT_FILES_CHANGED, files.length),
268
+ intAttr(ATTR_VCS_COMMIT_LINES_ADDED, sum('linesAdded')),
269
+ intAttr(ATTR_VCS_COMMIT_LINES_REMOVED, sum('linesRemoved')),
270
+ array(
271
+ ATTR_VCS_COMMIT_FILE_PATHS,
272
+ listed.map((f) => ({ stringValue: f.path })),
273
+ ),
274
+ array(
275
+ ATTR_VCS_COMMIT_FILE_LINES_ADDED,
276
+ listed.map((f) => ({ intValue: String(f.linesAdded) })),
277
+ ),
278
+ array(
279
+ ATTR_VCS_COMMIT_FILE_LINES_REMOVED,
280
+ listed.map((f) => ({ intValue: String(f.linesRemoved) })),
281
+ ),
282
+ array(
283
+ ATTR_VCS_COMMIT_FILE_IS_BINARY,
284
+ listed.map((f) => ({ boolValue: f.isBinary })),
285
+ ),
286
+ ],
287
+ }
288
+ }
289
+
290
+ /** The OTLP/JSON payload for one or more commits: one `vcs.commit.created`
291
+ * span each, in one request. */
292
+ export const buildCommitPayload = ({
293
+ commits,
294
+ sessionId,
295
+ userEmail,
296
+ userAccountUuid,
297
+ resourceAttrs,
298
+ hostSource,
299
+ callContext,
300
+ nowNs,
301
+ }) => {
302
+ const bodies = commits.map((commit) => {
303
+ const { strings, typed } = commitAttributes(commit)
304
+ return buildMarkerPayload({
305
+ spanName: VCS_COMMIT_CREATED,
306
+ scopeName: 'mainwave.git-commit-marker',
307
+ attributes: strings,
308
+ typedAttributes: typed,
309
+ sessionId,
310
+ userEmail,
311
+ userAccountUuid,
312
+ resourceAttrs,
313
+ source: MARKER_SOURCE,
314
+ service: MARKER_SERVICE,
315
+ hostSource,
316
+ callContext,
317
+ nowNs,
318
+ })
319
+ })
320
+ const [first, ...rest] = bodies
321
+ const spans = first.resourceSpans[0].scopeSpans[0].spans
322
+ for (const body of rest) spans.push(...body.resourceSpans[0].scopeSpans[0].spans)
323
+ return first
324
+ }
325
+
326
+ /** The directories to look a commit up in: each `-C` a commit named
327
+ * (against the command's directory), then the command's directory. */
328
+ const lookupDirs = (calls, cwd) => {
329
+ const dirs = calls.map((c) =>
330
+ c.dir === undefined ? cwd : isAbsolute(c.dir) ? c.dir : resolve(cwd, c.dir),
331
+ )
332
+ return [...new Set([...dirs, cwd])]
333
+ }
334
+
335
+ /**
336
+ * The feature: one span per commit the Bash command made, else nothing.
337
+ * `ctx.argv` carries the hook command's flags (and `--tool <host>` under the
338
+ * dispatcher); `ctx.emit` posts.
339
+ */
340
+ export const handle = async (payload, { argv = process.argv, emit = emitMarker } = {}) => {
341
+ // Cheap guard first: no log and no work unless the command ran a commit.
342
+ const calls = findGitCommits(payload?.tool_input?.command)
343
+ if (calls.length === 0) return
344
+ const log = markerLog(argv, LOG_NAME)
345
+
346
+ const shas = commitsInOutput(toolOutput(payload))
347
+ if (shas.length === 0) {
348
+ log(`skip: no new commit in tool output (${payloadShape(payload)})`)
349
+ return
350
+ }
351
+
352
+ const projectDir = markerProjectDir(payload)
353
+ const tool = markerTool(argv)
354
+ const managedDir = markerManagedDir(argv)
355
+ const env = markerSessionEnv(tool, payload)
356
+ const { endpoint, bearer, resourceAttrs } = loadOtelConfig(projectDir, env, tool, managedDir)
357
+ log(
358
+ `commits=${shas.length} endpoint=${endpoint ? 'set' : 'MISSING'} ` +
359
+ `bearer=${bearer ? 'set' : 'MISSING'} ucid=${resourceAttrs['mainwave.ucid'] || 'MISSING'}`,
360
+ )
361
+ if (!endpoint || !bearer) {
362
+ log('skip: collector endpoint/bearer not found in settings or env')
363
+ return
364
+ }
365
+
366
+ // git runs where the agent ran the commit; every lookup shares one budget.
367
+ const cwd = payload.cwd || process.cwd()
368
+ const dirs = lookupDirs(calls, cwd)
369
+ const bin = hookFlag(argv, '--git-bin')
370
+ const deadline = Date.now() + (Number(hookFlag(argv, '--git-timeout-ms')) || GIT_TIMEOUT_MS)
371
+ const commits = []
372
+ for (const sha of shas) {
373
+ let commit
374
+ for (const dir of dirs) {
375
+ commit = await fetchCommit(sha, { cwd: dir, bin, timeoutMs: deadline - Date.now() })
376
+ if (commit) break
377
+ }
378
+ if (commit) commits.push(commit)
379
+ else log(`skip: commit ${sha} not found or git failed`)
380
+ }
381
+ if (commits.length === 0) return
382
+
383
+ // Read only once the emit is certain: `.claude.json` can run to megabytes.
384
+ const { email: userEmail, accountUuid: userAccountUuid } = markerOauthAccount(tool, {
385
+ cwd: projectDir,
386
+ env,
387
+ managedDir,
388
+ })
389
+ const body = buildCommitPayload({
390
+ commits,
391
+ sessionId: payload.session_id,
392
+ userEmail,
393
+ userAccountUuid,
394
+ resourceAttrs,
395
+ hostSource: markerHostSource(tool),
396
+ callContext: markerCallContext(tool, payload),
397
+ nowNs: BigInt(Date.now()) * 1_000_000n,
398
+ })
399
+ await emit({
400
+ endpoint,
401
+ bearer,
402
+ body,
403
+ label: commits.map((c) => c.sha.slice(0, 12)).join(','),
404
+ log,
405
+ })
406
+ }