@mainwave/cli 0.9.0 → 0.11.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.
@@ -40,7 +40,7 @@ export const collectBehaviourHookIssues = async (cap, currentVersion, scan = sca
40
40
  if (s.status === 'error') {
41
41
  issues.push({
42
42
  level: 'warn',
43
- message: `Cursor hooks file could not be parsed: ${s.path} — ${s.error ?? 'invalid JSON'}.`,
43
+ message: `${cap.toolName} hooks file could not be parsed: ${s.path} — ${s.error ?? 'invalid JSON'}.`,
44
44
  });
45
45
  }
46
46
  }
@@ -48,7 +48,7 @@ export const collectBehaviourHookIssues = async (cap, currentVersion, scan = sca
48
48
  if (present.length === 0) {
49
49
  issues.push({
50
50
  level: 'info',
51
- message: 'Cursor behaviour hook is not registered in any hooks.json layer — re-run `mainwave-cli setup cursor` to enable it.',
51
+ message: `${cap.toolName} behaviour hook is not registered in any hooks file layer — re-run \`${cap.setupCommand}\` to enable it.`,
52
52
  });
53
53
  return issues;
54
54
  }
@@ -58,8 +58,8 @@ export const collectBehaviourHookIssues = async (cap, currentVersion, scan = sca
58
58
  if (version !== undefined && version !== currentVersion) {
59
59
  issues.push({
60
60
  level: 'warn',
61
- message: `Cursor hook in ${s.path} was written by @mainwave/cli@${version}; you are running ${currentVersion}. ` +
62
- 'Re-run `mainwave-cli setup cursor` to refresh it — a stale registration can silently stop emitting.',
61
+ message: `${cap.toolName} hook in ${s.path} was written by @mainwave/cli@${version}; you are running ${currentVersion}. ` +
62
+ `Re-run \`${cap.setupCommand}\` to refresh it — a stale registration can silently stop emitting.`,
63
63
  });
64
64
  }
65
65
  const script = scriptPathFromCommand(command);
@@ -70,13 +70,13 @@ export const collectBehaviourHookIssues = async (cap, currentVersion, scan = sca
70
70
  catch {
71
71
  issues.push({
72
72
  level: 'error',
73
- message: `Cursor hook script is missing: ${script} — the hook no-ops silently (fail-open). Re-run \`mainwave-cli setup cursor\`.`,
73
+ message: `${cap.toolName} hook script is missing: ${script} — the hook no-ops silently (fail-open). Re-run \`${cap.setupCommand}\`.`,
74
74
  });
75
75
  }
76
76
  if (basename(script) !== cap.script) {
77
77
  issues.push({
78
78
  level: 'warn',
79
- message: `Cursor hook in ${s.path} points at ${basename(script)}, not the expected ${cap.script}. ` +
79
+ message: `${cap.toolName} hook in ${s.path} points at ${basename(script)}, not the expected ${cap.script}. ` +
80
80
  'Re-run setup to refresh the registration.',
81
81
  });
82
82
  }
@@ -85,7 +85,7 @@ export const collectBehaviourHookIssues = async (cap, currentVersion, scan = sca
85
85
  if (s.layerId === 'managed') {
86
86
  issues.push({
87
87
  level: 'info',
88
- message: `Cursor behaviour hook is pinned by managed/enterprise settings (${s.path}) — it applies to every user on this machine and can't be changed without admin access.`,
88
+ message: `${cap.toolName} behaviour hook is pinned by managed/enterprise settings (${s.path}) — it applies to every user on this machine and can't be changed without admin access.`,
89
89
  });
90
90
  }
91
91
  }
@@ -0,0 +1,76 @@
1
+ import { commandOwnership } from '../markers.js';
2
+ export const KIRO_HOOK_TIMEOUT_SECONDS = 10;
3
+ export const kiroHookName = (trigger) => `Mainwave: ${trigger}`;
4
+ const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
5
+ const isCommandEntry = (v) => isPlainObject(v) &&
6
+ typeof v.trigger === 'string' &&
7
+ isPlainObject(v.action) &&
8
+ typeof v.action.command === 'string';
9
+ const isOwned = (v) => isCommandEntry(v) && commandOwnership(v.action.command) !== null;
10
+ const triggerOfKey = (key) => key.startsWith('hooks.') ? key.slice('hooks.'.length) : undefined;
11
+ const parse = (body, path) => {
12
+ let parsed;
13
+ try {
14
+ parsed = JSON.parse(body);
15
+ }
16
+ catch (err) {
17
+ throw new Error(`failed to parse ${path} as JSON: ${err.message}`);
18
+ }
19
+ if (!isPlainObject(parsed)) {
20
+ throw new Error(`${path}: expected a JSON object at the top level`);
21
+ }
22
+ return parsed;
23
+ };
24
+ const serialize = (doc) => {
25
+ if (!isPlainObject(doc))
26
+ throw new Error('expected a Kiro hooks document');
27
+ return JSON.stringify(doc, null, 2) + '\n';
28
+ };
29
+ const empty = () => ({ version: 'v1', hooks: [] });
30
+ const hooksOf = (doc) => {
31
+ if (doc.hooks === undefined)
32
+ return [];
33
+ if (!Array.isArray(doc.hooks))
34
+ throw new Error('Kiro hooks file: `hooks` is not an array');
35
+ return doc.hooks;
36
+ };
37
+ const readEnv = (doc) => {
38
+ if (!isPlainObject(doc))
39
+ throw new Error('expected a Kiro hooks document');
40
+ const out = {};
41
+ for (const entry of hooksOf(doc)) {
42
+ if (isOwned(entry) && !(`hooks.${entry.trigger}` in out)) {
43
+ out[`hooks.${entry.trigger}`] = entry.action.command;
44
+ }
45
+ }
46
+ return out;
47
+ };
48
+ const applyEnv = (doc, newEnv, _managedKeys) => {
49
+ const base = isPlainObject(doc) ? structuredClone(doc) : {};
50
+ base.version = typeof base.version === 'string' ? base.version : 'v1';
51
+ const kept = hooksOf(base).filter((e) => !isOwned(e));
52
+ const ours = Object.entries(newEnv).flatMap(([key, command]) => {
53
+ const trigger = triggerOfKey(key);
54
+ return trigger === undefined
55
+ ? []
56
+ : [
57
+ {
58
+ name: kiroHookName(trigger),
59
+ trigger,
60
+ action: { type: 'command', command },
61
+ timeout: KIRO_HOOK_TIMEOUT_SECONDS,
62
+ enabled: true,
63
+ },
64
+ ];
65
+ });
66
+ base.hooks = [...kept, ...ours];
67
+ return base;
68
+ };
69
+ export const kiroHooksJsonCodec = {
70
+ format: 'json',
71
+ parse,
72
+ serialize,
73
+ empty,
74
+ readEnv,
75
+ applyEnv,
76
+ };
@@ -72,7 +72,7 @@ const renderEffectiveEnv = (effective, adapter) => {
72
72
  };
73
73
  const collectEnvFileTargets = (adapter) => {
74
74
  const targets = [];
75
- if (adapter.codec.format === 'env') {
75
+ if (adapter.codec.format === 'env' && !adapter.hookReadsConfigFile) {
76
76
  targets.push({
77
77
  label: 'Primary',
78
78
  path: adapter.paths.global,
@@ -4,7 +4,13 @@ export const HOOK_NODE_ENTRY_SCRIPT = 'mainwave-hook-node.mjs';
4
4
  export const ORG_DELIVERED_MARK = 'org-delivered';
5
5
  export const HOOK_ENTRY_MARK = 'mainwave hook entry v2';
6
6
  export const ENTRY_HOSTS = ['claude-code', 'codex'];
7
- export const CODEX_BASH_FILTER = ['*pr*create*', '*mr*create*', '*mr*new*', '*merge_requests*'];
7
+ export const CODEX_BASH_FILTER = [
8
+ '*pr*create*',
9
+ '*mr*create*',
10
+ '*mr*new*',
11
+ '*merge_requests*',
12
+ '*git*commit*',
13
+ ];
8
14
  export const entryRouteKey = ({ host, event, route }) => `${host}/${event}/${route ?? ''}`;
9
15
  const SAFE_TOKEN = /^[A-Za-z0-9._+-]+$/;
10
16
  const shQuote = (value) => `'${value.replace(/'/g, `'\\''`)}'`;
@@ -3,10 +3,11 @@ import { claudeConfigDir } from '../adapters/claude-code.js';
3
3
  import { hasPath } from './detect.js';
4
4
  import { activeHierarchy } from './effective-settings.js';
5
5
  import { isManagedLayer } from './layer-policy.js';
6
- import { bootstrapGroup, buildHookGroups, DEFAULT_MARKER_TOOL, groupEvent, isBootstrapCommand, isDelivered, managedDeliversEntry, managedHooksDir, managedMarkerDeliveries, matchersForTool, packagedHooksDir, prepareMarkersFile, readPackagedMatchers, scanForMarkers, syncManagedHooks, syncOrgDelivered, userHookGroups, } from './markers.js';
6
+ import { bootstrapGroup, buildHookGroups, DEFAULT_MARKER_TOOL, groupEvent, isBootstrapCommand, isDelivered, managedDeliversEntry, managedHooksDir, managedMarkerDeliveries, matchersForTool, packagedHooksDir, prepareMarkersFile, readPackagedMatchers, routeKeyOf, scanForMarkers, syncManagedHooks, syncOrgDelivered, userHookGroups, } from './markers.js';
7
7
  import { applyUpdate } from './settings.js';
8
8
  import { readSettings } from './store.js';
9
9
  import { VERSION } from './version.js';
10
+ export const ROUTES_BEFORE_RECORD_EXCLUDES = ['PostToolUse:git'];
10
11
  export const PAYLOAD_EVENTS = [
11
12
  'SessionStart',
12
13
  'UserPromptSubmit',
@@ -43,12 +44,20 @@ export const installHooks = async (adapter, paths = defaultPaths()) => {
43
44
  const stored = paths.stored ?? (await readSettings().catch(() => ({}))).hooks ?? {};
44
45
  const userSettings = adapter.paths.global;
45
46
  const disclosed = stored.events?.[adapter.name]?.[userSettings];
47
+ const disclosedRoutes = stored.routes?.[adapter.name]?.[userSettings];
46
48
  let removedFromUser = 0;
47
49
  let addedToUser = 0;
48
50
  if ((managedDelivers || disclosed !== undefined) && hasPath(userSettings)) {
49
51
  const groups = disclosed === undefined
50
52
  ? []
51
- : userHookGroups(matchersForTool(all, DEFAULT_MARKER_TOOL), { markers: stored.markers?.[adapter.name] ?? true }, delivered, DEFAULT_MARKER_TOOL).filter((g) => disclosed.includes(groupEvent(g)));
53
+ : userHookGroups(matchersForTool(all, DEFAULT_MARKER_TOOL), { markers: stored.markers?.[adapter.name] ?? true }, delivered, DEFAULT_MARKER_TOOL).filter((g) => disclosed.includes(groupEvent(g)) &&
54
+ g.hooks.every((h) => {
55
+ const key = routeKeyOf(h.command);
56
+ return (key === undefined ||
57
+ (disclosedRoutes === undefined
58
+ ? !ROUTES_BEFORE_RECORD_EXCLUDES.includes(key)
59
+ : disclosedRoutes.includes(key)));
60
+ }));
52
61
  const { update, plan } = await prepareMarkersFile(userSettings, adapter.codec, groups, 0o600, (ownership, group) => ownership === 'cli' &&
53
62
  ((!isBootstrapCommand(group.command) &&
54
63
  isDelivered(delivered, group.event, group.command)) ||
@@ -1,4 +1,4 @@
1
- import { managedSnapshotDelivery, planSnapshotBlocked } from './apply.js';
1
+ import { effectiveOptIns, managedSnapshotDelivery, planSnapshotBlocked } from './apply.js';
2
2
  import { WizardAbort } from './errors.js';
3
3
  import { color } from './format.js';
4
4
  import { nativeIdentityReason } from './effective-settings.js';
@@ -47,17 +47,50 @@ const resolveCollectorUrl = async (input) => {
47
47
  return fallback;
48
48
  return promptCollectorUrl(fallback);
49
49
  };
50
- const resolveIdentity = async (input, identityAdapters) => {
51
- if (input.overrides.userEmail)
52
- return input.overrides.userEmail;
50
+ const resolveIdentity = async (input, identityAdapters, toolEmail) => {
51
+ if (input.overrides.userEmail) {
52
+ return {
53
+ email: input.overrides.userEmail,
54
+ source: input.overrides.userEmailFromInvite ? 'invite' : 'flag',
55
+ };
56
+ }
53
57
  if (identityAdapters.length === 0)
54
- return undefined;
58
+ return {};
55
59
  if (input.session)
56
- return input.session.email;
57
- const fallback = input.prefill.userEmail ?? input.settings.email ?? detectGitEmail();
60
+ return { email: input.session.email, source: 'session' };
61
+ const onDisk = input.prefill.userEmail ?? input.settings.email;
62
+ const fallback = onDisk ?? detectGitEmail();
63
+ const source = onDisk !== undefined ? 'prefill' : fallback !== undefined ? 'git' : undefined;
64
+ if (toolEmail !== undefined && identityAdapters.every((a) => a.detectIdentityEmail)) {
65
+ return { email: fallback, source };
66
+ }
58
67
  if (!input.interactive)
59
- return fallback;
60
- return promptUserEmail(fallback);
68
+ return { email: fallback, source };
69
+ const typed = await promptUserEmail(fallback);
70
+ return { email: typed, source: typed === fallback ? source : 'prompt' };
71
+ };
72
+ const resolveAdapterEmails = async (input, identityAdapters, general, toolEmail) => {
73
+ const tools = identityAdapters.filter((a) => a.detectIdentityEmail);
74
+ if (tools.length === 0 || general.source === 'flag' || toolEmail === undefined)
75
+ return {};
76
+ let chosen = toolEmail;
77
+ const given = general.source === 'session' || general.source === 'invite' || general.source === 'prompt'
78
+ ? general.email
79
+ : undefined;
80
+ const sessionEmail = given;
81
+ if (sessionEmail !== undefined && sessionEmail.toLowerCase() !== toolEmail.toLowerCase()) {
82
+ const names = tools.map((a) => a.displayName).join(', ');
83
+ if (input.interactive) {
84
+ say(`${names} is signed in as ${toolEmail}; this run's email is ${sessionEmail}.`);
85
+ say(color.dim(` ${names} activity is matched to the tool's own usage export by this email, so it should be the tool's.`));
86
+ chosen = (await promptUserEmail(toolEmail)) ?? toolEmail;
87
+ }
88
+ else {
89
+ say(color.yellow(`${names}: stamping the tool's sign-in ${toolEmail}, not ${sessionEmail}, ` +
90
+ "so its activity matches the tool's own usage export. Pass --email to choose."));
91
+ }
92
+ }
93
+ return Object.fromEntries(tools.map((a) => [a.name, chosen]));
61
94
  };
62
95
  export const noIdentityWarning = (headerTools, nonOauth) => {
63
96
  const names = [
@@ -118,9 +151,16 @@ const resolveUseCaseStep = async (input) => {
118
151
  }, context);
119
152
  return useCase;
120
153
  };
121
- const sayCaptureNotice = (optIns, adapters) => {
154
+ const sayCaptureNotice = (optIns, adapters, explicit) => {
155
+ const withoutPrompts = adapters.filter((a) => !effectiveOptIns(a, optIns, explicit).userPrompts);
156
+ const promptsAnywhere = withoutPrompts.length < adapters.length && optIns.userPrompts;
122
157
  const on = [
123
- optIns.userPrompts ? 'prompt text' : undefined,
158
+ promptsAnywhere
159
+ ? withoutPrompts.length > 0
160
+ ? `prompt text (not for ${withoutPrompts.map((a) => a.displayName).join(', ')}, which ` +
161
+ 'keep it off unless `--opt-in prompts` is given)'
162
+ : 'prompt text'
163
+ : undefined,
124
164
  optIns.userPrompts && adapters.some((a) => a.name === 'claude-desktop')
125
165
  ? 'assistant responses'
126
166
  : undefined,
@@ -156,17 +196,22 @@ export const runInterview = async (input) => {
156
196
  const collectorUrl = await resolveCollectorUrl(input);
157
197
  const useCase = await resolveUseCaseStep(input);
158
198
  const identityAdapters = input.adapters.filter((a) => a.injectsIdentity || a.stampsIdentityAttr);
159
- const userEmail = await resolveIdentity(input, identityAdapters);
199
+ const toolEmail = input.overrides.userEmail && !input.overrides.userEmailFromInvite
200
+ ? undefined
201
+ : identityAdapters.map((a) => a.detectIdentityEmail?.()).find((e) => e !== undefined);
202
+ const general = await resolveIdentity(input, identityAdapters, toolEmail);
203
+ const userEmail = general.email;
204
+ const adapterEmails = await resolveAdapterEmails(input, identityAdapters, general, toolEmail);
160
205
  if (!userEmail) {
161
206
  const nonOauth = (await Promise.all(identityAdapters
162
207
  .filter((a) => a.stampsIdentityAttr)
163
208
  .map(async (adapter) => ({ adapter, reason: await nativeIdentityReason(adapter) })))).filter((x) => x.reason !== undefined);
164
- const warning = noIdentityWarning(identityAdapters.filter((a) => a.injectsIdentity), nonOauth);
209
+ const warning = noIdentityWarning(identityAdapters.filter((a) => a.injectsIdentity && adapterEmails[a.name] === undefined), nonOauth);
165
210
  if (warning)
166
211
  say(color.yellow(warning));
167
212
  }
168
213
  const optIns = resolveOptIns(input);
169
- sayCaptureNotice(optIns, input.adapters);
214
+ sayCaptureNotice(optIns, input.adapters, input.overrides.optIns !== undefined);
170
215
  const capable = input.adapters.filter((a) => a.markers);
171
216
  const markers = resolveMarkers(input, capable);
172
217
  const blocked = new Map(markers
@@ -190,6 +235,9 @@ export const runInterview = async (input) => {
190
235
  ucid: useCase?.id,
191
236
  optIns,
192
237
  userEmail,
238
+ userEmailSource: general.source,
239
+ adapterEmails,
240
+ optInsExplicit: input.overrides.optIns !== undefined,
193
241
  markers,
194
242
  },
195
243
  useCase,
@@ -643,6 +643,7 @@ export const markerLogFiles = (home = homedir()) => [
643
643
  logFile(home, 'Jira tickets', 'jira-ticket-marker.log', '.mainwave-jira-ticket-marker.log'),
644
644
  logFile(home, 'PRs', 'pr-marker.log', '.mainwave-pr-marker.log'),
645
645
  logFile(home, 'GitLab MRs', 'glab-mr-marker.log', '.mainwave-glab-mr-marker.log'),
646
+ logFile(home, 'Git commits', 'git-commit-marker.log', '.mainwave-git-commit-marker.log'),
646
647
  {
647
648
  ...logFile(home, 'Claude plan snapshots', 'plan-snapshot.log', '.mainwave-plan-snapshot.log.ok'),
648
649
  activityPath: join(hookLogDir(home), 'plan-snapshot.log.ok'),
@@ -791,7 +792,8 @@ export const routeLabel = (key) => {
791
792
  UserPromptSubmit: 'the Claude plan snapshot',
792
793
  'PostToolUse:gh': 'the GitHub PR marker',
793
794
  'PostToolUse:glab': 'the GitLab MR marker',
794
- 'PostToolUse:bash': 'the PR and MR markers',
795
+ 'PostToolUse:git': 'the git commit marker',
796
+ 'PostToolUse:bash': 'the PR, MR and commit markers',
795
797
  'PostToolUse:linear': 'the Linear ticket marker',
796
798
  'PostToolUse:jira': 'the Jira ticket marker',
797
799
  StopFailure: 'the Claude turn-error span',
@@ -1139,8 +1141,8 @@ export const entryIssues = async (managedDir, matchers, managed, nodeEntry = fal
1139
1141
  if (missing.length > 0) {
1140
1142
  return [
1141
1143
  {
1142
- level: 'error',
1143
- message: `Release ${id} of the Mainwave hooks lacks ${missing.join(', ')}, so the hooks that need ${missing.length === 1 ? 'it' : 'them'} send nothing. ${fix}`,
1144
+ level: 'warn',
1145
+ message: `Release ${id} of the Mainwave hooks lacks ${missing.join(', ')}, so the hooks that need ${missing.length === 1 ? 'it' : 'them'} send nothing until a newer release is installed. ${fix}`,
1144
1146
  },
1145
1147
  ];
1146
1148
  }
@@ -1,5 +1,5 @@
1
1
  import { homedir, platform as osPlatform } from 'node:os';
2
- import { basename, isAbsolute, join } from 'node:path';
2
+ import { basename, join } from 'node:path';
3
3
  import { color } from './format.js';
4
4
  const detectShellKind = () => {
5
5
  const shellEnv = process.env.SHELL;
@@ -41,31 +41,14 @@ const profile = (kind) => {
41
41
  return { kind, rcFile: '~/.profile', oneShot: posixOneShot, rcLine: posixRcLine };
42
42
  };
43
43
  const indent = (line) => ` ${line}`;
44
- export const renderEnvFileBlock = (envFile, scope) => {
44
+ export const renderEnvFileBlock = (envFile) => {
45
45
  const sh = profile(detectShellKind());
46
46
  const shellLabel = sh.kind === 'unknown' ? 'your shell' : sh.kind;
47
- if (scope === 'global') {
48
- return [
49
- color.bold(`Persist for every ${shellLabel} session — add to ${sh.rcFile}:`),
50
- '',
51
- indent(color.cyan(sh.rcLine(envFile))),
52
- '',
53
- color.dim(` (or one-shot for the current terminal: ${color.reset(sh.oneShot(envFile))})`),
54
- ].join('\n');
55
- }
56
- const absoluteEnvFile = isAbsolute(envFile) ? envFile : join(process.cwd(), envFile);
57
47
  return [
58
- color.bold('Per-project setup — two options below. Pick the one(s) you want:'),
59
- '',
60
- color.bold('1. Current terminal (one-shot):'),
61
- indent(color.cyan(sh.oneShot(envFile))),
48
+ color.bold(`Persist for every ${shellLabel} session — add to ${sh.rcFile}:`),
62
49
  '',
63
- color.bold(`2. GUI launches (Spotlight/Dock) — add to ${sh.rcFile}:`),
64
- indent(color.cyan(sh.rcLine(absoluteEnvFile))),
65
- color.dim(' The rc line points at this project by absolute path, so VS Code picks'),
66
- color.dim(' it up on GUI launch. Comment out / swap the line when changing projects.'),
50
+ indent(color.cyan(sh.rcLine(envFile))),
67
51
  '',
68
- color.dim(`Or, to auto-load per directory, install direnv and add to ./.envrc:`),
69
- indent(color.cyan(`source_env ${envFile}`)),
52
+ color.dim(` (or one-shot for the current terminal: ${color.reset(sh.oneShot(envFile))})`),
70
53
  ].join('\n');
71
54
  };
@@ -0,0 +1,67 @@
1
+ import { WizardAbort } from './errors.js';
2
+ import { color } from './format.js';
3
+ import { promptConfirmWrite } from './prompts.js';
4
+ import { applyUpdate, removeSettingsFile } from './settings.js';
5
+ import { isInteractive } from './tty.js';
6
+ import { emitJson, say, setJsonMode } from './ui.js';
7
+ export const runRemove = async (adapters, options = {}) => {
8
+ setJsonMode(options.json === true);
9
+ const unsupported = adapters.filter((a) => !a.removal);
10
+ if (unsupported.length > 0) {
11
+ throw new WizardAbort(`--remove isn't available for ${unsupported.map((a) => a.name).join(', ')}`);
12
+ }
13
+ say(color.bold(`mainwave-cli — remove ${adapters.map((a) => a.displayName).join(', ')}`));
14
+ const groups = new Map();
15
+ for (const a of adapters)
16
+ groups.set(a.removal.group, [...(groups.get(a.removal.group) ?? []), a]);
17
+ const steps = [];
18
+ for (const members of groups.values()) {
19
+ steps.push(...(await members[0].removal.plan(members.map((a) => a.name))));
20
+ }
21
+ const notes = steps.filter((s) => s.kind === 'note');
22
+ const actions = steps.filter((s) => s.kind !== 'note');
23
+ for (const n of notes)
24
+ say(color.dim(n.note));
25
+ if (actions.length === 0) {
26
+ if (notes.length === 0) {
27
+ say(color.dim('Nothing to remove: no Mainwave config for these tools is on disk.'));
28
+ }
29
+ if (options.json)
30
+ emitJson({ status: 'nothing-to-remove', tools: adapters.map((a) => a.name) });
31
+ return 0;
32
+ }
33
+ say('');
34
+ for (const step of actions)
35
+ say(` ${step.kind === 'delete' ? '-' : '~'} ${step.note}`);
36
+ if (!options.yes) {
37
+ if (!isInteractive())
38
+ throw new WizardAbort('refusing to remove without confirmation — pass --yes');
39
+ say('');
40
+ if (!(await promptConfirmWrite()))
41
+ throw new WizardAbort();
42
+ }
43
+ const done = [];
44
+ for (const step of actions) {
45
+ if (step.kind === 'update') {
46
+ const result = await applyUpdate(step.update);
47
+ done.push({ path: result.written, action: 'updated', backup: result.backupPath });
48
+ }
49
+ else {
50
+ done.push({
51
+ path: step.path,
52
+ action: 'deleted',
53
+ backup: await removeSettingsFile(step.path, { backup: step.backup !== false }),
54
+ });
55
+ }
56
+ }
57
+ say('');
58
+ for (const d of done) {
59
+ say(color.green(`✓ ${d.action === 'deleted' ? 'Removed' : 'Updated'} ${d.path}`));
60
+ if (d.backup)
61
+ say(color.dim(` backup: ${d.backup}`));
62
+ }
63
+ say(color.dim('Restart open sessions of these tools so they stop loading the hooks.'));
64
+ if (options.json)
65
+ emitJson({ status: 'removed', tools: adapters.map((a) => a.name), files: done });
66
+ return 0;
67
+ };
@@ -81,8 +81,23 @@ export const prepareUpdate = async (args) => {
81
81
  const diff = diffEnv(baseEnv, newEnv, managedKeys);
82
82
  return { path, exists, codec, next, diff, mode };
83
83
  };
84
+ export const removeSettingsFile = async (path, { backup = true } = {}) => {
85
+ let body;
86
+ try {
87
+ body = await fs.readFile(path);
88
+ }
89
+ catch (err) {
90
+ if (isErrnoCode(err, 'ENOENT'))
91
+ return null;
92
+ throw err;
93
+ }
94
+ const mode = (await fs.stat(path)).mode & 0o777;
95
+ const backupPath = backup ? await writeBackup(path, body, mode) : null;
96
+ await fs.rm(path, { force: true });
97
+ return backupPath;
98
+ };
84
99
  export const applyUpdate = async (update) => {
85
- const { path, exists, next, codec, mode } = update;
100
+ const { path, exists, next, codec, mode, backup = true } = update;
86
101
  const fileMode = mode ?? 0o600;
87
102
  await fs.mkdir(dirname(path), { recursive: true });
88
103
  const target = exists ? await fs.realpath(path).catch(() => path) : path;
@@ -91,7 +106,7 @@ export const applyUpdate = async (update) => {
91
106
  let backupPath = null;
92
107
  try {
93
108
  await fs.access(dirname(target), fsConstants.W_OK);
94
- if (exists)
109
+ if (exists && backup)
95
110
  backupPath = await writeBackup(path, await fs.readFile(path), fileMode);
96
111
  try {
97
112
  await fs.rename(tmpPath, target);
@@ -2,6 +2,7 @@ import { promises as fs } from 'node:fs';
2
2
  import { homedir } from 'node:os';
3
3
  import { dirname, join } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
+ import { isErrnoCode } from './settings.js';
5
6
  export const BLOCK_OPEN = '<!-- mainwave:skills managed-by @mainwave/cli';
6
7
  export const BLOCK_CLOSE = '<!-- /mainwave:skills -->';
7
8
  export const SKILL_NAMES = [
@@ -56,7 +57,7 @@ export const renderBlock = (version, skillsDir, names = SKILL_NAMES) => {
56
57
  ];
57
58
  return lines.join('\n');
58
59
  };
59
- const isBlockOpen = (line) => line.startsWith(BLOCK_OPEN);
60
+ export const isBlockOpen = (line) => line.startsWith(BLOCK_OPEN);
60
61
  export const installedBlockVersion = (body) => {
61
62
  for (const line of body.split('\n')) {
62
63
  if (!isBlockOpen(line))
@@ -86,8 +87,53 @@ export const applyBlock = (existing, block) => {
86
87
  const kept = stripBlocks(existing).replace(/\s+$/, '');
87
88
  return kept.length === 0 ? `${block}\n` : `${kept}\n\n${block}\n`;
88
89
  };
89
- export const installToSurface = async (adapterName, surface, scope, version, srcRoot = packagedSkillsDir(), installedRoot = installedSkillsDir(), names = SKILL_NAMES) => {
90
- const target = scope === 'local' ? surface.local : surface.global;
90
+ const textCodec = {
91
+ format: 'text',
92
+ parse: (body) => body,
93
+ serialize: (doc) => String(doc),
94
+ empty: () => '',
95
+ readEnv: () => ({}),
96
+ applyEnv: (doc) => doc,
97
+ };
98
+ export const planBlockRemoval = async (path) => {
99
+ let body;
100
+ try {
101
+ body = await fs.readFile(path, 'utf8');
102
+ }
103
+ catch (err) {
104
+ if (isErrnoCode(err, 'ENOENT'))
105
+ return undefined;
106
+ throw err;
107
+ }
108
+ if (!body.split('\n').some(isBlockOpen))
109
+ return undefined;
110
+ const kept = stripBlocks(body)
111
+ .replace(/^(?:[ \t]*\r?\n)+/, '')
112
+ .replace(/\s+$/, '');
113
+ if (kept.length === 0) {
114
+ return {
115
+ kind: 'delete',
116
+ path,
117
+ backup: false,
118
+ note: `${path}: delete (only Mainwave's instructions in it)`,
119
+ };
120
+ }
121
+ return {
122
+ kind: 'update',
123
+ update: {
124
+ path,
125
+ exists: true,
126
+ codec: textCodec,
127
+ next: `${kept}${body.includes('\r\n') ? '\r\n' : '\n'}`,
128
+ diff: { added: [], changed: [], removed: [], unchanged: 0 },
129
+ mode: (await fs.stat(path)).mode & 0o777,
130
+ backup: false,
131
+ },
132
+ note: `${path}: remove Mainwave's instructions, keep the rest`,
133
+ };
134
+ };
135
+ export const installToSurface = async (adapterName, surface, version, srcRoot = packagedSkillsDir(), installedRoot = installedSkillsDir(), names = SKILL_NAMES) => {
136
+ const target = surface.global;
91
137
  if (surface.kind === 'skill-dir') {
92
138
  for (const name of names)
93
139
  await copySkillBundle(name, srcRoot, target);
@@ -125,7 +171,7 @@ export const installSkillsPayload = async (adapters, version, srcRoot = packaged
125
171
  if (seen.has(surface.global))
126
172
  continue;
127
173
  seen.add(surface.global);
128
- installs.push(await installToSurface(adapter.name, surface, 'global', version, srcRoot, installedRoot, names));
174
+ installs.push(await installToSurface(adapter.name, surface, version, srcRoot, installedRoot, names));
129
175
  }
130
176
  return { installs, noOps, bundleDir: join(installedRoot) };
131
177
  };
@@ -2,6 +2,7 @@ import { promises as fs } from 'node:fs';
2
2
  import { homedir } from 'node:os';
3
3
  import { dirname, join } from 'node:path';
4
4
  import { isErrnoCode } from './settings.js';
5
+ import { trimSlash } from './url.js';
5
6
  export const mainwaveDir = () => join(homedir(), '.mainwave');
6
7
  export const settingsPath = () => join(mainwaveDir(), 'settings.json');
7
8
  export const credentialsPath = () => join(mainwaveDir(), 'credentials.json');
@@ -76,7 +77,6 @@ export const rememberKey = async (orgId, key) => {
76
77
  const credentials = await readCredentials();
77
78
  await writeCredentials({ ...credentials, keys: { ...credentials.keys, [orgId]: key } });
78
79
  };
79
- const trimSlash = (url) => url.replace(/\/+$/, '');
80
80
  export const resolveEndpoints = (settings, overrides = {}, env = process.env) => ({
81
81
  apiUrl: trimSlash(overrides.apiUrl ?? env.MAINWAVE_API_URL ?? settings.apiUrl ?? DEFAULTS.apiUrl),
82
82
  appUrl: trimSlash(overrides.appUrl ?? env.MAINWAVE_APP_URL ?? settings.appUrl ?? DEFAULTS.appUrl),
@@ -0,0 +1 @@
1
+ export const trimSlash = (url) => url.replace(/\/+$/, '');