@mainwave/cli 0.10.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.
package/README.md CHANGED
@@ -170,7 +170,7 @@ mainwave-cli setup claude-code codex \
170
170
  | `--ucid <id\|url>` / `--use-case <name>` / `--no-use-case` | pin one use case, or `--no-use-case` to unpin (default: none) |
171
171
  | `--email <e>` | attribution identity for tools that need it injected |
172
172
  | `--opt-in prompts,tool-details,tool-content,repository` (or `all` / `none`) | content capture (default: all on; `none` sends metadata only; `repository` is Claude Code's repository names) |
173
- | `--no-markers` | skip the Mainwave hooks (installed by default): the ticket & PR markers and the Claude plan snapshot |
173
+ | `--no-markers` | skip the Mainwave hooks (installed by default): ticket, PR & commit markers, the Claude plan snapshot |
174
174
  | `--new-key` | mint a fresh machine key instead of reusing this machine's |
175
175
  | `--yes` | write without the confirmation prompt |
176
176
  | `--no-verify` / `--verify-timeout <s>` | the closing first-span check |
@@ -229,6 +229,14 @@ title, project id and the changed-file count. Never ticket bodies, never diff co
229
229
  open — a telemetry problem can never block or slow a coding session — and count forward only from
230
230
  when you enable them.
231
231
 
232
+ The same install adds a **commit marker**: when a Bash command that begins with `git` runs
233
+ `git commit`, the hook reads each new commit with `git show --numstat` (5 seconds at most) and
234
+ emits one event per commit. What leaves your machine: the commit's id and its parent's id, how many
235
+ files it changes and how many lines it adds and removes, and for each file its path inside the
236
+ repository, its added and removed line counts and whether it is binary (a binary file counts 0
237
+ lines). Never the commit message, never file contents. A commit that fails sends nothing, and so
238
+ does `git commit --quiet`, which prints no commit line to read.
239
+
232
240
  For Claude Code, the same install adds a **Claude plan snapshot**: a hook on Claude Code's
233
241
  `UserPromptSubmit` event (each prompt you submit) that reads Claude Code's local account record (`.claude.json`) and sends one event every time
234
242
  it runs. What leaves your machine: your Claude account id, organization id and email (the identity
@@ -84,6 +84,7 @@ const parseEnv = (env) => {
84
84
  };
85
85
  return out;
86
86
  };
87
+ const stripTrailingSlash = (url) => url.replace(/\/+$/, '');
87
88
  const buildEnv = ({ ucid, collectorUrl, apiKey, optIns, userEmail, }) => {
88
89
  const env = {
89
90
  CLAUDE_CODE_ENABLE_TELEMETRY: '1',
@@ -92,7 +93,7 @@ const buildEnv = ({ ucid, collectorUrl, apiKey, optIns, userEmail, }) => {
92
93
  OTEL_METRICS_EXPORTER: 'otlp',
93
94
  OTEL_LOGS_EXPORTER: 'otlp',
94
95
  OTEL_EXPORTER_OTLP_PROTOCOL: 'http/protobuf',
95
- OTEL_EXPORTER_OTLP_ENDPOINT: collectorUrl,
96
+ OTEL_EXPORTER_OTLP_ENDPOINT: stripTrailingSlash(collectorUrl),
96
97
  OTEL_EXPORTER_OTLP_HEADERS: `Authorization=Bearer ${apiKey}`,
97
98
  OTEL_RESOURCE_ATTRIBUTES: buildResourceAttrs(ucid, userEmail),
98
99
  };
@@ -114,30 +114,24 @@ const normalizeForGenericChecks = (env) => ({
114
114
  auth: undefined,
115
115
  ucid: undefined,
116
116
  });
117
- const printPostSetupInstructions = (_input, scope = 'global') => {
118
- const envFile = scope === 'local' ? ENV_FILE_LOCAL_PATH : ENV_FILE_GLOBAL_PATH;
117
+ const printPostSetupInstructions = (_input) => {
119
118
  if (osPlatform() === 'win32') {
120
119
  return [
121
120
  color.bold('Make the OTEL vars visible to VS Code on next launch:'),
122
121
  '',
123
- ` Copy the four KEY=VALUE lines from ${color.cyan(envFile)}, then in PowerShell run`,
122
+ ` Copy the four KEY=VALUE lines from ${color.cyan(ENV_FILE_GLOBAL_PATH)}, then in PowerShell run`,
124
123
  ` ${color.cyan('setx KEY "VALUE"')} for each.`,
125
124
  '',
126
125
  color.dim(' Fully close and reopen VS Code (close all windows + tray icon).'),
127
126
  color.dim(' `code --reload-window` is not enough — env is captured at process start.'),
128
127
  ].join('\n');
129
128
  }
130
- const epilogue = scope === 'global'
131
- ? [
132
- '',
133
- color.bold('Then fully restart VS Code:'),
134
- color.dim(' Cmd+Q + reopen (Reload Window is NOT enough — env is captured once per'),
135
- color.dim(' process by the shell-env resolver on GUI launch).'),
136
- ]
137
- : ['', color.bold('Then launch VS Code from this terminal:'), ` ${color.cyan('code .')}`];
138
129
  return [
139
- renderEnvFileBlock(envFile, scope),
140
- ...epilogue,
130
+ renderEnvFileBlock(ENV_FILE_GLOBAL_PATH),
131
+ '',
132
+ color.bold('Then fully restart VS Code:'),
133
+ color.dim(' Cmd+Q + reopen (Reload Window is NOT enough — env is captured once per'),
134
+ color.dim(' process by the shell-env resolver on GUI launch).'),
141
135
  '',
142
136
  color.dim('Verify the GUI shell-env reflects the file:'),
143
137
  ` ${color.cyan('mainwave-cli doctor copilot-chat --validate')}`,
@@ -58,18 +58,15 @@ const normalizeForGenericChecks = (env) => {
58
58
  }
59
59
  return { endpoint, auth, ucid };
60
60
  };
61
- const printPostSetupInstructions = (_input, scope = 'global') => {
62
- const file = scope === 'local' ? LOCAL_PATH : GLOBAL_PATH;
63
- return [
64
- renderEnvFileBlock(file, scope),
65
- '',
66
- color.dim('Cross-shell alternative (any shell):'),
67
- ` ${color.cyan('eval "$(mainwave-cli env copilot-cli)"')}`,
68
- '',
69
- color.bold('Then run:'),
70
- ` ${color.cyan('copilot')}`,
71
- ].join('\n');
72
- };
61
+ const printPostSetupInstructions = (_input) => [
62
+ renderEnvFileBlock(GLOBAL_PATH),
63
+ '',
64
+ color.dim('Cross-shell alternative (any shell):'),
65
+ ` ${color.cyan('eval "$(mainwave-cli env copilot-cli)"')}`,
66
+ '',
67
+ color.bold('Then run:'),
68
+ ` ${color.cyan('copilot')}`,
69
+ ].join('\n');
73
70
  const HIERARCHY = [
74
71
  {
75
72
  id: 'projectLocal',
@@ -4,7 +4,7 @@ import { adapters } from '../adapters/index.js';
4
4
  import { activeHierarchy, effectiveEnv } from './effective-settings.js';
5
5
  import { color, renderDiff } from './format.js';
6
6
  import { claudeHookShellMissing, GIT_BASH_FIX, GIT_BASH_MISSING_REASON } from './git-bash.js';
7
- import { activeManagedScans, BOOTSTRAP_KEY, commandGeneration, copyHookScripts, DEFAULT_MARKER_TOOL, describeMarkersPlan, hooksBlocked, hostRunsBootstrap, installedHooksDir, isPlanSnapshot, isPlanSnapshotRoute, legacyCommandSends, managedDeliversEntry, managedDeliversPlanSnapshot, managedHooksDir, managedMarkerDeliveries, matchersForTool, packagedHooksDir, planMarkers, prepareMarkersFile, readPackagedMatchers, routeLabel, scanForMarkers, scanRoutes, selectHookMatchers, syncManagedHooks, syncOrgDelivered, userHookGroups, writeOptOutFlags, } from './markers.js';
7
+ import { activeManagedScans, BOOTSTRAP_KEY, commandGeneration, copyHookScripts, DEFAULT_MARKER_TOOL, deliveryKey, describeMarkersPlan, hooksBlocked, hostRunsBootstrap, installedHooksDir, isPlanSnapshot, isPlanSnapshotRoute, legacyCommandSends, managedDeliversEntry, managedDeliversPlanSnapshot, managedHooksDir, managedMarkerDeliveries, matchersForTool, packagedHooksDir, planMarkers, prepareMarkersFile, readPackagedMatchers, routeLabel, scanForMarkers, scanRoutes, selectHookMatchers, syncManagedHooks, syncOrgDelivered, userHookGroups, writeOptOutFlags, } from './markers.js';
8
8
  import { isManagedLayer } from './layer-policy.js';
9
9
  import { adapterEffective } from './status.js';
10
10
  import { applyUpdate, prepareUpdate, readExistingEnv } from './settings.js';
@@ -106,6 +106,7 @@ export const planAdapter = async (adapter, answers, context = {}) => {
106
106
  let hookHost = null;
107
107
  let stageHooks = false;
108
108
  let hookEvents = [];
109
+ let hookRoutes = [];
109
110
  let orgDeliversEntry = false;
110
111
  let hookShellMissing = false;
111
112
  if (markersOn !== null) {
@@ -123,6 +124,12 @@ export const planAdapter = async (adapter, answers, context = {}) => {
123
124
  ...selected.map((m) => m.event),
124
125
  ]),
125
126
  ];
127
+ hookRoutes = [
128
+ ...new Set([
129
+ ...(stageHooks && hostRunsBootstrap(hookHost) ? [BOOTSTRAP_KEY] : []),
130
+ ...selected.map((m) => deliveryKey(m.event, m.route)),
131
+ ]),
132
+ ];
126
133
  const managedScans = adapter.markers?.hooksFile
127
134
  ? []
128
135
  : await scanForMarkers((await activeHierarchy(adapter)).filter(isManagedLayer));
@@ -182,6 +189,7 @@ export const planAdapter = async (adapter, answers, context = {}) => {
182
189
  hookHost,
183
190
  stageHooks,
184
191
  hookEvents,
192
+ hookRoutes,
185
193
  orgDeliversEntry,
186
194
  hookShellMissing,
187
195
  ...(teamUcid ? { teamUcid } : {}),
@@ -364,7 +372,7 @@ export const printPostSetup = (plan) => {
364
372
  'starts, resumes or forks: it refreshes the hook scripts from the latest release and keeps the hooks above ' +
365
373
  'current, on the same events only — a new kind of hook waits for your next setup run.'));
366
374
  }
367
- const snippet = plan.adapter.printPostSetupInstructions?.(plan.input, 'global');
375
+ const snippet = plan.adapter.printPostSetupInstructions?.(plan.input);
368
376
  if (snippet) {
369
377
  say('');
370
378
  say(snippet);
@@ -4,7 +4,13 @@ export const HOOK_NODE_ENTRY_SCRIPT = 'mainwave-hook-node.mjs';
4
4
  export const ORG_DELIVERED_MARK = 'org-delivered';
5
5
  export const HOOK_ENTRY_MARK = 'mainwave hook entry v2';
6
6
  export const ENTRY_HOSTS = ['claude-code', 'codex'];
7
- export const CODEX_BASH_FILTER = ['*pr*create*', '*mr*create*', '*mr*new*', '*merge_requests*'];
7
+ export const CODEX_BASH_FILTER = [
8
+ '*pr*create*',
9
+ '*mr*create*',
10
+ '*mr*new*',
11
+ '*merge_requests*',
12
+ '*git*commit*',
13
+ ];
8
14
  export const entryRouteKey = ({ host, event, route }) => `${host}/${event}/${route ?? ''}`;
9
15
  const SAFE_TOKEN = /^[A-Za-z0-9._+-]+$/;
10
16
  const shQuote = (value) => `'${value.replace(/'/g, `'\\''`)}'`;
@@ -3,10 +3,11 @@ import { claudeConfigDir } from '../adapters/claude-code.js';
3
3
  import { hasPath } from './detect.js';
4
4
  import { activeHierarchy } from './effective-settings.js';
5
5
  import { isManagedLayer } from './layer-policy.js';
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
+ import { bootstrapGroup, buildHookGroups, DEFAULT_MARKER_TOOL, groupEvent, isBootstrapCommand, isDelivered, managedDeliversEntry, managedHooksDir, managedMarkerDeliveries, matchersForTool, packagedHooksDir, prepareMarkersFile, readPackagedMatchers, routeKeyOf, scanForMarkers, syncManagedHooks, syncOrgDelivered, userHookGroups, } from './markers.js';
7
7
  import { applyUpdate } from './settings.js';
8
8
  import { readSettings } from './store.js';
9
9
  import { VERSION } from './version.js';
10
+ export const ROUTES_BEFORE_RECORD_EXCLUDES = ['PostToolUse:git'];
10
11
  export const PAYLOAD_EVENTS = [
11
12
  'SessionStart',
12
13
  'UserPromptSubmit',
@@ -43,12 +44,20 @@ export const installHooks = async (adapter, paths = defaultPaths()) => {
43
44
  const stored = paths.stored ?? (await readSettings().catch(() => ({}))).hooks ?? {};
44
45
  const userSettings = adapter.paths.global;
45
46
  const disclosed = stored.events?.[adapter.name]?.[userSettings];
47
+ const disclosedRoutes = stored.routes?.[adapter.name]?.[userSettings];
46
48
  let removedFromUser = 0;
47
49
  let addedToUser = 0;
48
50
  if ((managedDelivers || disclosed !== undefined) && hasPath(userSettings)) {
49
51
  const groups = disclosed === undefined
50
52
  ? []
51
- : userHookGroups(matchersForTool(all, DEFAULT_MARKER_TOOL), { markers: stored.markers?.[adapter.name] ?? true }, delivered, DEFAULT_MARKER_TOOL).filter((g) => disclosed.includes(groupEvent(g)));
53
+ : userHookGroups(matchersForTool(all, DEFAULT_MARKER_TOOL), { markers: stored.markers?.[adapter.name] ?? true }, delivered, DEFAULT_MARKER_TOOL).filter((g) => disclosed.includes(groupEvent(g)) &&
54
+ g.hooks.every((h) => {
55
+ const key = routeKeyOf(h.command);
56
+ return (key === undefined ||
57
+ (disclosedRoutes === undefined
58
+ ? !ROUTES_BEFORE_RECORD_EXCLUDES.includes(key)
59
+ : disclosedRoutes.includes(key)));
60
+ }));
52
61
  const { update, plan } = await prepareMarkersFile(userSettings, adapter.codec, groups, 0o600, (ownership, group) => ownership === 'cli' &&
53
62
  ((!isBootstrapCommand(group.command) &&
54
63
  isDelivered(delivered, group.event, group.command)) ||
@@ -643,6 +643,7 @@ export const markerLogFiles = (home = homedir()) => [
643
643
  logFile(home, 'Jira tickets', 'jira-ticket-marker.log', '.mainwave-jira-ticket-marker.log'),
644
644
  logFile(home, 'PRs', 'pr-marker.log', '.mainwave-pr-marker.log'),
645
645
  logFile(home, 'GitLab MRs', 'glab-mr-marker.log', '.mainwave-glab-mr-marker.log'),
646
+ logFile(home, 'Git commits', 'git-commit-marker.log', '.mainwave-git-commit-marker.log'),
646
647
  {
647
648
  ...logFile(home, 'Claude plan snapshots', 'plan-snapshot.log', '.mainwave-plan-snapshot.log.ok'),
648
649
  activityPath: join(hookLogDir(home), 'plan-snapshot.log.ok'),
@@ -791,7 +792,8 @@ export const routeLabel = (key) => {
791
792
  UserPromptSubmit: 'the Claude plan snapshot',
792
793
  'PostToolUse:gh': 'the GitHub PR marker',
793
794
  'PostToolUse:glab': 'the GitLab MR marker',
794
- 'PostToolUse:bash': 'the PR and MR markers',
795
+ 'PostToolUse:git': 'the git commit marker',
796
+ 'PostToolUse:bash': 'the PR, MR and commit markers',
795
797
  'PostToolUse:linear': 'the Linear ticket marker',
796
798
  'PostToolUse:jira': 'the Jira ticket marker',
797
799
  StopFailure: 'the Claude turn-error span',
@@ -1139,8 +1141,8 @@ export const entryIssues = async (managedDir, matchers, managed, nodeEntry = fal
1139
1141
  if (missing.length > 0) {
1140
1142
  return [
1141
1143
  {
1142
- level: 'error',
1143
- message: `Release ${id} of the Mainwave hooks lacks ${missing.join(', ')}, so the hooks that need ${missing.length === 1 ? 'it' : 'them'} send nothing. ${fix}`,
1144
+ level: 'warn',
1145
+ message: `Release ${id} of the Mainwave hooks lacks ${missing.join(', ')}, so the hooks that need ${missing.length === 1 ? 'it' : 'them'} send nothing until a newer release is installed. ${fix}`,
1144
1146
  },
1145
1147
  ];
1146
1148
  }
@@ -1,5 +1,5 @@
1
1
  import { homedir, platform as osPlatform } from 'node:os';
2
- import { basename, isAbsolute, join } from 'node:path';
2
+ import { basename, join } from 'node:path';
3
3
  import { color } from './format.js';
4
4
  const detectShellKind = () => {
5
5
  const shellEnv = process.env.SHELL;
@@ -41,31 +41,14 @@ const profile = (kind) => {
41
41
  return { kind, rcFile: '~/.profile', oneShot: posixOneShot, rcLine: posixRcLine };
42
42
  };
43
43
  const indent = (line) => ` ${line}`;
44
- export const renderEnvFileBlock = (envFile, scope) => {
44
+ export const renderEnvFileBlock = (envFile) => {
45
45
  const sh = profile(detectShellKind());
46
46
  const shellLabel = sh.kind === 'unknown' ? 'your shell' : sh.kind;
47
- if (scope === 'global') {
48
- return [
49
- color.bold(`Persist for every ${shellLabel} session — add to ${sh.rcFile}:`),
50
- '',
51
- indent(color.cyan(sh.rcLine(envFile))),
52
- '',
53
- color.dim(` (or one-shot for the current terminal: ${color.reset(sh.oneShot(envFile))})`),
54
- ].join('\n');
55
- }
56
- const absoluteEnvFile = isAbsolute(envFile) ? envFile : join(process.cwd(), envFile);
57
47
  return [
58
- color.bold('Per-project setup — two options below. Pick the one(s) you want:'),
59
- '',
60
- color.bold('1. Current terminal (one-shot):'),
61
- indent(color.cyan(sh.oneShot(envFile))),
48
+ color.bold(`Persist for every ${shellLabel} session — add to ${sh.rcFile}:`),
62
49
  '',
63
- color.bold(`2. GUI launches (Spotlight/Dock) — add to ${sh.rcFile}:`),
64
- indent(color.cyan(sh.rcLine(absoluteEnvFile))),
65
- color.dim(' The rc line points at this project by absolute path, so VS Code picks'),
66
- color.dim(' it up on GUI launch. Comment out / swap the line when changing projects.'),
50
+ indent(color.cyan(sh.rcLine(envFile))),
67
51
  '',
68
- color.dim(`Or, to auto-load per directory, install direnv and add to ./.envrc:`),
69
- indent(color.cyan(`source_env ${envFile}`)),
52
+ color.dim(` (or one-shot for the current terminal: ${color.reset(sh.oneShot(envFile))})`),
70
53
  ].join('\n');
71
54
  };
@@ -132,8 +132,8 @@ export const planBlockRemoval = async (path) => {
132
132
  note: `${path}: remove Mainwave's instructions, keep the rest`,
133
133
  };
134
134
  };
135
- export const installToSurface = async (adapterName, surface, scope, version, srcRoot = packagedSkillsDir(), installedRoot = installedSkillsDir(), names = SKILL_NAMES) => {
136
- const target = scope === 'local' ? surface.local : surface.global;
135
+ export const installToSurface = async (adapterName, surface, version, srcRoot = packagedSkillsDir(), installedRoot = installedSkillsDir(), names = SKILL_NAMES) => {
136
+ const target = surface.global;
137
137
  if (surface.kind === 'skill-dir') {
138
138
  for (const name of names)
139
139
  await copySkillBundle(name, srcRoot, target);
@@ -171,7 +171,7 @@ export const installSkillsPayload = async (adapters, version, srcRoot = packaged
171
171
  if (seen.has(surface.global))
172
172
  continue;
173
173
  seen.add(surface.global);
174
- installs.push(await installToSurface(adapter.name, surface, 'global', version, srcRoot, installedRoot, names));
174
+ installs.push(await installToSurface(adapter.name, surface, version, srcRoot, installedRoot, names));
175
175
  }
176
176
  return { installs, noOps, bundleDir: join(installedRoot) };
177
177
  };
@@ -2,6 +2,7 @@ import { promises as fs } from 'node:fs';
2
2
  import { homedir } from 'node:os';
3
3
  import { dirname, join } from 'node:path';
4
4
  import { isErrnoCode } from './settings.js';
5
+ import { trimSlash } from './url.js';
5
6
  export const mainwaveDir = () => join(homedir(), '.mainwave');
6
7
  export const settingsPath = () => join(mainwaveDir(), 'settings.json');
7
8
  export const credentialsPath = () => join(mainwaveDir(), 'credentials.json');
@@ -76,7 +77,6 @@ export const rememberKey = async (orgId, key) => {
76
77
  const credentials = await readCredentials();
77
78
  await writeCredentials({ ...credentials, keys: { ...credentials.keys, [orgId]: key } });
78
79
  };
79
- const trimSlash = (url) => url.replace(/\/+$/, '');
80
80
  export const resolveEndpoints = (settings, overrides = {}, env = process.env) => ({
81
81
  apiUrl: trimSlash(overrides.apiUrl ?? env.MAINWAVE_API_URL ?? settings.apiUrl ?? DEFAULTS.apiUrl),
82
82
  appUrl: trimSlash(overrides.appUrl ?? env.MAINWAVE_APP_URL ?? settings.appUrl ?? DEFAULTS.appUrl),
@@ -0,0 +1 @@
1
+ export const trimSlash = (url) => url.replace(/\/+$/, '');
@@ -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';
@@ -281,7 +282,8 @@ export const runSetup = async (adapters, rawOptions = {}) => {
281
282
  apiUrl: endpoints.apiUrl,
282
283
  });
283
284
  say('');
284
- 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);
285
287
  const answers = { ...interview, collectorUrl, apiKey };
286
288
  const plans = await Promise.all(adapters.map((adapter, i) => planAdapter(adapter, answers, {
287
289
  onDisk: prefills[i]?.values,
@@ -355,6 +357,13 @@ export const runSetup = async (adapters, rawOptions = {}) => {
355
357
  { ...filesOf(p.adapter.name), [userHooksPath(p.adapter)]: [...p.hookEvents] },
356
358
  ])),
357
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
+ };
358
367
  }
359
368
  await updateSettings({
360
369
  hooks,
@@ -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
+ }
@@ -52,12 +52,13 @@ export const WATCHDOG_MS = 9000
52
52
  * Caps are each feature's own worst case plus 250 ms: the plan snapshot's
53
53
  * 4 s send; the PR marker's 5 s `gh pr view` and 3 s post; the MR marker's
54
54
  * 2.5 s lookup and 1.5 s post; the ticket markers' and the StopFailure
55
- * span's 3 s post.
55
+ * span's 3 s post; the commit marker's 5 s of git and 3 s post.
56
56
  */
57
57
  export const FEATURES = Object.freeze({
58
58
  'plan-snapshot': { module: 'plan-snapshot.mjs', capMs: 4250, optOut: 'markers' },
59
59
  'github-pr-marker': { module: 'github-pr-marker.mjs', capMs: 8250, optOut: 'markers' },
60
60
  'glab-mr-marker': { module: 'glab-mr-marker.mjs', capMs: 4250, optOut: 'markers' },
61
+ 'git-commit-marker': { module: 'git-commit-marker.mjs', capMs: 8250, optOut: 'markers' },
61
62
  'linear-ticket-marker': { module: 'linear-ticket-marker.mjs', capMs: 3250, optOut: 'markers' },
62
63
  'jira-ticket-marker': { module: 'jira-ticket-marker.mjs', capMs: 3250, optOut: 'markers' },
63
64
  'stop-failure': { module: 'stop-failure.mjs', capMs: 3250, optOut: 'markers' },
@@ -66,17 +67,18 @@ export const FEATURES = Object.freeze({
66
67
  /**
67
68
  * `<host> <Event>[ <route>]` → the features that run there. Mirrors the
68
69
  * 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.
70
+ * filter, so its one Bash route runs the pull-request markers and the commit
71
+ * marker, which each check the command themselves.
71
72
  */
72
73
  export const ROUTES = Object.freeze({
73
74
  'claude-code UserPromptSubmit': ['plan-snapshot'],
74
75
  'claude-code PostToolUse gh': ['github-pr-marker'],
75
76
  'claude-code PostToolUse glab': ['glab-mr-marker'],
77
+ 'claude-code PostToolUse git': ['git-commit-marker'],
76
78
  'claude-code PostToolUse linear': ['linear-ticket-marker'],
77
79
  'claude-code PostToolUse jira': ['jira-ticket-marker'],
78
80
  'claude-code StopFailure': ['stop-failure'],
79
- 'codex PostToolUse bash': ['github-pr-marker', 'glab-mr-marker'],
81
+ 'codex PostToolUse bash': ['github-pr-marker', 'glab-mr-marker', 'git-commit-marker'],
80
82
  'codex PostToolUse linear': ['linear-ticket-marker'],
81
83
  'codex PostToolUse jira': ['jira-ticket-marker'],
82
84
  })
@@ -43,11 +43,26 @@
43
43
  ],
44
44
  "why": "Built-in tool, exact name, narrowed by the handler's `if` to Bash commands that start with `glab`. The feature still returns immediately unless the command was 'glab mr create' or a POST of 'glab api' to a project's merge_requests endpoint. The feature's own detector also accepts env, sudo and exec wrappers and a path-qualified glab, which `glab *` doesn't match; that miss is accepted rather than widening the `if`."
45
45
  },
46
+ {
47
+ "event": "PostToolUse",
48
+ "route": "git",
49
+ "matcher": "Bash",
50
+ "if": "Bash(git *)",
51
+ "features": ["git-commit-marker"],
52
+ "optOut": "markers",
53
+ "hosts": ["claude-code"],
54
+ "dataClasses": [
55
+ "commit sha and first parent sha",
56
+ "changed-file, added-line and removed-line counts",
57
+ "repository-relative file paths with per-file added and removed line counts and a binary flag"
58
+ ],
59
+ "why": "Built-in tool, exact name, narrowed by the handler's `if` to Bash commands that start with `git`. The feature still returns immediately unless the command ran 'git commit' at a command position, and sends nothing unless the tool output carries git's new-commit summary line, so a failed commit sends nothing. Each commit is then read with `git show --numstat` under a 5 s budget. A commit that isn't the command's first word (`cd x && git commit`) is matched by the feature but not by `git *`; that miss is accepted rather than widening the `if` to every Bash command."
60
+ },
46
61
  {
47
62
  "event": "PostToolUse",
48
63
  "route": "bash",
49
64
  "matcher": "Bash",
50
- "features": ["github-pr-marker", "glab-mr-marker"],
65
+ "features": ["github-pr-marker", "glab-mr-marker", "git-commit-marker"],
51
66
  "optOut": "markers",
52
67
  "hosts": ["codex"],
53
68
  "dataClasses": [
@@ -55,9 +70,11 @@
55
70
  "changed-file, added-line and removed-line counts",
56
71
  "merge request url, iid and title",
57
72
  "instance-namespaced project id",
58
- "changed-file count"
73
+ "changed-file count",
74
+ "commit sha and first parent sha",
75
+ "repository-relative file paths with per-file added and removed line counts and a binary flag"
59
76
  ],
60
- "why": "Codex has no `if` filter, so one Bash group serves both pull-request markers: the shell entry reads the hook input and starts Node only when it contains `pr`…`create`, `mr`…`create`, `mr`…`new` or `merge_requests` — a superset of what the two features' own detectors accept."
77
+ "why": "Codex has no `if` filter, so one Bash group serves the pull-request markers and the commit marker: the shell entry reads the hook input and starts Node only when it contains `pr`…`create`, `mr`…`create`, `mr`…`new`, `merge_requests` or `git`…`commit` — a superset of what the three features' own detectors accept."
61
78
  },
62
79
  {
63
80
  "event": "PostToolUse",
@@ -40,6 +40,19 @@ export const VCS_PROVIDER_GITHUB: string
40
40
  export const VCS_PROVIDER_GITLAB: string
41
41
  export const VCS_MARKER_KEYS: readonly string[]
42
42
 
43
+ export const VCS_COMMIT_CREATED: string
44
+ export const ATTR_VCS_COMMIT_SHA: string
45
+ export const ATTR_VCS_COMMIT_PARENT_SHA: string
46
+ export const ATTR_VCS_COMMIT_PARENT_COUNT: string
47
+ export const ATTR_VCS_COMMIT_FILES_CHANGED: string
48
+ export const ATTR_VCS_COMMIT_LINES_ADDED: string
49
+ export const ATTR_VCS_COMMIT_LINES_REMOVED: string
50
+ export const ATTR_VCS_COMMIT_FILE_PATHS: string
51
+ export const ATTR_VCS_COMMIT_FILE_LINES_ADDED: string
52
+ export const ATTR_VCS_COMMIT_FILE_LINES_REMOVED: string
53
+ export const ATTR_VCS_COMMIT_FILE_IS_BINARY: string
54
+ export const VCS_COMMIT_KEYS: readonly string[]
55
+
43
56
  export const ATTR_CODE_FILE_PATH: string
44
57
  export const CODE_KEYS: readonly string[]
45
58
 
@@ -163,6 +163,46 @@ export const VCS_MARKER_KEYS = [
163
163
  ATTR_VCS_CHANGE_LINES_REMOVED,
164
164
  ]
165
165
 
166
+ // ── Commit events — CLI git-commit-marker hook ───────────────────────────────
167
+ // One span per commit a coding agent made with `git commit`, read from
168
+ // `git show --numstat` for that commit. OTel's vcs namespace has no commit
169
+ // entity (v1.44.0 names a revision only as `vcs.ref.head.revision`), so these
170
+ // are house keys under the pinned vcs namespace, worded like the change size
171
+ // keys above.
172
+ export const VCS_COMMIT_CREATED = 'vcs.commit.created'
173
+
174
+ // The commit's full object name, and its first parent's (absent on a root
175
+ // commit). A merge commit has more than one parent; `parent_count` says so.
176
+ export const ATTR_VCS_COMMIT_SHA = 'vcs.commit.sha'
177
+ export const ATTR_VCS_COMMIT_PARENT_SHA = 'vcs.commit.parent_sha'
178
+ export const ATTR_VCS_COMMIT_PARENT_COUNT = 'vcs.commit.parent_count'
179
+ // Totals over every file in the commit. A binary file counts as changed and
180
+ // adds 0 lines either way.
181
+ export const ATTR_VCS_COMMIT_FILES_CHANGED = 'vcs.commit.files_changed'
182
+ export const ATTR_VCS_COMMIT_LINES_ADDED = 'vcs.commit.lines_added'
183
+ export const ATTR_VCS_COMMIT_LINES_REMOVED = 'vcs.commit.lines_removed'
184
+ // Per file, as four parallel OTLP arrays: element i of each describes the same
185
+ // file. Paths are repository-relative, as git prints them; a rename carries
186
+ // its new path. The lists may hold fewer files than `files_changed` on a very
187
+ // large commit (the hook caps them); the totals always cover every file.
188
+ export const ATTR_VCS_COMMIT_FILE_PATHS = 'vcs.commit.file.paths'
189
+ export const ATTR_VCS_COMMIT_FILE_LINES_ADDED = 'vcs.commit.file.lines_added'
190
+ export const ATTR_VCS_COMMIT_FILE_LINES_REMOVED = 'vcs.commit.file.lines_removed'
191
+ export const ATTR_VCS_COMMIT_FILE_IS_BINARY = 'vcs.commit.file.is_binary'
192
+
193
+ export const VCS_COMMIT_KEYS = [
194
+ ATTR_VCS_COMMIT_SHA,
195
+ ATTR_VCS_COMMIT_PARENT_SHA,
196
+ ATTR_VCS_COMMIT_PARENT_COUNT,
197
+ ATTR_VCS_COMMIT_FILES_CHANGED,
198
+ ATTR_VCS_COMMIT_LINES_ADDED,
199
+ ATTR_VCS_COMMIT_LINES_REMOVED,
200
+ ATTR_VCS_COMMIT_FILE_PATHS,
201
+ ATTR_VCS_COMMIT_FILE_LINES_ADDED,
202
+ ATTR_VCS_COMMIT_FILE_LINES_REMOVED,
203
+ ATTR_VCS_COMMIT_FILE_IS_BINARY,
204
+ ]
205
+
166
206
  // ── File references — CLI cursor behaviour hook ──────────────────────────────
167
207
  // The standard OTel Code (Stable) key, replacing the hook's former
168
208
  // `cursor.file_path`.
@@ -284,7 +324,7 @@ export const SUBSCRIPTION_SNAPSHOT_KEYS = [
284
324
 
285
325
  // Every governed v2 event name the CLI hooks emit — checked against the
286
326
  // registry's events_v2 lists.
287
- export const CLI_EVENT_NAMES = [WI_CREATED, WI_UPDATED, VCS_OPENED]
327
+ export const CLI_EVENT_NAMES = [WI_CREATED, WI_UPDATED, VCS_OPENED, VCS_COMMIT_CREATED]
288
328
 
289
329
  // ── Claude Code turn failures — CLI hook feature ─────────────────────────────
290
330
  // One more span under `mainwave.source = hook.anthropic`, beside the plan
@@ -329,6 +369,7 @@ export const FEATURE_EMITS = Object.freeze({
329
369
  },
330
370
  'github-pr-marker': { spans: [VCS_OPENED], keys: VCS_MARKER_KEYS, prefixes: [] },
331
371
  'glab-mr-marker': { spans: [VCS_OPENED], keys: VCS_MARKER_KEYS, prefixes: [] },
372
+ 'git-commit-marker': { spans: [VCS_COMMIT_CREATED], keys: VCS_COMMIT_KEYS, prefixes: [] },
332
373
  'linear-ticket-marker': {
333
374
  spans: [WI_CREATED, WI_UPDATED],
334
375
  keys: WORK_MARKER_KEYS,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mainwave/cli",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "Setup wizard for connecting third-party coding tools to Mainwave AI.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -36,22 +36,22 @@
36
36
  "format:check": "prettier --check .",
37
37
  "test": "vitest",
38
38
  "test:run": "vitest run",
39
- "test:hooks": "node --test tests/hooks/*.test.mjs",
39
+ "test:hooks": "node tests/hooks/check-node.mjs && node --import ./tests/hooks/setup.mjs --test tests/hooks/*.test.mjs",
40
40
  "prepare": "lefthook install",
41
41
  "api:generate": "openapi-ts"
42
42
  },
43
43
  "dependencies": {
44
- "@inquirer/prompts": "8.7.2",
44
+ "@inquirer/prompts": "8.7.3",
45
45
  "picocolors": "1.1.1"
46
46
  },
47
47
  "devDependencies": {
48
48
  "@hey-api/openapi-ts": "^0.99.0",
49
49
  "@types/node": "22.20.5",
50
- "lefthook": "2.1.16",
51
- "oxlint": "1.86.0",
52
- "prettier": "3.9.9",
50
+ "lefthook": "2.2.1",
51
+ "oxlint": "1.87.0",
52
+ "prettier": "3.9.10",
53
53
  "typescript": "6.0.3",
54
- "vite": "8.3.2",
54
+ "vite": "8.3.4",
55
55
  "vitest": "5.0.3",
56
56
  "yaml": "2.9.1"
57
57
  },
@@ -25,8 +25,11 @@ Answer these from the codebase, not from assumption:
25
25
  `ai` (with `@ai-sdk/otel`), `openai`, `@anthropic-ai/sdk`. More than one can
26
26
  apply. Note the installed versions: eve `>=0.66.3 <0.70.0`, `ai` `^7` with
27
27
  `@ai-sdk/otel` `^1`, `openai` `>=4.19.0 <8`, `@anthropic-ai/sdk`
28
- `>=0.51.0 <1`. A version outside its range is not instrumented: report it, do
29
- not wire around it.
28
+ `>=0.51.0 <0.134.0`. A version outside its range is not instrumented: report it, do
29
+ not wire around it. `@anthropic-ai/sdk` 0.134.0 and later emit their own
30
+ OpenTelemetry spans, so the SDK leaves them unpatched with one warning and
31
+ exports the client's own spans as they are; to get the SDK's Anthropic spans,
32
+ the app pins `@anthropic-ai/sdk` below 0.134.0.
30
33
  - **Does the app already register OpenTelemetry?** Search for `@vercel/otel`
31
34
  (`registerOTel`), `@opentelemetry/sdk-node` (`NodeSDK`),
32
35
  `NodeTracerProvider`, a Next.js `instrumentation.ts`, or an eve
@@ -280,10 +283,13 @@ instrument({ openai, anthropic })
280
283
  **Pass every module copy the app loads.** An ES module import and a
281
284
  `require()` result are two different copies, and a copy that was not passed is
282
285
  not traced: `instrument({ openai: [esm, required] })`. `instrument()` returns
283
- `{ openai: 'patched' }`, `'already'` (attached before), or `'unrecognized'`
284
- (what it was given is not the module), and never throws. Read the result: an
285
- `'unrecognized'` means the wiring is wrong, and a client missing from the
286
- spans usually means the code calls a copy you did not pass.
286
+ `{ openai: 'patched' }`, `'already'` (attached before), `'unsupported'`
287
+ (Anthropic only: an `@anthropic-ai/sdk` 0.134.0 or later client, which emits
288
+ its own spans), or `'unrecognized'` (what it was given is not the module), and
289
+ never throws. Read the result: an `'unrecognized'` means the wiring is wrong,
290
+ an `'unsupported'` means the app's Anthropic client is above the supported
291
+ range, and a client missing from the spans usually means the code calls a copy
292
+ you did not pass.
287
293
 
288
294
  An ES module app that uses neither the flag nor `instrument()` gets no spans
289
295
  from these clients and one not-attached warning naming both options.
@@ -5,20 +5,20 @@ the package is internal: do not import from `dist/` paths.
5
5
 
6
6
  ## Root exports (`@mainwave/sdk`)
7
7
 
8
- | Export | Use |
9
- | ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
10
- | `init(options)` | Owned mode: build a tracer provider and export every LLM trace. Once per process. Throws `MainwaveConfigError` for a missing key |
11
- | `createSpanProcessor(options)` | Host mode: one processor to pass to the host's provider. Same options as `init()` except `mode` |
12
- | `run(runId, [options], fn)` | A run around a block; resolves with what `fn` returns |
13
- | `startRun(runId, [options])` | A run you end yourself; bind a block with `handle.with(fn)`; `handle.end({ status, description, reason, decision, iterations, cost })` |
14
- | `span(name, [{ attributes }], fn)` | A custom span; `fn` gets the OpenTelemetry `Span` |
15
- | `bindIdentity({ useCaseId, useCaseKey, agentName }, fn)` | Bind a use case and agent name to every span started inside `fn` |
16
- | `instrument({ openai, anthropic })` | Attach to the module(s) passed; returns `'patched'`, `'already'` or `'unrecognized'` per client; never throws |
17
- | `flush({ timeoutMs })` | Send everything buffered; resolves `true` when accepted, `false` otherwise; never rejects. Default 30,000 ms |
18
- | `shutdown()` | Flush, shut the provider or processor down, remove the SDK's listeners; safe to call twice |
19
- | `useCaseIdFor(key)` | The UUID a key derives to; throws `MainwaveConfigError` before `init()` or `createSpanProcessor()`, or when disabled |
20
- | `registerFramework(name, [version])`, `VERSION` | Record a framework name on exported spans (for a custom integration); package version |
21
- | `MainwaveError`, `MainwaveConfigError`, `MainwaveReinitConflict` | Error classes. Config errors are invalid caller input; reinit conflict is a second `init()` with a different configuration |
8
+ | Export | Use |
9
+ | ---------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
10
+ | `init(options)` | Owned mode: build a tracer provider and export every LLM trace. Once per process. Throws `MainwaveConfigError` for a missing key |
11
+ | `createSpanProcessor(options)` | Host mode: one processor to pass to the host's provider. Same options as `init()` except `mode` |
12
+ | `run(runId, [options], fn)` | A run around a block; resolves with what `fn` returns |
13
+ | `startRun(runId, [options])` | A run you end yourself; bind a block with `handle.with(fn)`; `handle.end({ status, description, reason, decision, iterations, cost })` |
14
+ | `span(name, [{ attributes }], fn)` | A custom span; `fn` gets the OpenTelemetry `Span` |
15
+ | `bindIdentity({ useCaseId, useCaseKey, agentName }, fn)` | Bind a use case and agent name to every span started inside `fn` |
16
+ | `instrument({ openai, anthropic })` | Attach to the module(s) passed; returns `'patched'`, `'already'`, `'unsupported'` (Anthropic 0.134.0+) or `'unrecognized'` per client; never throws |
17
+ | `flush({ timeoutMs })` | Send everything buffered; resolves `true` when accepted, `false` otherwise; never rejects. Default 30,000 ms |
18
+ | `shutdown()` | Flush, shut the provider or processor down, remove the SDK's listeners; safe to call twice |
19
+ | `useCaseIdFor(key)` | The UUID a key derives to; throws `MainwaveConfigError` before `init()` or `createSpanProcessor()`, or when disabled |
20
+ | `registerFramework(name, [version])`, `VERSION` | Record a framework name on exported spans (for a custom integration); package version |
21
+ | `MainwaveError`, `MainwaveConfigError`, `MainwaveReinitConflict` | Error classes. Config errors are invalid caller input; reinit conflict is a second `init()` with a different configuration |
22
22
 
23
23
  Before `init()` or `createSpanProcessor()`, `run()`, `startRun()`, `span()` and
24
24
  `bindIdentity()` run their callbacks without telemetry and log one warning.
@@ -4,14 +4,16 @@ Supported ranges are the optional peer dependencies the application installs.
4
4
  A version outside its range is not instrumented and logs one warning with the
5
5
  package, version, and range: report it to the user instead of wiring around it.
6
6
 
7
- | Framework | Range | Wiring |
8
- | ------------- | ---------------------------------- | ------------------------------------------------------ |
9
- | eve | `>=0.66.3 <0.70.0`, Node 24+ | `mainwave()` from `@mainwave/sdk/eve`; no `init()` |
10
- | Vercel AI SDK | `ai` `^7` with `@ai-sdk/otel` `^1` | `registerTelemetry(mainwaveTelemetry())` |
11
- | OpenAI | `openai` `>=4.19.0 <8` | loader flag, `instrument({ openai })`, or the class |
12
- | Anthropic | `@anthropic-ai/sdk` `>=0.51.0 <1` | loader flag, `instrument({ anthropic })`, or the class |
13
-
14
- AI SDK v5 and v6 are not supported.
7
+ | Framework | Range | Wiring |
8
+ | ------------- | --------------------------------------- | ------------------------------------------------------ |
9
+ | eve | `>=0.66.3 <0.70.0`, Node 24+ | `mainwave()` from `@mainwave/sdk/eve`; no `init()` |
10
+ | Vercel AI SDK | `ai` `^7` with `@ai-sdk/otel` `^1` | `registerTelemetry(mainwaveTelemetry())` |
11
+ | OpenAI | `openai` `>=4.19.0 <8` | loader flag, `instrument({ openai })`, or the class |
12
+ | Anthropic | `@anthropic-ai/sdk` `>=0.51.0 <0.134.0` | loader flag, `instrument({ anthropic })`, or the class |
13
+
14
+ AI SDK v5 and v6 are not supported. `@anthropic-ai/sdk` 0.134.0 and later emit
15
+ their own OpenTelemetry spans: the SDK leaves them unpatched with one warning,
16
+ and their own spans export as they are.
15
17
 
16
18
  ## eve
17
19