@mainwave/cli 0.14.0 → 0.16.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 CHANGED
@@ -3,7 +3,7 @@
3
3
  Setup wizard that connects third-party coding tools to [Mainwave AI](https://mainwave.com), so their
4
4
  OpenTelemetry traces land in your dashboard, attributed to you.
5
5
 
6
- Installs as the `mainwave-cli` command. Requires Node 22.13 or newer.
6
+ Installs as the `mainwave-cli` command. Requires Node 22.22 or newer on 22.x, 24.15 or newer on 24.x, or Node 26 and later.
7
7
 
8
8
  ## Supported tools
9
9
 
@@ -470,7 +470,9 @@ tool waiting for your approval, and the start and end times. They never send you
470
470
  reply, a tool's input or output, or the transcript path. They run in the background, except the
471
471
  stop and interrupt hooks: Codex waits for those at the end of each turn while they send it (1.2 s at
472
472
  most for the send, 1 s for an interrupt), because `codex exec` exits without waiting for a background hook. They keep a
473
- small state file per session in `~/.mainwave/state/codex-turns/`, deleted after seven days.
473
+ small state file per session in `~/.mainwave/state/codex-turns/`, deleted after seven days, and a
474
+ one-line timestamp file, `~/.mainwave/logs/codex-turns.log.ok`, that records the last successful
475
+ send for `doctor`.
474
476
 
475
477
  Codex runs a hook only after you trust it. The first Codex session after setup shows "Hooks need
476
478
  review": choose "Trust all", or open `/hooks` and trust each Mainwave hook, the session-start hook
@@ -495,10 +497,13 @@ For a profile, setup writes the telemetry settings and the Mainwave hooks into
495
497
  `<codex home>/<name>.config.toml`, and writes none to `config.toml` or `hooks.json`. A session
496
498
  started without `--profile <name>` sends nothing to Mainwave and runs no Mainwave hook. If the Codex
497
499
  home already has the all-sessions setup, the same run removes it from `config.toml` and
498
- `hooks.json`, so the home never holds both. The setup preview lists every file it changes. Once a
499
- profile is set up, running setup again with the same `--profile` changes nothing. The first run on a
500
- profile file that already has content appends Mainwave's hook tables at the end of the file, moves
501
- any `[[hooks.<Event>]]` tables already there to join them, and keeps the rest as it was.
500
+ `hooks.json`, so the home never holds both. When that leaves nothing in `hooks.json`, setup removes
501
+ the file and keeps a backup beside it. When it moves another tool's hooks in `hooks.json` to a new
502
+ position, Codex asks you to trust them again, and the preview says so. The setup preview lists every
503
+ file it changes. Once a profile is set up, running setup again with the same `--profile` changes
504
+ nothing. The first run on a profile file that already has content appends Mainwave's hook tables at
505
+ the end of the file, moves any `[[hooks.<Event>]]` tables already there to join them, and keeps the
506
+ rest as it was.
502
507
 
503
508
  A profile name is 1 to 64 letters, digits, `_` or `-`, and does not start with `-`. `default` is
504
509
  reserved by Codex. Setup refuses a name whose file already has an `[otel]` table that isn't
@@ -515,10 +520,35 @@ Add a separate alias, for example `alias codex-mw='codex --profile mainwave'`, a
515
520
  `codex`. `--profile` goes before the subcommand: `codex --profile mainwave exec resume <id>` resumes
516
521
  with the profile, and `codex exec resume --profile mainwave` exits with an error.
517
522
 
518
- `setup codex --remove` is not available for Codex. To remove a profile setup, delete
519
- `<codex home>/<name>.config.toml` if it holds nothing else of yours, or remove its `[otel.*]` tables
520
- and the `[[hooks.<Event>]]` tables whose commands name `mainwave-hook.sh` or `install-hooks`. That
521
- file holds your Mainwave API key.
523
+ To take Mainwave out of Codex again:
524
+
525
+ ```bash
526
+ mainwave-cli setup codex --remove # the all-sessions setup
527
+ mainwave-cli setup codex --remove --profile <name> # a profile setup
528
+ ```
529
+
530
+ The all-sessions removal takes Mainwave's telemetry settings out of `config.toml`, Mainwave's hooks
531
+ out of `hooks.json`, and Codex's approvals of those hooks out of `config.toml`. The profile removal
532
+ takes Mainwave's telemetry settings, hooks and hook approvals out of `<codex home>/<name>.config.toml`,
533
+ and Codex's approvals of those hooks out of `config.toml`. Everything else in those files stays as
534
+ it was, including other tools' hooks and Codex's approvals of them. Codex keys an approval by the
535
+ hook's position, so a hook listed after a removed Mainwave hook needs approving again; the preview
536
+ names each approved hook of another tool that moves, by its program only, since its arguments may hold a secret. A file left with nothing but Mainwave's setup is deleted, unless it
537
+ is a symlink: then the link stays and the file it points to is left empty (`{}` for `hooks.json`). The
538
+ preview lists every file the removal changes, and each one gets a backup beside it. The summary
539
+ marks each backup that still holds your API key. When no Codex setup is left, the removal also takes Mainwave's instructions out
540
+ of `<codex home>/AGENTS.md`. Run it with the same `CODEX_HOME` you ran setup with.
541
+
542
+ A Codex app-server daemon that was already running keeps the settings it loaded when it started, and
543
+ new Codex sessions go through it. After an all-sessions setup or removal it keeps the old settings,
544
+ and after a removal it keeps sending telemetry to Mainwave, until it restarts. Both commands say so;
545
+ run `codex app-server daemon restart`. Profile sessions (`codex --profile`) run without the daemon
546
+ and don't need this.
547
+
548
+ Plain `--remove` in a home whose only Mainwave setup is a profile's changes nothing, exits with
549
+ code 1, and names the profile and the `--remove --profile <name>` command. A removal that leaves
550
+ another setup in the home names that setup and the command that removes it. Running `--remove`
551
+ again says there is nothing to remove.
522
552
 
523
553
  Plain `setup codex` in a home that has a profile setup asks whether to update the profile or to
524
554
  switch to all sessions, which removes Mainwave from the profile file. Without a terminal it exits
@@ -528,12 +558,17 @@ with code 1 and names the `--profile` command, and `--yes` doesn't choose.
528
558
  its own. A profile's report is titled `Codex CLI, profile <name>`, lists the profile file as
529
559
  `Profile <name>` and its hooks as `Profile <name> hooks file`, and checks the endpoint, the
530
560
  authorization header, the metrics exporter and the hook approvals recorded in the profile file. It
531
- warns when a home holds Mainwave settings or hooks for all sessions and in a profile at once. Codex
532
- merges `config.toml` under the profile file table by table, so in profile sessions any header or
533
- setting of another vendor's `[otel]` exporter in `config.toml` that the profile does not set is also
534
- sent to Mainwave's collector. Mainwave's key is not sent to the other collector. `setup codex
535
- --profile` and `doctor` both warn about that. `status codex` lists each profile setup by name after
536
- the all-sessions files, and its `--json` output marks a profile entry with `"setup": "profile <name>"`.
561
+ warns when a home holds Mainwave settings or hooks for all sessions and in a profile at once, and
562
+ when more than one profile holds a Mainwave setup; `setup codex --profile` says so too when another
563
+ profile already holds one. That warning and setup's both name `mainwave-cli setup codex --remove --profile <other>` as the way
564
+ to remove each other profile's setup. Codex merges `config.toml` under the profile file table by table, so in
565
+ profile sessions any header or setting of another vendor's `[otel]` exporter in `config.toml` that
566
+ the profile does not set is also sent to Mainwave's collector. Mainwave's key is not sent to the
567
+ other collector. `setup codex --profile` and `doctor` both warn about that. Plain `setup codex`
568
+ replaces only Mainwave's own keys in `config.toml`, so another vendor's exporter headers or settings
569
+ there stay beside Mainwave's and are sent to Mainwave's collector in every session; setup and
570
+ `doctor` warn about that too. `status codex` lists each profile setup by name after the all-sessions
571
+ files, and its `--json` output marks a profile entry with `"setup": "profile <name>"`.
537
572
 
538
573
  On Windows, the Claude Code hooks need Git for Windows. Claude Code runs hook commands through Git
539
574
  Bash, and through PowerShell when it finds none, where the entry's shell command can't run. Without
@@ -646,8 +681,8 @@ written into any tool's settings file.
646
681
 
647
682
  ```bash
648
683
  mainwave-cli status [<adapter>] # on-disk config for every tool, or just one
649
- mainwave-cli doctor <adapter> # settings hierarchy + health checks
650
- mainwave-cli doctor <adapter> --validate # also auth-check against the collector
684
+ mainwave-cli doctor <adapter> # settings hierarchy + health checks; exits 1 if the collector rejects the key
685
+ mainwave-cli doctor <adapter> --validate # also exit 1 if the key cannot be checked or the collector cannot be reached
651
686
  mainwave-cli edit <adapter> # open the settings file in $EDITOR
652
687
  mainwave-cli edit <adapter> --global # the user-level file, without the picker (--local: this project's)
653
688
  mainwave-cli env <adapter> # print shell export lines
@@ -666,6 +701,13 @@ needs your email has none — Codex or Copilot, or Claude Code when it isn't sig
666
701
  account (an API key, Bedrock or Vertex, or no sign-in at all) — or `cursor-enterprise` has no team
667
702
  use-case id.
668
703
 
704
+ When the configuration is Mainwave's, plain `doctor` also checks the key with the collector
705
+ (`/v1/whoami`, waiting up to 3 seconds). It skips the check when there is no endpoint or key, or when a
706
+ repository chose the endpoint, it fails on a rejected key, and it only warns when the collector can't
707
+ be reached. When the configuration isn't Mainwave's exporter (another vendor's endpoint and key), plain
708
+ `doctor` skips the check without a message, and `doctor --validate` exits 1 and says "the config isn't
709
+ Mainwave's exporter". `--validate` also exits 1 when there is no endpoint or key to check.
710
+
669
711
  From Claude Code 2.1.282, project and local settings (`.claude/settings.json`,
670
712
  `.claude/settings.local.json`) can no longer turn telemetry on, choose where it goes, or choose what
671
713
  it captures: Claude Code ignores those keys there. `doctor`, `status` and `edit --local` say so, name
@@ -700,7 +742,8 @@ lived there — and Cursor and VS Code Copilot Chat stop sending until then.
700
742
  To stop entirely, also remove the Mainwave entries from your tools' settings — for Claude Code,
701
743
  `mainwave-cli setup claude-code --no-markers` removes its hooks, or delete the hook groups that
702
744
  name `mainwave-hook.sh`, `install-hooks` or `--managed-by @mainwave/cli` from
703
- `~/.claude/settings.json`, along with the `OTEL_*` telemetry keys setup wrote. Hooks delivered
745
+ `~/.claude/settings.json`, along with the `OTEL_*` telemetry keys setup wrote. For Codex and Kiro,
746
+ `mainwave-cli setup <tool> --remove` takes their entries out. Hooks delivered
704
747
  through your organization's managed settings stay until your Claude admin removes them. Hooks
705
748
  now log under `~/.mainwave/logs/`; releases before that logged to `~/.mainwave-*.log` files in your
706
749
  home directory, which are left for you to delete.
@@ -8,7 +8,10 @@ import { tomlOtelCodec } from '../core/codecs/toml-otel.js';
8
8
  import { tomlProfileCodec } from '../core/codecs/toml-profile.js';
9
9
  import { UCID_SOURCE_EXPLICIT } from '../core/headers.js';
10
10
  import { versionAtLeast } from '../core/layer-policy.js';
11
+ import { WizardAbort } from '../core/errors.js';
11
12
  import { commandOwnership } from '../core/markers.js';
13
+ import { planSetupRemoval, removalSteps } from '../core/setup-removal.js';
14
+ import { planBlockRemoval } from '../core/skills.js';
12
15
  export const codexHome = (env = process.env) => {
13
16
  const dir = env.CODEX_HOME;
14
17
  if (dir === undefined || dir === '')
@@ -216,12 +219,49 @@ const profileFile = (home, profile) => join(home, profileFileName(profile));
216
219
  export const profileProcessNote = (profile) => `The profile applies to one Codex process: a session started without \`--profile ${profile}\`, ` +
217
220
  `\`codex resume\` included, sends nothing to Mainwave. Add a separate alias rather than ` +
218
221
  `typing the flag, for example \`alias codex-mw='codex --profile ${profile}'\`.`;
219
- const holdsMainwaveExporter = (env) => Object.keys(env).some((key) => {
222
+ const profileRuns = (profiles) => profiles.map((p) => `\`codex --profile ${p}\``).join(' or ');
223
+ const profilesWithFiles = (home, profiles) => profiles.map((p) => `${p} (${profileFile(home, p)})`).join(', ');
224
+ const removalCommands = (profiles) => profiles.map((p) => `\`mainwave-cli setup codex --remove --profile ${p}\``).join(' and ');
225
+ export const otherProfileSetupsNote = (home, profile) => {
226
+ const others = findCodexProfileSetups(home).filter((p) => p !== profile);
227
+ if (others.length === 0)
228
+ return undefined;
229
+ const one = others.length === 1;
230
+ return (`Codex ${one ? 'profile' : 'profiles'} ${profilesWithFiles(home, others)} already ` +
231
+ `${one ? 'holds' : 'hold'} a Mainwave setup. This run sets up profile ${profilesWithFiles(home, [profile])} ` +
232
+ `too and leaves ${others.join(', ')} as ${one ? 'it is' : 'they are'}, so sessions started with ` +
233
+ `${profileRuns([...others, profile])} send to Mainwave. To keep only ${profile}, run ` +
234
+ `${removalCommands(others)}.`);
235
+ };
236
+ const mainwaveExporterTables = (env) => Object.keys(env).flatMap((key) => {
220
237
  const m = /^(otel\..+)\.headers\.X-Mainwave-Source$/.exec(key);
221
- return (m !== null &&
222
- env[`${m[1]}.endpoint`] !== undefined &&
223
- env[`${m[1]}.headers.Authorization`] !== undefined);
238
+ return m !== null && env[key] === SOURCE_VALUE ? [m[1]] : [];
224
239
  });
240
+ const holdsMainwaveExporter = (env) => mainwaveExporterTables(env).length > 0;
241
+ const holdsMainwaveKey = (env) => mainwaveExporterTables(env).some((t) => (env[`${t}.headers.Authorization`] ?? '') !== '');
242
+ const missingExporterParts = (env) => {
243
+ const tables = mainwaveExporterTables(env);
244
+ const hasEndpoint = (t) => (env[`${t}.endpoint`] ?? '') !== '';
245
+ const hasAuth = (t) => (env[`${t}.headers.Authorization`] ?? '') !== '';
246
+ if (tables.length === 0 || tables.some((t) => hasEndpoint(t) && hasAuth(t)))
247
+ return [];
248
+ const missing = [
249
+ ...(tables.some(hasEndpoint) ? [] : ['endpoint']),
250
+ ...(tables.some(hasAuth) ? [] : ['Authorization header']),
251
+ ];
252
+ return missing.length > 0 ? missing : ['table with both an endpoint and an Authorization header'];
253
+ };
254
+ const brokenProfileIssues = (profile, path) => {
255
+ const env = readConfigEnv(path);
256
+ if (env === undefined)
257
+ return [];
258
+ return missingExporterParts(env).map((part) => ({
259
+ level: 'error',
260
+ message: `Mainwave's setup in ${path} has no ${part}, so sessions started with ` +
261
+ `\`codex --profile ${profile}\` send nothing to Mainwave. ` +
262
+ `Run \`mainwave-cli setup codex --profile ${profile}\` again to write it.`,
263
+ }));
264
+ };
225
265
  const EXPORTER_KEY = /^otel\.(?:exporter|trace_exporter|metrics_exporter)\./;
226
266
  const holdsOtherExporter = (env) => !holdsMainwaveExporter(env) && Object.keys(env).some((k) => EXPORTER_KEY.test(k));
227
267
  export const otherExporterNote = (config, profiles) => `${config} has telemetry settings for another collector. Codex applies config.toml under ` +
@@ -231,6 +271,22 @@ export const otherExporterNote = (config, profiles) => `${config} has telemetry
231
271
  "collector. Mainwave's key is not sent to the other collector. If that matters, move the other " +
232
272
  "collector's settings into a profile file of their own, or set Mainwave up in a separate Codex " +
233
273
  'home with CODEX_HOME.';
274
+ const foreignExporterKeys = (env) => Object.keys(env).filter((k) => EXPORTER_KEY.test(k) && !MANAGED_ENV_KEYS.includes(k));
275
+ export const sharedExporterNote = (config, keys) => `${config} has telemetry settings for another collector beside Mainwave's (${keys.join(', ')}). ` +
276
+ "Codex sends each signal to one collector, so in every session any header or setting of that collector's " +
277
+ "that Mainwave's exporter does not replace is also sent to Mainwave's collector, and that collector " +
278
+ "gets no Codex telemetry. If that matters, move the other collector's settings into a Codex profile " +
279
+ '(`setup codex --profile <name>` sets Mainwave up in one instead), or set Mainwave up in a separate ' +
280
+ 'Codex home with CODEX_HOME.';
281
+ const sharedExporterIssues = (config, env) => {
282
+ const keys = foreignExporterKeys(env);
283
+ return keys.length === 0 ? [] : [{ level: 'warn', message: sharedExporterNote(config, keys) }];
284
+ };
285
+ export const homeSharedExporterWarning = (home) => {
286
+ const config = join(home, 'config.toml');
287
+ const env = readConfigEnv(config, tomlOtelCodec);
288
+ return env === undefined ? undefined : sharedExporterIssues(config, env)[0]?.message;
289
+ };
234
290
  export const profileOtherExporterWarning = (home, profile) => {
235
291
  const config = join(home, 'config.toml');
236
292
  let env;
@@ -252,6 +308,23 @@ const readConfigEnv = (path, codec = tomlProfileCodec) => {
252
308
  return undefined;
253
309
  }
254
310
  };
311
+ export const profileRefusal = (home, profile) => {
312
+ const path = profileFile(home, profile);
313
+ let body;
314
+ try {
315
+ body = readFileSync(path, 'utf8');
316
+ }
317
+ catch {
318
+ return undefined;
319
+ }
320
+ try {
321
+ tomlProfileCodec.parse(body, path);
322
+ return undefined;
323
+ }
324
+ catch (err) {
325
+ return err.message;
326
+ }
327
+ };
255
328
  const holdsProfileSetup = (path) => {
256
329
  const env = readConfigEnv(path);
257
330
  if (env !== undefined)
@@ -322,6 +395,18 @@ const codexDoctorSetups = (home) => {
322
395
  const which = `${profiles.length === 1 ? 'profile' : 'profiles'} ${profiles.join(', ')} (${files})`;
323
396
  const rerun = `mainwave-cli setup codex --profile ${profiles.length === 1 ? profiles[0] : '<name>'}`;
324
397
  const issues = [];
398
+ if (profiles.length > 1) {
399
+ issues.push({
400
+ level: 'warn',
401
+ message: `Mainwave is set up in Codex profiles ${profilesWithFiles(home, profiles)}, so sessions started ` +
402
+ `with ${profileRuns(profiles)} send to Mainwave. ` +
403
+ `To keep one, run \`mainwave-cli setup codex --remove --profile <name>\` for each of the ` +
404
+ `others: ${profiles.join(', ')}.`,
405
+ });
406
+ }
407
+ const perProfileVersion = profiles.length > 1
408
+ ? profiles.flatMap((p) => profileVersionIssues([p]).map((i) => i.message))
409
+ : [];
325
410
  if (homeConfig) {
326
411
  const where = homeHooks ? `${config} and ${hooksJson}` : config;
327
412
  issues.push({
@@ -356,6 +441,14 @@ const codexDoctorSetups = (home) => {
356
441
  })),
357
442
  ],
358
443
  issues,
444
+ ...(perProfileVersion.length === 0
445
+ ? {}
446
+ : {
447
+ onceInText: {
448
+ replaces: (issue) => perProfileVersion.includes(issue.message),
449
+ issues: profileVersionIssues(profiles),
450
+ },
451
+ }),
359
452
  };
360
453
  };
361
454
  const projectLayer = {
@@ -397,11 +490,11 @@ export const CODEX_CLI = {
397
490
  },
398
491
  };
399
492
  const CODEX_PROFILE_MIN_VERSION = '0.169.0';
400
- const tooOldForProfile = (version, profile) => version !== undefined && versionAtLeast(version, CODEX_PROFILE_MIN_VERSION) === false
493
+ const tooOldForProfile = (version, profiles) => version !== undefined && versionAtLeast(version, CODEX_PROFILE_MIN_VERSION) === false
401
494
  ? `Codex ${version} is installed, and Codex reads profile files from ${CODEX_PROFILE_MIN_VERSION}, ` +
402
- `so sessions started with \`codex --profile ${profile}\` send nothing to Mainwave until Codex is upgraded.`
495
+ `so sessions started with ${profileRuns(profiles)} send nothing to Mainwave until Codex is upgraded.`
403
496
  : undefined;
404
- const profileVersionIssues = (profile) => {
497
+ const profileVersionIssues = (profiles) => {
405
498
  if (process.platform === 'win32')
406
499
  return [];
407
500
  const version = CODEX_CLI.version();
@@ -414,16 +507,14 @@ const profileVersionIssues = (profile) => {
414
507
  },
415
508
  ];
416
509
  }
417
- const old = tooOldForProfile(version, profile);
510
+ const old = tooOldForProfile(version, profiles);
418
511
  return old === undefined ? [] : [{ level: 'warn', message: old }];
419
512
  };
420
513
  const profilePostSetup = (profile) => {
421
- const old = tooOldForProfile(CODEX_CLI.version(), profile);
514
+ const old = tooOldForProfile(CODEX_CLI.version(), [profile]);
422
515
  return `${old === undefined ? '' : `! ${old}\n`}` + profileNext(profile);
423
516
  };
424
- const profileNext = (profile) => `Next for Codex CLI: start \`codex --profile ${profile}\` and trust the Mainwave hooks once there ` +
425
- `("Trust all" at the "Hooks need review" prompt). Until then \`codex exec --profile ${profile}\` ` +
426
- `skips them. ${profileProcessNote(profile)}`;
517
+ const profileNext = (profile) => `Next for Codex CLI: start \`codex --profile ${profile}\`. ${profileProcessNote(profile)}`;
427
518
  const targetParts = (target) => {
428
519
  const { home } = target;
429
520
  const config = join(home, 'config.toml');
@@ -440,8 +531,22 @@ const targetParts = (target) => {
440
531
  localPath: join('.codex', 'hooks.json'),
441
532
  codec: jsonEnvCodec,
442
533
  },
443
- collectChecks,
444
- kindOnly: { doctorSetups: () => codexDoctorSetups(home) },
534
+ collectChecks: (env) => {
535
+ const own = readConfigEnv(config, tomlOtelCodec);
536
+ return [
537
+ ...collectChecks(env),
538
+ ...(own !== undefined && holdsMainwaveExporter(own)
539
+ ? sharedExporterIssues(config, own)
540
+ : []),
541
+ ];
542
+ },
543
+ kindOnly: {
544
+ doctorSetups: () => codexDoctorSetups(home),
545
+ lingeringProcess: {
546
+ onSetup: 'Codex CLI: a running Codex app-server daemon keeps the settings it loaded when it started, and new sessions go through it. Run `codex app-server daemon restart` so they use the new settings.',
547
+ onRemove: 'Codex CLI: a running Codex app-server daemon keeps the old settings and keeps sending telemetry to Mainwave until it restarts, and new sessions go through it. Run `codex app-server daemon restart` to stop that.',
548
+ },
549
+ },
445
550
  };
446
551
  case 'profile': {
447
552
  const { profile } = target;
@@ -460,8 +565,9 @@ const targetParts = (target) => {
460
565
  hookArgs: ['--codex-profile', profile],
461
566
  collectChecks: (env) => [
462
567
  ...collectChecks(env),
568
+ ...brokenProfileIssues(profile, own),
463
569
  { level: 'info', message: profileProcessNote(profile) },
464
- ...profileVersionIssues(profile),
570
+ ...profileVersionIssues([profile]),
465
571
  ],
466
572
  kindOnly: {
467
573
  codexProfile: profile,
@@ -477,6 +583,52 @@ const targetParts = (target) => {
477
583
  }
478
584
  }
479
585
  };
586
+ const removeCommand = (profile) => `mainwave-cli setup codex --remove${profile === undefined ? '' : ` --profile ${profile}`}`;
587
+ const planCodexRemoval = async (target) => {
588
+ const { home } = target;
589
+ const steps = await removalSteps(await planSetupRemoval(codexCliFor(target), { approvals: true }));
590
+ const config = join(home, 'config.toml');
591
+ const homeSetup = holdsMainwaveExporter(readConfigEnv(config, tomlOtelCodec) ?? {}) ||
592
+ holdsMainwaveHooks(join(home, 'hooks.json'));
593
+ const profiles = findCodexProfileSetups(home).filter((p) => target.kind === 'home' || p !== target.profile);
594
+ if (target.kind === 'home' && steps.length === 0 && profiles.length > 0) {
595
+ const where = profiles.map((p) => `profile ${p} (${profileFile(home, p)})`).join(' and ');
596
+ throw new WizardAbort(`Mainwave isn't set up for every Codex session in ${home}; it is set up in ${where}. ` +
597
+ `To remove it, run ${profiles.map((p) => `\`${removeCommand(p)}\``).join(' and ')}.`);
598
+ }
599
+ const notes = [
600
+ ...(target.kind === 'profile' && steps.length === 0
601
+ ? [
602
+ {
603
+ kind: 'note',
604
+ note: `Nothing to remove: no Mainwave setup in ${profileFile(home, target.profile)}.`,
605
+ },
606
+ ]
607
+ : []),
608
+ ...(target.kind === 'profile' && homeSetup
609
+ ? [
610
+ {
611
+ kind: 'note',
612
+ note: `Mainwave is still set up for every Codex session (${config}); \`${removeCommand()}\` removes it.`,
613
+ },
614
+ ]
615
+ : []),
616
+ ...profiles.map((p) => ({
617
+ kind: 'note',
618
+ note: `Mainwave is still set up in profile ${p} (${profileFile(home, p)}); \`${removeCommand(p)}\` removes it.`,
619
+ })),
620
+ ];
621
+ const lastSetup = profiles.length === 0 && (target.kind === 'home' || !homeSetup);
622
+ const agents = lastSetup ? await planBlockRemoval(join(home, 'AGENTS.md')) : undefined;
623
+ return [...notes, ...steps, ...(agents === undefined ? [] : [withBackup(agents)])];
624
+ };
625
+ const withBackup = (step) => {
626
+ if (step.kind === 'update')
627
+ return { ...step, update: { ...step.update, backup: true } };
628
+ if (step.kind === 'delete')
629
+ return { ...step, backup: true };
630
+ return step;
631
+ };
480
632
  export const codexCliFor = (target) => {
481
633
  const { home } = target;
482
634
  const parts = targetParts(target);
@@ -508,6 +660,8 @@ export const codexCliFor = (target) => {
508
660
  collectFileChecks,
509
661
  normalizeForGenericChecks,
510
662
  holdsOwnSetup: holdsMainwaveExporter,
663
+ holdsOwnKey: holdsMainwaveKey,
664
+ removal: { group: 'codex', plan: () => planCodexRemoval(target) },
511
665
  ...parts.kindOnly,
512
666
  markers: {
513
667
  disclosure: 'Sends Linear/Jira issue ids and GitHub PR / GitLab MR urls to the collector — never ticket bodies or diff content. ' +
package/dist/commands.js CHANGED
@@ -80,12 +80,15 @@ export const COMMANDS = [
80
80
  ' sessions started with `codex --profile <name>`, from',
81
81
  ' <codex home>/<name>.config.toml. Moves an all-sessions Codex',
82
82
  ' setup there. Other tools named with it are set up as usual;',
83
- ' without codex among the tools it is an error',
83
+ ' without codex among the tools it is an error. With --remove',
84
+ ' it picks the profile setup to remove',
84
85
  ' --yes --json --no-verify --verify-timeout <seconds>',
85
86
  ' --skills / --no-skills install the agent skills payload (default: ask, or on in scripts)',
86
87
  ' --skills-only install only the skills, touching no telemetry config',
87
88
  " --remove take this CLI's config for the named tools back off this",
88
- ' machine (Kiro: its hooks file entries and kiro.env)',
89
+ ' machine (Kiro: its hooks file entries and kiro.env; Codex: its',
90
+ ' telemetry settings, hooks and hook approvals, from every',
91
+ ' session or, with --profile <name>, from that profile)',
89
92
  ],
90
93
  flags: [
91
94
  f('--api-key'),
@@ -9,7 +9,8 @@ import { activeManagedScans, BOOTSTRAP_KEY, codexRefreshCommand, commandGenerati
9
9
  import { hasCredentialShape } from './headers.js';
10
10
  import { isManagedLayer } from './layer-policy.js';
11
11
  import { adapterEffective, statusSetups } from './status.js';
12
- import { applyUpdate, isSamePath, prepareUpdate, readExistingEnv } from './settings.js';
12
+ import { applyUpdate, isSamePath, prepareUpdate, readExistingEnv, removeSettingsFile, } from './settings.js';
13
+ import { planSetupRemoval } from './setup-removal.js';
13
14
  import { say } from './ui.js';
14
15
  import { VERSION } from './version.js';
15
16
  const hasAnyChange = (diff) => diff.added.length > 0 || diff.changed.length > 0 || diff.removed.length > 0;
@@ -171,9 +172,14 @@ export const planAdapter = async (adapter, answers, context = {}) => {
171
172
  codec: aw.codec,
172
173
  mode: aw.mode,
173
174
  })));
174
- const replaced = (await Promise.all((adapter.replaces ?? []).map((r) => planReplaced(r)))).flat();
175
+ const replaced = (await Promise.all((adapter.replaces ?? []).map((r) => planSetupRemoval(r)))).flat();
175
176
  const labeled = [
176
- ...replaced.map(({ update }) => ({ label: update.path, update })),
177
+ ...replaced.map(({ update, remove, linkTarget }) => ({
178
+ label: update.path,
179
+ update,
180
+ ...(remove ? { remove } : {}),
181
+ ...(linkTarget !== undefined ? { linkTarget } : {}),
182
+ })),
177
183
  { label: primary, update: primaryUpdate },
178
184
  ...(separateMarkersUpdate
179
185
  ? [{ label: separateMarkersUpdate.path, update: separateMarkersUpdate }]
@@ -209,31 +215,6 @@ export const planAdapter = async (adapter, answers, context = {}) => {
209
215
  ...(keptPin ? { keptPin: pin } : {}),
210
216
  };
211
217
  };
212
- const planReplaced = async (replaced) => {
213
- const path = replaced.paths.global;
214
- const env = await readExistingEnv(path, replaced.codec);
215
- const owns = env !== null && (replaced.holdsOwnSetup?.(env) ?? true);
216
- const config = await prepareUpdate({
217
- path,
218
- newEnv: {},
219
- managedKeys: owns ? [...replaced.managedEnvKeys, ...(replaced.retiredEnvKeys ?? [])] : [],
220
- codec: replaced.codec,
221
- });
222
- const hooksFile = replaced.markers?.hooksFile;
223
- if (hooksFile === undefined)
224
- return [{ update: config, markersPlan: null }];
225
- if (isSamePath(hooksFile.path, path)) {
226
- const markersPlan = config.exists ? planMarkers(config.next, []) : null;
227
- if (markersPlan !== null)
228
- config.next = markersPlan.next;
229
- return [{ update: config, markersPlan }];
230
- }
231
- const hooks = await prepareMarkersFile(hooksFile.path, hooksFile.codec, []);
232
- return [
233
- { update: config, markersPlan: null },
234
- { update: hooks.update, markersPlan: hooks.plan },
235
- ];
236
- };
237
218
  export const hookShellMissingFor = async (adapter, settingsEnv) => {
238
219
  if (process.platform !== 'win32')
239
220
  return false;
@@ -279,7 +260,7 @@ export const renderPlan = (plan) => {
279
260
  say(color.dim(`${plan.adapter.displayName}: no changes needed in ${plan.primaryPath}.`));
280
261
  return;
281
262
  }
282
- for (const { label, update } of plan.changed) {
263
+ for (const { label, update, remove, linkTarget } of plan.changed) {
283
264
  say('');
284
265
  say(color.bold(`Changes to ${label}:`));
285
266
  const body = renderDiff(update.diff);
@@ -298,6 +279,20 @@ export const renderPlan = (plan) => {
298
279
  say(painted);
299
280
  }
300
281
  }
282
+ if (remove) {
283
+ say(color.dim(' Nothing else is in it, so setup removes the file and keeps a backup beside it.'));
284
+ }
285
+ if (linkTarget !== undefined) {
286
+ say(color.dim(` Nothing else is in it, but it links to ${linkTarget}, so setup keeps the link ` +
287
+ 'and leaves that file empty ({}), which Codex reads as no hooks. It keeps a backup ' +
288
+ 'beside the link.'));
289
+ }
290
+ const moved = markersPlan?.movedForeign ?? 0;
291
+ if (plan.hookHost === 'codex' && moved > 0) {
292
+ say(color.yellow(` Removing Mainwave's hooks from ${update.path} moves ${moved} of your other ` +
293
+ 'hooks there to a new position, so Codex will ask you to trust them again ("Hooks need review", ' +
294
+ 'or /hooks) the next time it starts.'));
295
+ }
301
296
  }
302
297
  };
303
298
  export const planHasChanges = (plans) => plans.some((p) => p.changed.length > 0);
@@ -327,10 +322,12 @@ export const writePlan = async (plan, dirs = defaultHookDirs(), holdFlat = false
327
322
  say(color.dim(`Hook scripts refreshed in ${dest}.`));
328
323
  }
329
324
  const done = [];
330
- for (const { update } of plan.changed) {
325
+ for (const { update, remove } of plan.changed) {
331
326
  let result;
332
327
  try {
333
- result = await applyUpdate(update);
328
+ result = remove
329
+ ? { backupPath: await removeSettingsFile(update.path), written: update.path }
330
+ : await applyUpdate(update);
334
331
  }
335
332
  catch (err) {
336
333
  if (done.length > 0)
@@ -339,13 +336,13 @@ export const writePlan = async (plan, dirs = defaultHookDirs(), holdFlat = false
339
336
  }
340
337
  done.push({ update, result });
341
338
  say('');
342
- say(color.green(`✓ Wrote ${result.written}`));
339
+ say(color.green(`✓ ${remove ? 'Removed' : 'Wrote'} ${result.written}`));
343
340
  if (result.backupPath) {
344
341
  say(color.dim(` backup: ${result.backupPath}`));
345
342
  }
346
343
  }
347
344
  };
348
- const setupCommand = (adapter) => ['mainwave-cli setup', adapter.name, ...(adapter.setupArgs ?? [])].join(' ');
345
+ export const setupCommand = (adapter) => ['mainwave-cli setup', adapter.name, ...(adapter.setupArgs ?? [])].join(' ');
349
346
  const partialWriteNote = (adapter, done) => {
350
347
  const lines = [
351
348
  '',
@@ -425,12 +422,14 @@ export const printMarkerCoexistenceNotes = async (adapter, targetPath, markersOn
425
422
  }
426
423
  }
427
424
  };
428
- const codexTrustNote = (reading, hooksPath, run = 'codex') => {
425
+ const codexTrustNote = (reading, hooksPath, profile) => {
426
+ const run = profile === undefined ? 'codex' : `codex --profile ${profile}`;
427
+ const exec = profile === undefined ? 'codex exec' : `codex exec --profile ${profile}`;
429
428
  const how = `Start \`${run}\` and choose "Trust all" at the "Hooks need review" prompt, or open /hooks and trust each ` +
430
429
  'Mainwave hook, the session-start hook included. Codex asks again whenever a Mainwave hook changes, such as ' +
431
430
  'when a setup run adds a route or a release changes a command, so approve again after such a run; a run that ' +
432
431
  "removes a Mainwave hook moves the hooks after it, so Codex may ask about other tools' hooks too. " +
433
- '`codex exec` skips them unless it runs with --dangerously-bypass-hook-trust. ' +
432
+ `\`${exec}\` skips them unless it runs with --dangerously-bypass-hook-trust. ` +
434
433
  '`mainwave-cli doctor` reports the hooks Codex skips.';
435
434
  if (reading?.state === 'read') {
436
435
  const n = countTrust(reading.hooks);
@@ -476,7 +475,7 @@ export const printPostSetup = (plan) => {
476
475
  ? undefined
477
476
  : readCodexTrust(hooksFile.path, plan.adapter.trustFiles ?? [], hooksFile.path, hooksFile.codec);
478
477
  say('');
479
- say(color.dim(codexTrustNote(reading, hooksFile?.path, plan.adapter.runInstruction)));
478
+ say(color.dim(codexTrustNote(reading, hooksFile?.path, plan.adapter.codexProfile)));
480
479
  }
481
480
  const snippet = plan.adapter.printPostSetupInstructions?.(plan.input);
482
481
  if (snippet) {
@@ -190,13 +190,7 @@ const renderGroup = (event, group) => {
190
190
  return lines.join('\n');
191
191
  };
192
192
  const parse = (body, path) => {
193
- let split;
194
- try {
195
- split = splitHooks(body, path);
196
- }
197
- catch (err) {
198
- throw new Error(`failed to parse ${path} as TOML: ${err.message}`);
199
- }
193
+ const split = splitHooks(body, path);
200
194
  const root = tomlOtelCodec.parse(split.rest, path);
201
195
  if (Object.keys(split.hooks).length > 0)
202
196
  root.hooks = split.hooks;