@evomap/evolver-cli 2.0.0-beta.0 → 2.0.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/dist/antiGeneBenchmark.js +12 -0
  2. package/dist/antiGeneEvidence.d.ts +15 -0
  3. package/dist/antiGeneEvidence.js +49 -0
  4. package/dist/antiGeneRollout.d.ts +3 -1
  5. package/dist/antiGeneRollout.js +16 -2
  6. package/dist/assetHealth.d.ts +6 -0
  7. package/dist/assetHealth.js +105 -0
  8. package/dist/assetSidecarRecovery.d.ts +14 -0
  9. package/dist/assetSidecarRecovery.js +171 -0
  10. package/dist/assetTrust.d.ts +24 -0
  11. package/dist/assetTrust.js +218 -0
  12. package/dist/atp.js +4 -2
  13. package/dist/autoDistillLlm.d.ts +6 -0
  14. package/dist/autoDistillLlm.js +44 -7
  15. package/dist/autoexec.d.ts +14 -12
  16. package/dist/autoexec.js +84 -34
  17. package/dist/autoexecConfig.d.ts +10 -0
  18. package/dist/autoexecConfig.js +68 -0
  19. package/dist/cli.js +12 -5
  20. package/dist/cliContracts.js +30 -3
  21. package/dist/cliLifecycle.d.ts +7 -0
  22. package/dist/cliLifecycle.js +9 -0
  23. package/dist/cycleConsumer.d.ts +61 -1
  24. package/dist/cycleConsumer.js +551 -16
  25. package/dist/dashboard.d.ts +33 -0
  26. package/dist/dashboard.js +352 -0
  27. package/dist/dispatch.d.ts +10 -1
  28. package/dist/dispatch.js +40 -2
  29. package/dist/distillAdmission.d.ts +13 -0
  30. package/dist/distillAdmission.js +35 -0
  31. package/dist/distillObserver.js +6 -8
  32. package/dist/distillPrimitives.d.ts +9 -7
  33. package/dist/distillPrimitives.js +65 -12
  34. package/dist/doctor.d.ts +2 -0
  35. package/dist/doctor.js +49 -3
  36. package/dist/index.d.ts +8 -2
  37. package/dist/index.js +350 -42
  38. package/dist/issueReport.d.ts +7 -0
  39. package/dist/issueReport.js +291 -0
  40. package/dist/lifecycle.d.ts +19 -1
  41. package/dist/lifecycle.js +226 -29
  42. package/dist/localMemoryGraph.d.ts +97 -0
  43. package/dist/localMemoryGraph.js +889 -0
  44. package/dist/login.d.ts +20 -4
  45. package/dist/login.js +58 -8
  46. package/dist/materialPackage.d.ts +52 -0
  47. package/dist/materialPackage.js +401 -0
  48. package/dist/materialSnapshot.d.ts +54 -0
  49. package/dist/materialSnapshot.js +370 -0
  50. package/dist/memoryEventMirror.d.ts +23 -0
  51. package/dist/memoryEventMirror.js +140 -0
  52. package/dist/migrate/fieldMap.js +25 -0
  53. package/dist/migrate/v1Import.d.ts +7 -1
  54. package/dist/migrate/v1Import.js +132 -11
  55. package/dist/nonGitWorkspaceNotice.d.ts +24 -0
  56. package/dist/nonGitWorkspaceNotice.js +122 -0
  57. package/dist/proxyToken.d.ts +10 -0
  58. package/dist/proxyToken.js +80 -0
  59. package/dist/recipe.d.ts +12 -2
  60. package/dist/recipe.js +381 -8
  61. package/dist/reuse.d.ts +5 -3
  62. package/dist/reuse.js +74 -6
  63. package/dist/reuseReport.js +16 -16
  64. package/dist/runtimeCapabilities.d.ts +18 -0
  65. package/dist/runtimeCapabilities.js +81 -0
  66. package/dist/runtimeSessionSource.d.ts +10 -0
  67. package/dist/runtimeSessionSource.js +32 -5
  68. package/dist/setupHooks.d.ts +11 -1
  69. package/dist/setupHooks.js +235 -16
  70. package/dist/skill2gep.d.ts +38 -9
  71. package/dist/skill2gep.js +147 -14
  72. package/dist/skillDistill.d.ts +1 -0
  73. package/dist/skillDistill.js +4 -4
  74. package/dist/skillFetch.d.ts +18 -0
  75. package/dist/skillFetch.js +391 -0
  76. package/dist/solo/mode.js +5 -0
  77. package/dist/sync.d.ts +38 -0
  78. package/dist/sync.js +1981 -0
  79. package/dist/trajectoryExport.js +23 -12
  80. package/dist/v1Compat.d.ts +24 -0
  81. package/dist/v1Compat.js +249 -0
  82. package/dist/version.js +2 -0
  83. package/dist/workflow.d.ts +39 -0
  84. package/dist/workflow.js +386 -0
  85. package/dist/workflowRuntime.d.ts +66 -0
  86. package/dist/workflowRuntime.js +631 -0
  87. package/package.json +12 -6
package/dist/autoexec.js CHANGED
@@ -7,46 +7,35 @@ import { readdirSync, readFileSync, writeFileSync, renameSync, mkdirSync, exists
7
7
  import { join, dirname } from 'node:path';
8
8
  import { events, assetstore, algo, exec, ops, observers, hooks, material as materialNs, util, verify, hub as hubNs, daemon as daemonNs, personality } from '@evomap/evolver-core';
9
9
  import { startResidentLoop } from './daemonLoop.js';
10
- import { connectPublicHub, createSolidifyPermitCheck, ReuseCache, reuseBeforeSolve } from '@evomap/evolver-adapter-public';
10
+ import { connectPublicHub, createSolidifyPermitCheck, ReuseCache, reuseBeforeSolve, resolveConfiguredHubUrl, resolveHubUrl } from '@evomap/evolver-adapter-public';
11
11
  import { loadEnvFileFromEnv, proxyClientFromEnv } from '@evomap/evolver-mcp';
12
12
  import { resolveValueDigestObserver } from './valueDigest.js';
13
13
  import { resolveReflectionObserver } from './reflectionObserver.js';
14
14
  import { resolveCursorRewriteObserver } from './cursorRewrite.js';
15
+ import { resolveMemoryEventMirrorObserver } from './memoryEventMirror.js';
15
16
  import { resolveDistillObserver } from './distillObserver.js';
16
17
  import { resolveAutoDistillLlm } from './autoDistillLlm.js';
17
18
  import { resolveAutoDistillAntiGene as resolveAntiGeneDistill } from './autoDistillAntiGene.js';
18
19
  import { runTranscriptDistillTick, transcriptDistillMode } from './autoDistillTranscript.js';
19
20
  import { runSessionIngestTick, scanSessionDirs } from './index.js';
21
+ import { LocalMemoryGraph, resolveLocalMemoryUserIdentity } from './localMemoryGraph.js';
20
22
  import { resolveAtpAutoDeliver } from './atpAutoDeliver.js';
21
23
  import { resolveAtpHome, resolveAtpSenderId } from './atp.js';
22
24
  import { runAutobuyPrompt } from './atpAutobuyPrompt.js';
23
25
  import * as solomode from './solo/mode.js';
24
26
  import * as gitGuard from './solo/gitGuard.js';
25
27
  import * as breaker from './solo/breaker.js';
28
+ import { initializeWorkflowStartupRecovery } from './workflowRuntime.js';
29
+ import { readAutoExecConfig } from './autoexecConfig.js';
30
+ export { readAutoExecConfig } from './autoexecConfig.js';
31
+ const ENV_FILE_UNAVAILABLE_DIAGNOSTIC = '[evolver-autoexec] env_file_unavailable\n';
26
32
  /** Create the queue layout under <home>/autoexec/{tasks,done,refused}. */
27
33
  export function ensureAutoExecDirs(base) {
28
34
  const dirs = { base, tasks: join(base, 'tasks'), done: join(base, 'done'), refused: join(base, 'refused') };
29
- for (const d of [dirs.tasks, dirs.done, dirs.refused])
30
- mkdirSync(d, { recursive: true });
35
+ for (const dir of [dirs.tasks, dirs.done, dirs.refused])
36
+ mkdirSync(dir, { recursive: true });
31
37
  return dirs;
32
38
  }
33
- /** Read <base>/config.json; deny-by-default (empty allowedRoots) when absent. Default runner 'claude' (#66). */
34
- export function readAutoExecConfig(base) {
35
- const p = join(base, 'config.json');
36
- const def = { allowedRoots: [], pollMs: 60_000, timeoutMs: 600_000, runner: 'claude' };
37
- if (!existsSync(p))
38
- return def;
39
- try {
40
- const c = JSON.parse(readFileSync(p, 'utf8'));
41
- // Coerce runner to the known set — an unknown value falls back to claude rather than reaching the registry.
42
- // cursor is a scaffold runner (#66, unverified flags); selectable here but its safe default keeps skip OFF.
43
- const runner = c.runner === 'codex' ? 'codex' : c.runner === 'cursor' ? 'cursor' : 'claude';
44
- return { ...def, ...c, allowedRoots: Array.isArray(c.allowedRoots) ? c.allowedRoots : [], runner };
45
- }
46
- catch {
47
- return def;
48
- }
49
- }
50
39
  function clippedValidationText(value) {
51
40
  return value.length <= 160 ? value : `${value.slice(0, 157)}...`;
52
41
  }
@@ -325,6 +314,40 @@ export function makeHubQuestionLink(cap, options = {}) {
325
314
  export function shouldSubmitProactiveQuestionsForTask(task) {
326
315
  return typeof task.publicQuestionContext === 'string' && task.publicQuestionContext.trim().length > 0;
327
316
  }
317
+ export function autoexecLockFailureMessage(error) {
318
+ if (error instanceof util.UnsafeLockPathError) {
319
+ return `evolver autoexec: unsafe single-instance lock (${error.reason}) - inspect the Evolver state directory before retrying\n`;
320
+ }
321
+ if (error instanceof util.LockTimeoutError) {
322
+ return 'evolver autoexec: another daemon holds the single-instance lock - refusing to start a second instance\n';
323
+ }
324
+ return 'evolver autoexec: failed to acquire the single-instance lock - refusing to start\n';
325
+ }
326
+ export function autoexecLockReleaseFailureMessage(error) {
327
+ const reason = error instanceof util.UnsafeLockPathError
328
+ ? error.reason
329
+ : typeof error === 'object' && error !== null && typeof error.reason === 'string'
330
+ ? error.reason
331
+ : null;
332
+ if (reason) {
333
+ return `evolver autoexec: could not safely release the single-instance lock (${reason}); inspect the Evolver state directory if the next start is blocked\n`;
334
+ }
335
+ return 'evolver autoexec: could not release the single-instance lock; inspect the Evolver state directory if the next start is blocked\n';
336
+ }
337
+ export function releaseAutoexecLock(lockPath, deps = {}) {
338
+ try {
339
+ const result = (deps.releaseLock ?? util.releaseLock)(lockPath);
340
+ if (result && !result.released) {
341
+ (deps.stderr ?? ((text) => { process.stderr.write(text); }))(autoexecLockReleaseFailureMessage(result));
342
+ return false;
343
+ }
344
+ return true;
345
+ }
346
+ catch (error) {
347
+ (deps.stderr ?? ((text) => { process.stderr.write(text); }))(autoexecLockReleaseFailureMessage(error));
348
+ return false;
349
+ }
350
+ }
328
351
  export function urgentQuestionRuntimeWiringStatus() {
329
352
  return hubNs.URGENT_QUESTION_RUNTIME_WIRING_STATUS;
330
353
  }
@@ -433,7 +456,7 @@ function resolvePublicHub(env = process.env, connectHub = connectPublicHub) {
433
456
  if (!existsSync(join(dir, 'token.json')))
434
457
  return undefined;
435
458
  try {
436
- const hubUrl = env['EVOMAP_HUB_URL'] ?? 'https://evomap.ai';
459
+ const hubUrl = resolveHubUrl(env);
437
460
  const resolvedSenderId = resolveAtpSenderId(env);
438
461
  if (!resolvedSenderId)
439
462
  return undefined;
@@ -444,6 +467,9 @@ function resolvePublicHub(env = process.env, connectHub = connectPublicHub) {
444
467
  return undefined;
445
468
  }
446
469
  }
470
+ function hubMode(env) {
471
+ return String(env['EVOMAP_HUB_MODE'] ?? 'public').trim().toLowerCase();
472
+ }
447
473
  /**
448
474
  * Resolve the hub link (reuse seam + outcome reporter) from the environment, or undefined when reuse is
449
475
  * not enabled/credentialed. Default OFF: requires EVOLVER_REUSE_BEFORE_SOLVE === '1' and an OAuth token at
@@ -453,11 +479,13 @@ function resolvePublicHub(env = process.env, connectHub = connectPublicHub) {
453
479
  */
454
480
  export function resolveHubLink(env = process.env, ingestor, connectHub = connectPublicHub) {
455
481
  const envFile = loadEnvFileFromEnv(env);
456
- if (envFile.error)
457
- process.stderr.write(`[evolver-autoexec] failed to load EVOLVER_ENV_FILE: ${envFile.error}\n`);
482
+ if (envFile.error) {
483
+ process.stderr.write(ENV_FILE_UNAVAILABLE_DIAGNOSTIC);
484
+ return undefined;
485
+ }
458
486
  if (env['EVOLVER_REUSE_BEFORE_SOLVE'] !== '1')
459
487
  return undefined;
460
- if (String(env['EVOMAP_HUB_MODE'] ?? 'public').toLowerCase() === 'private') {
488
+ if (hubMode(env) === 'private') {
461
489
  const proxy = proxyClientFromEnv(env);
462
490
  return proxy ? makeHubLink(makeProxyHubCapability(proxy), ingestor, env['EVOLVER_OUTCOME_REPORT'] !== '0') : undefined;
463
491
  }
@@ -478,6 +506,15 @@ export function resolveHubQuestionLink(env = process.env, connectHub = connectPu
478
506
  return undefined;
479
507
  return makeHubQuestionLink(hub, { env });
480
508
  }
509
+ export function resolveMemoryEventMirror(env = process.env, connectHub = connectPublicHub) {
510
+ if (hubMode(env) === 'private') {
511
+ return { enabled: false, reason: 'no_hub', observer: null };
512
+ }
513
+ const disabled = resolveMemoryEventMirrorObserver(env, null);
514
+ if (disabled.reason === 'disabled')
515
+ return disabled;
516
+ return resolveMemoryEventMirrorObserver(env, resolvePublicHub(env, connectHub));
517
+ }
481
518
  function solidifyVerifyFlag(env) {
482
519
  const raw = env[SOLIDIFY_VERIFY_ENV]?.trim().toLowerCase();
483
520
  if (raw === '0' || raw === 'false' || raw === 'off')
@@ -505,7 +542,7 @@ export function resolveSolidifyPermitGate(env = process.env, connectHub = connec
505
542
  const flag = solidifyVerifyFlag(env);
506
543
  if (flag === 'off')
507
544
  return undefined;
508
- const hubUrl = (env['EVOMAP_HUB_URL'] ?? env['A2A_HUB_URL'] ?? '').replace(/\/+$/, '');
545
+ const hubUrl = resolveConfiguredHubUrl(env) ?? (flag === 'on' ? resolveHubUrl(env) : undefined);
509
546
  if (!hubUrl) {
510
547
  if (flag === 'on')
511
548
  return () => ({ ok: false, reason: 'hub_solidify_verify_unavailable:no_hub_url' });
@@ -640,6 +677,8 @@ export function defaultSessionDirs(env = process.env) {
640
677
  join(h, '.cursor'),
641
678
  join(h, '.codex'),
642
679
  join(h, '.gemini', 'tmp'),
680
+ join(h, '.gemini', 'antigravity'),
681
+ join(h, '.gemini', 'antigravity-ide'),
643
682
  join(h, '.kimi'),
644
683
  join(h, 'Library', 'Application Support', 'Cursor', 'User', 'globalStorage'),
645
684
  join(h, 'AppData', 'Roaming', 'Cursor', 'User', 'globalStorage'),
@@ -767,8 +806,10 @@ export async function runAutoExec(argv) {
767
806
  // loads the file too (idempotent re-read) for its standalone callers/tests, so this is the single authoritative
768
807
  // early load, not a replacement. This MUST stay above runAutobuyPrompt() (which now runs after the lock below).
769
808
  const envFile = loadEnvFileFromEnv(process.env);
770
- if (envFile.error)
771
- process.stderr.write(`[evolver-autoexec] failed to load EVOLVER_ENV_FILE: ${envFile.error}\n`);
809
+ if (envFile.error) {
810
+ process.stderr.write(ENV_FILE_UNAVAILABLE_DIAGNOSTIC);
811
+ return 1;
812
+ }
772
813
  const home = argv.find((a) => !a.startsWith('-')) ?? join(events.evomapHome(), 'autoexec');
773
814
  const dirs = ensureAutoExecDirs(home);
774
815
  const cfg = readAutoExecConfig(home);
@@ -786,6 +827,9 @@ export async function runAutoExec(argv) {
786
827
  process.stdout.write(line + '\n');
787
828
  }
788
829
  const store = new assetstore.LocalJsonlProvider(events.assetsDir());
830
+ const memoryGraphDir = join(events.evomapHome(), 'evolution');
831
+ const memoryUser = resolveLocalMemoryUserIdentity(memoryGraphDir);
832
+ const memoryGraph = new LocalMemoryGraph({ dir: memoryGraphDir, ...memoryUser });
789
833
  // Observer bus (#113): the event total-bus, finally given its FIRST built-in observer. The value-digest
790
834
  // observer is hung off the bus and the bus is wired as the Ingestor's sink, so every emitted event fans out to
791
835
  // it; its weekly cadence + measured-value gate keep it quiet. Off via EVOLVER_VALUE_DIGEST=0. Fault-isolated:
@@ -813,6 +857,9 @@ export async function runAutoExec(argv) {
813
857
  const reflection = resolveReflectionObserver(process.env, { ingestor });
814
858
  if (reflection.observer)
815
859
  bus.register(reflection.observer);
860
+ const memoryEventMirror = resolveMemoryEventMirror(process.env);
861
+ if (memoryEventMirror.observer)
862
+ bus.register(memoryEventMirror.observer);
816
863
  const personalityStore = createAutoExecPersonalityStore();
817
864
  const engine = new algo.CycleEngine({ ingestor, selection: algo.makeGeneSelectionPoint(), store, now: () => Date.now(), personality: personalityStore });
818
865
  // Reuse-before-solve (#110) + outcome report-back: wire the adapter's reuseBeforeSolve as the hub-reuse
@@ -829,7 +876,7 @@ export async function runAutoExec(argv) {
829
876
  let warnedNoIsolation = false;
830
877
  const probationOn = geneProbationEnabled();
831
878
  const deps = {
832
- engine, store, provenance, review, personality: personalityStore,
879
+ engine, store, provenance, review, personality: personalityStore, memoryGraph,
833
880
  // Probation (#306, gated, default OFF via EVOLVER_GENE_PROBATION): try unproven auto-distilled genes (with their
834
881
  // strategy embedded) so the cross-AI loop self-closes — contained by the proven exec gates + worktree isolation.
835
882
  ...(probationOn ? { includeProbation: true } : {}),
@@ -884,7 +931,7 @@ export async function runAutoExec(argv) {
884
931
  const antiGeneDistill = resolveAutoDistillAntiGene(process.env, { store, review, ingestor });
885
932
  const transcriptDistill = resolveAutoDistillTranscript(process.env, { store, review, ingestor });
886
933
  const atpAutoDeliver = resolveAtpAutoDeliver(process.env);
887
- process.stdout.write(`evolver autoexec: runner=${cfg.runner} queue=${dirs.tasks} allowlist=${JSON.stringify(cfg.allowedRoots)} poll=${cfg.pollMs}ms reuse=${hubLink ? 'on' : 'off'} reuse-signal=${reuseSignalOn ? 'on' : 'off'} probation=${probationOn ? 'on' : 'off'} questions=${hubQuestionLink ? 'on' : 'off'} permit=${solidifyPermit ? 'on' : 'off'} value-digest=${digest.enabled ? 'on' : 'off'} reflection=${reflection.enabled ? 'on' : 'off'} cursor-rewrite=${cursorRewrite.enabled ? 'on' : `off(${cursorRewrite.reason})`} auto-distill=${distill.enabled ? 'on' : 'off'} auto-distill-llm=${llmDistill.enabled ? llmDistill.mode : 'off'} auto-distill-anti-gene=${antiGeneDistill.enabled ? antiGeneDistill.mode : 'off'} auto-distill-transcript=${transcriptDistill.enabled ? transcriptDistill.mode : 'off'} atp-autodeliver=${atpAutoDeliver.enabled ? 'on' : `off(${atpAutoDeliver.reason})`}\n`);
934
+ process.stdout.write(`evolver autoexec: runner=${cfg.runner} queue=${dirs.tasks} allowlist=${JSON.stringify(cfg.allowedRoots)} poll=${cfg.pollMs}ms reuse=${hubLink ? 'on' : 'off'} reuse-signal=${reuseSignalOn ? 'on' : 'off'} probation=${probationOn ? 'on' : 'off'} questions=${hubQuestionLink ? 'on' : 'off'} permit=${solidifyPermit ? 'on' : 'off'} value-digest=${digest.enabled ? 'on' : 'off'} reflection=${reflection.enabled ? 'on' : 'off'} memory-event-mirror=${memoryEventMirror.enabled ? 'on' : `off(${memoryEventMirror.reason ?? 'no_hub'})`} cursor-rewrite=${cursorRewrite.enabled ? 'on' : `off(${cursorRewrite.reason})`} auto-distill=${distill.enabled ? 'on' : 'off'} auto-distill-llm=${llmDistill.enabled ? llmDistill.mode : 'off'} auto-distill-anti-gene=${antiGeneDistill.enabled ? antiGeneDistill.mode : 'off'} auto-distill-transcript=${transcriptDistill.enabled ? transcriptDistill.mode : 'off'} atp-autodeliver=${atpAutoDeliver.enabled ? 'on' : `off(${atpAutoDeliver.reason})`}\n`);
888
935
  if (cfg.allowedRoots.length === 0)
889
936
  process.stdout.write(' (allowlist empty → deny-by-default: nothing runs until you add a repo to config.json)\n');
890
937
  // Single-instance lock (#106): a second daemon on the same home would double-process the queue. That is harmless
@@ -898,8 +945,8 @@ export async function runAutoExec(argv) {
898
945
  try {
899
946
  util.acquireLock(lockPath, { maxTries: 5 });
900
947
  }
901
- catch {
902
- process.stderr.write(`evolver autoexec: another daemon holds ${lockPath} — refusing to start a second instance\n`);
948
+ catch (error) {
949
+ process.stderr.write(autoexecLockFailureMessage(error));
903
950
  return 1;
904
951
  }
905
952
  // First-run auto-buyer opt-in (PORT v1 #10): introduce the autonomous spend path to interactive operators once,
@@ -914,8 +961,11 @@ export async function runAutoExec(argv) {
914
961
  process.stderr.write(`[ATP-AutoBuyer] first-run prompt failed: ${e instanceof Error ? e.message : String(e)}\n`);
915
962
  }
916
963
  const uninstallUnhandledRejectionGuard = daemonNs.installUnhandledRejectionWindow({
917
- beforeExit: () => { util.releaseLock(lockPath); },
964
+ beforeExit: () => { releaseAutoexecLock(lockPath); },
918
965
  });
966
+ // Durable workflow recovery uses the same policy/review-gated runtime factory as `evolver workflow start/resume`.
967
+ // Pass the already-loaded config so a custom autoexec home uses the same allowlist, runner, and validation profiles.
968
+ initializeWorkflowStartupRecovery({ autoExecHome: home, autoExecConfig: cfg });
919
969
  // SINGLE-FLIGHT the producer tick (same as autoExecPass): a session scan that outlasts pollMs must not let two
920
970
  // ticks interleave in recordSessionMaterial (which would re-emit material.batch_ready before watermarks settle).
921
971
  const guardedDistill = distill.enabled && distill.observer ? exec.singleFlight(() => distill.tick()) : null;
@@ -998,7 +1048,7 @@ export async function runAutoExec(argv) {
998
1048
  process.stderr.write(`[Solo] 连续失败 ${soloState.consecutiveFailures} 次达阈值,熔断停机(非盲重生)。\n`);
999
1049
  // Stop scheduling, release the lock, and exit non-zero. Detached so we
1000
1050
  // don't await our own loop.stop() from inside a tick.
1001
- void loop.stop().then(() => { uninstallUnhandledRejectionGuard(); util.releaseLock(lockPath); process.exit(1); });
1051
+ void loop.stop().then(() => { uninstallUnhandledRejectionGuard(); releaseAutoexecLock(lockPath); process.exit(1); });
1002
1052
  }
1003
1053
  };
1004
1054
  // Heartbeat (#106): record liveness + pacing on the AE spine for the WebUI console, THROTTLED so a fast poll does
@@ -1033,7 +1083,7 @@ export async function runAutoExec(argv) {
1033
1083
  return;
1034
1084
  stopping = true;
1035
1085
  process.stdout.write(`\nevolver autoexec: ${sig} → graceful stop (finishing in-flight, releasing lock)\n`);
1036
- void loop.stop().then(() => { uninstallUnhandledRejectionGuard(); util.releaseLock(lockPath); resolve(0); });
1086
+ void loop.stop().then(() => { uninstallUnhandledRejectionGuard(); releaseAutoexecLock(lockPath); resolve(0); });
1037
1087
  };
1038
1088
  process.once('SIGINT', () => shutdown('SIGINT'));
1039
1089
  process.once('SIGTERM', () => shutdown('SIGTERM'));
@@ -0,0 +1,10 @@
1
+ export type AutoExecRunner = 'claude' | 'codex' | 'cursor' | 'gemini';
2
+ export interface AutoExecConfig {
3
+ allowedRoots: string[];
4
+ pollMs: number;
5
+ timeoutMs: number;
6
+ runner: AutoExecRunner;
7
+ workflowValidationProfiles: Record<string, string[]>;
8
+ }
9
+ /** Read <base>/config.json with deny-by-default workflow and autoexec safety settings. */
10
+ export declare function readAutoExecConfig(base: string): AutoExecConfig;
@@ -0,0 +1,68 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { verify } from '@evomap/evolver-core';
4
+ const DEFAULT_POLL_MS = 60_000;
5
+ const DEFAULT_TIMEOUT_MS = 600_000;
6
+ const MAX_VALIDATION_PROFILES = 32;
7
+ const MAX_VALIDATION_COMMANDS = 16;
8
+ const MAX_VALIDATION_COMMAND_LENGTH = 300;
9
+ const PROFILE_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
10
+ const SECRET_TEXT_RE = /(?:\bBearer\s+[A-Za-z0-9._~+/=-]{8,}|\b(?:sk|gh[oprsu])_[A-Za-z0-9_-]{8,}|-----BEGIN [A-Z ]*PRIVATE KEY-----|\b(?:password|passwd|secret|token|api[_-]?key)\s*[:=]\s*\S+)/i;
11
+ function parseRunner(value) {
12
+ return value === 'codex' || value === 'cursor' || value === 'gemini' ? value : 'claude';
13
+ }
14
+ function isSafeValidationCommand(value) {
15
+ if (typeof value !== 'string')
16
+ return false;
17
+ const command = value.trim();
18
+ if (command.length === 0 || command.length > MAX_VALIDATION_COMMAND_LENGTH)
19
+ return false;
20
+ if (SECRET_TEXT_RE.test(command) || verify.SHELL_METACHARS.test(command))
21
+ return false;
22
+ return true;
23
+ }
24
+ function parseValidationProfiles(value) {
25
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
26
+ return {};
27
+ const profiles = {};
28
+ for (const [name, commands] of Object.entries(value).slice(0, MAX_VALIDATION_PROFILES)) {
29
+ if (!PROFILE_NAME_RE.test(name) || !Array.isArray(commands) || commands.length === 0 || commands.length > MAX_VALIDATION_COMMANDS)
30
+ continue;
31
+ if (!commands.every(isSafeValidationCommand))
32
+ continue;
33
+ profiles[name] = commands.map((command) => command.trim());
34
+ }
35
+ return profiles;
36
+ }
37
+ /** Read <base>/config.json with deny-by-default workflow and autoexec safety settings. */
38
+ export function readAutoExecConfig(base) {
39
+ const path = join(base, 'config.json');
40
+ const defaults = {
41
+ allowedRoots: [],
42
+ pollMs: DEFAULT_POLL_MS,
43
+ timeoutMs: DEFAULT_TIMEOUT_MS,
44
+ runner: 'claude',
45
+ workflowValidationProfiles: {},
46
+ };
47
+ if (!existsSync(path))
48
+ return defaults;
49
+ try {
50
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
51
+ return {
52
+ allowedRoots: Array.isArray(parsed['allowedRoots'])
53
+ ? parsed['allowedRoots'].filter((root) => typeof root === 'string' && root.trim().length > 0)
54
+ : [],
55
+ pollMs: typeof parsed['pollMs'] === 'number' && Number.isSafeInteger(parsed['pollMs']) && parsed['pollMs'] > 0
56
+ ? parsed['pollMs']
57
+ : DEFAULT_POLL_MS,
58
+ timeoutMs: typeof parsed['timeoutMs'] === 'number' && Number.isSafeInteger(parsed['timeoutMs']) && parsed['timeoutMs'] > 0
59
+ ? parsed['timeoutMs']
60
+ : DEFAULT_TIMEOUT_MS,
61
+ runner: parseRunner(parsed['runner']),
62
+ workflowValidationProfiles: parseValidationProfiles(parsed['workflowValidationProfiles']),
63
+ };
64
+ }
65
+ catch {
66
+ return defaults;
67
+ }
68
+ }
package/dist/cli.js CHANGED
@@ -1,7 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import { dispatch } from './dispatch.js';
2
+ import { settleCliProcess } from './cliLifecycle.js';
3
3
  const argv = process.argv.slice(2);
4
- const fail = (e) => { process.stderr.write(`${e instanceof Error ? e.message : String(e)}\n`); process.exit(1); };
5
- // Single dispatch path (registry in dispatch.ts): async handler if the verb is registered, else the runCli core.
6
- // Promise.resolve normalizes the sync (runCli → number) and async (handler → Promise<number>) branches to one exit.
7
- Promise.resolve(dispatch(argv)).then((code) => process.exit(code)).catch(fail);
4
+ async function main() {
5
+ if (argv[0] === 'proxy-token') {
6
+ const { runProxyToken } = await import('./proxyToken.js');
7
+ return runProxyToken(argv.slice(1));
8
+ }
9
+ const { dispatch } = await import('./dispatch.js');
10
+ // Single dispatch path (registry in dispatch.ts): async handler if the verb is registered, else the runCli core.
11
+ // Promise.resolve normalizes the sync (runCli → number) and async (handler → Promise<number>) branches to one exit.
12
+ return await Promise.resolve(dispatch(argv));
13
+ }
14
+ void settleCliProcess(main);
@@ -2,7 +2,7 @@ import { existsSync, readFileSync, statSync } from 'node:fs';
2
2
  import { resolve } from 'node:path';
3
3
  import { inspect, format } from 'node:util';
4
4
  import { assetstore, events, hub, wire } from '@evomap/evolver-core';
5
- import { AuthError, HubClientError, HubFetch, HubUnreachableError, connectPublicHub, gepEnvelope, globalFetchLike, } from '@evomap/evolver-adapter-public';
5
+ import { AuthError, HubClientError, HubFetch, HubUnreachableError, connectPublicHub, gepEnvelope, globalFetchLike, resolveHubUrl, } from '@evomap/evolver-adapter-public';
6
6
  import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
7
7
  import { resolveAtpHome, resolveAtpSenderId } from './atp.js';
8
8
  const REUSE_CONTRACT = 'reuse.v1';
@@ -388,11 +388,32 @@ async function findAssetInStore(ref, store) {
388
388
  }
389
389
  function loadLocalAssetsReadOnly(baseDir) {
390
390
  return [
391
- ...readJsonLines(`${baseDir}/genes.jsonl`, 'Gene'),
391
+ ...loadLocalGenesReadOnly(baseDir),
392
392
  ...readJsonLines(`${baseDir}/capsules.jsonl`, 'Capsule'),
393
393
  ...readJsonLines(`${baseDir}/events.jsonl`, 'EvolutionEvent'),
394
394
  ];
395
395
  }
396
+ function loadLocalGenesReadOnly(baseDir) {
397
+ const byId = new Map();
398
+ for (const gene of [...readGenesEnvelopeReadOnly(`${baseDir}/genes.json`), ...readJsonLines(`${baseDir}/genes.jsonl`, 'Gene')]) {
399
+ const id = stringField(gene, 'id') ?? gene.asset_id;
400
+ if (id && !byId.has(id))
401
+ byId.set(id, gene);
402
+ }
403
+ return [...byId.values()];
404
+ }
405
+ function readGenesEnvelopeReadOnly(filePath) {
406
+ if (!existsSync(filePath))
407
+ return [];
408
+ try {
409
+ const parsed = JSON.parse(readFileSync(filePath, 'utf8'));
410
+ const envelopeGenes = isRecord(parsed) && Array.isArray(parsed['genes']) ? parsed['genes'] : [];
411
+ return envelopeGenes.filter(isRecord).map((gene) => normalizeAsset({ ...gene, type: 'Gene' }));
412
+ }
413
+ catch {
414
+ throw new ContractError('schema_invalid', 'asset schema is invalid');
415
+ }
416
+ }
396
417
  function readJsonLines(filePath, type) {
397
418
  if (!existsSync(filePath))
398
419
  return [];
@@ -570,7 +591,7 @@ async function withMachineJsonConsole(enabled, deps, fn) {
570
591
  function createDefaultTransport(deps) {
571
592
  const env = deps.env ?? process.env;
572
593
  loadEnvFileFromEnv(env);
573
- const hubUrl = env['EVOMAP_HUB_URL'] ?? 'https://evomap.ai';
594
+ const hubUrl = resolveHubUrl(env);
574
595
  const evomapDir = resolveAtpHome(env);
575
596
  const sender = resolveAtpSenderId(env);
576
597
  const senderId = () => sender ?? env['A2A_NODE_ID']?.trim();
@@ -591,6 +612,8 @@ function createDefaultTransport(deps) {
591
612
  catch (err) {
592
613
  if (err instanceof AuthError)
593
614
  return { ok: false, status: err.status };
615
+ if (isAuthLikeError(err))
616
+ return { ok: false, status: 401 };
594
617
  if (err instanceof HubClientError)
595
618
  return { ok: false, status: err.status, body: err.body };
596
619
  return { ok: false, status: 0 };
@@ -602,6 +625,10 @@ function createDefaultTransport(deps) {
602
625
  publish: (bundle) => call('/a2a/publish', 'publish', bundle),
603
626
  };
604
627
  }
628
+ function isAuthLikeError(err) {
629
+ const message = err instanceof Error ? err.message : String(err);
630
+ return /oauth|login|credential|auth|401|403|node_secret/i.test(message);
631
+ }
605
632
  function classifyError(err, command) {
606
633
  if (err instanceof ContractError)
607
634
  return { reason: err.reason, message: err.safeMessage, retryable: err.reason === 'network_error' };
@@ -0,0 +1,7 @@
1
+ export interface CliProcessLike {
2
+ exitCode?: string | number | null;
3
+ stderr: {
4
+ write(chunk: string): unknown;
5
+ };
6
+ }
7
+ export declare function settleCliProcess(run: () => Promise<number>, proc?: CliProcessLike): Promise<void>;
@@ -0,0 +1,9 @@
1
+ export async function settleCliProcess(run, proc = process) {
2
+ try {
3
+ proc.exitCode = await run();
4
+ }
5
+ catch (error) {
6
+ proc.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
7
+ proc.exitCode = 1;
8
+ }
9
+ }
@@ -1,5 +1,7 @@
1
- import { assetstore, algo, events, exec, material as materialNs, personality } from '@evomap/evolver-core';
1
+ import { assetstore, algo, events, exec, material as materialNs, personality, verify } from '@evomap/evolver-core';
2
2
  type RunnerName = NonNullable<exec.AutonomousSafety['runner']>;
3
+ type SleepFn = (ms: number, signal?: AbortSignal) => Promise<void>;
4
+ type SandboxedValidationRunner = typeof verify.runSandboxedValidation;
3
5
  type MaterialCycleAction = 'cycle' | 'observe' | 'skip' | 'fail';
4
6
  type MaterialCycleStatus = exec.AutoExecVerdict['status'] | 'observed' | 'already_consumed' | 'already_terminal' | 'already_running' | 'no_signals' | 'parse_failed' | 'pending';
5
7
  interface MaterialCycleItem {
@@ -14,17 +16,63 @@ export interface MaterialCycleResult {
14
16
  processed: number;
15
17
  items: MaterialCycleItem[];
16
18
  }
19
+ export interface MaterialCycleWatchIteration {
20
+ ok: true;
21
+ group: 'cycle.watch';
22
+ iteration: number;
23
+ claimed: number;
24
+ processed: number;
25
+ cursor: number;
26
+ idle: boolean;
27
+ nextDelayMs: number;
28
+ items: MaterialCycleItem[];
29
+ }
30
+ export interface MaterialCycleWatchResult {
31
+ ok: true;
32
+ group: 'cycle.watch';
33
+ iterations: number;
34
+ claimed: number;
35
+ processed: number;
36
+ idleIterations: number;
37
+ failedItems: number;
38
+ cursor: number;
39
+ stopped: 'max_iterations' | 'max_idle' | 'cancelled';
40
+ }
41
+ export interface MaterialCycleWatchState {
42
+ ok: true;
43
+ group: 'cycle.watch.state';
44
+ updatedAt: string;
45
+ running: boolean;
46
+ iteration: number;
47
+ cursor: number;
48
+ claimed: number;
49
+ processed: number;
50
+ idleIterations: number;
51
+ failedItems: number;
52
+ lastIteration?: MaterialCycleWatchIteration;
53
+ stopped?: MaterialCycleWatchResult['stopped'] | 'state_write_failed';
54
+ }
17
55
  export interface MaterialCycleOptions {
18
56
  repo: string;
19
57
  limit?: number;
20
58
  target?: string;
21
59
  expectedEffect?: string;
60
+ validationCmds?: readonly string[];
61
+ validate?: exec.AutoExecDeps['validate'];
22
62
  runner?: RunnerName;
23
63
  timeoutMs?: number;
64
+ signal?: AbortSignal;
24
65
  safety?: Partial<exec.AutonomousSafety>;
25
66
  agent?: exec.AgentRunner;
26
67
  git?: exec.GitRunner;
27
68
  }
69
+ export interface MaterialCycleWatchOptions extends MaterialCycleOptions {
70
+ idleMs?: number;
71
+ maxIdleMs?: number;
72
+ backoffMultiplier?: number;
73
+ maxIdle?: number;
74
+ maxIterations?: number;
75
+ }
28
76
  export interface MaterialCycleDeps {
29
77
  materialStore?: materialNs.MaterialStore;
30
78
  consumer?: materialNs.ConsumerGroups;
@@ -34,9 +82,21 @@ export interface MaterialCycleDeps {
34
82
  ingestor?: events.Ingestor;
35
83
  engine?: algo.CycleEngine;
36
84
  personality?: personality.PersonalityStore;
85
+ memoryGraph?: algo.MemoryGraphProvider;
86
+ validate?: exec.AutoExecDeps['validate'];
87
+ /** Test/composition seam for the external validator; production defaults to the hardened core runner. */
88
+ runSandboxedValidation?: SandboxedValidationRunner;
89
+ agent?: exec.AgentRunner;
90
+ git?: exec.GitRunner;
91
+ safety?: Partial<exec.AutonomousSafety>;
92
+ sleep?: SleepFn;
93
+ watchStateWriter?: (path: string, state: MaterialCycleWatchState) => void;
37
94
  }
38
95
  export declare function cycleIdForMaterial(materialId: string): string;
39
96
  export declare function cycleLockPathForMaterial(materialStorePath: string, materialId: string): string;
40
97
  export declare function runMaterialCycleConsumer(opts: MaterialCycleOptions, injectedDeps?: MaterialCycleDeps): Promise<MaterialCycleResult>;
98
+ export declare function runMaterialCycleWatch(opts: MaterialCycleWatchOptions, injectedDeps?: MaterialCycleDeps, hooks?: {
99
+ onIteration?: (iteration: MaterialCycleWatchIteration) => void;
100
+ }): Promise<MaterialCycleWatchResult>;
41
101
  export declare function runCycleCommand(argv: readonly string[], injectedDeps?: MaterialCycleDeps): Promise<number>;
42
102
  export {};