@evomap/evolver-cli 2.0.0-beta.9 → 2.0.1

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 (87) hide show
  1. package/dist/antiGeneBenchmark.js +2 -0
  2. package/dist/antiGeneRollout.js +9 -3
  3. package/dist/assetHealth.js +2 -0
  4. package/dist/assetTrust.js +14 -1
  5. package/dist/atp.d.ts +10 -5
  6. package/dist/atp.js +119 -26
  7. package/dist/atpAutoBuyer.d.ts +120 -0
  8. package/dist/atpAutoBuyer.js +814 -0
  9. package/dist/atpAutoDeliver.js +2 -2
  10. package/dist/autoDistillLlm.js +2 -1
  11. package/dist/autoDistillTranscript.js +3 -2
  12. package/dist/autoexec.d.ts +101 -13
  13. package/dist/autoexec.js +794 -91
  14. package/dist/cli.js +13 -0
  15. package/dist/cliContracts.d.ts +23 -2
  16. package/dist/cliContracts.js +504 -54
  17. package/dist/commands.d.ts +1 -0
  18. package/dist/commands.js +1 -0
  19. package/dist/curriculumCapabilityGaps.d.ts +6 -0
  20. package/dist/curriculumCapabilityGaps.js +24 -0
  21. package/dist/cycleConsumer.d.ts +13 -0
  22. package/dist/cycleConsumer.js +186 -20
  23. package/dist/dashboard.js +47 -9
  24. package/dist/dispatch.js +8 -2
  25. package/dist/distillPrimitives.d.ts +3 -2
  26. package/dist/distillPrimitives.js +80 -12
  27. package/dist/doctor.js +120 -11
  28. package/dist/identityHome.d.ts +9 -0
  29. package/dist/identityHome.js +47 -0
  30. package/dist/index.d.ts +70 -40
  31. package/dist/index.js +581 -193
  32. package/dist/learningTrace.d.ts +15 -0
  33. package/dist/learningTrace.js +73 -0
  34. package/dist/lifecycle.d.ts +67 -1
  35. package/dist/lifecycle.js +738 -44
  36. package/dist/localMemoryGraph.d.ts +90 -3
  37. package/dist/localMemoryGraph.js +2031 -231
  38. package/dist/login.d.ts +1 -1
  39. package/dist/login.js +3 -3
  40. package/dist/materialSnapshot.d.ts +9 -1
  41. package/dist/materialSnapshot.js +23 -6
  42. package/dist/memoryGraphOps.d.ts +8 -0
  43. package/dist/memoryGraphOps.js +140 -0
  44. package/dist/migrate/assetFormatMap.d.ts +61 -0
  45. package/dist/migrate/assetFormatMap.js +53 -0
  46. package/dist/migrate/envTranslate.d.ts +26 -0
  47. package/dist/migrate/envTranslate.js +147 -0
  48. package/dist/migrate/fieldMap.d.ts +4 -2
  49. package/dist/migrate/fieldMap.js +9 -5
  50. package/dist/migrate/oauthImport.d.ts +66 -0
  51. package/dist/migrate/oauthImport.js +667 -0
  52. package/dist/migrate/v1Import.d.ts +92 -1
  53. package/dist/migrate/v1Import.js +1481 -141
  54. package/dist/promptRecallHook.d.ts +24 -0
  55. package/dist/promptRecallHook.js +425 -0
  56. package/dist/recallVerifyReport.d.ts +37 -0
  57. package/dist/recallVerifyReport.js +244 -0
  58. package/dist/recipe.d.ts +7 -1
  59. package/dist/recipe.js +426 -56
  60. package/dist/requiredSandboxValidation.d.ts +5 -0
  61. package/dist/requiredSandboxValidation.js +4 -0
  62. package/dist/reuse.d.ts +9 -0
  63. package/dist/reuse.js +151 -56
  64. package/dist/runtimeCapabilities.js +15 -15
  65. package/dist/runtimeSessionSource.d.ts +3 -2
  66. package/dist/runtimeSessionSource.js +63 -11
  67. package/dist/selectionPolicyConfig.d.ts +8 -0
  68. package/dist/selectionPolicyConfig.js +18 -0
  69. package/dist/semanticIdfConfig.d.ts +2 -0
  70. package/dist/semanticIdfConfig.js +4 -0
  71. package/dist/sessionIngest.d.ts +37 -0
  72. package/dist/sessionIngest.js +156 -0
  73. package/dist/setupHooks.js +95 -1
  74. package/dist/skill2gep.d.ts +13 -9
  75. package/dist/skill2gep.js +42 -30
  76. package/dist/skillDistill.d.ts +8 -4
  77. package/dist/skillDistill.js +38 -9
  78. package/dist/solo/mode.js +1 -0
  79. package/dist/sync.d.ts +12 -0
  80. package/dist/sync.js +1246 -151
  81. package/dist/thesis.d.ts +1 -1
  82. package/dist/thesis.js +20 -3
  83. package/dist/trajectoryExport.js +21 -3
  84. package/dist/v1Compat.d.ts +1 -0
  85. package/dist/v1Compat.js +9 -0
  86. package/dist/workflowRuntime.js +24 -18
  87. package/package.json +11 -8
package/dist/lifecycle.js CHANGED
@@ -1,15 +1,19 @@
1
1
  import { createRequire } from 'node:module';
2
- import { spawn, execFileSync } from 'node:child_process';
2
+ import { spawn, spawnSync, execFileSync } from 'node:child_process';
3
+ import { randomUUID } from 'node:crypto';
3
4
  import { existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4
5
  import { homedir } from 'node:os';
5
- import { basename, dirname, join } from 'node:path';
6
+ import { basename, dirname, extname, isAbsolute, join, posix, resolve as resolvePath } from 'node:path';
6
7
  import { fileURLToPath } from 'node:url';
7
- import { loadEnvFile, loadEnvFileFromEnv } from '@evomap/evolver-mcp';
8
+ import { expandHomePath, loadEnvFile, loadEnvFileFromEnv } from '@evomap/evolver-mcp';
8
9
  const requireFromHere = createRequire(import.meta.url);
9
10
  const DEFAULT_DAEMON_NAME = 'evolver-proxy';
10
11
  const DEFAULT_LABEL = 'com.evomap.evolver-proxy';
12
+ const AUTOEXEC_LABEL = 'com.evomap.evolver-autoexec';
11
13
  const DEFAULT_HEALTH_TIMEOUT_MS = 700;
12
14
  const DEFAULT_WATCH_INTERVAL_MS = 120_000;
15
+ const BOOTSTRAP_ENV_FILE_HANDOFF = 'EVOLVER_INTERNAL_BOOTSTRAP_ENV_FILE';
16
+ const LIFECYCLE_USAGE = 'Usage: evolver lifecycle <start|stop|restart|status|check|watch|install-service --target=launchd|systemd|windows [--with-autoexec] [--autoexec-home=<path>]|bootstrap [--target=launchd|systemd|windows] [--dry-run]|remove-autoexec-service --target=launchd|systemd|windows [--dry-run]>\n';
13
17
  export function runLifecycleCommand(argv, deps = {}) {
14
18
  return runLifecycleCommandInner(argv, deps).catch((err) => {
15
19
  const stderr = deps.stderr ?? ((text) => { process.stderr.write(text); });
@@ -18,10 +22,14 @@ export function runLifecycleCommand(argv, deps = {}) {
18
22
  });
19
23
  }
20
24
  async function runLifecycleCommandInner(argv, deps) {
21
- const action = argv[0];
22
25
  const env = deps.env ?? process.env;
23
26
  const stdout = deps.stdout ?? ((text) => { process.stdout.write(text); });
24
27
  const stderr = deps.stderr ?? ((text) => { process.stderr.write(text); });
28
+ if (argv[0] === '--help' || argv[0] === '-h') {
29
+ stdout(LIFECYCLE_USAGE);
30
+ return 0;
31
+ }
32
+ const action = argv[0];
25
33
  const flags = parseFlags(argv.slice(1));
26
34
  const paths = lifecyclePaths(env);
27
35
  switch (action) {
@@ -65,6 +73,17 @@ async function runLifecycleCommandInner(argv, deps) {
65
73
  }
66
74
  case 'watch':
67
75
  return runWatch(paths, env, flags, stdout, stderr);
76
+ case 'bootstrap': {
77
+ const requestedEnvFile = typeof flags['env-file'] === 'string' ? flags['env-file'] : undefined;
78
+ const envFileResult = requestedEnvFile
79
+ ? loadEnvFile(requestedEnvFile, env)
80
+ : loadEnvFileFromEnv(env);
81
+ if (envFileResult.error)
82
+ throw new Error('failed to load lifecycle environment file');
83
+ const result = await bootstrapService(flags, env, deps.argv1 ?? process.argv[1], deps.bootstrap ?? {}, deps.loadUnixRecoveryController);
84
+ stdout(`${JSON.stringify(result, null, 2)}\n`);
85
+ return 0;
86
+ }
68
87
  case 'install-service': {
69
88
  const requestedEnvFile = typeof flags['env-file'] === 'string' ? flags['env-file'] : undefined;
70
89
  const envFileResult = requestedEnvFile
@@ -73,12 +92,21 @@ async function runLifecycleCommandInner(argv, deps) {
73
92
  if (envFileResult.error)
74
93
  throw new Error('failed to load lifecycle environment file');
75
94
  const target = serviceTarget(flags);
76
- const result = await installService(target, flags, env, deps.argv1 ?? process.argv[1]);
95
+ const result = await installService(target, flags, env, deps.argv1 ?? process.argv[1], deps.loadUnixRecoveryController);
96
+ stdout(`${JSON.stringify(result, null, 2)}\n`);
97
+ return 0;
98
+ }
99
+ case 'remove-autoexec-service': {
100
+ if (flags['dry-run'] !== undefined && flags['dry-run'] !== true) {
101
+ throw new Error('--dry-run is a boolean flag and does not accept a value');
102
+ }
103
+ const target = serviceTarget(flags);
104
+ const result = (deps.removeAutoexecService ?? removeAutoexecService)(target, flags['dry-run'] === true);
77
105
  stdout(`${JSON.stringify(result, null, 2)}\n`);
78
106
  return 0;
79
107
  }
80
108
  default:
81
- stderr('用法: evolver lifecycle <start|stop|restart|status|check|watch|install-service --target=launchd|systemd|windows>\n');
109
+ stderr(LIFECYCLE_USAGE);
82
110
  return action === undefined ? 0 : 1;
83
111
  }
84
112
  }
@@ -168,7 +196,7 @@ export function stopLifecycle(paths, deps = {}) {
168
196
  rmSync(paths.pidFile, { force: true });
169
197
  return { status: 'not_running' };
170
198
  }
171
- if (!pidFile.owned || !waitForPidFileRecordMatch(pidFile, 1_000, deps.processCommandLine ?? processCommandLine, deps.processIdentity ?? processIdentity)) {
199
+ if (!pidFile.owned || !waitForPidFileRecordMatch(pidFile, 1_000, deps.processCommandLine ?? processCommandLine, deps.processIdentity ?? processIdentity, deps.platform ?? process.platform)) {
172
200
  return { status: 'not_owned', pid, reason: 'pidfile_owner_unconfirmed' };
173
201
  }
174
202
  try {
@@ -222,9 +250,39 @@ export async function lifecycleStatus(paths, env = process.env, options = {}) {
222
250
  logFile: paths.logFile,
223
251
  };
224
252
  }
253
+ /** Fetch enriched connection status for the daily summary. Builds on lifecycleStatus, adding hub details. */
254
+ export async function dailyConnectionStatus(paths, env = process.env, options = {}) {
255
+ const base = await lifecycleStatus(paths, env, { ...options, quietSettingsReadError: true });
256
+ if (!base.running || !base.healthy)
257
+ return base;
258
+ // Proxy is healthy — fetch /proxy/status for hub details
259
+ const settings = readProxySettings(paths.settingsFile, { quietReadError: true });
260
+ if (!settings.url || !settings.token)
261
+ return base;
262
+ const controller = new AbortController();
263
+ const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? DEFAULT_HEALTH_TIMEOUT_MS);
264
+ try {
265
+ const url = `${settings.url.replace(/\/+$/, '')}/proxy/status`;
266
+ const res = await fetch(url, { headers: { authorization: `Bearer ${settings.token}` }, signal: controller.signal });
267
+ if (!res.ok)
268
+ return base;
269
+ const body = await res.json();
270
+ return {
271
+ ...base,
272
+ hubAuthStatus: typeof body['hub_auth_status'] === 'string' ? body['hub_auth_status'] : undefined,
273
+ lastSyncAt: typeof body['last_sync_at'] === 'string' ? body['last_sync_at'] : undefined,
274
+ };
275
+ }
276
+ catch {
277
+ return base;
278
+ }
279
+ finally {
280
+ clearTimeout(timeout);
281
+ }
282
+ }
225
283
  export function lifecyclePaths(env = process.env) {
226
284
  const home = env['EVOLVER_HOME'] ?? env['EVOMAP_HOME'] ?? join(homedir(), '.evomap');
227
- const stateDir = env['EVOLVER_LIFECYCLE_STATE_DIR'] ?? join(home, 'lifecycle');
285
+ const stateDir = resolvePath(nonBlankEnv(env, 'EVOLVER_LIFECYCLE_STATE_DIR') ?? join(home, 'lifecycle'));
228
286
  const logDir = env['EVOLVER_LIFECYCLE_LOG_DIR'] ?? join(home, 'logs');
229
287
  const name = env['EVOLVER_LIFECYCLE_NAME'] ?? DEFAULT_DAEMON_NAME;
230
288
  const settingsHome = nonBlankEnv(env, 'EVOLVER_SETTINGS_DIR') ?? join(homedir(), '.evolver');
@@ -242,6 +300,10 @@ function nonBlankEnv(env, key) {
242
300
  return value ? value : undefined;
243
301
  }
244
302
  export function renderSystemdUnit(opts = {}) {
303
+ const execStart = assertSingleLine(opts.execStart ?? defaultServiceExecStart(), 'systemd ExecStart');
304
+ const workingDirectory = opts.workingDirectory === undefined
305
+ ? '%h'
306
+ : quoteSystemdArg(isAbsolute(opts.workingDirectory) ? opts.workingDirectory : resolvePath(opts.workingDirectory));
245
307
  return [
246
308
  '# Linux systemd user unit -- ~/.config/systemd/user/evolver-proxy.service',
247
309
  '[Unit]',
@@ -252,17 +314,23 @@ export function renderSystemdUnit(opts = {}) {
252
314
  'StartLimitIntervalSec=120s',
253
315
  '',
254
316
  '[Service]',
255
- 'Type=simple',
256
- `WorkingDirectory=${opts.workingDirectory ?? '%h'}`,
317
+ 'Type=notify',
318
+ '# The stable recovery controller may be MainPID; the proxy child invokes systemd-notify.',
319
+ 'NotifyAccess=all',
320
+ 'WatchdogSec=180s',
321
+ `WorkingDirectory=${workingDirectory}`,
257
322
  ...(opts.envFile ? [`Environment="EVOLVER_ENV_FILE=${escapeSystemdEnvValue(opts.envFile)}"`] : []),
258
323
  'Environment="EVOLVER_SELF_UPDATE_SUPERVISOR=systemd"',
324
+ ...(opts.lifecycleStateDir
325
+ ? [`Environment="EVOLVER_LIFECYCLE_STATE_DIR=${escapeSystemdEnvValue(opts.lifecycleStateDir)}"`]
326
+ : []),
259
327
  ...(opts.selfUpdateStateDir
260
328
  ? [`Environment="EVOLVER_SELF_UPDATE_STATE_DIR=${escapeSystemdEnvValue(opts.selfUpdateStateDir)}"`]
261
329
  : []),
262
330
  ...(opts.selfUpdateTarget
263
331
  ? [`Environment="EVOLVER_SELF_UPDATE_TARGET_PATH=${escapeSystemdEnvValue(opts.selfUpdateTarget)}"`]
264
332
  : []),
265
- `ExecStart=${opts.execStart ?? defaultServiceExecStart()}`,
333
+ `ExecStart=${execStart}`,
266
334
  'Restart=on-failure',
267
335
  'RestartSec=5s',
268
336
  'RestartPreventExitStatus=0',
@@ -279,12 +347,49 @@ export function renderSystemdUnit(opts = {}) {
279
347
  '',
280
348
  ].join('\n');
281
349
  }
350
+ export function renderAutoexecSystemdUnit(opts) {
351
+ const execStart = escapeSystemdPercent(assertSingleLine(opts.execStart, 'systemd ExecStart'));
352
+ const workingDirectory = opts.workingDirectory === undefined
353
+ ? '%h'
354
+ : escapeSystemdPercent(quoteSystemdArg(isAbsolute(opts.workingDirectory) ? opts.workingDirectory : resolvePath(opts.workingDirectory)));
355
+ return [
356
+ '# Linux systemd user unit -- ~/.config/systemd/user/evolver-autoexec.service',
357
+ '[Unit]',
358
+ 'Description=EvoMap Evolver Autoexec Daemon',
359
+ 'After=network-online.target evolver-proxy.service',
360
+ 'Wants=network-online.target evolver-proxy.service',
361
+ 'StartLimitBurst=5',
362
+ 'StartLimitIntervalSec=120s',
363
+ '',
364
+ '[Service]',
365
+ 'Type=simple',
366
+ `WorkingDirectory=${workingDirectory}`,
367
+ ...(opts.envFile ? [`Environment="EVOLVER_ENV_FILE=${escapeSystemdEnvValue(opts.envFile)}"`] : []),
368
+ `ExecStart=${execStart}`,
369
+ 'Restart=on-failure',
370
+ 'RestartSec=5s',
371
+ 'RestartPreventExitStatus=0',
372
+ 'TimeoutStopSec=30s',
373
+ 'StandardOutput=journal',
374
+ 'StandardError=journal',
375
+ 'SyslogIdentifier=evolver-autoexec',
376
+ 'NoNewPrivileges=true',
377
+ 'PrivateTmp=true',
378
+ '',
379
+ '[Install]',
380
+ 'WantedBy=default.target',
381
+ '',
382
+ ].join('\n');
383
+ }
282
384
  export function renderLaunchdPlist(opts = {}) {
283
385
  const workingDirectory = opts.workingDirectory ?? '/Users/YOU/your-project';
284
386
  const nodePath = opts.nodePath ?? '/usr/local/bin/node';
285
387
  const proxyBin = opts.proxyBin ?? '/Users/YOU/your-project/node_modules/@evomap/evolver-proxy/dist/bin/evolver-proxy.js';
286
388
  const programArguments = opts.programArguments ?? [nodePath, proxyBin];
287
389
  const logDir = opts.logDir ?? '/Users/YOU/Library/Logs';
390
+ const label = opts.label ?? DEFAULT_LABEL;
391
+ const logName = opts.logName ?? 'evolver-proxy';
392
+ const selfUpdateSupervisor = opts.selfUpdateSupervisor ?? true;
288
393
  const envFileBlock = opts.envFile ? ` <key>EVOLVER_ENV_FILE</key>\n <string>${escapeXml(opts.envFile)}</string>\n` : '';
289
394
  return [
290
395
  '<?xml version="1.0" encoding="UTF-8"?>',
@@ -292,7 +397,7 @@ export function renderLaunchdPlist(opts = {}) {
292
397
  '<plist version="1.0">',
293
398
  '<dict>',
294
399
  ' <key>Label</key>',
295
- ` <string>${DEFAULT_LABEL}</string>`,
400
+ ` <string>${escapeXml(label)}</string>`,
296
401
  ' <key>ProgramArguments</key>',
297
402
  ' <array>',
298
403
  ...programArguments.map((argument) => ` <string>${escapeXml(argument)}</string>`),
@@ -302,8 +407,14 @@ export function renderLaunchdPlist(opts = {}) {
302
407
  ' <key>EnvironmentVariables</key>',
303
408
  ' <dict>',
304
409
  envFileBlock.trimEnd(),
305
- ' <key>EVOLVER_SELF_UPDATE_SUPERVISOR</key>',
306
- ' <string>launchd</string>',
410
+ ...(opts.lifecycleStateDir ? [
411
+ ' <key>EVOLVER_LIFECYCLE_STATE_DIR</key>',
412
+ ` <string>${escapeXml(opts.lifecycleStateDir)}</string>`,
413
+ ] : []),
414
+ ...(selfUpdateSupervisor ? [
415
+ ' <key>EVOLVER_SELF_UPDATE_SUPERVISOR</key>',
416
+ ' <string>launchd</string>',
417
+ ] : []),
307
418
  ...(opts.selfUpdateStateDir ? [
308
419
  ' <key>EVOLVER_SELF_UPDATE_STATE_DIR</key>',
309
420
  ` <string>${escapeXml(opts.selfUpdateStateDir)}</string>`,
@@ -325,9 +436,9 @@ export function renderLaunchdPlist(opts = {}) {
325
436
  ' <key>ThrottleInterval</key>',
326
437
  ' <integer>5</integer>',
327
438
  ' <key>StandardOutPath</key>',
328
- ` <string>${escapeXml(join(logDir, 'evolver-proxy.log'))}</string>`,
439
+ ` <string>${escapeXml(posix.join(logDir, `${logName}.log`))}</string>`,
329
440
  ' <key>StandardErrorPath</key>',
330
- ` <string>${escapeXml(join(logDir, 'evolver-proxy.err.log'))}</string>`,
441
+ ` <string>${escapeXml(posix.join(logDir, `${logName}.err.log`))}</string>`,
331
442
  ' <key>ProcessType</key>',
332
443
  ' <string>Standard</string>',
333
444
  ' <key>LowPriorityIO</key>',
@@ -339,8 +450,16 @@ export function renderLaunchdPlist(opts = {}) {
339
450
  '',
340
451
  ].filter((line) => line !== '').join('\n');
341
452
  }
453
+ export function renderAutoexecLaunchdPlist(opts) {
454
+ return renderLaunchdPlist({
455
+ ...opts,
456
+ label: AUTOEXEC_LABEL,
457
+ logName: 'evolver-autoexec',
458
+ selfUpdateSupervisor: false,
459
+ });
460
+ }
342
461
  export function renderWindowsInstaller(defaults = {}) {
343
- const ps = (value) => `'${(value ?? '').replaceAll("'", "''")}'`;
462
+ const ps = (value) => `'${assertSingleLine(value ?? '', 'Windows installer value').replaceAll("'", "''")}'`;
344
463
  return String.raw `param(
345
464
  [switch]$Install,
346
465
  [switch]$Uninstall,
@@ -349,6 +468,7 @@ export function renderWindowsInstaller(defaults = {}) {
349
468
  [string]$NodePath = ${ps(defaults.nodePath)},
350
469
  [string]$ProxyBin = ${ps(defaults.proxyBin)},
351
470
  [string]$EnvFile = ${ps(defaults.envFile)},
471
+ [string]$LifecycleStateDir = ${ps(defaults.lifecycleStateDir)},
352
472
  [string]$SelfUpdateStateDir = ${ps(defaults.selfUpdateStateDir)}
353
473
  )
354
474
 
@@ -362,7 +482,21 @@ if (-not ($Install -or $Uninstall)) {
362
482
 
363
483
  if ($Uninstall) {
364
484
  $existing = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
365
- if ($existing) { Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false }
485
+ if ($existing) {
486
+ if ($existing.State -eq 'Running') {
487
+ Stop-ScheduledTask -TaskName $TaskName
488
+ $stopDeadline = [DateTime]::UtcNow.AddSeconds(15)
489
+ do {
490
+ Start-Sleep -Milliseconds 100
491
+ $existing = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
492
+ } while ($existing -and $existing.State -eq 'Running' -and [DateTime]::UtcNow -lt $stopDeadline)
493
+ if ($existing -and $existing.State -eq 'Running') {
494
+ Write-Error 'Existing Evolver Scheduled Task did not stop; refusing to uninstall.'
495
+ exit 1
496
+ }
497
+ }
498
+ Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false
499
+ }
366
500
  $launcher = Join-Path $env:LOCALAPPDATA 'EvoMap\evolver-proxy-task-launcher.vbs'
367
501
  if (Test-Path $launcher) { Remove-Item $launcher -Force -ErrorAction SilentlyContinue }
368
502
  exit 0
@@ -387,7 +521,7 @@ if ($EvolverBin) {
387
521
  }
388
522
  }
389
523
 
390
- foreach ($launcherValue in @($EvolverBin, $NodePath, $ProxyBin, $EnvFile, $SelfUpdateStateDir)) {
524
+ foreach ($launcherValue in @($EvolverBin, $NodePath, $ProxyBin, $EnvFile, $LifecycleStateDir, $SelfUpdateStateDir)) {
391
525
  if ($launcherValue -match "[\r\n]") {
392
526
  Write-Error 'Launcher paths must not contain line breaks.'
393
527
  exit 1
@@ -428,6 +562,7 @@ $nodeEsc = if ($NodePath) { $NodePath.Replace('"', '""') } else { '' }
428
562
  $proxyEsc = if ($ProxyBin) { $ProxyBin.Replace('"', '""') } else { '' }
429
563
  $evolverEsc = if ($EvolverBin) { $EvolverBin.Replace('"', '""') } else { '' }
430
564
  $envEsc = if ($EnvFile) { $EnvFile.Replace('"', '""') } else { '' }
565
+ $lifecycleStateDirEsc = if ($LifecycleStateDir) { $LifecycleStateDir.Replace('"', '""') } else { '' }
431
566
  $stateDirEsc = if ($SelfUpdateStateDir) { $SelfUpdateStateDir.Replace('"', '""') } else { '' }
432
567
 
433
568
  $launcherBody = @"
@@ -439,6 +574,7 @@ Set WshShell = CreateObject("WScript.Shell")
439
574
  Set env = WshShell.Environment("PROCESS")
440
575
  Set fso = CreateObject("Scripting.FileSystemObject")
441
576
  If "$envEsc" <> "" Then env("EVOLVER_ENV_FILE") = "$envEsc"
577
+ If "$lifecycleStateDirEsc" <> "" Then env("EVOLVER_LIFECYCLE_STATE_DIR") = "$lifecycleStateDirEsc"
442
578
  env("EVOLVER_SELF_UPDATE_SUPERVISOR") = "windows-scheduled-task"
443
579
  If "$evolverEsc" <> "" Then
444
580
  stateDir = "$stateDirEsc"
@@ -468,6 +604,130 @@ $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoi
468
604
  $principal = New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Limited
469
605
  $task = New-ScheduledTask -Action $action -Trigger $trigger -Settings $settings -Principal $principal
470
606
  Register-ScheduledTask -TaskName $TaskName -InputObject $task -Force | Out-Null
607
+ # The proxy hands off right after bootstrap; start the task now so the current session is
608
+ # supervised immediately, while the -AtLogOn trigger keeps it durable across logins.
609
+ Start-ScheduledTask -TaskName $TaskName
610
+ Write-Host "Installed scheduled task '$TaskName' using hidden wscript launcher $launcherPath."
611
+ `;
612
+ }
613
+ export function renderWindowsAutoexecInstaller(defaults = {}) {
614
+ const ps = (value) => `'${assertSingleLine(value ?? '', 'Windows installer value').replaceAll("'", "''")}'`;
615
+ return String.raw `param(
616
+ [switch]$Install,
617
+ [switch]$Uninstall,
618
+ [string]$TaskName = 'EvoMapEvolverAutoexecDaemon',
619
+ [string]$EvolverBin = ${ps(defaults.evolverBin)},
620
+ [string]$NodePath = ${ps(defaults.nodePath)},
621
+ [string]$CliBin = ${ps(defaults.cliBin)},
622
+ [string]$EnvFile = ${ps(defaults.envFile)},
623
+ [string]$AutoexecHome = ${ps(defaults.autoexecHome)},
624
+ [string]$WorkingDirectory = ${ps(defaults.workingDirectory)}
625
+ )
626
+
627
+ $ErrorActionPreference = 'Stop'
628
+
629
+ if (-not ($Install -or $Uninstall) -or ($Install -and $Uninstall)) {
630
+ Write-Host 'Usage: install-evolver-autoexec-windows.ps1 -Install [-EvolverBin ... | -NodePath ... -CliBin ...] [-EnvFile ...] [-AutoexecHome ...]'
631
+ Write-Host ' install-evolver-autoexec-windows.ps1 -Uninstall [-TaskName ...]'
632
+ exit 1
633
+ }
634
+
635
+ $launcherDir = Join-Path $env:LOCALAPPDATA 'EvoMap'
636
+ $launcherPath = Join-Path $launcherDir 'evolver-autoexec-task-launcher.vbs'
637
+
638
+ if ($Uninstall) {
639
+ $existing = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
640
+ if ($existing) {
641
+ if ($existing.State -eq 'Running') {
642
+ Stop-ScheduledTask -TaskName $TaskName
643
+ $stopDeadline = [DateTime]::UtcNow.AddSeconds(15)
644
+ do {
645
+ Start-Sleep -Milliseconds 100
646
+ $existing = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
647
+ } while ($existing -and $existing.State -eq 'Running' -and [DateTime]::UtcNow -lt $stopDeadline)
648
+ if ($existing -and $existing.State -eq 'Running') {
649
+ Write-Error 'Existing Evolver Autoexec Scheduled Task did not stop; refusing to uninstall.'
650
+ exit 1
651
+ }
652
+ }
653
+ Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false
654
+ }
655
+ if (Test-Path $launcherPath) { Remove-Item $launcherPath -Force -ErrorAction SilentlyContinue }
656
+ exit 0
657
+ }
658
+
659
+ if (-not $EvolverBin) {
660
+ if (-not $NodePath) {
661
+ $cmd = Get-Command node -ErrorAction SilentlyContinue
662
+ if (-not $cmd) { Write-Error 'Pass -EvolverBin, or install node.exe / pass -NodePath.'; exit 1 }
663
+ $NodePath = $cmd.Source
664
+ }
665
+ if (-not $CliBin) { Write-Error 'Pass -EvolverBin, or -CliBin pointing at evolver CLI cli.js.'; exit 1 }
666
+ if (-not (Test-Path $CliBin)) { Write-Error "Evolver CLI not found at $CliBin"; exit 1 }
667
+ } elseif (-not (Test-Path $EvolverBin)) {
668
+ Write-Error "Evolver binary not found at $EvolverBin"
669
+ exit 1
670
+ }
671
+
672
+ foreach ($launcherValue in @($EvolverBin, $NodePath, $CliBin, $EnvFile, $AutoexecHome, $WorkingDirectory)) {
673
+ if ($launcherValue -match "[\r\n]") {
674
+ Write-Error 'Launcher paths must not contain line breaks.'
675
+ exit 1
676
+ }
677
+ }
678
+
679
+ if (-not $WorkingDirectory) { $WorkingDirectory = $env:USERPROFILE }
680
+ if (-not (Test-Path $WorkingDirectory -PathType Container)) {
681
+ Write-Error 'WorkingDirectory must be an existing directory.'
682
+ exit 1
683
+ }
684
+
685
+ $existing = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
686
+ if ($existing -and $existing.State -eq 'Running') {
687
+ Stop-ScheduledTask -TaskName $TaskName
688
+ $stopDeadline = [DateTime]::UtcNow.AddSeconds(15)
689
+ do {
690
+ Start-Sleep -Milliseconds 100
691
+ $existing = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
692
+ } while ($existing -and $existing.State -eq 'Running' -and [DateTime]::UtcNow -lt $stopDeadline)
693
+ if ($existing -and $existing.State -eq 'Running') {
694
+ Write-Error 'Existing Evolver Autoexec Scheduled Task did not stop; refusing to replace it.'
695
+ exit 1
696
+ }
697
+ }
698
+
699
+ if (-not (Test-Path $launcherDir)) { New-Item -ItemType Directory -Path $launcherDir | Out-Null }
700
+
701
+ $nodeEsc = if ($NodePath) { $NodePath.Replace('"', '""') } else { '' }
702
+ $cliEsc = if ($CliBin) { $CliBin.Replace('"', '""') } else { '' }
703
+ $evolverEsc = if ($EvolverBin) { $EvolverBin.Replace('"', '""') } else { '' }
704
+ $envEsc = if ($EnvFile) { $EnvFile.Replace('"', '""') } else { '' }
705
+ $homeEsc = if ($AutoexecHome) { $AutoexecHome.Replace('"', '""') } else { '' }
706
+
707
+ $launcherBody = @"
708
+ ' AUTO-GENERATED by install-evolver-autoexec-windows.ps1 -- do not edit.
709
+ Dim WshShell, env, cmd, rc
710
+ Set WshShell = CreateObject("WScript.Shell")
711
+ Set env = WshShell.Environment("PROCESS")
712
+ If "$envEsc" <> "" Then env("EVOLVER_ENV_FILE") = "$envEsc"
713
+ If "$evolverEsc" <> "" Then
714
+ cmd = """$evolverEsc"" autoexec"
715
+ Else
716
+ cmd = """$nodeEsc"" ""$cliEsc"" autoexec"
717
+ End If
718
+ If "$homeEsc" <> "" Then cmd = cmd & " ""$homeEsc"""
719
+ rc = WshShell.Run(cmd, 0, True)
720
+ WScript.Quit rc
721
+ "@
722
+ Set-Content -Path $launcherPath -Value $launcherBody -Encoding Unicode
723
+
724
+ $action = New-ScheduledTaskAction -Execute 'wscript.exe' -Argument ('"{0}"' -f $launcherPath) -WorkingDirectory $WorkingDirectory
725
+ $user = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
726
+ $trigger = New-ScheduledTaskTrigger -AtLogOn -User $user
727
+ $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -RestartCount 5 -RestartInterval (New-TimeSpan -Minutes 2) -ExecutionTimeLimit (New-TimeSpan -Days 0) -MultipleInstances IgnoreNew
728
+ $principal = New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Limited
729
+ $task = New-ScheduledTask -Action $action -Trigger $trigger -Settings $settings -Principal $principal
730
+ Register-ScheduledTask -TaskName $TaskName -InputObject $task -Force | Out-Null
471
731
  Write-Host "Installed scheduled task '$TaskName' using hidden wscript launcher $launcherPath."
472
732
  `;
473
733
  }
@@ -494,9 +754,25 @@ function serviceTarget(flags) {
494
754
  return value;
495
755
  throw new Error('missing or invalid --target (expected: launchd|systemd|windows)');
496
756
  }
497
- async function installService(target, flags, env, argv1) {
757
+ async function installService(target, flags, env, argv1, loadUnixRecoveryController = () => import('@evomap/evolver-proxy')) {
498
758
  const dryRun = flags['dry-run'] === true;
499
- const envFile = typeof flags['env-file'] === 'string' ? flags['env-file'] : env['EVOLVER_ENV_FILE'];
759
+ const lifecycleStateDir = lifecyclePaths(env).stateDir;
760
+ if (flags['with-autoexec'] !== undefined && flags['with-autoexec'] !== true) {
761
+ throw new Error('--with-autoexec is a boolean flag and does not accept a value');
762
+ }
763
+ if (flags['autoexec-home'] === true) {
764
+ throw new Error('--autoexec-home requires a path');
765
+ }
766
+ const withAutoexec = flags['with-autoexec'] === true;
767
+ if (!withAutoexec && flags['autoexec-home'] !== undefined) {
768
+ throw new Error('--autoexec-home requires --with-autoexec');
769
+ }
770
+ const configuredEnvFile = typeof flags['env-file'] === 'string'
771
+ ? flags['env-file'].trim()
772
+ : nonBlankEnv(env, 'EVOLVER_ENV_FILE');
773
+ const envFile = configuredEnvFile
774
+ ? resolvePath(expandHomePath(configuredEnvFile))
775
+ : undefined;
500
776
  const supervised = configuredSelfUpdateTarget(env)
501
777
  ? resolveDaemonCommand(env, process.execPath, argv1)
502
778
  : resolveSelfUpdatingExecutable(process.execPath, argv1);
@@ -506,7 +782,7 @@ async function installService(target, flags, env, argv1) {
506
782
  let unixController;
507
783
  let unixControllerStateDir;
508
784
  if (target !== 'windows' && standaloneTarget) {
509
- const { provisionStableUnixRecoveryController, stableUnixRecoveryControllerPathForTarget, UNIX_RECOVERY_CONTROLLER_ARG, } = await import('@evomap/evolver-proxy');
785
+ const { provisionStableUnixRecoveryController, stableUnixRecoveryControllerPathForTarget, UNIX_RECOVERY_CONTROLLER_ARG, } = await loadUnixRecoveryController();
510
786
  const stateDir = env['EVOLVER_SELF_UPDATE_STATE_DIR']?.trim() || undefined;
511
787
  const controllerPath = dryRun
512
788
  ? stableUnixRecoveryControllerPathForTarget(standaloneTarget, stateDir)
@@ -522,11 +798,33 @@ async function installService(target, flags, env, argv1) {
522
798
  unixControllerStateDir = dirname(dirname(controllerPath));
523
799
  }
524
800
  const serviceCommand = unixController ?? supervised;
801
+ const autoexecHomeFlag = typeof flags['autoexec-home'] === 'string' ? flags['autoexec-home'].trim() : undefined;
802
+ if (autoexecHomeFlag !== undefined && !autoexecHomeFlag) {
803
+ throw new Error('--autoexec-home requires a non-empty path');
804
+ }
805
+ const companionWorkingDirectoryFlag = typeof flags['cwd'] === 'string'
806
+ ? assertSingleLine(flags['cwd'].trim(), 'service working directory')
807
+ : undefined;
808
+ const companionWorkingDirectory = companionWorkingDirectoryFlag
809
+ ? (isAbsolute(companionWorkingDirectoryFlag) ? companionWorkingDirectoryFlag : resolvePath(companionWorkingDirectoryFlag))
810
+ : process.cwd();
811
+ const autoexecHome = autoexecHomeFlag
812
+ ? assertSingleLine(isAbsolute(autoexecHomeFlag) ? autoexecHomeFlag : resolvePath(companionWorkingDirectory, autoexecHomeFlag), 'autoexec home')
813
+ : undefined;
814
+ const autoexecCommand = withAutoexec
815
+ ? resolveAutoexecDaemonCommand(env, process.execPath, argv1, autoexecHome)
816
+ : undefined;
817
+ if (withAutoexec && !autoexecCommand) {
818
+ throw new Error('cannot resolve the current evolver CLI for --with-autoexec; pass a standalone Evolver binary or run through cli.js');
819
+ }
525
820
  if (target === 'systemd') {
526
821
  const path = expandHome('~/.config/systemd/user/evolver-proxy.service');
822
+ const autoexecPath = expandHome('~/.config/systemd/user/evolver-autoexec.service');
823
+ const workingDirectory = typeof flags['cwd'] === 'string' ? flags['cwd'] : undefined;
527
824
  const unit = renderSystemdUnit({
528
825
  envFile,
529
- workingDirectory: typeof flags['cwd'] === 'string' ? flags['cwd'] : undefined,
826
+ lifecycleStateDir,
827
+ workingDirectory,
530
828
  ...(serviceCommand
531
829
  ? { execStart: [serviceCommand.command, ...serviceCommand.args].map(quoteSystemdArg).join(' ') }
532
830
  : {}),
@@ -535,17 +833,31 @@ async function installService(target, flags, env, argv1) {
535
833
  });
536
834
  if (!dryRun)
537
835
  writeTextFile(path, unit, 0o644);
836
+ if (autoexecCommand) {
837
+ const autoexecUnit = renderAutoexecSystemdUnit({
838
+ envFile,
839
+ workingDirectory: companionWorkingDirectory,
840
+ execStart: [autoexecCommand.command, ...autoexecCommand.args].map(quoteSystemdArg).join(' '),
841
+ });
842
+ if (!dryRun)
843
+ writeTextFile(autoexecPath, autoexecUnit, 0o644);
844
+ }
538
845
  return {
539
846
  status: dryRun ? 'rendered' : 'installed',
540
- files: [path, ...(unixController ? [unixController.command] : [])],
847
+ files: [path, ...(autoexecCommand ? [autoexecPath] : []), ...(unixController ? [unixController.command] : [])],
541
848
  service: 'systemd-user',
849
+ ...(autoexecHome ? { autoexecHome } : {}),
542
850
  };
543
851
  }
544
852
  if (target === 'launchd') {
545
853
  const path = expandHome('~/Library/LaunchAgents/com.evomap.evolver-proxy.plist');
854
+ const autoexecPath = expandHome('~/Library/LaunchAgents/com.evomap.evolver-autoexec.plist');
855
+ const workingDirectory = companionWorkingDirectory;
856
+ const logDir = join(homedir(), 'Library', 'Logs');
546
857
  const plist = renderLaunchdPlist({
547
858
  envFile,
548
- workingDirectory: typeof flags['cwd'] === 'string' ? flags['cwd'] : process.cwd(),
859
+ lifecycleStateDir,
860
+ workingDirectory,
549
861
  ...(serviceCommand
550
862
  ? { programArguments: [serviceCommand.command, ...serviceCommand.args] }
551
863
  : {}),
@@ -553,17 +865,29 @@ async function installService(target, flags, env, argv1) {
553
865
  ...(unixControllerStateDir ? { selfUpdateStateDir: unixControllerStateDir } : {}),
554
866
  nodePath: resolveStableNodePath(),
555
867
  proxyBin: resolveProxyBinPath() ?? (argv1?.startsWith('/') ? argv1 : undefined) ?? '/ABSOLUTE/PATH/TO/evolver-proxy.js',
556
- logDir: join(homedir(), 'Library', 'Logs'),
868
+ logDir,
557
869
  });
558
870
  if (!dryRun)
559
871
  writeTextFile(path, plist, 0o644);
872
+ if (autoexecCommand) {
873
+ const autoexecPlist = renderAutoexecLaunchdPlist({
874
+ envFile,
875
+ workingDirectory,
876
+ programArguments: [autoexecCommand.command, ...autoexecCommand.args],
877
+ logDir,
878
+ });
879
+ if (!dryRun)
880
+ writeTextFile(autoexecPath, autoexecPlist, 0o644);
881
+ }
560
882
  return {
561
883
  status: dryRun ? 'rendered' : 'installed',
562
- files: [path, ...(unixController ? [unixController.command] : [])],
884
+ files: [path, ...(autoexecCommand ? [autoexecPath] : []), ...(unixController ? [unixController.command] : [])],
563
885
  service: 'launchd',
886
+ ...(autoexecHome ? { autoexecHome } : {}),
564
887
  };
565
888
  }
566
- const path = expandHome('~/install-evolver-proxy-windows.ps1');
889
+ let path = expandHome('~/install-evolver-proxy-windows.ps1');
890
+ let autoexecPath = expandHome('~/install-evolver-autoexec-windows.ps1');
567
891
  const selfUpdateStateDir = env['EVOLVER_SELF_UPDATE_STATE_DIR']?.trim();
568
892
  const standalone = standaloneTarget;
569
893
  const script = renderWindowsInstaller({
@@ -572,11 +896,320 @@ async function installService(target, flags, env, argv1) {
572
896
  proxyBin: resolveProxyBinPath(),
573
897
  }),
574
898
  ...(envFile ? { envFile } : {}),
899
+ lifecycleStateDir,
575
900
  ...(selfUpdateStateDir ? { selfUpdateStateDir } : {}),
576
901
  });
577
902
  if (!dryRun)
578
- writeTextFile(path, script, 0o644);
579
- return { status: dryRun ? 'rendered' : 'installed', files: [path], service: 'windows-scheduled-task' };
903
+ path = writeWindowsHelper(path, script);
904
+ if (autoexecCommand) {
905
+ const standaloneAutoexec = autoexecCommand.args[0] === 'autoexec';
906
+ const autoexecScript = renderWindowsAutoexecInstaller({
907
+ ...(standaloneAutoexec
908
+ ? { evolverBin: autoexecCommand.command }
909
+ : { nodePath: autoexecCommand.command, cliBin: autoexecCommand.args[0] }),
910
+ ...(envFile ? { envFile } : {}),
911
+ ...(autoexecHome ? { autoexecHome } : {}),
912
+ workingDirectory: companionWorkingDirectory,
913
+ });
914
+ if (!dryRun)
915
+ autoexecPath = writeWindowsHelper(autoexecPath, autoexecScript);
916
+ }
917
+ return {
918
+ status: dryRun ? 'rendered' : 'installed',
919
+ files: [path, ...(autoexecCommand ? [autoexecPath] : [])],
920
+ service: 'windows-scheduled-task',
921
+ ...(autoexecHome ? { autoexecHome } : {}),
922
+ };
923
+ }
924
+ function defaultBootstrapTarget(platform) {
925
+ if (platform === 'darwin')
926
+ return 'launchd';
927
+ if (platform === 'win32')
928
+ return 'windows';
929
+ return 'systemd';
930
+ }
931
+ /**
932
+ * First-run supervision bootstrap: render + write the durable launcher for the current platform
933
+ * (reusing install-service), then ACTIVATE it (user-level, no admin required) and persist a
934
+ * success marker the proxy consults before attempting another bootstrap. The generated launcher
935
+ * carries the EVOLVER_SELF_UPDATE_SUPERVISOR attestation, so self-update becomes eligible on the
936
+ * next supervised startup. Activation failures throw (fail closed) after a best-effort rollback of
937
+ * the launcher artifacts, so a half-activated unit/agent/task never survives a failed bootstrap.
938
+ */
939
+ async function bootstrapService(flags, env, argv1, deps, loadUnixRecoveryController) {
940
+ if (flags['dry-run'] !== undefined && flags['dry-run'] !== true) {
941
+ throw new Error('--dry-run is a boolean flag and does not accept a value');
942
+ }
943
+ const platform = deps.platform ?? process.platform;
944
+ const target = typeof flags['target'] === 'string' ? serviceTarget(flags) : defaultBootstrapTarget(platform);
945
+ const dryRun = flags['dry-run'] === true;
946
+ if (platform !== 'win32') {
947
+ const uid = deps.uid ?? (typeof process.getuid === 'function' ? process.getuid() : undefined);
948
+ if (uid === 0) {
949
+ throw new Error('bootstrap must run as a regular (non-root) user: the systemd --user manager and the launchd gui domain do not exist for root; install as your normal user and, on headless hosts, run `loginctl enable-linger` for that user');
950
+ }
951
+ }
952
+ const install = deps.install ?? installService;
953
+ const handedOffEnvFile = nonBlankEnv(env, BOOTSTRAP_ENV_FILE_HANDOFF);
954
+ const installFlags = handedOffEnvFile && typeof flags['env-file'] !== 'string'
955
+ ? { ...flags, 'env-file': handedOffEnvFile }
956
+ : flags;
957
+ const installed = await install(target, installFlags, env, argv1, loadUnixRecoveryController);
958
+ const files = installed.files ?? [];
959
+ if (dryRun) {
960
+ return { status: 'planned', files, service: installed.service, actions: bootstrapActivationPlan(target, files, deps.uid) };
961
+ }
962
+ const run = deps.run ?? ((command, args) => {
963
+ const result = spawnSync(command, [...args], { stdio: 'ignore', timeout: 60_000, windowsHide: true });
964
+ return { status: result.status, ...(result.error ? { error: result.error } : {}) };
965
+ });
966
+ const preExisting = probePreExistingBootstrapService(target, run, deps.uid);
967
+ const markerPath = join(lifecyclePaths(env).stateDir, 'bootstrap.json');
968
+ let actions;
969
+ try {
970
+ actions = activateBootstrapTarget(target, files, run, deps.uid);
971
+ }
972
+ catch (error) {
973
+ const rollbackErrors = rollbackBootstrapArtifacts(target, files, run, deps.uid, preExisting);
974
+ // Activation failed, so supervision was never established and any success marker left over
975
+ // from a previous run is no longer true. Drop it (force, best-effort) so the proxy's
976
+ // shouldBootstrap no longer reports already_bootstrapped for a broken install; a failure here
977
+ // must not mask the original activation error.
978
+ try {
979
+ rmSync(markerPath, { force: true });
980
+ }
981
+ catch {
982
+ // best-effort: a stale marker is less harmful than swallowing the activation error
983
+ }
984
+ const rollbackSuffix = rollbackErrors.length > 0 ? ` (rollback also failed: ${rollbackErrors.join('; ')})` : '';
985
+ throw new Error(`${error.message}; launcher artifacts were rolled back${rollbackSuffix}`);
986
+ }
987
+ writeTextFile(markerPath, `${JSON.stringify({
988
+ bootstrappedAt: new Date().toISOString(),
989
+ target,
990
+ service: installed.service,
991
+ files,
992
+ })}\n`, 0o600);
993
+ return { status: 'bootstrapped', files: [...files, markerPath], service: installed.service, actions };
994
+ }
995
+ function bootstrapActivationPlan(target, files, uid) {
996
+ if (target === 'systemd') {
997
+ return [
998
+ 'systemctl --user daemon-reload',
999
+ 'systemctl --user enable --now evolver-proxy.service',
1000
+ ];
1001
+ }
1002
+ if (target === 'launchd') {
1003
+ const plist = expandHome('~/Library/LaunchAgents/com.evomap.evolver-proxy.plist');
1004
+ return [`launchctl bootstrap gui/${uid ?? '<uid>'} ${plist}`];
1005
+ }
1006
+ const installer = files[0] ?? expandHome('~/install-evolver-proxy-windows.ps1');
1007
+ return [`powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File ${installer} -Install`];
1008
+ }
1009
+ function activateBootstrapTarget(target, files, run, uid) {
1010
+ if (target === 'systemd') {
1011
+ requireBootstrapActivation(run('systemctl', ['--user', 'daemon-reload']), [0], 'reload systemd user manager');
1012
+ requireBootstrapActivation(run('systemctl', ['--user', 'enable', '--now', 'evolver-proxy.service']), [0], 'enable systemd user service', 'if no user session bus exists, run `loginctl enable-linger` and retry');
1013
+ return bootstrapActivationPlan(target, files, uid);
1014
+ }
1015
+ if (target === 'launchd') {
1016
+ const userId = uid ?? (typeof process.getuid === 'function' ? process.getuid() : undefined);
1017
+ if (userId === undefined)
1018
+ throw new Error('cannot determine the current user id for launchd bootstrap');
1019
+ const plist = expandHome('~/Library/LaunchAgents/com.evomap.evolver-proxy.plist');
1020
+ // 3/113: already bootstrapped/loaded; 5: "Bootstrap failed: service already loaded". All three
1021
+ // mean an identical agent is already registered, so a re-bootstrap stays idempotent instead of
1022
+ // failing and rolling back a working install.
1023
+ requireBootstrapActivation(run('launchctl', ['bootstrap', `gui/${userId}`, plist]), [0, 3, 5, 113], 'bootstrap launchd agent', 'launchctl bootstrap gui/<uid> requires an active GUI (Aqua) login session; log in at the console (or retry after your next GUI login)');
1024
+ return [`launchctl bootstrap gui/${userId} ${plist}`];
1025
+ }
1026
+ const installer = files[0];
1027
+ if (!installer)
1028
+ throw new Error('bootstrap could not locate the generated Windows installer script');
1029
+ requireBootstrapActivation(run('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', installer, '-Install']), [0], 'register Windows scheduled task');
1030
+ return [`powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File ${installer} -Install`];
1031
+ }
1032
+ function requireBootstrapActivation(result, allowedStatuses, operation, hint) {
1033
+ if (result.error || result.status === null || !allowedStatuses.includes(result.status)) {
1034
+ throw new Error(`bootstrap activation failed during ${operation}${hint ? ` (hint: ${hint})` : ''}`);
1035
+ }
1036
+ }
1037
+ /**
1038
+ * Best-effort probe for a same-name service registration that existed before this bootstrap run.
1039
+ * Only an unambiguous "not registered" exit status reports false; any error, inconclusive, or
1040
+ * loaded-looking outcome reports true, so a later rollback conservatively leaves an existing
1041
+ * registration intact instead of tearing down a working install. The probe must never block the
1042
+ * bootstrap itself.
1043
+ */
1044
+ function probePreExistingBootstrapService(target, run, uid) {
1045
+ let result;
1046
+ let absentStatuses;
1047
+ try {
1048
+ if (target === 'systemd') {
1049
+ // 1: not enabled, 4: no such unit. A working install is enabled (exit 0).
1050
+ result = run('systemctl', ['--user', 'is-enabled', '--quiet', 'evolver-proxy.service']);
1051
+ absentStatuses = [1, 4];
1052
+ }
1053
+ else if (target === 'launchd') {
1054
+ const userId = uid ?? (typeof process.getuid === 'function' ? process.getuid() : undefined);
1055
+ if (userId === undefined)
1056
+ return true;
1057
+ // 3: no such service, 113: the gui domain itself is absent (nothing can be loaded there).
1058
+ result = run('launchctl', ['print', `gui/${userId}`, 'com.evomap.evolver-proxy']);
1059
+ absentStatuses = [3, 113];
1060
+ }
1061
+ else {
1062
+ // 1: Get-ScheduledTask raised because the task does not exist; 0 means it is registered.
1063
+ result = run('powershell.exe', [
1064
+ '-NoProfile',
1065
+ '-NonInteractive',
1066
+ '-ExecutionPolicy',
1067
+ 'Bypass',
1068
+ '-Command',
1069
+ 'Get-ScheduledTask -TaskName EvoMapEvolverProxyDaemon',
1070
+ ]);
1071
+ absentStatuses = [1];
1072
+ }
1073
+ }
1074
+ catch {
1075
+ return true;
1076
+ }
1077
+ if (result.error !== undefined || result.status === null)
1078
+ return true;
1079
+ return !absentStatuses.includes(result.status);
1080
+ }
1081
+ /**
1082
+ * Best-effort rollback of the launcher artifacts written before a failed activation. Every step
1083
+ * ignores its own failure (reported back to the caller instead of thrown), so the original
1084
+ * activation error always surfaces. Uses the injected `run` so tests can observe the sequence.
1085
+ * When the probe detected a pre-existing same-name registration, this rollback is a strict no-op:
1086
+ * no teardown command, no file deletion, not even a systemd daemon-reload. installService already
1087
+ * overwrote the canonical unit/plist/installer before the probe could run, so the on-disk content
1088
+ * is inevitably the new rendering; deleting it would orphan a still-running service (no on-disk
1089
+ * definition, so it would stop auto-loading after a reboot), which is strictly worse than leaving
1090
+ * the updated content in place. The working install must survive a failed re-bootstrap untouched.
1091
+ */
1092
+ function rollbackBootstrapArtifacts(target, files, run, uid, preExisting = false) {
1093
+ const errors = [];
1094
+ if (preExisting)
1095
+ return errors;
1096
+ const attempt = (label, action) => {
1097
+ try {
1098
+ action();
1099
+ }
1100
+ catch (error) {
1101
+ errors.push(`${label}: ${error.message}`);
1102
+ }
1103
+ };
1104
+ const removeFile = (file) => attempt(`remove ${file}`, () => { rmSync(file, { force: true }); });
1105
+ if (target === 'systemd') {
1106
+ attempt('disable systemd user service', () => { run('systemctl', ['--user', 'disable', '--now', 'evolver-proxy.service']); });
1107
+ const unit = files.find((file) => basename(file) === 'evolver-proxy.service');
1108
+ if (unit)
1109
+ removeFile(unit);
1110
+ attempt('reload systemd user manager', () => { run('systemctl', ['--user', 'daemon-reload']); });
1111
+ return errors;
1112
+ }
1113
+ if (target === 'launchd') {
1114
+ const plist = files.find((file) => file.endsWith('.plist')) ?? expandHome('~/Library/LaunchAgents/com.evomap.evolver-proxy.plist');
1115
+ const userId = uid ?? (typeof process.getuid === 'function' ? process.getuid() : undefined);
1116
+ if (userId !== undefined) {
1117
+ attempt(`bootout launchd agent gui/${userId}`, () => { run('launchctl', ['bootout', `gui/${userId}`, plist]); });
1118
+ }
1119
+ removeFile(plist);
1120
+ return errors;
1121
+ }
1122
+ const installer = files[0];
1123
+ if (installer) {
1124
+ attempt('unregister Windows scheduled task', () => {
1125
+ run('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', installer, '-Uninstall']);
1126
+ });
1127
+ }
1128
+ for (const file of files)
1129
+ removeFile(file);
1130
+ return errors;
1131
+ }
1132
+ export function removeAutoexecService(target, dryRun, deps = {}) {
1133
+ const paths = {
1134
+ systemd: expandHome('~/.config/systemd/user/evolver-autoexec.service'),
1135
+ launchd: expandHome('~/Library/LaunchAgents/com.evomap.evolver-autoexec.plist'),
1136
+ windows: expandHome('~/install-evolver-autoexec-windows.ps1'),
1137
+ };
1138
+ const configuredPath = deps.paths?.[target] ?? paths[target];
1139
+ const path = target === 'windows' && !dryRun ? randomWindowsHelperPath(configuredPath) : configuredPath;
1140
+ const run = deps.run ?? ((command, args) => {
1141
+ const result = spawnSync(command, [...args], { stdio: 'ignore', timeout: 30_000, windowsHide: true });
1142
+ return { status: result.status, ...(result.error ? { error: result.error } : {}) };
1143
+ });
1144
+ const exists = deps.exists ?? existsSync;
1145
+ const remove = deps.remove ?? ((file) => { rmSync(file, { force: true }); });
1146
+ const write = deps.write ?? ((file, content, mode) => {
1147
+ writeTextFile(file, content, mode, 'wx');
1148
+ });
1149
+ if (target === 'systemd') {
1150
+ const actions = [
1151
+ 'systemctl --user disable --now evolver-autoexec.service',
1152
+ `remove ${path}`,
1153
+ 'systemctl --user daemon-reload',
1154
+ ];
1155
+ if (dryRun)
1156
+ return { status: 'planned', files: [path], service: 'systemd-user', actions };
1157
+ const active = requireServiceControlStatus(run('systemctl', ['--user', 'is-active', '--quiet', 'evolver-autoexec.service']), [0, 3, 4], 'inspect systemd autoexec activity');
1158
+ const enabled = requireServiceControlStatus(run('systemctl', ['--user', 'is-enabled', '--quiet', 'evolver-autoexec.service']), [0, 1, 4], 'inspect systemd autoexec enablement');
1159
+ const hasUnit = exists(path);
1160
+ if (active !== 0 && enabled !== 0 && !hasUnit) {
1161
+ return { status: 'absent', files: [path], service: 'systemd-user', actions: [] };
1162
+ }
1163
+ requireServiceControlStatus(run('systemctl', ['--user', 'disable', '--now', 'evolver-autoexec.service']), [0], 'disable systemd autoexec service');
1164
+ if (hasUnit)
1165
+ remove(path);
1166
+ requireServiceControlStatus(run('systemctl', ['--user', 'daemon-reload']), [0], 'reload systemd user services');
1167
+ return { status: 'removed', files: [path], service: 'systemd-user', actions };
1168
+ }
1169
+ if (target === 'launchd') {
1170
+ const uid = deps.uid ?? (typeof process.getuid === 'function' ? process.getuid() : undefined);
1171
+ const launchdTarget = `gui/${uid ?? '<uid>'}/${AUTOEXEC_LABEL}`;
1172
+ const actions = [`launchctl bootout ${launchdTarget}`, `remove ${path}`];
1173
+ if (dryRun)
1174
+ return { status: 'planned', files: [path], service: 'launchd', actions };
1175
+ if (uid === undefined)
1176
+ throw new Error('cannot determine the current user id for launchd autoexec removal');
1177
+ requireServiceControlStatus(run('launchctl', ['bootout', `gui/${uid}/${AUTOEXEC_LABEL}`]), [0, 3, 113], 'boot out launchd autoexec service');
1178
+ const hasPlist = exists(path);
1179
+ if (hasPlist)
1180
+ remove(path);
1181
+ return {
1182
+ status: hasPlist ? 'removed' : 'absent',
1183
+ files: [path],
1184
+ service: 'launchd',
1185
+ actions: hasPlist ? actions : actions.slice(0, 1),
1186
+ };
1187
+ }
1188
+ const actions = [
1189
+ `write ${path}`,
1190
+ `powershell.exe -File ${path} -Uninstall`,
1191
+ `remove ${path}`,
1192
+ ];
1193
+ if (dryRun)
1194
+ return { status: 'planned', files: [path], service: 'windows-scheduled-task', actions };
1195
+ write(path, renderWindowsAutoexecInstaller(), 0o644);
1196
+ requireServiceControlStatus(run('powershell.exe', [
1197
+ '-NoProfile',
1198
+ '-NonInteractive',
1199
+ '-ExecutionPolicy',
1200
+ 'Bypass',
1201
+ '-File',
1202
+ path,
1203
+ '-Uninstall',
1204
+ ]), [0], 'uninstall Windows autoexec scheduled task');
1205
+ remove(path);
1206
+ return { status: 'removed', files: [path], service: 'windows-scheduled-task', actions };
1207
+ }
1208
+ function requireServiceControlStatus(result, allowedStatuses, operation) {
1209
+ if (result.error || result.status === null || !allowedStatuses.includes(result.status)) {
1210
+ throw new Error(`${operation} failed; companion artifact was retained`);
1211
+ }
1212
+ return result.status;
580
1213
  }
581
1214
  async function runWatch(paths, env, flags, stdout, stderr) {
582
1215
  const once = flags['once'] === true;
@@ -675,6 +1308,23 @@ export function resolveSelfUpdatingExecutable(execPath, argv1) {
675
1308
  }
676
1309
  return undefined;
677
1310
  }
1311
+ export function resolveAutoexecDaemonCommand(env, execPath = process.execPath, argv1 = process.argv[1], autoexecHome) {
1312
+ const target = configuredSelfUpdateTarget(env);
1313
+ const proxyCommand = target
1314
+ ? standaloneProxyCommand(target)
1315
+ : resolveSelfUpdatingExecutable(execPath, argv1);
1316
+ if (!proxyCommand || proxyCommand.args.at(-1) !== 'proxy')
1317
+ return undefined;
1318
+ const args = [...proxyCommand.args.slice(0, -1), 'autoexec'];
1319
+ const home = autoexecHome?.trim();
1320
+ if (home)
1321
+ args.push(home);
1322
+ return {
1323
+ command: proxyCommand.command,
1324
+ args,
1325
+ display: [proxyCommand.command, ...args].join(' '),
1326
+ };
1327
+ }
678
1328
  export function resolveProxyBinPath() {
679
1329
  try {
680
1330
  const entry = requireFromHere.resolve('@evomap/evolver-proxy');
@@ -756,23 +1406,32 @@ function readPidFile(path) {
756
1406
  return { owned: false, legacy: false };
757
1407
  }
758
1408
  }
759
- function pidFileRecordMatchesProcess(pidFile, readCommandLine = processCommandLine, readIdentity = processIdentity) {
1409
+ function pidFileRecordMatchesProcess(pidFile, readCommandLine = processCommandLine, readIdentity = processIdentity, platform = process.platform) {
760
1410
  if (!pidFile.owned || !pidFile.record)
761
1411
  return false;
762
1412
  const record = pidFile.record;
763
1413
  const commandLine = readCommandLine(record.pid);
764
- if (commandLine && commandLine.includes(basename(record.command)))
765
- return record.args.every((arg) => commandLine.includes(arg));
766
- return processIdentityMatchesRecord(record, readIdentity(record.pid));
1414
+ const commandMatches = Boolean(commandLine
1415
+ && commandLine.includes(basename(record.command))
1416
+ && record.args.every((arg) => commandLine.includes(arg)));
1417
+ const identity = readIdentity(record.pid);
1418
+ if (commandLine?.includes(basename(record.command))) {
1419
+ if (!commandMatches)
1420
+ return false;
1421
+ if (identity !== undefined)
1422
+ return processIdentityMatchesRecord(record, identity);
1423
+ return platform !== 'win32';
1424
+ }
1425
+ return processIdentityMatchesRecord(record, identity);
767
1426
  }
768
- function waitForPidFileRecordMatch(pidFile, timeoutMs, readCommandLine = processCommandLine, readIdentity = processIdentity) {
1427
+ function waitForPidFileRecordMatch(pidFile, timeoutMs, readCommandLine = processCommandLine, readIdentity = processIdentity, platform = process.platform) {
769
1428
  const start = Date.now();
770
1429
  while (Date.now() - start < timeoutMs) {
771
- if (pidFileRecordMatchesProcess(pidFile, readCommandLine, readIdentity))
1430
+ if (pidFileRecordMatchesProcess(pidFile, readCommandLine, readIdentity, platform))
772
1431
  return true;
773
1432
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);
774
1433
  }
775
- return pidFileRecordMatchesProcess(pidFile, readCommandLine, readIdentity);
1434
+ return pidFileRecordMatchesProcess(pidFile, readCommandLine, readIdentity, platform);
776
1435
  }
777
1436
  function processCommandLine(pid) {
778
1437
  if (process.platform === 'win32') {
@@ -1031,12 +1690,42 @@ function expandHome(path) {
1031
1690
  return join(homedir(), path.slice(2));
1032
1691
  return path;
1033
1692
  }
1034
- function writeTextFile(path, content, mode) {
1693
+ function randomWindowsHelperPath(preferredPath) {
1694
+ const extension = extname(preferredPath) || '.ps1';
1695
+ const stem = basename(preferredPath, extension);
1696
+ return join(dirname(preferredPath), `${stem}-${randomUUID()}${extension}`);
1697
+ }
1698
+ function writeWindowsHelper(preferredPath, content) {
1699
+ try {
1700
+ writeTextFile(preferredPath, content, 0o600, 'wx');
1701
+ return preferredPath;
1702
+ }
1703
+ catch (error) {
1704
+ if (error.code !== 'EEXIST')
1705
+ throw error;
1706
+ }
1707
+ const fallbackPath = randomWindowsHelperPath(preferredPath);
1708
+ writeTextFile(fallbackPath, content, 0o600, 'wx');
1709
+ return fallbackPath;
1710
+ }
1711
+ export const _writeWindowsHelperForTest = writeWindowsHelper;
1712
+ function writeTextFile(path, content, mode = 0o600, flag = 'w') {
1035
1713
  mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
1036
- writeFileSync(path, content, { encoding: 'utf8', mode });
1714
+ writeFileSync(path, content, { encoding: 'utf8', mode, flag });
1715
+ }
1716
+ function assertSingleLine(value, label) {
1717
+ for (const character of value) {
1718
+ const code = character.charCodeAt(0);
1719
+ if (code <= 0x1f || code === 0x7f)
1720
+ throw new Error(`${label} must not contain control characters`);
1721
+ }
1722
+ return value;
1723
+ }
1724
+ function escapeSystemdPercent(value) {
1725
+ return value.replaceAll('%', '%%');
1037
1726
  }
1038
1727
  function escapeXml(value) {
1039
- return value
1728
+ return assertSingleLine(value, 'launchd value')
1040
1729
  .replaceAll('&', '&amp;')
1041
1730
  .replaceAll('<', '&lt;')
1042
1731
  .replaceAll('>', '&gt;')
@@ -1044,12 +1733,17 @@ function escapeXml(value) {
1044
1733
  .replaceAll("'", '&apos;');
1045
1734
  }
1046
1735
  function escapeSystemdEnvValue(value) {
1047
- return value.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('$', '\\$');
1736
+ return assertSingleLine(value, 'systemd environment value')
1737
+ .replaceAll('\\', '\\\\')
1738
+ .replaceAll('"', '\\"')
1739
+ .replaceAll('$', '\\$')
1740
+ .replaceAll('%', '%%');
1048
1741
  }
1049
1742
  function quoteSystemdArg(value) {
1050
- return /^[A-Za-z0-9_/:.@%+=,-]+$/.test(value)
1051
- ? value
1052
- : `"${value.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('$', '\\$')}"`;
1743
+ const safe = assertSingleLine(value, 'systemd argument');
1744
+ return /^[A-Za-z0-9_/:.@%+=,-]+$/.test(safe)
1745
+ ? safe
1746
+ : `"${safe.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('$', '\\$')}"`;
1053
1747
  }
1054
1748
  function resolveCurrentCliPath() {
1055
1749
  return fileURLToPath(new URL('./cli.js', import.meta.url));