@mainwave/cli 0.7.1 → 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.
Files changed (139) hide show
  1. package/README.md +141 -42
  2. package/dist/adapters/claude-code.js +33 -7
  3. package/dist/adapters/claude-desktop.js +0 -1
  4. package/dist/adapters/codex-cli.js +1 -2
  5. package/dist/adapters/copilot-chat.js +0 -1
  6. package/dist/adapters/copilot-cli.js +0 -1
  7. package/dist/adapters/cursor-enterprise.js +0 -1
  8. package/dist/adapters/cursor.js +15 -4
  9. package/dist/adapters/index.js +0 -1
  10. package/dist/adapters/types.js +0 -1
  11. package/dist/api/index.js +0 -1
  12. package/dist/api/types.gen.js +0 -1
  13. package/dist/cli.js +0 -1
  14. package/dist/core/apply.js +151 -42
  15. package/dist/core/auth-commands.js +0 -1
  16. package/dist/core/behaviour-hooks.js +0 -1
  17. package/dist/core/browser.js +0 -1
  18. package/dist/core/codecs/cursor-hooks-json.js +0 -1
  19. package/dist/core/codecs/env-file.js +0 -1
  20. package/dist/core/codecs/json-env.js +0 -1
  21. package/dist/core/codecs/json-flat.js +0 -1
  22. package/dist/core/codecs/json-managed.js +0 -1
  23. package/dist/core/codecs/toml-otel.js +0 -1
  24. package/dist/core/codecs/types.js +0 -1
  25. package/dist/core/detect.js +0 -1
  26. package/dist/core/device-login.js +0 -1
  27. package/dist/core/doctor.js +45 -9
  28. package/dist/core/edit.js +9 -5
  29. package/dist/core/effective-settings.js +71 -20
  30. package/dist/core/entry-script.js +90 -0
  31. package/dist/core/env-command.js +0 -1
  32. package/dist/core/errors.js +0 -1
  33. package/dist/core/flags.js +0 -1
  34. package/dist/core/format.js +0 -1
  35. package/dist/core/git-bash.js +40 -0
  36. package/dist/core/git.js +0 -1
  37. package/dist/core/headers.js +0 -1
  38. package/dist/core/install-hooks.js +127 -44
  39. package/dist/core/interview.js +53 -4
  40. package/dist/core/keys.js +0 -1
  41. package/dist/core/layer-policy.js +2 -1
  42. package/dist/core/markers.js +826 -133
  43. package/dist/core/pinned-use-case.js +0 -1
  44. package/dist/core/platform.js +0 -1
  45. package/dist/core/post-setup.js +0 -1
  46. package/dist/core/prompts.js +0 -1
  47. package/dist/core/settings.js +32 -8
  48. package/dist/core/skills.js +5 -2
  49. package/dist/core/status.js +7 -5
  50. package/dist/core/store.js +0 -1
  51. package/dist/core/tty.js +0 -1
  52. package/dist/core/ucid.js +0 -1
  53. package/dist/core/ui.js +0 -1
  54. package/dist/core/use-case.js +0 -1
  55. package/dist/core/validate.js +0 -1
  56. package/dist/core/verify.js +0 -1
  57. package/dist/core/version.js +0 -1
  58. package/dist/core/wizard.js +49 -8
  59. package/dist/main.js +16 -10
  60. package/hooks/cursor-otlp.mjs +13 -15
  61. package/hooks/github-pr-marker.mjs +55 -31
  62. package/hooks/glab-mr-marker.mjs +795 -0
  63. package/hooks/jira-ticket-marker.mjs +35 -23
  64. package/hooks/linear-ticket-marker.mjs +35 -21
  65. package/hooks/mainwave-hook-node.mjs +42 -0
  66. package/hooks/mainwave-hook.mjs +301 -0
  67. package/hooks/managed-entry.mjs +42 -0
  68. package/hooks/marker-core.mjs +389 -62
  69. package/hooks/matchers.json +82 -6
  70. package/hooks/plan-snapshot.mjs +529 -0
  71. package/hooks/stop-failure.mjs +43 -0
  72. package/hooks/vocabulary.d.mts +48 -0
  73. package/hooks/vocabulary.mjs +181 -0
  74. package/package.json +6 -5
  75. package/skills/mainwave-instrument/SKILL.md +21 -7
  76. package/skills/mainwave-instrument/reference/api.md +29 -10
  77. package/skills/mainwave-instrument/reference/frameworks.md +3 -3
  78. package/skills/mainwave-instrument/reference/troubleshooting.md +12 -5
  79. package/skills/mainwave-instrument-node/SKILL.md +420 -0
  80. package/skills/mainwave-instrument-node/reference/api.md +96 -0
  81. package/skills/mainwave-instrument-node/reference/frameworks.md +82 -0
  82. package/skills/mainwave-instrument-node/reference/troubleshooting.md +152 -0
  83. package/skills/mainwave-setup/SKILL.md +47 -12
  84. package/dist/adapters/claude-code.js.map +0 -1
  85. package/dist/adapters/claude-desktop.js.map +0 -1
  86. package/dist/adapters/codex-cli.js.map +0 -1
  87. package/dist/adapters/copilot-chat.js.map +0 -1
  88. package/dist/adapters/copilot-cli.js.map +0 -1
  89. package/dist/adapters/cursor-enterprise.js.map +0 -1
  90. package/dist/adapters/cursor.js.map +0 -1
  91. package/dist/adapters/index.js.map +0 -1
  92. package/dist/adapters/types.js.map +0 -1
  93. package/dist/api/index.js.map +0 -1
  94. package/dist/api/types.gen.js.map +0 -1
  95. package/dist/cli.js.map +0 -1
  96. package/dist/core/apply.js.map +0 -1
  97. package/dist/core/auth-commands.js.map +0 -1
  98. package/dist/core/behaviour-hooks.js.map +0 -1
  99. package/dist/core/browser.js.map +0 -1
  100. package/dist/core/codecs/cursor-hooks-json.js.map +0 -1
  101. package/dist/core/codecs/env-file.js.map +0 -1
  102. package/dist/core/codecs/json-env.js.map +0 -1
  103. package/dist/core/codecs/json-flat.js.map +0 -1
  104. package/dist/core/codecs/json-managed.js.map +0 -1
  105. package/dist/core/codecs/toml-otel.js.map +0 -1
  106. package/dist/core/codecs/types.js.map +0 -1
  107. package/dist/core/detect.js.map +0 -1
  108. package/dist/core/device-login.js.map +0 -1
  109. package/dist/core/doctor.js.map +0 -1
  110. package/dist/core/edit.js.map +0 -1
  111. package/dist/core/effective-settings.js.map +0 -1
  112. package/dist/core/env-command.js.map +0 -1
  113. package/dist/core/errors.js.map +0 -1
  114. package/dist/core/flags.js.map +0 -1
  115. package/dist/core/format.js.map +0 -1
  116. package/dist/core/git.js.map +0 -1
  117. package/dist/core/headers.js.map +0 -1
  118. package/dist/core/install-hooks.js.map +0 -1
  119. package/dist/core/interview.js.map +0 -1
  120. package/dist/core/keys.js.map +0 -1
  121. package/dist/core/layer-policy.js.map +0 -1
  122. package/dist/core/markers.js.map +0 -1
  123. package/dist/core/pinned-use-case.js.map +0 -1
  124. package/dist/core/platform.js.map +0 -1
  125. package/dist/core/post-setup.js.map +0 -1
  126. package/dist/core/prompts.js.map +0 -1
  127. package/dist/core/settings.js.map +0 -1
  128. package/dist/core/skills.js.map +0 -1
  129. package/dist/core/status.js.map +0 -1
  130. package/dist/core/store.js.map +0 -1
  131. package/dist/core/tty.js.map +0 -1
  132. package/dist/core/ucid.js.map +0 -1
  133. package/dist/core/ui.js.map +0 -1
  134. package/dist/core/use-case.js.map +0 -1
  135. package/dist/core/validate.js.map +0 -1
  136. package/dist/core/verify.js.map +0 -1
  137. package/dist/core/version.js.map +0 -1
  138. package/dist/core/wizard.js.map +0 -1
  139. package/dist/main.js.map +0 -1
@@ -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,9 +12,17 @@
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
- import { dirname, join, resolve } from 'node:path'
25
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path'
15
26
 
16
27
  import {
17
28
  ATTR_CALLER_SPAN_ID,
@@ -26,16 +37,96 @@ import {
26
37
 
27
38
  const EMIT_TIMEOUT_MS = 3000
28
39
 
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) => {
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
- appendFileSync(logPath, `${new Date().toISOString()} ${msg}\n`)
63
+ renameSync(logPath, `${logPath}.1`)
34
64
  } catch {
35
- // logging is best-effort — never let it throw
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
+
86
+ /**
87
+ * The value after `name` in the hook's own argv, or undefined. A flag is the
88
+ * one input a checked-out repository can't set: the hook command lives in the
89
+ * user's or the org's settings, not the repository's, while a repository's
90
+ * project settings `env` does reach the hook's environment (and a Cursor
91
+ * project hook can set env for later hooks). So anything that picks a file to
92
+ * write or a program to run comes from a flag, never from an env var.
93
+ */
94
+ export const hookFlag = (argv, name) => {
95
+ const i = (argv ?? []).indexOf(name)
96
+ return i !== -1 && argv[i + 1] ? argv[i + 1] : undefined
97
+ }
98
+
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)
110
+
111
+ /**
112
+ * The project root whose `.claude/` settings Claude Code loaded for this
113
+ * session: `CLAUDE_PROJECT_DIR`, which Claude Code sets for every hook. Not the
114
+ * payload's `cwd`, which follows each `cd` the agent runs — a vendored checkout
115
+ * underneath would otherwise have its own `.claude/settings.json` read as the
116
+ * session's project settings and re-attribute the marker. Only the session's
117
+ * own project settings could supply a different value there, and they already
118
+ * decide the session's attribution. Falls back to the payload's `cwd`, then the
119
+ * process cwd, when the variable is unset or not absolute (a hook run by hand).
120
+ */
121
+ export const markerProjectDir = (payload, env = process.env) => {
122
+ // Claude Code exports CLAUDE_PROJECT_DIR itself on every hook process, set to
123
+ // the root the session started in, so a project settings `env` value can't
124
+ // choose it.
125
+ const dir = env.CLAUDE_PROJECT_DIR
126
+ if (typeof dir === 'string' && isAbsolute(dir)) return dir
127
+ return payload?.cwd || process.cwd()
128
+ }
129
+
39
130
  /** Parse a comma-delimited `k=v,k2=v2` string (OTEL_RESOURCE_ATTRIBUTES / _HEADERS). */
40
131
  export const parseKv = (raw) => {
41
132
  const out = {}
@@ -97,16 +188,23 @@ const MANAGED_CREDENTIAL_KEYS = [
97
188
  /**
98
189
  * Merge settings layers (lowest precedence first), overlay any real process env
99
190
  * on top, and pull out the OTLP config the hooks need. A layer is
100
- * `{ env, exporter, managed }`:
191
+ * `{ env, exporter, managed, policy, headersHelper }`:
101
192
  *
102
193
  * - `exporter: false` layers (project and local settings) contribute only
103
194
  * `OTEL_RESOURCE_ATTRIBUTES`, never the endpoint or key.
104
195
  * - Across `managed` layers the telemetry unit travels together: its keys come
105
- * from the highest managed source that sets any of them, never an endpoint
106
- * from one source with a key from another. Other keys merge per key.
196
+ * from the highest managed source that sets any of them or sets
197
+ * `otelHeadersHelper` (`headersHelper`), never an endpoint from one source
198
+ * with a key from another. A source that claims the unit through the helper
199
+ * supplies its unit keys only when it is the managed source in effect (the
200
+ * highest one with `policy`, i.e. any policy key); otherwise it supplies none
201
+ * and still blocks the lower sources. Other keys merge per key.
107
202
  * - Over the developer's own layers, managed settings win key by key, and a
108
203
  * managed credential also removes the developer's endpoint (§
109
204
  * `MANAGED_CREDENTIAL_KEYS`).
205
+ * - With the helper in effect, the session's OTLP headers come from a command
206
+ * the hooks don't run, so no bearer is returned and no marker is sent: a
207
+ * static key found elsewhere may not be the one the session uses.
110
208
  *
111
209
  * The process env overlay only matters for a hook run by hand — Claude Code
112
210
  * removes `OTEL_*` variables from the environment it gives hooks.
@@ -120,13 +218,20 @@ export const resolveOtelConfig = (layers, processEnv) => {
120
218
  }
121
219
  }
122
220
  const managedLayers = layers.filter(({ managed }) => managed)
123
- const unitLayer = [...managedLayers]
124
- .reverse()
125
- .find(({ env }) => Object.keys(env ?? {}).some(isManagedTelemetryUnitKey))
221
+ const highestFirst = [...managedLayers].reverse()
222
+ const unitLayer = highestFirst.find(
223
+ ({ env, headersHelper }) =>
224
+ headersHelper === true || Object.keys(env ?? {}).some(isManagedTelemetryUnitKey),
225
+ )
226
+ // A layer built without `policy` delivers one if it sets any env.
227
+ const inEffect = highestFirst.find(
228
+ ({ env, policy }) => policy ?? Object.keys(env ?? {}).length > 0,
229
+ )
230
+ const unitLands = unitLayer?.headersHelper !== true || unitLayer === inEffect
126
231
  const managedEnv = {}
127
232
  for (const layer of managedLayers) {
128
233
  for (const [k, v] of Object.entries(layer.env ?? {})) {
129
- if (!isManagedTelemetryUnitKey(k) || layer === unitLayer) managedEnv[k] = v
234
+ if (!isManagedTelemetryUnitKey(k) || (layer === unitLayer && unitLands)) managedEnv[k] = v
130
235
  }
131
236
  }
132
237
  if (MANAGED_CREDENTIAL_KEYS.some((k) => managedEnv[k])) {
@@ -136,9 +241,10 @@ export const resolveOtelConfig = (layers, processEnv) => {
136
241
  for (const k of [...EXPORTER_KEYS, 'OTEL_RESOURCE_ATTRIBUTES']) {
137
242
  if (processEnv[k]) merged[k] = processEnv[k]
138
243
  }
244
+ const helperInEffect = unitLayer?.headersHelper === true && unitLands
139
245
  return {
140
246
  endpoint: merged.OTEL_EXPORTER_OTLP_ENDPOINT,
141
- bearer: bearerFromHeaders(merged.OTEL_EXPORTER_OTLP_HEADERS),
247
+ bearer: helperInEffect ? undefined : bearerFromHeaders(merged.OTEL_EXPORTER_OTLP_HEADERS),
142
248
  resourceAttrs: parseKv(merged.OTEL_RESOURCE_ATTRIBUTES),
143
249
  }
144
250
  }
@@ -151,6 +257,28 @@ const readFileSafe = (path) => {
151
257
  }
152
258
  }
153
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
+
154
282
  /** `CLAUDE_CONFIG_DIR`, ASCII-trimmed and resolved to an absolute path, or
155
283
  * `undefined` when unset or blank — a whitespace-only value counts as unset.
156
284
  * For the settings root (§ `claudeConfigDir`) only: the account cache is
@@ -163,14 +291,43 @@ const normalizedConfigDirEnv = (env) => {
163
291
 
164
292
  /** Claude Code's user config root: `$CLAUDE_CONFIG_DIR` when set, else
165
293
  * `~/.claude`. The hook runs as a Claude Code subprocess, so it sees
166
- * the same variable the session resolved its own settings from, and the CLI
167
- * resolves it the same way. A repository can't steer
294
+ * the same variable the session resolved its own settings from — or, when
295
+ * the credential scrub leaves it out, gets it back from the payload
296
+ * (§ `markerSessionEnv`) — and the CLI resolves it the same way. A repository can't steer
168
297
  * this through its project settings: Claude Code drops `CLAUDE_CONFIG_DIR`,
169
298
  * `HOME` and the other directory variables from project and local `env`
170
299
  * (since 2.1.251), so neither reaches the hook from there. */
171
300
  export const claudeConfigDir = (env = process.env) =>
172
301
  normalizedConfigDirEnv(env) ?? join(homedir(), '.claude')
173
302
 
303
+ /** The config dir a Claude Code transcript path lives under, or `undefined`
304
+ * when the path doesn't have the shape Claude Code writes:
305
+ * `<config dir>/projects/<project>/<session>.jsonl`, absolute. */
306
+ const configDirFromTranscript = (transcriptPath) => {
307
+ if (typeof transcriptPath !== 'string' || !isAbsolute(transcriptPath)) return undefined
308
+ if (!transcriptPath.endsWith('.jsonl')) return undefined
309
+ const projects = dirname(dirname(transcriptPath))
310
+ return basename(projects) === 'projects' ? dirname(projects) : undefined
311
+ }
312
+
313
+ /**
314
+ * The environment to resolve a marker's settings from: the hook's own, with
315
+ * the session's `CLAUDE_CONFIG_DIR` put back when the credential scrub
316
+ * (`CLAUDE_CODE_SUBPROCESS_ENV_SCRUB`) left it out. Without it a relocated
317
+ * config dir would resolve to `~/.claude` — another profile's user settings
318
+ * and server-managed cache. The hook payload's `transcript_path` names the
319
+ * session's config dir (§ `configDirFromTranscript`), so it is read from
320
+ * there — only for Claude Code, only with the scrub on, and only when the
321
+ * variable is unset or blank; otherwise `env` is returned as is.
322
+ */
323
+ export const markerSessionEnv = (tool, payload, env = process.env) => {
324
+ if (tool !== 'claude-code') return env
325
+ if (!isTruthyEnvValue(env.CLAUDE_CODE_SUBPROCESS_ENV_SCRUB)) return env
326
+ if (normalizedConfigDirEnv(env) !== undefined) return env
327
+ const dir = configDirFromTranscript(payload?.transcript_path)
328
+ return dir === undefined ? env : { ...env, CLAUDE_CONFIG_DIR: dir }
329
+ }
330
+
174
331
  /** A directory's `*.json` files, sorted, or `[]` when it is missing. */
175
332
  const jsonFilesIn = (dir) => {
176
333
  try {
@@ -275,19 +432,26 @@ export const managedSettingsPaths = (env = process.env, listDir = jsonFilesIn, m
275
432
  /** Top-level keys that don't make a managed file "deliver a policy". */
276
433
  const NON_POLICY_KEYS = new Set(['wslInheritsWindowsSettings', 'managedSourcesBehavior'])
277
434
 
278
- const hasPolicyKey = (text) => {
435
+ const parsedObject = (text) => {
279
436
  try {
280
437
  const doc = JSON.parse(text)
281
- return (
282
- doc !== null &&
283
- typeof doc === 'object' &&
284
- Object.keys(doc).some((k) => !NON_POLICY_KEYS.has(k))
285
- )
438
+ return doc !== null && typeof doc === 'object' && !Array.isArray(doc) ? doc : undefined
286
439
  } catch {
287
- return false
440
+ return undefined
288
441
  }
289
442
  }
290
443
 
444
+ const hasPolicyKey = (text) => {
445
+ const doc = parsedObject(text)
446
+ return doc !== undefined && Object.keys(doc).some((k) => !NON_POLICY_KEYS.has(k))
447
+ }
448
+
449
+ /** Whether a settings file's raw text sets a non-blank `otelHeadersHelper`. */
450
+ const hasOtelHeadersHelper = (text) => {
451
+ const helper = parsedObject(text)?.otelHeadersHelper
452
+ return typeof helper === 'string' && trimAscii(helper) !== ''
453
+ }
454
+
291
455
  /**
292
456
  * The managed source whose non-`env` settings (hooks, `apiKeyHelper`) Claude
293
457
  * Code uses: the first that sets any policy key, server-managed before the file
@@ -307,7 +471,8 @@ export const selectedManagedPaths = (
307
471
 
308
472
  /**
309
473
  * Settings layers Claude Code reads, lowest precedence first: user, project,
310
- * local, then one layer per managed source (§ `managedSources`). Project and
474
+ * local, then one layer per managed source (§ `managedSources`), each marked
475
+ * with whether it delivers a policy and sets `otelHeadersHelper`. Project and
311
476
  * local layers are `exporter: false` (§ `resolveOtelConfig`). `readFile`,
312
477
  * `listDir` and `managedDir` are overridable for tests.
313
478
  */
@@ -326,11 +491,16 @@ export const settingsLayers = (
326
491
  listDir,
327
492
  managedDir,
328
493
  sessionBypassesServer(cwd, env, readFile, listDir, managedDir),
329
- ).map((source) => ({
330
- env: Object.assign({}, ...source.paths.map((p) => settingsEnv(readFile(p)))),
331
- exporter: true,
332
- managed: true,
333
- })),
494
+ ).map((source) => {
495
+ const texts = source.paths.map((p) => readFile(p))
496
+ return {
497
+ env: Object.assign({}, ...texts.map(settingsEnv)),
498
+ exporter: true,
499
+ managed: true,
500
+ policy: texts.some(hasPolicyKey),
501
+ headersHelper: texts.some(hasOtelHeadersHelper),
502
+ }
503
+ }),
334
504
  ]
335
505
 
336
506
  /**
@@ -358,7 +528,7 @@ export const markerHostSource = (tool) =>
358
528
  * `String.prototype.trim`, whose Unicode `WhiteSpace`/`LineTerminator`
359
529
  * set also strips NBSP and other characters the collector would keep — so a
360
530
  * value trimmed here matches byte-for-byte what the collector sees. */
361
- 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, '')
362
532
 
363
533
  /** A file's UTF-8 text, or `undefined` when it is missing or unreadable. */
364
534
  const readOrUndefined = (path) => {
@@ -371,25 +541,34 @@ const readOrUndefined = (path) => {
371
541
 
372
542
  /** A string field ASCII-trimmed (§ `trimAscii`), or `undefined` for a
373
543
  * non-string or a value that trims to empty. */
374
- const trimmedOrUndefined = (v) => (typeof v === 'string' ? trimAscii(v) || undefined : undefined)
375
-
376
- /** `oauthAccount.emailAddress` and `oauthAccount.accountUuid` from one
377
- * `.claude.json`'s text, parsed once, each ASCII-trimmed (§ `trimAscii`) and
378
- * each independently `undefined` when missing, non-string, or blank. Both are
379
- * `undefined` for unparseable JSON. */
380
- const oauthAccountFromText = (text) => {
381
- let account
382
- try {
383
- account = JSON.parse(text)?.oauthAccount
384
- } catch {
385
- return {}
386
- }
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
387
554
  return {
388
555
  email: trimmedOrUndefined(account?.emailAddress),
389
556
  accountUuid: trimmedOrUndefined(account?.accountUuid),
390
557
  }
391
558
  }
392
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
+
393
572
  /**
394
573
  * Claude Code's own account cache — `.claude.json` (a top-level dotfile,
395
574
  * distinct from the `~/.claude/` settings directory) — written by its Claude.ai
@@ -420,10 +599,16 @@ const oauthAccountFromText = (text) => {
420
599
  * or changed shape.
421
600
  */
422
601
  export const claudeCodeOauthAccount = (home = homedir(), configDir) => {
423
- const text = readOrUndefined(resolve(configDir || home, '.claude.json'))
602
+ const text = readOrUndefined(claudeAccountPath(home, configDir))
424
603
  return text === undefined ? {} : oauthAccountFromText(text)
425
604
  }
426
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
+
427
612
  /** Env vars whose mere non-blank presence (ASCII-trimmed, § `trimAscii`) means
428
613
  * the Claude Code session does NOT authenticate through Claude.ai OAuth, so
429
614
  * `.claude.json`'s `oauthAccount` — which survives a switch to any of these —
@@ -476,10 +661,7 @@ const managedSettingsPath = (managedDir) => {
476
661
  /** The `--managed-settings-dir <dir>` flag, or undefined. Neither setup nor the
477
662
  * org-wide payload writes it; it lets tests point the hooks at a temp
478
663
  * directory instead of the machine's real org policy. */
479
- export const markerManagedDir = (argv) => {
480
- const i = (argv ?? []).indexOf('--managed-settings-dir')
481
- return i !== -1 && argv[i + 1] ? argv[i + 1] : undefined
482
- }
664
+ export const markerManagedDir = (argv) => hookFlag(argv, '--managed-settings-dir')
483
665
 
484
666
  /** Whether a settings file's raw text sets a non-blank `apiKeyHelper` — an
485
667
  * external script Claude Code invokes to resolve the API key. The hook can't
@@ -543,19 +725,34 @@ export const hasApiKeyHelper = (
543
725
  * identity beats a wrong one.
544
726
  *
545
727
  * `opts`: `env` (default `process.env`), `home` (default `homedir()`), `cwd`
546
- * (default `process.cwd()`, used for the project-local `apiKeyHelper` check),
547
- * and `configDir` — when the key is present its value is used as-is
728
+ * (the project root, § `markerProjectDir`; default `process.cwd()`, used for
729
+ * the project-local `apiKeyHelper` check), `configDir` — when the key is present its value is used as-is
548
730
  * (`undefined` = unset), otherwise `env.CLAUDE_CONFIG_DIR`, raw
549
- * (§ `claudeCodeOauthAccount`).
731
+ * (§ `claudeCodeOauthAccount`) — and `readFile` / `listDir` for the settings
732
+ * files (§ `onceReaders`).
550
733
  */
551
734
  export const markerOauthAccount = (tool, opts = {}) => {
552
- if (tool !== 'claude-code') return {}
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
553
750
  const env = opts.env ?? process.env
554
- if (isNonOauthEnv(env)) return {}
751
+ if (isNonOauthEnv(env)) return undefined
555
752
  const cwd = opts.cwd ?? process.cwd()
556
- if (hasApiKeyHelper(cwd, env, undefined, undefined, opts.managedDir)) return {}
753
+ if (hasApiKeyHelper(cwd, env, opts.readFile, opts.listDir, opts.managedDir)) return undefined
557
754
  const configDir = 'configDir' in opts ? opts.configDir : env.CLAUDE_CONFIG_DIR
558
- return claudeCodeOauthAccount(opts.home, configDir)
755
+ return claudeAccountPath(opts.home, configDir)
559
756
  }
560
757
 
561
758
  /** Last `key = "value"` match in TOML-ish text; last wins within the file. The key may
@@ -608,12 +805,13 @@ export const codexOtelConfig = (readFile = readFileSafe) => {
608
805
  }
609
806
 
610
807
  /** Resolve OTLP config for the marker emit. `tool` selects the source format:
611
- * 'codex' reads config.toml; the default reads Claude Code's settings.json env. */
612
- export const loadOtelConfig = (cwd, processEnv, tool = 'claude-code', managedDir) =>
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 = {}) =>
613
811
  tool === 'codex'
614
812
  ? codexOtelConfig()
615
813
  : resolveOtelConfig(
616
- settingsLayers(cwd, processEnv, undefined, undefined, managedDir),
814
+ settingsLayers(cwd, processEnv, readers.readFile, readers.listDir, managedDir),
617
815
  processEnv,
618
816
  )
619
817
 
@@ -649,6 +847,15 @@ export const markerResourceAttrs = (resourceAttrs, source, service, hostSource)
649
847
 
650
848
  const attr = (key, stringValue) => ({ key, value: { stringValue } })
651
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
+
652
859
  /** W3C `traceparent`, version `00`: `00-<32 hex trace id>-<16 hex span id>-<2
653
860
  * hex flags>`, lowercase only — the spec rejects uppercase hex, and a later
654
861
  * version may change the fields, so only `00` is read.
@@ -773,6 +980,10 @@ const callContextAttrs = (callContext) => {
773
980
  * which also stamps `hostSource` (optional; the marker hooks pass
774
981
  * § `markerHostSource`, the cursor behaviour hook passes nothing).
775
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
+ *
776
987
  * `callContext` (§ `markerCallContext`; optional) appends each of its fields
777
988
  * that is present as a span attribute. The span keeps its own random trace and
778
989
  * span ids either way: the calling span is referenced, never joined, because a
@@ -783,6 +994,7 @@ export const buildMarkerPayload = ({
783
994
  spanName,
784
995
  scopeName,
785
996
  attributes,
997
+ typedAttributes = [],
786
998
  sessionId,
787
999
  userEmail,
788
1000
  userAccountUuid,
@@ -815,6 +1027,7 @@ export const buildMarkerPayload = ({
815
1027
  ...Object.entries(attributes)
816
1028
  .filter(([k, v]) => !isBlankForAttr(k, v))
817
1029
  .map(([k, v]) => attr(k, String(v))),
1030
+ ...typedAttributes,
818
1031
  ...(sessionId ? [attr('session.id', sessionId)] : []),
819
1032
  ...callContextAttrs(callContext),
820
1033
  // isBlankAttr, not `in` or a truthy check: a key present but
@@ -835,7 +1048,16 @@ export const buildMarkerPayload = ({
835
1048
  ],
836
1049
  })
837
1050
 
838
- /** POST the OTLP body to the collector, failing open (any error is swallowed). */
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
+ */
839
1061
  export const emitMarker = async ({
840
1062
  endpoint,
841
1063
  bearer,
@@ -843,6 +1065,7 @@ export const emitMarker = async ({
843
1065
  label,
844
1066
  log,
845
1067
  timeoutMs = EMIT_TIMEOUT_MS,
1068
+ logOk = true,
846
1069
  }) => {
847
1070
  const controller = new AbortController()
848
1071
  const timer = setTimeout(() => controller.abort(), timeoutMs)
@@ -853,9 +1076,11 @@ export const emitMarker = async ({
853
1076
  body: JSON.stringify(body),
854
1077
  signal: controller.signal,
855
1078
  })
856
- log(`posted ${label}: status=${res.status}`)
1079
+ if (logOk || !isOkStatus(res.status)) log(`posted ${label}: status=${res.status}`)
1080
+ return res.status
857
1081
  } catch (e) {
858
1082
  log(`post failed for ${label}: ${e}`) // fail open — telemetry never blocks the session
1083
+ return undefined
859
1084
  } finally {
860
1085
  clearTimeout(timer)
861
1086
  }
@@ -887,6 +1112,108 @@ export const payloadShape = (payload) => {
887
1112
  return `keys=[${Object.keys(payload).join(',')}] output_field=${present ?? 'none'}`
888
1113
  }
889
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
+
890
1217
  /** Read all of stdin as a string; resolves '' on error. */
891
1218
  export const readStdin = () =>
892
1219
  new Promise((resolve) => {