@evomap/evolver-cli 2.0.0-beta.2 → 2.0.0-beta.4

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.
package/dist/doctor.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type MemoryGraphOperatorStatus } from './localMemoryGraph.js';
1
2
  type DoctorStatus = 'pass' | 'warn' | 'fail';
2
3
  export interface DoctorCheck {
3
4
  name: string;
@@ -36,6 +37,7 @@ export interface DoctorDeps {
36
37
  statMode?: (p: string) => number | undefined;
37
38
  profile?: DoctorProfile;
38
39
  label?: string;
40
+ memoryGraphStatus?: (env: Record<string, string | undefined>) => MemoryGraphOperatorStatus;
39
41
  }
40
42
  export interface EnvCatalogResult {
41
43
  profile: DoctorProfile;
package/dist/doctor.js CHANGED
@@ -5,6 +5,7 @@
5
5
  import { readFileSync, existsSync, statSync } from 'node:fs';
6
6
  import { isAbsolute, join } from 'node:path';
7
7
  import { expandHomePath, parseEnvFile } from '@evomap/evolver-mcp';
8
+ import { formatMemoryGraphOperatorStatus, loadMemoryGraphOperatorStatus } from './localMemoryGraph.js';
8
9
  // Secrets that must live ONLY behind the EVOLVER_ENV_FILE pointer — never inlined into a runtime config (#217).
9
10
  const SECRET_KEYS = [
10
11
  'A2A_NODE_SECRET',
@@ -432,6 +433,12 @@ const ENV_CATALOG_DEFINITIONS = [
432
433
  purpose: 'Public key used to verify self-update artifacts.',
433
434
  requiredFor: 'self-update verification',
434
435
  },
436
+ {
437
+ name: 'EVOLVER_SELF_UPDATE_SUPERVISOR',
438
+ group: 'self-update',
439
+ purpose: 'Attests that a generated durable service launcher owns relaunch.',
440
+ requiredFor: 'automatic self-update',
441
+ },
435
442
  {
436
443
  name: 'EVOLVER_SELF_UPDATE_TARGET_PATH',
437
444
  group: 'self-update',
@@ -568,6 +575,17 @@ export function runDoctorChecks(deps = {}) {
568
575
  if (deps.profile === 'private-runtime') {
569
576
  checks.push(...privateRuntimeChecks(env, envFileValues, envFileReadiness));
570
577
  }
578
+ try {
579
+ const status = (deps.memoryGraphStatus ?? loadMemoryGraphOperatorStatus)(effectiveEnv);
580
+ checks.push({
581
+ name: 'memory-graph',
582
+ status: status.recovery === 'degraded' ? 'warn' : 'pass',
583
+ detail: formatMemoryGraphOperatorStatus(status),
584
+ });
585
+ }
586
+ catch {
587
+ checks.push({ name: 'memory-graph', status: 'warn', detail: 'state=degraded corrupt=1 oversized_lines=0 oversized_files=0 archives=0' });
588
+ }
571
589
  return checks;
572
590
  }
573
591
  export function buildEnvCatalog(deps = {}) {
package/dist/index.d.ts CHANGED
@@ -43,7 +43,7 @@ export declare function runResetLocalSecret(argv: readonly string[], opts?: Rese
43
43
  export declare function rebuildViews(opts?: RebuildOptions): {
44
44
  rebuilt: string[];
45
45
  };
46
- /** migrate import-v1 <v1dir> [outDir]: v1→v2 只读迁移(异步, 由 cli.ts 调). */
46
+ /** migrate import-v1 <v1dir> [outDir] --workspace <path>: v1→v2 read-only migration. */
47
47
  export declare function runMigrate(argv: readonly string[]): Promise<number>;
48
48
  /** One-line summary of an asset for `asset-log` (pure, testable). */
49
49
  export declare function formatAssetLine(a: assetstore.AssetRecord): string;
package/dist/index.js CHANGED
@@ -3,6 +3,7 @@ import { readEvents, statusReport, listCycles, showCycle, listTriggers, buildNar
3
3
  import { runGeneValue } from './geneValue.js';
4
4
  import { assetstore, algo, signals, material as materialNs } from '@evomap/evolver-core';
5
5
  import { loadPriceTable } from '@evomap/evolver-adapter-public';
6
+ import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
6
7
  import { makeInjectEmitter } from './autoexec.js';
7
8
  import { listApprovedGenes, provenanceStoreForStore, reviewLedgerForStore } from './reviewFilter.js';
8
9
  import { ADAPTERS, parseJsonlLines } from '@evomap/evolver-runtime-adapters';
@@ -197,16 +198,50 @@ export function rebuildViews(opts = {}) {
197
198
  replayer.rebuild(ing.readAll());
198
199
  return { rebuilt: events.DEFAULT_PROJECTORS.map((p) => p.name) };
199
200
  }
200
- /** migrate import-v1 <v1dir> [outDir]: v1→v2 只读迁移(异步, 由 cli.ts 调). */
201
+ /** migrate import-v1 <v1dir> [outDir] --workspace <path>: v1→v2 read-only migration. */
201
202
  export async function runMigrate(argv) {
203
+ const usage = '用法: evolver migrate import-v1 <v1dir> [outDir] [--workspace <path>]\n';
202
204
  if (argv[0] !== 'import-v1' || !argv[1]) {
203
- process.stderr.write('用法: evolver migrate import-v1 <v1dir> [outDir]\n');
205
+ process.stderr.write(usage);
204
206
  return 1;
205
207
  }
206
- const outDir = argv[2] ?? process.cwd();
207
- const store = new assetstore.LocalJsonlProvider(`${outDir}/assets`);
208
- const rep = await importV1(argv[1], store, outDir);
209
- process.stdout.write(`迁移完成: Gene=${rep.imported.Gene} Capsule=${rep.imported.Capsule} Event=${rep.imported.EvolutionEvent} (冻结${rep.frozen}/新算${rep.recomputed}/去重${rep.deduped}); sidecar=${rep.sidecarExtensions}; memory_graph 归档=${rep.memoryGraphArchived}\n`);
208
+ let outDir;
209
+ let workspace;
210
+ for (let index = 2; index < argv.length; index += 1) {
211
+ const arg = argv[index] ?? '';
212
+ if (arg === '--workspace') {
213
+ const value = argv[index + 1];
214
+ if (!value || value.startsWith('--')) {
215
+ process.stderr.write(usage);
216
+ return 1;
217
+ }
218
+ workspace = value;
219
+ index += 1;
220
+ }
221
+ else if (arg.startsWith('--workspace=')) {
222
+ workspace = arg.slice('--workspace='.length);
223
+ if (!workspace) {
224
+ process.stderr.write(usage);
225
+ return 1;
226
+ }
227
+ }
228
+ else if (arg.startsWith('--') || outDir !== undefined) {
229
+ process.stderr.write(usage);
230
+ return 1;
231
+ }
232
+ else {
233
+ outDir = arg;
234
+ }
235
+ }
236
+ const envFile = loadEnvFileFromEnv(process.env);
237
+ if (envFile.error) {
238
+ process.stderr.write('migrate: failed to load EVOLVER_ENV_FILE\n');
239
+ return 1;
240
+ }
241
+ const targetDir = outDir ?? events.evomapHome();
242
+ const store = new assetstore.LocalJsonlProvider(`${targetDir}/assets`);
243
+ const rep = await importV1(argv[1], store, targetDir, workspace ? { workspace } : {});
244
+ process.stdout.write(`迁移完成: Gene=${rep.imported.Gene} Capsule=${rep.imported.Capsule} Event=${rep.imported.EvolutionEvent} (冻结${rep.frozen}/新算${rep.recomputed}/去重${rep.deduped}); sidecar=${rep.sidecarExtensions}; memory_graph 归档=${rep.memoryGraphArchived} 可查询=${rep.memoryGraphImported} 延后=${rep.memoryGraphDeferred}\n`);
210
245
  return 0;
211
246
  }
212
247
  /** One-line summary of an asset for `asset-log` (pure, testable). */
@@ -1350,7 +1385,7 @@ export function runCli(argv) {
1350
1385
  return 0;
1351
1386
  }
1352
1387
  default:
1353
- process.stderr.write('用法: evolver [--version|-v] <status|cycles|cycle show <id>|cycle status [--json]|cycle recover [--limit N] [--json]|cycle watch --repo <path> [--state-file <path>] [--validation-cmd <cmd>] [--json]|trigger|value [--window 7d|30d|all]|narrative [--limit N] [--json]|retention [--json]|retention archive-root [--keep-events N] [--write] [--json]|retention archive-material [--keep-records N] [--write] [--json]|dashboard [--port N] [--no-open]|webui [--port N] [--no-open]|trajectory-export [--input <trace-file-or-dir>] [--output <jsonl>]|gene-value [--gene <id>] [--json]|login|logout|proxy-token [--settings <file>]|inject session-start|lifecycle <start|stop|restart|status|check|watch|install-service>|phub <init|doctor|status>|replay|rebuild-views|reset-local-secret|asset-log [kind] [limit]|distill ...|review [limit|--approve <id> [--allow-weak-evidence]|--reject <id>]|recipe build|from-skills|reuse ...|publish ...|sync [--write] [--force] [--scope all|purchased|published] [--export <file.gepx>|--import <file.gepx>] [--json]|material package-gene --material <id> [--write] [--json]|skill fetch ...|fetch (--skill <id>|-s <id>|<id>) [--out <dir>] [--force] [--json]|skill-distill --skill <path> [--execution <json|@file>]|skill-md-update --gene <id> --skill <path> [--dry-run]|autoexec [home]|run [-v|--verbose] [--loop|--mad-dog] [--json]|solidify [--dry-run] [--json]|setup-hooks [--runtime] [--root] [--uninstall]|buy|orders|verify|atp|recall <transcript> (--gene <id> ...|--from-inject)>\n');
1388
+ process.stderr.write('用法: evolver [--version|-v] <status|cycles|cycle capabilities [--json]|cycle show <id>|cycle status [--json]|cycle recover [--limit N] [--json]|cycle watch --repo <path> [--state-file <path>] [--validation-cmd <cmd>] [--json]|trigger|value [--window 7d|30d|all]|narrative [--limit N] [--json]|retention [--json]|retention archive-root [--keep-events N] [--write] [--json]|retention archive-material [--keep-records N] [--write] [--json]|dashboard [--port N] [--no-open]|webui [--port N] [--no-open]|trajectory-export [--input <trace-file-or-dir>] [--output <jsonl>]|gene-value [--gene <id>] [--json]|login|logout|proxy|proxy-token [--settings <file>]|inject session-start|lifecycle <start|stop|restart|status|check|watch|install-service>|phub <init|doctor|status>|replay|rebuild-views|reset-local-secret|asset-log [kind] [limit]|asset-trust <list|show|promote|revoke>|asset-health [--json]|asset-health repair-sidecar --sidecar <kind> --replacement <file> [--write --acknowledge-corrupt-history] [--json]|distill ...|review [limit|--approve <id> [--allow-weak-evidence]|--reject <id>]|recipe build|from-skills|reuse ...|publish ...|sync [--write] [--force] [--scope all|purchased|published] [--export <file.gepx>|--import <file.gepx>] [--json]|material package-gene --material <id> [--write] [--json]|skill fetch ...|fetch (--skill <id>|-s <id>|<id>) [--out <dir>] [--force] [--json]|skill-distill --skill <path> [--execution <json|@file>]|skill-md-update --gene <id> --skill <path> [--dry-run]|autoexec [home]|run [-v|--verbose] [--loop|--mad-dog] [--json]|solidify [--dry-run] [--json]|setup-hooks [--runtime] [--root] [--uninstall]|buy|orders|verify|atp|recall <transcript> (--gene <id> ...|--from-inject)>\n');
1354
1389
  return cmd === undefined ? 0 : 1;
1355
1390
  }
1356
1391
  }
@@ -1,4 +1,9 @@
1
1
  import { spawn } from 'node:child_process';
2
+ export interface DaemonCommand {
3
+ command: string;
4
+ args: string[];
5
+ display: string;
6
+ }
2
7
  interface ProcessIdentity {
3
8
  executable?: string;
4
9
  parentPid?: number;
@@ -59,15 +64,28 @@ export declare function renderSystemdUnit(opts?: {
59
64
  envFile?: string;
60
65
  workingDirectory?: string;
61
66
  execStart?: string;
67
+ selfUpdateStateDir?: string;
68
+ selfUpdateTarget?: string;
62
69
  }): string;
63
70
  export declare function renderLaunchdPlist(opts?: {
64
71
  envFile?: string;
65
72
  workingDirectory?: string;
66
73
  nodePath?: string;
67
74
  proxyBin?: string;
75
+ programArguments?: readonly string[];
68
76
  logDir?: string;
77
+ selfUpdateStateDir?: string;
78
+ selfUpdateTarget?: string;
79
+ }): string;
80
+ export declare function renderWindowsInstaller(defaults?: {
81
+ evolverBin?: string;
82
+ nodePath?: string;
83
+ proxyBin?: string;
84
+ envFile?: string;
85
+ selfUpdateStateDir?: string;
69
86
  }): string;
70
- export declare function renderWindowsInstaller(): string;
87
+ export declare function resolveDaemonCommand(env: NodeJS.ProcessEnv, execPath?: string, argv1?: string | undefined): DaemonCommand;
88
+ export declare function resolveSelfUpdatingExecutable(execPath: string, argv1: string | undefined): DaemonCommand | undefined;
71
89
  export declare function resolveProxyBinPath(): string | undefined;
72
90
  export declare function resolveStableNodePath(): string;
73
91
  export declare function sessionStartHookVerboseEnabled(env?: NodeJS.ProcessEnv): boolean;
package/dist/lifecycle.js CHANGED
@@ -4,7 +4,7 @@ import { existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync }
4
4
  import { homedir } from 'node:os';
5
5
  import { basename, dirname, join } from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
7
- import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
7
+ import { loadEnvFile, loadEnvFileFromEnv } from '@evomap/evolver-mcp';
8
8
  const requireFromHere = createRequire(import.meta.url);
9
9
  const DEFAULT_DAEMON_NAME = 'evolver-proxy';
10
10
  const DEFAULT_LABEL = 'com.evomap.evolver-proxy';
@@ -66,8 +66,14 @@ async function runLifecycleCommandInner(argv, deps) {
66
66
  case 'watch':
67
67
  return runWatch(paths, env, flags, stdout, stderr);
68
68
  case 'install-service': {
69
+ const requestedEnvFile = typeof flags['env-file'] === 'string' ? flags['env-file'] : undefined;
70
+ const envFileResult = requestedEnvFile
71
+ ? loadEnvFile(requestedEnvFile, env)
72
+ : loadEnvFileFromEnv(env);
73
+ if (envFileResult.error)
74
+ throw new Error('failed to load lifecycle environment file');
69
75
  const target = serviceTarget(flags);
70
- const result = installService(target, flags, env, deps.argv1 ?? process.argv[1]);
76
+ const result = await installService(target, flags, env, deps.argv1 ?? process.argv[1]);
71
77
  stdout(`${JSON.stringify(result, null, 2)}\n`);
72
78
  return 0;
73
79
  }
@@ -130,7 +136,7 @@ export async function startLifecycle(paths, env = process.env) {
130
136
  cwd,
131
137
  detached: true,
132
138
  stdio: ['ignore', out, err],
133
- env: { ...env },
139
+ env: oneShotChildEnv(env),
134
140
  windowsHide: true,
135
141
  });
136
142
  child.once('error', (err) => {
@@ -150,6 +156,11 @@ export async function startLifecycle(paths, env = process.env) {
150
156
  });
151
157
  return { status: 'started', pid: child.pid, logFile: paths.logFile };
152
158
  }
159
+ function oneShotChildEnv(env) {
160
+ const childEnv = { ...env };
161
+ delete childEnv['EVOLVER_SELF_UPDATE_SUPERVISOR'];
162
+ return childEnv;
163
+ }
153
164
  export function stopLifecycle(paths, deps = {}) {
154
165
  const pidFile = readPidFile(paths.pidFile);
155
166
  const pid = pidFile.pid;
@@ -244,6 +255,13 @@ export function renderSystemdUnit(opts = {}) {
244
255
  'Type=simple',
245
256
  `WorkingDirectory=${opts.workingDirectory ?? '%h'}`,
246
257
  ...(opts.envFile ? [`Environment="EVOLVER_ENV_FILE=${escapeSystemdEnvValue(opts.envFile)}"`] : []),
258
+ 'Environment="EVOLVER_SELF_UPDATE_SUPERVISOR=systemd"',
259
+ ...(opts.selfUpdateStateDir
260
+ ? [`Environment="EVOLVER_SELF_UPDATE_STATE_DIR=${escapeSystemdEnvValue(opts.selfUpdateStateDir)}"`]
261
+ : []),
262
+ ...(opts.selfUpdateTarget
263
+ ? [`Environment="EVOLVER_SELF_UPDATE_TARGET_PATH=${escapeSystemdEnvValue(opts.selfUpdateTarget)}"`]
264
+ : []),
247
265
  `ExecStart=${opts.execStart ?? defaultServiceExecStart()}`,
248
266
  'Restart=on-failure',
249
267
  'RestartSec=5s',
@@ -265,6 +283,7 @@ export function renderLaunchdPlist(opts = {}) {
265
283
  const workingDirectory = opts.workingDirectory ?? '/Users/YOU/your-project';
266
284
  const nodePath = opts.nodePath ?? '/usr/local/bin/node';
267
285
  const proxyBin = opts.proxyBin ?? '/Users/YOU/your-project/node_modules/@evomap/evolver-proxy/dist/bin/evolver-proxy.js';
286
+ const programArguments = opts.programArguments ?? [nodePath, proxyBin];
268
287
  const logDir = opts.logDir ?? '/Users/YOU/Library/Logs';
269
288
  const envFileBlock = opts.envFile ? ` <key>EVOLVER_ENV_FILE</key>\n <string>${escapeXml(opts.envFile)}</string>\n` : '';
270
289
  return [
@@ -276,14 +295,23 @@ export function renderLaunchdPlist(opts = {}) {
276
295
  ` <string>${DEFAULT_LABEL}</string>`,
277
296
  ' <key>ProgramArguments</key>',
278
297
  ' <array>',
279
- ` <string>${escapeXml(nodePath)}</string>`,
280
- ` <string>${escapeXml(proxyBin)}</string>`,
298
+ ...programArguments.map((argument) => ` <string>${escapeXml(argument)}</string>`),
281
299
  ' </array>',
282
300
  ' <key>WorkingDirectory</key>',
283
301
  ` <string>${escapeXml(workingDirectory)}</string>`,
284
302
  ' <key>EnvironmentVariables</key>',
285
303
  ' <dict>',
286
304
  envFileBlock.trimEnd(),
305
+ ' <key>EVOLVER_SELF_UPDATE_SUPERVISOR</key>',
306
+ ' <string>launchd</string>',
307
+ ...(opts.selfUpdateStateDir ? [
308
+ ' <key>EVOLVER_SELF_UPDATE_STATE_DIR</key>',
309
+ ` <string>${escapeXml(opts.selfUpdateStateDir)}</string>`,
310
+ ] : []),
311
+ ...(opts.selfUpdateTarget ? [
312
+ ' <key>EVOLVER_SELF_UPDATE_TARGET_PATH</key>',
313
+ ` <string>${escapeXml(opts.selfUpdateTarget)}</string>`,
314
+ ] : []),
287
315
  ' <key>PATH</key>',
288
316
  ' <string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string>',
289
317
  ' </dict>',
@@ -311,20 +339,23 @@ export function renderLaunchdPlist(opts = {}) {
311
339
  '',
312
340
  ].filter((line) => line !== '').join('\n');
313
341
  }
314
- export function renderWindowsInstaller() {
342
+ export function renderWindowsInstaller(defaults = {}) {
343
+ const ps = (value) => `'${(value ?? '').replaceAll("'", "''")}'`;
315
344
  return String.raw `param(
316
345
  [switch]$Install,
317
346
  [switch]$Uninstall,
318
347
  [string]$TaskName = 'EvoMapEvolverProxyDaemon',
319
- [string]$NodePath,
320
- [string]$ProxyBin,
321
- [string]$EnvFile
348
+ [string]$EvolverBin = ${ps(defaults.evolverBin)},
349
+ [string]$NodePath = ${ps(defaults.nodePath)},
350
+ [string]$ProxyBin = ${ps(defaults.proxyBin)},
351
+ [string]$EnvFile = ${ps(defaults.envFile)},
352
+ [string]$SelfUpdateStateDir = ${ps(defaults.selfUpdateStateDir)}
322
353
  )
323
354
 
324
355
  $ErrorActionPreference = 'Stop'
325
356
 
326
357
  if (-not ($Install -or $Uninstall)) {
327
- Write-Host 'Usage: install-evolver-proxy-windows.ps1 -Install [-NodePath ...] [-ProxyBin ...] [-EnvFile ...]'
358
+ Write-Host 'Usage: install-evolver-proxy-windows.ps1 -Install [-EvolverBin ... | -NodePath ... -ProxyBin ...] [-EnvFile ...]'
328
359
  Write-Host ' install-evolver-proxy-windows.ps1 -Uninstall [-TaskName ...]'
329
360
  exit 1
330
361
  }
@@ -337,31 +368,94 @@ if ($Uninstall) {
337
368
  exit 0
338
369
  }
339
370
 
340
- if (-not $NodePath) {
341
- $cmd = Get-Command node -ErrorAction SilentlyContinue
342
- if (-not $cmd) { Write-Error 'node.exe not on PATH; pass -NodePath explicitly.'; exit 1 }
343
- $NodePath = $cmd.Source
371
+ if (-not $EvolverBin) {
372
+ if (-not $NodePath) {
373
+ $cmd = Get-Command node -ErrorAction SilentlyContinue
374
+ if (-not $cmd) { Write-Error 'Pass -EvolverBin, or install node.exe / pass -NodePath.'; exit 1 }
375
+ $NodePath = $cmd.Source
376
+ }
377
+ if (-not $ProxyBin) { Write-Error 'Pass -EvolverBin, or -ProxyBin pointing at evolver-proxy.js.'; exit 1 }
378
+ if (-not (Test-Path $ProxyBin)) { Write-Error "Proxy bin not found at $ProxyBin"; exit 1 }
379
+ } elseif (-not (Test-Path $EvolverBin)) {
380
+ Write-Error "Evolver binary not found at $EvolverBin"; exit 1
381
+ }
382
+
383
+ if ($EvolverBin) {
384
+ if (-not $SelfUpdateStateDir) { $SelfUpdateStateDir = $env:EVOLVER_SELF_UPDATE_STATE_DIR }
385
+ if (-not $SelfUpdateStateDir) {
386
+ $SelfUpdateStateDir = Join-Path (Split-Path -Parent $EvolverBin) '.evolver-update'
387
+ }
388
+ }
389
+
390
+ foreach ($launcherValue in @($EvolverBin, $NodePath, $ProxyBin, $EnvFile, $SelfUpdateStateDir)) {
391
+ if ($launcherValue -match "[\r\n]") {
392
+ Write-Error 'Launcher paths must not contain line breaks.'
393
+ exit 1
394
+ }
395
+ }
396
+
397
+ if ($EvolverBin) {
398
+ $EvolverBin = [System.IO.Path]::GetFullPath($EvolverBin)
399
+ $SelfUpdateStateDir = [System.IO.Path]::GetFullPath($SelfUpdateStateDir)
400
+ # Service installation is the explicit upgrade boundary for the stable controller.
401
+ $existingTask = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
402
+ if ($existingTask -and $existingTask.State -eq 'Running') {
403
+ Stop-ScheduledTask -TaskName $TaskName
404
+ $stopDeadline = [DateTime]::UtcNow.AddSeconds(15)
405
+ do {
406
+ Start-Sleep -Milliseconds 100
407
+ $existingTask = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
408
+ } while ($existingTask -and $existingTask.State -eq 'Running' -and [DateTime]::UtcNow -lt $stopDeadline)
409
+ if ($existingTask -and $existingTask.State -eq 'Running') {
410
+ Write-Error 'Existing Evolver Scheduled Task did not stop; refusing to replace its recovery controller.'
411
+ exit 1
412
+ }
413
+ }
414
+ $env:EVOLVER_SELF_UPDATE_STATE_DIR = $SelfUpdateStateDir
415
+ $env:EVOLVER_SELF_UPDATE_TARGET_PATH = $EvolverBin
416
+ & $EvolverBin 'proxy' '--evolver-windows-recovery-controller-provision'
417
+ if ($LASTEXITCODE -ne 0) {
418
+ Write-Error 'Failed to provision the stable Windows recovery controller.'
419
+ exit 1
420
+ }
344
421
  }
345
- if (-not $ProxyBin) { Write-Error 'Pass -ProxyBin pointing at evolver-proxy.js.'; exit 1 }
346
- if (-not (Test-Path $ProxyBin)) { Write-Error "Proxy bin not found at $ProxyBin"; exit 1 }
347
422
 
348
423
  $launcherDir = Join-Path $env:LOCALAPPDATA 'EvoMap'
349
424
  if (-not (Test-Path $launcherDir)) { New-Item -ItemType Directory -Path $launcherDir | Out-Null }
350
425
  $launcherPath = Join-Path $launcherDir 'evolver-proxy-task-launcher.vbs'
351
426
 
352
- $nodeEsc = $NodePath.Replace('"', '""')
353
- $proxyEsc = $ProxyBin.Replace('"', '""')
427
+ $nodeEsc = if ($NodePath) { $NodePath.Replace('"', '""') } else { '' }
428
+ $proxyEsc = if ($ProxyBin) { $ProxyBin.Replace('"', '""') } else { '' }
429
+ $evolverEsc = if ($EvolverBin) { $EvolverBin.Replace('"', '""') } else { '' }
354
430
  $envEsc = if ($EnvFile) { $EnvFile.Replace('"', '""') } else { '' }
431
+ $stateDirEsc = if ($SelfUpdateStateDir) { $SelfUpdateStateDir.Replace('"', '""') } else { '' }
355
432
 
356
433
  $launcherBody = @"
357
434
  ' AUTO-GENERATED by install-evolver-proxy-windows.ps1 -- do not edit.
358
435
  ' wscript.exe is a Windows-subsystem host. WshShell.Run(..., 0, True)
359
436
  ' launches node.exe hidden and waits so Task Scheduler sees the exit code.
360
- Dim WshShell, env, cmd, rc
437
+ Dim WshShell, env, fso, stateDir, pendingPath, updaterPath, controllerPath, controllerCmd, cmd, rc
361
438
  Set WshShell = CreateObject("WScript.Shell")
362
439
  Set env = WshShell.Environment("PROCESS")
440
+ Set fso = CreateObject("Scripting.FileSystemObject")
363
441
  If "$envEsc" <> "" Then env("EVOLVER_ENV_FILE") = "$envEsc"
364
- cmd = """$nodeEsc"" ""$proxyEsc"""
442
+ env("EVOLVER_SELF_UPDATE_SUPERVISOR") = "windows-scheduled-task"
443
+ If "$evolverEsc" <> "" Then
444
+ stateDir = "$stateDirEsc"
445
+ env("EVOLVER_SELF_UPDATE_STATE_DIR") = stateDir
446
+ env("EVOLVER_SELF_UPDATE_TARGET_PATH") = "$evolverEsc"
447
+ pendingPath = stateDir & "\windows-updater\pending.json"
448
+ updaterPath = stateDir & "\windows-updater\updater.exe"
449
+ controllerPath = stateDir & "\windows-controller\evolver-recovery-controller.exe"
450
+ cmd = """$evolverEsc"" proxy"
451
+ If Not fso.FileExists(controllerPath) Then WScript.Quit 1
452
+ If fso.FileExists(pendingPath) And Not fso.FileExists(updaterPath) Then WScript.Quit 1
453
+ controllerCmd = """" & controllerPath & """ proxy --evolver-windows-recovery-controller"
454
+ rc = WshShell.Run(controllerCmd, 0, True)
455
+ WScript.Quit rc
456
+ Else
457
+ cmd = """$nodeEsc"" ""$proxyEsc"""
458
+ End If
365
459
  rc = WshShell.Run(cmd, 0, True)
366
460
  WScript.Quit rc
367
461
  "@
@@ -400,31 +494,86 @@ function serviceTarget(flags) {
400
494
  return value;
401
495
  throw new Error('missing or invalid --target (expected: launchd|systemd|windows)');
402
496
  }
403
- function installService(target, flags, env, argv1) {
497
+ async function installService(target, flags, env, argv1) {
404
498
  const dryRun = flags['dry-run'] === true;
405
499
  const envFile = typeof flags['env-file'] === 'string' ? flags['env-file'] : env['EVOLVER_ENV_FILE'];
500
+ const supervised = configuredSelfUpdateTarget(env)
501
+ ? resolveDaemonCommand(env, process.execPath, argv1)
502
+ : resolveSelfUpdatingExecutable(process.execPath, argv1);
503
+ const standaloneTarget = supervised?.args.length === 1 && supervised.args[0] === 'proxy'
504
+ ? supervised.command
505
+ : undefined;
506
+ let unixController;
507
+ let unixControllerStateDir;
508
+ if (target !== 'windows' && standaloneTarget) {
509
+ const { provisionStableUnixRecoveryController, stableUnixRecoveryControllerPathForTarget, UNIX_RECOVERY_CONTROLLER_ARG, } = await import('@evomap/evolver-proxy');
510
+ const stateDir = env['EVOLVER_SELF_UPDATE_STATE_DIR']?.trim() || undefined;
511
+ const controllerPath = dryRun
512
+ ? stableUnixRecoveryControllerPathForTarget(standaloneTarget, stateDir)
513
+ : await provisionStableUnixRecoveryController({
514
+ env: { ...env, EVOLVER_SELF_UPDATE_TARGET_PATH: standaloneTarget },
515
+ processExecPath: standaloneTarget,
516
+ });
517
+ unixController = {
518
+ command: controllerPath,
519
+ args: ['proxy', UNIX_RECOVERY_CONTROLLER_ARG],
520
+ display: `${controllerPath} proxy ${UNIX_RECOVERY_CONTROLLER_ARG}`,
521
+ };
522
+ unixControllerStateDir = dirname(dirname(controllerPath));
523
+ }
524
+ const serviceCommand = unixController ?? supervised;
406
525
  if (target === 'systemd') {
407
526
  const path = expandHome('~/.config/systemd/user/evolver-proxy.service');
408
- const unit = renderSystemdUnit({ envFile, workingDirectory: typeof flags['cwd'] === 'string' ? flags['cwd'] : undefined });
527
+ const unit = renderSystemdUnit({
528
+ envFile,
529
+ workingDirectory: typeof flags['cwd'] === 'string' ? flags['cwd'] : undefined,
530
+ ...(serviceCommand
531
+ ? { execStart: [serviceCommand.command, ...serviceCommand.args].map(quoteSystemdArg).join(' ') }
532
+ : {}),
533
+ ...(standaloneTarget ? { selfUpdateTarget: standaloneTarget } : {}),
534
+ ...(unixControllerStateDir ? { selfUpdateStateDir: unixControllerStateDir } : {}),
535
+ });
409
536
  if (!dryRun)
410
537
  writeTextFile(path, unit, 0o644);
411
- return { status: dryRun ? 'rendered' : 'installed', files: [path], service: 'systemd-user' };
538
+ return {
539
+ status: dryRun ? 'rendered' : 'installed',
540
+ files: [path, ...(unixController ? [unixController.command] : [])],
541
+ service: 'systemd-user',
542
+ };
412
543
  }
413
544
  if (target === 'launchd') {
414
545
  const path = expandHome('~/Library/LaunchAgents/com.evomap.evolver-proxy.plist');
415
546
  const plist = renderLaunchdPlist({
416
547
  envFile,
417
548
  workingDirectory: typeof flags['cwd'] === 'string' ? flags['cwd'] : process.cwd(),
549
+ ...(serviceCommand
550
+ ? { programArguments: [serviceCommand.command, ...serviceCommand.args] }
551
+ : {}),
552
+ ...(standaloneTarget ? { selfUpdateTarget: standaloneTarget } : {}),
553
+ ...(unixControllerStateDir ? { selfUpdateStateDir: unixControllerStateDir } : {}),
418
554
  nodePath: resolveStableNodePath(),
419
555
  proxyBin: resolveProxyBinPath() ?? (argv1?.startsWith('/') ? argv1 : undefined) ?? '/ABSOLUTE/PATH/TO/evolver-proxy.js',
420
556
  logDir: join(homedir(), 'Library', 'Logs'),
421
557
  });
422
558
  if (!dryRun)
423
559
  writeTextFile(path, plist, 0o644);
424
- return { status: dryRun ? 'rendered' : 'installed', files: [path], service: 'launchd' };
560
+ return {
561
+ status: dryRun ? 'rendered' : 'installed',
562
+ files: [path, ...(unixController ? [unixController.command] : [])],
563
+ service: 'launchd',
564
+ };
425
565
  }
426
566
  const path = expandHome('~/install-evolver-proxy-windows.ps1');
427
- const script = renderWindowsInstaller();
567
+ const selfUpdateStateDir = env['EVOLVER_SELF_UPDATE_STATE_DIR']?.trim();
568
+ const standalone = standaloneTarget;
569
+ const script = renderWindowsInstaller({
570
+ ...(standalone ? { evolverBin: standalone } : {
571
+ nodePath: resolveStableNodePath(),
572
+ proxyBin: resolveProxyBinPath(),
573
+ }),
574
+ ...(envFile ? { envFile } : {}),
575
+ ...(selfUpdateStateDir ? { selfUpdateStateDir } : {}),
576
+ });
428
577
  if (!dryRun)
429
578
  writeTextFile(path, script, 0o644);
430
579
  return { status: dryRun ? 'rendered' : 'installed', files: [path], service: 'windows-scheduled-task' };
@@ -469,19 +618,63 @@ async function runWatch(paths, env, flags, stdout, stderr) {
469
618
  stdout(`[Watch] Supervisor running every ${Math.round(intervalMs / 1000)}s. Ctrl-C to stop.\n`);
470
619
  return new Promise(() => { });
471
620
  }
472
- function resolveDaemonCommand(env) {
621
+ export function resolveDaemonCommand(env, execPath = process.execPath, argv1 = process.argv[1]) {
473
622
  const explicit = env['EVOLVER_LIFECYCLE_COMMAND']?.trim();
623
+ const selfUpdateTarget = configuredSelfUpdateTarget(env);
624
+ if (selfUpdateTarget) {
625
+ const supervised = standaloneProxyCommand(selfUpdateTarget);
626
+ if (explicit) {
627
+ const parsed = repairUnquotedWindowsExePath(explicit, parseCommandLine(explicit));
628
+ if (!matchesStandaloneProxyCommand(parsed, selfUpdateTarget)) {
629
+ throw new Error('EVOLVER_LIFECYCLE_COMMAND must invoke EVOLVER_SELF_UPDATE_TARGET_PATH with only the "proxy" argument; refusing mismatched self-update supervision');
630
+ }
631
+ }
632
+ return supervised;
633
+ }
474
634
  if (explicit) {
475
635
  const parsed = repairUnquotedWindowsExePath(explicit, parseCommandLine(explicit));
476
636
  if (parsed.length === 0)
477
637
  throw new Error('EVOLVER_LIFECYCLE_COMMAND is empty');
478
638
  return { command: parsed[0], args: parsed.slice(1), display: explicit };
479
639
  }
640
+ const selfExecutable = resolveSelfUpdatingExecutable(execPath, argv1);
641
+ if (selfExecutable)
642
+ return selfExecutable;
480
643
  const proxyBin = resolveProxyBinPath();
481
644
  if (proxyBin)
482
- return { command: process.execPath, args: [proxyBin], display: `${process.execPath} ${proxyBin}` };
645
+ return { command: execPath, args: [proxyBin], display: `${execPath} ${proxyBin}` };
483
646
  return { command: DEFAULT_DAEMON_NAME, args: [], display: DEFAULT_DAEMON_NAME };
484
647
  }
648
+ function configuredSelfUpdateTarget(env) {
649
+ const target = env['EVOLVER_SELF_UPDATE_TARGET_PATH']?.trim();
650
+ return target || undefined;
651
+ }
652
+ function standaloneProxyCommand(targetPath) {
653
+ return { command: targetPath, args: ['proxy'], display: `${targetPath} proxy` };
654
+ }
655
+ function matchesStandaloneProxyCommand(parsed, targetPath) {
656
+ return parsed.length === 2
657
+ && sameExecutablePath(parsed[0], targetPath)
658
+ && parsed[1] === 'proxy';
659
+ }
660
+ function sameExecutablePath(left, right) {
661
+ if (left === right)
662
+ return true;
663
+ if (process.platform !== 'win32')
664
+ return false;
665
+ const normalizeWindowsPath = (value) => value.replaceAll('/', '\\').toLowerCase();
666
+ return normalizeWindowsPath(left) === normalizeWindowsPath(right);
667
+ }
668
+ export function resolveSelfUpdatingExecutable(execPath, argv1) {
669
+ const executableName = basename(execPath).toLowerCase();
670
+ if (/^evolver(?:\.exe|-(?:darwin-(?:arm64|x64)|linux-(?:arm64|x64)|windows-x64\.exe))?$/.test(executableName)) {
671
+ return { command: execPath, args: ['proxy'], display: `${execPath} proxy` };
672
+ }
673
+ if (argv1 && basename(argv1).toLowerCase() === 'cli.js') {
674
+ return { command: execPath, args: [argv1, 'proxy'], display: `${execPath} ${argv1} proxy` };
675
+ }
676
+ return undefined;
677
+ }
485
678
  export function resolveProxyBinPath() {
486
679
  try {
487
680
  const entry = requireFromHere.resolve('@evomap/evolver-proxy');
@@ -0,0 +1,97 @@
1
+ import { type UserInfo } from 'node:os';
2
+ import { algo } from '@evomap/evolver-core';
3
+ export interface LocalMemoryGraphOptions {
4
+ dir: string;
5
+ userId: string;
6
+ legacyUserIds?: readonly string[];
7
+ now?: () => number;
8
+ maxActiveBytes?: number;
9
+ maxTailBytes?: number;
10
+ maxLineBytes?: number;
11
+ maxCompactBytes?: number;
12
+ maxCompactEdges?: number;
13
+ archiveRetention?: number;
14
+ }
15
+ export declare function resolveLocalMemoryUserId(info?: Pick<UserInfo<string>, 'uid' | 'username' | 'homedir'>): string;
16
+ export declare function resolveLocalMemoryUserIdentity(graphDir: string, info?: Pick<UserInfo<string>, 'uid' | 'username' | 'homedir'>): {
17
+ userId: string;
18
+ legacyUserIds: string[];
19
+ };
20
+ export interface MemoryGraphMaintenanceReport {
21
+ rotated: boolean;
22
+ compactedRecords: number;
23
+ corruptLines: number;
24
+ oversizedLines: number;
25
+ archives: number;
26
+ recovery: 'healthy' | 'degraded' | 'recovered' | 'empty';
27
+ }
28
+ export interface MemoryGraphHealthReport {
29
+ recovery: MemoryGraphMaintenanceReport['recovery'];
30
+ compactedRecords: number;
31
+ activeRecords: number;
32
+ corruptLines: number;
33
+ oversizedLines: number;
34
+ oversizedFiles: number;
35
+ archives: number;
36
+ busy?: boolean;
37
+ }
38
+ export interface MemoryGraphOperatorStatus extends MemoryGraphHealthReport {
39
+ selectionReason?: string;
40
+ }
41
+ export declare class MemoryGraphImportStateRejectedError extends Error {
42
+ constructor();
43
+ }
44
+ export declare class MemoryGraphBusyError extends Error {
45
+ constructor();
46
+ }
47
+ export declare class LocalMemoryGraph implements algo.MemoryGraphProvider {
48
+ private readonly dir;
49
+ private readonly userScope;
50
+ private readonly readableUserScopes;
51
+ private readonly now;
52
+ private readonly maxActiveBytes;
53
+ private readonly maxTailBytes;
54
+ private readonly maxLineBytes;
55
+ private readonly maxCompactBytes;
56
+ private readonly maxCompactEdges;
57
+ private readonly archiveRetention;
58
+ private readonly importedFingerprints;
59
+ constructor(options: LocalMemoryGraphOptions);
60
+ query(input: algo.MemoryGraphQueryInput): algo.MemoryGraphAdvice;
61
+ recordOutcome(input: algo.MemoryGraphRecordInput): void;
62
+ importV1Outcome(workspace: string, raw: unknown, source?: string): boolean;
63
+ maintain(): MemoryGraphMaintenanceReport;
64
+ private maintainUnlocked;
65
+ recoverFromArchives(): MemoryGraphMaintenanceReport;
66
+ private recoverFromArchivesUnlocked;
67
+ inspectHealth(): MemoryGraphHealthReport;
68
+ private inspectHealthUnlocked;
69
+ private withGraphLock;
70
+ private importStateFingerprint;
71
+ private appendRecordUnlocked;
72
+ private rotateAndCompactUnlocked;
73
+ private compactRequiresRecovery;
74
+ private readQueryableRecords;
75
+ private readImportRecords;
76
+ private readCompact;
77
+ private readWholeBounded;
78
+ private readTail;
79
+ private readTailFromFd;
80
+ private readRawTail;
81
+ private parseBuffer;
82
+ private writeCompact;
83
+ private writeAtomic;
84
+ private ensureSecureDir;
85
+ private secureRegularFile;
86
+ private workspaceScope;
87
+ private archiveFiles;
88
+ private nextArchivePath;
89
+ private pruneArchives;
90
+ private writeRecoveryMarker;
91
+ private hasRecoveryMarker;
92
+ private clearRecoveryMarker;
93
+ private readRawBounded;
94
+ }
95
+ export declare function sanitizeMemoryGraphSelectionReason(value: unknown): string | undefined;
96
+ export declare function formatMemoryGraphOperatorStatus(status: MemoryGraphOperatorStatus): string;
97
+ export declare function loadMemoryGraphOperatorStatus(env?: Record<string, string | undefined>): MemoryGraphOperatorStatus;