@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.
- package/LICENSE +201 -0
- package/README.md +30 -2
- package/THIRD_PARTY.md +100 -0
- package/decider/.python-version +1 -0
- package/decider/README.md +35 -0
- package/decider/decider/__init__.py +1 -0
- package/decider/decider/server.py +327 -0
- package/decider/pyproject.toml +34 -0
- package/decider/uv.lock +1255 -0
- package/dist/agenda.js +51 -0
- package/dist/agents.js +58 -0
- package/dist/artifact/handoff.js +281 -0
- package/dist/ask.js +200 -0
- package/dist/backends.js +219 -0
- package/dist/backlog.js +414 -0
- package/dist/bench.js +427 -0
- package/dist/board.js +1 -0
- package/dist/brief.js +202 -0
- package/dist/browser.js +679 -0
- package/dist/budget.js +61 -0
- package/dist/catalog.js +187 -0
- package/dist/checkchange.js +145 -0
- package/dist/checkpoint.js +94 -0
- package/dist/cli.js +764 -0
- package/dist/comfy-gate.js +258 -0
- package/dist/compact.js +142 -0
- package/dist/config.js +344 -0
- package/dist/context/capture.js +1 -0
- package/dist/context/digest.js +1 -0
- package/dist/context/embed.js +1 -0
- package/dist/context/index.js +2 -0
- package/dist/context/ledger.js +1 -0
- package/dist/context/manager.js +1 -0
- package/dist/context/memory.js +1 -0
- package/dist/context/policy.js +1 -0
- package/dist/context/prices.js +1 -0
- package/dist/context/recall.js +1 -0
- package/dist/context/rules.js +1 -0
- package/dist/context/search.js +1 -0
- package/dist/context/status.js +1 -0
- package/dist/context/store.js +1 -0
- package/dist/context/summary.js +1 -0
- package/dist/context/tokens.js +1 -0
- package/dist/context/tools.js +1 -0
- package/dist/continuation.js +184 -0
- package/dist/contract.js +294 -0
- package/dist/contractround.js +178 -0
- package/dist/control.js +1 -0
- package/dist/creative-tools.js +237 -0
- package/dist/dataset.js +175 -0
- package/dist/decide.js +676 -0
- package/dist/decider.js +171 -0
- package/dist/design-shell.js +448 -0
- package/dist/design.js +1410 -0
- package/dist/desktop.js +44 -0
- package/dist/egress.js +156 -0
- package/dist/eval.js +60 -0
- package/dist/evolver.js +302 -0
- package/dist/features.js +193 -0
- package/dist/followups.js +32 -0
- package/dist/forms.js +195 -0
- package/dist/gate.js +108 -0
- package/dist/gatebox.js +46 -0
- package/dist/grants.js +189 -0
- package/dist/graph.js +65 -0
- package/dist/guard/index.js +1 -0
- package/dist/guard/wire.js +1 -0
- package/dist/helpers.js +85 -0
- package/dist/hooks.js +158 -0
- package/dist/image-models.js +117 -0
- package/dist/integration.js +3 -0
- package/dist/journal.js +1 -0
- package/dist/look.js +363 -0
- package/dist/memory.js +1 -0
- package/dist/mode.js +97 -0
- package/dist/native.js +3348 -0
- package/dist/nogit.js +259 -0
- package/dist/outcomes.js +148 -0
- package/dist/permission.js +35 -0
- package/dist/pick.js +89 -0
- package/dist/pipelines.js +262 -0
- package/dist/plan.js +641 -0
- package/dist/plandoc.js +211 -0
- package/dist/plugin.js +4736 -0
- package/dist/policy.js +58 -0
- package/dist/pools.js +1 -0
- package/dist/preview.js +274 -0
- package/dist/profile.js +165 -0
- package/dist/progress.js +1 -0
- package/dist/promote.js +313 -0
- package/dist/redact.js +1 -0
- package/dist/registry.js +179 -0
- package/dist/riskscore.js +126 -0
- package/dist/roles.js +1 -0
- package/dist/routing.js +1 -0
- package/dist/runner.js +1892 -0
- package/dist/sandbox.js +3 -0
- package/dist/sandboxgate.js +90 -0
- package/dist/scheduler.js +170 -0
- package/dist/services-main.js +131 -0
- package/dist/services.js +265 -0
- package/dist/session.js +241 -0
- package/dist/setup.js +423 -0
- package/dist/shell/decide.js +1 -0
- package/dist/shell/index.js +2 -0
- package/dist/shell/sandbox.js +1 -0
- package/dist/shell/wire.js +1 -0
- package/dist/skills.js +103 -0
- package/dist/state.js +1 -0
- package/dist/store.js +1 -0
- package/dist/switcher.js +1 -0
- package/dist/synth.js +418 -0
- package/dist/tools.js +477 -0
- package/dist/trials.js +223 -0
- package/dist/usage.js +1 -0
- package/dist/wait.js +167 -0
- package/dist/watchdog.js +476 -0
- package/dist/web-guidance.js +43 -0
- package/dist/which.js +20 -0
- package/dist/worktree/git.js +545 -0
- package/dist/writeguard.js +311 -0
- package/evolver/mm_evolve/__init__.py +1 -0
- package/evolver/mm_evolve/entry.py +3 -0
- package/evolver/mm_evolve/evaluator.py +119 -0
- package/evolver/mm_evolve/llm.py +76 -0
- package/evolver/mm_evolve/run.py +89 -0
- package/evolver/mm_evolve/spec.py +62 -0
- package/evolver/pyproject.toml +21 -0
- package/evolver/uv.lock +772 -0
- package/package.json +74 -4
- package/skills/THIRD_PARTY.md +58 -0
- package/skills/code-review/SKILL.md +46 -0
- package/skills/deck/SKILL.md +98 -0
- package/skills/deliberate/SKILL.md +39 -0
- package/skills/design/SKILL.md +150 -0
- package/skills/diagnosing-bugs/SKILL.md +75 -0
- package/skills/image/SKILL.md +66 -0
- package/skills/orchestrator/SKILL.md +107 -0
- package/skills/receiving-code-review/SKILL.md +36 -0
- package/skills/research/SKILL.md +18 -0
- package/skills/tdd/SKILL.md +56 -0
- package/skills/tdd/mocking.md +59 -0
- package/skills/tdd/tests.md +77 -0
- package/skills/verification-before-completion/SKILL.md +50 -0
- package/skills/video/SKILL.md +97 -0
- package/skills/web/SKILL.md +60 -0
package/dist/contract.js
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
// The fitness contract (design.md §25): what "better" means for a task that has no fixed end state ("make the search
|
|
2
|
+
// faster", "make meshing more reliable"), settled before a worker spends anything on it. A build task is done when its
|
|
3
|
+
// checks pass; an optimization task is never done that way, so it needs a number with a direction, a baseline to
|
|
4
|
+
// compare with, and guards against raising the number without improving the goal.
|
|
5
|
+
//
|
|
6
|
+
// The contract is the same for every domain and every search method: a single worker, a trial (the best score wins
|
|
7
|
+
// among the green attempts), and later lanes or an evolver. Its evaluator is one shell command that prints one line
|
|
8
|
+
// MM_SCORE {"valid":true,"scores":{"p50_ms":12.3},"cases":{"passed":7,"total":8},"category":"…"}
|
|
9
|
+
// and anything else -- a non-zero exit, a timeout, no such line, "valid":false, a score the contract names missing --
|
|
10
|
+
// makes the result invalid, which scores below everything (the hard constraints).
|
|
11
|
+
import { createHash } from "node:crypto";
|
|
12
|
+
import { cpSync, existsSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
|
|
13
|
+
import { isAbsolute, join, relative, resolve } from "node:path";
|
|
14
|
+
import { checkProblem, checkSafetyProblem } from "./plan.js";
|
|
15
|
+
import { heldOutRoot } from "@omacode/core/heldout";
|
|
16
|
+
import { projectId } from "@omacode/core/project";
|
|
17
|
+
// A line that starts like one but holds no JSON object is a broken result, not output to skip.
|
|
18
|
+
const LINE = /^MM_SCORE\s+(.*)$/;
|
|
19
|
+
// The last MM_SCORE line of a run's output, read as a measurement. Undefined when there is none: for an ordinary check
|
|
20
|
+
// that means nothing was graded, for an evaluator that the result is invalid.
|
|
21
|
+
export function parseScoreLines(stdout) {
|
|
22
|
+
const line = stdout.split("\n").map((l) => l.trim()).filter((l) => LINE.test(l)).at(-1);
|
|
23
|
+
if (!line)
|
|
24
|
+
return undefined;
|
|
25
|
+
let o;
|
|
26
|
+
try {
|
|
27
|
+
o = JSON.parse(line.match(LINE)[1]);
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return { valid: false, values: {}, error: "the MM_SCORE line is no JSON object" };
|
|
31
|
+
}
|
|
32
|
+
const values = {};
|
|
33
|
+
for (const [k, v] of Object.entries((o.scores ?? {})))
|
|
34
|
+
if (typeof v === "number" && Number.isFinite(v))
|
|
35
|
+
values[k] = v;
|
|
36
|
+
const c = o.cases;
|
|
37
|
+
const cases = c && typeof c.passed === "number" && typeof c.total === "number" && c.total > 0 ? { passed: c.passed, total: c.total } : undefined;
|
|
38
|
+
return {
|
|
39
|
+
valid: o.valid !== false,
|
|
40
|
+
values,
|
|
41
|
+
...(cases ? { cases } : {}),
|
|
42
|
+
...(typeof o.category === "string" && o.category ? { category: o.category.slice(0, 80) } : {}),
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
// One evaluator run as a measurement: the hard constraints first, then the line itself.
|
|
46
|
+
export function measuredOf(contract, run) {
|
|
47
|
+
if (run.timedOut)
|
|
48
|
+
return { valid: false, values: {}, error: `the evaluator timed out after ${Math.round(contract.timeoutMs / 1000)}s` };
|
|
49
|
+
const m = parseScoreLines(run.stdout);
|
|
50
|
+
if (run.code !== 0)
|
|
51
|
+
return { valid: false, values: m?.values ?? {}, ...(m?.category ? { category: m.category } : {}), error: `the evaluator exited ${run.code}: ${`${run.stderr}`.trim().slice(-300) || "no output"}` };
|
|
52
|
+
if (!m)
|
|
53
|
+
return { valid: false, values: {}, error: "the evaluator printed no MM_SCORE line" };
|
|
54
|
+
if (!m.valid)
|
|
55
|
+
return { ...m, error: m.error ?? `the evaluator reported the result invalid${m.category ? ` (${m.category})` : ""}` };
|
|
56
|
+
const missing = contract.scores.map((s) => s.name).filter((n) => !(n in m.values));
|
|
57
|
+
if (missing.length)
|
|
58
|
+
return { ...m, valid: false, error: `the MM_SCORE line lacks ${missing.join(", ")}` };
|
|
59
|
+
return m;
|
|
60
|
+
}
|
|
61
|
+
// Repeated runs as one measurement: any invalid run makes it invalid (a crash that happens once in three is a crash),
|
|
62
|
+
// and each value is the median of its runs.
|
|
63
|
+
export function median(runs) {
|
|
64
|
+
const bad = runs.find((r) => !r.valid);
|
|
65
|
+
if (bad || !runs.length)
|
|
66
|
+
return bad ?? { valid: false, values: {}, error: "nothing was measured" };
|
|
67
|
+
const mid = (xs) => {
|
|
68
|
+
const s = [...xs].sort((a, b) => a - b);
|
|
69
|
+
return s.length % 2 ? s[(s.length - 1) / 2] : (s[s.length / 2 - 1] + s[s.length / 2]) / 2;
|
|
70
|
+
};
|
|
71
|
+
const values = {};
|
|
72
|
+
for (const k of Object.keys(runs[0].values)) {
|
|
73
|
+
const xs = runs.map((r) => r.values[k]).filter((v) => v !== undefined);
|
|
74
|
+
if (xs.length === runs.length)
|
|
75
|
+
values[k] = mid(xs);
|
|
76
|
+
}
|
|
77
|
+
const last = runs.at(-1);
|
|
78
|
+
return { valid: true, values, ...(last.cases ? { cases: last.cases } : {}), ...(last.category ? { category: last.category } : {}) };
|
|
79
|
+
}
|
|
80
|
+
// How much worse b is than a for a value with this direction, relative to a (absolute when a is 0); negative: better.
|
|
81
|
+
function worse(direction, a, b) {
|
|
82
|
+
const d = direction === "min" ? b - a : a - b;
|
|
83
|
+
return a === 0 ? d : d / Math.abs(a);
|
|
84
|
+
}
|
|
85
|
+
// The guards a measurement breaks against the baseline. Without a baseline there is nothing to compare with.
|
|
86
|
+
export function guardViolations(c, m) {
|
|
87
|
+
if (!c.baseline)
|
|
88
|
+
return [];
|
|
89
|
+
return c.guards.flatMap((g) => {
|
|
90
|
+
const base = c.baseline.values[g.name];
|
|
91
|
+
const now = m.values[g.name];
|
|
92
|
+
if (base === undefined)
|
|
93
|
+
return [];
|
|
94
|
+
if (now === undefined)
|
|
95
|
+
return [`${g.name} was not measured`];
|
|
96
|
+
const by = worse(g.direction, base, now);
|
|
97
|
+
return by > g.tolerance ? [`${g.name} is ${fmt(now)}, worse than the baseline ${fmt(base)} by more than ${Math.round(g.tolerance * 100)} %`] : [];
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
// Which of two measurements is better under the contract: > 0 when a is, < 0 when b is, 0 when they count as equal.
|
|
101
|
+
// An invalid result loses to any valid one; the scores decide in their order, each inside its noise band.
|
|
102
|
+
export function better(c, a, b) {
|
|
103
|
+
if (a.valid !== b.valid)
|
|
104
|
+
return a.valid ? 1 : -1;
|
|
105
|
+
if (!a.valid)
|
|
106
|
+
return 0;
|
|
107
|
+
for (const s of c.scores) {
|
|
108
|
+
const x = a.values[s.name];
|
|
109
|
+
const y = b.values[s.name];
|
|
110
|
+
if (x === undefined || y === undefined)
|
|
111
|
+
continue;
|
|
112
|
+
const scale = Math.max(Math.abs(x), Math.abs(y));
|
|
113
|
+
if (scale === 0 || Math.abs(x - y) / scale <= (s.noise ?? 0))
|
|
114
|
+
continue;
|
|
115
|
+
return (s.direction === "min" ? y - x : x - y) > 0 ? 1 : -1;
|
|
116
|
+
}
|
|
117
|
+
return 0;
|
|
118
|
+
}
|
|
119
|
+
// The primary score's improvement over the baseline, signed so that better is positive: the reward the outcome log
|
|
120
|
+
// keeps for the router. 0 for an invalid result; undefined without a baseline to compare with.
|
|
121
|
+
export function reward(c, m) {
|
|
122
|
+
if (!m.valid)
|
|
123
|
+
return 0;
|
|
124
|
+
const s = c.scores[0];
|
|
125
|
+
const base = s && c.baseline?.values[s.name];
|
|
126
|
+
const now = s && m.values[s.name];
|
|
127
|
+
if (base === undefined || now === undefined)
|
|
128
|
+
return undefined;
|
|
129
|
+
return Math.round(-worse(s.direction, base, now) * 1e4) / 1e4;
|
|
130
|
+
}
|
|
131
|
+
// What a worker may hear of a held-out measurement: how many cases passed, or the category, never values per case.
|
|
132
|
+
export function coarse(m) {
|
|
133
|
+
if (m.cases)
|
|
134
|
+
return `${m.cases.passed}/${m.cases.total} passed`;
|
|
135
|
+
if (!m.valid)
|
|
136
|
+
return `invalid${m.category ? ` (${m.category})` : ""}`;
|
|
137
|
+
return "valid";
|
|
138
|
+
}
|
|
139
|
+
// A measurement in one line, next to the baseline: what a stage, a note and a worker see.
|
|
140
|
+
export function describe(c, m) {
|
|
141
|
+
if (!m.valid)
|
|
142
|
+
return m.error ?? "invalid";
|
|
143
|
+
return c.scores
|
|
144
|
+
.map((s) => {
|
|
145
|
+
const v = m.values[s.name];
|
|
146
|
+
const base = c.baseline?.values[s.name];
|
|
147
|
+
return v === undefined ? "" : `${s.name} ${fmt(v)}${base !== undefined ? ` (baseline ${fmt(base)})` : ""}`;
|
|
148
|
+
})
|
|
149
|
+
.filter(Boolean)
|
|
150
|
+
.join(", ");
|
|
151
|
+
}
|
|
152
|
+
function fmt(n) {
|
|
153
|
+
return Math.abs(n) >= 100 || Number.isInteger(n) ? String(Math.round(n * 100) / 100) : n.toPrecision(3);
|
|
154
|
+
}
|
|
155
|
+
// The held-out cases of a contract (design.md §25, P4): outside the project and every worktree, in the plugin's state
|
|
156
|
+
// directory, which the sandbox keeps from every worker. Only the evaluator sees them, through MM_CORPUS_DIR, and a
|
|
157
|
+
// worker only hears how many passed.
|
|
158
|
+
export { heldOutRoot } from "@omacode/core/heldout";
|
|
159
|
+
// Keyed by the project's id, not its path, so a renamed or moved project still finds its held-out cases. A directory
|
|
160
|
+
// under the old key (a hash of the path, before 2026-11-21) is still found while the project has not moved.
|
|
161
|
+
export function heldOutDir(project, jobId, contractId) {
|
|
162
|
+
const legacy = join(heldOutRoot(), createHash("sha256").update(resolve(project)).digest("hex").slice(0, 12), jobId, contractId);
|
|
163
|
+
if (existsSync(legacy))
|
|
164
|
+
return legacy;
|
|
165
|
+
return join(heldOutRoot(), projectId(project, { create: true }), jobId, contractId);
|
|
166
|
+
}
|
|
167
|
+
// Copies the held-out cases from a directory outside the project into the contract's held-out directory: their hash
|
|
168
|
+
// and count go into the contract, never their content. Returns why not instead when the directory will not do: it
|
|
169
|
+
// has to exist, hold files, and lie outside the project, because anything inside it is in every worker's checkout.
|
|
170
|
+
export function keepHeldOut(from, project, to) {
|
|
171
|
+
if (!isAbsolute(from))
|
|
172
|
+
return { problem: "corpus.heldOutFrom must be an absolute path" };
|
|
173
|
+
const rel = relative(resolve(project), resolve(from));
|
|
174
|
+
if (rel === "" || (!rel.startsWith("..") && !isAbsolute(rel)))
|
|
175
|
+
return { problem: "corpus.heldOutFrom must lie outside the project: anything inside it reaches every worker" };
|
|
176
|
+
if (!existsSync(from) || !statSync(from).isDirectory())
|
|
177
|
+
return { problem: `corpus.heldOutFrom ${from} is no directory` };
|
|
178
|
+
const files = readdirSync(from, { recursive: true }).filter((f) => statSync(join(from, f)).isFile()).sort();
|
|
179
|
+
if (!files.length)
|
|
180
|
+
return { problem: `corpus.heldOutFrom ${from} holds no files` };
|
|
181
|
+
rmSync(to, { recursive: true, force: true });
|
|
182
|
+
cpSync(from, to, { recursive: true });
|
|
183
|
+
const hash = createHash("sha256");
|
|
184
|
+
for (const f of files)
|
|
185
|
+
hash.update(f).update("\0").update(readFileSync(join(from, f)));
|
|
186
|
+
return { heldOut: { hash: hash.digest("hex").slice(0, 16), cases: files.length } };
|
|
187
|
+
}
|
|
188
|
+
// Whether a measurement reaches the contract's target on every score it names.
|
|
189
|
+
export function reached(c, m) {
|
|
190
|
+
const target = c.stop.target;
|
|
191
|
+
if (!m?.valid || !target || !Object.keys(target).length)
|
|
192
|
+
return false;
|
|
193
|
+
return Object.entries(target).every(([name, goal]) => {
|
|
194
|
+
const v = m.values[name];
|
|
195
|
+
const s = c.scores.find((x) => x.name === name) ?? c.guards.find((x) => x.name === name);
|
|
196
|
+
return v !== undefined && s !== undefined && (s.direction === "min" ? v <= goal : v >= goal);
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
// The parts that define what is measured; a change to any of them is a new version.
|
|
200
|
+
export function contractHash(c) {
|
|
201
|
+
const { goal, evaluator, scores, guards, corpus, stop, repeats } = c;
|
|
202
|
+
return createHash("sha256").update(JSON.stringify({ goal, evaluator, scores, guards, corpus, stop, repeats })).digest("hex").slice(0, 16);
|
|
203
|
+
}
|
|
204
|
+
const DIRECTIONS = new Set(["min", "max"]);
|
|
205
|
+
const NAME = /^[A-Za-z_][\w.-]{0,47}$/;
|
|
206
|
+
// A contract from the micromanager's JSON, validated; the id, version and status are the caller's. errors is empty when
|
|
207
|
+
// it is usable. The evaluator goes through the same rules as a check: it is a model-written string handed to `sh -c`.
|
|
208
|
+
export function parseContract(json) {
|
|
209
|
+
let o;
|
|
210
|
+
try {
|
|
211
|
+
o = JSON.parse(json);
|
|
212
|
+
}
|
|
213
|
+
catch (err) {
|
|
214
|
+
return { errors: [`the contract is no JSON object: ${err instanceof Error ? err.message : String(err)}`] };
|
|
215
|
+
}
|
|
216
|
+
if (!o || typeof o !== "object" || Array.isArray(o))
|
|
217
|
+
return { errors: ["the contract is no JSON object"] };
|
|
218
|
+
const errors = [];
|
|
219
|
+
const goal = typeof o.goal === "string" ? o.goal.trim() : "";
|
|
220
|
+
if (!goal)
|
|
221
|
+
errors.push("goal: say in words what the work is for");
|
|
222
|
+
const evaluator = typeof o.evaluator === "string" ? o.evaluator.trim() : "";
|
|
223
|
+
if (!evaluator)
|
|
224
|
+
errors.push('evaluator: a shell command that prints a line MM_SCORE {"scores":{...}}');
|
|
225
|
+
else {
|
|
226
|
+
const why = checkProblem(evaluator) ?? checkSafetyProblem(evaluator);
|
|
227
|
+
if (why)
|
|
228
|
+
errors.push(`evaluator: ${why}`);
|
|
229
|
+
}
|
|
230
|
+
const scores = [];
|
|
231
|
+
for (const [i, s] of (Array.isArray(o.scores) ? o.scores : []).entries()) {
|
|
232
|
+
const x = (s ?? {});
|
|
233
|
+
if (typeof x.name !== "string" || !NAME.test(x.name) || !DIRECTIONS.has(String(x.direction))) {
|
|
234
|
+
errors.push(`scores[${i}]: needs a name (letters, digits, _ . -) and a direction "min" or "max"`);
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
const noise = typeof x.noise === "number" && x.noise >= 0 && x.noise < 1 ? x.noise : undefined;
|
|
238
|
+
scores.push({ name: x.name, direction: x.direction, ...(noise !== undefined ? { noise } : {}) });
|
|
239
|
+
}
|
|
240
|
+
if (!scores.length)
|
|
241
|
+
errors.push("scores: at least one, the first is the one that decides");
|
|
242
|
+
if (new Set(scores.map((s) => s.name)).size !== scores.length)
|
|
243
|
+
errors.push("scores: a name is given twice");
|
|
244
|
+
const guards = [];
|
|
245
|
+
for (const [i, g] of (Array.isArray(o.guards) ? o.guards : []).entries()) {
|
|
246
|
+
const x = (g ?? {});
|
|
247
|
+
const tolerance = typeof x.tolerance === "number" && x.tolerance >= 0 ? x.tolerance : undefined;
|
|
248
|
+
if (typeof x.name !== "string" || !NAME.test(x.name) || !DIRECTIONS.has(String(x.direction)) || tolerance === undefined) {
|
|
249
|
+
errors.push(`guards[${i}]: needs a name, a direction "min" or "max" (which way is better) and a tolerance >= 0 (0.2: 20 % worse than the baseline at most)`);
|
|
250
|
+
continue;
|
|
251
|
+
}
|
|
252
|
+
guards.push({ name: x.name, direction: x.direction, tolerance, origin: x.origin === "redteam" || x.origin === "draft" ? x.origin : "user" });
|
|
253
|
+
}
|
|
254
|
+
const c = (o.corpus ?? {});
|
|
255
|
+
const visible = (Array.isArray(c.visible) ? c.visible : []).map(String).map((p) => p.trim()).filter(Boolean);
|
|
256
|
+
const outside = visible.filter((p) => p.startsWith("/") || p.split("/").includes(".."));
|
|
257
|
+
if (outside.length)
|
|
258
|
+
errors.push(`corpus.visible: project paths only, not ${outside.join(", ")}`);
|
|
259
|
+
const st = (o.stop ?? {});
|
|
260
|
+
const num = (v, min = 0) => (typeof v === "number" && Number.isFinite(v) && v > min ? v : undefined);
|
|
261
|
+
const target = {};
|
|
262
|
+
for (const [k, v] of Object.entries((st.target ?? {})))
|
|
263
|
+
if (typeof v === "number" && Number.isFinite(v))
|
|
264
|
+
target[k] = v;
|
|
265
|
+
const stop = {
|
|
266
|
+
...(Object.keys(target).length ? { target } : {}),
|
|
267
|
+
...(num(st.plateau) ? { plateau: Math.round(num(st.plateau)) } : {}),
|
|
268
|
+
...(num(st.evaluations) ? { evaluations: Math.round(num(st.evaluations)) } : {}),
|
|
269
|
+
...(num(st.seconds) ? { seconds: num(st.seconds) } : {}),
|
|
270
|
+
};
|
|
271
|
+
const repeats = Math.min(10, Math.max(1, Math.round(num(o.repeats) ?? 1)));
|
|
272
|
+
const timeoutMs = Math.min(3_600_000, Math.max(1000, Math.round((num(o.timeoutSeconds) ?? 300) * 1000)));
|
|
273
|
+
const heldOutFrom = typeof c.heldOutFrom === "string" && c.heldOutFrom.trim() ? c.heldOutFrom.trim() : undefined;
|
|
274
|
+
const quick = typeof o.quick === "string" ? o.quick.trim() : "";
|
|
275
|
+
if (quick) {
|
|
276
|
+
const why = checkProblem(quick) ?? checkSafetyProblem(quick);
|
|
277
|
+
if (why)
|
|
278
|
+
errors.push(`quick: ${why}`);
|
|
279
|
+
}
|
|
280
|
+
if (errors.length)
|
|
281
|
+
return { errors };
|
|
282
|
+
return { contract: { goal, evaluator, timeoutMs, repeats, scores, guards, corpus: { visible }, stop, ...(quick ? { quick: { evaluator: quick } } : {}) }, ...(heldOutFrom ? { heldOutFrom } : {}), errors };
|
|
283
|
+
}
|
|
284
|
+
// What a writer measured against a contract is told about it.
|
|
285
|
+
export function contractBrief(c) {
|
|
286
|
+
const scores = c.scores.map((s) => `${s.name} (${s.direction === "min" ? "lower" : "higher"} is better${c.baseline?.values[s.name] !== undefined ? `, today ${fmt(c.baseline.values[s.name])}` : ""})`);
|
|
287
|
+
const guards = c.guards.map((g) => `${g.name} may not get ${g.direction === "min" ? "higher" : "lower"} than today by more than ${Math.round(g.tolerance * 100)} %`);
|
|
288
|
+
return [
|
|
289
|
+
`Your work is measured against fitness contract ${c.id} (version ${c.version}): ${c.goal}`,
|
|
290
|
+
`When your checks pass, the plugin runs its evaluator, \`${c.evaluator}\`, ${c.repeats > 1 ? `${c.repeats} times (the median counts)` : "once"}. Scores, the first decides: ${scores.join("; ")}.`,
|
|
291
|
+
guards.length ? `Guards: ${guards.join("; ")}.` : "",
|
|
292
|
+
"An invalid result (a crash, a timeout, a wrong output) or a broken guard counts as a failing check. Improve the goal itself: a change that only raises the number is what the guards are there to catch.",
|
|
293
|
+
].filter(Boolean).join("\n");
|
|
294
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// The contract round (design.md §25, P5): how a fitness contract is worked out before any writer is measured against
|
|
2
|
+
// it. A draft contract says what one model thinks "better" means; the round makes it the user's:
|
|
3
|
+
// 1. draft: a reader reads the code, the tests and the data and writes the contract as JSON (the contract tool
|
|
4
|
+
// measures its baseline);
|
|
5
|
+
// 2. prefs: the user picks what decides, which guards stay and how far they may give, and the target, in a form;
|
|
6
|
+
// 3. redteam: a writer of another model family tries to raise the score WITHOUT improving the goal, in its own
|
|
7
|
+
// worktree, never merged; every loophole it reports can become a guard;
|
|
8
|
+
// 4. loopholes: the user picks the loopholes to close, in a form;
|
|
9
|
+
// 5. baseline: today's code measured again, three times on both corpora, and shown with its spread: "does this measure
|
|
10
|
+
// what I mean?";
|
|
11
|
+
// 6. frozen: the evaluator and the visible corpus are hashed (a worker cannot change them), and writers may be
|
|
12
|
+
// measured against it from now on.
|
|
13
|
+
// The micromanager drives it with contract_round and the forms; the plugin keeps the state on the contract.
|
|
14
|
+
import { formInput } from "./forms.js";
|
|
15
|
+
// What the drafter is asked: a contract as the contract tool takes it, from what the project has.
|
|
16
|
+
export function draftPrompt(goal) {
|
|
17
|
+
return [
|
|
18
|
+
`Work out a fitness contract for this goal: ${goal}`,
|
|
19
|
+
"Read the code, the tests, the benchmarks and the data the project has, then write what \"better\" means as JSON, in a ```json fence at the end of your answer:",
|
|
20
|
+
'{"goal": what the work is for; "evaluator": one shell command, run in the project directory, that prints a line MM_SCORE {"scores": {"<name>": <number>, …}, "cases": {"passed": n, "total": m}} and exits 0 (a crash, a timeout or a wrong output must make it exit non-zero); "scores": [{"name", "direction": "min"|"max", "noise": the relative spread two runs of the same code show}] (the first decides); "guards": [{"name", "direction", "tolerance": 0.05}] (values that must not get worse: correctness counts, sizes, memory; each one a way to raise the score without improving the goal that it closes); "corpus": {"visible": [the project paths it measures on]}; "repeats": 3 for timings, 1 otherwise; "timeoutSeconds"; "stop": {"evaluations": n}}',
|
|
21
|
+
"If the project has no command that measures this yet, say so plainly and describe the script that would (its path, what it runs, what it prints): a writer makes it first. Do not invent numbers.",
|
|
22
|
+
"Name what you are unsure about: which inputs matter, which thresholds are good enough. The user decides those next.",
|
|
23
|
+
].join("\n");
|
|
24
|
+
}
|
|
25
|
+
// What the red team is told: game the number, report how.
|
|
26
|
+
export function redteamPrompt(c) {
|
|
27
|
+
return [
|
|
28
|
+
`You are the red team of fitness contract ${c.id}: ${c.goal}`,
|
|
29
|
+
`Try to raise its score without improving the goal itself: special-case the inputs it measures, skip the work when it is measured, cache what it reads, weaken what it checks, change what it counts. The plugin measures your change with \`${c.evaluator}\` when your checks pass; your work is never merged.`,
|
|
30
|
+
"End your report with one line per way you found, whether it worked or not:",
|
|
31
|
+
"LOOPHOLE: what you did and what the score did | guard: <a measured value> <min|max> <tolerance> (the guard that would catch it, if a value the evaluator prints already shows it; leave out the part after | if none does)",
|
|
32
|
+
].join("\n");
|
|
33
|
+
}
|
|
34
|
+
// The red team's LOOPHOLE lines, with the guard each one names when it names one the contract can measure.
|
|
35
|
+
export function parseLoopholes(report) {
|
|
36
|
+
return [...report.matchAll(/^\s*\**LOOPHOLE\**\s*:\**\s*(.+)$/gim)]
|
|
37
|
+
.map((m) => m[1].split("|").map((p) => p.trim()))
|
|
38
|
+
.filter(([what]) => what && !/^(none|nothing|-)$/i.test(what))
|
|
39
|
+
.slice(0, 8)
|
|
40
|
+
.map(([what, guard]) => {
|
|
41
|
+
const g = guard?.match(/^guard:\s*([A-Za-z_][\w.-]*)\s+(min|max)\s+([\d.]+)\s*%?$/i);
|
|
42
|
+
if (!g)
|
|
43
|
+
return { what: what };
|
|
44
|
+
const tolerance = Number(g[3]) > 1 ? Number(g[3]) / 100 : Number(g[3]);
|
|
45
|
+
return { what: what, guard: { name: g[1], direction: g[2].toLowerCase(), tolerance, origin: "redteam" } };
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
const KEEP = { none: "No target: run to the budget" };
|
|
49
|
+
const BASELINE = { plausible: "Plausible: freeze it", again: "Measure again", change: "Change the contract" };
|
|
50
|
+
const TOLERANCE = { "Not at all (0 %)": 0, "A little (5 %)": 0.05, "Some (20 %)": 0.2 };
|
|
51
|
+
const TARGETS = { "10 % better": 0.1, "25 % better": 0.25, "50 % better": 0.5 };
|
|
52
|
+
export const roundHeader = (c, part) => `${c.id} ${part}`;
|
|
53
|
+
// The user's preferences: what decides, which guards stay and how far they may give, the target, and whether a red
|
|
54
|
+
// team tries the contract first.
|
|
55
|
+
export function prefsForm(c) {
|
|
56
|
+
const form = [{
|
|
57
|
+
header: roundHeader(c, "decides"),
|
|
58
|
+
question: `Contract ${c.id} (${c.goal.slice(0, 120)}): which score decides? Today: ${c.scores.map((s) => `${s.name} ${c.baseline?.values[s.name] ?? "?"} (${s.direction === "min" ? "lower" : "higher"} is better)`).join(", ")}.`,
|
|
59
|
+
options: c.scores.map((s, i) => ({ label: s.name, description: `${s.direction === "min" ? "Lower" : "Higher"} is better${i === 0 ? " (the draft's choice)" : ""}` })),
|
|
60
|
+
}];
|
|
61
|
+
if (c.guards.length) {
|
|
62
|
+
form.push({
|
|
63
|
+
header: roundHeader(c, "guards"),
|
|
64
|
+
question: "Which of these must not get worse? Each closes a way to raise the score without improving the goal. Tick the ones to keep; none ticked keeps none.",
|
|
65
|
+
multiple: true,
|
|
66
|
+
options: c.guards.map((g) => ({ label: g.name, description: `${g.direction === "min" ? "lower" : "higher"} is better; today ${c.baseline?.values[g.name] ?? "?"}` })),
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
form.push({
|
|
70
|
+
header: roundHeader(c, "preferences"),
|
|
71
|
+
question: "How much may a guard get worse than today?",
|
|
72
|
+
options: Object.keys(TOLERANCE).map((label) => ({ label, description: label.startsWith("Not") ? "Any change for the worse fails" : "Room for noise and small trade-offs" })),
|
|
73
|
+
}, {
|
|
74
|
+
header: roundHeader(c, "target"),
|
|
75
|
+
question: `When is it good enough? The work stops early once the deciding score is this much better than today${c.stop.evaluations ? `, and after ${c.stop.evaluations} evaluations in any case` : ""}.`,
|
|
76
|
+
options: [...Object.keys(TARGETS).map((label) => ({ label, description: "Than today's value of the deciding score" })), { label: KEEP.none, description: "Keep improving until the budget or the stop rule ends it" }],
|
|
77
|
+
}, {
|
|
78
|
+
header: roundHeader(c, "red team"),
|
|
79
|
+
question: "Should a red team try to game the score first (a worker on another model, about one task's cost)?",
|
|
80
|
+
options: [{ label: "Yes, red team first", description: "Each loophole it finds can become a guard" }, { label: "No, skip it", description: "Go straight to the baseline check" }],
|
|
81
|
+
});
|
|
82
|
+
return form;
|
|
83
|
+
}
|
|
84
|
+
const clean = (a) => a.trim().replace(/\s*\(recommended\)\s*$/i, "");
|
|
85
|
+
// The answers to the preferences form; typed text in place of a target or a tolerance is read as a number where it is
|
|
86
|
+
// one ("15", "15 %").
|
|
87
|
+
export function readPrefs(c, questions, answers) {
|
|
88
|
+
const of = (part) => {
|
|
89
|
+
const i = questions.findIndex((q) => q.header === roundHeader(c, part));
|
|
90
|
+
return i >= 0 ? (answers[i] ?? []).map(clean) : undefined;
|
|
91
|
+
};
|
|
92
|
+
const pct = (s) => {
|
|
93
|
+
const m = s.match(/^(\d+(?:\.\d+)?)\s*%?$/);
|
|
94
|
+
return m ? Number(m[1]) / 100 : undefined;
|
|
95
|
+
};
|
|
96
|
+
const decides = of("decides")?.find((a) => c.scores.some((s) => s.name === a));
|
|
97
|
+
const guards = of("guards")?.filter((a) => c.guards.some((g) => g.name === a));
|
|
98
|
+
const tol = of("preferences")?.[0];
|
|
99
|
+
const tolerance = tol === undefined ? undefined : TOLERANCE[tol] ?? pct(tol);
|
|
100
|
+
const tg = of("target")?.[0];
|
|
101
|
+
const target = tg === undefined ? undefined : tg === KEEP.none ? null : TARGETS[tg] ?? pct(tg) ?? undefined;
|
|
102
|
+
const said = [...(of("decides") ?? []), ...(of("target") ?? [])].find((a) => a && !c.scores.some((s) => s.name === a) && TARGETS[a] === undefined && a !== KEEP.none && pct(a) === undefined);
|
|
103
|
+
return { ...(decides ? { decides } : {}), ...(guards ? { guards } : {}), ...(tolerance !== undefined ? { tolerance } : {}), ...(target !== undefined ? { target } : {}), redteam: !(of("red team") ?? []).some((a) => a.startsWith("No")), ...(said ? { said } : {}) };
|
|
104
|
+
}
|
|
105
|
+
// The preferences, applied: the deciding score first, the guards the user kept with their tolerance, and the target
|
|
106
|
+
// as a value of the deciding score.
|
|
107
|
+
export function applyPrefs(c, p) {
|
|
108
|
+
if (p.decides)
|
|
109
|
+
c.scores = [...c.scores.filter((s) => s.name === p.decides), ...c.scores.filter((s) => s.name !== p.decides)];
|
|
110
|
+
if (p.guards)
|
|
111
|
+
c.guards = c.guards.filter((g) => p.guards.includes(g.name));
|
|
112
|
+
if (p.tolerance !== undefined)
|
|
113
|
+
c.guards = c.guards.map((g) => ({ ...g, tolerance: p.tolerance }));
|
|
114
|
+
const first = c.scores[0];
|
|
115
|
+
const base = c.baseline?.values[first.name];
|
|
116
|
+
if (p.target === null)
|
|
117
|
+
c.stop = { ...c.stop, target: undefined };
|
|
118
|
+
else if (p.target !== undefined && base !== undefined) {
|
|
119
|
+
const goal = first.direction === "min" ? base * (1 - p.target) : base * (1 + p.target);
|
|
120
|
+
c.stop = { ...c.stop, target: { [first.name]: Math.round(goal * 1000) / 1000 } };
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
// The loopholes the red team found, for the user to close.
|
|
124
|
+
export function loopholeForm(c) {
|
|
125
|
+
return [{
|
|
126
|
+
header: roundHeader(c, "loopholes"),
|
|
127
|
+
question: `The red team of contract ${c.id} found these ways to raise the score without improving the goal. Tick the ones to close (a guard is added where it named one; the others are noted for the corpus):`,
|
|
128
|
+
multiple: true,
|
|
129
|
+
options: (c.round?.loopholes ?? []).map((l, i) => ({ label: `L${i + 1}`, description: `${l.what.slice(0, 160)}${l.guard ? ` (guard: ${l.guard.name} ${l.guard.direction} ${Math.round(l.guard.tolerance * 100)} %)` : ""}` })),
|
|
130
|
+
}];
|
|
131
|
+
}
|
|
132
|
+
export function readLoopholes(answers) {
|
|
133
|
+
return answers.map(clean).flatMap((a) => (/^L\d+$/.test(a) ? [Number(a.slice(1)) - 1] : []));
|
|
134
|
+
}
|
|
135
|
+
// The baseline as the user sees it before the freeze: each score's median and spread over the runs, on both corpora.
|
|
136
|
+
export function baselineForm(c, runs, seconds) {
|
|
137
|
+
const spread = (ms, name) => {
|
|
138
|
+
const xs = ms.filter((m) => m.valid).map((m) => m.values[name]).filter((v) => v !== undefined);
|
|
139
|
+
if (!xs.length)
|
|
140
|
+
return "no valid run";
|
|
141
|
+
const lo = Math.min(...xs);
|
|
142
|
+
const hi = Math.max(...xs);
|
|
143
|
+
return lo === hi ? `${lo}` : `${lo} to ${hi}`;
|
|
144
|
+
};
|
|
145
|
+
const values = c.scores.map((s) => `${s.name}: ${spread(runs.visible, s.name)}${runs.heldOut.length ? `, held-out ${spread(runs.heldOut, s.name)}` : ""}`).join("; ");
|
|
146
|
+
return [{
|
|
147
|
+
header: roundHeader(c, "baseline"),
|
|
148
|
+
question: `Today's code under contract ${c.id}, ${runs.visible.length} runs (${seconds}s in all): ${values}. Does this measure what you mean?`,
|
|
149
|
+
options: [
|
|
150
|
+
{ label: BASELINE.plausible, description: "The evaluator and its corpus are frozen; writers are measured against it from now on" },
|
|
151
|
+
{ label: BASELINE.again, description: "Run the baseline again" },
|
|
152
|
+
{ label: BASELINE.change, description: "Say what is wrong; the contract comes back as a new draft" },
|
|
153
|
+
],
|
|
154
|
+
}];
|
|
155
|
+
}
|
|
156
|
+
export function readBaseline(answers) {
|
|
157
|
+
for (const a of answers.map(clean)) {
|
|
158
|
+
const k = Object.keys(BASELINE).find((x) => BASELINE[x].toLowerCase() === a.toLowerCase());
|
|
159
|
+
if (k)
|
|
160
|
+
return { decision: k };
|
|
161
|
+
}
|
|
162
|
+
const said = answers.find((a) => a.trim());
|
|
163
|
+
return said ? { said: said.trim() } : {};
|
|
164
|
+
}
|
|
165
|
+
// Which contract and which of its forms a submitted form is, from its headers; undefined for any other form.
|
|
166
|
+
export function roundFormOf(questions) {
|
|
167
|
+
for (const q of questions) {
|
|
168
|
+
const m = q.header?.match(/^(C\d+) (decides|guards|preferences|target|red team|loopholes|baseline)$/);
|
|
169
|
+
if (!m)
|
|
170
|
+
continue;
|
|
171
|
+
return { id: m[1], part: m[2] === "loopholes" ? "loopholes" : m[2] === "baseline" ? "baseline" : "prefs" };
|
|
172
|
+
}
|
|
173
|
+
return undefined;
|
|
174
|
+
}
|
|
175
|
+
// The instruction that puts a form to the user.
|
|
176
|
+
export function askWith(form, what) {
|
|
177
|
+
return `${what} Ask the user with the question tool, with exactly this input (a form; its answer reaches the plugin by itself), then end your turn:\n${formInput(form)}`;
|
|
178
|
+
}
|
package/dist/control.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "@omacode/state/control";
|