@mainwave/cli 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +137 -41
- package/dist/adapters/claude-code.js +23 -4
- package/dist/adapters/codex-cli.js +1 -1
- package/dist/adapters/cursor.js +2 -2
- package/dist/core/apply.js +151 -41
- package/dist/core/doctor.js +26 -8
- package/dist/core/effective-settings.js +10 -0
- package/dist/core/entry-script.js +90 -0
- package/dist/core/git-bash.js +40 -0
- package/dist/core/install-hooks.js +126 -43
- package/dist/core/interview.js +53 -3
- package/dist/core/markers.js +678 -140
- package/dist/core/settings.js +16 -5
- package/dist/core/status.js +2 -1
- package/dist/core/wizard.js +46 -1
- package/dist/main.js +16 -9
- package/hooks/cursor-otlp.mjs +1 -1
- package/hooks/github-pr-marker.mjs +35 -22
- package/hooks/glab-mr-marker.mjs +795 -0
- package/hooks/jira-ticket-marker.mjs +27 -15
- package/hooks/linear-ticket-marker.mjs +27 -15
- package/hooks/mainwave-hook-node.mjs +42 -0
- package/hooks/mainwave-hook.mjs +301 -0
- package/hooks/marker-core.mjs +273 -40
- package/hooks/matchers.json +82 -6
- package/hooks/plan-snapshot.mjs +529 -0
- package/hooks/stop-failure.mjs +43 -0
- package/hooks/vocabulary.d.mts +48 -0
- package/hooks/vocabulary.mjs +181 -0
- package/package.json +5 -5
- package/skills/mainwave-instrument/SKILL.md +21 -7
- package/skills/mainwave-instrument/reference/api.md +29 -10
- package/skills/mainwave-instrument/reference/frameworks.md +3 -3
- package/skills/mainwave-instrument/reference/troubleshooting.md +12 -5
- package/skills/mainwave-setup/SKILL.md +47 -12
package/hooks/marker-core.mjs
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
// Shared plumbing for the Mainwave
|
|
1
|
+
// Shared plumbing for the Mainwave hook features the dispatcher
|
|
2
|
+
// (mainwave-hook.mjs) runs: the PostToolUse ticket and PR markers, the Claude
|
|
3
|
+
// plan snapshot on UserPromptSubmit, and the StopFailure span (a turn that
|
|
4
|
+
// ended on an API error).
|
|
2
5
|
//
|
|
3
6
|
// Both the Linear ticket-marker and the GitHub PR-marker hooks emit one small
|
|
4
7
|
// OTLP span to the same collector Claude Code already exports to, reading the
|
|
@@ -9,7 +12,15 @@
|
|
|
9
12
|
// extraction logic and `main()`.
|
|
10
13
|
|
|
11
14
|
import { randomBytes } from 'node:crypto'
|
|
12
|
-
import {
|
|
15
|
+
import {
|
|
16
|
+
appendFileSync,
|
|
17
|
+
mkdirSync,
|
|
18
|
+
readFileSync,
|
|
19
|
+
readdirSync,
|
|
20
|
+
renameSync,
|
|
21
|
+
statSync,
|
|
22
|
+
writeFileSync,
|
|
23
|
+
} from 'node:fs'
|
|
13
24
|
import { homedir } from 'node:os'
|
|
14
25
|
import { basename, dirname, isAbsolute, join, resolve } from 'node:path'
|
|
15
26
|
|
|
@@ -26,16 +37,52 @@ import {
|
|
|
26
37
|
|
|
27
38
|
const EMIT_TIMEOUT_MS = 3000
|
|
28
39
|
|
|
29
|
-
/**
|
|
30
|
-
*
|
|
31
|
-
export const
|
|
40
|
+
/** Where every hook log lives by default: `~/.mainwave/logs/`, never the home
|
|
41
|
+
* directory itself. */
|
|
42
|
+
export const logDir = () => join(homedir(), '.mainwave', 'logs')
|
|
43
|
+
|
|
44
|
+
/** A hook log's default path: `name` in `~/.mainwave/logs/`. */
|
|
45
|
+
export const defaultLogPath = (name) => join(logDir(), name)
|
|
46
|
+
|
|
47
|
+
/** Create the directory a log file goes in, owner-only, if it is missing.
|
|
48
|
+
* Throws like any write; callers are best-effort. */
|
|
49
|
+
export const ensureLogDir = (logPath) =>
|
|
50
|
+
mkdirSync(dirname(logPath), { recursive: true, mode: 0o700 })
|
|
51
|
+
|
|
52
|
+
/** Every hook log's size bound. Past it the file is rotated to `<name>.1`, so
|
|
53
|
+
* a log keeps between this and twice this of recent history and never more
|
|
54
|
+
* than twice this on disk. */
|
|
55
|
+
export const LOG_MAX_BYTES = 256 * 1024
|
|
56
|
+
|
|
57
|
+
/** Move a too-big log to `<name>.1` (replacing the previous one). If the move
|
|
58
|
+
* fails (a directory squatting on `.1`, a permissions oddity), empty the log
|
|
59
|
+
* instead: losing history beats a log that grows without bound. Two hooks
|
|
60
|
+
* rotating at once may drop a few lines; neither throws. */
|
|
61
|
+
const rotateLog = (logPath) => {
|
|
32
62
|
try {
|
|
33
|
-
|
|
63
|
+
renameSync(logPath, `${logPath}.1`)
|
|
34
64
|
} catch {
|
|
35
|
-
|
|
65
|
+
writeFileSync(logPath, '')
|
|
36
66
|
}
|
|
37
67
|
}
|
|
38
68
|
|
|
69
|
+
/** A best-effort appender to `logPath` — never throws (a log hiccup must not
|
|
70
|
+
* surface as a hook failure). Creates the log's directory on demand. A file
|
|
71
|
+
* already larger than `maxBytes` is rotated (§ `rotateLog`) before the line
|
|
72
|
+
* lands, so a hook that runs on every prompt can't grow its log without
|
|
73
|
+
* bound and the history before the cap survives in `<name>.1`. */
|
|
74
|
+
export const makeLog =
|
|
75
|
+
(logPath, maxBytes = LOG_MAX_BYTES) =>
|
|
76
|
+
(msg) => {
|
|
77
|
+
try {
|
|
78
|
+
ensureLogDir(logPath)
|
|
79
|
+
if (statSync(logPath, { throwIfNoEntry: false })?.size > maxBytes) rotateLog(logPath)
|
|
80
|
+
appendFileSync(logPath, `${new Date().toISOString()} ${msg}\n`, { mode: 0o600 })
|
|
81
|
+
} catch {
|
|
82
|
+
// logging is best-effort — never let it throw
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
39
86
|
/**
|
|
40
87
|
* The value after `name` in the hook's own argv, or undefined. A flag is the
|
|
41
88
|
* one input a checked-out repository can't set: the hook command lives in the
|
|
@@ -49,12 +96,17 @@ export const hookFlag = (argv, name) => {
|
|
|
49
96
|
return i !== -1 && argv[i + 1] ? argv[i + 1] : undefined
|
|
50
97
|
}
|
|
51
98
|
|
|
52
|
-
/** The hook's log: `--log-file <path>` when the hook command passes one
|
|
53
|
-
* do), else `defaultName` in
|
|
54
|
-
* (§ `hookFlag`): a line logged here can carry a value the
|
|
55
|
-
* so the repository mustn't choose the file it lands in
|
|
56
|
-
|
|
57
|
-
|
|
99
|
+
/** The hook's log path: `--log-file <path>` when the hook command passes one
|
|
100
|
+
* (tests do), else `defaultName` in `~/.mainwave/logs/`. Never from the
|
|
101
|
+
* environment (§ `hookFlag`): a line logged here can carry a value the
|
|
102
|
+
* repository chose, so the repository mustn't choose the file it lands in
|
|
103
|
+
* either. */
|
|
104
|
+
export const markerLogPath = (argv, defaultName) =>
|
|
105
|
+
hookFlag(argv, '--log-file') || defaultLogPath(defaultName)
|
|
106
|
+
|
|
107
|
+
/** The hook's log (§ `markerLogPath`). */
|
|
108
|
+
export const markerLog = (argv, defaultName, maxBytes = LOG_MAX_BYTES) =>
|
|
109
|
+
makeLog(markerLogPath(argv, defaultName), maxBytes)
|
|
58
110
|
|
|
59
111
|
/**
|
|
60
112
|
* The project root whose `.claude/` settings Claude Code loaded for this
|
|
@@ -205,6 +257,28 @@ const readFileSafe = (path) => {
|
|
|
205
257
|
}
|
|
206
258
|
}
|
|
207
259
|
|
|
260
|
+
/**
|
|
261
|
+
* A `readFile` / `listDir` pair that reads each settings file and lists each
|
|
262
|
+
* drop-in directory once per hook run. The sign-in gate (§ `hasApiKeyHelper`)
|
|
263
|
+
* and the OTLP lookup (§ `settingsLayers`) read the same user, project, local
|
|
264
|
+
* and managed files; a second pass over them is time the hook doesn't need to spend. Only for one run: a
|
|
265
|
+
* long-lived cache would miss an edit.
|
|
266
|
+
*/
|
|
267
|
+
export const onceReaders = (readFile = readFileSafe, listDir = jsonFilesIn) => {
|
|
268
|
+
const files = new Map()
|
|
269
|
+
const dirs = new Map()
|
|
270
|
+
return {
|
|
271
|
+
readFile: (path) => {
|
|
272
|
+
if (!files.has(path)) files.set(path, readFile(path))
|
|
273
|
+
return files.get(path)
|
|
274
|
+
},
|
|
275
|
+
listDir: (dir) => {
|
|
276
|
+
if (!dirs.has(dir)) dirs.set(dir, listDir(dir))
|
|
277
|
+
return dirs.get(dir)
|
|
278
|
+
},
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
208
282
|
/** `CLAUDE_CONFIG_DIR`, ASCII-trimmed and resolved to an absolute path, or
|
|
209
283
|
* `undefined` when unset or blank — a whitespace-only value counts as unset.
|
|
210
284
|
* For the settings root (§ `claudeConfigDir`) only: the account cache is
|
|
@@ -454,7 +528,7 @@ export const markerHostSource = (tool) =>
|
|
|
454
528
|
* `String.prototype.trim`, whose Unicode `WhiteSpace`/`LineTerminator`
|
|
455
529
|
* set also strips NBSP and other characters the collector would keep — so a
|
|
456
530
|
* value trimmed here matches byte-for-byte what the collector sees. */
|
|
457
|
-
const trimAscii = (s) => s.replace(/^[ \t\n\r\v\f]+|[ \t\n\r\v\f]+$/g, '')
|
|
531
|
+
export const trimAscii = (s) => s.replace(/^[ \t\n\r\v\f]+|[ \t\n\r\v\f]+$/g, '')
|
|
458
532
|
|
|
459
533
|
/** A file's UTF-8 text, or `undefined` when it is missing or unreadable. */
|
|
460
534
|
const readOrUndefined = (path) => {
|
|
@@ -467,25 +541,34 @@ const readOrUndefined = (path) => {
|
|
|
467
541
|
|
|
468
542
|
/** A string field ASCII-trimmed (§ `trimAscii`), or `undefined` for a
|
|
469
543
|
* non-string or a value that trims to empty. */
|
|
470
|
-
const trimmedOrUndefined = (v) =>
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
*
|
|
475
|
-
* `undefined`
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
} catch {
|
|
481
|
-
return {}
|
|
482
|
-
}
|
|
544
|
+
export const trimmedOrUndefined = (v) =>
|
|
545
|
+
typeof v === 'string' ? trimAscii(v) || undefined : undefined
|
|
546
|
+
|
|
547
|
+
/** `oauthAccount.emailAddress` and `oauthAccount.accountUuid` from one parsed
|
|
548
|
+
* `.claude.json` document, each ASCII-trimmed (§ `trimAscii`) and each
|
|
549
|
+
* independently `undefined` when missing, non-string, or blank. The one
|
|
550
|
+
* place a Claude account's identity is normalized: the markers read it
|
|
551
|
+
* through § `oauthAccountFromText`, the plan snapshot directly. */
|
|
552
|
+
export const oauthAccountFromRecord = (doc) => {
|
|
553
|
+
const account = doc?.oauthAccount
|
|
483
554
|
return {
|
|
484
555
|
email: trimmedOrUndefined(account?.emailAddress),
|
|
485
556
|
accountUuid: trimmedOrUndefined(account?.accountUuid),
|
|
486
557
|
}
|
|
487
558
|
}
|
|
488
559
|
|
|
560
|
+
/** § `oauthAccountFromRecord` over one `.claude.json`'s text, parsed once.
|
|
561
|
+
* Both fields are `undefined` for unparseable JSON. */
|
|
562
|
+
export const oauthAccountFromText = (text) => {
|
|
563
|
+
let doc
|
|
564
|
+
try {
|
|
565
|
+
doc = JSON.parse(text)
|
|
566
|
+
} catch {
|
|
567
|
+
return {}
|
|
568
|
+
}
|
|
569
|
+
return oauthAccountFromRecord(doc)
|
|
570
|
+
}
|
|
571
|
+
|
|
489
572
|
/**
|
|
490
573
|
* Claude Code's own account cache — `.claude.json` (a top-level dotfile,
|
|
491
574
|
* distinct from the `~/.claude/` settings directory) — written by its Claude.ai
|
|
@@ -516,10 +599,16 @@ const oauthAccountFromText = (text) => {
|
|
|
516
599
|
* or changed shape.
|
|
517
600
|
*/
|
|
518
601
|
export const claudeCodeOauthAccount = (home = homedir(), configDir) => {
|
|
519
|
-
const text = readOrUndefined(
|
|
602
|
+
const text = readOrUndefined(claudeAccountPath(home, configDir))
|
|
520
603
|
return text === undefined ? {} : oauthAccountFromText(text)
|
|
521
604
|
}
|
|
522
605
|
|
|
606
|
+
/** Where Claude Code keeps its account cache, resolved exactly as
|
|
607
|
+
* § `claudeCodeOauthAccount` describes: `join(CLAUDE_CONFIG_DIR || home,
|
|
608
|
+
* '.claude.json')`, the raw `configDir`, a relative one against the cwd. */
|
|
609
|
+
export const claudeAccountPath = (home = homedir(), configDir) =>
|
|
610
|
+
resolve(configDir || home, '.claude.json')
|
|
611
|
+
|
|
523
612
|
/** Env vars whose mere non-blank presence (ASCII-trimmed, § `trimAscii`) means
|
|
524
613
|
* the Claude Code session does NOT authenticate through Claude.ai OAuth, so
|
|
525
614
|
* `.claude.json`'s `oauthAccount` — which survives a switch to any of these —
|
|
@@ -637,19 +726,33 @@ export const hasApiKeyHelper = (
|
|
|
637
726
|
*
|
|
638
727
|
* `opts`: `env` (default `process.env`), `home` (default `homedir()`), `cwd`
|
|
639
728
|
* (the project root, § `markerProjectDir`; default `process.cwd()`, used for
|
|
640
|
-
* the project-local `apiKeyHelper` check),
|
|
641
|
-
* and `configDir` — when the key is present its value is used as-is
|
|
729
|
+
* the project-local `apiKeyHelper` check), `configDir` — when the key is present its value is used as-is
|
|
642
730
|
* (`undefined` = unset), otherwise `env.CLAUDE_CONFIG_DIR`, raw
|
|
643
|
-
* (§ `claudeCodeOauthAccount`)
|
|
731
|
+
* (§ `claudeCodeOauthAccount`) — and `readFile` / `listDir` for the settings
|
|
732
|
+
* files (§ `onceReaders`).
|
|
644
733
|
*/
|
|
645
734
|
export const markerOauthAccount = (tool, opts = {}) => {
|
|
646
|
-
|
|
735
|
+
const path = markerOauthAccountPath(tool, opts)
|
|
736
|
+
if (path === undefined) return {}
|
|
737
|
+
const text = readOrUndefined(path)
|
|
738
|
+
return text === undefined ? {} : oauthAccountFromText(text)
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
/**
|
|
742
|
+
* The `.claude.json` a marker may read the session's Claude account from, or
|
|
743
|
+
* `undefined` when the gate in § `markerOauthAccount` is shut (not Claude
|
|
744
|
+
* Code, or a session not signed in with a Claude account). Same `opts`. The
|
|
745
|
+
* one place both the identity stamp and the plan snapshot decide whether the
|
|
746
|
+
* account cache describes this session.
|
|
747
|
+
*/
|
|
748
|
+
export const markerOauthAccountPath = (tool, opts = {}) => {
|
|
749
|
+
if (tool !== 'claude-code') return undefined
|
|
647
750
|
const env = opts.env ?? process.env
|
|
648
|
-
if (isNonOauthEnv(env)) return
|
|
751
|
+
if (isNonOauthEnv(env)) return undefined
|
|
649
752
|
const cwd = opts.cwd ?? process.cwd()
|
|
650
|
-
if (hasApiKeyHelper(cwd, env,
|
|
753
|
+
if (hasApiKeyHelper(cwd, env, opts.readFile, opts.listDir, opts.managedDir)) return undefined
|
|
651
754
|
const configDir = 'configDir' in opts ? opts.configDir : env.CLAUDE_CONFIG_DIR
|
|
652
|
-
return
|
|
755
|
+
return claudeAccountPath(opts.home, configDir)
|
|
653
756
|
}
|
|
654
757
|
|
|
655
758
|
/** Last `key = "value"` match in TOML-ish text; last wins within the file. The key may
|
|
@@ -702,12 +805,13 @@ export const codexOtelConfig = (readFile = readFileSafe) => {
|
|
|
702
805
|
}
|
|
703
806
|
|
|
704
807
|
/** Resolve OTLP config for the marker emit. `tool` selects the source format:
|
|
705
|
-
* 'codex' reads config.toml; the default reads Claude Code's settings.json env.
|
|
706
|
-
|
|
808
|
+
* 'codex' reads config.toml; the default reads Claude Code's settings.json env.
|
|
809
|
+
* `readers` (§ `onceReaders`) lets a caller share its file reads. */
|
|
810
|
+
export const loadOtelConfig = (cwd, processEnv, tool = 'claude-code', managedDir, readers = {}) =>
|
|
707
811
|
tool === 'codex'
|
|
708
812
|
? codexOtelConfig()
|
|
709
813
|
: resolveOtelConfig(
|
|
710
|
-
settingsLayers(cwd, processEnv,
|
|
814
|
+
settingsLayers(cwd, processEnv, readers.readFile, readers.listDir, managedDir),
|
|
711
815
|
processEnv,
|
|
712
816
|
)
|
|
713
817
|
|
|
@@ -743,6 +847,15 @@ export const markerResourceAttrs = (resourceAttrs, source, service, hostSource)
|
|
|
743
847
|
|
|
744
848
|
const attr = (key, stringValue) => ({ key, value: { stringValue } })
|
|
745
849
|
|
|
850
|
+
/** Typed OTLP/JSON attributes, for a span that carries more than strings.
|
|
851
|
+
* `intValue` is the decimal string the OTLP/JSON encoding uses for an int64;
|
|
852
|
+
* collectors accept the number form too. */
|
|
853
|
+
export const stringAttr = attr
|
|
854
|
+
export const intAttr = (key, n) => ({ key, value: { intValue: String(n) } })
|
|
855
|
+
export const boolAttr = (key, b) => ({ key, value: { boolValue: b } })
|
|
856
|
+
/** A finite number as an OTLP double (an integral one too: `31` is `31.0`). */
|
|
857
|
+
export const doubleAttr = (key, n) => ({ key, value: { doubleValue: n } })
|
|
858
|
+
|
|
746
859
|
/** W3C `traceparent`, version `00`: `00-<32 hex trace id>-<16 hex span id>-<2
|
|
747
860
|
* hex flags>`, lowercase only — the spec rejects uppercase hex, and a later
|
|
748
861
|
* version may change the fields, so only `00` is read.
|
|
@@ -867,6 +980,10 @@ const callContextAttrs = (callContext) => {
|
|
|
867
980
|
* which also stamps `hostSource` (optional; the marker hooks pass
|
|
868
981
|
* § `markerHostSource`, the cursor behaviour hook passes nothing).
|
|
869
982
|
*
|
|
983
|
+
* `typedAttributes` (optional) are OTLP key/value objects built with
|
|
984
|
+
* § `intAttr` / `boolAttr` / `stringAttr`, appended as given — for a marker
|
|
985
|
+
* whose values aren't all strings.
|
|
986
|
+
*
|
|
870
987
|
* `callContext` (§ `markerCallContext`; optional) appends each of its fields
|
|
871
988
|
* that is present as a span attribute. The span keeps its own random trace and
|
|
872
989
|
* span ids either way: the calling span is referenced, never joined, because a
|
|
@@ -877,6 +994,7 @@ export const buildMarkerPayload = ({
|
|
|
877
994
|
spanName,
|
|
878
995
|
scopeName,
|
|
879
996
|
attributes,
|
|
997
|
+
typedAttributes = [],
|
|
880
998
|
sessionId,
|
|
881
999
|
userEmail,
|
|
882
1000
|
userAccountUuid,
|
|
@@ -909,6 +1027,7 @@ export const buildMarkerPayload = ({
|
|
|
909
1027
|
...Object.entries(attributes)
|
|
910
1028
|
.filter(([k, v]) => !isBlankForAttr(k, v))
|
|
911
1029
|
.map(([k, v]) => attr(k, String(v))),
|
|
1030
|
+
...typedAttributes,
|
|
912
1031
|
...(sessionId ? [attr('session.id', sessionId)] : []),
|
|
913
1032
|
...callContextAttrs(callContext),
|
|
914
1033
|
// isBlankAttr, not `in` or a truthy check: a key present but
|
|
@@ -929,7 +1048,16 @@ export const buildMarkerPayload = ({
|
|
|
929
1048
|
],
|
|
930
1049
|
})
|
|
931
1050
|
|
|
932
|
-
/**
|
|
1051
|
+
/** Whether an HTTP status is a 2xx. */
|
|
1052
|
+
export const isOkStatus = (status) => Number.isInteger(status) && status >= 200 && status < 300
|
|
1053
|
+
|
|
1054
|
+
/**
|
|
1055
|
+
* POST the OTLP body to the collector, failing open (any error is swallowed).
|
|
1056
|
+
* Resolves the response's HTTP status, or `undefined` when no response came
|
|
1057
|
+
* (network error, abort at `timeoutMs`). Every outcome is logged, except a
|
|
1058
|
+
* 2xx when `logOk` is false — a caller that sends on every prompt keeps its
|
|
1059
|
+
* log to what someone diagnoses and records success itself from the status.
|
|
1060
|
+
*/
|
|
933
1061
|
export const emitMarker = async ({
|
|
934
1062
|
endpoint,
|
|
935
1063
|
bearer,
|
|
@@ -937,6 +1065,7 @@ export const emitMarker = async ({
|
|
|
937
1065
|
label,
|
|
938
1066
|
log,
|
|
939
1067
|
timeoutMs = EMIT_TIMEOUT_MS,
|
|
1068
|
+
logOk = true,
|
|
940
1069
|
}) => {
|
|
941
1070
|
const controller = new AbortController()
|
|
942
1071
|
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
|
@@ -947,9 +1076,11 @@ export const emitMarker = async ({
|
|
|
947
1076
|
body: JSON.stringify(body),
|
|
948
1077
|
signal: controller.signal,
|
|
949
1078
|
})
|
|
950
|
-
log(`posted ${label}: status=${res.status}`)
|
|
1079
|
+
if (logOk || !isOkStatus(res.status)) log(`posted ${label}: status=${res.status}`)
|
|
1080
|
+
return res.status
|
|
951
1081
|
} catch (e) {
|
|
952
1082
|
log(`post failed for ${label}: ${e}`) // fail open — telemetry never blocks the session
|
|
1083
|
+
return undefined
|
|
953
1084
|
} finally {
|
|
954
1085
|
clearTimeout(timer)
|
|
955
1086
|
}
|
|
@@ -981,6 +1112,108 @@ export const payloadShape = (payload) => {
|
|
|
981
1112
|
return `keys=[${Object.keys(payload).join(',')}] output_field=${present ?? 'none'}`
|
|
982
1113
|
}
|
|
983
1114
|
|
|
1115
|
+
/** An opaque id from the hook input, exactly as sent (Claude Code's session
|
|
1116
|
+
* and prompt ids are UUIDs): letters, digits and `_ . : -`, at most 256
|
|
1117
|
+
* characters, else `undefined`. */
|
|
1118
|
+
export const opaqueIdExact = (v) => (typeof v === 'string' && OPAQUE_ID_RE.test(v) ? v : undefined)
|
|
1119
|
+
|
|
1120
|
+
/** The source and service every Claude account span carries (the plan
|
|
1121
|
+
* snapshot and the stop-failure span): non-coding, about the Anthropic
|
|
1122
|
+
* account rather than a stretch of coding work. */
|
|
1123
|
+
export const ANTHROPIC_SOURCE = 'hook.anthropic'
|
|
1124
|
+
export const ANTHROPIC_SERVICE = 'mainwave.plan-hook'
|
|
1125
|
+
|
|
1126
|
+
/** The log the stop-failure feature writes. */
|
|
1127
|
+
export const CLAUDE_EVENTS_LOG = 'claude-events.log'
|
|
1128
|
+
|
|
1129
|
+
/**
|
|
1130
|
+
* Send one Claude Code event span under `hook.anthropic`: `attributes` (typed
|
|
1131
|
+
* OTLP attributes the feature built from one enumerated input field), plus the
|
|
1132
|
+
* input's prompt id, the session id, the Claude account identity when the
|
|
1133
|
+
* session is signed in with one (§ `markerOauthAccount`'s gate) and the
|
|
1134
|
+
* caller's trace context. Nothing else from the input is read. Logs a skip
|
|
1135
|
+
* when no collector is configured. Claude Code only.
|
|
1136
|
+
*/
|
|
1137
|
+
export const sendClaudeEvent = async ({
|
|
1138
|
+
payload,
|
|
1139
|
+
argv,
|
|
1140
|
+
emit = emitMarker,
|
|
1141
|
+
spanName,
|
|
1142
|
+
scopeName,
|
|
1143
|
+
attributes,
|
|
1144
|
+
promptIdKey,
|
|
1145
|
+
label,
|
|
1146
|
+
}) => {
|
|
1147
|
+
const tool = markerTool(argv)
|
|
1148
|
+
if (tool !== 'claude-code') return
|
|
1149
|
+
const log = markerLog(argv, CLAUDE_EVENTS_LOG)
|
|
1150
|
+
const projectDir = markerProjectDir(payload)
|
|
1151
|
+
const managedDir = markerManagedDir(argv)
|
|
1152
|
+
const env = markerSessionEnv(tool, payload)
|
|
1153
|
+
const readers = onceReaders()
|
|
1154
|
+
const { endpoint, bearer, resourceAttrs } = loadOtelConfig(
|
|
1155
|
+
projectDir,
|
|
1156
|
+
env,
|
|
1157
|
+
tool,
|
|
1158
|
+
managedDir,
|
|
1159
|
+
readers,
|
|
1160
|
+
)
|
|
1161
|
+
if (!endpoint || !bearer) {
|
|
1162
|
+
log(`skip ${label}: collector endpoint/bearer not found in settings or env`)
|
|
1163
|
+
return
|
|
1164
|
+
}
|
|
1165
|
+
const { email, accountUuid } = markerOauthAccount(tool, {
|
|
1166
|
+
cwd: projectDir,
|
|
1167
|
+
env,
|
|
1168
|
+
managedDir,
|
|
1169
|
+
...readers,
|
|
1170
|
+
})
|
|
1171
|
+
const promptId = opaqueIdExact(payload?.prompt_id)
|
|
1172
|
+
const body = buildMarkerPayload({
|
|
1173
|
+
spanName,
|
|
1174
|
+
scopeName,
|
|
1175
|
+
attributes: {},
|
|
1176
|
+
typedAttributes: [...attributes, ...(promptId ? [attr(promptIdKey, promptId)] : [])],
|
|
1177
|
+
sessionId: opaqueIdExact(payload?.session_id),
|
|
1178
|
+
userEmail: email,
|
|
1179
|
+
userAccountUuid: accountUuid,
|
|
1180
|
+
resourceAttrs,
|
|
1181
|
+
source: ANTHROPIC_SOURCE,
|
|
1182
|
+
service: ANTHROPIC_SERVICE,
|
|
1183
|
+
hostSource: markerHostSource(tool),
|
|
1184
|
+
callContext: { caller: parseTraceparent(env.TRACEPARENT) },
|
|
1185
|
+
nowNs: BigInt(Date.now()) * 1_000_000n,
|
|
1186
|
+
})
|
|
1187
|
+
await emit({ endpoint, bearer, body, label, log })
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
/** Read all of `stream` (stdin by default) as UTF-8, at most `maxBytes`;
|
|
1191
|
+
* resolves `undefined` once the input passes that size — the rest is never
|
|
1192
|
+
* read — or when the stream errors. */
|
|
1193
|
+
export const readStdinCapped = (maxBytes, stream = process.stdin) =>
|
|
1194
|
+
new Promise((resolve) => {
|
|
1195
|
+
const chunks = []
|
|
1196
|
+
let size = 0
|
|
1197
|
+
let settled = false
|
|
1198
|
+
const settle = (value) => {
|
|
1199
|
+
if (settled) return
|
|
1200
|
+
settled = true
|
|
1201
|
+
resolve(value)
|
|
1202
|
+
}
|
|
1203
|
+
stream.on('data', (chunk) => {
|
|
1204
|
+
if (settled) return
|
|
1205
|
+
size += chunk.length
|
|
1206
|
+
if (size > maxBytes) {
|
|
1207
|
+
settle(undefined)
|
|
1208
|
+
stream.destroy?.()
|
|
1209
|
+
return
|
|
1210
|
+
}
|
|
1211
|
+
chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk)
|
|
1212
|
+
})
|
|
1213
|
+
stream.on('end', () => settle(Buffer.concat(chunks).toString('utf8')))
|
|
1214
|
+
stream.on('error', () => settle(undefined))
|
|
1215
|
+
})
|
|
1216
|
+
|
|
984
1217
|
/** Read all of stdin as a string; resolves '' on error. */
|
|
985
1218
|
export const readStdin = () =>
|
|
986
1219
|
new Promise((resolve) => {
|
package/hooks/matchers.json
CHANGED
|
@@ -1,17 +1,93 @@
|
|
|
1
1
|
[
|
|
2
2
|
{
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"event": "UserPromptSubmit",
|
|
4
|
+
"features": ["plan-snapshot"],
|
|
5
|
+
"optOut": "markers",
|
|
6
|
+
"hosts": ["claude-code"],
|
|
7
|
+
"dataClasses": [
|
|
8
|
+
"Claude account email, account id and organization id",
|
|
9
|
+
"plan tier names and roles",
|
|
10
|
+
"subscription start, trial end and length, first-use date",
|
|
11
|
+
"usage against rate limits",
|
|
12
|
+
"extra-usage on/off, amount, limit, currency and why it is off",
|
|
13
|
+
"session id, prompt id, turn trace and span ids"
|
|
14
|
+
],
|
|
15
|
+
"why": "UserPromptSubmit fires on every submitted prompt, including one whose turn is later interrupted (Stop fires only on completed turns). It also fires on turns no person started (scheduled tasks and loops, background-subagent reports, cross-session messages), and Claude Code doesn't yet say which, so a snapshot marks when one was received, not developer activity. SessionEnd is deliberately not used: an exit-time snapshot would move the developer's last-seen to quit time with no work then, and a figure refreshed by /usage just before quitting reaches Mainwave at the next prompt, because Claude Code's cache persists on disk. It takes no matcher. Claude Code only: the feature reads Claude Code's own account record (.claude.json), which no other host has. The group is async, so the prompt never waits on the collector; the feature bounds its own send."
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
"event": "PostToolUse",
|
|
19
|
+
"route": "gh",
|
|
20
|
+
"matcher": "Bash",
|
|
21
|
+
"if": "Bash(gh *)",
|
|
22
|
+
"features": ["github-pr-marker"],
|
|
23
|
+
"optOut": "markers",
|
|
24
|
+
"hosts": ["claude-code"],
|
|
25
|
+
"dataClasses": [
|
|
26
|
+
"pull request url, number and title",
|
|
27
|
+
"changed-file, added-line and removed-line counts"
|
|
28
|
+
],
|
|
29
|
+
"why": "Built-in tool, exact name, narrowed by the handler's `if` to Bash commands that start with `gh` (compound commands and VAR= prefixes included), so Claude Code starts nothing for any other command. The feature still returns immediately unless the command was 'gh pr create'. A pattern naming more than the command (`Bash(gh pr create *)`) is deliberately not used: Claude Code runs such a hook on every command it can't parse, which is any command with $(), backticks or $VAR. A wrapper or a path (`env gh`, `/usr/local/bin/gh`) doesn't match `gh *`; that miss is accepted."
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
"event": "PostToolUse",
|
|
33
|
+
"route": "glab",
|
|
34
|
+
"matcher": "Bash",
|
|
35
|
+
"if": "Bash(glab *)",
|
|
36
|
+
"features": ["glab-mr-marker"],
|
|
37
|
+
"optOut": "markers",
|
|
38
|
+
"hosts": ["claude-code"],
|
|
39
|
+
"dataClasses": [
|
|
40
|
+
"merge request url, iid and title",
|
|
41
|
+
"instance-namespaced project id",
|
|
42
|
+
"changed-file count"
|
|
43
|
+
],
|
|
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`."
|
|
6
45
|
},
|
|
7
46
|
{
|
|
8
|
-
"
|
|
47
|
+
"event": "PostToolUse",
|
|
48
|
+
"route": "bash",
|
|
9
49
|
"matcher": "Bash",
|
|
10
|
-
"
|
|
50
|
+
"features": ["github-pr-marker", "glab-mr-marker"],
|
|
51
|
+
"optOut": "markers",
|
|
52
|
+
"hosts": ["codex"],
|
|
53
|
+
"dataClasses": [
|
|
54
|
+
"pull request url, number and title",
|
|
55
|
+
"changed-file, added-line and removed-line counts",
|
|
56
|
+
"merge request url, iid and title",
|
|
57
|
+
"instance-namespaced project id",
|
|
58
|
+
"changed-file count"
|
|
59
|
+
],
|
|
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."
|
|
11
61
|
},
|
|
12
62
|
{
|
|
13
|
-
"
|
|
63
|
+
"event": "PostToolUse",
|
|
64
|
+
"route": "linear",
|
|
65
|
+
"matcher": "^mcp__.*[Ll]inear.*_(save|create|update)_issue$",
|
|
66
|
+
"features": ["linear-ticket-marker"],
|
|
67
|
+
"optOut": "markers",
|
|
68
|
+
"hosts": ["claude-code", "codex"],
|
|
69
|
+
"dataClasses": ["issue key, url, team id and create/update"],
|
|
70
|
+
"why": "The server PREFIX and the separator both vary. Prefix: this workspace connects Linear as mcp__linear-server__save_issue, the older integration as mcp__linear__save_issue, and Codex exposes it as mcp__codex_apps__linear_save_issue — a SINGLE underscore before save_issue. So the separator is `.*_` (one-or-more via the greedy `.*`, which absorbs the extra underscore in the __ forms) rather than a literal `__`. 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 — the trailing `_issue$` excludes it."
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
"event": "PostToolUse",
|
|
74
|
+
"route": "jira",
|
|
14
75
|
"matcher": "^mcp__.*[Aa]tlassian.*__(createJiraIssue|editJiraIssue)$",
|
|
76
|
+
"features": ["jira-ticket-marker"],
|
|
77
|
+
"optOut": "markers",
|
|
78
|
+
"hosts": ["claude-code", "codex"],
|
|
79
|
+
"dataClasses": ["issue key, url, site id and create/update"],
|
|
15
80
|
"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, ...)."
|
|
81
|
+
},
|
|
82
|
+
{
|
|
83
|
+
"event": "StopFailure",
|
|
84
|
+
"features": ["stop-failure"],
|
|
85
|
+
"optOut": "markers",
|
|
86
|
+
"hosts": ["claude-code"],
|
|
87
|
+
"dataClasses": [
|
|
88
|
+
"the error type when a turn ends on an API error",
|
|
89
|
+
"session id, prompt id, Claude account id and email"
|
|
90
|
+
],
|
|
91
|
+
"why": "StopFailure fires instead of Stop when a turn ends on an API error. Rate-limit and billing errors are the developer's own limit hits, joined to the plan snapshot. No matcher: every error type is rare enough, and the feature sends only the type enum, never the error details or the rendered message. Notification is deliberately not used: Claude Code's usage-limit auto-resume notices (`quota_auto_resume_*`) can fire while the developer is idle, which would move the use case's last-seen with no work then, the same reason SessionEnd is not used."
|
|
16
92
|
}
|
|
17
93
|
]
|