@evomap/evolver-cli 2.0.0-beta.5 → 2.0.0-beta.7

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.
@@ -4,10 +4,12 @@
4
4
  // (the real device-wide scope); `--scope=project` (default) writes the project's own .mcp.json. Deny-nothing:
5
5
  // it only writes the runtime's own config, is idempotent, refuses symlinked adapter paths, and `--uninstall`
6
6
  // cleanly removes only evolver's entries.
7
- import { planInjection, installInjection, uninstallInjection, runtimeSupport, renderManualWiring, renderServiceGuidance, SETUP_RUNTIMES, SERVICE_TARGETS } from '@evomap/evolver-mcp';
7
+ import { planInjection, installInjection, uninstallInjection, runtimeSupport, renderManualWiring, renderServiceGuidance, SETUP_RUNTIMES, SERVICE_TARGETS, kiroConfigRoot, resolveOpenCodeConfig, McpConfigConflictError, McpConfigOwnershipError, McpConfigVerificationError, McpServerValidationError } from '@evomap/evolver-mcp';
8
8
  import { assetstore, events } from '@evomap/evolver-core';
9
- import { readFileSync } from 'node:fs';
9
+ import { accessSync, constants, existsSync, readFileSync, statSync } from 'node:fs';
10
10
  import { createRequire } from 'node:module';
11
+ import { homedir } from 'node:os';
12
+ import { delimiter, dirname, isAbsolute, join, relative, sep } from 'node:path';
11
13
  import { fileURLToPath } from 'node:url';
12
14
  import { currentTopCursorGenes } from './cursorRewrite.js';
13
15
  import { resolveProxyBinPath, resolveStableNodePath } from './lifecycle.js';
@@ -34,7 +36,133 @@ function parseFlags(argv) {
34
36
  }
35
37
  return out;
36
38
  }
37
- const USAGE = `usage: evolver setup-hooks [--runtime=${SETUP_RUNTIMES.join('|')}] [--scope=user|project|global] [--root=<dir>] [--env-file=<path>] [--profile-descriptor=<json>] [--service=${SERVICE_TARGETS.join('|')}] [--uninstall] [--force] [--json] [--hook-command="evolver inject session-start"] [--server-command=<cmd>] [--server-args=a,b] [--service-command=<cmd>] [--service-args=a,b]\n`;
39
+ const USAGE = `usage: evolver setup-hooks [--runtime=${SETUP_RUNTIMES.join('|')}] [--scope=user|project|global] [--root=<dir>] [--env-file=<path>] [--profile-descriptor=<json>] [--service=${SERVICE_TARGETS.join('|')}] [--uninstall] [--dry-run] [--force] [--json] [--hook-command="evolver inject session-start"] [--server-command=<cmd>] [--server-args=a,b] [--service-command=<cmd>] [--service-args=a,b]\n`;
40
+ export function commandNamesForPath(command, platform, pathExt) {
41
+ if (platform !== 'win32' || /\.[^\\/]+$/.test(command))
42
+ return [command];
43
+ const extensions = (pathExt?.trim() || '.COM;.EXE;.BAT;.CMD')
44
+ .split(';')
45
+ .map((extension) => extension.trim())
46
+ .filter((extension) => /^\.?[A-Za-z\d]+$/.test(extension))
47
+ .map((extension) => extension.startsWith('.') ? extension : `.${extension}`);
48
+ return [command, ...extensions.map((extension) => `${command}${extension}`)];
49
+ }
50
+ function commandOnPath(command) {
51
+ const names = commandNamesForPath(command, process.platform, process.env['PATHEXT']);
52
+ for (const directory of (process.env['PATH'] ?? '').split(delimiter).filter(Boolean)) {
53
+ for (const name of names) {
54
+ try {
55
+ const candidate = join(directory, name);
56
+ if (!statSync(candidate).isFile())
57
+ continue;
58
+ accessSync(candidate, constants.X_OK);
59
+ return true;
60
+ }
61
+ catch {
62
+ // Continue searching PATH.
63
+ }
64
+ }
65
+ }
66
+ return false;
67
+ }
68
+ function defaultRuntimeAvailable(runtime, configRoot, scope) {
69
+ if (runtime === 'opencode') {
70
+ const resolution = resolveOpenCodeConfig({
71
+ configRoot,
72
+ scope,
73
+ homeDir: homedir(),
74
+ xdgConfigHome: process.env['XDG_CONFIG_HOME'],
75
+ opencodeConfig: process.env['OPENCODE_CONFIG'],
76
+ opencodeConfigDir: process.env['OPENCODE_CONFIG_DIR'],
77
+ });
78
+ return commandOnPath('opencode') || (resolution.evidencePaths ?? [resolution.configPath]).some(existsSync);
79
+ }
80
+ const pathOptions = {
81
+ configRoot,
82
+ homeDir: homedir(),
83
+ kiroHome: process.env['KIRO_HOME'],
84
+ };
85
+ const evidenceRoots = scope === 'project'
86
+ ? [
87
+ kiroConfigRoot({ ...pathOptions, scope: 'project' }),
88
+ kiroConfigRoot({ ...pathOptions, scope: 'user' }),
89
+ ]
90
+ : [kiroConfigRoot({ ...pathOptions, scope: 'user' })];
91
+ return commandOnPath('kiro') || commandOnPath('kiro-cli') || evidenceRoots.some(existsSync);
92
+ }
93
+ function displaySetupPath(path, configRoot, scope) {
94
+ if (scope === 'user') {
95
+ const home = homedir();
96
+ const homePath = safeRelativePath(home, path);
97
+ if (homePath === '')
98
+ return '~';
99
+ if (homePath !== undefined)
100
+ return `~/${homePath.replaceAll('\\', '/')}`;
101
+ }
102
+ const projectPath = safeProjectRelativePath(configRoot, path);
103
+ if (projectPath === '')
104
+ return '.';
105
+ return projectPath !== undefined ? projectPath.replaceAll('\\', '/') : '<config-path>';
106
+ }
107
+ function safeRelativePath(root, path) {
108
+ const candidate = relative(root, path);
109
+ if (isAbsolute(candidate) || candidate === '..' || candidate.startsWith(`..${sep}`))
110
+ return undefined;
111
+ return candidate;
112
+ }
113
+ function safeProjectRelativePath(root, path) {
114
+ const descendant = safeRelativePath(root, path);
115
+ if (descendant !== undefined)
116
+ return descendant;
117
+ return safeRelativePath(dirname(path), root) === undefined ? undefined : relative(root, path);
118
+ }
119
+ function displayResultPaths(paths, configRoot, scope) {
120
+ return paths?.map((path) => displaySetupPath(path, configRoot, scope));
121
+ }
122
+ export function safeSetupOperationError(error) {
123
+ if (error instanceof McpConfigConflictError)
124
+ return error.message;
125
+ if (error instanceof McpConfigOwnershipError)
126
+ return error.message;
127
+ if (error instanceof McpConfigVerificationError) {
128
+ return error.restored
129
+ ? '[setup-hooks] runtime configuration verification failed; the previous configuration was restored.'
130
+ : '[setup-hooks] runtime configuration verification failed; rollback could not be confirmed. Inspect the runtime config before retrying.';
131
+ }
132
+ if (error instanceof McpServerValidationError)
133
+ return error.message;
134
+ const name = error instanceof Error ? error.name : '';
135
+ switch (name) {
136
+ case 'McpConfigConflictError': return '[setup-hooks] existing Evolver configuration conflicts; use --force to replace only the Evolver entry.';
137
+ case 'McpConfigOwnershipError': return '[setup-hooks] Evolver ownership metadata is ambiguous or no longer matches the runtime configuration; inspect it before retrying.';
138
+ case 'McpConfigShapeError': return '[setup-hooks] runtime configuration has an invalid JSON shape.';
139
+ case 'McpConfigVerificationError': return error.restored === true
140
+ ? '[setup-hooks] runtime configuration verification failed; the previous configuration was restored.'
141
+ : '[setup-hooks] runtime configuration verification failed; rollback could not be confirmed. Inspect the runtime config before retrying.';
142
+ case 'McpConfigChangedError': return '[setup-hooks] runtime configuration changed during the operation; retry after the runtime finishes writing it.';
143
+ case 'EmptySharedConfigError': return '[setup-hooks] runtime configuration is empty; repair or remove it before retrying.';
144
+ case 'UnparseableConfigError': return '[setup-hooks] runtime configuration is not valid JSON; repair it before retrying.';
145
+ case 'SymlinkRefusedError': return '[setup-hooks] refused an unsafe symbolic-link configuration path.';
146
+ default: return '[setup-hooks] runtime configuration operation failed.';
147
+ }
148
+ }
149
+ export function safeSetupResultError(error) {
150
+ if (typeof error !== 'string')
151
+ return safeSetupOperationError(error);
152
+ const reason = error.replace(/\s+/g, ' ').trim();
153
+ const passive = reason.match(/^passive runtime ([a-z0-9][a-z0-9-]{0,63}): no tool injection$/);
154
+ const unimplementedInstall = reason.match(/^installer not yet implemented for ([a-z0-9][a-z0-9-]{0,63}) \(supported: [a-z0-9, -]+\)$/);
155
+ const unimplementedUninstall = reason.match(/^uninstall not implemented for ([a-z0-9][a-z0-9-]{0,63})$/);
156
+ const runtime = passive?.[1] ?? unimplementedInstall?.[1] ?? unimplementedUninstall?.[1];
157
+ if (!runtime || !SETUP_RUNTIMES.includes(runtime)) {
158
+ return safeSetupOperationError(error);
159
+ }
160
+ if (passive)
161
+ return `[setup-hooks] passive runtime ${runtime}: no tool injection`;
162
+ if (unimplementedInstall)
163
+ return `[setup-hooks] installer not yet implemented for ${runtime}`;
164
+ return `[setup-hooks] uninstall not implemented for ${runtime}`;
165
+ }
38
166
  const PROFILE_DESCRIPTOR_FLAG = 'profile-descriptor';
39
167
  const SECRET_ASSIGNMENT_RE = /\b(?:A2A_NODE_SECRET|EVOMAP_ENTERPRISE_TOKEN|EVOMAP_PRIVATE_HUB_TOKEN|EVOMAP_NODE_SECRET|EVOLVER_IPC_TOKEN|EVOLVER_LLM_TOKEN|PHUB_ENTERPRISE_TOKEN|PRIVATE_HUB_ENTERPRISE_TOKEN)\b\s*[:=]\s*["']?[^"'\s<]+/;
40
168
  const INLINE_BEARER_RE = /\bBearer\s+(?!<|\$|%|REDACTED\b|TOKEN\b|token\b|env:)[A-Za-z0-9._~+/=-]{12,}/i;
@@ -306,19 +434,57 @@ export async function runSetupHooks(argv, store, review, deps = {}) {
306
434
  const configRoot = typeof f['root'] === 'string' ? f['root'] : process.cwd();
307
435
  // claude-code: user scope targets ~/.claude.json regardless of --root; project scope uses configRoot.
308
436
  const scope = scopeResult.scope;
437
+ if (f['dry-run'] === true && runtime !== 'opencode' && runtime !== 'kiro') {
438
+ const error = `--dry-run is currently supported for opencode and kiro setup only; no config was written.`;
439
+ if (json)
440
+ emit({ runtime, outcome: 'error', files: [], error });
441
+ else
442
+ process.stderr.write(`${error}\n`);
443
+ return 1;
444
+ }
309
445
  if (support.outcome === 'installed' && f['uninstall']) {
310
- const r = uninstallInjection(runtime, { configRoot, scope });
446
+ let r;
447
+ try {
448
+ r = uninstallInjection(runtime, {
449
+ configRoot,
450
+ scope,
451
+ homeDir: homedir(),
452
+ kiroHome: process.env['KIRO_HOME'],
453
+ xdgConfigHome: process.env['XDG_CONFIG_HOME'],
454
+ opencodeConfig: process.env['OPENCODE_CONFIG'],
455
+ opencodeConfigDir: process.env['OPENCODE_CONFIG_DIR'],
456
+ dryRun: f['dry-run'] === true,
457
+ });
458
+ }
459
+ catch (error) {
460
+ const message = safeSetupOperationError(error);
461
+ if (json)
462
+ emit({ runtime, action: 'uninstall', files: [], error: message });
463
+ else
464
+ process.stderr.write(`${message}\n`);
465
+ return 1;
466
+ }
467
+ const files = displayResultPaths(r.files, configRoot, scope) ?? [];
468
+ const backups = displayResultPaths(r.backups, configRoot, scope);
311
469
  if (!r.ok) {
470
+ const message = safeSetupResultError(r.error);
312
471
  if (json)
313
- emit({ runtime, action: 'uninstall', files: [], error: r.error ?? 'uninstall failed' });
472
+ emit({ runtime, action: 'uninstall', files: [], error: message });
314
473
  else
315
- process.stderr.write(`${r.error ?? 'uninstall failed'}\n`);
474
+ process.stderr.write(`${message}\n`);
316
475
  return 1;
317
476
  }
477
+ if (r.dryRun) {
478
+ if (json)
479
+ emit({ runtime, action: 'uninstall', files, backups, dryRun: true });
480
+ else
481
+ process.stdout.write(files.length ? `dry-run: would remove evolver from: ${files.join(', ')}\n` : 'dry-run: nothing to remove\n');
482
+ return 0;
483
+ }
318
484
  if (json)
319
- emit({ runtime, action: 'uninstall', files: r.files });
485
+ emit({ runtime, action: 'uninstall', files, backups });
320
486
  else
321
- process.stdout.write(r.files.length ? `removed evolver from: ${r.files.join(', ')}\n` : 'nothing to remove\n');
487
+ process.stdout.write(files.length ? `removed evolver from: ${files.join(', ')}\n` : 'nothing to remove\n');
322
488
  return 0;
323
489
  }
324
490
  const profileDescriptor = profileDescriptorFromFlag(f);
@@ -360,6 +526,28 @@ export async function runSetupHooks(argv, store, review, deps = {}) {
360
526
  return 0;
361
527
  }
362
528
  const server = buildServer(f, descriptor);
529
+ if ((runtime === 'opencode' || runtime === 'kiro') && f['dry-run'] !== true) {
530
+ let runtimeDetected;
531
+ try {
532
+ runtimeDetected = (deps.runtimeAvailable ?? defaultRuntimeAvailable)(runtime, configRoot, scope);
533
+ }
534
+ catch (error) {
535
+ const message = safeSetupOperationError(error);
536
+ if (json)
537
+ emit({ runtime, outcome: 'error', files: [], error: message });
538
+ else
539
+ process.stderr.write(`${message}\n`);
540
+ return 1;
541
+ }
542
+ if (!runtimeDetected) {
543
+ const error = `${runtime} runtime was not detected; install or launch ${runtime === 'opencode' ? 'OpenCode' : 'Kiro'} first, then rerun. No config was written.`;
544
+ if (json)
545
+ emit({ runtime, outcome: 'error', files: [], error });
546
+ else
547
+ process.stderr.write(`${error}\n`);
548
+ return 1;
549
+ }
550
+ }
363
551
  if (runtime === 'cursor')
364
552
  (deps.emitNonGitWorkspaceNotice ?? maybeEmitNonGitWorkspaceNotice)({ cwd: configRoot });
365
553
  // cursor seeds .cursor/rules/evolver.mdc with the CURRENT top REVIEW-APPROVED genes so the file is useful
@@ -376,6 +564,12 @@ export async function runSetupHooks(argv, store, review, deps = {}) {
376
564
  ...(typeof f['hook-command'] === 'string' ? { hookCommand: f['hook-command'] } : {}),
377
565
  ...(cursorGenes ? { genes: cursorGenes } : {}),
378
566
  force: f['force'] === true,
567
+ dryRun: f['dry-run'] === true,
568
+ homeDir: homedir(),
569
+ kiroHome: process.env['KIRO_HOME'],
570
+ xdgConfigHome: process.env['XDG_CONFIG_HOME'],
571
+ opencodeConfig: process.env['OPENCODE_CONFIG'],
572
+ opencodeConfigDir: process.env['OPENCODE_CONFIG_DIR'],
379
573
  });
380
574
  }
381
575
  catch (e) {
@@ -383,7 +577,7 @@ export async function runSetupHooks(argv, store, review, deps = {}) {
383
577
  // `unsupported` runtime. Reporting `unsupported` here would tell a bootstrapper the runtime isn't supported and
384
578
  // make it stop trying, when the real cause is operational. `error` is a CLI result status (the attempt failed),
385
579
  // distinct from the support-matrix `unsupported` (an unrecognized runtime id) (Bugbot #264).
386
- const msg = e instanceof Error ? e.message : String(e);
580
+ const msg = safeSetupOperationError(e);
387
581
  if (json)
388
582
  emit({ runtime, outcome: 'error', files: [], error: msg });
389
583
  else
@@ -392,22 +586,44 @@ export async function runSetupHooks(argv, store, review, deps = {}) {
392
586
  }
393
587
  if (!r.ok) {
394
588
  // Same reasoning for an ok:false install result: a failed install of a supported runtime is `error`, not `unsupported`.
589
+ const message = safeSetupResultError(r.error);
395
590
  if (json)
396
- emit({ runtime, outcome: 'error', files: [], error: r.error ?? 'install failed' });
591
+ emit({ runtime, outcome: 'error', files: [], error: message });
397
592
  else
398
- process.stderr.write(`${r.error ?? 'install failed'}\n`);
593
+ process.stderr.write(`${message}\n`);
399
594
  return 1;
400
595
  }
596
+ const files = displayResultPaths(r.files, configRoot, scope) ?? [];
597
+ const backups = displayResultPaths(r.backups, configRoot, scope);
598
+ if (r.dryRun) {
599
+ if (json) {
600
+ emit({
601
+ runtime,
602
+ outcome: 'installed',
603
+ files,
604
+ backups,
605
+ dryRun: true,
606
+ ...(r.alreadyInstalled ? { alreadyInstalled: true } : {}),
607
+ });
608
+ }
609
+ else if (r.alreadyInstalled) {
610
+ process.stdout.write('dry-run: evolver already installed (no changes)\n');
611
+ }
612
+ else {
613
+ process.stdout.write(`dry-run: would install evolver (${r.mode}) → ${files.join(', ')}\n`);
614
+ }
615
+ return 0;
616
+ }
401
617
  if (r.alreadyInstalled) {
402
618
  if (json)
403
- emit({ runtime, outcome: 'installed', files: r.files, alreadyInstalled: true });
619
+ emit({ runtime, outcome: 'installed', files, alreadyInstalled: true });
404
620
  else
405
621
  process.stdout.write('evolver already installed (use --force to reinstall)\n');
406
622
  return 0;
407
623
  }
408
624
  if (json)
409
- emit({ runtime, outcome: 'installed', files: r.files, mode: r.mode });
625
+ emit({ runtime, outcome: 'installed', files, backups, mode: r.mode, verified: r.verified });
410
626
  else
411
- process.stdout.write(`installed evolver (${r.mode}) → ${r.files.join(', ')}\n`);
627
+ process.stdout.write(`installed evolver (${r.mode}) → ${files.join(', ')}\n`);
412
628
  return 0;
413
629
  }
@@ -0,0 +1,39 @@
1
+ import { workflow } from '@evomap/evolver-core';
2
+ import { type ProductionWorkflowRuntimeOptions } from './workflowRuntime.js';
3
+ export declare const WORKFLOW_SUBCOMMANDS: readonly ["start", "submit", "list", "status", "history", "pause", "resume", "cancel", "approve", "reject"];
4
+ type OutputStream = Pick<NodeJS.WriteStream, 'write'>;
5
+ type RuntimeControlOptions = {
6
+ actor: string;
7
+ reason?: string;
8
+ };
9
+ type WorkflowRuntimeLike = {
10
+ start(spec: workflow.WorkflowSpec, options?: {
11
+ runId?: string;
12
+ }): Promise<unknown>;
13
+ pause?: (runId: string, options: RuntimeControlOptions) => Promise<unknown>;
14
+ resume?: (runId: string, options?: RuntimeControlOptions) => Promise<unknown>;
15
+ cancel?: (runId: string, options: RuntimeControlOptions) => Promise<unknown>;
16
+ approve?: (runId: string, gateId: string, options: RuntimeControlOptions) => Promise<unknown>;
17
+ reject?: (runId: string, gateId: string, options: RuntimeControlOptions) => Promise<unknown>;
18
+ };
19
+ type WorkflowStoreLike = {
20
+ read(runId: string): workflow.WorkflowRunState;
21
+ listRunIds(): string[];
22
+ history?: (runId: string) => unknown;
23
+ readHistory?: (runId: string) => unknown;
24
+ listHistory?: (runId: string) => unknown;
25
+ requestPause?: (runId: string, options: RuntimeControlOptions) => void;
26
+ requestCancel?: (runId: string, options: RuntimeControlOptions) => void;
27
+ approve?: (runId: string, gateId: string, options: RuntimeControlOptions) => void;
28
+ reject?: (runId: string, gateId: string, options: RuntimeControlOptions) => void;
29
+ };
30
+ export interface WorkflowCommandDeps {
31
+ stateDir?: string;
32
+ stdout?: OutputStream;
33
+ stderr?: OutputStream;
34
+ createStore?: (stateDir: string) => WorkflowStoreLike;
35
+ createRuntime?: (stateDir: string) => WorkflowRuntimeLike;
36
+ productionRuntimeOptions?: ProductionWorkflowRuntimeOptions;
37
+ }
38
+ export declare function runWorkflowCommand(argv: string[], deps?: WorkflowCommandDeps): Promise<number>;
39
+ export {};