@omacode/micromanager 0.0.0-stage → 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 (146) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +30 -2
  3. package/THIRD_PARTY.md +100 -0
  4. package/decider/.python-version +1 -0
  5. package/decider/README.md +35 -0
  6. package/decider/decider/__init__.py +1 -0
  7. package/decider/decider/server.py +327 -0
  8. package/decider/pyproject.toml +34 -0
  9. package/decider/uv.lock +1255 -0
  10. package/dist/agenda.js +51 -0
  11. package/dist/agents.js +58 -0
  12. package/dist/artifact/handoff.js +281 -0
  13. package/dist/ask.js +200 -0
  14. package/dist/backends.js +219 -0
  15. package/dist/backlog.js +414 -0
  16. package/dist/bench.js +427 -0
  17. package/dist/board.js +1 -0
  18. package/dist/brief.js +202 -0
  19. package/dist/browser.js +679 -0
  20. package/dist/budget.js +61 -0
  21. package/dist/catalog.js +187 -0
  22. package/dist/checkchange.js +145 -0
  23. package/dist/checkpoint.js +94 -0
  24. package/dist/cli.js +764 -0
  25. package/dist/comfy-gate.js +258 -0
  26. package/dist/compact.js +142 -0
  27. package/dist/config.js +344 -0
  28. package/dist/context/capture.js +1 -0
  29. package/dist/context/digest.js +1 -0
  30. package/dist/context/embed.js +1 -0
  31. package/dist/context/index.js +2 -0
  32. package/dist/context/ledger.js +1 -0
  33. package/dist/context/manager.js +1 -0
  34. package/dist/context/memory.js +1 -0
  35. package/dist/context/policy.js +1 -0
  36. package/dist/context/prices.js +1 -0
  37. package/dist/context/recall.js +1 -0
  38. package/dist/context/rules.js +1 -0
  39. package/dist/context/search.js +1 -0
  40. package/dist/context/status.js +1 -0
  41. package/dist/context/store.js +1 -0
  42. package/dist/context/summary.js +1 -0
  43. package/dist/context/tokens.js +1 -0
  44. package/dist/context/tools.js +1 -0
  45. package/dist/continuation.js +184 -0
  46. package/dist/contract.js +294 -0
  47. package/dist/contractround.js +178 -0
  48. package/dist/control.js +1 -0
  49. package/dist/creative-tools.js +237 -0
  50. package/dist/dataset.js +175 -0
  51. package/dist/decide.js +676 -0
  52. package/dist/decider.js +171 -0
  53. package/dist/design-shell.js +448 -0
  54. package/dist/design.js +1410 -0
  55. package/dist/desktop.js +44 -0
  56. package/dist/egress.js +156 -0
  57. package/dist/eval.js +60 -0
  58. package/dist/evolver.js +302 -0
  59. package/dist/features.js +193 -0
  60. package/dist/followups.js +32 -0
  61. package/dist/forms.js +195 -0
  62. package/dist/gate.js +108 -0
  63. package/dist/gatebox.js +46 -0
  64. package/dist/grants.js +189 -0
  65. package/dist/graph.js +65 -0
  66. package/dist/guard/index.js +1 -0
  67. package/dist/guard/wire.js +1 -0
  68. package/dist/helpers.js +85 -0
  69. package/dist/hooks.js +158 -0
  70. package/dist/image-models.js +117 -0
  71. package/dist/integration.js +3 -0
  72. package/dist/journal.js +1 -0
  73. package/dist/look.js +363 -0
  74. package/dist/memory.js +1 -0
  75. package/dist/mode.js +97 -0
  76. package/dist/native.js +3348 -0
  77. package/dist/nogit.js +259 -0
  78. package/dist/outcomes.js +148 -0
  79. package/dist/permission.js +35 -0
  80. package/dist/pick.js +89 -0
  81. package/dist/pipelines.js +262 -0
  82. package/dist/plan.js +641 -0
  83. package/dist/plandoc.js +211 -0
  84. package/dist/plugin.js +4736 -0
  85. package/dist/policy.js +58 -0
  86. package/dist/pools.js +1 -0
  87. package/dist/preview.js +274 -0
  88. package/dist/profile.js +165 -0
  89. package/dist/progress.js +1 -0
  90. package/dist/promote.js +313 -0
  91. package/dist/redact.js +1 -0
  92. package/dist/registry.js +179 -0
  93. package/dist/riskscore.js +126 -0
  94. package/dist/roles.js +1 -0
  95. package/dist/routing.js +1 -0
  96. package/dist/runner.js +1892 -0
  97. package/dist/sandbox.js +3 -0
  98. package/dist/sandboxgate.js +90 -0
  99. package/dist/scheduler.js +170 -0
  100. package/dist/services-main.js +131 -0
  101. package/dist/services.js +265 -0
  102. package/dist/session.js +241 -0
  103. package/dist/setup.js +423 -0
  104. package/dist/shell/decide.js +1 -0
  105. package/dist/shell/index.js +2 -0
  106. package/dist/shell/sandbox.js +1 -0
  107. package/dist/shell/wire.js +1 -0
  108. package/dist/skills.js +103 -0
  109. package/dist/state.js +1 -0
  110. package/dist/store.js +1 -0
  111. package/dist/switcher.js +1 -0
  112. package/dist/synth.js +418 -0
  113. package/dist/tools.js +477 -0
  114. package/dist/trials.js +223 -0
  115. package/dist/usage.js +1 -0
  116. package/dist/wait.js +167 -0
  117. package/dist/watchdog.js +476 -0
  118. package/dist/web-guidance.js +43 -0
  119. package/dist/which.js +20 -0
  120. package/dist/worktree/git.js +545 -0
  121. package/dist/writeguard.js +311 -0
  122. package/evolver/mm_evolve/__init__.py +1 -0
  123. package/evolver/mm_evolve/entry.py +3 -0
  124. package/evolver/mm_evolve/evaluator.py +119 -0
  125. package/evolver/mm_evolve/llm.py +76 -0
  126. package/evolver/mm_evolve/run.py +89 -0
  127. package/evolver/mm_evolve/spec.py +62 -0
  128. package/evolver/pyproject.toml +21 -0
  129. package/evolver/uv.lock +772 -0
  130. package/package.json +74 -4
  131. package/skills/THIRD_PARTY.md +58 -0
  132. package/skills/code-review/SKILL.md +46 -0
  133. package/skills/deck/SKILL.md +98 -0
  134. package/skills/deliberate/SKILL.md +39 -0
  135. package/skills/design/SKILL.md +150 -0
  136. package/skills/diagnosing-bugs/SKILL.md +75 -0
  137. package/skills/image/SKILL.md +66 -0
  138. package/skills/orchestrator/SKILL.md +107 -0
  139. package/skills/receiving-code-review/SKILL.md +36 -0
  140. package/skills/research/SKILL.md +18 -0
  141. package/skills/tdd/SKILL.md +56 -0
  142. package/skills/tdd/mocking.md +59 -0
  143. package/skills/tdd/tests.md +77 -0
  144. package/skills/verification-before-completion/SKILL.md +50 -0
  145. package/skills/video/SKILL.md +97 -0
  146. package/skills/web/SKILL.md +60 -0
package/dist/native.js ADDED
@@ -0,0 +1,3348 @@
1
+ // Native delegation: the micromanager starts workers with OpenCode's own subagent tool, in the background, and the
2
+ // plugin keeps each writer in its own git worktree (spike of 2026-10-05, docs/plan.md).
3
+ //
4
+ // - Before the micromanager's subagent call runs, delegate() turns it into a task of the session's job: the "Files:"
5
+ // and "Checks:" lines at the end of its prompt are the task's write scope and checks, a writer gets its own
6
+ // worktree off the session branch, a reader works in the session branch's worktree, and the prompt becomes the
7
+ // worker's brief.
8
+ // - OpenCode creates the child in the micromanager's directory (a child always starts in its parent's), and the
9
+ // plugin moves it in the child's first prompt hook (claim), before any tool runs.
10
+ // - The writer ends through finish_task: the plugin runs the checks in the worktree, commits, and merges through the
11
+ // merge train; a failure goes back to the worker, which fixes it in the same turn loop. OpenCode then notifies the
12
+ // micromanager with the worker's report, after the merge.
13
+ //
14
+ // Every plugin instance of one server shares this state (a moved worker is served by the instance of its worktree).
15
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
16
+ import { tmpdir } from "node:os";
17
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
18
+ import { Graphs, graphBrief, queryGraph } from "./graph.js";
19
+ import { HEADER } from "./hooks.js";
20
+ import { better, coarse, contractBrief, describe, guardViolations, heldOutDir, keepHeldOut, median, parseContract, reached } from "./contract.js";
21
+ import { changedFiles, checkTimeoutOf, commitTask, dirtyDeclared, dirtyPaths, exec as defaultExec, fastForward, frozenChanged, gradedOf, hashFiles, IntegrationError, planArea, prepareIntegration, preparePlanWorktree, prepareTaskWorktree, rebaseInProgress, rebaseTask, removePlanWorktree, removeTaskWorktree, resumeRebase, unresolvedConflicts, validateIntegration, workingDiff, repoRel, revertFiles, runEvaluator, runGate, taskDir, } from "./worktree/git.js";
22
+ import { addDelegated, checkCwdProblem, checkSetProblems, parseFiles, stripTaskWorktreeCwd } from "./plan.js";
23
+ import { gateFor, unsandboxedNote } from "./gatebox.js";
24
+ import { WRITERS } from "./profile.js";
25
+ import { FIX_ROUNDS } from "./watchdog.js";
26
+ import { ROLES, roleByAgent, roleById } from "./roles.js";
27
+ import { moveTask, newJob, moveJob, stage } from "./state.js";
28
+ import { excludeFromGit, jobId, listJobs, saveContract, saveJob, stateDir } from "./store.js";
29
+ import { combineBase, comparisonPage, pickNote } from "./pick.js";
30
+ import { chargeTask } from "./budget.js";
31
+ import { draftFromLater, draftFromTrial, localBackend } from "./backlog.js";
32
+ import { normalTarget } from "./checkchange.js";
33
+ import { applyPrefs, askWith, baselineForm, draftPrompt, loopholeForm, parseLoopholes, prefsForm, redteamPrompt } from "./contractround.js";
34
+ import { parseReport, sharedNote, skillLine, taskAcceptance, upstreamHandoffs, verbatimGoalLine } from "./brief.js";
35
+ import { settled, startable } from "./continuation.js";
36
+ import { isStarted, lastOptions, loadControl, optionsOf } from "./control.js";
37
+ import { formInput, startForm } from "./forms.js";
38
+ import { estimate, EVOLVER_MAX_EVAL_S, evolverFits, evolverForm } from "./evolver.js";
39
+ import { copyForPlan, gitState } from "./nogit.js";
40
+ import { isTrivialLowRiskDiff } from "./pipelines.js";
41
+ import { parseArtifacts, promoteArtifacts, writePromotionRecord } from "./promote.js";
42
+ import { docFromJob, readPlanDoc, renderPlanDoc, writePlanDoc } from "./plandoc.js";
43
+ import { allFailedText, attemptBrief, attemptFailedText, attempts, DEFAULT_GRACE, DEFAULT_PICK, fanOutText, graceMs, hasObjectiveEvaluator, pickFor, pickOf, rankQuality, ranked, standing, TRIAL_EVALUATOR_REQUIRED, wonText } from "./trials.js";
44
+ export { isTrivialLowRiskDiff } from "./pipelines.js";
45
+ export { hasObjectiveEvaluator } from "./trials.js";
46
+ const POST_GREEN_DIRECTIVE = "Post-green optimization mode: All functional checks are already green on the integration branch. Only make changes that measurably simplify hot paths, eliminate redundant passes/O(n^2) scans/allocations, or remove dead code while keeping every check green. If no worthwhile optimization exists, make NO file edits and call finish_task immediately.";
47
+ // The first line OpenCode puts before a new subagent's prompt; how the prompt hook tells a child's first turn.
48
+ export const CHILD_PREFIX = "You are a subagent spawned by another session.";
49
+ export class DelegationError extends Error {
50
+ }
51
+ // The "Files:" and "Checks:" lines of a delegation, wherever they stand; the checks go on over the following lines
52
+ // until a blank line or another such line.
53
+ export function parseDelegation(prompt) {
54
+ const body = [];
55
+ const checks = [];
56
+ const replaces = [];
57
+ let files = "";
58
+ let frozen = "";
59
+ let goal = "";
60
+ let planned;
61
+ let attempt;
62
+ let contract;
63
+ let redteam;
64
+ let method;
65
+ let pick;
66
+ let preview;
67
+ let inChecks = false;
68
+ for (const line of prompt.split("\n")) {
69
+ const pv = line.match(/^\s*preview:\s*(\S.*?)\s*$/i);
70
+ if (pv) {
71
+ preview = pv[1];
72
+ inChecks = false;
73
+ continue;
74
+ }
75
+ const pk = line.match(/^\s*pick:\s*(me|user|best|first)\s*$/i);
76
+ if (pk) {
77
+ const v = pk[1].toLowerCase();
78
+ pick = v === "me" ? "user" : v;
79
+ inChecks = false;
80
+ continue;
81
+ }
82
+ const mt = line.match(/^\s*method:\s*(worker|trial|evolver)\s*$/i);
83
+ if (mt) {
84
+ method = mt[1].toLowerCase();
85
+ inChecks = false;
86
+ continue;
87
+ }
88
+ const rt = line.match(/^\s*red team:\s*(C\d+)\s*·\s*(job-[\w-]+)\s*$/i);
89
+ if (rt) {
90
+ redteam = { contract: rt[1].toUpperCase(), job: rt[2] };
91
+ inChecks = false;
92
+ continue;
93
+ }
94
+ const k = line.match(/^\s*contract:\s*(C\d+)\s*$/i);
95
+ if (k) {
96
+ contract = k[1].toUpperCase();
97
+ inChecks = false;
98
+ continue;
99
+ }
100
+ // The line the plugin hands out for a trial's other attempts (src/trials.ts attemptLine).
101
+ const a = line.match(/^\s*attempt:\s*(T\d+(?:\.\w+)*)\s*·\s*(job-[\w-]+)\s*$/i);
102
+ if (a) {
103
+ attempt = { task: a[1].toUpperCase(), job: a[2] };
104
+ inChecks = false;
105
+ continue;
106
+ }
107
+ // Only the exact form run_job hands out (src/continuation.ts plannedLine): a prompt's own "Task: …" stays prose.
108
+ const t = line.match(/^\s*task:\s*(T\d+(?:\.\w+)*)\s*·\s*(job-[\w-]+)\s*$/i);
109
+ if (t) {
110
+ planned = { task: t[1].toUpperCase(), job: t[2] };
111
+ inChecks = false;
112
+ continue;
113
+ }
114
+ const z = line.match(/^\s*frozen:\s*(.*)$/i);
115
+ if (z) {
116
+ frozen = z[1].trim();
117
+ inChecks = false;
118
+ continue;
119
+ }
120
+ const g = line.match(/^\s*goal:\s*(.*)$/i);
121
+ const f = line.match(/^\s*files:\s*(.*)$/i);
122
+ const c = line.match(/^\s*checks:\s*(.*)$/i);
123
+ const r = line.match(/^\s*replaces:\s*(.*)$/i);
124
+ if (g) {
125
+ goal = g[1].trim();
126
+ inChecks = false;
127
+ }
128
+ else if (r) {
129
+ replaces.push(...replaceIds(r[1]));
130
+ inChecks = false;
131
+ }
132
+ else if (f) {
133
+ files = f[1].trim();
134
+ inChecks = false;
135
+ }
136
+ else if (c) {
137
+ inChecks = true;
138
+ if (c[1].trim())
139
+ checks.push(c[1].trim());
140
+ }
141
+ else if (inChecks && line.trim())
142
+ checks.push(line.trim().replace(/^[-*]\s+/, ""));
143
+ else {
144
+ inChecks = false;
145
+ body.push(line);
146
+ }
147
+ }
148
+ return { body: body.join("\n").trim(), files, checks, replaces, ...(goal ? { goal } : {}), ...(frozen ? { frozen } : {}), ...(planned ? { planned } : {}), ...(attempt ? { attempt } : {}), ...(contract ? { contract } : {}), ...(redteam ? { redteam } : {}), ...(method ? { method } : {}), ...(pick ? { pick } : {}), ...(preview ? { preview } : {}) };
149
+ }
150
+ // How much two task texts are about the same thing: the share of their words they have in common (Jaccard over the
151
+ // words of three letters or more, without the filler). "Remove dashed pill on lanes slide" and "Delete dashed pill on
152
+ // lanes slide" share four of six: the same work, delegated twice in a live run (2026-10-07).
153
+ const FILLER = new Set(["the", "and", "for", "with", "from", "into", "that", "this", "its", "are", "was", "not", "but", "you", "your"]);
154
+ function words(text) {
155
+ return new Set(text.toLowerCase().split(/[^a-z0-9äöüß]+/).filter((w) => w.length > 2 && !FILLER.has(w)));
156
+ }
157
+ export function similarity(a, b) {
158
+ const x = words(a);
159
+ const y = words(b);
160
+ if (x.size === 0 || y.size === 0)
161
+ return 0;
162
+ let shared = 0;
163
+ for (const w of x)
164
+ if (y.has(w))
165
+ shared++;
166
+ return shared / (x.size + y.size - shared);
167
+ }
168
+ const SAME_WORK = 0.5; // a writer on the same files with a title or brief this close is the same work
169
+ const SAME_PENDING = 0.8; // two todos that have not started are only duplicates when they are this close
170
+ const SAME_QUESTION = 0.8; // a reader with a brief this close asks the same question
171
+ const LIVE = new Set(["running", "gating", "fixing"]);
172
+ export const TRIAL_DEADLINE_MS = 20 * 60_000;
173
+ // A visual task's page when its delegation named none: the first built or plain index.html found in its directory.
174
+ export function defaultPreview(dir) {
175
+ return ["dist/index.html", "build/index.html", "out/index.html", "public/index.html", "index.html"].find((p) => existsSync(join(dir, p)));
176
+ }
177
+ // The project is no git repository, or one without a commit: nothing starts until the user said how to go on.
178
+ export class NoGitError extends DelegationError {
179
+ }
180
+ // Task ids in whatever a model wrote: ["T1", "T2"], "T1, T2", or "after T1 and T2 merged" (live run: the last one made
181
+ // a task wait for a task "MERGED").
182
+ export function taskIds(value) {
183
+ return (Array.isArray(value) ? value.join(" ") : String(value ?? "")).toUpperCase().match(/\bT\d+(?:\.\w+)*/g) ?? [];
184
+ }
185
+ // The tasks a todo or a delegation does over: "T19", or "job-…/T18" for a task of another job of the session.
186
+ export function replaceIds(value) {
187
+ const text = Array.isArray(value) ? value.join(" ") : String(value ?? "");
188
+ return [...text.matchAll(/\b(job-[\w-]+\/)?(T\d+(?:\.\w+)*)\b/gi)].map((m) => `${m[1]?.toLowerCase() ?? ""}${m[2].toUpperCase()}`);
189
+ }
190
+ export function parseTodo(items) {
191
+ const list = [];
192
+ const ids = [];
193
+ if (!items.trim())
194
+ return { list, ids };
195
+ let parsed;
196
+ try {
197
+ parsed = JSON.parse(items);
198
+ }
199
+ catch (err) {
200
+ return `items is not a JSON list: ${err instanceof Error ? err.message : String(err)}. Nothing was changed.`;
201
+ }
202
+ // Either the historic JSON list, or { "goal": "...", "items": [...] } so the session's job learns its real goal.
203
+ const root = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : undefined;
204
+ const goal = typeof root?.goal === "string" && root.goal.trim() ? root.goal.trim() : undefined;
205
+ if (root && Array.isArray(root.drop))
206
+ ids.push(...taskIds(root.drop));
207
+ const entries = root && Array.isArray(root.items) ? root.items : Array.isArray(parsed) ? parsed : [parsed];
208
+ for (const x of entries) {
209
+ const o = (x ?? {});
210
+ if (o.drop !== undefined) {
211
+ ids.push(...taskIds(o.drop));
212
+ if (!o.title)
213
+ continue;
214
+ }
215
+ const text = (v, join) => (v === undefined || v === null || v === "" ? undefined : Array.isArray(v) ? v.map(String).join(join) : String(v));
216
+ list.push({
217
+ title: String(o.title ?? "").replace(/^\s*T\d+(?:\.\w+)*\s*[:·.-]\s*/i, ""), // the plugin numbers todos itself
218
+ agent: text(o.agent, ""),
219
+ files: text(o.files, ", "),
220
+ checks: text(o.checks, "\n"),
221
+ after: taskIds(o.after),
222
+ brief: text(o.brief, "\n"),
223
+ replaces: replaceIds(o.replaces),
224
+ ...(typeof o.contract === "string" && /^c\d+$/i.test(o.contract.trim()) ? { contract: o.contract.trim().toUpperCase() } : {}),
225
+ ...(text(o.frozen, ", ") ? { frozen: text(o.frozen, ", ") } : {}),
226
+ });
227
+ }
228
+ return { list, ids, ...(goal ? { goal } : {}) };
229
+ }
230
+ // The job as it was before a plan task's finish: the task's artifacts not yet promoted, its status still open, its
231
+ // summary not yet recorded. The document rendered from it is what the plugin itself wrote at the task's start or at the
232
+ // previous plan finish, which is how a rewrite tells the plugin's own plan.md from a richer one a plan agent wrote.
233
+ function priorToFinish(job, task) {
234
+ return {
235
+ ...job,
236
+ tasks: job.tasks.map((t) => (t.id === task.id ? { ...t, status: "pending", promoted: [], summary: undefined } : t)),
237
+ };
238
+ }
239
+ export class Native {
240
+ #exec;
241
+ #skills;
242
+ #graphs;
243
+ #entries = new Map(); // "<job>/<task>" -> entry
244
+ #bySession = new Map(); // child session -> its entry's key
245
+ #jobs = new Map(); // "<project>\0<job>" -> the live job
246
+ #trains = new Map(); // per job: one merge at a time
247
+ #waiting = new Set(); // child sessions whose end is awaited
248
+ #delegating = new Map(); // per micromanager session: one delegation at a time
249
+ constructor(deps = {}) {
250
+ this.#exec = deps.exec ?? defaultExec;
251
+ this.#skills = deps.installedSkills ?? new Set();
252
+ this.#log = deps.log;
253
+ this.#graphs = deps.graphs ?? new Graphs(this.#exec);
254
+ this.#planFirst = deps.planFirst ?? false;
255
+ this.#noGit = deps.noGit;
256
+ this.#deadlineMs = deps.trialDeadlineMs ?? TRIAL_DEADLINE_MS;
257
+ this.#trialPick = deps.trialPick ?? DEFAULT_PICK;
258
+ this.#grace = deps.trialGrace ?? DEFAULT_GRACE;
259
+ this.#idle = deps.idle;
260
+ this.#review = deps.review;
261
+ this.#reviewTask = deps.taskReview;
262
+ this.#preview = deps.preview;
263
+ this.#notify = deps.notify;
264
+ this.#onSettled = deps.onSettled;
265
+ this.#evolverReady = deps.evolverReady ?? (() => false);
266
+ this.#evolverCallCost = deps.evolverCallCost ?? (() => 0.004);
267
+ this.#evolverMax = deps.evolverMaxEvalSeconds ?? (() => EVOLVER_MAX_EVAL_S);
268
+ this.#checkTimeoutMs = deps.checkTimeoutMs;
269
+ this.#nudge = deps.nudge;
270
+ this.#onNudge = deps.onNudge;
271
+ this.#sandboxAvailable = deps.sandboxAvailable;
272
+ this.#sandboxReason = deps.sandboxReason;
273
+ this.#unsandboxedAllowed = deps.unsandboxedAllowed;
274
+ this.#gateDeps = deps.gate;
275
+ }
276
+ #gateDeps;
277
+ #log;
278
+ #sandboxAvailable;
279
+ #sandboxReason;
280
+ #unsandboxedAllowed;
281
+ #nudge;
282
+ #onNudge;
283
+ #evolverMax;
284
+ #checkTimeoutMs;
285
+ // How long a check of this job may run.
286
+ #checkTimeout(job) {
287
+ return checkTimeoutOf(job, this.#checkTimeoutMs);
288
+ }
289
+ // The sandbox a check or a contract's evaluator runs in, built per run: its rules name the worktree and the job's
290
+ // grants. Undefined when the plugin wired no gate (a test that runs no sandbox), so the command runs as it did.
291
+ #gate(job, input) {
292
+ const deps = this.#gateDeps;
293
+ return deps ? gateFor(deps, { ...input, jobId: job.id, plan: job.isolation === "plan" }) : Promise.resolve(undefined);
294
+ }
295
+ // The gate of a worker's own run: its worktree, its role and its frozen files.
296
+ #entryGate(entry, job, role) {
297
+ return this.#gate(job, {
298
+ project: entry.project, writer: entry.writer, role, worktree: entry.worktree, dir: entry.dir,
299
+ frozen: entry.frozen ? [...entry.frozen.keys()].map((f) => resolve(entry.dir, f)) : [],
300
+ });
301
+ }
302
+ #evolverReady;
303
+ #evolverCallCost;
304
+ #offers = new Map();
305
+ #offered = 0;
306
+ // A writer measured against a contract whose gain lies in one block (N5's local_block), with a contract that
307
+ // measures fast and one or two files: it does not start, and the user is asked how it should be done instead. A
308
+ // "Method:" line is the answer and skips the question; "Method: trial" asks for a trial whatever the difficulty.
309
+ #offerEvolver(project, job, c, files, title, checks, d, assess) {
310
+ if (d.method === "evolver")
311
+ throw new DelegationError("Not started: the evolver is not a worker; ask an explorer which function or block holds the work, then call evolve_task with the contract, the file, the block and the checks.");
312
+ if (d.method || !c || !assess?.localBlock || !this.#evolverReady() || !evolverFits(c, files, this.#evolverMax()))
313
+ return;
314
+ const id = `M${++this.#offered}`;
315
+ this.#offers.set(id, { project, jobId: job.id, contract: c.id, files: [...files], title, checks: [...checks] });
316
+ const form = evolverForm(id, title, files, c, estimate(c, this.#evolverCallCost()));
317
+ throw new DelegationError(`Not started yet: this task suits the evolver as well as a worker, and how it is done is the user's to decide (it differs in cost). Ask them with the question tool, with exactly this input (a form; its answer reaches the plugin by itself), then end your turn:\n${formInput(form)}`);
318
+ }
319
+ // The user's answer to an evolver offer: what it was about, once.
320
+ takeOffer(id) {
321
+ const o = this.#offers.get(id);
322
+ this.#offers.delete(id);
323
+ return o;
324
+ }
325
+ #deadlineMs;
326
+ #onSettled;
327
+ #trialPick;
328
+ #grace;
329
+ #idle;
330
+ #review;
331
+ #reviewTask;
332
+ #preview;
333
+ #notify;
334
+ #deadlines = new Map(); // "<job>/<head>" -> its trial's deadline
335
+ #noGit;
336
+ // The user's choice for a project without git: its workers change the folder directly, one at a time.
337
+ withoutGit(project, parent) {
338
+ const job = this.job(project, parent);
339
+ job.isolation = "none";
340
+ saveJob(project, job);
341
+ return job;
342
+ }
343
+ // A workspace job: the folder is not a repository, but one of its nested repositories is. Worktrees, checks and the
344
+ // merge happen there; the session and the job stay in the folder, so the context still spans every repository.
345
+ inRepo(project, parent, rel) {
346
+ const job = this.job(project, parent);
347
+ const prefix = rel.replace(/\/+$/, "");
348
+ job.codeRoot = resolve(project, prefix);
349
+ job.integrationBranch = undefined;
350
+ job.integrationWorktree = undefined;
351
+ job.integrationRel = undefined;
352
+ job.integrationRepos = undefined;
353
+ for (const t of job.tasks)
354
+ t.files = t.files.map((f) => (f === prefix ? "" : f.startsWith(`${prefix}/`) ? f.slice(prefix.length + 1) : f));
355
+ saveJob(project, job);
356
+ return job;
357
+ }
358
+ // A1-T7, the one fail-closed rule of plan mode: with no sandbox, no plan writer or investigator starts. The job
359
+ // keeps the reason, once, so its status and its plan say why it ran reader-only. Returns whether it is set. why is
360
+ // the user's own choice when they answered "Run read-only" on the sandbox form (D23); otherwise the machine's.
361
+ readerOnly(project, job, why = "no sandbox on this machine") {
362
+ if (!job.planReaderOnly) {
363
+ job.planReaderOnly = why;
364
+ saveJob(project, job);
365
+ }
366
+ return Boolean(job.planReaderOnly);
367
+ }
368
+ // A1-T8: the plan document Build mode reads. The plugin always leaves one — docFromJob is the floor — but a plan
369
+ // agent's own, richer document wins: an existing document that parses and differs from the generated one is kept as
370
+ // it is, so a rewrite never clobbers findings, questions or recommendations the agent wrote down itself. To tell the
371
+ // plugin's own earlier document from the agent's, a finish compares against the render the plugin would have written
372
+ // before that finish (the job minus the task's just-promoted artifacts, src/plandoc.ts docFromJob): the file equals
373
+ // it, so it is the plugin's and the new artifacts replace it; it parses but differs, so the agent wrote it and it
374
+ // stays. The one exception is a reader-only job whose document does not say so: the restriction must be visible where
375
+ // the user and Build mode look, so that one is rewritten. A failure to write is logged, never thrown — a job does not
376
+ // fail to start because its plan.md could not be written, and the next finish tries again. Nothing here writes into
377
+ // the project: plan.md lives in the job's plan area.
378
+ #ensurePlanDoc(project, job, finishing) {
379
+ try {
380
+ const doc = docFromJob(job);
381
+ const existing = readPlanDoc(project, job.id);
382
+ const text = existing.doc ? readFileSync(existing.path, "utf8") : undefined;
383
+ const generated = renderPlanDoc(job, doc);
384
+ const ours = finishing ? renderPlanDoc(job, docFromJob(priorToFinish(job, finishing))) : undefined;
385
+ const keeps = existing.doc !== undefined && text !== generated && (ours === undefined || text !== ours) &&
386
+ (job.planReaderOnly === undefined || existing.doc.readerOnly !== undefined);
387
+ if (!keeps)
388
+ writePlanDoc(project, job.id, doc);
389
+ }
390
+ catch (err) {
391
+ this.#log?.("warn", `plan.md for ${job.id} could not be written: ${err instanceof Error ? err.message : String(err)}`);
392
+ }
393
+ }
394
+ // Whether this delegation must be refused because its plan job has no sandbox: it is then flagged and the job saved,
395
+ // and the caller throws. Readers are not asked: they investigate as usual. A job the user confirmed for exactly this
396
+ // (D23, its control file carries the grant) is not refused: the checks then run unwrapped and say so.
397
+ #refusePlanWriter(project, job, role) {
398
+ const off = loadControl(project, job.id).sandboxOff === true;
399
+ if (job.isolation !== "plan" || !WRITERS.has(role.id) || (!off && this.#sandboxAvailable?.() !== false))
400
+ return false;
401
+ if (off || this.#unsandboxedAllowed?.(project, job.id) === true)
402
+ return false;
403
+ return this.readerOnly(project, job, off ? "the sandbox is switched off for this job" : "no sandbox on this machine");
404
+ }
405
+ // The refusal of a plan writer without a sandbox: what did not start, why, and what to do first.
406
+ #readerOnlyError(project, job) {
407
+ const off = loadControl(project, job.id).sandboxOff === true;
408
+ const why = off ? "" : this.#sandboxReason?.();
409
+ const because = off
410
+ ? "the sandbox is switched off for this job"
411
+ : `there is no sandbox on this machine${why ? ` (${why})` : ""}`;
412
+ return new DelegationError(`Not started: plan job ${job.id} runs reader-only because ${because}. ` +
413
+ `Readers still investigate; ${off ? "turn the sandbox back on in Settings" : "fix the sandbox first (omacode doctor)"} and start the task again.`);
414
+ }
415
+ // A1-T11: a plan job started without a sandbox goes on reader-only, and the micromanager that started it says so
416
+ // instead of finding out at the first investigator. The job already carries the reason (readerOnly), this is what
417
+ // the user reads at the start.
418
+ #readerOnlyWarning(project, job) {
419
+ const off = loadControl(project, job.id).sandboxOff === true;
420
+ const why = off ? "" : this.#sandboxReason?.();
421
+ const because = off
422
+ ? "the sandbox is switched off for this job"
423
+ : `there is no sandbox on this machine${why ? ` (${why})` : ""}`;
424
+ return `Job ${job.id} starts reader-only: ${because}, so no investigator will be delegated and nothing of the project is touched. Readers still look; ${off ? "turn the sandbox back on in Settings" : "fix the sandbox first (omacode doctor)"} to run investigators.`;
425
+ }
426
+ #planFirst;
427
+ // The note that asks the user to start the job, with the start form to pass to the question tool; undefined once
428
+ // the job is started.
429
+ startNote(project, job) {
430
+ if (isStarted(job, loadControl(project, job.id)))
431
+ return undefined;
432
+ const open = job.tasks.filter((t) => ["pending", "ready", "planned"].includes(t.status));
433
+ if (!open.length)
434
+ return undefined;
435
+ const form = startForm(job.id, open.length, startable(job).length, lastOptions(project));
436
+ return `The plan is not started yet. When the todo list is complete, ask the user to start it: call the question tool with exactly this input (it is a form; the user ticks the options and says Start), then end your turn:\n${formInput(form)}`;
437
+ }
438
+ // The micromanager session's job: made at its first delegation, kept until the session ends.
439
+ job(project, parent) {
440
+ const live = [...this.#jobs.values()].find((j) => j.facilitator === parent && j.rolling && this.#jobs.get(key(project, j.id)) === j);
441
+ if (live)
442
+ return live;
443
+ const found = listJobs(project).find((j) => j.facilitator === parent && j.rolling && !["done", "stopped", "failed"].includes(j.phase));
444
+ const job = found ?? newJob(jobId(), `the delegated tasks of micromanager session ${parent}`);
445
+ if (!found) {
446
+ for (const p of ["triage", "plan", "plan_gate", "execute"])
447
+ moveJob(job, p);
448
+ job.rolling = true;
449
+ job.facilitator = parent;
450
+ saveJob(project, job);
451
+ }
452
+ this.#jobs.set(key(project, job.id), job);
453
+ return job;
454
+ }
455
+ // After a restart: the workers of the project's open jobs, rebuilt from the job files. Everything the plugin knew of
456
+ // them lived in memory, so a worker continued after a restart (reboot, 2026-10-14) answered finish_task with "no
457
+ // task", and the duplicate check could not see the change it had left in its worktree. Every session found here is
458
+ // over, since the restart ended it; resume() makes it live again when the micromanager continues it. Returns the
459
+ // adopted "<job>/<task>" keys.
460
+ adopt(project) {
461
+ const adopted = [];
462
+ for (const job of listJobs(project)) {
463
+ if (!(job.rolling || job.native) || !job.facilitator || ["done", "stopped", "failed"].includes(job.phase))
464
+ continue;
465
+ const known = this.#jobs.get(key(project, job.id));
466
+ if (known)
467
+ continue;
468
+ this.#jobs.set(key(project, job.id), job);
469
+ for (const task of job.tasks) {
470
+ const k = `${job.id}/${task.id}`;
471
+ if (!task.session || this.#entries.has(k))
472
+ continue;
473
+ const writer = WRITERS.has(task.role);
474
+ const integ = task.repo ? job.integrationRepos?.[task.repo] : undefined;
475
+ const worktree = writer ? task.worktree : integ?.worktree ?? job.integrationWorktree;
476
+ const rel = (writer ? task.worktreeRel : integ?.rel ?? job.integrationRel) ?? job.integrationRel ?? "";
477
+ const verify = job.acceptance.filter((a) => task.acceptance.includes(a.id)).map((a) => a.verify).filter((v) => Boolean(v));
478
+ const entry = {
479
+ project,
480
+ ...(task.repo ? { repo: task.repo } : {}),
481
+ jobId: job.id,
482
+ taskId: task.id,
483
+ parent: job.facilitator,
484
+ writer,
485
+ dir: worktree ? taskDir(worktree, rel) : project,
486
+ worktree: worktree ?? job.integrationWorktree ?? project,
487
+ rel,
488
+ branch: writer ? task.branch : undefined,
489
+ removed: writer && !task.worktree,
490
+ session: task.session,
491
+ // The checks as given; a job written before they were kept has only the joined verify to go by.
492
+ checks: task.checks ?? verify.flatMap((v) => v.split(" && ")).map((c) => c.trim()).filter(Boolean),
493
+ ...(task.contract ? { contract: task.contract.id } : {}),
494
+ ...(task.frozen ? { frozen: new Map(Object.entries(task.frozen)) } : {}),
495
+ ended: true,
496
+ };
497
+ this.#entries.set(k, entry);
498
+ for (const s of new Set([task.session, ...(task.sessions ?? [])]))
499
+ this.#bySession.set(s, k);
500
+ adopted.push(k);
501
+ }
502
+ // A trial decided by score whose deadline lived in the process that ended: armed again, from the time it had.
503
+ for (const head of job.tasks.filter((t) => t.settleBy && t.trial?.of === t.id)) {
504
+ const now = standing(job, head);
505
+ if (!now.winner && now.held.length && pickOf(head) !== "user")
506
+ this.#arm(project, job, head);
507
+ }
508
+ }
509
+ return adopted;
510
+ }
511
+ // The open jobs of earlier micromanager sessions of this project: rolling, not finished, and with something left in
512
+ // them (a merged task, or a task with a worktree). A new session starts a job of its own, so without this the
513
+ // previous session's work was out of sight: merged tasks the checkout never got, unfinished changes in worktrees.
514
+ openJobs(project, parent) {
515
+ return listJobs(project)
516
+ .filter((j) => j.rolling && j.facilitator && j.facilitator !== parent && !["done", "stopped", "failed"].includes(j.phase))
517
+ .map((j) => this.#jobs.get(key(project, j.id)) ?? j)
518
+ .filter((j) => j.tasks.some((t) => (t.status === "merged" && !t.undone) || (t.worktree && t.status !== "merged")));
519
+ }
520
+ // Whether this micromanager session has a job of its own yet.
521
+ hasJob(project, parent) {
522
+ return listJobs(project).some((j) => j.rolling && j.facilitator === parent && !["done", "stopped", "failed"].includes(j.phase));
523
+ }
524
+ // "Continue" at the start of a session: the earlier session's job becomes this session's. New workers land on the
525
+ // same branch, its unfinished workers can be continued by their sessions, and their notes and permission requests
526
+ // come to this session. Refused when this session started a job of its own already: two jobs of one session would
527
+ // split its work over two branches.
528
+ takeOver(project, jobId, parent) {
529
+ if (this.hasJob(project, parent))
530
+ return { problem: "this session has a job of its own already; continue the earlier one in a new session, or merge or discard it" };
531
+ this.adopt(project);
532
+ const job = this.#jobs.get(key(project, jobId)) ?? listJobs(project).find((j) => j.id === jobId);
533
+ if (!job || !job.rolling)
534
+ return { problem: `there is no open job ${jobId} of a micromanager session in this project` };
535
+ if (["done", "stopped", "failed"].includes(job.phase))
536
+ return { problem: `job ${jobId} is ${job.phase}` };
537
+ job.facilitator = parent;
538
+ this.#jobs.set(key(project, job.id), job);
539
+ for (const entry of this.#entries.values()) {
540
+ if (entry.jobId === job.id && entry.project === project)
541
+ entry.parent = parent;
542
+ }
543
+ saveJob(project, job);
544
+ return { job };
545
+ }
546
+ // A new subagent call of the micromanager: the task, its worktree and the worker's brief. Throws a
547
+ // DelegationError the micromanager can act on when the call is not a valid delegation. Calls of one message come
548
+ // at the same time; they go one after another (live test: two made the session branch at once, and one failed).
549
+ // assess: what the plugin found out about a writer before (src/trials.ts): its difficulty and how many attempts.
550
+ delegate(project, parent, input, model, assess) {
551
+ const next = (this.#delegating.get(parent) ?? Promise.resolve()).then(() => this.#delegate(project, parent, input, model, assess));
552
+ this.#delegating.set(parent, next.catch(() => undefined));
553
+ return next;
554
+ }
555
+ async #delegate(project, parent, input, model, assess) {
556
+ const role = roleByAgent(input.agent);
557
+ if (!role)
558
+ throw new DelegationError(`Not started: use one of the role agents (${ROLES.map((r) => r.agent).join(", ")}), not ${input.agent || "none"}.`);
559
+ const d = parseDelegation(input.prompt);
560
+ if (d.attempt)
561
+ return this.#attempt(project, parent, role, d, d.attempt, model);
562
+ if (d.planned)
563
+ return this.#planned(project, parent, role, d, d.planned, model, assess);
564
+ if (d.redteam)
565
+ return this.#redteam(project, parent, role, d, d.redteam, model);
566
+ if (this.#planFirst && WRITERS.has(role.id)) {
567
+ throw new DelegationError(`Not started: a ${role.agent} starts from a todo. Write it down with the todo tool first (with "after" for what it waits for, "replaces" for a task it does over), then start it with the prompt line "Task: T… · job-…".`);
568
+ }
569
+ const parsed = parseFiles(d.files, project);
570
+ if (parsed.problem)
571
+ throw new DelegationError(`Not started: ${parsed.problem}`);
572
+ const writer = WRITERS.has(role.id);
573
+ if (writer && !parsed.files.length)
574
+ throw new DelegationError(`Not started: a ${role.agent} changes files; end the prompt with a line "Files: <the project paths it may change>" and a line "Checks: <shell command>".`);
575
+ if (!writer && parsed.files.length)
576
+ throw new DelegationError(`Not started: ${role.agent} only reads; leave out the Files line, or pick a role that writes.`);
577
+ // Every check that will reach runGate is validated here, before the task or its worktree exist: a command that is
578
+ // not one, one that is destructive, and a writer whose set cannot fail at all. A refused delegation must leave
579
+ // nothing behind, and this runs before addDelegated and prepareTaskWorktree, so it does.
580
+ if (d.method === "trial" && !d.checks.length && !d.contract?.trim()) {
581
+ throw new DelegationError(`Not started: ${TRIAL_EVALUATOR_REQUIRED}`);
582
+ }
583
+ const checks = checkSetProblems(d.checks, writer && !d.contract?.trim());
584
+ if (checks)
585
+ throw new DelegationError(`Not started: ${checks}`);
586
+ const cwdProblem = d.checks.map((c) => checkCwdProblem(c, project, project, project)).find(Boolean);
587
+ if (cwdProblem)
588
+ throw new DelegationError(`Not started: ${cwdProblem}`);
589
+ if (!d.body)
590
+ throw new DelegationError("Not started: the prompt has no task.");
591
+ const job = this.job(project, parent);
592
+ if (this.#refusePlanWriter(project, job, role))
593
+ throw this.#readerOnlyError(project, job);
594
+ this.#setGoal(project, job, d.goal);
595
+ const c = this.#contractFor(job, writer, d.contract, assess);
596
+ this.#offerEvolver(project, job, c, parsed.files, input.description.trim() || d.body.split("\n")[0], d.checks, d, assess);
597
+ if (d.method === "trial")
598
+ assess = { ...(assess ?? {}), trials: Math.max(2, assess?.trials ?? 1) };
599
+ // Check before replacing: a refusal must not have discarded the worktree of a task named in Replaces. The replace
600
+ // check itself mutates nothing, so it runs first and keeps the more specific "still runs" message.
601
+ const cannotReplace = this.#replaceable(project, job, d.replaces);
602
+ if (cannotReplace.length)
603
+ throw new DelegationError(`Not started: ${cannotReplace.join("; ")}`);
604
+ const duplicate = this.#duplicate(job, role, input.description.trim(), d.body, parsed.files, d.replaces);
605
+ if (duplicate)
606
+ throw new DelegationError(duplicate);
607
+ await this.#replace(project, job, d.replaces);
608
+ if (WRITERS.has(role.id)) {
609
+ const [rel, working] = await Promise.all([repoRel(project), dirtyPaths(project)]);
610
+ const blocked = working.dirty ? dirtyDeclared(parsed.files, rel, working.paths) : [];
611
+ if (blocked.length > 0) {
612
+ throw new DelegationError(`Not started: this task may change ${blocked.slice(0, 5).join(", ")}${blocked.length > 5 ? `, +${blocked.length - 5} more` : ""}, ` +
613
+ `whose current version is uncommitted in your checkout. A worker starts from HEAD and would not see it. ` +
614
+ `Commit or stash those files first, then delegate again.`);
615
+ }
616
+ }
617
+ const rel = await this.#integrate(project, job, WRITERS.has(role.id));
618
+ const added = addDelegated(job, { title: input.description.trim() || d.body.split("\n")[0], prompt: d.body, files: parsed.files, dependsOn: [], checks: d.checks, ...(assess?.tier ? { tier: assess.tier } : {}) });
619
+ if (!added.task)
620
+ throw new DelegationError(`Not started: ${added.errors.join("; ")}`);
621
+ const task = added.task;
622
+ this.#bind(job, task, d.contract);
623
+ if (d.frozen)
624
+ task.freeze = parseFiles(d.frozen, project).files;
625
+ this.#link(project, job, task, d.replaces);
626
+ task.role = role.id;
627
+ task.model = model;
628
+ this.#assess(project, job, task, assess, d.pick, d.checks, d);
629
+ if (d.preview)
630
+ task.preview = d.preview;
631
+ for (const s of ["ready", "planned", "running"])
632
+ moveTask(task, s);
633
+ stage(task, "delegate", "pass", `${role.agent} on ${model}`);
634
+ return this.#start(project, parent, job, task, role, model, d, d.checks, rel);
635
+ }
636
+ // The contract a writer is measured against, checked before anything of the task exists: one that the job has, with
637
+ // a baseline to compare with. An open-ended task (N5's open_ended, src/trials.ts Assessment) without one is refused,
638
+ // as a writer without checks is: nothing could tell a better result from a worse one.
639
+ #contractFor(job, writer, id, assess) {
640
+ if (!writer) {
641
+ if (id)
642
+ throw new DelegationError("Not started: a fitness contract measures a writer's work; leave out the Contract line for a reader.");
643
+ return undefined;
644
+ }
645
+ if (!id) {
646
+ if (assess?.openEnded)
647
+ throw new DelegationError('Not started: this task asks to make something better with no fixed end, so it needs a fitness contract that says what "better" means. Define one with the contract tool (goal, an evaluator that prints MM_SCORE, scores with a direction, guards), then delegate again with a line "Contract: C…".');
648
+ return undefined;
649
+ }
650
+ const c = job.contracts?.find((x) => x.id === id);
651
+ if (!c)
652
+ throw new DelegationError(`Not started: job ${job.id} has no contract ${id}; define it with the contract tool first.`);
653
+ if (!c.baseline)
654
+ throw new DelegationError(`Not started: contract ${id} has no baseline, because its evaluator did not give a valid result on today's code; fix the contract with the contract tool first.`);
655
+ // What "better" means is the user's: a draft has not been through the round (their preferences, the red team, the
656
+ // baseline check) yet.
657
+ if (c.status !== "frozen")
658
+ throw new DelegationError(`Not started: contract ${id} is a draft; finish its round first (contract_round with input "${id}"), so the user decides what it measures.`);
659
+ return c;
660
+ }
661
+ // The task is measured against this version of the contract from now on.
662
+ #bind(job, task, id) {
663
+ const c = id ? job.contracts?.find((x) => x.id === id) : undefined;
664
+ if (c)
665
+ task.contract = { id: c.id, version: c.version };
666
+ }
667
+ // The contract tool: a contract for the job (the session's own when jobId is empty), new or as a new version of the
668
+ // one with its id, with its baseline measured on the job's branch as it is now. Returns the answer to the micromanager.
669
+ // byUser: a change the user accepted (request_check_change kind contract); it may change a frozen contract.
670
+ async contract(project, parent, jobId, json, byUser = false) {
671
+ const job = jobId ? this.#jobs.get(key(project, jobId)) ?? listJobs(project).find((j) => j.id === jobId) : this.job(project, parent);
672
+ if (!job)
673
+ return `There is no job ${jobId} in this project. Nothing was stored.`;
674
+ const parsed = parseContract(json);
675
+ if (!parsed.contract)
676
+ return `Not stored: ${parsed.errors.join("; ")}.`;
677
+ const wanted = String(JSON.parse(json).id ?? "").toUpperCase();
678
+ const old = wanted ? job.contracts?.find((c) => c.id === wanted) : undefined;
679
+ if (wanted && !old)
680
+ return `Not stored: job ${job.id} has no contract ${wanted} to change; leave out the id for a new one.`;
681
+ if (old?.status === "frozen" && !byUser)
682
+ return `Not stored: contract ${old.id} is frozen; only the user changes it.`;
683
+ const at = new Date().toISOString();
684
+ const n = Math.max(0, ...(job.contracts ?? []).map((c) => Number(c.id.slice(1)))) + 1;
685
+ const c = old
686
+ ? { ...old, ...parsed.contract, version: old.version + 1, baseline: undefined, history: [...old.history, { version: old.version + 1, change: "changed with the contract tool", at }] }
687
+ : { id: `C${n}`, version: 1, status: "draft", ...parsed.contract, history: [{ version: 1, change: "defined with the contract tool", at }] };
688
+ if (old) {
689
+ c.status = "draft"; // a new version goes through the round again, unless the user changed it (applyCheckChange)
690
+ c.round = undefined;
691
+ c.frozen = undefined;
692
+ }
693
+ // The held-out cases come from a directory outside the project and go to the plugin's state directory; a new
694
+ // version without them keeps the ones it had.
695
+ if (parsed.heldOutFrom) {
696
+ const kept = keepHeldOut(parsed.heldOutFrom, project, heldOutDir(project, job.id, c.id));
697
+ if (!kept.heldOut)
698
+ return `Not stored: ${kept.problem}.`;
699
+ c.corpus = { ...c.corpus, heldOut: kept.heldOut };
700
+ }
701
+ else if (old?.corpus.heldOut)
702
+ c.corpus = { ...c.corpus, heldOut: old.corpus.heldOut };
703
+ // The baseline is today's code on the job's branch, where the workers start from; a folder without git has only
704
+ // itself.
705
+ const rel = await this.#integrate(project, job, false);
706
+ const dir = taskDir(job.integrationWorktree ?? project, rel);
707
+ const gate = await this.#gate(job, { project, writer: true, role: "code", worktree: job.integrationWorktree ?? project, dir });
708
+ const { measured, seconds } = await runEvaluator(dir, c, "visible", this.#exec, undefined, gate);
709
+ this.#count(job, c, seconds);
710
+ // A guard or a target on a value the evaluator does not print is never checked (live run, 2026-10-26: a drafted
711
+ // guard "cases.passed", which is no score, held nothing): refused while the draft can still be fixed.
712
+ const named = [...c.guards.map((g) => g.name), ...Object.keys(c.stop.target ?? {})];
713
+ const unmeasured = measured.valid ? [...new Set(named.filter((n) => !(n in measured.values)))] : [];
714
+ if (unmeasured.length)
715
+ return `Not stored: ${unmeasured.join(", ")} ${unmeasured.length > 1 ? "are no values" : "is no value"} the evaluator prints, so ${unmeasured.length > 1 ? "they" : "it"} would never be checked. It prints ${Object.keys(measured.values).join(", ") || "no scores"}: name a guard or a target after one of those, or make the evaluator print it among its scores.`;
716
+ if (measured.valid) {
717
+ const commit = job.integrationWorktree ? (await this.#exec("git", ["rev-parse", "--short", "HEAD"], { cwd: job.integrationWorktree })).stdout.trim() : undefined;
718
+ c.baseline = { values: { ...measured.values }, at, ...(commit ? { commit } : {}) };
719
+ c.costPerEval = Math.round((seconds / c.repeats) * 10) / 10;
720
+ if (c.quick) {
721
+ // The quick stage's own baseline: the cascade compares a candidate there with today's code there.
722
+ const q = await runEvaluator(dir, { ...c, evaluator: c.quick.evaluator, repeats: 1 }, "visible", this.#exec, undefined, gate);
723
+ this.#count(job, c, q.seconds);
724
+ if (q.measured.valid) {
725
+ c.baseline.quick = { ...q.measured.values };
726
+ c.quick = { ...c.quick, costPerEval: q.seconds };
727
+ }
728
+ }
729
+ if (c.corpus.heldOut) {
730
+ const held = await runEvaluator(dir, c, "heldout", this.#exec, heldOutDir(project, job.id, c.id), gate);
731
+ this.#count(job, c, held.seconds);
732
+ if (held.measured.valid)
733
+ c.baseline.heldOut = { ...held.measured.values };
734
+ }
735
+ }
736
+ job.contracts = [...(job.contracts ?? []).filter((x) => x.id !== c.id), c];
737
+ this.#jobs.set(key(project, job.id), job);
738
+ saveJob(project, job);
739
+ saveContract(project, job.id, c);
740
+ if (!measured.valid)
741
+ return `Contract ${c.id} (version ${c.version}) is stored for job ${job.id}, but its evaluator gave no valid result on today's code (${measured.error}), so it has no baseline and no writer can be measured against it yet. Fix the evaluator and send the contract again with "id": "${c.id}".`;
742
+ const held = c.corpus.heldOut ? ` It has ${c.corpus.heldOut.cases} held-out cases, which only the evaluator sees${c.baseline?.heldOut ? "" : "; on them today's code gave no valid result"}.` : "";
743
+ return `Contract ${c.id} (version ${c.version}, ${c.status}) is stored for job ${job.id}. Baseline${c.baseline?.commit ? ` on ${c.baseline.commit}` : ""}: ${describe({ ...c, baseline: undefined }, measured)} (${c.costPerEval}s per run).${held} It is a draft: before a writer is measured against it, take it through its round with contract_round (input "${c.id}"), where the user decides what it measures.`;
744
+ }
745
+ // The files a writer may read and run but not change, hashed as its worktree has them now: the ones its todo or
746
+ // delegation asked for, the existing files its checks name that are not its own, and its contract's evaluator and
747
+ // visible corpus. A file of its own write scope is never frozen: the two would contradict each other.
748
+ async #freeze(job, task, entry) {
749
+ const own = new Set(task.files);
750
+ const c = entry.contract ? job.contracts?.find((x) => x.id === entry.contract) : undefined;
751
+ const corpus = [];
752
+ for (const p of c?.corpus.visible ?? []) {
753
+ const listed = await this.#exec("git", ["ls-files", "--", p], { cwd: entry.dir });
754
+ corpus.push(...listed.stdout.split("\n").map((l) => l.trim()).filter(Boolean));
755
+ }
756
+ const named = [...entry.checks, ...(c ? [c.evaluator] : [])].flatMap((command) => namedFiles(command, entry.dir));
757
+ const paths = [...new Set([...(task.freeze ?? []), ...named, ...corpus])].filter((p) => !own.has(p)).sort();
758
+ if (!paths.length)
759
+ return;
760
+ entry.frozen = await hashFiles(entry.worktree, paths, this.#exec, entry.dir);
761
+ task.frozen = Object.fromEntries(entry.frozen);
762
+ }
763
+ // A writer's frozen files as absolute paths, for the sandbox (src/shell/sandbox.ts denyWrite) and the permission hook.
764
+ frozenOf(session) {
765
+ const entry = this.#entry(session);
766
+ return entry?.writer && entry.frozen ? [...entry.frozen.keys()].map((f) => resolve(entry.dir, f)) : [];
767
+ }
768
+ // The resources of a write request that are frozen for this writer; resources are paths relative to its directory or
769
+ // absolute.
770
+ frozenHit(session, resources) {
771
+ const entry = this.#entry(session);
772
+ if (!entry?.writer || !entry.frozen?.size)
773
+ return [];
774
+ const frozen = new Set(this.frozenOf(session));
775
+ return resources.filter((r) => frozen.has(isAbsolute(r) ? resolve(r) : resolve(entry.dir, r)));
776
+ }
777
+ // A worker's report as it ended: its FOLLOWUP lines go to the job's later list, unless the job has the work already
778
+ // (a task with nearly that title) or the list has it. They become backlog drafts when the job ends (backlog()).
779
+ noteFollowUps(session, report) {
780
+ const entry = this.#entry(session);
781
+ const job = entry && this.#job(entry);
782
+ if (!entry || !job)
783
+ return [];
784
+ const task = job.tasks.find((t) => t.id === entry.taskId);
785
+ let dirty = false;
786
+ if (task && report.trim()) {
787
+ this.#recordReport(job, task, report, entry.writer, undefined, task.status);
788
+ dirty = true;
789
+ }
790
+ const known = [...job.tasks.map((t) => t.title), ...(job.later ?? []).map((l) => l.what)];
791
+ const added = parseReport(report).followUps
792
+ .filter((f) => !known.some((k) => similarity(k, f.what) >= SAME_WORK))
793
+ .slice(0, 5)
794
+ .map((f) => ({ ...f, from: entry.taskId, reason: "reported" }));
795
+ if (added.length)
796
+ job.later = [...(job.later ?? []), ...added];
797
+ if (dirty || added.length)
798
+ saveJob(entry.project, job);
799
+ return added;
800
+ }
801
+ // Pattern 6: capture structured STATUS / FILES / EVIDENCE / OPEN / LEARNED handoff fields on task.report so direct
802
+ // dependsOn children receive upstreamHandoffs() automatically without facilitator telephone loss.
803
+ #recordReport(job, task, raw, writer, touchedFiles, defaultStatus) {
804
+ const parsed = parseReport(raw);
805
+ const structured = Boolean(parsed.status || parsed.files.length || parsed.evidence || parsed.open || parsed.learned.length || parsed.followUps.length);
806
+ const files = [...new Set([
807
+ ...parsed.files,
808
+ ...(touchedFiles ?? []),
809
+ ...(parsed.files.length || touchedFiles?.length ? [] : task.report?.files.length ? task.report.files : writer ? task.files : []),
810
+ ])];
811
+ const prose = !structured && raw.trim() ? raw.trim().replace(/\s+/g, " ").slice(0, 500) : "";
812
+ const evidence = parsed.evidence || task.report?.evidence || prose || task.summary || "";
813
+ const open = parsed.open || task.report?.open || "none";
814
+ const learned = [...new Set([...(task.learned ?? []), ...(task.report?.learned ?? []), ...parsed.learned])];
815
+ if (learned.length) {
816
+ task.learned = learned;
817
+ for (const l of parsed.learned)
818
+ if (!job.lessons.includes(l))
819
+ job.lessons.push(l);
820
+ if (job.lessons.length > 20)
821
+ job.lessons.splice(0, job.lessons.length - 20);
822
+ }
823
+ const status = parsed.status ?? defaultStatus ?? task.report?.status;
824
+ task.report = {
825
+ ...(status ? { status } : {}),
826
+ files,
827
+ evidence,
828
+ open,
829
+ learned,
830
+ };
831
+ }
832
+ // The job ended (merged into the checkout or discarded): what it found and did not do goes to the backlog as drafts,
833
+ // so it outlives the session. A follow-up that a task of the job took up after all is left out, and so is a failed
834
+ // trial that a later task did over. Each item is written once. The item the job was started from (plan_job
835
+ // backlog:<slug>) is done once the job is merged, and ready again once it is discarded.
836
+ backlog(project, job, merged, backend = localBackend, now = new Date()) {
837
+ const live = this.#jobs.get(key(project, job.id)) ?? job;
838
+ const items = backend.list(project);
839
+ const source = items.filter((i) => i.job === live.id && i.status === "running");
840
+ for (const i of source) {
841
+ i.status = merged ? "done" : "ready";
842
+ backend.save(project, i);
843
+ }
844
+ const taken = new Set(items.map((i) => i.slug));
845
+ const drafts = [];
846
+ const save = (item) => {
847
+ backend.save(project, item);
848
+ taken.add(item.slug);
849
+ drafts.push(item);
850
+ };
851
+ for (const l of live.later ?? []) {
852
+ if (l.draft || live.tasks.some((t) => t.id !== l.from && similarity(t.title, l.what) >= SAME_WORK))
853
+ continue;
854
+ const item = draftFromLater(l, live, taken, now);
855
+ save(item);
856
+ l.draft = item.slug;
857
+ }
858
+ for (const head of live.tasks.filter((t) => t.trial?.of === t.id)) {
859
+ const trial = standing(live, head);
860
+ if (trial.winner || trial.live.length || !trial.failed.length || trial.all.some((t) => t.replacedBy) || head.stages.some((s) => s.stage === "backlog"))
861
+ continue;
862
+ const checks = live.acceptance.filter((a) => head.acceptance.includes(a.id)).flatMap((a) => (a.verify ? [a.verify] : []));
863
+ const item = draftFromTrial(live, head, trial.failed, checks, taken, now);
864
+ save(item);
865
+ stage(head, "backlog", "pass", `draft ${item.slug}`);
866
+ }
867
+ if (drafts.length)
868
+ saveJob(project, live);
869
+ return { drafts, source };
870
+ }
871
+ // What a writer asking for a check change is, for the request: its job, task, model and how often it asked.
872
+ changeContext(session) {
873
+ const entry = this.#entry(session);
874
+ const job = entry && this.#job(entry);
875
+ const task = job?.tasks.find((t) => t.id === entry.taskId);
876
+ if (!entry?.writer || !job || !task)
877
+ return undefined;
878
+ return { project: entry.project, job, task, parent: entry.parent, asked: task.checkChanges?.length ?? 0 };
879
+ }
880
+ // A decided check change, on the task (and the outcome log after it).
881
+ recordChange(project, jobId, taskId, kind, a, id, target) {
882
+ const job = this.#jobs.get(key(project, jobId));
883
+ const task = job?.tasks.find((t) => t.id === taskId);
884
+ if (!job || !task)
885
+ return;
886
+ task.checkChanges = [...(task.checkChanges ?? []), { kind, accepted: a.accepted, by: a.by }];
887
+ stage(task, "check-change", a.accepted ? "pass" : "fail", `${id} ${kind}: ${target.slice(0, 120)}${a.note ? ` (${a.note.slice(0, 120)})` : ""}`);
888
+ saveJob(project, job);
889
+ }
890
+ // An accepted check change, applied from outside: the worker never touches the check itself. A check command is
891
+ // replaced; a frozen file gets the proposed diff and is frozen again as it is now; a contract gets a new version. In a
892
+ // trial every attempt still at work gets the same change and a note, so all are measured by the same rule. Returns
893
+ // what was done, or why it could not be, and the notes for the other attempts.
894
+ async applyCheckChange(project, jobId, taskId, r) {
895
+ const job = this.#jobs.get(key(project, jobId));
896
+ const task = job?.tasks.find((t) => t.id === taskId);
897
+ const entry = this.#entries.get(`${jobId}/${taskId}`);
898
+ if (!job || !task || !entry)
899
+ return { ok: false, text: "the task is gone", steer: [] };
900
+ const siblings = task.trial ? standing(job, task).live.filter((t) => t !== task) : [];
901
+ const entries = [entry, ...siblings.map((t) => this.#entries.get(`${job.id}/${t.id}`)).filter((e) => Boolean(e && !e.ended))];
902
+ const steer = (what) => entries.slice(1).filter((e) => e.session).map((e) => ({ session: e.session, note: `[micromanager] ${r.id}: the check change another attempt asked for is accepted and applied to your worktree as well: ${what}. Your checks run against it from now on. This note comes from your own plugin; it is trusted.` }));
903
+ if (r.kind === "contract") {
904
+ const c = job.contracts?.find((x) => x.id === task.contract?.id);
905
+ if (!c)
906
+ return { ok: false, text: "the task is measured against no contract", steer: [] };
907
+ let proposal;
908
+ try {
909
+ proposal = JSON.parse(r.proposal);
910
+ }
911
+ catch {
912
+ return { ok: false, text: "the proposal is no contract JSON", steer: [] };
913
+ }
914
+ const wasFrozen = c.status === "frozen";
915
+ const text = await this.contract(project, entry.parent, job.id, JSON.stringify({ ...proposal, id: c.id }), true);
916
+ if (!text.startsWith(`Contract ${c.id} (version`))
917
+ return { ok: false, text, steer: [] };
918
+ const now = job.contracts.find((x) => x.id === c.id);
919
+ if (!now.baseline)
920
+ return { ok: false, text, steer: [] };
921
+ // The user decided this change, which is what the round is for: frozen again as it is now.
922
+ if (wasFrozen)
923
+ await this.#freezeContract(project, job, now);
924
+ for (const e of entries)
925
+ this.#bind(job, job.tasks.find((t) => t.id === e.taskId), c.id);
926
+ return { ok: true, text: `contract ${c.id} is version ${now.version} now`, steer: steer(`contract ${c.id} is version ${now.version} now`) };
927
+ }
928
+ if (r.kind === "spec_incomplete")
929
+ job.decisions.push({ id: `D${job.decisions.length + 1}`, text: `${r.problem.slice(0, 300)} Decided: ${r.proposal.slice(0, 300)}`, origin: "user" });
930
+ const target = normalTarget(r.target);
931
+ const check = entry.checks.find((c) => normalTarget(c) === target);
932
+ if (check) {
933
+ const next = r.proposal.trim();
934
+ const why = checkSetProblems([next], true);
935
+ if (why)
936
+ return { ok: false, text: `the proposed check is not one: ${why}`, steer: [] };
937
+ for (const e of entries) {
938
+ e.checks = e.checks.map((c) => (normalTarget(c) === target ? next : c));
939
+ const t = job.tasks.find((x) => x.id === e.taskId);
940
+ t.checks = [...e.checks];
941
+ job.acceptance = job.acceptance.map((a) => (t.acceptance.includes(a.id) && a.verify ? { ...a, verify: e.checks.join(" && ") } : a));
942
+ }
943
+ saveJob(project, job);
944
+ return { ok: true, text: `the check "${check}" is "${next}" now`, steer: steer(`the check "${check}" is "${next}" now`) };
945
+ }
946
+ const path = r.target.trim().replace(/^\.\//, "");
947
+ const known = entry.frozen?.has(path) || (() => { try {
948
+ return statSync(join(entry.dir, path)).isFile();
949
+ }
950
+ catch {
951
+ return false;
952
+ } })();
953
+ if (!known)
954
+ return { ok: false, text: `${r.target.trim()} is neither a check of the task nor a file in its directory`, steer: [] };
955
+ const scratch = mkdtempSync(join(tmpdir(), "mm-change-"));
956
+ try {
957
+ const patch = join(scratch, "change.patch");
958
+ writeFileSync(patch, r.proposal.endsWith("\n") ? r.proposal : `${r.proposal}\n`);
959
+ for (const e of entries) {
960
+ const args = ["apply", "--whitespace=nowarn", ...(e.rel ? [`--directory=${e.rel}`] : []), patch];
961
+ const applied = await this.#exec("git", args, { cwd: e.worktree });
962
+ if (applied.code !== 0)
963
+ return { ok: false, text: `the diff does not apply to ${path}${e === entry ? "" : ` in ${e.taskId}'s worktree`}: ${applied.stderr.trim().slice(0, 300)}`, steer: [] };
964
+ if (e.frozen?.has(path)) {
965
+ const hash = (await hashFiles(e.worktree, [path], this.#exec, e.dir)).get(path) ?? "";
966
+ e.frozen.set(path, hash);
967
+ const t = job.tasks.find((x) => x.id === e.taskId);
968
+ t.frozen = Object.fromEntries(e.frozen);
969
+ }
970
+ }
971
+ }
972
+ finally {
973
+ rmSync(scratch, { recursive: true, force: true });
974
+ }
975
+ saveJob(project, job);
976
+ return { ok: true, text: `${path} is changed as proposed${entry.frozen?.has(path) ? " and frozen again" : ""}`, steer: steer(`${path} is changed as proposed`) };
977
+ }
978
+ // --- the contract round (src/contractround.ts) ---------------------------------------------------------------
979
+ // contract_round: a new round from a goal (the drafter's prompt), a draft from the drafter's JSON, or an existing
980
+ // draft by its id. Returns what the micromanager does next.
981
+ async contractRound(project, parent, jobId, goal, input) {
982
+ const job = jobId ? this.#jobs.get(key(project, jobId)) ?? listJobs(project).find((j) => j.id === jobId) : this.job(project, parent);
983
+ if (!job)
984
+ return `There is no job ${jobId} in this project.`;
985
+ const text = input.trim();
986
+ if (!text) {
987
+ if (!goal.trim())
988
+ return "contract_round needs the goal (to start a round), or as input the drafter's contract JSON or a draft's id.";
989
+ return `Start a planner with the subagent tool (agent planner, description "contract draft"), with this prompt, and wait for its report. Then call contract_round with job "${job.id}" and its JSON as input (if it says a measuring script is missing, have a coder write that script first, with a check that it runs and prints MM_SCORE).
990
+
991
+ ${draftPrompt(goal.trim())}`;
992
+ }
993
+ let c;
994
+ if (/^c\d+$/i.test(text))
995
+ c = job.contracts?.find((x) => x.id === text.toUpperCase());
996
+ else {
997
+ const stored = await this.contract(project, parent, job.id, text);
998
+ const id = stored.match(/^Contract (C\d+) \(version/)?.[1];
999
+ if (!id)
1000
+ return stored;
1001
+ c = job.contracts?.find((x) => x.id === id);
1002
+ if (!c?.baseline)
1003
+ return stored;
1004
+ }
1005
+ if (!c)
1006
+ return `Job ${job.id} has no contract ${text}.`;
1007
+ if (c.status === "frozen")
1008
+ return `Contract ${c.id} is frozen already; writers are measured against it with a line "Contract: ${c.id}".`;
1009
+ if (!c.baseline)
1010
+ return `Contract ${c.id} has no baseline yet: its evaluator gave no valid result on today's code. Fix it with the contract tool first.`;
1011
+ c.round = { step: "prefs", loopholes: [] };
1012
+ saveJob(project, job);
1013
+ saveContract(project, job.id, c);
1014
+ return askWith(prefsForm(c), `Contract ${c.id} (version ${c.version}) is a draft, measured on today's code: ${describe({ ...c, baseline: undefined }, { valid: true, values: c.baseline.values })}. The user decides what it measures.`);
1015
+ }
1016
+ // The job a contract in its round belongs to, for the round's forms (they name only the contract).
1017
+ roundJob(project, parent, id) {
1018
+ const jobs = [...[...this.#jobs.entries()].filter(([k]) => k.startsWith(`${project}\0`)).map(([, j]) => j), ...listJobs(project)];
1019
+ const mine = jobs.filter((j) => j.facilitator === parent || j.facilitator === undefined);
1020
+ for (const job of [...mine, ...jobs]) {
1021
+ const contract = job.contracts?.find((c) => c.id === id && c.round && c.round.step !== "frozen");
1022
+ if (contract)
1023
+ return { job: this.#jobs.get(key(project, job.id)) ?? job, contract };
1024
+ }
1025
+ return undefined;
1026
+ }
1027
+ // The user's preferences: applied as a new version, then the red team, or straight to the baseline check.
1028
+ async roundPrefs(project, parent, id, prefs) {
1029
+ const found = this.roundJob(project, parent, id);
1030
+ if (!found || found.contract.round?.step !== "prefs")
1031
+ return `Contract ${id} waits for no preferences.`;
1032
+ const { job, contract: c } = found;
1033
+ if (prefs.said)
1034
+ return `"${prefs.said}" is no answer to the form for contract ${c.id}; ask with the same form again, or change the contract with the contract tool and start its round again.`;
1035
+ applyPrefs(c, prefs);
1036
+ c.version++;
1037
+ c.history.push({ version: c.version, change: `the user's preferences: ${c.scores[0].name} decides, guards ${c.guards.map((g) => g.name).join(", ") || "none"}${c.stop.target ? `, target ${JSON.stringify(c.stop.target)}` : ""}`, at: new Date().toISOString() });
1038
+ this.#jobs.set(key(project, job.id), job);
1039
+ if (prefs.redteam) {
1040
+ c.round.step = "redteam";
1041
+ saveJob(project, job);
1042
+ saveContract(project, job.id, c);
1043
+ return `Contract ${c.id} is version ${c.version} with the user's preferences. Now its red team: start a coder with the subagent tool (description "${c.id} red team", on another model family than the drafter if you can), with this prompt, filling in the files a worker on this goal would change:
1044
+ Red team: ${c.id} · ${job.id}
1045
+ Files: <those files>
1046
+ Its change is measured and never merged; its LOOPHOLE lines come to you when it ends.`;
1047
+ }
1048
+ return this.#roundBaseline(project, job, c);
1049
+ }
1050
+ // "Red team: C1 · job-…": a writer that tries to game the draft contract, in its own worktree; never merged.
1051
+ async #redteam(project, parent, role, d, ref, model) {
1052
+ const job = this.#jobs.get(key(project, ref.job)) ?? listJobs(project).find((j) => j.id === ref.job);
1053
+ if (!job)
1054
+ throw new DelegationError(`Not started: there is no job ${ref.job} in this project.`);
1055
+ const c = job.contracts?.find((x) => x.id === ref.contract);
1056
+ if (!c || c.round?.step !== "redteam")
1057
+ throw new DelegationError(`Not started: contract ${ref.contract} of job ${job.id} is not waiting for its red team.`);
1058
+ if (!WRITERS.has(role.id))
1059
+ throw new DelegationError("Not started: a red team changes files; start it with agent coder.");
1060
+ const parsed = parseFiles(d.files, project);
1061
+ if (parsed.problem || !parsed.files.length)
1062
+ throw new DelegationError(`Not started: ${parsed.problem ?? "a red team needs a line \"Files: <the files a worker on this goal would change>\""}.`);
1063
+ const checks = d.checks.length ? d.checks : ["true"];
1064
+ const why = checkSetProblems(checks, true);
1065
+ if (why)
1066
+ throw new DelegationError(`Not started: ${why}`);
1067
+ this.#jobs.set(key(project, job.id), job);
1068
+ const rel = await this.#integrate(project, job, true);
1069
+ const added = addDelegated(job, { title: `${c.id} red team`, prompt: redteamPrompt(c), files: parsed.files, dependsOn: [], checks });
1070
+ if (!added.task)
1071
+ throw new DelegationError(`Not started: ${added.errors.join("; ")}`);
1072
+ const task = added.task;
1073
+ task.role = role.id;
1074
+ task.model = model;
1075
+ task.redteam = c.id;
1076
+ task.contract = { id: c.id, version: c.version };
1077
+ c.round.redteam = task.id;
1078
+ for (const s of ["ready", "planned", "running"])
1079
+ moveTask(task, s);
1080
+ stage(task, "delegate", "pass", `${role.agent} on ${model}, red team of ${c.id}`);
1081
+ return this.#start(project, parent, job, task, role, model, { ...d, body: [redteamPrompt(c), d.body].filter(Boolean).join("\n\n") }, checks, rel);
1082
+ }
1083
+ // The red team's report as it ended: its loopholes go to the round, and the user picks the ones to close; without
1084
+ // any, the round goes on to the baseline. A red team whose change raised the score is a loophole in itself.
1085
+ async noteLoopholes(session, report) {
1086
+ const entry = this.#entry(session);
1087
+ const job = entry && this.#job(entry);
1088
+ const task = job?.tasks.find((t) => t.id === entry.taskId);
1089
+ const c = task?.redteam ? job.contracts?.find((x) => x.id === task.redteam) : undefined;
1090
+ if (!entry || !job || !task || !c || c.round?.step !== "redteam")
1091
+ return undefined;
1092
+ const found = parseLoopholes(report);
1093
+ const raised = task.score?.valid && c.baseline && better(c, task.score, { valid: true, values: c.baseline.values }) > 0;
1094
+ if (raised && !found.length)
1095
+ found.push({ what: `the red team raised the score (${describe(c, task.score)}) without improving the goal; see its report in session ${session}` });
1096
+ c.round.loopholes = found;
1097
+ if (!found.length) {
1098
+ c.history.push({ version: c.version, change: "the red team found no loophole", at: new Date().toISOString() });
1099
+ return `[micromanager] The red team of contract ${c.id} found no loophole. ${await this.#roundBaseline(entry.project, job, c)}`;
1100
+ }
1101
+ c.round.step = "loopholes";
1102
+ saveJob(entry.project, job);
1103
+ saveContract(entry.project, job.id, c);
1104
+ return `[micromanager] ${askWith(loopholeForm(c), `The red team of contract ${c.id} found ${found.length} way${found.length > 1 ? "s" : ""} to raise the score without improving the goal.`)}`;
1105
+ }
1106
+ // The loopholes the user chose to close: a guard each where the red team named one; then the baseline check.
1107
+ async roundLoopholes(project, parent, id, picked) {
1108
+ const found = this.roundJob(project, parent, id);
1109
+ if (!found || found.contract.round?.step !== "loopholes")
1110
+ return `Contract ${id} waits for no answer about loopholes.`;
1111
+ const { job, contract: c } = found;
1112
+ const chosen = picked.map((i) => c.round.loopholes[i]).filter((l) => Boolean(l));
1113
+ // A guard the red team named on a value the evaluator does not print would never be checked: noted instead, like a
1114
+ // loophole without a guard.
1115
+ const measurable = (l) => Boolean(l.guard && c.baseline && l.guard.name in c.baseline.values);
1116
+ for (const l of chosen)
1117
+ if (l.guard && !measurable(l))
1118
+ Object.assign(l, { guard: undefined });
1119
+ const guards = chosen.flatMap((l) => (l.guard && !c.guards.some((g) => g.name === l.guard.name) ? [l.guard] : []));
1120
+ c.guards = [...c.guards, ...guards];
1121
+ if (chosen.length) {
1122
+ c.version++;
1123
+ const unguarded = chosen.filter((l) => !l.guard);
1124
+ c.history.push({ version: c.version, change: `closed ${chosen.length} loophole(s) of the red team${guards.length ? `, guards ${guards.map((g) => g.name).join(", ")}` : ""}${unguarded.length ? `; without a guard: ${unguarded.map((l) => l.what.slice(0, 80)).join("; ")}` : ""}`, at: new Date().toISOString() });
1125
+ }
1126
+ const open = chosen.filter((l) => !l.guard);
1127
+ const note = open.length ? ` ${open.length} of them name no value the evaluator prints: change the evaluator or the corpus to catch ${open.length > 1 ? "them" : "it"} (the contract tool with "id": "${c.id}"), or go on.` : "";
1128
+ return `${guards.length ? `Contract ${c.id} has ${guards.length} new guard(s).` : "No guard was added."}${note} ${await this.#roundBaseline(project, job, c)}`;
1129
+ }
1130
+ // The baseline the user checks before the freeze: three runs on each corpus, shown with their spread.
1131
+ async #roundBaseline(project, job, c) {
1132
+ c.round = { ...(c.round ?? { loopholes: [] }), step: "baseline" };
1133
+ const rel = await this.#integrate(project, job, false);
1134
+ const dir = taskDir(job.integrationWorktree ?? project, rel);
1135
+ const gate = await this.#gate(job, { project, writer: true, role: "code", worktree: job.integrationWorktree ?? project, dir });
1136
+ const once = { ...c, repeats: 1 };
1137
+ const visible = [];
1138
+ const heldOut = [];
1139
+ let seconds = 0;
1140
+ for (let i = 0; i < Math.max(3, c.repeats); i++) {
1141
+ const r = await runEvaluator(dir, once, "visible", this.#exec, undefined, gate);
1142
+ visible.push(r.measured);
1143
+ seconds += r.seconds;
1144
+ if (c.corpus.heldOut) {
1145
+ const h = await runEvaluator(dir, once, "heldout", this.#exec, heldOutDir(project, job.id, c.id), gate);
1146
+ heldOut.push(h.measured);
1147
+ seconds += h.seconds;
1148
+ }
1149
+ }
1150
+ this.#count(job, c, seconds);
1151
+ const med = median(visible);
1152
+ if (med.valid)
1153
+ c.baseline = { ...c.baseline, values: { ...med.values }, at: new Date().toISOString() };
1154
+ const medHeld = heldOut.length ? median(heldOut) : undefined;
1155
+ if (medHeld?.valid)
1156
+ c.baseline = { ...c.baseline, heldOut: { ...medHeld.values } };
1157
+ this.#jobs.set(key(project, job.id), job);
1158
+ saveJob(project, job);
1159
+ saveContract(project, job.id, c);
1160
+ return askWith(baselineForm(c, { visible, heldOut }, Math.round(seconds * 10) / 10), `Contract ${c.id} (version ${c.version}) is measured on today's code again; the user checks it before it is frozen.`);
1161
+ }
1162
+ // The user's answer to the baseline: freeze, measure again, or back to a draft.
1163
+ async roundBaseline(project, parent, id, decision, said) {
1164
+ const found = this.roundJob(project, parent, id);
1165
+ if (!found || found.contract.round?.step !== "baseline")
1166
+ return `Contract ${id} waits for no baseline answer.`;
1167
+ const { job, contract: c } = found;
1168
+ if (decision === "again")
1169
+ return this.#roundBaseline(project, job, c);
1170
+ if (decision === "plausible") {
1171
+ await this.#freezeContract(project, job, c);
1172
+ return `Contract ${c.id} is frozen (version ${c.version}): its evaluator and visible corpus may not change any more, and writers are measured against it with a line "Contract: ${c.id}" (or "contract" in a todo).`;
1173
+ }
1174
+ c.round = undefined;
1175
+ saveJob(project, job);
1176
+ return `The user wants contract ${c.id} changed${said ? `: "${said}"` : decision === "change" ? "" : " (their answer was no choice of the form)"}. Ask what is wrong if it is not clear, send the changed contract with the contract tool ("id": "${c.id}"), then start its round again with contract_round (input "${c.id}").`;
1177
+ }
1178
+ // A contract frozen: the files its evaluator names and its visible corpus, hashed on the job's branch.
1179
+ async #freezeContract(project, job, c) {
1180
+ const rel = await this.#integrate(project, job, false);
1181
+ const worktree = job.integrationWorktree ?? project;
1182
+ const dir = taskDir(worktree, rel);
1183
+ const corpus = [];
1184
+ for (const p of c.corpus.visible) {
1185
+ const listed = await this.#exec("git", ["ls-files", "--", p], { cwd: dir });
1186
+ corpus.push(...listed.stdout.split("\n").map((l) => l.trim()).filter(Boolean));
1187
+ }
1188
+ const files = [...new Set([...namedFiles(c.evaluator, dir), ...corpus])].sort();
1189
+ c.frozen = { files: Object.fromEntries(await hashFiles(worktree, files, this.#exec, dir)), at: new Date().toISOString() };
1190
+ c.status = "frozen";
1191
+ c.round = { ...(c.round ?? { loopholes: [] }), step: "frozen" };
1192
+ c.history.push({ version: c.version, change: "frozen after the user checked the baseline", at: c.frozen.at });
1193
+ this.#jobs.set(key(project, job.id), job);
1194
+ saveJob(project, job);
1195
+ saveContract(project, job.id, c);
1196
+ }
1197
+ // For a contract the user settled outside the round (and the tests): frozen as it is.
1198
+ async freezeContract(project, jobId, id) {
1199
+ const job = this.#jobs.get(key(project, jobId)) ?? listJobs(project).find((j) => j.id === jobId);
1200
+ const c = job?.contracts?.find((x) => x.id === id);
1201
+ if (job && c)
1202
+ await this.#freezeContract(project, job, c);
1203
+ }
1204
+ // What a contract's evaluations cost: on the contract (its stop rule) and on the job (its counters).
1205
+ #count(job, c, seconds) {
1206
+ c.used = { evaluations: (c.used?.evaluations ?? 0) + 1, seconds: Math.round(((c.used?.seconds ?? 0) + seconds) * 10) / 10 };
1207
+ job.counters.evals = (job.counters.evals ?? 0) + 1;
1208
+ job.counters.evalSeconds = Math.round(((job.counters.evalSeconds ?? 0) + seconds) * 10) / 10;
1209
+ }
1210
+ // A writer's work measured against its contract, after its checks passed. Returns a failure the gate treats like a
1211
+ // failing check (an invalid result or a broken guard), with exhausted when the contract's stop rule allows no
1212
+ // further evaluation; or the evidence for a passing fitness stage.
1213
+ async #measure(entry, job, task) {
1214
+ const c = job.contracts?.find((x) => x.id === entry.contract);
1215
+ if (!c)
1216
+ return {};
1217
+ const used = c.used ?? { evaluations: 0, seconds: 0 };
1218
+ const spent = (c.stop.evaluations && used.evaluations >= c.stop.evaluations && `${c.stop.evaluations} evaluations`) || (c.stop.seconds && used.seconds >= c.stop.seconds && `${c.stop.seconds}s of evaluation`);
1219
+ if (spent)
1220
+ return { failed: { command: `evaluator of ${c.id}`, passed: false, code: -1, output: `not run: contract ${c.id} allows ${spent}, and they are used up` }, exhausted: true };
1221
+ const { measured, seconds } = await runEvaluator(entry.dir, c, "visible", this.#exec, undefined, await this.#entryGate(entry, job, task.role));
1222
+ this.#count(job, c, seconds);
1223
+ const broken = measured.valid ? guardViolations(c, measured) : [];
1224
+ if (!measured.valid || broken.length) {
1225
+ const why = measured.valid ? `guard broken: ${broken.join("; ")}` : measured.error ?? "invalid";
1226
+ return { failed: { command: `evaluator of ${c.id}: ${c.evaluator}`, passed: false, code: measured.valid ? 0 : 1, output: Object.keys(measured.values).length ? `${why}\nMeasured: ${describe(c, { ...measured, valid: true })}` : why } };
1227
+ }
1228
+ task.score = { ...measured, corpus: "visible", at: new Date().toISOString() };
1229
+ return { evidence: describe(c, measured) };
1230
+ }
1231
+ // The difficulty on the task, and a trial when the plugin asked for one and the job can run one: in worktrees of its
1232
+ // own (no trial without git), with Parallel on, and with an objective automated evaluator (Pattern 3).
1233
+ #assess(project, job, task, assess, pick, checks, d) {
1234
+ if (assess?.difficulty !== undefined)
1235
+ task.difficulty = assess.difficulty;
1236
+ if (assess?.tier)
1237
+ task.tier = assess.tier;
1238
+ let trials = assess?.trials ?? 1;
1239
+ if (trials >= 2 && (task.postGreen || !hasObjectiveEvaluator(job, task, d, checks ? { checks } : undefined)))
1240
+ trials = 1;
1241
+ if (trials < 2 || !WRITERS.has(task.role) || job.isolation === "none" || job.isolation === "plan")
1242
+ return;
1243
+ if (!optionsOf(loadControl(project, job.id), lastOptions(project)).parallel)
1244
+ return;
1245
+ task.trial = { of: task.id, n: trials, pick: pickFor(task.role, this.#trialPick, pick) };
1246
+ task.title = `${task.title.replace(/ \(attempt \d+\/\d+\)$/, "")} (attempt 1/${trials})`.slice(0, 140);
1247
+ }
1248
+ // "Attempt: T5 · job-…": another attempt of T5's trial. It gets T5's task, files and checks, a worktree of its own,
1249
+ // and is not refused as the same work: that is what it is meant to be.
1250
+ async #attempt(project, parent, role, d, attempt, model) {
1251
+ const job = this.#jobs.get(key(project, attempt.job)) ?? listJobs(project).find((j) => j.id === attempt.job);
1252
+ if (!job)
1253
+ throw new DelegationError(`Not started: there is no job ${attempt.job} in this project.`);
1254
+ if (job.facilitator && job.facilitator !== parent)
1255
+ throw new DelegationError(`Not started: job ${job.id} belongs to another micromanager session.`);
1256
+ if (loadControl(project, job.id).stopped)
1257
+ throw new DelegationError(`Not started: the user stopped job ${job.id}. Ask them whether to go on; nothing starts until they start it again.`);
1258
+ if (this.#refusePlanWriter(project, job, role))
1259
+ throw this.#readerOnlyError(project, job);
1260
+ const head = job.tasks.find((t) => t.id === attempt.task);
1261
+ if (!head?.trial || head.trial.of !== head.id)
1262
+ throw new DelegationError(`Not started: ${attempt.task} runs no trial; start a task with its own prompt instead.`);
1263
+ if (head.role !== role.id)
1264
+ throw new DelegationError(`Not started: ${head.id} is a task for ${roleById(head.role)?.agent ?? head.role}; start its attempts with that agent.`);
1265
+ const now = standing(job, head);
1266
+ if (now.winner)
1267
+ throw new DelegationError(`Not started: ${now.winner.id} already won the trial of ${head.id}; its work is merged.`);
1268
+ if (now.all.length >= head.trial.n)
1269
+ throw new DelegationError(`Not started: the trial of ${head.id} has all its ${head.trial.n} attempts already (${now.all.map((t) => t.id).join(", ")}).`);
1270
+ const checks = this.#entries.get(`${job.id}/${head.id}`)?.checks ?? [];
1271
+ const title = `${head.title.replace(/ \(attempt \d+\/\d+\)$/, "")} (attempt ${now.all.length + 1}/${head.trial.n})`;
1272
+ const added = addDelegated(job, { title, prompt: head.description, files: head.files, dependsOn: [], checks });
1273
+ if (!added.task)
1274
+ throw new DelegationError(`Not started: ${added.errors.join("; ")}`);
1275
+ const task = added.task;
1276
+ task.role = role.id;
1277
+ task.model = model;
1278
+ task.trial = { ...head.trial };
1279
+ if (head.difficulty !== undefined)
1280
+ task.difficulty = head.difficulty;
1281
+ if (head.tier)
1282
+ task.tier = head.tier;
1283
+ if (head.repo)
1284
+ task.repo = head.repo;
1285
+ if (head.contract)
1286
+ task.contract = { ...head.contract };
1287
+ if (head.freeze)
1288
+ task.freeze = [...head.freeze];
1289
+ if (head.preview)
1290
+ task.preview = head.preview;
1291
+ this.#jobs.set(key(project, job.id), job);
1292
+ for (const s of ["ready", "planned", "running"])
1293
+ moveTask(task, s);
1294
+ stage(task, "delegate", "pass", `${role.agent} on ${model}, attempt of ${head.id}`);
1295
+ const rel = await this.#integrate(project, job, true, task.repo);
1296
+ const body = job.rolling ? head.description : this.#plannedBody(job, head, d.body);
1297
+ return this.#start(project, parent, job, task, role, model, { ...d, body }, checks, rel);
1298
+ }
1299
+ // The fan-out note for a trial's first attempt, once its subagent call went through; undefined for any other task.
1300
+ trialNote(project, jobId, taskId) {
1301
+ const job = this.#jobs.get(key(project, jobId));
1302
+ const task = job?.tasks.find((t) => t.id === taskId);
1303
+ return job && task ? fanOutText(job, task) : undefined;
1304
+ }
1305
+ // The models a trial's attempts run on so far, so the next attempt goes to another family.
1306
+ trialModels(project, jobId, taskId) {
1307
+ const job = this.#jobs.get(key(project, jobId)) ?? listJobs(project).find((j) => j.id === jobId);
1308
+ const task = job?.tasks.find((t) => t.id === taskId);
1309
+ return job && task ? attempts(job, task).map((t) => t.model).filter((m) => Boolean(m)) : [];
1310
+ }
1311
+ // The task's repo key: "" is the job's own repository (codeRoot, else the project). A planner naming the job's
1312
+ // repository for a task means the same worktree, not a second integration branch in the same repo.
1313
+ #repoKey(project, job, task) {
1314
+ if (!task.repo)
1315
+ return "";
1316
+ return resolve(project, task.repo) === resolve(job.codeRoot ?? project) ? "" : task.repo;
1317
+ }
1318
+ // The job's branch and its worktree, made at its first task. Returns the project's offset inside the repository.
1319
+ async #integrate(project, job, writer = true, repo = "") {
1320
+ if (repo && resolve(project, repo) === resolve(job.codeRoot ?? project))
1321
+ repo = "";
1322
+ if (repo) {
1323
+ // A task in another repository of the workspace: its own integration branch and worktree there (roadmap 1.2).
1324
+ if (job.isolation === "plan" || job.isolation === "none")
1325
+ return "";
1326
+ const root = resolve(project, repo);
1327
+ const known = job.integrationRepos?.[repo];
1328
+ if (known) {
1329
+ const v = await validateIntegration({ ...job, integrationBranch: known.branch, integrationWorktree: known.worktree, integrationRel: known.rel }, this.#exec, root);
1330
+ if (!v.ok)
1331
+ throw new IntegrationError(`integration worktree of ${repo} invalid: ${v.message}`);
1332
+ return known.rel;
1333
+ }
1334
+ if ((await gitState(root, this.#exec)) !== "repo") {
1335
+ if (!writer)
1336
+ return "";
1337
+ throw new NoGitError(`Not started: ${repo} is no git repository with a commit, so workers cannot get a worktree each.`);
1338
+ }
1339
+ excludeFromGit(root);
1340
+ const integration = await prepareIntegration(root, job.id, this.#exec);
1341
+ job.integrationRepos = {
1342
+ ...(job.integrationRepos ?? {}),
1343
+ [repo]: { branch: integration.branch, worktree: integration.worktree, rel: integration.rel, ...(integration.base ? { base: integration.base } : {}) },
1344
+ };
1345
+ return integration.rel;
1346
+ }
1347
+ const root = job.codeRoot ?? project;
1348
+ if (job.isolation === "plan") {
1349
+ // A plan job works only in its plan worktrees: it gets no integration branch and no integration worktree, ever.
1350
+ job.integrationBranch = undefined;
1351
+ job.integrationWorktree = undefined;
1352
+ return "";
1353
+ }
1354
+ if (job.isolation === "none") {
1355
+ job.integrationWorktree = project;
1356
+ job.integrationRel = "";
1357
+ return "";
1358
+ }
1359
+ if (job.integrationWorktree) {
1360
+ const v = await validateIntegration(job, this.#exec, root);
1361
+ if (!v.ok)
1362
+ throw new IntegrationError(`integration worktree invalid: ${v.message}`);
1363
+ }
1364
+ if (!job.integrationWorktree) {
1365
+ if ((await gitState(root, this.#exec)) !== "repo") {
1366
+ if (!writer)
1367
+ return ""; // a reader changes nothing: it reads the project folder itself, no question needed
1368
+ const note = this.#noGit ? await this.#noGit(root) : `${root} is no git repository with a commit, so workers cannot get a worktree each. Ask the user whether to create one or to work without isolation, and never print a git command for them to run: the plugin performs the choice.`;
1369
+ throw new NoGitError(`Not started: ${note}`);
1370
+ }
1371
+ excludeFromGit(root);
1372
+ const integration = await prepareIntegration(root, job.id, this.#exec);
1373
+ job.integrationBranch = integration.branch;
1374
+ job.integrationWorktree = integration.worktree;
1375
+ // The offset and the uncommitted state are kept on the job: a worker session outlives this process, and a
1376
+ // project below the repository root (or a task that needs an uncommitted file) must not depend on this call.
1377
+ job.integrationRel = integration.rel;
1378
+ job.integrationBase = integration.base;
1379
+ job.integrationDirty = integration.dirty ? integration.dirtySummary : "";
1380
+ }
1381
+ // A job file written before the offset was tracked has none: git is asked once, so a job that predates this does
1382
+ // not keep sending its workers to the worktree root.
1383
+ return job.integrationRel ?? (job.integrationWorktree ? await repoRel(root, this.#exec) : "");
1384
+ }
1385
+ // A running task's entry, its worktree (writer) and the worker's brief.
1386
+ async #start(project, parent, job, task, role, model, d, checks, rel) {
1387
+ const writer = WRITERS.has(role.id);
1388
+ const repo = this.#repoKey(project, job, task);
1389
+ const integ = repo ? job.integrationRepos?.[repo] : undefined;
1390
+ const repoRoot = repo ? resolve(project, repo) : job.codeRoot ?? project;
1391
+ const base = integ?.worktree ?? job.integrationWorktree ?? project; // a reader in a folder without git reads the folder itself
1392
+ const entry = { project, jobId: job.id, taskId: task.id, parent, writer, ...(repo ? { repo } : {}), dir: taskDir(base, integ?.rel ?? rel), worktree: base, rel: integ?.rel ?? rel, checks, ...(task.contract ? { contract: task.contract.id } : {}) };
1393
+ if (writer && job.isolation === "plan") {
1394
+ // Plan mode: a writer drafts in a plan worktree of its own under the state directory, off HEAD, never in the
1395
+ // project. A project without a repository (or without a commit to start from) gets a copy instead, and no branch.
1396
+ const areaRoot = repoRoot;
1397
+ const at = join(planArea(areaRoot, job.id), "worktrees", task.id);
1398
+ // git materialises a worktree of the repository ROOT, so a project below it lives at <worktree>/<rel> and the
1399
+ // worker must be put there; a copy of the project is the project, and its offset is empty.
1400
+ let planRel = "";
1401
+ let w;
1402
+ if ((await gitState(areaRoot, this.#exec)) === "repo") {
1403
+ const prepared = await preparePlanWorktree(areaRoot, job.id, task.id, this.#exec);
1404
+ planRel = await repoRel(areaRoot, this.#exec);
1405
+ // The base travels with the task: the record's patch is `git diff base..HEAD`, and this is the process that
1406
+ // knows it (a restart adopts the task from its file).
1407
+ task.planBase = prepared.base;
1408
+ w = { branch: prepared.branch, worktree: prepared.worktree, dir: taskDir(prepared.worktree, planRel) };
1409
+ }
1410
+ else {
1411
+ copyForPlan(repoRoot, at);
1412
+ w = { worktree: at, dir: at };
1413
+ }
1414
+ entry.dir = w.dir;
1415
+ entry.worktree = w.worktree;
1416
+ entry.rel = planRel;
1417
+ if (w.branch)
1418
+ entry.branch = w.branch;
1419
+ task.worktree = w.worktree;
1420
+ task.worktreeRel = planRel;
1421
+ if (w.branch)
1422
+ task.branch = w.branch;
1423
+ }
1424
+ else if (writer && job.isolation === "none") {
1425
+ // No git: the project itself, and no branch; the worktree is the project, so adopt and resume keep it.
1426
+ task.worktree = repoRoot;
1427
+ task.worktreeRel = "";
1428
+ }
1429
+ else if (writer) {
1430
+ const w = await prepareTaskWorktree(repoRoot, job.id, task.id, integ?.branch ?? job.integrationBranch, this.#exec, undefined, rel);
1431
+ entry.dir = w.dir;
1432
+ entry.worktree = w.worktree;
1433
+ entry.branch = w.branch;
1434
+ task.worktree = w.worktree;
1435
+ task.worktreeRel = w.rel;
1436
+ task.branch = w.branch;
1437
+ }
1438
+ if (writer)
1439
+ await this.#freeze(job, task, entry);
1440
+ const graph = role.id === "explore" ? await this.#graphs.get(entry.dir) : undefined;
1441
+ entry.graph = Boolean(graph);
1442
+ this.#entries.set(`${job.id}/${task.id}`, entry);
1443
+ task.checks = [...checks];
1444
+ saveJob(project, job);
1445
+ // A project below the repository root and an uncommitted working tree are both invisible from the inside: the
1446
+ // worktree holds the whole repository, and no worker can see what the user has not committed.
1447
+ const notes = [
1448
+ repo ? `job ${job.id}: ${task.id} works in ${repo}, with its own integration branch ${integ?.branch ?? job.integrationBranch}` : "",
1449
+ !repo && rel !== "" ? `job ${job.id}: the project is ${rel} inside the repository, so its worktrees hold the repository root; the task works in the project directory ${entry.dir}` : "",
1450
+ !repo && job.integrationDirty ? `job ${job.id}: starts from commit ${job.integrationBase?.slice(0, 7) ?? "HEAD"} on ${job.integrationBranch}, and the working tree has uncommitted paths no worker will see (${job.integrationDirty})` : "",
1451
+ ].filter(Boolean);
1452
+ return { task, job, prompt: this.#brief(job, task, role, model, d, entry, graph), notes };
1453
+ }
1454
+ // run_job: a planned job runs on the micromanager's own workers from now on. The job's phase goes to execute and the
1455
+ // session becomes its facilitator; nextStep (src/continuation.ts) then names the tasks to start. Started from the plan
1456
+ // agent (plan = true), the job is a plan job even when it was planned as a normal one, and it then checks the
1457
+ // sandbox: with none it goes on reader-only, with the warning that says why (A1-T11).
1458
+ runPlanned(project, jobId, parent, plan = false) {
1459
+ const job = this.#jobs.get(key(project, jobId)) ?? listJobs(project).find((j) => j.id === jobId);
1460
+ if (!job)
1461
+ return { problem: `there is no job ${jobId} in this project` };
1462
+ if (plan)
1463
+ job.isolation = "plan";
1464
+ if (job.rolling)
1465
+ return { problem: `${jobId} holds the tasks you delegated yourself; it has no plan to run` };
1466
+ if (!job.tasks.length)
1467
+ return { problem: `${jobId} has no tasks yet; plan it with plan_job first` };
1468
+ if (job.phase === "plan_gate")
1469
+ moveJob(job, "execute");
1470
+ else if ((job.phase === "paused" || job.phase === "ask_user") && job.resumePhase === "execute")
1471
+ moveJob(job, "execute");
1472
+ if (job.phase !== "execute")
1473
+ return { problem: `job ${jobId} is in phase ${job.phase}, not ready to run` };
1474
+ job.native = true;
1475
+ if (job.facilitator !== parent) {
1476
+ job.facilitator = parent;
1477
+ for (const entry of this.#entries.values())
1478
+ if (entry.jobId === job.id && entry.project === project)
1479
+ entry.parent = parent;
1480
+ }
1481
+ this.#jobs.set(key(project, job.id), job);
1482
+ saveJob(project, job);
1483
+ // The job starts, and its first investigator would be refused: say it now, so the micromanager can tell the user
1484
+ // before it names a task that cannot start. A job the user confirmed may run unwrapped (D23) is not reader-only.
1485
+ const off = loadControl(project, job.id).sandboxOff === true;
1486
+ if (job.isolation === "plan" && !off && this.#sandboxAvailable?.() === false && this.#unsandboxedAllowed?.(project, job.id) !== true) {
1487
+ this.readerOnly(project, job, off ? "the sandbox is switched off for this job" : "no sandbox on this machine");
1488
+ // Its plan.md says so too (A1-T7/T8): from the start, before any task runs, not only once someone asks.
1489
+ this.#ensurePlanDoc(project, job);
1490
+ return { job, warning: this.#readerOnlyWarning(project, job) };
1491
+ }
1492
+ // A plan job always leaves the document Build mode reads, even before its first task hands anything back.
1493
+ if (job.isolation === "plan")
1494
+ this.#ensurePlanDoc(project, job);
1495
+ return { job };
1496
+ }
1497
+ // "Task: T5 · job-…": the micromanager starts a task of a planned job (run_job). The plan already says what it is:
1498
+ // its role, files, acceptance points and checks; the prompt can add to it. A task that ran before (on the runner, or
1499
+ // a worker that stopped) starts over in a fresh worktree; continuing its old worker is the way to keep its change.
1500
+ async #planned(project, parent, role, d, planned, model, assess) {
1501
+ const job = this.#jobs.get(key(project, planned.job)) ?? listJobs(project).find((j) => j.id === planned.job);
1502
+ if (!job)
1503
+ throw new DelegationError(`Not started: there is no job ${planned.job} in this project.`);
1504
+ if (!job.native && !job.rolling)
1505
+ throw new DelegationError(`Not started: job ${job.id} is not running on your workers; start it with run_job first.`);
1506
+ if (job.facilitator && job.facilitator !== parent)
1507
+ throw new DelegationError(`Not started: job ${job.id} belongs to another micromanager session; run_job ${job.id} here takes it over.`);
1508
+ if (job.phase !== "execute")
1509
+ throw new DelegationError(`Not started: job ${job.id} is ${job.phase}; run_job resumes it.`);
1510
+ const control = loadControl(project, job.id);
1511
+ if (control.stopped)
1512
+ throw new DelegationError(`Not started: the user stopped job ${job.id}. Ask them whether to go on; nothing starts until they start it again.`);
1513
+ if (this.#refusePlanWriter(project, job, role))
1514
+ throw this.#readerOnlyError(project, job);
1515
+ const unstarted = this.#planFirst && job.rolling && WRITERS.has(role.id) ? this.startNote(project, job) : undefined;
1516
+ if (unstarted)
1517
+ throw new DelegationError(`Not started: ${unstarted}`);
1518
+ const task = job.tasks.find((t) => t.id === planned.task);
1519
+ if (!task)
1520
+ throw new DelegationError(`Not started: job ${job.id} has no task ${planned.task}.`);
1521
+ const agent = roleById(task.role)?.agent ?? task.role;
1522
+ if (task.role !== role.id)
1523
+ throw new DelegationError(`Not started: ${task.id} is a task for ${agent}; start it with agent ${agent}.`);
1524
+ const k = `${job.id}/${task.id}`;
1525
+ const old = this.#entries.get(k);
1526
+ if (LIVE.has(task.status) && old && !old.ended)
1527
+ throw new DelegationError(`Not started: ${task.id} runs already${old.session ? ` (session ${old.session})` : ""}; its report comes to you when it ends.`);
1528
+ if (task.status === "merged" || task.status === "passed")
1529
+ throw new DelegationError(`Not started: ${task.id} is done already (${task.status}).`);
1530
+ if (WRITERS.has(role.id) && (job.isolation === "none" || !optionsOf(control, lastOptions(project)).parallel)) {
1531
+ const busy = [...this.#entries.values()].find((e) => e.jobId === job.id && e.project === project && e.writer && !e.ended && e.taskId !== task.id);
1532
+ if (busy)
1533
+ throw new DelegationError(`Not started: ${job.isolation === "none" ? `job ${job.id} works without git, so one writer at a time` : `Parallel is off for job ${job.id}`}, and ${busy.taskId} still runs; start ${task.id} after its report.`);
1534
+ }
1535
+ const byId = new Map(job.tasks.map((t) => [t.id, t]));
1536
+ const elsewhere = (id) => { const [owner, taskId] = this.#owner(project, job, id); return owner?.tasks.find((t) => t.id === taskId)?.status; };
1537
+ const waits = task.dependsOn.filter((id) => { const dep = byId.get(id); return !dep || !settled(job, dep, elsewhere); });
1538
+ if (waits.length)
1539
+ throw new DelegationError(`Not started: ${task.id} waits for ${waits.join(", ")}; start it when ${waits.length > 1 ? "they are" : "it is"} merged.`);
1540
+ const postGreenChecks = task.postGreen && !d.checks.length
1541
+ ? [...new Set(task.dependsOn.flatMap((id) => {
1542
+ const e = this.#entries.get(`${job.id}/${id}`);
1543
+ if (e?.checks.length)
1544
+ return e.checks;
1545
+ const dep = byId.get(id);
1546
+ return (dep?.checks ?? []).filter((cmd) => cmd !== "frozen files unchanged");
1547
+ }))]
1548
+ : [];
1549
+ const derived = d.checks.length
1550
+ ? d.checks
1551
+ : [...new Set([
1552
+ ...taskAcceptance(job, task).map((a) => a.verify).filter((v) => Boolean(v)),
1553
+ ...postGreenChecks,
1554
+ ])];
1555
+ const contract = d.contract ?? task.contract?.id;
1556
+ if (d.method === "trial" && !derived.length && !contract?.trim()) {
1557
+ throw new DelegationError(`Not started: ${TRIAL_EVALUATOR_REQUIRED}`);
1558
+ }
1559
+ const writerTask = WRITERS.has(role.id);
1560
+ const taskRepo = task.repo ?? "";
1561
+ const taskRoot = taskRepo ? resolve(project, taskRepo) : project;
1562
+ // A verify command can come from an earlier run whose worktree no longer exists; only a provably stale task-worktree
1563
+ // prefix is removed (and only for a root project). Everything else must stay inside this task's worktree.
1564
+ const checks = derived.map((c) => stripTaskWorktreeCwd(c, taskRepo ? "" : job.integrationRel ?? ""));
1565
+ const problem = writerTask && !contract?.trim() ? checkSetProblems(checks, true) : checks.length ? checkSetProblems(checks, false) : undefined;
1566
+ if (problem)
1567
+ throw new DelegationError(`Not started: ${problem}`);
1568
+ const cwdProblem = checks.map((c) => checkCwdProblem(c, taskRoot, taskRoot, taskRoot)).find(Boolean);
1569
+ if (cwdProblem)
1570
+ throw new DelegationError(`Not started: ${cwdProblem}`);
1571
+ const c = this.#contractFor(job, WRITERS.has(role.id), contract, assess);
1572
+ this.#offerEvolver(project, job, c, task.files, task.title, checks, d, assess);
1573
+ if (d.method === "trial")
1574
+ assess = { ...(assess ?? {}), trials: Math.max(2, assess?.trials ?? 1) };
1575
+ this.#jobs.set(key(project, job.id), job);
1576
+ // Before any worktree is dropped: a refusal must leave everything as it was. The task itself is exempt (a restart
1577
+ // reuses its id), and a replanned task replaces the cancelled tasks on purpose.
1578
+ const cannotReplace = this.#replaceable(project, job, task.replaces ?? []);
1579
+ if (cannotReplace.length)
1580
+ throw new DelegationError(`Not started: ${cannotReplace.join("; ")}`);
1581
+ const duplicate = task.postGreen ? undefined : this.#duplicate(job, role, task.title, task.description, task.files, task.replaces ?? [], { selfId: task.id, replan: task.origin === "replan" });
1582
+ if (duplicate)
1583
+ throw new DelegationError(duplicate);
1584
+ if (old) {
1585
+ await this.#dropWorktree(old, task);
1586
+ this.#entries.delete(k);
1587
+ }
1588
+ else if (task.worktree && task.branch) {
1589
+ await removeTaskWorktree(taskRoot, { worktree: task.worktree, branch: task.branch }, this.#exec).catch(() => undefined);
1590
+ task.worktree = undefined;
1591
+ task.branch = undefined;
1592
+ }
1593
+ // A todo that does other tasks over: their worktrees go now, as for a delegation's "Replaces:" line.
1594
+ await this.#replace(project, job, task.replaces ?? []);
1595
+ restart(task);
1596
+ task.model = model;
1597
+ task.attempts = 0;
1598
+ // A task started again starts a new trial, if it gets one: the old attempts' trial is over.
1599
+ task.trial = undefined;
1600
+ this.#bind(job, task, contract);
1601
+ if (d.frozen)
1602
+ task.freeze = [...new Set([...(task.freeze ?? []), ...parseFiles(d.frozen, project).files])];
1603
+ this.#assess(project, job, task, assess, d.pick, checks, d);
1604
+ if (d.preview)
1605
+ task.preview = d.preview;
1606
+ stage(task, "delegate", "pass", `${role.agent} on ${model}, planned task`);
1607
+ const rel = await this.#integrate(project, job, WRITERS.has(role.id), task.repo);
1608
+ return this.#start(project, parent, job, task, role, model, { ...d, body: this.#plannedBody(job, task, d.body) }, checks, rel);
1609
+ }
1610
+ // A planned task's brief: the job, verbatim user prompt, upstream dependsOn handoffs, acceptance points, decisions, and post-green guidance.
1611
+ #plannedBody(job, task, extra) {
1612
+ const acceptance = taskAcceptance(job, task).map((a) => `- ${a.id}: ${a.text}${a.verify ? ` (checked with: ${a.verify})` : ""}${sharedNote(job, task, a.id)}`);
1613
+ const handoffs = upstreamHandoffs(job, task);
1614
+ return [
1615
+ `The job: ${job.goal}`,
1616
+ verbatimGoalLine(job.goal),
1617
+ handoffs ? `\n${handoffs}` : "",
1618
+ `\nYour task (${task.id}): ${task.title.replace(/ \(attempt \d+\/\d+\)$/, "")}`,
1619
+ task.description,
1620
+ "\nAcceptance points:",
1621
+ ...(acceptance.length ? acceptance : ["- none given"]),
1622
+ job.decisions.length ? `\nDecisions that apply: ${job.decisions.map((x) => x.text).join("; ")}` : "",
1623
+ task.postGreen ? `\n${POST_GREEN_DIRECTIVE}` : "",
1624
+ extra ? `\nFrom the micromanager: ${extra}` : "",
1625
+ ].filter((line) => line !== "").join("\n");
1626
+ }
1627
+ // "Replaces: T5": the micromanager starts T5's work over on purpose. T5 is cancelled and its worktree, with whatever
1628
+ // change it held, goes; a task that still runs has to be stopped first, and a merged one has nothing to replace.
1629
+ async #replace(project, job, ids) {
1630
+ const cannot = this.#replaceable(project, job, ids);
1631
+ if (cannot.length)
1632
+ throw new DelegationError(`Not started: ${cannot.join("; ")}`);
1633
+ for (const id of ids) {
1634
+ const [owner, taskId] = this.#owner(project, job, id);
1635
+ if (owner && owner.tasks.find((t) => t.id === taskId)?.status !== "cancelled")
1636
+ await this.discard(project, owner, taskId, "replace", "started over by a new task");
1637
+ }
1638
+ }
1639
+ // The job a replaced id lives in and the task id inside it: "T19" in this job, "job-…/T18" in another of the project.
1640
+ #owner(project, job, id) {
1641
+ const [jobId, taskId] = id.includes("/") ? id.split("/") : [job.id, id];
1642
+ if (jobId === job.id)
1643
+ return [job, taskId];
1644
+ return [this.current(project, jobId) ?? listJobs(project).find((j) => j.id === jobId), taskId];
1645
+ }
1646
+ // Why the given tasks cannot be done over: missing, still running, or merged already. Empty when they can.
1647
+ #replaceable(project, job, ids) {
1648
+ return ids.flatMap((id) => {
1649
+ const [owner, taskId] = this.#owner(project, job, id);
1650
+ const task = owner?.tasks.find((t) => t.id === taskId);
1651
+ if (!owner || !task)
1652
+ return [`there is no task ${id} to replace`];
1653
+ if (LIVE.has(task.status) && !this.#entries.get(`${owner.id}/${taskId}`)?.ended)
1654
+ return [`${id} still runs; stop it with stop_task first, then replace it`];
1655
+ if (task.status === "merged" || task.status === "passed")
1656
+ return [`${id} is ${task.status}, so there is nothing to replace; say in the new task what to change on top of it`];
1657
+ return [];
1658
+ });
1659
+ }
1660
+ // The link both ways: the new task names what it does over, each old task the one doing it (job-qualified across jobs).
1661
+ #link(project, job, task, ids) {
1662
+ if (!ids.length)
1663
+ return;
1664
+ task.replaces = [...ids];
1665
+ for (const id of ids) {
1666
+ const [owner, taskId] = this.#owner(project, job, id);
1667
+ const old = owner?.tasks.find((t) => t.id === taskId);
1668
+ if (!owner || !old)
1669
+ continue;
1670
+ old.replacedBy = owner === job ? task.id : `${job.id}/${task.id}`;
1671
+ if (owner !== job)
1672
+ saveJob(project, owner);
1673
+ }
1674
+ }
1675
+ // A task given up for good: cancelled, and its worktree and branch gone, whatever change they held. For "Replaces:"
1676
+ // and for rewind_job, which must not leave a branch cut from a tip it took back (the merge train would replay it).
1677
+ async discard(project, job, taskId, why, evidence) {
1678
+ const task = job.tasks.find((t) => t.id === taskId);
1679
+ if (!task)
1680
+ return;
1681
+ const k = `${job.id}/${taskId}`;
1682
+ const entry = this.#entries.get(k);
1683
+ if (task.status !== "cancelled" && task.status !== "merged")
1684
+ moveTask(task, "cancelled");
1685
+ stage(task, why, "pass", evidence);
1686
+ if (entry) {
1687
+ await this.#dropWorktree(entry, task);
1688
+ this.#entries.delete(k);
1689
+ }
1690
+ else if (task.worktree && task.branch) {
1691
+ await removeTaskWorktree(project, { worktree: task.worktree, branch: task.branch }, this.#exec);
1692
+ task.worktree = undefined;
1693
+ task.branch = undefined;
1694
+ }
1695
+ saveJob(project, job);
1696
+ }
1697
+ // The job as this process holds it, when it holds it: the copy the plugin's tools must change, because this one is
1698
+ // saved over the file every time a worker moves on.
1699
+ current(project, jobId) {
1700
+ return this.#jobs.get(key(project, jobId));
1701
+ }
1702
+ // The same work delegated a second time (live run, 2026-10-07: three tasks each removed the same pill from the same
1703
+ // slide, because the first two stopped before their merge and the micromanager started over instead of continuing).
1704
+ // A writer on files another writer of this job is changing, or left unfinished with its change still in its worktree,
1705
+ // and whose title or brief is about the same thing, is refused with what to do instead; a reader is refused when one
1706
+ // with nearly the same brief still runs. It reads the job's task history, not only the live #entries: the todo path
1707
+ // has no entry yet, and a cancelled task's entry is deleted when its worktree goes. selfId: the task being started,
1708
+ // which is not a duplicate of itself. replan: applyReplan cancelled the old tasks on purpose; their replacements need
1709
+ // no Replaces line.
1710
+ #duplicate(job, role, title, body, files, replaced, o = {}) {
1711
+ const writer = WRITERS.has(role.id);
1712
+ for (const task of job.tasks) {
1713
+ if (task.id === o.selfId)
1714
+ continue;
1715
+ if (replaced.includes(task.id))
1716
+ continue;
1717
+ const entry = this.#entries.get(`${job.id}/${task.id}`);
1718
+ const session = task.session ?? entry?.session;
1719
+ if (!writer) {
1720
+ if (LIVE.has(task.status) && (!entry || !entry.ended) && task.role === role.id && similarity(body, task.description) >= SAME_QUESTION) {
1721
+ return `Not started: ${task.id} "${task.title}" asks this already (${session ? `session ${session}` : "its worker is starting"}); its report comes to you when it ends.`;
1722
+ }
1723
+ continue;
1724
+ }
1725
+ const shared = files.filter((f) => task.files.includes(f));
1726
+ if (!shared.length)
1727
+ continue;
1728
+ // Done work is a base for new work, not a duplicate.
1729
+ if (task.status === "merged" || task.status === "passed")
1730
+ continue;
1731
+ if (o.replan && task.status === "cancelled")
1732
+ continue;
1733
+ // A task that has not started is a duplicate only when its text is nearly the same: "implement parser" and
1734
+ // "implement parser tests" share a file and enough words, but are two steps. A stopped or running task is
1735
+ // different: a parallel restart of it loses work, so the lower SAME_WORK threshold applies.
1736
+ const open = task.status === "pending" || task.status === "ready" || task.status === "planned";
1737
+ const same = Math.max(similarity(title, task.title), similarity(body, task.description));
1738
+ if (same < (open ? SAME_PENDING : SAME_WORK))
1739
+ continue;
1740
+ if (LIVE.has(task.status) && (!entry || !entry.ended)) {
1741
+ return `Not started: ${task.id} "${task.title}" is doing this already (it changes ${shared.join(", ")}; ${session ? `session ${session}` : "its worker is starting"}). Send it a note with steer_task, or wait for its report. To replace it, stop it with stop_task, then delegate again with a line "Replaces: ${task.id}".`;
1742
+ }
1743
+ const last = task.stages[task.stages.length - 1];
1744
+ const stillThere = Boolean((entry && !entry.removed) || (task.worktree && existsSync(task.worktree)));
1745
+ if (session && stillThere) {
1746
+ return `Not started: ${task.id} "${task.title}" did this work and stopped before its merge${last ? ` (${last.stage}: ${last.evidence ?? last.result})` : ""}; its change is still in ${task.worktree ?? "its worktree"}. Continue it with the subagent tool and sessionID ${session}, saying what is left, so the change is kept. To start over instead, add a line "Replaces: ${task.id}": its worktree is discarded.`;
1747
+ }
1748
+ if (session && (task.status === "blocked" || task.status === "escalated")) {
1749
+ return `Not started: ${task.id} "${task.title}" is ${task.status}${last ? ` (${last.stage}: ${last.evidence ?? last.result})` : ""}. Continue it with the subagent tool and sessionID ${session}, or add "replaces": ["${task.id}"] to start over on purpose.`;
1750
+ }
1751
+ if (task.status === "cancelled") {
1752
+ return `Not started: ${task.id} "${task.title}" was cancelled and its worktree is gone. If this is the same work, add "replaces": ["${task.id}"]; otherwise drop it with the todo tool or choose a different title/files.`;
1753
+ }
1754
+ return `Not started: ${task.id} "${task.title}" is already on the todo list (${task.status}). Start it, drop it with the todo tool, or add "replaces": ["${task.id}"] if this task does the same work.`;
1755
+ }
1756
+ return undefined;
1757
+ }
1758
+ // The subagent call failed before its child took the task (refused, an unknown agent): the task is dropped.
1759
+ async abandon(prompt) {
1760
+ const k = tokenOf(prompt);
1761
+ const entry = k ? this.#entries.get(k) : undefined;
1762
+ if (!entry || entry.session)
1763
+ return;
1764
+ const job = this.#job(entry);
1765
+ const task = job?.tasks.find((t) => t.id === entry.taskId);
1766
+ if (task) {
1767
+ moveTask(task, "cancelled");
1768
+ stage(task, "delegate", "fail", "the subagent call failed");
1769
+ }
1770
+ await this.#dropWorktree(entry, task);
1771
+ this.#entries.delete(k);
1772
+ if (job)
1773
+ saveJob(entry.project, job);
1774
+ }
1775
+ // A child's first prompt: the directory it must move to, when it carries one of our tasks.
1776
+ claim(session, text) {
1777
+ if (!text.startsWith(CHILD_PREFIX))
1778
+ return undefined;
1779
+ const k = tokenOf(text);
1780
+ const entry = k ? this.#entries.get(k) : undefined;
1781
+ if (!entry || entry.session)
1782
+ return undefined;
1783
+ entry.session = session;
1784
+ this.#bySession.set(session, k);
1785
+ const job = this.#job(entry);
1786
+ const task = job?.tasks.find((t) => t.id === entry.taskId);
1787
+ if (job && task) {
1788
+ task.session = session;
1789
+ task.sessions = [...(task.sessions ?? []), session];
1790
+ saveJob(entry.project, job);
1791
+ }
1792
+ return { dir: entry.dir, task: `${entry.taskId} ${task?.title ?? ""}: ${task?.description ?? ""}`, parent: entry.parent };
1793
+ }
1794
+ // The micromanager continues a worker (subagent with its sessionID): a writer that ended (merged, cancelled, or
1795
+ // stopped) runs again on the same task, reusing its id, branch and worktree.
1796
+ async resume(session) {
1797
+ const entry = this.#entry(session);
1798
+ const job = entry && this.#job(entry);
1799
+ let task = job?.tasks.find((t) => t.id === entry.taskId);
1800
+ if (!entry || !job || !task)
1801
+ return undefined;
1802
+ entry.ended = false;
1803
+ entry.nudged = false;
1804
+ const wasTerminal = task.status === "merged" || task.status === "cancelled";
1805
+ if (task.status === "cancelled")
1806
+ restart(task);
1807
+ if (task.status === "merged")
1808
+ moveTask(task, "running"); // continued: next change on top of the merged one
1809
+ else if (task.status === "passed") {
1810
+ moveTask(task, "escalated");
1811
+ moveTask(task, "running");
1812
+ }
1813
+ else if (task.status === "escalated" || task.status === "blocked")
1814
+ moveTask(task, "running");
1815
+ if (wasTerminal) {
1816
+ task.attempts = 0;
1817
+ task.trial = undefined;
1818
+ }
1819
+ // readers and already-running tasks just keep going
1820
+ task.session = session;
1821
+ task.sessions = [...new Set([...(task.sessions ?? []), session])];
1822
+ // The sidebar tells a stopped worker by its last stage ("end"): continuing it runs again.
1823
+ stage(task, "resume", "pass", `continued in session ${session}`);
1824
+ if (entry.writer && entry.removed) {
1825
+ // The session keeps its directory, so the worktree comes back where it was: the worktree root, which is what git
1826
+ // registers, not the project directory inside it.
1827
+ const repoRoot = entry.repo ? resolve(entry.project, entry.repo) : entry.project;
1828
+ const branch = (entry.repo ? job.integrationRepos?.[entry.repo]?.branch : undefined) ?? job.integrationBranch;
1829
+ const w = await prepareTaskWorktree(repoRoot, job.id, entry.taskId, branch, this.#exec, entry.worktree, entry.rel);
1830
+ entry.worktree = w.worktree;
1831
+ entry.dir = w.dir;
1832
+ entry.branch = w.branch;
1833
+ entry.removed = false;
1834
+ task.worktree = w.worktree;
1835
+ task.worktreeRel = w.rel;
1836
+ task.branch = w.branch;
1837
+ }
1838
+ saveJob(entry.project, job);
1839
+ return task;
1840
+ }
1841
+ isWorker(session) {
1842
+ return this.#bySession.has(session);
1843
+ }
1844
+ // A worker's role, for the tools it may use (request_network: writers and researchers).
1845
+ roleOf(session) {
1846
+ const entry = this.#entry(session);
1847
+ return (entry && this.#job(entry)?.tasks.find((t) => t.id === entry.taskId)?.role);
1848
+ }
1849
+ isWriter(session) {
1850
+ return this.#entry(session)?.writer ?? false;
1851
+ }
1852
+ // The micromanager session a worker answers to, and how that session knows its task (src/ask.ts).
1853
+ ownerOf(session) {
1854
+ const entry = this.#entry(session);
1855
+ if (!entry)
1856
+ return undefined;
1857
+ const task = this.#job(entry)?.tasks.find((t) => t.id === entry.taskId);
1858
+ return { parent: entry.parent, task: task ? `${task.id} ${task.title}` : entry.taskId };
1859
+ }
1860
+ // A writer as its helpers see it (src/helpers.ts): where it works and what it works on. Undefined for anyone else.
1861
+ writerOf(session) {
1862
+ const entry = this.#entry(session);
1863
+ if (!entry?.writer)
1864
+ return undefined;
1865
+ const task = this.#job(entry)?.tasks.find((t) => t.id === entry.taskId);
1866
+ return { dir: entry.dir, label: `${entry.taskId} of ${entry.jobId}`, task: task ? `${task.title}: ${task.description}`.slice(0, 1500) : entry.taskId };
1867
+ }
1868
+ hasGraph(session) {
1869
+ return this.#entry(session)?.graph ?? false;
1870
+ }
1871
+ // The code_graph tool: one question to the graph of the explorer's directory, rebuilt first when the session
1872
+ // branch moved on (a writer merged) since the last build.
1873
+ async askGraph(session, action, symbol, to) {
1874
+ const entry = this.#entry(session);
1875
+ if (!entry?.graph)
1876
+ return "This session has no code graph.";
1877
+ if (!(await this.#graphs.get(entry.dir)))
1878
+ return "The code graph could not be built; use grep and read instead.";
1879
+ return queryGraph(entry.dir, action, symbol, to, this.#exec);
1880
+ }
1881
+ // finish_task: the checks in the worker's worktree, then the commit and the merge train. The text goes back to the
1882
+ // worker; note is what the micromanager should hear (undefined: nothing new).
1883
+ // stop: the sessions of a trial's other attempts, which the plugin interrupts once one attempt won.
1884
+ async finish(session, summary) {
1885
+ const entry = this.#entry(session);
1886
+ const job = entry && this.#job(entry);
1887
+ const task = job?.tasks.find((t) => t.id === entry.taskId);
1888
+ if (!entry || !job || !task)
1889
+ return { text: "This session has no task of the micromanager; there is nothing to finish." };
1890
+ return this.#finish(entry, job, task, summary, session);
1891
+ }
1892
+ // The evolver's best candidate (src/evolver.ts), written into its task's worktree: through the same gate as a
1893
+ // writer's finish_task (checks, frozen files, the contract, the merge train). There is no session to hand a failure
1894
+ // back to, so a failing round blocks the task at once.
1895
+ async finishEvolved(project, jobId, taskId, code, summary) {
1896
+ const entry = this.#entries.get(`${jobId}/${taskId}`);
1897
+ const job = this.#jobs.get(key(project, jobId));
1898
+ const task = job?.tasks.find((t) => t.id === taskId);
1899
+ if (!entry || !job || !task)
1900
+ return { text: `there is no evolving task ${taskId} in job ${jobId}` };
1901
+ writeFileSync(join(entry.dir, task.files[0]), code);
1902
+ task.attempts = FIX_ROUNDS; // no session to fix it: a failure is final
1903
+ return this.#finish(entry, job, task, summary, `the evolver of ${task.id}`);
1904
+ }
1905
+ // An evolving task: a writer task with its own worktree like any other, but no session; the evolver works on a
1906
+ // copy of its directory and its best candidate comes back through finishEvolved. Returns the task and its directory,
1907
+ // or why not.
1908
+ async prepareEvolve(project, parent, jobId, r) {
1909
+ const job = jobId ? this.#jobs.get(key(project, jobId)) ?? listJobs(project).find((j) => j.id === jobId) : this.job(project, parent);
1910
+ if (!job)
1911
+ return { problem: `there is no job ${jobId} in this project` };
1912
+ const parsed = parseFiles(r.file, project);
1913
+ if (parsed.problem || parsed.files.length !== 1)
1914
+ return { problem: parsed.problem ?? "file: the one file whose block evolves" };
1915
+ const checks = checkSetProblems(r.checks, true);
1916
+ if (checks)
1917
+ return { problem: checks };
1918
+ let c;
1919
+ try {
1920
+ c = this.#contractFor(job, true, r.contract.toUpperCase());
1921
+ }
1922
+ catch (err) {
1923
+ return { problem: err instanceof Error ? err.message.replace(/^Not started: /, "") : String(err) };
1924
+ }
1925
+ if (!c)
1926
+ return { problem: "contract: the frozen contract that measures the evolution" };
1927
+ this.#jobs.set(key(project, job.id), job);
1928
+ const rel = await this.#integrate(project, job, true);
1929
+ const added = addDelegated(job, { title: `evolve ${parsed.files[0]}: ${r.block}`.slice(0, 120), prompt: `The evolver improves ${r.block} in ${parsed.files[0]} against contract ${c.id}.`, files: parsed.files, dependsOn: [], checks: [...r.checks] });
1930
+ if (!added.task)
1931
+ return { problem: added.errors.join("; ") };
1932
+ const task = added.task;
1933
+ task.role = "code";
1934
+ task.model = "evolver";
1935
+ this.#bind(job, task, c.id);
1936
+ for (const s of ["ready", "planned", "running"])
1937
+ moveTask(task, s);
1938
+ stage(task, "delegate", "pass", `evolver on ${parsed.files[0]} (${r.block}), contract ${c.id}`);
1939
+ const role = roleById("code");
1940
+ await this.#start(project, parent, job, task, role, "evolver", { body: task.description, files: parsed.files.join(", "), checks: [...r.checks], replaces: [] }, [...r.checks], rel);
1941
+ const entry = this.#entries.get(`${job.id}/${task.id}`);
1942
+ return { job, task, dir: entry.dir, contract: c };
1943
+ }
1944
+ // The task a worker session works on, or the writer's task for one of its helpers: what its usage is charged to.
1945
+ taskOfSession(session) {
1946
+ const entry = this.#entry(session);
1947
+ return entry ? this.#job(entry)?.tasks.find((t) => t.id === entry.taskId) : undefined;
1948
+ }
1949
+ // A model call of the evolver's bridge, charged to the job as a worker's request is (src/budget.ts), and to its task.
1950
+ chargeEvolve(project, jobId, used, taskId) {
1951
+ const job = this.#jobs.get(key(project, jobId));
1952
+ if (!job)
1953
+ return;
1954
+ const task = taskId ? job.tasks.find((t) => t.id === taskId) : undefined;
1955
+ if (task)
1956
+ chargeTask(task, used);
1957
+ const c = job.counters;
1958
+ c.tokens = (c.tokens ?? 0) + used.tokens;
1959
+ c.cost = (c.cost ?? 0) + used.cost;
1960
+ c.requests = (c.requests ?? 0) + used.requests;
1961
+ saveJob(project, job);
1962
+ }
1963
+ // The evolver's state on its task, saved as it goes: the sidebar and job_status read it from the job file.
1964
+ noteEvolve(project, jobId, taskId, state) {
1965
+ const job = this.#jobs.get(key(project, jobId));
1966
+ const task = job?.tasks.find((t) => t.id === taskId);
1967
+ if (!job || !task)
1968
+ return;
1969
+ task.evolve = state;
1970
+ task.summary = `evolving: ${state.evaluations} candidates measured (${state.valid} valid)${state.best ? `, best ${Object.entries(state.best).filter(([k]) => k !== "combined_score" && k !== "valid").map(([k, v]) => `${k} ${v}`).join(", ")}` : ""}`;
1971
+ saveJob(project, job);
1972
+ }
1973
+ // An evolution that ended without a candidate to merge: the task is blocked with why.
1974
+ evolveFailed(project, jobId, taskId, why) {
1975
+ const job = this.#jobs.get(key(project, jobId));
1976
+ const task = job?.tasks.find((t) => t.id === taskId);
1977
+ if (!job || !task)
1978
+ return;
1979
+ if (["running", "gating", "fixing"].includes(task.status))
1980
+ moveTask(task, "blocked");
1981
+ stage(task, "evolve", "fail", why.slice(0, 300));
1982
+ task.summary = `the evolver found nothing to merge: ${why.slice(0, 300)}`;
1983
+ const entry = this.#entries.get(`${jobId}/${taskId}`);
1984
+ if (entry)
1985
+ entry.ended = true;
1986
+ saveJob(project, job);
1987
+ }
1988
+ async #finish(entry, job, task, summary, session) {
1989
+ // A task in another repository of a workspace merges into that repo's own integration branch and worktree.
1990
+ const integ = entry.repo ? job.integrationRepos?.[entry.repo] : undefined;
1991
+ const integrationBranch = integ?.branch ?? job.integrationBranch;
1992
+ const integrationWorktree = integ?.worktree ?? job.integrationWorktree;
1993
+ const integrationRel = integ?.rel ?? (entry.repo ? "" : job.integrationRel ?? "");
1994
+ if (!entry.writer)
1995
+ return { text: "You only read: there is nothing to check or merge. End with your findings; they are your result." };
1996
+ if (task.status === "merged")
1997
+ return { text: `${task.id} is already merged into ${job.integrationBranch}. End with your short report.` };
1998
+ if (task.trial && task.status === "cancelled")
1999
+ return { text: lostText(job, task) };
2000
+ if (task.status === "escalated")
2001
+ moveTask(task, "running");
2002
+ // A merge train step that conflicted left its rebase open in this worktree (rebaseTask). The worker resolves the
2003
+ // markers in place, because the plugin is the only side that may write git state; until it does, finish_task hands
2004
+ // the same files back instead of running the checks over a half-merged tree or escalating a task that is alive.
2005
+ const rebasing = entry.branch ? await rebaseInProgress(entry.worktree, this.#exec) : false;
2006
+ if (rebasing) {
2007
+ const unresolved = await unresolvedConflicts(entry.worktree, this.#exec);
2008
+ if (unresolved.length) {
2009
+ if (task.status === "passed") {
2010
+ moveTask(task, "escalated");
2011
+ moveTask(task, "running");
2012
+ }
2013
+ stage(task, "merge", "fail", `conflict in ${unresolved.join(", ")}: still unresolved`);
2014
+ saveJob(entry.project, job);
2015
+ return { text: conflictHeldText(job, entry, unresolved) };
2016
+ }
2017
+ }
2018
+ moveTask(task, "gating");
2019
+ task.summary = summary.trim().slice(0, 2000) || task.summary;
2020
+ // The checks run where the worker's files are, not in the worktree root: a project below the repository root lives
2021
+ // that far down, and a check naming one of its files finds nothing above it.
2022
+ // Frozen files first: a changed test is put back before the checks run, so they judge the code against the tests as
2023
+ // they were, and the worker hears what it may not do.
2024
+ const frozen = entry.frozen ? await frozenChanged(entry.worktree, entry.frozen, this.#exec, entry.dir) : [];
2025
+ if (frozen.length)
2026
+ await revertFiles(entry.worktree, frozen, this.#exec, entry.dir);
2027
+ // The checks are persisted and survive a restart, so they are validated again here, where the real worktree is
2028
+ // known: a check that cds to the user's checkout must not run and pass against files the worker never changed.
2029
+ const cwdProblems = entry.checks.map((c) => checkCwdProblem(c, entry.dir, entry.worktree, entry.project));
2030
+ const safeChecks = entry.checks.filter((_, i) => !cwdProblems[i]);
2031
+ const blockedChecks = entry.checks.flatMap((command, i) => {
2032
+ const why = cwdProblems[i];
2033
+ return why ? [{ command, passed: false, code: 1, output: why }] : [];
2034
+ });
2035
+ const gate = await this.#entryGate(entry, job, task.role);
2036
+ const results = [...(await runGate(entry.worktree, safeChecks, this.#exec, this.#checkTimeout(job), entry.dir, {}, gate)), ...blockedChecks];
2037
+ if (frozen.length)
2038
+ results.push({ command: "frozen files unchanged", passed: false, code: 1, output: `You changed ${frozen.join(", ")}, which you may read and run but not change; they are restored to how they were. Change the code instead. If one of them is wrong, ask for the change with request_check_change, with the line that shows it.` });
2039
+ const graded = gradedOf(results);
2040
+ if (graded)
2041
+ task.graded = graded;
2042
+ // D23: the checks ran without a box because the user confirmed this job; every stage line that reports them says so.
2043
+ const unsandboxed = unsandboxedNote(results);
2044
+ const failed = results.filter((r) => !r.passed);
2045
+ // Another attempt of its trial won while these checks ran (and took the worktree away).
2046
+ if (task.status === "cancelled")
2047
+ return { text: lostText(job, task) };
2048
+ // No sandbox to run the checks in: they did not run at all, and no fix round can change that (A1-T12). The task is
2049
+ // blocked with the gate's reason instead of being handed back to the worker.
2050
+ const skipped = failed.filter((r) => r.skipped);
2051
+ if (failed.length && skipped.length === failed.length) {
2052
+ if (task.postGreen) {
2053
+ return this.#discardPostGreen(entry, job, task, "checks did not pass — discarded candidate and kept green baseline", "skip");
2054
+ }
2055
+ const why = skipped[0].output;
2056
+ stage(task, "gate", "fail", why);
2057
+ moveTask(task, "blocked");
2058
+ task.summary = `its checks were not run, so it is blocked: ${why}`;
2059
+ const note = this.#trialFailed(job, task, entry.project) ?? `[micromanager] ${task.id} ${task.title}: its checks were not run (${why}), so the task is blocked instead of handed back. Make the sandbox usable and continue it with steer_task and its sessionID ${session}.`;
2060
+ saveJob(entry.project, job);
2061
+ return {
2062
+ text: `I could not run your checks, so ${task.id} is blocked rather than handed back to you: ${why}. A check never runs outside the sandbox. Your work is still in your worktree; say plainly in your report that the checks were not run.`,
2063
+ note,
2064
+ parent: entry.parent,
2065
+ };
2066
+ }
2067
+ if ((failed.length || (graded && graded.passed !== graded.total)) && task.postGreen) {
2068
+ return this.#discardPostGreen(entry, job, task, "checks did not pass — discarded candidate and kept green baseline", "skip");
2069
+ }
2070
+ // The contract's evaluator runs only once the checks pass: it may take minutes, and a broken build measures nothing.
2071
+ // A red team is measured without its guards (src/contractround.ts): gaming them is what it is for.
2072
+ const fitness = failed.length || task.redteam ? {} : await this.#measure(entry, job, task);
2073
+ // The evaluator can take minutes, and the trial may be decided meanwhile (TypeScript cannot see that across await).
2074
+ if (task.status === "cancelled")
2075
+ return { text: lostText(job, task) };
2076
+ if (fitness.failed) {
2077
+ if (task.postGreen) {
2078
+ return this.#discardPostGreen(entry, job, task, "did not improve fitness baseline — kept green baseline", "skip");
2079
+ }
2080
+ failed.push(fitness.failed);
2081
+ stage(task, "gate", "pass", `${entry.checks.join(", ")}${unsandboxed}`);
2082
+ // A used-up stop rule is final for this worker: another fix round could not be measured.
2083
+ if (fitness.exhausted)
2084
+ task.attempts = FIX_ROUNDS;
2085
+ }
2086
+ const what = fitness.failed ? "fitness" : "gate";
2087
+ if (failed.length) {
2088
+ // The same cap the runner applies to its fix rounds (runner.ts: #work, `fixRounds ?? 2`). Without it a check that
2089
+ // cannot be satisfied in this environment -- a path that does not exist, a command the gate refuses -- was handed
2090
+ // back to the model until the watchdog's step limit stopped it, burning a session for nothing (live test,
2091
+ // 2026-10-06: four identical gate failures, then the worker gave up). The last failure goes back with the
2092
+ // reason, because at the cap the useful message is that the CHECK is the problem, not the work.
2093
+ task.attempts++;
2094
+ if (task.attempts > FIX_ROUNDS) {
2095
+ stage(task, what, "fail", `${failed.map((f) => f.command).join(", ")}${unsandboxed}`);
2096
+ moveTask(task, "blocked");
2097
+ task.summary = `its checks still fail after ${FIX_ROUNDS} fix round(s): ${failed.map((f) => f.command).join(", ")}`;
2098
+ const note = this.#trialFailed(job, task, entry.project) ?? `[micromanager] ${task.id} ${task.title}: its worker hit the limit of ${FIX_ROUNDS} fix rounds with the checks still failing (${failed.map((f) => f.command).join(", ")}). If the check is what is wrong -- a path that does not exist in the worktree, a command the gate refuses -- correct the task with steer_task and its sessionID ${session} rather than starting a new worker.`;
2099
+ saveJob(entry.project, job);
2100
+ return {
2101
+ text: `Your checks still fail after ${FIX_ROUNDS} rounds, so I am stopping here rather than spending the rest of your budget on them:\n\n${failed.map((f) => `$ ${f.command} (exit ${f.code})\n${f.output}`).join("\n\n")}\n\nIf the work is done and the CHECK is what cannot be satisfied here, say so plainly in your report (request_check_change is the way to have a wrong check changed). If the work is not done, name what is missing.`,
2102
+ note,
2103
+ parent: entry.parent,
2104
+ };
2105
+ }
2106
+ moveTask(task, "fixing");
2107
+ moveTask(task, "running");
2108
+ stage(task, what, "fail", `${fitness.failed ? fitness.failed.output.split("\n")[0] : failed.map((f) => f.command).join(", ")}${unsandboxed}`);
2109
+ saveJob(entry.project, job);
2110
+ return { text: failText(fitness.failed ? `Your checks pass, but the fitness contract does not hold (fix round ${task.attempts} of ${FIX_ROUNDS})` : `The checks fail in your directory (fix round ${task.attempts} of ${FIX_ROUNDS})`, failed, entry.dir) };
2111
+ }
2112
+ const passedChecksCount = results.filter((r) => r.passed && !r.skipped).length;
2113
+ // "Review per task" (the job's switch): a reviewer of another family reads the change before it merges. Off by
2114
+ // default; a review finding goes back to this worker like a failed check, and a pool with no other family blocks.
2115
+ if (entry.writer && optionsOf(loadControl(entry.project, job.id), lastOptions(entry.project)).review) {
2116
+ const reviewed = await this.#taskReview(job, task, entry, session, passedChecksCount);
2117
+ if (reviewed) {
2118
+ if (task.postGreen) {
2119
+ return this.#discardPostGreen(entry, job, task, "reviewer flagged candidate — kept green baseline", "skip");
2120
+ }
2121
+ return reviewed;
2122
+ }
2123
+ }
2124
+ if (job.isolation === "none") {
2125
+ // No git: nothing to commit or merge, and no way to see what changed; the checks are the evidence.
2126
+ stage(task, "gate", "pass", `${entry.checks.length ? entry.checks.join(", ") : "no checks given"}${unsandboxed}`);
2127
+ if (fitness.evidence)
2128
+ stage(task, "fitness", "pass", fitness.evidence);
2129
+ moveTask(task, "passed");
2130
+ this.#recordReport(job, task, summary, entry.writer, undefined, "passed");
2131
+ saveJob(entry.project, job);
2132
+ const checks = `${entry.checks.length ? `checks passed: ${entry.checks.join("; ")}` : "no checks were given"}${fitness.evidence ? `; measured: ${fitness.evidence}` : ""}`;
2133
+ return {
2134
+ text: `Done; your change is in the project folder (no git, so nothing is committed); ${checks}. Now end with your short report.`,
2135
+ note: `[micromanager] ${task.id} ${task.title}: done in the project folder (no git); ${checks}.`,
2136
+ parent: entry.parent,
2137
+ };
2138
+ }
2139
+ if (job.isolation === "plan") {
2140
+ // A plan job's work stays in its plan worktree: nothing is merged and no branch outlives the task. A read-only
2141
+ // investigation may legitimately change nothing, so the "no file was changed" check below does not apply.
2142
+ // The one thing that leaves the worktree is what the report's Artifacts: lines name, and every path is validated
2143
+ // before a byte is copied (src/promote.ts). A refused path keeps the task open: a report that names something it
2144
+ // could not hand back is not done, and a silent drop would teach the planner that a bad path works.
2145
+ const artifacts = parseArtifacts(summary);
2146
+ const promotion = promoteArtifacts({ project: entry.project, jobId: job.id, taskId: task.id, root: entry.worktree, dir: entry.dir, paths: artifacts });
2147
+ if (!promotion.ok) {
2148
+ moveTask(task, "fixing");
2149
+ moveTask(task, "running");
2150
+ stage(task, "promote", "fail", promotion.rejected.map((r) => `${r.path}: ${r.reason}`).join(", ").slice(0, 300));
2151
+ saveJob(entry.project, job);
2152
+ return {
2153
+ text: `Your checks pass, but ${promotion.rejected.length} path(s) of your report's Artifacts: line cannot be promoted, so ${task.id} is not done yet:\n\n${promotion.rejected.map((r) => `- ${r.path}: ${r.reason}`).join("\n")}\n\nNothing of a refused path was copied. A path must name a regular file or a directory inside ${entry.dir}, with no symlinks, no absolute paths and no ".." leaving it. Fix the path, or remove it from the Artifacts: line, and call finish_task again.`,
2154
+ parent: entry.parent,
2155
+ };
2156
+ }
2157
+ stage(task, "gate", "pass", `${entry.checks.length ? entry.checks.join(", ") : "no checks given"}${unsandboxed}`);
2158
+ if (fitness.evidence)
2159
+ stage(task, "fitness", "pass", fitness.evidence);
2160
+ const area = planArea(entry.project, job.id);
2161
+ // The worktree dies with its branch, so the work is committed on that branch first: the record's patch is then
2162
+ // literally `git diff base..HEAD`, and the commit is thrown away with it, never reaching a branch of the user's.
2163
+ // A copy of the project has no branch, so there is no commit and no patch.
2164
+ let git;
2165
+ let record;
2166
+ try {
2167
+ if (entry.branch) {
2168
+ // A task adopted from a file that predates planBase has none: the commit it sits on now is the honest base
2169
+ // for what this finish adds.
2170
+ const base = task.planBase ?? (await this.#exec("git", ["rev-parse", "HEAD"], { cwd: entry.worktree })).stdout.trim();
2171
+ task.planBase = base;
2172
+ // A no-op commit is fine: a planner that changed nothing has nothing to record in the patch.
2173
+ await commitTask(entry.worktree, `${task.id}: ${task.title} (plan)`, `Plan job ${job.id}\nWorker: ${task.model ?? "?"} (${task.role}), session ${session}`, this.#exec);
2174
+ const head = await this.#exec("git", ["rev-parse", "HEAD"], { cwd: entry.worktree });
2175
+ if (head.code !== 0)
2176
+ throw new IntegrationError(`git rev-parse failed: ${head.stderr.trim()}`);
2177
+ const diff = await this.#exec("git", ["diff", `${base}..${head.stdout.trim()}`], { cwd: entry.worktree });
2178
+ if (diff.code !== 0)
2179
+ throw new IntegrationError(`git diff failed: ${diff.stderr.trim()}`);
2180
+ git = { base, head: head.stdout.trim(), patch: diff.stdout };
2181
+ }
2182
+ record = writePromotionRecord({ project: entry.project, jobId: job.id, taskId: task.id, title: task.title, report: summary, promotion, checks: entry.checks, ...(git ? { git } : {}) });
2183
+ }
2184
+ catch (err) {
2185
+ // The artifacts are already promoted, which is harmless; without a record the task is not done, and the worker
2186
+ // can call finish_task again once the cause is gone.
2187
+ return {
2188
+ text: `Your checks pass, but the record of this plan task could not be written, so ${task.id} is not done yet: ${err instanceof Error ? err.message : String(err)}. Its artifacts are already promoted. Call finish_task again.`,
2189
+ parent: entry.parent,
2190
+ };
2191
+ }
2192
+ task.promoted = promotion.promoted.map((a) => ({ path: a.path, bytes: a.bytes, sha256: a.sha256 }));
2193
+ stage(task, "promote", "pass", `${promotion.promoted.length} artifact file(s), ${promotion.rejected.length} rejected`);
2194
+ moveTask(task, "passed");
2195
+ this.#recordReport(job, task, summary, entry.writer, undefined, "passed");
2196
+ saveJob(entry.project, job);
2197
+ // The artifacts are now the job's, so its plan.md says so; a richer document the plan agent wrote is kept.
2198
+ this.#ensurePlanDoc(entry.project, job, task);
2199
+ // The record is on disk, so the throwaway worktree and its branch go now rather than at the job's end.
2200
+ await this.#dropWorktree(entry, task);
2201
+ const checks = `${entry.checks.length ? `checks passed: ${entry.checks.join("; ")}` : "no checks were given"}${fitness.evidence ? `; measured: ${fitness.evidence}` : ""}`;
2202
+ const promoted = artifacts.length
2203
+ ? `${promotion.promoted.length} artifact file(s) promoted to ${join(area, "artifacts", task.id)}`
2204
+ : "no Artifacts: line, so nothing was promoted";
2205
+ const named = [record.patch ? `patches/${task.id}.patch` : "no patch (no git)", `findings/${task.id}.md`, `artifacts/${task.id}/manifest.json`].join(", ");
2206
+ return {
2207
+ text: `Done; ${checks}. This is a plan job: nothing is committed or merged into your checkout, and the plan worktree is gone. The record is under ${area} (${named}); ${promoted}. Now end with your short report.`,
2208
+ parent: entry.parent,
2209
+ };
2210
+ }
2211
+ // A passing gate over an untouched tree proves nothing: read-only checks exit 0 on a worktree nobody wrote to, and
2212
+ // a worker whose session died mid-task never gets this far but a silent no-op worker does.
2213
+ const touched = await changedFiles(entry.worktree, this.#exec, task.worktreeRel ?? integrationRel);
2214
+ // A held rebase always has a commit of its own to merge; the resolution is folded into it below, so an empty
2215
+ // working tree here is the state after a restart, not a worker that changed nothing.
2216
+ if (!touched.length && !rebasing) {
2217
+ if (task.postGreen) {
2218
+ return this.#discardPostGreen(entry, job, task, "no changes needed — kept green baseline", "pass");
2219
+ }
2220
+ // A task whose change is already on the integration branch (its branch is fully contained in it, and its declared
2221
+ // files are already present there) legitimately needs no new commit: close it as done instead of blocking. A task
2222
+ // that changed nothing but claims success is still blocked below.
2223
+ let alreadyIntegrated = false;
2224
+ if (entry.branch && integrationBranch) {
2225
+ const anc = await this.#exec("git", ["merge-base", "--is-ancestor", entry.branch, integrationBranch], { cwd: entry.worktree });
2226
+ alreadyIntegrated = anc.code === 0;
2227
+ }
2228
+ const rel = task.worktreeRel ?? integrationRel;
2229
+ const integrationDir = taskDir(integrationWorktree ?? entry.worktree, rel);
2230
+ const filesAlreadyThere = task.files.length > 0 && task.files.every((f) => {
2231
+ try {
2232
+ return statSync(join(integrationDir, f)).isFile();
2233
+ }
2234
+ catch {
2235
+ return false;
2236
+ }
2237
+ });
2238
+ if (alreadyIntegrated && filesAlreadyThere) {
2239
+ stage(task, "gate", "pass", "no new changes: already on the integration branch");
2240
+ moveTask(task, "passed");
2241
+ this.#recordReport(job, task, summary, entry.writer, undefined, "passed");
2242
+ await this.#dropWorktree(entry, task);
2243
+ saveJob(entry.project, job);
2244
+ return {
2245
+ text: `Your checks pass, and your change is already on ${job.integrationBranch}, so there is nothing to commit; closed as done.`,
2246
+ note: `[micromanager] ${task.id} ${task.title}: closed as done, its change is already on ${job.integrationBranch}; nothing committed.`,
2247
+ parent: entry.parent,
2248
+ };
2249
+ }
2250
+ stage(task, "gate", "fail", "the checks passed but no file was changed");
2251
+ moveTask(task, "blocked");
2252
+ task.summary = "its checks passed but it changed no file, so nothing was verified.";
2253
+ saveJob(entry.project, job);
2254
+ return {
2255
+ text: `Your checks pass, but you changed no file, so there is nothing to commit and nothing was verified. If the task was already done by someone else, say so in your report. Otherwise make the change the task asked for and call finish_task again.`,
2256
+ note: this.#trialFailed(job, task, entry.project) ?? `[micromanager] ${task.id} ${task.title}: its checks passed but it changed no file, so nothing was committed. Continue it with the subagent tool and sessionID ${session}, or tell the user.`,
2257
+ parent: entry.parent,
2258
+ };
2259
+ }
2260
+ // The worker resolved the held conflict: stage the files and let git finish replaying the commit. A second
2261
+ // conflicting commit leaves the rebase open and hands the new file list back; a failure that is not a conflict
2262
+ // cannot be fixed by editing files, so the task is blocked with the real error and its work stays in the worktree.
2263
+ let commit;
2264
+ if (rebasing) {
2265
+ const resumed = await resumeRebase(entry.worktree, this.#exec);
2266
+ if (!resumed.ok) {
2267
+ if (task.postGreen) {
2268
+ return this.#discardPostGreen(entry, job, task, "merge conflict — kept green baseline", "skip");
2269
+ }
2270
+ if (!resumed.files.length) {
2271
+ moveTask(task, "blocked");
2272
+ stage(task, "merge", "fail", resumed.conflict);
2273
+ saveJob(entry.project, job);
2274
+ return {
2275
+ text: `The rebase onto ${job.integrationBranch} could not be continued (${resumed.conflict}). Your work and the conflict state are still in ${entry.dir}; nothing was thrown away. Tell the user.`,
2276
+ note: `[micromanager] ${task.id} ${task.title}: the held rebase could not be continued (${resumed.conflict}). Continue it with the subagent tool and sessionID ${session}, or tell the user.`,
2277
+ parent: entry.parent,
2278
+ };
2279
+ }
2280
+ if (task.status === "passed") {
2281
+ moveTask(task, "escalated");
2282
+ moveTask(task, "running");
2283
+ }
2284
+ stage(task, "merge", "fail", resumed.conflict);
2285
+ saveJob(entry.project, job);
2286
+ return { text: conflictHeldText(job, entry, resumed.files) };
2287
+ }
2288
+ commit = resumed.commit;
2289
+ }
2290
+ stage(task, "gate", "pass", `${entry.checks.length ? entry.checks.join(", ") : "no checks given"}${unsandboxed}`);
2291
+ if (fitness.evidence)
2292
+ stage(task, "fitness", "pass", fitness.evidence);
2293
+ const extra = await commitTask(entry.worktree, `${task.id}: ${task.title}`, `Job: ${job.id}\nWorker: ${task.model ?? "?"} (${task.role}), session ${session}${task.summary ? `\n\n${task.summary}` : ""}`, this.#exec);
2294
+ if (extra)
2295
+ commit = extra;
2296
+ if (commit)
2297
+ task.commit = commit;
2298
+ if (task.redteam)
2299
+ return this.#redteamDone(entry, job, task);
2300
+ moveTask(task, "passed");
2301
+ this.#recordReport(job, task, summary, entry.writer, touched, "passed");
2302
+ const scored = task.trial && entry.contract ? job.contracts?.find((x) => x.id === entry.contract) : undefined;
2303
+ if (scored)
2304
+ return this.#hold(entry, job, task, scored, fitness.evidence);
2305
+ const mode = task.trial ? pickOf(task) : undefined;
2306
+ if ((mode === "best" && this.#grace.factor > 0) || mode === "user")
2307
+ return this.#holdPick(entry, job, task, mode);
2308
+ const train = this.#trains.get(job.id) ?? Promise.resolve();
2309
+ const step = train.then(() => (task.status === "cancelled" ? { ok: false, text: lostText(job, task) } : this.#merge(entry, job, task)));
2310
+ this.#trains.set(job.id, step.catch(() => undefined));
2311
+ const merged = await step;
2312
+ if (!merged.ok) {
2313
+ if (task.postGreen) {
2314
+ return this.#discardPostGreen(entry, job, task, "merge conflict — kept green baseline", "skip");
2315
+ }
2316
+ saveJob(entry.project, job);
2317
+ return { text: merged.text };
2318
+ }
2319
+ if (task.postGreen)
2320
+ stage(task, "optimize", "pass", "merged post-green optimization");
2321
+ this.#recordReport(job, task, summary, entry.writer, touched, "merged");
2322
+ const won = task.trial ? await this.#settleTrial(entry, job, task) : undefined;
2323
+ // The commit as merged: a rebase onto other tasks' commits gave it a new id (live test).
2324
+ const head = commit && (await this.#exec("git", ["rev-parse", "--short", "HEAD"], { cwd: entry.worktree })).stdout.trim();
2325
+ if (head)
2326
+ task.commit = head;
2327
+ saveJob(entry.project, job);
2328
+ const checks = `${entry.checks.length ? `checks passed: ${entry.checks.join("; ")}` : "no checks were given"}${fitness.evidence ? `; measured: ${fitness.evidence}` : ""}`;
2329
+ return {
2330
+ text: `Merged into ${job.integrationBranch}${head ? ` as ${head}` : " (nothing to commit)"}; ${checks}. Now end with your short report.`,
2331
+ note: won?.note ?? `[micromanager] ${task.id} ${task.title}: merged into ${job.integrationBranch}${head ? ` (${head})` : ", nothing changed"}; ${checks}.`,
2332
+ parent: entry.parent,
2333
+ ...(won?.stop.length ? { stop: won.stop } : {}),
2334
+ };
2335
+ }
2336
+ // Walk a task to "passed" only along the state machine's legal edges (state.ts TASK_ALLOWED), so a status the
2337
+ // post-green settle did not expect (a reset left it "pending", a stopped run "cancelled") can never throw StateError.
2338
+ // "cancelled" is terminal and deliberately NOT moved here: its caller keeps it cancelled and just drops the worktree.
2339
+ #settlePassed(task) {
2340
+ const PATH = {
2341
+ pending: ["ready", "planned", "running", "passed"],
2342
+ ready: ["planned", "running", "passed"],
2343
+ planned: ["running", "passed"],
2344
+ running: ["passed"],
2345
+ gating: ["passed"],
2346
+ reviewing: ["passed"],
2347
+ fixing: ["running", "passed"],
2348
+ escalated: ["running", "passed"],
2349
+ blocked: ["running", "passed"],
2350
+ };
2351
+ const path = PATH[task.status];
2352
+ if (!path)
2353
+ return;
2354
+ for (const to of path) {
2355
+ if (task.status !== to)
2356
+ moveTask(task, to);
2357
+ }
2358
+ }
2359
+ // Strict do-no-harm settle for post-green optimization passes: discard the candidate worktree/branch and transition
2360
+ // cleanly to "passed" (NEVER "blocked") so the green integration branch stays intact and allDone(job) is true.
2361
+ async #discardPostGreen(entry, job, task, reason, stageStatus = "skip") {
2362
+ await this.#dropWorktree(entry, task);
2363
+ if (task.status === "cancelled") {
2364
+ // stop_task cancelled this post-green pass while it was queued in the merge train or awaiting a rebase. "cancelled"
2365
+ // is terminal and only resumable as "running", so keep it and clean up without the illegal move to "passed".
2366
+ saveJob(entry.project, job);
2367
+ return { text: lostText(job, task), parent: entry.parent };
2368
+ }
2369
+ this.#settlePassed(task);
2370
+ stage(task, "optimize", stageStatus, reason);
2371
+ task.summary = reason;
2372
+ this.#recordReport(job, task, task.summary, entry.writer, [], "passed");
2373
+ saveJob(entry.project, job);
2374
+ return {
2375
+ text: `Post-green optimization settled: ${reason}. Now end with your short report.`,
2376
+ note: `[micromanager] ${task.id} ${task.title}: post-green optimization settled (${reason}).`,
2377
+ parent: entry.parent,
2378
+ };
2379
+ }
2380
+ // A trial's attempt merged: it won. Every other attempt is done over by it (replacedBy, so what waits for the first
2381
+ // attempt waits for the winner), cancelled, and its worktree goes; the ones still at work are returned to be stopped.
2382
+ // score: how the winner won a trial decided by its contract, for the note; the held attempts it beat lost on score.
2383
+ async #settleTrial(winner, job, task, score, by = "score") {
2384
+ const now = standing(job, task);
2385
+ const stop = [];
2386
+ const stopped = now.live.filter((t) => t !== task);
2387
+ const beaten = now.held.filter((t) => t !== task);
2388
+ for (const other of now.all) {
2389
+ if (other === task || other.status === "merged" || other.status === "cancelled")
2390
+ continue;
2391
+ const e = this.#entries.get(`${job.id}/${other.id}`);
2392
+ if (e?.session && !e.ended && now.live.includes(other))
2393
+ stop.push(e.session);
2394
+ moveTask(other, "cancelled");
2395
+ stage(other, "trial", "pass", other.held ? `won by ${task.id} ${{ score: "on score", quality: "on quality", user: "as the user's pick" }[by]}` : `won by ${task.id}`);
2396
+ other.replacedBy = task.id;
2397
+ if (e)
2398
+ await this.#dropWorktree(e, other);
2399
+ }
2400
+ // The first attempt is what the plan and the dependants know: done over by the winner, it counts as done.
2401
+ stage(task, "trial", "pass", `won the trial of ${task.trial.of}${score ? ` ${{ score: "on score", quality: "on quality", user: "as the user's pick" }[by]} (${score})` : ""} (${now.failed.length} failed, ${stopped.length} stopped${beaten.length ? `, ${beaten.length} beaten` : ""})`);
2402
+ saveJob(winner.project, job);
2403
+ return { note: wonText(job, task, stopped, now.failed.length, undefined, score !== undefined ? { beaten, how: score, by } : undefined), stop };
2404
+ }
2405
+ // A passed attempt of a trial decided by score: measured on the held-out cases too, committed, and held in its
2406
+ // worktree instead of merged. The worker hears only how many held-out cases passed. The trial is decided when no
2407
+ // attempt is at work any more, at its deadline, or at once when one reaches the contract's target.
2408
+ async #hold(entry, job, task, c, visible) {
2409
+ let held;
2410
+ if (c.corpus.heldOut) {
2411
+ const r = await runEvaluator(entry.dir, c, "heldout", this.#exec, heldOutDir(entry.project, job.id, c.id), await this.#entryGate(entry, job, task.role));
2412
+ this.#count(job, c, r.seconds);
2413
+ held = r.measured;
2414
+ task.score = { ...held, corpus: "heldout", at: new Date().toISOString() };
2415
+ }
2416
+ task.held = true;
2417
+ stage(task, "trial", "pass", `passed, waits for the trial to be decided by score${held ? `; held-out ${coarse(held)}` : ""}`);
2418
+ const head = job.tasks.find((t) => t.id === task.trial.of) ?? task;
2419
+ this.#arm(entry.project, job, head);
2420
+ saveJob(entry.project, job);
2421
+ const settled = await this.#settleQueued(entry.project, job, head, false);
2422
+ // Decided here: finish_task carries the note and the sessions to stop; the outcomes are known now.
2423
+ if (settled)
2424
+ this.#onSettled?.({ project: entry.project, job, parent: entry.parent, stop: [], measured: settled.measured });
2425
+ if (settled?.winner === task) {
2426
+ return { text: `Your attempt won the trial on score and is merged into ${job.integrationBranch}. Now end with your short report.`, note: settled.note, parent: entry.parent, stop: settled.stop };
2427
+ }
2428
+ const measured = [visible ? `measured: ${visible}` : "", held ? `on the held-out cases, which you cannot see: ${coarse(held)}` : ""].filter(Boolean).join("; ");
2429
+ return {
2430
+ text: `Your checks pass${measured ? ` (${measured})` : ""}, and your commit waits in your worktree: the attempt with the best score is merged once every attempt of this trial is done. There is nothing more to do; end now with your short report.`,
2431
+ ...(settled ? { note: settled.note, parent: entry.parent, stop: settled.stop } : {}),
2432
+ };
2433
+ }
2434
+ // A passed attempt of a trial decided by quality or by the user: committed and held in its worktree. A "best" trial
2435
+ // opens its grace window with the first one (a share of that attempt's time) and stops the attempts that are getting
2436
+ // nowhere; a "user" trial waits for every attempt to end, with no deadline.
2437
+ async #holdPick(entry, job, task, mode) {
2438
+ task.held = true;
2439
+ stage(task, "trial", "pass", mode === "user" ? "passed, waits for the user's pick" : "passed, waits for the trial to be decided by quality");
2440
+ const head = job.tasks.find((t) => t.id === task.trial.of) ?? task;
2441
+ const stop = [];
2442
+ if (mode === "best") {
2443
+ if (!head.settleBy) {
2444
+ const started = Date.parse(task.stages.find((s) => s.stage === "delegate")?.at ?? "");
2445
+ const window = graceMs(this.#grace, Number.isFinite(started) ? Date.now() - started : 0);
2446
+ this.#arm(entry.project, job, head, window);
2447
+ stage(task, "trial", "pass", `first to pass: the others have ${Math.round(window / 1000)} s to finish`);
2448
+ }
2449
+ stop.push(...(await this.#stopIdle(job, head)));
2450
+ }
2451
+ saveJob(entry.project, job);
2452
+ const settled = await this.#settleQueued(entry.project, job, head, false);
2453
+ if (settled)
2454
+ this.#onSettled?.({ project: entry.project, job, parent: entry.parent, stop: [], measured: settled.measured });
2455
+ if (settled?.winner === task) {
2456
+ return { text: `Your attempt won the trial and is merged into ${job.integrationBranch}. Now end with your short report.`, note: settled.note, parent: entry.parent, stop: [...stop, ...settled.stop] };
2457
+ }
2458
+ const text = mode === "user"
2459
+ ? "Your checks pass, and your commit waits in your worktree: the user picks one of the attempts once all of them are done. There is nothing more to do; end now with your short report, saying in a sentence what makes your version yours."
2460
+ : "Your checks pass, and your commit waits in your worktree: once the other attempts had their grace window, the best one is merged. There is nothing more to do; end now with your short report.";
2461
+ const all = [...stop, ...(settled?.stop ?? [])];
2462
+ return { text, ...(settled ? { note: settled.note } : {}), ...(settled || all.length ? { parent: entry.parent } : {}), ...(all.length ? { stop: all } : {}) };
2463
+ }
2464
+ // The live attempts of a trial that are getting nowhere: cancelled, their worktrees gone; their sessions to stop.
2465
+ async #stopIdle(job, head) {
2466
+ if (!this.#idle)
2467
+ return [];
2468
+ const sessions = [];
2469
+ for (const t of standing(job, head).live) {
2470
+ const e = this.#entries.get(`${job.id}/${t.id}`);
2471
+ if (!e?.session || e.ended || !this.#idle(e.session))
2472
+ continue;
2473
+ moveTask(t, "cancelled");
2474
+ stage(t, "trial", "fail", "stopped: no progress when the grace window opened");
2475
+ sessions.push(e.session);
2476
+ await this.#dropWorktree(e, t);
2477
+ }
2478
+ return sessions;
2479
+ }
2480
+ // What the quality ranking knows about each passed attempt: its cases, cost and the size of its change.
2481
+ async #quality(job, held) {
2482
+ const q = [];
2483
+ const diffs = new Map();
2484
+ for (const t of held) {
2485
+ const e = this.#entries.get(`${job.id}/${t.id}`);
2486
+ let size = 0;
2487
+ if (e && !e.removed) {
2488
+ const stat = await this.#exec("git", ["diff", "--numstat", `${job.integrationBranch}...HEAD`], { cwd: e.worktree });
2489
+ for (const line of stat.stdout.split("\n")) {
2490
+ const [add, del] = line.split("\t");
2491
+ size += (Number(add) || 0) + (Number(del) || 0);
2492
+ }
2493
+ diffs.set(t.id, (await this.#exec("git", ["diff", `${job.integrationBranch}...HEAD`], { cwd: e.worktree })).stdout.slice(0, 30_000));
2494
+ }
2495
+ q.push({ task: t, size, ...(t.graded?.total ? { graded: t.graded.passed / t.graded.total } : {}), ...(t.usage ? { cost: t.usage.cost } : {}) });
2496
+ }
2497
+ return { q, diffs };
2498
+ }
2499
+ // A red team that passed its checks: measured on the visible corpus without its guards (gaming them is the point),
2500
+ // never committed or merged. What it found is in its report.
2501
+ async #redteamDone(entry, job, task) {
2502
+ const c = job.contracts?.find((x) => x.id === task.redteam);
2503
+ let seen = "nothing measured";
2504
+ if (c) {
2505
+ const { measured, seconds } = await runEvaluator(entry.dir, c, "visible", this.#exec, undefined, await this.#entryGate(entry, job, task.role));
2506
+ this.#count(job, c, seconds);
2507
+ if (measured.valid)
2508
+ task.score = { ...measured, corpus: "visible", at: new Date().toISOString() };
2509
+ seen = describe(c, measured);
2510
+ }
2511
+ moveTask(task, "passed");
2512
+ stage(task, "redteam", "pass", seen);
2513
+ saveJob(entry.project, job);
2514
+ return { text: `Measured: ${seen}. Your change is not merged. Now end with your report and one LOOPHOLE line per way you tried, as your brief says.` };
2515
+ }
2516
+ // The trial's deadline, armed once per trial from its first held attempt; after a restart from the time it had.
2517
+ #arm(project, job, head, ms = this.#deadlineMs) {
2518
+ head.settleBy ??= new Date(Date.now() + ms).toISOString();
2519
+ const k = `${job.id}/${head.id}`;
2520
+ if (this.#deadlines.has(k))
2521
+ return;
2522
+ const timer = setTimeout(() => {
2523
+ this.#deadlines.delete(k);
2524
+ this.#settleLater(project, job, head);
2525
+ }, Math.max(0, Date.parse(head.settleBy) - Date.now()));
2526
+ timer.unref?.();
2527
+ this.#deadlines.set(k, timer);
2528
+ }
2529
+ // A settle nobody's finish_task waits for (the deadline, the last attempt failing or ending): its note goes to the
2530
+ // micromanager through onSettled.
2531
+ #settleLater(project, job, head) {
2532
+ void this.#settleQueued(project, job, head, true).then((r) => {
2533
+ if (r)
2534
+ this.#onSettled?.({ project, job, parent: job.facilitator ?? this.#entries.get(`${job.id}/${head.id}`)?.parent ?? "", note: r.note, stop: r.stop, measured: r.measured });
2535
+ }).catch(() => undefined);
2536
+ }
2537
+ // On the job's merge train: one merge at a time, and a trial is decided once.
2538
+ #settleQueued(project, job, head, force) {
2539
+ const train = this.#trains.get(job.id) ?? Promise.resolve();
2540
+ const step = train.then(() => this.#settle(project, job, head, force));
2541
+ this.#trains.set(job.id, step.catch(() => undefined));
2542
+ return step;
2543
+ }
2544
+ // Decides a trial by score once no attempt is at work (or force: the deadline, or every other attempt ended): the
2545
+ // best held attempt is merged, the others are cancelled. The two best are measured again one after the other, so a
2546
+ // machine that was busier during one attempt's measurement does not decide it. One that reached the target wins at
2547
+ // once. When the best cannot be merged (a conflict), the next is tried.
2548
+ async #settle(project, job, head, force) {
2549
+ const mode = pickOf(head);
2550
+ if (mode === "best")
2551
+ return this.#settleBest(project, job, head, force);
2552
+ if (mode === "user")
2553
+ return this.#settleUser(project, job, head);
2554
+ const c = job.contracts?.find((x) => x.id === head.contract?.id);
2555
+ const now = standing(job, head);
2556
+ if (!c || now.winner || !now.held.length)
2557
+ return undefined;
2558
+ const target = now.held.find((t) => reached(c, t.score));
2559
+ if (!force && !target && now.live.length)
2560
+ return undefined;
2561
+ const corpus = c.corpus.heldOut ? "heldout" : "visible";
2562
+ let order = target ? [target, ...ranked(c, now.held).filter((t) => t !== target)] : ranked(c, now.held);
2563
+ if (!target && order.length >= 2) {
2564
+ for (const t of order.slice(0, 2)) {
2565
+ const e = this.#entries.get(`${job.id}/${t.id}`);
2566
+ if (!e || e.removed)
2567
+ continue;
2568
+ const r = await runEvaluator(e.dir, c, corpus, this.#exec, corpus === "heldout" ? heldOutDir(project, job.id, c.id) : undefined, await this.#entryGate(e, job, t.role));
2569
+ this.#count(job, c, r.seconds);
2570
+ t.score = { ...r.measured, corpus, at: new Date().toISOString() };
2571
+ }
2572
+ order = [...ranked(c, order.slice(0, 2)), ...order.slice(2)];
2573
+ }
2574
+ const k = `${job.id}/${head.id}`;
2575
+ for (const cand of order) {
2576
+ const e = this.#entries.get(`${job.id}/${cand.id}`);
2577
+ if (!e || e.removed)
2578
+ continue;
2579
+ const measured = cand.score ? (corpus === "heldout" ? `held-out ${coarse(cand.score)}` : describe(c, cand.score)) : "no score";
2580
+ // Within the noise band the scores do not tell the attempts apart (live run, 2026-10-27: 9.9 against 10.9 ms at
2581
+ // 15 %): the note says so rather than calling one the best.
2582
+ const tied = order.filter((t) => t !== cand && t.score && cand.score && better(c, cand.score, t.score) === 0).map((t) => t.id);
2583
+ const how = tied.length ? `${measured}, tied with ${tied.join(", ")} inside the noise band` : measured;
2584
+ const merged = await this.#merge(e, job, cand);
2585
+ if (!merged.ok) {
2586
+ stage(cand, "trial", "fail", "had the best score but did not merge");
2587
+ continue;
2588
+ }
2589
+ const won = await this.#settleTrial(e, job, cand, how);
2590
+ clearTimeout(this.#deadlines.get(k));
2591
+ this.#deadlines.delete(k);
2592
+ saveJob(project, job);
2593
+ return { winner: cand, note: won.note, stop: won.stop, measured: now.held };
2594
+ }
2595
+ saveJob(project, job);
2596
+ return { note: `${HEADER} The trial of ${head.id} is decided by score, but none of its passed attempts (${order.map((t) => t.id).join(", ")}) merged onto ${job.integrationBranch}: each conflicts with what other tasks merged meanwhile. Continue the best one with the subagent tool and its sessionID to resolve the conflict.`, stop: [], measured: now.held };
2597
+ }
2598
+ // Decides a "best" trial once no attempt is at work (or force: the grace window closed): the passed attempts ranked by
2599
+ // quality (src/trials.ts rankQuality), the best merged, the next tried when it does not merge.
2600
+ async #settleBest(project, job, head, force) {
2601
+ const now = standing(job, head);
2602
+ if (now.winner || !now.held.length)
2603
+ return undefined;
2604
+ if (!force && now.live.length)
2605
+ return undefined;
2606
+ const { q, diffs } = await this.#quality(job, now.held);
2607
+ const review = this.#review
2608
+ ? (a, b) => {
2609
+ const da = diffs.get(a.task.id) ?? "";
2610
+ const db = diffs.get(b.task.id) ?? "";
2611
+ // Near-identical changes need no reviewer: cost and size decide.
2612
+ if (similarity(da, db) >= 0.95)
2613
+ return Promise.resolve(undefined);
2614
+ return this.#review(head, { task: a.task, diff: da }, { task: b.task, diff: db });
2615
+ }
2616
+ : undefined;
2617
+ const ranking = await rankQuality(q, review);
2618
+ const k = `${job.id}/${head.id}`;
2619
+ for (const cand of ranking.order) {
2620
+ const e = this.#entries.get(`${job.id}/${cand.id}`);
2621
+ if (!e || e.removed)
2622
+ continue;
2623
+ const merged = await this.#merge(e, job, cand);
2624
+ if (!merged.ok) {
2625
+ stage(cand, "trial", "fail", "ranked best but did not merge");
2626
+ continue;
2627
+ }
2628
+ const won = await this.#settleTrial(e, job, cand, cand === ranking.order[0] ? ranking.how : "the better ones did not merge", "quality");
2629
+ clearTimeout(this.#deadlines.get(k));
2630
+ this.#deadlines.delete(k);
2631
+ saveJob(project, job);
2632
+ return { winner: cand, note: won.note, stop: won.stop, measured: now.held };
2633
+ }
2634
+ saveJob(project, job);
2635
+ return { note: `${HEADER} The trial of ${head.id} is decided, but none of its passed attempts (${ranking.order.map((t) => t.id).join(", ")}) merged onto ${job.integrationBranch}: each conflicts with what other tasks merged meanwhile. Continue the best one with the subagent tool and its sessionID to resolve the conflict.`, stop: [], measured: now.held };
2636
+ }
2637
+ // A "user" trial once no attempt is at work: the passed ones go on a comparison page, and the micromanager gets the
2638
+ // form to put to the user. Asked once; nothing is decided here (src/pick.ts, pickAnswer).
2639
+ async #settleUser(project, job, head) {
2640
+ const now = standing(job, head);
2641
+ if (now.winner || !now.held.length || now.live.length || head.pickAsked)
2642
+ return undefined;
2643
+ const candidates = [];
2644
+ for (const t of now.held) {
2645
+ const e = this.#entries.get(`${job.id}/${t.id}`);
2646
+ if (!e || e.removed)
2647
+ continue;
2648
+ const stat = await this.#exec("git", ["diff", "--numstat", `${job.integrationBranch}...HEAD`], { cwd: e.worktree });
2649
+ let added = 0;
2650
+ let removed = 0;
2651
+ const files = [];
2652
+ for (const line of stat.stdout.split("\n").filter(Boolean)) {
2653
+ const [a, r, f] = line.split("\t");
2654
+ added += Number(a) || 0;
2655
+ removed += Number(r) || 0;
2656
+ if (f)
2657
+ files.push(f);
2658
+ }
2659
+ const path = t.preview ?? (t.role === "visual" ? defaultPreview(e.dir) : undefined);
2660
+ const shot = path && this.#preview ? await this.#preview(e.dir, path, project, job.id).catch((err) => ({ problem: `No picture: ${String(err)}` })) : undefined;
2661
+ candidates.push({
2662
+ id: t.id, ...(t.model ? { model: t.model } : {}), ...(t.usage ? { cost: t.usage.cost } : {}), lines: { added, removed }, files, ...(t.summary ? { summary: t.summary } : {}),
2663
+ ...(path ? { preview: { path, ...(shot?.png ? { png: shot.png } : {}), ...(shot?.problem ? { problem: shot.problem } : {}) } } : {}),
2664
+ });
2665
+ }
2666
+ const title = head.title.replace(/ \(attempt \d+\/\d+\)$/, "");
2667
+ const page = join(project, stateDir(project), "trials", `${job.id}-${head.id}.html`);
2668
+ mkdirSync(dirname(page), { recursive: true });
2669
+ writeFileSync(page, comparisonPage(head.id, title, candidates));
2670
+ head.pickAsked = new Date().toISOString();
2671
+ stage(head, "trial", "pass", `asked the user to pick among ${candidates.map((c) => c.id).join(", ")}`);
2672
+ saveJob(project, job);
2673
+ this.#notify?.(`Pick a version of ${head.id}`, `${candidates.length} versions of "${title.slice(0, 80)}" passed. Comparison: ${page}`);
2674
+ return { note: pickNote(head.id, title, candidates, page), stop: [], measured: [] };
2675
+ }
2676
+ // The user's answer to a pick form (src/pick.ts): one attempt merged, a combination continued from one of them, or
2677
+ // none of them and the task done over. text: what the micromanager is told; stop and measured as for a settle.
2678
+ async pickAnswer(project, parent, headId, answer) {
2679
+ const job = listJobs(project).map((j) => this.#jobs.get(key(project, j.id)) ?? j).find((j) => j.facilitator === parent && j.tasks.some((t) => t.id === headId));
2680
+ const head = job?.tasks.find((t) => t.id === headId);
2681
+ if (!job || !head?.trial || pickOf(head) !== "user")
2682
+ return { text: `${headId} runs no trial for the user to pick.`, stop: [], measured: [] };
2683
+ this.#jobs.set(key(project, job.id), job);
2684
+ const now = standing(job, head);
2685
+ if (now.winner)
2686
+ return { text: `${now.winner.id} already won the trial of ${headId}.`, stop: [], measured: [] };
2687
+ if (now.live.length || !head.pickAsked)
2688
+ return { text: `Attempts of ${headId} are still at work; the form comes once all have ended.`, stop: [], measured: [] };
2689
+ const ids = now.held.map((t) => t.id);
2690
+ if (answer.kind === "unclear")
2691
+ return { text: `"${answer.said ?? ""}" is no answer to the form; ask with the same form again.`, stop: [], measured: [] };
2692
+ if (answer.kind === "attempt") {
2693
+ const cand = now.held.find((t) => t.id === answer.id);
2694
+ const e = cand && this.#entries.get(`${job.id}/${cand.id}`);
2695
+ if (!cand || !e)
2696
+ return { text: `${answer.id} is not one of the passed attempts (${ids.join(", ")}); ask with the same form again.`, stop: [], measured: [] };
2697
+ const train = this.#trains.get(job.id) ?? Promise.resolve();
2698
+ const step = train.then(() => this.#merge(e, job, cand));
2699
+ this.#trains.set(job.id, step.catch(() => undefined));
2700
+ const merged = await step;
2701
+ if (!merged.ok) {
2702
+ saveJob(project, job);
2703
+ return { text: `The user picked ${cand.id}, but it does not apply on top of ${job.integrationBranch}, which other tasks moved on meanwhile. Continue ${cand.id} with the subagent tool and its sessionID ${e.session ?? "?"} to resolve the conflict; it merges when it passes again.`, stop: [], measured: [] };
2704
+ }
2705
+ const won = await this.#settleTrial(e, job, cand, `picked by the user${answer.notes ? `: ${answer.notes.slice(0, 200)}` : ""}`, "user");
2706
+ saveJob(project, job);
2707
+ return { text: won.note, stop: won.stop, measured: now.held, job };
2708
+ }
2709
+ if (answer.kind === "combine") {
2710
+ const baseId = combineBase(answer.notes, ids);
2711
+ const base = now.held.find((t) => t.id === baseId);
2712
+ const be = this.#entries.get(`${job.id}/${base.id}`);
2713
+ if (!be?.session)
2714
+ return { text: `${base.id} has no session to continue.`, stop: [], measured: [] };
2715
+ const files = [];
2716
+ for (const other of now.held.filter((t) => t !== base)) {
2717
+ const oe = this.#entries.get(`${job.id}/${other.id}`);
2718
+ if (oe && !oe.removed) {
2719
+ const diff = (await this.#exec("git", ["diff", `${job.integrationBranch}...HEAD`], { cwd: oe.worktree })).stdout;
2720
+ const file = join(project, stateDir(project), "trials", `${job.id}-${other.id}.diff`);
2721
+ mkdirSync(dirname(file), { recursive: true });
2722
+ writeFileSync(file, diff);
2723
+ files.push(`${other.id}: ${file}`);
2724
+ await this.#dropWorktree(oe, other);
2725
+ }
2726
+ moveTask(other, "cancelled");
2727
+ other.replacedBy = base.id;
2728
+ stage(other, "trial", "pass", `combined into ${base.id} as the user asked`);
2729
+ }
2730
+ // From here on the base is a task of its own: its next pass merges.
2731
+ base.held = false;
2732
+ for (const t of [base, head])
2733
+ if (t.trial)
2734
+ t.trial.pick = "first";
2735
+ moveTask(base, "escalated");
2736
+ moveTask(base, "running");
2737
+ stage(base, "trial", "pass", `the user asked for a combination: ${(answer.notes ?? "").slice(0, 200)}`);
2738
+ saveJob(project, job);
2739
+ const agent = roleById(base.role)?.agent ?? base.role;
2740
+ return {
2741
+ text: `The user wants a combination${answer.notes ? `: "${answer.notes}"` : ""}. Continue ${base.id} with the subagent tool: agent ${agent}, its sessionID ${be.session}, and a prompt with the user's words and this: "The other version's change is in ${files.join("; ")}. Read it, take the parts the user named into your version, check it with look, and call finish_task." It merges when it passes.`,
2742
+ stop: [], measured: now.held.filter((t) => t !== base), job,
2743
+ };
2744
+ }
2745
+ for (const t of now.held) {
2746
+ const e = this.#entries.get(`${job.id}/${t.id}`);
2747
+ moveTask(t, "cancelled");
2748
+ stage(t, "trial", "pass", "the user picked none of the versions");
2749
+ if (e)
2750
+ await this.#dropWorktree(e, t);
2751
+ }
2752
+ saveJob(project, job);
2753
+ return {
2754
+ text: `The user wants none of the versions of ${head.id}${answer.notes ? `: "${answer.notes}"` : ""}. Write the task down again with the todo tool, "replaces": ["${head.id}"] and the user's words in its brief, and start it: it runs as a new trial, on other models.`,
2755
+ stop: [], measured: now.held, job,
2756
+ };
2757
+ }
2758
+ // The note when a trial's attempt failed: the trial's state (others still run, or all failed); undefined outside one.
2759
+ #trialFailed(job, task, project) {
2760
+ if (!task.trial)
2761
+ return undefined;
2762
+ const now = standing(job, task);
2763
+ if (now.winner)
2764
+ return undefined;
2765
+ if (now.live.length)
2766
+ return attemptFailedText(task, now.live);
2767
+ const head = job.tasks.find((t) => t.id === task.trial.of) ?? task;
2768
+ // Others passed and wait for the decision by score: it is due now, and its note says how it came out.
2769
+ if (now.held.length) {
2770
+ this.#settleLater(project, job, head);
2771
+ return undefined;
2772
+ }
2773
+ return allFailedText(job, head, now.failed);
2774
+ }
2775
+ // One task review behind the "Review per task" switch. A blocking finding goes back to the worker at most twice, like
2776
+ // a failed check; a pool with no family other than the worker's blocks the task rather than letting it review itself.
2777
+ async #taskReview(job, task, entry, session, passedChecksCount = 0) {
2778
+ if (!this.#reviewTask || job.isolation === "plan" || job.isolation === "none")
2779
+ return undefined;
2780
+ const diff = await workingDiff(entry.worktree, this.#exec);
2781
+ if (!diff.trim())
2782
+ return undefined;
2783
+ if (isTrivialLowRiskDiff(task, diff, passedChecksCount)) {
2784
+ stage(task, "review", "pass", "skipped LLM review: trivial low-risk diff verified by deterministic checks");
2785
+ saveJob(entry.project, job);
2786
+ return undefined;
2787
+ }
2788
+ const review = await this.#reviewTask(job, task, entry.dir, diff).catch((err) => ({ model: "", pass: false, blocking: [], error: String(err) }));
2789
+ if (!review)
2790
+ return undefined;
2791
+ if (review.model === "") {
2792
+ moveTask(task, "blocked");
2793
+ stage(task, "review", "fail", review.error ?? "no reviewer");
2794
+ saveJob(entry.project, job);
2795
+ const why = review.error ?? "no reviewer of another family could run";
2796
+ return {
2797
+ text: `No task review could run, so ${task.id} is blocked: ${why}. Nothing was merged.`,
2798
+ note: `[micromanager] ${task.id} ${task.title}: the review switch is on, but ${why}. Add a model of another family to the review pool in the TUI's models pane, then continue it with steer_task and its sessionID ${session}.`,
2799
+ parent: entry.parent,
2800
+ };
2801
+ }
2802
+ if (review.pass) {
2803
+ stage(task, "review", "pass", `by ${review.model}`);
2804
+ saveJob(entry.project, job);
2805
+ return undefined;
2806
+ }
2807
+ const findings = review.blocking.map((c) => `- ${c.point}: ${c.evidence}`).join("\n") || review.error || "the reviewer blocked without a named point";
2808
+ const rounds = task.stages.filter((s) => s.stage === "review" && s.result === "fail").length;
2809
+ stage(task, "review", "fail", `${review.model}: ${findings}`.slice(0, 500));
2810
+ if (rounds >= 2) {
2811
+ moveTask(task, "blocked");
2812
+ saveJob(entry.project, job);
2813
+ return {
2814
+ text: `A reviewer (${review.model}) still blocks ${task.id} after ${rounds + 1} rounds:\n\n${findings}\n\nNothing was merged. If the finding is wrong, say why in your report; otherwise name what remains.`,
2815
+ note: `[micromanager] ${task.id} ${task.title}: its review still blocks after ${rounds + 1} rounds (${findings.slice(0, 300)}). Nothing was merged; decide with the user whether to fix it, change the review, or send it back.`,
2816
+ parent: entry.parent,
2817
+ };
2818
+ }
2819
+ moveTask(task, "fixing");
2820
+ moveTask(task, "running");
2821
+ saveJob(entry.project, job);
2822
+ return {
2823
+ text: `A reviewer (${review.model}) read your change and found ${review.blocking.length || "an"} problem(s):\n\n${findings}${review.fixes?.length ? `\n\nSuggested fixes:\n${review.fixes.map((f) => `- ${f}`).join("\n")}` : ""}\n\nFix them in your task's files, then call finish_task again.`,
2824
+ parent: entry.parent,
2825
+ };
2826
+ }
2827
+ // Rebase onto the session branch, the checks again when it moved, then the fast-forward.
2828
+ async #merge(entry, job, task) {
2829
+ if (job.isolation === "plan")
2830
+ return { ok: false, text: `${task.id} belongs to plan job ${job.id}, which has no branch and nothing to merge.` };
2831
+ // A task in another repository of a workspace merges into that repo's own integration branch.
2832
+ const integ = entry.repo ? job.integrationRepos?.[entry.repo] : undefined;
2833
+ const integrationBranch = integ?.branch ?? job.integrationBranch;
2834
+ const integrationWorktree = integ?.worktree ?? job.integrationWorktree;
2835
+ const v = await validateIntegration(integ ? { ...job, integrationBranch, integrationWorktree, integrationRel: integ.rel } : job, this.#exec, integ ? resolve(entry.project, entry.repo) : entry.project);
2836
+ if (!v.ok) {
2837
+ moveTask(task, "escalated");
2838
+ stage(task, "merge", "fail", v.message);
2839
+ return { ok: false, text: `The integration worktree is not usable (${v.message}). Nothing was merged; report it.` };
2840
+ }
2841
+ const w = { worktree: entry.worktree, branch: entry.branch };
2842
+ // A merge is serialized per job in this process, but the integration branch can still move between the rebase and
2843
+ // the fast-forward (another plugin instance, the user, a second job). A fast-forward that fails while the branch
2844
+ // tip moved is a race, not a conflict: rebase again and retry, at most twice. A real conflict is held open for its
2845
+ // worker (see rebaseTask); anything else escalates with the real error.
2846
+ const tipOf = async () => (await this.#exec("git", ["rev-parse", integrationBranch], { cwd: integrationWorktree })).stdout.trim();
2847
+ let tip = await tipOf();
2848
+ for (let round = 0; round < 3; round++) {
2849
+ const step = await rebaseTask(w, integrationBranch, this.#exec);
2850
+ if (!step.ok) {
2851
+ if (step.files?.length) {
2852
+ // A real conflict is not an escalation: the rebase is open in the task's worktree, the worker resolves the
2853
+ // markers there and its next finish_task continues the rebase and merges. Git writes stay with the plugin.
2854
+ if (task.status === "passed") {
2855
+ moveTask(task, "escalated");
2856
+ moveTask(task, "running");
2857
+ }
2858
+ stage(task, "merge", "fail", step.conflict);
2859
+ return { ok: false, text: conflictHeldText(job, entry, step.files) };
2860
+ }
2861
+ moveTask(task, "escalated");
2862
+ stage(task, "merge", "fail", step.conflict);
2863
+ return { ok: false, text: `The merge into ${job.integrationBranch} failed (${step.conflict}). Nothing was written to the branch. Call finish_task again; if it fails the same way, report it.` };
2864
+ }
2865
+ if (step.moved) {
2866
+ const failed = (await runGate(entry.worktree, entry.checks, this.#exec, this.#checkTimeout(job), entry.dir, {}, await this.#entryGate(entry, job, task.role))).filter((r) => !r.passed);
2867
+ if (failed.length) {
2868
+ moveTask(task, "escalated");
2869
+ stage(task, "merge", "fail", `checks fail on top of the newer commits: ${failed.map((f) => f.command).join(", ")}`);
2870
+ return { ok: false, text: failText(`Your change is rebased onto ${job.integrationBranch}, which other tasks moved on meanwhile, and there the checks fail`, failed, entry.dir) };
2871
+ }
2872
+ // Other tasks' commits can change what the evaluator measures as much as what the checks see.
2873
+ const fitness = await this.#measure(entry, job, task);
2874
+ if (fitness.failed) {
2875
+ moveTask(task, "escalated");
2876
+ stage(task, "merge", "fail", `the fitness contract does not hold on top of the newer commits: ${fitness.failed.output.split("\n")[0]}`);
2877
+ return { ok: false, text: failText(`Your change is rebased onto ${job.integrationBranch}, which other tasks moved on meanwhile, and there the fitness contract does not hold`, [fitness.failed], entry.dir) };
2878
+ }
2879
+ if (fitness.evidence)
2880
+ stage(task, "fitness", "pass", `after the rebase: ${fitness.evidence}`);
2881
+ }
2882
+ const ff = await fastForward(integrationWorktree, entry.branch, this.#exec);
2883
+ if (ff.ok) {
2884
+ moveTask(task, "merged");
2885
+ stage(task, "merge", "pass", `merged into ${job.integrationBranch}`);
2886
+ return { ok: true };
2887
+ }
2888
+ const now = await tipOf();
2889
+ if (round < 2 && now !== tip) {
2890
+ tip = now;
2891
+ stage(task, "merge", "pass", `the branch moved during the merge; rebasing again (${round + 1} of 2)`);
2892
+ continue;
2893
+ }
2894
+ moveTask(task, "escalated");
2895
+ stage(task, "merge", "fail", ff.conflict);
2896
+ return { ok: false, text: `The merge into ${job.integrationBranch} failed (${ff.conflict}). Call finish_task again; if it fails the same way, report it.` };
2897
+ }
2898
+ moveTask(task, "escalated");
2899
+ stage(task, "merge", "fail", "the integration branch kept moving during the merge");
2900
+ return { ok: false, text: `The merge into ${job.integrationBranch} kept losing the race with other work on the branch. Call finish_task again; if it keeps failing, report it.` };
2901
+ }
2902
+ // Waits once per run for a worker's end (wait resolves when its session goes idle).
2903
+ // reason: why the watchdog stopped the worker, if it did.
2904
+ // ended gets the worker's task as it ended too, for the outcome log (src/outcomes.ts).
2905
+ watchEnd(session, wait, reason, ended) {
2906
+ if (this.#waiting.has(session) || !this.#bySession.has(session))
2907
+ return;
2908
+ this.#waiting.add(session);
2909
+ void wait().catch(() => undefined).then(async () => {
2910
+ this.#waiting.delete(session);
2911
+ const r = await this.ended(session, reason());
2912
+ const entry = this.#entry(session);
2913
+ const job = entry && this.#job(entry);
2914
+ const task = job?.tasks.find((t) => t.id === entry.taskId);
2915
+ // A nudge is not an end: the session goes on and its next end is watched again. Do not record an outcome, release
2916
+ // its helpers or mark the session dead here.
2917
+ if (r && !r.nudge && entry && job && task)
2918
+ ended(r.note, r.parent, { project: entry.project, job, task, writer: entry.writer });
2919
+ });
2920
+ }
2921
+ // A worker's run ended: a merged writer's worktree goes, a reader's task is done, and a writer that did not get
2922
+ // through finish_task is reported, with its change still in its worktree. reason: why the watchdog stopped it.
2923
+ async ended(session, reason, report) {
2924
+ const entry = this.#entry(session);
2925
+ const job = entry && this.#job(entry);
2926
+ const task = job?.tasks.find((t) => t.id === entry.taskId);
2927
+ if (!entry || !job || !task)
2928
+ return undefined;
2929
+ // A writer that goes idle with a change and never called finish_task is not necessarily finished, but it is not
2930
+ // abandoned either: one reminder keeps the worktree in play. Only when the plugin can prompt and the stop was not
2931
+ // the watchdog or the user; a second end takes the normal failure path.
2932
+ if (entry.writer && this.#nudge && !entry.nudged && !reason && !task.trial && ["running", "gating", "fixing"].includes(task.status)) {
2933
+ const changed = await changedFiles(entry.worktree, this.#exec, entry.rel);
2934
+ if (changed.length) {
2935
+ entry.nudged = true;
2936
+ stage(task, "nudge", "pass", "ended without finish_task; one reminder sent");
2937
+ this.#onNudge?.(session);
2938
+ saveJob(entry.project, job);
2939
+ this.#nudge(session, "[micromanager] You ended your turn without calling finish_task. If the task is complete, call finish_task now; otherwise report what remains. Do not start over.");
2940
+ return { parent: entry.parent, nudge: true };
2941
+ }
2942
+ }
2943
+ entry.ended = true;
2944
+ let note;
2945
+ if (!entry.writer) {
2946
+ if (task.status === "running") {
2947
+ moveTask(task, "gating");
2948
+ moveTask(task, "passed");
2949
+ stage(task, "report", "pass", "the reader ended");
2950
+ }
2951
+ if (report?.trim())
2952
+ task.summary = report.trim().slice(0, 2000);
2953
+ this.#recordReport(job, task, report ?? task.summary ?? "", false, undefined, "passed");
2954
+ }
2955
+ else if (task.status === "merged") {
2956
+ await this.#dropWorktree(entry, task);
2957
+ }
2958
+ else if (task.status === "passed" && !task.held) {
2959
+ await this.#dropWorktree(entry, task);
2960
+ }
2961
+ else if (task.postGreen) {
2962
+ await this.#dropWorktree(entry, task);
2963
+ if (task.status === "cancelled") {
2964
+ // stop_task cancelled this post-green pass; "cancelled" is terminal (resumable only as "running"), so keep it
2965
+ // and clean up without the illegal move the old code attempted. saveJob below persists the cancellation.
2966
+ }
2967
+ else {
2968
+ this.#settlePassed(task);
2969
+ const why = reason ?? "post-green worker ended without finish_task — kept green baseline";
2970
+ stage(task, "optimize", "skip", why);
2971
+ task.summary = why;
2972
+ this.#recordReport(job, task, why, entry.writer, [], "passed");
2973
+ }
2974
+ }
2975
+ else if (task.trial && task.status === "cancelled") {
2976
+ // Stopped because another attempt won: its work is not needed, and the winner's note said so.
2977
+ await this.#dropWorktree(entry, task);
2978
+ }
2979
+ else if (task.redteam) {
2980
+ // A red team's change is never merged: its worktree goes, its report is what it leaves.
2981
+ await this.#dropWorktree(entry, task);
2982
+ }
2983
+ else if (task.held && task.status === "passed") {
2984
+ // Passed and waiting for its trial to be decided by score: its commit stays in its worktree until then.
2985
+ }
2986
+ else {
2987
+ const blocked = task.status === "blocked";
2988
+ stage(task, "end", "fail", reason ?? "ended without finish_task");
2989
+ // In a trial, finish_task reported a blocked attempt already; one that ended unfinished is a failed attempt.
2990
+ if (task.trial)
2991
+ note = blocked ? undefined : this.#trialFailed(job, task, entry.project);
2992
+ else
2993
+ note = `[micromanager] ${task.id} ${task.title}: its worker ended${reason ? ` (${reason})` : ""} without passing finish_task, so nothing was checked or merged; its change is still in ${entry.dir}. Continue it with the subagent tool and sessionID ${session} to finish, or tell the user.`;
2994
+ }
2995
+ saveJob(entry.project, job);
2996
+ return { note, parent: entry.parent };
2997
+ }
2998
+ // The todo tool: the micromanager writes down the tasks it means to start, as open tasks of its session's job, so the
2999
+ // job file holds the whole list (the sidebar shows it; the continuation names the ready ones). v2 has no todowrite,
3000
+ // and a list kept in the model's context was lost on compaction. Each is started later with "Task: T… · job-…".
3001
+ // The session's rolling job starts with a placeholder goal ("the delegated tasks of micromanager session …"), which
3002
+ // is then copied into every brief and the digest. The first todo or delegation that knows the real goal replaces it;
3003
+ // a goal already set by the user or a plan is never overwritten.
3004
+ #setGoal(project, job, goal) {
3005
+ const text = goal?.trim().replace(/\s+/g, " ");
3006
+ if (!text)
3007
+ return;
3008
+ if (job.goal && !job.goal.startsWith("the delegated tasks of micromanager session"))
3009
+ return;
3010
+ job.goal = text.slice(0, 2000);
3011
+ saveJob(project, job);
3012
+ }
3013
+ todo(project, parent, items, drop, goal) {
3014
+ const job = this.job(project, parent);
3015
+ this.#setGoal(project, job, goal);
3016
+ const errors = [];
3017
+ const added = [];
3018
+ const dropped = [];
3019
+ for (const id of drop) {
3020
+ const task = job.tasks.find((t) => t.id === id);
3021
+ if (!task)
3022
+ errors.push(`${id}: no such task`);
3023
+ else if (!["pending", "ready", "planned"].includes(task.status))
3024
+ errors.push(`${id} is ${task.status}, not an open todo; stop_task stops a running one`);
3025
+ else {
3026
+ moveTask(task, "cancelled");
3027
+ stage(task, "drop", "pass", "dropped from the todo list");
3028
+ dropped.push(id);
3029
+ }
3030
+ }
3031
+ for (const item of items) {
3032
+ const title = item.title?.trim() ?? "";
3033
+ const role = roleByAgent(item.agent ?? "") ?? (item.agent ? undefined : roleByAgent("coder"));
3034
+ if (!title) {
3035
+ errors.push("a todo without a title");
3036
+ continue;
3037
+ }
3038
+ if (!role) {
3039
+ errors.push(`${title}: ${item.agent} is not a role agent (${ROLES.map((r) => r.agent).join(", ")})`);
3040
+ continue;
3041
+ }
3042
+ const writer = WRITERS.has(role.id);
3043
+ const parsed = parseFiles(item.files ?? "", project);
3044
+ if (parsed.problem) {
3045
+ errors.push(`${title}: ${parsed.problem}`);
3046
+ continue;
3047
+ }
3048
+ if (writer && !parsed.files.length) {
3049
+ errors.push(`${title}: a ${role.agent} changes files; give the files it may change`);
3050
+ continue;
3051
+ }
3052
+ if (!writer && parsed.files.length) {
3053
+ errors.push(`${title}: ${role.agent} only reads; leave out files`);
3054
+ continue;
3055
+ }
3056
+ const checks = (item.checks ?? "").split("\n").map((c) => c.trim()).filter(Boolean);
3057
+ // A writer without checks merges on an empty gate (live evidence: job-20261105 T8/T17/T19/T20 merged with no
3058
+ // checks). The rule was enforced on the delegation path only; apply it here too.
3059
+ const bad = writer ? checkSetProblems(checks, true) : checks.length ? checkSetProblems(checks, false) : undefined;
3060
+ if (bad) {
3061
+ errors.push(`${title}: ${bad}`);
3062
+ continue;
3063
+ }
3064
+ const cwdProblem = checks.map((c) => checkCwdProblem(c, project, project, project)).find(Boolean);
3065
+ if (cwdProblem) {
3066
+ errors.push(`${title}: ${cwdProblem}`);
3067
+ continue;
3068
+ }
3069
+ const replaces = item.replaces ?? [];
3070
+ const cannot = this.#replaceable(project, job, replaces);
3071
+ if (cannot.length) {
3072
+ errors.push(`${title}: ${cannot.join("; ")}`);
3073
+ continue;
3074
+ }
3075
+ const duplicate = this.#duplicate(job, role, title, item.brief?.trim() || title, parsed.files, replaces);
3076
+ if (duplicate) {
3077
+ errors.push(`${title}: ${duplicate.replace(/^Not started: /, "")}`);
3078
+ continue;
3079
+ }
3080
+ const after = (item.after ?? []).map((id) => id.trim().toUpperCase()).filter(Boolean);
3081
+ const unknown = after.filter((id) => !job.tasks.some((t) => t.id === id));
3082
+ if (unknown.length) {
3083
+ errors.push(`${title}: no task ${unknown.join(", ")} to wait for`);
3084
+ continue;
3085
+ }
3086
+ if (item.contract && !writer) {
3087
+ errors.push(`${title}: ${role.agent} only reads; a fitness contract measures a writer's work`);
3088
+ continue;
3089
+ }
3090
+ if (item.contract && !job.contracts?.some((c) => c.id === item.contract)) {
3091
+ errors.push(`${title}: job ${job.id} has no contract ${item.contract}; define it with the contract tool first`);
3092
+ continue;
3093
+ }
3094
+ const result = addDelegated(job, { title, prompt: item.brief?.trim() || title, files: parsed.files, dependsOn: after, checks });
3095
+ if (!result.task) {
3096
+ errors.push(`${title}: ${result.errors.join("; ")}`);
3097
+ continue;
3098
+ }
3099
+ this.#bind(job, result.task, item.contract);
3100
+ const freeze = item.frozen ? parseFiles(item.frozen, project) : undefined;
3101
+ if (freeze?.problem)
3102
+ errors.push(`${title}: frozen ${freeze.problem}`);
3103
+ else if (freeze?.files.length)
3104
+ result.task.freeze = freeze.files;
3105
+ this.#link(project, job, result.task, replaces);
3106
+ result.task.role = role.id;
3107
+ stage(result.task, "todo", "pass", "written down by the micromanager");
3108
+ added.push(result.task);
3109
+ }
3110
+ if (added.length || dropped.length)
3111
+ saveJob(project, job);
3112
+ return { job, added, dropped, errors };
3113
+ }
3114
+ // The job a worker works for, as this process holds it.
3115
+ jobOf(session) {
3116
+ const entry = this.#entry(session);
3117
+ const job = entry && this.#job(entry);
3118
+ return entry && job ? { project: entry.project, job } : undefined;
3119
+ }
3120
+ // The live worker that works in a directory (a shell command's cwd: its own directory or below), for the sandbox
3121
+ // The sandbox (src/shell/sandbox.ts). The deepest match wins, so a writer's worktree beats the job's integration worktree it lies in.
3122
+ workerAt(cwd) {
3123
+ const inside = (dir) => cwd === dir || cwd.startsWith(`${dir}/`);
3124
+ const found = [...this.#entries.values()]
3125
+ .filter((e) => !e.ended && (inside(e.dir) || inside(e.worktree)))
3126
+ .sort((a, b) => b.dir.length - a.dir.length)[0];
3127
+ return found && this.#task(found) ? this.#facts(found) : undefined;
3128
+ }
3129
+ // The live worker of a session, for the sandbox (src/shell/): the session that asked for the shell is known there,
3130
+ // while the shell hook itself gets no session id. The same facts as workerAt, but by session instead of by directory.
3131
+ workerBySession(session) {
3132
+ const found = this.#entry(session);
3133
+ if (!found || found.ended || !found.session)
3134
+ return undefined;
3135
+ return this.#task(found) ? this.#facts(found) : undefined;
3136
+ }
3137
+ #task(entry) {
3138
+ return this.#job(entry)?.tasks.find((t) => t.id === entry.taskId);
3139
+ }
3140
+ #facts(entry) {
3141
+ const task = this.#task(entry);
3142
+ return {
3143
+ project: entry.project,
3144
+ jobId: entry.jobId,
3145
+ role: task.role,
3146
+ writer: entry.writer,
3147
+ dir: entry.dir,
3148
+ worktree: entry.worktree,
3149
+ frozen: entry.writer && entry.frozen ? [...entry.frozen.keys()].map((f) => resolve(entry.dir, f)) : [],
3150
+ plan: this.#job(entry)?.isolation === "plan",
3151
+ };
3152
+ }
3153
+ // The workers of a micromanager session that still run.
3154
+ running(parent) {
3155
+ return [...this.#entries.values()]
3156
+ .filter((e) => e.parent === parent && e.session && !e.ended)
3157
+ .filter((e) => ["running", "gating", "fixing"].includes(this.#job(e)?.tasks.find((t) => t.id === e.taskId)?.status ?? ""))
3158
+ .map((e) => ({ session: e.session, task: e.taskId }));
3159
+ }
3160
+ #entry(session) {
3161
+ const k = this.#bySession.get(session);
3162
+ return k ? this.#entries.get(k) : undefined;
3163
+ }
3164
+ #job(entry) {
3165
+ return this.#jobs.get(key(entry.project, entry.jobId));
3166
+ }
3167
+ async #dropWorktree(entry, task) {
3168
+ if (!entry.writer || entry.removed)
3169
+ return;
3170
+ const job = this.#job(entry);
3171
+ if (job?.isolation === "plan") {
3172
+ // A plan job's worktree is its own: a git worktree (with a branch) goes through the plan removal; a copy of the
3173
+ // project has no branch, and only a directory that really lies in this job's plan area is ever removed.
3174
+ if (entry.branch) {
3175
+ await removePlanWorktree(entry.project, { worktree: entry.worktree, branch: entry.branch }, this.#exec);
3176
+ }
3177
+ else {
3178
+ const area = resolve(planArea(entry.project, job.id));
3179
+ const target = resolve(entry.worktree);
3180
+ if (target !== area && !target.startsWith(`${area}${sep}`))
3181
+ return;
3182
+ rmSync(entry.worktree, { recursive: true, force: true });
3183
+ }
3184
+ entry.removed = true;
3185
+ if (task) {
3186
+ task.worktree = undefined;
3187
+ task.branch = undefined;
3188
+ }
3189
+ return;
3190
+ }
3191
+ if (!entry.branch)
3192
+ return;
3193
+ await removeTaskWorktree(entry.project, { worktree: entry.worktree, branch: entry.branch }, this.#exec);
3194
+ entry.removed = true;
3195
+ if (task) {
3196
+ task.worktree = undefined;
3197
+ task.branch = undefined;
3198
+ }
3199
+ }
3200
+ #brief(job, task, role, model, d, entry, graph) {
3201
+ const skills = [...(entry.writer ? ["verification-before-completion"] : []), ...(role.id === "research" ? ["research"] : [])].filter((s) => this.#skills.has(s));
3202
+ const others = job.tasks.filter((t) => t.id !== task.id && ["running", "gating", "fixing"].includes(t.status));
3203
+ // The context a worker needs to reuse instead of rewriting: why the job exists, what is already merged, what earlier
3204
+ // workers learned, and what "done" means for this task. Planned jobs get goal/decisions/acceptance from
3205
+ // #plannedBody; rolling jobs (the todo path) got none of it.
3206
+ const finished = job.tasks.filter((t) => t.id !== task.id && (t.status === "merged" || t.status === "passed"));
3207
+ const doneLine = finished.length
3208
+ ? `Already done (${finished.length}): ${finished.slice(-8).map((t) => `${t.id} ${t.title}${t.commit ? ` (${t.commit})` : ""}${t.status === "passed" ? " [read-only]" : ""}`).join("; ")}${finished.length > 8 ? `; … and ${finished.length - 8} more` : ""}`
3209
+ : "";
3210
+ const lessonsLine = job.lessons.length ? `Learned earlier in this job: ${job.lessons.slice(-5).join("; ")}` : "";
3211
+ const acceptance = taskAcceptance(job, task).slice(0, 4);
3212
+ const handoffs = upstreamHandoffs(job, task);
3213
+ const rollingContext = job.rolling
3214
+ ? [
3215
+ `The job: ${job.goal}`,
3216
+ "",
3217
+ `Your task (${task.id}): ${task.title}`,
3218
+ d.planned ? "" : verbatimGoalLine(job.goal),
3219
+ d.planned ? "" : handoffs,
3220
+ !d.planned && task.postGreen ? POST_GREEN_DIRECTIVE : "",
3221
+ job.decisions.length ? `Decisions that apply: ${job.decisions.slice(-5).map((x) => x.text).join("; ")}` : "",
3222
+ acceptance.length ? `Acceptance points: ${acceptance.map((a) => `${a.id}: ${a.text}${a.verify ? ` (checked with: ${a.verify})` : ""}`).join("; ")}` : "",
3223
+ ].filter((line, idx) => line !== "" || idx === 1)
3224
+ : [];
3225
+ return [
3226
+ `${HEADER} task ${task.id} · job ${job.id} · role ${role.id} · model ${model}`,
3227
+ entry.repo ? `Repository: ${entry.repo} (this task's own repository inside the workspace, not the job's checkout).` : "",
3228
+ "",
3229
+ ...rollingContext,
3230
+ doneLine,
3231
+ lessonsLine,
3232
+ "",
3233
+ d.body,
3234
+ "",
3235
+ attemptBrief(task),
3236
+ "",
3237
+ graph ? graphBrief(graph) : "",
3238
+ "",
3239
+ entry.writer ? `Files you may change: ${task.files.join(", ")}. Work only in your current directory, ${job.isolation === "none" ? "the project folder itself (it has no git, so change nothing beyond your files)" : "a git worktree of its own"}.` : "Change no files.",
3240
+ // A worktree is a checkout of the repository root, so a project that is a subdirectory sits below it. Saying so
3241
+ // keeps a worker from concluding its premise is false when a path of its own does not resolve at the top.
3242
+ entry.rel ? `Your directory ${entry.dir} is the project directory inside the worktree ${entry.worktree}; the worktree holds the whole repository (${entry.rel} below its root). Every path you read or write is relative to your own directory, never to the worktree root.` : "",
3243
+ entry.repo ? `This task works in the workspace repository ${entry.repo}; your directory ${entry.dir} is that repository's worktree root. Every path is relative to your directory, not the workspace folder.` : "",
3244
+ dirtyNote(job, entry.writer),
3245
+ entry.writer
3246
+ ? entry.checks.length
3247
+ ? `Checks the plugin runs when you finish: ${entry.checks.join("; ")}`
3248
+ : "No checks were given: test your change yourself as far as you can."
3249
+ : "",
3250
+ entry.contract && !task.redteam && job.contracts?.find((c) => c.id === entry.contract) ? contractBrief(job.contracts.find((c) => c.id === entry.contract)) : "",
3251
+ entry.frozen?.size ? `Frozen, so read and run them but do not change them (the plugin puts them back and counts it as a failing check): ${[...entry.frozen.keys()].join(", ")}.` : "",
3252
+ entry.writer ? "If a check or a frozen test is itself wrong (a path that does not exist, a typo, a test that contradicts the task), do not work around it: ask with request_check_change ({ kind: \"check_bug\" | \"test_contradicts_spec\" | \"spec_incomplete\" | \"contract\", target: the check command or file, problem, evidence: the output or spec line that shows it, proposal: the new command or a unified diff }), inside the execute tool. Someone else decides; it waits for the answer. Twice per task at most, and a refused change stays refused." : "",
3253
+ others.length ? `Other workers change other files at the same time (not yours): ${others.map((t) => `${t.id} ${t.title}`).join("; ")}` : "",
3254
+ "Keys and tokens show as <secret> in what you read; never write <secret> into a file, leave such lines as they are.",
3255
+ // The sandbox's limits, and how to ask past them (src/grants.ts).
3256
+ entry.writer || role.id === "research"
3257
+ ? "Your shell commands run in a sandbox with a cleaned environment that reaches the package registries only. If a command fails because a variable is not set, ask for it with request_env; if it cannot reach a host, with request_network. Never set a missing variable yourself with a value you made up: the real value is the user's, and an invented one only makes a check pass that proves nothing. Both are called inside the execute tool, e.g. `await tools.request_env({ name: \"DATABASE_URL\", why: \"…\" })`, and wait until they are decided."
3258
+ : "Your shell commands run in a sandbox with a cleaned environment. If a command fails because a variable is not set, ask for it with request_env (never set it yourself with a value you made up), inside the execute tool: `await tools.request_env({ name: \"…\", why: \"…\" })`; it waits until it is decided.",
3259
+ skillLine(skills),
3260
+ "",
3261
+ entry.writer
3262
+ ? "Two helpers answer questions while you wait: explore (an explorer reads your directory, your change included) and research (a researcher looks it up on the web). Ask one when a question would take you many reads or needs documentation you cannot reach; at most 3 per task. Like finish_task, they are called inside the execute tool: `await tools.explore({ question: \"…\" })`."
3263
+ : "",
3264
+ entry.writer
3265
+ ? `When your change is done, call finish_task with a two-line summary, inside the execute tool: \`await tools.finish_task({ summary: "…" })\`. The plugin then runs the checks, commits and merges; if it answers with failures, fix them and call finish_task again. Once it says merged, end with a short report: what you changed, what the checks showed, anything left open. ${FOLLOWUP_LINE}`
3266
+ : `End with your findings: they are your result. ${FOLLOWUP_LINE}`,
3267
+ ].filter((line, i, all) => line !== "" || all[i - 1] !== "").join("\n").trim();
3268
+ }
3269
+ }
3270
+ // How a worker reports work outside its task, so the plugin can keep it (src/brief.ts parseReport reads these lines).
3271
+ const FOLLOWUP_LINE = "Name work you noticed outside your task that the project needs, one line each, as FOLLOWUP: what | why | the files it would change (leave it out if none).";
3272
+ // A planned task on its way to a worker, from wherever it stopped: open, given up, stopped, left running by a process
3273
+ // that ended, or cancelled by a sweep. Cancelled is final for the state machine, so a task started again on purpose
3274
+ // goes back to pending first.
3275
+ function restart(task) {
3276
+ if (task.status === "cancelled") {
3277
+ task.status = "pending";
3278
+ stage(task, "restart", "pass", "started again by the micromanager");
3279
+ }
3280
+ if (LIVE.has(task.status))
3281
+ moveTask(task, "escalated");
3282
+ if (task.status === "blocked")
3283
+ moveTask(task, "running");
3284
+ if (task.status === "escalated")
3285
+ moveTask(task, "running");
3286
+ if (task.status === "pending")
3287
+ moveTask(task, "ready");
3288
+ if (task.status === "ready")
3289
+ moveTask(task, "planned");
3290
+ if (task.status === "planned")
3291
+ moveTask(task, "running");
3292
+ }
3293
+ function key(project, job) {
3294
+ return `${project}\0${job}`;
3295
+ }
3296
+ // A worktree starts from the last commit, so the user's uncommitted work is not in it. A worker told this fails far more
3297
+ // gracefully than one that spends a session discovering its premise cannot hold.
3298
+ function dirtyNote(job, writer) {
3299
+ if (!job.integrationDirty)
3300
+ return "";
3301
+ return writer
3302
+ ? `The working tree of the project has uncommitted changes that this worktree does not have (${job.integrationDirty}); the worktree is a checkout of the last commit. Do not try to read them: say so in your report if your task depends on them.`
3303
+ : `The working tree of the project has uncommitted changes that this worktree does not have (${job.integrationDirty}); what you read here is the last commit. Say so if your question depends on them.`;
3304
+ }
3305
+ // What an attempt hears when another attempt of its trial won first.
3306
+ function lostText(job, task) {
3307
+ return `${task.replacedBy ?? "Another attempt"} of this trial merged into ${job.integrationBranch} first, so your work is not needed and nothing of it is merged. Stop now and end with a one-line report; add a LEARNED line if your attempt found something worth knowing.`;
3308
+ }
3309
+ // A conflicted merge train step is not a failure of the worker: the plugin leaves the rebase open in the worker's own
3310
+ // worktree and the files carry the conflict markers. All git writes stay with the plugin, because a writer's sandbox
3311
+ // can change files in its worktree but not the repository's .git (the index there is read-only). "Run git rebase", the
3312
+ // old advice, was a command the worker could never follow; this is the instruction it can follow.
3313
+ function conflictHeldText(job, entry, files) {
3314
+ const shown = files.map((f) => relative(entry.dir, resolve(entry.worktree, f)).split(sep).join("/") || f);
3315
+ const list = shown.join(", ");
3316
+ return [
3317
+ `Your commit does not apply on top of ${job.integrationBranch}, which other tasks moved on meanwhile (conflict in ${list}).`,
3318
+ `I started the rebase and left it open in your directory: ${shown.length === 1 ? "that file carries" : "those files carry"} the usual <<<<<<< / ======= / >>>>>>> markers.`,
3319
+ `Resolve them by editing the files so both changes survive. Do not run git: your sandbox can change files but not git state. \`git show ${job.integrationBranch}:<path>\` is read-only and works if you need the other side.`,
3320
+ `Then call finish_task again: I stage the files, finish the rebase, run the checks and merge.`,
3321
+ ].join("\n\n");
3322
+ }
3323
+ // "<job>/<task>" from a brief's header line.
3324
+ function tokenOf(text) {
3325
+ const m = text.match(/\[micromanager\] task (T\d+) · job (\S+) ·/);
3326
+ return m ? `${m[2]}/${m[1]}` : undefined;
3327
+ }
3328
+ // The directory is in the text: a check that says "No such file or directory" only makes sense next to the cwd it ran
3329
+ // in, and that was the one diagnostic missing when a worker hunted for a file three directories up.
3330
+ function failText(what, failed, dir) {
3331
+ return `${what}. Fix them, then call finish_task again:\n${failed.map((f) => `$ ${f.command} (exit ${f.code})\n${f.output}`).join("\n\n")}\n\nThe checks ran in ${dir}; a path in them is relative to that directory.`;
3332
+ }
3333
+ // The existing files a shell command names, project-relative: "node --test test/a.test.js" names test/a.test.js. A
3334
+ // word that is no path, or no file in dir, is left out; a check names a file it reads far more often than one it
3335
+ // writes, and one it would write does not exist yet.
3336
+ export function namedFiles(command, dir) {
3337
+ return [...new Set(command.split(/[\s;|&()<>=]+/).map((w) => w.replace(/^['"]+|['"]+$/g, "")))]
3338
+ .filter((w) => /^[\w./@+-]+$/.test(w) && /[./]/.test(w) && !w.startsWith("-") && !w.startsWith("/") && !w.split("/").includes(".."))
3339
+ .map((w) => w.replace(/^\.\//, ""))
3340
+ .filter((w) => {
3341
+ try {
3342
+ return statSync(join(dir, w)).isFile();
3343
+ }
3344
+ catch {
3345
+ return false;
3346
+ }
3347
+ });
3348
+ }