@omacode/micromanager 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +30 -2
  3. package/THIRD_PARTY.md +100 -0
  4. package/decider/.python-version +1 -0
  5. package/decider/README.md +35 -0
  6. package/decider/decider/__init__.py +1 -0
  7. package/decider/decider/server.py +327 -0
  8. package/decider/pyproject.toml +34 -0
  9. package/decider/uv.lock +1255 -0
  10. package/dist/agenda.js +51 -0
  11. package/dist/agents.js +58 -0
  12. package/dist/artifact/handoff.js +281 -0
  13. package/dist/ask.js +200 -0
  14. package/dist/backends.js +219 -0
  15. package/dist/backlog.js +414 -0
  16. package/dist/bench.js +427 -0
  17. package/dist/board.js +1 -0
  18. package/dist/brief.js +202 -0
  19. package/dist/browser.js +679 -0
  20. package/dist/budget.js +61 -0
  21. package/dist/catalog.js +187 -0
  22. package/dist/checkchange.js +145 -0
  23. package/dist/checkpoint.js +94 -0
  24. package/dist/cli.js +764 -0
  25. package/dist/comfy-gate.js +258 -0
  26. package/dist/compact.js +142 -0
  27. package/dist/config.js +344 -0
  28. package/dist/context/capture.js +1 -0
  29. package/dist/context/digest.js +1 -0
  30. package/dist/context/embed.js +1 -0
  31. package/dist/context/index.js +2 -0
  32. package/dist/context/ledger.js +1 -0
  33. package/dist/context/manager.js +1 -0
  34. package/dist/context/memory.js +1 -0
  35. package/dist/context/policy.js +1 -0
  36. package/dist/context/prices.js +1 -0
  37. package/dist/context/recall.js +1 -0
  38. package/dist/context/rules.js +1 -0
  39. package/dist/context/search.js +1 -0
  40. package/dist/context/status.js +1 -0
  41. package/dist/context/store.js +1 -0
  42. package/dist/context/summary.js +1 -0
  43. package/dist/context/tokens.js +1 -0
  44. package/dist/context/tools.js +1 -0
  45. package/dist/continuation.js +184 -0
  46. package/dist/contract.js +294 -0
  47. package/dist/contractround.js +178 -0
  48. package/dist/control.js +1 -0
  49. package/dist/creative-tools.js +237 -0
  50. package/dist/dataset.js +175 -0
  51. package/dist/decide.js +676 -0
  52. package/dist/decider.js +171 -0
  53. package/dist/design-shell.js +448 -0
  54. package/dist/design.js +1410 -0
  55. package/dist/desktop.js +44 -0
  56. package/dist/egress.js +156 -0
  57. package/dist/eval.js +60 -0
  58. package/dist/evolver.js +302 -0
  59. package/dist/features.js +193 -0
  60. package/dist/followups.js +32 -0
  61. package/dist/forms.js +195 -0
  62. package/dist/gate.js +108 -0
  63. package/dist/gatebox.js +46 -0
  64. package/dist/grants.js +189 -0
  65. package/dist/graph.js +65 -0
  66. package/dist/guard/index.js +1 -0
  67. package/dist/guard/wire.js +1 -0
  68. package/dist/helpers.js +85 -0
  69. package/dist/hooks.js +158 -0
  70. package/dist/image-models.js +117 -0
  71. package/dist/integration.js +3 -0
  72. package/dist/journal.js +1 -0
  73. package/dist/look.js +363 -0
  74. package/dist/memory.js +1 -0
  75. package/dist/mode.js +97 -0
  76. package/dist/native.js +3348 -0
  77. package/dist/nogit.js +259 -0
  78. package/dist/outcomes.js +148 -0
  79. package/dist/permission.js +35 -0
  80. package/dist/pick.js +89 -0
  81. package/dist/pipelines.js +262 -0
  82. package/dist/plan.js +641 -0
  83. package/dist/plandoc.js +211 -0
  84. package/dist/plugin.js +4736 -0
  85. package/dist/policy.js +58 -0
  86. package/dist/pools.js +1 -0
  87. package/dist/preview.js +274 -0
  88. package/dist/profile.js +165 -0
  89. package/dist/progress.js +1 -0
  90. package/dist/promote.js +313 -0
  91. package/dist/redact.js +1 -0
  92. package/dist/registry.js +179 -0
  93. package/dist/riskscore.js +126 -0
  94. package/dist/roles.js +1 -0
  95. package/dist/routing.js +1 -0
  96. package/dist/runner.js +1892 -0
  97. package/dist/sandbox.js +3 -0
  98. package/dist/sandboxgate.js +90 -0
  99. package/dist/scheduler.js +170 -0
  100. package/dist/services-main.js +131 -0
  101. package/dist/services.js +265 -0
  102. package/dist/session.js +241 -0
  103. package/dist/setup.js +423 -0
  104. package/dist/shell/decide.js +1 -0
  105. package/dist/shell/index.js +2 -0
  106. package/dist/shell/sandbox.js +1 -0
  107. package/dist/shell/wire.js +1 -0
  108. package/dist/skills.js +103 -0
  109. package/dist/state.js +1 -0
  110. package/dist/store.js +1 -0
  111. package/dist/switcher.js +1 -0
  112. package/dist/synth.js +418 -0
  113. package/dist/tools.js +477 -0
  114. package/dist/trials.js +223 -0
  115. package/dist/usage.js +1 -0
  116. package/dist/wait.js +167 -0
  117. package/dist/watchdog.js +476 -0
  118. package/dist/web-guidance.js +43 -0
  119. package/dist/which.js +20 -0
  120. package/dist/worktree/git.js +545 -0
  121. package/dist/writeguard.js +311 -0
  122. package/evolver/mm_evolve/__init__.py +1 -0
  123. package/evolver/mm_evolve/entry.py +3 -0
  124. package/evolver/mm_evolve/evaluator.py +119 -0
  125. package/evolver/mm_evolve/llm.py +76 -0
  126. package/evolver/mm_evolve/run.py +89 -0
  127. package/evolver/mm_evolve/spec.py +62 -0
  128. package/evolver/pyproject.toml +21 -0
  129. package/evolver/uv.lock +772 -0
  130. package/package.json +74 -4
  131. package/skills/THIRD_PARTY.md +58 -0
  132. package/skills/code-review/SKILL.md +46 -0
  133. package/skills/deck/SKILL.md +98 -0
  134. package/skills/deliberate/SKILL.md +39 -0
  135. package/skills/design/SKILL.md +150 -0
  136. package/skills/diagnosing-bugs/SKILL.md +75 -0
  137. package/skills/image/SKILL.md +66 -0
  138. package/skills/orchestrator/SKILL.md +107 -0
  139. package/skills/receiving-code-review/SKILL.md +36 -0
  140. package/skills/research/SKILL.md +18 -0
  141. package/skills/tdd/SKILL.md +56 -0
  142. package/skills/tdd/mocking.md +59 -0
  143. package/skills/tdd/tests.md +77 -0
  144. package/skills/verification-before-completion/SKILL.md +50 -0
  145. package/skills/video/SKILL.md +97 -0
  146. package/skills/web/SKILL.md +60 -0
@@ -0,0 +1,311 @@
1
+ // A1-T6: the plan boundary's guard on the tool calls themselves. Plan mode is a hard boundary (design.md, D10): the
2
+ // plan agent and the investigator it delegates to write only under <stateDir>/plan, and the obvious ways out of that
3
+ // directory in a shell command are refused before the command runs.
4
+ //
5
+ // This reads a path or a command, not what a program does. A shell line is not parsed: only the simple forms are seen
6
+ // (`cd ..`, `git checkout`, an absolute path spelled out), and the sandbox of A1-T7 is the barrier. What this adds is
7
+ // the cheap, readable refusal of the forms a model writes when it decides to change the project anyway.
8
+ //
9
+ // The target is resolved through the filesystem, not lexically: `realpath` of the nearest existing ancestor, with the
10
+ // part that does not exist yet appended in order. A symlink under the plan directory that points at the checkout is
11
+ // therefore seen for what it is, which a `resolve` would never show.
12
+ import { lstatSync, realpathSync } from "node:fs";
13
+ import { homedir, tmpdir } from "node:os";
14
+ import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
15
+ import { statePath } from "@omacode/core/paths";
16
+ // The tools that name a file they change. A `patch` with only patch text names nothing here and is left to the
17
+ // permission layer; the paths a model writes are the ones this guard can read.
18
+ const WRITE_TOOLS = new Set(["edit", "write", "patch"]);
19
+ const PATH_FIELDS = ["path", "filePath", "file", "filename"];
20
+ const PATH_LISTS = ["files", "paths"];
21
+ // A git subcommand that moves refs the user's own checkout shares. A plan reads the history; it never rewrites it.
22
+ const REFS = new Set(["checkout", "stash", "branch", "worktree", "config", "gc", "update-ref"]);
23
+ // The git options that take the next word, so the subcommand is found past them ("git -C dir checkout main").
24
+ const GIT_VALUE_OPTS = new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--config-env"]);
25
+ // Absolute paths that are not a place a command works in: the standard streams. Everything else absolute is checked,
26
+ // except the system temp directory, which is where a command writes its own scratch files.
27
+ const STREAMS = new Set(["/dev/null", "/dev/stdin", "/dev/stdout", "/dev/stderr"]);
28
+ // An absolute path with every symlink along it resolved, including the ones in the part that does not exist yet:
29
+ // `realpath` of the nearest existing ancestor, and the missing tail appended in order. A link that cannot be followed
30
+ // (its target is missing) is treated as that ancestor: its own directory resolves and its name stays a name, so
31
+ // nothing is followed through it. Never throws.
32
+ export function realish(path) {
33
+ let current = resolve(path);
34
+ const below = [];
35
+ for (;;) {
36
+ try {
37
+ const real = realpathSync(current);
38
+ return below.length ? join(real, ...below) : real;
39
+ }
40
+ catch {
41
+ // Not resolvable: missing, or a link whose target is missing.
42
+ }
43
+ let link = false;
44
+ try {
45
+ link = lstatSync(current).isSymbolicLink();
46
+ }
47
+ catch {
48
+ link = false;
49
+ }
50
+ const parent = dirname(current);
51
+ if (link) {
52
+ let up = parent;
53
+ try {
54
+ up = realpathSync(parent);
55
+ }
56
+ catch {
57
+ // The root itself is unreadable: use it as it is rather than guess.
58
+ }
59
+ return join(up, basename(current), ...below);
60
+ }
61
+ if (parent === current)
62
+ return join(current, ...below);
63
+ below.unshift(basename(current));
64
+ current = parent;
65
+ }
66
+ }
67
+ // Equals or lies under a resolved root, without a sibling whose name merely starts with the same characters:
68
+ // "/p/plan-old" is not "/p/plan".
69
+ export function insidePath(path, root) {
70
+ const p = resolve(path);
71
+ const r = resolve(root);
72
+ return p === r || p.startsWith(r.endsWith(sep) ? r : r + sep);
73
+ }
74
+ // Where a plan lives: <project>/<stateDir>/plan (statePath answers the directory's name, old or new).
75
+ export function planRoot(project) {
76
+ return statePath(project, "plan");
77
+ }
78
+ // Every path a call names: the single-valued fields and the list-valued ones, in that order. Nothing else in an
79
+ // input is a path; an unknown shape names nothing and is left to the permission layer.
80
+ export function writePaths(call) {
81
+ const out = [];
82
+ for (const field of PATH_FIELDS) {
83
+ const value = call.input[field];
84
+ if (typeof value === "string" && value.trim())
85
+ out.push(value);
86
+ }
87
+ for (const field of PATH_LISTS) {
88
+ const value = call.input[field];
89
+ if (Array.isArray(value))
90
+ for (const item of value)
91
+ if (typeof item === "string" && item.trim())
92
+ out.push(item);
93
+ }
94
+ return out;
95
+ }
96
+ // The guard itself: a pure answer for one call, so the hook stays a journal line and a throw. Nothing here blocks
97
+ // anything on its own; the caller turns `ok: false` into the tool's error and journals `advisory` without blocking.
98
+ export function writeGuard(call, scope) {
99
+ try {
100
+ const root = realish(scope.root);
101
+ const base = scope.directory === undefined ? undefined : realish(scope.directory);
102
+ if (WRITE_TOOLS.has(call.tool))
103
+ return writes(call, root, base);
104
+ if (call.tool === "shell")
105
+ return shell(call, root, base);
106
+ return { ok: true };
107
+ }
108
+ catch (err) {
109
+ // A throw here would become the tool's error anyway, but with no reason the journal can read. Failing closed is
110
+ // the boundary's rule (D10): a target this cannot resolve is refused, not waved through.
111
+ return {
112
+ ok: false,
113
+ reason: "a target the plan guard could not read",
114
+ message: `The plan guard could not read the target of this ${call.tool} call (${err instanceof Error ? err.message : String(err)}). Nothing was changed; use a path under the plan directory and say in the report what you wanted instead.`,
115
+ };
116
+ }
117
+ }
118
+ const refused = (reason, message) => ({ ok: false, reason, message });
119
+ function writes(call, root, base) {
120
+ const named = writePaths(call);
121
+ // Fail closed: a patch whose targets are inside its text, or a write tool whose input this guard cannot read, names
122
+ // no path it can check. Refusing is the boundary's rule; the message says which tool to use instead.
123
+ if (named.length === 0) {
124
+ return refused(`a ${call.tool} whose target cannot be read`, `This ${call.tool} call names no path this guard can check (the patch tool carries its targets inside the patch text). Plan mode changes nothing outside the plan directory, so it was refused; use edit or write with an explicit path under the plan directory.`);
125
+ }
126
+ for (const path of named) {
127
+ const expanded = homeward(path);
128
+ const target = realish(isAbsolute(expanded) ? expanded : resolve(base ?? process.cwd(), expanded));
129
+ if (!insidePath(target, root)) {
130
+ return refused("a write outside the plan root", `"${path}" resolves outside the plan directory (${root}). The project is read-only in plan mode, so this write was refused; write the plan and its artifacts under the plan directory, and say in the report what you wanted to change.`);
131
+ }
132
+ }
133
+ return { ok: true };
134
+ }
135
+ function shell(call, root, base) {
136
+ const command = typeof call.input.command === "string" ? call.input.command : "";
137
+ if (!command.trim())
138
+ return { ok: true };
139
+ const notes = [];
140
+ for (const words of segments(command)) {
141
+ for (let i = 0; i < words.length; i++) {
142
+ const word = opening(words[i]);
143
+ if (word === "cd") {
144
+ const target = words[i + 1];
145
+ // No argument goes home, `-` goes back to wherever the user was: both leave the plan root.
146
+ if (target === undefined || target === "-" || climbsOrLeaves(target, root)) {
147
+ return refused("a cd that leaves the plan root", `"${command.trim()}" changes directory out of the plan directory (${root}). A command outside the plan root sees the user's own checkout, which plan mode changes nothing of; stay in the plan directory or report what you need.`);
148
+ }
149
+ notes.push(`cd ${target} stays inside the plan directory`);
150
+ continue;
151
+ }
152
+ if (word === "git") {
153
+ const sub = gitSubcommand(words, i + 1);
154
+ if (sub !== undefined && REFS.has(sub)) {
155
+ return refused(`git ${sub}`, `"git ${sub}" moves refs that the user's own checkout shares with this worktree, and a plan changes nothing of the project. Read the history instead (git log, git show, git status).`);
156
+ }
157
+ continue;
158
+ }
159
+ if (word === "rm") {
160
+ const args = words.slice(i + 1).filter((w) => !w.startsWith("-"));
161
+ if (args.some((arg) => climbsOrLeaves(arg, root))) {
162
+ return refused("an rm that leaves the plan root", `"${command.trim()}" deletes outside the plan directory (${root}). Files there belong to the project, which plan mode changes nothing of; delete only what the plan itself wrote.`);
163
+ }
164
+ notes.push(`rm ${args.join(" ")} stays inside the plan directory, where deletion is allowed but not contained`);
165
+ continue;
166
+ }
167
+ }
168
+ // Last, so a path that belongs to a refused `cd`, `rm` or git command is named by that clearer refusal above.
169
+ for (const word of words) {
170
+ for (const abs of absolutePaths(word)) {
171
+ if (outside(abs, root, base)) {
172
+ return refused("an absolute path outside the plan root", `"${abs}" is outside the plan directory (${root}) and outside the session's own directory. A plan works in the plan directory; use a path there, or report what you need instead of reading or writing this one.`);
173
+ }
174
+ }
175
+ }
176
+ }
177
+ // The words this cannot read: it reads command text, not what a program does, so everything else is the sandbox's
178
+ // (A1-T7) to hold. What is named here is journalled, not blocked.
179
+ return notes.length ? { ok: true, advisory: notes.join("; ") } : { ok: true };
180
+ }
181
+ // A `~` is the user's home, which is outside the plan root and is refused by the same rule as any other outside path.
182
+ function homeward(path) {
183
+ if (path === "~")
184
+ return homedir();
185
+ if (path.startsWith("~/"))
186
+ return join(homedir(), path.slice(2));
187
+ return path;
188
+ }
189
+ // Whether a relative `cd`/`rm` argument climbs with `..`, or an absolute one points outside the root. A relative path
190
+ // without `..` stays where the command already is, so it cannot leave the root.
191
+ function climbsOrLeaves(word, root) {
192
+ const path = homeward(word);
193
+ if (path.split("/").includes(".."))
194
+ return true;
195
+ return isAbsolute(path) && !insidePath(realish(path), root);
196
+ }
197
+ // An absolute path outside the plan root and outside the session's own directory. The streams and the system temp
198
+ // directory are not places a command works in, so they are not refused.
199
+ function outside(path, root, base) {
200
+ if (!isAbsolute(path))
201
+ return false;
202
+ if (STREAMS.has(path))
203
+ return false;
204
+ const target = realish(path);
205
+ if (insidePath(target, root))
206
+ return false;
207
+ if (base !== undefined && insidePath(target, base))
208
+ return false;
209
+ return !insidePath(target, realish(tmpdir()));
210
+ }
211
+ // The simple commands a shell joins with `&&`, `||`, `;`, `|` and a newline, each as its words. Quotes keep a path in
212
+ // one piece; a backslash escapes the next character. Not a parser: a substitution or a heredoc is left alone, and the
213
+ // sandbox is what catches those.
214
+ function segments(command) {
215
+ const out = [];
216
+ let current = [];
217
+ let word = "";
218
+ let quoted;
219
+ let started = false;
220
+ const flush = () => {
221
+ if (started)
222
+ current.push(word);
223
+ word = "";
224
+ started = false;
225
+ };
226
+ const next = () => {
227
+ flush();
228
+ if (current.length)
229
+ out.push(current);
230
+ current = [];
231
+ };
232
+ for (let i = 0; i < command.length; i++) {
233
+ const c = command[i];
234
+ if (quoted !== undefined) {
235
+ if (c === quoted)
236
+ quoted = undefined;
237
+ else
238
+ word += c;
239
+ continue;
240
+ }
241
+ if (c === '"' || c === "'") {
242
+ quoted = c;
243
+ started = true;
244
+ continue;
245
+ }
246
+ if (c === "\\") {
247
+ i++;
248
+ if (i < command.length) {
249
+ word += command[i];
250
+ started = true;
251
+ }
252
+ continue;
253
+ }
254
+ if (c === " " || c === "\t" || c === "\r") {
255
+ flush();
256
+ continue;
257
+ }
258
+ if (c === "\n") {
259
+ next();
260
+ continue;
261
+ }
262
+ if (c === ";" || c === "|" || c === "&") {
263
+ next();
264
+ if (command[i + 1] === c)
265
+ i++;
266
+ continue;
267
+ }
268
+ word += c;
269
+ started = true;
270
+ }
271
+ next();
272
+ return out;
273
+ }
274
+ // A command name with a subshell's opening bracket in front of it: "(cd .." is a cd too.
275
+ function opening(word) {
276
+ return word.replace(/^[({]+/, "");
277
+ }
278
+ // The git subcommand, past the options that come before it. `-C <dir>` and the other value-taking options are
279
+ // stepped over with their value; anything else that starts with "-" is a flag on its own.
280
+ function gitSubcommand(words, from) {
281
+ for (let i = from; i < words.length; i++) {
282
+ const word = words[i];
283
+ if (word === "--")
284
+ return undefined;
285
+ if (word.startsWith("-")) {
286
+ if (!word.includes("=") && GIT_VALUE_OPTS.has(word))
287
+ i++;
288
+ continue;
289
+ }
290
+ return word;
291
+ }
292
+ return undefined;
293
+ }
294
+ // The absolute paths a word can name: the word itself, a redirection target ("2>/tmp/x"), and an option's value
295
+ // ("--out=/tmp/x").
296
+ function absolutePaths(word) {
297
+ const out = [];
298
+ let bare = word.replace(/^\d+(?=[<>])/, "");
299
+ bare = bare.replace(/^[<>]+/, "");
300
+ if (!bare)
301
+ return out;
302
+ if (isAbsolute(bare))
303
+ out.push(bare);
304
+ const eq = bare.indexOf("=");
305
+ if (eq > 0) {
306
+ const value = bare.slice(eq + 1);
307
+ if (isAbsolute(value))
308
+ out.push(value);
309
+ }
310
+ return out;
311
+ }
@@ -0,0 +1 @@
1
+ """micromanager's evolver: OpenEvolve run against a fitness contract (docs/design.md §26)."""
@@ -0,0 +1,3 @@
1
+ """The evaluator file OpenEvolve loads in its worker processes: a module with evaluate(program_path)."""
2
+
3
+ from mm_evolve.evaluator import evaluate # noqa: F401
@@ -0,0 +1,119 @@
1
+ """A fitness contract as OpenEvolve's evaluator.
2
+
3
+ Every candidate is measured in a fresh copy of the project: its checks first (the hard constraints; one failing scores
4
+ 0), then the contract's evaluator, whose MM_SCORE line must hold every score, keep every guard within its tolerance of
5
+ the baseline and say valid. combined_score is the first score's improvement over the baseline as a ratio (2.0: twice
6
+ as good), so OpenEvolve's selection follows the contract's direction. Each evaluation is appended to evals.jsonl,
7
+ which the plugin reads for progress.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import os
14
+ import shutil
15
+ import subprocess
16
+ import tempfile
17
+ import time
18
+ from pathlib import Path
19
+
20
+ from .spec import Spec, load
21
+
22
+ LINE = "MM_SCORE "
23
+
24
+
25
+ def parse_score(stdout: str) -> dict | None:
26
+ """The last MM_SCORE line as a dict; None when there is none or it is no JSON object."""
27
+ for line in reversed(stdout.splitlines()):
28
+ if line.strip().startswith(LINE):
29
+ try:
30
+ value = json.loads(line.strip()[len(LINE):])
31
+ except json.JSONDecodeError:
32
+ return None
33
+ return value if isinstance(value, dict) else None
34
+ return None
35
+
36
+
37
+ def worse(direction: str, base: float, now: float) -> float:
38
+ """How much worse now is than base, relative to base (absolute when base is 0); negative is better."""
39
+ d = now - base if direction == "min" else base - now
40
+ return d if base == 0 else d / abs(base)
41
+
42
+
43
+ def combined(spec: Spec, values: dict[str, float], baseline: dict[str, float] | None = None) -> float:
44
+ first = spec.scores[0]
45
+ base, now = (baseline if baseline is not None else spec.baseline).get(first.name), values.get(first.name)
46
+ if base is None or now is None:
47
+ return 0.0
48
+ if first.direction == "min":
49
+ return base / now if now > 0 else base / 1e-9
50
+ return now / base if base > 0 else now
51
+
52
+
53
+ def judge(spec: Spec, score: dict | None, code: int, timed_out: bool, baseline: dict[str, float] | None = None) -> dict:
54
+ """An evaluator run as metrics: invalid (0) on a timeout, an exit code, no line, valid false, a missing score or a
55
+ broken guard. baseline: what it is compared with (the quick stage has its own)."""
56
+ base = baseline if baseline is not None else spec.baseline
57
+ if timed_out:
58
+ return {"combined_score": 0.0, "valid": 0.0, "error": "the evaluator timed out"}
59
+ if code != 0:
60
+ return {"combined_score": 0.0, "valid": 0.0, "error": f"the evaluator exited {code}"}
61
+ if score is None:
62
+ return {"combined_score": 0.0, "valid": 0.0, "error": "no MM_SCORE line"}
63
+ values = {k: v for k, v in (score.get("scores") or {}).items() if isinstance(v, (int, float))}
64
+ if score.get("valid") is False:
65
+ return {"combined_score": 0.0, "valid": 0.0, "error": "the evaluator said invalid", **values}
66
+ missing = [s.name for s in spec.scores if s.name not in values]
67
+ if missing:
68
+ return {"combined_score": 0.0, "valid": 0.0, "error": f"missing {', '.join(missing)}", **values}
69
+ broken = [g.name for g in spec.guards if g.name in base and g.name in values and worse(g.direction, base[g.name], values[g.name]) > g.tolerance]
70
+ if broken:
71
+ return {"combined_score": 0.0, "valid": 0.0, "error": f"guard broken: {', '.join(broken)}", **values}
72
+ return {"combined_score": combined(spec, values, base), "valid": 1.0, **values}
73
+
74
+
75
+ def _run(spec: Spec, command: str, cwd: str, env: dict[str, str] | None = None) -> subprocess.CompletedProcess | None:
76
+ """A command in the candidate's directory, under the spec's runner (the sandbox); None on a timeout."""
77
+ prefix = [p.replace("{dir}", cwd) for p in spec.runner]
78
+ argv = [*prefix, "sh", "-c", command]
79
+ try:
80
+ return subprocess.run(argv, cwd=cwd, capture_output=True, text=True, timeout=spec.timeout_s, env={**os.environ, **(env or {})})
81
+ except subprocess.TimeoutExpired:
82
+ return None
83
+
84
+
85
+ def measure(spec: Spec, program_path: str, corpus: str = "visible", corpus_dir: str | None = None) -> dict:
86
+ """One candidate: copied into a fresh copy of the project, checked, then measured."""
87
+ d = tempfile.mkdtemp(prefix="mm-evolve-")
88
+ try:
89
+ shutil.copytree(spec.workdir, d, dirs_exist_ok=True, symlinks=True)
90
+ shutil.copy(program_path, os.path.join(d, spec.file))
91
+ for check in spec.checks:
92
+ r = _run(spec, check, d)
93
+ if r is None or r.returncode != 0:
94
+ return {"combined_score": 0.0, "valid": 0.0, "error": f"check failed: {check}"}
95
+ env = {"MM_CORPUS": corpus, **({"MM_CORPUS_DIR": corpus_dir} if corpus_dir else {})}
96
+ # The cascade: a slow evaluator's quick stage first. A candidate no better than today's code there scores
97
+ # below every one that went on (half its quick ratio), so the full minutes go to the promising ones only.
98
+ if spec.quick_evaluator and corpus == "visible":
99
+ q = _run(spec, spec.quick_evaluator, d, {**env, "MM_STAGE": "quick"})
100
+ quick = judge(spec, parse_score(q.stdout) if q else None, q.returncode if q else -1, q is None, spec.quick_baseline)
101
+ if quick["valid"] != 1.0 or quick["combined_score"] <= 1.0:
102
+ return {**quick, "combined_score": quick["combined_score"] * 0.5, "stage": 1.0}
103
+ r = _run(spec, spec.evaluator, d, env)
104
+ if r is None:
105
+ return judge(spec, None, -1, True)
106
+ return judge(spec, parse_score(r.stdout), r.returncode, False)
107
+ finally:
108
+ shutil.rmtree(d, ignore_errors=True)
109
+
110
+
111
+ def evaluate(program_path: str) -> dict:
112
+ """OpenEvolve's entry point: the spec is named by MM_EVOLVE_SPEC, since the evaluator runs in worker processes."""
113
+ spec = load(os.environ["MM_EVOLVE_SPEC"])
114
+ started = time.time()
115
+ metrics = measure(spec, program_path)
116
+ row = {"at": time.time(), "seconds": round(time.time() - started, 2), **{k: v for k, v in metrics.items() if k != "error"}, **({"error": metrics["error"]} if "error" in metrics else {})}
117
+ with open(Path(spec.output) / "evals.jsonl", "a") as f:
118
+ f.write(json.dumps(row) + "\n")
119
+ return {k: v for k, v in metrics.items() if isinstance(v, (int, float))}
@@ -0,0 +1,76 @@
1
+ """An OpenEvolve LLM backend that generates through OpenCode (`opencode run`).
2
+
3
+ The evolver needs no API key of its own: OpenCode's provider auth applies, and so does its cost accounting. The
4
+ plugin's summarizer agent has no tools, so a mutation is plain text. Each call's cost goes to llm.jsonl next to the
5
+ run's other files, which is how the plugin charges the job's budget (spike, 2026-10-26).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import json
12
+ import os
13
+ import subprocess
14
+ import time
15
+ from pathlib import Path
16
+
17
+ from openevolve.llm.base import LLMInterface
18
+
19
+ OPENCODE = os.environ.get("MM_OPENCODE_BIN", os.path.expanduser("~/.opencode/bin/opencode"))
20
+ AGENT = "summarizer"
21
+
22
+
23
+ def read_events(stdout: str) -> tuple[str, float, int]:
24
+ """The text, the cost and the tokens of one `opencode run --format json` answer."""
25
+ text, cost, tokens = [], 0.0, 0
26
+ for line in stdout.splitlines():
27
+ try:
28
+ e = json.loads(line)
29
+ except json.JSONDecodeError:
30
+ continue
31
+ part = e.get("part") or {}
32
+ if e.get("type") == "text":
33
+ text.append(part.get("text", ""))
34
+ elif e.get("type") == "step_finish":
35
+ cost += part.get("cost") or 0
36
+ t = part.get("tokens") or {}
37
+ tokens += (t.get("input") or 0) + (t.get("output") or 0) + (t.get("reasoning") or 0)
38
+ return "".join(text), cost, tokens
39
+
40
+
41
+ class OpenCodeLLM(LLMInterface):
42
+ def __init__(self, model_cfg=None):
43
+ self.model = getattr(model_cfg, "name", None) or "opencode-go/glm-5.3-flash"
44
+ self.timeout = getattr(model_cfg, "timeout", None) or 300
45
+ self.system_message = getattr(model_cfg, "system_message", None)
46
+ self.server = os.environ.get("MM_OPENCODE_SERVER", "http://127.0.0.1:4096")
47
+ self.workdir = os.environ.get("MM_OPENCODE_DIR", os.getcwd())
48
+ self.log = os.environ.get("MM_EVOLVE_LLM_LOG")
49
+
50
+ async def generate(self, prompt: str, **kwargs) -> str:
51
+ system = kwargs.pop("system_message", self.system_message) or ""
52
+ return await self.generate_with_context(system, [{"role": "user", "content": prompt}], **kwargs)
53
+
54
+ async def generate_with_context(self, system_message: str, messages: list[dict], **kwargs) -> str:
55
+ user = "\n\n".join(m.get("content", "") for m in messages if m.get("role") == "user")
56
+ prompt = f"{system_message}\n\n{user}" if system_message else user
57
+ return await asyncio.get_running_loop().run_in_executor(None, self._call, prompt)
58
+
59
+ def _call(self, prompt: str) -> str:
60
+ cmd = [OPENCODE, "run", "--server", self.server, "--agent", AGENT, "--model", self.model, "--format", "json", "--title", "[evolve] mutation", prompt]
61
+ started = time.time()
62
+ # OpenCode places the session by the client's PWD, not its working directory (live run, 2026-10-26), and reads
63
+ # stdin when it is no terminal: in OpenEvolve's worker processes it waited for an end of input that never came.
64
+ r = subprocess.run(cmd, capture_output=True, text=True, timeout=self.timeout, cwd=self.workdir, env={**os.environ, "PWD": self.workdir}, stdin=subprocess.DEVNULL)
65
+ text, cost, tokens = read_events(r.stdout)
66
+ if self.log:
67
+ with open(Path(self.log), "a") as f:
68
+ f.write(json.dumps({"at": time.time(), "model": self.model, "seconds": round(time.time() - started, 1), "cost": cost, "tokens": tokens, "ok": bool(text)}) + "\n")
69
+ if not text:
70
+ raise RuntimeError(f"no answer from opencode ({self.model}): {r.stderr[-300:]}")
71
+ return text
72
+
73
+
74
+ def init_opencode_client(model_cfg):
75
+ """OpenEvolve's init_client hook."""
76
+ return OpenCodeLLM(model_cfg)
@@ -0,0 +1,89 @@
1
+ """mm-evolve <spec.json>: one evolver run. Writes evals.jsonl and llm.jsonl as it goes and result.json at the end:
2
+ the best program, its metrics, its held-out measurement (taken once, for the best only, so the evolution never sees
3
+ the held-out cases), and what the run cost."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import json
8
+ import os
9
+ import sys
10
+ import time
11
+ from pathlib import Path
12
+
13
+ from .evaluator import measure
14
+ from .spec import load
15
+
16
+
17
+ def config_for(spec):
18
+ from openevolve.config import Config, LLMModelConfig
19
+
20
+ from .llm import init_opencode_client
21
+
22
+ cfg = Config()
23
+ cfg.language = os.path.splitext(spec.file)[1].lstrip(".") or None
24
+ models = [LLMModelConfig(name=m["name"], weight=float(m.get("weight", 1.0)), timeout=int(m.get("timeout", 300))) for m in spec.models]
25
+ cfg.llm.models = models
26
+ cfg.llm.evaluator_models = models
27
+ if spec.api_base:
28
+ # OpenEvolve's own OpenAI client against the plugin's bridge.
29
+ cfg.llm.update_model_params({"api_base": spec.api_base, "api_key": spec.api_key or "none"})
30
+ else:
31
+ cfg.llm.update_model_params({"init_client": init_opencode_client})
32
+ cfg.diff_based_evolution = not spec.full_rewrite
33
+ cfg.database.num_islands = 2
34
+ cfg.evaluator.parallel_evaluations = 1 # one measurement at a time: parallel timings disturb each other
35
+ cfg.evaluator.cascade_evaluation = False # the checks and the quick stage are the cascade, inside measure()
36
+ # OpenEvolve stops an evaluation after its own timeout (300 s by default), which a multi-step algorithm of minutes
37
+ # outlasts: room for every check, the quick stage and the full run, each bounded by the contract's timeout.
38
+ cfg.evaluator.timeout = int(spec.timeout_s * (len(spec.checks) + (2 if spec.quick_evaluator else 1)) + 60)
39
+ cfg.max_iterations = spec.iterations
40
+ return cfg
41
+
42
+
43
+ def target_score(spec) -> float | None:
44
+ """The contract's target on the deciding score, as a combined_score."""
45
+ first = spec.scores[0]
46
+ goal, base = spec.target.get(first.name), spec.baseline.get(first.name)
47
+ if goal is None or base is None or goal == 0:
48
+ return None
49
+ return base / goal if first.direction == "min" else goal / base
50
+
51
+
52
+ def main(argv: list[str] | None = None) -> int:
53
+ args = argv if argv is not None else sys.argv[1:]
54
+ if len(args) != 1:
55
+ print("usage: mm-evolve <spec.json>", file=sys.stderr)
56
+ return 2
57
+ spec_path = str(Path(args[0]).resolve())
58
+ spec = load(spec_path)
59
+ out = Path(spec.output)
60
+ out.mkdir(parents=True, exist_ok=True)
61
+ os.environ["MM_EVOLVE_SPEC"] = spec_path
62
+ os.environ["MM_EVOLVE_LLM_LOG"] = str(out / "llm.jsonl")
63
+ os.environ.setdefault("MM_OPENCODE_SERVER", spec.server)
64
+ os.environ.setdefault("MM_OPENCODE_DIR", spec.workdir)
65
+ from openevolve import run_evolution
66
+
67
+ started = time.time()
68
+ res = run_evolution(spec.initial, str(Path(__file__).with_name("entry.py")), config_for(spec), iterations=spec.iterations, output_dir=str(out / "openevolve"), cleanup=False, target_score=target_score(spec))
69
+ best = out / f"best{Path(spec.file).suffix}"
70
+ best.write_text(res.best_code)
71
+ held = measure(spec, str(best), "heldout", spec.held_out_dir) if spec.held_out_dir else None
72
+ llm = [json.loads(l) for l in (out / "llm.jsonl").read_text().splitlines()] if (out / "llm.jsonl").exists() else []
73
+ result = {
74
+ "best": str(best),
75
+ "metrics": res.metrics,
76
+ "heldOut": held,
77
+ "calls": len(llm),
78
+ "failedCalls": sum(1 for c in llm if not c.get("ok")),
79
+ "cost": round(sum(c.get("cost", 0) for c in llm), 6),
80
+ "tokens": sum(c.get("tokens", 0) for c in llm),
81
+ "seconds": round(time.time() - started),
82
+ }
83
+ (out / "result.json").write_text(json.dumps(result, indent=2))
84
+ print(f"MM_EVOLVE {json.dumps(result)}", flush=True)
85
+ return 0
86
+
87
+
88
+ if __name__ == "__main__":
89
+ sys.exit(main())
@@ -0,0 +1,62 @@
1
+ """The run's spec, as the plugin writes it (src/evolver.ts): what evolves, what measures it, which models think."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class Score:
12
+ name: str
13
+ direction: str # "min" or "max"
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class Guard:
18
+ name: str
19
+ direction: str
20
+ tolerance: float
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class Spec:
25
+ workdir: str # a copy of the project directory at the job's branch; candidates are measured in copies of it
26
+ file: str # the evolving file, relative to workdir
27
+ initial: str # that file with EVOLVE-BLOCK markers around what may change
28
+ checks: list[str] # the task's checks: hard constraints, a failing one scores 0
29
+ evaluator: str # the contract's evaluator command, printing one MM_SCORE line
30
+ scores: list[Score] # the first decides
31
+ guards: list[Guard]
32
+ baseline: dict[str, float] # the contract's baseline on the visible corpus
33
+ output: str # where the run writes evals.jsonl, llm.jsonl and result.json
34
+ models: list[dict] = field(default_factory=lambda: [{"name": "opencode-go/glm-5.3-flash", "weight": 1.0}])
35
+ server: str = "http://127.0.0.1:4096" # the OpenCode server the models are reached through (`opencode run`)
36
+ # Or an OpenAI-compatible endpoint: the plugin's own bridge (src/evolver.ts), which generates through its session
37
+ # API and charges the job; the key is the bridge's one-run token. When set, `server` is not used.
38
+ api_base: str | None = None
39
+ api_key: str | None = None
40
+ iterations: int = 20
41
+ timeout_s: float = 300.0 # per evaluator run
42
+ target: dict[str, float] = field(default_factory=dict) # the contract's stop.target
43
+ full_rewrite: bool = False # whole-program answers instead of diffs (cheap models often miss the diff format)
44
+ held_out_dir: str | None = None # measured once, for the best candidate only
45
+ # The contract's quick stage (a slow evaluator's cascade): the same scores on small instances, against its own
46
+ # baseline. A candidate gets the full measurement only when it is better there.
47
+ quick_evaluator: str | None = None
48
+ quick_baseline: dict[str, float] = field(default_factory=dict)
49
+ # The command prefix every candidate command runs under: the plugin's sandbox. "{dir}" is the candidate's
50
+ # directory. Empty: unsandboxed, for tests only.
51
+ runner: list[str] = field(default_factory=list)
52
+
53
+
54
+ def load(path: str | Path) -> Spec:
55
+ raw = json.loads(Path(path).read_text())
56
+ return Spec(
57
+ **{
58
+ **raw,
59
+ "scores": [Score(**s) for s in raw["scores"]],
60
+ "guards": [Guard(**g) for g in raw.get("guards", [])],
61
+ }
62
+ )