@evomap/evolver-cli 2.0.0-beta.18 → 2.0.0-beta.19

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 (63) hide show
  1. package/dist/antiGeneRollout.js +7 -3
  2. package/dist/assetTrust.js +14 -1
  3. package/dist/atp.d.ts +8 -3
  4. package/dist/atp.js +82 -11
  5. package/dist/atpAutoBuyer.d.ts +120 -0
  6. package/dist/atpAutoBuyer.js +814 -0
  7. package/dist/atpAutoDeliver.js +2 -2
  8. package/dist/autoDistillLlm.js +2 -1
  9. package/dist/autoDistillTranscript.js +3 -2
  10. package/dist/autoexec.d.ts +90 -13
  11. package/dist/autoexec.js +731 -84
  12. package/dist/cli.js +13 -0
  13. package/dist/cliContracts.d.ts +5 -2
  14. package/dist/cliContracts.js +135 -8
  15. package/dist/commands.d.ts +1 -0
  16. package/dist/commands.js +1 -0
  17. package/dist/curriculumCapabilityGaps.d.ts +6 -0
  18. package/dist/curriculumCapabilityGaps.js +24 -0
  19. package/dist/cycleConsumer.d.ts +4 -0
  20. package/dist/cycleConsumer.js +175 -20
  21. package/dist/dashboard.js +47 -9
  22. package/dist/dispatch.js +6 -2
  23. package/dist/distillPrimitives.js +18 -6
  24. package/dist/doctor.js +63 -5
  25. package/dist/identityHome.js +2 -1
  26. package/dist/index.d.ts +67 -39
  27. package/dist/index.js +504 -185
  28. package/dist/learningTrace.js +8 -2
  29. package/dist/lifecycle.d.ts +54 -1
  30. package/dist/lifecycle.js +489 -37
  31. package/dist/materialSnapshot.d.ts +9 -1
  32. package/dist/materialSnapshot.js +23 -6
  33. package/dist/migrate/envTranslate.d.ts +26 -0
  34. package/dist/migrate/envTranslate.js +145 -0
  35. package/dist/migrate/oauthImport.d.ts +66 -0
  36. package/dist/migrate/oauthImport.js +667 -0
  37. package/dist/migrate/v1Import.d.ts +13 -1
  38. package/dist/migrate/v1Import.js +621 -122
  39. package/dist/promptRecallHook.d.ts +24 -0
  40. package/dist/promptRecallHook.js +425 -0
  41. package/dist/recallVerifyReport.d.ts +37 -0
  42. package/dist/recallVerifyReport.js +244 -0
  43. package/dist/requiredSandboxValidation.d.ts +5 -0
  44. package/dist/requiredSandboxValidation.js +4 -0
  45. package/dist/reuse.d.ts +1 -0
  46. package/dist/reuse.js +45 -37
  47. package/dist/runtimeCapabilities.js +13 -13
  48. package/dist/runtimeSessionSource.d.ts +3 -2
  49. package/dist/runtimeSessionSource.js +63 -11
  50. package/dist/sessionIngest.d.ts +37 -0
  51. package/dist/sessionIngest.js +156 -0
  52. package/dist/setupHooks.js +95 -1
  53. package/dist/skill2gep.d.ts +4 -7
  54. package/dist/skill2gep.js +4 -21
  55. package/dist/solo/mode.js +1 -0
  56. package/dist/sync.js +125 -23
  57. package/dist/thesis.d.ts +1 -1
  58. package/dist/thesis.js +18 -3
  59. package/dist/trajectoryExport.js +21 -3
  60. package/dist/v1Compat.d.ts +1 -0
  61. package/dist/v1Compat.js +9 -0
  62. package/dist/workflowRuntime.js +24 -18
  63. package/package.json +10 -7
package/dist/lifecycle.js CHANGED
@@ -1,15 +1,18 @@
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
8
  import { 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 LIFECYCLE_USAGE = 'Usage: evolver lifecycle <start|stop|restart|status|check|watch|install-service --target=launchd|systemd|windows [--with-autoexec] [--autoexec-home=<path>]|remove-autoexec-service --target=launchd|systemd|windows [--dry-run]>\n';
13
16
  export function runLifecycleCommand(argv, deps = {}) {
14
17
  return runLifecycleCommandInner(argv, deps).catch((err) => {
15
18
  const stderr = deps.stderr ?? ((text) => { process.stderr.write(text); });
@@ -18,10 +21,14 @@ export function runLifecycleCommand(argv, deps = {}) {
18
21
  });
19
22
  }
20
23
  async function runLifecycleCommandInner(argv, deps) {
21
- const action = argv[0];
22
24
  const env = deps.env ?? process.env;
23
25
  const stdout = deps.stdout ?? ((text) => { process.stdout.write(text); });
24
26
  const stderr = deps.stderr ?? ((text) => { process.stderr.write(text); });
27
+ if (argv[0] === '--help' || argv[0] === '-h') {
28
+ stdout(LIFECYCLE_USAGE);
29
+ return 0;
30
+ }
31
+ const action = argv[0];
25
32
  const flags = parseFlags(argv.slice(1));
26
33
  const paths = lifecyclePaths(env);
27
34
  switch (action) {
@@ -77,8 +84,17 @@ async function runLifecycleCommandInner(argv, deps) {
77
84
  stdout(`${JSON.stringify(result, null, 2)}\n`);
78
85
  return 0;
79
86
  }
87
+ case 'remove-autoexec-service': {
88
+ if (flags['dry-run'] !== undefined && flags['dry-run'] !== true) {
89
+ throw new Error('--dry-run is a boolean flag and does not accept a value');
90
+ }
91
+ const target = serviceTarget(flags);
92
+ const result = (deps.removeAutoexecService ?? removeAutoexecService)(target, flags['dry-run'] === true);
93
+ stdout(`${JSON.stringify(result, null, 2)}\n`);
94
+ return 0;
95
+ }
80
96
  default:
81
- stderr('用法: evolver lifecycle <start|stop|restart|status|check|watch|install-service --target=launchd|systemd|windows>\n');
97
+ stderr(LIFECYCLE_USAGE);
82
98
  return action === undefined ? 0 : 1;
83
99
  }
84
100
  }
@@ -168,7 +184,7 @@ export function stopLifecycle(paths, deps = {}) {
168
184
  rmSync(paths.pidFile, { force: true });
169
185
  return { status: 'not_running' };
170
186
  }
171
- if (!pidFile.owned || !waitForPidFileRecordMatch(pidFile, 1_000, deps.processCommandLine ?? processCommandLine, deps.processIdentity ?? processIdentity)) {
187
+ if (!pidFile.owned || !waitForPidFileRecordMatch(pidFile, 1_000, deps.processCommandLine ?? processCommandLine, deps.processIdentity ?? processIdentity, deps.platform ?? process.platform)) {
172
188
  return { status: 'not_owned', pid, reason: 'pidfile_owner_unconfirmed' };
173
189
  }
174
190
  try {
@@ -222,6 +238,36 @@ export async function lifecycleStatus(paths, env = process.env, options = {}) {
222
238
  logFile: paths.logFile,
223
239
  };
224
240
  }
241
+ /** Fetch enriched connection status for the daily summary. Builds on lifecycleStatus, adding hub details. */
242
+ export async function dailyConnectionStatus(paths, env = process.env, options = {}) {
243
+ const base = await lifecycleStatus(paths, env, { ...options, quietSettingsReadError: true });
244
+ if (!base.running || !base.healthy)
245
+ return base;
246
+ // Proxy is healthy — fetch /proxy/status for hub details
247
+ const settings = readProxySettings(paths.settingsFile, { quietReadError: true });
248
+ if (!settings.url || !settings.token)
249
+ return base;
250
+ const controller = new AbortController();
251
+ const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? DEFAULT_HEALTH_TIMEOUT_MS);
252
+ try {
253
+ const url = `${settings.url.replace(/\/+$/, '')}/proxy/status`;
254
+ const res = await fetch(url, { headers: { authorization: `Bearer ${settings.token}` }, signal: controller.signal });
255
+ if (!res.ok)
256
+ return base;
257
+ const body = await res.json();
258
+ return {
259
+ ...base,
260
+ hubAuthStatus: typeof body['hub_auth_status'] === 'string' ? body['hub_auth_status'] : undefined,
261
+ lastSyncAt: typeof body['last_sync_at'] === 'string' ? body['last_sync_at'] : undefined,
262
+ };
263
+ }
264
+ catch {
265
+ return base;
266
+ }
267
+ finally {
268
+ clearTimeout(timeout);
269
+ }
270
+ }
225
271
  export function lifecyclePaths(env = process.env) {
226
272
  const home = env['EVOLVER_HOME'] ?? env['EVOMAP_HOME'] ?? join(homedir(), '.evomap');
227
273
  const stateDir = env['EVOLVER_LIFECYCLE_STATE_DIR'] ?? join(home, 'lifecycle');
@@ -242,6 +288,10 @@ function nonBlankEnv(env, key) {
242
288
  return value ? value : undefined;
243
289
  }
244
290
  export function renderSystemdUnit(opts = {}) {
291
+ const execStart = assertSingleLine(opts.execStart ?? defaultServiceExecStart(), 'systemd ExecStart');
292
+ const workingDirectory = opts.workingDirectory === undefined
293
+ ? '%h'
294
+ : quoteSystemdArg(isAbsolute(opts.workingDirectory) ? opts.workingDirectory : resolvePath(opts.workingDirectory));
245
295
  return [
246
296
  '# Linux systemd user unit -- ~/.config/systemd/user/evolver-proxy.service',
247
297
  '[Unit]',
@@ -252,8 +302,11 @@ export function renderSystemdUnit(opts = {}) {
252
302
  'StartLimitIntervalSec=120s',
253
303
  '',
254
304
  '[Service]',
255
- 'Type=simple',
256
- `WorkingDirectory=${opts.workingDirectory ?? '%h'}`,
305
+ 'Type=notify',
306
+ '# The stable recovery controller may be MainPID; the proxy child invokes systemd-notify.',
307
+ 'NotifyAccess=all',
308
+ 'WatchdogSec=180s',
309
+ `WorkingDirectory=${workingDirectory}`,
257
310
  ...(opts.envFile ? [`Environment="EVOLVER_ENV_FILE=${escapeSystemdEnvValue(opts.envFile)}"`] : []),
258
311
  'Environment="EVOLVER_SELF_UPDATE_SUPERVISOR=systemd"',
259
312
  ...(opts.selfUpdateStateDir
@@ -262,7 +315,7 @@ export function renderSystemdUnit(opts = {}) {
262
315
  ...(opts.selfUpdateTarget
263
316
  ? [`Environment="EVOLVER_SELF_UPDATE_TARGET_PATH=${escapeSystemdEnvValue(opts.selfUpdateTarget)}"`]
264
317
  : []),
265
- `ExecStart=${opts.execStart ?? defaultServiceExecStart()}`,
318
+ `ExecStart=${execStart}`,
266
319
  'Restart=on-failure',
267
320
  'RestartSec=5s',
268
321
  'RestartPreventExitStatus=0',
@@ -279,12 +332,49 @@ export function renderSystemdUnit(opts = {}) {
279
332
  '',
280
333
  ].join('\n');
281
334
  }
335
+ export function renderAutoexecSystemdUnit(opts) {
336
+ const execStart = escapeSystemdPercent(assertSingleLine(opts.execStart, 'systemd ExecStart'));
337
+ const workingDirectory = opts.workingDirectory === undefined
338
+ ? '%h'
339
+ : escapeSystemdPercent(quoteSystemdArg(isAbsolute(opts.workingDirectory) ? opts.workingDirectory : resolvePath(opts.workingDirectory)));
340
+ return [
341
+ '# Linux systemd user unit -- ~/.config/systemd/user/evolver-autoexec.service',
342
+ '[Unit]',
343
+ 'Description=EvoMap Evolver Autoexec Daemon',
344
+ 'After=network-online.target evolver-proxy.service',
345
+ 'Wants=network-online.target evolver-proxy.service',
346
+ 'StartLimitBurst=5',
347
+ 'StartLimitIntervalSec=120s',
348
+ '',
349
+ '[Service]',
350
+ 'Type=simple',
351
+ `WorkingDirectory=${workingDirectory}`,
352
+ ...(opts.envFile ? [`Environment="EVOLVER_ENV_FILE=${escapeSystemdEnvValue(opts.envFile)}"`] : []),
353
+ `ExecStart=${execStart}`,
354
+ 'Restart=on-failure',
355
+ 'RestartSec=5s',
356
+ 'RestartPreventExitStatus=0',
357
+ 'TimeoutStopSec=30s',
358
+ 'StandardOutput=journal',
359
+ 'StandardError=journal',
360
+ 'SyslogIdentifier=evolver-autoexec',
361
+ 'NoNewPrivileges=true',
362
+ 'PrivateTmp=true',
363
+ '',
364
+ '[Install]',
365
+ 'WantedBy=default.target',
366
+ '',
367
+ ].join('\n');
368
+ }
282
369
  export function renderLaunchdPlist(opts = {}) {
283
370
  const workingDirectory = opts.workingDirectory ?? '/Users/YOU/your-project';
284
371
  const nodePath = opts.nodePath ?? '/usr/local/bin/node';
285
372
  const proxyBin = opts.proxyBin ?? '/Users/YOU/your-project/node_modules/@evomap/evolver-proxy/dist/bin/evolver-proxy.js';
286
373
  const programArguments = opts.programArguments ?? [nodePath, proxyBin];
287
374
  const logDir = opts.logDir ?? '/Users/YOU/Library/Logs';
375
+ const label = opts.label ?? DEFAULT_LABEL;
376
+ const logName = opts.logName ?? 'evolver-proxy';
377
+ const selfUpdateSupervisor = opts.selfUpdateSupervisor ?? true;
288
378
  const envFileBlock = opts.envFile ? ` <key>EVOLVER_ENV_FILE</key>\n <string>${escapeXml(opts.envFile)}</string>\n` : '';
289
379
  return [
290
380
  '<?xml version="1.0" encoding="UTF-8"?>',
@@ -292,7 +382,7 @@ export function renderLaunchdPlist(opts = {}) {
292
382
  '<plist version="1.0">',
293
383
  '<dict>',
294
384
  ' <key>Label</key>',
295
- ` <string>${DEFAULT_LABEL}</string>`,
385
+ ` <string>${escapeXml(label)}</string>`,
296
386
  ' <key>ProgramArguments</key>',
297
387
  ' <array>',
298
388
  ...programArguments.map((argument) => ` <string>${escapeXml(argument)}</string>`),
@@ -302,8 +392,10 @@ export function renderLaunchdPlist(opts = {}) {
302
392
  ' <key>EnvironmentVariables</key>',
303
393
  ' <dict>',
304
394
  envFileBlock.trimEnd(),
305
- ' <key>EVOLVER_SELF_UPDATE_SUPERVISOR</key>',
306
- ' <string>launchd</string>',
395
+ ...(selfUpdateSupervisor ? [
396
+ ' <key>EVOLVER_SELF_UPDATE_SUPERVISOR</key>',
397
+ ' <string>launchd</string>',
398
+ ] : []),
307
399
  ...(opts.selfUpdateStateDir ? [
308
400
  ' <key>EVOLVER_SELF_UPDATE_STATE_DIR</key>',
309
401
  ` <string>${escapeXml(opts.selfUpdateStateDir)}</string>`,
@@ -325,9 +417,9 @@ export function renderLaunchdPlist(opts = {}) {
325
417
  ' <key>ThrottleInterval</key>',
326
418
  ' <integer>5</integer>',
327
419
  ' <key>StandardOutPath</key>',
328
- ` <string>${escapeXml(join(logDir, 'evolver-proxy.log'))}</string>`,
420
+ ` <string>${escapeXml(posix.join(logDir, `${logName}.log`))}</string>`,
329
421
  ' <key>StandardErrorPath</key>',
330
- ` <string>${escapeXml(join(logDir, 'evolver-proxy.err.log'))}</string>`,
422
+ ` <string>${escapeXml(posix.join(logDir, `${logName}.err.log`))}</string>`,
331
423
  ' <key>ProcessType</key>',
332
424
  ' <string>Standard</string>',
333
425
  ' <key>LowPriorityIO</key>',
@@ -339,8 +431,16 @@ export function renderLaunchdPlist(opts = {}) {
339
431
  '',
340
432
  ].filter((line) => line !== '').join('\n');
341
433
  }
434
+ export function renderAutoexecLaunchdPlist(opts) {
435
+ return renderLaunchdPlist({
436
+ ...opts,
437
+ label: AUTOEXEC_LABEL,
438
+ logName: 'evolver-autoexec',
439
+ selfUpdateSupervisor: false,
440
+ });
441
+ }
342
442
  export function renderWindowsInstaller(defaults = {}) {
343
- const ps = (value) => `'${(value ?? '').replaceAll("'", "''")}'`;
443
+ const ps = (value) => `'${assertSingleLine(value ?? '', 'Windows installer value').replaceAll("'", "''")}'`;
344
444
  return String.raw `param(
345
445
  [switch]$Install,
346
446
  [switch]$Uninstall,
@@ -362,7 +462,21 @@ if (-not ($Install -or $Uninstall)) {
362
462
 
363
463
  if ($Uninstall) {
364
464
  $existing = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
365
- if ($existing) { Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false }
465
+ if ($existing) {
466
+ if ($existing.State -eq 'Running') {
467
+ Stop-ScheduledTask -TaskName $TaskName
468
+ $stopDeadline = [DateTime]::UtcNow.AddSeconds(15)
469
+ do {
470
+ Start-Sleep -Milliseconds 100
471
+ $existing = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
472
+ } while ($existing -and $existing.State -eq 'Running' -and [DateTime]::UtcNow -lt $stopDeadline)
473
+ if ($existing -and $existing.State -eq 'Running') {
474
+ Write-Error 'Existing Evolver Scheduled Task did not stop; refusing to uninstall.'
475
+ exit 1
476
+ }
477
+ }
478
+ Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false
479
+ }
366
480
  $launcher = Join-Path $env:LOCALAPPDATA 'EvoMap\evolver-proxy-task-launcher.vbs'
367
481
  if (Test-Path $launcher) { Remove-Item $launcher -Force -ErrorAction SilentlyContinue }
368
482
  exit 0
@@ -471,6 +585,127 @@ Register-ScheduledTask -TaskName $TaskName -InputObject $task -Force | Out-Null
471
585
  Write-Host "Installed scheduled task '$TaskName' using hidden wscript launcher $launcherPath."
472
586
  `;
473
587
  }
588
+ export function renderWindowsAutoexecInstaller(defaults = {}) {
589
+ const ps = (value) => `'${assertSingleLine(value ?? '', 'Windows installer value').replaceAll("'", "''")}'`;
590
+ return String.raw `param(
591
+ [switch]$Install,
592
+ [switch]$Uninstall,
593
+ [string]$TaskName = 'EvoMapEvolverAutoexecDaemon',
594
+ [string]$EvolverBin = ${ps(defaults.evolverBin)},
595
+ [string]$NodePath = ${ps(defaults.nodePath)},
596
+ [string]$CliBin = ${ps(defaults.cliBin)},
597
+ [string]$EnvFile = ${ps(defaults.envFile)},
598
+ [string]$AutoexecHome = ${ps(defaults.autoexecHome)},
599
+ [string]$WorkingDirectory = ${ps(defaults.workingDirectory)}
600
+ )
601
+
602
+ $ErrorActionPreference = 'Stop'
603
+
604
+ if (-not ($Install -or $Uninstall) -or ($Install -and $Uninstall)) {
605
+ Write-Host 'Usage: install-evolver-autoexec-windows.ps1 -Install [-EvolverBin ... | -NodePath ... -CliBin ...] [-EnvFile ...] [-AutoexecHome ...]'
606
+ Write-Host ' install-evolver-autoexec-windows.ps1 -Uninstall [-TaskName ...]'
607
+ exit 1
608
+ }
609
+
610
+ $launcherDir = Join-Path $env:LOCALAPPDATA 'EvoMap'
611
+ $launcherPath = Join-Path $launcherDir 'evolver-autoexec-task-launcher.vbs'
612
+
613
+ if ($Uninstall) {
614
+ $existing = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
615
+ if ($existing) {
616
+ if ($existing.State -eq 'Running') {
617
+ Stop-ScheduledTask -TaskName $TaskName
618
+ $stopDeadline = [DateTime]::UtcNow.AddSeconds(15)
619
+ do {
620
+ Start-Sleep -Milliseconds 100
621
+ $existing = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
622
+ } while ($existing -and $existing.State -eq 'Running' -and [DateTime]::UtcNow -lt $stopDeadline)
623
+ if ($existing -and $existing.State -eq 'Running') {
624
+ Write-Error 'Existing Evolver Autoexec Scheduled Task did not stop; refusing to uninstall.'
625
+ exit 1
626
+ }
627
+ }
628
+ Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false
629
+ }
630
+ if (Test-Path $launcherPath) { Remove-Item $launcherPath -Force -ErrorAction SilentlyContinue }
631
+ exit 0
632
+ }
633
+
634
+ if (-not $EvolverBin) {
635
+ if (-not $NodePath) {
636
+ $cmd = Get-Command node -ErrorAction SilentlyContinue
637
+ if (-not $cmd) { Write-Error 'Pass -EvolverBin, or install node.exe / pass -NodePath.'; exit 1 }
638
+ $NodePath = $cmd.Source
639
+ }
640
+ if (-not $CliBin) { Write-Error 'Pass -EvolverBin, or -CliBin pointing at evolver CLI cli.js.'; exit 1 }
641
+ if (-not (Test-Path $CliBin)) { Write-Error "Evolver CLI not found at $CliBin"; exit 1 }
642
+ } elseif (-not (Test-Path $EvolverBin)) {
643
+ Write-Error "Evolver binary not found at $EvolverBin"
644
+ exit 1
645
+ }
646
+
647
+ foreach ($launcherValue in @($EvolverBin, $NodePath, $CliBin, $EnvFile, $AutoexecHome, $WorkingDirectory)) {
648
+ if ($launcherValue -match "[\r\n]") {
649
+ Write-Error 'Launcher paths must not contain line breaks.'
650
+ exit 1
651
+ }
652
+ }
653
+
654
+ if (-not $WorkingDirectory) { $WorkingDirectory = $env:USERPROFILE }
655
+ if (-not (Test-Path $WorkingDirectory -PathType Container)) {
656
+ Write-Error 'WorkingDirectory must be an existing directory.'
657
+ exit 1
658
+ }
659
+
660
+ $existing = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
661
+ if ($existing -and $existing.State -eq 'Running') {
662
+ Stop-ScheduledTask -TaskName $TaskName
663
+ $stopDeadline = [DateTime]::UtcNow.AddSeconds(15)
664
+ do {
665
+ Start-Sleep -Milliseconds 100
666
+ $existing = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
667
+ } while ($existing -and $existing.State -eq 'Running' -and [DateTime]::UtcNow -lt $stopDeadline)
668
+ if ($existing -and $existing.State -eq 'Running') {
669
+ Write-Error 'Existing Evolver Autoexec Scheduled Task did not stop; refusing to replace it.'
670
+ exit 1
671
+ }
672
+ }
673
+
674
+ if (-not (Test-Path $launcherDir)) { New-Item -ItemType Directory -Path $launcherDir | Out-Null }
675
+
676
+ $nodeEsc = if ($NodePath) { $NodePath.Replace('"', '""') } else { '' }
677
+ $cliEsc = if ($CliBin) { $CliBin.Replace('"', '""') } else { '' }
678
+ $evolverEsc = if ($EvolverBin) { $EvolverBin.Replace('"', '""') } else { '' }
679
+ $envEsc = if ($EnvFile) { $EnvFile.Replace('"', '""') } else { '' }
680
+ $homeEsc = if ($AutoexecHome) { $AutoexecHome.Replace('"', '""') } else { '' }
681
+
682
+ $launcherBody = @"
683
+ ' AUTO-GENERATED by install-evolver-autoexec-windows.ps1 -- do not edit.
684
+ Dim WshShell, env, cmd, rc
685
+ Set WshShell = CreateObject("WScript.Shell")
686
+ Set env = WshShell.Environment("PROCESS")
687
+ If "$envEsc" <> "" Then env("EVOLVER_ENV_FILE") = "$envEsc"
688
+ If "$evolverEsc" <> "" Then
689
+ cmd = """$evolverEsc"" autoexec"
690
+ Else
691
+ cmd = """$nodeEsc"" ""$cliEsc"" autoexec"
692
+ End If
693
+ If "$homeEsc" <> "" Then cmd = cmd & " ""$homeEsc"""
694
+ rc = WshShell.Run(cmd, 0, True)
695
+ WScript.Quit rc
696
+ "@
697
+ Set-Content -Path $launcherPath -Value $launcherBody -Encoding Unicode
698
+
699
+ $action = New-ScheduledTaskAction -Execute 'wscript.exe' -Argument ('"{0}"' -f $launcherPath) -WorkingDirectory $WorkingDirectory
700
+ $user = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
701
+ $trigger = New-ScheduledTaskTrigger -AtLogOn -User $user
702
+ $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -RestartCount 5 -RestartInterval (New-TimeSpan -Minutes 2) -ExecutionTimeLimit (New-TimeSpan -Days 0) -MultipleInstances IgnoreNew
703
+ $principal = New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Limited
704
+ $task = New-ScheduledTask -Action $action -Trigger $trigger -Settings $settings -Principal $principal
705
+ Register-ScheduledTask -TaskName $TaskName -InputObject $task -Force | Out-Null
706
+ Write-Host "Installed scheduled task '$TaskName' using hidden wscript launcher $launcherPath."
707
+ `;
708
+ }
474
709
  function parseFlags(argv) {
475
710
  const out = {};
476
711
  for (let i = 0; i < argv.length; i += 1) {
@@ -496,6 +731,16 @@ function serviceTarget(flags) {
496
731
  }
497
732
  async function installService(target, flags, env, argv1, loadUnixRecoveryController = () => import('@evomap/evolver-proxy')) {
498
733
  const dryRun = flags['dry-run'] === true;
734
+ if (flags['with-autoexec'] !== undefined && flags['with-autoexec'] !== true) {
735
+ throw new Error('--with-autoexec is a boolean flag and does not accept a value');
736
+ }
737
+ if (flags['autoexec-home'] === true) {
738
+ throw new Error('--autoexec-home requires a path');
739
+ }
740
+ const withAutoexec = flags['with-autoexec'] === true;
741
+ if (!withAutoexec && flags['autoexec-home'] !== undefined) {
742
+ throw new Error('--autoexec-home requires --with-autoexec');
743
+ }
499
744
  const envFile = typeof flags['env-file'] === 'string' ? flags['env-file'] : env['EVOLVER_ENV_FILE'];
500
745
  const supervised = configuredSelfUpdateTarget(env)
501
746
  ? resolveDaemonCommand(env, process.execPath, argv1)
@@ -522,11 +767,32 @@ async function installService(target, flags, env, argv1, loadUnixRecoveryControl
522
767
  unixControllerStateDir = dirname(dirname(controllerPath));
523
768
  }
524
769
  const serviceCommand = unixController ?? supervised;
770
+ const autoexecHomeFlag = typeof flags['autoexec-home'] === 'string' ? flags['autoexec-home'].trim() : undefined;
771
+ if (autoexecHomeFlag !== undefined && !autoexecHomeFlag) {
772
+ throw new Error('--autoexec-home requires a non-empty path');
773
+ }
774
+ const companionWorkingDirectoryFlag = typeof flags['cwd'] === 'string'
775
+ ? assertSingleLine(flags['cwd'].trim(), 'service working directory')
776
+ : undefined;
777
+ const companionWorkingDirectory = companionWorkingDirectoryFlag
778
+ ? (isAbsolute(companionWorkingDirectoryFlag) ? companionWorkingDirectoryFlag : resolvePath(companionWorkingDirectoryFlag))
779
+ : process.cwd();
780
+ const autoexecHome = autoexecHomeFlag
781
+ ? assertSingleLine(isAbsolute(autoexecHomeFlag) ? autoexecHomeFlag : resolvePath(companionWorkingDirectory, autoexecHomeFlag), 'autoexec home')
782
+ : undefined;
783
+ const autoexecCommand = withAutoexec
784
+ ? resolveAutoexecDaemonCommand(env, process.execPath, argv1, autoexecHome)
785
+ : undefined;
786
+ if (withAutoexec && !autoexecCommand) {
787
+ throw new Error('cannot resolve the current evolver CLI for --with-autoexec; pass a standalone Evolver binary or run through cli.js');
788
+ }
525
789
  if (target === 'systemd') {
526
790
  const path = expandHome('~/.config/systemd/user/evolver-proxy.service');
791
+ const autoexecPath = expandHome('~/.config/systemd/user/evolver-autoexec.service');
792
+ const workingDirectory = typeof flags['cwd'] === 'string' ? flags['cwd'] : undefined;
527
793
  const unit = renderSystemdUnit({
528
794
  envFile,
529
- workingDirectory: typeof flags['cwd'] === 'string' ? flags['cwd'] : undefined,
795
+ workingDirectory,
530
796
  ...(serviceCommand
531
797
  ? { execStart: [serviceCommand.command, ...serviceCommand.args].map(quoteSystemdArg).join(' ') }
532
798
  : {}),
@@ -535,17 +801,30 @@ async function installService(target, flags, env, argv1, loadUnixRecoveryControl
535
801
  });
536
802
  if (!dryRun)
537
803
  writeTextFile(path, unit, 0o644);
804
+ if (autoexecCommand) {
805
+ const autoexecUnit = renderAutoexecSystemdUnit({
806
+ envFile,
807
+ workingDirectory: companionWorkingDirectory,
808
+ execStart: [autoexecCommand.command, ...autoexecCommand.args].map(quoteSystemdArg).join(' '),
809
+ });
810
+ if (!dryRun)
811
+ writeTextFile(autoexecPath, autoexecUnit, 0o644);
812
+ }
538
813
  return {
539
814
  status: dryRun ? 'rendered' : 'installed',
540
- files: [path, ...(unixController ? [unixController.command] : [])],
815
+ files: [path, ...(autoexecCommand ? [autoexecPath] : []), ...(unixController ? [unixController.command] : [])],
541
816
  service: 'systemd-user',
817
+ ...(autoexecHome ? { autoexecHome } : {}),
542
818
  };
543
819
  }
544
820
  if (target === 'launchd') {
545
821
  const path = expandHome('~/Library/LaunchAgents/com.evomap.evolver-proxy.plist');
822
+ const autoexecPath = expandHome('~/Library/LaunchAgents/com.evomap.evolver-autoexec.plist');
823
+ const workingDirectory = companionWorkingDirectory;
824
+ const logDir = join(homedir(), 'Library', 'Logs');
546
825
  const plist = renderLaunchdPlist({
547
826
  envFile,
548
- workingDirectory: typeof flags['cwd'] === 'string' ? flags['cwd'] : process.cwd(),
827
+ workingDirectory,
549
828
  ...(serviceCommand
550
829
  ? { programArguments: [serviceCommand.command, ...serviceCommand.args] }
551
830
  : {}),
@@ -553,17 +832,29 @@ async function installService(target, flags, env, argv1, loadUnixRecoveryControl
553
832
  ...(unixControllerStateDir ? { selfUpdateStateDir: unixControllerStateDir } : {}),
554
833
  nodePath: resolveStableNodePath(),
555
834
  proxyBin: resolveProxyBinPath() ?? (argv1?.startsWith('/') ? argv1 : undefined) ?? '/ABSOLUTE/PATH/TO/evolver-proxy.js',
556
- logDir: join(homedir(), 'Library', 'Logs'),
835
+ logDir,
557
836
  });
558
837
  if (!dryRun)
559
838
  writeTextFile(path, plist, 0o644);
839
+ if (autoexecCommand) {
840
+ const autoexecPlist = renderAutoexecLaunchdPlist({
841
+ envFile,
842
+ workingDirectory,
843
+ programArguments: [autoexecCommand.command, ...autoexecCommand.args],
844
+ logDir,
845
+ });
846
+ if (!dryRun)
847
+ writeTextFile(autoexecPath, autoexecPlist, 0o644);
848
+ }
560
849
  return {
561
850
  status: dryRun ? 'rendered' : 'installed',
562
- files: [path, ...(unixController ? [unixController.command] : [])],
851
+ files: [path, ...(autoexecCommand ? [autoexecPath] : []), ...(unixController ? [unixController.command] : [])],
563
852
  service: 'launchd',
853
+ ...(autoexecHome ? { autoexecHome } : {}),
564
854
  };
565
855
  }
566
- const path = expandHome('~/install-evolver-proxy-windows.ps1');
856
+ let path = expandHome('~/install-evolver-proxy-windows.ps1');
857
+ let autoexecPath = expandHome('~/install-evolver-autoexec-windows.ps1');
567
858
  const selfUpdateStateDir = env['EVOLVER_SELF_UPDATE_STATE_DIR']?.trim();
568
859
  const standalone = standaloneTarget;
569
860
  const script = renderWindowsInstaller({
@@ -575,8 +866,108 @@ async function installService(target, flags, env, argv1, loadUnixRecoveryControl
575
866
  ...(selfUpdateStateDir ? { selfUpdateStateDir } : {}),
576
867
  });
577
868
  if (!dryRun)
578
- writeTextFile(path, script, 0o644);
579
- return { status: dryRun ? 'rendered' : 'installed', files: [path], service: 'windows-scheduled-task' };
869
+ path = writeWindowsHelper(path, script);
870
+ if (autoexecCommand) {
871
+ const standaloneAutoexec = autoexecCommand.args[0] === 'autoexec';
872
+ const autoexecScript = renderWindowsAutoexecInstaller({
873
+ ...(standaloneAutoexec
874
+ ? { evolverBin: autoexecCommand.command }
875
+ : { nodePath: autoexecCommand.command, cliBin: autoexecCommand.args[0] }),
876
+ ...(envFile ? { envFile } : {}),
877
+ ...(autoexecHome ? { autoexecHome } : {}),
878
+ workingDirectory: companionWorkingDirectory,
879
+ });
880
+ if (!dryRun)
881
+ autoexecPath = writeWindowsHelper(autoexecPath, autoexecScript);
882
+ }
883
+ return {
884
+ status: dryRun ? 'rendered' : 'installed',
885
+ files: [path, ...(autoexecCommand ? [autoexecPath] : [])],
886
+ service: 'windows-scheduled-task',
887
+ ...(autoexecHome ? { autoexecHome } : {}),
888
+ };
889
+ }
890
+ export function removeAutoexecService(target, dryRun, deps = {}) {
891
+ const paths = {
892
+ systemd: expandHome('~/.config/systemd/user/evolver-autoexec.service'),
893
+ launchd: expandHome('~/Library/LaunchAgents/com.evomap.evolver-autoexec.plist'),
894
+ windows: expandHome('~/install-evolver-autoexec-windows.ps1'),
895
+ };
896
+ const configuredPath = deps.paths?.[target] ?? paths[target];
897
+ const path = target === 'windows' && !dryRun ? randomWindowsHelperPath(configuredPath) : configuredPath;
898
+ const run = deps.run ?? ((command, args) => {
899
+ const result = spawnSync(command, [...args], { stdio: 'ignore', timeout: 30_000, windowsHide: true });
900
+ return { status: result.status, ...(result.error ? { error: result.error } : {}) };
901
+ });
902
+ const exists = deps.exists ?? existsSync;
903
+ const remove = deps.remove ?? ((file) => { rmSync(file, { force: true }); });
904
+ const write = deps.write ?? ((file, content, mode) => {
905
+ writeTextFile(file, content, mode, 'wx');
906
+ });
907
+ if (target === 'systemd') {
908
+ const actions = [
909
+ 'systemctl --user disable --now evolver-autoexec.service',
910
+ `remove ${path}`,
911
+ 'systemctl --user daemon-reload',
912
+ ];
913
+ if (dryRun)
914
+ return { status: 'planned', files: [path], service: 'systemd-user', actions };
915
+ const active = requireServiceControlStatus(run('systemctl', ['--user', 'is-active', '--quiet', 'evolver-autoexec.service']), [0, 3, 4], 'inspect systemd autoexec activity');
916
+ const enabled = requireServiceControlStatus(run('systemctl', ['--user', 'is-enabled', '--quiet', 'evolver-autoexec.service']), [0, 1, 4], 'inspect systemd autoexec enablement');
917
+ const hasUnit = exists(path);
918
+ if (active !== 0 && enabled !== 0 && !hasUnit) {
919
+ return { status: 'absent', files: [path], service: 'systemd-user', actions: [] };
920
+ }
921
+ requireServiceControlStatus(run('systemctl', ['--user', 'disable', '--now', 'evolver-autoexec.service']), [0], 'disable systemd autoexec service');
922
+ if (hasUnit)
923
+ remove(path);
924
+ requireServiceControlStatus(run('systemctl', ['--user', 'daemon-reload']), [0], 'reload systemd user services');
925
+ return { status: 'removed', files: [path], service: 'systemd-user', actions };
926
+ }
927
+ if (target === 'launchd') {
928
+ const uid = deps.uid ?? (typeof process.getuid === 'function' ? process.getuid() : undefined);
929
+ const launchdTarget = `gui/${uid ?? '<uid>'}/${AUTOEXEC_LABEL}`;
930
+ const actions = [`launchctl bootout ${launchdTarget}`, `remove ${path}`];
931
+ if (dryRun)
932
+ return { status: 'planned', files: [path], service: 'launchd', actions };
933
+ if (uid === undefined)
934
+ throw new Error('cannot determine the current user id for launchd autoexec removal');
935
+ requireServiceControlStatus(run('launchctl', ['bootout', `gui/${uid}/${AUTOEXEC_LABEL}`]), [0, 3, 113], 'boot out launchd autoexec service');
936
+ const hasPlist = exists(path);
937
+ if (hasPlist)
938
+ remove(path);
939
+ return {
940
+ status: hasPlist ? 'removed' : 'absent',
941
+ files: [path],
942
+ service: 'launchd',
943
+ actions: hasPlist ? actions : actions.slice(0, 1),
944
+ };
945
+ }
946
+ const actions = [
947
+ `write ${path}`,
948
+ `powershell.exe -File ${path} -Uninstall`,
949
+ `remove ${path}`,
950
+ ];
951
+ if (dryRun)
952
+ return { status: 'planned', files: [path], service: 'windows-scheduled-task', actions };
953
+ write(path, renderWindowsAutoexecInstaller(), 0o644);
954
+ requireServiceControlStatus(run('powershell.exe', [
955
+ '-NoProfile',
956
+ '-NonInteractive',
957
+ '-ExecutionPolicy',
958
+ 'Bypass',
959
+ '-File',
960
+ path,
961
+ '-Uninstall',
962
+ ]), [0], 'uninstall Windows autoexec scheduled task');
963
+ remove(path);
964
+ return { status: 'removed', files: [path], service: 'windows-scheduled-task', actions };
965
+ }
966
+ function requireServiceControlStatus(result, allowedStatuses, operation) {
967
+ if (result.error || result.status === null || !allowedStatuses.includes(result.status)) {
968
+ throw new Error(`${operation} failed; companion artifact was retained`);
969
+ }
970
+ return result.status;
580
971
  }
581
972
  async function runWatch(paths, env, flags, stdout, stderr) {
582
973
  const once = flags['once'] === true;
@@ -675,6 +1066,23 @@ export function resolveSelfUpdatingExecutable(execPath, argv1) {
675
1066
  }
676
1067
  return undefined;
677
1068
  }
1069
+ export function resolveAutoexecDaemonCommand(env, execPath = process.execPath, argv1 = process.argv[1], autoexecHome) {
1070
+ const target = configuredSelfUpdateTarget(env);
1071
+ const proxyCommand = target
1072
+ ? standaloneProxyCommand(target)
1073
+ : resolveSelfUpdatingExecutable(execPath, argv1);
1074
+ if (!proxyCommand || proxyCommand.args.at(-1) !== 'proxy')
1075
+ return undefined;
1076
+ const args = [...proxyCommand.args.slice(0, -1), 'autoexec'];
1077
+ const home = autoexecHome?.trim();
1078
+ if (home)
1079
+ args.push(home);
1080
+ return {
1081
+ command: proxyCommand.command,
1082
+ args,
1083
+ display: [proxyCommand.command, ...args].join(' '),
1084
+ };
1085
+ }
678
1086
  export function resolveProxyBinPath() {
679
1087
  try {
680
1088
  const entry = requireFromHere.resolve('@evomap/evolver-proxy');
@@ -756,23 +1164,32 @@ function readPidFile(path) {
756
1164
  return { owned: false, legacy: false };
757
1165
  }
758
1166
  }
759
- function pidFileRecordMatchesProcess(pidFile, readCommandLine = processCommandLine, readIdentity = processIdentity) {
1167
+ function pidFileRecordMatchesProcess(pidFile, readCommandLine = processCommandLine, readIdentity = processIdentity, platform = process.platform) {
760
1168
  if (!pidFile.owned || !pidFile.record)
761
1169
  return false;
762
1170
  const record = pidFile.record;
763
1171
  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));
1172
+ const commandMatches = Boolean(commandLine
1173
+ && commandLine.includes(basename(record.command))
1174
+ && record.args.every((arg) => commandLine.includes(arg)));
1175
+ const identity = readIdentity(record.pid);
1176
+ if (commandLine?.includes(basename(record.command))) {
1177
+ if (!commandMatches)
1178
+ return false;
1179
+ if (identity !== undefined)
1180
+ return processIdentityMatchesRecord(record, identity);
1181
+ return platform !== 'win32';
1182
+ }
1183
+ return processIdentityMatchesRecord(record, identity);
767
1184
  }
768
- function waitForPidFileRecordMatch(pidFile, timeoutMs, readCommandLine = processCommandLine, readIdentity = processIdentity) {
1185
+ function waitForPidFileRecordMatch(pidFile, timeoutMs, readCommandLine = processCommandLine, readIdentity = processIdentity, platform = process.platform) {
769
1186
  const start = Date.now();
770
1187
  while (Date.now() - start < timeoutMs) {
771
- if (pidFileRecordMatchesProcess(pidFile, readCommandLine, readIdentity))
1188
+ if (pidFileRecordMatchesProcess(pidFile, readCommandLine, readIdentity, platform))
772
1189
  return true;
773
1190
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);
774
1191
  }
775
- return pidFileRecordMatchesProcess(pidFile, readCommandLine, readIdentity);
1192
+ return pidFileRecordMatchesProcess(pidFile, readCommandLine, readIdentity, platform);
776
1193
  }
777
1194
  function processCommandLine(pid) {
778
1195
  if (process.platform === 'win32') {
@@ -1031,12 +1448,42 @@ function expandHome(path) {
1031
1448
  return join(homedir(), path.slice(2));
1032
1449
  return path;
1033
1450
  }
1034
- function writeTextFile(path, content, mode) {
1451
+ function randomWindowsHelperPath(preferredPath) {
1452
+ const extension = extname(preferredPath) || '.ps1';
1453
+ const stem = basename(preferredPath, extension);
1454
+ return join(dirname(preferredPath), `${stem}-${randomUUID()}${extension}`);
1455
+ }
1456
+ function writeWindowsHelper(preferredPath, content) {
1457
+ try {
1458
+ writeTextFile(preferredPath, content, 0o600, 'wx');
1459
+ return preferredPath;
1460
+ }
1461
+ catch (error) {
1462
+ if (error.code !== 'EEXIST')
1463
+ throw error;
1464
+ }
1465
+ const fallbackPath = randomWindowsHelperPath(preferredPath);
1466
+ writeTextFile(fallbackPath, content, 0o600, 'wx');
1467
+ return fallbackPath;
1468
+ }
1469
+ export const _writeWindowsHelperForTest = writeWindowsHelper;
1470
+ function writeTextFile(path, content, mode = 0o600, flag = 'w') {
1035
1471
  mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
1036
- writeFileSync(path, content, { encoding: 'utf8', mode });
1472
+ writeFileSync(path, content, { encoding: 'utf8', mode, flag });
1473
+ }
1474
+ function assertSingleLine(value, label) {
1475
+ for (const character of value) {
1476
+ const code = character.charCodeAt(0);
1477
+ if (code <= 0x1f || code === 0x7f)
1478
+ throw new Error(`${label} must not contain control characters`);
1479
+ }
1480
+ return value;
1481
+ }
1482
+ function escapeSystemdPercent(value) {
1483
+ return value.replaceAll('%', '%%');
1037
1484
  }
1038
1485
  function escapeXml(value) {
1039
- return value
1486
+ return assertSingleLine(value, 'launchd value')
1040
1487
  .replaceAll('&', '&amp;')
1041
1488
  .replaceAll('<', '&lt;')
1042
1489
  .replaceAll('>', '&gt;')
@@ -1044,12 +1491,17 @@ function escapeXml(value) {
1044
1491
  .replaceAll("'", '&apos;');
1045
1492
  }
1046
1493
  function escapeSystemdEnvValue(value) {
1047
- return value.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('$', '\\$');
1494
+ return assertSingleLine(value, 'systemd environment value')
1495
+ .replaceAll('\\', '\\\\')
1496
+ .replaceAll('"', '\\"')
1497
+ .replaceAll('$', '\\$')
1498
+ .replaceAll('%', '%%');
1048
1499
  }
1049
1500
  function quoteSystemdArg(value) {
1050
- return /^[A-Za-z0-9_/:.@%+=,-]+$/.test(value)
1051
- ? value
1052
- : `"${value.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('$', '\\$')}"`;
1501
+ const safe = assertSingleLine(value, 'systemd argument');
1502
+ return /^[A-Za-z0-9_/:.@%+=,-]+$/.test(safe)
1503
+ ? safe
1504
+ : `"${safe.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('$', '\\$')}"`;
1053
1505
  }
1054
1506
  function resolveCurrentCliPath() {
1055
1507
  return fileURLToPath(new URL('./cli.js', import.meta.url));