@mainwave/cli 0.8.0 → 0.10.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.
Files changed (42) hide show
  1. package/README.md +169 -42
  2. package/dist/adapters/claude-code.js +23 -4
  3. package/dist/adapters/codex-cli.js +1 -1
  4. package/dist/adapters/cursor.js +4 -2
  5. package/dist/adapters/index.js +3 -0
  6. package/dist/adapters/kiro.js +361 -0
  7. package/dist/core/apply.js +161 -46
  8. package/dist/core/behaviour-hooks.js +7 -7
  9. package/dist/core/codecs/kiro-hooks-json.js +76 -0
  10. package/dist/core/doctor.js +27 -9
  11. package/dist/core/effective-settings.js +10 -0
  12. package/dist/core/entry-script.js +90 -0
  13. package/dist/core/git-bash.js +40 -0
  14. package/dist/core/install-hooks.js +126 -43
  15. package/dist/core/interview.js +114 -16
  16. package/dist/core/markers.js +678 -140
  17. package/dist/core/remove.js +67 -0
  18. package/dist/core/settings.js +32 -6
  19. package/dist/core/skills.js +47 -1
  20. package/dist/core/status.js +2 -1
  21. package/dist/core/wizard.js +64 -3
  22. package/dist/main.js +28 -9
  23. package/hooks/cursor-otlp.mjs +4 -27
  24. package/hooks/github-pr-marker.mjs +35 -22
  25. package/hooks/glab-mr-marker.mjs +795 -0
  26. package/hooks/jira-ticket-marker.mjs +27 -15
  27. package/hooks/kiro-otlp.mjs +570 -0
  28. package/hooks/linear-ticket-marker.mjs +27 -15
  29. package/hooks/mainwave-hook-node.mjs +42 -0
  30. package/hooks/mainwave-hook.mjs +301 -0
  31. package/hooks/marker-core.mjs +368 -41
  32. package/hooks/matchers.json +82 -6
  33. package/hooks/plan-snapshot.mjs +529 -0
  34. package/hooks/stop-failure.mjs +43 -0
  35. package/hooks/vocabulary.d.mts +49 -0
  36. package/hooks/vocabulary.mjs +188 -0
  37. package/package.json +5 -5
  38. package/skills/mainwave-instrument/SKILL.md +21 -7
  39. package/skills/mainwave-instrument/reference/api.md +29 -10
  40. package/skills/mainwave-instrument/reference/frameworks.md +3 -3
  41. package/skills/mainwave-instrument/reference/troubleshooting.md +12 -5
  42. package/skills/mainwave-setup/SKILL.md +47 -12
@@ -0,0 +1,361 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { promises as fsp, readFileSync, statSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { basename, dirname, join } from 'node:path';
5
+ import { envFileCodec } from '../core/codecs/env-file.js';
6
+ import { kiroHooksJsonCodec } from '../core/codecs/kiro-hooks-json.js';
7
+ import { hasBinary, hasPath } from '../core/detect.js';
8
+ import { buildHeaders, HEADER_NAME, headerBearerToken, kvPairsHeaders } from '../core/headers.js';
9
+ import { prepareUpdate, readExistingEnv } from '../core/settings.js';
10
+ import { hookLogDir, installedHooksDir, MANAGED_BY } from '../core/markers.js';
11
+ import { planBlockRemoval } from '../core/skills.js';
12
+ import { VERSION } from '../core/version.js';
13
+ const SOURCE = {
14
+ ide: 'coding_agent.kiro_ide',
15
+ cli: 'coding_agent.kiro_cli',
16
+ };
17
+ export const kiroHome = (env = process.env) => env.KIRO_HOME && env.KIRO_HOME.trim() !== '' ? env.KIRO_HOME : join(homedir(), '.kiro');
18
+ const CONFIG_MANAGED_KEYS = [
19
+ 'OTEL_EXPORTER_OTLP_ENDPOINT',
20
+ 'OTEL_EXPORTER_OTLP_HEADERS',
21
+ 'OTEL_LOG_USER_PROMPTS',
22
+ ];
23
+ export const KIRO_SURFACE_KEY = {
24
+ ide: 'MAINWAVE_KIRO_IDE',
25
+ cli: 'MAINWAVE_KIRO_CLI',
26
+ };
27
+ const ADAPTER_NAME = { ide: 'kiro-ide', cli: 'kiro-cli' };
28
+ const OTHER = { ide: 'cli', cli: 'ide' };
29
+ const CONFIG_GLOBAL = join(homedir(), '.mainwave', 'kiro.env');
30
+ const CONFIG_LOCAL = join('.mainwave', 'kiro.env');
31
+ const HOOKS_FILE = 'mainwave.json';
32
+ const HOOKS_GLOBAL = join(kiroHome(), 'hooks', HOOKS_FILE);
33
+ const HOOKS_LOCAL = join('.kiro', 'hooks', HOOKS_FILE);
34
+ const STEERING_FILE = 'mainwave.md';
35
+ const STEERING_GLOBAL = join(kiroHome(), 'steering', STEERING_FILE);
36
+ export const KIRO_HOOK_SCRIPT = 'kiro-otlp.mjs';
37
+ export const KIRO_TRIGGERS = [
38
+ 'SessionStart',
39
+ 'UserPromptSubmit',
40
+ 'PostToolUse',
41
+ 'PostFileCreate',
42
+ 'PostFileSave',
43
+ 'PostFileDelete',
44
+ 'Stop',
45
+ 'SessionEnd',
46
+ ];
47
+ export const hookKey = (trigger) => `hooks.${trigger}`;
48
+ const HOOKS_MANAGED_KEYS = KIRO_TRIGGERS.map(hookKey);
49
+ export const buildKiroHookCommand = (scriptPath, version, trigger, plat = process.platform) => {
50
+ const args = `${MANAGED_BY}@${version} --trigger ${trigger}`;
51
+ return plat === 'win32'
52
+ ? `cmd /d /s /c ""node" "${scriptPath}" ${args} >NUL 2>&1 & exit /b 0"`
53
+ : `sh -c '[ -f "$0" ] && node "$0" ${args} >/dev/null 2>&1; exit 0' "${scriptPath}"`;
54
+ };
55
+ const hookCommand = (trigger) => buildKiroHookCommand(join(installedHooksDir(), KIRO_HOOK_SCRIPT), VERSION, trigger);
56
+ const stripTrailingSlash = (url) => url.replace(/\/+$/, '');
57
+ const parseHeaders = (raw) => kvPairsHeaders.decode(raw) ?? {};
58
+ export const emailFromWhoami = (stdout) => {
59
+ let parsed;
60
+ try {
61
+ parsed = JSON.parse(stdout);
62
+ }
63
+ catch {
64
+ return undefined;
65
+ }
66
+ const seen = [parsed];
67
+ for (let i = 0; i < seen.length && i < 200; i++) {
68
+ const v = seen[i];
69
+ if (v === null || typeof v !== 'object')
70
+ continue;
71
+ for (const [k, child] of Object.entries(v)) {
72
+ if (typeof child === 'string' &&
73
+ /e-?mail/i.test(k) &&
74
+ /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(child.trim())) {
75
+ return child.trim();
76
+ }
77
+ if (child !== null && typeof child === 'object')
78
+ seen.push(child);
79
+ }
80
+ }
81
+ return undefined;
82
+ };
83
+ export const parseKiroCliVersion = (stdout) => /(\d+)\.(\d+)\.(\d+)/.exec(stdout)?.[0];
84
+ const run = (args) => {
85
+ try {
86
+ const r = spawnSync('kiro-cli', args, { encoding: 'utf8', timeout: 5000 });
87
+ return r.status === 0 ? r.stdout : undefined;
88
+ }
89
+ catch {
90
+ return undefined;
91
+ }
92
+ };
93
+ let whoamiOnce;
94
+ export const KIRO_CLI = {
95
+ version: () => {
96
+ const out = run(['--version']);
97
+ return out === undefined ? undefined : parseKiroCliVersion(out);
98
+ },
99
+ whoamiEmail: () => {
100
+ if (!whoamiOnce) {
101
+ const out = run(['whoami', '--format', 'json']);
102
+ whoamiOnce = { email: out === undefined ? undefined : emailFromWhoami(out) };
103
+ }
104
+ return whoamiOnce.email;
105
+ },
106
+ };
107
+ export const KIRO_CLI_MIN_VERSION = '2.13.0';
108
+ const versionAtLeast = (v, min) => {
109
+ const a = v.split('.').map(Number);
110
+ const b = min.split('.').map(Number);
111
+ for (let i = 0; i < 3; i++) {
112
+ if ((a[i] ?? 0) !== (b[i] ?? 0))
113
+ return (a[i] ?? 0) > (b[i] ?? 0);
114
+ }
115
+ return true;
116
+ };
117
+ export const kiroActivityPath = (home = homedir()) => join(hookLogDir(home), 'kiro.log.ok');
118
+ export const KIRO_STALE_DAYS = 7;
119
+ export const kiroHooksRegistered = (path = HOOKS_GLOBAL) => {
120
+ try {
121
+ const doc = kiroHooksJsonCodec.parse(readFileSync(path, 'utf8'), path);
122
+ return Object.keys(kiroHooksJsonCodec.readEnv(doc)).length > 0;
123
+ }
124
+ catch {
125
+ return false;
126
+ }
127
+ };
128
+ export const kiroActivityIssue = (path = kiroActivityPath(), registered = kiroHooksRegistered(), now = new Date()) => {
129
+ let mtime;
130
+ try {
131
+ mtime = statSync(path).mtime;
132
+ }
133
+ catch {
134
+ mtime = undefined;
135
+ }
136
+ if (mtime && registered && now.getTime() - mtime.getTime() > KIRO_STALE_DAYS * 86_400_000) {
137
+ return {
138
+ level: 'warn',
139
+ message: `The Kiro hooks are registered but the last span was delivered ${mtime.toISOString()}, ` +
140
+ `over ${KIRO_STALE_DAYS} days ago. If you used Kiro since, check ${join(hookLogDir(), 'kiro.log')}.`,
141
+ };
142
+ }
143
+ return mtime
144
+ ? { level: 'info', message: `Last Kiro hook span delivered ${mtime.toISOString()}.` }
145
+ : {
146
+ level: 'info',
147
+ message: 'No Kiro hook span delivered yet. Start a new Kiro session (the hooks load at session start), ' +
148
+ `then check ${join(hookLogDir(), 'kiro.log')} for skips and failures.`,
149
+ };
150
+ };
151
+ export const kiroCliIssues = (version = KIRO_CLI.version()) => {
152
+ const v3 = 'Mainwave records Kiro CLI sessions only in V3 mode (`kiro-cli --v3`); the 2.x default mode ' +
153
+ 'reads hooks from agent configs, not ~/.kiro/hooks/, and is not supported.';
154
+ if (version === undefined) {
155
+ return [
156
+ { level: 'warn', message: `Kiro CLI not found on PATH (\`kiro-cli --version\`). ${v3}` },
157
+ ];
158
+ }
159
+ if (!versionAtLeast(version, KIRO_CLI_MIN_VERSION)) {
160
+ return [
161
+ {
162
+ level: 'error',
163
+ message: `Kiro CLI ${version} is older than ${KIRO_CLI_MIN_VERSION}, which global hooks need. Update Kiro CLI. ${v3}`,
164
+ },
165
+ ];
166
+ }
167
+ return [{ level: 'info', message: `Kiro CLI ${version}. ${v3}` }];
168
+ };
169
+ export const planKiroRemoval = async (removing, paths = {
170
+ config: CONFIG_GLOBAL,
171
+ hooks: HOOKS_GLOBAL,
172
+ steering: STEERING_GLOBAL,
173
+ }) => {
174
+ const env = (await readExistingEnv(paths.config, envFileCodec)) ?? {};
175
+ const surfaces = ['ide', 'cli'].filter((s) => env[KIRO_SURFACE_KEY[s]] === '1');
176
+ const source = parseHeaders(env.OTEL_EXPORTER_OTLP_HEADERS ?? '')[HEADER_NAME.source];
177
+ const installed = surfaces.length > 0
178
+ ? surfaces
179
+ : source === SOURCE.cli
180
+ ? ['cli']
181
+ : source === SOURCE.ide
182
+ ? ['ide']
183
+ : [];
184
+ const asked = ['ide', 'cli'].filter((s) => removing.includes(ADAPTER_NAME[s]));
185
+ const steps = installed.length === 0
186
+ ? []
187
+ : asked
188
+ .filter((s) => !installed.includes(s))
189
+ .map((s) => ({ kind: 'note', note: `${ADAPTER_NAME[s]} isn't set up.` }));
190
+ const removed = installed.length === 0 ? asked : asked.filter((s) => installed.includes(s));
191
+ if (removed.length === 0)
192
+ return steps;
193
+ const remaining = installed.filter((s) => !removed.includes(s));
194
+ if (remaining.length > 0) {
195
+ const update = await prepareUpdate({
196
+ path: paths.config,
197
+ newEnv: Object.fromEntries(removed.map((s) => [KIRO_SURFACE_KEY[s], '0'])),
198
+ managedKeys: removed.map((s) => KIRO_SURFACE_KEY[s]),
199
+ codec: envFileCodec,
200
+ });
201
+ steps.push({
202
+ kind: 'update',
203
+ update,
204
+ note: `${paths.config}: drop ${removed.map((s) => ADAPTER_NAME[s]).join(', ')}; the hooks stay for ${remaining.map((s) => ADAPTER_NAME[s]).join(', ')}`,
205
+ });
206
+ return steps;
207
+ }
208
+ const hooks = await prepareUpdate({
209
+ path: paths.hooks,
210
+ newEnv: {},
211
+ managedKeys: HOOKS_MANAGED_KEYS,
212
+ codec: kiroHooksJsonCodec,
213
+ mode: 0o644,
214
+ });
215
+ const left = hooks.next.hooks ?? [];
216
+ if (hooks.exists) {
217
+ steps.push(left.length === 0
218
+ ? {
219
+ kind: 'delete',
220
+ path: paths.hooks,
221
+ note: `${paths.hooks}: delete (only Mainwave hooks in it)`,
222
+ }
223
+ : {
224
+ kind: 'update',
225
+ update: hooks,
226
+ note: `${paths.hooks}: remove the Mainwave hooks, keep ${left.length} other`,
227
+ });
228
+ }
229
+ const steering = await planBlockRemoval(paths.steering);
230
+ if (steering)
231
+ steps.push(steering);
232
+ if ((await readExistingEnv(paths.config, envFileCodec)) !== null) {
233
+ steps.push({
234
+ kind: 'delete',
235
+ path: paths.config,
236
+ backup: false,
237
+ note: `${paths.config}: delete`,
238
+ });
239
+ }
240
+ const prefix = `${basename(paths.config)}.bak.`;
241
+ const backups = await fsp.readdir(dirname(paths.config)).catch(() => []);
242
+ for (const name of backups.filter((n) => n.startsWith(prefix)).sort()) {
243
+ const path = join(dirname(paths.config), name);
244
+ steps.push({ kind: 'delete', path, backup: false, note: `${path}: delete (holds the API key)` });
245
+ }
246
+ return steps;
247
+ };
248
+ const kiroAdapter = (surface) => {
249
+ const source = SOURCE[surface];
250
+ const buildEnv = ({ collectorUrl, apiKey, optIns, userEmail, passAdapters, }) => ({
251
+ OTEL_EXPORTER_OTLP_ENDPOINT: stripTrailingSlash(collectorUrl),
252
+ OTEL_EXPORTER_OTLP_HEADERS: kvPairsHeaders.encode(buildHeaders({ apiKey, source, userEmail })),
253
+ ...(optIns.userPrompts ? { OTEL_LOG_USER_PROMPTS: '1' } : {}),
254
+ [KIRO_SURFACE_KEY[surface]]: '1',
255
+ ...(passAdapters?.includes(ADAPTER_NAME[OTHER[surface]])
256
+ ? { [KIRO_SURFACE_KEY[OTHER[surface]]]: '1' }
257
+ : {}),
258
+ });
259
+ const parseEnv = (env) => {
260
+ if (!CONFIG_MANAGED_KEYS.some((k) => k in env))
261
+ return {};
262
+ const out = {};
263
+ const endpoint = env.OTEL_EXPORTER_OTLP_ENDPOINT;
264
+ if (endpoint)
265
+ out.collectorUrl = stripTrailingSlash(endpoint);
266
+ const raw = env.OTEL_EXPORTER_OTLP_HEADERS;
267
+ if (raw) {
268
+ const headers = parseHeaders(raw);
269
+ const token = headerBearerToken(headers[HEADER_NAME.authorization]);
270
+ if (token)
271
+ out.apiKey = token;
272
+ const email = headers[HEADER_NAME.userEmail];
273
+ if (email)
274
+ out.userEmail = email;
275
+ }
276
+ out.optIns = {
277
+ userPrompts: env.OTEL_LOG_USER_PROMPTS === '1',
278
+ toolDetails: true,
279
+ toolContent: true,
280
+ };
281
+ return out;
282
+ };
283
+ const normalizeForGenericChecks = (env) => {
284
+ const raw = env.OTEL_EXPORTER_OTLP_HEADERS;
285
+ return {
286
+ endpoint: env.OTEL_EXPORTER_OTLP_ENDPOINT,
287
+ auth: raw ? parseHeaders(raw)[HEADER_NAME.authorization] : undefined,
288
+ ucid: undefined,
289
+ };
290
+ };
291
+ const hooksWrite = {
292
+ id: 'kiro-hooks',
293
+ label: 'Kiro hooks',
294
+ codec: kiroHooksJsonCodec,
295
+ path: HOOKS_GLOBAL,
296
+ localPath: HOOKS_LOCAL,
297
+ mode: 0o644,
298
+ managedKeys: HOOKS_MANAGED_KEYS,
299
+ build: () => Object.fromEntries(KIRO_TRIGGERS.map((t) => [hookKey(t), hookCommand(t)])),
300
+ parse: () => ({}),
301
+ };
302
+ const collectChecks = () => [
303
+ {
304
+ level: 'info',
305
+ message: 'Kiro hooks carry session behaviour only (sessions, prompts, tool calls, file operations) — ' +
306
+ "no tokens or cost; those come from Kiro's enterprise usage export, when your org has it.",
307
+ },
308
+ ...(surface === 'cli' ? kiroCliIssues() : []),
309
+ kiroActivityIssue(),
310
+ ];
311
+ return {
312
+ name: surface === 'ide' ? 'kiro-ide' : 'kiro-cli',
313
+ displayName: surface === 'ide' ? 'Kiro IDE' : 'Kiro CLI',
314
+ paths: {
315
+ local: CONFIG_LOCAL,
316
+ global: CONFIG_GLOBAL,
317
+ localIgnored: `The Kiro hook ignores ${CONFIG_LOCAL}: it reads only ~/.mainwave/kiro.env`,
318
+ },
319
+ instructionSurface: {
320
+ kind: 'instructions-file',
321
+ global: STEERING_GLOBAL,
322
+ local: join('.kiro', 'steering', STEERING_FILE),
323
+ label: 'steering file',
324
+ },
325
+ runInstruction: surface === 'ide'
326
+ ? 'Kiro (start a new session so the hooks load)'
327
+ : 'kiro-cli --v3 (start a new session so the hooks load)',
328
+ detect: surface === 'ide'
329
+ ? () => hasBinary('kiro') ||
330
+ hasPath('/Applications/Kiro.app') ||
331
+ hasPath(join(homedir(), 'Applications', 'Kiro.app'))
332
+ : () => hasBinary('kiro-cli'),
333
+ injectsIdentity: true,
334
+ carriesNoUcid: true,
335
+ defaultOptIns: { userPrompts: false },
336
+ removal: { group: 'kiro', plan: (removing) => planKiroRemoval(removing) },
337
+ detectIdentityEmail: () => KIRO_CLI.whoamiEmail(),
338
+ codec: envFileCodec,
339
+ managedEnvKeys: [...CONFIG_MANAGED_KEYS, KIRO_SURFACE_KEY[surface]],
340
+ hierarchy: [{ id: 'user', label: 'User (global)', path: CONFIG_GLOBAL, kind: 'file' }],
341
+ hookReadsConfigFile: true,
342
+ buildEnv,
343
+ parseEnv,
344
+ collectChecks,
345
+ normalizeForGenericChecks,
346
+ additionalWrites: [hooksWrite],
347
+ bundledHookScripts: ['marker-core.mjs', 'vocabulary.mjs', KIRO_HOOK_SCRIPT],
348
+ behaviourHooks: {
349
+ toolName: 'Kiro',
350
+ setupCommand: `mainwave-cli setup ${surface === 'ide' ? 'kiro-ide' : 'kiro-cli'}`,
351
+ layers: [
352
+ { id: 'project', label: 'Workspace', path: HOOKS_LOCAL, kind: 'file' },
353
+ { id: 'user', label: 'User (global)', path: HOOKS_GLOBAL, kind: 'file' },
354
+ ],
355
+ codec: kiroHooksJsonCodec,
356
+ script: KIRO_HOOK_SCRIPT,
357
+ },
358
+ };
359
+ };
360
+ export const kiroIde = kiroAdapter('ide');
361
+ export const kiroCli = kiroAdapter('cli');
@@ -1,9 +1,10 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { basename, resolve } from 'node:path';
2
+ import { dirname, resolve } from 'node:path';
3
3
  import { adapters } from '../adapters/index.js';
4
- import { activeHierarchy } from './effective-settings.js';
4
+ import { activeHierarchy, effectiveEnv } from './effective-settings.js';
5
5
  import { color, renderDiff } from './format.js';
6
- import { buildHookGroups, copyHookScripts, activeManagedScans, describeMarkersPlan, managedMarkerScripts, hookScriptFiles, planMarkers, prepareMarkersFile, readPackagedMatchers, hooksBlocked, scriptPathFromCommand, scanForMarkers, } from './markers.js';
6
+ import { claudeHookShellMissing, GIT_BASH_FIX, GIT_BASH_MISSING_REASON } from './git-bash.js';
7
+ import { activeManagedScans, BOOTSTRAP_KEY, commandGeneration, copyHookScripts, DEFAULT_MARKER_TOOL, describeMarkersPlan, hooksBlocked, hostRunsBootstrap, installedHooksDir, isPlanSnapshot, isPlanSnapshotRoute, legacyCommandSends, managedDeliversEntry, managedDeliversPlanSnapshot, managedHooksDir, managedMarkerDeliveries, matchersForTool, packagedHooksDir, planMarkers, prepareMarkersFile, readPackagedMatchers, routeLabel, scanForMarkers, scanRoutes, selectHookMatchers, syncManagedHooks, syncOrgDelivered, userHookGroups, writeOptOutFlags, } from './markers.js';
7
8
  import { isManagedLayer } from './layer-policy.js';
8
9
  import { adapterEffective } from './status.js';
9
10
  import { applyUpdate, prepareUpdate, readExistingEnv } from './settings.js';
@@ -65,25 +66,30 @@ const decideTeamUcid = async (adapter, existing, stored) => {
65
66
  }
66
67
  return { status: 'kept', id: existing };
67
68
  };
69
+ export const effectiveOptIns = (adapter, optIns, explicit) => explicit ? optIns : { ...optIns, ...adapter.defaultOptIns };
68
70
  export const planAdapter = async (adapter, answers, context = {}) => {
69
71
  const { primary, additional } = writeTargets(adapter);
70
- const explicit = answers.ucid !== undefined;
72
+ const explicitUcid = adapter.carriesNoUcid ? undefined : answers.ucid;
73
+ const explicit = explicitUcid !== undefined;
71
74
  const pin = context.unpin ? undefined : context.storedUseCase;
72
75
  const needsDisk = !explicit && (pin?.pinned === true || adapter.teamUcid === true);
73
76
  const onDiskUcid = needsDisk
74
77
  ? (context.onDisk ?? (await readPrefill(adapter)).values).ucid
75
78
  : undefined;
76
- const keptPin = !explicit && pin?.pinned === true && onDiskUcid === pin.id;
79
+ const keptPin = !adapter.carriesNoUcid && !explicit && pin?.pinned === true && onDiskUcid === pin.id;
77
80
  const teamUcid = adapter.teamUcid && !explicit && !keptPin
78
81
  ?
79
82
  await decideTeamUcid(adapter, onDiskUcid, context.storedUseCase && { ...context.storedUseCase, pinned: pin?.pinned })
80
83
  : undefined;
81
84
  const input = {
82
- ucid: answers.ucid ?? (keptPin ? pin.id : teamUcid?.id),
85
+ ucid: explicitUcid ?? (keptPin ? pin.id : teamUcid?.id),
83
86
  collectorUrl: answers.collectorUrl,
84
87
  apiKey: answers.apiKey,
85
- optIns: answers.optIns,
86
- userEmail: adapter.injectsIdentity || adapter.stampsIdentityAttr ? answers.userEmail : undefined,
88
+ ...(context.pass ? { passAdapters: context.pass } : {}),
89
+ optIns: effectiveOptIns(adapter, answers.optIns, answers.optInsExplicit === true),
90
+ userEmail: adapter.injectsIdentity || adapter.stampsIdentityAttr
91
+ ? (answers.adapterEmails?.[adapter.name] ?? answers.userEmail)
92
+ : undefined,
87
93
  };
88
94
  const primaryUpdate = await prepareUpdate({
89
95
  path: primary,
@@ -92,19 +98,38 @@ export const planAdapter = async (adapter, answers, context = {}) => {
92
98
  codec: adapter.codec,
93
99
  });
94
100
  const markersOn = adapter.markers ? answers.markers : null;
101
+ let planSnapshotOn = null;
102
+ let planSnapshotOrgDelivered = false;
95
103
  let markersPlan = null;
96
- let hookFiles = [];
97
104
  let separateMarkersUpdate = null;
98
105
  let markersCarrier = null;
106
+ let hookHost = null;
107
+ let stageHooks = false;
108
+ let hookEvents = [];
109
+ let orgDeliversEntry = false;
110
+ let hookShellMissing = false;
99
111
  if (markersOn !== null) {
100
- const matchers = await readPackagedMatchers();
101
- hookFiles = hookScriptFiles(matchers);
102
- const delivered = adapter.markers?.hooksFile
103
- ? new Set()
104
- : managedMarkerScripts(await scanForMarkers((await activeHierarchy(adapter)).filter(isManagedLayer)));
105
- const groups = markersOn
106
- ? buildHookGroups(matchers.filter((m) => !delivered.has(m.hook)), VERSION, undefined, undefined, adapter.markers?.runtimeTool)
107
- : [];
112
+ hookHost = adapter.markers?.runtimeTool ?? DEFAULT_MARKER_TOOL;
113
+ const hosted = matchersForTool(await readPackagedMatchers(), hookHost);
114
+ if (hosted.some(isPlanSnapshot))
115
+ planSnapshotOn = markersOn;
116
+ hookShellMissing = await hookShellMissingFor(adapter, async () => effectiveEnv(adapter, adapter.codec.readEnv(primaryUpdate.next)));
117
+ const on = { markers: markersOn };
118
+ const selected = hookShellMissing ? [] : selectHookMatchers(hosted, on);
119
+ stageHooks = selected.length > 0;
120
+ hookEvents = [
121
+ ...new Set([
122
+ ...(stageHooks && hostRunsBootstrap(hookHost) ? ['SessionStart'] : []),
123
+ ...selected.map((m) => m.event),
124
+ ]),
125
+ ];
126
+ const managedScans = adapter.markers?.hooksFile
127
+ ? []
128
+ : await scanForMarkers((await activeHierarchy(adapter)).filter(isManagedLayer));
129
+ const delivered = managedMarkerDeliveries(managedScans);
130
+ orgDeliversEntry = managedDeliversEntry(managedScans);
131
+ planSnapshotOrgDelivered = planSnapshotOn !== null && managedDeliversPlanSnapshot(managedScans);
132
+ const groups = hookShellMissing ? [] : userHookGroups(hosted, on, delivered, hookHost);
108
133
  const hooksFile = adapter.markers?.hooksFile;
109
134
  if (hooksFile) {
110
135
  const prepared = await prepareMarkersFile(hooksFile.path, hooksFile.codec, groups);
@@ -113,7 +138,14 @@ export const planAdapter = async (adapter, answers, context = {}) => {
113
138
  markersCarrier = prepared.update;
114
139
  }
115
140
  else {
116
- markersPlan = planMarkers(primaryUpdate.next, groups);
141
+ const keepRunnable = (o, g) => !(markersOn &&
142
+ o === 'cli' &&
143
+ commandGeneration(g.command) === 'legacy' &&
144
+ legacyCommandSends(g.command) &&
145
+ /^node "/.test(g.command));
146
+ markersPlan = hookShellMissing
147
+ ? planMarkers(primaryUpdate.next, groups, keepRunnable)
148
+ : planMarkers(primaryUpdate.next, groups);
117
149
  primaryUpdate.next = markersPlan.next;
118
150
  markersCarrier = primaryUpdate;
119
151
  }
@@ -143,14 +175,59 @@ export const planAdapter = async (adapter, answers, context = {}) => {
143
175
  input,
144
176
  changed,
145
177
  markersOn,
178
+ planSnapshotOn,
179
+ planSnapshotOrgDelivered,
146
180
  markersPlan,
147
181
  markersCarrier,
148
- hookFiles,
182
+ hookHost,
183
+ stageHooks,
184
+ hookEvents,
185
+ orgDeliversEntry,
186
+ hookShellMissing,
149
187
  ...(teamUcid ? { teamUcid } : {}),
150
188
  ...(keptPin ? { keptPin: pin } : {}),
151
189
  };
152
190
  };
191
+ export const hookShellMissingFor = async (adapter, settingsEnv) => {
192
+ if (process.platform !== 'win32')
193
+ return false;
194
+ const markers = adapter.markers;
195
+ if (markers === undefined || markers.hooksFile !== undefined)
196
+ return false;
197
+ if ((markers.runtimeTool ?? DEFAULT_MARKER_TOOL) !== DEFAULT_MARKER_TOOL)
198
+ return false;
199
+ return claudeHookShellMissing({ ...process.env, ...((await settingsEnv()) ?? {}) });
200
+ };
201
+ export const managedSnapshotDelivery = async (adapter) => {
202
+ if (!adapter.markers?.planSnapshotDisclosure || adapter.markers.hooksFile)
203
+ return false;
204
+ const managed = (await activeHierarchy(adapter)).filter(isManagedLayer);
205
+ return managedDeliversPlanSnapshot(await scanForMarkers(managed));
206
+ };
207
+ export const planSnapshotBlocked = async (adapter) => {
208
+ if (!adapter.markers?.planSnapshotDisclosure || adapter.markers.hooksFile)
209
+ return undefined;
210
+ if (await hookShellMissingFor(adapter, () => effectiveEnv(adapter))) {
211
+ return { reason: GIT_BASH_MISSING_REASON, fix: GIT_BASH_FIX, notInstalled: true };
212
+ }
213
+ const scans = await scanForMarkers(await activeHierarchy(adapter));
214
+ const blocked = hooksBlocked(scans);
215
+ if (blocked.developer === undefined)
216
+ return undefined;
217
+ if (blocked.managed === undefined && managedDeliversPlanSnapshot(scans))
218
+ return undefined;
219
+ const fix = blocked.managed !== undefined
220
+ ? 'Only your Claude admin can turn hooks back on.'
221
+ : blocked.managedOnly
222
+ ? 'Ask your Claude admin to deliver it through managed settings.'
223
+ : 'Remove disableAllHooks from that file to let it run.';
224
+ return { reason: blocked.developer, fix };
225
+ };
153
226
  export const renderPlan = (plan) => {
227
+ for (const { message } of plan.markersPlan?.skipped ?? []) {
228
+ say('');
229
+ say(color.yellow(`! ${plan.adapter.displayName}: ${message}`));
230
+ }
154
231
  if (plan.changed.length === 0) {
155
232
  say('');
156
233
  say(color.dim(`${plan.adapter.displayName}: no changes needed in ${plan.primaryPath}.`));
@@ -175,17 +252,30 @@ export const renderPlan = (plan) => {
175
252
  }
176
253
  };
177
254
  export const planHasChanges = (plans) => plans.some((p) => p.changed.length > 0);
178
- export const writePlan = async (plan) => {
179
- const scripts = [
180
- ...(plan.markersOn ? plan.hookFiles : []),
181
- ...(plan.adapter.bundledHookScripts ?? []),
182
- ];
183
- if (scripts.length > 0) {
184
- const dest = await copyHookScripts(scripts);
255
+ const defaultHookDirs = () => ({
256
+ managedDir: managedHooksDir(),
257
+ flatDir: installedHooksDir(),
258
+ });
259
+ export const userHooksPath = (adapter) => adapter.markers?.hooksFile?.path ?? adapter.paths.global;
260
+ export const writePlan = async (plan, dirs = defaultHookDirs()) => {
261
+ if (plan.stageHooks) {
262
+ const updated = await syncManagedHooks(await readPackagedMatchers(), packagedHooksDir(), dirs.managedDir, VERSION);
185
263
  say('');
186
- say(plan.changed.length === 0
187
- ? color.dim(`Hook scripts refreshed in ${dest}.`)
188
- : color.green(`✓ Hook scripts installed to ${dest}`));
264
+ say(updated.length === 0
265
+ ? color.dim(`Hook scripts in ${dirs.managedDir} are current.`)
266
+ : color.green(`✓ Hook scripts installed to ${dirs.managedDir}`));
267
+ }
268
+ if (plan.hookHost !== null) {
269
+ await writeOptOutFlags(plan.hookHost, { markers: plan.markersOn ?? undefined }, resolve(dirs.managedDir, '..'));
270
+ if (plan.hookHost === DEFAULT_MARKER_TOOL) {
271
+ await syncOrgDelivered(plan.orgDeliversEntry, dirname(plan.adapter.paths.global), dirs.managedDir);
272
+ }
273
+ }
274
+ const bundled = plan.adapter.bundledHookScripts ?? [];
275
+ if (bundled.length > 0) {
276
+ const dest = await copyHookScripts(bundled, packagedHooksDir(), dirs.flatDir);
277
+ say('');
278
+ say(color.dim(`Hook scripts refreshed in ${dest}.`));
189
279
  }
190
280
  for (const { update } of plan.changed) {
191
281
  const result = await applyUpdate(update);
@@ -202,10 +292,7 @@ export const printMarkerCoexistenceNotes = async (adapter, targetPath, markersOn
202
292
  const blockedBy = hooksBlocked(scans);
203
293
  const blocked = blockedBy.developer;
204
294
  const targetHasMarkers = scans.some((s) => resolve(s.path) === resolve(targetPath) && s.groups.some((g) => g.ownership === 'cli'));
205
- if (markersOn &&
206
- blocked !== undefined &&
207
- targetHasMarkers &&
208
- adapter.markers?.hooksFile === undefined) {
295
+ if (blocked !== undefined && targetHasMarkers && adapter.markers?.hooksFile === undefined) {
209
296
  say('');
210
297
  say(color.yellow(`Note: Claude Code won't run the marker hooks in ${targetPath}: ${blocked}.`));
211
298
  }
@@ -217,16 +304,33 @@ export const printMarkerCoexistenceNotes = async (adapter, targetPath, markersOn
217
304
  for (const s of others) {
218
305
  const hasInternal = cliRuns && runs(s) && s.groups.some((g) => g.ownership === 'internal');
219
306
  const hasCli = s.groups.some((g) => g.ownership === 'cli');
220
- const scripts = s.groups
221
- .filter((g) => g.ownership === 'cli')
222
- .map((g) => basename(scriptPathFromCommand(g.command) ?? g.command));
223
- if (hasCli && s.managed) {
224
- say('');
225
- say(color.dim(markersOn
226
- ? `Note: your organization's managed settings (${s.path}) deliver ${scripts.join(', ')},\n` +
227
- 'so setup left those out of your user settings to avoid marking each ticket and PR twice.'
228
- : `Note: your organization's managed settings (${s.path}) still run the marker hooks;\n` +
229
- '--no-markers removes only the copy in your user settings.'));
307
+ const routes = scanRoutes(s).filter((k) => k !== BOOTSTRAP_KEY);
308
+ const leftOut = markersOn ? routes : [];
309
+ const stillRun = markersOn ? [] : routes;
310
+ if (hasCli && s.managed && routes.length === 0) {
311
+ }
312
+ else if (hasCli && s.managed) {
313
+ if (leftOut.length > 0) {
314
+ const leftMarkers = leftOut.some((k) => !isPlanSnapshotRoute(k));
315
+ const leftSnapshot = leftOut.some(isPlanSnapshotRoute);
316
+ const twice = [
317
+ ...(leftMarkers ? ['marking each ticket and PR'] : []),
318
+ ...(leftSnapshot ? ['sending the plan snapshot'] : []),
319
+ ].join(' or ');
320
+ say('');
321
+ say(color.dim(`Note: your organization's managed settings (${s.path}) deliver ${leftOut.map(routeLabel).join(', ')},\n` +
322
+ `so setup left those out of your user settings to avoid ${twice} twice.`));
323
+ }
324
+ if (stillRun.length > 0) {
325
+ const markerRun = stillRun.some((k) => !isPlanSnapshotRoute(k));
326
+ const snapshotRun = stillRun.some(isPlanSnapshotRoute);
327
+ say('');
328
+ say(color.dim(`Note: your organization's managed settings (${s.path}) still run the ${markerRun
329
+ ? snapshotRun
330
+ ? 'marker hooks and the plan snapshot'
331
+ : 'marker hooks'
332
+ : 'plan snapshot'};\n--no-markers removes only the copy in your user settings.`));
333
+ }
230
334
  }
231
335
  else if (hasInternal) {
232
336
  say('');
@@ -237,17 +341,28 @@ export const printMarkerCoexistenceNotes = async (adapter, targetPath, markersOn
237
341
  }
238
342
  else if (hasCli) {
239
343
  say('');
240
- say(color.dim(`Note: ${s.path} also carries CLI-managed marker hooks. Identical handlers run\n` +
344
+ say(color.dim(`Note: ${s.path} also carries CLI-managed Mainwave hooks. Identical handlers run\n` +
241
345
  'once, so counts stay correct; `mainwave-cli doctor` flags them if they drift.'));
242
346
  }
243
347
  }
244
348
  };
245
349
  export const printPostSetup = (plan) => {
246
- if (plan.markersOn === true && plan.adapter.markers) {
350
+ if (plan.hookShellMissing && plan.markersOn === true) {
351
+ say('');
352
+ say(color.yellow(`No Mainwave hooks installed for ${plan.adapter.displayName}: ${GIT_BASH_MISSING_REASON}. ${GIT_BASH_FIX}`));
353
+ }
354
+ else if (plan.markersOn === true && plan.adapter.markers) {
247
355
  say('');
248
356
  say(color.dim(`Ticket & PR markers installed for ${plan.adapter.displayName}. ` +
249
357
  `${plan.adapter.markers.disclosure}\n` +
250
- `Remove them with \`mainwave-cli setup ${plan.adapter.name} --no-markers\`.`));
358
+ `Remove them${plan.planSnapshotOn === true ? ' and the Claude plan snapshot' : ''} with ` +
359
+ `\`mainwave-cli setup ${plan.adapter.name} --no-markers\`, which installs no Mainwave hooks.`));
360
+ }
361
+ if (plan.hookEvents.includes('SessionStart')) {
362
+ say('');
363
+ say(color.dim(`${plan.adapter.displayName} also runs \`npx @mainwave/cli@latest install-hooks\` in the background when a session ` +
364
+ 'starts, resumes or forks: it refreshes the hook scripts from the latest release and keeps the hooks above ' +
365
+ 'current, on the same events only — a new kind of hook waits for your next setup run.'));
251
366
  }
252
367
  const snippet = plan.adapter.printPostSetupInstructions?.(plan.input, 'global');
253
368
  if (snippet) {