@omacode/micromanager 0.1.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (213) hide show
  1. package/README.md +7 -4
  2. package/THIRD_PARTY.md +100 -0
  3. package/decider/.python-version +1 -0
  4. package/decider/README.md +35 -0
  5. package/decider/decider/__init__.py +1 -0
  6. package/decider/decider/server.py +327 -0
  7. package/decider/pyproject.toml +34 -0
  8. package/decider/uv.lock +1255 -0
  9. package/dist/agenda.js +51 -0
  10. package/dist/agents.js +58 -0
  11. package/dist/artifact/handoff.js +281 -0
  12. package/dist/ask.js +200 -0
  13. package/dist/backends.js +219 -0
  14. package/dist/backlog.js +414 -0
  15. package/dist/bench.js +427 -0
  16. package/dist/board.js +1 -0
  17. package/dist/brief.js +202 -0
  18. package/dist/browser.js +679 -0
  19. package/dist/budget.js +61 -0
  20. package/dist/catalog.js +187 -0
  21. package/dist/checkchange.js +145 -0
  22. package/dist/checkpoint.js +94 -0
  23. package/dist/cli.js +764 -0
  24. package/dist/comfy-gate.js +258 -0
  25. package/dist/compact.js +142 -0
  26. package/dist/config.js +344 -0
  27. package/dist/context/capture.js +1 -0
  28. package/dist/context/digest.js +1 -0
  29. package/dist/context/embed.js +1 -0
  30. package/dist/context/index.js +2 -0
  31. package/dist/context/ledger.js +1 -0
  32. package/dist/context/manager.js +1 -0
  33. package/dist/context/memory.js +1 -0
  34. package/dist/context/policy.js +1 -0
  35. package/dist/context/prices.js +1 -0
  36. package/dist/context/recall.js +1 -0
  37. package/dist/context/rules.js +1 -0
  38. package/dist/context/search.js +1 -0
  39. package/dist/context/status.js +1 -0
  40. package/dist/context/store.js +1 -0
  41. package/dist/context/summary.js +1 -0
  42. package/dist/context/tokens.js +1 -0
  43. package/dist/context/tools.js +1 -0
  44. package/dist/continuation.js +184 -0
  45. package/dist/contract.js +294 -0
  46. package/dist/contractround.js +178 -0
  47. package/dist/control.js +1 -0
  48. package/dist/creative-tools.js +237 -0
  49. package/dist/dataset.js +175 -0
  50. package/dist/decide.js +676 -0
  51. package/dist/decider.js +171 -0
  52. package/dist/design-shell.js +448 -0
  53. package/dist/design.js +1410 -0
  54. package/dist/desktop.js +44 -0
  55. package/dist/egress.js +156 -0
  56. package/dist/eval.js +60 -0
  57. package/dist/evolver.js +302 -0
  58. package/dist/features.js +193 -0
  59. package/dist/followups.js +32 -0
  60. package/dist/forms.js +195 -0
  61. package/dist/gate.js +108 -0
  62. package/dist/gatebox.js +46 -0
  63. package/dist/grants.js +189 -0
  64. package/dist/graph.js +65 -0
  65. package/dist/guard/index.js +1 -0
  66. package/dist/guard/wire.js +1 -0
  67. package/dist/helpers.js +85 -0
  68. package/dist/hooks.js +158 -0
  69. package/dist/image-models.js +117 -0
  70. package/{src/integration.ts → dist/integration.js} +1 -2
  71. package/dist/journal.js +1 -0
  72. package/dist/look.js +363 -0
  73. package/dist/memory.js +1 -0
  74. package/dist/mode.js +97 -0
  75. package/dist/native.js +3348 -0
  76. package/dist/nogit.js +259 -0
  77. package/dist/outcomes.js +148 -0
  78. package/dist/permission.js +35 -0
  79. package/dist/pick.js +89 -0
  80. package/dist/pipelines.js +262 -0
  81. package/dist/plan.js +641 -0
  82. package/dist/plandoc.js +211 -0
  83. package/dist/plugin.js +4736 -0
  84. package/dist/policy.js +58 -0
  85. package/dist/pools.js +1 -0
  86. package/dist/preview.js +274 -0
  87. package/dist/profile.js +165 -0
  88. package/dist/progress.js +1 -0
  89. package/dist/promote.js +313 -0
  90. package/dist/redact.js +1 -0
  91. package/dist/registry.js +179 -0
  92. package/dist/riskscore.js +126 -0
  93. package/dist/roles.js +1 -0
  94. package/dist/routing.js +1 -0
  95. package/dist/runner.js +1892 -0
  96. package/{src/sandbox.ts → dist/sandbox.js} +1 -2
  97. package/dist/sandboxgate.js +90 -0
  98. package/dist/scheduler.js +170 -0
  99. package/dist/services-main.js +131 -0
  100. package/dist/services.js +265 -0
  101. package/dist/session.js +241 -0
  102. package/dist/setup.js +423 -0
  103. package/dist/shell/decide.js +1 -0
  104. package/dist/shell/index.js +2 -0
  105. package/dist/shell/sandbox.js +1 -0
  106. package/dist/shell/wire.js +1 -0
  107. package/dist/skills.js +103 -0
  108. package/dist/state.js +1 -0
  109. package/dist/store.js +1 -0
  110. package/dist/switcher.js +1 -0
  111. package/dist/synth.js +418 -0
  112. package/dist/tools.js +477 -0
  113. package/dist/trials.js +223 -0
  114. package/dist/usage.js +1 -0
  115. package/dist/wait.js +167 -0
  116. package/dist/watchdog.js +476 -0
  117. package/dist/web-guidance.js +43 -0
  118. package/dist/which.js +20 -0
  119. package/dist/worktree/git.js +545 -0
  120. package/dist/writeguard.js +311 -0
  121. package/package.json +36 -17
  122. package/skills/deck/SKILL.md +98 -0
  123. package/skills/design/SKILL.md +150 -0
  124. package/skills/image/SKILL.md +66 -0
  125. package/skills/orchestrator/SKILL.md +107 -0
  126. package/skills/video/SKILL.md +97 -0
  127. package/skills/web/SKILL.md +60 -0
  128. package/src/agenda.ts +0 -56
  129. package/src/agents.ts +0 -74
  130. package/src/ask.ts +0 -243
  131. package/src/backends.ts +0 -144
  132. package/src/backlog.ts +0 -436
  133. package/src/bench.ts +0 -163
  134. package/src/board.ts +0 -1
  135. package/src/brief.ts +0 -151
  136. package/src/browser.ts +0 -624
  137. package/src/budget.ts +0 -73
  138. package/src/catalog.ts +0 -214
  139. package/src/checkchange.ts +0 -180
  140. package/src/checkpoint.ts +0 -99
  141. package/src/cli.ts +0 -117
  142. package/src/compact.ts +0 -162
  143. package/src/config.ts +0 -340
  144. package/src/context/capture.ts +0 -1
  145. package/src/context/digest.ts +0 -1
  146. package/src/context/embed.ts +0 -1
  147. package/src/context/index.ts +0 -2
  148. package/src/context/ledger.ts +0 -1
  149. package/src/context/manager.ts +0 -1
  150. package/src/context/memory.ts +0 -1
  151. package/src/context/policy.ts +0 -1
  152. package/src/context/prices.ts +0 -1
  153. package/src/context/recall.ts +0 -1
  154. package/src/context/rules.ts +0 -1
  155. package/src/context/search.ts +0 -1
  156. package/src/context/status.ts +0 -1
  157. package/src/context/store.ts +0 -1
  158. package/src/context/summary.ts +0 -1
  159. package/src/context/tokens.ts +0 -1
  160. package/src/context/tools.ts +0 -1
  161. package/src/continuation.ts +0 -122
  162. package/src/contract.ts +0 -342
  163. package/src/contractround.ts +0 -225
  164. package/src/control.ts +0 -1
  165. package/src/dataset.ts +0 -133
  166. package/src/decide.ts +0 -690
  167. package/src/eval.ts +0 -66
  168. package/src/evolver.ts +0 -369
  169. package/src/followups.ts +0 -50
  170. package/src/forms.ts +0 -191
  171. package/src/gate.ts +0 -90
  172. package/src/grants.ts +0 -239
  173. package/src/graph.ts +0 -74
  174. package/src/guard/index.ts +0 -1
  175. package/src/guard/wire.ts +0 -1
  176. package/src/helpers.ts +0 -105
  177. package/src/hooks.ts +0 -199
  178. package/src/jev.ts +0 -141
  179. package/src/journal.ts +0 -1
  180. package/src/look.ts +0 -390
  181. package/src/memory.ts +0 -1
  182. package/src/native.ts +0 -2455
  183. package/src/nogit.ts +0 -112
  184. package/src/outcomes.ts +0 -210
  185. package/src/pick.ts +0 -112
  186. package/src/pipelines.ts +0 -252
  187. package/src/plan.ts +0 -449
  188. package/src/plugin.ts +0 -3187
  189. package/src/policy.ts +0 -84
  190. package/src/pools.ts +0 -1
  191. package/src/profile.ts +0 -186
  192. package/src/progress.ts +0 -1
  193. package/src/redact.ts +0 -1
  194. package/src/registry.ts +0 -207
  195. package/src/roles.ts +0 -1
  196. package/src/routing.ts +0 -1
  197. package/src/runner.ts +0 -1506
  198. package/src/scheduler.ts +0 -200
  199. package/src/session.ts +0 -269
  200. package/src/shell/decide.ts +0 -1
  201. package/src/shell/index.ts +0 -2
  202. package/src/shell/sandbox.ts +0 -1
  203. package/src/shell/wire.ts +0 -1
  204. package/src/skills.ts +0 -111
  205. package/src/state.ts +0 -1
  206. package/src/store.ts +0 -1
  207. package/src/switcher.ts +0 -1
  208. package/src/tools.ts +0 -480
  209. package/src/trials.ts +0 -247
  210. package/src/usage.ts +0 -1
  211. package/src/wait.ts +0 -180
  212. package/src/watchdog.ts +0 -498
  213. package/src/worktree/git.ts +0 -378
package/src/runner.ts DELETED
@@ -1,1506 +0,0 @@
1
- // Phase B's runner: a job from goal to its own branch, one task at a time on pipeline P1 (implement -> gate,
2
- // fix at most twice). The planner and the workers are plugin-started sessions (Phase A, A2); code moves the
3
- // state, runs the checks and commits. The decision model joins in later phases; here the rules decide.
4
-
5
- import { readdirSync, readFileSync } from "node:fs"
6
- import { join } from "node:path"
7
-
8
- import { buildAgenda, nextProposal } from "./agenda.ts"
9
- import { Decider, RulesBackend } from "./backends.ts"
10
- import { createHash } from "node:crypto"
11
-
12
- import {
13
- ANSWER, batchQuestions, CHOICE_FLOOR, complexityOf, ESCALATE, ESCALATION, NOUL_FLOOR, nextQuestionChoice, PROGRESS, splitQuestions, TRIAGE,
14
- type EscalationKind,
15
- } from "./catalog.ts"
16
- import { n7Questions, n7State, triage, type N7Context, type Verdict } from "./followups.ts"
17
- import { checkGuards, flagsWithoutUser, gateAnswer, gateQuestion, injected, injectionScore, type Unchecked } from "./gate.ts"
18
- import { brief, fixPrompt, handoffText, lastAssistantText, parseReport, refused, skillLine, taskAcceptance, usage } from "./brief.ts"
19
- import {
20
- changedFiles, commitTask, exec as defaultExec, fastForward, frozenCheck, hashFiles, prepareIntegration, prepareTaskWorktree, rebaseTask, removeTaskWorktree, revertFiles,
21
- runGate, taskDir, workingDiff, type Exec, type GateResult,
22
- } from "./integration.ts"
23
- import { checkTimeoutOf } from "./worktree/git.ts"
24
- import { redact } from "./jev.ts"
25
- import { learnQuestions, readMemory, RECALL_MAX, writeMemory } from "./memory.ts"
26
- import { record } from "./journal.ts"
27
- import { HEADER } from "./hooks.ts"
28
- import {
29
- choosePipeline, citationCheck, riskAtLeast, greenNote, mergeReviews, readerCount, readerPrompt, redPrompt, researchPath, reviewFixPrompt, reviewPrompt, parseReview,
30
- standardsPrompt, synthesisPrompt, TEST_FILE, type Review, type ReviewAxis,
31
- } from "./pipelines.ts"
32
- import {
33
- addDelegated, addDiscovered, applyPlan, applyReplan, applySplits, MAX_SPLIT_LEVEL, parsePlan, PLAN_FORMAT, replanFormat, splitFormat, waves,
34
- type Delegation, type Parsed, type Plan, type PlannedTask,
35
- } from "./plan.ts"
36
- import { classifyQuestions, classifyState, combine, narrowing, profileText, type Profile, type Skill } from "./profile.ts"
37
- import { resolvePolicy, type Policies } from "./policy.ts"
38
- import { route, type Availability, type ModelEntry } from "./registry.ts"
39
- import { family, roleById, type Rule } from "./roles.ts"
40
- import {
41
- addNodes, applyAnswer, applyShortcut, decisionsText, frontier, instruction, matchSessionShortcut, nextStep, parseTree, settle,
42
- type AnswerReading, type DesignTree, type Step,
43
- } from "./session.ts"
44
- import { discoveredCap, isDone, parallelSafe, moveJob, moveTask, newJob, promoteReady, stage, type FollowUp, type Job, type JobPhase, type Later, type Task } from "./state.ts"
45
- import { skillsFor, type Stage } from "./skills.ts"
46
- import { excludeFromGit, jobId, loadJob, saveJob, saveNote } from "./store.ts"
47
- import { FIX_ROUNDS, handoffNote, MAX_STEPS, TIER_STEPS, type Signal } from "./watchdog.ts"
48
- import { overBudget } from "./budget.ts"
49
-
50
- // The part of ctx.session the runner needs (argument shapes as seen in Phase A).
51
- export interface SessionApi {
52
- create(args: Record<string, unknown>): Promise<{ id: string }>
53
- prompt(args: { sessionID: string; text: string }): Promise<unknown>
54
- wait(args: { sessionID: string }): Promise<unknown>
55
- context(args: { sessionID: string }): Promise<unknown>
56
- interrupt(args: { sessionID: string }): Promise<unknown>
57
- }
58
-
59
- export interface RunnerDeps {
60
- readonly session: SessionApi
61
- readonly project: string
62
- readonly registry: readonly ModelEntry[]
63
- readonly policies?: Policies
64
- readonly availability?: () => Promise<Map<string, Availability>>
65
- readonly exec?: Exec
66
- readonly journal?: (entry: Record<string, unknown>) => void
67
- readonly progress?: (text: string, task?: boolean) => void // task: a task finished or was added
68
- readonly parentID?: string // the micromanager session; workers show up as its children
69
- readonly onWorker?: (sessionID: string, task: string, rules: readonly Rule[]) => void // a worker's task and narrowed rights, for permissions
70
- readonly workerTimeoutMs?: number
71
- readonly stallMs?: number // a session whose messages do not change this long is stalled (default 4 min)
72
- readonly pollMs?: number // how often a running session is looked at for that (default 20 s)
73
- readonly fixRounds?: number
74
- readonly planRetries?: number
75
- readonly decider?: Decider // the decision model per node; without one, the rules decide
76
- readonly watch?: (sessionID: string, maxSteps: number) => void // the loop watchdog starts judging a session
77
- readonly stopped?: (sessionID: string) => Signal | undefined // why the watchdog stopped a session, if it did
78
- readonly unchecked?: Unchecked // what G0 does when nothing local could check a job
79
- readonly cloudOnly?: boolean // local models are switched off (the user's choice for now): nothing may need them
80
- readonly skills?: readonly Skill[] // the skills the decision model may pick per task (design.md §13.1)
81
- readonly installedSkills?: ReadonlySet<string> // the skills a brief may name: linked into OpenCode by install.sh
82
- readonly cancelled?: () => boolean // the user stopped the job (stop_job); checked around every session turn
83
- readonly budget?: { tokens?: number; requests?: number; cost?: number } // per job, from the config (design.md §10.2)
84
- readonly parallel?: number // tasks of a job at the same time (Phase F); 1 runs them one after another in the job's worktree
85
- readonly perModel?: number // sessions of one cloud model at the same time; a local model serves one at a time
86
- readonly taskEnded?: (job: Job, task: Task) => void // a task of a rolling job merged, escalated or waits for the user
87
- readonly waiting?: (sessionID: string) => boolean // a permission request of the session is paused for an answer (src/ask.ts)
88
- readonly checkTimeoutMs?: number // how long one check may run (default 300 s); the job may override it
89
- }
90
-
91
- // Thrown out of a session turn when the user stopped the job; run() pauses the job, and the next run resumes it.
92
- export class Cancelled extends Error {}
93
-
94
- // A worker session in progress: its model, its last answer, and whether it is already the fresh retry.
95
- interface Work {
96
- s: { id: string }
97
- model: { id: string; reason: string }
98
- answer: { text: string; timedOut: boolean; stopped?: Signal }
99
- fresh: boolean
100
- uncensored?: boolean // rerouted to a local uncensored model after a refusal
101
- }
102
-
103
- const REVIEW_ROUNDS = 3
104
-
105
- // What a step of the micromanager's tools ends with: text for the micromanager to act on.
106
- export interface Outcome {
107
- readonly kind: "gate" | "session" | "plan" | "failed" | "info"
108
- readonly job: Job
109
- readonly text: string
110
- }
111
-
112
- export function toModel(id: string): { providerID: string; id: string } {
113
- const i = id.indexOf("/")
114
- return { providerID: id.slice(0, i), id: id.slice(i + 1) }
115
- }
116
-
117
- export class Runner {
118
- readonly #d: RunnerDeps
119
- readonly #exec: Exec
120
- readonly #journal: (entry: Record<string, unknown>) => void
121
-
122
- readonly #decider: Decider
123
- #job?: Job // the job this runner works on; its counters take every session's usage
124
- readonly #seen = new Map<string, { tokens: number; cost: number; requests: number }>() // usage per session so far
125
- readonly #tokenCaps = new Map<string, number>() // N5's budget tier per worker session
126
- readonly #sessionModel = new Map<string, string>() // for the per-model limit
127
- readonly #slots = new Map<string, { used: number; waiting: (() => void)[] }>()
128
- #train: Promise<void> = Promise.resolve() // the merge train: one task's branch at a time
129
-
130
- constructor(deps: RunnerDeps) {
131
- this.#d = deps
132
- this.#exec = deps.exec ?? defaultExec
133
- this.#journal = deps.journal ?? record
134
- this.#decider = deps.decider ?? new Decider({ default: "rules", nodes: {}, urls: {} }, { rules: new RulesBackend() }, this.#journal)
135
- }
136
-
137
- #policies(job: Job, task?: string): Policies {
138
- return { ...(this.#d.policies ?? {}), job: job.pins, ...(task && job.taskPins?.[task] ? { task: job.taskPins[task] } : {}) }
139
- }
140
-
141
- // How long one of this job's checks may run: the job's own setting where it has one, else the config's, else 300 s.
142
- #checkTimeout(job: Job | undefined): number {
143
- return checkTimeoutOf(job, this.#d.checkTimeoutMs)
144
- }
145
-
146
- // A model's family as the registry knows it ("qwen" for qwen3.8-flash and qwen3.8-u alike), so "another family"
147
- // means what routing compares.
148
- #family(id: string): string {
149
- return this.#d.registry.find((m) => m.id === id)?.family ?? family(id)
150
- }
151
-
152
- #say(text: string, task = false): void {
153
- this.#d.progress?.(text, task)
154
- }
155
-
156
- // The model for a role: the user's preset if any, else the router over the registry, else the role's cloud model.
157
- // uncensored: this task needs a local uncensored model (a worker refused it); routed is false when none fits.
158
- async #model(job: Job, role: string, difficulty: number, task?: string, avoidFamilies?: string[], vision = false, uncensored = false): Promise<{ id: string; reason: string; routed: boolean }> {
159
- const preset = resolvePolicy("N5.model", this.#policies(job, task))
160
- const presetModel = preset.policy.kind === "fixed" ? this.#d.registry.find((m) => m.id === (preset.policy as { value: string }).value) : undefined
161
- const local = job.flags?.localOnly || uncensored
162
- const free = job.flags?.uncensored || uncensored
163
- const presetBreaksGate = local && (presetModel?.location === "cloud" || (free && presetModel?.censored !== false))
164
- if (preset.policy.kind === "fixed" && !presetBreaksGate) {
165
- this.#journal({ kind: "routing", job: job.id, task, role, model: preset.policy.value, reason: `preset (${preset.level})` })
166
- return { id: preset.policy.value, reason: `preset (${preset.level})`, routed: true }
167
- }
168
- if (presetBreaksGate) this.#say(`preset ${(preset.policy as { value: string }).value} ignored: the ${uncensored ? "task" : "job"} must stay local${free ? " and uncensored" : ""}`)
169
- const availability = await this.#d.availability?.().catch(() => undefined)
170
- const r = route(this.#d.registry, { role, difficulty, vision, sensitive: local, refusalLikely: free, avoidFamilies }, availability)
171
- const id = r.model ?? roleById(role)?.models[0] ?? this.#d.registry[0]!.id
172
- this.#journal({ kind: "routing", job: job.id, task, role, model: id, reason: r.model ? r.reason : `fallback: ${r.reason}`, ranked: r.ranked.slice(0, 5) })
173
- return { id, reason: r.model ? r.reason : "fallback", routed: r.model !== undefined }
174
- }
175
-
176
- async #ask(sessionID: string, text: string): Promise<{ text: string; timedOut: boolean; stopped?: Signal }> {
177
- if (this.#d.cancelled?.()) throw new Cancelled()
178
- const model = this.#sessionModel.get(sessionID)
179
- const release = model ? await this.#acquire(model) : () => {}
180
- const timeoutMs = this.#d.workerTimeoutMs ?? 20 * 60_000
181
- let timer: ReturnType<typeof setTimeout> | undefined
182
- let timedOut: boolean
183
- let stalled: Signal | undefined
184
- let done = false
185
- try {
186
- // Briefs, handoff notes, check output and review diffs may quote a key; no model needs one (E2b).
187
- await this.#d.session.prompt({ sessionID, text: redact(text) })
188
- timedOut = await Promise.race([
189
- this.#d.session.wait({ sessionID }).then(() => false),
190
- new Promise<boolean>((resolve) => { timer = setTimeout(() => resolve(true), timeoutMs) }),
191
- this.#stall(sessionID, () => done).then((s) => { stalled = s; return s !== undefined }),
192
- ])
193
- } finally {
194
- done = true
195
- clearTimeout(timer) // also when wait() fails, or the timer keeps the process alive for the whole timeout
196
- release()
197
- }
198
- if (timedOut && !stalled) await this.#d.session.interrupt({ sessionID }).catch(() => undefined) // a stall interrupted already
199
- if (this.#d.cancelled?.()) throw new Cancelled()
200
- const messages = await this.#d.session.context({ sessionID })
201
- const used = this.#count(sessionID, messages)
202
- const cap = this.#tokenCaps.get(sessionID)
203
- const stopped = stalled ?? this.#d.stopped?.(sessionID) ?? (cap && used.tokens > cap ? { kind: "tokens" as const, detail: `${used.tokens} tokens in one session, over the task's ${cap}` } : undefined)
204
- return { text: lastAssistantText(messages), timedOut: timedOut && !stalled, stopped }
205
- }
206
-
207
- // A provider stream that stops mid-answer leaves a session waiting with no hook firing (live test: a reviewer's
208
- // message started streaming and never completed). The session is looked at every pollMs; when nothing changed for
209
- // stallMs, it is stalled and treated like a watchdog stop: a fresh session on another family.
210
- //
211
- // "Did anything change?" is answered by the message bookkeeping, not by the messages: JSON.stringify over the
212
- // whole history of a session in the hundreds of thousands of tokens cost megabytes per poll, per active session,
213
- // to learn nothing. The fingerprint is the number of messages plus the last one's id and updated time, all of it
214
- // monotonic and O(1) to read.
215
- async #stall(sessionID: string, finished: () => boolean): Promise<Signal | undefined> {
216
- const pollMs = this.#d.pollMs ?? 20_000
217
- const stallMs = this.#d.stallMs ?? 4 * 60_000
218
- const fingerprint = (messages: unknown): string => {
219
- if (!Array.isArray(messages)) return ""
220
- const last = messages[messages.length - 1] as { id?: unknown; time?: { created?: unknown; updated?: unknown } } | undefined
221
- return `${messages.length}:${String(last?.id ?? "")}:${String(last?.time?.updated ?? last?.time?.created ?? "")}`
222
- }
223
- let last = ""
224
- let since = Date.now()
225
- while (!finished()) {
226
- await new Promise<void>((resolve) => { const t = setTimeout(resolve, pollMs); t.unref?.() })
227
- if (finished()) return undefined
228
- // A context call that fails counts as no change, as before: an unreadable session is not a moving one.
229
- const seen = await this.#d.session.context({ sessionID }).catch(() => undefined)
230
- const now = seen === undefined ? last : fingerprint(seen)
231
- // A session paused on a permission request waits for an answer, not for a stuck model: it is no stall.
232
- if (now !== last || this.#d.waiting?.(sessionID)) [last, since] = [now, Date.now()]
233
- else if (Date.now() - since >= stallMs) {
234
- await this.#d.session.interrupt({ sessionID }).catch(() => undefined)
235
- return { kind: "stalled", detail: `no progress for ${Math.round(stallMs / 1000)} s (the model stopped answering)` }
236
- }
237
- }
238
- return undefined
239
- }
240
-
241
- // A turn on a model waits for a free slot: 2 sessions per cloud model, 1 per local one (design.md §11).
242
- async #acquire(model: string): Promise<() => void> {
243
- const cap = this.#d.registry.find((m) => m.id === model)?.location === "local" ? 1 : (this.#d.perModel ?? 2)
244
- const slot = this.#slots.get(model) ?? { used: 0, waiting: [] }
245
- this.#slots.set(model, slot)
246
- while (slot.used >= cap) await new Promise<void>((resolve) => slot.waiting.push(resolve))
247
- slot.used++
248
- return () => {
249
- slot.used--
250
- slot.waiting.shift()?.()
251
- }
252
- }
253
-
254
- // A session's usage so far; what is new since the last turn goes to the job's counters.
255
- #count(sessionID: string, messages: unknown): { tokens: number; cost: number; requests: number } {
256
- const now = { ...usage(messages), requests: Array.isArray(messages) ? (messages as { type?: string }[]).filter((m) => m.type === "assistant").length : 0 }
257
- const before = this.#seen.get(sessionID) ?? { tokens: 0, cost: 0, requests: 0 }
258
- this.#seen.set(sessionID, now)
259
- const c = this.#job?.counters
260
- if (c) {
261
- c.tokens = (c.tokens ?? 0) + Math.max(0, now.tokens - before.tokens)
262
- c.cost = (c.cost ?? 0) + Math.max(0, now.cost - before.cost)
263
- c.requests = (c.requests ?? 0) + Math.max(0, now.requests - before.requests)
264
- }
265
- return now
266
- }
267
-
268
- // The first budget the job has used up, as a reason; checked before every start (design.md §10.2).
269
- #overBudget(job: Job): string | undefined {
270
- return overBudget(job)
271
- }
272
-
273
- // Goal -> validated plan, waiting at the plan gate for the user's go.
274
- async plan(goal: string): Promise<{ job: Job; errors?: string[] }> {
275
- const job = newJob(jobId(), goal)
276
- excludeFromGit(this.#d.project)
277
- moveJob(job, "triage")
278
- return this.planJob(job)
279
- }
280
-
281
- // A job from triage or a confirmed checkpoint to a validated plan at the plan gate.
282
- // In cloud-only mode a job is local-only only by the user's choice. A local-only flag that came from the "nothing
283
- // local could check it" default (the GLiNER server was down) is dropped.
284
- #cloudFlags(job: Job): void {
285
- if (this.#d.cloudOnly && job.flags?.localOnly && job.flags.gate && !job.flags.gate.checked) {
286
- job.flags = { ...job.flags, localOnly: false }
287
- job.lessons.push("cloud only: the local-only default of an unchecked goal was dropped")
288
- }
289
- }
290
-
291
- async planJob(job: Job): Promise<{ job: Job; errors?: string[] }> {
292
- this.#cloudFlags(job)
293
- if (job.phase !== "plan") moveJob(job, "plan")
294
- saveJob(this.#d.project, job)
295
- const model = await this.#model(job, "plan", 0.7)
296
- this.#say(`planning with ${model.id} (${model.reason})`)
297
- let s = await this.#plannerSession(job, model.id)
298
- let answer = await this.#ask(s.id, plannerPrompt(job))
299
- if (answer.stopped) {
300
- // never resume a stopped session: one fresh planner with a handoff note
301
- this.#say(`the planner was stopped by the loop watchdog (${answer.stopped.detail}); one fresh try`)
302
- s = await this.#plannerSession(job, model.id)
303
- answer = await this.#ask(s.id, `${plannerPrompt(job)}\n\n${handoffNote(answer.stopped, [])}`)
304
- }
305
- let parsed: Parsed = answer.stopped ? { errors: [`the planner was stopped by the loop watchdog: ${answer.stopped.detail}`] } : parsePlan(answer.text)
306
- for (let retry = 0; parsed.errors && !answer.timedOut && !answer.stopped && retry < (this.#d.planRetries ?? 2); retry++) {
307
- this.#say(`the plan has ${parsed.errors.length} problem(s), asking again`)
308
- answer = await this.#ask(s.id, `${HEADER} The plan has these problems:\n- ${parsed.errors.join("\n- ")}\n\nAnswer again with the corrected JSON only.`)
309
- parsed = answer.stopped ? { errors: [`the planner was stopped by the loop watchdog: ${answer.stopped.detail}`] } : parsePlan(answer.text)
310
- }
311
- if (!parsed.plan) {
312
- job.lessons.push(`planning failed: ${answer.timedOut ? "the planner timed out" : (parsed.errors ?? []).join("; ")}`)
313
- moveJob(job, "failed")
314
- saveJob(this.#d.project, job)
315
- return { job, errors: answer.timedOut ? ["the planner timed out"] : parsed.errors }
316
- }
317
- let plan = parsed.plan
318
- let candidates: readonly PlannedTask[] = plan.tasks
319
- for (let level = 1; level <= MAX_SPLIT_LEVEL && candidates.length > 0 && !answer.stopped; level++) {
320
- const before = new Set(plan.tasks.map((t) => t.id))
321
- plan = await this.#split(job, s.id, plan, candidates)
322
- candidates = plan.tasks.filter((t) => !before.has(t.id))
323
- }
324
- applyPlan(job, plan)
325
- moveJob(job, "plan_gate")
326
- saveJob(this.#d.project, job)
327
- return { job }
328
- }
329
-
330
- // N4: tasks that are too big for one fresh session and can be split go back to the planner, which writes the parts;
331
- // code re-validates. Without a decision model, more than 3 files means too big. A split that stays invalid keeps
332
- // the task whole.
333
- async #split(job: Job, plannerSession: string, plan: Plan, candidates: readonly PlannedTask[]): Promise<Plan> {
334
- const policy = resolvePolicy("N4", this.#policies(job)).policy
335
- if (policy.kind === "fixed") return plan // "N4": "fixed:no" keeps the planner's tasks
336
- const asked = policy.kind === "rule" ? undefined : await this.#decider.ask("N4", { goal: job.goal }, splitQuestions(candidates), { localOnly: job.flags?.localOnly, job: job.id })
337
- const a = asked?.decision.answers ?? {}
338
- const p = (q: string) => (a[q]?.type === "noul" ? (a[q] as { noul: number }).noul : undefined)
339
- const ids = candidates.filter((t) => {
340
- const big = p(`too_big.${t.id}`)
341
- const hard = p(`hard.${t.id}`)
342
- const splittable = p(`splittable.${t.id}`)
343
- if (big === undefined && hard === undefined) return t.files.length > 3
344
- return Math.max(big ?? 0, hard ?? 0) >= NOUL_FLOOR && (splittable ?? 0) >= NOUL_FLOOR
345
- }).map((t) => t.id)
346
- if (ids.length === 0) return plan
347
- this.#say(`splitting ${ids.join(", ")}`)
348
- let answer = await this.#ask(plannerSession, `${HEADER} ${splitFormat(ids)}`)
349
- let r = answer.stopped || answer.timedOut ? { errors: ["the planner stopped"] } as Parsed : applySplits(plan, answer.text, ids)
350
- if (r.errors && !answer.stopped && !answer.timedOut) {
351
- answer = await this.#ask(plannerSession, `${HEADER} The split has these problems:\n- ${r.errors.join("\n- ")}\n\nAnswer again with the corrected JSON only.`)
352
- r = answer.stopped || answer.timedOut ? { errors: ["the planner stopped"] } : applySplits(plan, answer.text, ids)
353
- }
354
- if (r.errors) {
355
- job.lessons.push(`split of ${ids.join(", ")} kept whole: ${r.errors.slice(0, 3).join("; ")}`)
356
- this.#say(`the split of ${ids.join(", ")} stays invalid; the tasks stay whole`)
357
- return plan
358
- }
359
- return r.plan
360
- }
361
-
362
- // A new job from the micromanager: the local gate, triage, then a planning session or the planner (design.md §6).
363
- async start(goal: string, facilitator?: string): Promise<Outcome> {
364
- const job = newJob(jobId(), goal)
365
- job.facilitator = facilitator
366
- excludeFromGit(this.#d.project)
367
- moveJob(job, "triage")
368
- const gate = await checkGuards(this.#decider, goal, job.id)
369
- const flags = flagsWithoutUser(gate, this.#d.unchecked ?? (this.#d.cloudOnly ? "cloud" : "local"), this.#d.cloudOnly)
370
- if (flags === "ask_user") {
371
- job.flags = { gate }
372
- moveJob(job, "ask_user")
373
- saveJob(this.#d.project, job)
374
- return { kind: "gate", job, text: `[job ${job.id}] Only the user can answer the local check, so ask them now: show the question below word for word, call no tool, and end your turn. Their reply reaches the plugin by itself.\n\n${gateQuestion(gate, this.#d.cloudOnly)}` }
375
- }
376
- job.flags = flags
377
- return this.#triage(job)
378
- }
379
-
380
- // plan_job with a job id: go on from wherever the job stands.
381
- // feedback: what the user wants changed in a plan at the plan gate. It becomes a decision, and the planner writes
382
- // the plan again (live test: the micromanager asked eight times for a fuller plan and always got the old one back).
383
- async continueJob(id: string, feedback?: string): Promise<Outcome> {
384
- const job = loadJob(this.#d.project, id)
385
- if (!job) return { kind: "failed", job: newJob(id, ""), text: `no job ${id}` }
386
- if (job.phase === "plan_gate" && feedback?.trim()) {
387
- job.decisions.push({ id: `F${job.decisions.length + 1}`, text: `plan feedback: ${feedback.trim()}`, origin: "user" })
388
- moveJob(job, "plan")
389
- saveJob(this.#d.project, job)
390
- return this.#planned(await this.planJob(job))
391
- }
392
- if (job.phase === "triage") return this.#triage(job)
393
- if (job.phase === "plan") return this.#planned(await this.planJob(job))
394
- if (job.phase === "planning_session" && job.designTree) {
395
- const node = job.designTree.nodes.find((n) => n.id === job.designTree!.current)
396
- return { kind: "session", job, text: node ? instruction({ kind: "ask", node, reason: "continued" }, job.id, job.designTree) : draftInstruction(job) }
397
- }
398
- if (job.phase === "planning_session") return { kind: "session", job, text: draftInstruction(job) }
399
- if (job.phase === "paused" && job.resumePhase === "planning_session") {
400
- moveJob(job, "planning_session")
401
- saveJob(this.#d.project, job)
402
- return this.continueJob(id)
403
- }
404
- return { kind: "info", job, text: `job ${job.id} is in phase ${job.phase}` }
405
- }
406
-
407
- #planned(r: { job: Job; errors?: string[] }): Outcome {
408
- return r.errors
409
- ? { kind: "failed", job: r.job, text: `The planner could not produce a valid plan (job ${r.job.id}):\n- ${r.errors.join("\n- ")}` }
410
- : { kind: "plan", job: r.job, text: "" }
411
- }
412
-
413
- // N1: how complex, and does it need the user's decisions first? A pin ("no planning session") skips the session.
414
- async #triage(job: Job): Promise<Outcome> {
415
- const pin = resolvePolicy("N2.clarity", this.#policies(job)).policy
416
- const asked = await this.#decider.ask("N1", { goal: job.goal, files: topLevel(this.#d.project) }, TRIAGE, { localOnly: job.flags?.localOnly, job: job.id })
417
- const c = asked.decision.answers.complexity
418
- const n = asked.decision.answers.needs_clarification
419
- const complexity = c?.type === "score" ? complexityOf(c.score) : undefined
420
- const clarification = n?.type === "noul" ? n.noul : undefined
421
- let session: boolean
422
- let reason: string
423
- if (pin.kind === "fixed") [session, reason] = [pin.value !== "clear", `preset ${pin.value}`]
424
- else if (pin.kind === "ask") [session, reason] = [true, "the user wants to be asked"]
425
- else if (clarification === undefined) [session, reason] = [true, "no decision model answer: open questions count as open"]
426
- else if (clarification >= NOUL_FLOOR) [session, reason] = [true, `open decisions (${clarification.toFixed(2)})`]
427
- else [session, reason] = [false, `clear enough (${clarification.toFixed(2)})`]
428
- job.triage = { complexity, clarification, session, reason }
429
- if (!session) return this.#planned(await this.planJob(job))
430
- moveJob(job, "clarity")
431
- moveJob(job, "planning_session")
432
- saveJob(this.#d.project, job)
433
- return { kind: "session", job, text: draftInstruction(job) }
434
- }
435
-
436
- // The facilitator's draft of the design tree, or new branches for an existing one.
437
- async questions(id: string, json: string): Promise<string> {
438
- const job = loadJob(this.#d.project, id)
439
- if (!job || (job.phase !== "planning_session" && job.phase !== "design_checkpoint")) return `no planning session for job ${id}`
440
- let raw: unknown
441
- try {
442
- raw = JSON.parse(json)
443
- } catch (err) {
444
- return `invalid JSON: ${err instanceof Error ? err.message : String(err)}. Send the list of questions again.`
445
- }
446
- if (!job.designTree) {
447
- const parsed = parseTree(raw)
448
- if (parsed.errors) return `The questions have problems:\n- ${parsed.errors.join("\n- ")}\nSend them again.`
449
- job.designTree = parsed.tree
450
- } else {
451
- const errors = addNodes(job.designTree, raw)
452
- if (errors.length) return `The new questions have problems:\n- ${errors.join("\n- ")}\nSend them again.`
453
- }
454
- if (job.phase === "design_checkpoint") moveJob(job, "planning_session")
455
- await this.#settledByJob(job)
456
- return this.#advance(job, nextStep(job.designTree, await this.#pick(job)))
457
- }
458
-
459
- // N2: questions the job text already answers are settled without asking (one request, one noul per question).
460
- async #settledByJob(job: Job): Promise<void> {
461
- const tree = job.designTree!
462
- const open = tree.nodes.filter((n) => n.status === "open" && n.kind === "decision")
463
- if (open.length === 0) return
464
- const questions = Object.fromEntries(open.map((n) => [`settled_${n.id}`, {
465
- type: "noul" as const,
466
- instructions: `The question "${n.question}" is already answered by the job text, so the user does not need to be asked.`,
467
- }]))
468
- const asked = await this.#decider.ask("N2", { goal: job.goal }, questions, { localOnly: job.flags?.localOnly, job: job.id })
469
- for (const n of open) {
470
- const a = asked.decision.answers[`settled_${n.id}`]
471
- if (a?.type === "noul" && a.noul >= 0.8) settle(tree, n.id, "answered by the job text", "fact")
472
- }
473
- }
474
-
475
- // N2b: which frontier question next; below the floor the rules pick.
476
- async #pick(job: Job): Promise<string | undefined> {
477
- const options = frontier(job.designTree!)
478
- if (options.length < 2) return undefined
479
- const asked = await this.#decider.ask("N2b", { goal: job.goal, decided: decisionsText(job.designTree!) },
480
- { next: nextQuestionChoice(Object.fromEntries(options.map((n) => [n.id, n.question]))) }, { localOnly: job.flags?.localOnly, job: job.id })
481
- const a = asked.decision.answers.next
482
- return a?.type === "choice" && a.confidence >= CHOICE_FLOOR ? a.choice : undefined
483
- }
484
-
485
- #advance(job: Job, step: Step): string {
486
- if (step.kind === "checkpoint" && job.phase === "planning_session") moveJob(job, "design_checkpoint")
487
- if (step.kind === "stopped") moveJob(job, "paused")
488
- saveJob(this.#d.project, job)
489
- return instruction(step, job.id, job.designTree!)
490
- }
491
-
492
- // One user turn in the micromanager session: the gate answer, a planning-session answer, or the checkpoint reply.
493
- // Returns the instruction for the micromanager's next turn, or undefined when the turn is not about this job.
494
- async answer(id: string, text: string): Promise<string | undefined> {
495
- const job = loadJob(this.#d.project, id)
496
- if (!job) return undefined
497
- if (job.phase === "ask_user" && job.resumePhase === "triage" && job.flags?.gate) {
498
- const reply = gateAnswer(text)
499
- if (reply === undefined) return `[job ${id}] Waiting for the user's answer to the local check: "always local", "use uncensored", "continue" or "stop".`
500
- if (reply === "stop") {
501
- moveJob(job, "stopped")
502
- saveJob(this.#d.project, job)
503
- return `[job ${id}] The user stopped the job. Confirm briefly.`
504
- }
505
- job.flags = { ...job.flags, ...reply }
506
- moveJob(job, "triage")
507
- saveJob(this.#d.project, job)
508
- return `[job ${id}] The user answered the local check${reply.uncensored ? ": local uncensored models only" : reply.localOnly ? ": everything stays local" : ""}. Call plan_job with goal "${id}" to continue.`
509
- }
510
- const tree = job.designTree
511
- if (job.phase === "design_checkpoint" && tree) {
512
- const s = matchSessionShortcut(text)
513
- if (s?.kind === "confirm") {
514
- job.decisions = tree.nodes.filter((n) => n.status === "settled").map((n) => ({ id: n.id, text: `${n.question} -> ${n.answer}`, origin: n.origin === "fact" ? "fact" : "user" }))
515
- moveJob(job, "plan")
516
- saveJob(this.#d.project, job)
517
- return `[job ${id}] The user confirmed the design. Call plan_job with goal "${id}" to plan it now.`
518
- }
519
- moveJob(job, "planning_session")
520
- saveJob(this.#d.project, job)
521
- return `[planning session ${id}] The user wants to change something ("${text.slice(0, 200)}"). Ask which decision they mean, one question, no suggestions. Reopen it with their words in mind; "back to <id>" reopens a question.`
522
- }
523
- if (job.phase !== "planning_session" || !tree) return undefined
524
- const shortcut = matchSessionShortcut(text)
525
- if (shortcut) {
526
- const step = applyShortcut(tree, shortcut)
527
- return this.#advance(job, step ?? nextStep(tree, await this.#pick(job)))
528
- }
529
- const reading = await this.#read(job, tree, text)
530
- const step = applyAnswer(tree, text, reading)
531
- return this.#advance(job, step ?? nextStep(tree, await this.#pick(job)))
532
- }
533
-
534
- // N2c: what the answer does; without the decision model an answer counts as settling the question.
535
- async #read(job: Job, tree: DesignTree, text: string): Promise<AnswerReading> {
536
- const node = tree.nodes.find((n) => n.id === tree.current)
537
- const asked = await this.#decider.ask("N2c", { question: node?.question, answer: text, decided: decisionsText(tree) }, ANSWER, { localOnly: job.flags?.localOnly, job: job.id })
538
- const yes = (q: string) => {
539
- const a = asked.decision.answers[q]
540
- return a?.type === "noul" ? a.noul >= NOUL_FLOOR : undefined
541
- }
542
- if (Object.keys(asked.decision.answers).length === 0) return { settles: true }
543
- return { settles: yes("settles_decision"), newBranches: yes("opens_new_branches"), stuck: yes("user_stuck"), asksOptions: yes("user_asks_for_options"), contradicts: yes("contradicts_earlier_decision"), outOfScope: yes("out_of_scope") }
544
- }
545
-
546
- // The user said go: work the plan on the job's branch until it is done or needs the user.
547
- // note: the user's answer when the job stopped for them; it becomes a decision every later brief carries, and a
548
- // blocked task starts again with it.
549
- async run(id: string, note?: string): Promise<Job> {
550
- const job = loadJob(this.#d.project, id)
551
- if (!job) throw new Error(`no job ${id}`)
552
- if (job.phase === "plan_gate") moveJob(job, "execute")
553
- else if (job.phase === "paused" && job.resumePhase === "execute") moveJob(job, "execute")
554
- else if (job.phase === "ask_user" && job.resumePhase === "execute") {
555
- // Running the job again after "confirm Tn before it runs" is the user's go for those tasks.
556
- for (const t of job.tasks) if (t.confirmed === false) t.confirmed = true
557
- for (const t of job.tasks) if (t.status === "blocked") moveTask(t, "pending")
558
- moveJob(job, "execute")
559
- }
560
- if (note?.trim()) job.decisions.push({ id: `U${job.decisions.length + 1}`, text: note.trim(), origin: "user" })
561
- if (job.phase !== "execute") throw new Error(`job ${id} is in phase ${job.phase}, not ready to run`)
562
- this.#job = job
563
- this.#cloudFlags(job)
564
- // Never quietly to the cloud: a job that must stay on this machine waits while local models are switched off.
565
- if (this.#d.cloudOnly && job.flags?.localOnly) {
566
- this.#stop(job, "this job must stay on this machine, but local models are switched off (cloudOnly); the user can let it go to the cloud, or switch local models on")
567
- saveJob(this.#d.project, job)
568
- return job
569
- }
570
- job.budget.tokensMax ??= this.#d.budget?.tokens
571
- job.budget.requestsMax ??= this.#d.budget?.requests
572
- job.budget.costMax ??= this.#d.budget?.cost
573
- if (!job.integrationWorktree) {
574
- excludeFromGit(this.#d.project) // also for a rolling job, which never passes plan or start
575
- const integration = await prepareIntegration(this.#d.project, job.id, this.#exec)
576
- job.integrationBranch = integration.branch
577
- job.integrationWorktree = integration.worktree
578
- // A git worktree is a checkout of the repository ROOT, so a project below it keeps an offset: without it every
579
- // worker and every check would work three levels above its own files.
580
- job.integrationRel = integration.rel
581
- job.integrationBase = integration.base
582
- job.integrationDirty = integration.dirty ? integration.dirtySummary : ""
583
- this.#say(`working on branch ${integration.branch}`)
584
- if (integration.rel) this.#say(`the project is ${integration.rel} below the repository root, so the worktree holds the whole repository; the tasks work in ${taskDir(integration.worktree, integration.rel)}`)
585
- if (integration.dirty) this.#say(`the working tree has uncommitted paths no worker will see (${integration.dirtySummary}); this job starts from ${integration.base.slice(0, 7)}`)
586
- } else await this.#reconcile(job)
587
- saveJob(this.#d.project, job)
588
- // Tasks run as promises; with parallel 1 one at a time, as before Phase F. A task that stops the job lets the
589
- // others finish what they are doing; a stop by the user cuts them all.
590
- const running = new Map<string, Promise<void>>()
591
- let cancelled = false
592
- let failure: unknown
593
- const start = (task: Task) => {
594
- const p = this.#dispatch(job, task)
595
- .catch((err: unknown) => { if (err instanceof Cancelled) cancelled = true; else failure ??= err })
596
- .finally(() => { running.delete(task.id); saveJob(this.#d.project, job) })
597
- running.set(task.id, p)
598
- }
599
- const settle = () => Promise.race(running.values())
600
- try {
601
- for (;;) {
602
- if (failure) throw failure
603
- if (cancelled || job.phase !== "execute") {
604
- if (running.size) await settle()
605
- else break
606
- continue
607
- }
608
- promoteReady(job)
609
- // A rolling job only runs what the orchestrator delegated: no verify, replan or wrap; it ends when nothing is
610
- // left to start, and the next delegation runs it again.
611
- const agenda = buildAgenda(job).filter((p) => (!p.taskId || !running.has(p.taskId)) && (!job.rolling || p.action === "dispatch"))
612
- const next = nextProposal(agenda)
613
- if (!next || (next.action !== "dispatch" && running.size)) {
614
- // verify, replan and asking the user wait until every running task has finished
615
- if (running.size) await settle()
616
- else break
617
- continue
618
- }
619
- if (++job.counters.turns > job.budget.turnsMax) {
620
- this.#stop(job, `turn budget of ${job.budget.turnsMax} used up`)
621
- continue
622
- }
623
- const over = this.#overBudget(job)
624
- if (over) {
625
- this.#stop(job, `budget: ${over}; raise it in the config or with a pin, then run the job again`)
626
- continue
627
- }
628
- if (next.action === "dispatch") {
629
- const batch = await this.#batch(job, agenda, running)
630
- if (batch.length === 0) await settle()
631
- for (const t of batch) start(t)
632
- if ((this.#d.parallel ?? 1) <= 1) while (running.size) await settle()
633
- } else if (next.action === "verify") await this.#verify(job)
634
- else if (next.action === "replan") await this.#replan(job)
635
- else this.#stop(job, next.label)
636
- saveJob(this.#d.project, job)
637
- }
638
- if (failure) throw failure
639
- if (cancelled) throw new Cancelled()
640
- } catch (err) {
641
- if (!(err instanceof Cancelled)) throw err
642
- // The tasks in progress are cut; the next run's reconcile starts them again from the last commit.
643
- if ((job.phase as JobPhase) === "replan") moveJob(job, "execute")
644
- job.lessons.push("stopped by the user")
645
- const phase = job.phase as JobPhase
646
- if (phase === "ask_user") moveJob(job, job.resumePhase ?? "execute") // a task had stopped it: pause the run itself
647
- if ((job.phase as JobPhase) !== "paused") moveJob(job, "paused")
648
- this.#say("stopped by the user; run the job again to resume")
649
- }
650
- saveJob(this.#d.project, job)
651
- return job
652
- }
653
-
654
- // The next ready tasks that may run next to the running ones: disjoint files, within the job's limit. Two or more
655
- // new ones are a batch the decision model confirms (N10); one it doubts waits for a later batch.
656
- async #batch(job: Job, agenda: readonly { action: string; taskId?: string }[], running: ReadonlyMap<string, unknown>): Promise<Task[]> {
657
- const limit = Math.max(1, this.#d.parallel ?? 1)
658
- const busy = job.tasks.filter((t) => running.has(t.id))
659
- const batch: Task[] = []
660
- for (const p of agenda) {
661
- if (p.action !== "dispatch" || !p.taskId || busy.length + batch.length >= limit) continue
662
- const t = job.tasks.find((x) => x.id === p.taskId)!
663
- if ([...busy, ...batch].every((o) => parallelSafe(o, t))) batch.push(t)
664
- }
665
- // N10 is opt-in ("N10": "auto" in the config): disjoint files are enough to run side by side.
666
- const n10 = resolvePolicy("N10", this.#policies(job))
667
- if (batch.length + busy.length < 2 || batch.length === 0 || n10.level === undefined || n10.policy.kind !== "auto") {
668
- if (batch.length + busy.length > 1) this.#say(`starting ${batch.map((t) => t.id).join(", ")}${busy.length ? ` next to ${busy.map((t) => t.id).join(", ")}` : " in parallel"}`)
669
- return batch
670
- }
671
- const all = [...busy, ...batch]
672
- const others = (id: string) => all.filter((t) => t.id !== id).map((t) => `${t.id} ("${t.title}")`).join(", ")
673
- const asked = await this.#decider.ask("N10", { goal: job.goal, tasks: all.map((t) => `${t.id} ${t.title}: ${t.description.slice(0, 300)} (files: ${t.files.join(", ") || "none"})`) }, batchQuestions(batch, others), { localOnly: job.flags?.localOnly, job: job.id })
674
- const a = asked.decision.answers
675
- // The first new task always goes when nothing runs; the others need the model's yes when it answered.
676
- const kept = batch.filter((t, i) => {
677
- const p = a[`independent.${t.id}`]
678
- return (i === 0 && busy.length === 0) || p?.type !== "noul" || p.noul >= NOUL_FLOOR
679
- })
680
- if (kept.length > 1 || busy.length) this.#say(`starting ${kept.map((t) => t.id).join(", ")} in parallel${busy.length ? ` with ${busy.map((t) => t.id).join(", ")}` : ""}`)
681
- return kept
682
- }
683
-
684
- // One task: in the job's worktree when tasks run one at a time, else in its own worktree, then the merge train.
685
- async #dispatch(job: Job, task: Task): Promise<void> {
686
- if ((this.#d.parallel ?? 1) <= 1) return this.#runTask(job, task)
687
- const w = await prepareTaskWorktree(this.#d.project, job.id, task.id, job.integrationBranch!, this.#exec, undefined, job.integrationRel ?? "")
688
- task.worktree = w.worktree
689
- task.worktreeRel = w.rel
690
- task.branch = w.branch
691
- try {
692
- await this.#runTask(job, task)
693
- if (task.status === "passed") {
694
- const step = this.#train.then(() => this.#merge(job, task))
695
- this.#train = step.catch(() => undefined)
696
- await step
697
- }
698
- } finally {
699
- if (task.worktree && task.status !== "blocked") await this.#dropWorktree(task)
700
- }
701
- }
702
-
703
- async #dropWorktree(task: Task): Promise<void> {
704
- if (!task.worktree || !task.branch) return
705
- await removeTaskWorktree(this.#d.project, { worktree: task.worktree, branch: task.branch }, this.#exec)
706
- task.worktree = undefined
707
- task.branch = undefined
708
- }
709
-
710
- // The merge train (design.md §11): rebase onto the job's branch, the task's checks again when that moved, then a
711
- // fast-forward. A conflict sends the task back to start again from the newest commit once; the second goes to the
712
- // user.
713
- async #merge(job: Job, task: Task): Promise<void> {
714
- const w = { worktree: task.worktree!, branch: task.branch! }
715
- let step = await rebaseTask(w, job.integrationBranch!, this.#exec)
716
- if (step.ok && step.moved) {
717
- const checks = [...new Set(taskAcceptance(job, task).map((a) => a.verify).filter((v): v is string => Boolean(v)))]
718
- const failed = (await runGate(w.worktree, checks, this.#exec, this.#checkTimeout(job), this.#dir(job, task))).filter((r) => !r.passed)
719
- if (failed.length) step = { ok: false, conflict: `checks fail on top of the newer commits (in ${this.#dir(job, task)}): ${failed.map((f) => f.command).join(", ")}` }
720
- }
721
- if (step.ok) step = await fastForward(job.integrationWorktree!, w.branch, this.#exec)
722
- if (step.ok) {
723
- moveTask(task, "merged")
724
- stage(task, "merge", "pass", `merged into ${job.integrationBranch}`)
725
- this.#say(`${task.id} merged into ${job.integrationBranch}`, true)
726
- await this.#dropWorktree(task)
727
- await this.#ended(job, task)
728
- return
729
- }
730
- task.conflicts = (task.conflicts ?? 0) + 1
731
- stage(task, "merge", "fail", step.conflict)
732
- await this.#dropWorktree(task)
733
- if (task.conflicts === 1) {
734
- moveTask(task, "pending")
735
- job.lessons.push(`${task.id} did not merge (${step.conflict}); it starts again from the newest commit`)
736
- this.#say(`${task.id}: ${step.conflict}; it starts again from the newest commit`)
737
- return
738
- }
739
- await this.#escalate(job, task, `it did not merge twice: ${step.conflict}`, "", "merge_conflict")
740
- }
741
-
742
- // omo-hybrid: the orchestrator's delegation goes into the job this runner works on, so the run loop sees it at its
743
- // next turn; undefined when this runner does not work on that job (the caller then writes the job file).
744
- addTask(jobId: string, d: Delegation): { task?: Task; errors?: string[] } | undefined {
745
- const job = this.#job
746
- if (!job || job.id !== jobId) return undefined
747
- const r = addDelegated(job, d)
748
- if (r.task) saveJob(this.#d.project, job)
749
- return r
750
- }
751
-
752
- // The user's answer for a task of the job this runner works on, applied to the live job so the run loop starts the
753
- // task again; undefined when this runner does not work on that job.
754
- answerTask(jobId: string, taskId: string, text: string, checks: readonly string[] = []): string | undefined | false {
755
- const job = this.#job
756
- if (!job || job.id !== jobId) return false
757
- const err = Runner.answer(job, taskId, text, checks)
758
- if (!err) saveJob(this.#d.project, job)
759
- return err
760
- }
761
-
762
- // A rolling job's task that waits for the user: the answer becomes a decision every later brief carries, and the
763
- // task starts again from the job's newest commit.
764
- // checks: new checks for the task, replacing the ones it was delegated with (live test: a check with a wrong path
765
- // kept a finished reader blocked, and no answer could change it).
766
- static answer(job: Job, taskId: string, text: string, checks: readonly string[] = []): string | undefined {
767
- const task = job.tasks.find((t) => t.id === taskId)
768
- if (!task) return `no task ${taskId}`
769
- if (task.status !== "blocked" && task.status !== "escalated") return `task ${taskId} is ${task.status}; it waits for nobody`
770
- if (checks.length) {
771
- const own = job.acceptance.filter((a) => task.acceptance.includes(a.id) && !job.tasks.some((t) => t.id !== task.id && t.acceptance.includes(a.id)))
772
- if (!own.length) return `task ${taskId} shares its acceptance points with other tasks; its checks cannot change alone`
773
- job.acceptance = job.acceptance.map((a) => (own.some((o) => o.id === a.id) ? { ...a, verify: checks.join(" && ") } : a))
774
- }
775
- job.decisions.push({ id: `U${job.decisions.length + 1}`, text: `${taskId}: ${text}`, origin: "user" })
776
- moveTask(task, "pending")
777
- task.confirmed = true
778
- task.attempts = 0
779
- return undefined
780
- }
781
-
782
- // A run that ended in the middle of a task (the server stopped, a crash) leaves it running with half a change in
783
- // the worktree. Nothing of this process works on it, so it goes back to pending and the worktree back to the last
784
- // commit; the passed tasks are commits and stay.
785
- async #reconcile(job: Job): Promise<void> {
786
- const PATH: Partial<Record<Task["status"], Task["status"][]>> = {
787
- planned: ["running", "escalated", "pending"],
788
- running: ["escalated", "pending"],
789
- gating: ["escalated", "pending"],
790
- reviewing: ["fixing", "escalated", "pending"],
791
- fixing: ["escalated", "pending"],
792
- passed: ["pending"], // passed in its own worktree, but the train had not merged it yet
793
- }
794
- const cut = job.tasks.filter((t) => PATH[t.status])
795
- for (const t of cut) await this.#dropWorktree(t)
796
- if (cut.length === 0) return
797
- for (const t of cut) {
798
- for (const to of PATH[t.status]!) moveTask(t, to)
799
- stage(t, "reconcile", "skip", "the run ended in the middle of this task; it starts again")
800
- }
801
- const dirty = await changedFiles(job.integrationWorktree!, this.#exec)
802
- await revertFiles(job.integrationWorktree!, dirty, this.#exec)
803
- job.lessons.push(`interrupted run: ${cut.map((t) => t.id).join(", ")} started again${dirty.length ? `, unfinished changes undone (${dirty.join(", ")})` : ""}`)
804
- this.#say(`resuming: ${cut.map((t) => t.id).join(", ")} start again`)
805
- }
806
-
807
- // task: the stop concerns one task. In a rolling job that never stops the job: the task waits, and the orchestrator
808
- // hears of it and asks the user.
809
- #stop(job: Job, reason: string, task?: Task): void {
810
- job.lessons.push(reason)
811
- if (job.rolling && task) {
812
- this.#say(`${task.id} waits: ${reason}`)
813
- this.#d.taskEnded?.(job, task)
814
- return
815
- }
816
- // A parallel task may stop a job another task already stopped; the job keeps the phase it returns to.
817
- if (job.phase !== "ask_user" && job.phase !== "paused") moveJob(job, "ask_user")
818
- this.#say(`stopped: ${reason}`)
819
- }
820
-
821
- async #runTask(job: Job, task: Task): Promise<void> {
822
- if (job.budget.workersUsed >= job.budget.workersMax) return this.#stop(job, `worker budget of ${job.budget.workersMax} used up`)
823
- const worktree = this.#worktree(job, task) // git commands run in the worktree root
824
- const dir = this.#dir(job, task) // the worker and its checks work in the project directory
825
- const profile = task.profile ?? (await this.#classify(job, task))
826
- if (profile.injection) {
827
- moveTask(task, "blocked")
828
- task.summary = "the task text looks like an attempt to make the agent ignore its rules"
829
- return this.#stop(job, `${task.id}: ${task.summary}; check the plan before going on`, task)
830
- }
831
- const pipeline = choosePipeline(task, profile, this.#policies(job, task.id))
832
- task.pipeline = pipeline.id
833
- const askFirst = pipeline.modifiers.includes("user_confirm") || resolvePolicy("N5", this.#policies(job, task.id)).policy.kind === "ask"
834
- if (askFirst && task.confirmed !== true) {
835
- task.confirmed = false
836
- if (job.rolling) {
837
- moveTask(task, "blocked")
838
- task.summary = `waits for the user's go: ${profileText(profile)}`
839
- }
840
- return this.#stop(job, `confirm ${task.id} before it runs: ${profileText(profile)} · pipeline ${pipeline.id} (${pipeline.reason}). Run the job again to go on, or pin a change first ("${task.id} use <model>", "pipeline P2").`, task)
841
- }
842
- moveTask(task, "planned")
843
- let model = await this.#model(job, task.role, profile.difficulty, task.id, undefined, profile.vision)
844
- task.model = model.id
845
- moveTask(task, "running")
846
- job.budget.workersUsed++
847
- this.#say(`${task.id} ${task.title}: ${task.role} on ${model.id} (${model.reason}), ${pipeline.id} (${pipeline.reason})`)
848
- if (pipeline.id === "P9") return this.#research(job, task, model.id)
849
- const checks = [...new Set(taskAcceptance(job, task).map((a) => a.verify).filter((v): v is string => Boolean(v)))]
850
- let frozen = new Map<string, string>()
851
- if (pipeline.id === "P3") {
852
- const red = await this.#red(job, task, checks)
853
- if (!red) return
854
- frozen = red
855
- }
856
- const s = await this.#workerSession(job, task, model.id)
857
- const first = [brief(job, task, model.id, dir, this.#skills("implement", task)), frozen.size ? greenNote([...frozen.keys()]) : ""].filter(Boolean).join("\n\n")
858
- let work: Work | undefined = { s, model, answer: await this.#ask(s.id, first), fresh: false }
859
- work = await this.#untilGreen(job, task, work, checks, frozen)
860
- if (!work) return
861
- const review = (pipeline.id === "P2" || pipeline.id === "P3") && resolvePolicy("N6.review", this.#policies(job, task.id)).policy.kind !== "fixed"
862
- let lastIssues = ""
863
- for (let round = 1; review; round++) {
864
- moveTask(task, "reviewing")
865
- const r = await this.#review(job, task, work.model.id)
866
- stage(task, "review", r.blocking.length ? "fail" : "pass", r.error ?? (r.blocking.length ? r.blocking.map((c) => `${c.point}: ${c.evidence}`).join("; ").slice(0, 500) : `verdict ${r.verdict ?? "none"}, nothing blocking`))
867
- if (r.blocking.length === 0) break
868
- // N8 signature: the same unmet points as the last round mean this session is not getting there.
869
- const issues = r.blocking.map((c) => c.point).sort().join(",")
870
- const repeated = issues === lastIssues
871
- lastIssues = issues
872
- if (round >= REVIEW_ROUNDS || repeated) {
873
- const why = repeated ? `the review found the same unmet points twice: ${issues}` : `the review still finds unmet points after ${REVIEW_ROUNDS} rounds: ${issues}`
874
- work = await this.#nextRung(job, task, work, frozen, why, r.blocking.map((c) => `- ${c.point}: ${c.evidence}`).join("\n"), "conflicting_review")
875
- if (!work) return
876
- round = 0
877
- lastIssues = ""
878
- } else {
879
- moveTask(task, "fixing")
880
- moveTask(task, "running")
881
- this.#say(`${task.id}: the review found ${r.blocking.length} unmet point(s), round ${round + 1}`)
882
- work.answer = await this.#ask(work.s.id, [reviewFixPrompt(r), skillLine(this.#skills("review_fix", task))].filter(Boolean).join("\n\n"))
883
- }
884
- work = await this.#untilGreen(job, task, work, checks, frozen)
885
- if (!work) return
886
- }
887
- moveTask(task, "passed")
888
- task.summary = work.answer.text.slice(-500)
889
- const outside = (await changedFiles(worktree, this.#exec)).filter((f) => task.files.length > 0 && !task.files.includes(f) && !frozen.has(f))
890
- const commit = await commitTask(worktree, `${task.id}: ${task.title}`, `Job: ${job.id}\nWorker: ${work.model.id} (${task.role}), pipeline ${pipeline.id}${outside.length ? `\nOutside the declared files: ${outside.join(", ")}` : ""}`, this.#exec)
891
- job.counters.stalls = Math.max(0, job.counters.stalls - 1)
892
- if (task.worktree) return this.#say(`${task.id} passed${commit ? ` (${commit})` : ", nothing to commit"}; waiting for the merge train`)
893
- moveTask(task, "merged")
894
- this.#say(`${task.id} passed${commit ? ` (${commit})` : ", nothing to commit"}`, true)
895
- await this.#ended(job, task)
896
- }
897
-
898
- // A merged task: in a rolling job the orchestrator gets its report and decides on its follow-ups; in a planned job
899
- // N7 does (design.md §8).
900
- async #ended(job: Job, task: Task): Promise<void> {
901
- await this.#learn(job, task)
902
- if (job.rolling) this.#d.taskEnded?.(job, task)
903
- else await this.#discover(job, task)
904
- }
905
-
906
- // N15: a merged task's LEARNED lines go into the project memory when Jev calls them lasting and not yet known.
907
- // Without an answer nothing is kept: a wrong fact in the memory misleads every later task.
908
- async #learn(job: Job, task: Task): Promise<void> {
909
- const items = (task.learned ?? []).slice(0, 5)
910
- if (items.length === 0) return
911
- const memory = readMemory(this.#d.project)
912
- const asked = await this.#decider.ask("N15", { project: this.#d.project.split("/").pop(), memory: memory.slice(-40), learned: items }, learnQuestions(items), { localOnly: job.flags?.localOnly, job: job.id, task: task.id })
913
- const a = asked.decision.answers
914
- const p = (q: string) => (a[q]?.type === "noul" ? (a[q] as { noul: number }).noul : undefined)
915
- const keep = items.filter((_, i) => (p(`lasting.${i}`) ?? 0) >= NOUL_FLOOR && (p(`useful.${i}`) ?? 0) >= NOUL_FLOOR && (p(`known.${i}`) ?? 1) < NOUL_FLOOR)
916
- this.#journal({ kind: "memory", job: job.id, task: task.id, offered: items, kept: keep, decision: asked.id })
917
- task.learned = []
918
- if (keep.length === 0) return
919
- excludeFromGit(this.#d.project)
920
- writeMemory(this.#d.project, [...memory, ...keep.map((k) => k.slice(0, 300))])
921
- this.#say(`${task.id}: remembered for this project: ${keep.join("; ")}`)
922
- }
923
-
924
- // N7: what the worker found outside its task. Needed or in scope: a new task after this one, with the priority the
925
- // model gave. The user's call, out of scope, or over the cap: the job's "later" list, shown at the end. Without a
926
- // decision model a follow-up is in scope when every file it names is already in the plan.
927
- async #discover(job: Job, task: Task): Promise<void> {
928
- const items = task.followUps ?? []
929
- if (items.length === 0) return
930
- const policy = resolvePolicy("N7", this.#policies(job, task.id)).policy
931
- const live = job.tasks.filter((t) => t.id !== task.id && t.status !== "cancelled")
932
- const ctx: N7Context = {
933
- goal: job.goal,
934
- acceptance: job.acceptance.map((a) => a.text),
935
- task: `${task.id} ${task.title}`,
936
- otherTasks: live.map((t) => `${t.id} ${t.title} (files: ${t.files.join(", ") || "none"})`),
937
- openFiles: new Set(live.filter((t) => !isDone(t)).flatMap((t) => t.files)),
938
- doneFiles: new Set(job.tasks.filter((t) => isDone(t) || t.id === task.id).flatMap((t) => t.files)),
939
- }
940
- const asked = policy.kind === "rule" || policy.kind === "fixed" ? undefined
941
- : await this.#decider.ask("N7", n7State(ctx, items), n7Questions(items), { localOnly: job.flags?.localOnly, job: job.id, task: task.id })
942
- // "N7": "fixed:yes" takes every follow-up as a task, "fixed:no" none.
943
- const verdicts: Verdict[] = policy.kind === "fixed"
944
- ? items.map((f) => (policy.value === "no" ? { kind: "later", reason: "out_of_scope" } : f.files.length ? { kind: "task", priority: 3 } : { kind: "later", reason: "no_files" }))
945
- : triage(asked?.decision.answers ?? {}, items, ctx)
946
- for (const [i, item] of items.entries()) {
947
- const v = verdicts[i]!
948
- if (v.kind === "planned") {
949
- this.#journal({ kind: "discovered", job: job.id, from: task.id, what: item.what, dropped: "already planned", decision: asked?.id })
950
- continue
951
- }
952
- let reason: Later["reason"] | undefined = v.kind === "later" ? v.reason : undefined
953
- // A follow-up is text a model wrote, so it passes the local guards like a goal before it can become a task.
954
- if (v.kind === "task") {
955
- const guard = await checkGuards(this.#decider, `${item.what}. ${item.why}`, job.id, task.id)
956
- if (guard.flagged.includes("sensitive") && !job.flags?.localOnly && !this.#d.cloudOnly) {
957
- job.flags = { ...job.flags, localOnly: true }
958
- this.#say(`a follow-up of ${task.id} looks sensitive: the rest of the job stays on this machine`)
959
- }
960
- if (guard.flagged.some((g) => g === "injection" || g === "harmful")) reason = "flagged"
961
- else if (job.tasks.filter((t) => t.origin === "discovered").length >= discoveredCap(job)) reason = "cap"
962
- }
963
- if (v.kind === "task" && !reason) {
964
- const added = addDiscovered(job, task, item, v.priority)
965
- if (added.task) {
966
- this.#journal({ kind: "discovered", job: job.id, task: added.task.id, from: task.id, what: item.what, priority: v.priority, decision: asked?.id })
967
- this.#say(`${added.task.id} added (found by ${task.id}, priority ${v.priority}): ${item.what}`, true)
968
- continue
969
- }
970
- job.lessons.push(`follow-up of ${task.id} not added: ${added.errors!.slice(0, 2).join("; ")}`)
971
- reason = "invalid"
972
- }
973
- job.later = [...(job.later ?? []), { ...item, from: task.id, reason: reason! }]
974
- }
975
- task.followUps = []
976
- saveJob(this.#d.project, job)
977
- }
978
-
979
- // The job is stalled: the planner rewrites the unfinished part; done tasks and their commits stay.
980
- async #replan(job: Job): Promise<void> {
981
- moveJob(job, "replan")
982
- job.counters.replans++
983
- const model = await this.#model(job, "plan", 0.7)
984
- this.#say(`replanning (${job.counters.replans} of ${job.budget.replansMax}) with ${model.id}`)
985
- const s = await this.#plannerSession(job, model.id)
986
- let answer = await this.#ask(s.id, `${HEADER} replanning job ${job.id}\n\nThe user's job: ${job.goal}\n\n${replanFormat(job)}`)
987
- let r: Parsed = answer.stopped || answer.timedOut ? { errors: ["the planner stopped"] } : applyReplan(job, answer.text)
988
- if (r.errors && !answer.stopped && !answer.timedOut) {
989
- answer = await this.#ask(s.id, `${HEADER} The plan has these problems:\n- ${r.errors.join("\n- ")}\n\nAnswer again with the corrected JSON only.`)
990
- r = answer.stopped || answer.timedOut ? { errors: ["the planner stopped"] } : applyReplan(job, answer.text)
991
- }
992
- if (r.errors) {
993
- moveJob(job, "execute")
994
- return this.#stop(job, `the replan failed: ${r.errors.slice(0, 3).join("; ")}`)
995
- }
996
- const cut = job.tasks.filter((t) => !isDone(t) && t.status !== "cancelled")
997
- for (const t of cut) moveTask(t, "cancelled")
998
- const w = waves([...job.tasks.filter(isDone).map((t) => ({ ...t, dependsOn: t.dependsOn })), ...r.plan.tasks])
999
- job.acceptance = [...r.plan.acceptance]
1000
- for (const t of r.plan.tasks) {
1001
- job.tasks.push({
1002
- id: t.id, title: t.title, description: t.description, role: t.role, acceptance: [...t.acceptance], dependsOn: [...t.dependsOn],
1003
- files: [...t.files], wave: w.get(t.id) ?? 0, status: "pending", attempts: 0, stages: [], signatures: [],
1004
- priority: t.priority ?? 3, origin: "replan",
1005
- })
1006
- }
1007
- job.counters.stalls = 0
1008
- job.lessons.push(`replanned: ${cut.map((t) => t.id).join(", ")} replaced by ${r.plan.tasks.map((t) => t.id).join(", ")}`)
1009
- this.#journal({ kind: "replan", job: job.id, cancelled: cut.map((t) => t.id), added: r.plan.tasks.map((t) => t.id) })
1010
- this.#say(`replanned: ${cut.map((t) => t.id).join(", ")} -> ${r.plan.tasks.map((t) => t.id).join(", ")}`)
1011
- moveJob(job, "execute")
1012
- }
1013
-
1014
- // N5 + N5b: one request classifies the task and sets its profile; the role may change to one that can do it.
1015
- async #classify(job: Job, task: Task): Promise<Profile> {
1016
- const policies = this.#policies(job, task.id)
1017
- const acceptance = taskAcceptance(job, task)
1018
- const skip = resolvePolicy("N5", policies).policy.kind === "rule"
1019
- const memory = readMemory(this.#d.project)
1020
- const asked = skip ? undefined : await this.#decider.ask("N5", { ...classifyState(job.goal, task, acceptance), ...(memory.length ? { projectMemory: memory.slice(-RECALL_MAX) } : {}) }, classifyQuestions(task, this.#d.skills ?? [], memory), { localOnly: job.flags?.localOnly, job: job.id, task: task.id })
1021
- const profile = combine(task, acceptance, asked, policies, this.#d.skills ?? [], memory)
1022
- if (profile.role !== task.role) this.#say(`${task.id}: role ${task.role} -> ${profile.role} (${profile.roleReason})`)
1023
- task.role = profile.role
1024
- task.profile = profile
1025
- stage(task, "classify", "pass", profileText(profile))
1026
- saveJob(this.#d.project, job)
1027
- return profile
1028
- }
1029
-
1030
- // Worker turns until the task's checks pass: the watchdog's stops, the report, the gate, at most fixRounds fixes,
1031
- // then the N9 ladder. Returns undefined when the task went to the user or was given up (escalated or blocked).
1032
- async #untilGreen(job: Job, task: Task, work: Work, checks: readonly string[], frozen: ReadonlyMap<string, string>): Promise<Work | undefined> {
1033
- const worktree = this.#worktree(job, task) // git work
1034
- const dir = this.#dir(job, task) // the checks name the worker's own paths
1035
- let lastDiff: string | undefined
1036
- let lastFailure: string | undefined
1037
- for (;;) {
1038
- const answer = work.answer
1039
- if (answer.stopped?.kind === "handback") {
1040
- // A checkpoint found the task itself unclear or blocked: no fresh try, the micromanager rethinks it.
1041
- stage(task, "implement", "fail", answer.stopped.detail)
1042
- await this.#escalate(job, task, answer.stopped.detail, "", "spec_ambiguous")
1043
- return undefined
1044
- }
1045
- if (answer.stopped) {
1046
- // The watchdog stopped it: never resume that session.
1047
- stage(task, "implement", "fail", `loop watchdog: ${answer.stopped.detail}`)
1048
- const next = await this.#nextRung(job, task, work, frozen, `stopped by the loop watchdog: ${answer.stopped.detail}`, handoffNote(answer.stopped, await changedFiles(this.#worktree(job, task), this.#exec)))
1049
- if (!next) return undefined
1050
- ;[work, lastDiff, lastFailure] = [next, undefined, undefined]
1051
- continue
1052
- }
1053
- if (!answer.timedOut && refused(answer.text)) {
1054
- // worker_refused: a safety-tuned model said no. Never for a job the gate flagged as possibly harmful; else one
1055
- // fresh session on a local uncensored model (design.md §10.2, §21).
1056
- stage(task, "implement", "fail", `worker_refused: ${answer.text.slice(0, 200)}`)
1057
- this.#journal({ kind: "watchdog", job: job.id, task: task.id, signal: "worker_refused", model: work.model.id })
1058
- const harmful = job.flags?.gate?.flagged.includes("harmful")
1059
- if (harmful || work.uncensored) {
1060
- await this.#escalate(job, task, harmful ? "the model refused, and the gate flagged the job as possibly harmful" : "even a local uncensored model refused", answer.text.slice(-1500), "refused")
1061
- return undefined
1062
- }
1063
- const next = await this.#nextRung(job, task, { ...work, fresh: false }, frozen, "the model refused the task", "", "too_hard", true)
1064
- if (!next) return undefined
1065
- ;[work, lastDiff, lastFailure] = [next, undefined, undefined]
1066
- continue
1067
- }
1068
- const report = parseReport(answer.text)
1069
- collectFollowUps(task, report.followUps)
1070
- for (const l of report.learned) if (!(task.learned ?? []).includes(l)) task.learned = [...(task.learned ?? []), l]
1071
- stage(task, "implement", answer.timedOut ? "fail" : "pass", answer.timedOut ? "timed out" : `status ${report.status ?? "missing"}`)
1072
- if (answer.timedOut) {
1073
- const next = await this.#nextRung(job, task, work, frozen, "the worker timed out", "")
1074
- if (!next) return undefined
1075
- ;[work, lastDiff, lastFailure] = [next, undefined, undefined]
1076
- continue
1077
- }
1078
- if (report.status === "BLOCKED" || report.status === "NEEDS_CONTEXT") {
1079
- moveTask(task, "blocked")
1080
- task.summary = report.open || report.text.slice(-500)
1081
- this.#stop(job, `${task.id} needs the user: ${task.summary}`, task)
1082
- return undefined
1083
- }
1084
- moveTask(task, "gating")
1085
- const results = [...(await runGate(worktree, checks, this.#exec, this.#checkTimeout(job), dir, { cancelled: () => Boolean(this.#d.cancelled?.()) })), ...(await frozenCheck(worktree, frozen, this.#exec))]
1086
- const failed = results.filter((r) => !r.passed)
1087
- const changed = await changedFiles(worktree, this.#exec, task.worktreeRel ?? job.integrationRel ?? "")
1088
- const outside = task.files.length ? changed.filter((f) => !task.files.includes(f) && !frozen.has(f)) : changed
1089
- stage(task, "gate", failed.length ? "fail" : "pass", results.length ? results.map((r) => `${r.command}: exit ${r.code}`).join("; ") : "no checks defined")
1090
- saveNote(this.#d.project, job.id, task.id, noteText(task, report.text, results, outside))
1091
- if (failed.length === 0) {
1092
- // A gate that only reads exits 0 on an untouched tree, so passing it proves nothing: a worker that wrote
1093
- // nothing, or died before writing, would otherwise merge as a success (live test, 2026-10-06). Reported apart
1094
- // from a failing check, because the fix is different -- a passing check set and no diff means the task was
1095
- // never done, not that it is broken.
1096
- if (!changed.length) {
1097
- moveTask(task, "blocked")
1098
- task.summary = "its checks passed but it changed no file, so nothing was verified. Ask the worker what it did, or give the task checks that can fail on an unchanged tree."
1099
- this.#stop(job, `${task.id} finished without changing anything: ${task.summary}`, task)
1100
- return undefined
1101
- }
1102
- return work
1103
- }
1104
- // N8: the same diff as the last round (the worker changed nothing) is a loop; the same failure is one when the
1105
- // decision model says so, or without one. A loop skips the remaining fix rounds.
1106
- const diff = createHash("sha1").update(await workingDiff(worktree, this.#exec)).digest("hex").slice(0, 12)
1107
- // The directory the checks ran in travels with the failure: a check naming a file of the project says "No such
1108
- // file or directory" without it, and the worker has no way to tell which tree it was run against.
1109
- const failure = failed.map((f) => `$ ${f.command} (exit ${f.code}) [in ${dir}]\n${f.output.slice(-1500)}`).join("\n\n")
1110
- const loop = diff === lastDiff || (failure === lastFailure && (await this.#inLoop(job, task, lastFailure, failure)))
1111
- task.signatures.push(`diff:${diff}`)
1112
- ;[lastDiff, lastFailure] = [diff, failure]
1113
- task.attempts++
1114
- if (loop || task.attempts > (this.#d.fixRounds ?? FIX_ROUNDS)) {
1115
- const why = loop ? `it kept failing the same way: ${failed.map((f) => f.command).join(", ")}` : `checks still fail after ${task.attempts - 1} fix round(s): ${failed.map((f) => f.command).join(", ")}`
1116
- const next = await this.#nextRung(job, task, work, frozen, why, failure)
1117
- if (!next) return undefined
1118
- ;[work, lastDiff, lastFailure] = [next, undefined, undefined]
1119
- continue
1120
- }
1121
- moveTask(task, "fixing")
1122
- this.#say(`${task.id}: ${failed.length} check(s) failed, fix round ${task.attempts}`)
1123
- moveTask(task, "running")
1124
- // fixPrompt is brief.ts's, and it takes the failures as they are; the directory goes in as part of the output.
1125
- work.answer = await this.#ask(work.s.id, fixPrompt(failed.map((f) => ({ ...f, output: `checked in ${dir}\n${f.output}` }))))
1126
- }
1127
- }
1128
-
1129
- // N8 with the decision model: is a failure that came back unchanged a loop? Without an answer, yes.
1130
- async #inLoop(job: Job, task: Task, before: string, now: string): Promise<boolean> {
1131
- const asked = await this.#decider.ask("N8", { task: `${task.id} ${task.title}`, previous: before.slice(-1500), now: now.slice(-1500) }, PROGRESS, { localOnly: job.flags?.localOnly, job: job.id, task: task.id })
1132
- const a = asked.decision.answers.in_loop
1133
- return a?.type === "noul" ? a.noul >= NOUL_FLOOR : true
1134
- }
1135
-
1136
- // N9 (design.md §10.2): rung 1 is the fix rounds in the same session; rung 2 a fresh session on another model family
1137
- // with a handoff note; rung 3 the escalation. A budget that is used up skips rung 2.
1138
- async #nextRung(job: Job, task: Task, work: Work, frozen: ReadonlyMap<string, string>, reason: string, details: string, hint: EscalationKind = "too_hard", uncensored = work.uncensored ?? false): Promise<Work | undefined> {
1139
- const over = this.#overBudget(job)
1140
- if (work.fresh || over) {
1141
- await this.#escalate(job, task, over ?? reason, details, over ? "budget" : hint)
1142
- return undefined
1143
- }
1144
- const model = await this.#model(job, task.role, task.profile?.difficulty ?? 0.5, task.id, [this.#family(work.model.id)], task.profile?.vision, uncensored)
1145
- if (uncensored && !model.routed) {
1146
- await this.#escalate(job, task, `${reason}, and no local uncensored model is available`, details, "refused")
1147
- return undefined
1148
- }
1149
- task.model = model.id
1150
- toRunning(task)
1151
- task.attempts = 0
1152
- stage(task, "escalate", "skip", `rung 2: fresh session on ${model.id} after: ${reason}`)
1153
- this.#say(`${task.id}: ${reason}; fresh session on ${model.id}`)
1154
- const s = await this.#workerSession(job, task, model.id)
1155
- const text = [
1156
- brief(job, task, model.id, this.#dir(job, task), this.#skills("implement", task)),
1157
- frozen.size ? greenNote([...frozen.keys()]) : "",
1158
- handoffText(reason, details, await changedFiles(this.#worktree(job, task), this.#exec)),
1159
- ].filter(Boolean).join("\n\n")
1160
- return { s, model, answer: await this.#ask(s.id, text), fresh: true, uncensored }
1161
- }
1162
-
1163
- // P3's red stage: a test worker writes the tests first, and they must fail before anything is built. Returns the
1164
- // frozen test files with their hashes (empty: no red could be shown, the task goes on as P2), or undefined when
1165
- // the task went to the user.
1166
- async #red(job: Job, task: Task, checks: readonly string[]): Promise<Map<string, string> | undefined> {
1167
- const worktree = this.#worktree(job, task)
1168
- const dir = this.#dir(job, task)
1169
- const model = await this.#model(job, "test", task.profile?.difficulty ?? 0.5, task.id)
1170
- const s = await this.#workerSession(job, task, model.id, "test")
1171
- const testFiles = task.files.filter((f) => TEST_FILE.test(f))
1172
- const answer = await this.#ask(s.id, `${brief(job, task, model.id, dir, this.#skills("red", task))}\n\n${redPrompt(task, testFiles)}`)
1173
- if (answer.stopped || answer.timedOut) {
1174
- stage(task, "red", "fail", answer.stopped ? `loop watchdog: ${answer.stopped.detail}` : "timed out")
1175
- await this.#escalate(job, task, `the tests-first worker ${answer.stopped ? "was stopped by the loop watchdog" : "timed out"}`)
1176
- return undefined
1177
- }
1178
- const changed = await changedFiles(worktree, this.#exec)
1179
- const tests = changed.filter((f) => TEST_FILE.test(f) && (testFiles.length === 0 || testFiles.includes(f)))
1180
- const other = changed.filter((f) => !tests.includes(f))
1181
- // Only tests in this stage: anything else the worker wrote is undone, the implementation comes after red.
1182
- await revertFiles(worktree, other, this.#exec)
1183
- if (tests.length === 0 || checks.length === 0) {
1184
- stage(task, "red", "skip", tests.length === 0 ? "no tests written" : "no checks to show red with")
1185
- this.#say(`${task.id}: no red stage (${tests.length === 0 ? "no tests written" : "no checks"}), going on as P2`)
1186
- return new Map()
1187
- }
1188
- const results = await runGate(worktree, checks, this.#exec, this.#checkTimeout(job), dir)
1189
- if (results.every((r) => r.passed)) {
1190
- stage(task, "red", "skip", "the new tests pass before the change, so they do not show the missing behaviour")
1191
- this.#say(`${task.id}: the tests pass before the change; not frozen, going on as P2`)
1192
- return new Map()
1193
- }
1194
- stage(task, "red", "pass", `${tests.join(", ")} fail before the change: ${results.filter((r) => !r.passed).map((r) => r.command).join(", ")}`)
1195
- return hashFiles(worktree, tests, this.#exec)
1196
- }
1197
-
1198
- // Two reviewers of other model families read the change in parallel (P2, P3; design.md §9): one against the
1199
- // acceptance points, one against the repository's standards. Only findings with evidence and confidence block; what
1200
- // they saw outside the task becomes a follow-up. A reviewer whose answer is not JSON after one reminder blocks
1201
- // nothing.
1202
- async #review(job: Job, task: Task, workerModel: string): Promise<Review> {
1203
- const diff = await workingDiff(this.#worktree(job, task), this.#exec)
1204
- const worker = this.#family(workerModel)
1205
- const specModel = await this.#model(job, "review", task.profile?.difficulty ?? 0.5, task.id, [worker], task.profile?.vision)
1206
- const standardsModel = await this.#model(job, "review", task.profile?.difficulty ?? 0.5, task.id, [worker, this.#family(specModel.id)], task.profile?.vision)
1207
- const skills = skillLine(this.#skills("review", task))
1208
- const one = async (axis: ReviewAxis, first: string, prompt: string): Promise<Review> => {
1209
- let model = first
1210
- let s = await this.#workerSession(job, task, model, "review", TIER_STEPS.S)
1211
- let answer = await this.#ask(s.id, [prompt, skills].filter(Boolean).join("\n\n"))
1212
- if (answer.stopped?.kind === "stalled") {
1213
- // The model stopped answering: once more on another family, so a hanging provider does not skip the review.
1214
- model = (await this.#model(job, "review", task.profile?.difficulty ?? 0.5, task.id, [worker, this.#family(model)], task.profile?.vision)).id
1215
- this.#say(`${task.id}: the ${axis} reviewer stalled; again on ${model}`)
1216
- s = await this.#workerSession(job, task, model, "review", TIER_STEPS.S)
1217
- answer = await this.#ask(s.id, [prompt, skills].filter(Boolean).join("\n\n"))
1218
- }
1219
- const confidence = axis === "spec" ? 100 : 0
1220
- let review: Review = answer.stopped || answer.timedOut ? { checks: [], fixes: [], blocking: [], outside: [], error: answer.stopped ? `${axis} reviewer stopped: ${answer.stopped.detail}` : `${axis} reviewer timed out` } : parseReview(answer.text, confidence)
1221
- if (review.error && !answer.stopped && !answer.timedOut) {
1222
- answer = await this.#ask(s.id, `${HEADER} Answer again with the JSON only.`)
1223
- review = parseReview(answer.text, confidence)
1224
- }
1225
- saveNote(this.#d.project, job.id, `${task.id}.review-${axis}`, `# ${axis} review of ${task.id} by ${model}\n\n${answer.text}\n`)
1226
- return review
1227
- }
1228
- const spec = () => one("spec", specModel.id, reviewPrompt(job, task, taskAcceptance(job, task), diff))
1229
- const standards = () => one("standards", standardsModel.id, standardsPrompt(job, task, diff))
1230
- // omo-hybrid: the standards axis only for data or security risk, or when the config asks for it.
1231
- const both = riskAtLeast(task.profile?.risk ?? "internal", "data_security") || resolvePolicy("N6.standards", this.#policies(job, task.id)).level !== undefined
1232
- const none: Review = { checks: [], fixes: [], blocking: [], outside: [] }
1233
- // A local device serves one model at a time, so local reviewers take turns (like P9 readers).
1234
- const local = [specModel, standardsModel].every((m) => this.#d.registry.find((e) => e.id === m.id)?.location === "local")
1235
- const [a, b] = !both ? [await spec(), none] : local ? [await spec(), await standards()] : await Promise.all([spec(), standards()])
1236
- const merged = mergeReviews(a, b)
1237
- collectFollowUps(task, merged.outside)
1238
- const advisory = merged.checks.filter((c) => !c.met && !merged.blocking.includes(c))
1239
- if (advisory.length) stage(task, "review_notes", "skip", advisory.map((c) => `${c.point} (${c.confidence}): ${c.evidence}`).join("; ").slice(0, 500))
1240
- return merged
1241
- }
1242
-
1243
- // P9: parallel readers, one synthesis written to docs/research/, and a citation check by code.
1244
- async #research(job: Job, task: Task, model: string): Promise<void> {
1245
- const worktree = this.#worktree(job, task)
1246
- const dir = this.#dir(job, task)
1247
- const n = readerCount(task.profile?.difficulty ?? 0.5)
1248
- const read = async (i: number) => {
1249
- const s = await this.#workerSession(job, task, model, "research")
1250
- return this.#ask(s.id, [readerPrompt(job, task, i, n), skillLine(this.#skills("reader", task))].filter(Boolean).join("\n\n"))
1251
- }
1252
- // Readers run in parallel in the cloud; a local device serves one model at a time, so there they take turns.
1253
- const local = this.#d.registry.find((m) => m.id === model)?.location === "local"
1254
- const readers: Awaited<ReturnType<typeof read>>[] = []
1255
- if (local) for (let i = 0; i < n; i++) readers.push(await read(i))
1256
- else readers.push(...(await Promise.all(Array.from({ length: n }, (_, i) => read(i)))))
1257
- const answered = readers.filter((r) => !r.stopped && !r.timedOut && r.text).map((r) => r.text)
1258
- readers.forEach((r, i) => saveNote(this.#d.project, job.id, `${task.id}.reader${i + 1}`, r.text || "(no answer)"))
1259
- // Readers quote the web; a note that carries an injection never reaches the synthesis (E2b).
1260
- const notes: string[] = []
1261
- for (const note of answered) {
1262
- const score = await injectionScore(this.#decider, note, job.id, task.id)
1263
- if (!injected(score)) notes.push(note)
1264
- else {
1265
- this.#journal({ kind: "guard", job: job.id, task: task.id, guard: "injection", score, action: "reader note dropped" })
1266
- job.lessons.push(`${task.id}: a research note was dropped, it looked like a prompt injection (${score!.toFixed(2)})`)
1267
- }
1268
- }
1269
- stage(task, "readers", notes.length ? "pass" : "fail", `${notes.length} of ${n} readers answered`)
1270
- if (notes.length === 0) return await this.#escalate(job, task, "no research reader came back with findings")
1271
- const path = researchPath(task)
1272
- const writerModel = await this.#model(job, "write", task.profile?.difficulty ?? 0.5, task.id)
1273
- const s = await this.#workerSession(job, task, writerModel.id, "write")
1274
- let answer = await this.#ask(s.id, synthesisPrompt(job, task, path, notes))
1275
- for (let round = 0; ; round++) {
1276
- if (answer.stopped || answer.timedOut) return await this.#escalate(job, task, `the synthesis ${answer.stopped ? "was stopped by the loop watchdog" : "timed out"}`)
1277
- let doc = ""
1278
- try {
1279
- doc = readFileSync(join(dir, path), "utf8") // the writer worked in the project directory, so the doc is there
1280
- } catch {
1281
- // checked below: no file means no citations
1282
- }
1283
- const check = citationCheck(doc, notes)
1284
- stage(task, "citations", check.ok ? "pass" : "fail", doc ? `${check.cited} cited${check.unknown.length ? `, not from a reader: ${check.unknown.join(" ")}` : ""}` : `${path} was not written`)
1285
- if (check.ok) break
1286
- if (round >= 1) return await this.#escalate(job, task, `the research synthesis fails the citation check: ${doc ? (check.unknown.length ? `${check.unknown.length} URL(s) not from a reader` : "no citations") : `${path} missing`}`)
1287
- answer = await this.#ask(s.id, `${HEADER} ${doc ? (check.unknown.length ? `These URLs are not in any reader's notes: ${check.unknown.join(" ")}. Remove them or the claims they support.` : "The document cites nothing. Cite every claim with a URL from the readers' notes.") : `Write ${path} as asked.`}`)
1288
- }
1289
- moveTask(task, "gating")
1290
- const checks = [...new Set(taskAcceptance(job, task).map((a) => a.verify).filter((v): v is string => Boolean(v)))]
1291
- const failed = (await runGate(worktree, checks, this.#exec, this.#checkTimeout(job), dir)).filter((r) => !r.passed)
1292
- if (failed.length) return await this.#escalate(job, task, `checks fail after the research (in ${dir}): ${failed.map((f) => f.command).join(", ")}`)
1293
- moveTask(task, "passed")
1294
- task.summary = `research written to ${path}`
1295
- const commit = await commitTask(worktree, `${task.id}: ${task.title}`, `Job: ${job.id}\nResearch: ${n} reader(s) on ${model}, synthesis by ${writerModel.id}, pipeline P9`, this.#exec)
1296
- moveTask(task, "merged")
1297
- this.#say(`${task.id} researched${commit ? ` (${commit})` : ""}: ${path}`, true)
1298
- }
1299
-
1300
- // The git worktree root of a task: its own in a parallel batch, else the job's. Git commands run here; a worktree is
1301
- // always a checkout of the repository root, whatever the project is.
1302
- #worktree(job: Job, task: Task): string {
1303
- return task.worktree ?? job.integrationWorktree!
1304
- }
1305
-
1306
- // Where a task works: the worktree root plus the project's offset inside it, because the worker's paths, its tools and
1307
- // its checks are all relative to the project directory, not to the repository root.
1308
- #dir(job: Job, task: Task): string {
1309
- return taskDir(this.#worktree(job, task), task.worktreeRel ?? job.integrationRel ?? "")
1310
- }
1311
-
1312
- #skills(stage: Stage, task: Task): string[] {
1313
- return skillsFor(stage, task.profile, task.pipeline, this.#d.installedSkills ?? new Set())
1314
- }
1315
-
1316
- // OpenCode 2.0.18's plugin session.create drops parentID, so these sessions are not children of the micromanager in
1317
- // OpenCode's eyes. The metadata names it instead, for the clients that list sessions: oc-voice treats a session with
1318
- // a parent there as a sub-agent and does not announce it as one of the user's own.
1319
- #origin(job: Job, task?: Task): Record<string, unknown> {
1320
- return this.#d.parentID ? { metadata: { micromanager: { parent: this.#d.parentID, job: job.id, ...(task ? { task: task.id } : {}) } } } : {}
1321
- }
1322
-
1323
- async #plannerSession(job: Job, model: string): Promise<{ id: string }> {
1324
- const s = await this.#d.session.create({
1325
- ...(this.#d.parentID ? { parentID: this.#d.parentID } : {}),
1326
- title: `plan ${job.id}`,
1327
- agent: roleById("plan")!.agent,
1328
- model: toModel(model),
1329
- location: { directory: this.#d.project },
1330
- ...this.#origin(job),
1331
- })
1332
- this.#d.watch?.(s.id, 40)
1333
- return s
1334
- }
1335
-
1336
- // A worker session: the task's role unless a stage needs another (red: test, review, research readers), with the
1337
- // profile's narrowed rights as the session's own permission rules (Phase A, A5).
1338
- async #workerSession(job: Job, task: Task, model: string, role = task.role, steps?: number): Promise<{ id: string }> {
1339
- const rules = role === task.role && task.profile ? narrowing(task.profile) : []
1340
- const s = await this.#d.session.create({
1341
- ...(this.#d.parentID ? { parentID: this.#d.parentID } : {}),
1342
- title: `${task.id} · ${roleById(role)?.agent ?? role} · ${task.title}`,
1343
- agent: roleById(role)?.agent ?? "coder",
1344
- model: toModel(model),
1345
- location: { directory: this.#dir(job, task) },
1346
- ...(rules.length ? { permissions: rules } : {}),
1347
- ...this.#origin(job, task),
1348
- })
1349
- task.session = s.id
1350
- task.sessions = [...(task.sessions ?? []), s.id]
1351
- this.#sessionModel.set(s.id, model)
1352
- this.#d.onWorker?.(s.id, `${task.id} ${task.title}: ${task.description}`, rules)
1353
- this.#d.watch?.(s.id, steps ?? MAX_STEPS)
1354
- saveJob(this.#d.project, job)
1355
- return s
1356
- }
1357
-
1358
-
1359
- // N9 rung 3: the task stops, with a typed reason. A task that is too hard as planned does not stop the job: other
1360
- // tasks go on and the job replans around it (stalls, design.md §10.2). Everything else needs the user.
1361
- async #escalate(job: Job, task: Task, reason: string, details = "", hint: EscalationKind = "too_hard"): Promise<void> {
1362
- let kind = hint
1363
- let decision: string | undefined
1364
- // N9 is opt-in ("N9": "auto"): the call site's reason type is good enough by default (omo-hybrid).
1365
- const n9 = resolvePolicy("N9", this.#policies(job, task.id))
1366
- if (hint !== "budget" && hint !== "refused" && n9.level !== undefined && n9.policy.kind === "auto") {
1367
- const asked = await this.#decider.ask(
1368
- "N9",
1369
- { goal: job.goal, task: `${task.id} ${task.title}: ${task.description}`, acceptance: taskAcceptance(job, task).map((a) => a.text), reason, details: details.slice(-2000), stages: task.stages.slice(-6).map((s) => `${s.stage} ${s.result}${s.evidence ? `: ${s.evidence.slice(0, 200)}` : ""}`) },
1370
- { reason: ESCALATE },
1371
- { localOnly: job.flags?.localOnly, job: job.id, task: task.id },
1372
- )
1373
- decision = asked.id
1374
- const c = asked.decision.answers.reason
1375
- if (c?.type === "choice" && c.confidence >= CHOICE_FLOOR && c.choice in ESCALATION) kind = c.choice as EscalationKind
1376
- }
1377
- moveTask(task, "escalated")
1378
- task.escalation = { kind, detail: reason }
1379
- job.counters.stalls++
1380
- this.#journal({ kind: "escalation", job: job.id, task: task.id, reason, type: kind, decision })
1381
- if (kind === "too_hard") {
1382
- job.lessons.push(`${task.id} given up as planned: ${reason}`)
1383
- this.#say(`${task.id} given up as planned (${reason}); the job goes on and replans around it`, true)
1384
- if (job.rolling) this.#d.taskEnded?.(job, task)
1385
- return
1386
- }
1387
- this.#stop(job, `${task.id} (${kind.replace(/_/g, " ")}): ${reason}`, task)
1388
- }
1389
-
1390
- async #verify(job: Job): Promise<void> {
1391
- moveJob(job, "verify")
1392
- const checks = [...new Set(job.acceptance.map((a) => a.verify).filter((v): v is string => Boolean(v)))]
1393
- const results = await runGate(job.integrationWorktree!, checks, this.#exec, this.#checkTimeout(job), taskDir(job.integrationWorktree!, job.integrationRel ?? ""))
1394
- const failed = results.filter((r) => !r.passed)
1395
- if (failed.length > 0) {
1396
- moveJob(job, "execute")
1397
- return this.#stop(job, `the final checks fail: ${failed.map((f) => f.command).join(", ")}`)
1398
- }
1399
- moveJob(job, "integrate") // the user merges, keeps or discards the branch
1400
- this.#say(`all checks pass on ${job.integrationBranch}`)
1401
- }
1402
-
1403
- async sessionUsage(sessionID: string): Promise<{ tokens: number; cost: number }> {
1404
- return usage(await this.#d.session.context({ sessionID }))
1405
- }
1406
- }
1407
-
1408
- export function plannerPrompt(job: Job): string {
1409
- // The planning session's decisions and anything else decided with the user (plan feedback included).
1410
- const decided = [...(job.designTree ? decisionsText(job.designTree) : []), ...job.decisions.map((d) => d.text)]
1411
- return `${HEADER} planning job ${job.id}
1412
-
1413
- The user's job: ${job.goal}
1414
- ${decided.length ? `\nDecided with the user (follow these; for assumed points, decide and say what you chose). Every decision must show up in
1415
- the plan's tasks and acceptance points; a large job gets as many tasks as it needs:\n- ${decided.join("\n- ")}\n` : ""}
1416
- Read as much of the project as you need (read, glob, grep); change nothing.
1417
- Verify commands run from the project root in a fresh checkout of the current commit; use only commands that
1418
- work there, such as the project's own test script.
1419
-
1420
- ${PLAN_FORMAT}`
1421
- }
1422
-
1423
- // Back to running from wherever a task's last stage left it, for a fresh session (N9 rung 2).
1424
- function toRunning(task: Task): void {
1425
- if (task.status === "gating" || task.status === "reviewing") moveTask(task, "fixing")
1426
- if (task.status !== "running") moveTask(task, "running")
1427
- }
1428
-
1429
- // A worker's follow-ups over all its reports in this task, without repeats.
1430
- function collectFollowUps(task: Task, items: readonly FollowUp[]): void {
1431
- if (items.length === 0) return
1432
- const seen = new Set((task.followUps ?? []).map((f) => f.what.toLowerCase()))
1433
- task.followUps = [...(task.followUps ?? []), ...items.filter((f) => !seen.has(f.what.toLowerCase()))]
1434
- }
1435
-
1436
- function noteText(task: Task, report: string, results: readonly { command: string; code: number; output: string }[], outside: readonly string[]): string {
1437
- return [
1438
- `# ${task.id} ${task.title}`,
1439
- "",
1440
- "## Report",
1441
- report || "(none)",
1442
- "",
1443
- "## Checks",
1444
- ...(results.length ? results.map((r) => `$ ${r.command} (exit ${r.code})\n${r.output}`) : ["none defined"]),
1445
- ...(outside.length ? ["", `## Changed outside the declared files`, outside.join(", ")] : []),
1446
- "",
1447
- ].join("\n")
1448
- }
1449
-
1450
- // What the orchestrator learns when a delegated task ends (omo-hybrid): status and why, the worker's report, the
1451
- // checks, and its follow-ups with a hint when another task already covers their files.
1452
- export function taskReport(job: Job, task: Task): string {
1453
- const open = new Set(job.tasks.filter((t) => t.id !== task.id && !isDone(t) && t.status !== "cancelled").flatMap((t) => t.files))
1454
- const gate = [...task.stages].reverse().find((s) => s.stage === "gate")
1455
- const follow = (task.followUps ?? []).map((f) => ` - ${f.what}${f.why ? ` (${f.why})` : ""}${f.files.length ? ` · files: ${f.files.join(", ")}` : ""}${f.files.length && f.files.every((x) => open.has(x)) ? " · another open task has these files" : ""}`)
1456
- const status = task.status === "merged" ? `merged into ${job.integrationBranch}` : task.status === "escalated" ? `given up (${task.escalation?.kind?.replace(/_/g, " ")}): ${task.escalation?.detail}` : task.status === "blocked" ? `waits for the user: ${task.summary}` : task.status
1457
- return [
1458
- `${task.id} ${task.title}: ${status}`,
1459
- task.model ? ` ${task.role} on ${task.model}, ${task.pipeline ?? "P1"}` : "",
1460
- gate ? ` checks: ${gate.evidence}` : "",
1461
- task.status === "merged" && task.summary ? ` report: ${task.summary.replace(/\s+/g, " ").slice(-400)}` : "",
1462
- follow.length ? ` follow-ups the worker found (yours to decide):\n${follow.join("\n")}` : "",
1463
- task.sessions?.length ? ` sessions: ${task.sessions.join(", ")} (open one with: opencode -s <id>)` : "",
1464
- ` notes: notes/${job.id}/${task.id}.md in the project's .micromanager directory`,
1465
- ].filter(Boolean).join("\n")
1466
- }
1467
-
1468
- export function summary(job: Job): string {
1469
- const lines = job.tasks.map((t) => `- ${t.id} ${t.title}: ${t.status}${t.model ? ` (${t.role} on ${t.model}${t.pipeline ? `, ${t.pipeline}` : ""})` : ""}`)
1470
- const head = `job ${job.id}: ${job.phase}${job.resumePhase ? ` (from ${job.resumePhase})` : ""}`
1471
- const branch = job.integrationBranch
1472
- ? `\nbranch ${job.integrationBranch} in ${job.integrationWorktree}\nmerge: git merge ${job.integrationBranch} · discard: git worktree remove --force ${job.integrationWorktree} && git branch -D ${job.integrationBranch}`
1473
- : ""
1474
- const why = job.phase === "ask_user" && job.lessons.length ? `\nwhy: ${job.lessons[job.lessons.length - 1]}` : ""
1475
- const later = job.later?.length ? `\nfound but not done (for the user to decide):\n${job.later.map((l) => `- ${l.what} (from ${l.from}, ${l.reason.replace(/_/g, " ")})`).join("\n")}` : ""
1476
- return `${head}\n${lines.join("\n")}${branch}${why}${later}`
1477
- }
1478
-
1479
- // The instruction to draft the design tree; the format is the one parseTree reads.
1480
- export function draftInstruction(job: Job): string {
1481
- return `[planning session ${job.id}] Before planning, the user's open decisions are settled in a planning session.
1482
- Draft the design questions this job leaves open and send them with plan_questions (job "${job.id}", tree as a
1483
- JSON list): [{ "id": "D1", "question": "...", "kind": "decision" | "fact" | "assumption", "dependsOn": [], "impact":
1484
- "low" | "medium" | "high" }]. Decisions are what only the user can decide (behaviour, scope, interfaces, trade-offs);
1485
- facts are what agents can look up; at most 25. Write every question open: never list possible answers or examples
1486
- of answers in it. Do not ask the user anything in this turn, and do not call plan_job again.`
1487
- }
1488
-
1489
- // The project's top-level entries, as cheap context for triage.
1490
- function topLevel(project: string): string[] {
1491
- try {
1492
- return readdirSync(project).filter((f) => !f.startsWith(".")).slice(0, 40)
1493
- } catch {
1494
- return []
1495
- }
1496
- }
1497
-
1498
- // A goal the same session failed to plan a short while ago: the micromanager reports that instead of starting the
1499
- // same job again (live test: a looping local planner made it restart three times). "retry: <goal>" overrides.
1500
- export function recentFailure(job: Job | undefined, goal: string, now = Date.now(), windowMs = 30 * 60_000): string | undefined {
1501
- if (!job || job.phase !== "failed" || /^retry:/i.test(goal.trim())) return undefined
1502
- const same = job.goal.trim().toLowerCase() === goal.trim().toLowerCase()
1503
- if (!same || now - Date.parse(job.updated) > windowMs) return undefined
1504
- const why = job.lessons.at(-1) ?? "unknown reason"
1505
- return `Job ${job.id} with this goal failed ${Math.round((now - Date.parse(job.updated)) / 60_000)} min ago (${why}). Tell the user and do not start it again by yourself; if the user wants another try, call plan_job with goal "retry: <goal>".`
1506
- }