@evomap/evolver-cli 2.0.0-beta.0

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 (91) hide show
  1. package/dist/antiGeneBenchmark.d.ts +9 -0
  2. package/dist/antiGeneBenchmark.js +173 -0
  3. package/dist/antiGeneRollout.d.ts +14 -0
  4. package/dist/antiGeneRollout.js +276 -0
  5. package/dist/atp.d.ts +122 -0
  6. package/dist/atp.js +413 -0
  7. package/dist/atpAutoDeliver.d.ts +53 -0
  8. package/dist/atpAutoDeliver.js +197 -0
  9. package/dist/atpAutobuyPrompt.d.ts +48 -0
  10. package/dist/atpAutobuyPrompt.js +109 -0
  11. package/dist/autoDistillAntiGene.d.ts +63 -0
  12. package/dist/autoDistillAntiGene.js +396 -0
  13. package/dist/autoDistillLlm.d.ts +94 -0
  14. package/dist/autoDistillLlm.js +510 -0
  15. package/dist/autoDistillTranscript.d.ts +87 -0
  16. package/dist/autoDistillTranscript.js +364 -0
  17. package/dist/autoRecall.d.ts +25 -0
  18. package/dist/autoRecall.js +80 -0
  19. package/dist/autoexec.d.ts +237 -0
  20. package/dist/autoexec.js +1041 -0
  21. package/dist/cli.d.ts +2 -0
  22. package/dist/cli.js +7 -0
  23. package/dist/cliContracts.d.ts +72 -0
  24. package/dist/cliContracts.js +815 -0
  25. package/dist/commands.d.ts +9 -0
  26. package/dist/commands.js +10 -0
  27. package/dist/cursorRewrite.d.ts +42 -0
  28. package/dist/cursorRewrite.js +65 -0
  29. package/dist/cycleConsumer.d.ts +42 -0
  30. package/dist/cycleConsumer.js +519 -0
  31. package/dist/daemonLoop.d.ts +33 -0
  32. package/dist/daemonLoop.js +72 -0
  33. package/dist/dispatch.d.ts +10 -0
  34. package/dist/dispatch.js +75 -0
  35. package/dist/distillObserver.d.ts +33 -0
  36. package/dist/distillObserver.js +146 -0
  37. package/dist/distillPrimitives.d.ts +48 -0
  38. package/dist/distillPrimitives.js +142 -0
  39. package/dist/doctor.d.ts +54 -0
  40. package/dist/doctor.js +931 -0
  41. package/dist/geneValue.d.ts +37 -0
  42. package/dist/geneValue.js +97 -0
  43. package/dist/index.d.ts +193 -0
  44. package/dist/index.js +1135 -0
  45. package/dist/lifecycle.d.ts +75 -0
  46. package/dist/lifecycle.js +859 -0
  47. package/dist/login.d.ts +10 -0
  48. package/dist/login.js +38 -0
  49. package/dist/migrate/divergenceAudit.d.ts +29 -0
  50. package/dist/migrate/divergenceAudit.js +37 -0
  51. package/dist/migrate/fieldMap.d.ts +18 -0
  52. package/dist/migrate/fieldMap.js +68 -0
  53. package/dist/migrate/v1Import.d.ts +16 -0
  54. package/dist/migrate/v1Import.js +118 -0
  55. package/dist/phub.d.ts +18 -0
  56. package/dist/phub.js +284 -0
  57. package/dist/recall.d.ts +26 -0
  58. package/dist/recall.js +162 -0
  59. package/dist/recipe.d.ts +61 -0
  60. package/dist/recipe.js +564 -0
  61. package/dist/reflectionObserver.d.ts +8 -0
  62. package/dist/reflectionObserver.js +6 -0
  63. package/dist/reuse.d.ts +48 -0
  64. package/dist/reuse.js +300 -0
  65. package/dist/reuseReport.d.ts +20 -0
  66. package/dist/reuseReport.js +255 -0
  67. package/dist/reviewFilter.d.ts +4 -0
  68. package/dist/reviewFilter.js +6 -0
  69. package/dist/runtimeSessionSource.d.ts +9 -0
  70. package/dist/runtimeSessionSource.js +29 -0
  71. package/dist/setupHooks.d.ts +2 -0
  72. package/dist/setupHooks.js +410 -0
  73. package/dist/skill2gep.d.ts +144 -0
  74. package/dist/skill2gep.js +321 -0
  75. package/dist/skillDistill.d.ts +75 -0
  76. package/dist/skillDistill.js +342 -0
  77. package/dist/solo/breaker.d.ts +14 -0
  78. package/dist/solo/breaker.js +21 -0
  79. package/dist/solo/gitGuard.d.ts +17 -0
  80. package/dist/solo/gitGuard.js +62 -0
  81. package/dist/solo/mode.d.ts +12 -0
  82. package/dist/solo/mode.js +55 -0
  83. package/dist/thesis.d.ts +43 -0
  84. package/dist/thesis.js +179 -0
  85. package/dist/trajectoryExport.d.ts +1 -0
  86. package/dist/trajectoryExport.js +895 -0
  87. package/dist/valueDigest.d.ts +33 -0
  88. package/dist/valueDigest.js +94 -0
  89. package/dist/version.d.ts +2 -0
  90. package/dist/version.js +14 -0
  91. package/package.json +38 -0
package/dist/doctor.js ADDED
@@ -0,0 +1,931 @@
1
+ // `evolver doctor` (#217 slice 3, read-only) — verify a runtime onboarding is SAFE without ever printing a secret.
2
+ // Read-only: it reads env + the runtime config files and reports pass/warn/fail; it never mutates config, never
3
+ // loads the env file into the process, and redacts any value before output. The smoke/reachability checks
4
+ // (heartbeat, proxy path) touch the proxy and are a SEPARATE, gated step — not here.
5
+ import { readFileSync, existsSync, statSync } from 'node:fs';
6
+ import { isAbsolute, join } from 'node:path';
7
+ import { expandHomePath, parseEnvFile } from '@evomap/evolver-mcp';
8
+ // Secrets that must live ONLY behind the EVOLVER_ENV_FILE pointer — never inlined into a runtime config (#217).
9
+ const SECRET_KEYS = [
10
+ 'A2A_NODE_SECRET',
11
+ 'EVOMAP_ENTERPRISE_TOKEN',
12
+ 'EVOMAP_PRIVATE_HUB_TOKEN',
13
+ 'EVOMAP_NODE_SECRET',
14
+ 'EVOLVER_IPC_TOKEN',
15
+ 'EVOLVER_LLM_TOKEN',
16
+ 'PHUB_ENTERPRISE_TOKEN',
17
+ 'PRIVATE_HUB_ENTERPRISE_TOKEN',
18
+ ];
19
+ const PRIVATE_TOKEN_KEYS = ['EVOMAP_ENTERPRISE_TOKEN', 'EVOMAP_PRIVATE_HUB_TOKEN', 'PHUB_ENTERPRISE_TOKEN', 'PRIVATE_HUB_ENTERPRISE_TOKEN'];
20
+ const PRIVATE_LIVE_SMOKE_FLAGS = ['EVOLVER_PRIVATE_SMOKE_SEARCH', 'EVOLVER_PRIVATE_SMOKE_REUSE_RESULT', 'EVOLVER_PRIVATE_SMOKE_PUBLISH'];
21
+ // Runtime config files setup-hooks may write (claude-code / codex). cursor's .mdc carries gene text, not creds.
22
+ const CONFIG_FILES = ['.mcp.json', join('.claude', 'settings.json'), join('.codex', 'config.toml')];
23
+ const ENV_CATALOG_DEFINITIONS = [
24
+ {
25
+ name: 'EVOLVER_ENV_FILE',
26
+ group: 'credential-store',
27
+ purpose: 'Pointer to the local env file that stores private credentials outside runtime config.',
28
+ requiredFor: 'PHub/private proxy, setup-hooks pointer-only credential flow',
29
+ defaultValue: 'unset',
30
+ },
31
+ {
32
+ name: 'A2A_NODE_SECRET',
33
+ group: 'credential-store',
34
+ purpose: 'Public hub node secret used by A2A hub authentication.',
35
+ requiredFor: 'public hub sync/publish when not using an enterprise token',
36
+ secret: true,
37
+ },
38
+ {
39
+ name: 'EVOMAP_NODE_SECRET',
40
+ group: 'credential-store',
41
+ purpose: 'Legacy/public hub node secret alias used by hub clients.',
42
+ requiredFor: 'public hub sync/publish compatibility',
43
+ secret: true,
44
+ },
45
+ {
46
+ name: 'EVOMAP_ENTERPRISE_TOKEN',
47
+ aliases: PRIVATE_TOKEN_KEYS.filter((key) => key !== 'EVOMAP_ENTERPRISE_TOKEN'),
48
+ group: 'credential-store',
49
+ purpose: 'Enterprise token used by private PHub runtime. Keep exactly one token alias set.',
50
+ requiredFor: 'EVOMAP_HUB_MODE=private',
51
+ secret: true,
52
+ },
53
+ {
54
+ name: 'EVOMAP_ENTERPRISE_SUBJECT',
55
+ aliases: ['EVOMAP_PRIVATE_SUBJECT', 'PHUB_ENTERPRISE_SUBJECT', 'USER'],
56
+ group: 'credential-store',
57
+ purpose: 'Operator or SSO subject sent to the private adapter.',
58
+ requiredFor: 'PHub inventory/audit identity',
59
+ },
60
+ {
61
+ name: 'EVOLVER_IPC_TOKEN',
62
+ group: 'credential-store',
63
+ purpose: 'Bearer token for loopback evolver-proxy IPC endpoints.',
64
+ requiredFor: 'local proxy status/search/fetch/reuse-result clients',
65
+ secret: true,
66
+ },
67
+ {
68
+ name: 'EVOLVER_LLM_TOKEN',
69
+ group: 'credential-store',
70
+ purpose: 'Bearer token for the local LLM proxy surface.',
71
+ requiredFor: 'local LLM proxy clients',
72
+ secret: true,
73
+ },
74
+ {
75
+ name: 'EVOMAP_HUB_MODE',
76
+ group: 'hub-runtime',
77
+ purpose: 'Selects public or private hub adapter mode.',
78
+ requiredFor: 'PHub runtime requires private',
79
+ defaultValue: 'public',
80
+ },
81
+ {
82
+ name: 'EVOMAP_HUB_URL',
83
+ aliases: ['A2A_HUB_URL'],
84
+ group: 'hub-runtime',
85
+ purpose: 'Hub base URL for public/private adapter connections.',
86
+ requiredFor: 'hub sync, PHub runtime, live smoke',
87
+ },
88
+ {
89
+ name: 'EVOMAP_PRIVATE_ADAPTER_MODULE',
90
+ group: 'hub-runtime',
91
+ purpose: 'Optional private adapter module override.',
92
+ requiredFor: 'local/private adapter development',
93
+ defaultValue: '@evomap/evolver-adapter-private',
94
+ },
95
+ {
96
+ name: 'EVOMAP_HUB_ALLOW_INSECURE',
97
+ group: 'hub-runtime',
98
+ purpose: 'Allows insecure hub transport when explicitly set by the operator.',
99
+ requiredFor: 'local/dev hub testing only',
100
+ defaultValue: 'unset',
101
+ },
102
+ {
103
+ name: 'EVOLVER_HEARTBEAT_MS',
104
+ group: 'hub-runtime',
105
+ purpose: 'Proxy heartbeat interval.',
106
+ requiredFor: 'proxy daemon heartbeat tuning',
107
+ },
108
+ {
109
+ name: 'EVOLVER_PROXY_URL',
110
+ group: 'proxy-loopback',
111
+ purpose: 'Loopback evolver-proxy URL used by CLI/MCP clients.',
112
+ requiredFor: 'proxy status/search/fetch/reuse-result',
113
+ defaultValue: '~/.evolver/settings.json when available',
114
+ },
115
+ {
116
+ name: 'EVOLVER_PROXY_SETTINGS_FILE',
117
+ group: 'proxy-loopback',
118
+ purpose: 'Override path for the proxy-published local settings file.',
119
+ requiredFor: 'custom proxy settings location',
120
+ },
121
+ {
122
+ name: 'EVOLVER_IPC_PORT',
123
+ aliases: ['EVOMAP_PROXY_PORT'],
124
+ group: 'proxy-loopback',
125
+ purpose: 'Loopback IPC port for evolver-proxy.',
126
+ requiredFor: 'proxy daemon startup',
127
+ },
128
+ {
129
+ name: 'NO_PROXY',
130
+ aliases: ['no_proxy'],
131
+ group: 'proxy-loopback',
132
+ purpose: 'Bypasses corporate/system proxy for local loopback traffic.',
133
+ requiredFor: 'safe local IPC when HTTP_PROXY/HTTPS_PROXY/ALL_PROXY is set',
134
+ },
135
+ {
136
+ name: 'HTTP_PROXY',
137
+ aliases: ['HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy'],
138
+ group: 'proxy-loopback',
139
+ purpose: 'System proxy variables that can affect outbound and loopback traffic.',
140
+ requiredFor: 'operator network environments',
141
+ },
142
+ {
143
+ name: 'EVOLVER_REUSE_BEFORE_SOLVE',
144
+ group: 'autoexec-reuse',
145
+ purpose: 'Enables autoexec reuse-before-solve through local/proxy candidates.',
146
+ requiredFor: 'live reuse loop',
147
+ defaultValue: '0',
148
+ },
149
+ {
150
+ name: 'EVOLVER_REUSE_SIGNAL',
151
+ group: 'autoexec-reuse',
152
+ purpose: 'Emergency switch for reuse soft-rerank.',
153
+ requiredFor: 'reuse ranking tuning',
154
+ defaultValue: 'enabled unless set to 0',
155
+ },
156
+ {
157
+ name: 'EVOLVER_REUSE_MODE',
158
+ group: 'autoexec-reuse',
159
+ purpose: 'Controls reuse mode behavior for candidate selection.',
160
+ requiredFor: 'reuse experiments',
161
+ },
162
+ {
163
+ name: 'EVOLVER_MIN_REUSE_SCORE',
164
+ group: 'autoexec-reuse',
165
+ purpose: 'Minimum score threshold for selected reuse candidates.',
166
+ requiredFor: 'reuse quality tuning',
167
+ },
168
+ {
169
+ name: 'EVOLVER_GENE_PROBATION',
170
+ group: 'autoexec-reuse',
171
+ purpose: 'Enables probation promotion/demotion loop.',
172
+ requiredFor: 'probation rollout',
173
+ defaultValue: '0',
174
+ },
175
+ {
176
+ name: 'EVOLVER_AUTO_DISTILL_LLM',
177
+ aliases: ['EVOLVER_AUTO_DISTILL'],
178
+ group: 'distill',
179
+ purpose: 'Enables LLM distillation from successful capsules.',
180
+ requiredFor: 'online gene distill',
181
+ defaultValue: 'off',
182
+ },
183
+ {
184
+ name: 'EVOLVER_AUTO_DISTILL_TRANSCRIPT',
185
+ group: 'distill',
186
+ purpose: 'Enables watched transcript distillation.',
187
+ requiredFor: 'passive transcript distill',
188
+ defaultValue: 'off',
189
+ },
190
+ {
191
+ name: 'EVOLVER_AUTO_DISTILL_ANTI_GENE',
192
+ group: 'distill',
193
+ purpose: 'Enables anti-gene distill from repeated failures.',
194
+ requiredFor: 'anti-gene rollout',
195
+ defaultValue: 'off',
196
+ },
197
+ {
198
+ name: 'EVOLVER_REFLECTION',
199
+ group: 'distill',
200
+ purpose: 'Enables reflection observer/event path.',
201
+ requiredFor: 'reflection observability',
202
+ defaultValue: 'enabled unless set to 0',
203
+ },
204
+ {
205
+ name: 'EVOLVER_VALUE_DIGEST',
206
+ group: 'observability',
207
+ purpose: 'Enables value digest observer.',
208
+ requiredFor: 'operator value summaries',
209
+ defaultValue: 'enabled unless set to 0',
210
+ },
211
+ {
212
+ name: 'EVOLVER_VALUE_DIGEST_MOTD',
213
+ group: 'observability',
214
+ purpose: 'Prints value digest as MOTD-style output when enabled.',
215
+ requiredFor: 'operator dashboard summaries',
216
+ defaultValue: '0',
217
+ },
218
+ {
219
+ name: 'EVOLVER_LLM_TRACE_CAPTURE_BODIES',
220
+ aliases: ['EVOMAP_PROXY_TRACE_CAPTURE_BODIES', 'EVOMAP_PROXY_TRACE'],
221
+ group: 'llm-trace',
222
+ purpose: 'Controls native LLM trace body capture.',
223
+ requiredFor: 'offline trajectory/raw data capture',
224
+ defaultValue: 'capture enabled unless explicitly disabled',
225
+ },
226
+ {
227
+ name: 'EVOLVER_LLM_TRACE_BODY_MAX_CHARS',
228
+ aliases: ['EVOMAP_PROXY_TRACE_MAX_FIELD_BYTES'],
229
+ group: 'llm-trace',
230
+ purpose: 'Per-body redacted capture cap.',
231
+ requiredFor: 'LLM trace storage bounds',
232
+ defaultValue: '4194304',
233
+ },
234
+ {
235
+ name: 'EVOLVER_LLM_TRACE_ENVELOPE_MAX_CHARS',
236
+ aliases: ['EVOMAP_PROXY_TRACE_ENVELOPE_MAX_BYTES'],
237
+ group: 'llm-trace',
238
+ purpose: 'Default envelope cap for trace body/stream capture.',
239
+ requiredFor: 'LLM trace storage bounds',
240
+ defaultValue: '4194304',
241
+ },
242
+ {
243
+ name: 'EVOLVER_LLM_TRACE_ENCRYPTION',
244
+ aliases: ['EVOMAP_PROXY_TRACE_ENCRYPTION'],
245
+ group: 'llm-trace',
246
+ purpose: 'Controls trace encryption envelope.',
247
+ requiredFor: 'trace privacy mode',
248
+ defaultValue: 'enabled',
249
+ },
250
+ {
251
+ name: 'EVOLVER_LLM_TRACE_DIR',
252
+ group: 'llm-trace',
253
+ purpose: 'Override directory for local LLM trace files.',
254
+ requiredFor: 'custom trace storage',
255
+ },
256
+ {
257
+ name: 'EVOLVER_TRAJECTORY_RUNTIME_SESSIONS',
258
+ aliases: ['EVOLVER_TRAJECTORY_EXPORT_RUNTIME_SESSIONS'],
259
+ group: 'trajectory-export',
260
+ purpose: 'Enables runtime session discovery during trajectory export.',
261
+ requiredFor: 'offline trajectory export',
262
+ defaultValue: '0',
263
+ },
264
+ {
265
+ name: 'EVOLVER_TRAJECTORY_RUNTIME_SESSION_DIRS',
266
+ aliases: ['EVOLVER_TRAJECTORY_EXPORT_RUNTIME_SESSION_DIRS'],
267
+ group: 'trajectory-export',
268
+ purpose: 'Extra runtime session directories for trajectory export.',
269
+ requiredFor: 'offline trajectory export',
270
+ },
271
+ {
272
+ name: 'EVOLVER_CURSOR_TRANSCRIPTS_DIR',
273
+ group: 'trajectory-export',
274
+ purpose: 'Cursor transcript directory override.',
275
+ requiredFor: 'Cursor runtime session export',
276
+ },
277
+ {
278
+ name: 'EVOLVER_SESSION_SOURCE',
279
+ group: 'trajectory-export',
280
+ purpose: 'Runtime session source selector.',
281
+ requiredFor: 'runtime adapter filtering',
282
+ },
283
+ {
284
+ name: 'EVOLVER_TRAJECTORY_INCLUDE_UNMARKED',
285
+ group: 'trajectory-export',
286
+ purpose: 'Includes unmarked runtime sessions in export.',
287
+ requiredFor: 'legacy/full trajectory capture',
288
+ defaultValue: '0',
289
+ },
290
+ {
291
+ name: 'EVOLVER_TRAJECTORY_INCLUDE_GATEWAY_CAPTURED',
292
+ group: 'trajectory-export',
293
+ purpose: 'Includes gateway-captured sessions in export.',
294
+ requiredFor: 'full trajectory capture',
295
+ defaultValue: '0',
296
+ },
297
+ {
298
+ name: 'EVOLVER_PRIVATE_SMOKE',
299
+ group: 'phub-live-smoke',
300
+ purpose: 'Opt-in switch for controlled PHub live smoke.',
301
+ requiredFor: 'real PHub test-env verification',
302
+ defaultValue: '0',
303
+ },
304
+ {
305
+ name: 'EVOLVER_PRIVATE_SMOKE_SEARCH',
306
+ group: 'phub-live-smoke',
307
+ purpose: 'Enables live PHub search/fetch smoke side effects.',
308
+ requiredFor: 'real PHub search/fetch verification',
309
+ defaultValue: '0',
310
+ },
311
+ {
312
+ name: 'EVOLVER_PRIVATE_SMOKE_REUSE_RESULT',
313
+ group: 'phub-live-smoke',
314
+ purpose: 'Enables live PHub reuse-result smoke side effects.',
315
+ requiredFor: 'real PHub outcome verification',
316
+ defaultValue: '0',
317
+ },
318
+ {
319
+ name: 'EVOLVER_PRIVATE_SMOKE_PUBLISH',
320
+ group: 'phub-live-smoke',
321
+ purpose: 'Enables live PHub publish smoke side effects.',
322
+ requiredFor: 'real PHub publish verification',
323
+ defaultValue: '0',
324
+ },
325
+ {
326
+ name: 'EVOLVER_PRIVATE_SMOKE_ASSET_ID',
327
+ group: 'phub-live-smoke',
328
+ purpose: 'Asset id used by live PHub reuse-result smoke when search is not enabled.',
329
+ requiredFor: 'EVOLVER_PRIVATE_SMOKE_REUSE_RESULT=1 without search',
330
+ },
331
+ {
332
+ name: 'EVOLVER_PRIVATE_SMOKE_SIGNALS',
333
+ group: 'phub-live-smoke',
334
+ purpose: 'Comma-separated signals used by live PHub search smoke.',
335
+ requiredFor: 'EVOLVER_PRIVATE_SMOKE_SEARCH=1',
336
+ },
337
+ {
338
+ name: 'EVOLVER_HOME',
339
+ aliases: ['EVOMAP_HOME', 'EVOMAP_DIR'],
340
+ group: 'local-paths',
341
+ purpose: 'Local Evolver data/settings root.',
342
+ requiredFor: 'custom local state location',
343
+ defaultValue: '~/.evomap or ~/.evolver depending on component',
344
+ },
345
+ {
346
+ name: 'EVOLVER_SETTINGS_DIR',
347
+ group: 'local-paths',
348
+ purpose: 'Settings directory override used by telemetry/settings readers.',
349
+ requiredFor: 'custom settings location',
350
+ },
351
+ {
352
+ name: 'EVOLVER_REPO_ROOT',
353
+ group: 'local-paths',
354
+ purpose: 'Repository root override for export/discovery flows.',
355
+ requiredFor: 'trajectory/runtime discovery',
356
+ },
357
+ {
358
+ name: 'EVOLVER_SOLO',
359
+ group: 'safety-mode',
360
+ purpose: 'Enables solo lockdown mode, disabling hub reuse and ATP paths.',
361
+ requiredFor: 'local-only safe mode',
362
+ defaultValue: '0',
363
+ },
364
+ {
365
+ name: 'EVOLVER_SOLO_MAX_FAILS',
366
+ group: 'safety-mode',
367
+ purpose: 'Circuit-breaker threshold for solo mode.',
368
+ requiredFor: 'solo lockdown tuning',
369
+ },
370
+ {
371
+ name: 'EVOLVER_ATP',
372
+ group: 'marketplace-atp',
373
+ purpose: 'Controls ATP marketplace/payment feature surface.',
374
+ requiredFor: 'ATP flows',
375
+ defaultValue: 'off unless explicitly enabled',
376
+ },
377
+ {
378
+ name: 'EVOLVER_ATP_AUTOBUY',
379
+ group: 'marketplace-atp',
380
+ purpose: 'Controls automatic ATP buy behavior.',
381
+ requiredFor: 'operator-approved ATP automation',
382
+ defaultValue: 'off',
383
+ },
384
+ {
385
+ name: 'EVOLVER_ATP_AUTODELIVER',
386
+ group: 'marketplace-atp',
387
+ purpose: 'Controls automatic ATP delivery behavior.',
388
+ requiredFor: 'operator-approved ATP automation',
389
+ defaultValue: 'off',
390
+ },
391
+ {
392
+ name: 'EVOLVER_LIFECYCLE_COMMAND',
393
+ group: 'lifecycle',
394
+ purpose: 'Command managed by the lifecycle supervisor.',
395
+ requiredFor: 'lifecycle start/stop/status flows',
396
+ },
397
+ {
398
+ name: 'EVOLVER_LIFECYCLE_STATE_DIR',
399
+ group: 'lifecycle',
400
+ purpose: 'Lifecycle state directory override.',
401
+ requiredFor: 'custom lifecycle state location',
402
+ },
403
+ {
404
+ name: 'EVOLVER_LIFECYCLE_LOG_DIR',
405
+ group: 'lifecycle',
406
+ purpose: 'Lifecycle log directory override.',
407
+ requiredFor: 'custom lifecycle logs',
408
+ },
409
+ {
410
+ name: 'EVOLVER_LIFECYCLE_REQUIRE_PROXY_STATUS',
411
+ group: 'lifecycle',
412
+ purpose: 'Requires proxy status readiness during lifecycle checks.',
413
+ requiredFor: 'proxy service supervision',
414
+ },
415
+ {
416
+ name: 'EVOLVER_SELF_UPDATE',
417
+ group: 'self-update',
418
+ purpose: 'Controls self-update behavior.',
419
+ requiredFor: 'operator-controlled proxy update rollout',
420
+ defaultValue: 'off unless explicitly enabled',
421
+ },
422
+ {
423
+ name: 'EVOLVER_SELF_UPDATE_PUBLIC_KEY',
424
+ group: 'self-update',
425
+ purpose: 'Public key used to verify self-update artifacts.',
426
+ requiredFor: 'self-update verification',
427
+ },
428
+ {
429
+ name: 'EVOLVER_SELF_UPDATE_TARGET_PATH',
430
+ group: 'self-update',
431
+ purpose: 'Target path for self-update installation.',
432
+ requiredFor: 'self-update installation',
433
+ },
434
+ ];
435
+ /** Mask token-like runs (>=16 chars of base64/hex/url-safe) so doctor output can never leak a secret value. */
436
+ export function redact(s) {
437
+ return s.replace(/[A-Za-z0-9_\-+/=]{16,}/g, 'REDACTED');
438
+ }
439
+ // The EVOLVER_ENV_FILE pointer as written into a runtime config — JSON (`"EVOLVER_ENV_FILE": "…"`) or TOML
440
+ // (`EVOLVER_ENV_FILE = "…"`). Format-agnostic so doctor finds the pointer setup-hooks wrote even when the operator's
441
+ // shell does not export it (#279 Bugbot).
442
+ const POINTER_RE = /EVOLVER_ENV_FILE"?\s*[:=]\s*"([^"]+)"/;
443
+ /** Loopback hosts a NO_PROXY entry must EXACTLY be to cover local IPC/proxy ('*' = bypass all). Exact-entry match,
444
+ * not substring, so `127.0.0.10` / `notlocalhost.com` do not count (#279 Bugbot). */
445
+ const LOOPBACK_ENTRIES = new Set(['127.0.0.1', 'localhost', '::1', '[::1]', '*']);
446
+ /**
447
+ * Run the read-only doctor checks. Pure given its (injectable) deps — no config mutation, no env-file load into the
448
+ * process. Returns the check list; the CLI formats + sets the exit code.
449
+ */
450
+ export function runDoctorChecks(deps = {}) {
451
+ const env = deps.env ?? process.env;
452
+ const root = deps.configRoot ?? process.cwd();
453
+ const read = deps.readFile ?? ((p) => readFileSync(p, 'utf8'));
454
+ const exists = deps.exists ?? existsSync;
455
+ const statMode = deps.statMode ?? ((p) => {
456
+ try {
457
+ return statSync(p).mode;
458
+ }
459
+ catch {
460
+ return undefined;
461
+ }
462
+ });
463
+ const checks = [];
464
+ // 1. env-file: EVOLVER_ENV_FILE should point at a readable credential store. The pointer may come from the
465
+ // operator's shell OR from the runtime config setup-hooks wrote (#279 Bugbot) — check both. Report KEY NAMES
466
+ // only (never values), parsed PURELY (parseEnvFile) so the file is not loaded into this process.
467
+ const envFromProc = env['EVOLVER_ENV_FILE']?.trim();
468
+ let envSource = 'env';
469
+ let envPath = envFromProc;
470
+ if (!envPath) {
471
+ for (const rel of CONFIG_FILES) {
472
+ const p = join(root, rel);
473
+ if (!exists(p))
474
+ continue;
475
+ let text;
476
+ try {
477
+ text = read(p);
478
+ }
479
+ catch {
480
+ continue;
481
+ }
482
+ const m = POINTER_RE.exec(text);
483
+ if (m?.[1]) {
484
+ envPath = m[1];
485
+ envSource = rel;
486
+ break;
487
+ }
488
+ }
489
+ }
490
+ let envFileValues = {};
491
+ let envFileReadiness = { status: 'missing_pointer' };
492
+ if (!envPath) {
493
+ checks.push({ name: 'env-file', status: 'warn', detail: 'EVOLVER_ENV_FILE not set in env or runtime config — hub/proxy features have no credential store to read' });
494
+ }
495
+ else {
496
+ const resolved = isAbsolute(envPath) ? envPath : expandHomePath(envPath);
497
+ if (!exists(resolved)) {
498
+ const detail = `EVOLVER_ENV_FILE points at a missing file: ${redact(resolved)}`;
499
+ envFileReadiness = { status: 'unusable', detail };
500
+ checks.push({ name: 'env-file', status: 'fail', detail });
501
+ }
502
+ else {
503
+ try {
504
+ const parsed = parseEnvFile(read(resolved));
505
+ envFileValues = parsed;
506
+ const keys = Object.keys(parsed);
507
+ const insecureMode = insecureSecretFileMode(keys, statMode(resolved));
508
+ if (insecureMode) {
509
+ const detail = `${redact(resolved)} readable (via ${envSource}), but mode ${insecureMode.modeText} exposes secret-like keys [${insecureMode.keys.join(', ')}]; run chmod 600 on the credential store`;
510
+ envFileReadiness = { status: 'unusable', detail };
511
+ checks.push({ name: 'env-file', status: 'fail', detail });
512
+ }
513
+ else {
514
+ envFileReadiness = { status: 'readable' };
515
+ checks.push({ name: 'env-file', status: 'pass', detail: `${redact(resolved)} readable (via ${envSource}), ${keys.length} key(s): ${keys.join(', ')}` });
516
+ }
517
+ }
518
+ catch (e) {
519
+ const detail = `EVOLVER_ENV_FILE unreadable: ${redact(e instanceof Error ? e.message : String(e))}`;
520
+ envFileReadiness = { status: 'unusable', detail };
521
+ checks.push({ name: 'env-file', status: 'fail', detail });
522
+ }
523
+ }
524
+ }
525
+ // 2. config-no-secrets: runtime config must reference creds via the EVOLVER_ENV_FILE pointer, never inline a secret.
526
+ const offenders = [];
527
+ for (const rel of CONFIG_FILES) {
528
+ const p = join(root, rel);
529
+ if (!exists(p))
530
+ continue;
531
+ let text;
532
+ try {
533
+ text = read(p);
534
+ }
535
+ catch {
536
+ continue;
537
+ }
538
+ // Match an actual KEY ASSIGNMENT (`KEY:`/`KEY =`, JSON or TOML), with a left boundary, so the key name merely
539
+ // appearing inside a path / comment / unrelated string is NOT a false positive (#279 Bugbot).
540
+ const found = SECRET_KEYS.filter((k) => new RegExp(`(^|[^A-Za-z0-9_])${k}"?\\s*[:=]`).test(text));
541
+ if (found.length > 0)
542
+ offenders.push(`${rel} [${found.join(', ')}]`);
543
+ }
544
+ checks.push(offenders.length > 0
545
+ ? { name: 'config-no-secrets', status: 'fail', detail: `runtime config inlines secret keys (use the EVOLVER_ENV_FILE pointer instead): ${offenders.join('; ')}` }
546
+ : { name: 'config-no-secrets', status: 'pass', detail: 'no inline secret keys in runtime config (pointer-only)' });
547
+ const effectiveEnv = { ...env, ...envFileValues };
548
+ // 3. no-proxy-loopback: a system proxy must not intercept loopback IPC/LLM-proxy traffic (NO_PROXY must list 127.0.0.1).
549
+ const noProxyEntries = `${effectiveEnv['NO_PROXY'] ?? ''},${effectiveEnv['no_proxy'] ?? ''}`.split(/[\s,]+/).map((s) => s.trim().toLowerCase()).filter(Boolean);
550
+ const proxySet = Boolean(effectiveEnv['HTTP_PROXY'] || effectiveEnv['http_proxy'] || effectiveEnv['HTTPS_PROXY'] || effectiveEnv['https_proxy'] || effectiveEnv['ALL_PROXY'] || effectiveEnv['all_proxy']);
551
+ const loopbackCovered = noProxyEntries.some((e) => LOOPBACK_ENTRIES.has(e));
552
+ if (!proxySet) {
553
+ checks.push({ name: 'no-proxy-loopback', status: 'pass', detail: 'no system proxy set — loopback IPC/proxy is not at risk' });
554
+ }
555
+ else if (loopbackCovered) {
556
+ checks.push({ name: 'no-proxy-loopback', status: 'pass', detail: 'NO_PROXY covers loopback (127.0.0.1/localhost)' });
557
+ }
558
+ else {
559
+ checks.push({ name: 'no-proxy-loopback', status: 'warn', detail: 'a system proxy is set but NO_PROXY lacks 127.0.0.1/localhost — local IPC/LLM-proxy traffic may be intercepted; add them to NO_PROXY' });
560
+ }
561
+ if (deps.profile === 'private-runtime') {
562
+ checks.push(...privateRuntimeChecks(env, envFileValues, envFileReadiness));
563
+ }
564
+ return checks;
565
+ }
566
+ export function buildEnvCatalog(deps = {}) {
567
+ const env = deps.env ?? process.env;
568
+ const root = deps.configRoot ?? process.cwd();
569
+ const read = deps.readFile ?? ((p) => readFileSync(p, 'utf8'));
570
+ const exists = deps.exists ?? existsSync;
571
+ const statMode = deps.statMode ?? ((p) => {
572
+ try {
573
+ return statSync(p).mode;
574
+ }
575
+ catch {
576
+ return undefined;
577
+ }
578
+ });
579
+ const envFile = readEnvFileForCatalog({ env, root, read, exists, statMode });
580
+ const entries = ENV_CATALOG_DEFINITIONS.map((def) => materializeCatalogEntry(def, env, envFile.values, envFile.pointerSource));
581
+ return { profile: deps.profile ?? 'general', envFile: envFile.readiness, entries };
582
+ }
583
+ function readEnvFileForCatalog(args) {
584
+ const { env, root, read, exists, statMode } = args;
585
+ const envFromProc = env['EVOLVER_ENV_FILE']?.trim();
586
+ let pointerSource = envFromProc ? 'env' : undefined;
587
+ let envPath = envFromProc;
588
+ if (!envPath) {
589
+ for (const rel of CONFIG_FILES) {
590
+ const p = join(root, rel);
591
+ if (!exists(p))
592
+ continue;
593
+ let text;
594
+ try {
595
+ text = read(p);
596
+ }
597
+ catch {
598
+ continue;
599
+ }
600
+ const m = POINTER_RE.exec(text);
601
+ if (m?.[1]) {
602
+ envPath = m[1];
603
+ pointerSource = rel;
604
+ break;
605
+ }
606
+ }
607
+ }
608
+ if (!envPath)
609
+ return { values: {}, readiness: { status: 'missing_pointer' } };
610
+ const resolved = isAbsolute(envPath) ? envPath : expandHomePath(envPath);
611
+ if (!exists(resolved))
612
+ return withPointerSource({ values: {}, readiness: { status: 'unusable', detail: 'EVOLVER_ENV_FILE points at a missing file' } }, pointerSource);
613
+ try {
614
+ const values = parseEnvFile(read(resolved));
615
+ const insecureMode = insecureSecretFileMode(Object.keys(values), statMode(resolved));
616
+ if (insecureMode) {
617
+ return withPointerSource({
618
+ values,
619
+ readiness: {
620
+ status: 'unusable',
621
+ detail: `EVOLVER_ENV_FILE is readable, but mode ${insecureMode.modeText} exposes secret-like keys [${insecureMode.keys.join(', ')}]; run chmod 600 on the credential store`,
622
+ },
623
+ }, pointerSource);
624
+ }
625
+ return withPointerSource({ values, readiness: { status: 'readable' } }, pointerSource);
626
+ }
627
+ catch {
628
+ return withPointerSource({ values: {}, readiness: { status: 'unusable', detail: 'EVOLVER_ENV_FILE is unreadable or invalid; check credential store syntax and permissions' } }, pointerSource);
629
+ }
630
+ }
631
+ function withPointerSource(read, pointerSource) {
632
+ return pointerSource ? { ...read, pointerSource } : read;
633
+ }
634
+ function materializeCatalogEntry(def, env, envFile, envFilePointerSource) {
635
+ const keys = [def.name, ...(def.aliases ?? [])];
636
+ const sources = [];
637
+ const setKeys = [];
638
+ let sawEmpty = false;
639
+ for (const key of keys) {
640
+ const envOwn = Object.prototype.hasOwnProperty.call(env, key);
641
+ const fileOwn = Object.prototype.hasOwnProperty.call(envFile, key);
642
+ if (fileOwn && hasValue(envFile[key])) {
643
+ sources.push('env-file');
644
+ setKeys.push(key);
645
+ }
646
+ else if (fileOwn) {
647
+ sources.push('env-file');
648
+ sawEmpty = true;
649
+ }
650
+ else if (envOwn && hasValue(env[key])) {
651
+ sources.push('env');
652
+ setKeys.push(key);
653
+ }
654
+ else if (envOwn) {
655
+ sources.push('env');
656
+ sawEmpty = true;
657
+ }
658
+ }
659
+ if (def.name === 'EVOLVER_ENV_FILE' && envFilePointerSource) {
660
+ sources.push(envFilePointerSource);
661
+ setKeys.push('EVOLVER_ENV_FILE');
662
+ }
663
+ const uniqueSources = [...new Set(sources)];
664
+ const uniqueSetKeys = [...new Set(setKeys)];
665
+ const state = uniqueSetKeys.length > 0 ? 'set' : sawEmpty ? 'empty' : 'unset';
666
+ return {
667
+ name: def.name,
668
+ group: def.group,
669
+ purpose: def.purpose,
670
+ ...(def.requiredFor ? { requiredFor: def.requiredFor } : {}),
671
+ ...(def.defaultValue ? { defaultValue: def.defaultValue } : {}),
672
+ ...(def.aliases && def.aliases.length > 0 ? { aliases: [...def.aliases] } : {}),
673
+ secret: Boolean(def.secret) || keys.some(isSecretKeyName),
674
+ state,
675
+ sources: uniqueSources,
676
+ setKeys: uniqueSetKeys,
677
+ };
678
+ }
679
+ function privateRuntimeChecks(env, envFile, envFileReadiness) {
680
+ const checks = [];
681
+ const mode = privateValue(env, envFile, 'EVOMAP_HUB_MODE')?.toLowerCase();
682
+ if (mode === 'private') {
683
+ checks.push({ name: 'phub-mode', status: 'pass', detail: 'EVOMAP_HUB_MODE=private' });
684
+ }
685
+ else if (!mode) {
686
+ checks.push({ name: 'phub-mode', status: 'fail', detail: 'EVOMAP_HUB_MODE is missing; set EVOMAP_HUB_MODE=private in EVOLVER_ENV_FILE for PHub runtime' });
687
+ }
688
+ else {
689
+ checks.push({ name: 'phub-mode', status: 'fail', detail: `EVOMAP_HUB_MODE=${redact(mode)}; expected private for PHub runtime` });
690
+ }
691
+ const hubUrl = privateValue(env, envFile, 'EVOMAP_HUB_URL');
692
+ if (!hubUrl) {
693
+ checks.push({ name: 'phub-url', status: 'fail', detail: 'EVOMAP_HUB_URL is missing; point it at the PHub test-env URL' });
694
+ }
695
+ else if (isProductionLikeHubUrl(hubUrl)) {
696
+ checks.push({ name: 'phub-url', status: 'warn', detail: `${redact(hubUrl)} does not look like a test-env URL; do not run live smoke against production PHub` });
697
+ }
698
+ else {
699
+ checks.push({ name: 'phub-url', status: 'pass', detail: `${redact(hubUrl)} configured` });
700
+ }
701
+ const tokenKeys = PRIVATE_TOKEN_KEYS.filter((key) => hasValue(privateValue(env, envFile, key)));
702
+ if (tokenKeys.length === 0) {
703
+ checks.push({ name: 'phub-token', status: 'fail', detail: `missing enterprise token key in EVOLVER_ENV_FILE; expected one of ${PRIVATE_TOKEN_KEYS.join(', ')}` });
704
+ }
705
+ else if (tokenKeys.length > 1) {
706
+ checks.push({ name: 'phub-token', status: 'warn', detail: `multiple enterprise token aliases are set (${tokenKeys.join(', ')}); keep exactly one alias to avoid adapter precedence drift` });
707
+ }
708
+ else {
709
+ checks.push({ name: 'phub-token', status: 'pass', detail: `enterprise token key present: ${tokenKeys.join(', ')}` });
710
+ }
711
+ const subjectKeys = ['EVOMAP_ENTERPRISE_SUBJECT', 'EVOMAP_PRIVATE_SUBJECT', 'PHUB_ENTERPRISE_SUBJECT', 'USER'];
712
+ const subjectKey = subjectKeys.find((key) => hasValue(privateValue(env, envFile, key)));
713
+ checks.push(subjectKey
714
+ ? { name: 'phub-subject', status: 'pass', detail: `enterprise subject key present: ${subjectKey}` }
715
+ : { name: 'phub-subject', status: 'warn', detail: 'enterprise subject not set; private adapter will fall back to evolver-proxy' });
716
+ const adapter = privateValue(env, envFile, 'EVOMAP_PRIVATE_ADAPTER_MODULE');
717
+ checks.push(adapter
718
+ ? { name: 'phub-adapter', status: 'pass', detail: `private adapter module configured: ${redact(adapter)}` }
719
+ : { name: 'phub-adapter', status: 'pass', detail: 'EVOMAP_PRIVATE_ADAPTER_MODULE not set; default @evomap/evolver-adapter-private will be used' });
720
+ const proxyUrl = privateValue(env, envFile, 'EVOLVER_PROXY_URL');
721
+ const ipcToken = privateValue(env, envFile, 'EVOLVER_IPC_TOKEN');
722
+ if (proxyUrl && !isLoopbackProxyUrl(proxyUrl)) {
723
+ checks.push({ name: 'phub-proxy', status: 'fail', detail: `EVOLVER_PROXY_URL must be loopback for local IPC, got ${redact(proxyUrl)}` });
724
+ }
725
+ else if (proxyUrl && ipcToken) {
726
+ checks.push({ name: 'phub-proxy', status: 'pass', detail: `loopback proxy env configured at ${redact(proxyUrl)}` });
727
+ }
728
+ else if (proxyUrl || ipcToken) {
729
+ checks.push({ name: 'phub-proxy', status: 'warn', detail: 'partial proxy env; set both EVOLVER_PROXY_URL and EVOLVER_IPC_TOKEN, or rely on ~/.evolver/settings.json after proxy start' });
730
+ }
731
+ else {
732
+ checks.push({ name: 'phub-proxy', status: 'warn', detail: 'no explicit EVOLVER_PROXY_URL/EVOLVER_IPC_TOKEN; clients must read ~/.evolver/settings.json after evolver-proxy starts' });
733
+ }
734
+ const reuse = privateValue(env, envFile, 'EVOLVER_REUSE_BEFORE_SOLVE');
735
+ checks.push(reuse === '1'
736
+ ? { name: 'phub-reuse', status: 'pass', detail: 'EVOLVER_REUSE_BEFORE_SOLVE=1 enables autoexec private reuse through the proxy' }
737
+ : { name: 'phub-reuse', status: 'warn', detail: 'EVOLVER_REUSE_BEFORE_SOLVE is not 1; autoexec will not use PHub reuse-before-solve' });
738
+ checks.push(privateLiveSmokeCheck(env, envFile, {
739
+ mode,
740
+ hubUrl,
741
+ envFileReadiness,
742
+ tokenCount: tokenKeys.length,
743
+ }));
744
+ return checks;
745
+ }
746
+ function privateLiveSmokeCheck(env, envFile, essentials) {
747
+ const enabled = privateValue(env, envFile, 'EVOLVER_PRIVATE_SMOKE') === '1';
748
+ const optionalFlags = PRIVATE_LIVE_SMOKE_FLAGS.filter((key) => privateValue(env, envFile, key) === '1');
749
+ if (essentials.envFileReadiness.status === 'unusable') {
750
+ return {
751
+ name: 'phub-live-smoke',
752
+ status: 'fail',
753
+ detail: `live smoke readiness cannot be verified because ${essentials.envFileReadiness.detail}`,
754
+ };
755
+ }
756
+ if (!enabled && optionalFlags.length === 0) {
757
+ return {
758
+ name: 'phub-live-smoke',
759
+ status: 'warn',
760
+ detail: 'live PHub smoke is opt-in; set EVOLVER_PRIVATE_SMOKE=1 only in a controlled PHub test-env',
761
+ };
762
+ }
763
+ if (!enabled && optionalFlags.length > 0) {
764
+ return {
765
+ name: 'phub-live-smoke',
766
+ status: 'fail',
767
+ detail: `${optionalFlags.join(', ')} set but EVOLVER_PRIVATE_SMOKE is not 1; live smoke would be skipped while side-effect flags look enabled`,
768
+ };
769
+ }
770
+ const missing = [];
771
+ if (essentials.mode !== 'private')
772
+ missing.push('EVOMAP_HUB_MODE=private');
773
+ if (!essentials.hubUrl)
774
+ missing.push('EVOMAP_HUB_URL');
775
+ if (essentials.tokenCount === 0)
776
+ missing.push(`one of ${PRIVATE_TOKEN_KEYS.join('|')}`);
777
+ if (missing.length > 0) {
778
+ return {
779
+ name: 'phub-live-smoke',
780
+ status: 'fail',
781
+ detail: `EVOLVER_PRIVATE_SMOKE=1 but required live smoke input is missing: ${missing.join(', ')}`,
782
+ };
783
+ }
784
+ if (essentials.hubUrl && isProductionLikeHubUrl(essentials.hubUrl)) {
785
+ return {
786
+ name: 'phub-live-smoke',
787
+ status: 'fail',
788
+ detail: `EVOLVER_PRIVATE_SMOKE=1 refuses production-like PHub URL ${redact(essentials.hubUrl)}; use a test/staging/dev/local PHub URL`,
789
+ };
790
+ }
791
+ const reuseResult = privateValue(env, envFile, 'EVOLVER_PRIVATE_SMOKE_REUSE_RESULT') === '1';
792
+ const search = privateValue(env, envFile, 'EVOLVER_PRIVATE_SMOKE_SEARCH') === '1';
793
+ const assetId = privateValue(env, envFile, 'EVOLVER_PRIVATE_SMOKE_ASSET_ID');
794
+ if (reuseResult && !search && !assetId) {
795
+ return {
796
+ name: 'phub-live-smoke',
797
+ status: 'fail',
798
+ detail: 'EVOLVER_PRIVATE_SMOKE_REUSE_RESULT=1 needs EVOLVER_PRIVATE_SMOKE_ASSET_ID or EVOLVER_PRIVATE_SMOKE_SEARCH=1',
799
+ };
800
+ }
801
+ const sideEffects = optionalFlags.length > 0 ? optionalFlags.join(', ') : 'hello/heartbeat only';
802
+ return {
803
+ name: 'phub-live-smoke',
804
+ status: 'pass',
805
+ detail: `live smoke inputs are ready for controlled test-env (${sideEffects})`,
806
+ };
807
+ }
808
+ function insecureSecretFileMode(keys, mode) {
809
+ if (mode === undefined)
810
+ return undefined;
811
+ if ((mode & 0o077) === 0)
812
+ return undefined;
813
+ const secretKeys = keys.filter(isSecretKeyName);
814
+ return secretKeys.length > 0 ? { modeText: (mode & 0o777).toString(8).padStart(3, '0'), keys: secretKeys } : undefined;
815
+ }
816
+ function isSecretKeyName(key) {
817
+ if (SECRET_KEYS.includes(key))
818
+ return true;
819
+ return /(^|_)(SECRET|TOKEN|PASSWORD|PRIVATE_KEY|API_KEY|NODE_SECRET|IPC_TOKEN)(_|$)/.test(key);
820
+ }
821
+ function hasValue(value) {
822
+ return value !== undefined && value.trim().length > 0;
823
+ }
824
+ function privateValue(env, envFile, key) {
825
+ if (Object.prototype.hasOwnProperty.call(envFile, key))
826
+ return envFile[key]?.trim();
827
+ const fromEnv = env[key]?.trim();
828
+ return fromEnv || undefined;
829
+ }
830
+ function isLoopbackProxyUrl(raw) {
831
+ try {
832
+ const url = new URL(raw);
833
+ const hostname = url.hostname.toLowerCase();
834
+ return (url.protocol === 'http:' || url.protocol === 'https:')
835
+ && (hostname === '127.0.0.1' || hostname === 'localhost' || hostname === '::1' || hostname === '[::1]');
836
+ }
837
+ catch {
838
+ return false;
839
+ }
840
+ }
841
+ function isProductionLikeHubUrl(raw) {
842
+ try {
843
+ const host = new URL(raw).hostname.toLowerCase();
844
+ if (isLocalHubHost(host))
845
+ return false;
846
+ return !/(^|[-.])(test|staging|stage|dev|local)([-.]|$)/.test(host);
847
+ }
848
+ catch {
849
+ return true;
850
+ }
851
+ }
852
+ function isLocalHubHost(host) {
853
+ return host === 'localhost'
854
+ || host === '::1'
855
+ || host === '[::1]'
856
+ || /^127(?:\.\d{1,3}){3}$/.test(host);
857
+ }
858
+ function parseFlags(argv) {
859
+ let root;
860
+ let json = false;
861
+ let envCatalog = false;
862
+ let profile = 'general';
863
+ for (let i = 0; i < argv.length; i++) {
864
+ const a = argv[i];
865
+ if (a === '--json')
866
+ json = true;
867
+ else if (a === '--root') {
868
+ const v = argv[++i];
869
+ if (v)
870
+ root = v;
871
+ }
872
+ else if (a?.startsWith('--root='))
873
+ root = a.slice('--root='.length);
874
+ else if (a === '--private-runtime' || a === '--phub')
875
+ profile = 'private-runtime';
876
+ else if (a === '--env-catalog')
877
+ envCatalog = true;
878
+ }
879
+ return { ...(root !== undefined ? { root } : {}), json, profile, envCatalog };
880
+ }
881
+ const ICON = { pass: 'ok ', warn: 'warn', fail: 'FAIL' };
882
+ export async function runDoctor(argv, deps = {}) {
883
+ const f = parseFlags(argv);
884
+ if (f.envCatalog) {
885
+ const catalog = buildEnvCatalog({ ...deps, profile: f.profile, ...(f.root !== undefined ? { configRoot: f.root } : {}) });
886
+ if (f.json) {
887
+ process.stdout.write(`${JSON.stringify({ ok: true, ...catalog })}\n`);
888
+ }
889
+ else {
890
+ process.stdout.write(formatEnvCatalog(catalog, deps.label ?? (f.profile === 'private-runtime' ? 'evolver phub doctor' : 'evolver doctor')));
891
+ }
892
+ return 0;
893
+ }
894
+ const checks = runDoctorChecks({ ...deps, profile: f.profile, ...(f.root !== undefined ? { configRoot: f.root } : {}) });
895
+ const failed = checks.some((c) => c.status === 'fail');
896
+ if (f.json) {
897
+ process.stdout.write(`${JSON.stringify({ ok: !failed, profile: f.profile, checks })}\n`);
898
+ }
899
+ else {
900
+ process.stdout.write(`${deps.label ?? (f.profile === 'private-runtime' ? 'evolver phub doctor' : 'evolver doctor')} (read-only):\n`);
901
+ for (const c of checks)
902
+ process.stdout.write(` [${ICON[c.status]}] ${c.name}: ${c.detail}\n`);
903
+ process.stdout.write(failed ? 'doctor: FAIL — fix the items above.\n' : 'doctor: ok.\n');
904
+ }
905
+ return failed ? 1 : 0;
906
+ }
907
+ /** Registry-shaped handler (argv -> exit code). */
908
+ export const runDoctorCommand = (argv) => runDoctor(argv);
909
+ function formatEnvCatalog(catalog, label) {
910
+ const groups = [...new Set(catalog.entries.map((entry) => entry.group))];
911
+ const lines = [
912
+ `${label} env catalog (read-only):`,
913
+ ` env-file: ${catalog.envFile.status}`,
914
+ ...('detail' in catalog.envFile ? [` env-file-detail: ${catalog.envFile.detail}`] : []),
915
+ ' values: never printed; secret entries only show state/source/key names',
916
+ ];
917
+ for (const group of groups) {
918
+ lines.push('', `[${group}]`);
919
+ for (const entry of catalog.entries.filter((item) => item.group === group)) {
920
+ const aliases = entry.aliases && entry.aliases.length > 0 ? ` aliases=${entry.aliases.join(',')}` : '';
921
+ const source = entry.sources.length > 0 ? entry.sources.join('+') : 'none';
922
+ const setKeys = entry.setKeys.length > 0 ? ` keys=${entry.setKeys.join(',')}` : '';
923
+ const secret = entry.secret ? ' secret' : '';
924
+ const def = entry.defaultValue ? ` default=${entry.defaultValue}` : '';
925
+ const required = entry.requiredFor ? ` required-for=${entry.requiredFor}` : '';
926
+ lines.push(` ${entry.name}: ${entry.state} source=${source}${setKeys}${aliases}${secret}${def}${required}`);
927
+ lines.push(` ${entry.purpose}`);
928
+ }
929
+ }
930
+ return `${lines.join('\n')}\n`;
931
+ }