@evomap/evolver-cli 2.0.39 → 2.0.40

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.
@@ -59,6 +59,8 @@ export interface MaterialCycleOptions {
59
59
  target?: string;
60
60
  expectedEffect?: string;
61
61
  validationCmds?: readonly string[];
62
+ /** Independent operator acceptance for the opt-in LLM file executor. */
63
+ validationSpec?: verify.DeclarativeValidationSpec;
62
64
  validate?: exec.AutoExecDeps['validate'];
63
65
  runner?: RunnerName;
64
66
  /** Resume the single native Claude Code or Cursor session represented by each material. Default false. */
@@ -68,6 +70,7 @@ export interface MaterialCycleOptions {
68
70
  safety?: Partial<exec.AutonomousSafety>;
69
71
  agent?: exec.AgentRunner;
70
72
  git?: exec.GitRunner;
73
+ gitPatchWriter?: exec.GitPatchWriter;
71
74
  }
72
75
  export interface MaterialCycleWatchOptions extends MaterialCycleOptions {
73
76
  idleMs?: number;
@@ -91,6 +94,7 @@ export interface MaterialCycleDeps {
91
94
  runSandboxedValidation?: SandboxedValidationRunner;
92
95
  agent?: exec.AgentRunner;
93
96
  git?: exec.GitRunner;
97
+ gitPatchWriter?: exec.GitPatchWriter;
94
98
  safety?: Partial<exec.AutonomousSafety>;
95
99
  sleep?: SleepFn;
96
100
  watchStateWriter?: (path: string, state: MaterialCycleWatchState) => void;
@@ -6,6 +6,7 @@ import { MATERIAL_RUNTIME_SESSION_SNAPSHOT_SCHEMA, materialHasRuntimeSessionSnap
6
6
  import { runRequiredSandboxedValidation } from './requiredSandboxValidation.js';
7
7
  import { signalTokens } from './distillPrimitives.js';
8
8
  import { readEvents, showCycle } from './commands.js';
9
+ import { prepareLlmCycle, readCycleValidationSpec } from './llmCycle.js';
9
10
  import { RUNTIME_CAPABILITY_MATRIX, runtimeCapabilities } from './runtimeCapabilities.js';
10
11
  import { parseRuntimeSessionSources } from './runtimeSessionSource.js';
11
12
  import { LocalMemoryGraph, resolveLocalMemoryUserIdentity } from './localMemoryGraph.js';
@@ -17,8 +18,8 @@ const DEFAULT_LIMIT = 5;
17
18
  const DEFAULT_WATCH_IDLE_MS = 1000;
18
19
  const DEFAULT_WATCH_MAX_IDLE_MS = 30_000;
19
20
  const DEFAULT_WATCH_BACKOFF = 2;
20
- 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> [--resume] [--idle-ms N] [--max-idle N] [--state-file <path>] [--validation-cmd <cmd>] [--timeout-ms N] [--json] | evolver cycle --repo <path> [--resume] [--limit N] [--target <path>] [--expected-effect <text>] [--runner claude|codex|gemini] [--validation-cmd <cmd>] [--timeout-ms N]\n';
21
- const WATCH_USAGE = 'usage: evolver cycle watch --repo <path> [--resume] [--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|gemini] [--validation-cmd <cmd>] [--timeout-ms N] [--json]\n';
21
+ 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> [--resume] [--idle-ms N] [--max-idle N] [--state-file <path>] [--validation-cmd <cmd>] [--timeout-ms N] [--json] | evolver cycle --repo <path> [--resume] [--limit N] [--target <path>] [--expected-effect <text>] [--runner claude|codex|gemini|llm] [--validation-spec <file>] [--validation-cmd <cmd>] [--timeout-ms N]\n';
22
+ const WATCH_USAGE = 'usage: evolver cycle watch --repo <path> [--resume] [--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|gemini|llm] [--validation-spec <file>] [--validation-cmd <cmd>] [--timeout-ms N] [--json]\n';
22
23
  class CycleWatchStateWriteError extends Error {
23
24
  constructor() {
24
25
  super('cycle watch state file write failed');
@@ -114,17 +115,23 @@ function parseRunner(value) {
114
115
  if (value === undefined || value === 'claude')
115
116
  return { ok: true, runner: 'claude' };
116
117
  if (value.trim() === '')
117
- return { ok: false, error: 'runner value is required (supported: claude, codex, gemini)' };
118
- if (value === 'codex' || value === 'gemini')
118
+ return { ok: false, error: 'runner value is required (supported: claude, codex, gemini, llm)' };
119
+ if (value === 'codex' || value === 'gemini' || value === 'llm')
119
120
  return { ok: true, runner: value };
120
121
  if (value === 'cursor' || value === 'antigravity' || value === 'kimi' || value === 'kiro' || value === 'opencode') {
121
122
  const capability = RUNTIME_CAPABILITY_MATRIX[value].execute;
122
123
  return { ok: false, error: `runner '${value}' execute capability is ${capability.status}: ${capability.evidence}` };
123
124
  }
124
- return { ok: false, error: `unknown runner '${value}' (supported: claude, codex, gemini)` };
125
+ return { ok: false, error: `unknown runner '${value}' (supported: claude, codex, gemini, llm)` };
125
126
  }
126
127
  function resolveMaterialRunner(material, requestedRunner) {
127
128
  const sourceAgent = material.sourceAgent;
129
+ // Executor identity is explicit; the material remains attributed to its original runtime.
130
+ const sourceCapability = sourceAgent ? RUNTIME_CAPABILITY_MATRIX[sourceAgent] : undefined;
131
+ if (requestedRunner === 'llm' && material.sourceKind === 'runtime_session'
132
+ && sourceCapability && sourceCapability.ingest.status !== 'unsupported') {
133
+ return { ok: true, runner: 'llm' };
134
+ }
128
135
  let runner;
129
136
  switch (sourceAgent) {
130
137
  case 'claude-code':
@@ -158,6 +165,23 @@ function resolveMaterialRunner(material, requestedRunner) {
158
165
  }
159
166
  return { ok: true, runner };
160
167
  }
168
+ function cycleValidationSpec(flags, runner, resume, commands) {
169
+ if (runner !== 'llm') {
170
+ if ('validation-spec' in flags)
171
+ throw new Error('--validation-spec requires explicit --runner llm');
172
+ return undefined;
173
+ }
174
+ if (resume)
175
+ throw new Error('llm executes a new file task; native session resume is unsupported');
176
+ if (commands.length > 0)
177
+ throw new Error('--validation-spec cannot replace or combine with --validation-cmd; script validation still requires an OS sandbox');
178
+ if (!flags['validation-spec'])
179
+ throw new Error('--runner llm requires --validation-spec with independent expected file hashes');
180
+ const spec = readCycleValidationSpec(flags['validation-spec']);
181
+ exec.readLlmRunnerConfig();
182
+ verify.assertDeclarativeValidationAvailable(flags['repo']);
183
+ return spec;
184
+ }
161
185
  function printRuntimeCapabilities() {
162
186
  for (const entry of runtimeCapabilities()) {
163
187
  const values = ['ingest', 'inject', 'execute', 'verify', 'resume']
@@ -543,6 +567,35 @@ async function processMaterial(material, opts, deps) {
543
567
  ...(resume?.ok ? { resume: resume.resume } : {}),
544
568
  ...(opts.signal ? { signal: opts.signal } : {}),
545
569
  };
570
+ if (opts.validationSpec) {
571
+ await deps.ingestor.ingest({
572
+ type: 'cycle.execution_admitted',
573
+ human: { title: 'LLM 文件执行准入', severity: 'info' },
574
+ payload: { cycleId, materialId: material.materialId, sourceAgent: material.sourceAgent, runner: runner.runner,
575
+ validationSpec: opts.validationSpec, validationPlanDigest: verify.declarativeValidationDigest(opts.validationSpec) },
576
+ actor: { kind: 'machine' },
577
+ });
578
+ }
579
+ let validationEvidence;
580
+ const recordValidation = (input) => {
581
+ const validate = opts.validate?.(input);
582
+ if (!validate)
583
+ return () => ({ passed: false, score: 0.2 });
584
+ return async (mutation, decision, cwd, signal) => {
585
+ const result = await validate(mutation, decision, cwd, signal);
586
+ if (result.validator) {
587
+ validationEvidence = structuredClone(result.validator);
588
+ if (opts.validationSpec)
589
+ await deps.ingestor.ingest({
590
+ type: 'cycle.validation',
591
+ human: { title: '独立文件验收回执', severity: result.passed ? 'info' : 'warn' },
592
+ payload: { cycleId, materialId: material.materialId, runner: runner.runner, validator: validationEvidence },
593
+ actor: { kind: 'machine' },
594
+ });
595
+ }
596
+ return result;
597
+ };
598
+ };
546
599
  const verdict = await exec.runAutoExecTask({
547
600
  engine: deps.engine,
548
601
  store: deps.store,
@@ -555,9 +608,10 @@ async function processMaterial(material, opts, deps) {
555
608
  ...(deps.selectionPolicy !== 'engine-health' ? { selectionPolicy: deps.selectionPolicy } : {}),
556
609
  selectionGuard: deps.selectionGuard,
557
610
  ...(deps.selectionFloor !== undefined ? { selectionFloor: deps.selectionFloor } : {}),
558
- ...(opts.validate ? { validate: opts.validate } : {}),
611
+ ...(opts.validate ? { validate: recordValidation } : {}),
559
612
  ...(opts.agent ? { agent: opts.agent } : {}),
560
613
  ...(opts.git ? { git: opts.git } : {}),
614
+ ...(opts.gitPatchWriter ? { gitPatchWriter: opts.gitPatchWriter } : {}),
561
615
  }, task, safety);
562
616
  const item = {
563
617
  materialId: material.materialId,
@@ -571,6 +625,9 @@ async function processMaterial(material, opts, deps) {
571
625
  signalCount: extracted.signals.length,
572
626
  signals: extracted.signals,
573
627
  runner: runner.runner,
628
+ ...(material.sourceAgent ? { sourceAgent: material.sourceAgent } : {}),
629
+ ...(opts.validationSpec ? { validationKind: 'exact_file_sha256', validationPlanDigest: verify.declarativeValidationDigest(opts.validationSpec) } : {}),
630
+ ...(validationEvidence ? { validationEvidence } : {}),
574
631
  ...(resume?.ok && verdict.status === 'solidified' ? { resumedSession: true } : {}),
575
632
  });
576
633
  ackOne(deps.consumer, material);
@@ -581,6 +638,10 @@ async function processMaterial(material, opts, deps) {
581
638
  }
582
639
  }
583
640
  export async function runMaterialCycleConsumer(opts, injectedDeps = {}) {
641
+ opts = prepareLlmCycle(opts);
642
+ // The LLM Git runner verifies executable repository configuration before claiming input.
643
+ if (opts.runner === 'llm')
644
+ await opts.git?.(['rev-parse', '--is-inside-work-tree'], opts.repo, opts.signal);
584
645
  const deps = resolveMaterialCycleDeps(injectedDeps);
585
646
  const limit = Math.max(1, opts.limit ?? DEFAULT_LIMIT);
586
647
  const claimed = deps.consumer.claim(CYCLE_GROUP, limit);
@@ -1040,6 +1101,14 @@ export async function runCycleCommand(argv, injectedDeps = {}) {
1040
1101
  process.stderr.write(WATCH_USAGE);
1041
1102
  return 1;
1042
1103
  }
1104
+ let validationSpec;
1105
+ try {
1106
+ validationSpec = cycleValidationSpec(flags, runner.runner, resume, validationCmds);
1107
+ }
1108
+ catch (error) {
1109
+ process.stderr.write(`${error instanceof Error ? error.message : 'invalid LLM cycle configuration'}\n`);
1110
+ return 1;
1111
+ }
1043
1112
  const validate = makeCycleValidationHook(validationCmds, injectedDeps.validate, injectedDeps.runSandboxedValidation);
1044
1113
  const maxIdle = parseRequiredPositiveIntFlag(flags, 'max-idle');
1045
1114
  const maxIterations = parseRequiredPositiveIntFlag(flags, 'max-iterations');
@@ -1074,10 +1143,12 @@ export async function runCycleCommand(argv, injectedDeps = {}) {
1074
1143
  signal,
1075
1144
  ...(timeoutMs !== undefined ? { timeoutMs } : {}),
1076
1145
  ...(validationCmds.length > 0 ? { validationCmds } : {}),
1146
+ ...(validationSpec ? { validationSpec } : {}),
1077
1147
  ...(validate ? { validate } : {}),
1078
1148
  safety: { ...injectedDeps.safety, signal },
1079
1149
  ...(injectedDeps.agent ? { agent: injectedDeps.agent } : {}),
1080
1150
  ...(injectedDeps.git ? { git: injectedDeps.git } : {}),
1151
+ ...(injectedDeps.gitPatchWriter ? { gitPatchWriter: injectedDeps.gitPatchWriter } : {}),
1081
1152
  idleMs: parsePositiveInt(flags['idle-ms'], DEFAULT_WATCH_IDLE_MS),
1082
1153
  maxIdleMs: parsePositiveInt(flags['max-idle-ms'], DEFAULT_WATCH_MAX_IDLE_MS),
1083
1154
  ...(maxIdle !== undefined ? { maxIdle } : {}),
@@ -1192,6 +1263,14 @@ export async function runCycleCommand(argv, injectedDeps = {}) {
1192
1263
  process.stderr.write(CYCLE_USAGE);
1193
1264
  return 1;
1194
1265
  }
1266
+ let validationSpec;
1267
+ try {
1268
+ validationSpec = cycleValidationSpec(flags, runner.runner, resume, validationCmds);
1269
+ }
1270
+ catch (error) {
1271
+ process.stderr.write(`${error instanceof Error ? error.message : 'invalid LLM cycle configuration'}\n`);
1272
+ return 1;
1273
+ }
1195
1274
  const validate = makeCycleValidationHook(validationCmds, injectedDeps.validate, injectedDeps.runSandboxedValidation);
1196
1275
  const cancellation = createProcessCancellation();
1197
1276
  const signal = combineSignals(cancellation.signal, injectedDeps.safety?.signal);
@@ -1207,10 +1286,12 @@ export async function runCycleCommand(argv, injectedDeps = {}) {
1207
1286
  signal,
1208
1287
  ...(timeoutMs !== undefined ? { timeoutMs } : {}),
1209
1288
  ...(validationCmds.length > 0 ? { validationCmds } : {}),
1289
+ ...(validationSpec ? { validationSpec } : {}),
1210
1290
  ...(validate ? { validate } : {}),
1211
1291
  safety: { ...injectedDeps.safety, signal },
1212
1292
  ...(injectedDeps.agent ? { agent: injectedDeps.agent } : {}),
1213
1293
  ...(injectedDeps.git ? { git: injectedDeps.git } : {}),
1294
+ ...(injectedDeps.gitPatchWriter ? { gitPatchWriter: injectedDeps.gitPatchWriter } : {}),
1214
1295
  }, injectedDeps);
1215
1296
  }
1216
1297
  finally {
@@ -0,0 +1,6 @@
1
+ import { verify } from '@evomap/evolver-core';
2
+ import type { MaterialCycleOptions } from './cycleConsumer.js';
3
+ /** Read the operator's acceptance plan once, before any material is claimed or model dispatched. */
4
+ export declare function readCycleValidationSpec(path: string): verify.DeclarativeValidationSpec;
5
+ /** The LLM file executor is opt-in and never converts a script validation plan into a weaker check. */
6
+ export declare function prepareLlmCycle(options: MaterialCycleOptions): MaterialCycleOptions;
@@ -0,0 +1,90 @@
1
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from 'node:fs';
2
+ import { exec, verify } from '@evomap/evolver-core';
3
+ import { createLlmGit } from './llmGit.js';
4
+ /** Read the operator's acceptance plan once, before any material is claimed or model dispatched. */
5
+ export function readCycleValidationSpec(path) {
6
+ if (!path)
7
+ throw new Error('--validation-spec requires a file path');
8
+ let fd;
9
+ try {
10
+ const before = lstatSync(path, { bigint: true });
11
+ if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1n || before.size > 65536n)
12
+ throw new Error();
13
+ fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
14
+ const opened = fstatSync(fd, { bigint: true });
15
+ if (before.dev !== opened.dev || before.ino !== opened.ino || before.size !== opened.size
16
+ || before.mtimeNs !== opened.mtimeNs || before.ctimeNs !== opened.ctimeNs)
17
+ throw new Error();
18
+ const buffer = Buffer.alloc(65_537);
19
+ let count = 0;
20
+ while (count < buffer.length) {
21
+ const read = readSync(fd, buffer, count, buffer.length - count, count);
22
+ if (read === 0)
23
+ break;
24
+ count += read;
25
+ }
26
+ const bytes = buffer.subarray(0, count);
27
+ const after = fstatSync(fd, { bigint: true });
28
+ if (bytes.length > 65_536 || after.size !== opened.size || after.mtimeNs !== opened.mtimeNs || after.ctimeNs !== opened.ctimeNs)
29
+ throw new Error();
30
+ return verify.parseDeclarativeValidationSpec(JSON.parse(bytes.toString('utf8')));
31
+ }
32
+ catch {
33
+ throw new Error('invalid --validation-spec; provide a regular file of at most 64 KiB containing version: 1 and nonempty files with path/sha256');
34
+ }
35
+ finally {
36
+ if (fd !== undefined)
37
+ closeSync(fd);
38
+ }
39
+ }
40
+ /** The LLM file executor is opt-in and never converts a script validation plan into a weaker check. */
41
+ export function prepareLlmCycle(options) {
42
+ if (options.runner !== 'llm') {
43
+ if (options.validationSpec !== undefined)
44
+ throw new Error('--validation-spec requires explicit --runner llm');
45
+ return options;
46
+ }
47
+ if (!options.validationSpec)
48
+ throw new Error('--runner llm requires --validation-spec with independent expected file hashes');
49
+ if (options.resume)
50
+ throw new Error('llm executes a new file task; native session resume is unsupported');
51
+ if (options.validationCmds?.length)
52
+ throw new Error('--validation-spec cannot replace or combine with --validation-cmd; script validation still requires an OS sandbox');
53
+ if (options.safety?.isolation === 'none' || options.safety?.scrubEnv === false)
54
+ throw new Error('llm cycle requires a private worktree and scrubbed environment');
55
+ if (options.timeoutMs !== undefined && (!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs <= 0))
56
+ throw new Error('llm cycle timeout must be a positive integer');
57
+ const spec = verify.parseDeclarativeValidationSpec(options.validationSpec);
58
+ const config = options.agent ? undefined : exec.readLlmRunnerConfig();
59
+ verify.assertDeclarativeValidationAvailable(options.repo);
60
+ const agent = options.agent ?? exec.makeLlmHeadlessRunner({}, { config, writePaths: spec.files.map((file) => file.path) });
61
+ const priorValidate = options.validate;
62
+ const safeGit = options.git ? undefined : createLlmGit(options.repo, spec.files.map((file) => file.path));
63
+ const git = options.git ?? safeGit.git;
64
+ const gitPatchWriter = options.gitPatchWriter ?? safeGit?.gitPatchWriter;
65
+ return {
66
+ ...options,
67
+ validationSpec: spec,
68
+ agent,
69
+ git,
70
+ ...(gitPatchWriter ? { gitPatchWriter } : {}),
71
+ safety: { ...options.safety, isolation: 'worktree', scrubEnv: true, declarativeValidationOnly: true },
72
+ validate: (task) => {
73
+ const additional = priorValidate?.(task);
74
+ return async (mutation, decision, cwd, signal) => {
75
+ if (signal.aborted)
76
+ return { passed: false, score: 0.2 };
77
+ // Include ignored untracked files too: an acceptance hash cannot authorize unrelated output.
78
+ const tracked = await git(['diff', '--no-ext-diff', '--name-only', '-z', 'HEAD', '--'], cwd, signal);
79
+ const untracked = await git(['ls-files', '--others', '-z', '--'], cwd, signal);
80
+ const changed = [...new Set([...tracked.split('\0'), ...untracked.split('\0')].filter(Boolean))];
81
+ const result = await verify.runDeclarativeValidation(spec, cwd, changed, signal);
82
+ if (!result.passed || !additional)
83
+ return result;
84
+ const other = await additional(mutation, decision, cwd, signal);
85
+ return other.passed ? result : { ...result, passed: false, score: 0.2,
86
+ validator: { ...result.validator, passed: false, score: 0.2, reason: 'policy_denied' } };
87
+ };
88
+ },
89
+ };
90
+ }
@@ -0,0 +1,10 @@
1
+ import { exec } from '@evomap/evolver-core';
2
+ /**
3
+ * Trusted host Git composition for the bounded file executor. Repository configuration is
4
+ * rechecked for each invocation, including worktree creation before model dispatch. This is
5
+ * not a sandbox for custom Git runners: an injected runner and patch writer are trusted seams.
6
+ */
7
+ export declare function createLlmGit(repo: string, acceptancePaths?: readonly string[]): {
8
+ git: exec.GitRunner;
9
+ gitPatchWriter: exec.GitPatchWriter;
10
+ };
package/dist/llmGit.js ADDED
@@ -0,0 +1,362 @@
1
+ import { accessSync, constants, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmdirSync, statSync } from 'node:fs';
2
+ import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
3
+ import { exec, verify } from '@evomap/evolver-core';
4
+ const TIMEOUT_MS = 30_000;
5
+ const CONFIG_PATTERN = '^(filter[.].*[.](clean|smudge|process)|includeif[.].*[.]path|extensions[.]partialclone|remote[.].*[.]promisor|core[.](alternaterefscommand|worktree))$';
6
+ const GUARDS = [
7
+ '--no-pager',
8
+ '-c', 'core.hooksPath=/dev/null',
9
+ '-c', 'core.fsmonitor=false',
10
+ '-c', 'core.untrackedCache=false',
11
+ '-c', 'core.attributesFile=/dev/null',
12
+ '-c', 'core.excludesFile=/dev/null',
13
+ '-c', 'core.autocrlf=false',
14
+ '-c', 'core.eol=lf',
15
+ '-c', 'gc.auto=0',
16
+ '-c', 'maintenance.auto=false',
17
+ '-c', 'submodule.recurse=false',
18
+ '-c', 'protocol.allow=never',
19
+ ];
20
+ function inside(root, path) {
21
+ const value = relative(root, path);
22
+ return value === '' || (!isAbsolute(value) && value !== '..' && !value.startsWith(`..${sep}`));
23
+ }
24
+ function directoryIdentity(path) {
25
+ try {
26
+ const stat = lstatSync(path, { bigint: true });
27
+ if (!stat.isDirectory() || stat.isSymbolicLink())
28
+ return undefined;
29
+ return { path: realpathSync.native(path), dev: stat.dev, ino: stat.ino };
30
+ }
31
+ catch {
32
+ return undefined;
33
+ }
34
+ }
35
+ function sameDirectory(actual, expected) {
36
+ return actual !== undefined && expected !== undefined && actual.path === expected.path
37
+ && actual.dev === expected.dev && actual.ino === expected.ino;
38
+ }
39
+ function absent(path) {
40
+ try {
41
+ lstatSync(path);
42
+ return false;
43
+ }
44
+ catch (error) {
45
+ return error.code === 'ENOENT';
46
+ }
47
+ }
48
+ /** Only Git's own incomplete-creation lock permits stronger removal than ordinary cleanup. */
49
+ function initializingLock(path) {
50
+ try {
51
+ const stat = lstatSync(path, { bigint: true });
52
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 32n)
53
+ return undefined;
54
+ if (!/^initializing\n?$/u.test(readFileSync(path, 'utf8')))
55
+ return undefined;
56
+ return { path, dev: stat.dev, ino: stat.ino };
57
+ }
58
+ catch {
59
+ return undefined;
60
+ }
61
+ }
62
+ /** Resolve a host executable once; subsequent model writes cannot change command lookup. */
63
+ function hostGit(repo, env) {
64
+ const root = realpathSync.native(repo);
65
+ const path = Object.entries(env).find(([key]) => key.toUpperCase() === 'PATH')?.[1] ?? '';
66
+ for (const directory of path.split(delimiter)) {
67
+ if (!isAbsolute(directory))
68
+ continue;
69
+ try {
70
+ const candidate = realpathSync.native(join(directory, process.platform === 'win32' ? 'git.exe' : 'git'));
71
+ if (inside(root, candidate) || !statSync(candidate).isFile())
72
+ continue;
73
+ accessSync(candidate, constants.X_OK);
74
+ return candidate;
75
+ }
76
+ catch { /* A missing PATH entry is not executable authority. */ }
77
+ }
78
+ throw new Error('llm cycle requires a native Git executable outside the repository');
79
+ }
80
+ function command(args) {
81
+ if (!['rev-parse', 'worktree', 'diff', 'ls-files', 'add', 'reset'].includes(args[0] ?? '')) {
82
+ throw new Error('unsupported llm Git operation');
83
+ }
84
+ const separator = args.indexOf('--');
85
+ const flags = args.slice(1, separator < 0 ? undefined : separator);
86
+ if (flags.some((arg) => arg === '--ext-diff' || arg === '--textconv' || arg === '--recurse-submodules')) {
87
+ throw new Error('executable Git extensions are not allowed for llm cycle');
88
+ }
89
+ return [...GUARDS, args[0], ...(args[0] === 'diff' ? ['--no-ext-diff', '--no-textconv'] : []), ...args.slice(1)];
90
+ }
91
+ /**
92
+ * Trusted host Git composition for the bounded file executor. Repository configuration is
93
+ * rechecked for each invocation, including worktree creation before model dispatch. This is
94
+ * not a sandbox for custom Git runners: an injected runner and patch writer are trusted seams.
95
+ */
96
+ export function createLlmGit(repo, acceptancePaths = []) {
97
+ if (acceptancePaths.length > 64)
98
+ throw new Error('llm Git acceptance paths exceed their bound');
99
+ const paths = Object.freeze(acceptancePaths.map((path) => verify.declarativeValidationPath(path)));
100
+ const env = {
101
+ ...exec.scrubAgentEnv(process.env),
102
+ // Git localizes its incomplete-worktree lock reason; ownership proof needs stable metadata.
103
+ LC_ALL: 'C',
104
+ LANGUAGE: 'C',
105
+ GIT_CONFIG_NOSYSTEM: '1',
106
+ GIT_CONFIG_SYSTEM: '/dev/null',
107
+ GIT_CONFIG_GLOBAL: '/dev/null',
108
+ GIT_TERMINAL_PROMPT: '0',
109
+ GIT_NO_LAZY_FETCH: '1',
110
+ GIT_LITERAL_PATHSPECS: '1',
111
+ GIT_ATTR_NOSYSTEM: '1',
112
+ };
113
+ const executable = hostGit(repo, env);
114
+ const repository = directoryIdentity(repo);
115
+ if (!repository)
116
+ throw new Error('llm Git repository identity is unavailable');
117
+ const ownedWorktrees = new Map();
118
+ const complete = (result, allowMissing = false) => {
119
+ if (result.termination !== 'exit')
120
+ throw new Error(`llm Git operation ${result.termination}`);
121
+ if (result.stdoutTruncated)
122
+ throw new Error('llm Git proof exceeds its capture bound');
123
+ if (result.code !== 0 && !(allowMissing && result.code === 1))
124
+ throw new Error('llm Git operation failed');
125
+ };
126
+ const metadata = async (args, cwd, signal, options) => {
127
+ const result = await exec.spawnCapture(executable, [...GUARDS, ...args], {
128
+ cwd, timeoutMs: TIMEOUT_MS, env, ...(signal ? { signal } : {}), ...options,
129
+ });
130
+ complete(result);
131
+ return result.stdout;
132
+ };
133
+ const metadataDirectory = async (flag, cwd, signal, options) => {
134
+ const output = await metadata(['rev-parse', '--path-format=absolute', flag], cwd, signal, options);
135
+ const path = output.endsWith('\n') ? output.slice(0, -1) : '';
136
+ return isAbsolute(path) ? directoryIdentity(path) : undefined;
137
+ };
138
+ const reserveCreation = async (path, cwd, signal, options) => {
139
+ const target = resolve(cwd, path);
140
+ const parent = directoryIdentity(dirname(target));
141
+ if (!parent || !absent(target))
142
+ return undefined;
143
+ const common = await metadataDirectory('--git-common-dir', cwd, signal, options);
144
+ if (!common || !sameDirectory(directoryIdentity(cwd), repository)
145
+ || !sameDirectory(directoryIdentity(dirname(target)), parent) || !absent(target))
146
+ return undefined;
147
+ // Observing absence is not ownership: another Git process could create the target
148
+ // before our add starts. Atomically create the empty leaf Git will populate instead.
149
+ try {
150
+ mkdirSync(target, { mode: 0o700 });
151
+ }
152
+ catch (error) {
153
+ if (error.code === 'EEXIST')
154
+ return undefined;
155
+ throw error;
156
+ }
157
+ const leaf = directoryIdentity(target);
158
+ if (!leaf || leaf.path !== join(parent.path, basename(target))
159
+ || !sameDirectory(directoryIdentity(dirname(target)), parent)) {
160
+ throw new Error('llm Git reserved worktree identity changed; retain reservation for recovery');
161
+ }
162
+ return { path: leaf.path, parent, common, leaf };
163
+ };
164
+ const creationUnchanged = (creation) => sameDirectory(directoryIdentity(repo), repository)
165
+ && sameDirectory(directoryIdentity(dirname(creation.path)), creation.parent)
166
+ && sameDirectory(directoryIdentity(creation.path), creation.leaf)
167
+ && sameDirectory(directoryIdentity(creation.common.path), creation.common);
168
+ const worktreeListing = async () => {
169
+ const listing = await metadata(['worktree', 'list', '--porcelain', '-z'], repo, undefined, { processSignalMode: 'ignore' });
170
+ const records = listing.split('\0\0');
171
+ if (records.pop() !== '' || records.length === 0)
172
+ throw new Error('llm Git worktree listing is incomplete');
173
+ return records.map((record) => {
174
+ const [location, ...fields] = record.split('\0');
175
+ if (!location?.startsWith('worktree ') || !isAbsolute(location.slice('worktree '.length)) || fields.length === 0) {
176
+ throw new Error('llm Git worktree listing is malformed');
177
+ }
178
+ return { path: location.slice('worktree '.length), detached: fields.includes('detached') };
179
+ });
180
+ };
181
+ const listedCreation = (path, creation) => {
182
+ const actual = resolve(path);
183
+ return (process.platform === 'win32' ? actual.toLowerCase() === creation.path.toLowerCase() : actual === creation.path)
184
+ || sameDirectory(directoryIdentity(path), creation.leaf);
185
+ };
186
+ const removeEmptyCreation = async (creation) => {
187
+ if (!creationUnchanged(creation) || readdirSync(creation.path).length !== 0)
188
+ return;
189
+ // Only a successful, complete listing proving absence permits empty-reservation
190
+ // cleanup. A failed/truncated/unknown proof must retain the directory for recovery.
191
+ const listing = await worktreeListing();
192
+ if (listing.some((entry) => listedCreation(entry.path, creation)) || !creationUnchanged(creation))
193
+ return;
194
+ // Nonrecursive removal also refuses a directory populated after the readback.
195
+ rmdirSync(creation.path);
196
+ };
197
+ const reconcileCreation = async (creation) => {
198
+ const created = creation.leaf;
199
+ if (!creationUnchanged(creation))
200
+ return undefined;
201
+ // Fixed metadata-only commands do not checkout files or run filters. Shield the original
202
+ // cancellation only after spawnCapture has returned its settled child result.
203
+ const cleanup = { processSignalMode: 'ignore' };
204
+ const common = await metadataDirectory('--git-common-dir', created.path, undefined, cleanup);
205
+ const admin = await metadataDirectory('--git-dir', created.path, undefined, cleanup);
206
+ if (!sameDirectory(common, creation.common) || !admin
207
+ || dirname(admin.path) !== join(creation.common.path, 'worktrees'))
208
+ return undefined;
209
+ const backPointer = join(admin.path, 'gitdir');
210
+ const pointerStat = lstatSync(backPointer);
211
+ if (!pointerStat.isFile() || pointerStat.isSymbolicLink() || pointerStat.size > 4096)
212
+ return undefined;
213
+ const pointer = readFileSync(backPointer, 'utf8');
214
+ if (!pointer.endsWith('\n') || realpathSync.native(pointer.slice(0, -1)) !== join(created.path, '.git'))
215
+ return undefined;
216
+ const listing = await worktreeListing();
217
+ const registered = listing.some((entry) => entry.detached && listedCreation(entry.path, creation));
218
+ if (!registered || !creationUnchanged(creation) || !sameDirectory(directoryIdentity(admin.path), admin))
219
+ return undefined;
220
+ const lock = initializingLock(join(admin.path, 'locked'));
221
+ return { ...created, ...(lock ? { initializingLock: lock } : {}) };
222
+ };
223
+ let versionChecked = false;
224
+ const preflight = async (cwd, signal, options, cleanup = false) => {
225
+ const spawnOptions = { cwd, timeoutMs: TIMEOUT_MS, env, ...(signal ? { signal } : {}), ...options };
226
+ if (!versionChecked) {
227
+ const result = await exec.spawnCapture(executable, ['--version'], spawnOptions);
228
+ complete(result);
229
+ const match = /^git version (\d+)\.(\d+)(?:\.|\s)/.exec(result.stdout);
230
+ if (!match || Number(match[1]) < 2 || (Number(match[1]) === 2 && Number(match[2]) < 43)) {
231
+ throw new Error('llm cycle requires Git 2.43 or newer for non-executable monitoring and committed attribute proof');
232
+ }
233
+ versionChecked = true;
234
+ }
235
+ // Exact cleanup calls have already established ownership below. Their fixed argv does
236
+ // not inspect working-tree content, so changed admission policy cannot strand that owner.
237
+ if (cleanup)
238
+ return;
239
+ const config = await exec.spawnCapture(executable, [...GUARDS, 'config', '--null', '--get-regexp', CONFIG_PATTERN], spawnOptions);
240
+ complete(config, true);
241
+ for (const entry of config.stdout.split('\0').filter(Boolean)) {
242
+ const newline = entry.indexOf('\n');
243
+ const key = (newline < 0 ? entry : entry.slice(0, newline)).toLowerCase();
244
+ const value = newline < 0 ? '' : entry.slice(newline + 1);
245
+ // A pinned cwd does not constrain Git when repository config redirects its worktree.
246
+ if (key === 'core.worktree')
247
+ throw new Error('llm cycle refuses Git worktree redirection');
248
+ // Conditional includes may activate inside `worktree add` before that new cwd can be checked.
249
+ if (!key.startsWith('filter.') || value.trim() !== '') {
250
+ throw new Error('llm cycle refuses executable Git filters, conditional configuration, or lazy object sources');
251
+ }
252
+ }
253
+ const tree = await exec.spawnCapture(executable, [...GUARDS, 'ls-tree', '-r', '-z', 'HEAD'], spawnOptions);
254
+ complete(tree);
255
+ if (tree.stdout.split('\0').some((entry) => entry.startsWith('160000 '))) {
256
+ throw new Error('llm cycle does not admit submodules whose output is absent from the outer Git patch');
257
+ }
258
+ if (paths.length > 0) {
259
+ // Worktree creation reads committed attributes, which an uncommitted local file may mask.
260
+ for (const source of [[], ['--source=HEAD']]) {
261
+ const attrs = await exec.spawnCapture(executable, [...GUARDS, 'check-attr', '-z', ...source, 'text', 'eol', 'crlf', 'ident', 'filter', 'working-tree-encoding', '--', ...paths], spawnOptions);
262
+ complete(attrs);
263
+ const fields = attrs.stdout.split('\0');
264
+ if (fields.pop() !== '' || fields.length !== paths.length * 6 * 3)
265
+ throw new Error('llm Git attributes proof is incomplete');
266
+ for (let index = 0; index < fields.length; index += 3) {
267
+ if (!paths.includes(fields[index]) || !['unspecified', 'unset'].includes(fields[index + 2])) {
268
+ throw new Error('llm cycle refuses byte-transforming Git attributes on acceptance paths');
269
+ }
270
+ }
271
+ }
272
+ }
273
+ };
274
+ const git = async (args, cwd, signal, options) => {
275
+ const argv = command(args);
276
+ const cwdIdentity = directoryIdentity(cwd);
277
+ const atRepository = sameDirectory(cwdIdentity, repository);
278
+ const atOwnedWorktree = cwdIdentity !== undefined && sameDirectory(cwdIdentity, ownedWorktrees.get(cwdIdentity.path));
279
+ const commonDirectory = args.length === 3 && args[0] === 'rev-parse'
280
+ && args[1] === '--path-format=absolute' && args[2] === '--git-common-dir'
281
+ && (atRepository || atOwnedWorktree);
282
+ const removed = args.length === 4 && args[0] === 'worktree' && args[1] === 'remove' && args[2] === '--force'
283
+ && atRepository ? directoryIdentity(resolve(cwd, args[3])) : undefined;
284
+ const removeOwned = removed !== undefined && sameDirectory(removed, ownedWorktrees.get(removed.path));
285
+ if (args[0] === 'worktree' && args[1] === 'remove' && !removeOwned) {
286
+ throw new Error('llm Git worktree removal requires an exact owned identity');
287
+ }
288
+ const retainedLock = removed && ownedWorktrees.get(removed.path)?.initializingLock;
289
+ if (removeOwned && retainedLock && sameDirectory(initializingLock(retainedLock.path), retainedLock))
290
+ argv.push('--force');
291
+ // No exemption for arbitrary rev-parse flags, unowned/replaced directories, or reset.
292
+ await preflight(cwd, signal, options, commonDirectory || removeOwned);
293
+ const adding = args.length === 5 && args[0] === 'worktree' && args[1] === 'add' && args[2] === '--detach'
294
+ && args[4] === 'HEAD' && atRepository;
295
+ const creation = adding ? await reserveCreation(args[3], cwd, signal, options) : undefined;
296
+ if (adding && !creation)
297
+ throw new Error('llm Git worktree target must be absent under a stable parent');
298
+ if (creation && !creationUnchanged(creation))
299
+ throw new Error('llm Git reserved worktree identity changed; retain reservation for recovery');
300
+ const result = await exec.spawnCapture(executable, argv, {
301
+ cwd, timeoutMs: TIMEOUT_MS, env, ...(signal ? { signal } : {}), ...options,
302
+ });
303
+ try {
304
+ complete(result);
305
+ }
306
+ catch (error) {
307
+ // A failed result can follow a real registration/checkout. Never adopt an existing
308
+ // target or reconcile a rejected spawn whose child settlement is unknown.
309
+ if (creation) {
310
+ let retained;
311
+ try {
312
+ retained = await reconcileCreation(creation);
313
+ }
314
+ catch { /* Missing or ambiguous proof cannot confer cleanup authority. */ }
315
+ if (retained)
316
+ ownedWorktrees.set(retained.path, retained);
317
+ else {
318
+ try {
319
+ await removeEmptyCreation(creation);
320
+ }
321
+ catch { /* Preserve the original failure and retained recovery evidence. */ }
322
+ }
323
+ }
324
+ throw error;
325
+ }
326
+ if (adding) {
327
+ let created;
328
+ try {
329
+ created = await reconcileCreation(creation);
330
+ }
331
+ catch { /* Unknown proof cannot confer cleanup authority. */ }
332
+ if (!created) {
333
+ try {
334
+ await removeEmptyCreation(creation);
335
+ }
336
+ catch { /* Retain ambiguous or populated reservations for recovery. */ }
337
+ throw new Error('llm Git worktree identity could not be retained');
338
+ }
339
+ ownedWorktrees.set(created.path, created);
340
+ }
341
+ if (removeOwned)
342
+ ownedWorktrees.delete(removed.path);
343
+ return result.stdout;
344
+ };
345
+ const gitPatchWriter = async (args, cwd, destination, signal, onDestinationOpened) => {
346
+ if (args[0] !== 'diff')
347
+ throw new Error('llm patch writer only accepts a Git diff');
348
+ const argv = command(args);
349
+ await preflight(cwd, signal);
350
+ // spawnCapture owns exclusive creation, complete streaming, and settlement of this file.
351
+ // Preserve its finalize error so the bridge can retain the correct cleanup ownership.
352
+ const result = await exec.spawnCapture(executable, argv, {
353
+ cwd, timeoutMs: TIMEOUT_MS, env, stdoutFile: destination,
354
+ ...(signal ? { signal } : {}),
355
+ ...(onDestinationOpened ? { onStdoutFileOpened: onDestinationOpened } : {}),
356
+ });
357
+ if (result.termination !== 'exit' || result.code !== 0 || result.stdoutRedirected !== true) {
358
+ throw new Error('llm Git patch streaming did not complete');
359
+ }
360
+ };
361
+ return { git, gitPatchWriter };
362
+ }
@@ -1,5 +1,5 @@
1
1
  type RuntimeCapabilityStatus = 'supported' | 'experimental' | 'unsupported';
2
- type RuntimeCapabilityId = 'claude-code' | 'codex' | 'cursor' | 'gemini' | 'antigravity' | 'kimi' | 'kiro' | 'opencode' | 'generic-chat';
2
+ type RuntimeCapabilityId = 'claude-code' | 'codex' | 'cursor' | 'gemini' | 'antigravity' | 'kimi' | 'kiro' | 'opencode' | 'generic-chat' | 'llm';
3
3
  interface RuntimeCapability {
4
4
  status: RuntimeCapabilityStatus;
5
5
  evidence: string;
@@ -3,6 +3,14 @@ const experimental = (evidence) => ({ status: 'experimental', evidence });
3
3
  const unsupported = (evidence) => ({ status: 'unsupported', evidence });
4
4
  /** Product-level runtime matrix. A transcript parser never implies execution, verification, or resumability. */
5
5
  export const RUNTIME_CAPABILITY_MATRIX = {
6
+ llm: {
7
+ runtime: 'llm',
8
+ ingest: unsupported('explicit file executor; preserves the imported runtime Material sourceAgent'),
9
+ inject: unsupported('no native harness or injection installer'),
10
+ execute: experimental('opt-in --runner llm with an OpenAI-compatible provider and a frozen --validation-spec; bounded file tools only, no model-selected processes; live provider/release acceptance pending'),
11
+ verify: experimental('independent exact file SHA-256 acceptance on native Windows, Linux and macOS code paths; no script execution or OS sandbox claim; platform and published-artifact acceptance required'),
12
+ resume: unsupported('starts a new file task; interrupted cycles retain their original event/cleanup recovery boundary'),
13
+ },
6
14
  'claude-code': {
7
15
  runtime: 'claude-code',
8
16
  ingest: supported('normalized Claude Code JSONL adapter'),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@evomap/evolver-cli",
3
- "version": "2.0.39",
3
+ "version": "2.0.40",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "engines": {
@@ -23,12 +23,12 @@
23
23
  }
24
24
  },
25
25
  "dependencies": {
26
- "@evomap/evolver-core": "2.0.39",
27
- "@evomap/evolver-adapter-public": "2.0.39",
28
- "@evomap/evolver-mcp": "2.0.39",
29
- "@evomap/evolver-proxy": "2.0.39",
30
- "@evomap/evolver-runtime-adapters": "2.0.39",
31
- "@evomap/evolver-webui": "2.0.39"
26
+ "@evomap/evolver-core": "2.0.40",
27
+ "@evomap/evolver-adapter-public": "2.0.40",
28
+ "@evomap/evolver-mcp": "2.0.40",
29
+ "@evomap/evolver-proxy": "2.0.40",
30
+ "@evomap/evolver-runtime-adapters": "2.0.40",
31
+ "@evomap/evolver-webui": "2.0.40"
32
32
  },
33
33
  "repository": {
34
34
  "type": "git",