@mainwave/cli 0.14.0 → 0.15.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.
@@ -117,6 +117,90 @@ const readText = (path) => {
117
117
  };
118
118
  const isRecord = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
119
119
  export const hookTrustKey = (sourceFile, event, group, handler) => `${sourceFile}:${eventLabel(event)}:${group}:${handler}`;
120
+ const mainwaveHooks = (hooks, keySource) => {
121
+ const out = [];
122
+ for (const [event, groups] of Object.entries(hooks)) {
123
+ if (!Array.isArray(groups))
124
+ continue;
125
+ for (const [gi, group] of groups.entries()) {
126
+ if (!isRecord(group) || !Array.isArray(group.hooks))
127
+ continue;
128
+ for (const [hi, handler] of group.hooks.entries()) {
129
+ if (!isRecord(handler) || typeof handler.command !== 'string')
130
+ continue;
131
+ if (commandOwnership(handler.command) !== 'cli')
132
+ continue;
133
+ const hash = codexHookHash(event, typeof group.matcher === 'string' ? group.matcher : undefined, {
134
+ type: 'command',
135
+ command: handler.command,
136
+ ...(typeof handler.timeout === 'number' ? { timeout: handler.timeout } : {}),
137
+ ...(handler.async === true ? { async: true } : {}),
138
+ ...(typeof handler.statusMessage === 'string'
139
+ ? { statusMessage: handler.statusMessage }
140
+ : {}),
141
+ });
142
+ out.push({ key: hookTrustKey(keySource, event, gi, hi), event, hash });
143
+ }
144
+ }
145
+ }
146
+ return out;
147
+ };
148
+ export const mainwaveHookKeys = (doc, keySource) => isRecord(doc) && isRecord(doc.hooks) ? mainwaveHooks(doc.hooks, keySource).map((h) => h.key) : [];
149
+ export const withoutHookStates = (toml, keys) => {
150
+ if (keys.size === 0)
151
+ return { text: toml, dropped: 0 };
152
+ const kept = [];
153
+ const dropped = new Set();
154
+ let path = [];
155
+ let skipping = false;
156
+ let pending = [];
157
+ for (const raw of toml.split('\n')) {
158
+ const line = raw.trim();
159
+ if (line.startsWith('[')) {
160
+ path = line.startsWith('[[') ? undefined : tablePath(line);
161
+ const skipNext = path?.length === 3 && keys.has(path[2]);
162
+ if (skipping && !skipNext) {
163
+ const lastBlank = kept.length === 0 || kept[kept.length - 1].trim() === '';
164
+ const first = lastBlank ? pending.findIndex((l) => l.trim() !== '') : 0;
165
+ if (first >= 0)
166
+ kept.push(...pending.slice(first));
167
+ }
168
+ pending = [];
169
+ skipping = skipNext;
170
+ if (skipping)
171
+ dropped.add(path[2]);
172
+ else
173
+ kept.push(raw);
174
+ continue;
175
+ }
176
+ if (skipping) {
177
+ if (line === '' || line.startsWith('#'))
178
+ pending.push(raw);
179
+ else
180
+ pending = [];
181
+ continue;
182
+ }
183
+ if (path !== undefined && path.length < 3 && line !== '' && !line.startsWith('#')) {
184
+ const lead = ['hooks', 'state'].slice(Math.min(path.length, 2));
185
+ const prefix = lead.map((part) => `${part}${DOT}`).join('');
186
+ const field = new RegExp(String.raw `^${prefix}${QUOTED_KEY}${DOT}(?:trusted_hash|enabled)\s*=`).exec(line);
187
+ if (field !== null && keys.has(quotedKey(field, 1))) {
188
+ dropped.add(quotedKey(field, 1));
189
+ continue;
190
+ }
191
+ }
192
+ kept.push(raw);
193
+ }
194
+ if (dropped.size === 0)
195
+ return { text: toml, dropped: 0 };
196
+ if (skipping) {
197
+ while (kept.length > 0 && kept[kept.length - 1].trim() === '')
198
+ kept.pop();
199
+ if (toml.endsWith('\n') && kept.length > 0)
200
+ kept.push('');
201
+ }
202
+ return { text: kept.join('\n'), dropped: dropped.size };
203
+ };
120
204
  const mergedStates = (trustFiles) => {
121
205
  const merged = new Map();
122
206
  for (const file of trustFiles) {
@@ -134,6 +218,12 @@ const mergedStates = (trustFiles) => {
134
218
  }
135
219
  return { states: merged };
136
220
  };
221
+ export const approvedHookKeys = (trustFiles) => {
222
+ const merged = mergedStates(trustFiles);
223
+ if ('unreadable' in merged)
224
+ return undefined;
225
+ return new Set([...merged.states].filter(([, s]) => s.trustedHash !== undefined).map(([key]) => key));
226
+ };
137
227
  export const readCodexTrust = (hooksPath, trustFiles, keySource = hooksPath, codec) => {
138
228
  const body = readText(hooksPath);
139
229
  let doc;
@@ -158,40 +248,17 @@ export const readCodexTrust = (hooksPath, trustFiles, keySource = hooksPath, cod
158
248
  };
159
249
  }
160
250
  const { states } = merged;
161
- const hooks = [];
162
- for (const [event, groups] of Object.entries(doc.hooks)) {
163
- if (!Array.isArray(groups))
164
- continue;
165
- for (const [gi, group] of groups.entries()) {
166
- if (!isRecord(group) || !Array.isArray(group.hooks))
167
- continue;
168
- for (const [hi, handler] of group.hooks.entries()) {
169
- if (!isRecord(handler) || typeof handler.command !== 'string')
170
- continue;
171
- if (commandOwnership(handler.command) !== 'cli')
172
- continue;
173
- const key = hookTrustKey(keySource, event, gi, hi);
174
- const state = states.get(key);
175
- const current = codexHookHash(event, typeof group.matcher === 'string' ? group.matcher : undefined, {
176
- type: 'command',
177
- command: handler.command,
178
- ...(typeof handler.timeout === 'number' ? { timeout: handler.timeout } : {}),
179
- ...(handler.async === true ? { async: true } : {}),
180
- ...(typeof handler.statusMessage === 'string'
181
- ? { statusMessage: handler.statusMessage }
182
- : {}),
183
- });
184
- const trust = state?.trustedHash === undefined
185
- ? 'untrusted'
186
- : state.trustedHash !== current
187
- ? 'modified'
188
- : state.enabled === false
189
- ? 'disabled'
190
- : 'trusted';
191
- hooks.push({ key, event, trust });
192
- }
193
- }
194
- }
251
+ const hooks = mainwaveHooks(doc.hooks, keySource).map(({ key, event, hash }) => {
252
+ const state = states.get(key);
253
+ const trust = state?.trustedHash === undefined
254
+ ? 'untrusted'
255
+ : state.trustedHash !== hash
256
+ ? 'modified'
257
+ : state.enabled === false
258
+ ? 'disabled'
259
+ : 'trusted';
260
+ return { key, event, trust };
261
+ });
195
262
  return hooks.length === 0 ? { state: 'no-hooks' } : { state: 'read', hooks };
196
263
  };
197
264
  export const countTrust = (hooks) => {
@@ -691,19 +691,22 @@ export const runDoctor = async (adapter, options = {}) => {
691
691
  return code;
692
692
  }
693
693
  let code = together;
694
+ const once = many.onceInText;
694
695
  for (const [i, { label, adapter: setup }] of many.setups.entries()) {
695
696
  if (i > 0)
696
697
  console.log();
697
- if ((await reportSetup(setup, options, `${adapter.displayName}, ${label}`)) !== 0)
698
+ const title = `${adapter.displayName}, ${label}`;
699
+ if ((await reportSetup(setup, options, title, once?.replaces)) !== 0)
698
700
  code = 1;
699
701
  }
700
- if (many.issues.length > 0) {
702
+ const togetherIssues = [...many.issues, ...(once?.issues ?? [])];
703
+ if (togetherIssues.length > 0) {
701
704
  console.log();
702
- renderChecks(many.issues, `${adapter.displayName} setups together:`);
705
+ renderChecks(togetherIssues, `${adapter.displayName} setups together:`);
703
706
  }
704
707
  return code;
705
708
  };
706
- const reportSetup = async (adapter, options, title = adapter.displayName) => {
709
+ const reportSetup = async (adapter, options, title = adapter.displayName, omit = () => false) => {
707
710
  console.log(color.bold(`mainwave-cli doctor — ${title}`));
708
711
  console.log();
709
712
  const effective = await computeEffective(adapter);
@@ -729,7 +732,7 @@ const reportSetup = async (adapter, options, title = adapter.displayName) => {
729
732
  const behaviourHookIssues = adapter.behaviourHooks
730
733
  ? await collectBehaviourHookIssues(adapter.behaviourHooks, VERSION)
731
734
  : [];
732
- renderChecks([...issues, ...shellEnvIssues, ...markerIssues, ...behaviourHookIssues]);
735
+ renderChecks([...issues, ...shellEnvIssues, ...markerIssues, ...behaviourHookIssues].filter((i) => !omit(i)));
733
736
  let validateFailed = false;
734
737
  if (options.validate) {
735
738
  console.log();
@@ -87,7 +87,9 @@ const installHooksNpx = (version, { quiet = true, redactionPacks = [], host = DE
87
87
  (redactionPacks.length > 0
88
88
  ? ` ${REDACTION_PACKS_FLAG} ${canonicalPacks(redactionPacks).join(',')}`
89
89
  : '');
90
- export const codexRefreshCommand = (args = []) => installHooksNpx(PAYLOAD_CLI_SPEC, { host: 'codex', args });
90
+ export const codexRefreshCommand = (args = []) => args.length === 0
91
+ ? `npx @mainwave/cli@${PAYLOAD_CLI_SPEC} install-hooks --host codex`
92
+ : installHooksNpx(PAYLOAD_CLI_SPEC, { host: 'codex', args });
91
93
  export const bootstrapCommand = (version, redactionPacks = []) => `{ ${installHooksCommand(version, { redactionPacks })}; } >/dev/null 2>&1; exit 0`;
92
94
  export const codexBootstrapCommand = (version, plat = process.platform, args = []) => plat === 'win32'
93
95
  ? `(cd /d "%USERPROFILE%" && ${installHooksNpx(version, { host: 'codex', args })}) >NUL 2>&1 & exit /b 0`
@@ -621,6 +623,7 @@ export const planMarkers = (doc, groups, remove = () => true) => {
621
623
  const identical = new Set();
622
624
  const placed = new Set();
623
625
  let pruned = false;
626
+ let movedForeign = 0;
624
627
  const removedInfo = [];
625
628
  for (const event of MARKER_HOOK_EVENTS) {
626
629
  if (skipped.has(event))
@@ -647,6 +650,9 @@ export const planMarkers = (doc, groups, remove = () => true) => {
647
650
  current.forEach((g, i) => {
648
651
  const info = owned[i];
649
652
  if (info === null || info === undefined || keep[i]) {
653
+ if (kept.length !== i && groupOwnership(g) === null && isPlainObject(g)) {
654
+ movedForeign += Array.isArray(g.hooks) ? g.hooks.length : 0;
655
+ }
650
656
  kept.push(g);
651
657
  return;
652
658
  }
@@ -686,6 +692,7 @@ export const planMarkers = (doc, groups, remove = () => true) => {
686
692
  added,
687
693
  unchanged,
688
694
  changed: removed.length > 0 || added.length > 0,
695
+ movedForeign,
689
696
  skipped: skippedEvents,
690
697
  };
691
698
  };
@@ -746,7 +753,7 @@ export const hookLogDir = (home = homedir()) => join(home, '.mainwave', 'logs');
746
753
  const logFile = (home, label, name, legacyName) => ({
747
754
  label,
748
755
  path: join(hookLogDir(home), name),
749
- legacyPath: join(home, legacyName),
756
+ ...(legacyName === undefined ? {} : { legacyPath: join(home, legacyName) }),
750
757
  });
751
758
  export const markerLogFiles = (home = homedir()) => [
752
759
  logFile(home, 'Linear tickets', 'ticket-marker.log', '.mainwave-ticket-marker.log'),
@@ -759,9 +766,13 @@ export const markerLogFiles = (home = homedir()) => [
759
766
  activityPath: join(hookLogDir(home), 'plan-snapshot.log.ok'),
760
767
  },
761
768
  logFile(home, 'Claude turn errors', 'claude-events.log', '.mainwave-claude-events.log'),
769
+ {
770
+ ...logFile(home, 'Codex turns', 'codex-turns.log'),
771
+ activityPath: join(hookLogDir(home), 'codex-turns.log.ok'),
772
+ },
762
773
  ];
763
774
  export const lastLogActivity = async (lf) => {
764
- const times = await Promise.all([lf.activityPath ?? lf.path, lf.legacyPath].map((p) => fs.stat(p).then((s) => s.mtime, () => undefined)));
775
+ const times = await Promise.all([lf.activityPath ?? lf.path, ...(lf.legacyPath === undefined ? [] : [lf.legacyPath])].map((p) => fs.stat(p).then((s) => s.mtime, () => undefined)));
765
776
  return times
766
777
  .filter((t) => t !== undefined)
767
778
  .sort((a, b) => b.getTime() - a.getTime())[0];
@@ -1260,8 +1271,11 @@ export const collectMarkerIssues = async (scans, currentVersion, matchers, skipp
1260
1271
  level: 'info',
1261
1272
  message: activity.length > 0
1262
1273
  ? `Mainwave hook activity — ${activity.join('; ')}.`
1263
- : 'Mainwave hooks are configured but no hook activity is recorded yet (~/.mainwave/logs/*-marker.log; for plan snapshots, ~/.mainwave/logs/plan-snapshot.log.ok). ' +
1264
- 'File a ticket or open a PR with `gh pr create`, then check the log and the use case activity.',
1274
+ : 'Mainwave hooks are configured but no hook activity is recorded yet (~/.mainwave/logs/*-marker.log; for plan snapshots, ~/.mainwave/logs/plan-snapshot.log.ok; for Codex turns, ~/.mainwave/logs/codex-turns.log.ok, with skip reasons in codex-turns.log). ' +
1275
+ (host === 'codex'
1276
+ ? 'Run a Codex session with a prompt'
1277
+ : 'File a ticket or open a PR with `gh pr create`') +
1278
+ ', then check the log and the use case activity.',
1265
1279
  });
1266
1280
  }
1267
1281
  return issues;
@@ -1,7 +1,9 @@
1
+ import { userHooksPath } from './apply.js';
1
2
  import { WizardAbort } from './errors.js';
2
3
  import { color } from './format.js';
3
4
  import { promptConfirmWrite } from './prompts.js';
4
5
  import { applyUpdate, removeSettingsFile } from './settings.js';
6
+ import { forgetHookFiles, settingsPath } from './store.js';
5
7
  import { isInteractive } from './tty.js';
6
8
  import { emitJson, say, setJsonMode } from './ui.js';
7
9
  export const runRemove = async (adapters, options = {}) => {
@@ -26,9 +28,15 @@ export const runRemove = async (adapters, options = {}) => {
26
28
  if (notes.length === 0) {
27
29
  say(color.dim('Nothing to remove: no Mainwave config for these tools is on disk.'));
28
30
  }
29
- if (options.json)
30
- emitJson({ status: 'nothing-to-remove', tools: adapters.map((a) => a.name) });
31
- return 0;
31
+ const problem = await forgetHookRecords(adapters);
32
+ if (options.json) {
33
+ emitJson({
34
+ status: 'nothing-to-remove',
35
+ tools: adapters.map((a) => a.name),
36
+ ...(problem === undefined ? {} : { error: problem }),
37
+ });
38
+ }
39
+ return problem === undefined ? 0 : 1;
32
40
  }
33
41
  say('');
34
42
  for (const step of actions)
@@ -44,24 +52,57 @@ export const runRemove = async (adapters, options = {}) => {
44
52
  for (const step of actions) {
45
53
  if (step.kind === 'update') {
46
54
  const result = await applyUpdate(step.update);
47
- done.push({ path: result.written, action: 'updated', backup: result.backupPath });
55
+ const backup = result.backupPath;
56
+ done.push({
57
+ path: result.written,
58
+ action: 'updated',
59
+ backup,
60
+ backupHoldsApiKey: backup !== null && step.holdsKey === true,
61
+ });
48
62
  }
49
63
  else {
64
+ const backup = await removeSettingsFile(step.path, { backup: step.backup !== false });
50
65
  done.push({
51
66
  path: step.path,
52
67
  action: 'deleted',
53
- backup: await removeSettingsFile(step.path, { backup: step.backup !== false }),
68
+ backup,
69
+ backupHoldsApiKey: backup !== null && step.holdsKey === true,
54
70
  });
55
71
  }
56
72
  }
57
73
  say('');
58
74
  for (const d of done) {
59
75
  say(color.green(`✓ ${d.action === 'deleted' ? 'Removed' : 'Updated'} ${d.path}`));
60
- if (d.backup)
61
- say(color.dim(` backup: ${d.backup}`));
76
+ if (d.backup) {
77
+ say(color.dim(` backup: ${d.backup}${d.backupHoldsApiKey ? ' (holds your API key)' : ''}`));
78
+ }
62
79
  }
63
80
  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;
81
+ const problem = await forgetHookRecords(adapters);
82
+ if (options.json) {
83
+ emitJson({
84
+ status: 'removed',
85
+ tools: adapters.map((a) => a.name),
86
+ files: done,
87
+ ...(problem === undefined ? {} : { error: problem }),
88
+ });
89
+ }
90
+ return problem === undefined ? 0 : 1;
91
+ };
92
+ const forgetHookRecords = async (adapters) => {
93
+ const files = adapters
94
+ .filter((a) => a.markers !== undefined)
95
+ .map((a) => ({ adapter: a.name, file: userHooksPath(a) }));
96
+ if (files.length === 0)
97
+ return undefined;
98
+ try {
99
+ await forgetHookFiles(files);
100
+ return undefined;
101
+ }
102
+ catch (err) {
103
+ const problem = `Couldn't drop setup's record of the removed hooks from ${settingsPath()}: ` +
104
+ `${err instanceof Error ? err.message : String(err)}. Run the same command again to retry.`;
105
+ say(color.yellow(problem));
106
+ return problem;
107
+ }
67
108
  };
@@ -0,0 +1,197 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import { tomlOtelCodec } from './codecs/toml-otel.js';
3
+ import { approvedHookKeys, hookTrustKey, mainwaveHookKeys, withoutHookStates, } from './codex-trust.js';
4
+ import { planMarkers, prepareMarkersFile } from './markers.js';
5
+ import { isErrnoCode, isSamePath, prepareUpdate, readExistingEnv } from './settings.js';
6
+ export const planSetupRemoval = async (adapter, options = {}) => {
7
+ const path = adapter.paths.global;
8
+ const env = await readExistingEnv(path, adapter.codec);
9
+ const owns = env !== null && (adapter.holdsOwnSetup?.(env) ?? true);
10
+ const config = await prepareUpdate({
11
+ path,
12
+ newEnv: {},
13
+ managedKeys: owns ? [...adapter.managedEnvKeys, ...(adapter.retiredEnvKeys ?? [])] : [],
14
+ codec: adapter.codec,
15
+ });
16
+ const holdsKey = (fileEnv) => fileEnv !== null && adapter.holdsOwnSetup?.(fileEnv) === true;
17
+ const configKey = holdsKey(env);
18
+ const hooksFile = adapter.markers?.hooksFile;
19
+ const approvals = options.approvals === true;
20
+ let removals;
21
+ let keys = [];
22
+ if (hooksFile === undefined) {
23
+ removals = [{ update: config, markersPlan: null, approvals: 0, holdsKey: configKey }];
24
+ }
25
+ else if (isSamePath(hooksFile.path, path)) {
26
+ const before = config.next;
27
+ const markersPlan = config.exists ? planMarkers(config.next, []) : null;
28
+ if (markersPlan !== null)
29
+ config.next = markersPlan.next;
30
+ const removal = {
31
+ update: config,
32
+ markersPlan,
33
+ approvals: 0,
34
+ holdsKey: configKey,
35
+ };
36
+ if (approvals && markersPlan !== null) {
37
+ keys = mainwaveHookKeys(before, hooksFile.path);
38
+ removal.moved = movedHooks(before, markersPlan.next, hooksFile.path, adapter.trustFiles);
39
+ }
40
+ removals = [removal];
41
+ }
42
+ else {
43
+ const hooks = await prepareMarkersFile(hooksFile.path, hooksFile.codec, []);
44
+ const next = hooks.plan.next;
45
+ const empty = next !== null && typeof next === 'object' && Object.keys(next).length === 0;
46
+ const emptied = hooks.update.exists && hooks.plan.changed && empty;
47
+ const linkTarget = emptied && (await fs.lstat(hooksFile.path)).isSymbolicLink()
48
+ ? await fs.realpath(hooksFile.path)
49
+ : undefined;
50
+ const removal = {
51
+ update: hooks.update,
52
+ markersPlan: hooks.plan,
53
+ approvals: 0,
54
+ holdsKey: false,
55
+ ...(linkTarget !== undefined ? { linkTarget } : emptied ? { remove: true } : {}),
56
+ };
57
+ if (approvals && hooks.plan.removed.length > 0) {
58
+ const body = await fs.readFile(hooksFile.path, 'utf8');
59
+ const before = hooksFile.codec.parse(body, hooksFile.path);
60
+ keys = mainwaveHookKeys(before, hooksFile.path);
61
+ removal.moved = movedHooks(before, hooks.plan.next, hooksFile.path, adapter.trustFiles);
62
+ }
63
+ removals = [{ update: config, markersPlan: null, approvals: 0, holdsKey: configKey }, removal];
64
+ }
65
+ if (keys.length === 0)
66
+ return removals;
67
+ return dropApprovals(removals, adapter.trustFiles ?? [], new Set(keys), (doc) => holdsKey(tomlOtelCodec.readEnv(doc)));
68
+ };
69
+ const movedHooks = (before, after, keySource, trustFiles = []) => {
70
+ const eventsOf = (doc) => isRecord(doc) && isRecord(doc.hooks) ? doc.hooks : {};
71
+ const approved = approvedHookKeys(trustFiles);
72
+ const moved = [];
73
+ const kept = eventsOf(after);
74
+ for (const [event, groups] of Object.entries(eventsOf(before))) {
75
+ const left = kept[event];
76
+ if (!Array.isArray(groups) || !Array.isArray(left))
77
+ continue;
78
+ let at = 0;
79
+ for (const [gi, group] of groups.entries()) {
80
+ if (at >= left.length || JSON.stringify(group) !== JSON.stringify(left[at]))
81
+ continue;
82
+ if (at !== gi && isRecord(group) && Array.isArray(group.hooks)) {
83
+ for (const [hi, handler] of group.hooks.entries()) {
84
+ if (!isRecord(handler) || typeof handler.command !== 'string')
85
+ continue;
86
+ if (approved?.has(hookTrustKey(keySource, event, gi, hi)) === false)
87
+ continue;
88
+ moved.push({ event, command: handler.command });
89
+ }
90
+ }
91
+ at++;
92
+ }
93
+ }
94
+ return moved;
95
+ };
96
+ const isRecord = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
97
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
98
+ const shownCommand = (command) => {
99
+ const program = command
100
+ .trim()
101
+ .split(/\s+/)
102
+ .find((word) => !ASSIGNMENT.test(word));
103
+ const name = program
104
+ ?.replace(/^["']|["']$/g, '')
105
+ .split(/[\\/]/)
106
+ .pop();
107
+ return name ? `${name} (arguments hidden)` : '(command hidden)';
108
+ };
109
+ const dropApprovals = async (removals, trustFiles, keys, holdsKey) => {
110
+ const out = [...removals];
111
+ for (const file of trustFiles) {
112
+ let at = out.findIndex((r) => isSamePath(r.update.path, file));
113
+ if (at < 0) {
114
+ const update = await prepareUpdate({
115
+ path: file,
116
+ newEnv: {},
117
+ managedKeys: [],
118
+ codec: tomlOtelCodec,
119
+ });
120
+ if (!update.exists)
121
+ continue;
122
+ at = out.findIndex((r) => removals.includes(r));
123
+ out.splice(at, 0, {
124
+ update,
125
+ markersPlan: null,
126
+ approvals: 0,
127
+ holdsKey: holdsKey(update.next),
128
+ });
129
+ }
130
+ const removal = out[at];
131
+ const { codec } = removal.update;
132
+ const { text, dropped } = withoutHookStates(codec.serialize(removal.update.next), keys);
133
+ if (dropped === 0)
134
+ continue;
135
+ removal.update.next = codec.parse(text, removal.update.path);
136
+ removal.approvals += dropped;
137
+ }
138
+ return out;
139
+ };
140
+ const removalChanges = ({ update, markersPlan, approvals }) => update.diff.added.length > 0 ||
141
+ update.diff.changed.length > 0 ||
142
+ update.diff.removed.length > 0 ||
143
+ markersPlan?.changed === true ||
144
+ approvals > 0;
145
+ export const removalSteps = async (removals) => Promise.all(removals.filter(removalChanges).map(removalStep));
146
+ const isSymlink = async (path) => {
147
+ try {
148
+ return (await fs.lstat(path)).isSymbolicLink();
149
+ }
150
+ catch (err) {
151
+ if (isErrnoCode(err, 'ENOENT'))
152
+ return false;
153
+ throw err;
154
+ }
155
+ };
156
+ const removalStep = async (removal) => {
157
+ const { update, markersPlan, approvals, holdsKey } = removal;
158
+ const left = update.codec.serialize(update.next).trim();
159
+ if (left === '' || left === '{}') {
160
+ if (await isSymlink(update.path)) {
161
+ const target = await fs.realpath(update.path);
162
+ return {
163
+ kind: 'update',
164
+ update,
165
+ holdsKey,
166
+ note: `${update.path}: links to ${target}; keep the link and leave that file ` +
167
+ `${left === '{}' ? 'as {}' : 'empty'} (only Mainwave's setup in it)`,
168
+ };
169
+ }
170
+ return {
171
+ kind: 'delete',
172
+ path: update.path,
173
+ holdsKey,
174
+ note: `${update.path}: delete (only Mainwave's setup in it)`,
175
+ };
176
+ }
177
+ const hooks = markersPlan?.removed.length ?? 0;
178
+ const parts = [
179
+ ...(update.diff.removed.length > 0 ? ["Mainwave's telemetry settings"] : []),
180
+ ...(hooks > 0 ? [`${hooks} Mainwave ${hooks === 1 ? 'hook' : 'hooks'}`] : []),
181
+ ...(approvals > 0
182
+ ? [`Codex's ${approvals === 1 ? 'approval' : 'approvals'} of Mainwave hooks`]
183
+ : []),
184
+ ];
185
+ const moved = removal.moved ?? [];
186
+ const reapprove = moved.length === 0
187
+ ? ''
188
+ : `\n This moves ${moved.length === 1 ? 'a hook' : 'hooks'} of other tools that Codex ` +
189
+ `approved by position, so Codex will ask you to approve ${moved.length === 1 ? 'it' : 'them'} again:` +
190
+ moved.map((h) => `\n ${h.event}: ${shownCommand(h.command)}`).join('');
191
+ return {
192
+ kind: 'update',
193
+ update,
194
+ holdsKey,
195
+ note: `${update.path}: remove ${parts.join(', ')}; keep the rest${reapprove}`,
196
+ };
197
+ };
@@ -174,6 +174,43 @@ export const updateSettings = async (patch) => withFileLock(settingsPath(), asyn
174
174
  await writeJson(settingsPath(), next);
175
175
  return next;
176
176
  });
177
+ const withoutHookFiles = (hooks, files) => {
178
+ if (!isPlainObject(hooks))
179
+ return undefined;
180
+ const next = { ...hooks };
181
+ let changed = false;
182
+ for (const kind of ['events', 'routes']) {
183
+ const record = next[kind];
184
+ if (!isPlainObject(record))
185
+ continue;
186
+ let kept = record;
187
+ for (const { adapter, file } of files) {
188
+ const perFile = kept[adapter];
189
+ if (!isPlainObject(perFile) || !(file in perFile))
190
+ continue;
191
+ kept = {
192
+ ...kept,
193
+ [adapter]: Object.fromEntries(Object.entries(perFile).filter(([f]) => f !== file)),
194
+ };
195
+ changed = true;
196
+ }
197
+ next[kind] = kept;
198
+ }
199
+ return changed ? next : undefined;
200
+ };
201
+ export const forgetHookFiles = async (files) => {
202
+ if (withoutHookFiles((await readSettings()).hooks, files) === undefined)
203
+ return false;
204
+ return withFileLock(settingsPath(), async () => {
205
+ await assertSettingsWritable();
206
+ const current = await readSettings();
207
+ const hooks = withoutHookFiles(current.hooks, files);
208
+ if (hooks === undefined)
209
+ return false;
210
+ await writeJson(settingsPath(), { ...current, hooks });
211
+ return true;
212
+ });
213
+ };
177
214
  export const KEEP_ORG_PACKS = 'keep';
178
215
  export const hasOrgEntry = async (configDir, path) => orgDirsIn(await readSettingsText(path)).includes(configDir);
179
216
  const sameList = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
@@ -19,7 +19,7 @@ import { VERSION } from './version.js';
19
19
  import { emitJson, say, setJsonMode } from './ui.js';
20
20
  import { validateCollector } from './validate.js';
21
21
  import { runVerify } from './verify.js';
22
- import { CODEX_ADAPTER_NAME, codexCliFor, codexHome, codexHomeIssues, findCodexProfileSetups, parseProfileName, profileConflict, profileFileName, profileOtherExporterWarning, } from '../adapters/codex-cli.js';
22
+ import { CODEX_ADAPTER_NAME, codexCliFor, codexHome, codexHomeIssues, findCodexProfileSetups, homeSharedExporterWarning, otherProfileSetupsNote, parseProfileName, profileConflict, profileFileName, profileOtherExporterWarning, profileRefusal, } from '../adapters/codex-cli.js';
23
23
  const validateWithRetry = async (initialUrl, initialKey, interactive) => {
24
24
  let url = initialUrl;
25
25
  let key = initialKey;
@@ -265,6 +265,25 @@ const resolveCodexAdapters = async (adapters, profile, interactive) => {
265
265
  const found = findCodexProfileSetups(home);
266
266
  if (found.length === 0)
267
267
  return { adapters: [...adapters] };
268
+ const refused = found.flatMap((p) => {
269
+ const refusal = profileRefusal(home, p);
270
+ return refusal === undefined ? [] : [{ profile: p, refusal }];
271
+ });
272
+ if (refused.length > 0) {
273
+ const run = (p) => `\`mainwave-cli setup codex --profile ${p}\``;
274
+ const healthy = found.filter((p) => !refused.some((r) => r.profile === p));
275
+ throw new WizardAbort([
276
+ ...refused.map((r) => `Codex profile ${r.profile} holds a Mainwave setup in a file setup can't edit: ${r.refusal}.`),
277
+ `Until then, ${refused.map((r) => run(r.profile)).join(' and ')} and a switch to all ` +
278
+ 'sessions stop on the same problem.',
279
+ ...(healthy.length === 0
280
+ ? []
281
+ : [
282
+ `To update ${healthy.length === 1 ? 'profile' : 'profiles'} ${healthy.join(', ')} now, ` +
283
+ `run ${healthy.map(run).join(' or ')}.`,
284
+ ]),
285
+ ].join(' '));
286
+ }
268
287
  if (!interactive) {
269
288
  const files = found.map(profileFileName).join(', ');
270
289
  throw new WizardAbort(`Codex sends to Mainwave only from ${found.length === 1 ? 'profile' : 'profiles'} ${found.join(', ')} (${files} in ${home}). ` +
@@ -370,11 +389,20 @@ export const runSetup = async (requested, rawOptions = {}) => {
370
389
  `(${plan.keptPin.name ?? plan.keptPin.id}). Pass --no-use-case to unpin it.`));
371
390
  }
372
391
  }
373
- const otherExporter = codexProfile === undefined ? undefined : profileOtherExporterWarning(codexHome(), codexProfile);
392
+ const otherExporter = !adapters.some((a) => a.name === CODEX_ADAPTER_NAME)
393
+ ? undefined
394
+ : codexProfile === undefined
395
+ ? homeSharedExporterWarning(codexHome())
396
+ : profileOtherExporterWarning(codexHome(), codexProfile);
374
397
  if (otherExporter !== undefined) {
375
398
  say('');
376
399
  say(color.yellow(`⚠ ${otherExporter}`));
377
400
  }
401
+ const otherProfiles = codexProfile === undefined ? undefined : otherProfileSetupsNote(codexHome(), codexProfile);
402
+ if (otherProfiles !== undefined) {
403
+ say('');
404
+ say(color.yellow(`⚠ ${otherProfiles}`));
405
+ }
378
406
  if (planHasChanges(plans) && !options.yes) {
379
407
  if (!interactive) {
380
408
  throw new WizardAbort('refusing to write without confirmation — pass --yes');