@omacode/micromanager 0.1.1 → 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 (213) hide show
  1. package/README.md +7 -4
  2. package/THIRD_PARTY.md +100 -0
  3. package/decider/.python-version +1 -0
  4. package/decider/README.md +35 -0
  5. package/decider/decider/__init__.py +1 -0
  6. package/decider/decider/server.py +327 -0
  7. package/decider/pyproject.toml +34 -0
  8. package/decider/uv.lock +1255 -0
  9. package/dist/agenda.js +51 -0
  10. package/dist/agents.js +58 -0
  11. package/dist/artifact/handoff.js +281 -0
  12. package/dist/ask.js +200 -0
  13. package/dist/backends.js +219 -0
  14. package/dist/backlog.js +414 -0
  15. package/dist/bench.js +427 -0
  16. package/dist/board.js +1 -0
  17. package/dist/brief.js +202 -0
  18. package/dist/browser.js +679 -0
  19. package/dist/budget.js +61 -0
  20. package/dist/catalog.js +187 -0
  21. package/dist/checkchange.js +145 -0
  22. package/dist/checkpoint.js +94 -0
  23. package/dist/cli.js +764 -0
  24. package/dist/comfy-gate.js +258 -0
  25. package/dist/compact.js +142 -0
  26. package/dist/config.js +344 -0
  27. package/dist/context/capture.js +1 -0
  28. package/dist/context/digest.js +1 -0
  29. package/dist/context/embed.js +1 -0
  30. package/dist/context/index.js +2 -0
  31. package/dist/context/ledger.js +1 -0
  32. package/dist/context/manager.js +1 -0
  33. package/dist/context/memory.js +1 -0
  34. package/dist/context/policy.js +1 -0
  35. package/dist/context/prices.js +1 -0
  36. package/dist/context/recall.js +1 -0
  37. package/dist/context/rules.js +1 -0
  38. package/dist/context/search.js +1 -0
  39. package/dist/context/status.js +1 -0
  40. package/dist/context/store.js +1 -0
  41. package/dist/context/summary.js +1 -0
  42. package/dist/context/tokens.js +1 -0
  43. package/dist/context/tools.js +1 -0
  44. package/dist/continuation.js +184 -0
  45. package/dist/contract.js +294 -0
  46. package/dist/contractround.js +178 -0
  47. package/dist/control.js +1 -0
  48. package/dist/creative-tools.js +237 -0
  49. package/dist/dataset.js +175 -0
  50. package/dist/decide.js +676 -0
  51. package/dist/decider.js +171 -0
  52. package/dist/design-shell.js +448 -0
  53. package/dist/design.js +1410 -0
  54. package/dist/desktop.js +44 -0
  55. package/dist/egress.js +156 -0
  56. package/dist/eval.js +60 -0
  57. package/dist/evolver.js +302 -0
  58. package/dist/features.js +193 -0
  59. package/dist/followups.js +32 -0
  60. package/dist/forms.js +195 -0
  61. package/dist/gate.js +108 -0
  62. package/dist/gatebox.js +46 -0
  63. package/dist/grants.js +189 -0
  64. package/dist/graph.js +65 -0
  65. package/dist/guard/index.js +1 -0
  66. package/dist/guard/wire.js +1 -0
  67. package/dist/helpers.js +85 -0
  68. package/dist/hooks.js +158 -0
  69. package/dist/image-models.js +117 -0
  70. package/{src/integration.ts → dist/integration.js} +1 -2
  71. package/dist/journal.js +1 -0
  72. package/dist/look.js +363 -0
  73. package/dist/memory.js +1 -0
  74. package/dist/mode.js +97 -0
  75. package/dist/native.js +3348 -0
  76. package/dist/nogit.js +259 -0
  77. package/dist/outcomes.js +148 -0
  78. package/dist/permission.js +35 -0
  79. package/dist/pick.js +89 -0
  80. package/dist/pipelines.js +262 -0
  81. package/dist/plan.js +641 -0
  82. package/dist/plandoc.js +211 -0
  83. package/dist/plugin.js +4736 -0
  84. package/dist/policy.js +58 -0
  85. package/dist/pools.js +1 -0
  86. package/dist/preview.js +274 -0
  87. package/dist/profile.js +165 -0
  88. package/dist/progress.js +1 -0
  89. package/dist/promote.js +313 -0
  90. package/dist/redact.js +1 -0
  91. package/dist/registry.js +179 -0
  92. package/dist/riskscore.js +126 -0
  93. package/dist/roles.js +1 -0
  94. package/dist/routing.js +1 -0
  95. package/dist/runner.js +1892 -0
  96. package/{src/sandbox.ts → dist/sandbox.js} +1 -2
  97. package/dist/sandboxgate.js +90 -0
  98. package/dist/scheduler.js +170 -0
  99. package/dist/services-main.js +131 -0
  100. package/dist/services.js +265 -0
  101. package/dist/session.js +241 -0
  102. package/dist/setup.js +423 -0
  103. package/dist/shell/decide.js +1 -0
  104. package/dist/shell/index.js +2 -0
  105. package/dist/shell/sandbox.js +1 -0
  106. package/dist/shell/wire.js +1 -0
  107. package/dist/skills.js +103 -0
  108. package/dist/state.js +1 -0
  109. package/dist/store.js +1 -0
  110. package/dist/switcher.js +1 -0
  111. package/dist/synth.js +418 -0
  112. package/dist/tools.js +477 -0
  113. package/dist/trials.js +223 -0
  114. package/dist/usage.js +1 -0
  115. package/dist/wait.js +167 -0
  116. package/dist/watchdog.js +476 -0
  117. package/dist/web-guidance.js +43 -0
  118. package/dist/which.js +20 -0
  119. package/dist/worktree/git.js +545 -0
  120. package/dist/writeguard.js +311 -0
  121. package/package.json +36 -17
  122. package/skills/deck/SKILL.md +98 -0
  123. package/skills/design/SKILL.md +150 -0
  124. package/skills/image/SKILL.md +66 -0
  125. package/skills/orchestrator/SKILL.md +107 -0
  126. package/skills/video/SKILL.md +97 -0
  127. package/skills/web/SKILL.md +60 -0
  128. package/src/agenda.ts +0 -56
  129. package/src/agents.ts +0 -74
  130. package/src/ask.ts +0 -243
  131. package/src/backends.ts +0 -144
  132. package/src/backlog.ts +0 -436
  133. package/src/bench.ts +0 -163
  134. package/src/board.ts +0 -1
  135. package/src/brief.ts +0 -151
  136. package/src/browser.ts +0 -624
  137. package/src/budget.ts +0 -73
  138. package/src/catalog.ts +0 -214
  139. package/src/checkchange.ts +0 -180
  140. package/src/checkpoint.ts +0 -99
  141. package/src/cli.ts +0 -117
  142. package/src/compact.ts +0 -162
  143. package/src/config.ts +0 -340
  144. package/src/context/capture.ts +0 -1
  145. package/src/context/digest.ts +0 -1
  146. package/src/context/embed.ts +0 -1
  147. package/src/context/index.ts +0 -2
  148. package/src/context/ledger.ts +0 -1
  149. package/src/context/manager.ts +0 -1
  150. package/src/context/memory.ts +0 -1
  151. package/src/context/policy.ts +0 -1
  152. package/src/context/prices.ts +0 -1
  153. package/src/context/recall.ts +0 -1
  154. package/src/context/rules.ts +0 -1
  155. package/src/context/search.ts +0 -1
  156. package/src/context/status.ts +0 -1
  157. package/src/context/store.ts +0 -1
  158. package/src/context/summary.ts +0 -1
  159. package/src/context/tokens.ts +0 -1
  160. package/src/context/tools.ts +0 -1
  161. package/src/continuation.ts +0 -122
  162. package/src/contract.ts +0 -342
  163. package/src/contractround.ts +0 -225
  164. package/src/control.ts +0 -1
  165. package/src/dataset.ts +0 -133
  166. package/src/decide.ts +0 -690
  167. package/src/eval.ts +0 -66
  168. package/src/evolver.ts +0 -369
  169. package/src/followups.ts +0 -50
  170. package/src/forms.ts +0 -191
  171. package/src/gate.ts +0 -90
  172. package/src/grants.ts +0 -239
  173. package/src/graph.ts +0 -74
  174. package/src/guard/index.ts +0 -1
  175. package/src/guard/wire.ts +0 -1
  176. package/src/helpers.ts +0 -105
  177. package/src/hooks.ts +0 -199
  178. package/src/jev.ts +0 -141
  179. package/src/journal.ts +0 -1
  180. package/src/look.ts +0 -390
  181. package/src/memory.ts +0 -1
  182. package/src/native.ts +0 -2455
  183. package/src/nogit.ts +0 -112
  184. package/src/outcomes.ts +0 -210
  185. package/src/pick.ts +0 -112
  186. package/src/pipelines.ts +0 -252
  187. package/src/plan.ts +0 -449
  188. package/src/plugin.ts +0 -3187
  189. package/src/policy.ts +0 -84
  190. package/src/pools.ts +0 -1
  191. package/src/profile.ts +0 -186
  192. package/src/progress.ts +0 -1
  193. package/src/redact.ts +0 -1
  194. package/src/registry.ts +0 -207
  195. package/src/roles.ts +0 -1
  196. package/src/routing.ts +0 -1
  197. package/src/runner.ts +0 -1506
  198. package/src/scheduler.ts +0 -200
  199. package/src/session.ts +0 -269
  200. package/src/shell/decide.ts +0 -1
  201. package/src/shell/index.ts +0 -2
  202. package/src/shell/sandbox.ts +0 -1
  203. package/src/shell/wire.ts +0 -1
  204. package/src/skills.ts +0 -111
  205. package/src/state.ts +0 -1
  206. package/src/store.ts +0 -1
  207. package/src/switcher.ts +0 -1
  208. package/src/tools.ts +0 -480
  209. package/src/trials.ts +0 -247
  210. package/src/usage.ts +0 -1
  211. package/src/wait.ts +0 -180
  212. package/src/watchdog.ts +0 -498
  213. package/src/worktree/git.ts +0 -378
@@ -1 +0,0 @@
1
- export * from "@omacode/context/search"
@@ -1 +0,0 @@
1
- export * from "@omacode/context/status"
@@ -1 +0,0 @@
1
- export * from "@omacode/context/store"
@@ -1 +0,0 @@
1
- export * from "@omacode/context/summary"
@@ -1 +0,0 @@
1
- export * from "@omacode/context/tokens"
@@ -1 +0,0 @@
1
- export * from "@omacode/context/tools"
@@ -1,122 +0,0 @@
1
- // The continuation of a planned job on native workers (run_job, omo-hybrid): which tasks the micromanager starts next.
2
- //
3
- // A planned job used to run on the runner, which made its worker sessions itself: they were not children of the
4
- // micromanager (opencode 2.0.18 drops parentID on a plugin's session.create), so the user could not find them in the
5
- // TUI (2026-10-19). Now the micromanager starts each planned task with the subagent tool, as it does its own tasks, and
6
- // the code keeps the plan: after every worker's end it says which tasks are ready, until the job is done or stuck.
7
- // That is the todo continuation of Sisyphus, driven by the job file rather than by the model's memory.
8
-
9
- import { HEADER } from "./hooks.ts"
10
- import { jobBranch } from "./integration.ts"
11
- import { roleById } from "./roles.ts"
12
- import { isDone, settled, startable, type Job, type Task } from "./state.ts"
13
- export { settled, startable }
14
-
15
- const LIVE = new Set<Task["status"]>(["running", "gating", "fixing", "reviewing"])
16
- const OPEN = new Set<Task["status"]>(["pending", "ready", "planned"])
17
- const HALTED = new Set<Job["phase"]>(["paused", "stopped", "done", "failed"])
18
-
19
- export type Step =
20
- | { readonly kind: "start"; readonly tasks: readonly Task[]; readonly text: string }
21
- | { readonly kind: "done"; readonly text: string }
22
- | { readonly kind: "stuck"; readonly text: string }
23
-
24
- // The line of a subagent prompt that starts a planned task; native.ts parses it back (parseDelegation).
25
- export const plannedLine = (task: string, job: string) => `Task: ${task} · ${job}`
26
-
27
- // Whether a task's work is in: it is merged, or the task that does it over is (in this job, or in another one the
28
- // caller can look up: "job-…/T17").
29
-
30
- function call(job: Job, task: Task): string {
31
- const agent = roleById(task.role)?.agent ?? task.role
32
- return `- agent ${agent}, description "${task.id} ${task.title}", prompt "${plannedLine(task.id, job.id)}"`
33
- }
34
-
35
- // What the micromanager does next for a planned job on native workers, or for its session's own job when it wrote
36
- // todos (the todo tool); undefined while workers run and nothing new can start, for a job the runner runs, and for a
37
- // paused or stopped one. A session's own job only hears which todos can start: it is "done" whenever the micromanager
38
- // has nothing more in mind, which is not news.
39
- export function nextStep(job: Job, parallel: number): Step | undefined {
40
- if (!(job.native || job.rolling) || HALTED.has(job.phase)) return undefined
41
- const live = job.tasks.filter((t) => LIVE.has(t.status))
42
- const ready = startable(job).slice(0, Math.max(0, parallel - live.length))
43
- if (ready.length) {
44
- return {
45
- kind: "start",
46
- tasks: ready,
47
- text: [
48
- `${HEADER} job ${job.id}: start ${ready.length === 1 ? "this task" : "these tasks"} of your ${job.rolling ? "todo list" : "plan"} now, in one message, with the subagent tool (background = true):`,
49
- ...ready.map((t) => call(job, t)),
50
- `The plugin gives each worker its task, files, checks and acceptance points from the ${job.rolling ? "todo" : "plan"}; add to a prompt only what it does not say, below that line. Do not wait for them: the next tasks follow in a note like this one when they end.`,
51
- live.length ? `Still running: ${live.map((t) => t.id).join(", ")}.` : "",
52
- ].filter(Boolean).join("\n"),
53
- }
54
- }
55
- if (live.length || !job.native) return undefined
56
- // A cancelled task is out of the plan, unless an open task still needs it.
57
- const needed = new Set(job.tasks.filter((t) => OPEN.has(t.status)).flatMap((t) => t.dependsOn))
58
- const left = job.tasks.filter((t) => !isDone(t) && !t.undone && (t.status !== "cancelled" || needed.has(t.id)))
59
- if (!left.length) {
60
- const merged = job.tasks.filter((t) => isDone(t)).length
61
- return {
62
- kind: "done",
63
- text: `${HEADER} job ${job.id}: the plan is through, ${merged} of ${job.tasks.length} tasks merged on ${job.integrationBranch ?? jobBranch(job.id)}${merged < job.tasks.length ? " (the rest were cancelled)" : ""}. Tell the user briefly what changed; merge_job brings it into their checkout once they say so.`,
64
- }
65
- }
66
- const stopped = left.filter((t) => !OPEN.has(t.status))
67
- const waiting = left.filter((t) => OPEN.has(t.status))
68
- return {
69
- kind: "stuck",
70
- text: [
71
- `${HEADER} job ${job.id} cannot go on by itself:`,
72
- ...stopped.map((t) => `- ${t.id} ${t.title}: ${t.status}${t.escalation ? ` (${t.escalation.detail.slice(0, 200)})` : t.summary ? ` (${t.summary.slice(0, 200)})` : ""}${t.session ? `, session ${t.session}` : ""}`),
73
- waiting.length ? `Waiting on those: ${waiting.map((t) => `${t.id} (after ${t.dependsOn.join(", ")})`).join("; ")}.` : "",
74
- `For each stopped task: continue its worker with the subagent tool and its sessionID when its change is worth keeping, start it again with a prompt "${plannedLine("T…", job.id)}", or ask the user. A task that is not needed any more: stop_task.`,
75
- ].filter(Boolean).join("\n"),
76
- }
77
- }
78
-
79
- // Auto-continue (the user, 2026-10-20, like Sisyphus' todo continuation): when the micromanager's turn ends while todos
80
- // are open and no worker runs, nothing else would wake it, so the plugin does. What to say, or why to pause instead:
81
- // - every todo done: the final summary, and auto-continue goes off;
82
- // - todos that can start: start them (all, or the next one when Parallel is off), unless two wakes in a row brought no
83
- // progress, then it pauses and asks the user;
84
- // - only blocked, stopped or failed work left: it pauses and asks the user how to go on.
85
- // A running worker needs no wake (its report starts the next turn), and a form waiting for the user keeps the turn open.
86
- export type AutoStep =
87
- | { readonly kind: "wake"; readonly text: string; readonly seen: string; readonly wakes: number }
88
- | { readonly kind: "done"; readonly text: string }
89
- | { readonly kind: "pause"; readonly pause: string; readonly text: string }
90
-
91
- export function autoStep(job: Job, running: number, parallel: boolean, last: { seen?: string; wakes?: number } = {}): AutoStep | undefined {
92
- if (running > 0) return undefined
93
- const ended = (t: Task) => LIVE.has(t.status) && t.stages.at(-1)?.stage === "end"
94
- const open = job.tasks.filter((t) => OPEN.has(t.status))
95
- const stopped = job.tasks.filter((t) => ended(t) || ["escalated", "blocked"].includes(t.status)).filter((t) => !t.replacedBy)
96
- const ready = startable(job)
97
- if (!open.length && !stopped.length) {
98
- return { kind: "done", text: `${HEADER} auto-continue: every todo of job ${job.id} is done. Give the user the final summary: what changed, and that merge_job brings it into their checkout once they say so.` }
99
- }
100
- const askUser = "Ask the user with the question tool how to go on (a form; their answer comes back to you)."
101
- const list = (tasks: readonly Task[]) => tasks.map((t) => `${t.id} ${t.title} (${t.status}${ended(t) ? ", its worker ended unfinished" : ""})`).join("; ")
102
- if (!ready.length) {
103
- return { kind: "pause", pause: "waits for you", text: `${HEADER} auto-continue: job ${job.id} cannot go on by itself. ${stopped.length ? `Stopped or failed: ${list(stopped)}. ` : ""}${open.length ? `Waiting on those: ${open.map((t) => `${t.id} (after ${t.dependsOn.join(", ")})`).join("; ")}. ` : ""}${askUser}` }
104
- }
105
- const seen = `${job.tasks.filter(isDone).length}:${job.tasks.filter((t) => t.stages.some((s) => s.stage === "delegate")).length}`
106
- const wakes = seen === last.seen ? (last.wakes ?? 0) + 1 : 0
107
- if (wakes >= 2) {
108
- return { kind: "pause", pause: "no progress", text: `${HEADER} auto-continue paused: two wakes in a row started no todo of job ${job.id} and finished none, though ${ready.map((t) => t.id).join(", ")} can start. ${askUser}` }
109
- }
110
- const now = parallel ? ready : ready.slice(0, 1)
111
- return {
112
- kind: "wake",
113
- seen,
114
- wakes,
115
- text: [
116
- `${HEADER} auto-continue: job ${job.id} goes on. Start ${now.length > 1 ? "these todos now, in one message" : "this todo now"}, with the subagent tool (background = true):`,
117
- ...now.map((t) => call(job, t)),
118
- stopped.length ? `Also stopped: ${list(stopped)}: continue a worker with its sessionID when its change is worth keeping, or write a todo that replaces it.` : "",
119
- "Ask the user only what only they can decide, with the question tool.",
120
- ].filter(Boolean).join("\n"),
121
- }
122
- }
package/src/contract.ts DELETED
@@ -1,342 +0,0 @@
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
-
12
- import { createHash } from "node:crypto"
13
- import { cpSync, existsSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs"
14
- import { isAbsolute, join, relative, resolve } from "node:path"
15
-
16
- import { checkProblem, checkSafetyProblem } from "./plan.ts"
17
- import { heldOutRoot } from "@omacode/core/heldout"
18
- import type { Run } from "./integration.ts"
19
-
20
- // The contract travels with the job's JSON; state.ts owns the interfaces, the fields are declared here (as
21
- // integration.ts does) so the contract's types stay in one file.
22
- declare module "./state.ts" {
23
- interface Job {
24
- contracts?: Contract[]
25
- }
26
- interface Task {
27
- contract?: { id: string; version: number } // the contract its work is measured against
28
- score?: Measured & { corpus: "visible" | "heldout"; at: string } // its last valid measurement
29
- graded?: { passed: number; total: number } // what its checks' own MM_SCORE lines counted, at its last gate
30
- // A trial attempt measured against a contract whose checks passed: committed, kept in its worktree, and waiting for
31
- // the trial to be decided by score (src/native.ts settle) instead of merging first.
32
- held?: boolean
33
- settleBy?: string // on a trial's first attempt: when the trial is decided at the latest
34
- }
35
- }
36
-
37
- export type Direction = "min" | "max"
38
-
39
- export interface Score {
40
- readonly name: string
41
- readonly direction: Direction
42
- // A relative band inside which two values count as equal (0.05: 5 %): a timing measured twice is never the same
43
- // number, and without a band "the best wins" picks noise.
44
- readonly noise?: number
45
- }
46
-
47
- // A value that must not get worse than the baseline by more than tolerance (relative; absolute when the baseline is
48
- // 0). It is how a contract closes a loophole: "faster, but the element count stays within 20 %".
49
- export interface Guard {
50
- readonly name: string
51
- readonly direction: Direction // which way is better
52
- readonly tolerance: number
53
- readonly origin: "user" | "draft" | "redteam"
54
- }
55
-
56
- export interface Corpus {
57
- readonly visible: readonly string[] // project paths the evaluator measures on, which workers may read
58
- readonly heldOut?: { readonly hash: string; readonly cases: number } // kept outside the project (P4); never its content
59
- }
60
-
61
- export interface Measured {
62
- readonly valid: boolean
63
- readonly values: Readonly<Record<string, number>>
64
- readonly cases?: { readonly passed: number; readonly total: number }
65
- readonly category?: string // the evaluator's own word for what went wrong, coarse enough to show a worker
66
- readonly error?: string // why the result is invalid
67
- }
68
-
69
- export interface Contract {
70
- readonly id: string // "C1", per job
71
- version: number
72
- status: "draft" | "frozen"
73
- goal: string
74
- evaluator: string // a shell command, run in the worker's directory
75
- timeoutMs: number
76
- repeats: number // runs per measurement; the median counts
77
- scores: Score[] // the first is the primary score, the others break ties inside its noise band
78
- guards: Guard[]
79
- corpus: Corpus
80
- baseline?: { values: Record<string, number>; heldOut?: Record<string, number>; quick?: Record<string, number>; at: string; commit?: string }
81
- // A quick stage for a slow evaluator (the evolver's cascade, src/evolver.ts): the same scores on small instances, in
82
- // seconds. A candidate only gets the full measurement once its checks pass and it beats the baseline here.
83
- quick?: { evaluator: string; costPerEval?: number }
84
- stop: { target?: Record<string, number>; plateau?: number; evaluations?: number; seconds?: number }
85
- costPerEval?: number // seconds per run, measured with the baseline
86
- used?: { evaluations: number; seconds: number }
87
- // When the round froze it (src/contractround.ts): the evaluator's files and the visible corpus with their hashes in
88
- // the job's branch. A worker measured against it has these frozen as well (src/native.ts #freeze).
89
- frozen?: { files: Record<string, string>; at: string }
90
- history: { version: number; change: string; at: string }[]
91
- }
92
-
93
- // A line that starts like one but holds no JSON object is a broken result, not output to skip.
94
- const LINE = /^MM_SCORE\s+(.*)$/
95
-
96
- // The last MM_SCORE line of a run's output, read as a measurement. Undefined when there is none: for an ordinary check
97
- // that means nothing was graded, for an evaluator that the result is invalid.
98
- export function parseScoreLines(stdout: string): Measured | undefined {
99
- const line = stdout.split("\n").map((l) => l.trim()).filter((l) => LINE.test(l)).at(-1)
100
- if (!line) return undefined
101
- let o: Record<string, unknown>
102
- try {
103
- o = JSON.parse(line.match(LINE)![1]!) as Record<string, unknown>
104
- } catch {
105
- return { valid: false, values: {}, error: "the MM_SCORE line is no JSON object" }
106
- }
107
- const values: Record<string, number> = {}
108
- for (const [k, v] of Object.entries((o.scores ?? {}) as Record<string, unknown>)) if (typeof v === "number" && Number.isFinite(v)) values[k] = v
109
- const c = o.cases as { passed?: unknown; total?: unknown } | undefined
110
- const cases = c && typeof c.passed === "number" && typeof c.total === "number" && c.total > 0 ? { passed: c.passed, total: c.total } : undefined
111
- return {
112
- valid: o.valid !== false,
113
- values,
114
- ...(cases ? { cases } : {}),
115
- ...(typeof o.category === "string" && o.category ? { category: o.category.slice(0, 80) } : {}),
116
- }
117
- }
118
-
119
- // One evaluator run as a measurement: the hard constraints first, then the line itself.
120
- export function measuredOf(contract: Contract, run: Run): Measured {
121
- if (run.timedOut) return { valid: false, values: {}, error: `the evaluator timed out after ${Math.round(contract.timeoutMs / 1000)}s` }
122
- const m = parseScoreLines(run.stdout)
123
- if (run.code !== 0) return { valid: false, values: m?.values ?? {}, ...(m?.category ? { category: m.category } : {}), error: `the evaluator exited ${run.code}: ${`${run.stderr}`.trim().slice(-300) || "no output"}` }
124
- if (!m) return { valid: false, values: {}, error: "the evaluator printed no MM_SCORE line" }
125
- if (!m.valid) return { ...m, error: m.error ?? `the evaluator reported the result invalid${m.category ? ` (${m.category})` : ""}` }
126
- const missing = contract.scores.map((s) => s.name).filter((n) => !(n in m.values))
127
- if (missing.length) return { ...m, valid: false, error: `the MM_SCORE line lacks ${missing.join(", ")}` }
128
- return m
129
- }
130
-
131
- // Repeated runs as one measurement: any invalid run makes it invalid (a crash that happens once in three is a crash),
132
- // and each value is the median of its runs.
133
- export function median(runs: readonly Measured[]): Measured {
134
- const bad = runs.find((r) => !r.valid)
135
- if (bad || !runs.length) return bad ?? { valid: false, values: {}, error: "nothing was measured" }
136
- const mid = (xs: number[]) => {
137
- const s = [...xs].sort((a, b) => a - b)
138
- return s.length % 2 ? s[(s.length - 1) / 2]! : (s[s.length / 2 - 1]! + s[s.length / 2]!) / 2
139
- }
140
- const values: Record<string, number> = {}
141
- for (const k of Object.keys(runs[0]!.values)) {
142
- const xs = runs.map((r) => r.values[k]).filter((v): v is number => v !== undefined)
143
- if (xs.length === runs.length) values[k] = mid(xs)
144
- }
145
- const last = runs.at(-1)!
146
- return { valid: true, values, ...(last.cases ? { cases: last.cases } : {}), ...(last.category ? { category: last.category } : {}) }
147
- }
148
-
149
- // How much worse b is than a for a value with this direction, relative to a (absolute when a is 0); negative: better.
150
- function worse(direction: Direction, a: number, b: number): number {
151
- const d = direction === "min" ? b - a : a - b
152
- return a === 0 ? d : d / Math.abs(a)
153
- }
154
-
155
- // The guards a measurement breaks against the baseline. Without a baseline there is nothing to compare with.
156
- export function guardViolations(c: Contract, m: Measured): string[] {
157
- if (!c.baseline) return []
158
- return c.guards.flatMap((g) => {
159
- const base = c.baseline!.values[g.name]
160
- const now = m.values[g.name]
161
- if (base === undefined) return []
162
- if (now === undefined) return [`${g.name} was not measured`]
163
- const by = worse(g.direction, base, now)
164
- return by > g.tolerance ? [`${g.name} is ${fmt(now)}, worse than the baseline ${fmt(base)} by more than ${Math.round(g.tolerance * 100)} %`] : []
165
- })
166
- }
167
-
168
- // Which of two measurements is better under the contract: > 0 when a is, < 0 when b is, 0 when they count as equal.
169
- // An invalid result loses to any valid one; the scores decide in their order, each inside its noise band.
170
- export function better(c: Contract, a: Measured, b: Measured): number {
171
- if (a.valid !== b.valid) return a.valid ? 1 : -1
172
- if (!a.valid) return 0
173
- for (const s of c.scores) {
174
- const x = a.values[s.name]
175
- const y = b.values[s.name]
176
- if (x === undefined || y === undefined) continue
177
- const scale = Math.max(Math.abs(x), Math.abs(y))
178
- if (scale === 0 || Math.abs(x - y) / scale <= (s.noise ?? 0)) continue
179
- return (s.direction === "min" ? y - x : x - y) > 0 ? 1 : -1
180
- }
181
- return 0
182
- }
183
-
184
- // The primary score's improvement over the baseline, signed so that better is positive: the reward the outcome log
185
- // keeps for the router. 0 for an invalid result; undefined without a baseline to compare with.
186
- export function reward(c: Contract, m: Measured): number | undefined {
187
- if (!m.valid) return 0
188
- const s = c.scores[0]
189
- const base = s && c.baseline?.values[s.name]
190
- const now = s && m.values[s.name]
191
- if (base === undefined || now === undefined) return undefined
192
- return Math.round(-worse(s.direction, base, now) * 1e4) / 1e4
193
- }
194
-
195
- // What a worker may hear of a held-out measurement: how many cases passed, or the category, never values per case.
196
- export function coarse(m: Measured): string {
197
- if (m.cases) return `${m.cases.passed}/${m.cases.total} passed`
198
- if (!m.valid) return `invalid${m.category ? ` (${m.category})` : ""}`
199
- return "valid"
200
- }
201
-
202
- // A measurement in one line, next to the baseline: what a stage, a note and a worker see.
203
- export function describe(c: Contract, m: Measured): string {
204
- if (!m.valid) return m.error ?? "invalid"
205
- return c.scores
206
- .map((s) => {
207
- const v = m.values[s.name]
208
- const base = c.baseline?.values[s.name]
209
- return v === undefined ? "" : `${s.name} ${fmt(v)}${base !== undefined ? ` (baseline ${fmt(base)})` : ""}`
210
- })
211
- .filter(Boolean)
212
- .join(", ")
213
- }
214
-
215
- function fmt(n: number): string {
216
- return Math.abs(n) >= 100 || Number.isInteger(n) ? String(Math.round(n * 100) / 100) : n.toPrecision(3)
217
- }
218
-
219
- // The held-out cases of a contract (design.md §25, P4): outside the project and every worktree, in the plugin's state
220
- // directory, which the sandbox keeps from every worker. Only the evaluator sees them, through MM_CORPUS_DIR, and a
221
- // worker only hears how many passed.
222
- export { heldOutRoot } from "@omacode/core/heldout"
223
-
224
- export function heldOutDir(project: string, jobId: string, contractId: string): string {
225
- return join(heldOutRoot(), createHash("sha256").update(resolve(project)).digest("hex").slice(0, 12), jobId, contractId)
226
- }
227
-
228
- // Copies the held-out cases from a directory outside the project into the contract's held-out directory: their hash
229
- // and count go into the contract, never their content. Returns why not instead when the directory will not do: it
230
- // has to exist, hold files, and lie outside the project, because anything inside it is in every worker's checkout.
231
- export function keepHeldOut(from: string, project: string, to: string): { heldOut?: { hash: string; cases: number }; problem?: string } {
232
- if (!isAbsolute(from)) return { problem: "corpus.heldOutFrom must be an absolute path" }
233
- const rel = relative(resolve(project), resolve(from))
234
- if (rel === "" || (!rel.startsWith("..") && !isAbsolute(rel))) return { problem: "corpus.heldOutFrom must lie outside the project: anything inside it reaches every worker" }
235
- if (!existsSync(from) || !statSync(from).isDirectory()) return { problem: `corpus.heldOutFrom ${from} is no directory` }
236
- const files = (readdirSync(from, { recursive: true }) as string[]).filter((f) => statSync(join(from, f)).isFile()).sort()
237
- if (!files.length) return { problem: `corpus.heldOutFrom ${from} holds no files` }
238
- rmSync(to, { recursive: true, force: true })
239
- cpSync(from, to, { recursive: true })
240
- const hash = createHash("sha256")
241
- for (const f of files) hash.update(f).update("\0").update(readFileSync(join(from, f)))
242
- return { heldOut: { hash: hash.digest("hex").slice(0, 16), cases: files.length } }
243
- }
244
-
245
- // Whether a measurement reaches the contract's target on every score it names.
246
- export function reached(c: Contract, m: Measured | undefined): boolean {
247
- const target = c.stop.target
248
- if (!m?.valid || !target || !Object.keys(target).length) return false
249
- return Object.entries(target).every(([name, goal]) => {
250
- const v = m.values[name]
251
- const s = c.scores.find((x) => x.name === name) ?? c.guards.find((x) => x.name === name)
252
- return v !== undefined && s !== undefined && (s.direction === "min" ? v <= goal : v >= goal)
253
- })
254
- }
255
-
256
- // The parts that define what is measured; a change to any of them is a new version.
257
- export function contractHash(c: Contract): string {
258
- const { goal, evaluator, scores, guards, corpus, stop, repeats } = c
259
- return createHash("sha256").update(JSON.stringify({ goal, evaluator, scores, guards, corpus, stop, repeats })).digest("hex").slice(0, 16)
260
- }
261
-
262
- const DIRECTIONS = new Set(["min", "max"])
263
- const NAME = /^[A-Za-z_][\w.-]{0,47}$/
264
-
265
- // A contract from the micromanager's JSON, validated; the id, version and status are the caller's. errors is empty when
266
- // it is usable. The evaluator goes through the same rules as a check: it is a model-written string handed to `sh -c`.
267
- export function parseContract(json: string): { contract?: Omit<Contract, "id" | "version" | "status" | "history">; heldOutFrom?: string; errors: string[] } {
268
- let o: Record<string, unknown>
269
- try {
270
- o = JSON.parse(json) as Record<string, unknown>
271
- } catch (err) {
272
- return { errors: [`the contract is no JSON object: ${err instanceof Error ? err.message : String(err)}`] }
273
- }
274
- if (!o || typeof o !== "object" || Array.isArray(o)) return { errors: ["the contract is no JSON object"] }
275
- const errors: string[] = []
276
- const goal = typeof o.goal === "string" ? o.goal.trim() : ""
277
- if (!goal) errors.push("goal: say in words what the work is for")
278
- const evaluator = typeof o.evaluator === "string" ? o.evaluator.trim() : ""
279
- if (!evaluator) errors.push('evaluator: a shell command that prints a line MM_SCORE {"scores":{...}}')
280
- else {
281
- const why = checkProblem(evaluator) ?? checkSafetyProblem(evaluator)
282
- if (why) errors.push(`evaluator: ${why}`)
283
- }
284
- const scores: Score[] = []
285
- for (const [i, s] of (Array.isArray(o.scores) ? o.scores : []).entries()) {
286
- const x = (s ?? {}) as Record<string, unknown>
287
- if (typeof x.name !== "string" || !NAME.test(x.name) || !DIRECTIONS.has(String(x.direction))) {
288
- errors.push(`scores[${i}]: needs a name (letters, digits, _ . -) and a direction "min" or "max"`)
289
- continue
290
- }
291
- const noise = typeof x.noise === "number" && x.noise >= 0 && x.noise < 1 ? x.noise : undefined
292
- scores.push({ name: x.name, direction: x.direction as Direction, ...(noise !== undefined ? { noise } : {}) })
293
- }
294
- if (!scores.length) errors.push("scores: at least one, the first is the one that decides")
295
- if (new Set(scores.map((s) => s.name)).size !== scores.length) errors.push("scores: a name is given twice")
296
- const guards: Guard[] = []
297
- for (const [i, g] of (Array.isArray(o.guards) ? o.guards : []).entries()) {
298
- const x = (g ?? {}) as Record<string, unknown>
299
- const tolerance = typeof x.tolerance === "number" && x.tolerance >= 0 ? x.tolerance : undefined
300
- if (typeof x.name !== "string" || !NAME.test(x.name) || !DIRECTIONS.has(String(x.direction)) || tolerance === undefined) {
301
- 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)`)
302
- continue
303
- }
304
- guards.push({ name: x.name, direction: x.direction as Direction, tolerance, origin: x.origin === "redteam" || x.origin === "draft" ? x.origin : "user" })
305
- }
306
- const c = (o.corpus ?? {}) as Record<string, unknown>
307
- const visible = (Array.isArray(c.visible) ? c.visible : []).map(String).map((p) => p.trim()).filter(Boolean)
308
- const outside = visible.filter((p) => p.startsWith("/") || p.split("/").includes(".."))
309
- if (outside.length) errors.push(`corpus.visible: project paths only, not ${outside.join(", ")}`)
310
- const st = (o.stop ?? {}) as Record<string, unknown>
311
- const num = (v: unknown, min = 0) => (typeof v === "number" && Number.isFinite(v) && v > min ? v : undefined)
312
- const target: Record<string, number> = {}
313
- for (const [k, v] of Object.entries((st.target ?? {}) as Record<string, unknown>)) if (typeof v === "number" && Number.isFinite(v)) target[k] = v
314
- const stop = {
315
- ...(Object.keys(target).length ? { target } : {}),
316
- ...(num(st.plateau) ? { plateau: Math.round(num(st.plateau)!) } : {}),
317
- ...(num(st.evaluations) ? { evaluations: Math.round(num(st.evaluations)!) } : {}),
318
- ...(num(st.seconds) ? { seconds: num(st.seconds)! } : {}),
319
- }
320
- const repeats = Math.min(10, Math.max(1, Math.round(num(o.repeats) ?? 1)))
321
- const timeoutMs = Math.min(3_600_000, Math.max(1000, Math.round((num(o.timeoutSeconds) ?? 300) * 1000)))
322
- const heldOutFrom = typeof c.heldOutFrom === "string" && c.heldOutFrom.trim() ? c.heldOutFrom.trim() : undefined
323
- const quick = typeof o.quick === "string" ? o.quick.trim() : ""
324
- if (quick) {
325
- const why = checkProblem(quick) ?? checkSafetyProblem(quick)
326
- if (why) errors.push(`quick: ${why}`)
327
- }
328
- if (errors.length) return { errors }
329
- return { contract: { goal, evaluator, timeoutMs, repeats, scores, guards, corpus: { visible }, stop, ...(quick ? { quick: { evaluator: quick } } : {}) }, ...(heldOutFrom ? { heldOutFrom } : {}), errors }
330
- }
331
-
332
- // What a writer measured against a contract is told about it.
333
- export function contractBrief(c: Contract): string {
334
- 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]!)}` : ""})`)
335
- 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)} %`)
336
- return [
337
- `Your work is measured against fitness contract ${c.id} (version ${c.version}): ${c.goal}`,
338
- `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("; ")}.`,
339
- guards.length ? `Guards: ${guards.join("; ")}.` : "",
340
- "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.",
341
- ].filter(Boolean).join("\n")
342
- }