@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.
- package/LICENSE +201 -0
- package/README.md +27 -2
- package/evolver/mm_evolve/__init__.py +1 -0
- package/evolver/mm_evolve/entry.py +3 -0
- package/evolver/mm_evolve/evaluator.py +119 -0
- package/evolver/mm_evolve/llm.py +76 -0
- package/evolver/mm_evolve/run.py +89 -0
- package/evolver/mm_evolve/spec.py +62 -0
- package/evolver/pyproject.toml +21 -0
- package/evolver/uv.lock +772 -0
- package/package.json +55 -4
- package/skills/THIRD_PARTY.md +58 -0
- package/skills/code-review/SKILL.md +46 -0
- package/skills/deliberate/SKILL.md +39 -0
- package/skills/diagnosing-bugs/SKILL.md +75 -0
- package/skills/receiving-code-review/SKILL.md +36 -0
- package/skills/research/SKILL.md +18 -0
- package/skills/tdd/SKILL.md +56 -0
- package/skills/tdd/mocking.md +59 -0
- package/skills/tdd/tests.md +77 -0
- package/skills/verification-before-completion/SKILL.md +50 -0
- package/src/agenda.ts +56 -0
- package/src/agents.ts +74 -0
- package/src/ask.ts +243 -0
- package/src/backends.ts +144 -0
- package/src/backlog.ts +436 -0
- package/src/bench.ts +163 -0
- package/src/board.ts +1 -0
- package/src/brief.ts +151 -0
- package/src/browser.ts +624 -0
- package/src/budget.ts +73 -0
- package/src/catalog.ts +214 -0
- package/src/checkchange.ts +180 -0
- package/src/checkpoint.ts +99 -0
- package/src/cli.ts +117 -0
- package/src/compact.ts +162 -0
- package/src/config.ts +340 -0
- package/src/context/capture.ts +1 -0
- package/src/context/digest.ts +1 -0
- package/src/context/embed.ts +1 -0
- package/src/context/index.ts +2 -0
- package/src/context/ledger.ts +1 -0
- package/src/context/manager.ts +1 -0
- package/src/context/memory.ts +1 -0
- package/src/context/policy.ts +1 -0
- package/src/context/prices.ts +1 -0
- package/src/context/recall.ts +1 -0
- package/src/context/rules.ts +1 -0
- package/src/context/search.ts +1 -0
- package/src/context/status.ts +1 -0
- package/src/context/store.ts +1 -0
- package/src/context/summary.ts +1 -0
- package/src/context/tokens.ts +1 -0
- package/src/context/tools.ts +1 -0
- package/src/continuation.ts +122 -0
- package/src/contract.ts +342 -0
- package/src/contractround.ts +225 -0
- package/src/control.ts +1 -0
- package/src/dataset.ts +133 -0
- package/src/decide.ts +690 -0
- package/src/eval.ts +66 -0
- package/src/evolver.ts +369 -0
- package/src/followups.ts +50 -0
- package/src/forms.ts +191 -0
- package/src/gate.ts +90 -0
- package/src/grants.ts +239 -0
- package/src/graph.ts +74 -0
- package/src/guard/index.ts +1 -0
- package/src/guard/wire.ts +1 -0
- package/src/helpers.ts +105 -0
- package/src/hooks.ts +199 -0
- package/src/integration.ts +4 -0
- package/src/jev.ts +141 -0
- package/src/journal.ts +1 -0
- package/src/look.ts +390 -0
- package/src/memory.ts +1 -0
- package/src/native.ts +2455 -0
- package/src/nogit.ts +112 -0
- package/src/outcomes.ts +210 -0
- package/src/pick.ts +112 -0
- package/src/pipelines.ts +252 -0
- package/src/plan.ts +449 -0
- package/src/plugin.ts +3187 -0
- package/src/policy.ts +84 -0
- package/src/pools.ts +1 -0
- package/src/profile.ts +186 -0
- package/src/progress.ts +1 -0
- package/src/redact.ts +1 -0
- package/src/registry.ts +207 -0
- package/src/roles.ts +1 -0
- package/src/routing.ts +1 -0
- package/src/runner.ts +1506 -0
- package/src/sandbox.ts +4 -0
- package/src/scheduler.ts +200 -0
- package/src/session.ts +269 -0
- package/src/shell/decide.ts +1 -0
- package/src/shell/index.ts +2 -0
- package/src/shell/sandbox.ts +1 -0
- package/src/shell/wire.ts +1 -0
- package/src/skills.ts +111 -0
- package/src/state.ts +1 -0
- package/src/store.ts +1 -0
- package/src/switcher.ts +1 -0
- package/src/tools.ts +480 -0
- package/src/trials.ts +247 -0
- package/src/usage.ts +1 -0
- package/src/wait.ts +180 -0
- package/src/watchdog.ts +498 -0
- package/src/worktree/git.ts +378 -0
|
@@ -0,0 +1,378 @@
|
|
|
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
|
+
}
|