@omacode/micromanager 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +27 -2
- package/evolver/mm_evolve/__init__.py +1 -0
- package/evolver/mm_evolve/entry.py +3 -0
- package/evolver/mm_evolve/evaluator.py +119 -0
- package/evolver/mm_evolve/llm.py +76 -0
- package/evolver/mm_evolve/run.py +89 -0
- package/evolver/mm_evolve/spec.py +62 -0
- package/evolver/pyproject.toml +21 -0
- package/evolver/uv.lock +772 -0
- package/package.json +55 -4
- package/skills/THIRD_PARTY.md +58 -0
- package/skills/code-review/SKILL.md +46 -0
- package/skills/deliberate/SKILL.md +39 -0
- package/skills/diagnosing-bugs/SKILL.md +75 -0
- package/skills/receiving-code-review/SKILL.md +36 -0
- package/skills/research/SKILL.md +18 -0
- package/skills/tdd/SKILL.md +56 -0
- package/skills/tdd/mocking.md +59 -0
- package/skills/tdd/tests.md +77 -0
- package/skills/verification-before-completion/SKILL.md +50 -0
- package/src/agenda.ts +56 -0
- package/src/agents.ts +74 -0
- package/src/ask.ts +243 -0
- package/src/backends.ts +144 -0
- package/src/backlog.ts +436 -0
- package/src/bench.ts +163 -0
- package/src/board.ts +1 -0
- package/src/brief.ts +151 -0
- package/src/browser.ts +624 -0
- package/src/budget.ts +73 -0
- package/src/catalog.ts +214 -0
- package/src/checkchange.ts +180 -0
- package/src/checkpoint.ts +99 -0
- package/src/cli.ts +117 -0
- package/src/compact.ts +162 -0
- package/src/config.ts +340 -0
- package/src/context/capture.ts +1 -0
- package/src/context/digest.ts +1 -0
- package/src/context/embed.ts +1 -0
- package/src/context/index.ts +2 -0
- package/src/context/ledger.ts +1 -0
- package/src/context/manager.ts +1 -0
- package/src/context/memory.ts +1 -0
- package/src/context/policy.ts +1 -0
- package/src/context/prices.ts +1 -0
- package/src/context/recall.ts +1 -0
- package/src/context/rules.ts +1 -0
- package/src/context/search.ts +1 -0
- package/src/context/status.ts +1 -0
- package/src/context/store.ts +1 -0
- package/src/context/summary.ts +1 -0
- package/src/context/tokens.ts +1 -0
- package/src/context/tools.ts +1 -0
- package/src/continuation.ts +122 -0
- package/src/contract.ts +342 -0
- package/src/contractround.ts +225 -0
- package/src/control.ts +1 -0
- package/src/dataset.ts +133 -0
- package/src/decide.ts +690 -0
- package/src/eval.ts +66 -0
- package/src/evolver.ts +369 -0
- package/src/followups.ts +50 -0
- package/src/forms.ts +191 -0
- package/src/gate.ts +90 -0
- package/src/grants.ts +239 -0
- package/src/graph.ts +74 -0
- package/src/guard/index.ts +1 -0
- package/src/guard/wire.ts +1 -0
- package/src/helpers.ts +105 -0
- package/src/hooks.ts +199 -0
- package/src/integration.ts +4 -0
- package/src/jev.ts +141 -0
- package/src/journal.ts +1 -0
- package/src/look.ts +390 -0
- package/src/memory.ts +1 -0
- package/src/native.ts +2455 -0
- package/src/nogit.ts +112 -0
- package/src/outcomes.ts +210 -0
- package/src/pick.ts +112 -0
- package/src/pipelines.ts +252 -0
- package/src/plan.ts +449 -0
- package/src/plugin.ts +3187 -0
- package/src/policy.ts +84 -0
- package/src/pools.ts +1 -0
- package/src/profile.ts +186 -0
- package/src/progress.ts +1 -0
- package/src/redact.ts +1 -0
- package/src/registry.ts +207 -0
- package/src/roles.ts +1 -0
- package/src/routing.ts +1 -0
- package/src/runner.ts +1506 -0
- package/src/sandbox.ts +4 -0
- package/src/scheduler.ts +200 -0
- package/src/session.ts +269 -0
- package/src/shell/decide.ts +1 -0
- package/src/shell/index.ts +2 -0
- package/src/shell/sandbox.ts +1 -0
- package/src/shell/wire.ts +1 -0
- package/src/skills.ts +111 -0
- package/src/state.ts +1 -0
- package/src/store.ts +1 -0
- package/src/switcher.ts +1 -0
- package/src/tools.ts +480 -0
- package/src/trials.ts +247 -0
- package/src/usage.ts +1 -0
- package/src/wait.ts +180 -0
- package/src/watchdog.ts +498 -0
- package/src/worktree/git.ts +378 -0
package/src/native.ts
ADDED
|
@@ -0,0 +1,2455 @@
|
|
|
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
|
+
|
|
16
|
+
import { existsSync, mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs"
|
|
17
|
+
import { tmpdir } from "node:os"
|
|
18
|
+
import { dirname, isAbsolute, join, resolve } from "node:path"
|
|
19
|
+
|
|
20
|
+
import { Graphs, graphBrief, queryGraph, type Graph } from "./graph.ts"
|
|
21
|
+
import { HEADER } from "./hooks.ts"
|
|
22
|
+
import { better, coarse, contractBrief, describe, guardViolations, heldOutDir, keepHeldOut, median, parseContract, reached, type Contract, type Measured } from "./contract.ts"
|
|
23
|
+
import {
|
|
24
|
+
changedFiles, checkTimeoutOf, commitTask, dirtyDeclared, dirtyPaths, exec as defaultExec, fastForward, frozenChanged, gradedOf, hashFiles, IntegrationError, prepareIntegration, prepareTaskWorktree, rebaseTask, removeTaskWorktree, validateIntegration,
|
|
25
|
+
repoRel, revertFiles, runEvaluator, runGate, taskDir,
|
|
26
|
+
type Exec, type GateResult,
|
|
27
|
+
} from "./worktree/git.ts"
|
|
28
|
+
import { addDelegated, checkSetProblems, parseFiles } from "./plan.ts"
|
|
29
|
+
import { WRITERS } from "./profile.ts"
|
|
30
|
+
import { FIX_ROUNDS } from "./watchdog.ts"
|
|
31
|
+
import { ROLES, roleByAgent, roleById, type Role, type RoleId } from "./roles.ts"
|
|
32
|
+
import { isDone, moveTask, newJob, moveJob, stage, type Job, type Later, type Task } from "./state.ts"
|
|
33
|
+
import { excludeFromGit, jobId, listJobs, saveContract, saveJob, stateDir } from "./store.ts"
|
|
34
|
+
import { combineBase, comparisonPage, pickNote, type Candidate, type PickAnswer } from "./pick.ts"
|
|
35
|
+
import { chargeTask } from "./budget.ts"
|
|
36
|
+
import { draftFromLater, draftFromTrial, localBackend, type BacklogBackend, type BacklogItem } from "./backlog.ts"
|
|
37
|
+
import { normalTarget, type ChangeAnswer, type ChangeKind } from "./checkchange.ts"
|
|
38
|
+
import { applyPrefs, askWith, baselineForm, draftPrompt, loopholeForm, parseLoopholes, prefsForm, redteamPrompt, type Prefs } from "./contractround.ts"
|
|
39
|
+
import { parseReport, sharedNote, skillLine, taskAcceptance } from "./brief.ts"
|
|
40
|
+
import { settled, startable } from "./continuation.ts"
|
|
41
|
+
import { isStarted, lastOptions, loadControl, optionsOf } from "./control.ts"
|
|
42
|
+
import { formInput, startForm } from "./forms.ts"
|
|
43
|
+
import { estimate, EVOLVER_MAX_EVAL_S, evolverFits, evolverForm } from "./evolver.ts"
|
|
44
|
+
import { gitState } from "./nogit.ts"
|
|
45
|
+
import { allFailedText, attemptBrief, attemptFailedText, attempts, DEFAULT_GRACE, DEFAULT_PICK, fanOutText, graceMs, pickFor, pickOf, rankQuality, ranked, standing, wonText, type Assessment, type Grace, type Pick as TrialPick, type Quality, type Review } from "./trials.ts"
|
|
46
|
+
|
|
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
|
+
|
|
50
|
+
export class DelegationError extends Error {}
|
|
51
|
+
|
|
52
|
+
export interface Delegation {
|
|
53
|
+
readonly body: string // the prompt without the Files, Checks, Replaces and Task lines
|
|
54
|
+
readonly files: string // as written, parsed by parseFiles
|
|
55
|
+
readonly checks: string[]
|
|
56
|
+
readonly replaces: string[] // tasks this one deliberately starts over ("Replaces: T5")
|
|
57
|
+
readonly planned?: { readonly task: string; readonly job: string } // a planned task to start ("Task: T5 · job-…")
|
|
58
|
+
readonly attempt?: { readonly task: string; readonly job: string } // another attempt of a trial ("Attempt: T5 · job-…")
|
|
59
|
+
readonly contract?: string // the fitness contract its work is measured against ("Contract: C1", src/contract.ts)
|
|
60
|
+
readonly frozen?: string // files it may read and run but not change, as written ("Frozen: test/a.test.js")
|
|
61
|
+
readonly redteam?: { readonly contract: string; readonly job: string } // a contract's red team ("Red team: C1 · job-…")
|
|
62
|
+
readonly method?: "worker" | "trial" | "evolver" // how the user chose to have it done ("Method: trial", src/evolver.ts)
|
|
63
|
+
readonly pick?: "first" | "best" | "user" // who decides its trial ("Pick: me", src/trials.ts)
|
|
64
|
+
readonly preview?: string // the page that shows its result ("Preview: dist/index.html", src/pick.ts)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// The "Files:" and "Checks:" lines of a delegation, wherever they stand; the checks go on over the following lines
|
|
68
|
+
// until a blank line or another such line.
|
|
69
|
+
export function parseDelegation(prompt: string): Delegation {
|
|
70
|
+
const body: string[] = []
|
|
71
|
+
const checks: string[] = []
|
|
72
|
+
const replaces: string[] = []
|
|
73
|
+
let files = ""
|
|
74
|
+
let frozen = ""
|
|
75
|
+
let planned: Delegation["planned"]
|
|
76
|
+
let attempt: Delegation["attempt"]
|
|
77
|
+
let contract: string | undefined
|
|
78
|
+
let redteam: Delegation["redteam"]
|
|
79
|
+
let method: Delegation["method"]
|
|
80
|
+
let pick: Delegation["pick"]
|
|
81
|
+
let preview: string | undefined
|
|
82
|
+
let inChecks = false
|
|
83
|
+
for (const line of prompt.split("\n")) {
|
|
84
|
+
const pv = line.match(/^\s*preview:\s*(\S.*?)\s*$/i)
|
|
85
|
+
if (pv) {
|
|
86
|
+
preview = pv[1]!
|
|
87
|
+
inChecks = false
|
|
88
|
+
continue
|
|
89
|
+
}
|
|
90
|
+
const pk = line.match(/^\s*pick:\s*(me|user|best|first)\s*$/i)
|
|
91
|
+
if (pk) {
|
|
92
|
+
const v = pk[1]!.toLowerCase()
|
|
93
|
+
pick = v === "me" ? "user" : (v as Delegation["pick"])
|
|
94
|
+
inChecks = false
|
|
95
|
+
continue
|
|
96
|
+
}
|
|
97
|
+
const mt = line.match(/^\s*method:\s*(worker|trial|evolver)\s*$/i)
|
|
98
|
+
if (mt) {
|
|
99
|
+
method = mt[1]!.toLowerCase() as Delegation["method"]
|
|
100
|
+
inChecks = false
|
|
101
|
+
continue
|
|
102
|
+
}
|
|
103
|
+
const rt = line.match(/^\s*red team:\s*(C\d+)\s*·\s*(job-[\w-]+)\s*$/i)
|
|
104
|
+
if (rt) {
|
|
105
|
+
redteam = { contract: rt[1]!.toUpperCase(), job: rt[2]! }
|
|
106
|
+
inChecks = false
|
|
107
|
+
continue
|
|
108
|
+
}
|
|
109
|
+
const k = line.match(/^\s*contract:\s*(C\d+)\s*$/i)
|
|
110
|
+
if (k) {
|
|
111
|
+
contract = k[1]!.toUpperCase()
|
|
112
|
+
inChecks = false
|
|
113
|
+
continue
|
|
114
|
+
}
|
|
115
|
+
// The line the plugin hands out for a trial's other attempts (src/trials.ts attemptLine).
|
|
116
|
+
const a = line.match(/^\s*attempt:\s*(T\d+(?:\.\w+)*)\s*·\s*(job-[\w-]+)\s*$/i)
|
|
117
|
+
if (a) {
|
|
118
|
+
attempt = { task: a[1]!.toUpperCase(), job: a[2]! }
|
|
119
|
+
inChecks = false
|
|
120
|
+
continue
|
|
121
|
+
}
|
|
122
|
+
// Only the exact form run_job hands out (src/continuation.ts plannedLine): a prompt's own "Task: …" stays prose.
|
|
123
|
+
const t = line.match(/^\s*task:\s*(T\d+(?:\.\w+)*)\s*·\s*(job-[\w-]+)\s*$/i)
|
|
124
|
+
if (t) {
|
|
125
|
+
planned = { task: t[1]!.toUpperCase(), job: t[2]! }
|
|
126
|
+
inChecks = false
|
|
127
|
+
continue
|
|
128
|
+
}
|
|
129
|
+
const z = line.match(/^\s*frozen:\s*(.*)$/i)
|
|
130
|
+
if (z) {
|
|
131
|
+
frozen = z[1]!.trim()
|
|
132
|
+
inChecks = false
|
|
133
|
+
continue
|
|
134
|
+
}
|
|
135
|
+
const f = line.match(/^\s*files:\s*(.*)$/i)
|
|
136
|
+
const c = line.match(/^\s*checks:\s*(.*)$/i)
|
|
137
|
+
const r = line.match(/^\s*replaces:\s*(.*)$/i)
|
|
138
|
+
if (r) {
|
|
139
|
+
replaces.push(...replaceIds(r[1]))
|
|
140
|
+
inChecks = false
|
|
141
|
+
} else if (f) {
|
|
142
|
+
files = f[1]!.trim()
|
|
143
|
+
inChecks = false
|
|
144
|
+
} else if (c) {
|
|
145
|
+
inChecks = true
|
|
146
|
+
if (c[1]!.trim()) checks.push(c[1]!.trim())
|
|
147
|
+
} else if (inChecks && line.trim()) checks.push(line.trim().replace(/^[-*]\s+/, ""))
|
|
148
|
+
else {
|
|
149
|
+
inChecks = false
|
|
150
|
+
body.push(line)
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return { body: body.join("\n").trim(), files, checks, replaces, ...(frozen ? { frozen } : {}), ...(planned ? { planned } : {}), ...(attempt ? { attempt } : {}), ...(contract ? { contract } : {}), ...(redteam ? { redteam } : {}), ...(method ? { method } : {}), ...(pick ? { pick } : {}), ...(preview ? { preview } : {}) }
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// How much two task texts are about the same thing: the share of their words they have in common (Jaccard over the
|
|
157
|
+
// words of three letters or more, without the filler). "Remove dashed pill on lanes slide" and "Delete dashed pill on
|
|
158
|
+
// lanes slide" share four of six: the same work, delegated twice in a live run (2026-10-07).
|
|
159
|
+
const FILLER = new Set(["the", "and", "for", "with", "from", "into", "that", "this", "its", "are", "was", "not", "but", "you", "your"])
|
|
160
|
+
function words(text: string): Set<string> {
|
|
161
|
+
return new Set(text.toLowerCase().split(/[^a-z0-9äöüß]+/).filter((w) => w.length > 2 && !FILLER.has(w)))
|
|
162
|
+
}
|
|
163
|
+
export function similarity(a: string, b: string): number {
|
|
164
|
+
const x = words(a)
|
|
165
|
+
const y = words(b)
|
|
166
|
+
if (x.size === 0 || y.size === 0) return 0
|
|
167
|
+
let shared = 0
|
|
168
|
+
for (const w of x) if (y.has(w)) shared++
|
|
169
|
+
return shared / (x.size + y.size - shared)
|
|
170
|
+
}
|
|
171
|
+
const SAME_WORK = 0.5 // a writer on the same files with a title or brief this close is the same work
|
|
172
|
+
const SAME_QUESTION = 0.8 // a reader with a brief this close asks the same question
|
|
173
|
+
const LIVE = new Set(["running", "gating", "fixing"])
|
|
174
|
+
const UNFINISHED = new Set(["blocked", "escalated", "cancelled"])
|
|
175
|
+
|
|
176
|
+
interface Entry {
|
|
177
|
+
readonly project: string
|
|
178
|
+
readonly jobId: string
|
|
179
|
+
taskId: string
|
|
180
|
+
parent: string // the micromanager session; a later session that takes the job over becomes it
|
|
181
|
+
readonly writer: boolean
|
|
182
|
+
dir: string // where the worker works: its own worktree (writer) or the session branch's (reader), at the project offset
|
|
183
|
+
worktree: string // the git worktree root of dir: what git commands need
|
|
184
|
+
rel: string // the project directory's offset inside worktree; "" when the project is the repository root
|
|
185
|
+
branch?: string // a writer's task branch
|
|
186
|
+
removed?: boolean // the writer's worktree was removed after its merge
|
|
187
|
+
session?: string // the child session, once claimed
|
|
188
|
+
checks: string[]
|
|
189
|
+
contract?: string // the fitness contract its work is measured against, by id
|
|
190
|
+
frozen?: Map<string, string> // project-relative path -> content hash when the writer started (task.frozen)
|
|
191
|
+
graph?: boolean // an explorer with a code graph of its directory (the code_graph tool)
|
|
192
|
+
ended?: boolean // its session ended; a writer that did not merge stays "running" until it is continued or swept
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export interface NativeDeps {
|
|
196
|
+
readonly exec?: Exec
|
|
197
|
+
readonly installedSkills?: ReadonlySet<string>
|
|
198
|
+
readonly graphs?: Pick<Graphs, "get"> // the code graph an explorer starts from
|
|
199
|
+
// Plan first (the user, 2026-10-20): a writer starts only from a todo of a job the user started with the start form,
|
|
200
|
+
// so the work is planned with its order before anything changes files. Readers still start on the fly. Off in the
|
|
201
|
+
// tests that delegate writers directly.
|
|
202
|
+
readonly planFirst?: boolean
|
|
203
|
+
// The note when the project is no git repository: the form that asks the user how to go on (src/plugin.ts, with
|
|
204
|
+
// Jev's recommendation). Without it a plain note says the same.
|
|
205
|
+
readonly noGit?: (project: string) => Promise<string>
|
|
206
|
+
// A trial decided by score (src/contract.ts) waits this long after its first passing attempt for the others (the
|
|
207
|
+
// "trialDeadline" setting); then the best of the passed ones is merged and the rest are stopped.
|
|
208
|
+
readonly trialDeadlineMs?: number
|
|
209
|
+
// Who decides a trial by role id ("trialPick", src/trials.ts), and the grace window of a "best" trial ("trialGrace").
|
|
210
|
+
readonly trialPick?: Readonly<Record<string, TrialPick>>
|
|
211
|
+
readonly trialGrace?: Grace
|
|
212
|
+
// Whether an attempt's session is getting nowhere (the watchdog's counts, src/trials.ts idleAttempt): stopped when a
|
|
213
|
+
// "best" trial's grace window opens.
|
|
214
|
+
readonly idle?: (session: string) => boolean
|
|
215
|
+
// A pairwise review of two passed attempts by a model of a third family (src/plugin.ts); undefined when none can.
|
|
216
|
+
readonly review?: (task: Task, a: { task: Task; diff: string }, b: { task: Task; diff: string }) => Promise<Review | undefined>
|
|
217
|
+
// A picture of an attempt's preview page for the user's comparison (src/look.ts), and a desktop notification.
|
|
218
|
+
readonly preview?: (dir: string, path: string, project: string, job: string) => Promise<{ png?: Buffer; problem?: string }>
|
|
219
|
+
readonly notify?: (title: string, body: string) => void
|
|
220
|
+
// A trial was decided by score. note and stop are set when nobody's finish_task carries them (a deadline, the last
|
|
221
|
+
// attempt ending): the note goes to the micromanager, the sessions are interrupted. measured: the attempts that
|
|
222
|
+
// waited for the decision, whose outcomes the log gets now that they are known.
|
|
223
|
+
readonly onSettled?: (r: { project: string; job: Job; parent: string; note?: string; stop: string[]; measured: Task[] }) => void
|
|
224
|
+
// Whether the evolver can run here (uv and a sandbox, src/evolver.ts), and what one of its model calls costs on
|
|
225
|
+
// average: without the first it is never offered, the second prices the offer.
|
|
226
|
+
readonly evolverReady?: () => boolean
|
|
227
|
+
readonly evolverCallCost?: () => number
|
|
228
|
+
readonly evolverMaxEvalSeconds?: () => number // the "evolver.maxEvalSeconds" setting
|
|
229
|
+
// How long one of a job's checks may run: the job's own setting where it has one, else this (the "checkTimeout"
|
|
230
|
+
// setting), else the default of 300 s (src/worktree/git.ts).
|
|
231
|
+
readonly checkTimeoutMs?: number
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export const TRIAL_DEADLINE_MS = 20 * 60_000
|
|
235
|
+
|
|
236
|
+
// A visual task's page when its delegation named none: the first built or plain index.html found in its directory.
|
|
237
|
+
export function defaultPreview(dir: string): string | undefined {
|
|
238
|
+
return ["dist/index.html", "build/index.html", "out/index.html", "public/index.html", "index.html"].find((p) => existsSync(join(dir, p)))
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// The project is no git repository, or one without a commit: nothing starts until the user said how to go on.
|
|
242
|
+
export class NoGitError extends DelegationError {}
|
|
243
|
+
|
|
244
|
+
// One entry of the todo tool: what the micromanager means to start later.
|
|
245
|
+
export interface TodoItem {
|
|
246
|
+
readonly title?: string
|
|
247
|
+
readonly agent?: string // the role agent that will do it (coder when left out)
|
|
248
|
+
readonly files?: string // a writer's write scope, as a delegation's Files line
|
|
249
|
+
readonly checks?: string // shell commands, one per line
|
|
250
|
+
readonly after?: readonly string[] // task ids it waits for
|
|
251
|
+
readonly brief?: string // what the worker needs to know beyond the title
|
|
252
|
+
readonly replaces?: readonly string[] // tasks it does over: "T19", or "job-…/T18" in another job of the session
|
|
253
|
+
readonly contract?: string // the fitness contract it is measured against: "C1"
|
|
254
|
+
readonly frozen?: string // files it may read and run but not change, comma separated
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// Task ids in whatever a model wrote: ["T1", "T2"], "T1, T2", or "after T1 and T2 merged" (live run: the last one made
|
|
258
|
+
// a task wait for a task "MERGED").
|
|
259
|
+
export function taskIds(value: unknown): string[] {
|
|
260
|
+
return (Array.isArray(value) ? value.join(" ") : String(value ?? "")).toUpperCase().match(/\bT\d+(?:\.\w+)*/g) ?? []
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// The tasks a todo or a delegation does over: "T19", or "job-…/T18" for a task of another job of the session.
|
|
264
|
+
export function replaceIds(value: unknown): string[] {
|
|
265
|
+
const text = Array.isArray(value) ? value.join(" ") : String(value ?? "")
|
|
266
|
+
return [...text.matchAll(/\b(job-[\w-]+\/)?(T\d+(?:\.\w+)*)\b/gi)].map((m) => `${m[1]?.toLowerCase() ?? ""}${m[2]!.toUpperCase()}`)
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// The todo tool's one argument: a JSON list of todos, with {"drop": [...]} entries for the ones to remove. A string
|
|
270
|
+
// when it cannot be read: the answer to the micromanager.
|
|
271
|
+
export function parseTodo(items: string): { list: TodoItem[]; ids: string[] } | string {
|
|
272
|
+
const list: TodoItem[] = []
|
|
273
|
+
const ids: string[] = []
|
|
274
|
+
if (!items.trim()) return { list, ids }
|
|
275
|
+
let parsed: unknown
|
|
276
|
+
try {
|
|
277
|
+
parsed = JSON.parse(items)
|
|
278
|
+
} catch (err) {
|
|
279
|
+
return `items is not a JSON list: ${err instanceof Error ? err.message : String(err)}. Nothing was changed.`
|
|
280
|
+
}
|
|
281
|
+
for (const x of Array.isArray(parsed) ? parsed : [parsed]) {
|
|
282
|
+
const o = (x ?? {}) as Record<string, unknown>
|
|
283
|
+
if (o.drop !== undefined) {
|
|
284
|
+
ids.push(...taskIds(o.drop))
|
|
285
|
+
if (!o.title) continue
|
|
286
|
+
}
|
|
287
|
+
const text = (v: unknown, join: string) => (v === undefined || v === null || v === "" ? undefined : Array.isArray(v) ? v.map(String).join(join) : String(v))
|
|
288
|
+
list.push({
|
|
289
|
+
title: String(o.title ?? "").replace(/^\s*T\d+(?:\.\w+)*\s*[:·.-]\s*/i, ""), // the plugin numbers todos itself
|
|
290
|
+
agent: text(o.agent, ""),
|
|
291
|
+
files: text(o.files, ", "),
|
|
292
|
+
checks: text(o.checks, "\n"),
|
|
293
|
+
after: taskIds(o.after),
|
|
294
|
+
brief: text(o.brief, "\n"),
|
|
295
|
+
replaces: replaceIds(o.replaces),
|
|
296
|
+
...(typeof o.contract === "string" && /^c\d+$/i.test(o.contract.trim()) ? { contract: o.contract.trim().toUpperCase() } : {}),
|
|
297
|
+
...(text(o.frozen, ", ") ? { frozen: text(o.frozen, ", ")! } : {}),
|
|
298
|
+
})
|
|
299
|
+
}
|
|
300
|
+
return { list, ids }
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// A worker's task as its session ended.
|
|
304
|
+
export interface Worker {
|
|
305
|
+
readonly project: string
|
|
306
|
+
readonly job: Job
|
|
307
|
+
readonly task: Task
|
|
308
|
+
readonly writer: boolean
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
export interface Delegated {
|
|
312
|
+
readonly task: Task
|
|
313
|
+
readonly job: Job
|
|
314
|
+
readonly prompt: string // the worker's brief
|
|
315
|
+
readonly notes: readonly string[] // what the plugin logs at info level: the project offset, uncommitted state
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
export class Native {
|
|
319
|
+
readonly #exec: Exec
|
|
320
|
+
readonly #skills: ReadonlySet<string>
|
|
321
|
+
readonly #graphs: Pick<Graphs, "get">
|
|
322
|
+
readonly #entries = new Map<string, Entry>() // "<job>/<task>" -> entry
|
|
323
|
+
readonly #bySession = new Map<string, string>() // child session -> its entry's key
|
|
324
|
+
readonly #jobs = new Map<string, Job>() // "<project>\0<job>" -> the live job
|
|
325
|
+
readonly #trains = new Map<string, Promise<unknown>>() // per job: one merge at a time
|
|
326
|
+
readonly #waiting = new Set<string>() // child sessions whose end is awaited
|
|
327
|
+
readonly #delegating = new Map<string, Promise<unknown>>() // per micromanager session: one delegation at a time
|
|
328
|
+
|
|
329
|
+
constructor(deps: NativeDeps = {}) {
|
|
330
|
+
this.#exec = deps.exec ?? defaultExec
|
|
331
|
+
this.#skills = deps.installedSkills ?? new Set()
|
|
332
|
+
this.#graphs = deps.graphs ?? new Graphs(this.#exec)
|
|
333
|
+
this.#planFirst = deps.planFirst ?? false
|
|
334
|
+
this.#noGit = deps.noGit
|
|
335
|
+
this.#deadlineMs = deps.trialDeadlineMs ?? TRIAL_DEADLINE_MS
|
|
336
|
+
this.#trialPick = deps.trialPick ?? DEFAULT_PICK
|
|
337
|
+
this.#grace = deps.trialGrace ?? DEFAULT_GRACE
|
|
338
|
+
this.#idle = deps.idle
|
|
339
|
+
this.#review = deps.review
|
|
340
|
+
this.#preview = deps.preview
|
|
341
|
+
this.#notify = deps.notify
|
|
342
|
+
this.#onSettled = deps.onSettled
|
|
343
|
+
this.#evolverReady = deps.evolverReady ?? (() => false)
|
|
344
|
+
this.#evolverCallCost = deps.evolverCallCost ?? (() => 0.004)
|
|
345
|
+
this.#evolverMax = deps.evolverMaxEvalSeconds ?? (() => EVOLVER_MAX_EVAL_S)
|
|
346
|
+
this.#checkTimeoutMs = deps.checkTimeoutMs
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
readonly #evolverMax: () => number
|
|
350
|
+
|
|
351
|
+
readonly #checkTimeoutMs: number | undefined
|
|
352
|
+
|
|
353
|
+
// How long a check of this job may run.
|
|
354
|
+
#checkTimeout(job: Job | undefined): number {
|
|
355
|
+
return checkTimeoutOf(job, this.#checkTimeoutMs)
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
readonly #evolverReady: () => boolean
|
|
359
|
+
readonly #evolverCallCost: () => number
|
|
360
|
+
readonly #offers = new Map<string, { project: string; jobId: string; contract: string; files: string[]; title: string; checks: string[] }>()
|
|
361
|
+
#offered = 0
|
|
362
|
+
|
|
363
|
+
// A writer measured against a contract whose gain lies in one block (N5's local_block), with a contract that
|
|
364
|
+
// measures fast and one or two files: it does not start, and the user is asked how it should be done instead. A
|
|
365
|
+
// "Method:" line is the answer and skips the question; "Method: trial" asks for a trial whatever the difficulty.
|
|
366
|
+
#offerEvolver(project: string, job: Job, c: Contract | undefined, files: readonly string[], title: string, checks: readonly string[], d: Delegation, assess?: Assessment): void {
|
|
367
|
+
if (d.method === "evolver") 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.")
|
|
368
|
+
if (d.method || !c || !assess?.localBlock || !this.#evolverReady() || !evolverFits(c, files, this.#evolverMax())) return
|
|
369
|
+
const id = `M${++this.#offered}`
|
|
370
|
+
this.#offers.set(id, { project, jobId: job.id, contract: c.id, files: [...files], title, checks: [...checks] })
|
|
371
|
+
const form = evolverForm(id, title, files, c, estimate(c, this.#evolverCallCost()))
|
|
372
|
+
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)}`)
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// The user's answer to an evolver offer: what it was about, once.
|
|
376
|
+
takeOffer(id: string): { project: string; jobId: string; contract: string; files: string[]; title: string; checks: string[] } | undefined {
|
|
377
|
+
const o = this.#offers.get(id)
|
|
378
|
+
this.#offers.delete(id)
|
|
379
|
+
return o
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
readonly #deadlineMs: number
|
|
383
|
+
readonly #onSettled?: NativeDeps["onSettled"]
|
|
384
|
+
readonly #trialPick: Readonly<Record<string, TrialPick>>
|
|
385
|
+
readonly #grace: Grace
|
|
386
|
+
readonly #idle?: NativeDeps["idle"]
|
|
387
|
+
readonly #review?: NativeDeps["review"]
|
|
388
|
+
readonly #preview?: NativeDeps["preview"]
|
|
389
|
+
readonly #notify?: NativeDeps["notify"]
|
|
390
|
+
readonly #deadlines = new Map<string, ReturnType<typeof setTimeout>>() // "<job>/<head>" -> its trial's deadline
|
|
391
|
+
|
|
392
|
+
readonly #noGit?: (project: string) => Promise<string>
|
|
393
|
+
|
|
394
|
+
// The user's choice for a project without git: its workers change the folder directly, one at a time.
|
|
395
|
+
withoutGit(project: string, parent: string): Job {
|
|
396
|
+
const job = this.job(project, parent)
|
|
397
|
+
job.isolation = "none"
|
|
398
|
+
saveJob(project, job)
|
|
399
|
+
return job
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
readonly #planFirst: boolean
|
|
403
|
+
|
|
404
|
+
// The note that asks the user to start the job, with the start form to pass to the question tool; undefined once
|
|
405
|
+
// the job is started.
|
|
406
|
+
startNote(project: string, job: Job): string | undefined {
|
|
407
|
+
if (isStarted(job, loadControl(project, job.id))) return undefined
|
|
408
|
+
const open = job.tasks.filter((t) => ["pending", "ready", "planned"].includes(t.status))
|
|
409
|
+
if (!open.length) return undefined
|
|
410
|
+
const form = startForm(job.id, open.length, startable(job).length, lastOptions(project))
|
|
411
|
+
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)}`
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
// The micromanager session's job: made at its first delegation, kept until the session ends.
|
|
415
|
+
job(project: string, parent: string): Job {
|
|
416
|
+
const live = [...this.#jobs.values()].find((j) => j.facilitator === parent && j.rolling && this.#jobs.get(key(project, j.id)) === j)
|
|
417
|
+
if (live) return live
|
|
418
|
+
const found = listJobs(project).find((j) => j.facilitator === parent && j.rolling && !["done", "stopped", "failed"].includes(j.phase))
|
|
419
|
+
const job = found ?? newJob(jobId(), `the delegated tasks of micromanager session ${parent}`)
|
|
420
|
+
if (!found) {
|
|
421
|
+
for (const p of ["triage", "plan", "plan_gate", "execute"] as const) moveJob(job, p)
|
|
422
|
+
job.rolling = true
|
|
423
|
+
job.facilitator = parent
|
|
424
|
+
saveJob(project, job)
|
|
425
|
+
}
|
|
426
|
+
this.#jobs.set(key(project, job.id), job)
|
|
427
|
+
return job
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
// After a restart: the workers of the project's open jobs, rebuilt from the job files. Everything the plugin knew of
|
|
431
|
+
// them lived in memory, so a worker continued after a restart (reboot, 2026-10-14) answered finish_task with "no
|
|
432
|
+
// task", and the duplicate check could not see the change it had left in its worktree. Every session found here is
|
|
433
|
+
// over, since the restart ended it; resume() makes it live again when the micromanager continues it. Returns the
|
|
434
|
+
// adopted "<job>/<task>" keys.
|
|
435
|
+
adopt(project: string): string[] {
|
|
436
|
+
const adopted: string[] = []
|
|
437
|
+
for (const job of listJobs(project)) {
|
|
438
|
+
if (!(job.rolling || job.native) || !job.facilitator || ["done", "stopped", "failed"].includes(job.phase)) continue
|
|
439
|
+
const known = this.#jobs.get(key(project, job.id))
|
|
440
|
+
if (known) continue
|
|
441
|
+
this.#jobs.set(key(project, job.id), job)
|
|
442
|
+
for (const task of job.tasks) {
|
|
443
|
+
const k = `${job.id}/${task.id}`
|
|
444
|
+
if (!task.session || this.#entries.has(k)) continue
|
|
445
|
+
const writer = WRITERS.has(task.role)
|
|
446
|
+
const worktree = writer ? task.worktree : job.integrationWorktree
|
|
447
|
+
const rel = (writer ? task.worktreeRel : job.integrationRel) ?? job.integrationRel ?? ""
|
|
448
|
+
const verify = job.acceptance.filter((a) => task.acceptance.includes(a.id)).map((a) => a.verify).filter((v): v is string => Boolean(v))
|
|
449
|
+
const entry: Entry = {
|
|
450
|
+
project,
|
|
451
|
+
jobId: job.id,
|
|
452
|
+
taskId: task.id,
|
|
453
|
+
parent: job.facilitator,
|
|
454
|
+
writer,
|
|
455
|
+
dir: worktree ? taskDir(worktree, rel) : project,
|
|
456
|
+
worktree: worktree ?? job.integrationWorktree ?? project,
|
|
457
|
+
rel,
|
|
458
|
+
branch: writer ? task.branch : undefined,
|
|
459
|
+
removed: writer && !task.worktree,
|
|
460
|
+
session: task.session,
|
|
461
|
+
// The checks as given; a job written before they were kept has only the joined verify to go by.
|
|
462
|
+
checks: task.checks ?? verify.flatMap((v) => v.split(" && ")).map((c) => c.trim()).filter(Boolean),
|
|
463
|
+
...(task.contract ? { contract: task.contract.id } : {}),
|
|
464
|
+
...(task.frozen ? { frozen: new Map(Object.entries(task.frozen)) } : {}),
|
|
465
|
+
ended: true,
|
|
466
|
+
}
|
|
467
|
+
this.#entries.set(k, entry)
|
|
468
|
+
for (const s of new Set([task.session, ...(task.sessions ?? [])])) this.#bySession.set(s, k)
|
|
469
|
+
adopted.push(k)
|
|
470
|
+
}
|
|
471
|
+
// A trial decided by score whose deadline lived in the process that ended: armed again, from the time it had.
|
|
472
|
+
for (const head of job.tasks.filter((t) => t.settleBy && t.trial?.of === t.id)) {
|
|
473
|
+
const now = standing(job, head)
|
|
474
|
+
if (!now.winner && now.held.length && pickOf(head) !== "user") this.#arm(project, job, head)
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
return adopted
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
// The open jobs of earlier micromanager sessions of this project: rolling, not finished, and with something left in
|
|
481
|
+
// them (a merged task, or a task with a worktree). A new session starts a job of its own, so without this the
|
|
482
|
+
// previous session's work was out of sight: merged tasks the checkout never got, unfinished changes in worktrees.
|
|
483
|
+
openJobs(project: string, parent: string): Job[] {
|
|
484
|
+
return listJobs(project)
|
|
485
|
+
.filter((j) => j.rolling && j.facilitator && j.facilitator !== parent && !["done", "stopped", "failed"].includes(j.phase))
|
|
486
|
+
.map((j) => this.#jobs.get(key(project, j.id)) ?? j)
|
|
487
|
+
.filter((j) => j.tasks.some((t) => (t.status === "merged" && !t.undone) || (t.worktree && t.status !== "merged")))
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
// Whether this micromanager session has a job of its own yet.
|
|
491
|
+
hasJob(project: string, parent: string): boolean {
|
|
492
|
+
return listJobs(project).some((j) => j.rolling && j.facilitator === parent && !["done", "stopped", "failed"].includes(j.phase))
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
// "Continue" at the start of a session: the earlier session's job becomes this session's. New workers land on the
|
|
496
|
+
// same branch, its unfinished workers can be continued by their sessions, and their notes and permission requests
|
|
497
|
+
// come to this session. Refused when this session started a job of its own already: two jobs of one session would
|
|
498
|
+
// split its work over two branches.
|
|
499
|
+
takeOver(project: string, jobId: string, parent: string): { job?: Job; problem?: string } {
|
|
500
|
+
if (this.hasJob(project, parent)) return { problem: "this session has a job of its own already; continue the earlier one in a new session, or merge or discard it" }
|
|
501
|
+
this.adopt(project)
|
|
502
|
+
const job = this.#jobs.get(key(project, jobId)) ?? listJobs(project).find((j) => j.id === jobId)
|
|
503
|
+
if (!job || !job.rolling) return { problem: `there is no open job ${jobId} of a micromanager session in this project` }
|
|
504
|
+
if (["done", "stopped", "failed"].includes(job.phase)) return { problem: `job ${jobId} is ${job.phase}` }
|
|
505
|
+
job.facilitator = parent
|
|
506
|
+
this.#jobs.set(key(project, job.id), job)
|
|
507
|
+
for (const entry of this.#entries.values()) {
|
|
508
|
+
if (entry.jobId === job.id && entry.project === project) entry.parent = parent
|
|
509
|
+
}
|
|
510
|
+
saveJob(project, job)
|
|
511
|
+
return { job }
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
// A new subagent call of the micromanager: the task, its worktree and the worker's brief. Throws a
|
|
515
|
+
// DelegationError the micromanager can act on when the call is not a valid delegation. Calls of one message come
|
|
516
|
+
// at the same time; they go one after another (live test: two made the session branch at once, and one failed).
|
|
517
|
+
// assess: what the plugin found out about a writer before (src/trials.ts): its difficulty and how many attempts.
|
|
518
|
+
delegate(project: string, parent: string, input: { agent: string; description: string; prompt: string }, model: string, assess?: Assessment): Promise<Delegated> {
|
|
519
|
+
const next = (this.#delegating.get(parent) ?? Promise.resolve()).then(() => this.#delegate(project, parent, input, model, assess))
|
|
520
|
+
this.#delegating.set(parent, next.catch(() => undefined))
|
|
521
|
+
return next
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
async #delegate(project: string, parent: string, input: { agent: string; description: string; prompt: string }, model: string, assess?: Assessment): Promise<Delegated> {
|
|
525
|
+
const role = roleByAgent(input.agent)
|
|
526
|
+
if (!role) throw new DelegationError(`Not started: use one of the role agents (${ROLES.map((r) => r.agent).join(", ")}), not ${input.agent || "none"}.`)
|
|
527
|
+
const d = parseDelegation(input.prompt)
|
|
528
|
+
if (d.attempt) return this.#attempt(project, parent, role, d, d.attempt, model)
|
|
529
|
+
if (d.planned) return this.#planned(project, parent, role, d, d.planned, model, assess)
|
|
530
|
+
if (d.redteam) return this.#redteam(project, parent, role, d, d.redteam, model)
|
|
531
|
+
if (this.#planFirst && WRITERS.has(role.id)) {
|
|
532
|
+
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-…".`)
|
|
533
|
+
}
|
|
534
|
+
const parsed = parseFiles(d.files, project)
|
|
535
|
+
if (parsed.problem) throw new DelegationError(`Not started: ${parsed.problem}`)
|
|
536
|
+
const writer = WRITERS.has(role.id)
|
|
537
|
+
if (writer && !parsed.files.length) 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>".`)
|
|
538
|
+
if (!writer && parsed.files.length) throw new DelegationError(`Not started: ${role.agent} only reads; leave out the Files line, or pick a role that writes.`)
|
|
539
|
+
// Every check that will reach runGate is validated here, before the task or its worktree exist: a command that is
|
|
540
|
+
// not one, one that is destructive, and a writer whose set cannot fail at all. A refused delegation must leave
|
|
541
|
+
// nothing behind, and this runs before addDelegated and prepareTaskWorktree, so it does.
|
|
542
|
+
const checks = checkSetProblems(d.checks, writer)
|
|
543
|
+
if (checks) throw new DelegationError(`Not started: ${checks}`)
|
|
544
|
+
if (!d.body) throw new DelegationError("Not started: the prompt has no task.")
|
|
545
|
+
|
|
546
|
+
const job = this.job(project, parent)
|
|
547
|
+
const c = this.#contractFor(job, writer, d.contract, assess)
|
|
548
|
+
this.#offerEvolver(project, job, c, parsed.files, input.description.trim() || d.body.split("\n")[0]!, d.checks, d, assess)
|
|
549
|
+
if (d.method === "trial") assess = { ...(assess ?? {}), trials: Math.max(2, assess?.trials ?? 1) }
|
|
550
|
+
await this.#replace(project, job, d.replaces)
|
|
551
|
+
const duplicate = this.#duplicate(job, role, input.description.trim(), d.body, parsed.files, d.replaces)
|
|
552
|
+
if (duplicate) throw new DelegationError(duplicate)
|
|
553
|
+
if (WRITERS.has(role.id)) {
|
|
554
|
+
const [rel, working] = await Promise.all([repoRel(project), dirtyPaths(project)])
|
|
555
|
+
const blocked = working.dirty ? dirtyDeclared(parsed.files, rel, working.paths) : []
|
|
556
|
+
if (blocked.length > 0) {
|
|
557
|
+
throw new DelegationError(
|
|
558
|
+
`Not started: this task may change ${blocked.slice(0, 5).join(", ")}${blocked.length > 5 ? `, +${blocked.length - 5} more` : ""}, ` +
|
|
559
|
+
`whose current version is uncommitted in your checkout. A worker starts from HEAD and would not see it. ` +
|
|
560
|
+
`Commit or stash those files first, then delegate again.`,
|
|
561
|
+
)
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
const rel = await this.#integrate(project, job, WRITERS.has(role.id))
|
|
565
|
+
const added = addDelegated(job, { title: input.description.trim() || d.body.split("\n")[0]!, prompt: d.body, files: parsed.files, dependsOn: [], checks: d.checks })
|
|
566
|
+
if (!added.task) throw new DelegationError(`Not started: ${added.errors!.join("; ")}`)
|
|
567
|
+
const task = added.task
|
|
568
|
+
this.#bind(job, task, d.contract)
|
|
569
|
+
if (d.frozen) task.freeze = parseFiles(d.frozen, project).files
|
|
570
|
+
this.#link(project, job, task, d.replaces)
|
|
571
|
+
task.role = role.id
|
|
572
|
+
task.model = model
|
|
573
|
+
this.#assess(project, job, task, assess, d.pick)
|
|
574
|
+
if (d.preview) task.preview = d.preview
|
|
575
|
+
for (const s of ["ready", "planned", "running"] as const) moveTask(task, s)
|
|
576
|
+
stage(task, "delegate", "pass", `${role.agent} on ${model}`)
|
|
577
|
+
return this.#start(project, parent, job, task, role, model, d, d.checks, rel)
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
// The contract a writer is measured against, checked before anything of the task exists: one that the job has, with
|
|
581
|
+
// a baseline to compare with. An open-ended task (N5's open_ended, src/trials.ts Assessment) without one is refused,
|
|
582
|
+
// as a writer without checks is: nothing could tell a better result from a worse one.
|
|
583
|
+
#contractFor(job: Job, writer: boolean, id: string | undefined, assess?: Assessment): Contract | undefined {
|
|
584
|
+
if (!writer) {
|
|
585
|
+
if (id) throw new DelegationError("Not started: a fitness contract measures a writer's work; leave out the Contract line for a reader.")
|
|
586
|
+
return undefined
|
|
587
|
+
}
|
|
588
|
+
if (!id) {
|
|
589
|
+
if (assess?.openEnded) 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…".')
|
|
590
|
+
return undefined
|
|
591
|
+
}
|
|
592
|
+
const c = job.contracts?.find((x) => x.id === id)
|
|
593
|
+
if (!c) throw new DelegationError(`Not started: job ${job.id} has no contract ${id}; define it with the contract tool first.`)
|
|
594
|
+
if (!c.baseline) 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.`)
|
|
595
|
+
// What "better" means is the user's: a draft has not been through the round (their preferences, the red team, the
|
|
596
|
+
// baseline check) yet.
|
|
597
|
+
if (c.status !== "frozen") 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.`)
|
|
598
|
+
return c
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
// The task is measured against this version of the contract from now on.
|
|
602
|
+
#bind(job: Job, task: Task, id: string | undefined): void {
|
|
603
|
+
const c = id ? job.contracts?.find((x) => x.id === id) : undefined
|
|
604
|
+
if (c) task.contract = { id: c.id, version: c.version }
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
// The contract tool: a contract for the job (the session's own when jobId is empty), new or as a new version of the
|
|
608
|
+
// one with its id, with its baseline measured on the job's branch as it is now. Returns the answer to the micromanager.
|
|
609
|
+
// byUser: a change the user accepted (request_check_change kind contract); it may change a frozen contract.
|
|
610
|
+
async contract(project: string, parent: string, jobId: string, json: string, byUser = false): Promise<string> {
|
|
611
|
+
const job = jobId ? this.#jobs.get(key(project, jobId)) ?? listJobs(project).find((j) => j.id === jobId) : this.job(project, parent)
|
|
612
|
+
if (!job) return `There is no job ${jobId} in this project. Nothing was stored.`
|
|
613
|
+
const parsed = parseContract(json)
|
|
614
|
+
if (!parsed.contract) return `Not stored: ${parsed.errors.join("; ")}.`
|
|
615
|
+
const wanted = String((JSON.parse(json) as { id?: unknown }).id ?? "").toUpperCase()
|
|
616
|
+
const old = wanted ? job.contracts?.find((c) => c.id === wanted) : undefined
|
|
617
|
+
if (wanted && !old) return `Not stored: job ${job.id} has no contract ${wanted} to change; leave out the id for a new one.`
|
|
618
|
+
if (old?.status === "frozen" && !byUser) return `Not stored: contract ${old.id} is frozen; only the user changes it.`
|
|
619
|
+
const at = new Date().toISOString()
|
|
620
|
+
const n = Math.max(0, ...(job.contracts ?? []).map((c) => Number(c.id.slice(1)))) + 1
|
|
621
|
+
const c: Contract = old
|
|
622
|
+
? { ...old, ...parsed.contract, version: old.version + 1, baseline: undefined, history: [...old.history, { version: old.version + 1, change: "changed with the contract tool", at }] }
|
|
623
|
+
: { id: `C${n}`, version: 1, status: "draft", ...parsed.contract, history: [{ version: 1, change: "defined with the contract tool", at }] }
|
|
624
|
+
if (old) {
|
|
625
|
+
c.status = "draft" // a new version goes through the round again, unless the user changed it (applyCheckChange)
|
|
626
|
+
c.round = undefined
|
|
627
|
+
c.frozen = undefined
|
|
628
|
+
}
|
|
629
|
+
// The held-out cases come from a directory outside the project and go to the plugin's state directory; a new
|
|
630
|
+
// version without them keeps the ones it had.
|
|
631
|
+
if (parsed.heldOutFrom) {
|
|
632
|
+
const kept = keepHeldOut(parsed.heldOutFrom, project, heldOutDir(project, job.id, c.id))
|
|
633
|
+
if (!kept.heldOut) return `Not stored: ${kept.problem}.`
|
|
634
|
+
c.corpus = { ...c.corpus, heldOut: kept.heldOut }
|
|
635
|
+
} else if (old?.corpus.heldOut) c.corpus = { ...c.corpus, heldOut: old.corpus.heldOut }
|
|
636
|
+
// The baseline is today's code on the job's branch, where the workers start from; a folder without git has only
|
|
637
|
+
// itself.
|
|
638
|
+
const rel = await this.#integrate(project, job, false)
|
|
639
|
+
const dir = taskDir(job.integrationWorktree ?? project, rel)
|
|
640
|
+
const { measured, seconds } = await runEvaluator(dir, c, "visible", this.#exec)
|
|
641
|
+
this.#count(job, c, seconds)
|
|
642
|
+
// A guard or a target on a value the evaluator does not print is never checked (live run, 2026-10-26: a drafted
|
|
643
|
+
// guard "cases.passed", which is no score, held nothing): refused while the draft can still be fixed.
|
|
644
|
+
const named = [...c.guards.map((g) => g.name), ...Object.keys(c.stop.target ?? {})]
|
|
645
|
+
const unmeasured = measured.valid ? [...new Set(named.filter((n) => !(n in measured.values)))] : []
|
|
646
|
+
if (unmeasured.length) 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.`
|
|
647
|
+
if (measured.valid) {
|
|
648
|
+
const commit = job.integrationWorktree ? (await this.#exec("git", ["rev-parse", "--short", "HEAD"], { cwd: job.integrationWorktree })).stdout.trim() : undefined
|
|
649
|
+
c.baseline = { values: { ...measured.values }, at, ...(commit ? { commit } : {}) }
|
|
650
|
+
c.costPerEval = Math.round((seconds / c.repeats) * 10) / 10
|
|
651
|
+
if (c.quick) {
|
|
652
|
+
// The quick stage's own baseline: the cascade compares a candidate there with today's code there.
|
|
653
|
+
const q = await runEvaluator(dir, { ...c, evaluator: c.quick.evaluator, repeats: 1 }, "visible", this.#exec)
|
|
654
|
+
this.#count(job, c, q.seconds)
|
|
655
|
+
if (q.measured.valid) {
|
|
656
|
+
c.baseline.quick = { ...q.measured.values }
|
|
657
|
+
c.quick = { ...c.quick, costPerEval: q.seconds }
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
if (c.corpus.heldOut) {
|
|
661
|
+
const held = await runEvaluator(dir, c, "heldout", this.#exec, heldOutDir(project, job.id, c.id))
|
|
662
|
+
this.#count(job, c, held.seconds)
|
|
663
|
+
if (held.measured.valid) c.baseline.heldOut = { ...held.measured.values }
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
job.contracts = [...(job.contracts ?? []).filter((x) => x.id !== c.id), c]
|
|
667
|
+
this.#jobs.set(key(project, job.id), job)
|
|
668
|
+
saveJob(project, job)
|
|
669
|
+
saveContract(project, job.id, c)
|
|
670
|
+
if (!measured.valid) 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}".`
|
|
671
|
+
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"}.` : ""
|
|
672
|
+
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.`
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
// The files a writer may read and run but not change, hashed as its worktree has them now: the ones its todo or
|
|
676
|
+
// delegation asked for, the existing files its checks name that are not its own, and its contract's evaluator and
|
|
677
|
+
// visible corpus. A file of its own write scope is never frozen: the two would contradict each other.
|
|
678
|
+
async #freeze(job: Job, task: Task, entry: Entry): Promise<void> {
|
|
679
|
+
const own = new Set(task.files)
|
|
680
|
+
const c = entry.contract ? job.contracts?.find((x) => x.id === entry.contract) : undefined
|
|
681
|
+
const corpus: string[] = []
|
|
682
|
+
for (const p of c?.corpus.visible ?? []) {
|
|
683
|
+
const listed = await this.#exec("git", ["ls-files", "--", p], { cwd: entry.dir })
|
|
684
|
+
corpus.push(...listed.stdout.split("\n").map((l) => l.trim()).filter(Boolean))
|
|
685
|
+
}
|
|
686
|
+
const named = [...entry.checks, ...(c ? [c.evaluator] : [])].flatMap((command) => namedFiles(command, entry.dir))
|
|
687
|
+
const paths = [...new Set([...(task.freeze ?? []), ...named, ...corpus])].filter((p) => !own.has(p)).sort()
|
|
688
|
+
if (!paths.length) return
|
|
689
|
+
entry.frozen = await hashFiles(entry.worktree, paths, this.#exec, entry.dir)
|
|
690
|
+
task.frozen = Object.fromEntries(entry.frozen)
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
// A writer's frozen files as absolute paths, for the sandbox (src/shell/sandbox.ts denyWrite) and the permission hook.
|
|
694
|
+
frozenOf(session: string): string[] {
|
|
695
|
+
const entry = this.#entry(session)
|
|
696
|
+
return entry?.writer && entry.frozen ? [...entry.frozen.keys()].map((f) => resolve(entry.dir, f)) : []
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
// The resources of a write request that are frozen for this writer; resources are paths relative to its directory or
|
|
700
|
+
// absolute.
|
|
701
|
+
frozenHit(session: string, resources: readonly string[]): string[] {
|
|
702
|
+
const entry = this.#entry(session)
|
|
703
|
+
if (!entry?.writer || !entry.frozen?.size) return []
|
|
704
|
+
const frozen = new Set(this.frozenOf(session))
|
|
705
|
+
return resources.filter((r) => frozen.has(isAbsolute(r) ? resolve(r) : resolve(entry.dir, r)))
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
// A worker's report as it ended: its FOLLOWUP lines go to the job's later list, unless the job has the work already
|
|
709
|
+
// (a task with nearly that title) or the list has it. They become backlog drafts when the job ends (backlog()).
|
|
710
|
+
noteFollowUps(session: string, report: string): Later[] {
|
|
711
|
+
const entry = this.#entry(session)
|
|
712
|
+
const job = entry && this.#job(entry)
|
|
713
|
+
if (!entry || !job) return []
|
|
714
|
+
const known = [...job.tasks.map((t) => t.title), ...(job.later ?? []).map((l) => l.what)]
|
|
715
|
+
const added = parseReport(report).followUps
|
|
716
|
+
.filter((f) => !known.some((k) => similarity(k, f.what) >= SAME_WORK))
|
|
717
|
+
.slice(0, 5)
|
|
718
|
+
.map((f): Later => ({ ...f, from: entry.taskId, reason: "reported" }))
|
|
719
|
+
if (!added.length) return []
|
|
720
|
+
job.later = [...(job.later ?? []), ...added]
|
|
721
|
+
saveJob(entry.project, job)
|
|
722
|
+
return added
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
// The job ended (merged into the checkout or discarded): what it found and did not do goes to the backlog as drafts,
|
|
726
|
+
// 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
|
|
727
|
+
// trial that a later task did over. Each item is written once. The item the job was started from (plan_job
|
|
728
|
+
// backlog:<slug>) is done once the job is merged, and ready again once it is discarded.
|
|
729
|
+
backlog(project: string, job: Job, merged: boolean, backend: BacklogBackend = localBackend, now = new Date()): { drafts: BacklogItem[]; source: BacklogItem[] } {
|
|
730
|
+
const live = this.#jobs.get(key(project, job.id)) ?? job
|
|
731
|
+
const items = backend.list(project)
|
|
732
|
+
const source = items.filter((i) => i.job === live.id && i.status === "running")
|
|
733
|
+
for (const i of source) {
|
|
734
|
+
i.status = merged ? "done" : "ready"
|
|
735
|
+
backend.save(project, i)
|
|
736
|
+
}
|
|
737
|
+
const taken = new Set(items.map((i) => i.slug))
|
|
738
|
+
const drafts: BacklogItem[] = []
|
|
739
|
+
const save = (item: BacklogItem) => {
|
|
740
|
+
backend.save(project, item)
|
|
741
|
+
taken.add(item.slug)
|
|
742
|
+
drafts.push(item)
|
|
743
|
+
}
|
|
744
|
+
for (const l of live.later ?? []) {
|
|
745
|
+
if (l.draft || live.tasks.some((t) => t.id !== l.from && similarity(t.title, l.what) >= SAME_WORK)) continue
|
|
746
|
+
const item = draftFromLater(l, live, taken, now)
|
|
747
|
+
save(item)
|
|
748
|
+
l.draft = item.slug
|
|
749
|
+
}
|
|
750
|
+
for (const head of live.tasks.filter((t) => t.trial?.of === t.id)) {
|
|
751
|
+
const trial = standing(live, head)
|
|
752
|
+
if (trial.winner || trial.live.length || !trial.failed.length || trial.all.some((t) => t.replacedBy) || head.stages.some((s) => s.stage === "backlog")) continue
|
|
753
|
+
const checks = live.acceptance.filter((a) => head.acceptance.includes(a.id)).flatMap((a) => (a.verify ? [a.verify] : []))
|
|
754
|
+
const item = draftFromTrial(live, head, trial.failed, checks, taken, now)
|
|
755
|
+
save(item)
|
|
756
|
+
stage(head, "backlog", "pass", `draft ${item.slug}`)
|
|
757
|
+
}
|
|
758
|
+
if (drafts.length) saveJob(project, live)
|
|
759
|
+
return { drafts, source }
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
// What a writer asking for a check change is, for the request: its job, task, model and how often it asked.
|
|
763
|
+
changeContext(session: string): { project: string; job: Job; task: Task; parent: string; asked: number } | undefined {
|
|
764
|
+
const entry = this.#entry(session)
|
|
765
|
+
const job = entry && this.#job(entry)
|
|
766
|
+
const task = job?.tasks.find((t) => t.id === entry!.taskId)
|
|
767
|
+
if (!entry?.writer || !job || !task) return undefined
|
|
768
|
+
return { project: entry.project, job, task, parent: entry.parent, asked: task.checkChanges?.length ?? 0 }
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
// A decided check change, on the task (and the outcome log after it).
|
|
772
|
+
recordChange(project: string, jobId: string, taskId: string, kind: ChangeKind, a: ChangeAnswer, id: string, target: string): void {
|
|
773
|
+
const job = this.#jobs.get(key(project, jobId))
|
|
774
|
+
const task = job?.tasks.find((t) => t.id === taskId)
|
|
775
|
+
if (!job || !task) return
|
|
776
|
+
task.checkChanges = [...(task.checkChanges ?? []), { kind, accepted: a.accepted, by: a.by }]
|
|
777
|
+
stage(task, "check-change", a.accepted ? "pass" : "fail", `${id} ${kind}: ${target.slice(0, 120)}${a.note ? ` (${a.note.slice(0, 120)})` : ""}`)
|
|
778
|
+
saveJob(project, job)
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
// An accepted check change, applied from outside: the worker never touches the check itself. A check command is
|
|
782
|
+
// replaced; a frozen file gets the proposed diff and is frozen again as it is now; a contract gets a new version. In a
|
|
783
|
+
// trial every attempt still at work gets the same change and a note, so all are measured by the same rule. Returns
|
|
784
|
+
// what was done, or why it could not be, and the notes for the other attempts.
|
|
785
|
+
async applyCheckChange(project: string, jobId: string, taskId: string, r: { kind: ChangeKind; target: string; problem: string; proposal: string; id: string }): Promise<{ ok: boolean; text: string; steer: { session: string; note: string }[] }> {
|
|
786
|
+
const job = this.#jobs.get(key(project, jobId))
|
|
787
|
+
const task = job?.tasks.find((t) => t.id === taskId)
|
|
788
|
+
const entry = this.#entries.get(`${jobId}/${taskId}`)
|
|
789
|
+
if (!job || !task || !entry) return { ok: false, text: "the task is gone", steer: [] }
|
|
790
|
+
const siblings = task.trial ? standing(job, task).live.filter((t) => t !== task) : []
|
|
791
|
+
const entries = [entry, ...siblings.map((t) => this.#entries.get(`${job.id}/${t.id}`)).filter((e): e is Entry => Boolean(e && !e.ended))]
|
|
792
|
+
const steer = (what: string) => 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.` }))
|
|
793
|
+
if (r.kind === "contract") {
|
|
794
|
+
const c = job.contracts?.find((x) => x.id === task.contract?.id)
|
|
795
|
+
if (!c) return { ok: false, text: "the task is measured against no contract", steer: [] }
|
|
796
|
+
let proposal: Record<string, unknown>
|
|
797
|
+
try {
|
|
798
|
+
proposal = JSON.parse(r.proposal) as Record<string, unknown>
|
|
799
|
+
} catch {
|
|
800
|
+
return { ok: false, text: "the proposal is no contract JSON", steer: [] }
|
|
801
|
+
}
|
|
802
|
+
const wasFrozen = c.status === "frozen"
|
|
803
|
+
const text = await this.contract(project, entry.parent, job.id, JSON.stringify({ ...proposal, id: c.id }), true)
|
|
804
|
+
if (!text.startsWith(`Contract ${c.id} (version`)) return { ok: false, text, steer: [] }
|
|
805
|
+
const now = job.contracts!.find((x) => x.id === c.id)!
|
|
806
|
+
if (!now.baseline) return { ok: false, text, steer: [] }
|
|
807
|
+
// The user decided this change, which is what the round is for: frozen again as it is now.
|
|
808
|
+
if (wasFrozen) await this.#freezeContract(project, job, now)
|
|
809
|
+
for (const e of entries) this.#bind(job, job.tasks.find((t) => t.id === e.taskId)!, c.id)
|
|
810
|
+
return { ok: true, text: `contract ${c.id} is version ${now.version} now`, steer: steer(`contract ${c.id} is version ${now.version} now`) }
|
|
811
|
+
}
|
|
812
|
+
if (r.kind === "spec_incomplete") job.decisions.push({ id: `D${job.decisions.length + 1}`, text: `${r.problem.slice(0, 300)} Decided: ${r.proposal.slice(0, 300)}`, origin: "user" })
|
|
813
|
+
const target = normalTarget(r.target)
|
|
814
|
+
const check = entry.checks.find((c) => normalTarget(c) === target)
|
|
815
|
+
if (check) {
|
|
816
|
+
const next = r.proposal.trim()
|
|
817
|
+
const why = checkSetProblems([next], true)
|
|
818
|
+
if (why) return { ok: false, text: `the proposed check is not one: ${why}`, steer: [] }
|
|
819
|
+
for (const e of entries) {
|
|
820
|
+
e.checks = e.checks.map((c) => (normalTarget(c) === target ? next : c))
|
|
821
|
+
const t = job.tasks.find((x) => x.id === e.taskId)!
|
|
822
|
+
t.checks = [...e.checks]
|
|
823
|
+
job.acceptance = job.acceptance.map((a) => (t.acceptance.includes(a.id) && a.verify ? { ...a, verify: e.checks.join(" && ") } : a))
|
|
824
|
+
}
|
|
825
|
+
saveJob(project, job)
|
|
826
|
+
return { ok: true, text: `the check "${check}" is "${next}" now`, steer: steer(`the check "${check}" is "${next}" now`) }
|
|
827
|
+
}
|
|
828
|
+
const path = r.target.trim().replace(/^\.\//, "")
|
|
829
|
+
const known = entry.frozen?.has(path) || (() => { try { return statSync(join(entry.dir, path)).isFile() } catch { return false } })()
|
|
830
|
+
if (!known) return { ok: false, text: `${r.target.trim()} is neither a check of the task nor a file in its directory`, steer: [] }
|
|
831
|
+
const scratch = mkdtempSync(join(tmpdir(), "mm-change-"))
|
|
832
|
+
try {
|
|
833
|
+
const patch = join(scratch, "change.patch")
|
|
834
|
+
writeFileSync(patch, r.proposal.endsWith("\n") ? r.proposal : `${r.proposal}\n`)
|
|
835
|
+
for (const e of entries) {
|
|
836
|
+
const args = ["apply", "--whitespace=nowarn", ...(e.rel ? [`--directory=${e.rel}`] : []), patch]
|
|
837
|
+
const applied = await this.#exec("git", args, { cwd: e.worktree })
|
|
838
|
+
if (applied.code !== 0) 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: [] }
|
|
839
|
+
if (e.frozen?.has(path)) {
|
|
840
|
+
const hash = (await hashFiles(e.worktree, [path], this.#exec, e.dir)).get(path) ?? ""
|
|
841
|
+
e.frozen.set(path, hash)
|
|
842
|
+
const t = job.tasks.find((x) => x.id === e.taskId)!
|
|
843
|
+
t.frozen = Object.fromEntries(e.frozen)
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
} finally {
|
|
847
|
+
rmSync(scratch, { recursive: true, force: true })
|
|
848
|
+
}
|
|
849
|
+
saveJob(project, job)
|
|
850
|
+
return { ok: true, text: `${path} is changed as proposed${entry.frozen?.has(path) ? " and frozen again" : ""}`, steer: steer(`${path} is changed as proposed`) }
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
// --- the contract round (src/contractround.ts) ---------------------------------------------------------------
|
|
854
|
+
|
|
855
|
+
// contract_round: a new round from a goal (the drafter's prompt), a draft from the drafter's JSON, or an existing
|
|
856
|
+
// draft by its id. Returns what the micromanager does next.
|
|
857
|
+
async contractRound(project: string, parent: string, jobId: string, goal: string, input: string): Promise<string> {
|
|
858
|
+
const job = jobId ? this.#jobs.get(key(project, jobId)) ?? listJobs(project).find((j) => j.id === jobId) : this.job(project, parent)
|
|
859
|
+
if (!job) return `There is no job ${jobId} in this project.`
|
|
860
|
+
const text = input.trim()
|
|
861
|
+
if (!text) {
|
|
862
|
+
if (!goal.trim()) return "contract_round needs the goal (to start a round), or as input the drafter's contract JSON or a draft's id."
|
|
863
|
+
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).
|
|
864
|
+
|
|
865
|
+
${draftPrompt(goal.trim())}`
|
|
866
|
+
}
|
|
867
|
+
let c: Contract | undefined
|
|
868
|
+
if (/^c\d+$/i.test(text)) c = job.contracts?.find((x) => x.id === text.toUpperCase())
|
|
869
|
+
else {
|
|
870
|
+
const stored = await this.contract(project, parent, job.id, text)
|
|
871
|
+
const id = stored.match(/^Contract (C\d+) \(version/)?.[1]
|
|
872
|
+
if (!id) return stored
|
|
873
|
+
c = job.contracts?.find((x) => x.id === id)
|
|
874
|
+
if (!c?.baseline) return stored
|
|
875
|
+
}
|
|
876
|
+
if (!c) return `Job ${job.id} has no contract ${text}.`
|
|
877
|
+
if (c.status === "frozen") return `Contract ${c.id} is frozen already; writers are measured against it with a line "Contract: ${c.id}".`
|
|
878
|
+
if (!c.baseline) 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.`
|
|
879
|
+
c.round = { step: "prefs", loopholes: [] }
|
|
880
|
+
saveJob(project, job)
|
|
881
|
+
saveContract(project, job.id, c)
|
|
882
|
+
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.`)
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
// The job a contract in its round belongs to, for the round's forms (they name only the contract).
|
|
886
|
+
roundJob(project: string, parent: string, id: string): { job: Job; contract: Contract } | undefined {
|
|
887
|
+
const jobs = [...[...this.#jobs.entries()].filter(([k]) => k.startsWith(`${project}\0`)).map(([, j]) => j), ...listJobs(project)]
|
|
888
|
+
const mine = jobs.filter((j) => j.facilitator === parent || j.facilitator === undefined)
|
|
889
|
+
for (const job of [...mine, ...jobs]) {
|
|
890
|
+
const contract = job.contracts?.find((c) => c.id === id && c.round && c.round.step !== "frozen")
|
|
891
|
+
if (contract) return { job: this.#jobs.get(key(project, job.id)) ?? job, contract }
|
|
892
|
+
}
|
|
893
|
+
return undefined
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
// The user's preferences: applied as a new version, then the red team, or straight to the baseline check.
|
|
897
|
+
async roundPrefs(project: string, parent: string, id: string, prefs: Prefs): Promise<string> {
|
|
898
|
+
const found = this.roundJob(project, parent, id)
|
|
899
|
+
if (!found || found.contract.round?.step !== "prefs") return `Contract ${id} waits for no preferences.`
|
|
900
|
+
const { job, contract: c } = found
|
|
901
|
+
if (prefs.said) 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.`
|
|
902
|
+
applyPrefs(c, prefs)
|
|
903
|
+
c.version++
|
|
904
|
+
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() })
|
|
905
|
+
this.#jobs.set(key(project, job.id), job)
|
|
906
|
+
if (prefs.redteam) {
|
|
907
|
+
c.round!.step = "redteam"
|
|
908
|
+
saveJob(project, job)
|
|
909
|
+
saveContract(project, job.id, c)
|
|
910
|
+
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:
|
|
911
|
+
Red team: ${c.id} · ${job.id}
|
|
912
|
+
Files: <those files>
|
|
913
|
+
Its change is measured and never merged; its LOOPHOLE lines come to you when it ends.`
|
|
914
|
+
}
|
|
915
|
+
return this.#roundBaseline(project, job, c)
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
// "Red team: C1 · job-…": a writer that tries to game the draft contract, in its own worktree; never merged.
|
|
919
|
+
async #redteam(project: string, parent: string, role: Role, d: Delegation, ref: NonNullable<Delegation["redteam"]>, model: string): Promise<Delegated> {
|
|
920
|
+
const job = this.#jobs.get(key(project, ref.job)) ?? listJobs(project).find((j) => j.id === ref.job)
|
|
921
|
+
if (!job) throw new DelegationError(`Not started: there is no job ${ref.job} in this project.`)
|
|
922
|
+
const c = job.contracts?.find((x) => x.id === ref.contract)
|
|
923
|
+
if (!c || c.round?.step !== "redteam") throw new DelegationError(`Not started: contract ${ref.contract} of job ${job.id} is not waiting for its red team.`)
|
|
924
|
+
if (!WRITERS.has(role.id)) throw new DelegationError("Not started: a red team changes files; start it with agent coder.")
|
|
925
|
+
const parsed = parseFiles(d.files, project)
|
|
926
|
+
if (parsed.problem || !parsed.files.length) throw new DelegationError(`Not started: ${parsed.problem ?? "a red team needs a line \"Files: <the files a worker on this goal would change>\""}.`)
|
|
927
|
+
const checks = d.checks.length ? d.checks : ["true"]
|
|
928
|
+
const why = checkSetProblems(checks, true)
|
|
929
|
+
if (why) throw new DelegationError(`Not started: ${why}`)
|
|
930
|
+
this.#jobs.set(key(project, job.id), job)
|
|
931
|
+
const rel = await this.#integrate(project, job, true)
|
|
932
|
+
const added = addDelegated(job, { title: `${c.id} red team`, prompt: redteamPrompt(c), files: parsed.files, dependsOn: [], checks })
|
|
933
|
+
if (!added.task) throw new DelegationError(`Not started: ${added.errors!.join("; ")}`)
|
|
934
|
+
const task = added.task
|
|
935
|
+
task.role = role.id
|
|
936
|
+
task.model = model
|
|
937
|
+
task.redteam = c.id
|
|
938
|
+
task.contract = { id: c.id, version: c.version }
|
|
939
|
+
c.round!.redteam = task.id
|
|
940
|
+
for (const s of ["ready", "planned", "running"] as const) moveTask(task, s)
|
|
941
|
+
stage(task, "delegate", "pass", `${role.agent} on ${model}, red team of ${c.id}`)
|
|
942
|
+
return this.#start(project, parent, job, task, role, model, { ...d, body: [redteamPrompt(c), d.body].filter(Boolean).join("\n\n") }, checks, rel)
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
// The red team's report as it ended: its loopholes go to the round, and the user picks the ones to close; without
|
|
946
|
+
// any, the round goes on to the baseline. A red team whose change raised the score is a loophole in itself.
|
|
947
|
+
async noteLoopholes(session: string, report: string): Promise<string | undefined> {
|
|
948
|
+
const entry = this.#entry(session)
|
|
949
|
+
const job = entry && this.#job(entry)
|
|
950
|
+
const task = job?.tasks.find((t) => t.id === entry!.taskId)
|
|
951
|
+
const c = task?.redteam ? job!.contracts?.find((x) => x.id === task.redteam) : undefined
|
|
952
|
+
if (!entry || !job || !task || !c || c.round?.step !== "redteam") return undefined
|
|
953
|
+
const found = parseLoopholes(report)
|
|
954
|
+
const raised = task.score?.valid && c.baseline && better(c, task.score, { valid: true, values: c.baseline.values }) > 0
|
|
955
|
+
if (raised && !found.length) found.push({ what: `the red team raised the score (${describe(c, task.score!)}) without improving the goal; see its report in session ${session}` })
|
|
956
|
+
c.round.loopholes = found
|
|
957
|
+
if (!found.length) {
|
|
958
|
+
c.history.push({ version: c.version, change: "the red team found no loophole", at: new Date().toISOString() })
|
|
959
|
+
return `[micromanager] The red team of contract ${c.id} found no loophole. ${await this.#roundBaseline(entry.project, job, c)}`
|
|
960
|
+
}
|
|
961
|
+
c.round.step = "loopholes"
|
|
962
|
+
saveJob(entry.project, job)
|
|
963
|
+
saveContract(entry.project, job.id, c)
|
|
964
|
+
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.`)}`
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
// The loopholes the user chose to close: a guard each where the red team named one; then the baseline check.
|
|
968
|
+
async roundLoopholes(project: string, parent: string, id: string, picked: readonly number[]): Promise<string> {
|
|
969
|
+
const found = this.roundJob(project, parent, id)
|
|
970
|
+
if (!found || found.contract.round?.step !== "loopholes") return `Contract ${id} waits for no answer about loopholes.`
|
|
971
|
+
const { job, contract: c } = found
|
|
972
|
+
const chosen = picked.map((i) => c.round!.loopholes[i]).filter((l): l is NonNullable<typeof l> => Boolean(l))
|
|
973
|
+
// A guard the red team named on a value the evaluator does not print would never be checked: noted instead, like a
|
|
974
|
+
// loophole without a guard.
|
|
975
|
+
const measurable = (l: (typeof chosen)[number]) => Boolean(l.guard && c.baseline && l.guard.name in c.baseline.values)
|
|
976
|
+
for (const l of chosen) if (l.guard && !measurable(l)) Object.assign(l, { guard: undefined })
|
|
977
|
+
const guards = chosen.flatMap((l) => (l.guard && !c.guards.some((g) => g.name === l.guard!.name) ? [l.guard] : []))
|
|
978
|
+
c.guards = [...c.guards, ...guards]
|
|
979
|
+
if (chosen.length) {
|
|
980
|
+
c.version++
|
|
981
|
+
const unguarded = chosen.filter((l) => !l.guard)
|
|
982
|
+
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() })
|
|
983
|
+
}
|
|
984
|
+
const open = chosen.filter((l) => !l.guard)
|
|
985
|
+
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.` : ""
|
|
986
|
+
return `${guards.length ? `Contract ${c.id} has ${guards.length} new guard(s).` : "No guard was added."}${note} ${await this.#roundBaseline(project, job, c)}`
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
// The baseline the user checks before the freeze: three runs on each corpus, shown with their spread.
|
|
990
|
+
async #roundBaseline(project: string, job: Job, c: Contract): Promise<string> {
|
|
991
|
+
c.round = { ...(c.round ?? { loopholes: [] }), step: "baseline" }
|
|
992
|
+
const rel = await this.#integrate(project, job, false)
|
|
993
|
+
const dir = taskDir(job.integrationWorktree ?? project, rel)
|
|
994
|
+
const once = { ...c, repeats: 1 }
|
|
995
|
+
const visible: Measured[] = []
|
|
996
|
+
const heldOut: Measured[] = []
|
|
997
|
+
let seconds = 0
|
|
998
|
+
for (let i = 0; i < Math.max(3, c.repeats); i++) {
|
|
999
|
+
const r = await runEvaluator(dir, once, "visible", this.#exec)
|
|
1000
|
+
visible.push(r.measured)
|
|
1001
|
+
seconds += r.seconds
|
|
1002
|
+
if (c.corpus.heldOut) {
|
|
1003
|
+
const h = await runEvaluator(dir, once, "heldout", this.#exec, heldOutDir(project, job.id, c.id))
|
|
1004
|
+
heldOut.push(h.measured)
|
|
1005
|
+
seconds += h.seconds
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
this.#count(job, c, seconds)
|
|
1009
|
+
const med = median(visible)
|
|
1010
|
+
if (med.valid) c.baseline = { ...c.baseline!, values: { ...med.values }, at: new Date().toISOString() }
|
|
1011
|
+
const medHeld = heldOut.length ? median(heldOut) : undefined
|
|
1012
|
+
if (medHeld?.valid) c.baseline = { ...c.baseline!, heldOut: { ...medHeld.values } }
|
|
1013
|
+
this.#jobs.set(key(project, job.id), job)
|
|
1014
|
+
saveJob(project, job)
|
|
1015
|
+
saveContract(project, job.id, c)
|
|
1016
|
+
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.`)
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
// The user's answer to the baseline: freeze, measure again, or back to a draft.
|
|
1020
|
+
async roundBaseline(project: string, parent: string, id: string, decision: "plausible" | "again" | "change" | undefined, said?: string): Promise<string> {
|
|
1021
|
+
const found = this.roundJob(project, parent, id)
|
|
1022
|
+
if (!found || found.contract.round?.step !== "baseline") return `Contract ${id} waits for no baseline answer.`
|
|
1023
|
+
const { job, contract: c } = found
|
|
1024
|
+
if (decision === "again") return this.#roundBaseline(project, job, c)
|
|
1025
|
+
if (decision === "plausible") {
|
|
1026
|
+
await this.#freezeContract(project, job, c)
|
|
1027
|
+
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).`
|
|
1028
|
+
}
|
|
1029
|
+
c.round = undefined
|
|
1030
|
+
saveJob(project, job)
|
|
1031
|
+
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}").`
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
// A contract frozen: the files its evaluator names and its visible corpus, hashed on the job's branch.
|
|
1035
|
+
async #freezeContract(project: string, job: Job, c: Contract): Promise<void> {
|
|
1036
|
+
const rel = await this.#integrate(project, job, false)
|
|
1037
|
+
const worktree = job.integrationWorktree ?? project
|
|
1038
|
+
const dir = taskDir(worktree, rel)
|
|
1039
|
+
const corpus: string[] = []
|
|
1040
|
+
for (const p of c.corpus.visible) {
|
|
1041
|
+
const listed = await this.#exec("git", ["ls-files", "--", p], { cwd: dir })
|
|
1042
|
+
corpus.push(...listed.stdout.split("\n").map((l) => l.trim()).filter(Boolean))
|
|
1043
|
+
}
|
|
1044
|
+
const files = [...new Set([...namedFiles(c.evaluator, dir), ...corpus])].sort()
|
|
1045
|
+
c.frozen = { files: Object.fromEntries(await hashFiles(worktree, files, this.#exec, dir)), at: new Date().toISOString() }
|
|
1046
|
+
c.status = "frozen"
|
|
1047
|
+
c.round = { ...(c.round ?? { loopholes: [] }), step: "frozen" }
|
|
1048
|
+
c.history.push({ version: c.version, change: "frozen after the user checked the baseline", at: c.frozen.at })
|
|
1049
|
+
this.#jobs.set(key(project, job.id), job)
|
|
1050
|
+
saveJob(project, job)
|
|
1051
|
+
saveContract(project, job.id, c)
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
// For a contract the user settled outside the round (and the tests): frozen as it is.
|
|
1055
|
+
async freezeContract(project: string, jobId: string, id: string): Promise<void> {
|
|
1056
|
+
const job = this.#jobs.get(key(project, jobId)) ?? listJobs(project).find((j) => j.id === jobId)
|
|
1057
|
+
const c = job?.contracts?.find((x) => x.id === id)
|
|
1058
|
+
if (job && c) await this.#freezeContract(project, job, c)
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
// What a contract's evaluations cost: on the contract (its stop rule) and on the job (its counters).
|
|
1062
|
+
#count(job: Job, c: Contract, seconds: number): void {
|
|
1063
|
+
c.used = { evaluations: (c.used?.evaluations ?? 0) + 1, seconds: Math.round(((c.used?.seconds ?? 0) + seconds) * 10) / 10 }
|
|
1064
|
+
job.counters.evals = (job.counters.evals ?? 0) + 1
|
|
1065
|
+
job.counters.evalSeconds = Math.round(((job.counters.evalSeconds ?? 0) + seconds) * 10) / 10
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
// A writer's work measured against its contract, after its checks passed. Returns a failure the gate treats like a
|
|
1069
|
+
// failing check (an invalid result or a broken guard), with exhausted when the contract's stop rule allows no
|
|
1070
|
+
// further evaluation; or the evidence for a passing fitness stage.
|
|
1071
|
+
async #measure(entry: Entry, job: Job, task: Task): Promise<{ failed?: GateResult; exhausted?: boolean; evidence?: string }> {
|
|
1072
|
+
const c = job.contracts?.find((x) => x.id === entry.contract)
|
|
1073
|
+
if (!c) return {}
|
|
1074
|
+
const used = c.used ?? { evaluations: 0, seconds: 0 }
|
|
1075
|
+
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`)
|
|
1076
|
+
if (spent) 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 }
|
|
1077
|
+
const { measured, seconds } = await runEvaluator(entry.dir, c, "visible", this.#exec)
|
|
1078
|
+
this.#count(job, c, seconds)
|
|
1079
|
+
const broken = measured.valid ? guardViolations(c, measured) : []
|
|
1080
|
+
if (!measured.valid || broken.length) {
|
|
1081
|
+
const why = measured.valid ? `guard broken: ${broken.join("; ")}` : measured.error ?? "invalid"
|
|
1082
|
+
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 } }
|
|
1083
|
+
}
|
|
1084
|
+
task.score = { ...measured, corpus: "visible", at: new Date().toISOString() }
|
|
1085
|
+
return { evidence: describe(c, measured) }
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
// The difficulty on the task, and a trial when the plugin asked for one and the job can run one: in worktrees of its
|
|
1089
|
+
// own (no trial without git) and with Parallel on.
|
|
1090
|
+
#assess(project: string, job: Job, task: Task, assess?: Assessment, pick?: Delegation["pick"]): void {
|
|
1091
|
+
if (assess?.difficulty !== undefined) task.difficulty = assess.difficulty
|
|
1092
|
+
if (!assess || assess.trials < 2 || !WRITERS.has(task.role) || job.isolation === "none") return
|
|
1093
|
+
if (!optionsOf(loadControl(project, job.id), lastOptions(project)).parallel) return
|
|
1094
|
+
task.trial = { of: task.id, n: assess.trials, pick: pickFor(task.role, this.#trialPick, pick) }
|
|
1095
|
+
task.title = `${task.title.replace(/ \(attempt \d+\/\d+\)$/, "")} (attempt 1/${assess.trials})`.slice(0, 140)
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
// "Attempt: T5 · job-…": another attempt of T5's trial. It gets T5's task, files and checks, a worktree of its own,
|
|
1099
|
+
// and is not refused as the same work: that is what it is meant to be.
|
|
1100
|
+
async #attempt(project: string, parent: string, role: Role, d: Delegation, attempt: NonNullable<Delegation["attempt"]>, model: string): Promise<Delegated> {
|
|
1101
|
+
const job = this.#jobs.get(key(project, attempt.job)) ?? listJobs(project).find((j) => j.id === attempt.job)
|
|
1102
|
+
if (!job) throw new DelegationError(`Not started: there is no job ${attempt.job} in this project.`)
|
|
1103
|
+
if (job.facilitator && job.facilitator !== parent) throw new DelegationError(`Not started: job ${job.id} belongs to another micromanager session.`)
|
|
1104
|
+
if (loadControl(project, job.id).stopped) throw new DelegationError(`Not started: the user stopped job ${job.id}. Ask them whether to go on; nothing starts until they start it again.`)
|
|
1105
|
+
const head = job.tasks.find((t) => t.id === attempt.task)
|
|
1106
|
+
if (!head?.trial || head.trial.of !== head.id) throw new DelegationError(`Not started: ${attempt.task} runs no trial; start a task with its own prompt instead.`)
|
|
1107
|
+
if (head.role !== role.id) throw new DelegationError(`Not started: ${head.id} is a task for ${roleById(head.role)?.agent ?? head.role}; start its attempts with that agent.`)
|
|
1108
|
+
const now = standing(job, head)
|
|
1109
|
+
if (now.winner) throw new DelegationError(`Not started: ${now.winner.id} already won the trial of ${head.id}; its work is merged.`)
|
|
1110
|
+
if (now.all.length >= head.trial.n) 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(", ")}).`)
|
|
1111
|
+
const checks = this.#entries.get(`${job.id}/${head.id}`)?.checks ?? []
|
|
1112
|
+
const title = `${head.title.replace(/ \(attempt \d+\/\d+\)$/, "")} (attempt ${now.all.length + 1}/${head.trial.n})`
|
|
1113
|
+
const added = addDelegated(job, { title, prompt: head.description, files: head.files, dependsOn: [], checks })
|
|
1114
|
+
if (!added.task) throw new DelegationError(`Not started: ${added.errors!.join("; ")}`)
|
|
1115
|
+
const task = added.task
|
|
1116
|
+
task.role = role.id
|
|
1117
|
+
task.model = model
|
|
1118
|
+
task.trial = { ...head.trial }
|
|
1119
|
+
if (head.difficulty !== undefined) task.difficulty = head.difficulty
|
|
1120
|
+
if (head.contract) task.contract = { ...head.contract }
|
|
1121
|
+
if (head.freeze) task.freeze = [...head.freeze]
|
|
1122
|
+
if (head.preview) task.preview = head.preview
|
|
1123
|
+
this.#jobs.set(key(project, job.id), job)
|
|
1124
|
+
for (const s of ["ready", "planned", "running"] as const) moveTask(task, s)
|
|
1125
|
+
stage(task, "delegate", "pass", `${role.agent} on ${model}, attempt of ${head.id}`)
|
|
1126
|
+
const rel = await this.#integrate(project, job, true)
|
|
1127
|
+
const body = job.rolling ? head.description : this.#plannedBody(job, head, d.body)
|
|
1128
|
+
return this.#start(project, parent, job, task, role, model, { ...d, body }, checks, rel)
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
// The fan-out note for a trial's first attempt, once its subagent call went through; undefined for any other task.
|
|
1132
|
+
trialNote(project: string, jobId: string, taskId: string): string | undefined {
|
|
1133
|
+
const job = this.#jobs.get(key(project, jobId))
|
|
1134
|
+
const task = job?.tasks.find((t) => t.id === taskId)
|
|
1135
|
+
return job && task ? fanOutText(job, task) : undefined
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
// The models a trial's attempts run on so far, so the next attempt goes to another family.
|
|
1139
|
+
trialModels(project: string, jobId: string, taskId: string): string[] {
|
|
1140
|
+
const job = this.#jobs.get(key(project, jobId)) ?? listJobs(project).find((j) => j.id === jobId)
|
|
1141
|
+
const task = job?.tasks.find((t) => t.id === taskId)
|
|
1142
|
+
return job && task ? attempts(job, task).map((t) => t.model).filter((m): m is string => Boolean(m)) : []
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
// The job's branch and its worktree, made at its first task. Returns the project's offset inside the repository.
|
|
1146
|
+
async #integrate(project: string, job: Job, writer = true): Promise<string> {
|
|
1147
|
+
if (job.isolation === "none") {
|
|
1148
|
+
job.integrationWorktree = project
|
|
1149
|
+
job.integrationRel = ""
|
|
1150
|
+
return ""
|
|
1151
|
+
}
|
|
1152
|
+
if (job.integrationWorktree) {
|
|
1153
|
+
const v = await validateIntegration(job, this.#exec)
|
|
1154
|
+
if (!v.ok) throw new IntegrationError(`integration worktree invalid: ${v.message}`)
|
|
1155
|
+
}
|
|
1156
|
+
if (!job.integrationWorktree) {
|
|
1157
|
+
if ((await gitState(project, this.#exec)) !== "repo") {
|
|
1158
|
+
if (!writer) return "" // a reader changes nothing: it reads the project folder itself, no question needed
|
|
1159
|
+
const note = this.#noGit ? await this.#noGit(project) : `${project} 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.`
|
|
1160
|
+
throw new NoGitError(`Not started: ${note}`)
|
|
1161
|
+
}
|
|
1162
|
+
excludeFromGit(project)
|
|
1163
|
+
const integration = await prepareIntegration(project, job.id, this.#exec)
|
|
1164
|
+
job.integrationBranch = integration.branch
|
|
1165
|
+
job.integrationWorktree = integration.worktree
|
|
1166
|
+
// The offset and the uncommitted state are kept on the job: a worker session outlives this process, and a
|
|
1167
|
+
// project below the repository root (or a task that needs an uncommitted file) must not depend on this call.
|
|
1168
|
+
job.integrationRel = integration.rel
|
|
1169
|
+
job.integrationBase = integration.base
|
|
1170
|
+
job.integrationDirty = integration.dirty ? integration.dirtySummary : ""
|
|
1171
|
+
}
|
|
1172
|
+
// A job file written before the offset was tracked has none: git is asked once, so a job that predates this does
|
|
1173
|
+
// not keep sending its workers to the worktree root.
|
|
1174
|
+
return job.integrationRel ?? (job.integrationWorktree ? await repoRel(project, this.#exec) : "")
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
// A running task's entry, its worktree (writer) and the worker's brief.
|
|
1178
|
+
async #start(project: string, parent: string, job: Job, task: Task, role: Role, model: string, d: Delegation, checks: string[], rel: string): Promise<Delegated> {
|
|
1179
|
+
const writer = WRITERS.has(role.id)
|
|
1180
|
+
const base = job.integrationWorktree ?? project // a reader in a folder without git reads the folder itself
|
|
1181
|
+
const entry: Entry = { project, jobId: job.id, taskId: task.id, parent, writer, dir: taskDir(base, rel), worktree: base, rel, checks, ...(task.contract ? { contract: task.contract.id } : {}) }
|
|
1182
|
+
if (writer && job.isolation === "none") {
|
|
1183
|
+
// No git: the project itself, and no branch; the worktree is the project, so adopt and resume keep it.
|
|
1184
|
+
task.worktree = project
|
|
1185
|
+
task.worktreeRel = ""
|
|
1186
|
+
} else if (writer) {
|
|
1187
|
+
const w = await prepareTaskWorktree(project, job.id, task.id, job.integrationBranch!, this.#exec, undefined, rel)
|
|
1188
|
+
entry.dir = w.dir
|
|
1189
|
+
entry.worktree = w.worktree
|
|
1190
|
+
entry.branch = w.branch
|
|
1191
|
+
task.worktree = w.worktree
|
|
1192
|
+
task.worktreeRel = w.rel
|
|
1193
|
+
task.branch = w.branch
|
|
1194
|
+
}
|
|
1195
|
+
if (writer) await this.#freeze(job, task, entry)
|
|
1196
|
+
const graph = role.id === "explore" ? await this.#graphs.get(entry.dir) : undefined
|
|
1197
|
+
entry.graph = Boolean(graph)
|
|
1198
|
+
this.#entries.set(`${job.id}/${task.id}`, entry)
|
|
1199
|
+
task.checks = [...checks]
|
|
1200
|
+
saveJob(project, job)
|
|
1201
|
+
// A project below the repository root and an uncommitted working tree are both invisible from the inside: the
|
|
1202
|
+
// worktree holds the whole repository, and no worker can see what the user has not committed.
|
|
1203
|
+
const notes = [
|
|
1204
|
+
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}` : "",
|
|
1205
|
+
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})` : "",
|
|
1206
|
+
].filter(Boolean)
|
|
1207
|
+
return { task, job, prompt: this.#brief(job, task, role, model, d, entry, graph), notes }
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
// run_job: a planned job runs on the micromanager's own workers from now on. The job's phase goes to execute and the
|
|
1211
|
+
// session becomes its facilitator; nextStep (src/continuation.ts) then names the tasks to start.
|
|
1212
|
+
runPlanned(project: string, jobId: string, parent: string): { job?: Job; problem?: string } {
|
|
1213
|
+
const job = this.#jobs.get(key(project, jobId)) ?? listJobs(project).find((j) => j.id === jobId)
|
|
1214
|
+
if (!job) return { problem: `there is no job ${jobId} in this project` }
|
|
1215
|
+
if (job.rolling) return { problem: `${jobId} holds the tasks you delegated yourself; it has no plan to run` }
|
|
1216
|
+
if (!job.tasks.length) return { problem: `${jobId} has no tasks yet; plan it with plan_job first` }
|
|
1217
|
+
if (job.phase === "plan_gate") moveJob(job, "execute")
|
|
1218
|
+
else if ((job.phase === "paused" || job.phase === "ask_user") && job.resumePhase === "execute") moveJob(job, "execute")
|
|
1219
|
+
if (job.phase !== "execute") return { problem: `job ${jobId} is in phase ${job.phase}, not ready to run` }
|
|
1220
|
+
job.native = true
|
|
1221
|
+
if (job.facilitator !== parent) {
|
|
1222
|
+
job.facilitator = parent
|
|
1223
|
+
for (const entry of this.#entries.values()) if (entry.jobId === job.id && entry.project === project) entry.parent = parent
|
|
1224
|
+
}
|
|
1225
|
+
this.#jobs.set(key(project, job.id), job)
|
|
1226
|
+
saveJob(project, job)
|
|
1227
|
+
return { job }
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
// "Task: T5 · job-…": the micromanager starts a task of a planned job (run_job). The plan already says what it is:
|
|
1231
|
+
// its role, files, acceptance points and checks; the prompt can add to it. A task that ran before (on the runner, or
|
|
1232
|
+
// a worker that stopped) starts over in a fresh worktree; continuing its old worker is the way to keep its change.
|
|
1233
|
+
async #planned(project: string, parent: string, role: Role, d: Delegation, planned: NonNullable<Delegation["planned"]>, model: string, assess?: Assessment): Promise<Delegated> {
|
|
1234
|
+
const job = this.#jobs.get(key(project, planned.job)) ?? listJobs(project).find((j) => j.id === planned.job)
|
|
1235
|
+
if (!job) throw new DelegationError(`Not started: there is no job ${planned.job} in this project.`)
|
|
1236
|
+
if (!job.native && !job.rolling) throw new DelegationError(`Not started: job ${job.id} is not running on your workers; start it with run_job first.`)
|
|
1237
|
+
if (job.facilitator && job.facilitator !== parent) throw new DelegationError(`Not started: job ${job.id} belongs to another micromanager session; run_job ${job.id} here takes it over.`)
|
|
1238
|
+
if (job.phase !== "execute") throw new DelegationError(`Not started: job ${job.id} is ${job.phase}; run_job resumes it.`)
|
|
1239
|
+
const control = loadControl(project, job.id)
|
|
1240
|
+
if (control.stopped) throw new DelegationError(`Not started: the user stopped job ${job.id}. Ask them whether to go on; nothing starts until they start it again.`)
|
|
1241
|
+
const unstarted = this.#planFirst && job.rolling && WRITERS.has(role.id) ? this.startNote(project, job) : undefined
|
|
1242
|
+
if (unstarted) throw new DelegationError(`Not started: ${unstarted}`)
|
|
1243
|
+
const task = job.tasks.find((t) => t.id === planned.task)
|
|
1244
|
+
if (!task) throw new DelegationError(`Not started: job ${job.id} has no task ${planned.task}.`)
|
|
1245
|
+
const agent = roleById(task.role)?.agent ?? task.role
|
|
1246
|
+
if (task.role !== role.id) throw new DelegationError(`Not started: ${task.id} is a task for ${agent}; start it with agent ${agent}.`)
|
|
1247
|
+
const k = `${job.id}/${task.id}`
|
|
1248
|
+
const old = this.#entries.get(k)
|
|
1249
|
+
if (LIVE.has(task.status) && old && !old.ended) throw new DelegationError(`Not started: ${task.id} runs already${old.session ? ` (session ${old.session})` : ""}; its report comes to you when it ends.`)
|
|
1250
|
+
if (task.status === "merged" || task.status === "passed") throw new DelegationError(`Not started: ${task.id} is done already (${task.status}).`)
|
|
1251
|
+
if (WRITERS.has(role.id) && (job.isolation === "none" || !optionsOf(control, lastOptions(project)).parallel)) {
|
|
1252
|
+
const busy = [...this.#entries.values()].find((e) => e.jobId === job.id && e.project === project && e.writer && !e.ended && e.taskId !== task.id)
|
|
1253
|
+
if (busy) 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.`)
|
|
1254
|
+
}
|
|
1255
|
+
const byId = new Map(job.tasks.map((t) => [t.id, t]))
|
|
1256
|
+
const elsewhere = (id: string) => { const [owner, taskId] = this.#owner(project, job, id); return owner?.tasks.find((t) => t.id === taskId)?.status }
|
|
1257
|
+
const waits = task.dependsOn.filter((id) => { const dep = byId.get(id); return !dep || !settled(job, dep, elsewhere) })
|
|
1258
|
+
if (waits.length) throw new DelegationError(`Not started: ${task.id} waits for ${waits.join(", ")}; start it when ${waits.length > 1 ? "they are" : "it is"} merged.`)
|
|
1259
|
+
const checks = d.checks.length ? d.checks : [...new Set(taskAcceptance(job, task).map((a) => a.verify).filter((v): v is string => Boolean(v)))]
|
|
1260
|
+
if (d.checks.length) {
|
|
1261
|
+
const problem = checkSetProblems(d.checks, WRITERS.has(role.id))
|
|
1262
|
+
if (problem) throw new DelegationError(`Not started: ${problem}`)
|
|
1263
|
+
}
|
|
1264
|
+
const contract = d.contract ?? task.contract?.id
|
|
1265
|
+
const c = this.#contractFor(job, WRITERS.has(role.id), contract, assess)
|
|
1266
|
+
this.#offerEvolver(project, job, c, task.files, task.title, checks, d, assess)
|
|
1267
|
+
if (d.method === "trial") assess = { ...(assess ?? {}), trials: Math.max(2, assess?.trials ?? 1) }
|
|
1268
|
+
this.#jobs.set(key(project, job.id), job)
|
|
1269
|
+
if (old) {
|
|
1270
|
+
await this.#dropWorktree(old, task)
|
|
1271
|
+
this.#entries.delete(k)
|
|
1272
|
+
} else if (task.worktree && task.branch) {
|
|
1273
|
+
await removeTaskWorktree(project, { worktree: task.worktree, branch: task.branch }, this.#exec).catch(() => undefined)
|
|
1274
|
+
task.worktree = undefined
|
|
1275
|
+
task.branch = undefined
|
|
1276
|
+
}
|
|
1277
|
+
// A todo that does other tasks over: their worktrees go now, as for a delegation's "Replaces:" line.
|
|
1278
|
+
await this.#replace(project, job, task.replaces ?? [])
|
|
1279
|
+
restart(task)
|
|
1280
|
+
task.model = model
|
|
1281
|
+
task.attempts = 0
|
|
1282
|
+
// A task started again starts a new trial, if it gets one: the old attempts' trial is over.
|
|
1283
|
+
task.trial = undefined
|
|
1284
|
+
this.#assess(project, job, task, assess, d.pick)
|
|
1285
|
+
if (d.preview) task.preview = d.preview
|
|
1286
|
+
this.#bind(job, task, contract)
|
|
1287
|
+
if (d.frozen) task.freeze = [...new Set([...(task.freeze ?? []), ...parseFiles(d.frozen, project).files])]
|
|
1288
|
+
stage(task, "delegate", "pass", `${role.agent} on ${model}, planned task`)
|
|
1289
|
+
const rel = await this.#integrate(project, job, WRITERS.has(role.id))
|
|
1290
|
+
return this.#start(project, parent, job, task, role, model, { ...d, body: this.#plannedBody(job, task, d.body) }, checks, rel)
|
|
1291
|
+
}
|
|
1292
|
+
|
|
1293
|
+
// A planned task's brief: the job, the task, its acceptance points and decisions, and what the micromanager added.
|
|
1294
|
+
#plannedBody(job: Job, task: Task, extra: string): string {
|
|
1295
|
+
const acceptance = taskAcceptance(job, task).map((a) => `- ${a.id}: ${a.text}${a.verify ? ` (checked with: ${a.verify})` : ""}${sharedNote(job, task, a.id)}`)
|
|
1296
|
+
return [
|
|
1297
|
+
`The job: ${job.goal}`,
|
|
1298
|
+
"",
|
|
1299
|
+
`Your task (${task.id}): ${task.title.replace(/ \(attempt \d+\/\d+\)$/, "")}`,
|
|
1300
|
+
task.description,
|
|
1301
|
+
"",
|
|
1302
|
+
"Acceptance points:",
|
|
1303
|
+
...(acceptance.length ? acceptance : ["- none given"]),
|
|
1304
|
+
job.decisions.length ? `\nDecisions that apply: ${job.decisions.map((x) => x.text).join("; ")}` : "",
|
|
1305
|
+
extra ? `\nFrom the micromanager: ${extra}` : "",
|
|
1306
|
+
].filter((line) => line !== "").join("\n")
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
// "Replaces: T5": the micromanager starts T5's work over on purpose. T5 is cancelled and its worktree, with whatever
|
|
1310
|
+
// change it held, goes; a task that still runs has to be stopped first, and a merged one has nothing to replace.
|
|
1311
|
+
async #replace(project: string, job: Job, ids: readonly string[]): Promise<void> {
|
|
1312
|
+
const cannot = this.#replaceable(project, job, ids)
|
|
1313
|
+
if (cannot.length) throw new DelegationError(`Not started: ${cannot.join("; ")}`)
|
|
1314
|
+
for (const id of ids) {
|
|
1315
|
+
const [owner, taskId] = this.#owner(project, job, id)
|
|
1316
|
+
if (owner && owner.tasks.find((t) => t.id === taskId)?.status !== "cancelled") await this.discard(project, owner, taskId, "replace", "started over by a new task")
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
// The job a replaced id lives in and the task id inside it: "T19" in this job, "job-…/T18" in another of the project.
|
|
1321
|
+
#owner(project: string, job: Job, id: string): [Job | undefined, string] {
|
|
1322
|
+
const [jobId, taskId] = id.includes("/") ? id.split("/") as [string, string] : [job.id, id]
|
|
1323
|
+
if (jobId === job.id) return [job, taskId]
|
|
1324
|
+
return [this.current(project, jobId) ?? listJobs(project).find((j) => j.id === jobId), taskId]
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
// Why the given tasks cannot be done over: missing, still running, or merged already. Empty when they can.
|
|
1328
|
+
#replaceable(project: string, job: Job, ids: readonly string[]): string[] {
|
|
1329
|
+
return ids.flatMap((id) => {
|
|
1330
|
+
const [owner, taskId] = this.#owner(project, job, id)
|
|
1331
|
+
const task = owner?.tasks.find((t) => t.id === taskId)
|
|
1332
|
+
if (!owner || !task) return [`there is no task ${id} to replace`]
|
|
1333
|
+
if (LIVE.has(task.status) && !this.#entries.get(`${owner.id}/${taskId}`)?.ended) return [`${id} still runs; stop it with stop_task first, then replace it`]
|
|
1334
|
+
if (task.status === "merged" || task.status === "passed") return [`${id} is ${task.status}, so there is nothing to replace; say in the new task what to change on top of it`]
|
|
1335
|
+
return []
|
|
1336
|
+
})
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
// The link both ways: the new task names what it does over, each old task the one doing it (job-qualified across jobs).
|
|
1340
|
+
#link(project: string, job: Job, task: Task, ids: readonly string[]): void {
|
|
1341
|
+
if (!ids.length) return
|
|
1342
|
+
task.replaces = [...ids]
|
|
1343
|
+
for (const id of ids) {
|
|
1344
|
+
const [owner, taskId] = this.#owner(project, job, id)
|
|
1345
|
+
const old = owner?.tasks.find((t) => t.id === taskId)
|
|
1346
|
+
if (!owner || !old) continue
|
|
1347
|
+
old.replacedBy = owner === job ? task.id : `${job.id}/${task.id}`
|
|
1348
|
+
if (owner !== job) saveJob(project, owner)
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
// A task given up for good: cancelled, and its worktree and branch gone, whatever change they held. For "Replaces:"
|
|
1353
|
+
// and for rewind_job, which must not leave a branch cut from a tip it took back (the merge train would replay it).
|
|
1354
|
+
async discard(project: string, job: Job, taskId: string, why: string, evidence: string): Promise<void> {
|
|
1355
|
+
const task = job.tasks.find((t) => t.id === taskId)
|
|
1356
|
+
if (!task) return
|
|
1357
|
+
const k = `${job.id}/${taskId}`
|
|
1358
|
+
const entry = this.#entries.get(k)
|
|
1359
|
+
if (task.status !== "cancelled" && task.status !== "merged") moveTask(task, "cancelled")
|
|
1360
|
+
stage(task, why, "pass", evidence)
|
|
1361
|
+
if (entry) {
|
|
1362
|
+
await this.#dropWorktree(entry, task)
|
|
1363
|
+
this.#entries.delete(k)
|
|
1364
|
+
} else if (task.worktree && task.branch) {
|
|
1365
|
+
await removeTaskWorktree(project, { worktree: task.worktree, branch: task.branch }, this.#exec)
|
|
1366
|
+
task.worktree = undefined
|
|
1367
|
+
task.branch = undefined
|
|
1368
|
+
}
|
|
1369
|
+
saveJob(project, job)
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
// The job as this process holds it, when it holds it: the copy the plugin's tools must change, because this one is
|
|
1373
|
+
// saved over the file every time a worker moves on.
|
|
1374
|
+
current(project: string, jobId: string): Job | undefined {
|
|
1375
|
+
return this.#jobs.get(key(project, jobId))
|
|
1376
|
+
}
|
|
1377
|
+
|
|
1378
|
+
// The same work delegated a second time (live run, 2026-10-07: three tasks each removed the same pill from the same
|
|
1379
|
+
// slide, because the first two stopped before their merge and the micromanager started over instead of continuing).
|
|
1380
|
+
// A writer on files another writer of this job is changing, or left unfinished with its change still in its worktree,
|
|
1381
|
+
// and whose title or brief is about the same thing, is refused with what to do instead; a reader is refused when one
|
|
1382
|
+
// with nearly the same brief still runs. Returns the refusal, or undefined.
|
|
1383
|
+
#duplicate(job: Job, role: Role, title: string, body: string, files: readonly string[], replaced: readonly string[]): string | undefined {
|
|
1384
|
+
const writer = WRITERS.has(role.id)
|
|
1385
|
+
for (const task of job.tasks) {
|
|
1386
|
+
if (replaced.includes(task.id)) continue
|
|
1387
|
+
const entry = this.#entries.get(`${job.id}/${task.id}`)
|
|
1388
|
+
// A task whose worker has not started yet counts as running: two equal calls in one message come one after the
|
|
1389
|
+
// other, before either child exists.
|
|
1390
|
+
if (!entry || entry.writer !== writer) continue
|
|
1391
|
+
const session = entry.session ? `session ${entry.session}` : "its worker is starting"
|
|
1392
|
+
if (!writer) {
|
|
1393
|
+
if (LIVE.has(task.status) && !entry.ended && task.role === role.id && similarity(body, task.description) >= SAME_QUESTION) {
|
|
1394
|
+
return `Not started: ${task.id} "${task.title}" asks this already (${session}); its report comes to you when it ends.`
|
|
1395
|
+
}
|
|
1396
|
+
continue
|
|
1397
|
+
}
|
|
1398
|
+
const shared = files.filter((f) => task.files.includes(f))
|
|
1399
|
+
if (!shared.length) continue
|
|
1400
|
+
if (similarity(title, task.title) < SAME_WORK && similarity(body, task.description) < SAME_WORK) continue
|
|
1401
|
+
if (LIVE.has(task.status) && !entry.ended) {
|
|
1402
|
+
return `Not started: ${task.id} "${task.title}" is doing this already (it changes ${shared.join(", ")}; ${session}). 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}".`
|
|
1403
|
+
}
|
|
1404
|
+
if ((UNFINISHED.has(task.status) || (LIVE.has(task.status) && entry.ended)) && !entry.removed && entry.session) {
|
|
1405
|
+
const last = task.stages[task.stages.length - 1]
|
|
1406
|
+
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 its worktree. Continue it with the subagent tool and sessionID ${entry.session}, saying what is left, so the change is kept. To start over instead, add a line "Replaces: ${task.id}": its worktree is discarded.`
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
return undefined
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
// The subagent call failed before its child took the task (refused, an unknown agent): the task is dropped.
|
|
1413
|
+
async abandon(prompt: string): Promise<void> {
|
|
1414
|
+
const k = tokenOf(prompt)
|
|
1415
|
+
const entry = k ? this.#entries.get(k) : undefined
|
|
1416
|
+
if (!entry || entry.session) return
|
|
1417
|
+
const job = this.#job(entry)
|
|
1418
|
+
const task = job?.tasks.find((t) => t.id === entry.taskId)
|
|
1419
|
+
if (task) {
|
|
1420
|
+
moveTask(task, "cancelled")
|
|
1421
|
+
stage(task, "delegate", "fail", "the subagent call failed")
|
|
1422
|
+
}
|
|
1423
|
+
await this.#dropWorktree(entry, task)
|
|
1424
|
+
this.#entries.delete(k!)
|
|
1425
|
+
if (job) saveJob(entry.project, job)
|
|
1426
|
+
}
|
|
1427
|
+
|
|
1428
|
+
// A child's first prompt: the directory it must move to, when it carries one of our tasks.
|
|
1429
|
+
claim(session: string, text: string): { dir: string; task: string; parent: string } | undefined {
|
|
1430
|
+
if (!text.startsWith(CHILD_PREFIX)) return undefined
|
|
1431
|
+
const k = tokenOf(text)
|
|
1432
|
+
const entry = k ? this.#entries.get(k) : undefined
|
|
1433
|
+
if (!entry || entry.session) return undefined
|
|
1434
|
+
entry.session = session
|
|
1435
|
+
this.#bySession.set(session, k!)
|
|
1436
|
+
const job = this.#job(entry)
|
|
1437
|
+
const task = job?.tasks.find((t) => t.id === entry.taskId)
|
|
1438
|
+
if (job && task) {
|
|
1439
|
+
task.session = session
|
|
1440
|
+
task.sessions = [...(task.sessions ?? []), session]
|
|
1441
|
+
saveJob(entry.project, job)
|
|
1442
|
+
}
|
|
1443
|
+
return { dir: entry.dir, task: `${entry.taskId} ${task?.title ?? ""}: ${task?.description ?? ""}`, parent: entry.parent }
|
|
1444
|
+
}
|
|
1445
|
+
|
|
1446
|
+
// The micromanager continues a worker (subagent with its sessionID): a writer that ended (merged, cancelled, or
|
|
1447
|
+
// stopped) runs again on the same task, reusing its id, branch and worktree.
|
|
1448
|
+
async resume(session: string): Promise<Task | undefined> {
|
|
1449
|
+
const entry = this.#entry(session)
|
|
1450
|
+
const job = entry && this.#job(entry)
|
|
1451
|
+
let task = job?.tasks.find((t) => t.id === entry!.taskId)
|
|
1452
|
+
if (!entry || !job || !task) return undefined
|
|
1453
|
+
entry.ended = false
|
|
1454
|
+
const wasTerminal = task.status === "merged" || task.status === "cancelled"
|
|
1455
|
+
if (task.status === "cancelled") restart(task)
|
|
1456
|
+
if (task.status === "merged") moveTask(task, "running") // continued: next change on top of the merged one
|
|
1457
|
+
else if (task.status === "passed") { moveTask(task, "escalated"); moveTask(task, "running") }
|
|
1458
|
+
else if (task.status === "escalated" || task.status === "blocked") moveTask(task, "running")
|
|
1459
|
+
if (wasTerminal) { task.attempts = 0; task.trial = undefined }
|
|
1460
|
+
// readers and already-running tasks just keep going
|
|
1461
|
+
task.session = session
|
|
1462
|
+
task.sessions = [...new Set([...(task.sessions ?? []), session])]
|
|
1463
|
+
// The sidebar tells a stopped worker by its last stage ("end"): continuing it runs again.
|
|
1464
|
+
stage(task, "resume", "pass", `continued in session ${session}`)
|
|
1465
|
+
if (entry.writer && entry.removed) {
|
|
1466
|
+
// The session keeps its directory, so the worktree comes back where it was: the worktree root, which is what git
|
|
1467
|
+
// registers, not the project directory inside it.
|
|
1468
|
+
const w = await prepareTaskWorktree(entry.project, job.id, entry.taskId, job.integrationBranch!, this.#exec, entry.worktree, entry.rel)
|
|
1469
|
+
entry.worktree = w.worktree
|
|
1470
|
+
entry.dir = w.dir
|
|
1471
|
+
entry.branch = w.branch
|
|
1472
|
+
entry.removed = false
|
|
1473
|
+
task.worktree = w.worktree
|
|
1474
|
+
task.worktreeRel = w.rel
|
|
1475
|
+
task.branch = w.branch
|
|
1476
|
+
}
|
|
1477
|
+
saveJob(entry.project, job)
|
|
1478
|
+
return task
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1481
|
+
isWorker(session: string): boolean {
|
|
1482
|
+
return this.#bySession.has(session)
|
|
1483
|
+
}
|
|
1484
|
+
|
|
1485
|
+
// A worker's role, for the tools it may use (request_network: writers and researchers).
|
|
1486
|
+
roleOf(session: string): RoleId | undefined {
|
|
1487
|
+
const entry = this.#entry(session)
|
|
1488
|
+
return (entry && this.#job(entry)?.tasks.find((t) => t.id === entry.taskId)?.role) as RoleId | undefined
|
|
1489
|
+
}
|
|
1490
|
+
|
|
1491
|
+
isWriter(session: string): boolean {
|
|
1492
|
+
return this.#entry(session)?.writer ?? false
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
// The micromanager session a worker answers to, and how that session knows its task (src/ask.ts).
|
|
1496
|
+
ownerOf(session: string): { parent: string; task: string } | undefined {
|
|
1497
|
+
const entry = this.#entry(session)
|
|
1498
|
+
if (!entry) return undefined
|
|
1499
|
+
const task = this.#job(entry)?.tasks.find((t) => t.id === entry.taskId)
|
|
1500
|
+
return { parent: entry.parent, task: task ? `${task.id} ${task.title}` : entry.taskId }
|
|
1501
|
+
}
|
|
1502
|
+
|
|
1503
|
+
// A writer as its helpers see it (src/helpers.ts): where it works and what it works on. Undefined for anyone else.
|
|
1504
|
+
writerOf(session: string): { dir: string; label: string; task: string } | undefined {
|
|
1505
|
+
const entry = this.#entry(session)
|
|
1506
|
+
if (!entry?.writer) return undefined
|
|
1507
|
+
const task = this.#job(entry)?.tasks.find((t) => t.id === entry.taskId)
|
|
1508
|
+
return { dir: entry.dir, label: `${entry.taskId} of ${entry.jobId}`, task: task ? `${task.title}: ${task.description}`.slice(0, 1500) : entry.taskId }
|
|
1509
|
+
}
|
|
1510
|
+
|
|
1511
|
+
hasGraph(session: string): boolean {
|
|
1512
|
+
return this.#entry(session)?.graph ?? false
|
|
1513
|
+
}
|
|
1514
|
+
|
|
1515
|
+
// The code_graph tool: one question to the graph of the explorer's directory, rebuilt first when the session
|
|
1516
|
+
// branch moved on (a writer merged) since the last build.
|
|
1517
|
+
async askGraph(session: string, action: string, symbol: string, to: string): Promise<string> {
|
|
1518
|
+
const entry = this.#entry(session)
|
|
1519
|
+
if (!entry?.graph) return "This session has no code graph."
|
|
1520
|
+
if (!(await this.#graphs.get(entry.dir))) return "The code graph could not be built; use grep and read instead."
|
|
1521
|
+
return queryGraph(entry.dir, action, symbol, to, this.#exec)
|
|
1522
|
+
}
|
|
1523
|
+
|
|
1524
|
+
// finish_task: the checks in the worker's worktree, then the commit and the merge train. The text goes back to the
|
|
1525
|
+
// worker; note is what the micromanager should hear (undefined: nothing new).
|
|
1526
|
+
// stop: the sessions of a trial's other attempts, which the plugin interrupts once one attempt won.
|
|
1527
|
+
async finish(session: string, summary: string): Promise<{ text: string; note?: string; parent?: string; stop?: string[] }> {
|
|
1528
|
+
const entry = this.#entry(session)
|
|
1529
|
+
const job = entry && this.#job(entry)
|
|
1530
|
+
const task = job?.tasks.find((t) => t.id === entry!.taskId)
|
|
1531
|
+
if (!entry || !job || !task) return { text: "This session has no task of the micromanager; there is nothing to finish." }
|
|
1532
|
+
return this.#finish(entry, job, task, summary, session)
|
|
1533
|
+
}
|
|
1534
|
+
|
|
1535
|
+
// The evolver's best candidate (src/evolver.ts), written into its task's worktree: through the same gate as a
|
|
1536
|
+
// writer's finish_task (checks, frozen files, the contract, the merge train). There is no session to hand a failure
|
|
1537
|
+
// back to, so a failing round blocks the task at once.
|
|
1538
|
+
async finishEvolved(project: string, jobId: string, taskId: string, code: string, summary: string): Promise<{ text: string; note?: string; parent?: string; stop?: string[] }> {
|
|
1539
|
+
const entry = this.#entries.get(`${jobId}/${taskId}`)
|
|
1540
|
+
const job = this.#jobs.get(key(project, jobId))
|
|
1541
|
+
const task = job?.tasks.find((t) => t.id === taskId)
|
|
1542
|
+
if (!entry || !job || !task) return { text: `there is no evolving task ${taskId} in job ${jobId}` }
|
|
1543
|
+
writeFileSync(join(entry.dir, task.files[0]!), code)
|
|
1544
|
+
task.attempts = FIX_ROUNDS // no session to fix it: a failure is final
|
|
1545
|
+
return this.#finish(entry, job, task, summary, `the evolver of ${task.id}`)
|
|
1546
|
+
}
|
|
1547
|
+
|
|
1548
|
+
// An evolving task: a writer task with its own worktree like any other, but no session; the evolver works on a
|
|
1549
|
+
// copy of its directory and its best candidate comes back through finishEvolved. Returns the task and its directory,
|
|
1550
|
+
// or why not.
|
|
1551
|
+
async prepareEvolve(project: string, parent: string, jobId: string, r: { contract: string; file: string; block: string; checks: readonly string[] }): Promise<{ job?: Job; task?: Task; dir?: string; contract?: Contract; problem?: string }> {
|
|
1552
|
+
const job = jobId ? this.#jobs.get(key(project, jobId)) ?? listJobs(project).find((j) => j.id === jobId) : this.job(project, parent)
|
|
1553
|
+
if (!job) return { problem: `there is no job ${jobId} in this project` }
|
|
1554
|
+
const parsed = parseFiles(r.file, project)
|
|
1555
|
+
if (parsed.problem || parsed.files.length !== 1) return { problem: parsed.problem ?? "file: the one file whose block evolves" }
|
|
1556
|
+
const checks = checkSetProblems(r.checks, true)
|
|
1557
|
+
if (checks) return { problem: checks }
|
|
1558
|
+
let c: Contract | undefined
|
|
1559
|
+
try {
|
|
1560
|
+
c = this.#contractFor(job, true, r.contract.toUpperCase())
|
|
1561
|
+
} catch (err) {
|
|
1562
|
+
return { problem: err instanceof Error ? err.message.replace(/^Not started: /, "") : String(err) }
|
|
1563
|
+
}
|
|
1564
|
+
if (!c) return { problem: "contract: the frozen contract that measures the evolution" }
|
|
1565
|
+
this.#jobs.set(key(project, job.id), job)
|
|
1566
|
+
const rel = await this.#integrate(project, job, true)
|
|
1567
|
+
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] })
|
|
1568
|
+
if (!added.task) return { problem: added.errors!.join("; ") }
|
|
1569
|
+
const task = added.task
|
|
1570
|
+
task.role = "code"
|
|
1571
|
+
task.model = "evolver"
|
|
1572
|
+
this.#bind(job, task, c.id)
|
|
1573
|
+
for (const s of ["ready", "planned", "running"] as const) moveTask(task, s)
|
|
1574
|
+
stage(task, "delegate", "pass", `evolver on ${parsed.files[0]} (${r.block}), contract ${c.id}`)
|
|
1575
|
+
const role = roleById("code")!
|
|
1576
|
+
await this.#start(project, parent, job, task, role, "evolver", { body: task.description, files: parsed.files.join(", "), checks: [...r.checks], replaces: [] }, [...r.checks], rel)
|
|
1577
|
+
const entry = this.#entries.get(`${job.id}/${task.id}`)!
|
|
1578
|
+
return { job, task, dir: entry.dir, contract: c }
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1581
|
+
// The task a worker session works on, or the writer's task for one of its helpers: what its usage is charged to.
|
|
1582
|
+
taskOfSession(session: string): Task | undefined {
|
|
1583
|
+
const entry = this.#entry(session)
|
|
1584
|
+
return entry ? this.#job(entry)?.tasks.find((t) => t.id === entry.taskId) : undefined
|
|
1585
|
+
}
|
|
1586
|
+
|
|
1587
|
+
// 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.
|
|
1588
|
+
chargeEvolve(project: string, jobId: string, used: { tokens: number; cost: number; requests: number }, taskId?: string): void {
|
|
1589
|
+
const job = this.#jobs.get(key(project, jobId))
|
|
1590
|
+
if (!job) return
|
|
1591
|
+
const task = taskId ? job.tasks.find((t) => t.id === taskId) : undefined
|
|
1592
|
+
if (task) chargeTask(task, used)
|
|
1593
|
+
const c = job.counters
|
|
1594
|
+
c.tokens = (c.tokens ?? 0) + used.tokens
|
|
1595
|
+
c.cost = (c.cost ?? 0) + used.cost
|
|
1596
|
+
c.requests = (c.requests ?? 0) + used.requests
|
|
1597
|
+
saveJob(project, job)
|
|
1598
|
+
}
|
|
1599
|
+
|
|
1600
|
+
// The evolver's state on its task, saved as it goes: the sidebar and job_status read it from the job file.
|
|
1601
|
+
noteEvolve(project: string, jobId: string, taskId: string, state: NonNullable<Task["evolve"]>): void {
|
|
1602
|
+
const job = this.#jobs.get(key(project, jobId))
|
|
1603
|
+
const task = job?.tasks.find((t) => t.id === taskId)
|
|
1604
|
+
if (!job || !task) return
|
|
1605
|
+
task.evolve = state
|
|
1606
|
+
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(", ")}` : ""}`
|
|
1607
|
+
saveJob(project, job)
|
|
1608
|
+
}
|
|
1609
|
+
|
|
1610
|
+
// An evolution that ended without a candidate to merge: the task is blocked with why.
|
|
1611
|
+
evolveFailed(project: string, jobId: string, taskId: string, why: string): void {
|
|
1612
|
+
const job = this.#jobs.get(key(project, jobId))
|
|
1613
|
+
const task = job?.tasks.find((t) => t.id === taskId)
|
|
1614
|
+
if (!job || !task) return
|
|
1615
|
+
if (["running", "gating", "fixing"].includes(task.status)) moveTask(task, "blocked")
|
|
1616
|
+
stage(task, "evolve", "fail", why.slice(0, 300))
|
|
1617
|
+
task.summary = `the evolver found nothing to merge: ${why.slice(0, 300)}`
|
|
1618
|
+
const entry = this.#entries.get(`${jobId}/${taskId}`)
|
|
1619
|
+
if (entry) entry.ended = true
|
|
1620
|
+
saveJob(project, job)
|
|
1621
|
+
}
|
|
1622
|
+
|
|
1623
|
+
async #finish(entry: Entry, job: Job, task: Task, summary: string, session: string): Promise<{ text: string; note?: string; parent?: string; stop?: string[] }> {
|
|
1624
|
+
if (!entry.writer) return { text: "You only read: there is nothing to check or merge. End with your findings; they are your result." }
|
|
1625
|
+
if (task.status === "merged") return { text: `${task.id} is already merged into ${job.integrationBranch}. End with your short report.` }
|
|
1626
|
+
if (task.trial && task.status === "cancelled") return { text: lostText(job, task) }
|
|
1627
|
+
if (task.status === "escalated") moveTask(task, "running")
|
|
1628
|
+
moveTask(task, "gating")
|
|
1629
|
+
task.summary = summary.trim().slice(0, 2000) || task.summary
|
|
1630
|
+
// The checks run where the worker's files are, not in the worktree root: a project below the repository root lives
|
|
1631
|
+
// that far down, and a check naming one of its files finds nothing above it.
|
|
1632
|
+
// Frozen files first: a changed test is put back before the checks run, so they judge the code against the tests as
|
|
1633
|
+
// they were, and the worker hears what it may not do.
|
|
1634
|
+
const frozen = entry.frozen ? await frozenChanged(entry.worktree, entry.frozen, this.#exec, entry.dir) : []
|
|
1635
|
+
if (frozen.length) await revertFiles(entry.worktree, frozen, this.#exec, entry.dir)
|
|
1636
|
+
const results = await runGate(entry.worktree, entry.checks, this.#exec, this.#checkTimeout(job), entry.dir)
|
|
1637
|
+
if (frozen.length) 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.` })
|
|
1638
|
+
const graded = gradedOf(results)
|
|
1639
|
+
if (graded) task.graded = graded
|
|
1640
|
+
const failed = results.filter((r) => !r.passed)
|
|
1641
|
+
// Another attempt of its trial won while these checks ran (and took the worktree away).
|
|
1642
|
+
if (task.status === "cancelled") return { text: lostText(job, task) }
|
|
1643
|
+
// The contract's evaluator runs only once the checks pass: it may take minutes, and a broken build measures nothing.
|
|
1644
|
+
// A red team is measured without its guards (src/contractround.ts): gaming them is what it is for.
|
|
1645
|
+
const fitness = failed.length || task.redteam ? {} : await this.#measure(entry, job, task)
|
|
1646
|
+
// The evaluator can take minutes, and the trial may be decided meanwhile (TypeScript cannot see that across await).
|
|
1647
|
+
if ((task.status as Task["status"]) === "cancelled") return { text: lostText(job, task) }
|
|
1648
|
+
if (fitness.failed) {
|
|
1649
|
+
failed.push(fitness.failed)
|
|
1650
|
+
stage(task, "gate", "pass", entry.checks.join(", "))
|
|
1651
|
+
// A used-up stop rule is final for this worker: another fix round could not be measured.
|
|
1652
|
+
if (fitness.exhausted) task.attempts = FIX_ROUNDS
|
|
1653
|
+
}
|
|
1654
|
+
const what = fitness.failed ? "fitness" : "gate"
|
|
1655
|
+
if (failed.length) {
|
|
1656
|
+
// The same cap the runner applies to its fix rounds (runner.ts: #work, `fixRounds ?? 2`). Without it a check that
|
|
1657
|
+
// cannot be satisfied in this environment -- a path that does not exist, a command the gate refuses -- was handed
|
|
1658
|
+
// back to the model until the watchdog's step limit stopped it, burning a session for nothing (live test,
|
|
1659
|
+
// 2026-10-06: four identical gate failures, then the worker gave up). The last failure goes back with the
|
|
1660
|
+
// reason, because at the cap the useful message is that the CHECK is the problem, not the work.
|
|
1661
|
+
task.attempts++
|
|
1662
|
+
if (task.attempts > FIX_ROUNDS) {
|
|
1663
|
+
stage(task, what, "fail", failed.map((f) => f.command).join(", "))
|
|
1664
|
+
moveTask(task, "blocked")
|
|
1665
|
+
task.summary = `its checks still fail after ${FIX_ROUNDS} fix round(s): ${failed.map((f) => f.command).join(", ")}`
|
|
1666
|
+
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.`
|
|
1667
|
+
saveJob(entry.project, job)
|
|
1668
|
+
return {
|
|
1669
|
+
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.`,
|
|
1670
|
+
note,
|
|
1671
|
+
parent: entry.parent,
|
|
1672
|
+
}
|
|
1673
|
+
}
|
|
1674
|
+
moveTask(task, "fixing")
|
|
1675
|
+
moveTask(task, "running")
|
|
1676
|
+
stage(task, what, "fail", fitness.failed ? fitness.failed.output.split("\n")[0]! : failed.map((f) => f.command).join(", "))
|
|
1677
|
+
saveJob(entry.project, job)
|
|
1678
|
+
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) }
|
|
1679
|
+
}
|
|
1680
|
+
if (job.isolation === "none") {
|
|
1681
|
+
// No git: nothing to commit or merge, and no way to see what changed; the checks are the evidence.
|
|
1682
|
+
stage(task, "gate", "pass", entry.checks.length ? entry.checks.join(", ") : "no checks given")
|
|
1683
|
+
if (fitness.evidence) stage(task, "fitness", "pass", fitness.evidence)
|
|
1684
|
+
moveTask(task, "passed")
|
|
1685
|
+
saveJob(entry.project, job)
|
|
1686
|
+
const checks = `${entry.checks.length ? `checks passed: ${entry.checks.join("; ")}` : "no checks were given"}${fitness.evidence ? `; measured: ${fitness.evidence}` : ""}`
|
|
1687
|
+
return {
|
|
1688
|
+
text: `Done; your change is in the project folder (no git, so nothing is committed); ${checks}. Now end with your short report.`,
|
|
1689
|
+
note: `[micromanager] ${task.id} ${task.title}: done in the project folder (no git); ${checks}.`,
|
|
1690
|
+
parent: entry.parent,
|
|
1691
|
+
}
|
|
1692
|
+
}
|
|
1693
|
+
// A passing gate over an untouched tree proves nothing: read-only checks exit 0 on a worktree nobody wrote to, and
|
|
1694
|
+
// a worker whose session died mid-task never gets this far but a silent no-op worker does.
|
|
1695
|
+
const touched = await changedFiles(entry.worktree, this.#exec, task.worktreeRel ?? job.integrationRel ?? "")
|
|
1696
|
+
if (!touched.length) {
|
|
1697
|
+
// A task whose change is already on the integration branch (its branch is fully contained in it, and its declared
|
|
1698
|
+
// files are already present there) legitimately needs no new commit: close it as done instead of blocking. A task
|
|
1699
|
+
// that changed nothing but claims success is still blocked below.
|
|
1700
|
+
let alreadyIntegrated = false
|
|
1701
|
+
if (entry.branch && job.integrationBranch) {
|
|
1702
|
+
const anc = await this.#exec("git", ["merge-base", "--is-ancestor", entry.branch, job.integrationBranch], { cwd: entry.worktree })
|
|
1703
|
+
alreadyIntegrated = anc.code === 0
|
|
1704
|
+
}
|
|
1705
|
+
const rel = task.worktreeRel ?? job.integrationRel ?? ""
|
|
1706
|
+
const integrationDir = taskDir(job.integrationWorktree ?? entry.worktree, rel)
|
|
1707
|
+
const filesAlreadyThere = task.files.length > 0 && task.files.every((f) => {
|
|
1708
|
+
try { return statSync(join(integrationDir, f)).isFile() } catch { return false }
|
|
1709
|
+
})
|
|
1710
|
+
if (alreadyIntegrated && filesAlreadyThere) {
|
|
1711
|
+
stage(task, "gate", "pass", "no new changes: already on the integration branch")
|
|
1712
|
+
moveTask(task, "passed")
|
|
1713
|
+
await this.#dropWorktree(entry, task)
|
|
1714
|
+
saveJob(entry.project, job)
|
|
1715
|
+
return {
|
|
1716
|
+
text: `Your checks pass, and your change is already on ${job.integrationBranch}, so there is nothing to commit; closed as done.`,
|
|
1717
|
+
note: `[micromanager] ${task.id} ${task.title}: closed as done, its change is already on ${job.integrationBranch}; nothing committed.`,
|
|
1718
|
+
parent: entry.parent,
|
|
1719
|
+
}
|
|
1720
|
+
}
|
|
1721
|
+
stage(task, "gate", "fail", "the checks passed but no file was changed")
|
|
1722
|
+
moveTask(task, "blocked")
|
|
1723
|
+
task.summary = "its checks passed but it changed no file, so nothing was verified."
|
|
1724
|
+
saveJob(entry.project, job)
|
|
1725
|
+
return {
|
|
1726
|
+
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.`,
|
|
1727
|
+
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.`,
|
|
1728
|
+
parent: entry.parent,
|
|
1729
|
+
}
|
|
1730
|
+
}
|
|
1731
|
+
stage(task, "gate", "pass", entry.checks.length ? entry.checks.join(", ") : "no checks given")
|
|
1732
|
+
if (fitness.evidence) stage(task, "fitness", "pass", fitness.evidence)
|
|
1733
|
+
const commit = 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)
|
|
1734
|
+
if (task.redteam) return this.#redteamDone(entry, job, task)
|
|
1735
|
+
moveTask(task, "passed")
|
|
1736
|
+
const scored = task.trial && entry.contract ? job.contracts?.find((x) => x.id === entry.contract) : undefined
|
|
1737
|
+
if (scored) return this.#hold(entry, job, task, scored, fitness.evidence)
|
|
1738
|
+
const mode = task.trial ? pickOf(task) : undefined
|
|
1739
|
+
if ((mode === "best" && this.#grace.factor > 0) || mode === "user") return this.#holdPick(entry, job, task, mode)
|
|
1740
|
+
const train = this.#trains.get(job.id) ?? Promise.resolve()
|
|
1741
|
+
const step = train.then(() => (task.status === "cancelled" ? { ok: false as const, text: lostText(job, task) } : this.#merge(entry, job, task)))
|
|
1742
|
+
this.#trains.set(job.id, step.catch(() => undefined))
|
|
1743
|
+
const merged = await step
|
|
1744
|
+
saveJob(entry.project, job)
|
|
1745
|
+
if (!merged.ok) return { text: merged.text }
|
|
1746
|
+
const won = task.trial ? await this.#settleTrial(entry, job, task) : undefined
|
|
1747
|
+
// The commit as merged: a rebase onto other tasks' commits gave it a new id (live test).
|
|
1748
|
+
const head = commit && (await this.#exec("git", ["rev-parse", "--short", "HEAD"], { cwd: entry.worktree })).stdout.trim()
|
|
1749
|
+
const checks = `${entry.checks.length ? `checks passed: ${entry.checks.join("; ")}` : "no checks were given"}${fitness.evidence ? `; measured: ${fitness.evidence}` : ""}`
|
|
1750
|
+
return {
|
|
1751
|
+
text: `Merged into ${job.integrationBranch}${head ? ` as ${head}` : " (nothing to commit)"}; ${checks}. Now end with your short report.`,
|
|
1752
|
+
note: won?.note ?? `[micromanager] ${task.id} ${task.title}: merged into ${job.integrationBranch}${head ? ` (${head})` : ", nothing changed"}; ${checks}.`,
|
|
1753
|
+
parent: entry.parent,
|
|
1754
|
+
...(won?.stop.length ? { stop: won.stop } : {}),
|
|
1755
|
+
}
|
|
1756
|
+
}
|
|
1757
|
+
|
|
1758
|
+
// A trial's attempt merged: it won. Every other attempt is done over by it (replacedBy, so what waits for the first
|
|
1759
|
+
// attempt waits for the winner), cancelled, and its worktree goes; the ones still at work are returned to be stopped.
|
|
1760
|
+
// score: how the winner won a trial decided by its contract, for the note; the held attempts it beat lost on score.
|
|
1761
|
+
async #settleTrial(winner: Entry, job: Job, task: Task, score?: string, by: "score" | "quality" | "user" = "score"): Promise<{ note: string; stop: string[] }> {
|
|
1762
|
+
const now = standing(job, task)
|
|
1763
|
+
const stop: string[] = []
|
|
1764
|
+
const stopped = now.live.filter((t) => t !== task)
|
|
1765
|
+
const beaten = now.held.filter((t) => t !== task)
|
|
1766
|
+
for (const other of now.all) {
|
|
1767
|
+
if (other === task || other.status === "merged" || other.status === "cancelled") continue
|
|
1768
|
+
const e = this.#entries.get(`${job.id}/${other.id}`)
|
|
1769
|
+
if (e?.session && !e.ended && now.live.includes(other)) stop.push(e.session)
|
|
1770
|
+
moveTask(other, "cancelled")
|
|
1771
|
+
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}`)
|
|
1772
|
+
other.replacedBy = task.id
|
|
1773
|
+
if (e) await this.#dropWorktree(e, other)
|
|
1774
|
+
}
|
|
1775
|
+
// The first attempt is what the plan and the dependants know: done over by the winner, it counts as done.
|
|
1776
|
+
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` : ""})`)
|
|
1777
|
+
saveJob(winner.project, job)
|
|
1778
|
+
return { note: wonText(job, task, stopped, now.failed.length, undefined, score !== undefined ? { beaten, how: score, by } : undefined), stop }
|
|
1779
|
+
}
|
|
1780
|
+
|
|
1781
|
+
// A passed attempt of a trial decided by score: measured on the held-out cases too, committed, and held in its
|
|
1782
|
+
// worktree instead of merged. The worker hears only how many held-out cases passed. The trial is decided when no
|
|
1783
|
+
// attempt is at work any more, at its deadline, or at once when one reaches the contract's target.
|
|
1784
|
+
async #hold(entry: Entry, job: Job, task: Task, c: Contract, visible?: string): Promise<{ text: string; note?: string; parent?: string; stop?: string[] }> {
|
|
1785
|
+
let held: Measured | undefined
|
|
1786
|
+
if (c.corpus.heldOut) {
|
|
1787
|
+
const r = await runEvaluator(entry.dir, c, "heldout", this.#exec, heldOutDir(entry.project, job.id, c.id))
|
|
1788
|
+
this.#count(job, c, r.seconds)
|
|
1789
|
+
held = r.measured
|
|
1790
|
+
task.score = { ...held, corpus: "heldout", at: new Date().toISOString() }
|
|
1791
|
+
}
|
|
1792
|
+
task.held = true
|
|
1793
|
+
stage(task, "trial", "pass", `passed, waits for the trial to be decided by score${held ? `; held-out ${coarse(held)}` : ""}`)
|
|
1794
|
+
const head = job.tasks.find((t) => t.id === task.trial!.of) ?? task
|
|
1795
|
+
this.#arm(entry.project, job, head)
|
|
1796
|
+
saveJob(entry.project, job)
|
|
1797
|
+
const settled = await this.#settleQueued(entry.project, job, head, false)
|
|
1798
|
+
// Decided here: finish_task carries the note and the sessions to stop; the outcomes are known now.
|
|
1799
|
+
if (settled) this.#onSettled?.({ project: entry.project, job, parent: entry.parent, stop: [], measured: settled.measured })
|
|
1800
|
+
if (settled?.winner === task) {
|
|
1801
|
+
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 }
|
|
1802
|
+
}
|
|
1803
|
+
const measured = [visible ? `measured: ${visible}` : "", held ? `on the held-out cases, which you cannot see: ${coarse(held)}` : ""].filter(Boolean).join("; ")
|
|
1804
|
+
return {
|
|
1805
|
+
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.`,
|
|
1806
|
+
...(settled ? { note: settled.note, parent: entry.parent, stop: settled.stop } : {}),
|
|
1807
|
+
}
|
|
1808
|
+
}
|
|
1809
|
+
|
|
1810
|
+
// A passed attempt of a trial decided by quality or by the user: committed and held in its worktree. A "best" trial
|
|
1811
|
+
// opens its grace window with the first one (a share of that attempt's time) and stops the attempts that are getting
|
|
1812
|
+
// nowhere; a "user" trial waits for every attempt to end, with no deadline.
|
|
1813
|
+
async #holdPick(entry: Entry, job: Job, task: Task, mode: "best" | "user"): Promise<{ text: string; note?: string; parent?: string; stop?: string[] }> {
|
|
1814
|
+
task.held = true
|
|
1815
|
+
stage(task, "trial", "pass", mode === "user" ? "passed, waits for the user's pick" : "passed, waits for the trial to be decided by quality")
|
|
1816
|
+
const head = job.tasks.find((t) => t.id === task.trial!.of) ?? task
|
|
1817
|
+
const stop: string[] = []
|
|
1818
|
+
if (mode === "best") {
|
|
1819
|
+
if (!head.settleBy) {
|
|
1820
|
+
const started = Date.parse(task.stages.find((s) => s.stage === "delegate")?.at ?? "")
|
|
1821
|
+
const window = graceMs(this.#grace, Number.isFinite(started) ? Date.now() - started : 0)
|
|
1822
|
+
this.#arm(entry.project, job, head, window)
|
|
1823
|
+
stage(task, "trial", "pass", `first to pass: the others have ${Math.round(window / 1000)} s to finish`)
|
|
1824
|
+
}
|
|
1825
|
+
stop.push(...(await this.#stopIdle(job, head)))
|
|
1826
|
+
}
|
|
1827
|
+
saveJob(entry.project, job)
|
|
1828
|
+
const settled = await this.#settleQueued(entry.project, job, head, false)
|
|
1829
|
+
if (settled) this.#onSettled?.({ project: entry.project, job, parent: entry.parent, stop: [], measured: settled.measured })
|
|
1830
|
+
if (settled?.winner === task) {
|
|
1831
|
+
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] }
|
|
1832
|
+
}
|
|
1833
|
+
const text = mode === "user"
|
|
1834
|
+
? "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."
|
|
1835
|
+
: "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."
|
|
1836
|
+
const all = [...stop, ...(settled?.stop ?? [])]
|
|
1837
|
+
return { text, ...(settled ? { note: settled.note } : {}), ...(settled || all.length ? { parent: entry.parent } : {}), ...(all.length ? { stop: all } : {}) }
|
|
1838
|
+
}
|
|
1839
|
+
|
|
1840
|
+
// The live attempts of a trial that are getting nowhere: cancelled, their worktrees gone; their sessions to stop.
|
|
1841
|
+
async #stopIdle(job: Job, head: Task): Promise<string[]> {
|
|
1842
|
+
if (!this.#idle) return []
|
|
1843
|
+
const sessions: string[] = []
|
|
1844
|
+
for (const t of standing(job, head).live) {
|
|
1845
|
+
const e = this.#entries.get(`${job.id}/${t.id}`)
|
|
1846
|
+
if (!e?.session || e.ended || !this.#idle(e.session)) continue
|
|
1847
|
+
moveTask(t, "cancelled")
|
|
1848
|
+
stage(t, "trial", "fail", "stopped: no progress when the grace window opened")
|
|
1849
|
+
sessions.push(e.session)
|
|
1850
|
+
await this.#dropWorktree(e, t)
|
|
1851
|
+
}
|
|
1852
|
+
return sessions
|
|
1853
|
+
}
|
|
1854
|
+
|
|
1855
|
+
// What the quality ranking knows about each passed attempt: its cases, cost and the size of its change.
|
|
1856
|
+
async #quality(job: Job, held: readonly Task[]): Promise<{ q: Quality[]; diffs: Map<string, string> }> {
|
|
1857
|
+
const q: Quality[] = []
|
|
1858
|
+
const diffs = new Map<string, string>()
|
|
1859
|
+
for (const t of held) {
|
|
1860
|
+
const e = this.#entries.get(`${job.id}/${t.id}`)
|
|
1861
|
+
let size = 0
|
|
1862
|
+
if (e && !e.removed) {
|
|
1863
|
+
const stat = await this.#exec("git", ["diff", "--numstat", `${job.integrationBranch}...HEAD`], { cwd: e.worktree })
|
|
1864
|
+
for (const line of stat.stdout.split("\n")) {
|
|
1865
|
+
const [add, del] = line.split("\t")
|
|
1866
|
+
size += (Number(add) || 0) + (Number(del) || 0)
|
|
1867
|
+
}
|
|
1868
|
+
diffs.set(t.id, (await this.#exec("git", ["diff", `${job.integrationBranch}...HEAD`], { cwd: e.worktree })).stdout.slice(0, 30_000))
|
|
1869
|
+
}
|
|
1870
|
+
q.push({ task: t, size, ...(t.graded?.total ? { graded: t.graded.passed / t.graded.total } : {}), ...(t.usage ? { cost: t.usage.cost } : {}) })
|
|
1871
|
+
}
|
|
1872
|
+
return { q, diffs }
|
|
1873
|
+
}
|
|
1874
|
+
|
|
1875
|
+
// A red team that passed its checks: measured on the visible corpus without its guards (gaming them is the point),
|
|
1876
|
+
// never committed or merged. What it found is in its report.
|
|
1877
|
+
async #redteamDone(entry: Entry, job: Job, task: Task): Promise<{ text: string }> {
|
|
1878
|
+
const c = job.contracts?.find((x) => x.id === task.redteam)
|
|
1879
|
+
let seen = "nothing measured"
|
|
1880
|
+
if (c) {
|
|
1881
|
+
const { measured, seconds } = await runEvaluator(entry.dir, c, "visible", this.#exec)
|
|
1882
|
+
this.#count(job, c, seconds)
|
|
1883
|
+
if (measured.valid) task.score = { ...measured, corpus: "visible", at: new Date().toISOString() }
|
|
1884
|
+
seen = describe(c, measured)
|
|
1885
|
+
}
|
|
1886
|
+
moveTask(task, "passed")
|
|
1887
|
+
stage(task, "redteam", "pass", seen)
|
|
1888
|
+
saveJob(entry.project, job)
|
|
1889
|
+
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.` }
|
|
1890
|
+
}
|
|
1891
|
+
|
|
1892
|
+
// The trial's deadline, armed once per trial from its first held attempt; after a restart from the time it had.
|
|
1893
|
+
#arm(project: string, job: Job, head: Task, ms = this.#deadlineMs): void {
|
|
1894
|
+
head.settleBy ??= new Date(Date.now() + ms).toISOString()
|
|
1895
|
+
const k = `${job.id}/${head.id}`
|
|
1896
|
+
if (this.#deadlines.has(k)) return
|
|
1897
|
+
const timer = setTimeout(() => {
|
|
1898
|
+
this.#deadlines.delete(k)
|
|
1899
|
+
this.#settleLater(project, job, head)
|
|
1900
|
+
}, Math.max(0, Date.parse(head.settleBy) - Date.now()))
|
|
1901
|
+
timer.unref?.()
|
|
1902
|
+
this.#deadlines.set(k, timer)
|
|
1903
|
+
}
|
|
1904
|
+
|
|
1905
|
+
// A settle nobody's finish_task waits for (the deadline, the last attempt failing or ending): its note goes to the
|
|
1906
|
+
// micromanager through onSettled.
|
|
1907
|
+
#settleLater(project: string, job: Job, head: Task): void {
|
|
1908
|
+
void this.#settleQueued(project, job, head, true).then((r) => {
|
|
1909
|
+
if (r) this.#onSettled?.({ project, job, parent: job.facilitator ?? this.#entries.get(`${job.id}/${head.id}`)?.parent ?? "", note: r.note, stop: r.stop, measured: r.measured })
|
|
1910
|
+
}).catch(() => undefined)
|
|
1911
|
+
}
|
|
1912
|
+
|
|
1913
|
+
// On the job's merge train: one merge at a time, and a trial is decided once.
|
|
1914
|
+
#settleQueued(project: string, job: Job, head: Task, force: boolean): Promise<{ winner?: Task; note: string; stop: string[]; measured: Task[] } | undefined> {
|
|
1915
|
+
const train = this.#trains.get(job.id) ?? Promise.resolve()
|
|
1916
|
+
const step = train.then(() => this.#settle(project, job, head, force))
|
|
1917
|
+
this.#trains.set(job.id, step.catch(() => undefined))
|
|
1918
|
+
return step
|
|
1919
|
+
}
|
|
1920
|
+
|
|
1921
|
+
// Decides a trial by score once no attempt is at work (or force: the deadline, or every other attempt ended): the
|
|
1922
|
+
// best held attempt is merged, the others are cancelled. The two best are measured again one after the other, so a
|
|
1923
|
+
// machine that was busier during one attempt's measurement does not decide it. One that reached the target wins at
|
|
1924
|
+
// once. When the best cannot be merged (a conflict), the next is tried.
|
|
1925
|
+
async #settle(project: string, job: Job, head: Task, force: boolean): Promise<{ winner?: Task; note: string; stop: string[]; measured: Task[] } | undefined> {
|
|
1926
|
+
const mode = pickOf(head)
|
|
1927
|
+
if (mode === "best") return this.#settleBest(project, job, head, force)
|
|
1928
|
+
if (mode === "user") return this.#settleUser(project, job, head)
|
|
1929
|
+
const c = job.contracts?.find((x) => x.id === head.contract?.id)
|
|
1930
|
+
const now = standing(job, head)
|
|
1931
|
+
if (!c || now.winner || !now.held.length) return undefined
|
|
1932
|
+
const target = now.held.find((t) => reached(c, t.score))
|
|
1933
|
+
if (!force && !target && now.live.length) return undefined
|
|
1934
|
+
const corpus = c.corpus.heldOut ? "heldout" : "visible"
|
|
1935
|
+
let order = target ? [target, ...ranked(c, now.held).filter((t) => t !== target)] : ranked(c, now.held)
|
|
1936
|
+
if (!target && order.length >= 2) {
|
|
1937
|
+
for (const t of order.slice(0, 2)) {
|
|
1938
|
+
const e = this.#entries.get(`${job.id}/${t.id}`)
|
|
1939
|
+
if (!e || e.removed) continue
|
|
1940
|
+
const r = await runEvaluator(e.dir, c, corpus, this.#exec, corpus === "heldout" ? heldOutDir(project, job.id, c.id) : undefined)
|
|
1941
|
+
this.#count(job, c, r.seconds)
|
|
1942
|
+
t.score = { ...r.measured, corpus, at: new Date().toISOString() }
|
|
1943
|
+
}
|
|
1944
|
+
order = [...ranked(c, order.slice(0, 2)), ...order.slice(2)]
|
|
1945
|
+
}
|
|
1946
|
+
const k = `${job.id}/${head.id}`
|
|
1947
|
+
for (const cand of order) {
|
|
1948
|
+
const e = this.#entries.get(`${job.id}/${cand.id}`)
|
|
1949
|
+
if (!e || e.removed) continue
|
|
1950
|
+
const measured = cand.score ? (corpus === "heldout" ? `held-out ${coarse(cand.score)}` : describe(c, cand.score)) : "no score"
|
|
1951
|
+
// Within the noise band the scores do not tell the attempts apart (live run, 2026-10-27: 9.9 against 10.9 ms at
|
|
1952
|
+
// 15 %): the note says so rather than calling one the best.
|
|
1953
|
+
const tied = order.filter((t) => t !== cand && t.score && cand.score && better(c, cand.score, t.score) === 0).map((t) => t.id)
|
|
1954
|
+
const how = tied.length ? `${measured}, tied with ${tied.join(", ")} inside the noise band` : measured
|
|
1955
|
+
const merged = await this.#merge(e, job, cand)
|
|
1956
|
+
if (!merged.ok) {
|
|
1957
|
+
stage(cand, "trial", "fail", "had the best score but did not merge")
|
|
1958
|
+
continue
|
|
1959
|
+
}
|
|
1960
|
+
const won = await this.#settleTrial(e, job, cand, how)
|
|
1961
|
+
clearTimeout(this.#deadlines.get(k))
|
|
1962
|
+
this.#deadlines.delete(k)
|
|
1963
|
+
saveJob(project, job)
|
|
1964
|
+
return { winner: cand, note: won.note, stop: won.stop, measured: now.held }
|
|
1965
|
+
}
|
|
1966
|
+
saveJob(project, job)
|
|
1967
|
+
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 }
|
|
1968
|
+
}
|
|
1969
|
+
|
|
1970
|
+
// Decides a "best" trial once no attempt is at work (or force: the grace window closed): the passed attempts ranked by
|
|
1971
|
+
// quality (src/trials.ts rankQuality), the best merged, the next tried when it does not merge.
|
|
1972
|
+
async #settleBest(project: string, job: Job, head: Task, force: boolean): Promise<{ winner?: Task; note: string; stop: string[]; measured: Task[] } | undefined> {
|
|
1973
|
+
const now = standing(job, head)
|
|
1974
|
+
if (now.winner || !now.held.length) return undefined
|
|
1975
|
+
if (!force && now.live.length) return undefined
|
|
1976
|
+
const { q, diffs } = await this.#quality(job, now.held)
|
|
1977
|
+
const review = this.#review
|
|
1978
|
+
? (a: Quality, b: Quality) => {
|
|
1979
|
+
const da = diffs.get(a.task.id) ?? ""
|
|
1980
|
+
const db = diffs.get(b.task.id) ?? ""
|
|
1981
|
+
// Near-identical changes need no reviewer: cost and size decide.
|
|
1982
|
+
if (similarity(da, db) >= 0.95) return Promise.resolve(undefined)
|
|
1983
|
+
return this.#review!(head, { task: a.task, diff: da }, { task: b.task, diff: db })
|
|
1984
|
+
}
|
|
1985
|
+
: undefined
|
|
1986
|
+
const ranking = await rankQuality(q, review)
|
|
1987
|
+
const k = `${job.id}/${head.id}`
|
|
1988
|
+
for (const cand of ranking.order) {
|
|
1989
|
+
const e = this.#entries.get(`${job.id}/${cand.id}`)
|
|
1990
|
+
if (!e || e.removed) continue
|
|
1991
|
+
const merged = await this.#merge(e, job, cand)
|
|
1992
|
+
if (!merged.ok) {
|
|
1993
|
+
stage(cand, "trial", "fail", "ranked best but did not merge")
|
|
1994
|
+
continue
|
|
1995
|
+
}
|
|
1996
|
+
const won = await this.#settleTrial(e, job, cand, cand === ranking.order[0] ? ranking.how : "the better ones did not merge", "quality")
|
|
1997
|
+
clearTimeout(this.#deadlines.get(k))
|
|
1998
|
+
this.#deadlines.delete(k)
|
|
1999
|
+
saveJob(project, job)
|
|
2000
|
+
return { winner: cand, note: won.note, stop: won.stop, measured: now.held }
|
|
2001
|
+
}
|
|
2002
|
+
saveJob(project, job)
|
|
2003
|
+
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 }
|
|
2004
|
+
}
|
|
2005
|
+
|
|
2006
|
+
// A "user" trial once no attempt is at work: the passed ones go on a comparison page, and the micromanager gets the
|
|
2007
|
+
// form to put to the user. Asked once; nothing is decided here (src/pick.ts, pickAnswer).
|
|
2008
|
+
async #settleUser(project: string, job: Job, head: Task): Promise<{ winner?: Task; note: string; stop: string[]; measured: Task[] } | undefined> {
|
|
2009
|
+
const now = standing(job, head)
|
|
2010
|
+
if (now.winner || !now.held.length || now.live.length || head.pickAsked) return undefined
|
|
2011
|
+
const candidates: Candidate[] = []
|
|
2012
|
+
for (const t of now.held) {
|
|
2013
|
+
const e = this.#entries.get(`${job.id}/${t.id}`)
|
|
2014
|
+
if (!e || e.removed) continue
|
|
2015
|
+
const stat = await this.#exec("git", ["diff", "--numstat", `${job.integrationBranch}...HEAD`], { cwd: e.worktree })
|
|
2016
|
+
let added = 0
|
|
2017
|
+
let removed = 0
|
|
2018
|
+
const files: string[] = []
|
|
2019
|
+
for (const line of stat.stdout.split("\n").filter(Boolean)) {
|
|
2020
|
+
const [a, r, f] = line.split("\t")
|
|
2021
|
+
added += Number(a) || 0
|
|
2022
|
+
removed += Number(r) || 0
|
|
2023
|
+
if (f) files.push(f)
|
|
2024
|
+
}
|
|
2025
|
+
const path = t.preview ?? (t.role === "visual" ? defaultPreview(e.dir) : undefined)
|
|
2026
|
+
const shot: { png?: Buffer; problem?: string } | undefined = path && this.#preview ? await this.#preview(e.dir, path, project, job.id).catch((err: unknown) => ({ problem: `No picture: ${String(err)}` })) : undefined
|
|
2027
|
+
candidates.push({
|
|
2028
|
+
id: t.id, ...(t.model ? { model: t.model } : {}), ...(t.usage ? { cost: t.usage.cost } : {}), lines: { added, removed }, files, ...(t.summary ? { summary: t.summary } : {}),
|
|
2029
|
+
...(path ? { preview: { path, ...(shot?.png ? { png: shot.png } : {}), ...(shot?.problem ? { problem: shot.problem } : {}) } } : {}),
|
|
2030
|
+
})
|
|
2031
|
+
}
|
|
2032
|
+
const title = head.title.replace(/ \(attempt \d+\/\d+\)$/, "")
|
|
2033
|
+
const page = join(project, stateDir(project), "trials", `${job.id}-${head.id}.html`)
|
|
2034
|
+
mkdirSync(dirname(page), { recursive: true })
|
|
2035
|
+
writeFileSync(page, comparisonPage(head.id, title, candidates))
|
|
2036
|
+
head.pickAsked = new Date().toISOString()
|
|
2037
|
+
stage(head, "trial", "pass", `asked the user to pick among ${candidates.map((c) => c.id).join(", ")}`)
|
|
2038
|
+
saveJob(project, job)
|
|
2039
|
+
this.#notify?.(`Pick a version of ${head.id}`, `${candidates.length} versions of "${title.slice(0, 80)}" passed. Comparison: ${page}`)
|
|
2040
|
+
return { note: pickNote(head.id, title, candidates, page), stop: [], measured: [] }
|
|
2041
|
+
}
|
|
2042
|
+
|
|
2043
|
+
// The user's answer to a pick form (src/pick.ts): one attempt merged, a combination continued from one of them, or
|
|
2044
|
+
// none of them and the task done over. text: what the micromanager is told; stop and measured as for a settle.
|
|
2045
|
+
async pickAnswer(project: string, parent: string, headId: string, answer: PickAnswer): Promise<{ text: string; stop: string[]; measured: Task[]; job?: Job }> {
|
|
2046
|
+
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))
|
|
2047
|
+
const head = job?.tasks.find((t) => t.id === headId)
|
|
2048
|
+
if (!job || !head?.trial || pickOf(head) !== "user") return { text: `${headId} runs no trial for the user to pick.`, stop: [], measured: [] }
|
|
2049
|
+
this.#jobs.set(key(project, job.id), job)
|
|
2050
|
+
const now = standing(job, head)
|
|
2051
|
+
if (now.winner) return { text: `${now.winner.id} already won the trial of ${headId}.`, stop: [], measured: [] }
|
|
2052
|
+
if (now.live.length || !head.pickAsked) return { text: `Attempts of ${headId} are still at work; the form comes once all have ended.`, stop: [], measured: [] }
|
|
2053
|
+
const ids = now.held.map((t) => t.id)
|
|
2054
|
+
if (answer.kind === "unclear") return { text: `"${answer.said ?? ""}" is no answer to the form; ask with the same form again.`, stop: [], measured: [] }
|
|
2055
|
+
if (answer.kind === "attempt") {
|
|
2056
|
+
const cand = now.held.find((t) => t.id === answer.id)
|
|
2057
|
+
const e = cand && this.#entries.get(`${job.id}/${cand.id}`)
|
|
2058
|
+
if (!cand || !e) return { text: `${answer.id} is not one of the passed attempts (${ids.join(", ")}); ask with the same form again.`, stop: [], measured: [] }
|
|
2059
|
+
const train = this.#trains.get(job.id) ?? Promise.resolve()
|
|
2060
|
+
const step = train.then(() => this.#merge(e, job, cand))
|
|
2061
|
+
this.#trains.set(job.id, step.catch(() => undefined))
|
|
2062
|
+
const merged = await step
|
|
2063
|
+
if (!merged.ok) {
|
|
2064
|
+
saveJob(project, job)
|
|
2065
|
+
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: [] }
|
|
2066
|
+
}
|
|
2067
|
+
const won = await this.#settleTrial(e, job, cand, `picked by the user${answer.notes ? `: ${answer.notes.slice(0, 200)}` : ""}`, "user")
|
|
2068
|
+
saveJob(project, job)
|
|
2069
|
+
return { text: won.note, stop: won.stop, measured: now.held, job }
|
|
2070
|
+
}
|
|
2071
|
+
if (answer.kind === "combine") {
|
|
2072
|
+
const baseId = combineBase(answer.notes, ids)!
|
|
2073
|
+
const base = now.held.find((t) => t.id === baseId)!
|
|
2074
|
+
const be = this.#entries.get(`${job.id}/${base.id}`)
|
|
2075
|
+
if (!be?.session) return { text: `${base.id} has no session to continue.`, stop: [], measured: [] }
|
|
2076
|
+
const files: string[] = []
|
|
2077
|
+
for (const other of now.held.filter((t) => t !== base)) {
|
|
2078
|
+
const oe = this.#entries.get(`${job.id}/${other.id}`)
|
|
2079
|
+
if (oe && !oe.removed) {
|
|
2080
|
+
const diff = (await this.#exec("git", ["diff", `${job.integrationBranch}...HEAD`], { cwd: oe.worktree })).stdout
|
|
2081
|
+
const file = join(project, stateDir(project), "trials", `${job.id}-${other.id}.diff`)
|
|
2082
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
2083
|
+
writeFileSync(file, diff)
|
|
2084
|
+
files.push(`${other.id}: ${file}`)
|
|
2085
|
+
await this.#dropWorktree(oe, other)
|
|
2086
|
+
}
|
|
2087
|
+
moveTask(other, "cancelled")
|
|
2088
|
+
other.replacedBy = base.id
|
|
2089
|
+
stage(other, "trial", "pass", `combined into ${base.id} as the user asked`)
|
|
2090
|
+
}
|
|
2091
|
+
// From here on the base is a task of its own: its next pass merges.
|
|
2092
|
+
base.held = false
|
|
2093
|
+
for (const t of [base, head]) if (t.trial) t.trial.pick = "first"
|
|
2094
|
+
moveTask(base, "escalated")
|
|
2095
|
+
moveTask(base, "running")
|
|
2096
|
+
stage(base, "trial", "pass", `the user asked for a combination: ${(answer.notes ?? "").slice(0, 200)}`)
|
|
2097
|
+
saveJob(project, job)
|
|
2098
|
+
const agent = roleById(base.role)?.agent ?? base.role
|
|
2099
|
+
return {
|
|
2100
|
+
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.`,
|
|
2101
|
+
stop: [], measured: now.held.filter((t) => t !== base), job,
|
|
2102
|
+
}
|
|
2103
|
+
}
|
|
2104
|
+
for (const t of now.held) {
|
|
2105
|
+
const e = this.#entries.get(`${job.id}/${t.id}`)
|
|
2106
|
+
moveTask(t, "cancelled")
|
|
2107
|
+
stage(t, "trial", "pass", "the user picked none of the versions")
|
|
2108
|
+
if (e) await this.#dropWorktree(e, t)
|
|
2109
|
+
}
|
|
2110
|
+
saveJob(project, job)
|
|
2111
|
+
return {
|
|
2112
|
+
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.`,
|
|
2113
|
+
stop: [], measured: now.held, job,
|
|
2114
|
+
}
|
|
2115
|
+
}
|
|
2116
|
+
|
|
2117
|
+
// The note when a trial's attempt failed: the trial's state (others still run, or all failed); undefined outside one.
|
|
2118
|
+
#trialFailed(job: Job, task: Task, project: string): string | undefined {
|
|
2119
|
+
if (!task.trial) return undefined
|
|
2120
|
+
const now = standing(job, task)
|
|
2121
|
+
if (now.winner) return undefined
|
|
2122
|
+
if (now.live.length) return attemptFailedText(task, now.live)
|
|
2123
|
+
const head = job.tasks.find((t) => t.id === task.trial!.of) ?? task
|
|
2124
|
+
// Others passed and wait for the decision by score: it is due now, and its note says how it came out.
|
|
2125
|
+
if (now.held.length) {
|
|
2126
|
+
this.#settleLater(project, job, head)
|
|
2127
|
+
return undefined
|
|
2128
|
+
}
|
|
2129
|
+
return allFailedText(job, head, now.failed)
|
|
2130
|
+
}
|
|
2131
|
+
|
|
2132
|
+
// Rebase onto the session branch, the checks again when it moved, then the fast-forward.
|
|
2133
|
+
async #merge(entry: Entry, job: Job, task: Task): Promise<{ ok: true } | { ok: false; text: string }> {
|
|
2134
|
+
const v = await validateIntegration(job, this.#exec)
|
|
2135
|
+
if (!v.ok) {
|
|
2136
|
+
moveTask(task, "escalated")
|
|
2137
|
+
stage(task, "merge", "fail", v.message)
|
|
2138
|
+
return { ok: false, text: `The integration worktree is not usable: ${v.message}. Fix it (or recreate it) and call finish_task again.` }
|
|
2139
|
+
}
|
|
2140
|
+
const w = { worktree: entry.worktree, branch: entry.branch! }
|
|
2141
|
+
const step = await rebaseTask(w, job.integrationBranch!, this.#exec)
|
|
2142
|
+
if (!step.ok) {
|
|
2143
|
+
moveTask(task, "escalated")
|
|
2144
|
+
stage(task, "merge", "fail", step.conflict)
|
|
2145
|
+
return { ok: false, text: `Your commit does not apply on top of ${job.integrationBranch}, which other tasks moved on meanwhile (${step.conflict}). Run git rebase ${job.integrationBranch} in your directory, resolve the conflict keeping both changes, run the checks, and call finish_task again.` }
|
|
2146
|
+
}
|
|
2147
|
+
if (step.moved) {
|
|
2148
|
+
const failed = (await runGate(entry.worktree, entry.checks, this.#exec, this.#checkTimeout(job), entry.dir)).filter((r) => !r.passed)
|
|
2149
|
+
if (failed.length) {
|
|
2150
|
+
moveTask(task, "escalated")
|
|
2151
|
+
stage(task, "merge", "fail", `checks fail on top of the newer commits: ${failed.map((f) => f.command).join(", ")}`)
|
|
2152
|
+
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) }
|
|
2153
|
+
}
|
|
2154
|
+
// Other tasks' commits can change what the evaluator measures as much as what the checks see.
|
|
2155
|
+
const fitness = await this.#measure(entry, job, task)
|
|
2156
|
+
if (fitness.failed) {
|
|
2157
|
+
moveTask(task, "escalated")
|
|
2158
|
+
stage(task, "merge", "fail", `the fitness contract does not hold on top of the newer commits: ${fitness.failed.output.split("\n")[0]}`)
|
|
2159
|
+
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) }
|
|
2160
|
+
}
|
|
2161
|
+
if (fitness.evidence) stage(task, "fitness", "pass", `after the rebase: ${fitness.evidence}`)
|
|
2162
|
+
}
|
|
2163
|
+
const ff = await fastForward(job.integrationWorktree!, entry.branch!, this.#exec)
|
|
2164
|
+
if (!ff.ok) {
|
|
2165
|
+
moveTask(task, "escalated")
|
|
2166
|
+
stage(task, "merge", "fail", ff.conflict)
|
|
2167
|
+
return { ok: false, text: `The merge into ${job.integrationBranch} failed (${ff.conflict}). Call finish_task again; if it fails the same way, report it.` }
|
|
2168
|
+
}
|
|
2169
|
+
moveTask(task, "merged")
|
|
2170
|
+
stage(task, "merge", "pass", `merged into ${job.integrationBranch}`)
|
|
2171
|
+
return { ok: true }
|
|
2172
|
+
}
|
|
2173
|
+
|
|
2174
|
+
// Waits once per run for a worker's end (wait resolves when its session goes idle).
|
|
2175
|
+
// reason: why the watchdog stopped the worker, if it did.
|
|
2176
|
+
// ended gets the worker's task as it ended too, for the outcome log (src/outcomes.ts).
|
|
2177
|
+
watchEnd(session: string, wait: () => Promise<unknown>, reason: () => string | undefined, ended: (note: string | undefined, parent: string, w: Worker) => void): void {
|
|
2178
|
+
if (this.#waiting.has(session) || !this.#bySession.has(session)) return
|
|
2179
|
+
this.#waiting.add(session)
|
|
2180
|
+
void wait().catch(() => undefined).then(async () => {
|
|
2181
|
+
this.#waiting.delete(session)
|
|
2182
|
+
const r = await this.ended(session, reason())
|
|
2183
|
+
const entry = this.#entry(session)
|
|
2184
|
+
const job = entry && this.#job(entry)
|
|
2185
|
+
const task = job?.tasks.find((t) => t.id === entry!.taskId)
|
|
2186
|
+
if (r && entry && job && task) ended(r.note, r.parent, { project: entry.project, job, task, writer: entry.writer })
|
|
2187
|
+
})
|
|
2188
|
+
}
|
|
2189
|
+
|
|
2190
|
+
// A worker's run ended: a merged writer's worktree goes, a reader's task is done, and a writer that did not get
|
|
2191
|
+
// through finish_task is reported, with its change still in its worktree. reason: why the watchdog stopped it.
|
|
2192
|
+
async ended(session: string, reason?: string): Promise<{ note?: string; parent: string } | undefined> {
|
|
2193
|
+
const entry = this.#entry(session)
|
|
2194
|
+
const job = entry && this.#job(entry)
|
|
2195
|
+
const task = job?.tasks.find((t) => t.id === entry!.taskId)
|
|
2196
|
+
if (!entry || !job || !task) return undefined
|
|
2197
|
+
entry.ended = true
|
|
2198
|
+
let note: string | undefined
|
|
2199
|
+
if (!entry.writer) {
|
|
2200
|
+
if (task.status === "running") {
|
|
2201
|
+
moveTask(task, "gating")
|
|
2202
|
+
moveTask(task, "passed")
|
|
2203
|
+
stage(task, "report", "pass", "the reader ended")
|
|
2204
|
+
}
|
|
2205
|
+
} else if (task.status === "merged") {
|
|
2206
|
+
await this.#dropWorktree(entry, task)
|
|
2207
|
+
} else if (task.trial && task.status === "cancelled") {
|
|
2208
|
+
// Stopped because another attempt won: its work is not needed, and the winner's note said so.
|
|
2209
|
+
await this.#dropWorktree(entry, task)
|
|
2210
|
+
} else if (task.redteam) {
|
|
2211
|
+
// A red team's change is never merged: its worktree goes, its report is what it leaves.
|
|
2212
|
+
await this.#dropWorktree(entry, task)
|
|
2213
|
+
} else if (task.held && task.status === "passed") {
|
|
2214
|
+
// Passed and waiting for its trial to be decided by score: its commit stays in its worktree until then.
|
|
2215
|
+
} else {
|
|
2216
|
+
const blocked = task.status === "blocked"
|
|
2217
|
+
stage(task, "end", "fail", reason ?? "ended without finish_task")
|
|
2218
|
+
// In a trial, finish_task reported a blocked attempt already; one that ended unfinished is a failed attempt.
|
|
2219
|
+
if (task.trial) note = blocked ? undefined : this.#trialFailed(job, task, entry.project)
|
|
2220
|
+
else 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.`
|
|
2221
|
+
}
|
|
2222
|
+
saveJob(entry.project, job)
|
|
2223
|
+
return { note, parent: entry.parent }
|
|
2224
|
+
}
|
|
2225
|
+
|
|
2226
|
+
// The todo tool: the micromanager writes down the tasks it means to start, as open tasks of its session's job, so the
|
|
2227
|
+
// job file holds the whole list (the sidebar shows it; the continuation names the ready ones). v2 has no todowrite,
|
|
2228
|
+
// and a list kept in the model's context was lost on compaction. Each is started later with "Task: T… · job-…".
|
|
2229
|
+
todo(project: string, parent: string, items: readonly TodoItem[], drop: readonly string[]): { job: Job; added: Task[]; dropped: string[]; errors: string[] } {
|
|
2230
|
+
const job = this.job(project, parent)
|
|
2231
|
+
const errors: string[] = []
|
|
2232
|
+
const added: Task[] = []
|
|
2233
|
+
const dropped: string[] = []
|
|
2234
|
+
for (const id of drop) {
|
|
2235
|
+
const task = job.tasks.find((t) => t.id === id)
|
|
2236
|
+
if (!task) errors.push(`${id}: no such task`)
|
|
2237
|
+
else if (!["pending", "ready", "planned"].includes(task.status)) errors.push(`${id} is ${task.status}, not an open todo; stop_task stops a running one`)
|
|
2238
|
+
else {
|
|
2239
|
+
moveTask(task, "cancelled")
|
|
2240
|
+
stage(task, "drop", "pass", "dropped from the todo list")
|
|
2241
|
+
dropped.push(id)
|
|
2242
|
+
}
|
|
2243
|
+
}
|
|
2244
|
+
for (const item of items) {
|
|
2245
|
+
const title = item.title?.trim() ?? ""
|
|
2246
|
+
const role = roleByAgent(item.agent ?? "") ?? (item.agent ? undefined : roleByAgent("coder"))
|
|
2247
|
+
if (!title) { errors.push("a todo without a title"); continue }
|
|
2248
|
+
if (!role) { errors.push(`${title}: ${item.agent} is not a role agent (${ROLES.map((r) => r.agent).join(", ")})`); continue }
|
|
2249
|
+
const writer = WRITERS.has(role.id)
|
|
2250
|
+
const parsed = parseFiles(item.files ?? "", project)
|
|
2251
|
+
if (parsed.problem) { errors.push(`${title}: ${parsed.problem}`); continue }
|
|
2252
|
+
if (writer && !parsed.files.length) { errors.push(`${title}: a ${role.agent} changes files; give the files it may change`); continue }
|
|
2253
|
+
if (!writer && parsed.files.length) { errors.push(`${title}: ${role.agent} only reads; leave out files`); continue }
|
|
2254
|
+
const checks = (item.checks ?? "").split("\n").map((c) => c.trim()).filter(Boolean)
|
|
2255
|
+
const bad = checks.length ? checkSetProblems(checks, writer) : undefined
|
|
2256
|
+
if (bad) { errors.push(`${title}: ${bad}`); continue }
|
|
2257
|
+
const after = (item.after ?? []).map((id) => id.trim().toUpperCase()).filter(Boolean)
|
|
2258
|
+
const unknown = after.filter((id) => !job.tasks.some((t) => t.id === id))
|
|
2259
|
+
if (unknown.length) { errors.push(`${title}: no task ${unknown.join(", ")} to wait for`); continue }
|
|
2260
|
+
const replaces = item.replaces ?? []
|
|
2261
|
+
const cannot = this.#replaceable(project, job, replaces)
|
|
2262
|
+
if (cannot.length) { errors.push(`${title}: ${cannot.join("; ")}`); continue }
|
|
2263
|
+
if (item.contract && !writer) { errors.push(`${title}: ${role.agent} only reads; a fitness contract measures a writer's work`); continue }
|
|
2264
|
+
if (item.contract && !job.contracts?.some((c) => c.id === item.contract)) { errors.push(`${title}: job ${job.id} has no contract ${item.contract}; define it with the contract tool first`); continue }
|
|
2265
|
+
const result = addDelegated(job, { title, prompt: item.brief?.trim() || title, files: parsed.files, dependsOn: after, checks })
|
|
2266
|
+
if (!result.task) { errors.push(`${title}: ${result.errors!.join("; ")}`); continue }
|
|
2267
|
+
this.#bind(job, result.task, item.contract)
|
|
2268
|
+
const freeze = item.frozen ? parseFiles(item.frozen, project) : undefined
|
|
2269
|
+
if (freeze?.problem) errors.push(`${title}: frozen ${freeze.problem}`)
|
|
2270
|
+
else if (freeze?.files.length) result.task.freeze = freeze.files
|
|
2271
|
+
this.#link(project, job, result.task, replaces)
|
|
2272
|
+
result.task.role = role.id
|
|
2273
|
+
stage(result.task, "todo", "pass", "written down by the micromanager")
|
|
2274
|
+
added.push(result.task)
|
|
2275
|
+
}
|
|
2276
|
+
if (added.length || dropped.length) saveJob(project, job)
|
|
2277
|
+
return { job, added, dropped, errors }
|
|
2278
|
+
}
|
|
2279
|
+
|
|
2280
|
+
// The job a worker works for, as this process holds it.
|
|
2281
|
+
jobOf(session: string): { project: string; job: Job } | undefined {
|
|
2282
|
+
const entry = this.#entry(session)
|
|
2283
|
+
const job = entry && this.#job(entry)
|
|
2284
|
+
return entry && job ? { project: entry.project, job } : undefined
|
|
2285
|
+
}
|
|
2286
|
+
|
|
2287
|
+
// The live worker that works in a directory (a shell command's cwd: its own directory or below), for the sandbox
|
|
2288
|
+
// The sandbox (src/shell/sandbox.ts). The deepest match wins, so a writer's worktree beats the job's integration worktree it lies in.
|
|
2289
|
+
workerAt(cwd: string): { project: string; jobId: string; role: RoleId; writer: boolean; dir: string; worktree: string; frozen: string[] } | undefined {
|
|
2290
|
+
const inside = (dir: string) => cwd === dir || cwd.startsWith(`${dir}/`)
|
|
2291
|
+
const found = [...this.#entries.values()]
|
|
2292
|
+
.filter((e) => !e.ended && (inside(e.dir) || inside(e.worktree)))
|
|
2293
|
+
.sort((a, b) => b.dir.length - a.dir.length)[0]
|
|
2294
|
+
return found && this.#task(found) ? this.#facts(found) : undefined
|
|
2295
|
+
}
|
|
2296
|
+
|
|
2297
|
+
// The live worker of a session, for the sandbox (src/shell/): the session that asked for the shell is known there,
|
|
2298
|
+
// while the shell hook itself gets no session id. The same facts as workerAt, but by session instead of by directory.
|
|
2299
|
+
workerBySession(session: string): { project: string; jobId: string; role: RoleId; writer: boolean; dir: string; worktree: string; frozen: string[] } | undefined {
|
|
2300
|
+
const found = this.#entry(session)
|
|
2301
|
+
if (!found || found.ended || !found.session) return undefined
|
|
2302
|
+
return this.#task(found) ? this.#facts(found) : undefined
|
|
2303
|
+
}
|
|
2304
|
+
|
|
2305
|
+
#task(entry: Entry): Task | undefined {
|
|
2306
|
+
return this.#job(entry)?.tasks.find((t) => t.id === entry.taskId)
|
|
2307
|
+
}
|
|
2308
|
+
|
|
2309
|
+
#facts(entry: Entry): { project: string; jobId: string; role: RoleId; writer: boolean; dir: string; worktree: string; frozen: string[] } {
|
|
2310
|
+
const task = this.#task(entry)!
|
|
2311
|
+
return {
|
|
2312
|
+
project: entry.project,
|
|
2313
|
+
jobId: entry.jobId,
|
|
2314
|
+
role: task.role as RoleId,
|
|
2315
|
+
writer: entry.writer,
|
|
2316
|
+
dir: entry.dir,
|
|
2317
|
+
worktree: entry.worktree,
|
|
2318
|
+
frozen: entry.writer && entry.frozen ? [...entry.frozen.keys()].map((f) => resolve(entry.dir, f)) : [],
|
|
2319
|
+
}
|
|
2320
|
+
}
|
|
2321
|
+
|
|
2322
|
+
// The workers of a micromanager session that still run.
|
|
2323
|
+
running(parent: string): { session: string; task: string }[] {
|
|
2324
|
+
return [...this.#entries.values()]
|
|
2325
|
+
.filter((e) => e.parent === parent && e.session && !e.ended)
|
|
2326
|
+
.filter((e) => ["running", "gating", "fixing"].includes(this.#job(e)?.tasks.find((t) => t.id === e.taskId)?.status ?? ""))
|
|
2327
|
+
.map((e) => ({ session: e.session!, task: e.taskId }))
|
|
2328
|
+
}
|
|
2329
|
+
|
|
2330
|
+
#entry(session: string): Entry | undefined {
|
|
2331
|
+
const k = this.#bySession.get(session)
|
|
2332
|
+
return k ? this.#entries.get(k) : undefined
|
|
2333
|
+
}
|
|
2334
|
+
|
|
2335
|
+
#job(entry: Entry): Job | undefined {
|
|
2336
|
+
return this.#jobs.get(key(entry.project, entry.jobId))
|
|
2337
|
+
}
|
|
2338
|
+
|
|
2339
|
+
async #dropWorktree(entry: Entry, task?: Task): Promise<void> {
|
|
2340
|
+
if (!entry.writer || entry.removed || !entry.branch) return
|
|
2341
|
+
await removeTaskWorktree(entry.project, { worktree: entry.worktree, branch: entry.branch }, this.#exec)
|
|
2342
|
+
entry.removed = true
|
|
2343
|
+
if (task) {
|
|
2344
|
+
task.worktree = undefined
|
|
2345
|
+
task.branch = undefined
|
|
2346
|
+
}
|
|
2347
|
+
}
|
|
2348
|
+
|
|
2349
|
+
#brief(job: Job, task: Task, role: Role, model: string, d: Delegation, entry: Entry, graph?: Graph): string {
|
|
2350
|
+
const skills = [...(entry.writer ? ["verification-before-completion"] : []), ...(role.id === "research" ? ["research"] : [])].filter((s) => this.#skills.has(s))
|
|
2351
|
+
const others = job.tasks.filter((t) => t.id !== task.id && ["running", "gating", "fixing"].includes(t.status))
|
|
2352
|
+
return [
|
|
2353
|
+
`${HEADER} task ${task.id} · job ${job.id} · role ${role.id} · model ${model}`,
|
|
2354
|
+
"",
|
|
2355
|
+
d.body,
|
|
2356
|
+
"",
|
|
2357
|
+
attemptBrief(task),
|
|
2358
|
+
"",
|
|
2359
|
+
graph ? graphBrief(graph) : "",
|
|
2360
|
+
"",
|
|
2361
|
+
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.",
|
|
2362
|
+
// A worktree is a checkout of the repository root, so a project that is a subdirectory sits below it. Saying so
|
|
2363
|
+
// keeps a worker from concluding its premise is false when a path of its own does not resolve at the top.
|
|
2364
|
+
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.` : "",
|
|
2365
|
+
dirtyNote(job, entry.writer),
|
|
2366
|
+
entry.writer
|
|
2367
|
+
? entry.checks.length
|
|
2368
|
+
? `Checks the plugin runs when you finish: ${entry.checks.join("; ")}`
|
|
2369
|
+
: "No checks were given: test your change yourself as far as you can."
|
|
2370
|
+
: "",
|
|
2371
|
+
entry.contract && !task.redteam && job.contracts?.find((c) => c.id === entry.contract) ? contractBrief(job.contracts.find((c) => c.id === entry.contract)!) : "",
|
|
2372
|
+
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(", ")}.` : "",
|
|
2373
|
+
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." : "",
|
|
2374
|
+
others.length ? `Other workers change other files at the same time (not yours): ${others.map((t) => `${t.id} ${t.title}`).join("; ")}` : "",
|
|
2375
|
+
"Keys and tokens show as <secret> in what you read; never write <secret> into a file, leave such lines as they are.",
|
|
2376
|
+
// The sandbox's limits, and how to ask past them (src/grants.ts).
|
|
2377
|
+
entry.writer || role.id === "research"
|
|
2378
|
+
? "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."
|
|
2379
|
+
: "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.",
|
|
2380
|
+
skillLine(skills),
|
|
2381
|
+
"",
|
|
2382
|
+
entry.writer
|
|
2383
|
+
? "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: \"…\" })`."
|
|
2384
|
+
: "",
|
|
2385
|
+
entry.writer
|
|
2386
|
+
? `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}`
|
|
2387
|
+
: `End with your findings: they are your result. ${FOLLOWUP_LINE}`,
|
|
2388
|
+
].filter((line, i, all) => line !== "" || all[i - 1] !== "").join("\n").trim()
|
|
2389
|
+
}
|
|
2390
|
+
}
|
|
2391
|
+
|
|
2392
|
+
// How a worker reports work outside its task, so the plugin can keep it (src/brief.ts parseReport reads these lines).
|
|
2393
|
+
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)."
|
|
2394
|
+
|
|
2395
|
+
// A planned task on its way to a worker, from wherever it stopped: open, given up, stopped, left running by a process
|
|
2396
|
+
// that ended, or cancelled by a sweep. Cancelled is final for the state machine, so a task started again on purpose
|
|
2397
|
+
// goes back to pending first.
|
|
2398
|
+
function restart(task: Task): void {
|
|
2399
|
+
if (task.status === "cancelled") {
|
|
2400
|
+
task.status = "pending"
|
|
2401
|
+
stage(task, "restart", "pass", "started again by the micromanager")
|
|
2402
|
+
}
|
|
2403
|
+
if (LIVE.has(task.status)) moveTask(task, "escalated")
|
|
2404
|
+
if (task.status === "blocked") moveTask(task, "running")
|
|
2405
|
+
if (task.status === "escalated") moveTask(task, "running")
|
|
2406
|
+
if (task.status === "pending") moveTask(task, "ready")
|
|
2407
|
+
if (task.status === "ready") moveTask(task, "planned")
|
|
2408
|
+
if (task.status === "planned") moveTask(task, "running")
|
|
2409
|
+
}
|
|
2410
|
+
|
|
2411
|
+
function key(project: string, job: string): string {
|
|
2412
|
+
return `${project}\0${job}`
|
|
2413
|
+
}
|
|
2414
|
+
|
|
2415
|
+
// A worktree starts from the last commit, so the user's uncommitted work is not in it. A worker told this fails far more
|
|
2416
|
+
// gracefully than one that spends a session discovering its premise cannot hold.
|
|
2417
|
+
function dirtyNote(job: Job, writer: boolean): string {
|
|
2418
|
+
if (!job.integrationDirty) return ""
|
|
2419
|
+
return writer
|
|
2420
|
+
? `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.`
|
|
2421
|
+
: `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.`
|
|
2422
|
+
}
|
|
2423
|
+
|
|
2424
|
+
// What an attempt hears when another attempt of its trial won first.
|
|
2425
|
+
function lostText(job: Job, task: Task): string {
|
|
2426
|
+
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.`
|
|
2427
|
+
}
|
|
2428
|
+
|
|
2429
|
+
// "<job>/<task>" from a brief's header line.
|
|
2430
|
+
function tokenOf(text: string): string | undefined {
|
|
2431
|
+
const m = text.match(/\[micromanager\] task (T\d+) · job (\S+) ·/)
|
|
2432
|
+
return m ? `${m[2]}/${m[1]}` : undefined
|
|
2433
|
+
}
|
|
2434
|
+
|
|
2435
|
+
// The directory is in the text: a check that says "No such file or directory" only makes sense next to the cwd it ran
|
|
2436
|
+
// in, and that was the one diagnostic missing when a worker hunted for a file three directories up.
|
|
2437
|
+
function failText(what: string, failed: readonly GateResult[], dir: string): string {
|
|
2438
|
+
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.`
|
|
2439
|
+
}
|
|
2440
|
+
|
|
2441
|
+
// The existing files a shell command names, project-relative: "node --test test/a.test.js" names test/a.test.js. A
|
|
2442
|
+
// 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
|
|
2443
|
+
// writes, and one it would write does not exist yet.
|
|
2444
|
+
export function namedFiles(command: string, dir: string): string[] {
|
|
2445
|
+
return [...new Set(command.split(/[\s;|&()<>=]+/).map((w) => w.replace(/^['"]+|['"]+$/g, "")))]
|
|
2446
|
+
.filter((w) => /^[\w./@+-]+$/.test(w) && /[./]/.test(w) && !w.startsWith("-") && !w.startsWith("/") && !w.split("/").includes(".."))
|
|
2447
|
+
.map((w) => w.replace(/^\.\//, ""))
|
|
2448
|
+
.filter((w) => {
|
|
2449
|
+
try {
|
|
2450
|
+
return statSync(join(dir, w)).isFile()
|
|
2451
|
+
} catch {
|
|
2452
|
+
return false
|
|
2453
|
+
}
|
|
2454
|
+
})
|
|
2455
|
+
}
|