@mainwave/cli 0.1.1 → 0.2.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.
@@ -0,0 +1,214 @@
1
+ #!/usr/bin/env node
2
+ // Claude Code PostToolUse hook for Linear issue saves (MAI-930).
3
+ //
4
+ // Matches any Linear MCP's issue-save tool. The tool name is `save_issue` on both
5
+ // integrations seen so far; what differs is the server prefix (`mcp__linear__` vs
6
+ // `mcp__linear-server__`), which is what the matcher widens over — see
7
+ // hooks/matchers.json.
8
+ //
9
+ // Claude Code's telemetry records only that the *call* happened — the
10
+ // span carries the tool name and nothing about which ticket. This hook runs
11
+ // after each such call, pulls the Linear issue key out of the tool
12
+ // *result* (the only place a freshly-created issue's key exists), and emits one
13
+ // small OTLP marker span to the same collector Claude Code already exports to,
14
+ // carrying just the issue key + whether it was a create or an update. The
15
+ // platform then counts distinct issue keys for a true "tickets filed" number
16
+ // instead of a call count.
17
+ //
18
+ // Shared OTLP plumbing (config resolution, MAI-936 source neutralization,
19
+ // payload build, fail-open emit) lives in ./marker-core.mjs; this file keeps
20
+ // only the ticket-specific extraction and main(). Privacy: emits the issue key
21
+ // (e.g. "MAI-930") and the operation only — never the ticket title or body.
22
+ // Fails open and fast so a telemetry hiccup can never block or slow the session.
23
+
24
+ import { homedir } from 'node:os'
25
+ import { join } from 'node:path'
26
+ import { pathToFileURL } from 'node:url'
27
+
28
+ import {
29
+ buildMarkerPayload,
30
+ emitMarker,
31
+ loadOtelConfig,
32
+ makeLog,
33
+ markerResourceAttrs as coreMarkerResourceAttrs,
34
+ payloadShape,
35
+ readStdin,
36
+ toolOutput,
37
+ } from './marker-core.mjs'
38
+
39
+ // Re-export the shared pure helpers so existing importers keep resolving them here.
40
+ export {
41
+ bearerFromHeaders,
42
+ parseKv,
43
+ payloadShape,
44
+ resolveOtelConfig,
45
+ settingsEnv,
46
+ toolOutput,
47
+ } from './marker-core.mjs'
48
+
49
+ const log = makeLog(process.env.MAINWAVE_HOOK_LOG || join(homedir(), '.mainwave-ticket-marker.log'))
50
+
51
+ // A source tag the collector does NOT classify as a coding agent, and a service
52
+ // name outside its coding-agent `service.name` allow-list, so the marker lands
53
+ // as an ordinary ("other") span rather than a Claude Code one (MAI-936).
54
+ const MARKER_SOURCE = 'mainwave.ticket_marker'
55
+ const MARKER_SERVICE = 'mainwave.ticket-hook'
56
+
57
+ const KEY = '[A-Z][A-Z0-9]+-\\d+'
58
+
59
+ /** True when `v` is exactly an issue key ("MAI-933"). Case-insensitive, but the
60
+ * full-string anchor rejects a UUID `id` ("9ca7…" starts non-alpha; a UUID that
61
+ * starts with a letter still fails on the `-\d+$` tail) — so trusting `obj.id`
62
+ * is safe on MCPs that return the UUID there instead of the identifier. */
63
+ const isIssueKey = (v) => typeof v === 'string' && new RegExp(`^${KEY}$`, 'i').test(v)
64
+
65
+ /** The issue key from a canonical Linear issue URL's `/issue/<KEY>/` segment. */
66
+ const keyFromUrl = (v) => {
67
+ const m = typeof v === 'string' ? v.match(new RegExp(`/issue/(${KEY})(?:[/?#]|$)`, 'i')) : null
68
+ return m ? m[1].toUpperCase() : undefined
69
+ }
70
+
71
+ /** Normalize a PostToolUse tool output to the save_issue result object, or
72
+ * undefined for a non-JSON string. Handles the MCP content-array wrapper
73
+ * (`[{type:'text', text:'<json>'}]`) by parsing its concatenated text. */
74
+ const resultObject = (toolResult) => {
75
+ let v = toolResult
76
+ if (typeof v === 'string') {
77
+ try {
78
+ v = JSON.parse(v)
79
+ } catch {
80
+ return undefined // a plain string result, not JSON
81
+ }
82
+ }
83
+ if (Array.isArray(v)) {
84
+ const text = v.map((b) => (b && typeof b.text === 'string' ? b.text : '')).join('')
85
+ try {
86
+ return JSON.parse(text)
87
+ } catch {
88
+ return undefined
89
+ }
90
+ }
91
+ return v && typeof v === 'object' ? v : undefined
92
+ }
93
+
94
+ /**
95
+ * Pull the Linear issue key (e.g. "MAI-929") out of a save_issue tool result.
96
+ * For a JSON result object, reads ONLY the authoritative structured fields —
97
+ * `identifier` / `issueIdentifier` / `id`, then the top-level `url`'s issue
98
+ * segment — never the free-text body: a ticket's `description` can reference
99
+ * *other* MAI-XXX tickets (Linear serializes those as `…/issue/MAI-XXX/…`
100
+ * links) and, appearing before the canonical `url`, an earlier blind text scan
101
+ * matched a body reference instead of the ticket actually saved (MAI-985).
102
+ * The plain-string fallback ("Issue MAI-x created") still scans, but requires an
103
+ * `issue`-qualified key so a bare token like a model name ("GPT-5") is ignored.
104
+ * Returns undefined if none is found.
105
+ */
106
+ export const extractIssueKey = (toolResult) => {
107
+ const obj = resultObject(toolResult)
108
+ if (obj) {
109
+ const id = [obj.identifier, obj.issueIdentifier, obj.id].find(isIssueKey)
110
+ if (id) return id.toUpperCase()
111
+ return keyFromUrl(obj.url)
112
+ }
113
+ const text = typeof toolResult === 'string' ? toolResult : ''
114
+ const m = text.match(new RegExp(`issue[\\/\\s]+(${KEY})`, 'i'))
115
+ return m ? m[1].toUpperCase() : undefined
116
+ }
117
+
118
+ /**
119
+ * The canonical Linear issue URL from a save_issue result — the top-level `url`
120
+ * field when it points at an issue. Emitted so the platform can link a ticket key
121
+ * out without knowing the workspace slug (MAI-1007). A URL is not sensitive the way
122
+ * a title or body is, so this keeps the marker's ids-only privacy stance. Reads
123
+ * only the canonical `url` (never the body, which links to *other* tickets, the
124
+ * MAI-985 trap). Undefined for a non-JSON result or a url that isn't an issue link.
125
+ */
126
+ export const extractIssueUrl = (toolResult) => {
127
+ const obj = resultObject(toolResult)
128
+ const url = obj && typeof obj.url === 'string' ? obj.url : undefined
129
+ return url && new RegExp(`/issue/${KEY}`, 'i').test(url) ? url : undefined
130
+ }
131
+
132
+ /**
133
+ * create vs update, preferring the tool NAME when it says so. `save_issue` is one
134
+ * tool for both operations, so the only signal there is whether the input carried
135
+ * an issue id — that stays the fallback, and is the path every Linear integration
136
+ * seen so far actually takes. The name check is defensive: an integration that
137
+ * splits the save into `create_issue` / `update_issue` makes the name
138
+ * authoritative, and misreading a create as an update drops the ticket from
139
+ * "filed" entirely, which is a silent undercount rather than a visible error.
140
+ */
141
+ export const detectOp = (toolName, toolInput) => {
142
+ if (typeof toolName === 'string') {
143
+ if (toolName.endsWith('create_issue')) return 'create'
144
+ if (toolName.endsWith('update_issue')) return 'update'
145
+ }
146
+ return toolInput && toolInput.id ? 'update' : 'create'
147
+ }
148
+
149
+ /** Marker resource attrs with the ticket hook's non-coding source/service (MAI-936). */
150
+ export const markerResourceAttrs = (resourceAttrs) =>
151
+ coreMarkerResourceAttrs(resourceAttrs, MARKER_SOURCE, MARKER_SERVICE)
152
+
153
+ /** Build the OTLP/JSON payload for one ticket-marker span. `issueUrl` is dropped
154
+ * by `buildMarkerPayload` when absent (an older result, or no issue url). */
155
+ export const buildTracePayload = ({ issueKey, issueUrl, op, sessionId, resourceAttrs, nowNs }) =>
156
+ buildMarkerPayload({
157
+ spanName: 'mainwave.ticket_marker',
158
+ scopeName: 'mainwave.linear-ticket-marker',
159
+ attributes: { 'linear.issue_id': issueKey, 'linear.op': op, 'linear.issue_url': issueUrl },
160
+ sessionId,
161
+ resourceAttrs,
162
+ source: MARKER_SOURCE,
163
+ service: MARKER_SERVICE,
164
+ nowNs,
165
+ })
166
+
167
+ const main = async () => {
168
+ let payload
169
+ try {
170
+ payload = JSON.parse(await readStdin())
171
+ } catch {
172
+ log('skip: no parseable hook payload')
173
+ return
174
+ }
175
+
176
+ const output = toolOutput(payload)
177
+ const issueKey = extractIssueKey(output)
178
+ if (!issueKey) {
179
+ log(`skip: no issue key in tool output (${payloadShape(payload)})`)
180
+ return
181
+ }
182
+ const issueUrl = extractIssueUrl(output)
183
+ const op = detectOp(payload.tool_name, payload.tool_input)
184
+
185
+ const cwd = payload.cwd || process.cwd()
186
+ const { endpoint, bearer, resourceAttrs } = loadOtelConfig(cwd, process.env)
187
+ log(
188
+ `issue=${issueKey} op=${op} endpoint=${endpoint ? 'set' : 'MISSING'} ` +
189
+ `bearer=${bearer ? 'set' : 'MISSING'} ucid=${resourceAttrs['mainwave.ucid'] || 'MISSING'}`,
190
+ )
191
+ if (!endpoint || !bearer) {
192
+ log('skip: collector endpoint/bearer not found in settings or env')
193
+ return
194
+ }
195
+
196
+ const body = buildTracePayload({
197
+ issueKey,
198
+ issueUrl,
199
+ op,
200
+ sessionId: payload.session_id,
201
+ resourceAttrs,
202
+ nowNs: BigInt(Date.now()) * 1_000_000n,
203
+ })
204
+ await emitMarker({ endpoint, bearer, body, label: issueKey, log })
205
+ }
206
+
207
+ // Run the IO path only when executed directly, so tests can import the pure fns.
208
+ // Use pathToFileURL so a script path with characters that percent-encode in a
209
+ // file URL (e.g. the space in the managed install dir "/Library/Application
210
+ // Support/…") still matches import.meta.url — a raw `file://${argv[1]}` template
211
+ // keeps the literal space, never matches, and silently skips main(). (MAI-957)
212
+ if (import.meta.url === pathToFileURL(process.argv[1]).href) {
213
+ await main()
214
+ }
@@ -0,0 +1,228 @@
1
+ // Shared plumbing for the Mainwave PostToolUse marker hooks (MAI-930, MAI-942).
2
+ //
3
+ // Both the Linear ticket-marker and the GitHub PR-marker hooks emit one small
4
+ // OTLP span to the same collector Claude Code already exports to, reading the
5
+ // endpoint / auth / ucid from the same `.claude/settings.json` `env` blocks
6
+ // (Claude Code does not hand its OTLP env to hook subprocesses). This module is
7
+ // the half they share: config resolution, resource-attr neutralization (MAI-936),
8
+ // payload building, and the fail-open emit. Each hook keeps only its own
9
+ // extraction logic and `main()`.
10
+
11
+ import { randomBytes } from 'node:crypto'
12
+ import { appendFileSync, readFileSync } from 'node:fs'
13
+ import { homedir } from 'node:os'
14
+ import { join } from 'node:path'
15
+
16
+ const EMIT_TIMEOUT_MS = 3000
17
+
18
+ /** A best-effort appender to `logPath` — never throws (a log hiccup must not
19
+ * surface as a hook failure). */
20
+ export const makeLog = (logPath) => (msg) => {
21
+ try {
22
+ appendFileSync(logPath, `${new Date().toISOString()} ${msg}\n`)
23
+ } catch {
24
+ // logging is best-effort — never let it throw
25
+ }
26
+ }
27
+
28
+ /** Parse a comma-delimited `k=v,k2=v2` string (OTEL_RESOURCE_ATTRIBUTES / _HEADERS). */
29
+ export const parseKv = (raw) => {
30
+ const out = {}
31
+ for (const pair of (raw ?? '').split(',')) {
32
+ const eq = pair.indexOf('=')
33
+ if (eq === -1) continue
34
+ const key = pair.slice(0, eq).trim()
35
+ const value = pair.slice(eq + 1).trim()
36
+ if (key) out[key] = value
37
+ }
38
+ return out
39
+ }
40
+
41
+ /** The Bearer value from an `Authorization=Bearer xyz` OTEL header string. */
42
+ export const bearerFromHeaders = (raw) => {
43
+ for (const [k, v] of Object.entries(parseKv(raw))) {
44
+ if (k.toLowerCase() === 'authorization') return v
45
+ }
46
+ return undefined
47
+ }
48
+
49
+ /** The `env` object from a Claude Code settings.json's text; {} on any error. */
50
+ export const settingsEnv = (text) => {
51
+ try {
52
+ const parsed = JSON.parse(text)
53
+ return parsed && typeof parsed.env === 'object' && parsed.env ? parsed.env : {}
54
+ } catch {
55
+ return {}
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Merge env blocks (lowest precedence first), overlay any real process env on
61
+ * top, and pull out the OTLP config the hooks need. The settings files are the
62
+ * reliable source since Claude Code doesn't hand its telemetry env to hooks.
63
+ */
64
+ export const resolveOtelConfig = (envBlocks, processEnv) => {
65
+ const merged = {}
66
+ for (const block of envBlocks) Object.assign(merged, block)
67
+ for (const k of [
68
+ 'OTEL_EXPORTER_OTLP_ENDPOINT',
69
+ 'OTEL_EXPORTER_OTLP_HEADERS',
70
+ 'OTEL_RESOURCE_ATTRIBUTES',
71
+ ]) {
72
+ if (processEnv[k]) merged[k] = processEnv[k]
73
+ }
74
+ return {
75
+ endpoint: merged.OTEL_EXPORTER_OTLP_ENDPOINT,
76
+ bearer: bearerFromHeaders(merged.OTEL_EXPORTER_OTLP_HEADERS),
77
+ resourceAttrs: parseKv(merged.OTEL_RESOURCE_ATTRIBUTES),
78
+ }
79
+ }
80
+
81
+ const readFileSafe = (path) => {
82
+ try {
83
+ return readFileSync(path, 'utf8')
84
+ } catch {
85
+ return ''
86
+ }
87
+ }
88
+
89
+ /** Settings env blocks Claude Code reads, lowest precedence first. */
90
+ export const settingsEnvBlocks = (cwd) =>
91
+ [
92
+ join(homedir(), '.claude', 'settings.json'),
93
+ join(cwd, '.claude', 'settings.json'),
94
+ join(cwd, '.claude', 'settings.local.json'),
95
+ ].map((p) => settingsEnv(readFileSafe(p)))
96
+
97
+ /** Resolve OTLP config from the settings files at `cwd`, overlaid with process env. */
98
+ export const loadOtelConfig = (cwd, processEnv) =>
99
+ resolveOtelConfig(settingsEnvBlocks(cwd), processEnv)
100
+
101
+ /**
102
+ * Keep the developer's identity attrs — above all `mainwave.ucid`, so the marker
103
+ * attributes to the same use case as the session — but override the two the
104
+ * collector reads to classify a span as a coding agent (`mainwave.source` and
105
+ * `service.name`, see collector `processors/claude_code.rs`). The developer's own
106
+ * `OTEL_RESOURCE_ATTRIBUTES` carries the coding values (mainwave-cli sets
107
+ * `mainwave.source=coding_agent.claude_code`, `service.name=claude-code`);
108
+ * forwarding them verbatim would stamp the marker with a coding source, and the
109
+ * outcome-trend / activity segmentation (MAI-931) would then miscount each marker
110
+ * as a phantom stretch. Each hook passes its own non-coding source/service. (MAI-936)
111
+ */
112
+ export const markerResourceAttrs = (resourceAttrs, source, service) => ({
113
+ ...(resourceAttrs ?? {}),
114
+ 'mainwave.source': source,
115
+ 'service.name': service,
116
+ })
117
+
118
+ const attr = (key, stringValue) => ({ key, value: { stringValue } })
119
+
120
+ /**
121
+ * Build an OTLP/JSON traces payload with a single marker span. `attributes` is a
122
+ * plain string→string map; empty / null / undefined values are dropped (so an
123
+ * absent optional attr like a PR title emits nothing), and `session.id` is
124
+ * appended when present. `resourceAttrs` are neutralized via `markerResourceAttrs`.
125
+ */
126
+ export const buildMarkerPayload = ({
127
+ spanName,
128
+ scopeName,
129
+ attributes,
130
+ sessionId,
131
+ resourceAttrs,
132
+ source,
133
+ service,
134
+ nowNs,
135
+ }) => ({
136
+ resourceSpans: [
137
+ {
138
+ resource: {
139
+ attributes: Object.entries(markerResourceAttrs(resourceAttrs, source, service)).map(
140
+ ([k, v]) => attr(k, v),
141
+ ),
142
+ },
143
+ scopeSpans: [
144
+ {
145
+ scope: { name: scopeName },
146
+ spans: [
147
+ {
148
+ traceId: randomBytes(16).toString('hex'),
149
+ spanId: randomBytes(8).toString('hex'),
150
+ name: spanName,
151
+ kind: 1,
152
+ startTimeUnixNano: String(nowNs),
153
+ endTimeUnixNano: String(nowNs),
154
+ attributes: [
155
+ ...Object.entries(attributes)
156
+ .filter(([, v]) => v !== undefined && v !== null && v !== '')
157
+ .map(([k, v]) => attr(k, String(v))),
158
+ ...(sessionId ? [attr('session.id', sessionId)] : []),
159
+ ],
160
+ },
161
+ ],
162
+ },
163
+ ],
164
+ },
165
+ ],
166
+ })
167
+
168
+ /** POST the OTLP body to the collector, failing open (any error is swallowed). */
169
+ export const emitMarker = async ({
170
+ endpoint,
171
+ bearer,
172
+ body,
173
+ label,
174
+ log,
175
+ timeoutMs = EMIT_TIMEOUT_MS,
176
+ }) => {
177
+ const controller = new AbortController()
178
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
179
+ try {
180
+ const res = await fetch(`${endpoint.replace(/\/$/, '')}/v1/traces`, {
181
+ method: 'POST',
182
+ headers: { 'content-type': 'application/json', authorization: bearer },
183
+ body: JSON.stringify(body),
184
+ signal: controller.signal,
185
+ })
186
+ log(`posted ${label}: status=${res.status}`)
187
+ } catch (e) {
188
+ log(`post failed for ${label}: ${e}`) // fail open — telemetry never blocks the session
189
+ } finally {
190
+ clearTimeout(timer)
191
+ }
192
+ }
193
+
194
+ // The output fields a PostToolUse payload may carry the tool's result under,
195
+ // most-current first. Claude Code v2.1.220 delivers it as `tool_output`; earlier
196
+ // and adjacent schemas used `tool_response` / `tool_result`. The hooks originally
197
+ // read only `tool_result`, which the runtime never populates, so every real call
198
+ // silently emitted nothing (MAI-980).
199
+ const OUTPUT_FIELDS = ['tool_output', 'tool_response', 'tool_result']
200
+
201
+ /** The tool's output from a PostToolUse payload, reading each known output field
202
+ * in turn so a field rename can't silently starve the markers again (MAI-980).
203
+ * The value shape (string, MCP content array, object) is left to the extractors. */
204
+ export const toolOutput = (payload) => {
205
+ for (const k of OUTPUT_FIELDS) {
206
+ if (payload?.[k] !== undefined && payload?.[k] !== '') return payload[k]
207
+ }
208
+ return undefined
209
+ }
210
+
211
+ /** A value-free description of a hook payload for skip diagnostics: which top-level
212
+ * keys are present and which output field (if any) carried data. Records enough to
213
+ * spot a schema drift from the log alone, without ever logging ticket/PR content. */
214
+ export const payloadShape = (payload) => {
215
+ if (!payload || typeof payload !== 'object') return `non-object payload (${typeof payload})`
216
+ const present = OUTPUT_FIELDS.find((k) => payload[k] !== undefined && payload[k] !== '')
217
+ return `keys=[${Object.keys(payload).join(',')}] output_field=${present ?? 'none'}`
218
+ }
219
+
220
+ /** Read all of stdin as a string; resolves '' on error. */
221
+ export const readStdin = () =>
222
+ new Promise((resolve) => {
223
+ let buf = ''
224
+ process.stdin.setEncoding('utf8')
225
+ process.stdin.on('data', (c) => (buf += c))
226
+ process.stdin.on('end', () => resolve(buf))
227
+ process.stdin.on('error', () => resolve(''))
228
+ })
@@ -0,0 +1,17 @@
1
+ [
2
+ {
3
+ "hook": "linear-ticket-marker.mjs",
4
+ "matcher": "^mcp__.*[Ll]inear.*__(save|create|update)_issue$",
5
+ "why": "The server PREFIX is what varies: this workspace connects Linear as mcp__linear-server__save_issue, the older integration as mcp__linear__save_issue — same tool name, and matching only the latter is what silently emitted nothing. create_issue / update_issue are covered defensively in case an integration splits the save; detectOp reads the op off the tool name and falls back to the input's id. Anchored because linear-server really does expose create_issue_label."
6
+ },
7
+ {
8
+ "hook": "github-pr-marker.mjs",
9
+ "matcher": "Bash",
10
+ "why": "Built-in tool — exact name. Fires on every Bash call but returns immediately unless the command was 'gh pr create'."
11
+ },
12
+ {
13
+ "hook": "jira-ticket-marker.mjs",
14
+ "matcher": "^mcp__.*[Aa]tlassian.*__(createJiraIssue|editJiraIssue)$",
15
+ "why": "The Atlassian MCP keeps its tool names stable but the server prefix varies (mcp__atlassian__, mcp__claude_ai_Atlassian_Rovo__). detectOp already matches on the tool-name suffix, so widening the prefix is all that is needed. Anchored to exclude the other *JiraIssue tools (transition, addComment, ...)."
16
+ }
17
+ ]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mainwave/cli",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Setup wizard for connecting third-party coding tools to Mainwave AI.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -8,6 +8,7 @@
8
8
  },
9
9
  "files": [
10
10
  "dist",
11
+ "hooks",
11
12
  "README.md",
12
13
  "LICENSE"
13
14
  ],
@@ -34,6 +35,7 @@
34
35
  "format:check": "prettier --check .",
35
36
  "test": "vitest",
36
37
  "test:run": "vitest run",
38
+ "test:hooks": "node --test tests/hooks/*.test.mjs",
37
39
  "prepare": "lefthook install"
38
40
  },
39
41
  "dependencies": {