@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
@@ -1,10 +1,24 @@
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';
7
+ import { RUNTIME_CAPABILITY_MATRIX, runtimeCapabilities } from './runtimeCapabilities.js';
8
+ import { LocalMemoryGraph, resolveLocalMemoryUserIdentity } from './localMemoryGraph.js';
6
9
  const CYCLE_GROUP = 'cycle';
7
10
  const DEFAULT_LIMIT = 5;
11
+ const DEFAULT_WATCH_IDLE_MS = 1000;
12
+ const DEFAULT_WATCH_MAX_IDLE_MS = 30_000;
13
+ const DEFAULT_WATCH_BACKOFF = 2;
14
+ const CYCLE_USAGE = 'usage: evolver cycle capabilities [--json] | 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|gemini] [--validation-cmd <cmd>] [--timeout-ms N]\n';
15
+ 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|gemini] [--validation-cmd <cmd>] [--timeout-ms N] [--json]\n';
16
+ class CycleWatchStateWriteError extends Error {
17
+ constructor() {
18
+ super('cycle watch state file write failed');
19
+ this.name = 'CycleWatchStateWriteError';
20
+ }
21
+ }
8
22
  function parseFlags(argv) {
9
23
  const out = {};
10
24
  for (let i = 0; i < argv.length; i++) {
@@ -22,14 +36,118 @@ function parseFlags(argv) {
22
36
  }
23
37
  return out;
24
38
  }
39
+ function parseRepeatedFlag(argv, name) {
40
+ const values = [];
41
+ const flag = `--${name}`;
42
+ const flagEquals = `${flag}=`;
43
+ for (let i = 0; i < argv.length; i++) {
44
+ const arg = argv[i];
45
+ if (arg?.startsWith(flagEquals)) {
46
+ const value = arg.slice(flagEquals.length);
47
+ if (value.trim() === '')
48
+ return null;
49
+ values.push(value);
50
+ continue;
51
+ }
52
+ if (arg !== flag)
53
+ continue;
54
+ const value = argv[i + 1];
55
+ if (value === undefined || value.startsWith('--') || value.trim() === '')
56
+ return null;
57
+ values.push(value);
58
+ i++;
59
+ }
60
+ return values;
61
+ }
62
+ function makeCycleValidationHook(validationCmds, fallback, runSandboxedValidation = verify.runSandboxedValidation) {
63
+ if (validationCmds.length === 0)
64
+ return fallback;
65
+ let warnedNoIsolation = false;
66
+ return (task) => {
67
+ const fallbackHook = fallback?.(task);
68
+ return async (mutation, decision, cwd) => {
69
+ const fallbackResult = fallbackHook ? await fallbackHook(mutation, decision, cwd) : null;
70
+ if (fallbackResult && !fallbackResult.passed)
71
+ return fallbackResult;
72
+ const result = await runSandboxedValidation(task.validationCmds ?? validationCmds, cwd);
73
+ if (!result.isolated && !warnedNoIsolation) {
74
+ warnedNoIsolation = true;
75
+ process.stdout.write(' warning: validation runs WITHOUT network/FS isolation on this platform; non-namespace hardening still applies.\n');
76
+ }
77
+ return { passed: result.passed, score: result.score };
78
+ };
79
+ };
80
+ }
25
81
  function parsePositiveInt(value, fallback) {
26
82
  if (value === undefined || value.trim() === '')
27
83
  return fallback;
28
84
  const n = Number(value);
29
85
  return Number.isInteger(n) && n > 0 ? n : fallback;
30
86
  }
87
+ function parseRequiredPositiveIntFlag(flags, name) {
88
+ if (!(name in flags))
89
+ return undefined;
90
+ const value = flags[name] ?? '';
91
+ if (value.trim() === '')
92
+ return null;
93
+ const n = Number(value);
94
+ return Number.isInteger(n) && n > 0 ? n : null;
95
+ }
31
96
  function parseRunner(value) {
32
- return value === 'codex' || value === 'cursor' ? value : 'claude';
97
+ if (value === undefined || value === 'claude')
98
+ return { ok: true, runner: 'claude' };
99
+ if (value.trim() === '')
100
+ return { ok: false, error: 'runner value is required (supported: claude, codex, cursor, gemini)' };
101
+ if (value === 'codex' || value === 'cursor' || value === 'gemini')
102
+ return { ok: true, runner: value };
103
+ if (value === 'antigravity' || value === 'kimi' || value === 'kiro' || value === 'opencode') {
104
+ const capability = RUNTIME_CAPABILITY_MATRIX[value].execute;
105
+ return { ok: false, error: `runner '${value}' execute capability is ${capability.status}: ${capability.evidence}` };
106
+ }
107
+ return { ok: false, error: `unknown runner '${value}' (supported: claude, codex, cursor, gemini)` };
108
+ }
109
+ function resolveMaterialRunner(material, requestedRunner) {
110
+ const sourceAgent = material.sourceAgent;
111
+ let runner;
112
+ switch (sourceAgent) {
113
+ case 'claude-code':
114
+ runner = 'claude';
115
+ break;
116
+ case 'codex':
117
+ case 'cursor':
118
+ case 'gemini':
119
+ runner = sourceAgent;
120
+ break;
121
+ case 'antigravity':
122
+ case 'kimi': {
123
+ const capability = RUNTIME_CAPABILITY_MATRIX[sourceAgent].execute;
124
+ return {
125
+ ok: false,
126
+ error: `sourceAgent '${sourceAgent}' execute capability is ${capability.status}: ${capability.evidence}`,
127
+ };
128
+ }
129
+ case 'kiro':
130
+ case 'opencode':
131
+ case 'generic-chat':
132
+ return { ok: false, error: `sourceAgent '${sourceAgent}' has no supported cycle runner` };
133
+ default:
134
+ return { ok: false, error: 'runtime_session material has no supported sourceAgent' };
135
+ }
136
+ if (requestedRunner !== undefined && requestedRunner !== runner) {
137
+ return {
138
+ ok: false,
139
+ error: `explicit runner '${requestedRunner}' does not match sourceAgent '${sourceAgent}' runner '${runner}'`,
140
+ };
141
+ }
142
+ return { ok: true, runner };
143
+ }
144
+ function printRuntimeCapabilities() {
145
+ for (const entry of runtimeCapabilities()) {
146
+ const values = ['ingest', 'inject', 'execute', 'verify', 'resume']
147
+ .map((capability) => `${capability}=${entry[capability].status}`)
148
+ .join(' ');
149
+ process.stdout.write(`${entry.runtime}: ${values}\n`);
150
+ }
33
151
  }
34
152
  function resolveMaterialCycleDeps(deps = {}) {
35
153
  const materialStore = deps.materialStore ?? new materialNs.MaterialStore({ path: events.materialStorePath() });
@@ -43,6 +161,11 @@ function resolveMaterialCycleDeps(deps = {}) {
43
161
  const review = deps.review ?? new assetstore.ReviewLedger(assetDir);
44
162
  const ingestor = deps.ingestor ?? new events.Ingestor({ path: events.rootEventsPath() });
45
163
  const personalityStore = deps.personality ?? new personality.PersonalityStore();
164
+ const memoryGraphDir = join(events.evomapHome(), 'evolution');
165
+ const memoryGraph = deps.memoryGraph ?? new LocalMemoryGraph({
166
+ dir: memoryGraphDir,
167
+ ...resolveLocalMemoryUserIdentity(memoryGraphDir),
168
+ });
46
169
  const engine = deps.engine ?? new algo.CycleEngine({
47
170
  ingestor,
48
171
  selection: algo.makeGeneSelectionPoint(),
@@ -50,7 +173,7 @@ function resolveMaterialCycleDeps(deps = {}) {
50
173
  now: () => Date.now(),
51
174
  personality: personalityStore,
52
175
  });
53
- return { materialStore, consumer, store, provenance, review, ingestor, engine, personality: personalityStore };
176
+ return { materialStore, consumer, store, provenance, review, ingestor, engine, personality: personalityStore, memoryGraph };
54
177
  }
55
178
  export function cycleIdForMaterial(materialId) {
56
179
  return `autoexec-material-${materialId}`;
@@ -151,7 +274,7 @@ function fallbackSignalTokens(sigs) {
151
274
  return [...out];
152
275
  }
153
276
  function materialSignals(material) {
154
- const sources = parseRuntimeSessionSources(material.sourcePath);
277
+ const sources = runtimeSessionSourcesForMaterial(material);
155
278
  const sigs = sources.flatMap((source) => signals.extractSignals(source.turns));
156
279
  const tokens = signalTokens(sigs);
157
280
  return {
@@ -225,6 +348,19 @@ async function processMaterial(material, opts, deps) {
225
348
  ackOne(deps.consumer, material);
226
349
  return item;
227
350
  }
351
+ const runner = resolveMaterialRunner(material, opts.runner);
352
+ if (!runner.ok) {
353
+ const item = {
354
+ materialId: material.materialId,
355
+ action: 'fail',
356
+ status: 'refused',
357
+ cycleId,
358
+ reason: runner.error,
359
+ };
360
+ await emitConsumed(deps.ingestor, material, item);
361
+ ackOne(deps.consumer, material);
362
+ return item;
363
+ }
228
364
  let extracted;
229
365
  try {
230
366
  extracted = materialSignals(material);
@@ -250,12 +386,14 @@ async function processMaterial(material, opts, deps) {
250
386
  target: opts.target ?? '.',
251
387
  expectedEffect: opts.expectedEffect ?? 'evolve from consumed session material',
252
388
  signals: extracted.signals,
389
+ ...(opts.validationCmds ? { validationCmds: opts.validationCmds } : {}),
253
390
  };
254
391
  const safety = {
255
392
  allowedRoots: [repo],
256
- runner: opts.runner ?? 'claude',
257
393
  ...(opts.timeoutMs !== undefined ? { timeoutMs: opts.timeoutMs } : {}),
258
394
  ...opts.safety,
395
+ runner: runner.runner,
396
+ ...(opts.signal ? { signal: opts.signal } : {}),
259
397
  };
260
398
  const verdict = await exec.runAutoExecTask({
261
399
  engine: deps.engine,
@@ -263,6 +401,8 @@ async function processMaterial(material, opts, deps) {
263
401
  provenance: deps.provenance,
264
402
  review: deps.review,
265
403
  personality: deps.personality,
404
+ memoryGraph: deps.memoryGraph,
405
+ ...(opts.validate ? { validate: opts.validate } : {}),
266
406
  ...(opts.agent ? { agent: opts.agent } : {}),
267
407
  ...(opts.git ? { git: opts.git } : {}),
268
408
  }, task, safety);
@@ -277,6 +417,7 @@ async function processMaterial(material, opts, deps) {
277
417
  finalStage: verdict.finalStage,
278
418
  signalCount: extracted.signals.length,
279
419
  signals: extracted.signals,
420
+ runner: runner.runner,
280
421
  });
281
422
  ackOne(deps.consumer, material);
282
423
  return item;
@@ -291,10 +432,142 @@ export async function runMaterialCycleConsumer(opts, injectedDeps = {}) {
291
432
  const claimed = deps.consumer.claim(CYCLE_GROUP, limit);
292
433
  const items = [];
293
434
  for (const material of claimed) {
435
+ if (opts.signal?.aborted)
436
+ break;
294
437
  items.push(await processMaterial(material, opts, deps));
295
438
  }
296
439
  return { claimed: claimed.length, processed: items.length, items };
297
440
  }
441
+ function defaultSleep(ms, signal) {
442
+ return new Promise((resolveSleep) => {
443
+ if (signal?.aborted) {
444
+ resolveSleep();
445
+ return;
446
+ }
447
+ const timer = setTimeout(finish, ms);
448
+ function finish() {
449
+ clearTimeout(timer);
450
+ signal?.removeEventListener('abort', finish);
451
+ resolveSleep();
452
+ }
453
+ signal?.addEventListener('abort', finish, { once: true });
454
+ });
455
+ }
456
+ function watchResult(deps, stopped, counters) {
457
+ return {
458
+ ok: true,
459
+ group: 'cycle.watch',
460
+ ...counters,
461
+ cursor: deps.consumer.position(CYCLE_GROUP),
462
+ stopped,
463
+ };
464
+ }
465
+ function positiveNumber(value, fallback) {
466
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : fallback;
467
+ }
468
+ function hasCycleWatchProgress(result, cursorBefore, cursorAfter) {
469
+ if (cursorAfter > cursorBefore)
470
+ return true;
471
+ return result.items.some((item) => (item.action === 'cycle'
472
+ || item.action === 'observe'
473
+ || item.action === 'fail'
474
+ || item.status === 'already_terminal'));
475
+ }
476
+ function watchFailedItemCount(items) {
477
+ return items.filter((item) => item.action === 'fail' || item.status === 'refused' || item.status === 'failed').length;
478
+ }
479
+ export async function runMaterialCycleWatch(opts, injectedDeps = {}, hooks = {}) {
480
+ const deps = resolveMaterialCycleDeps(injectedDeps);
481
+ const sleep = injectedDeps.sleep ?? defaultSleep;
482
+ const idleBase = Math.floor(positiveNumber(opts.idleMs, DEFAULT_WATCH_IDLE_MS));
483
+ const idleMax = Math.floor(Math.max(idleBase, positiveNumber(opts.maxIdleMs, DEFAULT_WATCH_MAX_IDLE_MS)));
484
+ const backoff = Math.max(1, positiveNumber(opts.backoffMultiplier, DEFAULT_WATCH_BACKOFF));
485
+ const maxIdle = opts.maxIdle !== undefined && opts.maxIdle > 0 ? Math.floor(opts.maxIdle) : undefined;
486
+ const maxIterations = opts.maxIterations !== undefined && opts.maxIterations > 0 ? Math.floor(opts.maxIterations) : undefined;
487
+ let nextDelayMs = idleBase;
488
+ let iterations = 0;
489
+ let idleIterations = 0;
490
+ let totalClaimed = 0;
491
+ let totalProcessed = 0;
492
+ let totalFailedItems = 0;
493
+ for (;;) {
494
+ if (opts.signal?.aborted) {
495
+ return watchResult(deps, 'cancelled', {
496
+ iterations,
497
+ claimed: totalClaimed,
498
+ processed: totalProcessed,
499
+ idleIterations,
500
+ failedItems: totalFailedItems,
501
+ });
502
+ }
503
+ iterations += 1;
504
+ const cursorBefore = deps.consumer.position(CYCLE_GROUP);
505
+ const result = await runMaterialCycleConsumer(opts, deps);
506
+ const cursorAfter = deps.consumer.position(CYCLE_GROUP);
507
+ const progress = hasCycleWatchProgress(result, cursorBefore, cursorAfter);
508
+ const idle = !progress;
509
+ const iteration = {
510
+ ok: true,
511
+ group: 'cycle.watch',
512
+ iteration: iterations,
513
+ claimed: result.claimed,
514
+ processed: result.processed,
515
+ cursor: cursorAfter,
516
+ idle,
517
+ nextDelayMs: idle ? nextDelayMs : 0,
518
+ items: result.items,
519
+ };
520
+ totalClaimed += result.claimed;
521
+ totalProcessed += result.processed;
522
+ totalFailedItems += watchFailedItemCount(result.items);
523
+ hooks.onIteration?.(iteration);
524
+ if (idle)
525
+ idleIterations += 1;
526
+ else {
527
+ idleIterations = 0;
528
+ nextDelayMs = idleBase;
529
+ }
530
+ const stopped = opts.signal?.aborted
531
+ ? 'cancelled'
532
+ : maxIterations !== undefined && iterations >= maxIterations
533
+ ? 'max_iterations'
534
+ : maxIdle !== undefined && idleIterations >= maxIdle
535
+ ? 'max_idle'
536
+ : null;
537
+ if (stopped) {
538
+ return watchResult(deps, stopped, {
539
+ iterations,
540
+ claimed: totalClaimed,
541
+ processed: totalProcessed,
542
+ idleIterations,
543
+ failedItems: totalFailedItems,
544
+ });
545
+ }
546
+ if (idle) {
547
+ await sleep(nextDelayMs, opts.signal);
548
+ nextDelayMs = Math.min(idleMax, Math.max(idleBase, Math.ceil(nextDelayMs * backoff)));
549
+ }
550
+ }
551
+ }
552
+ function createProcessCancellation() {
553
+ const controller = new AbortController();
554
+ let code = 1;
555
+ const interrupt = () => { code = 130; controller.abort(); };
556
+ const terminate = () => { code = 143; controller.abort(); };
557
+ process.once('SIGINT', interrupt);
558
+ process.once('SIGTERM', terminate);
559
+ return {
560
+ signal: controller.signal,
561
+ exitCode: () => code,
562
+ dispose: () => {
563
+ process.removeListener('SIGINT', interrupt);
564
+ process.removeListener('SIGTERM', terminate);
565
+ },
566
+ };
567
+ }
568
+ function combineSignals(primary, secondary) {
569
+ return secondary ? AbortSignal.any([primary, secondary]) : primary;
570
+ }
298
571
  async function recoverMaterialCycleAudit(material, deps) {
299
572
  const cycleId = cycleIdForMaterial(material.materialId);
300
573
  const lockPath = cycleLockPathForMaterial(deps.materialStore.path, material.materialId);
@@ -394,12 +667,17 @@ function summarizeCycleConsumer(injectedDeps = {}) {
394
667
  recoverLimit = index - cursor + 1;
395
668
  }
396
669
  if (index >= cursor && next.length < 5 && status !== 'consumed' && status !== 'observed') {
670
+ const sourceAvailable = materialSourceAvailable(material);
671
+ const hasSnapshot = materialHasRuntimeSessionSnapshot(material);
397
672
  next.push({
398
673
  materialId: material.materialId,
399
674
  sourceKind: material.sourceKind,
400
675
  kind: material.kind,
401
676
  capturedAt: material.capturedAt,
402
677
  status,
678
+ sourceAvailable,
679
+ hasSnapshot,
680
+ recoverable: material.sourceKind === 'runtime_session' && (sourceAvailable || hasSnapshot),
403
681
  });
404
682
  }
405
683
  });
@@ -462,6 +740,82 @@ function printRecoverResult(result) {
462
740
  process.stdout.write(` material=${item.materialId} action=${item.action} status=${item.status}${cycle}${reason}\n`);
463
741
  }
464
742
  }
743
+ function printWatchIteration(iteration) {
744
+ process.stdout.write(`cycle watch: iteration=${iteration.iteration} claimed=${iteration.claimed} processed=${iteration.processed} cursor=${iteration.cursor} idle=${iteration.idle} nextDelayMs=${iteration.nextDelayMs}\n`);
745
+ for (const item of iteration.items) {
746
+ const cycle = item.cycleId ? ` cycle=${item.cycleId}` : '';
747
+ const reason = item.reason ? ' reason=details-redacted' : '';
748
+ process.stdout.write(` material=${item.materialId} action=${item.action} status=${item.status}${cycle}${reason}\n`);
749
+ }
750
+ }
751
+ function printWatchResult(result) {
752
+ 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`);
753
+ }
754
+ function redactedCycleItem(item) {
755
+ return item.reason ? { ...item, reason: 'details-redacted' } : item;
756
+ }
757
+ function redactedWatchIteration(iteration) {
758
+ return { ...iteration, items: iteration.items.map(redactedCycleItem) };
759
+ }
760
+ function prepareWatchStateFile(path) {
761
+ const trimmed = path?.trim();
762
+ if (!trimmed)
763
+ return null;
764
+ try {
765
+ const stat = lstatSync(trimmed);
766
+ if (!stat.isFile() || stat.isSymbolicLink())
767
+ return null;
768
+ accessSync(trimmed, constants.W_OK);
769
+ }
770
+ catch (error) {
771
+ if (error.code !== 'ENOENT')
772
+ return null;
773
+ }
774
+ try {
775
+ mkdirSync(dirname(trimmed), { recursive: true, mode: 0o700 });
776
+ return probeWatchStateFile(trimmed) ? trimmed : null;
777
+ }
778
+ catch {
779
+ return null;
780
+ }
781
+ }
782
+ function writeWatchStateFile(path, state) {
783
+ const tmp = join(dirname(path), `.${basename(path)}.${process.pid}.tmp`);
784
+ writeFileSync(tmp, `${JSON.stringify(state)}\n`, { encoding: 'utf8', mode: 0o600 });
785
+ renameSync(tmp, path);
786
+ }
787
+ function probeWatchStateFile(path) {
788
+ const dir = dirname(path);
789
+ const base = basename(path);
790
+ const probe = join(dir, `.${base}.${process.pid}.probe`);
791
+ const renamed = `${probe}.renamed`;
792
+ try {
793
+ writeFileSync(probe, '', { encoding: 'utf8', mode: 0o600 });
794
+ renameSync(probe, renamed);
795
+ unlinkSync(renamed);
796
+ return true;
797
+ }
798
+ catch {
799
+ try {
800
+ unlinkSync(probe);
801
+ }
802
+ catch { /* best effort */ }
803
+ try {
804
+ unlinkSync(renamed);
805
+ }
806
+ catch { /* best effort */ }
807
+ return false;
808
+ }
809
+ }
810
+ function tryWriteWatchStateFile(path, state, writer = writeWatchStateFile) {
811
+ try {
812
+ writer(path, state);
813
+ return true;
814
+ }
815
+ catch {
816
+ return false;
817
+ }
818
+ }
465
819
  function hasFailedItem(item) {
466
820
  return item.action === 'fail'
467
821
  || item.status === 'refused'
@@ -472,6 +826,14 @@ function materialCycleExitCode(result) {
472
826
  return result.items.some(hasFailedItem) ? 1 : 0;
473
827
  }
474
828
  export async function runCycleCommand(argv, injectedDeps = {}) {
829
+ if (argv[0] === 'capabilities') {
830
+ const flags = parseFlags(argv.slice(1));
831
+ if ('json' in flags)
832
+ process.stdout.write(`${JSON.stringify(runtimeCapabilities())}\n`);
833
+ else
834
+ printRuntimeCapabilities();
835
+ return 0;
836
+ }
475
837
  if (argv[0] === 'show') {
476
838
  if (!argv[1]) {
477
839
  process.stderr.write('usage: evolver cycle show <id>\n');
@@ -501,19 +863,192 @@ export async function runCycleCommand(argv, injectedDeps = {}) {
501
863
  printRecoverResult(result);
502
864
  return 0;
503
865
  }
866
+ if (argv[0] === 'watch') {
867
+ const flags = parseFlags(argv.slice(1));
868
+ const runner = parseRunner(flags['runner']);
869
+ if (!runner.ok) {
870
+ process.stderr.write(`${runner.error}\n`);
871
+ return 1;
872
+ }
873
+ const validationCmds = parseRepeatedFlag(argv.slice(1), 'validation-cmd');
874
+ const repo = flags['repo'];
875
+ if (!repo) {
876
+ process.stderr.write(WATCH_USAGE);
877
+ return 1;
878
+ }
879
+ if (validationCmds === null) {
880
+ process.stderr.write(WATCH_USAGE);
881
+ return 1;
882
+ }
883
+ const validate = makeCycleValidationHook(validationCmds, injectedDeps.validate, injectedDeps.runSandboxedValidation);
884
+ const maxIdle = parseRequiredPositiveIntFlag(flags, 'max-idle');
885
+ const maxIterations = parseRequiredPositiveIntFlag(flags, 'max-iterations');
886
+ const timeoutMs = parseRequiredPositiveIntFlag(flags, 'timeout-ms');
887
+ if (maxIdle === null || maxIterations === null || timeoutMs === null) {
888
+ process.stderr.write(WATCH_USAGE);
889
+ return 1;
890
+ }
891
+ const stateFile = prepareWatchStateFile(flags['state-file']);
892
+ if ('state-file' in flags && !stateFile) {
893
+ process.stderr.write(WATCH_USAGE);
894
+ return 1;
895
+ }
896
+ const json = 'json' in flags;
897
+ let stateClaimed = 0;
898
+ let stateProcessed = 0;
899
+ let stateIdleIterations = 0;
900
+ let stateFailedItems = 0;
901
+ let lastIteration;
902
+ const writeState = injectedDeps.watchStateWriter ?? writeWatchStateFile;
903
+ const cancellation = createProcessCancellation();
904
+ const signal = combineSignals(cancellation.signal, injectedDeps.safety?.signal);
905
+ let result;
906
+ try {
907
+ result = await runMaterialCycleWatch({
908
+ repo,
909
+ limit: parsePositiveInt(flags['limit'], DEFAULT_LIMIT),
910
+ target: flags['target'] || '.',
911
+ expectedEffect: flags['expected-effect'] || 'evolve from consumed session material',
912
+ ...('runner' in flags ? { runner: runner.runner } : {}),
913
+ signal,
914
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
915
+ ...(validationCmds.length > 0 ? { validationCmds } : {}),
916
+ ...(validate ? { validate } : {}),
917
+ safety: { ...injectedDeps.safety, signal },
918
+ ...(injectedDeps.agent ? { agent: injectedDeps.agent } : {}),
919
+ ...(injectedDeps.git ? { git: injectedDeps.git } : {}),
920
+ idleMs: parsePositiveInt(flags['idle-ms'], DEFAULT_WATCH_IDLE_MS),
921
+ maxIdleMs: parsePositiveInt(flags['max-idle-ms'], DEFAULT_WATCH_MAX_IDLE_MS),
922
+ ...(maxIdle !== undefined ? { maxIdle } : {}),
923
+ ...(maxIterations !== undefined ? { maxIterations } : {}),
924
+ }, injectedDeps, {
925
+ onIteration: (iteration) => {
926
+ const safeIteration = redactedWatchIteration(iteration);
927
+ if (json)
928
+ process.stdout.write(`${JSON.stringify(safeIteration)}\n`);
929
+ else
930
+ printWatchIteration(iteration);
931
+ stateClaimed += iteration.claimed;
932
+ stateProcessed += iteration.processed;
933
+ stateFailedItems += watchFailedItemCount(iteration.items);
934
+ stateIdleIterations = iteration.idle ? stateIdleIterations + 1 : 0;
935
+ lastIteration = safeIteration;
936
+ if (stateFile && !tryWriteWatchStateFile(stateFile, {
937
+ ok: true,
938
+ group: 'cycle.watch.state',
939
+ updatedAt: new Date().toISOString(),
940
+ running: true,
941
+ iteration: iteration.iteration,
942
+ cursor: iteration.cursor,
943
+ claimed: stateClaimed,
944
+ processed: stateProcessed,
945
+ idleIterations: stateIdleIterations,
946
+ failedItems: stateFailedItems,
947
+ lastIteration: safeIteration,
948
+ }, writeState)) {
949
+ throw new CycleWatchStateWriteError();
950
+ }
951
+ },
952
+ });
953
+ }
954
+ catch (error) {
955
+ if (!(error instanceof CycleWatchStateWriteError))
956
+ throw error;
957
+ if (stateFile) {
958
+ tryWriteWatchStateFile(stateFile, {
959
+ ok: true,
960
+ group: 'cycle.watch.state',
961
+ updatedAt: new Date().toISOString(),
962
+ running: false,
963
+ iteration: lastIteration?.iteration ?? 0,
964
+ cursor: lastIteration?.cursor ?? 0,
965
+ claimed: stateClaimed,
966
+ processed: stateProcessed,
967
+ idleIterations: stateIdleIterations,
968
+ failedItems: stateFailedItems,
969
+ ...(lastIteration ? { lastIteration } : {}),
970
+ stopped: 'state_write_failed',
971
+ }, writeState);
972
+ }
973
+ process.stderr.write('cycle watch failed: state_write_failed\n');
974
+ return 1;
975
+ }
976
+ finally {
977
+ cancellation.dispose();
978
+ }
979
+ const finalState = {
980
+ ok: true,
981
+ group: 'cycle.watch.state',
982
+ updatedAt: new Date().toISOString(),
983
+ running: false,
984
+ iteration: result.iterations,
985
+ cursor: result.cursor,
986
+ claimed: result.claimed,
987
+ processed: result.processed,
988
+ idleIterations: result.idleIterations,
989
+ failedItems: result.failedItems,
990
+ ...(lastIteration ? { lastIteration } : {}),
991
+ stopped: result.stopped,
992
+ };
993
+ if (stateFile && !tryWriteWatchStateFile(stateFile, finalState, writeState)) {
994
+ tryWriteWatchStateFile(stateFile, {
995
+ ...finalState,
996
+ updatedAt: new Date().toISOString(),
997
+ stopped: 'state_write_failed',
998
+ }, writeState);
999
+ process.stderr.write('cycle watch failed: state_write_failed\n');
1000
+ return 1;
1001
+ }
1002
+ if (json)
1003
+ process.stdout.write(`${JSON.stringify(result)}\n`);
1004
+ else
1005
+ printWatchResult(result);
1006
+ return result.stopped === 'cancelled' ? cancellation.exitCode() : 0;
1007
+ }
504
1008
  const flags = parseFlags(argv);
1009
+ const runner = parseRunner(flags['runner']);
1010
+ if (!runner.ok) {
1011
+ process.stderr.write(`${runner.error}\n`);
1012
+ return 1;
1013
+ }
1014
+ const validationCmds = parseRepeatedFlag(argv, 'validation-cmd');
505
1015
  const repo = flags['repo'];
506
1016
  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');
1017
+ process.stderr.write(CYCLE_USAGE);
1018
+ return 1;
1019
+ }
1020
+ if (validationCmds === null) {
1021
+ process.stderr.write(CYCLE_USAGE);
508
1022
  return 1;
509
1023
  }
510
- const result = await runMaterialCycleConsumer({
511
- repo,
512
- limit: parsePositiveInt(flags['limit'], DEFAULT_LIMIT),
513
- target: flags['target'] || '.',
514
- expectedEffect: flags['expected-effect'] || 'evolve from consumed session material',
515
- runner: parseRunner(flags['runner']),
516
- }, injectedDeps);
1024
+ const timeoutMs = parseRequiredPositiveIntFlag(flags, 'timeout-ms');
1025
+ if (timeoutMs === null) {
1026
+ process.stderr.write(CYCLE_USAGE);
1027
+ return 1;
1028
+ }
1029
+ const validate = makeCycleValidationHook(validationCmds, injectedDeps.validate, injectedDeps.runSandboxedValidation);
1030
+ const cancellation = createProcessCancellation();
1031
+ const signal = combineSignals(cancellation.signal, injectedDeps.safety?.signal);
1032
+ let result;
1033
+ try {
1034
+ result = await runMaterialCycleConsumer({
1035
+ repo,
1036
+ limit: parsePositiveInt(flags['limit'], DEFAULT_LIMIT),
1037
+ target: flags['target'] || '.',
1038
+ expectedEffect: flags['expected-effect'] || 'evolve from consumed session material',
1039
+ ...('runner' in flags ? { runner: runner.runner } : {}),
1040
+ signal,
1041
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
1042
+ ...(validationCmds.length > 0 ? { validationCmds } : {}),
1043
+ ...(validate ? { validate } : {}),
1044
+ safety: { ...injectedDeps.safety, signal },
1045
+ ...(injectedDeps.agent ? { agent: injectedDeps.agent } : {}),
1046
+ ...(injectedDeps.git ? { git: injectedDeps.git } : {}),
1047
+ }, injectedDeps);
1048
+ }
1049
+ finally {
1050
+ cancellation.dispose();
1051
+ }
517
1052
  printResult(result);
518
- return materialCycleExitCode(result);
1053
+ return signal.aborted ? cancellation.exitCode() : materialCycleExitCode(result);
519
1054
  }