@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.
- package/README.md +7 -4
- package/THIRD_PARTY.md +100 -0
- package/decider/.python-version +1 -0
- package/decider/README.md +35 -0
- package/decider/decider/__init__.py +1 -0
- package/decider/decider/server.py +327 -0
- package/decider/pyproject.toml +34 -0
- package/decider/uv.lock +1255 -0
- package/dist/agenda.js +51 -0
- package/dist/agents.js +58 -0
- package/dist/artifact/handoff.js +281 -0
- package/dist/ask.js +200 -0
- package/dist/backends.js +219 -0
- package/dist/backlog.js +414 -0
- package/dist/bench.js +427 -0
- package/dist/board.js +1 -0
- package/dist/brief.js +202 -0
- package/dist/browser.js +679 -0
- package/dist/budget.js +61 -0
- package/dist/catalog.js +187 -0
- package/dist/checkchange.js +145 -0
- package/dist/checkpoint.js +94 -0
- package/dist/cli.js +764 -0
- package/dist/comfy-gate.js +258 -0
- package/dist/compact.js +142 -0
- package/dist/config.js +344 -0
- package/dist/context/capture.js +1 -0
- package/dist/context/digest.js +1 -0
- package/dist/context/embed.js +1 -0
- package/dist/context/index.js +2 -0
- package/dist/context/ledger.js +1 -0
- package/dist/context/manager.js +1 -0
- package/dist/context/memory.js +1 -0
- package/dist/context/policy.js +1 -0
- package/dist/context/prices.js +1 -0
- package/dist/context/recall.js +1 -0
- package/dist/context/rules.js +1 -0
- package/dist/context/search.js +1 -0
- package/dist/context/status.js +1 -0
- package/dist/context/store.js +1 -0
- package/dist/context/summary.js +1 -0
- package/dist/context/tokens.js +1 -0
- package/dist/context/tools.js +1 -0
- package/dist/continuation.js +184 -0
- package/dist/contract.js +294 -0
- package/dist/contractround.js +178 -0
- package/dist/control.js +1 -0
- package/dist/creative-tools.js +237 -0
- package/dist/dataset.js +175 -0
- package/dist/decide.js +676 -0
- package/dist/decider.js +171 -0
- package/dist/design-shell.js +448 -0
- package/dist/design.js +1410 -0
- package/dist/desktop.js +44 -0
- package/dist/egress.js +156 -0
- package/dist/eval.js +60 -0
- package/dist/evolver.js +302 -0
- package/dist/features.js +193 -0
- package/dist/followups.js +32 -0
- package/dist/forms.js +195 -0
- package/dist/gate.js +108 -0
- package/dist/gatebox.js +46 -0
- package/dist/grants.js +189 -0
- package/dist/graph.js +65 -0
- package/dist/guard/index.js +1 -0
- package/dist/guard/wire.js +1 -0
- package/dist/helpers.js +85 -0
- package/dist/hooks.js +158 -0
- package/dist/image-models.js +117 -0
- package/{src/integration.ts → dist/integration.js} +1 -2
- package/dist/journal.js +1 -0
- package/dist/look.js +363 -0
- package/dist/memory.js +1 -0
- package/dist/mode.js +97 -0
- package/dist/native.js +3348 -0
- package/dist/nogit.js +259 -0
- package/dist/outcomes.js +148 -0
- package/dist/permission.js +35 -0
- package/dist/pick.js +89 -0
- package/dist/pipelines.js +262 -0
- package/dist/plan.js +641 -0
- package/dist/plandoc.js +211 -0
- package/dist/plugin.js +4736 -0
- package/dist/policy.js +58 -0
- package/dist/pools.js +1 -0
- package/dist/preview.js +274 -0
- package/dist/profile.js +165 -0
- package/dist/progress.js +1 -0
- package/dist/promote.js +313 -0
- package/dist/redact.js +1 -0
- package/dist/registry.js +179 -0
- package/dist/riskscore.js +126 -0
- package/dist/roles.js +1 -0
- package/dist/routing.js +1 -0
- package/dist/runner.js +1892 -0
- package/{src/sandbox.ts → dist/sandbox.js} +1 -2
- package/dist/sandboxgate.js +90 -0
- package/dist/scheduler.js +170 -0
- package/dist/services-main.js +131 -0
- package/dist/services.js +265 -0
- package/dist/session.js +241 -0
- package/dist/setup.js +423 -0
- package/dist/shell/decide.js +1 -0
- package/dist/shell/index.js +2 -0
- package/dist/shell/sandbox.js +1 -0
- package/dist/shell/wire.js +1 -0
- package/dist/skills.js +103 -0
- package/dist/state.js +1 -0
- package/dist/store.js +1 -0
- package/dist/switcher.js +1 -0
- package/dist/synth.js +418 -0
- package/dist/tools.js +477 -0
- package/dist/trials.js +223 -0
- package/dist/usage.js +1 -0
- package/dist/wait.js +167 -0
- package/dist/watchdog.js +476 -0
- package/dist/web-guidance.js +43 -0
- package/dist/which.js +20 -0
- package/dist/worktree/git.js +545 -0
- package/dist/writeguard.js +311 -0
- package/package.json +36 -17
- package/skills/deck/SKILL.md +98 -0
- package/skills/design/SKILL.md +150 -0
- package/skills/image/SKILL.md +66 -0
- package/skills/orchestrator/SKILL.md +107 -0
- package/skills/video/SKILL.md +97 -0
- package/skills/web/SKILL.md +60 -0
- package/src/agenda.ts +0 -56
- package/src/agents.ts +0 -74
- package/src/ask.ts +0 -243
- package/src/backends.ts +0 -144
- package/src/backlog.ts +0 -436
- package/src/bench.ts +0 -163
- package/src/board.ts +0 -1
- package/src/brief.ts +0 -151
- package/src/browser.ts +0 -624
- package/src/budget.ts +0 -73
- package/src/catalog.ts +0 -214
- package/src/checkchange.ts +0 -180
- package/src/checkpoint.ts +0 -99
- package/src/cli.ts +0 -117
- package/src/compact.ts +0 -162
- package/src/config.ts +0 -340
- package/src/context/capture.ts +0 -1
- package/src/context/digest.ts +0 -1
- package/src/context/embed.ts +0 -1
- package/src/context/index.ts +0 -2
- package/src/context/ledger.ts +0 -1
- package/src/context/manager.ts +0 -1
- package/src/context/memory.ts +0 -1
- package/src/context/policy.ts +0 -1
- package/src/context/prices.ts +0 -1
- package/src/context/recall.ts +0 -1
- package/src/context/rules.ts +0 -1
- package/src/context/search.ts +0 -1
- package/src/context/status.ts +0 -1
- package/src/context/store.ts +0 -1
- package/src/context/summary.ts +0 -1
- package/src/context/tokens.ts +0 -1
- package/src/context/tools.ts +0 -1
- package/src/continuation.ts +0 -122
- package/src/contract.ts +0 -342
- package/src/contractround.ts +0 -225
- package/src/control.ts +0 -1
- package/src/dataset.ts +0 -133
- package/src/decide.ts +0 -690
- package/src/eval.ts +0 -66
- package/src/evolver.ts +0 -369
- package/src/followups.ts +0 -50
- package/src/forms.ts +0 -191
- package/src/gate.ts +0 -90
- package/src/grants.ts +0 -239
- package/src/graph.ts +0 -74
- package/src/guard/index.ts +0 -1
- package/src/guard/wire.ts +0 -1
- package/src/helpers.ts +0 -105
- package/src/hooks.ts +0 -199
- package/src/jev.ts +0 -141
- package/src/journal.ts +0 -1
- package/src/look.ts +0 -390
- package/src/memory.ts +0 -1
- package/src/native.ts +0 -2455
- package/src/nogit.ts +0 -112
- package/src/outcomes.ts +0 -210
- package/src/pick.ts +0 -112
- package/src/pipelines.ts +0 -252
- package/src/plan.ts +0 -449
- package/src/plugin.ts +0 -3187
- package/src/policy.ts +0 -84
- package/src/pools.ts +0 -1
- package/src/profile.ts +0 -186
- package/src/progress.ts +0 -1
- package/src/redact.ts +0 -1
- package/src/registry.ts +0 -207
- package/src/roles.ts +0 -1
- package/src/routing.ts +0 -1
- package/src/runner.ts +0 -1506
- package/src/scheduler.ts +0 -200
- package/src/session.ts +0 -269
- package/src/shell/decide.ts +0 -1
- package/src/shell/index.ts +0 -2
- package/src/shell/sandbox.ts +0 -1
- package/src/shell/wire.ts +0 -1
- package/src/skills.ts +0 -111
- package/src/state.ts +0 -1
- package/src/store.ts +0 -1
- package/src/switcher.ts +0 -1
- package/src/tools.ts +0 -480
- package/src/trials.ts +0 -247
- package/src/usage.ts +0 -1
- package/src/wait.ts +0 -180
- package/src/watchdog.ts +0 -498
- package/src/worktree/git.ts +0 -378
|
@@ -0,0 +1,545 @@
|
|
|
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 <state dir>/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
|
+
import { execFile } from "node:child_process";
|
|
11
|
+
import { createHash } from "node:crypto";
|
|
12
|
+
import { existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
|
|
13
|
+
import { basename, join, relative, resolve, sep } from "node:path";
|
|
14
|
+
import { statePath } from "@omacode/core/paths";
|
|
15
|
+
import { measuredOf, median, parseScoreLines } from "../contract.js";
|
|
16
|
+
import { scrub } from "../redact.js";
|
|
17
|
+
import { stateDir } from "../store.js";
|
|
18
|
+
export const BRANCH_PREFIX = "micromanager";
|
|
19
|
+
export const LEGACY_BRANCH_PREFIX = "jev";
|
|
20
|
+
// The job's integration branch. The job file's recorded branch wins, so a job started under the old prefix keeps
|
|
21
|
+
// working; only new jobs get the new name.
|
|
22
|
+
export function jobBranch(jobId) {
|
|
23
|
+
return `${BRANCH_PREFIX}/${jobId}`;
|
|
24
|
+
}
|
|
25
|
+
export function taskBranch(jobId, taskId) {
|
|
26
|
+
return `${jobBranch(jobId)}--${taskId}`;
|
|
27
|
+
}
|
|
28
|
+
// Never throws: a failing command is a result. Gates run with a low priority, so a test suite does not take the
|
|
29
|
+
// whole machine.
|
|
30
|
+
export const exec = (command, args, options) => new Promise((resolve) => {
|
|
31
|
+
const env = options.env ? { ...process.env, ...options.env } : undefined;
|
|
32
|
+
execFile(command, [...args], { cwd: options.cwd, timeout: options.timeoutMs ?? 120_000, maxBuffer: 8 * 1024 * 1024, ...(env ? { env } : {}) }, (err, stdout, stderr) => {
|
|
33
|
+
const e = err;
|
|
34
|
+
resolve({
|
|
35
|
+
code: e ? (typeof e.code === "number" ? e.code : 1) : 0,
|
|
36
|
+
stdout: String(stdout),
|
|
37
|
+
stderr: String(stderr) || (e && typeof e.code !== "number" ? e.message : ""),
|
|
38
|
+
timedOut: Boolean(e?.killed),
|
|
39
|
+
});
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
export class IntegrationError extends Error {
|
|
43
|
+
}
|
|
44
|
+
// The project directory's path inside the repository root, as git reports it. Empty when the project is the root, which
|
|
45
|
+
// is the common case and the one where a worktree and the project coincide. An offset that climbs out of the root would
|
|
46
|
+
// point a worker at the user's checkout, so it is refused.
|
|
47
|
+
export function projectRel(topLevel, project) {
|
|
48
|
+
const rel = relative(resolve(topLevel), resolve(project)).split(sep).join("/");
|
|
49
|
+
if (rel === "")
|
|
50
|
+
return "";
|
|
51
|
+
if (rel === ".." || rel.startsWith("../") || rel.includes("/../") || rel.startsWith("/")) {
|
|
52
|
+
throw new IntegrationError(`${project} is not inside the repository ${topLevel}`);
|
|
53
|
+
}
|
|
54
|
+
return rel;
|
|
55
|
+
}
|
|
56
|
+
// The project's offset inside its repository, as git reports it from the project. Empty when git cannot answer, which
|
|
57
|
+
// keeps the plugin behaving as before (the worktree root stands in for the project) instead of refusing to start.
|
|
58
|
+
export async function repoRel(project, run = exec) {
|
|
59
|
+
const top = await run("git", ["rev-parse", "--show-toplevel"], { cwd: project });
|
|
60
|
+
return top.code === 0 && top.stdout.trim() ? projectRel(top.stdout.trim(), project) : "";
|
|
61
|
+
}
|
|
62
|
+
// Where a worker works and where its checks run: the project directory inside a worktree of the repository root. The
|
|
63
|
+
// worktree argument is the git worktree root, because that is what git commands need; this is what tools and paths in a
|
|
64
|
+
// task's Files and Checks lines resolve against.
|
|
65
|
+
export function taskDir(worktree, rel) {
|
|
66
|
+
if (rel === "")
|
|
67
|
+
return resolve(worktree);
|
|
68
|
+
if (rel.startsWith("/") || rel.split("/").includes(".."))
|
|
69
|
+
throw new IntegrationError(`a project offset may not leave the worktree: ${rel}`);
|
|
70
|
+
return resolve(worktree, ...rel.split("/").filter((p) => p && p !== "."));
|
|
71
|
+
}
|
|
72
|
+
// git only checks out paths that exist in the commit, so a project directory with no tracked files (a new slide deck,
|
|
73
|
+
// a folder the user will fill later) is missing from a fresh worktree. OpenCode refuses to move a session into a
|
|
74
|
+
// missing directory, so the worker's first prompt would never be stored: create it before anyone is moved there.
|
|
75
|
+
function materializeTaskDir(worktree, rel) {
|
|
76
|
+
const dir = taskDir(worktree, rel);
|
|
77
|
+
try {
|
|
78
|
+
mkdirSync(dir, { recursive: true });
|
|
79
|
+
}
|
|
80
|
+
catch (err) {
|
|
81
|
+
const why = err instanceof Error ? err.message : String(err);
|
|
82
|
+
throw new IntegrationError(`could not create the project directory ${dir} in the worktree: ${why}`);
|
|
83
|
+
}
|
|
84
|
+
return dir;
|
|
85
|
+
}
|
|
86
|
+
// Uncommitted changes in the user's working tree, which no worktree carries: a task that depends on them can never
|
|
87
|
+
// pass its checks, so the caller reports it rather than letting a worker discover it.
|
|
88
|
+
export async function dirtyPaths(project, run = exec) {
|
|
89
|
+
const status = await run("git", ["status", "--porcelain", "-z", "--untracked-files=all"], { cwd: project });
|
|
90
|
+
const records = status.stdout.split("\0").filter(Boolean);
|
|
91
|
+
const paths = [];
|
|
92
|
+
for (let i = 0; i < records.length; i++) {
|
|
93
|
+
paths.push(records[i].slice(3));
|
|
94
|
+
// A rename has its source path as a second NUL-separated record. Both matter for an overlap check.
|
|
95
|
+
if (records[i][0] === "R" || records[i][0] === "C")
|
|
96
|
+
paths.push(records[++i] ?? "");
|
|
97
|
+
}
|
|
98
|
+
const clean = paths.map((path) => path.replace(/\/$/, "")).filter(Boolean);
|
|
99
|
+
return { dirty: clean.length > 0, paths: clean, summary: clean.slice(0, 5).join(", ") + (clean.length > 5 ? `, +${clean.length - 5} more` : "") };
|
|
100
|
+
}
|
|
101
|
+
// A writer starts from HEAD. Uncommitted versions of files it may change cannot reach it, so starting would either lose
|
|
102
|
+
// those edits or end in a merge the user has to untangle. Find that before creating a task or worktree.
|
|
103
|
+
export function dirtyDeclared(files, projectRel, dirty) {
|
|
104
|
+
const root = projectRel.split(sep).filter(Boolean);
|
|
105
|
+
const declared = files.map((file) => [...root, ...file.split("/").filter(Boolean)].join("/"));
|
|
106
|
+
return dirty.filter((path) => declared.some((file) => path === file || path.startsWith(`${file}/`) || file.startsWith(`${path}/`)));
|
|
107
|
+
}
|
|
108
|
+
export async function prepareIntegration(project, jobId, run = exec) {
|
|
109
|
+
const inside = await run("git", ["rev-parse", "--is-inside-work-tree"], { cwd: project });
|
|
110
|
+
if (inside.code !== 0 || inside.stdout.trim() !== "true")
|
|
111
|
+
throw new IntegrationError(`${project} is not a git repository`);
|
|
112
|
+
// The worktree is a checkout of the root, so the offset between the two decides where a worker works and checks run.
|
|
113
|
+
const rel = await repoRel(project, run);
|
|
114
|
+
const head = await run("git", ["rev-parse", "HEAD"], { cwd: project });
|
|
115
|
+
if (head.code !== 0)
|
|
116
|
+
throw new IntegrationError("the repository has no commit to start from");
|
|
117
|
+
// Before the worktree exists: its own checkout must not be counted as the user's uncommitted work.
|
|
118
|
+
const { dirty, summary } = await dirtyPaths(project, run);
|
|
119
|
+
const branch = jobBranch(jobId);
|
|
120
|
+
const worktree = join(project, stateDir(project), "worktrees", jobId);
|
|
121
|
+
const added = await run("git", ["worktree", "add", "-q", "-b", branch, worktree, "HEAD"], { cwd: project });
|
|
122
|
+
if (added.code !== 0)
|
|
123
|
+
throw new IntegrationError(`git worktree add failed: ${added.stderr.trim()}`);
|
|
124
|
+
materializeTaskDir(worktree, rel);
|
|
125
|
+
return { branch, worktree, base: head.stdout.trim(), rel, dirty, dirtySummary: summary };
|
|
126
|
+
}
|
|
127
|
+
// Validates the job's integration worktree before it is created or reused: it must exist, be a registered git work
|
|
128
|
+
// tree, sit on the job's integration branch, and point at that branch's tip. project is optional only for callers that
|
|
129
|
+
// predate the path checks (tests); the real callers pass it. Returns an actionable message instead of leaving a
|
|
130
|
+
// cryptic git error for the merge.
|
|
131
|
+
export async function validateIntegration(job, run = exec, project) {
|
|
132
|
+
if (!job.integrationWorktree || !job.integrationBranch) {
|
|
133
|
+
return { ok: false, message: "the job has no integration worktree or branch recorded" };
|
|
134
|
+
}
|
|
135
|
+
const wt = job.integrationWorktree;
|
|
136
|
+
const resolved = resolve(wt);
|
|
137
|
+
if (!existsSync(wt)) {
|
|
138
|
+
return { ok: false, message: `the integration worktree ${wt} does not exist` };
|
|
139
|
+
}
|
|
140
|
+
// Without git, the project folder itself is the integration worktree (src/native.ts, isolation: "none").
|
|
141
|
+
const noGit = job.isolation === "none";
|
|
142
|
+
if (!noGit && project && resolve(project) === resolved) {
|
|
143
|
+
return { ok: false, message: `the integration worktree ${wt} is the project checkout; it must be the job's own worktree` };
|
|
144
|
+
}
|
|
145
|
+
// A task worktree is named "<job>--T…"; it must never become the integration worktree (live run: this is how the
|
|
146
|
+
// job worktree was destroyed and every merge became a no-op).
|
|
147
|
+
if (!noGit && basename(wt).startsWith(`${job.id}--`)) {
|
|
148
|
+
return { ok: false, message: `the integration worktree ${wt} is a task worktree, not the job's worktree` };
|
|
149
|
+
}
|
|
150
|
+
const inside = await run("git", ["rev-parse", "--is-inside-work-tree"], { cwd: wt });
|
|
151
|
+
if (inside.code !== 0 || inside.stdout.trim() !== "true") {
|
|
152
|
+
return { ok: false, message: `the integration worktree ${wt} is not a git work tree (${inside.stderr.trim() || "git rev-parse failed"})` };
|
|
153
|
+
}
|
|
154
|
+
// Registered with git, not merely a directory that happens to be there: a stale or copied checkout would otherwise
|
|
155
|
+
// pass the checks below and then fail the merge with "not a work tree".
|
|
156
|
+
const list = await run("git", ["worktree", "list", "--porcelain"], { cwd: wt });
|
|
157
|
+
const registered = list.code === 0
|
|
158
|
+
? list.stdout.split("\n").filter((line) => line.startsWith("worktree ")).map((line) => resolve(line.slice("worktree ".length).trim()))
|
|
159
|
+
: [];
|
|
160
|
+
if (!registered.includes(resolved)) {
|
|
161
|
+
return { ok: false, message: `the integration worktree ${wt} is not registered with git (run git worktree prune and recreate it)` };
|
|
162
|
+
}
|
|
163
|
+
const head = await run("git", ["rev-parse", "--abbrev-ref", "HEAD"], { cwd: wt });
|
|
164
|
+
if (head.code !== 0 || head.stdout.trim() !== job.integrationBranch) {
|
|
165
|
+
return { ok: false, message: `the integration worktree ${wt} is on ${head.stdout.trim() || "unknown"}, expected ${job.integrationBranch}` };
|
|
166
|
+
}
|
|
167
|
+
// The branch name is not enough: a renamed or stale ref can leave the worktree on a commit that is not the branch's
|
|
168
|
+
// tip. A merge from there silently loses the other tasks' commits.
|
|
169
|
+
const headSha = await run("git", ["rev-parse", "HEAD"], { cwd: wt });
|
|
170
|
+
const tipSha = await run("git", ["rev-parse", "--verify", job.integrationBranch], { cwd: wt });
|
|
171
|
+
if (headSha.code !== 0 || tipSha.code !== 0 || headSha.stdout.trim() !== tipSha.stdout.trim()) {
|
|
172
|
+
return { ok: false, message: `the integration worktree ${wt} is at ${headSha.stdout.trim() || "unknown"}, but ${job.integrationBranch} is at ${tipSha.stdout.trim() || "unknown"}; reset it to the branch before merging` };
|
|
173
|
+
}
|
|
174
|
+
return { ok: true };
|
|
175
|
+
}
|
|
176
|
+
// Files the worker changed in the worktree since the last commit, untracked ones included.
|
|
177
|
+
// The paths come back relative to the project directory inside the worktree, the basis every caller compares them on:
|
|
178
|
+
// task.files and a task's Checks line are project-relative. git always reports from the repository root, so with a
|
|
179
|
+
// non-empty rel the offset is resolved away; a change outside the project comes back as a "../" path, which cannot
|
|
180
|
+
// match a declared file (which is what it is: outside).
|
|
181
|
+
export async function changedFiles(worktree, run = exec, rel = "") {
|
|
182
|
+
const status = await run("git", ["status", "--porcelain", "--untracked-files=all"], { cwd: worktree });
|
|
183
|
+
const project = taskDir(worktree, rel);
|
|
184
|
+
return status.stdout
|
|
185
|
+
.split("\n")
|
|
186
|
+
.filter(Boolean)
|
|
187
|
+
.map((line) => line.slice(3).trim())
|
|
188
|
+
.map((path) => relative(project, resolve(worktree, path)).split(sep).join("/"));
|
|
189
|
+
}
|
|
190
|
+
// Commits a passed task on the job's branch. Returns the commit, or undefined when nothing changed.
|
|
191
|
+
// The identity is the user's own, as git resolves it: the task's commits belong to them, not to the plugin.
|
|
192
|
+
export async function commitTask(worktree, subject, body, run = exec) {
|
|
193
|
+
if ((await changedFiles(worktree, run)).length === 0)
|
|
194
|
+
return undefined;
|
|
195
|
+
await run("git", ["add", "-A"], { cwd: worktree });
|
|
196
|
+
// What lands in git history is redacted, like every other egress.
|
|
197
|
+
const commit = await run("git", ["commit", "-q", "-m", scrub(subject), "-m", scrub(body)], { cwd: worktree });
|
|
198
|
+
if (commit.code !== 0)
|
|
199
|
+
throw new IntegrationError(`git commit failed: ${commit.stderr.trim()}`);
|
|
200
|
+
return (await run("git", ["rev-parse", "--short", "HEAD"], { cwd: worktree })).stdout.trim();
|
|
201
|
+
}
|
|
202
|
+
// The default cap of one check: five minutes. A check is a command the worker wrote, and a command that hangs
|
|
203
|
+
// (a test waiting for a port, a build waiting for a network) would hold the gate forever, so it is bounded.
|
|
204
|
+
export const DEFAULT_CHECK_TIMEOUT_MS = 300_000;
|
|
205
|
+
// How long this job's checks may run: the job's own setting where it has one, else the config's, else the default.
|
|
206
|
+
// The job's setting wins over the config's, because a job that was given a longer cap (a slow integration suite)
|
|
207
|
+
// should not be cut back to the config's default.
|
|
208
|
+
export function checkTimeoutOf(job, configMs) {
|
|
209
|
+
if (job?.checkTimeoutMs !== undefined && Number.isFinite(job.checkTimeoutMs) && job.checkTimeoutMs > 0)
|
|
210
|
+
return job.checkTimeoutMs;
|
|
211
|
+
if (configMs !== undefined && Number.isFinite(configMs) && configMs > 0)
|
|
212
|
+
return configMs;
|
|
213
|
+
return DEFAULT_CHECK_TIMEOUT_MS;
|
|
214
|
+
}
|
|
215
|
+
// cancel: checked between checks, not inside one. A single check is bounded by its own timeout (300s by default),
|
|
216
|
+
// because there is nothing to interrupt a shell with once it started; but without this a job with five checks could
|
|
217
|
+
// not be stopped until all five ran, and stop_job looked broken for as long as the first one took.
|
|
218
|
+
// gate: the sandbox the check runs in (src/gatebox.ts). Without one the behaviour is the old one, unwrapped; with one
|
|
219
|
+
// whose box is unavailable the check is reported as skipped and never run.
|
|
220
|
+
export async function runGate(worktree, commands, run = exec, timeoutMs = DEFAULT_CHECK_TIMEOUT_MS, dir, cancel = {}, gate) {
|
|
221
|
+
const cwd = dir ?? worktree;
|
|
222
|
+
const out = [];
|
|
223
|
+
for (const command of commands) {
|
|
224
|
+
if (cancel.cancelled?.()) {
|
|
225
|
+
out.push({ command, passed: false, code: -1, output: "not run: the job was stopped" });
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
if (gate?.skip) {
|
|
229
|
+
out.push({ command, passed: false, code: -1, skipped: true, output: `[not run: ${gate.skip}]` });
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
const r = gate
|
|
233
|
+
? await run("sh", ["-c", await gate.wrap(`nice -n 15 sh -c ${shellQuote(command)}`)], { cwd, timeoutMs, ...(Object.keys(gate.env).length ? { env: gate.env } : {}) })
|
|
234
|
+
: await run("nice", ["-n", "15", "sh", "-c", command], { cwd, timeoutMs });
|
|
235
|
+
const text = `${r.stdout}\n${r.stderr}`.trim();
|
|
236
|
+
const score = parseScoreLines(r.stdout);
|
|
237
|
+
out.push({ command, passed: r.code === 0 && !r.timedOut, code: r.code, output: (r.timedOut ? "[timed out]\n" : "") + text.slice(-3000), ...(score ? { score } : {}), ...(gate?.unsandboxed ? { unsandboxed: true } : {}) });
|
|
238
|
+
}
|
|
239
|
+
return out;
|
|
240
|
+
}
|
|
241
|
+
// One shell word in single quotes: a check's text reaches `sh -c` as one argument, whatever quotes and spaces it has.
|
|
242
|
+
function shellQuote(value) {
|
|
243
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
244
|
+
}
|
|
245
|
+
// The cases the checks' MM_SCORE lines counted together; undefined when none of them graded anything.
|
|
246
|
+
export function gradedOf(results) {
|
|
247
|
+
const cases = results.map((r) => r.score?.cases).filter((c) => Boolean(c));
|
|
248
|
+
return cases.length ? { passed: cases.reduce((s, c) => s + c.passed, 0), total: cases.reduce((s, c) => s + c.total, 0) } : undefined;
|
|
249
|
+
}
|
|
250
|
+
// A contract's evaluator in the worker's directory, repeated as the contract says; the median of the runs is the
|
|
251
|
+
// measurement, and seconds what all runs took (the contract's cost per evaluation, for its stop rule). The evaluator
|
|
252
|
+
// is told which corpus it measures on; the held-out corpus (P4) comes with its directory.
|
|
253
|
+
// gate: the sandbox it runs in, like a check (A1-T12). Its MM_* variables are set on the command line, because a
|
|
254
|
+
// wrapped command does not keep the environment the caller passed to `run` alone.
|
|
255
|
+
export async function runEvaluator(dir, contract, corpus = "visible", run = exec, corpusDir, gate) {
|
|
256
|
+
if (gate?.skip)
|
|
257
|
+
return { measured: measuredOf(contract, { code: -1, stdout: "", stderr: `not run: ${gate.skip}`, timedOut: false }), seconds: 0 };
|
|
258
|
+
const started = Date.now();
|
|
259
|
+
const runs = [];
|
|
260
|
+
for (let i = 0; i < contract.repeats; i++) {
|
|
261
|
+
const env = { MM_CORPUS: corpus, MM_REPEAT: String(i + 1), ...(corpusDir ? { MM_CORPUS_DIR: corpusDir } : {}) };
|
|
262
|
+
const told = `MM_CORPUS=${shellQuote(env.MM_CORPUS)} MM_REPEAT=${shellQuote(env.MM_REPEAT)}${corpusDir ? ` MM_CORPUS_DIR=${shellQuote(corpusDir)}` : ""}`;
|
|
263
|
+
const r = gate
|
|
264
|
+
? await run("sh", ["-c", `${told} ${await gate.wrap(`nice -n 15 sh -c ${shellQuote(contract.evaluator)}`)}`], { cwd: dir, timeoutMs: contract.timeoutMs, env: gate.env })
|
|
265
|
+
: await run("nice", ["-n", "15", "sh", "-c", contract.evaluator], { cwd: dir, timeoutMs: contract.timeoutMs, env });
|
|
266
|
+
const m = measuredOf(contract, r);
|
|
267
|
+
runs.push(m);
|
|
268
|
+
if (!m.valid)
|
|
269
|
+
break; // one invalid run makes the measurement invalid; the others would only cost time
|
|
270
|
+
}
|
|
271
|
+
return { measured: median(runs), seconds: Math.round((Date.now() - started) / 100) / 10 };
|
|
272
|
+
}
|
|
273
|
+
// The worker's change against the last commit, new files included, for a reviewer that has no git.
|
|
274
|
+
export async function workingDiff(worktree, run = exec) {
|
|
275
|
+
await run("git", ["add", "-A", "-N"], { cwd: worktree });
|
|
276
|
+
return (await run("git", ["diff", "HEAD"], { cwd: worktree })).stdout;
|
|
277
|
+
}
|
|
278
|
+
// Content hashes of files, to see whether frozen tests were changed; a missing file hashes to "".
|
|
279
|
+
// dir: the project directory inside the worktree, because the paths are project-relative (changedFiles).
|
|
280
|
+
export async function hashFiles(worktree, files, run = exec, dir = worktree) {
|
|
281
|
+
const out = new Map();
|
|
282
|
+
for (const f of files)
|
|
283
|
+
out.set(f, (await run("git", ["hash-object", "--", f], { cwd: dir })).stdout.trim());
|
|
284
|
+
return out;
|
|
285
|
+
}
|
|
286
|
+
// The frozen files whose content is no longer what it was when they were frozen (changed, deleted or, for one that did
|
|
287
|
+
// not exist, created). dir: the project directory inside the worktree, as for hashFiles.
|
|
288
|
+
export async function frozenChanged(worktree, frozen, run = exec, dir = worktree) {
|
|
289
|
+
if (frozen.size === 0)
|
|
290
|
+
return [];
|
|
291
|
+
const now = await hashFiles(worktree, [...frozen.keys()], run, dir);
|
|
292
|
+
return [...frozen].filter(([f, h]) => now.get(f) !== h).map(([f]) => f);
|
|
293
|
+
}
|
|
294
|
+
// Frozen tests must not change: a changed or deleted one fails the gate like a failing check. The runner freezes the
|
|
295
|
+
// tests its red stage wrote (P3); a native writer the tests its checks name and its contract's files.
|
|
296
|
+
export async function frozenCheck(worktree, frozen, run = exec, dir = worktree, why = "changed after the red stage") {
|
|
297
|
+
if (frozen.size === 0)
|
|
298
|
+
return [];
|
|
299
|
+
const changed = await frozenChanged(worktree, frozen, run, dir);
|
|
300
|
+
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` : "" }];
|
|
301
|
+
}
|
|
302
|
+
// Undoes a worker's changes to the given files: tracked ones back to the last commit, new ones removed.
|
|
303
|
+
// dir: the project directory inside the worktree, because the paths are project-relative (changedFiles). git resolves a
|
|
304
|
+
// pathspec against the directory it runs in, so resolving the wrong one would silently touch a file of the same name.
|
|
305
|
+
export async function revertFiles(worktree, files, run = exec, dir = worktree) {
|
|
306
|
+
for (const f of files) {
|
|
307
|
+
const restored = await run("git", ["checkout", "-q", "HEAD", "--", f], { cwd: dir });
|
|
308
|
+
if (restored.code !== 0)
|
|
309
|
+
await run("git", ["clean", "-q", "-f", "--", f], { cwd: dir });
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
// A task of a parallel batch works in its own worktree, on a branch off the job's branch at its current commit.
|
|
313
|
+
// "micromanager/<job>--<task>", since "micromanager/<job>/<task>" cannot sit next to the branch "micromanager/<job>"
|
|
314
|
+
// in git's refs. at: another place for it (a continued worker keeps its session's directory). rel: the project's
|
|
315
|
+
// offset inside the worktree.
|
|
316
|
+
export async function prepareTaskWorktree(project, jobId, taskId, from, run = exec, at, rel = "") {
|
|
317
|
+
const branch = taskBranch(jobId, taskId);
|
|
318
|
+
if (at) {
|
|
319
|
+
// A continued worker keeps its session's directory (src/native.ts resume), but that directory must never be the
|
|
320
|
+
// project checkout or the job's integration worktree: creating a task branch there is how the job worktree was
|
|
321
|
+
// destroyed in a live run (job-20261030, T44).
|
|
322
|
+
const integration = join(project, stateDir(project), "worktrees", jobId);
|
|
323
|
+
if (resolve(at) === resolve(project))
|
|
324
|
+
throw new IntegrationError(`refusing to make a task worktree at the project checkout ${at}`);
|
|
325
|
+
if (resolve(at) === resolve(integration) || resolve(at).startsWith(`${resolve(integration)}${sep}`)) {
|
|
326
|
+
throw new IntegrationError(`refusing to make a task worktree at the job's integration worktree ${at}`);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
const worktree = at ?? join(project, stateDir(project), "worktrees", `${jobId}--${taskId}`);
|
|
330
|
+
await removeTaskWorktree(project, { branch, worktree }, run); // a leftover of an interrupted run
|
|
331
|
+
// Before the checkout exists, so the plugin never reports its own worktree as the user's uncommitted work.
|
|
332
|
+
const { dirty, summary } = await dirtyPaths(project, run);
|
|
333
|
+
const added = await run("git", ["worktree", "add", "-q", "-b", branch, worktree, from], { cwd: project });
|
|
334
|
+
if (added.code !== 0)
|
|
335
|
+
throw new IntegrationError(`git worktree add failed: ${added.stderr.trim()}`);
|
|
336
|
+
const dir = materializeTaskDir(worktree, rel);
|
|
337
|
+
return { branch, worktree, dir, rel, dirty, dirtySummary: summary };
|
|
338
|
+
}
|
|
339
|
+
// Only the worktree root and the branch: a worktree can be removed by name alone, and callers that hold no project
|
|
340
|
+
// offset (a removal after a merge) must not have to invent one.
|
|
341
|
+
export async function removeTaskWorktree(project, w, run = exec) {
|
|
342
|
+
await run("git", ["worktree", "remove", "--force", w.worktree], { cwd: project });
|
|
343
|
+
await run("git", ["branch", "-D", w.branch], { cwd: project });
|
|
344
|
+
}
|
|
345
|
+
// The first half of a merge train step: the task's branch is rebased onto the job's branch when that moved on since
|
|
346
|
+
// the task started. moved tells the caller to run the task's checks again before the fast-forward.
|
|
347
|
+
//
|
|
348
|
+
// A conflict is left open in the worktree on purpose (the Unmerged index, the conflict markers in the files). Aborting
|
|
349
|
+
// it here would throw away the only state that makes the conflict resolvable, and the worker cannot run git to rebase
|
|
350
|
+
// again: a writer's sandbox allows writes to its worktree but not to the repository's .git, where the index lives. So
|
|
351
|
+
// the worker edits the markers in place and finish_task continues the rebase (resumeRebase below).
|
|
352
|
+
export async function rebaseTask(w, integrationBranch, run = exec) {
|
|
353
|
+
// A rebase left open by an earlier merge belongs to the worker that is resolving it: never start a second one on top
|
|
354
|
+
// of it (git refuses), and tell the caller which files still wait.
|
|
355
|
+
if (await rebaseInProgress(w.worktree, run)) {
|
|
356
|
+
const files = await unmergedFiles(w.worktree, run);
|
|
357
|
+
return { ok: false, conflict: files.length ? `conflict in ${files.join(", ")}` : "a rebase is already in progress in the worktree", ...(files.length ? { files } : {}) };
|
|
358
|
+
}
|
|
359
|
+
const base = (await run("git", ["merge-base", "HEAD", integrationBranch], { cwd: w.worktree })).stdout.trim();
|
|
360
|
+
const tip = (await run("git", ["rev-parse", integrationBranch], { cwd: w.worktree })).stdout.trim();
|
|
361
|
+
if (base === tip)
|
|
362
|
+
return { ok: true, moved: false };
|
|
363
|
+
const rebased = await run("git", ["rebase", "-q", integrationBranch], { cwd: w.worktree });
|
|
364
|
+
if (rebased.code === 0)
|
|
365
|
+
return { ok: true, moved: true };
|
|
366
|
+
const files = await unmergedFiles(w.worktree, run);
|
|
367
|
+
if (files.length)
|
|
368
|
+
return { ok: false, conflict: `conflict in ${files.join(", ")}`, files };
|
|
369
|
+
// Not a conflict (a dirty tree, an untracked file in the way, ...): put the worktree back the way it was and report
|
|
370
|
+
// why. There is no resolution for the worker to make, so no state is left behind.
|
|
371
|
+
await abortRebase(w.worktree, run);
|
|
372
|
+
return { ok: false, conflict: rebased.stderr.trim().slice(-500) };
|
|
373
|
+
}
|
|
374
|
+
// Is a rebase open in this worktree? The state is per worktree (git puts it under .git/worktrees/<name>), so it travels
|
|
375
|
+
// with the worker's directory and survives a restart of the plugin.
|
|
376
|
+
export async function rebaseInProgress(worktree, run = exec) {
|
|
377
|
+
for (const name of ["rebase-merge", "rebase-apply"]) {
|
|
378
|
+
const out = await run("git", ["rev-parse", "--git-path", name], { cwd: worktree });
|
|
379
|
+
if (out.code === 0 && out.stdout.trim() && existsSync(resolve(worktree, out.stdout.trim())))
|
|
380
|
+
return true;
|
|
381
|
+
}
|
|
382
|
+
return false;
|
|
383
|
+
}
|
|
384
|
+
// The paths git could not merge, relative to the worktree root. Empty outside a conflict.
|
|
385
|
+
export async function unmergedFiles(worktree, run = exec) {
|
|
386
|
+
const out = await run("git", ["-c", "core.quotePath=false", "diff", "--name-only", "--diff-filter=U"], { cwd: worktree });
|
|
387
|
+
return out.code === 0 ? out.stdout.trim().split("\n").map((f) => f.trim()).filter(Boolean) : [];
|
|
388
|
+
}
|
|
389
|
+
// The unmerged files that still carry conflict markers. A worker that resolved a file removes the markers but cannot
|
|
390
|
+
// stage it (no git writes in its sandbox), so the Unmerged index alone is not evidence that it is unresolved.
|
|
391
|
+
const CONFLICT_MARKER = /^(?:<{7}|>{7})(?:\s|$)/m;
|
|
392
|
+
export async function unresolvedConflicts(worktree, run = exec) {
|
|
393
|
+
const files = await unmergedFiles(worktree, run);
|
|
394
|
+
return files.filter((f) => {
|
|
395
|
+
try {
|
|
396
|
+
return CONFLICT_MARKER.test(readFileSync(join(worktree, f), "utf8"));
|
|
397
|
+
}
|
|
398
|
+
catch {
|
|
399
|
+
// A deleted file is a resolution too (keep both changes does not have to mean keep both files).
|
|
400
|
+
return false;
|
|
401
|
+
}
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
// The second half of a held conflict: the worker resolved the markers in its own directory, so stage them and let git
|
|
405
|
+
// replay the commit onto the branch it was rebased to. The editor is silenced: the original message is the task's.
|
|
406
|
+
export async function resumeRebase(worktree, run = exec) {
|
|
407
|
+
const unresolved = await unresolvedConflicts(worktree, run);
|
|
408
|
+
if (unresolved.length)
|
|
409
|
+
return { ok: false, conflict: `conflict in ${unresolved.join(", ")}: still unresolved`, files: unresolved };
|
|
410
|
+
await run("git", ["add", "-A"], { cwd: worktree });
|
|
411
|
+
const cont = await run("git", ["-c", "core.editor=true", "rebase", "--continue"], { cwd: worktree });
|
|
412
|
+
if (cont.code === 0) {
|
|
413
|
+
const head = await run("git", ["rev-parse", "--short", "HEAD"], { cwd: worktree });
|
|
414
|
+
return { ok: true, commit: head.stdout.trim() };
|
|
415
|
+
}
|
|
416
|
+
// The replay hit the next commit's conflict: keep the rebase open and hand the new files back.
|
|
417
|
+
const files = await unmergedFiles(worktree, run);
|
|
418
|
+
// A failure that is not a conflict cannot be resolved by editing files; keep the state (the worktree holds the
|
|
419
|
+
// worker's resolution) and let the caller block the task with the real error rather than discard it.
|
|
420
|
+
return { ok: false, conflict: files.length ? `conflict in ${files.join(", ")}` : cont.stderr.trim().slice(-500), files };
|
|
421
|
+
}
|
|
422
|
+
// Put a conflicted worktree back the way it was. Only the paths that discard the worktree anyway (a runner that starts
|
|
423
|
+
// the task over) call this; a worker's resolution is never thrown away by the plugin.
|
|
424
|
+
export async function abortRebase(worktree, run = exec) {
|
|
425
|
+
if (await rebaseInProgress(worktree, run))
|
|
426
|
+
await run("git", ["rebase", "--abort"], { cwd: worktree });
|
|
427
|
+
}
|
|
428
|
+
// The second half: the job's branch moves forward to the task's commits; nothing else is ever merged into it.
|
|
429
|
+
export async function fastForward(integrationWorktree, taskBranch, run = exec) {
|
|
430
|
+
const ff = await run("git", ["merge", "-q", "--ff-only", taskBranch], { cwd: integrationWorktree });
|
|
431
|
+
return ff.code === 0 ? { ok: true, moved: false } : { ok: false, conflict: ff.stderr.trim().slice(-500) };
|
|
432
|
+
}
|
|
433
|
+
// --- Plan mode: a throwaway worktree of its own -------------------------------------------------------------
|
|
434
|
+
// A plan's drafts sit apart from the job's worktrees, under the state directory like everything else the plugin writes,
|
|
435
|
+
// so a throwaway branch is never mistaken for a job's branch when the plan is read later.
|
|
436
|
+
export function planArea(project, jobId) {
|
|
437
|
+
return statePath(project, "plan", jobId);
|
|
438
|
+
}
|
|
439
|
+
// A plan is drafted in a worktree off HEAD and thrown away: the user's checkout stays untouched while the planner
|
|
440
|
+
// reads and writes, and nothing it writes can reach a task. The branch name is the plan's own, so no job branch can
|
|
441
|
+
// collide with it.
|
|
442
|
+
export async function preparePlanWorktree(project, jobId, taskId, run = exec) {
|
|
443
|
+
const branch = `plan/${jobId}/${taskId}`;
|
|
444
|
+
const worktree = join(planArea(project, jobId), "worktrees", taskId);
|
|
445
|
+
const head = await run("git", ["rev-parse", "HEAD"], { cwd: project });
|
|
446
|
+
if (head.code !== 0)
|
|
447
|
+
throw new IntegrationError("the project has no commit for a plan worktree to start from");
|
|
448
|
+
const base = head.stdout.trim();
|
|
449
|
+
await removePlanWorktree(project, { branch, worktree }, run); // a leftover of an interrupted run
|
|
450
|
+
const added = await run("git", ["worktree", "add", "-q", "-b", branch, worktree, base], { cwd: project });
|
|
451
|
+
if (added.code !== 0)
|
|
452
|
+
throw new IntegrationError(`git worktree add failed: ${added.stderr.trim()}`);
|
|
453
|
+
return { branch, worktree, dir: worktree, base };
|
|
454
|
+
}
|
|
455
|
+
// Unlike a task worktree, a plan one is removed both when its task is done and when the plan is: the second removal
|
|
456
|
+
// finds nothing, and that is the expected state, not a failure.
|
|
457
|
+
export async function removePlanWorktree(project, w, run = exec) {
|
|
458
|
+
await run("git", ["worktree", "remove", "--force", w.worktree], { cwd: project });
|
|
459
|
+
await run("git", ["branch", "-D", w.branch], { cwd: project });
|
|
460
|
+
}
|
|
461
|
+
function sha256Path(worktree, path) {
|
|
462
|
+
const full = join(worktree, path);
|
|
463
|
+
if (!existsSync(full))
|
|
464
|
+
return undefined;
|
|
465
|
+
try {
|
|
466
|
+
const st = statSync(full);
|
|
467
|
+
if (!st.isFile())
|
|
468
|
+
return undefined;
|
|
469
|
+
return createHash("sha256").update(readFileSync(full)).digest("hex");
|
|
470
|
+
}
|
|
471
|
+
catch {
|
|
472
|
+
return undefined;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
// Diff of exactly the given paths, relative to HEAD. Never stages anything.
|
|
476
|
+
export async function diffPaths(worktree, paths, run = exec) {
|
|
477
|
+
if (paths.length === 0)
|
|
478
|
+
return "";
|
|
479
|
+
const out = await run("git", ["diff", "HEAD", "--", ...paths], { cwd: worktree });
|
|
480
|
+
if (out.code !== 0)
|
|
481
|
+
return out.stdout || out.stderr;
|
|
482
|
+
return out.stdout;
|
|
483
|
+
}
|
|
484
|
+
// Stage exactly the given paths and commit them in one commit. Never `git add -A`, never `-A -N`.
|
|
485
|
+
// `told` maps a path to the sha256 hash the caller read before editing; if any path's current hash differs,
|
|
486
|
+
// or the path is missing from `told`, the commit is refused - a changed hash not told about is drift.
|
|
487
|
+
// `record` receives a design.commit decision entry when a commit is made.
|
|
488
|
+
export async function commitPaths(worktree, paths, message, toldOrOpts, runOrRecord, maybeRecord) {
|
|
489
|
+
if (paths.length === 0)
|
|
490
|
+
return undefined;
|
|
491
|
+
let told;
|
|
492
|
+
let run = exec;
|
|
493
|
+
let record;
|
|
494
|
+
if (typeof toldOrOpts === "function") {
|
|
495
|
+
run = toldOrOpts;
|
|
496
|
+
}
|
|
497
|
+
else if (toldOrOpts instanceof Map) {
|
|
498
|
+
told = toldOrOpts;
|
|
499
|
+
}
|
|
500
|
+
else if (toldOrOpts && typeof toldOrOpts === "object") {
|
|
501
|
+
const o = toldOrOpts;
|
|
502
|
+
if ("told" in o || "run" in o || "record" in o) {
|
|
503
|
+
told = o.told;
|
|
504
|
+
if (o.run)
|
|
505
|
+
run = o.run;
|
|
506
|
+
record = o.record;
|
|
507
|
+
}
|
|
508
|
+
else {
|
|
509
|
+
// Plain object used as a string->string map.
|
|
510
|
+
told = new Map(Object.entries(toldOrOpts));
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
if (typeof runOrRecord === "function") {
|
|
514
|
+
// Exec takes (cmd, args, opts) arity 3; record takes (entry) arity 1.
|
|
515
|
+
if (maybeRecord || runOrRecord.length >= 2)
|
|
516
|
+
run = runOrRecord;
|
|
517
|
+
else
|
|
518
|
+
record = runOrRecord;
|
|
519
|
+
}
|
|
520
|
+
if (maybeRecord)
|
|
521
|
+
record = maybeRecord;
|
|
522
|
+
if (told) {
|
|
523
|
+
for (const p of paths) {
|
|
524
|
+
const expected = told.get(p);
|
|
525
|
+
const actual = sha256Path(worktree, p);
|
|
526
|
+
if (expected === undefined || actual !== expected) {
|
|
527
|
+
throw new IntegrationError(`Design drift: ${p} changed (expected ${expected ?? "untold"}, got ${actual ?? "missing"}); refusing to commit a hash not told about.`);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
// Commit only these paths (stages them for this commit). Unrelated dirty/staged files are left alone.
|
|
532
|
+
const out = await run("git", ["commit", "-m", message, "--", ...paths], { cwd: worktree });
|
|
533
|
+
if (out.code !== 0) {
|
|
534
|
+
const text = `${out.stdout}\n${out.stderr}`;
|
|
535
|
+
if (/nothing to commit|no changes added|nothing added to commit/i.test(text))
|
|
536
|
+
return undefined;
|
|
537
|
+
throw new IntegrationError(`git commit failed: ${out.stderr.trim() || out.stdout.trim()}`);
|
|
538
|
+
}
|
|
539
|
+
// `git commit` prints the diffstat, whose last token is "insertion(+)" or "deletion(-)", not the commit. Read the
|
|
540
|
+
// hash git actually made; the caller (design_commit) reports it back.
|
|
541
|
+
const head = await run("git", ["rev-parse", "--short", "HEAD"], { cwd: worktree });
|
|
542
|
+
const hash = head.code === 0 ? head.stdout.trim() : undefined;
|
|
543
|
+
record?.({ kind: "design.commit", worktree, paths: [...paths], message, commit: hash });
|
|
544
|
+
return hash;
|
|
545
|
+
}
|