@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.
@@ -117,6 +117,124 @@ 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
+ const lines = withoutEmptyHeader(withoutEmptyHeader(kept, ['hooks', 'state']), ['hooks']);
203
+ if (lines !== kept && toml.endsWith('\n') && lines[lines.length - 1] !== '') {
204
+ while (lines.length > 0 && lines[lines.length - 1].trim() === '')
205
+ lines.pop();
206
+ if (lines.length > 0)
207
+ lines.push('');
208
+ }
209
+ return { text: lines.join('\n'), dropped: dropped.size };
210
+ };
211
+ const withoutEmptyHeader = (lines, target) => {
212
+ const headerAt = lines.findIndex((l) => {
213
+ const t = l.trim();
214
+ return t.startsWith('[') && !t.startsWith('[[') && tablePath(t)?.join('.') === target.join('.');
215
+ });
216
+ if (headerAt < 0)
217
+ return lines;
218
+ let next = lines.findIndex((l, i) => i > headerAt && l.trim().startsWith('['));
219
+ if (next < 0)
220
+ next = lines.length;
221
+ const body = lines.slice(headerAt + 1, next);
222
+ if (body.some((l) => l.trim() !== '' && !l.trim().startsWith('#')))
223
+ return lines;
224
+ const implied = (l) => {
225
+ const t = l.trim();
226
+ if (!t.startsWith('['))
227
+ return false;
228
+ return new RegExp(String.raw `^\[\[?\s*${target.join(String.raw `\s*\.\s*`)}\s*[.\]]`).test(t);
229
+ };
230
+ if (lines.some((l, i) => i !== headerAt && implied(l)))
231
+ return lines;
232
+ const before = lines.slice(0, headerAt);
233
+ const lastBlank = before.length === 0 || before[before.length - 1].trim() === '';
234
+ const first = lastBlank ? body.findIndex((l) => l.trim() !== '') : 0;
235
+ const carried = next === lines.length || first < 0 ? [] : body.slice(first);
236
+ return [...before, ...carried, ...lines.slice(next)];
237
+ };
120
238
  const mergedStates = (trustFiles) => {
121
239
  const merged = new Map();
122
240
  for (const file of trustFiles) {
@@ -134,6 +252,12 @@ const mergedStates = (trustFiles) => {
134
252
  }
135
253
  return { states: merged };
136
254
  };
255
+ export const approvedHookKeys = (trustFiles) => {
256
+ const merged = mergedStates(trustFiles);
257
+ if ('unreadable' in merged)
258
+ return undefined;
259
+ return new Set([...merged.states].filter(([, s]) => s.trustedHash !== undefined).map(([key]) => key));
260
+ };
137
261
  export const readCodexTrust = (hooksPath, trustFiles, keySource = hooksPath, codec) => {
138
262
  const body = readText(hooksPath);
139
263
  let doc;
@@ -158,40 +282,17 @@ export const readCodexTrust = (hooksPath, trustFiles, keySource = hooksPath, cod
158
282
  };
159
283
  }
160
284
  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
- }
285
+ const hooks = mainwaveHooks(doc.hooks, keySource).map(({ key, event, hash }) => {
286
+ const state = states.get(key);
287
+ const trust = state?.trustedHash === undefined
288
+ ? 'untrusted'
289
+ : state.trustedHash !== hash
290
+ ? 'modified'
291
+ : state.enabled === false
292
+ ? 'disabled'
293
+ : 'trusted';
294
+ return { key, event, trust };
295
+ });
195
296
  return hooks.length === 0 ? { state: 'no-hooks' } : { state: 'read', hooks };
196
297
  };
197
298
  export const countTrust = (hooks) => {
@@ -5,13 +5,14 @@ import { envFileCodec } from './codecs/env-file.js';
5
5
  import { countTrust, readCodexTrust } from './codex-trust.js';
6
6
  import { activeHierarchy, computeEffective, effectiveFrom, flattenEffective, nativeIdentityReason, } from './effective-settings.js';
7
7
  import { ValidateError } from './errors.js';
8
+ import { HEADER_NAME, jsonObjectHeaders, kvPairsHeaders } from './headers.js';
8
9
  import { color, maskForDisplay } from './format.js';
9
10
  import { collectBehaviourHookIssues, scanBehaviourHooks } from './behaviour-hooks.js';
10
11
  import { isManagedIdentityConfig, isManagedLayer, policyState } from './layer-policy.js';
11
12
  import { collectMarkerIssues, DEFAULT_MARKER_TOOL, managedHooksDir, matchersForTool, readPackagedMatchers, scanForMarkers, } from './markers.js';
12
13
  import { flatCopyIssues } from './hook-copies.js';
13
14
  import { readExistingEnv } from './settings.js';
14
- import { hookShellMissingFor, teamUcidStanding } from './apply.js';
15
+ import { hookShellMissingFor, setupCommand, teamUcidStanding } from './apply.js';
15
16
  import { adapterEffective, primaryCarries } from './status.js';
16
17
  import { hasRulesFile, redactionLines, redactionView, sendsUnredactedContent, uncoveredNotice, } from './redaction.js';
17
18
  import { readSettings } from './store.js';
@@ -617,7 +618,28 @@ const skippedMarkerScans = async (effective) => {
617
618
  }
618
619
  return out;
619
620
  };
620
- const runValidate = async (effective, adapter) => {
621
+ const unchecked = (message, probe = 'skipped') => ({
622
+ ok: false,
623
+ message,
624
+ outcome: 'unchecked',
625
+ probe,
626
+ });
627
+ const PLAIN_PROBE_TIMEOUT_MS = 3_000;
628
+ const VALIDATE_PROBE_TIMEOUT_MS = 10_000;
629
+ const keySource = (effective, adapter, apiKey) => Object.values(effective.effective).find((e) => adapter.parseEnv({ [e.key]: e.value }).apiKey === apiKey);
630
+ export const holdsMainwaveConfig = (adapter, env) => {
631
+ const own = adapter.holdsOwnSetup?.(env);
632
+ if (own !== undefined)
633
+ return own;
634
+ const sourceName = HEADER_NAME.source.toLowerCase();
635
+ const headerSets = [
636
+ kvPairsHeaders.decode(env.OTEL_EXPORTER_OTLP_HEADERS ?? ''),
637
+ jsonObjectHeaders.decode(env.otlpHeaders ?? ''),
638
+ ];
639
+ return (headerSets.some((headers) => Object.keys(headers ?? {}).some((name) => name.toLowerCase() === sourceName)) || /(^|,)\s*mainwave\.source=/.test(env.OTEL_RESOURCE_ATTRIBUTES ?? ''));
640
+ };
641
+ const runValidate = async (effective, adapter, options) => {
642
+ const asked = options.validate === true;
621
643
  const fromRepo = (scan) => !isAbsolute(scan.layer.path) || adapter.layerKeyPolicy?.layers.includes(scan.layer.id) === true;
622
644
  const withoutRepo = effectiveFrom(adapter, effective.scans.filter((s) => !fromRepo(s)), effective.policy);
623
645
  const endpoint = adapter.parseEnv(flattenEffective(effective)).collectorUrl;
@@ -625,27 +647,57 @@ const runValidate = async (effective, adapter) => {
625
647
  endpoint !== adapter.parseEnv(flattenEffective(withoutRepo)).collectorUrl) {
626
648
  const repoScan = effective.scans.find((s) => fromRepo(s) && Object.keys(s.env).length > 0);
627
649
  return {
628
- ok: false,
629
- message: `not validating: the collector endpoint comes from ${repoScan?.layer.label ?? 'project settings'}` +
630
- `${repoScan ? ` (${repoScan.path})` : ''}, and the CLI won't send your key to a destination a repository chose`,
650
+ ...unchecked(`not validating: the collector endpoint comes from ${repoScan?.layer.label ?? 'project settings'}` +
651
+ `${repoScan ? ` (${repoScan.path})` : ''}, and the CLI won't send your key to a destination a repository chose`),
652
+ quiet: !asked,
631
653
  };
632
654
  }
633
- const parsed = adapter.parseEnv(flattenEffective(effective));
655
+ const flat = flattenEffective(effective);
656
+ if (!holdsMainwaveConfig(adapter, flat)) {
657
+ return {
658
+ ...unchecked("key check skipped: the config isn't Mainwave's exporter"),
659
+ quiet: !asked,
660
+ };
661
+ }
662
+ const parsed = adapter.parseEnv(flat);
634
663
  if (!parsed.collectorUrl) {
635
- return { ok: false, message: 'no OTEL_EXPORTER_OTLP_ENDPOINT to validate against' };
664
+ return {
665
+ ...unchecked('no OTEL_EXPORTER_OTLP_ENDPOINT to validate against'),
666
+ quiet: !asked,
667
+ };
636
668
  }
637
669
  if (!parsed.apiKey) {
638
- return { ok: false, message: 'no Bearer token in OTEL_EXPORTER_OTLP_HEADERS' };
639
- }
640
- try {
641
- await validateCollector(parsed.collectorUrl, parsed.apiKey);
642
- return { ok: true, message: 'authenticated' };
643
- }
644
- catch (err) {
645
- if (err instanceof ValidateError)
646
- return { ok: false, message: err.message };
647
- throw err;
648
- }
670
+ return { ...unchecked('no Bearer token in OTEL_EXPORTER_OTLP_HEADERS'), quiet: !asked };
671
+ }
672
+ const apiKey = parsed.apiKey;
673
+ const probeKey = `${parsed.collectorUrl}\n${apiKey}`;
674
+ let probe = options.probes.get(probeKey);
675
+ if (probe === undefined) {
676
+ probe = validateCollector(parsed.collectorUrl, apiKey, {
677
+ timeoutMs: asked ? VALIDATE_PROBE_TIMEOUT_MS : PLAIN_PROBE_TIMEOUT_MS,
678
+ }).then(() => undefined, (err) => {
679
+ if (!(err instanceof ValidateError))
680
+ throw err;
681
+ return err;
682
+ });
683
+ options.probes.set(probeKey, probe);
684
+ }
685
+ const err = await probe;
686
+ if (err === undefined)
687
+ return { ok: true, message: 'authenticated', outcome: 'ok', probe: 'ok' };
688
+ if (err.reason !== 'unauthorized')
689
+ return unchecked(err.message, err.reason);
690
+ const source = keySource(effective, adapter, apiKey);
691
+ const where = source ? ` in ${source.source.path}` : '';
692
+ return {
693
+ ok: false,
694
+ outcome: 'rejected',
695
+ probe: 'rejected',
696
+ message: `the collector rejects the Mainwave key${where} (HTTP ${err.status}). ` +
697
+ (source !== undefined && isManagedLayer(source.source.layer)
698
+ ? "Your organization's managed settings supply the key. Ask your admin to update it."
699
+ : `Rerun \`${setupCommand(adapter)}\` with a valid key.`),
700
+ };
649
701
  };
650
702
  const doctorJson = async (adapter, effective, issues, validation, redaction) => ({
651
703
  adapter: adapter.name,
@@ -665,19 +717,24 @@ const doctorJson = async (adapter, effective, issues, validation, redaction) =>
665
717
  })),
666
718
  redaction,
667
719
  issues: issues.map((issue) => ({ level: issue.level, message: issue.message })),
668
- validation,
720
+ validation: validation && {
721
+ ok: validation.ok,
722
+ message: validation.message,
723
+ outcome: validation.probe,
724
+ },
669
725
  });
670
726
  export const runDoctor = async (adapter, options = {}) => {
727
+ const run = { ...options, probes: new Map() };
671
728
  const many = adapter.doctorSetups?.();
672
729
  if (many === undefined) {
673
- return options.json ? runDoctorJson(adapter, options) : reportSetup(adapter, options);
730
+ return options.json ? runDoctorJson(adapter, run) : reportSetup(adapter, run);
674
731
  }
675
732
  const together = many.issues.some((i) => i.level === 'error') ? 1 : 0;
676
733
  if (options.json) {
677
734
  const setups = [];
678
735
  let code = together;
679
736
  for (const { label, adapter: setup } of many.setups) {
680
- const { doc, failed } = await setupJson(setup, options);
737
+ const { doc, failed } = await setupJson(setup, run);
681
738
  setups.push({ setup: label, ...doc });
682
739
  if (failed)
683
740
  code = 1;
@@ -691,19 +748,22 @@ export const runDoctor = async (adapter, options = {}) => {
691
748
  return code;
692
749
  }
693
750
  let code = together;
751
+ const once = many.onceInText;
694
752
  for (const [i, { label, adapter: setup }] of many.setups.entries()) {
695
753
  if (i > 0)
696
754
  console.log();
697
- if ((await reportSetup(setup, options, `${adapter.displayName}, ${label}`)) !== 0)
755
+ const title = `${adapter.displayName}, ${label}`;
756
+ if ((await reportSetup(setup, run, title, once?.replaces)) !== 0)
698
757
  code = 1;
699
758
  }
700
- if (many.issues.length > 0) {
759
+ const togetherIssues = [...many.issues, ...(once?.issues ?? [])];
760
+ if (togetherIssues.length > 0) {
701
761
  console.log();
702
- renderChecks(many.issues, `${adapter.displayName} setups together:`);
762
+ renderChecks(togetherIssues, `${adapter.displayName} setups together:`);
703
763
  }
704
764
  return code;
705
765
  };
706
- const reportSetup = async (adapter, options, title = adapter.displayName) => {
766
+ const reportSetup = async (adapter, options, title = adapter.displayName, omit = () => false) => {
707
767
  console.log(color.bold(`mainwave-cli doctor — ${title}`));
708
768
  console.log();
709
769
  const effective = await computeEffective(adapter);
@@ -729,19 +789,22 @@ const reportSetup = async (adapter, options, title = adapter.displayName) => {
729
789
  const behaviourHookIssues = adapter.behaviourHooks
730
790
  ? await collectBehaviourHookIssues(adapter.behaviourHooks, VERSION)
731
791
  : [];
732
- renderChecks([...issues, ...shellEnvIssues, ...markerIssues, ...behaviourHookIssues]);
792
+ renderChecks([...issues, ...shellEnvIssues, ...markerIssues, ...behaviourHookIssues].filter((i) => !omit(i)));
733
793
  let validateFailed = false;
734
- if (options.validate) {
794
+ const result = await runValidate(effective, adapter, options);
795
+ if (!result.quiet) {
735
796
  console.log();
736
797
  console.log(color.bold('Auth check:'));
737
- const result = await runValidate(effective, adapter);
738
798
  if (result.ok) {
739
799
  console.log(color.green(` ✓ ${result.message}`));
740
800
  }
741
- else {
801
+ else if (result.outcome === 'rejected' || options.validate) {
742
802
  console.log(color.red(` ✗ ${result.message}`));
743
803
  validateFailed = true;
744
804
  }
805
+ else {
806
+ console.log(color.yellow(` ! could not check the key: ${result.message}`));
807
+ }
745
808
  }
746
809
  const hasError = [...issues, ...shellEnvIssues, ...markerIssues, ...behaviourHookIssues].some((i) => i.level === 'error');
747
810
  return hasError || validateFailed ? 1 : 0;
@@ -763,9 +826,11 @@ const setupJson = async (adapter, options) => {
763
826
  ? await collectBehaviourHookIssues(adapter.behaviourHooks, VERSION)
764
827
  : []),
765
828
  ];
766
- const validation = options.validate ? await runValidate(effective, adapter) : undefined;
829
+ const validation = await runValidate(effective, adapter, options);
767
830
  return {
768
- doc: await doctorJson(adapter, effective, issues, validation, redaction),
769
- failed: issues.some((i) => i.level === 'error') || validation?.ok === false,
831
+ doc: await doctorJson(adapter, effective, issues, validation.quiet ? undefined : validation, redaction),
832
+ failed: issues.some((i) => i.level === 'error') ||
833
+ validation.outcome === 'rejected' ||
834
+ (options.validate === true && !validation.ok),
770
835
  };
771
836
  };
@@ -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,60 @@ 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
+ for (const a of adapters)
82
+ if (a.lingeringProcess)
83
+ say(color.yellow(a.lingeringProcess.onRemove));
84
+ const problem = await forgetHookRecords(adapters);
85
+ if (options.json) {
86
+ emitJson({
87
+ status: 'removed',
88
+ tools: adapters.map((a) => a.name),
89
+ files: done,
90
+ ...(problem === undefined ? {} : { error: problem }),
91
+ });
92
+ }
93
+ return problem === undefined ? 0 : 1;
94
+ };
95
+ const forgetHookRecords = async (adapters) => {
96
+ const files = adapters
97
+ .filter((a) => a.markers !== undefined)
98
+ .map((a) => ({ adapter: a.name, file: userHooksPath(a) }));
99
+ if (files.length === 0)
100
+ return undefined;
101
+ try {
102
+ await forgetHookFiles(files);
103
+ return undefined;
104
+ }
105
+ catch (err) {
106
+ const problem = `Couldn't drop setup's record of the removed hooks from ${settingsPath()}: ` +
107
+ `${err instanceof Error ? err.message : String(err)}. Run the same command again to retry.`;
108
+ say(color.yellow(problem));
109
+ return problem;
110
+ }
67
111
  };