@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.
@@ -50,6 +50,20 @@ const diffEnv = (before, after, managedKeys) => {
50
50
  const pad2 = (n) => String(n).padStart(2, '0');
51
51
  const timestamp = (d = new Date()) => `${d.getFullYear()}${pad2(d.getMonth() + 1)}${pad2(d.getDate())}` +
52
52
  `-${pad2(d.getHours())}${pad2(d.getMinutes())}${pad2(d.getSeconds())}`;
53
+ const writeBackup = async (path, body, mode) => {
54
+ const base = `${path}.bak.${timestamp()}`;
55
+ for (let n = 1;; n++) {
56
+ const candidate = n === 1 ? base : `${base}-${n}`;
57
+ try {
58
+ await fs.writeFile(candidate, body, { mode, flag: 'wx' });
59
+ return candidate;
60
+ }
61
+ catch (err) {
62
+ if (err.code !== 'EEXIST' || n >= 1000)
63
+ throw err;
64
+ }
65
+ }
66
+ };
53
67
  export const readExistingEnv = async (path, codec) => {
54
68
  const body = await readFileOrNull(path);
55
69
  if (body === null)
@@ -77,11 +91,8 @@ export const applyUpdate = async (update) => {
77
91
  let backupPath = null;
78
92
  try {
79
93
  await fs.access(dirname(target), fsConstants.W_OK);
80
- if (exists) {
81
- backupPath = `${path}.bak.${timestamp()}`;
82
- const body = await fs.readFile(path);
83
- await fs.writeFile(backupPath, body, { mode: fileMode, flag: 'wx' });
84
- }
94
+ if (exists)
95
+ backupPath = await writeBackup(path, await fs.readFile(path), fileMode);
85
96
  try {
86
97
  await fs.rename(tmpPath, target);
87
98
  }
@@ -30,7 +30,8 @@ const collectorHost = (url) => {
30
30
  };
31
31
  const formatOptIns = (o) => `prompts:${o.userPrompts ? 'yes' : 'no'} ` +
32
32
  `details:${o.toolDetails ? 'yes' : 'no'} ` +
33
- `content:${o.toolContent ? 'yes' : 'no'}`;
33
+ `content:${o.toolContent ? 'yes' : 'no'}` +
34
+ (o.repository === undefined ? '' : ` repository:${o.repository ? 'yes' : 'no'}`);
34
35
  const fileRowsFor = (adapter) => {
35
36
  const primaryParse = (env) => adapter.parseEnv(env);
36
37
  const policy = adapter.layerKeyPolicy;
@@ -1,5 +1,5 @@
1
1
  import { select } from '@inquirer/prompts';
2
- import { mergePrefills, planAdapter, planHasChanges, printMarkerCoexistenceNotes, printPostSetup, readPrefill, renderPlan, writePlan, } from './apply.js';
2
+ import { mergePrefills, planAdapter, planHasChanges, planSnapshotBlocked, printMarkerCoexistenceNotes, printPostSetup, readPrefill, renderPlan, userHooksPath, writePlan, } from './apply.js';
3
3
  import { runLogin } from './auth-commands.js';
4
4
  import { computeEffective, isManagedUnitDrop, nativeIdentityReason } from './effective-settings.js';
5
5
  import { isManagedIdentityConfig, isManagedLayer } from './layer-policy.js';
@@ -324,7 +324,27 @@ export const runSetup = async (adapters, rawOptions = {}) => {
324
324
  });
325
325
  }
326
326
  const developerPin = useCase && adapters.some((a) => !a.teamUcid) ? { ...useCase, pinned: true } : undefined;
327
+ const markerTools = plans.filter((p) => p.markersOn !== null);
328
+ const hooks = { ...settings.hooks };
329
+ if (markerTools.length > 0) {
330
+ hooks.markers = {
331
+ ...hooks.markers,
332
+ ...Object.fromEntries(markerTools.map((p) => [p.adapter.name, p.markersOn === true])),
333
+ };
334
+ const filesOf = (name) => {
335
+ const files = hooks.events?.[name];
336
+ return files !== undefined && !Array.isArray(files) ? files : {};
337
+ };
338
+ hooks.events = {
339
+ ...hooks.events,
340
+ ...Object.fromEntries(markerTools.map((p) => [
341
+ p.adapter.name,
342
+ { ...filesOf(p.adapter.name), [userHooksPath(p.adapter)]: [...p.hookEvents] },
343
+ ])),
344
+ };
345
+ }
327
346
  await updateSettings({
347
+ hooks,
328
348
  collectorUrl,
329
349
  orgName: identity.orgName,
330
350
  orgId: identity.orgId ?? settings.orgId,
@@ -369,6 +389,7 @@ export const runSetup = async (adapters, rawOptions = {}) => {
369
389
  ]))),
370
390
  optIns: answers.optIns,
371
391
  markers: answers.markers,
392
+ ...planSnapshotReport(plans, await blockedSnapshots(plans)),
372
393
  verified,
373
394
  skills: skills
374
395
  ? { installed: skills.installs.map((i) => i.path), noOps: skills.noOps }
@@ -378,6 +399,30 @@ export const runSetup = async (adapters, rawOptions = {}) => {
378
399
  }
379
400
  return 0;
380
401
  };
402
+ const blockedSnapshots = async (plans) => new Map((await Promise.all(plans
403
+ .filter((p) => p.planSnapshotOn === true)
404
+ .map(async (p) => [p.adapter.name, await planSnapshotBlocked(p.adapter)]))).flatMap(([name, why]) => (why ? [[name, why]] : [])));
405
+ export const planSnapshotReport = (plans, blocked = new Map()) => {
406
+ const hosts = plans.filter((p) => p.planSnapshotOn !== null);
407
+ if (hosts.length === 0) {
408
+ return { planSnapshot: false, planSnapshotReason: 'not-hosted' };
409
+ }
410
+ const on = hosts.filter((p) => p.planSnapshotOn === true);
411
+ if (on.length === 0) {
412
+ return hosts.some((p) => p.planSnapshotOrgDelivered)
413
+ ? { planSnapshot: true, planSnapshotReason: 'org-delivered' }
414
+ : { planSnapshot: false, planSnapshotReason: 'no-markers' };
415
+ }
416
+ const blockedHosts = on.filter((p) => blocked.has(p.adapter.name));
417
+ if (blockedHosts.length === on.length) {
418
+ return {
419
+ planSnapshot: false,
420
+ planSnapshotReason: 'blocked',
421
+ planSnapshotBlockedBy: Object.fromEntries(blockedHosts.map((p) => [p.adapter.name, blocked.get(p.adapter.name).reason])),
422
+ };
423
+ }
424
+ return { planSnapshot: true };
425
+ };
381
426
  const maybeVerify = async (options, signedIn, ucid, apiUrl, teamOnly) => {
382
427
  if (options.skipVerify || !signedIn)
383
428
  return { verified: undefined, printed: undefined };
package/dist/main.js CHANGED
@@ -1,11 +1,11 @@
1
- import { claudeCode } from './adapters/claude-code.js';
1
+ import { claudeCodeFor } from './adapters/claude-code.js';
2
2
  import { adapterNames, adapters } from './adapters/index.js';
3
3
  import { runLogin, runLogout, runWhoami } from './core/auth-commands.js';
4
4
  import { runDoctor } from './core/doctor.js';
5
5
  import { runEdit } from './core/edit.js';
6
6
  import { runEnvCommand } from './core/env-command.js';
7
7
  import { PlatformError, WizardAbort } from './core/errors.js';
8
- import { runInstallHooks } from './core/install-hooks.js';
8
+ import { runInstallHooks, sessionConfigDir } from './core/install-hooks.js';
9
9
  import { flagBool, flagValue, hasFlag, parseArgs } from './core/flags.js';
10
10
  import { color } from './core/format.js';
11
11
  import { promptAdapters } from './core/prompts.js';
@@ -47,9 +47,10 @@ Usage:
47
47
  show settings hierarchy and run health checks
48
48
  mainwave-cli env <adapter> print export lines for shell-sourceable adapters
49
49
  (usage: \`eval "$(mainwave-cli env <adapter>)"\`)
50
- mainwave-cli install-hooks [--quiet] install or refresh the Claude Code ticket & PR marker
51
- hook scripts, with no prompts or sign-in (run by an
52
- org's managed settings at session start)
50
+ mainwave-cli install-hooks [--quiet] install or refresh the Mainwave hook entry and the
51
+ latest release's hook scripts, with no prompts or
52
+ sign-in (run at session start by an org's managed
53
+ settings, and by setup's own session-start hook)
53
54
  mainwave-cli --help show this message
54
55
 
55
56
  Setup flags (every prompt has one, so scripts and coding agents can drive it):
@@ -62,9 +63,11 @@ Setup flags (every prompt has one, so scripts and coding agents can drive it):
62
63
  --invite <token> redeem an account-less developer invite: no login, no key
63
64
  to paste — the token brings its own key, collector, and
64
65
  identity (mutually exclusive with --api-key/--ucid/--use-case)
65
- --opt-in prompts,tool-details,tool-content|all|none content capture
66
- (default: all on — "--opt-in none" sends metadata only)
67
- --no-markers skip the ticket & PR marker hooks (installed by default)
66
+ --opt-in prompts,tool-details,tool-content,repository|all|none content capture
67
+ (default: all on — "--opt-in none" sends metadata only;
68
+ repository = repository names on Claude Code telemetry)
69
+ --no-markers skip the Mainwave hooks (installed by default): the ticket
70
+ & PR markers and, for Claude Code, the plan snapshot
68
71
  --yes --json --no-verify --verify-timeout <seconds>
69
72
  --skills / --no-skills install the agent skills payload (default: ask, or on in scripts)
70
73
  --skills-only install only the skills, touching no telemetry config
@@ -109,6 +112,7 @@ const parseOptIns = (value) => {
109
112
  userPrompts: has('prompts', 'user-prompts'),
110
113
  toolDetails: has('tool-details', 'details'),
111
114
  toolContent: has('tool-content', 'content'),
115
+ repository: has('repository', 'repo'),
112
116
  };
113
117
  };
114
118
  const detectedAdapters = () => {
@@ -257,7 +261,10 @@ export const main = async (argv) => {
257
261
  }
258
262
  if (cmd === 'install-hooks') {
259
263
  const parsed = parseArgs(args.slice(1));
260
- return runInstallHooks(claudeCode, { quiet: flagBool(parsed, 'quiet') === true });
264
+ const dir = await sessionConfigDir();
265
+ return runInstallHooks(dir === undefined ? undefined : claudeCodeFor(dir), {
266
+ quiet: flagBool(parsed, 'quiet') === true,
267
+ });
261
268
  }
262
269
  if (cmd === 'setup') {
263
270
  const parsed = parseArgs(args.slice(1));
@@ -38,7 +38,7 @@ import {
38
38
  } from './marker-core.mjs'
39
39
  import { ATTR_CODE_FILE_PATH } from './vocabulary.mjs'
40
40
 
41
- const log = markerLog(process.argv, '.mainwave-cursor.log')
41
+ const log = markerLog(process.argv, 'cursor.log')
42
42
 
43
43
  // Classified by the collector as a coding agent via `mainwave.source`; the
44
44
  // service name matches Cursor's own native-export resource (`service.name=cursor`)
@@ -1,5 +1,8 @@
1
1
  #!/usr/bin/env node
2
- // Claude Code PostToolUse hook for `gh pr create`.
2
+ // The GitHub pull-request marker: a PostToolUse feature of the Mainwave hook
3
+ // dispatcher (mainwave-hook.mjs) for `gh pr create`. It also still runs on its
4
+ // own (§ the main at the bottom), because hook settings pasted before the
5
+ // dispatcher name this file.
3
6
  //
4
7
  // The platform detects "PR opened" by regex-matching `gh pr create` in the
5
8
  // captured Bash *command* text, which yields the title but never the PR number
@@ -12,10 +15,11 @@
12
15
  //
13
16
  // Shared OTLP plumbing lives in ./marker-core.mjs. Privacy: emits the PR url /
14
17
  // number / title and *aggregate* diff counts (changed files, additions,
15
- // deletions) — never the diff contents or body. This hook is matched to the
16
- // Bash tool, so it fires after every Bash command; it returns immediately (no
17
- // log, no network) for anything that isn't a `gh pr create`, and fails open and
18
- // fast otherwise, so it can never block or slow the session.
18
+ // deletions) — never the diff contents or body. Claude Code runs it only for a
19
+ // Bash command that starts with `gh` (the hook group's `if` filter); it still
20
+ // returns immediately (no log, no network) for anything that isn't a
21
+ // `gh pr create`, and fails open and fast otherwise, so it can never block or
22
+ // slow the session.
19
23
 
20
24
  import { execFile } from 'node:child_process'
21
25
  import { pathToFileURL } from 'node:url'
@@ -52,7 +56,7 @@ import {
52
56
  // Re-export the shared output-reading helpers so the tests can import them here.
53
57
  export { payloadShape, toolOutput } from './marker-core.mjs'
54
58
 
55
- const log = markerLog(process.argv, '.mainwave-pr-marker.log')
59
+ const LOG_NAME = 'pr-marker.log'
56
60
 
57
61
  // Non-coding source/service so the marker lands as an ordinary span and stays
58
62
  // out of the coding-work segmentation, same as the ticket marker.
@@ -178,18 +182,17 @@ export const buildPrPayload = ({
178
182
  nowNs,
179
183
  })
180
184
 
181
- const main = async () => {
182
- let payload
183
- try {
184
- payload = JSON.parse(await readStdin())
185
- } catch {
186
- return // fires on every Bash call — stay silent for anything we can't read
187
- }
188
-
189
- // Cheap guard first: this hook sees every Bash command, so bail with no log and
190
- // no work unless the command actually opened a PR.
191
- const command = payload.tool_input?.command
185
+ /**
186
+ * The feature: one marker span when the Bash command opened a PR, else
187
+ * nothing. `ctx.argv` carries the hook command's flags (and `--tool <host>`
188
+ * under the dispatcher); `ctx.emit` posts.
189
+ */
190
+ export const handle = async (payload, { argv = process.argv, emit = emitMarker } = {}) => {
191
+ // Cheap guard first: bail with no log and no work unless the command
192
+ // actually opened a PR.
193
+ const command = payload?.tool_input?.command
192
194
  if (!isPrCreate(command)) return
195
+ const log = markerLog(argv, LOG_NAME)
193
196
 
194
197
  const url = extractPrUrl(toolOutput(payload))
195
198
  if (!url) {
@@ -201,8 +204,8 @@ const main = async () => {
201
204
 
202
205
  const cwd = payload.cwd || process.cwd()
203
206
  const projectDir = markerProjectDir(payload)
204
- const tool = markerTool(process.argv)
205
- const managedDir = markerManagedDir(process.argv)
207
+ const tool = markerTool(argv)
208
+ const managedDir = markerManagedDir(argv)
206
209
  const env = markerSessionEnv(tool, payload)
207
210
  const { endpoint, bearer, resourceAttrs } = loadOtelConfig(projectDir, env, tool, managedDir)
208
211
  log(
@@ -226,7 +229,7 @@ const main = async () => {
226
229
  // repository.
227
230
  const { changedFiles, additions, deletions } = await fetchPrStats(number, {
228
231
  cwd,
229
- bin: hookFlag(process.argv, '--gh-bin'),
232
+ bin: hookFlag(argv, '--gh-bin'),
230
233
  })
231
234
  log(
232
235
  `stats changed_files=${changedFiles ?? 'na'} additions=${additions ?? 'na'} ` +
@@ -248,7 +251,17 @@ const main = async () => {
248
251
  callContext: markerCallContext(tool, payload),
249
252
  nowNs: BigInt(Date.now()) * 1_000_000n,
250
253
  })
251
- await emitMarker({ endpoint, bearer, body, label: `#${number}`, log })
254
+ await emit({ endpoint, bearer, body, label: `#${number}`, log })
255
+ }
256
+
257
+ const main = async () => {
258
+ let payload
259
+ try {
260
+ payload = JSON.parse(await readStdin())
261
+ } catch {
262
+ return // fires on every Bash call — stay silent for anything we can't read
263
+ }
264
+ await handle(payload)
252
265
  }
253
266
 
254
267
  // Run the IO path only when executed directly, so tests can import the pure fns.
@@ -256,6 +269,6 @@ const main = async () => {
256
269
  // file URL (e.g. the space in the managed install dir "/Library/Application
257
270
  // Support/…") still matches import.meta.url — a raw `file://${argv[1]}` template
258
271
  // keeps the literal space, never matches, and silently skips main().
259
- if (import.meta.url === pathToFileURL(process.argv[1]).href) {
272
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
260
273
  await main()
261
274
  }