@mainwave/cli 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +169 -42
  2. package/dist/adapters/claude-code.js +23 -4
  3. package/dist/adapters/codex-cli.js +1 -1
  4. package/dist/adapters/cursor.js +4 -2
  5. package/dist/adapters/index.js +3 -0
  6. package/dist/adapters/kiro.js +361 -0
  7. package/dist/core/apply.js +161 -46
  8. package/dist/core/behaviour-hooks.js +7 -7
  9. package/dist/core/codecs/kiro-hooks-json.js +76 -0
  10. package/dist/core/doctor.js +27 -9
  11. package/dist/core/effective-settings.js +10 -0
  12. package/dist/core/entry-script.js +90 -0
  13. package/dist/core/git-bash.js +40 -0
  14. package/dist/core/install-hooks.js +126 -43
  15. package/dist/core/interview.js +114 -16
  16. package/dist/core/markers.js +678 -140
  17. package/dist/core/remove.js +67 -0
  18. package/dist/core/settings.js +32 -6
  19. package/dist/core/skills.js +47 -1
  20. package/dist/core/status.js +2 -1
  21. package/dist/core/wizard.js +64 -3
  22. package/dist/main.js +28 -9
  23. package/hooks/cursor-otlp.mjs +4 -27
  24. package/hooks/github-pr-marker.mjs +35 -22
  25. package/hooks/glab-mr-marker.mjs +795 -0
  26. package/hooks/jira-ticket-marker.mjs +27 -15
  27. package/hooks/kiro-otlp.mjs +570 -0
  28. package/hooks/linear-ticket-marker.mjs +27 -15
  29. package/hooks/mainwave-hook-node.mjs +42 -0
  30. package/hooks/mainwave-hook.mjs +301 -0
  31. package/hooks/marker-core.mjs +368 -41
  32. package/hooks/matchers.json +82 -6
  33. package/hooks/plan-snapshot.mjs +529 -0
  34. package/hooks/stop-failure.mjs +43 -0
  35. package/hooks/vocabulary.d.mts +49 -0
  36. package/hooks/vocabulary.mjs +188 -0
  37. package/package.json +5 -5
  38. package/skills/mainwave-instrument/SKILL.md +21 -7
  39. package/skills/mainwave-instrument/reference/api.md +29 -10
  40. package/skills/mainwave-instrument/reference/frameworks.md +3 -3
  41. package/skills/mainwave-instrument/reference/troubleshooting.md +12 -5
  42. package/skills/mainwave-setup/SKILL.md +47 -12
@@ -1,4 +1,7 @@
1
- // Shared plumbing for the Mainwave PostToolUse marker hooks.
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,13 +12,23 @@
9
12
  // extraction logic and `main()`.
10
13
 
11
14
  import { randomBytes } from 'node:crypto'
12
- import { appendFileSync, readFileSync, readdirSync } from 'node:fs'
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'
26
+ import { fileURLToPath } from 'node:url'
15
27
 
16
28
  import {
17
29
  ATTR_CALLER_SPAN_ID,
18
30
  ATTR_CALLER_TRACE_ID,
31
+ ATTR_CLI_VERSION,
19
32
  ATTR_HOST_SOURCE,
20
33
  ATTR_SCHEMA_VERSION,
21
34
  ATTR_SUBAGENT_ID,
@@ -26,16 +39,52 @@ import {
26
39
 
27
40
  const EMIT_TIMEOUT_MS = 3000
28
41
 
29
- /** A best-effort appender to `logPath` — never throws (a log hiccup must not
30
- * surface as a hook failure). */
31
- export const makeLog = (logPath) => (msg) => {
42
+ /** Where every hook log lives by default: `~/.mainwave/logs/`, never the home
43
+ * directory itself. */
44
+ export const logDir = () => join(homedir(), '.mainwave', 'logs')
45
+
46
+ /** A hook log's default path: `name` in `~/.mainwave/logs/`. */
47
+ export const defaultLogPath = (name) => join(logDir(), name)
48
+
49
+ /** Create the directory a log file goes in, owner-only, if it is missing.
50
+ * Throws like any write; callers are best-effort. */
51
+ export const ensureLogDir = (logPath) =>
52
+ mkdirSync(dirname(logPath), { recursive: true, mode: 0o700 })
53
+
54
+ /** Every hook log's size bound. Past it the file is rotated to `<name>.1`, so
55
+ * a log keeps between this and twice this of recent history and never more
56
+ * than twice this on disk. */
57
+ export const LOG_MAX_BYTES = 256 * 1024
58
+
59
+ /** Move a too-big log to `<name>.1` (replacing the previous one). If the move
60
+ * fails (a directory squatting on `.1`, a permissions oddity), empty the log
61
+ * instead: losing history beats a log that grows without bound. Two hooks
62
+ * rotating at once may drop a few lines; neither throws. */
63
+ const rotateLog = (logPath) => {
32
64
  try {
33
- appendFileSync(logPath, `${new Date().toISOString()} ${msg}\n`)
65
+ renameSync(logPath, `${logPath}.1`)
34
66
  } catch {
35
- // logging is best-effort — never let it throw
67
+ writeFileSync(logPath, '')
36
68
  }
37
69
  }
38
70
 
71
+ /** A best-effort appender to `logPath` — never throws (a log hiccup must not
72
+ * surface as a hook failure). Creates the log's directory on demand. A file
73
+ * already larger than `maxBytes` is rotated (§ `rotateLog`) before the line
74
+ * lands, so a hook that runs on every prompt can't grow its log without
75
+ * bound and the history before the cap survives in `<name>.1`. */
76
+ export const makeLog =
77
+ (logPath, maxBytes = LOG_MAX_BYTES) =>
78
+ (msg) => {
79
+ try {
80
+ ensureLogDir(logPath)
81
+ if (statSync(logPath, { throwIfNoEntry: false })?.size > maxBytes) rotateLog(logPath)
82
+ appendFileSync(logPath, `${new Date().toISOString()} ${msg}\n`, { mode: 0o600 })
83
+ } catch {
84
+ // logging is best-effort — never let it throw
85
+ }
86
+ }
87
+
39
88
  /**
40
89
  * The value after `name` in the hook's own argv, or undefined. A flag is the
41
90
  * one input a checked-out repository can't set: the hook command lives in the
@@ -49,12 +98,17 @@ export const hookFlag = (argv, name) => {
49
98
  return i !== -1 && argv[i + 1] ? argv[i + 1] : undefined
50
99
  }
51
100
 
52
- /** The hook's log: `--log-file <path>` when the hook command passes one (tests
53
- * do), else `defaultName` in the home directory. Never from the environment
54
- * (§ `hookFlag`): a line logged here can carry a value the repository chose,
55
- * so the repository mustn't choose the file it lands in either. */
56
- export const markerLog = (argv, defaultName) =>
57
- makeLog(hookFlag(argv, '--log-file') || join(homedir(), defaultName))
101
+ /** The hook's log path: `--log-file <path>` when the hook command passes one
102
+ * (tests do), else `defaultName` in `~/.mainwave/logs/`. Never from the
103
+ * environment (§ `hookFlag`): a line logged here can carry a value the
104
+ * repository chose, so the repository mustn't choose the file it lands in
105
+ * either. */
106
+ export const markerLogPath = (argv, defaultName) =>
107
+ hookFlag(argv, '--log-file') || defaultLogPath(defaultName)
108
+
109
+ /** The hook's log (§ `markerLogPath`). */
110
+ export const markerLog = (argv, defaultName, maxBytes = LOG_MAX_BYTES) =>
111
+ makeLog(markerLogPath(argv, defaultName), maxBytes)
58
112
 
59
113
  /**
60
114
  * The project root whose `.claude/` settings Claude Code loaded for this
@@ -88,6 +142,33 @@ export const parseKv = (raw) => {
88
142
  return out
89
143
  }
90
144
 
145
+ /** Reverse of the env-file codec's double-quoting (KEY="value" with \\ \" \n). */
146
+ const unquote = (raw) => {
147
+ const v = raw.trim()
148
+ if (v.startsWith('"') && v.endsWith('"') && v.length >= 2) {
149
+ return v.slice(1, -1).replace(/\\n/g, '\n').replace(/\\"/g, '"').replace(/\\\\/g, '\\')
150
+ }
151
+ if (v.startsWith("'") && v.endsWith("'") && v.length >= 2) return v.slice(1, -1)
152
+ return v
153
+ }
154
+
155
+ /** Parse a `KEY="value"` env file (the CLI's env-file codec output) into a flat record; {} on any error. */
156
+ export const parseEnvFile = (text) => {
157
+ const out = {}
158
+ for (const line of (text ?? '').split('\n')) {
159
+ const trimmed = line.trim()
160
+ if (trimmed === '' || trimmed.startsWith('#')) continue
161
+ let rest = trimmed
162
+ if (rest.startsWith('export ')) rest = rest.slice('export '.length).trimStart()
163
+ const eq = rest.indexOf('=')
164
+ if (eq < 0) continue
165
+ const key = rest.slice(0, eq).trim()
166
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) continue
167
+ out[key] = unquote(rest.slice(eq + 1))
168
+ }
169
+ return out
170
+ }
171
+
91
172
  /** The Bearer value from an `Authorization=Bearer xyz` OTEL header string. */
92
173
  export const bearerFromHeaders = (raw) => {
93
174
  for (const [k, v] of Object.entries(parseKv(raw))) {
@@ -205,6 +286,28 @@ const readFileSafe = (path) => {
205
286
  }
206
287
  }
207
288
 
289
+ /**
290
+ * A `readFile` / `listDir` pair that reads each settings file and lists each
291
+ * drop-in directory once per hook run. The sign-in gate (§ `hasApiKeyHelper`)
292
+ * and the OTLP lookup (§ `settingsLayers`) read the same user, project, local
293
+ * and managed files; a second pass over them is time the hook doesn't need to spend. Only for one run: a
294
+ * long-lived cache would miss an edit.
295
+ */
296
+ export const onceReaders = (readFile = readFileSafe, listDir = jsonFilesIn) => {
297
+ const files = new Map()
298
+ const dirs = new Map()
299
+ return {
300
+ readFile: (path) => {
301
+ if (!files.has(path)) files.set(path, readFile(path))
302
+ return files.get(path)
303
+ },
304
+ listDir: (dir) => {
305
+ if (!dirs.has(dir)) dirs.set(dir, listDir(dir))
306
+ return dirs.get(dir)
307
+ },
308
+ }
309
+ }
310
+
208
311
  /** `CLAUDE_CONFIG_DIR`, ASCII-trimmed and resolved to an absolute path, or
209
312
  * `undefined` when unset or blank — a whitespace-only value counts as unset.
210
313
  * For the settings root (§ `claudeConfigDir`) only: the account cache is
@@ -454,7 +557,7 @@ export const markerHostSource = (tool) =>
454
557
  * `String.prototype.trim`, whose Unicode `WhiteSpace`/`LineTerminator`
455
558
  * set also strips NBSP and other characters the collector would keep — so a
456
559
  * 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, '')
560
+ export const trimAscii = (s) => s.replace(/^[ \t\n\r\v\f]+|[ \t\n\r\v\f]+$/g, '')
458
561
 
459
562
  /** A file's UTF-8 text, or `undefined` when it is missing or unreadable. */
460
563
  const readOrUndefined = (path) => {
@@ -467,25 +570,34 @@ const readOrUndefined = (path) => {
467
570
 
468
571
  /** A string field ASCII-trimmed (§ `trimAscii`), or `undefined` for a
469
572
  * non-string or a value that trims to empty. */
470
- const trimmedOrUndefined = (v) => (typeof v === 'string' ? trimAscii(v) || undefined : undefined)
471
-
472
- /** `oauthAccount.emailAddress` and `oauthAccount.accountUuid` from one
473
- * `.claude.json`'s text, parsed once, each ASCII-trimmed (§ `trimAscii`) and
474
- * each independently `undefined` when missing, non-string, or blank. Both are
475
- * `undefined` for unparseable JSON. */
476
- const oauthAccountFromText = (text) => {
477
- let account
478
- try {
479
- account = JSON.parse(text)?.oauthAccount
480
- } catch {
481
- return {}
482
- }
573
+ export const trimmedOrUndefined = (v) =>
574
+ typeof v === 'string' ? trimAscii(v) || undefined : undefined
575
+
576
+ /** `oauthAccount.emailAddress` and `oauthAccount.accountUuid` from one parsed
577
+ * `.claude.json` document, each ASCII-trimmed (§ `trimAscii`) and each
578
+ * independently `undefined` when missing, non-string, or blank. The one
579
+ * place a Claude account's identity is normalized: the markers read it
580
+ * through § `oauthAccountFromText`, the plan snapshot directly. */
581
+ export const oauthAccountFromRecord = (doc) => {
582
+ const account = doc?.oauthAccount
483
583
  return {
484
584
  email: trimmedOrUndefined(account?.emailAddress),
485
585
  accountUuid: trimmedOrUndefined(account?.accountUuid),
486
586
  }
487
587
  }
488
588
 
589
+ /** § `oauthAccountFromRecord` over one `.claude.json`'s text, parsed once.
590
+ * Both fields are `undefined` for unparseable JSON. */
591
+ export const oauthAccountFromText = (text) => {
592
+ let doc
593
+ try {
594
+ doc = JSON.parse(text)
595
+ } catch {
596
+ return {}
597
+ }
598
+ return oauthAccountFromRecord(doc)
599
+ }
600
+
489
601
  /**
490
602
  * Claude Code's own account cache — `.claude.json` (a top-level dotfile,
491
603
  * distinct from the `~/.claude/` settings directory) — written by its Claude.ai
@@ -516,10 +628,16 @@ const oauthAccountFromText = (text) => {
516
628
  * or changed shape.
517
629
  */
518
630
  export const claudeCodeOauthAccount = (home = homedir(), configDir) => {
519
- const text = readOrUndefined(resolve(configDir || home, '.claude.json'))
631
+ const text = readOrUndefined(claudeAccountPath(home, configDir))
520
632
  return text === undefined ? {} : oauthAccountFromText(text)
521
633
  }
522
634
 
635
+ /** Where Claude Code keeps its account cache, resolved exactly as
636
+ * § `claudeCodeOauthAccount` describes: `join(CLAUDE_CONFIG_DIR || home,
637
+ * '.claude.json')`, the raw `configDir`, a relative one against the cwd. */
638
+ export const claudeAccountPath = (home = homedir(), configDir) =>
639
+ resolve(configDir || home, '.claude.json')
640
+
523
641
  /** Env vars whose mere non-blank presence (ASCII-trimmed, § `trimAscii`) means
524
642
  * the Claude Code session does NOT authenticate through Claude.ai OAuth, so
525
643
  * `.claude.json`'s `oauthAccount` — which survives a switch to any of these —
@@ -637,19 +755,33 @@ export const hasApiKeyHelper = (
637
755
  *
638
756
  * `opts`: `env` (default `process.env`), `home` (default `homedir()`), `cwd`
639
757
  * (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
758
+ * the project-local `apiKeyHelper` check), `configDir` — when the key is present its value is used as-is
642
759
  * (`undefined` = unset), otherwise `env.CLAUDE_CONFIG_DIR`, raw
643
- * (§ `claudeCodeOauthAccount`).
760
+ * (§ `claudeCodeOauthAccount`) — and `readFile` / `listDir` for the settings
761
+ * files (§ `onceReaders`).
644
762
  */
645
763
  export const markerOauthAccount = (tool, opts = {}) => {
646
- if (tool !== 'claude-code') return {}
764
+ const path = markerOauthAccountPath(tool, opts)
765
+ if (path === undefined) return {}
766
+ const text = readOrUndefined(path)
767
+ return text === undefined ? {} : oauthAccountFromText(text)
768
+ }
769
+
770
+ /**
771
+ * The `.claude.json` a marker may read the session's Claude account from, or
772
+ * `undefined` when the gate in § `markerOauthAccount` is shut (not Claude
773
+ * Code, or a session not signed in with a Claude account). Same `opts`. The
774
+ * one place both the identity stamp and the plan snapshot decide whether the
775
+ * account cache describes this session.
776
+ */
777
+ export const markerOauthAccountPath = (tool, opts = {}) => {
778
+ if (tool !== 'claude-code') return undefined
647
779
  const env = opts.env ?? process.env
648
- if (isNonOauthEnv(env)) return {}
780
+ if (isNonOauthEnv(env)) return undefined
649
781
  const cwd = opts.cwd ?? process.cwd()
650
- if (hasApiKeyHelper(cwd, env, undefined, undefined, opts.managedDir)) return {}
782
+ if (hasApiKeyHelper(cwd, env, opts.readFile, opts.listDir, opts.managedDir)) return undefined
651
783
  const configDir = 'configDir' in opts ? opts.configDir : env.CLAUDE_CONFIG_DIR
652
- return claudeCodeOauthAccount(opts.home, configDir)
784
+ return claudeAccountPath(opts.home, configDir)
653
785
  }
654
786
 
655
787
  /** Last `key = "value"` match in TOML-ish text; last wins within the file. The key may
@@ -702,15 +834,69 @@ export const codexOtelConfig = (readFile = readFileSafe) => {
702
834
  }
703
835
 
704
836
  /** 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
- export const loadOtelConfig = (cwd, processEnv, tool = 'claude-code', managedDir) =>
837
+ * 'codex' reads config.toml; the default reads Claude Code's settings.json env.
838
+ * `readers` (§ `onceReaders`) lets a caller share its file reads. */
839
+ export const loadOtelConfig = (cwd, processEnv, tool = 'claude-code', managedDir, readers = {}) =>
707
840
  tool === 'codex'
708
841
  ? codexOtelConfig()
709
842
  : resolveOtelConfig(
710
- settingsLayers(cwd, processEnv, undefined, undefined, managedDir),
843
+ settingsLayers(cwd, processEnv, readers.readFile, readers.listDir, managedDir),
711
844
  processEnv,
712
845
  )
713
846
 
847
+ /** A staged release directory's name: `<version>-<12 hex content hash>`, as
848
+ * the CLI's installer names it under the managed `versions/` directory. */
849
+ const STAGED_RELEASE_RE = /^(.+)-[0-9a-f]{12}$/
850
+ /** The `--managed-by` value setup writes into a hook command it owns,
851
+ * `@mainwave/cli@<version>`. A concrete semver only: a payload that names a
852
+ * dist-tag (`@latest`) says nothing about which release is installed. */
853
+ const MANAGED_BY_RE = /^@mainwave\/cli@(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)$/
854
+
855
+ /**
856
+ * The `@mainwave/cli` release a hook script belongs to, or `undefined` when it
857
+ * can't tell, never a guess. Checked in order:
858
+ *
859
+ * 1. a release staged under the managed hooks directory: the directory's
860
+ * name, `…/versions/<version>-<hash>/`;
861
+ * 2. the package itself, `<package>/hooks/`: the package's own
862
+ * `package.json` one level up;
863
+ * 3. a flat copy (the Cursor and Kiro scripts under `~/.mainwave/hooks/`): the
864
+ * `--managed-by @mainwave/cli@<version>` flag on the hook command, which
865
+ * the setup run that copied the script wrote with the same version.
866
+ *
867
+ * The flag comes last: a first-generation managed command runs a staged
868
+ * release through `managed-entry.mjs` and still carries the version (or
869
+ * `@latest`) the payload was pasted with.
870
+ */
871
+ export const hookReleaseVersion = (dir, readFile = readFileSync, argv = []) => {
872
+ const staged = STAGED_RELEASE_RE.exec(basename(dir))
873
+ if (staged && basename(dirname(dir)) === 'versions') return staged[1]
874
+ try {
875
+ const pkg = JSON.parse(readFile(join(dir, '..', 'package.json'), 'utf8'))
876
+ if (pkg?.name === '@mainwave/cli' && typeof pkg.version === 'string' && pkg.version !== '') {
877
+ return pkg.version
878
+ }
879
+ } catch {
880
+ // no package beside it — not a release we can name from the files
881
+ }
882
+ return MANAGED_BY_RE.exec(hookFlag(argv, '--managed-by') ?? '')?.[1]
883
+ }
884
+
885
+ let ownVersionMemo
886
+ /** This script's own release (§ `hookReleaseVersion`), read once per process. */
887
+ const ownCliVersion = () => {
888
+ if (ownVersionMemo === undefined) {
889
+ ownVersionMemo = {
890
+ value: hookReleaseVersion(
891
+ dirname(fileURLToPath(import.meta.url)),
892
+ readFileSync,
893
+ process.argv,
894
+ ),
895
+ }
896
+ }
897
+ return ownVersionMemo.value
898
+ }
899
+
714
900
  /**
715
901
  * Keep the developer's identity attrs — above all `mainwave.ucid`, so the marker
716
902
  * attributes to the same use case as the session — but override the two the
@@ -726,15 +912,27 @@ export const loadOtelConfig = (cwd, processEnv, tool = 'claude-code', managedDir
726
912
  * — lands as `mainwave.host_source`. Absent → the key is omitted, and any value
727
913
  * inherited from the developer's `OTEL_RESOURCE_ATTRIBUTES` is dropped too, so
728
914
  * the attribute only ever carries what the hook itself resolved.
915
+ *
916
+ * `cliVersion` — the release this script belongs to, defaulting to its own
917
+ * (§ `hookReleaseVersion`) — lands as `mainwave.cli.version`, under the same
918
+ * rule: absent → omitted, and an inherited value is never forwarded.
729
919
  */
730
- export const markerResourceAttrs = (resourceAttrs, source, service, hostSource) => {
920
+ export const markerResourceAttrs = (
921
+ resourceAttrs,
922
+ source,
923
+ service,
924
+ hostSource,
925
+ cliVersion = ownCliVersion(),
926
+ ) => {
731
927
  const rest = { ...(resourceAttrs ?? {}) }
732
928
  delete rest[ATTR_HOST_SOURCE]
929
+ delete rest[ATTR_CLI_VERSION]
733
930
  return {
734
931
  ...rest,
735
932
  'mainwave.source': source,
736
933
  'service.name': service,
737
934
  ...(hostSource ? { [ATTR_HOST_SOURCE]: hostSource } : {}),
935
+ ...(cliVersion ? { [ATTR_CLI_VERSION]: cliVersion } : {}),
738
936
  // The v2 contract stamp on every hook emission (marker + cursor), so the
739
937
  // collector shim's lifetime can be measured against v1-vs-v2 traffic.
740
938
  [ATTR_SCHEMA_VERSION]: SCHEMA_VERSION,
@@ -743,6 +941,15 @@ export const markerResourceAttrs = (resourceAttrs, source, service, hostSource)
743
941
 
744
942
  const attr = (key, stringValue) => ({ key, value: { stringValue } })
745
943
 
944
+ /** Typed OTLP/JSON attributes, for a span that carries more than strings.
945
+ * `intValue` is the decimal string the OTLP/JSON encoding uses for an int64;
946
+ * collectors accept the number form too. */
947
+ export const stringAttr = attr
948
+ export const intAttr = (key, n) => ({ key, value: { intValue: String(n) } })
949
+ export const boolAttr = (key, b) => ({ key, value: { boolValue: b } })
950
+ /** A finite number as an OTLP double (an integral one too: `31` is `31.0`). */
951
+ export const doubleAttr = (key, n) => ({ key, value: { doubleValue: n } })
952
+
746
953
  /** W3C `traceparent`, version `00`: `00-<32 hex trace id>-<16 hex span id>-<2
747
954
  * hex flags>`, lowercase only — the spec rejects uppercase hex, and a later
748
955
  * version may change the fields, so only `00` is read.
@@ -867,6 +1074,10 @@ const callContextAttrs = (callContext) => {
867
1074
  * which also stamps `hostSource` (optional; the marker hooks pass
868
1075
  * § `markerHostSource`, the cursor behaviour hook passes nothing).
869
1076
  *
1077
+ * `typedAttributes` (optional) are OTLP key/value objects built with
1078
+ * § `intAttr` / `boolAttr` / `stringAttr`, appended as given — for a marker
1079
+ * whose values aren't all strings.
1080
+ *
870
1081
  * `callContext` (§ `markerCallContext`; optional) appends each of its fields
871
1082
  * that is present as a span attribute. The span keeps its own random trace and
872
1083
  * span ids either way: the calling span is referenced, never joined, because a
@@ -877,6 +1088,7 @@ export const buildMarkerPayload = ({
877
1088
  spanName,
878
1089
  scopeName,
879
1090
  attributes,
1091
+ typedAttributes = [],
880
1092
  sessionId,
881
1093
  userEmail,
882
1094
  userAccountUuid,
@@ -909,6 +1121,7 @@ export const buildMarkerPayload = ({
909
1121
  ...Object.entries(attributes)
910
1122
  .filter(([k, v]) => !isBlankForAttr(k, v))
911
1123
  .map(([k, v]) => attr(k, String(v))),
1124
+ ...typedAttributes,
912
1125
  ...(sessionId ? [attr('session.id', sessionId)] : []),
913
1126
  ...callContextAttrs(callContext),
914
1127
  // isBlankAttr, not `in` or a truthy check: a key present but
@@ -929,7 +1142,16 @@ export const buildMarkerPayload = ({
929
1142
  ],
930
1143
  })
931
1144
 
932
- /** POST the OTLP body to the collector, failing open (any error is swallowed). */
1145
+ /** Whether an HTTP status is a 2xx. */
1146
+ export const isOkStatus = (status) => Number.isInteger(status) && status >= 200 && status < 300
1147
+
1148
+ /**
1149
+ * POST the OTLP body to the collector, failing open (any error is swallowed).
1150
+ * Resolves the response's HTTP status, or `undefined` when no response came
1151
+ * (network error, abort at `timeoutMs`). Every outcome is logged, except a
1152
+ * 2xx when `logOk` is false — a caller that sends on every prompt keeps its
1153
+ * log to what someone diagnoses and records success itself from the status.
1154
+ */
933
1155
  export const emitMarker = async ({
934
1156
  endpoint,
935
1157
  bearer,
@@ -937,6 +1159,7 @@ export const emitMarker = async ({
937
1159
  label,
938
1160
  log,
939
1161
  timeoutMs = EMIT_TIMEOUT_MS,
1162
+ logOk = true,
940
1163
  }) => {
941
1164
  const controller = new AbortController()
942
1165
  const timer = setTimeout(() => controller.abort(), timeoutMs)
@@ -947,9 +1170,11 @@ export const emitMarker = async ({
947
1170
  body: JSON.stringify(body),
948
1171
  signal: controller.signal,
949
1172
  })
950
- log(`posted ${label}: status=${res.status}`)
1173
+ if (logOk || !isOkStatus(res.status)) log(`posted ${label}: status=${res.status}`)
1174
+ return res.status
951
1175
  } catch (e) {
952
1176
  log(`post failed for ${label}: ${e}`) // fail open — telemetry never blocks the session
1177
+ return undefined
953
1178
  } finally {
954
1179
  clearTimeout(timer)
955
1180
  }
@@ -981,6 +1206,108 @@ export const payloadShape = (payload) => {
981
1206
  return `keys=[${Object.keys(payload).join(',')}] output_field=${present ?? 'none'}`
982
1207
  }
983
1208
 
1209
+ /** An opaque id from the hook input, exactly as sent (Claude Code's session
1210
+ * and prompt ids are UUIDs): letters, digits and `_ . : -`, at most 256
1211
+ * characters, else `undefined`. */
1212
+ export const opaqueIdExact = (v) => (typeof v === 'string' && OPAQUE_ID_RE.test(v) ? v : undefined)
1213
+
1214
+ /** The source and service every Claude account span carries (the plan
1215
+ * snapshot and the stop-failure span): non-coding, about the Anthropic
1216
+ * account rather than a stretch of coding work. */
1217
+ export const ANTHROPIC_SOURCE = 'hook.anthropic'
1218
+ export const ANTHROPIC_SERVICE = 'mainwave.plan-hook'
1219
+
1220
+ /** The log the stop-failure feature writes. */
1221
+ export const CLAUDE_EVENTS_LOG = 'claude-events.log'
1222
+
1223
+ /**
1224
+ * Send one Claude Code event span under `hook.anthropic`: `attributes` (typed
1225
+ * OTLP attributes the feature built from one enumerated input field), plus the
1226
+ * input's prompt id, the session id, the Claude account identity when the
1227
+ * session is signed in with one (§ `markerOauthAccount`'s gate) and the
1228
+ * caller's trace context. Nothing else from the input is read. Logs a skip
1229
+ * when no collector is configured. Claude Code only.
1230
+ */
1231
+ export const sendClaudeEvent = async ({
1232
+ payload,
1233
+ argv,
1234
+ emit = emitMarker,
1235
+ spanName,
1236
+ scopeName,
1237
+ attributes,
1238
+ promptIdKey,
1239
+ label,
1240
+ }) => {
1241
+ const tool = markerTool(argv)
1242
+ if (tool !== 'claude-code') return
1243
+ const log = markerLog(argv, CLAUDE_EVENTS_LOG)
1244
+ const projectDir = markerProjectDir(payload)
1245
+ const managedDir = markerManagedDir(argv)
1246
+ const env = markerSessionEnv(tool, payload)
1247
+ const readers = onceReaders()
1248
+ const { endpoint, bearer, resourceAttrs } = loadOtelConfig(
1249
+ projectDir,
1250
+ env,
1251
+ tool,
1252
+ managedDir,
1253
+ readers,
1254
+ )
1255
+ if (!endpoint || !bearer) {
1256
+ log(`skip ${label}: collector endpoint/bearer not found in settings or env`)
1257
+ return
1258
+ }
1259
+ const { email, accountUuid } = markerOauthAccount(tool, {
1260
+ cwd: projectDir,
1261
+ env,
1262
+ managedDir,
1263
+ ...readers,
1264
+ })
1265
+ const promptId = opaqueIdExact(payload?.prompt_id)
1266
+ const body = buildMarkerPayload({
1267
+ spanName,
1268
+ scopeName,
1269
+ attributes: {},
1270
+ typedAttributes: [...attributes, ...(promptId ? [attr(promptIdKey, promptId)] : [])],
1271
+ sessionId: opaqueIdExact(payload?.session_id),
1272
+ userEmail: email,
1273
+ userAccountUuid: accountUuid,
1274
+ resourceAttrs,
1275
+ source: ANTHROPIC_SOURCE,
1276
+ service: ANTHROPIC_SERVICE,
1277
+ hostSource: markerHostSource(tool),
1278
+ callContext: { caller: parseTraceparent(env.TRACEPARENT) },
1279
+ nowNs: BigInt(Date.now()) * 1_000_000n,
1280
+ })
1281
+ await emit({ endpoint, bearer, body, label, log })
1282
+ }
1283
+
1284
+ /** Read all of `stream` (stdin by default) as UTF-8, at most `maxBytes`;
1285
+ * resolves `undefined` once the input passes that size — the rest is never
1286
+ * read — or when the stream errors. */
1287
+ export const readStdinCapped = (maxBytes, stream = process.stdin) =>
1288
+ new Promise((resolve) => {
1289
+ const chunks = []
1290
+ let size = 0
1291
+ let settled = false
1292
+ const settle = (value) => {
1293
+ if (settled) return
1294
+ settled = true
1295
+ resolve(value)
1296
+ }
1297
+ stream.on('data', (chunk) => {
1298
+ if (settled) return
1299
+ size += chunk.length
1300
+ if (size > maxBytes) {
1301
+ settle(undefined)
1302
+ stream.destroy?.()
1303
+ return
1304
+ }
1305
+ chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk)
1306
+ })
1307
+ stream.on('end', () => settle(Buffer.concat(chunks).toString('utf8')))
1308
+ stream.on('error', () => settle(undefined))
1309
+ })
1310
+
984
1311
  /** Read all of stdin as a string; resolves '' on error. */
985
1312
  export const readStdin = () =>
986
1313
  new Promise((resolve) => {