@evomap/evolver 1.89.14 → 1.89.17

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 (72) hide show
  1. package/index.js +219 -29
  2. package/package.json +1 -1
  3. package/src/adapters/claudeCode.js +2 -2
  4. package/src/adapters/codex.js +2 -2
  5. package/src/adapters/hookAdapter.js +14 -2
  6. package/src/adapters/scripts/evolver-session-start.js +182 -2
  7. package/src/config.js +11 -3
  8. package/src/evolve/guards.js +1 -1
  9. package/src/evolve/pipeline/collect.js +1 -1
  10. package/src/evolve/pipeline/dispatch.js +1 -1
  11. package/src/evolve/pipeline/enrich.js +1 -1
  12. package/src/evolve/pipeline/hub.js +1 -1
  13. package/src/evolve/pipeline/select.js +1 -1
  14. package/src/evolve/pipeline/signals.js +1 -1
  15. package/src/evolve/utils.js +1 -1
  16. package/src/evolve.js +1 -1
  17. package/src/forceUpdate.js +499 -119
  18. package/src/gep/a2aProtocol.js +1 -1
  19. package/src/gep/antiAbuseTelemetry.js +1 -1
  20. package/src/gep/autoDistillConv.js +1 -1
  21. package/src/gep/autoDistillLlm.js +1 -1
  22. package/src/gep/candidateEval.js +1 -1
  23. package/src/gep/candidates.js +1 -1
  24. package/src/gep/cliContracts.js +1154 -0
  25. package/src/gep/contentHash.js +1 -1
  26. package/src/gep/conversationDistiller.js +1 -1
  27. package/src/gep/conversationSniffer.js +1 -1
  28. package/src/gep/crypto.js +1 -1
  29. package/src/gep/curriculum.js +1 -1
  30. package/src/gep/deviceId.js +1 -1
  31. package/src/gep/envFingerprint.js +1 -1
  32. package/src/gep/epigenetics.js +1 -1
  33. package/src/gep/execBridge.js +1 -1
  34. package/src/gep/explore.js +1 -1
  35. package/src/gep/hash.js +1 -1
  36. package/src/gep/hostErrorClassifier.js +34 -0
  37. package/src/gep/hubFetch.js +1 -1
  38. package/src/gep/hubReview.js +1 -1
  39. package/src/gep/hubSearch.js +1 -1
  40. package/src/gep/hubVerify.js +1 -1
  41. package/src/gep/issueReporter.js +87 -0
  42. package/src/gep/learningSignals.js +1 -1
  43. package/src/gep/memoryGraph.js +1 -1
  44. package/src/gep/memoryGraphAdapter.js +1 -1
  45. package/src/gep/mutation.js +1 -1
  46. package/src/gep/narrativeMemory.js +1 -1
  47. package/src/gep/openPRRegistry.js +1 -1
  48. package/src/gep/paths.js +20 -0
  49. package/src/gep/personality.js +1 -1
  50. package/src/gep/policyCheck.js +1 -1
  51. package/src/gep/prompt.js +1 -1
  52. package/src/gep/recallInject.js +1 -1
  53. package/src/gep/recallVerifier.js +1 -1
  54. package/src/gep/reflection.js +1 -1
  55. package/src/gep/sanitize.js +20 -4
  56. package/src/gep/savingsCore.js +1 -1
  57. package/src/gep/selector.js +1 -1
  58. package/src/gep/signals.js +70 -24
  59. package/src/gep/skillDistiller.js +1 -1
  60. package/src/gep/solidify.js +1 -1
  61. package/src/gep/strategy.js +1 -1
  62. package/src/gep/tokenSavings.js +1 -1
  63. package/src/gep/workspaceKeychain.js +1 -1
  64. package/src/ops/lifecycle.js +501 -31
  65. package/src/proxy/extensions/traceControl.js +1 -1
  66. package/src/proxy/index.js +4 -4
  67. package/src/proxy/inject.js +1 -1
  68. package/src/proxy/lifecycle/manager.js +233 -33
  69. package/src/proxy/sync/inbound.js +5 -4
  70. package/src/proxy/sync/outbound.js +3 -2
  71. package/src/proxy/trace/extractor.js +1 -1
  72. package/src/proxy/trace/usage.js +1 -1
@@ -7,6 +7,7 @@ const fs = require('fs');
7
7
  const path = require('path');
8
8
  const os = require('os');
9
9
  const { execFileSync, execSync, spawn } = require('child_process');
10
+ const { readSettings } = require('../proxy/server/settings');
10
11
  // 10 MB — prevents RangeError on large child process output (e.g. git log/diff
11
12
  // on large repos). See GHSA reports / issue #451.
12
13
  const MAX_EXEC_BUFFER = 10 * 1024 * 1024;
@@ -46,7 +47,30 @@ function execFileText(file, args) {
46
47
  });
47
48
  }
48
49
 
50
+ // --- Test-only process-table injection -------------------------------------
51
+ // Lets the lifecycle proxy-health tests run hermetically on a host that already
52
+ // has REAL `node index.js --loop` processes (CI runners, or a live agent box).
53
+ // Without it, getRunningPids()/checkHealth()/stopOwnedLoops() read the actual
54
+ // process table via ps/proc and would (a) fail their "not_running" assertions
55
+ // against unrelated real loops and (b) risk SIGTERM-ing real production loops.
56
+ // Production never installs a table; listProcesses()/getPidCwd()/isPidRunning()
57
+ // consult it only when one has been set. Entries are { pid, args, cwd }.
58
+ var _processTableForTest = null;
59
+ function _setProcessTableForTest(table) {
60
+ _processTableForTest = Array.isArray(table) ? table.map(function (p) {
61
+ return {
62
+ pid: parseInt(p.pid, 10),
63
+ args: String(p.args || ''),
64
+ cwd: p.cwd != null ? String(p.cwd) : null,
65
+ };
66
+ }) : null;
67
+ }
68
+ function _resetProcessTableForTest() { _processTableForTest = null; }
69
+
49
70
  function listProcesses() {
71
+ if (_processTableForTest) {
72
+ return _processTableForTest.map(function (p) { return { pid: p.pid, args: p.args }; });
73
+ }
50
74
  if (process.platform === 'win32') {
51
75
  var out = execFileText('powershell', [
52
76
  '-NoProfile',
@@ -101,9 +125,225 @@ function getRunningPids() {
101
125
  }
102
126
 
103
127
  function isPidRunning(pid) {
128
+ if (_processTableForTest) {
129
+ var spRun = parseInt(pid, 10);
130
+ return _processTableForTest.some(function (p) { return p.pid === spRun; });
131
+ }
104
132
  try { process.kill(pid, 0); return true; } catch (e) { return false; }
105
133
  }
106
134
 
135
+ function boolEnv(value) {
136
+ var raw = String(value || '').trim().toLowerCase();
137
+ return raw === '1' || raw === 'true' || raw === 'yes' || raw === 'on';
138
+ }
139
+
140
+ function isLoopbackProxyUrl(value) {
141
+ var raw = String(value || '').trim().replace(/\/+$/, '');
142
+ if (!raw) return false;
143
+ try {
144
+ var parsed = new URL(raw);
145
+ if (parsed.protocol !== 'http:') return false;
146
+ var host = parsed.hostname.toLowerCase();
147
+ return host === '127.0.0.1' || host === 'localhost' || host === '::1' || host === '[::1]';
148
+ } catch (_) {
149
+ return false;
150
+ }
151
+ }
152
+
153
+ function readJsonFile(file) {
154
+ try {
155
+ if (!file || !fs.existsSync(file)) return null;
156
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
157
+ } catch (_) {
158
+ return null;
159
+ }
160
+ }
161
+
162
+ function getClaudeSettingsFile(env) {
163
+ var e = env || process.env;
164
+ var explicit = String(e.CLAUDE_SETTINGS_FILE || e.EVOMAP_CLAUDE_SETTINGS_FILE || '').trim();
165
+ if (explicit) return explicit;
166
+ var home = e.HOME || os.homedir();
167
+ return home ? path.join(home, '.claude', 'settings.json') : null;
168
+ }
169
+
170
+ function getCodexConfigFile(env) {
171
+ var e = env || process.env;
172
+ var explicit = String(e.CODEX_CONFIG_FILE || e.EVOMAP_CODEX_CONFIG_FILE || '').trim();
173
+ if (explicit) return explicit;
174
+ var home = e.HOME || os.homedir();
175
+ return home ? path.join(home, '.codex', 'config.toml') : null;
176
+ }
177
+
178
+ function stripTomlComment(line) {
179
+ var out = '';
180
+ var quote = null;
181
+ var escaped = false;
182
+ for (var i = 0; i < String(line || '').length; i++) {
183
+ var ch = line[i];
184
+ if (escaped) {
185
+ out += ch;
186
+ escaped = false;
187
+ continue;
188
+ }
189
+ if (ch === '\\' && quote === '"') {
190
+ out += ch;
191
+ escaped = true;
192
+ continue;
193
+ }
194
+ if ((ch === '"' || ch === "'") && !quote) {
195
+ quote = ch;
196
+ out += ch;
197
+ continue;
198
+ }
199
+ if (ch === quote) {
200
+ quote = null;
201
+ out += ch;
202
+ continue;
203
+ }
204
+ if (ch === '#' && !quote) break;
205
+ out += ch;
206
+ }
207
+ return out.trim();
208
+ }
209
+
210
+ function readTomlStringValue(value) {
211
+ var raw = stripTomlComment(value);
212
+ var match = raw.match(/^(['"])([\s\S]*)\1$/);
213
+ if (match) return match[2];
214
+ return raw.trim();
215
+ }
216
+
217
+ function codexConfigExpectsProxy(env) {
218
+ var file = getCodexConfigFile(env);
219
+ if (!file || !fs.existsSync(file)) return false;
220
+ var selectedProvider = null;
221
+ var section = '';
222
+ var providerUrls = {};
223
+ try {
224
+ var content = fs.readFileSync(file, 'utf8');
225
+ for (var line of content.split(/\r?\n/)) {
226
+ var clean = stripTomlComment(line);
227
+ if (!clean) continue;
228
+ var sectionMatch = clean.match(/^\[([^\]]+)\]$/);
229
+ if (sectionMatch) {
230
+ section = sectionMatch[1].trim();
231
+ continue;
232
+ }
233
+ var kv = clean.match(/^([A-Za-z0-9_.-]+)\s*=\s*([\s\S]+)$/);
234
+ if (!kv) continue;
235
+ var key = kv[1].trim();
236
+ var val = readTomlStringValue(kv[2]);
237
+ if (!section && key === 'model_provider') {
238
+ selectedProvider = val;
239
+ continue;
240
+ }
241
+ var providerMatch = section.match(/^model_providers\.([A-Za-z0-9_.-]+)$/);
242
+ if (providerMatch && key === 'base_url') {
243
+ providerUrls[providerMatch[1]] = val;
244
+ continue;
245
+ }
246
+ if (!section && key === 'base_url' && isLoopbackProxyUrl(val)) {
247
+ return true;
248
+ }
249
+ }
250
+ } catch (_) {
251
+ return false;
252
+ }
253
+ if (selectedProvider && isLoopbackProxyUrl(providerUrls[selectedProvider])) return true;
254
+ return Object.keys(providerUrls).some(function(name) {
255
+ return /(?:evomap|proxy)/i.test(name) && isLoopbackProxyUrl(providerUrls[name]);
256
+ });
257
+ }
258
+
259
+ function clientSettingsExpectProxy(env) {
260
+ var settings = readJsonFile(getClaudeSettingsFile(env));
261
+ var cfg = settings && settings.env;
262
+ if (!cfg || typeof cfg !== 'object') return false;
263
+ if (isLoopbackProxyUrl(cfg.EVOMAP_PROXY_URL)) return true;
264
+ if (String(cfg.EVOMAP_PROXY_AUTO_INJECTED || '') === '1' && isLoopbackProxyUrl(cfg.ANTHROPIC_BASE_URL)) return true;
265
+ return !!(settings._evomap_proxy_client_env && settings._evomap_proxy_client_env.managed_by === 'evomap-proxy'
266
+ && isLoopbackProxyUrl(cfg.ANTHROPIC_BASE_URL));
267
+ }
268
+
269
+ function expectsProxy(env) {
270
+ var e = env || process.env;
271
+ if (boolEnv(e.EVOMAP_PROXY)) return true;
272
+ if (String(e.A2A_TRANSPORT || '').trim().toLowerCase() === 'mailbox') return true;
273
+ if (isLoopbackProxyUrl(e.EVOMAP_PROXY_URL) || isLoopbackProxyUrl(e.ANTHROPIC_BASE_URL)) return true;
274
+ if (codexConfigExpectsProxy(e)) return true;
275
+ return clientSettingsExpectProxy(e);
276
+ }
277
+
278
+ function prepareStartEnv(env) {
279
+ var next = Object.assign({}, env || process.env);
280
+ if (expectsProxy(next)) {
281
+ next.EVOMAP_PROXY = '1';
282
+ }
283
+ return next;
284
+ }
285
+
286
+ function isProxyUrlReachable(url, token) {
287
+ if (!url || !token) return false;
288
+ try {
289
+ execFileSync(process.execPath, ['-e', `
290
+ const fs = require('fs');
291
+ const http = require('http');
292
+ const url = process.argv[1];
293
+ const token = fs.readFileSync(0, 'utf8').trim();
294
+ if (!token) process.exit(1);
295
+ const req = http.get(url.replace(/\\/+$/, '') + '/proxy/status', {
296
+ headers: { Authorization: 'Bearer ' + token },
297
+ }, (res) => {
298
+ let body = '';
299
+ res.setEncoding('utf8');
300
+ res.on('data', (chunk) => {
301
+ body += chunk;
302
+ if (body.length > 1024 * 1024) req.destroy(new Error('response too large'));
303
+ });
304
+ res.on('end', () => {
305
+ if (res.statusCode < 200 || res.statusCode >= 300) process.exit(1);
306
+ let parsed;
307
+ try { parsed = JSON.parse(body); } catch (_) { process.exit(1); }
308
+ if (parsed && parsed.status === 'running' && (parsed.proxy_protocol_version || parsed.schema_version || parsed.node_id != null)) {
309
+ process.exit(0);
310
+ }
311
+ process.exit(1);
312
+ });
313
+ });
314
+ req.setTimeout(800, () => { req.destroy(new Error('timeout')); });
315
+ req.on('error', () => process.exit(1));
316
+ `, url], { input: String(token), stdio: ['pipe', 'ignore', 'ignore'], timeout: 1500, windowsHide: true });
317
+ return true;
318
+ } catch (_) {
319
+ return false;
320
+ }
321
+ }
322
+
323
+ function checkProxyHealth(env) {
324
+ if (!expectsProxy(env)) return { healthy: true, expected: false };
325
+ var proxy = readSettings().proxy || {};
326
+ if (!proxy.url) {
327
+ return { healthy: false, expected: true, reason: 'proxy_not_configured' };
328
+ }
329
+ if (proxy.pid && !isPidRunning(proxy.pid)) {
330
+ return { healthy: false, expected: true, reason: 'proxy_pid_stale', proxyPid: proxy.pid, proxyUrl: proxy.url };
331
+ }
332
+ if (!proxy.token) {
333
+ return { healthy: false, expected: true, reason: 'proxy_token_missing', proxyPid: proxy.pid, proxyUrl: proxy.url };
334
+ }
335
+ if (!isProxyUrlReachable(proxy.url, proxy.token)) {
336
+ return { healthy: false, expected: true, reason: 'proxy_unreachable', proxyPid: proxy.pid, proxyUrl: proxy.url };
337
+ }
338
+ return { healthy: true, expected: true, proxyPid: proxy.pid, proxyUrl: proxy.url };
339
+ }
340
+
341
+ function shouldRestartForProxy(pids, env) {
342
+ if (!pids || pids.length === 0) return false;
343
+ var proxyHealth = checkProxyHealth(env);
344
+ return proxyHealth.expected === true && proxyHealth.healthy === false;
345
+ }
346
+
107
347
  function getCmdLine(pid) {
108
348
  try {
109
349
  const safePid = parseInt(pid, 10);
@@ -115,14 +355,235 @@ function getCmdLine(pid) {
115
355
  }
116
356
  }
117
357
 
358
+ function getPidCwd(pid) {
359
+ const safePid = parseInt(pid, 10);
360
+ if (!Number.isFinite(safePid) || safePid <= 0) return null;
361
+ if (_processTableForTest) {
362
+ var cwdEntry = _processTableForTest.find(function (p) { return p.pid === safePid; });
363
+ return cwdEntry ? cwdEntry.cwd : null;
364
+ }
365
+ if (process.platform === 'win32') return null;
366
+ if (process.platform === 'linux') {
367
+ try { return fs.realpathSync('/proc/' + safePid + '/cwd'); } catch (_) {}
368
+ }
369
+ try {
370
+ var lsofOut = execFileSync('lsof', ['-a', '-p', String(safePid), '-d', 'cwd', '-Fn'], {
371
+ encoding: 'utf8',
372
+ stdio: ['ignore', 'pipe', 'ignore'],
373
+ maxBuffer: MAX_EXEC_BUFFER,
374
+ timeout: 1000,
375
+ windowsHide: true
376
+ });
377
+ for (var line of lsofOut.split(/\r?\n/)) {
378
+ if (line && line[0] === 'n') {
379
+ try { return fs.realpathSync(line.slice(1)); } catch (_) { return path.resolve(line.slice(1)); }
380
+ }
381
+ }
382
+ } catch (_) {}
383
+ try {
384
+ var pwdxOut = execFileText('pwdx', [String(safePid)]).trim();
385
+ var match = pwdxOut.match(/^\d+:\s*(.+)$/);
386
+ if (match) {
387
+ try { return fs.realpathSync(match[1]); } catch (_) { return path.resolve(match[1]); }
388
+ }
389
+ } catch (_) {}
390
+ return null;
391
+ }
392
+
393
+ function commandIncludesPath(cmd, targetPath) {
394
+ if (!cmd || !targetPath) return false;
395
+ var cmdNorm = String(cmd).replace(/\\/g, '/');
396
+ var candidates = [targetPath];
397
+ try { candidates.push(fs.realpathSync(targetPath)); } catch (_) {}
398
+ return candidates.some(function(candidate) {
399
+ var normalized = path.resolve(candidate).replace(/\\/g, '/');
400
+ return normalized && cmdNorm.includes(normalized);
401
+ });
402
+ }
403
+
404
+ function splitCommandLine(cmd) {
405
+ var tokens = [];
406
+ var current = '';
407
+ var quote = null;
408
+ var escaped = false;
409
+ var raw = String(cmd || '');
410
+ for (var i = 0; i < raw.length; i++) {
411
+ var ch = raw[i];
412
+ if (escaped) {
413
+ current += ch;
414
+ escaped = false;
415
+ continue;
416
+ }
417
+ if (ch === '\\') {
418
+ escaped = true;
419
+ continue;
420
+ }
421
+ if ((ch === '"' || ch === "'") && !quote) {
422
+ quote = ch;
423
+ continue;
424
+ }
425
+ if (ch === quote) {
426
+ quote = null;
427
+ continue;
428
+ }
429
+ if (/\s/.test(ch) && !quote) {
430
+ if (current) {
431
+ tokens.push(current);
432
+ current = '';
433
+ }
434
+ continue;
435
+ }
436
+ current += ch;
437
+ }
438
+ if (escaped) current += '\\';
439
+ if (current) tokens.push(current);
440
+ return tokens;
441
+ }
442
+
443
+ function looksLikeNodeToken(token) {
444
+ var base = path.basename(String(token || '').replace(/\\/g, '/')).toLowerCase();
445
+ return base === 'node' || base === 'node.exe';
446
+ }
447
+
448
+ function nodeOptionTakesValue(option) {
449
+ var name = String(option || '').split('=')[0];
450
+ return name === '-r' || name === '--require' ||
451
+ name === '--import' ||
452
+ name === '--loader' || name === '--experimental-loader' ||
453
+ name === '--icu-data-dir' ||
454
+ name === '--openssl-config' ||
455
+ name === '--redirect-warnings';
456
+ }
457
+
458
+ function nodeOptionIsEvalMode(option) {
459
+ var name = String(option || '').split('=')[0];
460
+ return name === '-e' || name === '--eval' ||
461
+ name === '-p' || name === '--print' ||
462
+ name === '-c' || name === '--check';
463
+ }
464
+
465
+ function getNodeScriptToken(tokens) {
466
+ for (var i = 0; i < tokens.length; i++) {
467
+ if (!looksLikeNodeToken(tokens[i])) continue;
468
+ for (var j = i + 1; j < tokens.length; j++) {
469
+ var token = tokens[j];
470
+ if (!token) continue;
471
+ if (token === '--') return tokens[j + 1] || null;
472
+ if (token[0] === '-') {
473
+ if (nodeOptionIsEvalMode(token)) return null;
474
+ if (nodeOptionTakesValue(token) && !token.includes('=')) j++;
475
+ continue;
476
+ }
477
+ return token;
478
+ }
479
+ }
480
+ return null;
481
+ }
482
+
483
+ function sameRealPath(left, right) {
484
+ try {
485
+ return fs.realpathSync(left) === fs.realpathSync(right);
486
+ } catch (_) {
487
+ return false;
488
+ }
489
+ }
490
+
491
+ function commandUsesCurrentRepoRelativeIndex(cmd, cwd) {
492
+ if (!cwd) return false;
493
+ var script = getNodeScriptToken(splitCommandLine(cmd));
494
+ if (!script || path.isAbsolute(script)) return false;
495
+ if (path.basename(script.replace(/\\/g, '/')).toLowerCase() !== 'index.js') return false;
496
+ return sameRealPath(path.resolve(cwd, script), path.join(getRepoRoot(), 'index.js'));
497
+ }
498
+
499
+ function isCurrentLoopCommand(cmd, cwd) {
500
+ var raw = String(cmd || '');
501
+ var lower = raw.toLowerCase();
502
+ if (!lower.includes('node') || !lower.includes('--loop')) return false;
503
+ if (commandIncludesPath(raw, getLoopScript())) return true;
504
+ if (commandIncludesPath(raw, path.join(getRepoRoot(), 'index.js'))) return true;
505
+ return commandUsesCurrentRepoRelativeIndex(raw, cwd);
506
+ }
507
+
508
+ function readPidFile(file) {
509
+ try {
510
+ if (!file || !fs.existsSync(file)) return null;
511
+ var raw = fs.readFileSync(file, 'utf8').trim();
512
+ var pid = parseInt(raw, 10);
513
+ return Number.isFinite(pid) && pid > 0 ? pid : null;
514
+ } catch (_) {
515
+ return null;
516
+ }
517
+ }
518
+
519
+ function getOwnedLoopPids(discoveredPids) {
520
+ var candidates = new Set();
521
+ function addPid(pid) {
522
+ var parsed = parseInt(pid, 10);
523
+ if (Number.isFinite(parsed) && parsed > 0) candidates.add(parsed);
524
+ }
525
+ (discoveredPids || []).forEach(addPid);
526
+ addPid(readPidFile(PID_FILE));
527
+ try {
528
+ var proxyPid = (readSettings().proxy || {}).pid;
529
+ addPid(proxyPid);
530
+ } catch (_) {}
531
+ return Array.from(candidates).filter(function(pid) {
532
+ if (!isPidRunning(pid)) return false;
533
+ var cmd = getCmdLine(pid);
534
+ if (isCurrentLoopCommand(cmd)) return true;
535
+ return isCurrentLoopCommand(cmd, getPidCwd(pid));
536
+ });
537
+ }
538
+
539
+ function stopPids(pids, options) {
540
+ var targets = Array.from(new Set(pids || [])).map(function(pid) {
541
+ return parseInt(pid, 10);
542
+ }).filter(Number.isFinite);
543
+ for (var i = 0; i < targets.length; i++) {
544
+ console.log('[Lifecycle] Stopping PID ' + targets[i] + '...');
545
+ try { process.kill(targets[i], 'SIGTERM'); } catch (e) {}
546
+ }
547
+ var attempts = 0;
548
+ while (targets.some(isPidRunning) && attempts < 10) {
549
+ sleepMs(500);
550
+ attempts++;
551
+ }
552
+ var remaining = targets.filter(isPidRunning);
553
+ for (var j = 0; j < remaining.length; j++) {
554
+ console.log('[Lifecycle] Force-killing PID ' + remaining[j]);
555
+ if (process.platform === 'win32') {
556
+ try { execFileSync('taskkill', ['/F', '/PID', String(remaining[j])], { stdio: 'ignore', windowsHide: true }); } catch (e) {}
557
+ } else {
558
+ try { process.kill(remaining[j], 'SIGKILL'); } catch (e) {}
559
+ }
560
+ }
561
+ if (options && options.unlinkPidFile) {
562
+ try { if (fs.existsSync(PID_FILE)) fs.unlinkSync(PID_FILE); } catch (_) {}
563
+ }
564
+ if (options && options.unlinkLock) {
565
+ var evolverLock = path.join(getRepoRoot(), 'evolver.pid');
566
+ try { if (fs.existsSync(evolverLock)) fs.unlinkSync(evolverLock); } catch (_) {}
567
+ }
568
+ return { status: 'stopped', killed: targets };
569
+ }
570
+
118
571
  // --- Lifecycle ---
119
572
 
120
573
  function start(options) {
121
574
  var delayMs = (options && options.delayMs) || 0;
122
575
  var pids = getRunningPids();
123
- if (pids.length > 0) {
124
- console.log('[Lifecycle] Already running (PIDs: ' + pids.join(', ') + ').');
125
- return { status: 'already_running', pids: pids };
576
+ var ownedPids = getOwnedLoopPids(pids);
577
+ if (ownedPids.length > 0) {
578
+ if (shouldRestartForProxy(ownedPids, process.env)) {
579
+ console.log('[Lifecycle] Loop running but proxy is unhealthy; restarting.');
580
+ stopPids(ownedPids, { unlinkPidFile: true, unlinkLock: true });
581
+ ownedPids = getOwnedLoopPids(getRunningPids());
582
+ }
583
+ }
584
+ if (ownedPids.length > 0) {
585
+ console.log('[Lifecycle] Already running (PIDs: ' + ownedPids.join(', ') + ').');
586
+ return { status: 'already_running', pids: ownedPids };
126
587
  }
127
588
  if (delayMs > 0) {
128
589
  sleepMs(delayMs);
@@ -134,7 +595,7 @@ function start(options) {
134
595
  var out = fs.openSync(LOG_FILE, 'a');
135
596
  var err = fs.openSync(LOG_FILE, 'a');
136
597
 
137
- var env = Object.assign({}, process.env);
598
+ var env = prepareStartEnv(process.env);
138
599
  // .npm-global/bin is a Unix-only convention; skip the PATH injection on Windows
139
600
  // to avoid polluting the environment with a path that does not exist.
140
601
  if (process.platform !== 'win32') {
@@ -162,36 +623,23 @@ function stop() {
162
623
  try { if (fs.existsSync(PID_FILE)) fs.unlinkSync(PID_FILE); } catch (_) {}
163
624
  return { status: 'not_running' };
164
625
  }
165
- for (var i = 0; i < pids.length; i++) {
166
- console.log('[Lifecycle] Stopping PID ' + pids[i] + '...');
167
- try { process.kill(pids[i], 'SIGTERM'); } catch (e) {}
168
- }
169
- var attempts = 0;
170
- while (getRunningPids().length > 0 && attempts < 10) {
171
- sleepMs(500);
172
- attempts++;
173
- }
174
- var remaining = getRunningPids();
175
- for (var j = 0; j < remaining.length; j++) {
176
- console.log('[Lifecycle] Force-killing PID ' + remaining[j]);
177
- // Windows does not support SIGKILL; use taskkill /F instead.
178
- if (process.platform === 'win32') {
179
- try { execFileSync('taskkill', ['/F', '/PID', String(remaining[j])], { stdio: 'ignore', windowsHide: true }); } catch (e) {}
180
- } else {
181
- try { process.kill(remaining[j], 'SIGKILL'); } catch (e) {}
182
- }
183
- }
184
- // Wrap in try/catch: on Windows a just-killed process may still hold its
185
- // file handles open for a brief moment, causing EBUSY on unlinkSync.
186
- try { if (fs.existsSync(PID_FILE)) fs.unlinkSync(PID_FILE); } catch (_) {}
187
- var evolverLock = path.join(getRepoRoot(), 'evolver.pid');
188
- try { if (fs.existsSync(evolverLock)) fs.unlinkSync(evolverLock); } catch (_) {}
626
+ // Preserve the existing CLI stop semantics: stop every discoverable loop.
627
+ stopPids(pids, { unlinkPidFile: true, unlinkLock: true });
189
628
  console.log('[Lifecycle] All stopped.');
190
629
  return { status: 'stopped', killed: pids };
191
630
  }
192
631
 
632
+ function stopOwnedLoops() {
633
+ var ownedPids = getOwnedLoopPids(getRunningPids());
634
+ if (ownedPids.length === 0) {
635
+ try { if (fs.existsSync(PID_FILE)) fs.unlinkSync(PID_FILE); } catch (_) {}
636
+ return { status: 'not_running' };
637
+ }
638
+ return stopPids(ownedPids, { unlinkPidFile: true, unlinkLock: true });
639
+ }
640
+
193
641
  function restart(options) {
194
- stop();
642
+ stopOwnedLoops();
195
643
  return start(Object.assign({ delayMs: 2000 }, options || {}));
196
644
  }
197
645
 
@@ -241,8 +689,12 @@ function tailLog(lines) {
241
689
  }
242
690
 
243
691
  function checkHealth() {
244
- var pids = getRunningPids();
692
+ var pids = getOwnedLoopPids(getRunningPids());
245
693
  if (pids.length === 0) return { healthy: false, reason: 'not_running' };
694
+ var proxyHealth = checkProxyHealth(process.env);
695
+ if (!proxyHealth.healthy) {
696
+ return Object.assign({ healthy: false }, proxyHealth);
697
+ }
246
698
  if (fs.existsSync(LOG_FILE)) {
247
699
  var silenceMs = Date.now() - fs.statSync(LOG_FILE).mtimeMs;
248
700
  if (silenceMs > MAX_SILENCE_MS) {
@@ -325,4 +777,22 @@ if (require.main === module) {
325
777
  }
326
778
  }
327
779
 
328
- module.exports = { start, stop, restart, status, tailLog, checkHealth, getRunningPids };
780
+ module.exports = {
781
+ start,
782
+ stop,
783
+ restart,
784
+ status,
785
+ tailLog,
786
+ checkHealth,
787
+ getRunningPids,
788
+ expectsProxy,
789
+ prepareStartEnv,
790
+ checkProxyHealth,
791
+ shouldRestartForProxy,
792
+ isProxyUrlReachable,
793
+ isCurrentLoopCommand,
794
+ getOwnedLoopPids,
795
+ stopOwnedLoops,
796
+ _setProcessTableForTest,
797
+ _resetProcessTableForTest,
798
+ };