@omacode/micromanager 0.0.0-stage → 0.1.1

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 (109) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +27 -2
  3. package/evolver/mm_evolve/__init__.py +1 -0
  4. package/evolver/mm_evolve/entry.py +3 -0
  5. package/evolver/mm_evolve/evaluator.py +119 -0
  6. package/evolver/mm_evolve/llm.py +76 -0
  7. package/evolver/mm_evolve/run.py +89 -0
  8. package/evolver/mm_evolve/spec.py +62 -0
  9. package/evolver/pyproject.toml +21 -0
  10. package/evolver/uv.lock +772 -0
  11. package/package.json +55 -4
  12. package/skills/THIRD_PARTY.md +58 -0
  13. package/skills/code-review/SKILL.md +46 -0
  14. package/skills/deliberate/SKILL.md +39 -0
  15. package/skills/diagnosing-bugs/SKILL.md +75 -0
  16. package/skills/receiving-code-review/SKILL.md +36 -0
  17. package/skills/research/SKILL.md +18 -0
  18. package/skills/tdd/SKILL.md +56 -0
  19. package/skills/tdd/mocking.md +59 -0
  20. package/skills/tdd/tests.md +77 -0
  21. package/skills/verification-before-completion/SKILL.md +50 -0
  22. package/src/agenda.ts +56 -0
  23. package/src/agents.ts +74 -0
  24. package/src/ask.ts +243 -0
  25. package/src/backends.ts +144 -0
  26. package/src/backlog.ts +436 -0
  27. package/src/bench.ts +163 -0
  28. package/src/board.ts +1 -0
  29. package/src/brief.ts +151 -0
  30. package/src/browser.ts +624 -0
  31. package/src/budget.ts +73 -0
  32. package/src/catalog.ts +214 -0
  33. package/src/checkchange.ts +180 -0
  34. package/src/checkpoint.ts +99 -0
  35. package/src/cli.ts +117 -0
  36. package/src/compact.ts +162 -0
  37. package/src/config.ts +340 -0
  38. package/src/context/capture.ts +1 -0
  39. package/src/context/digest.ts +1 -0
  40. package/src/context/embed.ts +1 -0
  41. package/src/context/index.ts +2 -0
  42. package/src/context/ledger.ts +1 -0
  43. package/src/context/manager.ts +1 -0
  44. package/src/context/memory.ts +1 -0
  45. package/src/context/policy.ts +1 -0
  46. package/src/context/prices.ts +1 -0
  47. package/src/context/recall.ts +1 -0
  48. package/src/context/rules.ts +1 -0
  49. package/src/context/search.ts +1 -0
  50. package/src/context/status.ts +1 -0
  51. package/src/context/store.ts +1 -0
  52. package/src/context/summary.ts +1 -0
  53. package/src/context/tokens.ts +1 -0
  54. package/src/context/tools.ts +1 -0
  55. package/src/continuation.ts +122 -0
  56. package/src/contract.ts +342 -0
  57. package/src/contractround.ts +225 -0
  58. package/src/control.ts +1 -0
  59. package/src/dataset.ts +133 -0
  60. package/src/decide.ts +690 -0
  61. package/src/eval.ts +66 -0
  62. package/src/evolver.ts +369 -0
  63. package/src/followups.ts +50 -0
  64. package/src/forms.ts +191 -0
  65. package/src/gate.ts +90 -0
  66. package/src/grants.ts +239 -0
  67. package/src/graph.ts +74 -0
  68. package/src/guard/index.ts +1 -0
  69. package/src/guard/wire.ts +1 -0
  70. package/src/helpers.ts +105 -0
  71. package/src/hooks.ts +199 -0
  72. package/src/integration.ts +4 -0
  73. package/src/jev.ts +141 -0
  74. package/src/journal.ts +1 -0
  75. package/src/look.ts +390 -0
  76. package/src/memory.ts +1 -0
  77. package/src/native.ts +2455 -0
  78. package/src/nogit.ts +112 -0
  79. package/src/outcomes.ts +210 -0
  80. package/src/pick.ts +112 -0
  81. package/src/pipelines.ts +252 -0
  82. package/src/plan.ts +449 -0
  83. package/src/plugin.ts +3187 -0
  84. package/src/policy.ts +84 -0
  85. package/src/pools.ts +1 -0
  86. package/src/profile.ts +186 -0
  87. package/src/progress.ts +1 -0
  88. package/src/redact.ts +1 -0
  89. package/src/registry.ts +207 -0
  90. package/src/roles.ts +1 -0
  91. package/src/routing.ts +1 -0
  92. package/src/runner.ts +1506 -0
  93. package/src/sandbox.ts +4 -0
  94. package/src/scheduler.ts +200 -0
  95. package/src/session.ts +269 -0
  96. package/src/shell/decide.ts +1 -0
  97. package/src/shell/index.ts +2 -0
  98. package/src/shell/sandbox.ts +1 -0
  99. package/src/shell/wire.ts +1 -0
  100. package/src/skills.ts +111 -0
  101. package/src/state.ts +1 -0
  102. package/src/store.ts +1 -0
  103. package/src/switcher.ts +1 -0
  104. package/src/tools.ts +480 -0
  105. package/src/trials.ts +247 -0
  106. package/src/usage.ts +1 -0
  107. package/src/wait.ts +180 -0
  108. package/src/watchdog.ts +498 -0
  109. package/src/worktree/git.ts +378 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,28 @@
1
- # Temporary Holding Version
1
+ # @omacode/micromanager
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An OpenCode plugin that turns one chat into a job: it plans with you, splits the work into tasks, runs each task in
4
+ its own worktree with a role-scoped worker, reviews the result and merges what passes.
5
+
6
+ ```bash
7
+ opencode plugin add @omacode/micromanager # the orchestrator alone
8
+ opencode plugin add @omacode/full # orchestrator + guard + sandbox + context
9
+ ```
10
+
11
+ The orchestrator delegates; it never edits files or runs commands itself. Every worker runs under a role
12
+ (`explorer`, `coder`, `tester`, `designer`, `writer`, `debugger`, `reviewer`, `oracle`), asks the permission layer for
13
+ what it needs, and reports back against acceptance points. A watchdog catches loops, a checkpoint hands stuck tasks
14
+ back, and a merge train waits for the checks.
15
+
16
+ ## What it needs
17
+
18
+ - OpenCode v2 and Node.js 22.12 or later.
19
+ - On Linux, the sandbox uses `bubblewrap`, `socat` and `ripgrep`; without them the plugin still runs, unwrapped.
20
+ - The decision model (Jev) is configured under `jev` in `micromanager.jsonc`; a local decision server can replace it
21
+ for the local-first guards.
22
+
23
+ Configuration, the job flow, the roles and the design notes live in the repository:
24
+ <https://github.com/RentschlerTobias/Omacode#readme>.
25
+
26
+ ## License
27
+
28
+ Apache-2.0. See `LICENSE` in the package.
@@ -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
+ )
@@ -0,0 +1,21 @@
1
+ [project]
2
+ name = "mm-evolver"
3
+ version = "0.1.0"
4
+ description = "OpenEvolve as micromanager's evolver: a fitness contract's evaluator, models through OpenCode"
5
+ requires-python = ">=3.12"
6
+ dependencies = [
7
+ "openevolve==0.4.0",
8
+ ]
9
+
10
+ [project.scripts]
11
+ mm-evolve = "mm_evolve.run:main"
12
+
13
+ [dependency-groups]
14
+ dev = ["pytest>=8"]
15
+
16
+ [build-system]
17
+ requires = ["hatchling"]
18
+ build-backend = "hatchling.build"
19
+
20
+ [tool.hatch.build.targets.wheel]
21
+ packages = ["mm_evolve"]