@mainwave/cli 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,9 +7,9 @@ import { ValidateError } from './errors.js';
7
7
  import { color, maskForDisplay } from './format.js';
8
8
  import { collectBehaviourHookIssues } from './behaviour-hooks.js';
9
9
  import { isManagedIdentityConfig, isManagedLayer, policyState } from './layer-policy.js';
10
- import { collectMarkerIssues, readPackagedMatchers, scanForMarkers } from './markers.js';
10
+ import { collectMarkerIssues, DEFAULT_MARKER_TOOL, managedHooksDir, matchersForTool, readPackagedMatchers, scanForMarkers, } from './markers.js';
11
11
  import { readExistingEnv } from './settings.js';
12
- import { teamUcidStanding } from './apply.js';
12
+ import { hookShellMissingFor, teamUcidStanding } from './apply.js';
13
13
  import { adapterEffective, primaryCarries } from './status.js';
14
14
  import { readSettings } from './store.js';
15
15
  import { emitJson } from './ui.js';
@@ -463,6 +463,28 @@ const renderChecks = (issues) => {
463
463
  console.log(`${prefix} ${issue.message}`);
464
464
  }
465
465
  };
466
+ const markerMatchers = (adapter, matchers) => matchersForTool(matchers, adapter.markers?.runtimeTool ?? DEFAULT_MARKER_TOOL);
467
+ const hookChoices = async (adapter) => {
468
+ const { hooks } = await readSettings();
469
+ return { markers: hooks?.markers?.[adapter.name] ?? true };
470
+ };
471
+ const markerLayers = async (adapter) => {
472
+ const hooksFile = adapter.markers?.hooksFile;
473
+ if (hooksFile === undefined)
474
+ return activeHierarchy(adapter);
475
+ return [
476
+ ...(hooksFile.localPath
477
+ ? [{ id: 'project', label: 'Project hooks file', path: hooksFile.localPath, kind: 'file' }]
478
+ : []),
479
+ { id: 'user', label: 'User hooks file', path: hooksFile.path, kind: 'file' },
480
+ ];
481
+ };
482
+ const markerIssuesFor = async (adapter, effective) => adapter.markers
483
+ ? collectMarkerIssues(await scanForMarkers(await markerLayers(adapter)), VERSION, markerMatchers(adapter, await readPackagedMatchers()), await skippedMarkerScans(effective), await hookChoices(adapter), adapter.markers.runtimeTool ?? DEFAULT_MARKER_TOOL, {
484
+ managedDir: managedHooksDir(),
485
+ hookShellMissing: await hookShellMissingFor(adapter, () => flattenEffective(effective)),
486
+ })
487
+ : [];
466
488
  const skippedMarkerScans = async (effective) => {
467
489
  const out = [];
468
490
  for (const { layer, reason } of effective.skipped ?? []) {
@@ -536,9 +558,7 @@ export const runDoctor = async (adapter, options = {}) => {
536
558
  console.log();
537
559
  const issues = collectIssues(effective, adapter, await attributionContext(adapter, effective));
538
560
  const shellEnvIssues = await checkShellEnv(adapter);
539
- const markerIssues = adapter.markers
540
- ? await collectMarkerIssues(await scanForMarkers(await activeHierarchy(adapter)), VERSION, await readPackagedMatchers(), await skippedMarkerScans(effective))
541
- : [];
561
+ const markerIssues = await markerIssuesFor(adapter, effective);
542
562
  const behaviourHookIssues = adapter.behaviourHooks
543
563
  ? await collectBehaviourHookIssues(adapter.behaviourHooks, VERSION)
544
564
  : [];
@@ -564,9 +584,7 @@ const runDoctorJson = async (adapter, options) => {
564
584
  const issues = [
565
585
  ...collectIssues(effective, adapter, await attributionContext(adapter, effective)),
566
586
  ...(await checkShellEnv(adapter)),
567
- ...(adapter.markers
568
- ? await collectMarkerIssues(await scanForMarkers(await activeHierarchy(adapter)), VERSION, await readPackagedMatchers(), await skippedMarkerScans(effective))
569
- : []),
587
+ ...(await markerIssuesFor(adapter, effective)),
570
588
  ...(adapter.behaviourHooks
571
589
  ? await collectBehaviourHookIssues(adapter.behaviourHooks, VERSION)
572
590
  : []),
@@ -109,6 +109,16 @@ export const flattenEffective = (effective) => {
109
109
  }
110
110
  return out;
111
111
  };
112
+ export const effectiveEnv = async (adapter, userEnv) => {
113
+ const effective = await computeEffective(adapter);
114
+ if (userEnv === undefined)
115
+ return flattenEffective(effective);
116
+ const written = resolve(adapter.paths.global);
117
+ const scans = effective.scans.map((scan) => resolve(scan.path) === written
118
+ ? { ...scan, status: 'present', env: { ...userEnv } }
119
+ : scan);
120
+ return flattenEffective(effectiveFrom(adapter, scans));
121
+ };
112
122
  export const nativeIdentityReason = async (adapter, effective) => {
113
123
  if (!adapter.nativeIdentityAbsent)
114
124
  return undefined;
@@ -0,0 +1,90 @@
1
+ export const HOOK_ENTRY_SCRIPT = 'mainwave-hook.sh';
2
+ export const HOOK_DISPATCHER_SCRIPT = 'mainwave-hook.mjs';
3
+ export const HOOK_NODE_ENTRY_SCRIPT = 'mainwave-hook-node.mjs';
4
+ export const ORG_DELIVERED_MARK = 'org-delivered';
5
+ export const HOOK_ENTRY_MARK = 'mainwave hook entry v2';
6
+ export const ENTRY_HOSTS = ['claude-code', 'codex'];
7
+ export const CODEX_BASH_FILTER = ['*pr*create*', '*mr*create*', '*mr*new*', '*merge_requests*'];
8
+ export const entryRouteKey = ({ host, event, route }) => `${host}/${event}/${route ?? ''}`;
9
+ const SAFE_TOKEN = /^[A-Za-z0-9._+-]+$/;
10
+ const shQuote = (value) => `'${value.replace(/'/g, `'\\''`)}'`;
11
+ export const renderHookEntry = ({ versionId, version, nodePath, routes, }) => {
12
+ for (const r of routes) {
13
+ for (const part of [r.host, r.event, r.route ?? 'x', r.optOut]) {
14
+ if (!SAFE_TOKEN.test(part))
15
+ throw new Error(`hook entry: unsafe route token ${part}`);
16
+ }
17
+ }
18
+ if (!SAFE_TOKEN.test(versionId))
19
+ throw new Error(`hook entry: unsafe release id ${versionId}`);
20
+ const byOptOut = new Map();
21
+ for (const r of routes) {
22
+ byOptOut.set(r.optOut, [...(byOptOut.get(r.optOut) ?? []), entryRouteKey(r)]);
23
+ }
24
+ const arms = [...byOptOut].map(([optOut, keys]) => ` ${keys.join('|')}) k=${optOut} ;;`);
25
+ const codexBash = routes.some((r) => entryRouteKey(r) === 'codex/PostToolUse/bash');
26
+ const lines = [
27
+ '#!/bin/sh',
28
+ `# ${HOOK_ENTRY_MARK}`,
29
+ '#',
30
+ `# Generated by mainwave-cli ${version.replace(/[^A-Za-z0-9._+-]/g, '_')}; replaced whole by the next`,
31
+ '# release. Every Mainwave hook group runs it as',
32
+ '# sh mainwave-hook.sh <host> <Event> [<route>]',
33
+ "# and it runs that release's Node dispatcher. It prints nothing, never",
34
+ '# blocks, and exits 0.',
35
+ 'main() {',
36
+ ' exec >/dev/null 2>&1',
37
+ ` V=${shQuote(versionId)}`,
38
+ ` N=${shQuote(nodePath)}`,
39
+ ' d=${0%/*}',
40
+ ` js="$d/versions/$V/${HOOK_DISPATCHER_SCRIPT}"`,
41
+ ' [ -f "$js" ] || return 0',
42
+ ' r=$3',
43
+ ' case "$r" in -*) r= ;; esac',
44
+ ' k=',
45
+ ' case "$1/$2/$r" in',
46
+ ...arms,
47
+ ' *) return 0 ;;',
48
+ ' esac',
49
+ ` [ -f "\${d%/*}/off/$1/$k" ] && [ ! -f "$d/${ORG_DELIVERED_MARK}" ] && return 0`,
50
+ ' n=node',
51
+ ' command -v node >/dev/null 2>&1 || n=$N',
52
+ ...(codexBash
53
+ ? [
54
+ ' if [ "$1/$2/$r" = codex/PostToolUse/bash ]; then',
55
+ ' in=$(cat)',
56
+ ' case "$in" in',
57
+ ` ${CODEX_BASH_FILTER.join('|')}) ;;`,
58
+ ' *) return 0 ;;',
59
+ ' esac',
60
+ ' printf \'%s\' "$in" | "$n" "$js" "$@"',
61
+ ' return 0',
62
+ ' fi',
63
+ ]
64
+ : []),
65
+ ' "$n" "$js" "$@"',
66
+ ' return 0',
67
+ '}',
68
+ 'main "$@"',
69
+ 'exit 0',
70
+ ];
71
+ return `${lines.join('\n')}\n`;
72
+ };
73
+ export const entryVersionId = (text) => {
74
+ if (!text.includes(HOOK_ENTRY_MARK))
75
+ return undefined;
76
+ const m = /^\s*V='([A-Za-z0-9._+-]+)'$/m.exec(text);
77
+ return m?.[1];
78
+ };
79
+ export const entryCommand = (host, event, route) => `f="$HOME/.mainwave/hooks/managed/${HOOK_ENTRY_SCRIPT}"; [ -f "$f" ] && exec sh "$f" ${host} ${event}${route === undefined ? '' : ` ${route}`}; exit 0`;
80
+ export const nodeEntryCommand = (nodeEntryPath, host, event, route) => `(if exist "${nodeEntryPath}" node "${nodeEntryPath}" ${host} ${event}${route === undefined ? '' : ` ${route}`}) & exit /b 0`;
81
+ export const parseEntryCommand = (command) => {
82
+ const m = new RegExp(`${HOOK_ENTRY_SCRIPT.replace('.', '\\.')}"; \\[ -f "\\$f" \\] && exec sh "\\$f" ([A-Za-z0-9_-]+) ([A-Za-z]+)(?: ([A-Za-z0-9_-]+))?; exit 0`).exec(command);
83
+ if (!m) {
84
+ const loose = new RegExp(`(?:${HOOK_ENTRY_SCRIPT.replace('.', '\\.')}|${HOOK_NODE_ENTRY_SCRIPT.replace('.', '\\.')})"?\\s+([A-Za-z0-9_-]+)\\s+([A-Za-z]+)(?:\\s+([A-Za-z0-9_-]+))?`).exec(command);
85
+ if (!loose)
86
+ return undefined;
87
+ return { host: loose[1], event: loose[2], ...(loose[3] ? { route: loose[3] } : {}) };
88
+ }
89
+ return { host: m[1], event: m[2], ...(m[3] ? { route: m[3] } : {}) };
90
+ };
@@ -0,0 +1,40 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { win32 } from 'node:path';
3
+ const BASH_NAMES = new Set(['bash.exe', 'sh.exe', 'bash', 'sh']);
4
+ const DEFAULT_GIT_BASH = [
5
+ 'C:\\Program Files\\Git\\bin\\bash.exe',
6
+ 'C:\\Program Files (x86)\\Git\\bin\\bash.exe',
7
+ ];
8
+ const gitOnPath = (env, exists) => {
9
+ const key = Object.keys(env).find((k) => k.toUpperCase() === 'PATH');
10
+ for (const dir of (key ? (env[key] ?? '') : '').split(win32.delimiter)) {
11
+ if (!dir)
12
+ continue;
13
+ for (const name of ['git.exe', 'git.cmd', 'git']) {
14
+ const candidate = win32.join(dir, name);
15
+ if (exists(candidate))
16
+ return candidate;
17
+ }
18
+ }
19
+ return undefined;
20
+ };
21
+ export const findGitBash = (env, exists = existsSync) => {
22
+ const configured = env.CLAUDE_CODE_GIT_BASH_PATH?.trim();
23
+ if (configured &&
24
+ BASH_NAMES.has(win32.basename(configured).toLowerCase()) &&
25
+ exists(configured)) {
26
+ return configured;
27
+ }
28
+ const installed = DEFAULT_GIT_BASH.find(exists);
29
+ if (installed !== undefined)
30
+ return installed;
31
+ const git = gitOnPath(env, exists);
32
+ if (git === undefined)
33
+ return undefined;
34
+ const bash = win32.join(git, '..', '..', 'bin', 'bash.exe');
35
+ return exists(bash) ? bash : undefined;
36
+ };
37
+ export const claudeHookShellMissing = (env, plat = process.platform, exists = existsSync) => plat === 'win32' && findGitBash(env, exists) === undefined;
38
+ export const GIT_BASH_MISSING_REASON = "Git Bash isn't installed, so Claude Code runs hook commands in PowerShell, where the Mainwave hook commands can't run";
39
+ export const GIT_BASH_FIX = 'Install Git for Windows (https://git-scm.com/downloads/win), or set CLAUDE_CODE_GIT_BASH_PATH to your bash.exe, ' +
40
+ 'then re-run `mainwave-cli setup claude-code`.';
@@ -1,58 +1,72 @@
1
- import { basename } from 'node:path';
1
+ import { basename, dirname, isAbsolute, resolve } from 'node:path';
2
+ import { claudeConfigDir } from '../adapters/claude-code.js';
2
3
  import { hasPath } from './detect.js';
3
4
  import { activeHierarchy } from './effective-settings.js';
4
5
  import { isManagedLayer } from './layer-policy.js';
5
- import { buildHookCommand, installHooksCommand, managedHooksDir, managedMarkerScripts, packagedHooksDir, PAYLOAD_CLI_SPEC, prepareMarkersFile, readPackagedMatchers, scanForMarkers, scriptPathFromCommand, syncManagedHooks, } from './markers.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
7
  import { applyUpdate } from './settings.js';
8
+ import { readSettings } from './store.js';
7
9
  import { VERSION } from './version.js';
8
- const PAYLOAD_HOOKS_DIR = '$HOME/.mainwave/hooks/managed';
9
- export const managedPayloadHooks = (matchers) => ({
10
- SessionStart: [
11
- {
12
- matcher: 'startup|resume',
13
- hooks: [
14
- {
15
- type: 'command',
16
- command: installHooksCommand(PAYLOAD_CLI_SPEC),
17
- async: true,
18
- },
19
- ],
20
- },
21
- ],
22
- PostToolUse: matchers.map((m) => ({
23
- matcher: m.matcher,
24
- hooks: [
25
- {
26
- type: 'command',
27
- command: buildHookCommand(`${PAYLOAD_HOOKS_DIR}/${m.hook}`, PAYLOAD_CLI_SPEC, 'darwin'),
28
- timeout: 5,
29
- },
30
- ],
31
- })),
32
- });
10
+ export const PAYLOAD_EVENTS = [
11
+ 'SessionStart',
12
+ 'UserPromptSubmit',
13
+ 'PostToolUse',
14
+ 'StopFailure',
15
+ ];
16
+ const payloadGroup = ({ event: _event, ...group }) => group;
17
+ export const managedPayloadHooks = (matchers) => {
18
+ const groups = [bootstrapGroup(), ...buildHookGroups(matchersForTool(matchers), 'claude-code')];
19
+ const under = (event) => groups.filter((g) => groupEvent(g) === event).map(payloadGroup);
20
+ return Object.fromEntries(PAYLOAD_EVENTS.map((e) => [e, under(e)]));
21
+ };
33
22
  const defaultPaths = () => ({
34
23
  srcDir: packagedHooksDir(),
35
24
  destDir: managedHooksDir(),
36
25
  });
37
26
  export const installHooks = async (adapter, paths = defaultPaths()) => {
38
- const matchers = await readPackagedMatchers(paths.srcDir);
39
- const updated = await syncManagedHooks(matchers, paths.srcDir, paths.destDir, paths.version ?? VERSION);
40
- const managedLayers = (await activeHierarchy(adapter)).filter(isManagedLayer);
41
- const delivered = managedMarkerScripts(await scanForMarkers(managedLayers));
27
+ const all = await readPackagedMatchers(paths.srcDir);
28
+ const updated = await syncManagedHooks(all, paths.srcDir, paths.destDir, paths.version ?? VERSION, paths.nodePath);
29
+ if (adapter === undefined) {
30
+ return {
31
+ updated,
32
+ destDir: paths.destDir,
33
+ managedDelivers: false,
34
+ removedFromUser: 0,
35
+ addedToUser: 0,
36
+ userSettings: undefined,
37
+ };
38
+ }
39
+ const scans = await scanForMarkers((await activeHierarchy(adapter)).filter(isManagedLayer));
40
+ const delivered = managedMarkerDeliveries(scans);
41
+ await syncOrgDelivered(managedDeliversEntry(scans), dirname(adapter.paths.global), paths.destDir);
42
42
  const managedDelivers = delivered.size > 0;
43
+ const stored = paths.stored ?? (await readSettings().catch(() => ({}))).hooks ?? {};
43
44
  const userSettings = adapter.paths.global;
45
+ const disclosed = stored.events?.[adapter.name]?.[userSettings];
44
46
  let removedFromUser = 0;
45
- if (managedDelivers && hasPath(userSettings)) {
46
- const { update, plan } = await prepareMarkersFile(userSettings, adapter.codec, [], 0o600, (ownership, group) => {
47
- const script = scriptPathFromCommand(group.command);
48
- return ownership === 'cli' && script !== undefined && delivered.has(basename(script));
49
- });
47
+ let addedToUser = 0;
48
+ if ((managedDelivers || disclosed !== undefined) && hasPath(userSettings)) {
49
+ const groups = disclosed === undefined
50
+ ? []
51
+ : userHookGroups(matchersForTool(all, DEFAULT_MARKER_TOOL), { markers: stored.markers?.[adapter.name] ?? true }, delivered, DEFAULT_MARKER_TOOL).filter((g) => disclosed.includes(groupEvent(g)));
52
+ const { update, plan } = await prepareMarkersFile(userSettings, adapter.codec, groups, 0o600, (ownership, group) => ownership === 'cli' &&
53
+ ((!isBootstrapCommand(group.command) &&
54
+ isDelivered(delivered, group.event, group.command)) ||
55
+ (disclosed?.includes(group.event) ?? false)));
50
56
  if (plan.changed) {
51
57
  await applyUpdate(update);
52
58
  removedFromUser = plan.removed.length;
59
+ addedToUser = plan.added.length;
53
60
  }
54
61
  }
55
- return { updated, destDir: paths.destDir, managedDelivers, removedFromUser, userSettings };
62
+ return {
63
+ updated,
64
+ destDir: paths.destDir,
65
+ managedDelivers,
66
+ removedFromUser,
67
+ addedToUser,
68
+ userSettings,
69
+ };
56
70
  };
57
71
  export const runInstallHooks = async (adapter, options = {}, paths) => {
58
72
  let result;
@@ -68,14 +82,83 @@ export const runInstallHooks = async (adapter, options = {}, paths) => {
68
82
  return 0;
69
83
  const dest = result.destDir;
70
84
  console.log(result.updated.length > 0
71
- ? `Installed marker hook scripts in ${dest}: ${result.updated.join(', ')}`
72
- : `Marker hook scripts in ${dest} are already current.`);
73
- if (result.removedFromUser > 0) {
74
- console.log(`Removed ${result.removedFromUser} marker hook entries from ${result.userSettings} — ` +
75
- 'your managed settings deliver them now.');
85
+ ? `Installed Mainwave hook scripts in ${dest}: ${result.updated.join(', ')}`
86
+ : `Mainwave hook scripts in ${dest} are already current.`);
87
+ if (result.userSettings === undefined) {
88
+ console.log("CLAUDE_CODE_SUBPROCESS_ENV_SCRUB hid this session's CLAUDE_CONFIG_DIR and the hook input " +
89
+ "didn't name it, so no Claude config dir's settings were changed.");
90
+ }
91
+ else if (result.removedFromUser > 0 || result.addedToUser > 0) {
92
+ console.log(`Updated the Mainwave hooks in ${result.userSettings}` +
93
+ (result.removedFromUser > 0 && result.managedDelivers
94
+ ? ' — your managed settings deliver some of them now.'
95
+ : '.'));
76
96
  }
77
97
  else if (!result.managedDelivers) {
78
- console.log('No managed settings deliver the marker hooks, so your user settings were left as they are.');
98
+ console.log('No managed settings deliver the Mainwave hooks, so your user settings were left as they are.');
79
99
  }
80
100
  return 0;
81
101
  };
102
+ const HOOK_INPUT_CAP = 1024 * 1024;
103
+ const HOOK_INPUT_WAIT_MS = 2000;
104
+ const TRUTHY = new Set(['1', 'true', 'yes', 'on']);
105
+ export const readHookInput = (stream, cap = HOOK_INPUT_CAP, ms = HOOK_INPUT_WAIT_MS) => new Promise((done) => {
106
+ if (stream.isTTY) {
107
+ done(undefined);
108
+ return;
109
+ }
110
+ const chunks = [];
111
+ let size = 0;
112
+ let settled = false;
113
+ const finish = (value, stop = false) => {
114
+ if (settled)
115
+ return;
116
+ settled = true;
117
+ clearTimeout(timer);
118
+ stream.off('data', onData);
119
+ stream.off('end', onEnd);
120
+ stream.off('error', onError);
121
+ if (stop)
122
+ stream.destroy();
123
+ done(value);
124
+ };
125
+ const onData = (chunk) => {
126
+ const buf = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
127
+ size += buf.length;
128
+ if (size > cap)
129
+ finish(undefined, true);
130
+ else
131
+ chunks.push(buf);
132
+ };
133
+ const onEnd = () => {
134
+ try {
135
+ finish(JSON.parse(Buffer.concat(chunks).toString('utf8')));
136
+ }
137
+ catch {
138
+ finish(undefined);
139
+ }
140
+ };
141
+ const onError = () => finish(undefined);
142
+ const timer = setTimeout(() => finish(undefined, true), ms);
143
+ stream.on('data', onData);
144
+ stream.on('end', onEnd);
145
+ stream.on('error', onError);
146
+ });
147
+ export const configDirFromTranscript = (transcriptPath) => {
148
+ if (typeof transcriptPath !== 'string' || !isAbsolute(transcriptPath))
149
+ return undefined;
150
+ if (!transcriptPath.endsWith('.jsonl'))
151
+ return undefined;
152
+ const projects = dirname(dirname(transcriptPath));
153
+ return basename(projects) === 'projects' ? resolve(dirname(projects)) : undefined;
154
+ };
155
+ export const sessionConfigDir = async (env = process.env, stdin = process.stdin) => {
156
+ const scrubbed = TRUTHY.has((env.CLAUDE_CODE_SUBPROCESS_ENV_SCRUB ?? '').trim().toLowerCase());
157
+ if (!scrubbed || env.CLAUDE_CONFIG_DIR?.trim() || stdin.isTTY)
158
+ return claudeConfigDir(env);
159
+ const input = await readHookInput(stdin);
160
+ const transcript = input !== null && typeof input === 'object'
161
+ ? input.transcript_path
162
+ : undefined;
163
+ return configDirFromTranscript(transcript);
164
+ };
@@ -1,3 +1,4 @@
1
+ import { managedSnapshotDelivery, planSnapshotBlocked } from './apply.js';
1
2
  import { WizardAbort } from './errors.js';
2
3
  import { color } from './format.js';
3
4
  import { nativeIdentityReason } from './effective-settings.js';
@@ -70,12 +71,44 @@ export const noIdentityWarning = (headerTools, nonOauth) => {
70
71
  ' Fix: re-run setup with `--email you@company.com`, or sign in first (`mainwave-cli login`).' +
71
72
  (nonOauth.length > 0 ? ' For Claude Code, signing in with a Claude account also fixes it.' : ''));
72
73
  };
73
- const resolveOptIns = (input) => input.overrides.optIns ?? { userPrompts: true, toolDetails: true, toolContent: true };
74
+ const resolveOptIns = (input) => input.overrides.optIns ?? {
75
+ userPrompts: true,
76
+ toolDetails: true,
77
+ toolContent: true,
78
+ repository: true,
79
+ };
74
80
  const resolveMarkers = (input, capable) => {
75
81
  if (input.overrides.markers !== undefined)
76
82
  return input.overrides.markers;
77
83
  return capable.length > 0;
78
84
  };
85
+ const sayPlanSnapshotNotice = (adapters, markers, blocked = new Map(), orgSends = []) => {
86
+ const hosts = adapters.filter((a) => a.markers?.planSnapshotDisclosure !== undefined);
87
+ if (hosts.length === 0)
88
+ return;
89
+ if (!markers) {
90
+ for (const a of hosts) {
91
+ say(orgSends.includes(a)
92
+ ? color.yellow(`Claude plan snapshot is ON for ${a.displayName}: --no-markers installs no Mainwave hooks, ` +
93
+ "but your organization's managed settings send it; only your Claude admin can remove it.")
94
+ : color.dim(`Claude plan snapshot is off for ${a.displayName}: --no-markers installs no Mainwave hooks.`));
95
+ }
96
+ return;
97
+ }
98
+ for (const a of hosts) {
99
+ const why = blocked.get(a);
100
+ if (why) {
101
+ say(color.yellow(`Claude plan snapshot can't run for ${a.displayName}: ${why.reason}. ` +
102
+ (why.notInstalled
103
+ ? 'Setup installs no Mainwave hooks there, so nothing is sent. '
104
+ : "Setup installs it in your user settings, but Claude Code won't run it there, so nothing is sent. ") +
105
+ why.fix));
106
+ continue;
107
+ }
108
+ say(color.yellow(`Claude plan snapshot is ON for ${a.displayName}. ${a.markers.planSnapshotDisclosure}\n` +
109
+ '`--no-markers` installs no Mainwave hooks, this included.'));
110
+ }
111
+ };
79
112
  const resolveUseCaseStep = async (input) => {
80
113
  const context = input.session ? { apiUrl: input.apiUrl, token: input.session.token } : undefined;
81
114
  const { useCase } = await resolveUseCase({
@@ -93,6 +126,9 @@ const sayCaptureNotice = (optIns, adapters) => {
93
126
  : undefined,
94
127
  optIns.toolDetails ? 'shell commands and file paths' : undefined,
95
128
  optIns.toolContent ? 'tool result bodies' : undefined,
129
+ optIns.repository && adapters.some((a) => a.name === 'claude-code')
130
+ ? 'repository names (Claude Code)'
131
+ : undefined,
96
132
  ].filter((s) => s !== undefined);
97
133
  const codex = adapters.some((a) => a.name === 'codex');
98
134
  const codexToolsOff = codex && !optIns.toolDetails && !optIns.toolContent;
@@ -102,7 +138,7 @@ const sayCaptureNotice = (optIns, adapters) => {
102
138
  else {
103
139
  say(color.yellow(`Content capture is ON: ${on.join(', ')} will be sent to your collector.\n` +
104
140
  'Turn it off with `--opt-in none`, or pick what you want with\n' +
105
- '`--opt-in prompts,tool-details,tool-content`.' +
141
+ '`--opt-in prompts,tool-details,tool-content,repository`.' +
106
142
  (codex
107
143
  ? '\nFor Codex, keep `--opt-in tool-details` at minimum — without it Codex\n' +
108
144
  'reports no tool names, success or approvals.'
@@ -133,6 +169,13 @@ export const runInterview = async (input) => {
133
169
  sayCaptureNotice(optIns, input.adapters);
134
170
  const capable = input.adapters.filter((a) => a.markers);
135
171
  const markers = resolveMarkers(input, capable);
172
+ const blocked = new Map(markers
173
+ ? (await Promise.all(input.adapters.map(async (a) => [a, await planSnapshotBlocked(a)]))).flatMap(([a, why]) => (why ? [[a, why]] : []))
174
+ : []);
175
+ const orgSends = markers
176
+ ? []
177
+ : (await Promise.all(input.adapters.map(async (a) => [a, await managedSnapshotDelivery(a)]))).flatMap(([a, sends]) => (sends ? [a] : []));
178
+ sayPlanSnapshotNotice(input.adapters, markers, blocked, orgSends);
136
179
  const markerless = input.adapters.filter((a) => !a.markers);
137
180
  if (markerless.length > 0) {
138
181
  say(color.dim(`Ticket & PR markers aren't available for ${markerless
@@ -141,7 +184,14 @@ export const runInterview = async (input) => {
141
184
  'mechanism the CLI can attach to, so "tickets filed" / "PRs created" stay empty.'));
142
185
  }
143
186
  return {
144
- answers: { apiKey, collectorUrl, ucid: useCase?.id, optIns, userEmail, markers },
187
+ answers: {
188
+ apiKey,
189
+ collectorUrl,
190
+ ucid: useCase?.id,
191
+ optIns,
192
+ userEmail,
193
+ markers,
194
+ },
145
195
  useCase,
146
196
  };
147
197
  };