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

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 (60) 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/atp.js +4 -2
  7. package/dist/autoDistillLlm.js +4 -1
  8. package/dist/autoexec.d.ts +4 -1
  9. package/dist/autoexec.js +23 -5
  10. package/dist/cli.js +12 -5
  11. package/dist/cliContracts.js +8 -2
  12. package/dist/cliLifecycle.d.ts +7 -0
  13. package/dist/cliLifecycle.js +9 -0
  14. package/dist/cycleConsumer.d.ts +59 -1
  15. package/dist/cycleConsumer.js +382 -5
  16. package/dist/dashboard.d.ts +21 -0
  17. package/dist/dashboard.js +173 -0
  18. package/dist/dispatch.d.ts +1 -0
  19. package/dist/dispatch.js +27 -2
  20. package/dist/distillObserver.js +2 -2
  21. package/dist/distillPrimitives.d.ts +1 -1
  22. package/dist/distillPrimitives.js +29 -2
  23. package/dist/doctor.js +15 -3
  24. package/dist/index.d.ts +6 -1
  25. package/dist/index.js +251 -30
  26. package/dist/lifecycle.js +6 -2
  27. package/dist/login.d.ts +20 -4
  28. package/dist/login.js +58 -8
  29. package/dist/materialPackage.d.ts +52 -0
  30. package/dist/materialPackage.js +404 -0
  31. package/dist/materialSnapshot.d.ts +30 -0
  32. package/dist/materialSnapshot.js +148 -0
  33. package/dist/memoryEventMirror.d.ts +23 -0
  34. package/dist/memoryEventMirror.js +140 -0
  35. package/dist/migrate/fieldMap.js +25 -0
  36. package/dist/nonGitWorkspaceNotice.d.ts +24 -0
  37. package/dist/nonGitWorkspaceNotice.js +122 -0
  38. package/dist/proxyToken.d.ts +10 -0
  39. package/dist/proxyToken.js +80 -0
  40. package/dist/recipe.d.ts +10 -2
  41. package/dist/recipe.js +349 -7
  42. package/dist/reuseReport.js +16 -16
  43. package/dist/runtimeSessionSource.d.ts +10 -0
  44. package/dist/runtimeSessionSource.js +32 -5
  45. package/dist/setupHooks.d.ts +6 -1
  46. package/dist/setupHooks.js +5 -2
  47. package/dist/skill2gep.d.ts +38 -9
  48. package/dist/skill2gep.js +147 -14
  49. package/dist/skillDistill.d.ts +1 -0
  50. package/dist/skillDistill.js +4 -4
  51. package/dist/skillFetch.d.ts +18 -0
  52. package/dist/skillFetch.js +391 -0
  53. package/dist/solo/mode.js +5 -0
  54. package/dist/sync.d.ts +26 -0
  55. package/dist/sync.js +988 -0
  56. package/dist/trajectoryExport.js +23 -12
  57. package/dist/v1Compat.d.ts +24 -0
  58. package/dist/v1Compat.js +249 -0
  59. package/dist/version.js +2 -0
  60. package/package.json +8 -6
@@ -1,10 +1,22 @@
1
- import { dirname, join, resolve } from 'node:path';
2
- import { assetstore, algo, events, exec, material as materialNs, personality, schema, signals, util } from '@evomap/evolver-core';
3
- import { parseRuntimeSessionSources } from './runtimeSessionSource.js';
1
+ import { accessSync, constants, lstatSync, mkdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
2
+ import { basename, dirname, join, resolve } from 'node:path';
3
+ import { assetstore, algo, events, exec, material as materialNs, personality, schema, signals, util, verify } from '@evomap/evolver-core';
4
+ import { materialHasRuntimeSessionSnapshot, materialSourceAvailable, runtimeSessionSourcesForMaterial } from './materialSnapshot.js';
4
5
  import { signalTokens } from './distillPrimitives.js';
5
6
  import { readEvents, showCycle } from './commands.js';
6
7
  const CYCLE_GROUP = 'cycle';
7
8
  const DEFAULT_LIMIT = 5;
9
+ const DEFAULT_WATCH_IDLE_MS = 1000;
10
+ const DEFAULT_WATCH_MAX_IDLE_MS = 30_000;
11
+ const DEFAULT_WATCH_BACKOFF = 2;
12
+ const CYCLE_USAGE = 'usage: evolver cycle show <id> | evolver cycle status [--json] | evolver cycle recover [--limit N] [--json] | evolver cycle watch --repo <path> [--idle-ms N] [--max-idle N] [--state-file <path>] [--validation-cmd <cmd>] [--timeout-ms N] [--json] | evolver cycle --repo <path> [--limit N] [--target <path>] [--expected-effect <text>] [--runner claude|codex|cursor] [--validation-cmd <cmd>] [--timeout-ms N]\n';
13
+ const WATCH_USAGE = 'usage: evolver cycle watch --repo <path> [--limit N] [--idle-ms N] [--max-idle-ms N] [--max-idle N] [--max-iterations N] [--state-file <path>] [--target <path>] [--expected-effect <text>] [--runner claude|codex|cursor] [--validation-cmd <cmd>] [--timeout-ms N] [--json]\n';
14
+ class CycleWatchStateWriteError extends Error {
15
+ constructor() {
16
+ super('cycle watch state file write failed');
17
+ this.name = 'CycleWatchStateWriteError';
18
+ }
19
+ }
8
20
  function parseFlags(argv) {
9
21
  const out = {};
10
22
  for (let i = 0; i < argv.length; i++) {
@@ -22,12 +34,63 @@ function parseFlags(argv) {
22
34
  }
23
35
  return out;
24
36
  }
37
+ function parseRepeatedFlag(argv, name) {
38
+ const values = [];
39
+ const flag = `--${name}`;
40
+ const flagEquals = `${flag}=`;
41
+ for (let i = 0; i < argv.length; i++) {
42
+ const arg = argv[i];
43
+ if (arg?.startsWith(flagEquals)) {
44
+ const value = arg.slice(flagEquals.length);
45
+ if (value.trim() === '')
46
+ return null;
47
+ values.push(value);
48
+ continue;
49
+ }
50
+ if (arg !== flag)
51
+ continue;
52
+ const value = argv[i + 1];
53
+ if (value === undefined || value.startsWith('--') || value.trim() === '')
54
+ return null;
55
+ values.push(value);
56
+ i++;
57
+ }
58
+ return values;
59
+ }
60
+ function makeCycleValidationHook(validationCmds, fallback, runSandboxedValidation = verify.runSandboxedValidation) {
61
+ if (validationCmds.length === 0)
62
+ return fallback;
63
+ let warnedNoIsolation = false;
64
+ return (task) => {
65
+ const fallbackHook = fallback?.(task);
66
+ return async (mutation, decision, cwd) => {
67
+ const fallbackResult = fallbackHook ? await fallbackHook(mutation, decision, cwd) : null;
68
+ if (fallbackResult && !fallbackResult.passed)
69
+ return fallbackResult;
70
+ const result = await runSandboxedValidation(task.validationCmds ?? validationCmds, cwd);
71
+ if (!result.isolated && !warnedNoIsolation) {
72
+ warnedNoIsolation = true;
73
+ process.stdout.write(' warning: validation runs WITHOUT network/FS isolation on this platform; non-namespace hardening still applies.\n');
74
+ }
75
+ return { passed: result.passed, score: result.score };
76
+ };
77
+ };
78
+ }
25
79
  function parsePositiveInt(value, fallback) {
26
80
  if (value === undefined || value.trim() === '')
27
81
  return fallback;
28
82
  const n = Number(value);
29
83
  return Number.isInteger(n) && n > 0 ? n : fallback;
30
84
  }
85
+ function parseRequiredPositiveIntFlag(flags, name) {
86
+ if (!(name in flags))
87
+ return undefined;
88
+ const value = flags[name] ?? '';
89
+ if (value.trim() === '')
90
+ return null;
91
+ const n = Number(value);
92
+ return Number.isInteger(n) && n > 0 ? n : null;
93
+ }
31
94
  function parseRunner(value) {
32
95
  return value === 'codex' || value === 'cursor' ? value : 'claude';
33
96
  }
@@ -151,7 +214,7 @@ function fallbackSignalTokens(sigs) {
151
214
  return [...out];
152
215
  }
153
216
  function materialSignals(material) {
154
- const sources = parseRuntimeSessionSources(material.sourcePath);
217
+ const sources = runtimeSessionSourcesForMaterial(material);
155
218
  const sigs = sources.flatMap((source) => signals.extractSignals(source.turns));
156
219
  const tokens = signalTokens(sigs);
157
220
  return {
@@ -250,6 +313,7 @@ async function processMaterial(material, opts, deps) {
250
313
  target: opts.target ?? '.',
251
314
  expectedEffect: opts.expectedEffect ?? 'evolve from consumed session material',
252
315
  signals: extracted.signals,
316
+ ...(opts.validationCmds ? { validationCmds: opts.validationCmds } : {}),
253
317
  };
254
318
  const safety = {
255
319
  allowedRoots: [repo],
@@ -263,6 +327,7 @@ async function processMaterial(material, opts, deps) {
263
327
  provenance: deps.provenance,
264
328
  review: deps.review,
265
329
  personality: deps.personality,
330
+ ...(opts.validate ? { validate: opts.validate } : {}),
266
331
  ...(opts.agent ? { agent: opts.agent } : {}),
267
332
  ...(opts.git ? { git: opts.git } : {}),
268
333
  }, task, safety);
@@ -295,6 +360,89 @@ export async function runMaterialCycleConsumer(opts, injectedDeps = {}) {
295
360
  }
296
361
  return { claimed: claimed.length, processed: items.length, items };
297
362
  }
363
+ function defaultSleep(ms) {
364
+ return new Promise((resolveSleep) => setTimeout(resolveSleep, ms));
365
+ }
366
+ function positiveNumber(value, fallback) {
367
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : fallback;
368
+ }
369
+ function hasCycleWatchProgress(result, cursorBefore, cursorAfter) {
370
+ if (cursorAfter > cursorBefore)
371
+ return true;
372
+ return result.items.some((item) => (item.action === 'cycle'
373
+ || item.action === 'observe'
374
+ || item.action === 'fail'
375
+ || item.status === 'already_terminal'));
376
+ }
377
+ function watchFailedItemCount(items) {
378
+ return items.filter((item) => item.action === 'fail' || item.status === 'refused' || item.status === 'failed').length;
379
+ }
380
+ export async function runMaterialCycleWatch(opts, injectedDeps = {}, hooks = {}) {
381
+ const deps = resolveMaterialCycleDeps(injectedDeps);
382
+ const sleep = injectedDeps.sleep ?? defaultSleep;
383
+ const idleBase = Math.floor(positiveNumber(opts.idleMs, DEFAULT_WATCH_IDLE_MS));
384
+ const idleMax = Math.floor(Math.max(idleBase, positiveNumber(opts.maxIdleMs, DEFAULT_WATCH_MAX_IDLE_MS)));
385
+ const backoff = Math.max(1, positiveNumber(opts.backoffMultiplier, DEFAULT_WATCH_BACKOFF));
386
+ const maxIdle = opts.maxIdle !== undefined && opts.maxIdle > 0 ? Math.floor(opts.maxIdle) : undefined;
387
+ const maxIterations = opts.maxIterations !== undefined && opts.maxIterations > 0 ? Math.floor(opts.maxIterations) : undefined;
388
+ let nextDelayMs = idleBase;
389
+ let iterations = 0;
390
+ let idleIterations = 0;
391
+ let totalClaimed = 0;
392
+ let totalProcessed = 0;
393
+ let totalFailedItems = 0;
394
+ for (;;) {
395
+ iterations += 1;
396
+ const cursorBefore = deps.consumer.position(CYCLE_GROUP);
397
+ const result = await runMaterialCycleConsumer(opts, deps);
398
+ const cursorAfter = deps.consumer.position(CYCLE_GROUP);
399
+ const progress = hasCycleWatchProgress(result, cursorBefore, cursorAfter);
400
+ const idle = !progress;
401
+ const iteration = {
402
+ ok: true,
403
+ group: 'cycle.watch',
404
+ iteration: iterations,
405
+ claimed: result.claimed,
406
+ processed: result.processed,
407
+ cursor: cursorAfter,
408
+ idle,
409
+ nextDelayMs: idle ? nextDelayMs : 0,
410
+ items: result.items,
411
+ };
412
+ totalClaimed += result.claimed;
413
+ totalProcessed += result.processed;
414
+ totalFailedItems += watchFailedItemCount(result.items);
415
+ hooks.onIteration?.(iteration);
416
+ if (idle)
417
+ idleIterations += 1;
418
+ else {
419
+ idleIterations = 0;
420
+ nextDelayMs = idleBase;
421
+ }
422
+ const stopped = maxIterations !== undefined && iterations >= maxIterations
423
+ ? 'max_iterations'
424
+ : maxIdle !== undefined && idleIterations >= maxIdle
425
+ ? 'max_idle'
426
+ : null;
427
+ if (stopped) {
428
+ return {
429
+ ok: true,
430
+ group: 'cycle.watch',
431
+ iterations,
432
+ claimed: totalClaimed,
433
+ processed: totalProcessed,
434
+ idleIterations,
435
+ failedItems: totalFailedItems,
436
+ cursor: deps.consumer.position(CYCLE_GROUP),
437
+ stopped,
438
+ };
439
+ }
440
+ if (idle) {
441
+ await sleep(nextDelayMs);
442
+ nextDelayMs = Math.min(idleMax, Math.max(idleBase, Math.ceil(nextDelayMs * backoff)));
443
+ }
444
+ }
445
+ }
298
446
  async function recoverMaterialCycleAudit(material, deps) {
299
447
  const cycleId = cycleIdForMaterial(material.materialId);
300
448
  const lockPath = cycleLockPathForMaterial(deps.materialStore.path, material.materialId);
@@ -394,12 +542,17 @@ function summarizeCycleConsumer(injectedDeps = {}) {
394
542
  recoverLimit = index - cursor + 1;
395
543
  }
396
544
  if (index >= cursor && next.length < 5 && status !== 'consumed' && status !== 'observed') {
545
+ const sourceAvailable = materialSourceAvailable(material);
546
+ const hasSnapshot = materialHasRuntimeSessionSnapshot(material);
397
547
  next.push({
398
548
  materialId: material.materialId,
399
549
  sourceKind: material.sourceKind,
400
550
  kind: material.kind,
401
551
  capturedAt: material.capturedAt,
402
552
  status,
553
+ sourceAvailable,
554
+ hasSnapshot,
555
+ recoverable: material.sourceKind === 'runtime_session' && (sourceAvailable || hasSnapshot),
403
556
  });
404
557
  }
405
558
  });
@@ -462,6 +615,82 @@ function printRecoverResult(result) {
462
615
  process.stdout.write(` material=${item.materialId} action=${item.action} status=${item.status}${cycle}${reason}\n`);
463
616
  }
464
617
  }
618
+ function printWatchIteration(iteration) {
619
+ process.stdout.write(`cycle watch: iteration=${iteration.iteration} claimed=${iteration.claimed} processed=${iteration.processed} cursor=${iteration.cursor} idle=${iteration.idle} nextDelayMs=${iteration.nextDelayMs}\n`);
620
+ for (const item of iteration.items) {
621
+ const cycle = item.cycleId ? ` cycle=${item.cycleId}` : '';
622
+ const reason = item.reason ? ' reason=details-redacted' : '';
623
+ process.stdout.write(` material=${item.materialId} action=${item.action} status=${item.status}${cycle}${reason}\n`);
624
+ }
625
+ }
626
+ function printWatchResult(result) {
627
+ process.stdout.write(`cycle watch stopped: reason=${result.stopped} iterations=${result.iterations} claimed=${result.claimed} processed=${result.processed} idleIterations=${result.idleIterations} failedItems=${result.failedItems} cursor=${result.cursor}\n`);
628
+ }
629
+ function redactedCycleItem(item) {
630
+ return item.reason ? { ...item, reason: 'details-redacted' } : item;
631
+ }
632
+ function redactedWatchIteration(iteration) {
633
+ return { ...iteration, items: iteration.items.map(redactedCycleItem) };
634
+ }
635
+ function prepareWatchStateFile(path) {
636
+ const trimmed = path?.trim();
637
+ if (!trimmed)
638
+ return null;
639
+ try {
640
+ const stat = lstatSync(trimmed);
641
+ if (!stat.isFile() || stat.isSymbolicLink())
642
+ return null;
643
+ accessSync(trimmed, constants.W_OK);
644
+ }
645
+ catch (error) {
646
+ if (error.code !== 'ENOENT')
647
+ return null;
648
+ }
649
+ try {
650
+ mkdirSync(dirname(trimmed), { recursive: true, mode: 0o700 });
651
+ return probeWatchStateFile(trimmed) ? trimmed : null;
652
+ }
653
+ catch {
654
+ return null;
655
+ }
656
+ }
657
+ function writeWatchStateFile(path, state) {
658
+ const tmp = join(dirname(path), `.${basename(path)}.${process.pid}.tmp`);
659
+ writeFileSync(tmp, `${JSON.stringify(state)}\n`, { encoding: 'utf8', mode: 0o600 });
660
+ renameSync(tmp, path);
661
+ }
662
+ function probeWatchStateFile(path) {
663
+ const dir = dirname(path);
664
+ const base = basename(path);
665
+ const probe = join(dir, `.${base}.${process.pid}.probe`);
666
+ const renamed = `${probe}.renamed`;
667
+ try {
668
+ writeFileSync(probe, '', { encoding: 'utf8', mode: 0o600 });
669
+ renameSync(probe, renamed);
670
+ unlinkSync(renamed);
671
+ return true;
672
+ }
673
+ catch {
674
+ try {
675
+ unlinkSync(probe);
676
+ }
677
+ catch { /* best effort */ }
678
+ try {
679
+ unlinkSync(renamed);
680
+ }
681
+ catch { /* best effort */ }
682
+ return false;
683
+ }
684
+ }
685
+ function tryWriteWatchStateFile(path, state, writer = writeWatchStateFile) {
686
+ try {
687
+ writer(path, state);
688
+ return true;
689
+ }
690
+ catch {
691
+ return false;
692
+ }
693
+ }
465
694
  function hasFailedItem(item) {
466
695
  return item.action === 'fail'
467
696
  || item.status === 'refused'
@@ -501,18 +730,166 @@ export async function runCycleCommand(argv, injectedDeps = {}) {
501
730
  printRecoverResult(result);
502
731
  return 0;
503
732
  }
733
+ if (argv[0] === 'watch') {
734
+ const flags = parseFlags(argv.slice(1));
735
+ const validationCmds = parseRepeatedFlag(argv.slice(1), 'validation-cmd');
736
+ const repo = flags['repo'];
737
+ if (!repo) {
738
+ process.stderr.write(WATCH_USAGE);
739
+ return 1;
740
+ }
741
+ if (validationCmds === null) {
742
+ process.stderr.write(WATCH_USAGE);
743
+ return 1;
744
+ }
745
+ const validate = makeCycleValidationHook(validationCmds, injectedDeps.validate, injectedDeps.runSandboxedValidation);
746
+ const maxIdle = parseRequiredPositiveIntFlag(flags, 'max-idle');
747
+ const maxIterations = parseRequiredPositiveIntFlag(flags, 'max-iterations');
748
+ const timeoutMs = parseRequiredPositiveIntFlag(flags, 'timeout-ms');
749
+ if (maxIdle === null || maxIterations === null || timeoutMs === null) {
750
+ process.stderr.write(WATCH_USAGE);
751
+ return 1;
752
+ }
753
+ const stateFile = prepareWatchStateFile(flags['state-file']);
754
+ if ('state-file' in flags && !stateFile) {
755
+ process.stderr.write(WATCH_USAGE);
756
+ return 1;
757
+ }
758
+ const json = 'json' in flags;
759
+ let stateClaimed = 0;
760
+ let stateProcessed = 0;
761
+ let stateIdleIterations = 0;
762
+ let stateFailedItems = 0;
763
+ let lastIteration;
764
+ const writeState = injectedDeps.watchStateWriter ?? writeWatchStateFile;
765
+ let result;
766
+ try {
767
+ result = await runMaterialCycleWatch({
768
+ repo,
769
+ limit: parsePositiveInt(flags['limit'], DEFAULT_LIMIT),
770
+ target: flags['target'] || '.',
771
+ expectedEffect: flags['expected-effect'] || 'evolve from consumed session material',
772
+ runner: parseRunner(flags['runner']),
773
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
774
+ ...(validationCmds.length > 0 ? { validationCmds } : {}),
775
+ ...(validate ? { validate } : {}),
776
+ ...(injectedDeps.safety ? { safety: injectedDeps.safety } : {}),
777
+ ...(injectedDeps.agent ? { agent: injectedDeps.agent } : {}),
778
+ ...(injectedDeps.git ? { git: injectedDeps.git } : {}),
779
+ idleMs: parsePositiveInt(flags['idle-ms'], DEFAULT_WATCH_IDLE_MS),
780
+ maxIdleMs: parsePositiveInt(flags['max-idle-ms'], DEFAULT_WATCH_MAX_IDLE_MS),
781
+ ...(maxIdle !== undefined ? { maxIdle } : {}),
782
+ ...(maxIterations !== undefined ? { maxIterations } : {}),
783
+ }, injectedDeps, {
784
+ onIteration: (iteration) => {
785
+ const safeIteration = redactedWatchIteration(iteration);
786
+ if (json)
787
+ process.stdout.write(`${JSON.stringify(safeIteration)}\n`);
788
+ else
789
+ printWatchIteration(iteration);
790
+ stateClaimed += iteration.claimed;
791
+ stateProcessed += iteration.processed;
792
+ stateFailedItems += watchFailedItemCount(iteration.items);
793
+ stateIdleIterations = iteration.idle ? stateIdleIterations + 1 : 0;
794
+ lastIteration = safeIteration;
795
+ if (stateFile && !tryWriteWatchStateFile(stateFile, {
796
+ ok: true,
797
+ group: 'cycle.watch.state',
798
+ updatedAt: new Date().toISOString(),
799
+ running: true,
800
+ iteration: iteration.iteration,
801
+ cursor: iteration.cursor,
802
+ claimed: stateClaimed,
803
+ processed: stateProcessed,
804
+ idleIterations: stateIdleIterations,
805
+ failedItems: stateFailedItems,
806
+ lastIteration: safeIteration,
807
+ }, writeState)) {
808
+ throw new CycleWatchStateWriteError();
809
+ }
810
+ },
811
+ });
812
+ }
813
+ catch (error) {
814
+ if (!(error instanceof CycleWatchStateWriteError))
815
+ throw error;
816
+ if (stateFile) {
817
+ tryWriteWatchStateFile(stateFile, {
818
+ ok: true,
819
+ group: 'cycle.watch.state',
820
+ updatedAt: new Date().toISOString(),
821
+ running: false,
822
+ iteration: lastIteration?.iteration ?? 0,
823
+ cursor: lastIteration?.cursor ?? 0,
824
+ claimed: stateClaimed,
825
+ processed: stateProcessed,
826
+ idleIterations: stateIdleIterations,
827
+ failedItems: stateFailedItems,
828
+ ...(lastIteration ? { lastIteration } : {}),
829
+ stopped: 'state_write_failed',
830
+ }, writeState);
831
+ }
832
+ process.stderr.write('cycle watch failed: state_write_failed\n');
833
+ return 1;
834
+ }
835
+ const finalState = {
836
+ ok: true,
837
+ group: 'cycle.watch.state',
838
+ updatedAt: new Date().toISOString(),
839
+ running: false,
840
+ iteration: result.iterations,
841
+ cursor: result.cursor,
842
+ claimed: result.claimed,
843
+ processed: result.processed,
844
+ idleIterations: result.idleIterations,
845
+ failedItems: result.failedItems,
846
+ ...(lastIteration ? { lastIteration } : {}),
847
+ stopped: result.stopped,
848
+ };
849
+ if (stateFile && !tryWriteWatchStateFile(stateFile, finalState, writeState)) {
850
+ tryWriteWatchStateFile(stateFile, {
851
+ ...finalState,
852
+ updatedAt: new Date().toISOString(),
853
+ stopped: 'state_write_failed',
854
+ }, writeState);
855
+ process.stderr.write('cycle watch failed: state_write_failed\n');
856
+ return 1;
857
+ }
858
+ if (json)
859
+ process.stdout.write(`${JSON.stringify(result)}\n`);
860
+ else
861
+ printWatchResult(result);
862
+ return 0;
863
+ }
504
864
  const flags = parseFlags(argv);
865
+ const validationCmds = parseRepeatedFlag(argv, 'validation-cmd');
505
866
  const repo = flags['repo'];
506
867
  if (!repo) {
507
- process.stderr.write('usage: evolver cycle show <id> | evolver cycle status [--json] | evolver cycle recover [--limit N] [--json] | evolver cycle --repo <path> [--limit N] [--target <path>] [--expected-effect <text>] [--runner claude|codex|cursor]\n');
868
+ process.stderr.write(CYCLE_USAGE);
869
+ return 1;
870
+ }
871
+ if (validationCmds === null) {
872
+ process.stderr.write(CYCLE_USAGE);
873
+ return 1;
874
+ }
875
+ const timeoutMs = parseRequiredPositiveIntFlag(flags, 'timeout-ms');
876
+ if (timeoutMs === null) {
877
+ process.stderr.write(CYCLE_USAGE);
508
878
  return 1;
509
879
  }
880
+ const validate = makeCycleValidationHook(validationCmds, injectedDeps.validate, injectedDeps.runSandboxedValidation);
510
881
  const result = await runMaterialCycleConsumer({
511
882
  repo,
512
883
  limit: parsePositiveInt(flags['limit'], DEFAULT_LIMIT),
513
884
  target: flags['target'] || '.',
514
885
  expectedEffect: flags['expected-effect'] || 'evolve from consumed session material',
515
886
  runner: parseRunner(flags['runner']),
887
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
888
+ ...(validationCmds.length > 0 ? { validationCmds } : {}),
889
+ ...(validate ? { validate } : {}),
890
+ ...(injectedDeps.safety ? { safety: injectedDeps.safety } : {}),
891
+ ...(injectedDeps.agent ? { agent: injectedDeps.agent } : {}),
892
+ ...(injectedDeps.git ? { git: injectedDeps.git } : {}),
516
893
  }, injectedDeps);
517
894
  printResult(result);
518
895
  return materialCycleExitCode(result);
@@ -0,0 +1,21 @@
1
+ export interface DashboardServer {
2
+ readonly token: string;
3
+ readonly launchTicket: string;
4
+ listen(port?: number): Promise<number>;
5
+ close(): Promise<void>;
6
+ }
7
+ export interface DashboardDeps {
8
+ createServer?: () => DashboardServer;
9
+ openUrl?: (url: string) => Promise<boolean>;
10
+ waitForShutdown?: () => Promise<void>;
11
+ stdout?: (text: string) => void;
12
+ stderr?: (text: string) => void;
13
+ }
14
+ export interface DashboardCommandOptions {
15
+ eaddrinusePortAttempts?: number;
16
+ }
17
+ export declare function dashboardOpenCommand(url: string, platform?: NodeJS.Platform): {
18
+ command: string;
19
+ args: string[];
20
+ };
21
+ export declare function runDashboardCommand(argv: readonly string[], deps?: DashboardDeps, options?: DashboardCommandOptions): Promise<number>;
@@ -0,0 +1,173 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { assetstore, events, ops } from '@evomap/evolver-core';
3
+ import { loadPriceTable } from '@evomap/evolver-adapter-public';
4
+ import { WebUIServer } from '@evomap/evolver-webui';
5
+ const USAGE = 'usage: evolver dashboard [--port N] [--no-open]\n';
6
+ function parsePort(raw) {
7
+ if (!/^\d+$/.test(raw))
8
+ return null;
9
+ const port = Number(raw);
10
+ return Number.isSafeInteger(port) && port >= 0 && port <= 65_535 ? port : null;
11
+ }
12
+ function parseDashboardOptions(argv) {
13
+ const options = { help: false, noOpen: false, port: 0 };
14
+ for (let i = 0; i < argv.length; i += 1) {
15
+ const arg = argv[i] ?? '';
16
+ if (arg === '--help' || arg === '-h') {
17
+ options.help = true;
18
+ continue;
19
+ }
20
+ if (arg === '--no-open') {
21
+ options.noOpen = true;
22
+ continue;
23
+ }
24
+ if (arg === '--port') {
25
+ const raw = argv[i + 1];
26
+ if (raw === undefined || raw.startsWith('--'))
27
+ return { ok: false, error: 'missing_port' };
28
+ const port = parsePort(raw);
29
+ if (port === null)
30
+ return { ok: false, error: 'invalid_port' };
31
+ options.port = port;
32
+ i += 1;
33
+ continue;
34
+ }
35
+ if (arg.startsWith('--port=')) {
36
+ const port = parsePort(arg.slice('--port='.length));
37
+ if (port === null)
38
+ return { ok: false, error: 'invalid_port' };
39
+ options.port = port;
40
+ continue;
41
+ }
42
+ return { ok: false, error: 'unknown_argument' };
43
+ }
44
+ return { ok: true, options };
45
+ }
46
+ function createDashboardServer() {
47
+ const eventsPath = events.rootEventsPath();
48
+ const tracesDir = events.tracesDir();
49
+ const store = new assetstore.LocalJsonlProvider(events.assetsDir());
50
+ const prices = loadPriceTable();
51
+ return new WebUIServer({
52
+ eventsPath,
53
+ store,
54
+ valueSummary: (window, eventSnapshot) => ops.loadValueSummary({
55
+ traces: ops.readTraceRecords(tracesDir),
56
+ events: eventSnapshot,
57
+ prices,
58
+ }, window),
59
+ retentionReport: () => events.buildRetentionReport(),
60
+ });
61
+ }
62
+ export function dashboardOpenCommand(url, platform = process.platform) {
63
+ if (platform === 'win32')
64
+ return { command: 'rundll32.exe', args: ['url.dll,FileProtocolHandler', url] };
65
+ if (platform === 'darwin')
66
+ return { command: 'open', args: [url] };
67
+ return { command: 'xdg-open', args: [url] };
68
+ }
69
+ async function openDashboardUrl(url) {
70
+ const command = dashboardOpenCommand(url);
71
+ return new Promise((resolve) => {
72
+ const child = spawn(command.command, command.args, {
73
+ detached: true,
74
+ shell: false,
75
+ stdio: 'ignore',
76
+ windowsHide: true,
77
+ });
78
+ child.once('error', () => resolve(false));
79
+ child.once('spawn', () => {
80
+ child.unref();
81
+ resolve(true);
82
+ });
83
+ });
84
+ }
85
+ function waitForShutdownSignal() {
86
+ return new Promise((resolve) => {
87
+ const finish = () => {
88
+ process.removeListener('SIGINT', finish);
89
+ process.removeListener('SIGTERM', finish);
90
+ resolve();
91
+ };
92
+ process.once('SIGINT', finish);
93
+ process.once('SIGTERM', finish);
94
+ });
95
+ }
96
+ function isAddressInUse(error) {
97
+ return typeof error === 'object'
98
+ && error !== null
99
+ && 'code' in error
100
+ && error.code === 'EADDRINUSE';
101
+ }
102
+ async function listenWithPortFallback(server, requestedPort, maxAttempts) {
103
+ const attempts = requestedPort === 0
104
+ ? 1
105
+ : Math.min(Math.max(1, maxAttempts), 65_536 - requestedPort);
106
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
107
+ try {
108
+ return await server.listen(requestedPort + attempt);
109
+ }
110
+ catch (error) {
111
+ if (!isAddressInUse(error) || attempt === attempts - 1)
112
+ throw error;
113
+ }
114
+ }
115
+ throw new Error('dashboard_start_failed');
116
+ }
117
+ export async function runDashboardCommand(argv, deps = {}, options = {}) {
118
+ const stdout = deps.stdout ?? ((text) => { process.stdout.write(text); });
119
+ const stderr = deps.stderr ?? ((text) => { process.stderr.write(text); });
120
+ const parsed = parseDashboardOptions(argv);
121
+ if (!parsed.ok) {
122
+ stderr(`dashboard: ${parsed.error}\n${USAGE}`);
123
+ return 2;
124
+ }
125
+ if (parsed.options.help) {
126
+ stdout(USAGE);
127
+ return 0;
128
+ }
129
+ const createServer = deps.createServer ?? createDashboardServer;
130
+ const openUrl = deps.openUrl ?? openDashboardUrl;
131
+ const waitForShutdown = deps.waitForShutdown ?? waitForShutdownSignal;
132
+ let server;
133
+ try {
134
+ server = createServer();
135
+ }
136
+ catch {
137
+ stderr('dashboard: dashboard_start_failed\n');
138
+ return 1;
139
+ }
140
+ let listening = false;
141
+ try {
142
+ const port = await listenWithPortFallback(server, parsed.options.port, options.eaddrinusePortAttempts ?? 1);
143
+ listening = true;
144
+ const baseUrl = `http://127.0.0.1:${port}/`;
145
+ const launchUrl = `${baseUrl}launch?ticket=${encodeURIComponent(server.launchTicket)}`;
146
+ if (parsed.options.noOpen) {
147
+ stdout(`dashboard: ${launchUrl}\n`);
148
+ }
149
+ else if (await openUrl(launchUrl)) {
150
+ stdout(`dashboard: ${baseUrl}\n`);
151
+ }
152
+ else {
153
+ stderr('dashboard: browser_open_failed\n');
154
+ stdout(`dashboard: ${launchUrl}\n`);
155
+ }
156
+ await waitForShutdown();
157
+ return 0;
158
+ }
159
+ catch {
160
+ stderr(`dashboard: ${listening ? 'dashboard_runtime_failed' : 'dashboard_start_failed'}\n`);
161
+ return 1;
162
+ }
163
+ finally {
164
+ if (listening) {
165
+ try {
166
+ await server.close();
167
+ }
168
+ catch {
169
+ // The process is already shutting down; avoid replacing the command result with a close race.
170
+ }
171
+ }
172
+ }
173
+ }
@@ -6,5 +6,6 @@ export declare const ASYNC_COMMANDS: Readonly<Record<string, CommandHandler>>;
6
6
  export declare const SYNC_COMMANDS: readonly ["status", "cycles", "trigger", "value", "narrative", "retention", "gene-value", "replay", "rebuild-views", "reset-local-secret"];
7
7
  /** Every top-level verb `evolver` resolves to (async-dispatched ∪ runCli core). */
8
8
  export declare const ALL_COMMANDS: ReadonlySet<string>;
9
+ export declare function v1TopLevelRunArgs(argv: readonly string[]): readonly string[] | undefined;
9
10
  /** Run a top-level argv against the registry: async handler if present, else the synchronous runCli core. */
10
11
  export declare function dispatch(argv: readonly string[]): Promise<number> | number;