@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,378 +0,0 @@
1
- // The worktree plugin's handling: the job's own branch and worktree, a task's own worktree, and the merge train that
2
- // puts a task's commits back on the job's branch. It works on its own, with no micromanager installed.
3
- //
4
- // The job's own branch and worktree (design.md §11): workers change files there, never in the user's checkout.
5
- // The worktree lives inside the project, under .micromanager/worktrees/, so workers stay inside the project
6
- // directory (no external_directory ask) and git ignores it through .git/info/exclude.
7
- //
8
- // Branches used to be named jev/<job>. New jobs use micromanager/<job>; old job files keep their recorded branch, so
9
- // finished work still merges and rewinds. Reading checkpoints accepts both prefixes.
10
-
11
- import { execFile } from "node:child_process"
12
- import { existsSync, mkdirSync } from "node:fs"
13
- import { join, relative, resolve, sep } from "node:path"
14
-
15
- import { measuredOf, median, parseScoreLines, type Contract, type Measured } from "../contract.ts"
16
- import { scrub } from "../redact.ts"
17
- import { stateDir } from "../store.ts"
18
- import type { Job, Task } from "../state.ts"
19
-
20
- export const BRANCH_PREFIX = "micromanager"
21
- export const LEGACY_BRANCH_PREFIX = "jev"
22
-
23
- // The job's integration branch. The job file's recorded branch wins, so a job started under the old prefix keeps
24
- // working; only new jobs get the new name.
25
- export function jobBranch(jobId: string): string {
26
- return `${BRANCH_PREFIX}/${jobId}`
27
- }
28
-
29
- export function taskBranch(jobId: string, taskId: string): string {
30
- return `${jobBranch(jobId)}--${taskId}`
31
- }
32
-
33
- // Git always materialises a worktree of the REPOSITORY ROOT, never of the directory the plugin asked from. A project
34
- // that is a subdirectory of the repository (a monorepo package) therefore has to carry its offset into every worktree,
35
- // or the worker is moved to the root, several levels above its own files, and its checks run against the wrong tree.
36
- // state.ts owns these interfaces; the two fields are declared here so the offset travels with the job's JSON and
37
- // survives a restart.
38
- declare module "../state.ts" {
39
- interface Job {
40
- integrationRel?: string // the project directory's path inside the repository root; "" when the project IS the root
41
- integrationBase?: string // the commit the job's branch started from
42
- integrationDirty?: string // uncommitted paths in the user's tree when the worktree was made, "" when it was clean
43
- }
44
- interface Task {
45
- worktreeRel?: string // the same offset for the task's own worktree
46
- }
47
- }
48
-
49
- export interface Run {
50
- readonly code: number
51
- readonly stdout: string
52
- readonly stderr: string
53
- readonly timedOut?: boolean
54
- }
55
-
56
- // env: added to the plugin's own environment, for an evaluator told which corpus to measure on.
57
- export type Exec = (command: string, args: readonly string[], options: { cwd: string; timeoutMs?: number; env?: Readonly<Record<string, string>> }) => Promise<Run>
58
-
59
- // Never throws: a failing command is a result. Gates run with a low priority, so a test suite does not take the
60
- // whole machine.
61
- export const exec: Exec = (command, args, options) =>
62
- new Promise((resolve) => {
63
- const env = options.env ? { ...process.env, ...options.env } : undefined
64
- execFile(command, [...args], { cwd: options.cwd, timeout: options.timeoutMs ?? 120_000, maxBuffer: 8 * 1024 * 1024, ...(env ? { env } : {}) }, (err, stdout, stderr) => {
65
- const e = err as (NodeJS.ErrnoException & { killed?: boolean; code?: number | string }) | null
66
- resolve({
67
- code: e ? (typeof e.code === "number" ? e.code : 1) : 0,
68
- stdout: String(stdout),
69
- stderr: String(stderr) || (e && typeof e.code !== "number" ? e.message : ""),
70
- timedOut: Boolean(e?.killed),
71
- })
72
- })
73
- })
74
-
75
- export interface Integration {
76
- readonly branch: string
77
- readonly worktree: string // the git worktree root: the repository root, not the project
78
- readonly base: string // the commit the branch started from
79
- readonly rel: string // the project directory's path inside the repository root; "" when the project IS the root
80
- readonly dirty: boolean // the user's working tree has changes no worker will see
81
- readonly dirtySummary: string // the first few of those paths
82
- }
83
-
84
- export class IntegrationError extends Error {}
85
-
86
- // The project directory's path inside the repository root, as git reports it. Empty when the project is the root, which
87
- // is the common case and the one where a worktree and the project coincide. An offset that climbs out of the root would
88
- // point a worker at the user's checkout, so it is refused.
89
- export function projectRel(topLevel: string, project: string): string {
90
- const rel = relative(resolve(topLevel), resolve(project)).split(sep).join("/")
91
- if (rel === "") return ""
92
- if (rel === ".." || rel.startsWith("../") || rel.includes("/../") || rel.startsWith("/")) {
93
- throw new IntegrationError(`${project} is not inside the repository ${topLevel}`)
94
- }
95
- return rel
96
- }
97
-
98
- // The project's offset inside its repository, as git reports it from the project. Empty when git cannot answer, which
99
- // keeps the plugin behaving as before (the worktree root stands in for the project) instead of refusing to start.
100
- export async function repoRel(project: string, run: Exec = exec): Promise<string> {
101
- const top = await run("git", ["rev-parse", "--show-toplevel"], { cwd: project })
102
- return top.code === 0 && top.stdout.trim() ? projectRel(top.stdout.trim(), project) : ""
103
- }
104
-
105
- // Where a worker works and where its checks run: the project directory inside a worktree of the repository root. The
106
- // worktree argument is the git worktree root, because that is what git commands need; this is what tools and paths in a
107
- // task's Files and Checks lines resolve against.
108
- export function taskDir(worktree: string, rel: string): string {
109
- if (rel === "") return resolve(worktree)
110
- if (rel.startsWith("/") || rel.split("/").includes("..")) throw new IntegrationError(`a project offset may not leave the worktree: ${rel}`)
111
- return resolve(worktree, ...rel.split("/").filter((p) => p && p !== "."))
112
- }
113
-
114
- // git only checks out paths that exist in the commit, so a project directory with no tracked files (a new slide deck,
115
- // a folder the user will fill later) is missing from a fresh worktree. OpenCode refuses to move a session into a
116
- // missing directory, so the worker's first prompt would never be stored: create it before anyone is moved there.
117
- function materializeTaskDir(worktree: string, rel: string): string {
118
- const dir = taskDir(worktree, rel)
119
- try {
120
- mkdirSync(dir, { recursive: true })
121
- } catch (err) {
122
- const why = err instanceof Error ? err.message : String(err)
123
- throw new IntegrationError(`could not create the project directory ${dir} in the worktree: ${why}`)
124
- }
125
- return dir
126
- }
127
-
128
- // Uncommitted changes in the user's working tree, which no worktree carries: a task that depends on them can never
129
- // pass its checks, so the caller reports it rather than letting a worker discover it.
130
- export async function dirtyPaths(project: string, run: Exec = exec): Promise<{ dirty: boolean; paths: string[]; summary: string }> {
131
- const status = await run("git", ["status", "--porcelain", "-z", "--untracked-files=all"], { cwd: project })
132
- const records = status.stdout.split("\0").filter(Boolean)
133
- const paths: string[] = []
134
- for (let i = 0; i < records.length; i++) {
135
- paths.push(records[i]!.slice(3))
136
- // A rename has its source path as a second NUL-separated record. Both matter for an overlap check.
137
- if (records[i]![0] === "R" || records[i]![0] === "C") paths.push(records[++i] ?? "")
138
- }
139
- const clean = paths.map((path) => path.replace(/\/$/, "")).filter(Boolean)
140
- return { dirty: clean.length > 0, paths: clean, summary: clean.slice(0, 5).join(", ") + (clean.length > 5 ? `, +${clean.length - 5} more` : "") }
141
- }
142
-
143
- // A writer starts from HEAD. Uncommitted versions of files it may change cannot reach it, so starting would either lose
144
- // those edits or end in a merge the user has to untangle. Find that before creating a task or worktree.
145
- export function dirtyDeclared(files: readonly string[], projectRel: string, dirty: readonly string[]): string[] {
146
- const root = projectRel.split(sep).filter(Boolean)
147
- const declared = files.map((file) => [...root, ...file.split("/").filter(Boolean)].join("/"))
148
- return dirty.filter((path) => declared.some((file) => path === file || path.startsWith(`${file}/`) || file.startsWith(`${path}/`)))
149
- }
150
-
151
- export async function prepareIntegration(project: string, jobId: string, run: Exec = exec): Promise<Integration> {
152
- const inside = await run("git", ["rev-parse", "--is-inside-work-tree"], { cwd: project })
153
- if (inside.code !== 0 || inside.stdout.trim() !== "true") throw new IntegrationError(`${project} is not a git repository`)
154
- // The worktree is a checkout of the root, so the offset between the two decides where a worker works and checks run.
155
- const rel = await repoRel(project, run)
156
- const head = await run("git", ["rev-parse", "HEAD"], { cwd: project })
157
- if (head.code !== 0) throw new IntegrationError("the repository has no commit to start from")
158
- // Before the worktree exists: its own checkout must not be counted as the user's uncommitted work.
159
- const { dirty, summary } = await dirtyPaths(project, run)
160
- const branch = jobBranch(jobId)
161
- const worktree = join(project, stateDir(project), "worktrees", jobId)
162
- const added = await run("git", ["worktree", "add", "-q", "-b", branch, worktree, "HEAD"], { cwd: project })
163
- if (added.code !== 0) throw new IntegrationError(`git worktree add failed: ${added.stderr.trim()}`)
164
- materializeTaskDir(worktree, rel)
165
- return { branch, worktree, base: head.stdout.trim(), rel, dirty, dirtySummary: summary }
166
- }
167
-
168
- // Validates the job's integration worktree before it is created or reused: it must exist, be a git work tree, and sit on
169
- // the job's integration branch. Returns an actionable message instead of leaving a cryptic git error for the merge.
170
- export async function validateIntegration(job: Job, run: Exec = exec): Promise<{ ok: true } | { ok: false; message: string }> {
171
- if (!job.integrationWorktree || !job.integrationBranch) {
172
- return { ok: false, message: "the job has no integration worktree or branch recorded" }
173
- }
174
- const wt = job.integrationWorktree
175
- if (!existsSync(wt)) {
176
- return { ok: false, message: `the integration worktree ${wt} does not exist` }
177
- }
178
- const inside = await run("git", ["rev-parse", "--is-inside-work-tree"], { cwd: wt })
179
- if (inside.code !== 0 || inside.stdout.trim() !== "true") {
180
- return { ok: false, message: `the integration worktree ${wt} is not a git work tree (${inside.stderr.trim() || "git rev-parse failed"})` }
181
- }
182
- const head = await run("git", ["rev-parse", "--abbrev-ref", "HEAD"], { cwd: wt })
183
- if (head.code !== 0 || head.stdout.trim() !== job.integrationBranch) {
184
- return { ok: false, message: `the integration worktree ${wt} is on ${head.stdout.trim() || "unknown"}, expected ${job.integrationBranch}` }
185
- }
186
- return { ok: true }
187
- }
188
-
189
- // Files the worker changed in the worktree since the last commit, untracked ones included.
190
- // The paths come back relative to the project directory inside the worktree, the basis every caller compares them on:
191
- // task.files and a task's Checks line are project-relative. git always reports from the repository root, so with a
192
- // non-empty rel the offset is resolved away; a change outside the project comes back as a "../" path, which cannot
193
- // match a declared file (which is what it is: outside).
194
- export async function changedFiles(worktree: string, run: Exec = exec, rel = ""): Promise<string[]> {
195
- const status = await run("git", ["status", "--porcelain", "--untracked-files=all"], { cwd: worktree })
196
- const project = taskDir(worktree, rel)
197
- return status.stdout
198
- .split("\n")
199
- .filter(Boolean)
200
- .map((line) => line.slice(3).trim())
201
- .map((path) => relative(project, resolve(worktree, path)).split(sep).join("/"))
202
- }
203
-
204
- // Commits a passed task on the job's branch. Returns the commit, or undefined when nothing changed.
205
- // The identity is the user's own, as git resolves it: the task's commits belong to them, not to the plugin.
206
- export async function commitTask(worktree: string, subject: string, body: string, run: Exec = exec): Promise<string | undefined> {
207
- if ((await changedFiles(worktree, run)).length === 0) return undefined
208
- await run("git", ["add", "-A"], { cwd: worktree })
209
- // What lands in git history is redacted, like every other egress.
210
- const commit = await run("git", ["commit", "-q", "-m", scrub(subject), "-m", scrub(body)], { cwd: worktree })
211
- if (commit.code !== 0) throw new IntegrationError(`git commit failed: ${commit.stderr.trim()}`)
212
- return (await run("git", ["rev-parse", "--short", "HEAD"], { cwd: worktree })).stdout.trim()
213
- }
214
-
215
- export interface GateResult {
216
- readonly command: string
217
- readonly passed: boolean
218
- readonly code: number
219
- readonly output: string // the tail, enough for the worker to fix it
220
- // The check's own MM_SCORE line (src/contract.ts), read before the output is cut: an ordinary check may say how many
221
- // of its cases passed, which grades a build task without deciding it; pass or fail is still its exit code.
222
- readonly score?: Measured
223
- }
224
-
225
- // The default cap of one check: five minutes. A check is a command the worker wrote, and a command that hangs
226
- // (a test waiting for a port, a build waiting for a network) would hold the gate forever, so it is bounded.
227
- export const DEFAULT_CHECK_TIMEOUT_MS = 300_000
228
-
229
- // How long this job's checks may run: the job's own setting where it has one, else the config's, else the default.
230
- // The job's setting wins over the config's, because a job that was given a longer cap (a slow integration suite)
231
- // should not be cut back to the config's default.
232
- export function checkTimeoutOf(job: Pick<Job, "checkTimeoutMs"> | undefined, configMs?: number): number {
233
- if (job?.checkTimeoutMs !== undefined && Number.isFinite(job.checkTimeoutMs) && job.checkTimeoutMs > 0) return job.checkTimeoutMs
234
- if (configMs !== undefined && Number.isFinite(configMs) && configMs > 0) return configMs
235
- return DEFAULT_CHECK_TIMEOUT_MS
236
- }
237
-
238
- // Runs each check in the task's directory at low priority; a check passes on exit code 0.
239
- // worktree is the git worktree root; dir is where the worker's own paths resolve, which is the project directory inside
240
- // the worktree. Without it a check names a file of the project and the shell looks for it in the wrong tree.
241
- export interface Cancelled {
242
- readonly cancelled?: () => boolean
243
- }
244
-
245
- // cancel: checked between checks, not inside one. A single check is bounded by its own timeout (300s by default),
246
- // because there is nothing to interrupt a shell with once it started; but without this a job with five checks could
247
- // not be stopped until all five ran, and stop_job looked broken for as long as the first one took.
248
- export async function runGate(worktree: string, commands: readonly string[], run: Exec = exec, timeoutMs = DEFAULT_CHECK_TIMEOUT_MS, dir?: string, cancel: Cancelled = {}): Promise<GateResult[]> {
249
- const cwd = dir ?? worktree
250
- const out: GateResult[] = []
251
- for (const command of commands) {
252
- if (cancel.cancelled?.()) {
253
- out.push({ command, passed: false, code: -1, output: "not run: the job was stopped" })
254
- continue
255
- }
256
- const r = await run("nice", ["-n", "15", "sh", "-c", command], { cwd, timeoutMs })
257
- const text = `${r.stdout}\n${r.stderr}`.trim()
258
- const score = parseScoreLines(r.stdout)
259
- out.push({ command, passed: r.code === 0 && !r.timedOut, code: r.code, output: (r.timedOut ? "[timed out]\n" : "") + text.slice(-3000), ...(score ? { score } : {}) })
260
- }
261
- return out
262
- }
263
-
264
- // The cases the checks' MM_SCORE lines counted together; undefined when none of them graded anything.
265
- export function gradedOf(results: readonly GateResult[]): { passed: number; total: number } | undefined {
266
- const cases = results.map((r) => r.score?.cases).filter((c): c is NonNullable<typeof c> => Boolean(c))
267
- return cases.length ? { passed: cases.reduce((s, c) => s + c.passed, 0), total: cases.reduce((s, c) => s + c.total, 0) } : undefined
268
- }
269
-
270
- // A contract's evaluator in the worker's directory, repeated as the contract says; the median of the runs is the
271
- // measurement, and seconds what all runs took (the contract's cost per evaluation, for its stop rule). The evaluator
272
- // is told which corpus it measures on; the held-out corpus (P4) comes with its directory.
273
- export async function runEvaluator(dir: string, contract: Contract, corpus: "visible" | "heldout" = "visible", run: Exec = exec, corpusDir?: string): Promise<{ measured: Measured; seconds: number }> {
274
- const started = Date.now()
275
- const runs: Measured[] = []
276
- for (let i = 0; i < contract.repeats; i++) {
277
- const env = { MM_CORPUS: corpus, MM_REPEAT: String(i + 1), ...(corpusDir ? { MM_CORPUS_DIR: corpusDir } : {}) }
278
- const m = measuredOf(contract, await run("nice", ["-n", "15", "sh", "-c", contract.evaluator], { cwd: dir, timeoutMs: contract.timeoutMs, env }))
279
- runs.push(m)
280
- if (!m.valid) break // one invalid run makes the measurement invalid; the others would only cost time
281
- }
282
- return { measured: median(runs), seconds: Math.round((Date.now() - started) / 100) / 10 }
283
- }
284
-
285
- // The worker's change against the last commit, new files included, for a reviewer that has no git.
286
- export async function workingDiff(worktree: string, run: Exec = exec): Promise<string> {
287
- await run("git", ["add", "-A", "-N"], { cwd: worktree })
288
- return (await run("git", ["diff", "HEAD"], { cwd: worktree })).stdout
289
- }
290
-
291
- // Content hashes of files, to see whether frozen tests were changed; a missing file hashes to "".
292
- // dir: the project directory inside the worktree, because the paths are project-relative (changedFiles).
293
- export async function hashFiles(worktree: string, files: readonly string[], run: Exec = exec, dir = worktree): Promise<Map<string, string>> {
294
- const out = new Map<string, string>()
295
- for (const f of files) out.set(f, (await run("git", ["hash-object", "--", f], { cwd: dir })).stdout.trim())
296
- return out
297
- }
298
-
299
- // The frozen files whose content is no longer what it was when they were frozen (changed, deleted or, for one that did
300
- // not exist, created). dir: the project directory inside the worktree, as for hashFiles.
301
- export async function frozenChanged(worktree: string, frozen: ReadonlyMap<string, string>, run: Exec = exec, dir = worktree): Promise<string[]> {
302
- if (frozen.size === 0) return []
303
- const now = await hashFiles(worktree, [...frozen.keys()], run, dir)
304
- return [...frozen].filter(([f, h]) => now.get(f) !== h).map(([f]) => f)
305
- }
306
-
307
- // Frozen tests must not change: a changed or deleted one fails the gate like a failing check. The runner freezes the
308
- // tests its red stage wrote (P3); a native writer the tests its checks name and its contract's files.
309
- export async function frozenCheck(worktree: string, frozen: ReadonlyMap<string, string>, run: Exec = exec, dir = worktree, why = "changed after the red stage"): Promise<GateResult[]> {
310
- if (frozen.size === 0) return []
311
- const changed = await frozenChanged(worktree, frozen, run, dir)
312
- return [{ command: "frozen tests unchanged", passed: changed.length === 0, code: changed.length ? 1 : 0, output: changed.length ? `${why}: ${changed.join(", ")}; restore them and change the code instead` : "" }]
313
- }
314
-
315
- // Undoes a worker's changes to the given files: tracked ones back to the last commit, new ones removed.
316
- // dir: the project directory inside the worktree, because the paths are project-relative (changedFiles). git resolves a
317
- // pathspec against the directory it runs in, so resolving the wrong one would silently touch a file of the same name.
318
- export async function revertFiles(worktree: string, files: readonly string[], run: Exec = exec, dir = worktree): Promise<void> {
319
- for (const f of files) {
320
- const restored = await run("git", ["checkout", "-q", "HEAD", "--", f], { cwd: dir })
321
- if (restored.code !== 0) await run("git", ["clean", "-q", "-f", "--", f], { cwd: dir })
322
- }
323
- }
324
-
325
- // --- Phase F: parallel writers and the merge train (design.md §11) ------------------------------------------
326
-
327
- export interface TaskWorktree {
328
- readonly branch: string
329
- readonly worktree: string // the git worktree root: what git commands need
330
- readonly dir: string // where the worker works and its checks run: the project directory inside the worktree
331
- readonly rel: string
332
- readonly dirty: boolean
333
- readonly dirtySummary: string
334
- }
335
-
336
- // A task of a parallel batch works in its own worktree, on a branch off the job's branch at its current commit.
337
- // "micromanager/<job>--<task>", since "micromanager/<job>/<task>" cannot sit next to the branch "micromanager/<job>"
338
- // in git's refs. at: another place for it (a continued worker keeps its session's directory). rel: the project's
339
- // offset inside the worktree.
340
- export async function prepareTaskWorktree(project: string, jobId: string, taskId: string, from: string, run: Exec = exec, at?: string, rel = ""): Promise<TaskWorktree> {
341
- const branch = taskBranch(jobId, taskId)
342
- const worktree = at ?? join(project, stateDir(project), "worktrees", `${jobId}--${taskId}`)
343
- await removeTaskWorktree(project, { branch, worktree }, run) // a leftover of an interrupted run
344
- // Before the checkout exists, so the plugin never reports its own worktree as the user's uncommitted work.
345
- const { dirty, summary } = await dirtyPaths(project, run)
346
- const added = await run("git", ["worktree", "add", "-q", "-b", branch, worktree, from], { cwd: project })
347
- if (added.code !== 0) throw new IntegrationError(`git worktree add failed: ${added.stderr.trim()}`)
348
- const dir = materializeTaskDir(worktree, rel)
349
- return { branch, worktree, dir, rel, dirty, dirtySummary: summary }
350
- }
351
-
352
- // Only the worktree root and the branch: a worktree can be removed by name alone, and callers that hold no project
353
- // offset (a removal after a merge) must not have to invent one.
354
- export async function removeTaskWorktree(project: string, w: Pick<TaskWorktree, "branch" | "worktree">, run: Exec = exec): Promise<void> {
355
- await run("git", ["worktree", "remove", "--force", w.worktree], { cwd: project })
356
- await run("git", ["branch", "-D", w.branch], { cwd: project })
357
- }
358
-
359
- export type TrainStep = { readonly ok: true; readonly moved: boolean } | { readonly ok: false; readonly conflict: string }
360
-
361
- // The first half of a merge train step: the task's branch is rebased onto the job's branch when that moved on since
362
- // the task started. moved tells the caller to run the task's checks again before the fast-forward.
363
- export async function rebaseTask(w: Pick<TaskWorktree, "worktree">, integrationBranch: string, run: Exec = exec): Promise<TrainStep> {
364
- const base = (await run("git", ["merge-base", "HEAD", integrationBranch], { cwd: w.worktree })).stdout.trim()
365
- const tip = (await run("git", ["rev-parse", integrationBranch], { cwd: w.worktree })).stdout.trim()
366
- if (base === tip) return { ok: true, moved: false }
367
- const rebased = await run("git", ["rebase", "-q", integrationBranch], { cwd: w.worktree })
368
- if (rebased.code === 0) return { ok: true, moved: true }
369
- const files = (await run("git", ["diff", "--name-only", "--diff-filter=U"], { cwd: w.worktree })).stdout.trim().split("\n").filter(Boolean)
370
- await run("git", ["rebase", "--abort"], { cwd: w.worktree })
371
- return { ok: false, conflict: files.length ? `conflict in ${files.join(", ")}` : rebased.stderr.trim().slice(-500) }
372
- }
373
-
374
- // The second half: the job's branch moves forward to the task's commits; nothing else is ever merged into it.
375
- export async function fastForward(integrationWorktree: string, taskBranch: string, run: Exec = exec): Promise<TrainStep> {
376
- const ff = await run("git", ["merge", "-q", "--ff-only", taskBranch], { cwd: integrationWorktree })
377
- return ff.code === 0 ? { ok: true, moved: false } : { ok: false, conflict: ff.stderr.trim().slice(-500) }
378
- }