@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/src/nogit.ts ADDED
@@ -0,0 +1,112 @@
1
+ // A project folder that is no git repository (the user, 2026-10-20: the micromanager could not work there at all).
2
+ // Workers normally get a git worktree each, so they run in parallel and a change is checked and merged on its own;
3
+ // OpenCode's own worktrees are git worktrees too. So the user is asked, with a form: create a repository, or let the
4
+ // workers change the folder directly, one task after another, checks only (src/native.ts, isolation "none").
5
+ //
6
+ // Whether it is a repository is a fact the code checks. What to recommend is judgement (Jev, src/plugin.ts): a code
7
+ // project wants git, a config folder or notes may not. What the first commit must leave out is decided here, by rules
8
+ // that do not guess: secrets, dependency and build folders, and files too large for a repository.
9
+
10
+ import { lstatSync, readdirSync, writeFileSync, existsSync, readFileSync } from "node:fs"
11
+ import { join } from "node:path"
12
+
13
+ import { exec as defaultExec, type Exec } from "./integration.ts"
14
+
15
+ export type GitState = "repo" | "no-repo" | "no-commit"
16
+
17
+ export async function gitState(project: string, run: Exec = defaultExec): Promise<GitState> {
18
+ const inside = await run("git", ["rev-parse", "--is-inside-work-tree"], { cwd: project }).catch(() => undefined)
19
+ if (!inside || inside.code !== 0 || inside.stdout.trim() !== "true") return "no-repo"
20
+ const head = await run("git", ["rev-parse", "--verify", "--quiet", "HEAD"], { cwd: project }).catch(() => undefined)
21
+ return head && head.code === 0 ? "repo" : "no-commit"
22
+ }
23
+
24
+ // Folders that are installed or built, never written by hand.
25
+ const GENERATED = new Set(["node_modules", ".venv", "venv", "__pycache__", "dist", "build", "target", ".cache", ".next", ".pytest_cache", ".mypy_cache", ".tox", ".gradle"])
26
+ // Names that hold secrets: keys, certificates, environment files, credentials.
27
+ const SECRET = [/^\.env(\..+)?$/i, /\.(pem|key|p12|pfx|kdbx|keystore|jks)$/i, /^id_(rsa|ed25519|ecdsa|dsa)(\.pub)?$/i, /^(credentials|secrets?)(\..+)?$/i, /^\.netrc$/i, /^\.npmrc$/i, /^\.pypirc$/i]
28
+ // The plugin's own state and anything above this size stay out.
29
+ const OWN = new Set([".micromanager", ".jev-micromanager", ".git"])
30
+ export const MAX_FILE_BYTES = 10 * 1024 * 1024
31
+ const MAX_ENTRIES = 20_000 // a folder this large is surveyed only so far
32
+
33
+ export interface Survey {
34
+ readonly files: number
35
+ readonly bytes: number
36
+ readonly excluded: readonly string[] // project-relative, a folder with a trailing "/"
37
+ readonly top: readonly string[] // the top-level names, for the recommendation
38
+ readonly extensions: Readonly<Record<string, number>> // file count per extension, for the recommendation
39
+ }
40
+
41
+ export function surveyFolder(project: string): Survey {
42
+ let files = 0
43
+ let bytes = 0
44
+ let seen = 0
45
+ const excluded: string[] = []
46
+ const extensions: Record<string, number> = {}
47
+ const walk = (dir: string, rel: string) => {
48
+ let names: string[]
49
+ try {
50
+ names = readdirSync(dir)
51
+ } catch {
52
+ return
53
+ }
54
+ for (const name of names) {
55
+ if (++seen > MAX_ENTRIES) return
56
+ const path = join(dir, name)
57
+ const relPath = rel ? `${rel}/${name}` : name
58
+ let st
59
+ try {
60
+ st = lstatSync(path)
61
+ } catch {
62
+ continue
63
+ }
64
+ if (st.isSymbolicLink()) continue
65
+ if (st.isDirectory()) {
66
+ if (OWN.has(name)) continue
67
+ if (GENERATED.has(name)) { excluded.push(`${relPath}/`); continue }
68
+ walk(path, relPath)
69
+ continue
70
+ }
71
+ if (SECRET.some((re) => re.test(name)) || st.size > MAX_FILE_BYTES) { excluded.push(relPath); continue }
72
+ files++
73
+ bytes += st.size
74
+ const ext = name.includes(".") ? name.split(".").pop()!.toLowerCase() : "(none)"
75
+ extensions[ext] = (extensions[ext] ?? 0) + 1
76
+ }
77
+ }
78
+ walk(project, "")
79
+ let top: string[] = []
80
+ try {
81
+ top = readdirSync(project).filter((n) => !OWN.has(n)).slice(0, 40)
82
+ } catch {
83
+ // an unreadable folder: nothing to show
84
+ }
85
+ return { files, bytes, excluded, top, extensions }
86
+ }
87
+
88
+ export function humanSize(bytes: number): string {
89
+ return bytes < 1024 ? `${bytes} B` : bytes < 1024 ** 2 ? `${(bytes / 1024).toFixed(0)} KB` : bytes < 1024 ** 3 ? `${(bytes / 1024 ** 2).toFixed(1)} MB` : `${(bytes / 1024 ** 3).toFixed(1)} GB`
90
+ }
91
+
92
+ // git init, a .gitignore with what stays out (kept and extended when there is one), and a first commit of the rest.
93
+ export async function initRepo(project: string, excluded: readonly string[], run: Exec = defaultExec): Promise<{ ok: boolean; text: string }> {
94
+ const state = await gitState(project, run)
95
+ if (state === "no-repo") {
96
+ const init = await run("git", ["init", "-q"], { cwd: project })
97
+ if (init.code !== 0) return { ok: false, text: `git init failed: ${init.stderr.trim()}` }
98
+ }
99
+ const ignore = join(project, ".gitignore")
100
+ const had = existsSync(ignore) ? readFileSync(ignore, "utf8") : ""
101
+ const lines = had.split("\n").map((l) => l.trim())
102
+ // The plugin's state stays out, except its backlog and contracts, which are the user's to commit (design.md §25).
103
+ const own = [...OWN].filter((n) => n !== ".git").flatMap((n) => [`${n}/*`, `!${n}/backlog/`, `!${n}/contracts/`])
104
+ const add = own.concat(excluded.map((p) => `/${p}`)).filter((p) => !lines.includes(p))
105
+ if (add.length) writeFileSync(ignore, `${had}${had && !had.endsWith("\n") ? "\n" : ""}${had ? "\n" : ""}# left out of the first commit by micromanager\n${add.join("\n")}\n`)
106
+ const staged = await run("git", ["add", "-A"], { cwd: project })
107
+ if (staged.code !== 0) return { ok: false, text: `git add failed: ${staged.stderr.trim()}` }
108
+ // The user's own identity, as git resolves it: without one the commit fails and they see git's own message.
109
+ const commit = await run("git", ["commit", "-qm", "Initial commit", "--allow-empty"], { cwd: project })
110
+ if (commit.code !== 0) return { ok: false, text: `git commit failed: ${commit.stderr.trim()}` }
111
+ return { ok: true, text: `Created a git repository in ${project} with a first commit${excluded.length ? `; left out (in .gitignore): ${excluded.join(", ")}` : ""}.` }
112
+ }
@@ -0,0 +1,210 @@
1
+ // What every writer attempt cost and whether its checks passed, one JSON line per worker end: the data a router can
2
+ // learn from later (phase 2 of the trials plan: a small local model that picks tier, n and families, trained on
3
+ // success minus cost, with tasks compared inside their class). Until then it answers one question for src/trials.ts:
4
+ // does this class of task mostly fail on a single worker?
5
+ // ${XDG_STATE_HOME:-~/.local/state}/micromanager/outcomes.jsonl
6
+
7
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs"
8
+ import { createHash } from "node:crypto"
9
+ import { dirname, join } from "node:path"
10
+
11
+ import { contractHash, reward } from "./contract.ts"
12
+ import { journalPath } from "./journal.ts"
13
+ import { family } from "./roles.ts"
14
+ import { tierFor } from "./registry.ts"
15
+ import type { Job, Task } from "./state.ts"
16
+ import { pickOf } from "./trials.ts"
17
+
18
+ export function outcomesPath(): string {
19
+ return join(dirname(journalPath()), "outcomes.jsonl")
20
+ }
21
+
22
+ export type Gate = "pass" | "fail" | "unverified" | "none"
23
+
24
+ export interface Outcome {
25
+ readonly time: string
26
+ readonly project: string
27
+ readonly job: string
28
+ readonly task: string
29
+ readonly trial?: string // the trial's first attempt; absent for a task in no trial
30
+ readonly n: number // attempts of its trial; 1 without one
31
+ readonly role: string
32
+ readonly model?: string
33
+ readonly family?: string
34
+ readonly difficulty?: number
35
+ readonly cls: string // the task class (role, tier, size) that baselines are taken in
36
+ readonly files: number
37
+ readonly checks: readonly string[]
38
+ readonly brief: string // the task text, cut
39
+ readonly briefHash: string
40
+ readonly gate: Gate // the last gate result
41
+ readonly fixRounds: number
42
+ readonly merged: boolean
43
+ // lost_on_score: its checks passed, but another attempt of its trial had the better score (src/contract.ts);
44
+ // lost_on_quality: passed, ranked below another (a "best" trial); lost_on_pick: passed, the user chose another.
45
+ // combined: passed, and the user had parts of it taken into another attempt, which went on.
46
+ // These are observed results; only sibling_won (stopped by a "first" trial's winner) is censored.
47
+ readonly end: "merged" | "sibling_won" | "lost_on_score" | "lost_on_quality" | "lost_on_pick" | "combined" | "blocked" | "unfinished" | "cancelled"
48
+ // How the winner of a trial was chosen (src/trials.ts Pick): the first to pass, by quality, by a review, by score, or
49
+ // by the user.
50
+ readonly chosenBy?: "first" | "quality" | "review" | "score" | "user"
51
+ readonly seconds?: number // from its delegation to its end
52
+ readonly tokens?: number
53
+ readonly cost?: number
54
+ // A task measured against a fitness contract (src/contract.ts): which version, what it measured last, and the reward,
55
+ // the primary score's improvement over the baseline (positive is better, 0 for an invalid result). The hash tells
56
+ // two versions of "better" apart, which a router must not mix.
57
+ readonly contract?: { readonly id: string; readonly version: number; readonly hash: string }
58
+ readonly score?: { readonly valid: boolean; readonly values: Readonly<Record<string, number>> }
59
+ readonly reward?: number
60
+ readonly graded?: number // the share of cases its checks' own MM_SCORE lines passed, at its last gate
61
+ // Its requests to change a check (src/checkchange.ts): how often the checks or the spec were wrong, and who said so,
62
+ // is something to learn about the tasks and their planners.
63
+ readonly checkChanges?: readonly { readonly kind: string; readonly accepted: boolean; readonly by: string }[]
64
+ // A task the evolver did instead of a worker (src/evolver.ts): the method a router chose, and what it took.
65
+ readonly method?: "evolver"
66
+ readonly steps?: number // the worker's steps until it ended (the adaptive checkpoint learns its first interval from them)
67
+ readonly evolve?: { readonly evaluations: number; readonly valid: number; readonly calls: number }
68
+ }
69
+
70
+ // The class a task is compared in: what a router could know before it starts.
71
+ export function classOf(role: string, difficulty: number | undefined, files: number): string {
72
+ return `${role}:${difficulty === undefined ? "unknown" : tierFor(difficulty)}:${files <= 1 ? "1" : files <= 3 ? "2-3" : "4+"}`
73
+ }
74
+
75
+ // The row for a writer task whose worker ended. usage: the session's tokens and cost, when the caller could read them.
76
+ export function outcomeOf(project: string, job: Job, task: Task, usage?: { tokens: number; cost: number }, now = new Date()): Outcome {
77
+ const gates = task.stages.filter((s) => s.stage === "gate")
78
+ const last = gates.at(-1)
79
+ const gate: Gate = !last ? "none" : last.result === "pass" ? "pass" : /changed no file/.test(last.evidence ?? "") ? "unverified" : "fail"
80
+ const won = task.stages.some((s) => s.stage === "trial" && s.result === "pass" && /won by/.test(s.evidence ?? ""))
81
+ const pick = task.trial ? pickOf(task) : undefined
82
+ const lost = pick === "best" ? "lost_on_quality" : pick === "user" ? "lost_on_pick" : "lost_on_score"
83
+ const combined = task.stages.some((s) => s.stage === "trial" && /^combined into /.test(s.evidence ?? ""))
84
+ const end: Outcome["end"] = task.status === "merged" ? "merged" : task.status === "cancelled" ? (won ? (task.held ? lost : "sibling_won") : combined ? "combined" : "cancelled") : task.status === "blocked" ? "blocked" : "unfinished"
85
+ const winning = task.status === "merged" && task.trial ? task.stages.findLast((s) => s.stage === "trial" && /^won the trial/.test(s.evidence ?? ""))?.evidence : undefined
86
+ // A combination the user asked for won by its next pass, a "first" pick after the fact: the user chose it.
87
+ const asked = task.stages.some((s) => s.stage === "trial" && /^the user asked for a combination/.test(s.evidence ?? ""))
88
+ const chosenBy: Outcome["chosenBy"] = !winning ? undefined : asked || /as the user's pick/.test(winning) ? "user" : /on quality \(on review/.test(winning) ? "review" : /on quality/.test(winning) ? "quality" : /on score/.test(winning) ? "score" : "first"
89
+ const started = task.stages.find((s) => s.stage === "delegate")?.at
90
+ const verify = job.acceptance.filter((a) => task.acceptance.includes(a.id)).map((a) => a.verify).filter((v): v is string => Boolean(v))
91
+ const contract = task.contract && job.contracts?.find((c) => c.id === task.contract!.id)
92
+ const r = contract && task.score ? reward(contract, task.score) : undefined
93
+ return {
94
+ time: now.toISOString(),
95
+ project,
96
+ job: job.id,
97
+ task: task.id,
98
+ ...(task.trial ? { trial: task.trial.of } : {}),
99
+ n: task.trial?.n ?? 1,
100
+ role: task.role,
101
+ ...(task.model ? { model: task.model, family: family(task.model) } : {}),
102
+ ...(task.difficulty !== undefined ? { difficulty: task.difficulty } : {}),
103
+ cls: classOf(task.role, task.difficulty, task.files.length),
104
+ files: task.files.length,
105
+ checks: verify,
106
+ brief: task.description.slice(0, 2000),
107
+ briefHash: createHash("sha256").update(task.description).digest("hex").slice(0, 16),
108
+ gate,
109
+ // A failed fitness measurement is a fix round as much as a failing check (src/native.ts finish).
110
+ fixRounds: task.stages.filter((s) => (s.stage === "gate" || s.stage === "fitness") && s.result === "fail").length,
111
+ merged: task.status === "merged",
112
+ end,
113
+ ...(chosenBy ? { chosenBy } : {}),
114
+ ...(started ? { seconds: Math.round((now.getTime() - Date.parse(started)) / 1000) } : {}),
115
+ ...(usage ? { tokens: usage.tokens, cost: usage.cost } : {}),
116
+ ...(contract ? { contract: { id: contract.id, version: task.contract!.version, hash: contractHash(contract) } } : {}),
117
+ ...(task.score ? { score: { valid: task.score.valid, values: task.score.values } } : {}),
118
+ ...(r !== undefined ? { reward: r } : {}),
119
+ ...(task.graded ? { graded: Math.round((task.graded.passed / task.graded.total) * 1000) / 1000 } : {}),
120
+ ...(task.checkChanges?.length ? { checkChanges: task.checkChanges } : {}),
121
+ ...(task.steps ? { steps: task.steps } : {}),
122
+ ...(task.evolve ? { method: "evolver" as const, evolve: { evaluations: task.evolve.evaluations, valid: task.evolve.valid, calls: task.evolve.calls } } : {}),
123
+ }
124
+ }
125
+
126
+ export function recordOutcome(row: Outcome, path = outcomesPath()): void {
127
+ try {
128
+ mkdirSync(dirname(path), { recursive: true })
129
+ appendFileSync(path, JSON.stringify(row) + "\n")
130
+ } catch {
131
+ // the log must never break a worker's end
132
+ }
133
+ }
134
+
135
+ export function readOutcomes(path = outcomesPath()): Outcome[] {
136
+ if (!existsSync(path)) return []
137
+ return readFileSync(path, "utf8").split("\n").flatMap((line) => {
138
+ if (!line.trim()) return []
139
+ try {
140
+ return [JSON.parse(line) as Outcome]
141
+ } catch {
142
+ return []
143
+ }
144
+ })
145
+ }
146
+
147
+ // Whether tasks of this class mostly fail on a single worker: of its last `window` single attempts (no trial), at least
148
+ // `min` ended, and fewer than half merged. A class that won trials after failed attempts counts too: a trial where
149
+ // some attempt failed and one won says one worker alone would likely have failed.
150
+ export function needsTrials(rows: readonly Outcome[], cls: string, window = 20, min = 4): boolean {
151
+ const mine = rows.filter((r) => r.cls === cls && r.end !== "cancelled")
152
+ const singles = mine.filter((r) => r.n === 1).slice(-window)
153
+ const trials = groupTrials(mine.filter((r) => r.n > 1)).slice(-window)
154
+ const tries = singles.length + trials.reduce((s, t) => s + t.attempts.filter((a) => a.end !== "sibling_won").length, 0)
155
+ if (tries < min) return false
156
+ const passed = singles.filter((r) => r.merged).length + trials.filter((t) => t.k > 0).length
157
+ return passed / tries < 0.5
158
+ }
159
+
160
+ // The steps merged tasks of a class needed, at their 75th percentile: when a task like it is usually done. Undefined
161
+ // below min rows, where a percentile says nothing.
162
+ export function learnedSteps(rows: readonly Outcome[], cls: string, min = 5): number | undefined {
163
+ const steps = rows.filter((r) => r.cls === cls && r.merged && r.steps).map((r) => r.steps!).sort((a, b) => a - b)
164
+ if (steps.length < min) return undefined
165
+ return steps[Math.min(steps.length - 1, Math.ceil(steps.length * 0.75) - 1)]
166
+ }
167
+
168
+ export interface TrialRow {
169
+ readonly key: string // "<job>/<trial or task>"
170
+ readonly cls: string
171
+ readonly n: number
172
+ readonly k: number // attempts whose checks passed
173
+ readonly attempts: readonly Outcome[]
174
+ }
175
+
176
+ function groupTrials(rows: readonly Outcome[]): TrialRow[] {
177
+ const by = new Map<string, Outcome[]>()
178
+ for (const r of rows) {
179
+ const k = `${r.job}/${r.trial ?? r.task}`
180
+ by.set(k, [...(by.get(k) ?? []), r])
181
+ }
182
+ return [...by.entries()].map(([key, attempts]) => ({ key, cls: attempts[0]!.cls, n: attempts[0]!.n, k: attempts.filter((a) => a.gate === "pass").length, attempts }))
183
+ }
184
+
185
+ // export-dataset --target router: one row per task (a trial's attempts joined), with what a router sees before the
186
+ // start, what it chose, and what came of it. Censored attempts (stopped because a sibling won) are kept as such; an
187
+ // attempt that passed and lost on quality, score or the user's pick is an observed result, and the row says which
188
+ // model won and how it was chosen.
189
+ export function routerRows(rows: readonly Outcome[]): Record<string, unknown>[] {
190
+ return groupTrials(rows).map((t) => {
191
+ const first = t.attempts[0]!
192
+ return {
193
+ key: t.key,
194
+ cls: t.cls,
195
+ features: { role: first.role, difficulty: first.difficulty, files: first.files, checks: first.checks, brief: first.brief },
196
+ allocation: { n: t.n, models: t.attempts.map((a) => a.model) },
197
+ outcome: {
198
+ k: t.k,
199
+ merged: t.attempts.some((a) => a.merged),
200
+ censored: t.attempts.filter((a) => a.end === "sibling_won").length,
201
+ tokens: t.attempts.reduce((s, a) => s + (a.tokens ?? 0), 0),
202
+ cost: Math.round(t.attempts.reduce((s, a) => s + (a.cost ?? 0), 0) * 1e6) / 1e6,
203
+ seconds: Math.max(0, ...t.attempts.map((a) => a.seconds ?? 0)),
204
+ ...(t.attempts.some((a) => a.reward !== undefined) ? { reward: Math.max(...t.attempts.map((a) => a.reward ?? 0)) } : {}),
205
+ ...(t.attempts.some((a) => a.chosenBy) ? { winner: t.attempts.find((a) => a.chosenBy)!.model, chosenBy: t.attempts.find((a) => a.chosenBy)!.chosenBy } : {}),
206
+ ...(t.attempts.some((a) => a.end.startsWith("lost_on_")) ? { lost: t.attempts.filter((a) => a.end.startsWith("lost_on_")).map((a) => a.model) } : {}),
207
+ },
208
+ }
209
+ })
210
+ }
package/src/pick.ts ADDED
@@ -0,0 +1,112 @@
1
+ // A trial the user decides (src/trials.ts pick "user"; the user, 2026-10-27: design drafts are a matter of taste). Once
2
+ // every attempt has ended, those that passed are put side by side on a comparison page, and the micromanager asks the
3
+ // user with a form: one of the attempts, a combination ("the layout of T2 with the colours of T3"), or none of them.
4
+ // The answer is read from the form's result, which only the user fills in; the micromanager cannot pick for them.
5
+
6
+ import { formInput, type Question } from "./forms.ts"
7
+ import { HEADER } from "./hooks.ts"
8
+
9
+ // One passed attempt as the comparison shows it.
10
+ export interface Candidate {
11
+ readonly id: string
12
+ readonly model?: string
13
+ readonly cost?: number
14
+ readonly lines: { readonly added: number; readonly removed: number }
15
+ readonly files: readonly string[]
16
+ readonly summary?: string // the worker's own words at finish_task
17
+ readonly preview?: { readonly path: string; readonly png?: Buffer; readonly problem?: string }
18
+ }
19
+
20
+ const COMBINE = "Combine"
21
+ const NONE = "None of them"
22
+ const NOTHING = "Nothing to add"
23
+
24
+ export const pickHeader = (head: string) => `Pick ${head}`
25
+ const notesHeader = (head: string) => `Pick ${head} notes`
26
+
27
+ const money = (n: number | undefined) => (n === undefined ? "cost unknown" : `$${n.toFixed(3)}`)
28
+
29
+ // The form: which attempt, and the user's words for a combination or for none.
30
+ export function pickForm(head: string, title: string, candidates: readonly Candidate[], page: string): Question[] {
31
+ return [
32
+ {
33
+ header: pickHeader(head),
34
+ question: `Which version of "${title.slice(0, 120)}" do you want? The comparison with pictures is in ${page}.`,
35
+ options: [
36
+ ...candidates.map((c) => ({ label: c.id, description: `${c.model ?? "?"} · ${money(c.cost)} · +${c.lines.added}/-${c.lines.removed} lines` })),
37
+ { label: COMBINE, description: "Take parts of several; say which in the next question" },
38
+ { label: NONE, description: "None fits; say why in the next question, and the task is tried again" },
39
+ ],
40
+ },
41
+ {
42
+ header: notesHeader(head),
43
+ question: `For ${COMBINE} or ${NONE}: what should change? Name the versions you mean (e.g. "layout of T2, colours of T3").`,
44
+ options: [{ label: NOTHING, description: "I picked one version above" }],
45
+ },
46
+ ]
47
+ }
48
+
49
+ export type PickAnswer =
50
+ | { readonly kind: "attempt"; readonly id: string; readonly notes?: string }
51
+ | { readonly kind: "combine"; readonly notes?: string }
52
+ | { readonly kind: "none"; readonly notes?: string }
53
+ | { readonly kind: "unclear"; readonly said?: string }
54
+
55
+ // The answer to a pick form, or undefined when the form is none. head: the trial's first attempt, from the header.
56
+ export function readPick(questions: readonly Partial<Question>[], answers: readonly (readonly string[])[]): { head: string; answer: PickAnswer } | undefined {
57
+ const at = questions.findIndex((q) => /^Pick T\d+(?:\.\w+)*$/.test(q.header ?? ""))
58
+ if (at < 0) return undefined
59
+ const head = questions[at]!.header!.slice(5)
60
+ const labels = new Set((questions[at]!.options ?? []).map((o) => o.label))
61
+ const chosen = (answers[at] ?? []).map((a) => a.trim())
62
+ const n = questions.findIndex((q) => q.header === notesHeader(head))
63
+ const typed = (n >= 0 ? answers[n] ?? [] : []).map((a) => a.trim()).filter((a) => a && a !== NOTHING)
64
+ const notes = typed.join(" ") || undefined
65
+ const one = chosen.find((c) => labels.has(c))
66
+ if (!one) return { head, answer: { kind: "unclear", ...(chosen[0] ? { said: chosen[0] } : {}) } }
67
+ if (one === COMBINE) return { head, answer: { kind: "combine", ...(notes ? { notes } : {}) } }
68
+ if (one === NONE) return { head, answer: { kind: "none", ...(notes ? { notes } : {}) } }
69
+ return { head, answer: { kind: "attempt", id: one, ...(notes ? { notes } : {}) } }
70
+ }
71
+
72
+ // What the micromanager reads when every attempt has ended: the form to put to the user.
73
+ export function pickNote(head: string, title: string, candidates: readonly Candidate[], page: string): string {
74
+ return [
75
+ `${HEADER} Every attempt at ${head} (${title.slice(0, 120)}) has ended, and ${candidates.length} passed their checks: ${candidates.map((c) => c.id).join(", ")}. The user picks the version to merge.`,
76
+ `Ask them with the question tool, with exactly this input (a form that waits for their answer; it reaches the plugin by itself), then end your turn; tell them the comparison page is ${page}:`,
77
+ formInput(pickForm(head, title, candidates, page)),
78
+ "Do not pick for them, and do not merge anything yourself: nothing that depends on this task starts before they answer.",
79
+ ].join("\n")
80
+ }
81
+
82
+ // The base of a combination: the first attempt the user's words name, else the first candidate.
83
+ export function combineBase(notes: string | undefined, ids: readonly string[]): string | undefined {
84
+ const named = (notes ?? "").toUpperCase().match(/\bT\d+(?:\.\w+)*\b/g) ?? []
85
+ return named.find((id) => ids.includes(id)) ?? ids[0]
86
+ }
87
+
88
+ const esc = (s: string) => s.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]!)
89
+
90
+ // The comparison page: one column per passed attempt, its picture first. Self-contained, pictures inline.
91
+ export function comparisonPage(head: string, title: string, candidates: readonly Candidate[]): string {
92
+ const cards = candidates.map((c) => {
93
+ const pic = c.preview?.png
94
+ ? `<img src="data:image/png;base64,${c.preview.png.toString("base64")}" alt="${esc(c.id)}: ${esc(c.preview.path)}">`
95
+ : `<p class="none">${esc(c.preview?.problem ?? "No picture: the task named no preview.")}</p>`
96
+ return `<section><h2>${esc(c.id)}</h2><p class="meta">${esc(c.model ?? "?")} · ${esc(money(c.cost))} · +${c.lines.added}/-${c.lines.removed} lines · ${c.files.length} file${c.files.length === 1 ? "" : "s"}</p>${pic}${c.summary ? `<p>${esc(c.summary)}</p>` : ""}<details><summary>Files</summary><ul>${c.files.map((f) => `<li><code>${esc(f)}</code></li>`).join("")}</ul></details></section>`
97
+ }).join("\n")
98
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Pick ${esc(head)}</title>
99
+ <style>
100
+ :root{--bg:#f4f5f7;--card:#fff;--ink:#1b1f24;--muted:#5c6570;--line:#d6dbe1;color-scheme:light}
101
+ @media (prefers-color-scheme:dark){:root{--bg:#111418;--card:#1a1f25;--ink:#e6eaef;--muted:#98a2ad;--line:#2c343d;color-scheme:dark}}
102
+ body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.5 system-ui,sans-serif;padding:20px}
103
+ h1{font-size:22px;margin:0 0 4px}.lead{color:var(--muted);margin:0 0 18px}
104
+ main{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:16px;align-items:start}
105
+ section{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:14px;min-width:0}
106
+ h2{margin:0;font-size:18px}.meta{color:var(--muted);font-size:13px;margin:2px 0 10px}
107
+ img{width:100%;border:1px solid var(--line);border-radius:6px;display:block}.none{color:var(--muted);font-style:italic}
108
+ code{font-size:12px}
109
+ </style></head><body><h1>Pick a version of ${esc(head)}</h1><p class="lead">${esc(title)}: every version below passed its checks. Answer in the form in OpenCode.</p><main>
110
+ ${cards}
111
+ </main></body></html>`
112
+ }