@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/dist/runner.js ADDED
@@ -0,0 +1,1892 @@
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
+ import { readdirSync, readFileSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ import { buildAgenda, nextProposal } from "./agenda.js";
7
+ import { rulesDecider } from "./backends.js";
8
+ import { isRepoRoot, surveyFolder } from "./nogit.js";
9
+ import { createHash } from "node:crypto";
10
+ import { ANSWER, batchQuestions, CHOICE_FLOOR, complexityOf, ESCALATE, ESCALATION, NOUL_FLOOR, nextQuestionChoice, PROGRESS, splitQuestions, TRIAGE, } from "./catalog.js";
11
+ import { n7Questions, n7State, triage } from "./followups.js";
12
+ import { checkGuards, flagsWithoutUser, gateAnswer, gateQuestion, injected, injectionScore } from "./gate.js";
13
+ import { gateFor, unsandboxedNote } from "./gatebox.js";
14
+ import { brief, fixPrompt, handoffText, lastAssistantText, parseReport, refused, skillLine, taskAcceptance, usage, verbatimGoalLine } from "./brief.js";
15
+ import { abortRebase, changedFiles, commitTask, exec as defaultExec, fastForward, frozenCheck, hashFiles, prepareIntegration, prepareTaskWorktree, rebaseTask, removeTaskWorktree, revertFiles, runGate, taskDir, workingDiff, } from "./integration.js";
16
+ import { checkTimeoutOf } from "./worktree/git.js";
17
+ import { redact } from "./decider.js";
18
+ import { learnQuestions, readMemory, RECALL_MAX, writeMemory } from "./memory.js";
19
+ import { record } from "./journal.js";
20
+ import { HEADER } from "./hooks.js";
21
+ import { choosePipeline, citationCheck, riskAtLeast, greenNote, mergeReviews, readerCount, readerPrompt, redPrompt, researchPath, reviewFixPrompt, reviewPrompt, parseReview, standardsPrompt, synthesisPrompt, TEST_FILE, } from "./pipelines.js";
22
+ import { addDelegated, addDiscovered, applyPlan, applyReplan, applySplits, coalesceCoupledTasks, MAX_SPLIT_LEVEL, parsePlan, PLAN_FORMAT, planModeRoles, replanFormat, splitFormat, waves, } from "./plan.js";
23
+ import { classifyQuestions, classifyState, combine, narrowing, profileText } from "./profile.js";
24
+ import { resolvePolicy } from "./policy.js";
25
+ import { route } from "./registry.js";
26
+ import { family, roleById } from "./roles.js";
27
+ import { chain, DEFAULT_ROUTING } from "./routing.js";
28
+ import { addNodes, applyAnswer, applyShortcut, decisionsText, frontier, instruction, matchSessionShortcut, nextStep, parseTree, settle, } from "./session.js";
29
+ import { discoveredCap, isDone, parallelSafe, moveJob, moveTask, newJob, promoteReady, stage } from "./state.js";
30
+ import { skillsFor } from "./skills.js";
31
+ import { excludeFromGit, jobId, loadJob, saveJob, saveNote } from "./store.js";
32
+ import { loadControl, updateControl } from "@omacode/state/control";
33
+ import { FIX_ROUNDS, handoffNote, MAX_STEPS, TIER_STEPS } from "./watchdog.js";
34
+ import { overBudget } from "./budget.js";
35
+ // Thrown out of a session turn when the user stopped the job; run() pauses the job, and the next run resumes it.
36
+ export class Cancelled extends Error {
37
+ }
38
+ const REVIEW_ROUNDS = 3;
39
+ export function toModel(id) {
40
+ const i = id.indexOf("/");
41
+ return { providerID: id.slice(0, i), id: id.slice(i + 1) };
42
+ }
43
+ export class Runner {
44
+ #d;
45
+ #exec;
46
+ #journal;
47
+ #decider;
48
+ #job; // the job this runner works on; its counters take every session's usage
49
+ #seen = new Map(); // usage per session so far
50
+ #tokenCaps = new Map(); // N5's budget tier per worker session
51
+ #sessionModel = new Map(); // for the per-model limit
52
+ #slots = new Map();
53
+ #train = Promise.resolve(); // the merge train: one task's branch at a time
54
+ constructor(deps) {
55
+ this.#d = deps;
56
+ this.#exec = deps.exec ?? defaultExec;
57
+ this.#journal = deps.journal ?? record;
58
+ this.#decider = deps.decider ?? rulesDecider(this.#journal);
59
+ }
60
+ #policies(job, task) {
61
+ return { ...(this.#d.policies ?? {}), job: job.pins, ...(task && job.taskPins?.[task] ? { task: job.taskPins[task] } : {}) };
62
+ }
63
+ // 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.
64
+ #checkTimeout(job) {
65
+ return checkTimeoutOf(job, this.#d.checkTimeoutMs);
66
+ }
67
+ // The sandbox a check runs in (src/gatebox.ts, A1-T12): its own task's worktree, the job's grants, and its role
68
+ // where a task is known (this runner predates plan jobs).
69
+ #gate(job, task, worktree, dir) {
70
+ const deps = this.#d.gate;
71
+ return deps
72
+ ? gateFor(deps, { project: this.#d.project, jobId: job.id, plan: job.isolation === "plan", writer: true, role: task?.role || "code", worktree, dir })
73
+ : Promise.resolve(undefined);
74
+ }
75
+ // A model's family as the registry knows it ("qwen" for qwen3.8-flash and qwen3.8-u alike), so "another family"
76
+ // means what routing compares.
77
+ #family(id) {
78
+ return this.#d.registry.find((m) => m.id === id)?.family ?? family(id);
79
+ }
80
+ #say(text, task = false) {
81
+ this.#d.progress?.(text, task);
82
+ }
83
+ // The role's pool: the user's picks if the role has any, else the role matrix in src/roles.ts.
84
+ #pool(role) {
85
+ const def = roleById(role);
86
+ return def ? chain(def, this.#d.routing?.() ?? DEFAULT_ROUTING) : [];
87
+ }
88
+ // The model for a role: the user's preset if any, else the best model of the role's pool. The pool is
89
+ // authoritative: no model outside it is ever returned, and when none fits `routed` is false (the caller decides
90
+ // whether that stops the job). uncensored: this task needs a local uncensored model (a worker refused it).
91
+ async #model(job, role, difficulty, task, avoidFamilies, vision = false, uncensored = false) {
92
+ const preset = resolvePolicy("N5.model", this.#policies(job, task));
93
+ const presetModel = preset.policy.kind === "fixed" ? this.#d.registry.find((m) => m.id === preset.policy.value) : undefined;
94
+ const local = job.flags?.localOnly || uncensored;
95
+ const free = job.flags?.uncensored || uncensored;
96
+ const presetBreaksGate = local && (presetModel?.location === "cloud" || (free && presetModel?.censored !== false));
97
+ if (preset.policy.kind === "fixed" && !presetBreaksGate) {
98
+ this.#journal({ kind: "routing", job: job.id, task, role, model: preset.policy.value, reason: `preset (${preset.level})` });
99
+ return { id: preset.policy.value, reason: `preset (${preset.level})`, routed: true };
100
+ }
101
+ if (presetBreaksGate)
102
+ this.#say(`preset ${preset.policy.value} ignored: the ${uncensored ? "task" : "job"} must stay local${free ? " and uncensored" : ""}`);
103
+ const availability = await this.#d.availability?.().catch(() => undefined);
104
+ const pool = this.#pool(role);
105
+ const r = route(this.#d.registry, { role, difficulty, vision, sensitive: local, uncensored: free, avoidFamilies, ...(pool.length ? { allow: pool } : {}) }, availability);
106
+ if (!r.model) {
107
+ // The user's pool is authoritative: a model the registry does not know (a new provider, a subscription the user
108
+ // added since the registry was written) still runs when the host has it — the registry carries capability
109
+ // metadata, not the right to refuse work (the user, 2026-12-04: "models must be added to the registry" is a bug).
110
+ const fromPool = local || free ? undefined : pool.find((id) => availability?.get(id)?.reachable !== false && !avoidFamilies?.includes(family(id)));
111
+ if (fromPool) {
112
+ const reason = "from the pool (the registry does not know it)";
113
+ this.#journal({ kind: "routing", job: job.id, task, role, model: fromPool, reason, pool: pool.slice(0, 6), ranked: [] });
114
+ return { id: fromPool, reason, routed: true };
115
+ }
116
+ }
117
+ this.#journal({ kind: "routing", job: job.id, task, role, ...(r.model ? { model: r.model } : {}), reason: r.reason, pool: pool.slice(0, 6), ranked: r.ranked.slice(0, 5) });
118
+ return { id: r.model ?? "", reason: r.reason, routed: r.model !== undefined };
119
+ }
120
+ // #model, or stop the job with a message the user can act on (the pool and the constraint that failed). A job
121
+ // must never fall back to a model outside the role's pool.
122
+ async #requiredModel(job, role, difficulty, task, avoidFamilies, vision = false, uncensored = false) {
123
+ const model = await this.#model(job, role, difficulty, task?.id, avoidFamilies, vision, uncensored);
124
+ if (model.routed && model.id)
125
+ return model;
126
+ const text = `no model for the ${role} work: ${model.reason}. Add a model to models.${role} in omacode-models.json, or pin N5.model.`;
127
+ if (task) {
128
+ task.summary = text;
129
+ if (job.rolling)
130
+ moveTask(task, "blocked");
131
+ }
132
+ this.#stop(job, text, task);
133
+ return undefined;
134
+ }
135
+ async #ask(sessionID, text) {
136
+ if (this.#d.cancelled?.())
137
+ throw new Cancelled();
138
+ const model = this.#sessionModel.get(sessionID);
139
+ const release = model ? await this.#acquire(model) : () => { };
140
+ const timeoutMs = this.#d.workerTimeoutMs ?? 20 * 60_000;
141
+ let timer;
142
+ let timedOut;
143
+ let stalled;
144
+ let done = false;
145
+ try {
146
+ // Briefs, handoff notes, check output and review diffs may quote a key; no model needs one (E2b).
147
+ await this.#d.session.prompt({ sessionID, text: redact(text) });
148
+ timedOut = await Promise.race([
149
+ this.#d.session.wait({ sessionID }).then(() => false),
150
+ new Promise((resolve) => { timer = setTimeout(() => resolve(true), timeoutMs); }),
151
+ this.#stall(sessionID, () => done).then((s) => { stalled = s; return s !== undefined; }),
152
+ ]);
153
+ }
154
+ finally {
155
+ done = true;
156
+ clearTimeout(timer); // also when wait() fails, or the timer keeps the process alive for the whole timeout
157
+ release();
158
+ }
159
+ if (timedOut && !stalled)
160
+ await this.#d.session.interrupt({ sessionID }).catch(() => undefined); // a stall interrupted already
161
+ if (this.#d.cancelled?.())
162
+ throw new Cancelled();
163
+ const messages = await this.#d.session.context({ sessionID });
164
+ const used = this.#count(sessionID, messages);
165
+ const cap = this.#tokenCaps.get(sessionID);
166
+ const stopped = stalled ?? this.#d.stopped?.(sessionID) ?? (cap && used.tokens > cap ? { kind: "tokens", detail: `${used.tokens} tokens in one session, over the task's ${cap}` } : undefined);
167
+ return { text: lastAssistantText(messages), timedOut: timedOut && !stalled, stopped };
168
+ }
169
+ // A provider stream that stops mid-answer leaves a session waiting with no hook firing (live test: a reviewer's
170
+ // message started streaming and never completed). The session is looked at every pollMs; when nothing changed for
171
+ // stallMs, it is stalled and treated like a watchdog stop: a fresh session on another family.
172
+ //
173
+ // "Did anything change?" is answered by the message bookkeeping, not by the messages: JSON.stringify over the
174
+ // whole history of a session in the hundreds of thousands of tokens cost megabytes per poll, per active session,
175
+ // to learn nothing. The fingerprint is the number of messages plus the last one's id and updated time, all of it
176
+ // monotonic and O(1) to read.
177
+ async #stall(sessionID, finished) {
178
+ const pollMs = this.#d.pollMs ?? 20_000;
179
+ const stallMs = this.#d.stallMs ?? 4 * 60_000;
180
+ const fingerprint = (messages) => {
181
+ if (!Array.isArray(messages))
182
+ return "";
183
+ const last = messages[messages.length - 1];
184
+ return `${messages.length}:${String(last?.id ?? "")}:${String(last?.time?.updated ?? last?.time?.created ?? "")}`;
185
+ };
186
+ let last = "";
187
+ let since = Date.now();
188
+ while (!finished()) {
189
+ await new Promise((resolve) => { const t = setTimeout(resolve, pollMs); t.unref?.(); });
190
+ if (finished())
191
+ return undefined;
192
+ // A context call that fails counts as no change, as before: an unreadable session is not a moving one.
193
+ const seen = await this.#d.session.context({ sessionID }).catch(() => undefined);
194
+ const now = seen === undefined ? last : fingerprint(seen);
195
+ // A session paused on a permission request waits for an answer, not for a stuck model: it is no stall.
196
+ if (now !== last || this.#d.waiting?.(sessionID))
197
+ [last, since] = [now, Date.now()];
198
+ else if (Date.now() - since >= stallMs) {
199
+ await this.#d.session.interrupt({ sessionID }).catch(() => undefined);
200
+ return { kind: "stalled", detail: `no progress for ${Math.round(stallMs / 1000)} s (the model stopped answering)` };
201
+ }
202
+ }
203
+ return undefined;
204
+ }
205
+ // A turn on a model waits for a free slot: 2 sessions per cloud model, 1 per local one (design.md §11).
206
+ async #acquire(model) {
207
+ const cap = this.#d.registry.find((m) => m.id === model)?.location === "local" ? 1 : (this.#d.perModel ?? 2);
208
+ const slot = this.#slots.get(model) ?? { used: 0, waiting: [] };
209
+ this.#slots.set(model, slot);
210
+ while (slot.used >= cap)
211
+ await new Promise((resolve) => slot.waiting.push(resolve));
212
+ slot.used++;
213
+ return () => {
214
+ slot.used--;
215
+ slot.waiting.shift()?.();
216
+ };
217
+ }
218
+ // A session's usage so far; what is new since the last turn goes to the job's counters.
219
+ #count(sessionID, messages) {
220
+ const now = { ...usage(messages), requests: Array.isArray(messages) ? messages.filter((m) => m.type === "assistant").length : 0 };
221
+ const before = this.#seen.get(sessionID) ?? { tokens: 0, cost: 0, requests: 0 };
222
+ this.#seen.set(sessionID, now);
223
+ const c = this.#job?.counters;
224
+ if (c) {
225
+ c.tokens = (c.tokens ?? 0) + Math.max(0, now.tokens - before.tokens);
226
+ c.cost = (c.cost ?? 0) + Math.max(0, now.cost - before.cost);
227
+ c.requests = (c.requests ?? 0) + Math.max(0, now.requests - before.requests);
228
+ }
229
+ return now;
230
+ }
231
+ // The first budget the job has used up, as a reason; checked before every start (design.md §10.2).
232
+ #overBudget(job) {
233
+ return overBudget(job);
234
+ }
235
+ // Goal -> validated plan, waiting at the plan gate for the user's go.
236
+ async plan(goal) {
237
+ const job = newJob(jobId(), goal);
238
+ excludeFromGit(this.#d.project);
239
+ moveJob(job, "triage");
240
+ return this.planJob(job);
241
+ }
242
+ // A job from triage or a confirmed checkpoint to a validated plan at the plan gate.
243
+ // In cloud mode a job is local-only only by the user's choice. A local-only flag that came from the "nothing
244
+ // local could check it" default (the GLiNER server was down) is dropped.
245
+ #cloudFlags(job) {
246
+ if (this.#d.mode === "cloud" && job.flags?.localOnly && job.flags.gate && !job.flags.gate.checked) {
247
+ job.flags = { ...job.flags, localOnly: false };
248
+ job.lessons.push("cloud mode: the local-only default of an unchecked goal was dropped");
249
+ }
250
+ }
251
+ #cancelled() {
252
+ return Boolean(this.#d.cancelled?.());
253
+ }
254
+ #isStopped(job) {
255
+ return this.#cancelled() || Boolean(loadControl(this.#d.project, job.id).stopped);
256
+ }
257
+ #syncDiskNotes(job) {
258
+ const disk = loadJob(this.#d.project, job.id);
259
+ if (!disk)
260
+ return [];
261
+ const have = new Set(job.decisions.map((d) => d.id));
262
+ const added = disk.decisions.filter((d) => !have.has(d.id));
263
+ if (added.length > 0)
264
+ job.decisions.push(...added);
265
+ return added;
266
+ }
267
+ #pausePlan(job) {
268
+ this.#syncDiskNotes(job);
269
+ if (job.phase === "plan")
270
+ moveJob(job, "paused");
271
+ saveJob(this.#d.project, job);
272
+ return { job, stopped: true };
273
+ }
274
+ #deferOrPlan(job, opts) {
275
+ if (opts?.deferPlan) {
276
+ this.#cloudFlags(job);
277
+ if (job.phase !== "plan")
278
+ moveJob(job, "plan");
279
+ this.#syncDiskNotes(job);
280
+ saveJob(this.#d.project, job);
281
+ return Promise.resolve({ kind: "planning", job, text: "" });
282
+ }
283
+ return this.planJob(job).then((r) => this.#planned(r));
284
+ }
285
+ async planJob(job) {
286
+ this.#cloudFlags(job);
287
+ if (job.phase !== "plan")
288
+ moveJob(job, "plan");
289
+ this.#syncDiskNotes(job);
290
+ saveJob(this.#d.project, job);
291
+ if (this.#isStopped(job))
292
+ return this.#pausePlan(job);
293
+ try {
294
+ if (!(await this.#localOrAllowed(job, "plan", 0.7))) {
295
+ this.#syncDiskNotes(job);
296
+ saveJob(this.#d.project, job);
297
+ return { job };
298
+ }
299
+ if (this.#isStopped(job))
300
+ return this.#pausePlan(job);
301
+ const model = await this.#requiredModel(job, "plan", 0.7);
302
+ if (!model) {
303
+ this.#syncDiskNotes(job);
304
+ saveJob(this.#d.project, job);
305
+ return { job, errors: [job.lessons.at(-1) ?? "no model for the plan"] };
306
+ }
307
+ if (this.#isStopped(job))
308
+ return this.#pausePlan(job);
309
+ this.#say(`planning with ${model.id} (${model.reason})`);
310
+ const repos = surveyFolder(this.#d.project).repos;
311
+ const rootIsRepo = isRepoRoot(this.#d.project);
312
+ this.#syncDiskNotes(job);
313
+ const basePrompt = plannerPrompt(job, repos, rootIsRepo);
314
+ // The Blind Plan Council runs only on the first, unfettered plan of a high-complexity job. A plan-refinement
315
+ // round (a "plan feedback" decision) always returns to the single-planner loop so its added decisions fold in.
316
+ const planFeedback = job.decisions.find((d) => d.text.startsWith("plan feedback:"))?.text;
317
+ const councilled = await this.#councilPlan(job, basePrompt, planFeedback);
318
+ if (this.#isStopped(job))
319
+ return this.#pausePlan(job);
320
+ let s;
321
+ let answer;
322
+ let parsed;
323
+ if (councilled) {
324
+ parsed = { plan: councilled };
325
+ // The council's blind synthesis already opened a planner session; reuse it for any N4 split.
326
+ s = job.plannerSession ? { id: job.plannerSession } : undefined;
327
+ }
328
+ else {
329
+ s = await this.#plannerSession(job, model.id);
330
+ if (this.#isStopped(job))
331
+ return this.#pausePlan(job);
332
+ const seenIds = new Set(job.decisions.map((d) => d.id));
333
+ answer = await this.#ask(s.id, basePrompt);
334
+ if (this.#isStopped(job))
335
+ return this.#pausePlan(job);
336
+ if (answer.stopped) {
337
+ // never resume a stopped session: one fresh planner with a handoff note
338
+ this.#say(`the planner was stopped by the loop watchdog (${answer.stopped.detail}); one fresh try`);
339
+ s = await this.#plannerSession(job, model.id);
340
+ if (this.#isStopped(job))
341
+ return this.#pausePlan(job);
342
+ this.#syncDiskNotes(job);
343
+ for (const d of job.decisions)
344
+ seenIds.add(d.id);
345
+ answer = await this.#ask(s.id, `${basePrompt}\n\n${handoffNote(answer.stopped, [])}`);
346
+ if (this.#isStopped(job))
347
+ return this.#pausePlan(job);
348
+ }
349
+ parsed = answer.stopped ? { errors: [`the planner was stopped by the loop watchdog: ${answer.stopped.detail}`] } : parsePlan(answer.text);
350
+ for (let retry = 0; parsed.errors && !answer.timedOut && !answer.stopped && retry < (this.#d.planRetries ?? 2); retry++) {
351
+ if (this.#isStopped(job))
352
+ return this.#pausePlan(job);
353
+ this.#say(`the plan has ${parsed.errors.length} problem(s), asking again`);
354
+ 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.`);
355
+ if (this.#isStopped(job))
356
+ return this.#pausePlan(job);
357
+ parsed = answer.stopped ? { errors: [`the planner was stopped by the loop watchdog: ${answer.stopped.detail}`] } : parsePlan(answer.text);
358
+ }
359
+ this.#syncDiskNotes(job);
360
+ let added = job.decisions.filter((d) => !seenIds.has(d.id));
361
+ while (parsed.plan && added.length > 0 && !this.#isStopped(job)) {
362
+ for (const d of added)
363
+ seenIds.add(d.id);
364
+ answer = await this.#ask(s.id, `${HEADER} While you were planning, the user added:\n${added.map((d) => `- ${d.text}`).join("\n")}\n\nUpdate and return the complete JSON plan incorporating these notes (JSON only).`);
365
+ if (this.#isStopped(job))
366
+ return this.#pausePlan(job);
367
+ parsed = answer.stopped ? { errors: [`the planner was stopped by the loop watchdog: ${answer.stopped.detail}`] } : parsePlan(answer.text);
368
+ for (let retry = 0; parsed.errors && !answer.timedOut && !answer.stopped && retry < (this.#d.planRetries ?? 2); retry++) {
369
+ if (this.#isStopped(job))
370
+ return this.#pausePlan(job);
371
+ this.#say(`the plan has ${parsed.errors.length} problem(s), asking again`);
372
+ 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.`);
373
+ if (this.#isStopped(job))
374
+ return this.#pausePlan(job);
375
+ parsed = answer.stopped ? { errors: [`the planner was stopped by the loop watchdog: ${answer.stopped.detail}`] } : parsePlan(answer.text);
376
+ }
377
+ this.#syncDiskNotes(job);
378
+ added = job.decisions.filter((d) => !seenIds.has(d.id));
379
+ }
380
+ if (this.#isStopped(job))
381
+ return this.#pausePlan(job);
382
+ }
383
+ if (this.#isStopped(job))
384
+ return this.#pausePlan(job);
385
+ if (!parsed.plan) {
386
+ job.lessons.push(`planning failed: ${answer?.timedOut ? "the planner timed out" : (parsed.errors ?? []).join("; ")}`);
387
+ moveJob(job, "failed");
388
+ this.#syncDiskNotes(job);
389
+ saveJob(this.#d.project, job);
390
+ return { job, errors: answer?.timedOut ? ["the planner timed out"] : parsed.errors };
391
+ }
392
+ let plan = parsed.plan;
393
+ let candidates = plan.tasks;
394
+ for (let level = 1; level <= MAX_SPLIT_LEVEL && candidates.length > 0 && !answer?.stopped; level++) {
395
+ if (this.#isStopped(job))
396
+ return this.#pausePlan(job);
397
+ const before = new Set(plan.tasks.map((t) => t.id));
398
+ if (!s)
399
+ s = await this.#plannerSession(job, model.id);
400
+ if (this.#isStopped(job))
401
+ return this.#pausePlan(job);
402
+ plan = await this.#split(job, s.id, plan, candidates);
403
+ if (this.#isStopped(job))
404
+ return this.#pausePlan(job);
405
+ candidates = plan.tasks.filter((t) => !before.has(t.id));
406
+ }
407
+ const coalesced = coalesceCoupledTasks(plan);
408
+ if (coalesced.merged.length > 0) {
409
+ this.#say(`coalesced ${coalesced.merged.length} coupled same-file chain${coalesced.merged.length === 1 ? "" : "s"}: ${coalesced.merged.map((m) => `${m.absorbed} into ${m.into}`).join(", ")}`);
410
+ }
411
+ applyPlan(job, coalesced.plan);
412
+ moveJob(job, "plan_gate");
413
+ this.#syncDiskNotes(job);
414
+ saveJob(this.#d.project, job);
415
+ return { job };
416
+ }
417
+ catch (err) {
418
+ if (err instanceof Cancelled || this.#isStopped(job))
419
+ return this.#pausePlan(job);
420
+ throw err;
421
+ }
422
+ }
423
+ // N4: tasks that are too big for one fresh session and can be split go back to the planner, which writes the parts;
424
+ // code re-validates. Without a decision model, more than 3 files means too big. A split that stays invalid keeps
425
+ // the task whole.
426
+ async #split(job, plannerSession, plan, candidates) {
427
+ const policy = resolvePolicy("N4", this.#policies(job)).policy;
428
+ if (policy.kind === "fixed")
429
+ return plan; // "N4": "fixed:no" keeps the planner's tasks
430
+ const asked = policy.kind === "rule" ? undefined : await this.#decider.ask("N4", { goal: job.goal }, splitQuestions(candidates), { localOnly: job.flags?.localOnly, job: job.id });
431
+ const a = asked?.decision.answers ?? {};
432
+ const p = (q) => (a[q]?.type === "noul" ? a[q].noul : undefined);
433
+ const ids = candidates.filter((t) => {
434
+ const big = p(`too_big.${t.id}`);
435
+ const hard = p(`hard.${t.id}`);
436
+ const splittable = p(`splittable.${t.id}`);
437
+ if (big === undefined && hard === undefined)
438
+ return t.files.length > 3;
439
+ return Math.max(big ?? 0, hard ?? 0) >= NOUL_FLOOR && (splittable ?? 0) >= NOUL_FLOOR;
440
+ }).map((t) => t.id);
441
+ if (ids.length === 0)
442
+ return plan;
443
+ this.#say(`splitting ${ids.join(", ")}`);
444
+ let answer = await this.#ask(plannerSession, `${HEADER} ${splitFormat(ids)}`);
445
+ let r = answer.stopped || answer.timedOut ? { errors: ["the planner stopped"] } : applySplits(plan, answer.text, ids);
446
+ if (r.errors && !answer.stopped && !answer.timedOut) {
447
+ answer = await this.#ask(plannerSession, `${HEADER} The split has these problems:\n- ${r.errors.join("\n- ")}\n\nAnswer again with the corrected JSON only.`);
448
+ r = answer.stopped || answer.timedOut ? { errors: ["the planner stopped"] } : applySplits(plan, answer.text, ids);
449
+ }
450
+ if (r.errors) {
451
+ job.lessons.push(`split of ${ids.join(", ")} kept whole: ${r.errors.slice(0, 3).join("; ")}`);
452
+ this.#say(`the split of ${ids.join(", ")} stays invalid; the tasks stay whole`);
453
+ return plan;
454
+ }
455
+ return r.plan;
456
+ }
457
+ // A new job from the micromanager: the local gate, triage, then a planning session or the planner (design.md §6).
458
+ async start(goal, facilitator, opts) {
459
+ const job = newJob(jobId(), goal);
460
+ job.facilitator = facilitator;
461
+ excludeFromGit(this.#d.project);
462
+ moveJob(job, "triage");
463
+ const gate = await checkGuards(this.#decider, goal, job.id);
464
+ const flags = flagsWithoutUser(gate, this.#d.unchecked ?? (this.#d.mode === "cloud" ? "cloud" : "local"), this.#d.mode ?? "local");
465
+ if (flags === "ask_user") {
466
+ job.flags = { gate };
467
+ moveJob(job, "ask_user");
468
+ saveJob(this.#d.project, job);
469
+ 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.mode ?? "local")}` };
470
+ }
471
+ job.flags = flags;
472
+ return this.#triage(job, opts);
473
+ }
474
+ // plan_job with a job id: go on from wherever the job stands.
475
+ // feedback: what the user wants changed in a plan at the plan gate. It becomes a decision, and the planner writes
476
+ // the plan again (live test: the micromanager asked eight times for a fuller plan and always got the old one back).
477
+ async continueJob(id, feedback, opts) {
478
+ const job = loadJob(this.#d.project, id);
479
+ if (!job)
480
+ return { kind: "failed", job: newJob(id, ""), text: `no job ${id}` };
481
+ if (job.phase === "plan_gate" && feedback?.trim()) {
482
+ job.decisions.push({ id: `F${job.decisions.length + 1}`, text: `plan feedback: ${feedback.trim()}`, origin: "user" });
483
+ moveJob(job, "plan");
484
+ saveJob(this.#d.project, job);
485
+ return this.#deferOrPlan(job, opts);
486
+ }
487
+ if (job.phase === "paused" && job.resumePhase === "plan") {
488
+ if (loadControl(this.#d.project, job.id).stopped)
489
+ updateControl(this.#d.project, job.id, { stopped: false });
490
+ if (feedback?.trim())
491
+ job.decisions.push({ id: `F${job.decisions.length + 1}`, text: `plan feedback: ${feedback.trim()}`, origin: "user" });
492
+ moveJob(job, "plan");
493
+ saveJob(this.#d.project, job);
494
+ return this.#deferOrPlan(job, opts);
495
+ }
496
+ if (job.phase === "triage")
497
+ return this.#triage(job, opts);
498
+ if (job.phase === "plan") {
499
+ if (feedback?.trim()) {
500
+ job.decisions.push({ id: `F${job.decisions.length + 1}`, text: `plan feedback: ${feedback.trim()}`, origin: "user" });
501
+ saveJob(this.#d.project, job);
502
+ }
503
+ return this.#deferOrPlan(job, opts);
504
+ }
505
+ if (job.phase === "planning_session" && job.designTree) {
506
+ const node = job.designTree.nodes.find((n) => n.id === job.designTree.current);
507
+ return { kind: "session", job, text: node ? instruction({ kind: "ask", node, reason: "continued" }, job.id, job.designTree) : draftInstruction(job) };
508
+ }
509
+ if (job.phase === "planning_session")
510
+ return { kind: "session", job, text: draftInstruction(job) };
511
+ if (job.phase === "paused" && job.resumePhase === "planning_session") {
512
+ if (loadControl(this.#d.project, job.id).stopped)
513
+ updateControl(this.#d.project, job.id, { stopped: false });
514
+ moveJob(job, "planning_session");
515
+ saveJob(this.#d.project, job);
516
+ return this.continueJob(id, feedback, opts);
517
+ }
518
+ return { kind: "info", job, text: `job ${job.id} is in phase ${job.phase}` };
519
+ }
520
+ #planned(r) {
521
+ if (r.stopped)
522
+ return { kind: "info", job: r.job, text: `job ${r.job.id} is paused` };
523
+ return r.errors
524
+ ? { kind: "failed", job: r.job, text: `The planner could not produce a valid plan (job ${r.job.id}):\n- ${r.errors.join("\n- ")}` }
525
+ : { kind: "plan", job: r.job, text: "" };
526
+ }
527
+ // N1: how complex, and does it need the user's decisions first? A pin ("no planning session") skips the session.
528
+ async #triage(job, opts) {
529
+ const pin = resolvePolicy("N2.clarity", this.#policies(job)).policy;
530
+ const asked = await this.#decider.ask("N1", { goal: job.goal, files: topLevel(this.#d.project) }, TRIAGE, { localOnly: job.flags?.localOnly, job: job.id });
531
+ const c = asked.decision.answers.complexity;
532
+ const n = asked.decision.answers.needs_clarification;
533
+ const complexity = c?.type === "score" ? complexityOf(c.score) : undefined;
534
+ const clarification = n?.type === "noul" ? n.noul : undefined;
535
+ let session;
536
+ let reason;
537
+ if (pin.kind === "fixed")
538
+ [session, reason] = [pin.value !== "clear", `preset ${pin.value}`];
539
+ else if (pin.kind === "ask")
540
+ [session, reason] = [true, "the user wants to be asked"];
541
+ else if (clarification === undefined)
542
+ [session, reason] = [true, "no decision model answer: open questions count as open"];
543
+ else if (clarification >= NOUL_FLOOR)
544
+ [session, reason] = [true, `open decisions (${clarification.toFixed(2)})`];
545
+ else
546
+ [session, reason] = [false, `clear enough (${clarification.toFixed(2)})`];
547
+ job.triage = { complexity, clarification, session, reason };
548
+ if (!session)
549
+ return this.#deferOrPlan(job, opts);
550
+ moveJob(job, "clarity");
551
+ moveJob(job, "planning_session");
552
+ saveJob(this.#d.project, job);
553
+ return { kind: "session", job, text: draftInstruction(job) };
554
+ }
555
+ // The facilitator's draft of the design tree, or new branches for an existing one.
556
+ async questions(id, json) {
557
+ const job = loadJob(this.#d.project, id);
558
+ if (!job || (job.phase !== "planning_session" && job.phase !== "design_checkpoint"))
559
+ return `no planning session for job ${id}`;
560
+ let raw;
561
+ try {
562
+ raw = JSON.parse(json);
563
+ }
564
+ catch (err) {
565
+ return `invalid JSON: ${err instanceof Error ? err.message : String(err)}. Send the list of questions again.`;
566
+ }
567
+ if (!job.designTree) {
568
+ const parsed = parseTree(raw);
569
+ if (parsed.errors)
570
+ return `The questions have problems:\n- ${parsed.errors.join("\n- ")}\nSend them again.`;
571
+ job.designTree = parsed.tree;
572
+ }
573
+ else {
574
+ const errors = addNodes(job.designTree, raw);
575
+ if (errors.length)
576
+ return `The new questions have problems:\n- ${errors.join("\n- ")}\nSend them again.`;
577
+ }
578
+ if (job.phase === "design_checkpoint")
579
+ moveJob(job, "planning_session");
580
+ await this.#settledByJob(job);
581
+ return this.#advance(job, nextStep(job.designTree, await this.#pick(job)));
582
+ }
583
+ // N2: questions the job text already answers are settled without asking (one request, one noul per question).
584
+ async #settledByJob(job) {
585
+ const tree = job.designTree;
586
+ const open = tree.nodes.filter((n) => n.status === "open" && n.kind === "decision");
587
+ if (open.length === 0)
588
+ return;
589
+ const questions = Object.fromEntries(open.map((n) => [`settled_${n.id}`, {
590
+ type: "noul",
591
+ instructions: `The question "${n.question}" is already answered by the job text, so the user does not need to be asked.`,
592
+ }]));
593
+ const asked = await this.#decider.ask("N2", { goal: job.goal }, questions, { localOnly: job.flags?.localOnly, job: job.id });
594
+ for (const n of open) {
595
+ const a = asked.decision.answers[`settled_${n.id}`];
596
+ if (a?.type === "noul" && a.noul >= 0.8)
597
+ settle(tree, n.id, "answered by the job text", "fact");
598
+ }
599
+ }
600
+ // N2b: which frontier question next; below the floor the rules pick.
601
+ async #pick(job) {
602
+ const options = frontier(job.designTree);
603
+ if (options.length < 2)
604
+ return undefined;
605
+ const asked = await this.#decider.ask("N2b", { goal: job.goal, decided: decisionsText(job.designTree) }, { next: nextQuestionChoice(Object.fromEntries(options.map((n) => [n.id, n.question]))) }, { localOnly: job.flags?.localOnly, job: job.id });
606
+ const a = asked.decision.answers.next;
607
+ return a?.type === "choice" && a.confidence >= CHOICE_FLOOR ? a.choice : undefined;
608
+ }
609
+ #advance(job, step) {
610
+ if (step.kind === "checkpoint" && job.phase === "planning_session")
611
+ moveJob(job, "design_checkpoint");
612
+ if (step.kind === "stopped")
613
+ moveJob(job, "paused");
614
+ saveJob(this.#d.project, job);
615
+ return instruction(step, job.id, job.designTree);
616
+ }
617
+ // One user turn in the micromanager session: the gate answer, a planning-session answer, or the checkpoint reply.
618
+ // Returns the instruction for the micromanager's next turn, or undefined when the turn is not about this job.
619
+ async answer(id, text, opts) {
620
+ const job = loadJob(this.#d.project, id);
621
+ if (!job)
622
+ return undefined;
623
+ if (job.phase === "ask_user" && job.resumePhase === "triage" && job.flags?.gate) {
624
+ const reply = gateAnswer(text);
625
+ if (reply === undefined)
626
+ return `[job ${id}] Waiting for the user's answer to the local check: "always local", "use uncensored", "continue" or "stop".`;
627
+ if (reply === "stop") {
628
+ moveJob(job, "stopped");
629
+ saveJob(this.#d.project, job);
630
+ return `[job ${id}] The user stopped the job. Confirm briefly.`;
631
+ }
632
+ job.flags = { ...job.flags, ...reply };
633
+ moveJob(job, "triage");
634
+ saveJob(this.#d.project, job);
635
+ 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.`;
636
+ }
637
+ const tree = job.designTree;
638
+ if (job.phase === "design_checkpoint" && tree) {
639
+ const s = matchSessionShortcut(text);
640
+ if (s?.kind === "confirm") {
641
+ 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" }));
642
+ moveJob(job, "plan");
643
+ saveJob(this.#d.project, job);
644
+ return opts?.deferPlan
645
+ ? `[job ${id}] The user confirmed the design; ready to plan.`
646
+ : `[job ${id}] The user confirmed the design. Call plan_job with goal "${id}" to plan it now.`;
647
+ }
648
+ moveJob(job, "planning_session");
649
+ saveJob(this.#d.project, job);
650
+ 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.`;
651
+ }
652
+ if (job.phase !== "planning_session" || !tree)
653
+ return undefined;
654
+ const shortcut = matchSessionShortcut(text);
655
+ if (shortcut) {
656
+ const step = applyShortcut(tree, shortcut);
657
+ return this.#advance(job, step ?? nextStep(tree, await this.#pick(job)));
658
+ }
659
+ const reading = await this.#read(job, tree, text);
660
+ const step = applyAnswer(tree, text, reading);
661
+ return this.#advance(job, step ?? nextStep(tree, await this.#pick(job)));
662
+ }
663
+ // N2c: what the answer does; without the decision model an answer counts as settling the question.
664
+ async #read(job, tree, text) {
665
+ const node = tree.nodes.find((n) => n.id === tree.current);
666
+ const asked = await this.#decider.ask("N2c", { question: node?.question, answer: text, decided: decisionsText(tree) }, ANSWER, { localOnly: job.flags?.localOnly, job: job.id });
667
+ const yes = (q) => {
668
+ const a = asked.decision.answers[q];
669
+ return a?.type === "noul" ? a.noul >= NOUL_FLOOR : undefined;
670
+ };
671
+ if (Object.keys(asked.decision.answers).length === 0)
672
+ return { settles: true };
673
+ 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") };
674
+ }
675
+ // The user said go: work the plan on the job's branch until it is done or needs the user.
676
+ // note: the user's answer when the job stopped for them; it becomes a decision every later brief carries, and a
677
+ // blocked task starts again with it.
678
+ async run(id, note) {
679
+ const job = loadJob(this.#d.project, id);
680
+ if (!job)
681
+ throw new Error(`no job ${id}`);
682
+ if (job.phase === "plan_gate")
683
+ moveJob(job, "execute");
684
+ else if (job.phase === "paused" && job.resumePhase === "execute")
685
+ moveJob(job, "execute");
686
+ else if (job.phase === "ask_user" && job.resumePhase === "execute") {
687
+ // Running the job again after "confirm Tn before it runs" is the user's go for those tasks.
688
+ for (const t of job.tasks)
689
+ if (t.confirmed === false)
690
+ t.confirmed = true;
691
+ for (const t of job.tasks)
692
+ if (t.status === "blocked")
693
+ moveTask(t, "pending");
694
+ moveJob(job, "execute");
695
+ }
696
+ if (note?.trim())
697
+ job.decisions.push({ id: `U${job.decisions.length + 1}`, text: note.trim(), origin: "user" });
698
+ if (job.phase !== "execute")
699
+ throw new Error(`job ${id} is in phase ${job.phase}, not ready to run`);
700
+ this.#job = job;
701
+ this.#cloudFlags(job);
702
+ // Never quietly to the cloud: a job that must stay on this machine asks while local models are switched off.
703
+ if (this.#d.mode === "cloud" && job.flags?.localOnly && !(await this.#localOrAllowed(job, "code", 0.5))) {
704
+ saveJob(this.#d.project, job);
705
+ return job;
706
+ }
707
+ job.budget.tokensMax ??= this.#d.budget?.tokens;
708
+ job.budget.requestsMax ??= this.#d.budget?.requests;
709
+ job.budget.costMax ??= this.#d.budget?.cost;
710
+ if (!job.integrationWorktree) {
711
+ excludeFromGit(this.#d.project); // also for a rolling job, which never passes plan or start
712
+ const integration = await prepareIntegration(this.#d.project, job.id, this.#exec);
713
+ job.integrationBranch = integration.branch;
714
+ job.integrationWorktree = integration.worktree;
715
+ // A git worktree is a checkout of the repository ROOT, so a project below it keeps an offset: without it every
716
+ // worker and every check would work three levels above its own files.
717
+ job.integrationRel = integration.rel;
718
+ job.integrationBase = integration.base;
719
+ job.integrationDirty = integration.dirty ? integration.dirtySummary : "";
720
+ this.#say(`working on branch ${integration.branch}`);
721
+ if (integration.rel)
722
+ 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)}`);
723
+ if (integration.dirty)
724
+ this.#say(`the working tree has uncommitted paths no worker will see (${integration.dirtySummary}); this job starts from ${integration.base.slice(0, 7)}`);
725
+ }
726
+ else
727
+ await this.#reconcile(job);
728
+ saveJob(this.#d.project, job);
729
+ // Tasks run as promises; with parallel 1 one at a time, as before Phase F. A task that stops the job lets the
730
+ // others finish what they are doing; a stop by the user cuts them all.
731
+ const running = new Map();
732
+ let cancelled = false;
733
+ let failure;
734
+ const start = (task) => {
735
+ const p = this.#dispatch(job, task)
736
+ .catch((err) => { if (err instanceof Cancelled)
737
+ cancelled = true;
738
+ else
739
+ failure ??= err; })
740
+ .finally(() => { running.delete(task.id); saveJob(this.#d.project, job); });
741
+ running.set(task.id, p);
742
+ };
743
+ const settle = () => Promise.race(running.values());
744
+ try {
745
+ for (;;) {
746
+ if (failure)
747
+ throw failure;
748
+ if (cancelled || job.phase !== "execute") {
749
+ if (running.size)
750
+ await settle();
751
+ else
752
+ break;
753
+ continue;
754
+ }
755
+ promoteReady(job);
756
+ // A rolling job only runs what the orchestrator delegated: no verify, replan or wrap; it ends when nothing is
757
+ // left to start, and the next delegation runs it again.
758
+ const agenda = buildAgenda(job).filter((p) => (!p.taskId || !running.has(p.taskId)) && (!job.rolling || p.action === "dispatch"));
759
+ const next = nextProposal(agenda);
760
+ if (!next || (next.action !== "dispatch" && running.size)) {
761
+ // verify, replan and asking the user wait until every running task has finished
762
+ if (running.size)
763
+ await settle();
764
+ else
765
+ break;
766
+ continue;
767
+ }
768
+ if (++job.counters.turns > job.budget.turnsMax) {
769
+ this.#stop(job, `turn budget of ${job.budget.turnsMax} used up`);
770
+ continue;
771
+ }
772
+ const over = this.#overBudget(job);
773
+ if (over) {
774
+ this.#stop(job, `budget: ${over}; raise it in the config or with a pin, then run the job again`);
775
+ continue;
776
+ }
777
+ if (next.action === "dispatch") {
778
+ const batch = await this.#batch(job, agenda, running);
779
+ if (batch.length === 0)
780
+ await settle();
781
+ for (const t of batch)
782
+ start(t);
783
+ if ((this.#d.parallel ?? 1) <= 1)
784
+ while (running.size)
785
+ await settle();
786
+ }
787
+ else if (next.action === "verify")
788
+ await this.#verify(job);
789
+ else if (next.action === "replan")
790
+ await this.#replan(job);
791
+ else
792
+ this.#stop(job, next.label);
793
+ saveJob(this.#d.project, job);
794
+ }
795
+ if (failure)
796
+ throw failure;
797
+ if (cancelled)
798
+ throw new Cancelled();
799
+ }
800
+ catch (err) {
801
+ if (!(err instanceof Cancelled))
802
+ throw err;
803
+ // The tasks in progress are cut; the next run's reconcile starts them again from the last commit.
804
+ if (job.phase === "replan")
805
+ moveJob(job, "execute");
806
+ job.lessons.push("stopped by the user");
807
+ const phase = job.phase;
808
+ if (phase === "ask_user")
809
+ moveJob(job, job.resumePhase ?? "execute"); // a task had stopped it: pause the run itself
810
+ if (job.phase !== "paused")
811
+ moveJob(job, "paused");
812
+ this.#say("stopped by the user; run the job again to resume");
813
+ }
814
+ saveJob(this.#d.project, job);
815
+ return job;
816
+ }
817
+ // The next ready tasks that may run next to the running ones: disjoint files, within the job's limit. Two or more
818
+ // new ones are a batch the decision model confirms (N10); one it doubts waits for a later batch.
819
+ async #batch(job, agenda, running) {
820
+ const limit = Math.max(1, this.#d.parallel ?? 1);
821
+ const busy = job.tasks.filter((t) => running.has(t.id));
822
+ const batch = [];
823
+ for (const p of agenda) {
824
+ if (p.action !== "dispatch" || !p.taskId || busy.length + batch.length >= limit)
825
+ continue;
826
+ const t = job.tasks.find((x) => x.id === p.taskId);
827
+ if ([...busy, ...batch].every((o) => parallelSafe(o, t)))
828
+ batch.push(t);
829
+ }
830
+ // N10 is opt-in ("N10": "auto" in the config): disjoint files are enough to run side by side.
831
+ const n10 = resolvePolicy("N10", this.#policies(job));
832
+ if (batch.length + busy.length < 2 || batch.length === 0 || n10.level === undefined || n10.policy.kind !== "auto") {
833
+ if (batch.length + busy.length > 1)
834
+ this.#say(`starting ${batch.map((t) => t.id).join(", ")}${busy.length ? ` next to ${busy.map((t) => t.id).join(", ")}` : " in parallel"}`);
835
+ return batch;
836
+ }
837
+ const all = [...busy, ...batch];
838
+ const others = (id) => all.filter((t) => t.id !== id).map((t) => `${t.id} ("${t.title}")`).join(", ");
839
+ 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 });
840
+ const a = asked.decision.answers;
841
+ // The first new task always goes when nothing runs; the others need the model's yes when it answered.
842
+ const kept = batch.filter((t, i) => {
843
+ const p = a[`independent.${t.id}`];
844
+ return (i === 0 && busy.length === 0) || p?.type !== "noul" || p.noul >= NOUL_FLOOR;
845
+ });
846
+ if (kept.length > 1 || busy.length)
847
+ this.#say(`starting ${kept.map((t) => t.id).join(", ")} in parallel${busy.length ? ` with ${busy.map((t) => t.id).join(", ")}` : ""}`);
848
+ return kept;
849
+ }
850
+ // One task: in the job's worktree when tasks run one at a time, else in its own worktree, then the merge train.
851
+ async #dispatch(job, task) {
852
+ if ((this.#d.parallel ?? 1) <= 1)
853
+ return this.#runTask(job, task);
854
+ const w = await prepareTaskWorktree(this.#d.project, job.id, task.id, job.integrationBranch, this.#exec, undefined, job.integrationRel ?? "");
855
+ task.worktree = w.worktree;
856
+ task.worktreeRel = w.rel;
857
+ task.branch = w.branch;
858
+ try {
859
+ await this.#runTask(job, task);
860
+ if (task.status === "passed") {
861
+ const step = this.#train.then(() => this.#merge(job, task));
862
+ this.#train = step.catch(() => undefined);
863
+ await step;
864
+ }
865
+ }
866
+ finally {
867
+ if (task.worktree && task.status !== "blocked")
868
+ await this.#dropWorktree(task);
869
+ }
870
+ }
871
+ async #dropWorktree(task) {
872
+ if (!task.worktree || !task.branch)
873
+ return;
874
+ await removeTaskWorktree(this.#d.project, { worktree: task.worktree, branch: task.branch }, this.#exec);
875
+ task.worktree = undefined;
876
+ task.branch = undefined;
877
+ }
878
+ // The merge train (design.md §11): rebase onto the job's branch, the task's checks again when that moved, then a
879
+ // fast-forward. A conflict sends the task back to start again from the newest commit once; the second goes to the
880
+ // user.
881
+ async #merge(job, task) {
882
+ const w = { worktree: task.worktree, branch: task.branch };
883
+ let step = await rebaseTask(w, job.integrationBranch, this.#exec);
884
+ if (step.ok && step.moved) {
885
+ const checks = [...new Set(taskAcceptance(job, task).map((a) => a.verify).filter((v) => Boolean(v)))];
886
+ const failed = (await runGate(w.worktree, checks, this.#exec, this.#checkTimeout(job), this.#dir(job, task), {}, await this.#gate(job, task, w.worktree, this.#dir(job, task)))).filter((r) => !r.passed);
887
+ if (failed.length)
888
+ step = { ok: false, conflict: `checks fail on top of the newer commits (in ${this.#dir(job, task)}): ${failed.map((f) => f.command).join(", ")}` };
889
+ }
890
+ if (step.ok)
891
+ step = await fastForward(job.integrationWorktree, w.branch, this.#exec);
892
+ if (step.ok) {
893
+ moveTask(task, "merged");
894
+ stage(task, "merge", "pass", `merged into ${job.integrationBranch}`);
895
+ this.#say(`${task.id} merged into ${job.integrationBranch}`, true);
896
+ await this.#dropWorktree(task);
897
+ await this.#ended(job, task);
898
+ return;
899
+ }
900
+ task.conflicts = (task.conflicts ?? 0) + 1;
901
+ stage(task, "merge", "fail", step.conflict);
902
+ // rebaseTask leaves a real conflict open for a worker to resolve. This runner has no such worker once a task
903
+ // failed, so it drops the worktree and starts the task again: abort first so removal is a plain cleanup.
904
+ await abortRebase(w.worktree, this.#exec);
905
+ await this.#dropWorktree(task);
906
+ if (task.conflicts === 1) {
907
+ moveTask(task, "pending");
908
+ job.lessons.push(`${task.id} did not merge (${step.conflict}); it starts again from the newest commit`);
909
+ this.#say(`${task.id}: ${step.conflict}; it starts again from the newest commit`);
910
+ return;
911
+ }
912
+ await this.#escalate(job, task, `it did not merge twice: ${step.conflict}`, "", "merge_conflict");
913
+ }
914
+ // omo-hybrid: the orchestrator's delegation goes into the job this runner works on, so the run loop sees it at its
915
+ // next turn; undefined when this runner does not work on that job (the caller then writes the job file).
916
+ addTask(jobId, d) {
917
+ const job = this.#job;
918
+ if (!job || job.id !== jobId)
919
+ return undefined;
920
+ const r = addDelegated(job, d);
921
+ if (r.task)
922
+ saveJob(this.#d.project, job);
923
+ return r;
924
+ }
925
+ // 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
926
+ // task again; undefined when this runner does not work on that job.
927
+ answerTask(jobId, taskId, text, checks = []) {
928
+ const job = this.#job;
929
+ if (!job || job.id !== jobId)
930
+ return false;
931
+ const err = Runner.answer(job, taskId, text, checks);
932
+ if (!err)
933
+ saveJob(this.#d.project, job);
934
+ return err;
935
+ }
936
+ // A rolling job's task that waits for the user: the answer becomes a decision every later brief carries, and the
937
+ // task starts again from the job's newest commit.
938
+ // checks: new checks for the task, replacing the ones it was delegated with (live test: a check with a wrong path
939
+ // kept a finished reader blocked, and no answer could change it).
940
+ static answer(job, taskId, text, checks = []) {
941
+ const task = job.tasks.find((t) => t.id === taskId);
942
+ if (!task)
943
+ return `no task ${taskId}`;
944
+ if (task.status !== "blocked" && task.status !== "escalated")
945
+ return `task ${taskId} is ${task.status}; it waits for nobody`;
946
+ if (checks.length) {
947
+ const own = job.acceptance.filter((a) => task.acceptance.includes(a.id) && !job.tasks.some((t) => t.id !== task.id && t.acceptance.includes(a.id)));
948
+ if (!own.length)
949
+ return `task ${taskId} shares its acceptance points with other tasks; its checks cannot change alone`;
950
+ job.acceptance = job.acceptance.map((a) => (own.some((o) => o.id === a.id) ? { ...a, verify: checks.join(" && ") } : a));
951
+ }
952
+ job.decisions.push({ id: `U${job.decisions.length + 1}`, text: `${taskId}: ${text}`, origin: "user" });
953
+ moveTask(task, "pending");
954
+ task.confirmed = true;
955
+ task.attempts = 0;
956
+ return undefined;
957
+ }
958
+ // A run that ended in the middle of a task (the server stopped, a crash) leaves it running with half a change in
959
+ // the worktree. Nothing of this process works on it, so it goes back to pending and the worktree back to the last
960
+ // commit; the passed tasks are commits and stay.
961
+ async #reconcile(job) {
962
+ const PATH = {
963
+ planned: ["running", "escalated", "pending"],
964
+ running: ["escalated", "pending"],
965
+ gating: ["escalated", "pending"],
966
+ reviewing: ["fixing", "escalated", "pending"],
967
+ fixing: ["escalated", "pending"],
968
+ passed: ["pending"], // passed in its own worktree, but the train had not merged it yet
969
+ };
970
+ const cut = job.tasks.filter((t) => PATH[t.status]);
971
+ for (const t of cut)
972
+ await this.#dropWorktree(t);
973
+ if (cut.length === 0)
974
+ return;
975
+ for (const t of cut) {
976
+ for (const to of PATH[t.status])
977
+ moveTask(t, to);
978
+ stage(t, "reconcile", "skip", "the run ended in the middle of this task; it starts again");
979
+ }
980
+ const dirty = await changedFiles(job.integrationWorktree, this.#exec);
981
+ await revertFiles(job.integrationWorktree, dirty, this.#exec);
982
+ job.lessons.push(`interrupted run: ${cut.map((t) => t.id).join(", ")} started again${dirty.length ? `, unfinished changes undone (${dirty.join(", ")})` : ""}`);
983
+ this.#say(`resuming: ${cut.map((t) => t.id).join(", ")} start again`);
984
+ }
985
+ // task: the stop concerns one task. In a rolling job that never stops the job: the task waits, and the orchestrator
986
+ // hears of it and asks the user.
987
+ // A job that must stay on this machine (the sensitive guard, or the user's "always local") whose work no local model
988
+ // can do. Before 2026-11-25 the router fell back to the role's cloud model here without a word. Now the user says
989
+ // whether it may go to the cloud after all, once for the job; without their word the job stops. A job that needs an
990
+ // uncensored model stops either way: no cloud model is one.
991
+ // The job's cloud switch, as the user set it in the settings panel. Only an explicit "on" wins over a local-only
992
+ // job; the default new jobs start with is written into their control file by the start form.
993
+ #cloudWanted(job) {
994
+ return loadControl(this.#d.project, job.id).cloud === true;
995
+ }
996
+ async #localOrAllowed(job, role, difficulty, vision = false, task) {
997
+ if (!job.flags?.localOnly)
998
+ return true;
999
+ if (!job.flags.uncensored && this.#cloudWanted(job)) {
1000
+ const why = "this job allows cloud models (the cloud switch is on)";
1001
+ job.flags = { ...job.flags, localOnly: false };
1002
+ job.lessons.push(`the user allows cloud models for this job: ${why}`);
1003
+ this.#journal({ kind: "consent", consent: "sensitive", job: job.id, task: task?.id, allowed: true, why });
1004
+ this.#say(`${job.id}: cloud models are allowed for this job (${why})`);
1005
+ return true;
1006
+ }
1007
+ let why = "local models are switched off (decider mode cloud)";
1008
+ if (this.#d.mode !== "cloud") {
1009
+ const availability = await this.#d.availability?.().catch(() => undefined);
1010
+ const pool = this.#pool(role);
1011
+ const r = route(this.#d.registry, { role, difficulty, vision, sensitive: true, uncensored: job.flags.uncensored, ...(pool.length ? { allow: pool } : {}) }, availability);
1012
+ if (r.model)
1013
+ return true;
1014
+ why = `no local model is running for the ${role} work (${r.reason})`;
1015
+ }
1016
+ if (job.flags.uncensored) {
1017
+ this.#stop(job, `this job runs on local uncensored models only, but ${why}. Start one, then run the job again.`, task);
1018
+ return false;
1019
+ }
1020
+ const score = job.flags.gate?.scores.sensitive;
1021
+ const text = [
1022
+ `[omacode] Job ${job.id} was marked as sensitive${score !== undefined ? ` (${score.toFixed(2)})` : ""}${job.flags.gate ? "" : " (you chose to keep it on this machine)"}, but ${why}.`,
1023
+ `Job: "${job.goal.slice(0, 300)}${job.goal.length > 300 ? "…" : ""}"`,
1024
+ ...(task ? [`Task ${task.id}: "${task.title}"`] : []),
1025
+ "Allowing the next permission lets this job use cloud models from now on: keys, e-mail, phone, IBAN and card numbers, names and addresses are replaced before anything leaves; the rest of the content goes as it is. Rejecting stops the job.",
1026
+ ].join("\n");
1027
+ const allowed = this.#d.consent ? await this.#d.consent(job, text).catch(() => false) : false;
1028
+ this.#journal({ kind: "consent", consent: "sensitive", job: job.id, task: task?.id, allowed, why });
1029
+ if (allowed) {
1030
+ job.flags = { ...job.flags, localOnly: false };
1031
+ job.lessons.push(`the user let this sensitive job use cloud models: ${why}`);
1032
+ this.#say(`${job.id}: the user allowed cloud models for this sensitive job (${why})`);
1033
+ return true;
1034
+ }
1035
+ this.#stop(job, `this job must stay on this machine, but ${why}, and the cloud was not allowed. Turn on the cloud switch in the settings panel, or start a local model, then run the job again.`, task);
1036
+ return false;
1037
+ }
1038
+ #stop(job, reason, task) {
1039
+ job.lessons.push(reason);
1040
+ if (job.rolling && task) {
1041
+ this.#say(`${task.id} waits: ${reason}`);
1042
+ this.#d.taskEnded?.(job, task);
1043
+ return;
1044
+ }
1045
+ // A parallel task may stop a job another task already stopped; the job keeps the phase it returns to.
1046
+ if (job.phase !== "ask_user" && job.phase !== "paused")
1047
+ moveJob(job, "ask_user");
1048
+ this.#say(`stopped: ${reason}`);
1049
+ }
1050
+ async #runTask(job, task) {
1051
+ if (job.budget.workersUsed >= job.budget.workersMax)
1052
+ return this.#stop(job, `worker budget of ${job.budget.workersMax} used up`);
1053
+ const worktree = this.#worktree(job, task); // git commands run in the worktree root
1054
+ const dir = this.#dir(job, task); // the worker and its checks work in the project directory
1055
+ const profile = task.profile ?? (await this.#classify(job, task));
1056
+ if (profile.injection) {
1057
+ moveTask(task, "blocked");
1058
+ task.summary = "the task text looks like an attempt to make the agent ignore its rules";
1059
+ return this.#stop(job, `${task.id}: ${task.summary}; check the plan before going on`, task);
1060
+ }
1061
+ const pipeline = choosePipeline(task, profile, this.#policies(job, task.id));
1062
+ task.pipeline = pipeline.id;
1063
+ const askFirst = pipeline.modifiers.includes("user_confirm") || resolvePolicy("N5", this.#policies(job, task.id)).policy.kind === "ask";
1064
+ if (askFirst && task.confirmed !== true) {
1065
+ task.confirmed = false;
1066
+ if (job.rolling) {
1067
+ moveTask(task, "blocked");
1068
+ task.summary = `waits for the user's go: ${profileText(profile)}`;
1069
+ }
1070
+ 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);
1071
+ }
1072
+ moveTask(task, "planned");
1073
+ if (!(await this.#localOrAllowed(job, task.role, profile.difficulty, profile.vision, task)))
1074
+ return;
1075
+ const model = await this.#requiredModel(job, task.role, profile.difficulty, task, undefined, profile.vision);
1076
+ if (!model)
1077
+ return;
1078
+ task.model = model.id;
1079
+ moveTask(task, "running");
1080
+ job.budget.workersUsed++;
1081
+ this.#say(`${task.id} ${task.title}: ${task.role} on ${model.id} (${model.reason}), ${pipeline.id} (${pipeline.reason})`);
1082
+ if (pipeline.id === "P9")
1083
+ return this.#research(job, task, model.id);
1084
+ const checks = [...new Set(taskAcceptance(job, task).map((a) => a.verify).filter((v) => Boolean(v)))];
1085
+ let frozen = new Map();
1086
+ if (pipeline.id === "P3") {
1087
+ const red = await this.#red(job, task, checks);
1088
+ if (!red)
1089
+ return;
1090
+ frozen = red;
1091
+ }
1092
+ const s = await this.#workerSession(job, task, model.id);
1093
+ const first = [brief(job, task, model.id, dir, this.#skills("implement", task)), frozen.size ? greenNote([...frozen.keys()]) : ""].filter(Boolean).join("\n\n");
1094
+ let work = { s, model, answer: await this.#ask(s.id, first), fresh: false };
1095
+ work = await this.#untilGreen(job, task, work, checks, frozen);
1096
+ if (!work)
1097
+ return;
1098
+ const review = (pipeline.id === "P2" || pipeline.id === "P3") && resolvePolicy("N6.review", this.#policies(job, task.id)).policy.kind !== "fixed";
1099
+ let lastIssues = "";
1100
+ for (let round = 1; review; round++) {
1101
+ moveTask(task, "reviewing");
1102
+ const r = await this.#review(job, task, work.model.id);
1103
+ // A missing review model stops the job inside #requiredModel: do not go on with a review that could not run.
1104
+ if (job.phase === "ask_user" || job.phase === "paused")
1105
+ return;
1106
+ 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`));
1107
+ if (r.blocking.length === 0)
1108
+ break;
1109
+ // N8 signature: the same unmet points as the last round mean this session is not getting there.
1110
+ const issues = r.blocking.map((c) => c.point).sort().join(",");
1111
+ const repeated = issues === lastIssues;
1112
+ lastIssues = issues;
1113
+ if (round >= REVIEW_ROUNDS || repeated) {
1114
+ const why = repeated ? `the review found the same unmet points twice: ${issues}` : `the review still finds unmet points after ${REVIEW_ROUNDS} rounds: ${issues}`;
1115
+ work = await this.#nextRung(job, task, work, frozen, why, r.blocking.map((c) => `- ${c.point}: ${c.evidence}`).join("\n"), "conflicting_review");
1116
+ if (!work)
1117
+ return;
1118
+ round = 0;
1119
+ lastIssues = "";
1120
+ }
1121
+ else {
1122
+ moveTask(task, "fixing");
1123
+ moveTask(task, "running");
1124
+ this.#say(`${task.id}: the review found ${r.blocking.length} unmet point(s), round ${round + 1}`);
1125
+ work.answer = await this.#ask(work.s.id, [reviewFixPrompt(r), skillLine(this.#skills("review_fix", task))].filter(Boolean).join("\n\n"));
1126
+ }
1127
+ work = await this.#untilGreen(job, task, work, checks, frozen);
1128
+ if (!work)
1129
+ return;
1130
+ }
1131
+ moveTask(task, "passed");
1132
+ task.summary = work.answer.text.slice(-500);
1133
+ const outside = (await changedFiles(worktree, this.#exec)).filter((f) => task.files.length > 0 && !task.files.includes(f) && !frozen.has(f));
1134
+ 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);
1135
+ job.counters.stalls = Math.max(0, job.counters.stalls - 1);
1136
+ if (task.worktree)
1137
+ return this.#say(`${task.id} passed${commit ? ` (${commit})` : ", nothing to commit"}; waiting for the merge train`);
1138
+ moveTask(task, "merged");
1139
+ this.#say(`${task.id} passed${commit ? ` (${commit})` : ", nothing to commit"}`, true);
1140
+ await this.#ended(job, task);
1141
+ }
1142
+ // A merged task: in a rolling job the orchestrator gets its report and decides on its follow-ups; in a planned job
1143
+ // N7 does (design.md §8).
1144
+ async #ended(job, task) {
1145
+ await this.#learn(job, task);
1146
+ if (job.rolling)
1147
+ this.#d.taskEnded?.(job, task);
1148
+ else
1149
+ await this.#discover(job, task);
1150
+ }
1151
+ // N15: a merged task's LEARNED lines go into the project memory when the decider calls them lasting and not yet known.
1152
+ // Without an answer nothing is kept: a wrong fact in the memory misleads every later task.
1153
+ async #learn(job, task) {
1154
+ const items = (task.learned ?? []).slice(0, 5);
1155
+ if (items.length === 0)
1156
+ return;
1157
+ const memory = readMemory(this.#d.project);
1158
+ 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 });
1159
+ const a = asked.decision.answers;
1160
+ const p = (q) => (a[q]?.type === "noul" ? a[q].noul : undefined);
1161
+ const keep = items.filter((_, i) => (p(`lasting.${i}`) ?? 0) >= NOUL_FLOOR && (p(`useful.${i}`) ?? 0) >= NOUL_FLOOR && (p(`known.${i}`) ?? 1) < NOUL_FLOOR);
1162
+ this.#journal({ kind: "memory", job: job.id, task: task.id, offered: items, kept: keep, decision: asked.id });
1163
+ task.learned = [];
1164
+ if (keep.length === 0)
1165
+ return;
1166
+ excludeFromGit(this.#d.project);
1167
+ writeMemory(this.#d.project, [...memory, ...keep.map((k) => k.slice(0, 300))]);
1168
+ this.#say(`${task.id}: remembered for this project: ${keep.join("; ")}`);
1169
+ }
1170
+ // N7: what the worker found outside its task. Needed or in scope: a new task after this one, with the priority the
1171
+ // model gave. The user's call, out of scope, or over the cap: the job's "later" list, shown at the end. Without a
1172
+ // decision model a follow-up is in scope when every file it names is already in the plan.
1173
+ async #discover(job, task) {
1174
+ const items = task.followUps ?? [];
1175
+ if (items.length === 0)
1176
+ return;
1177
+ const policy = resolvePolicy("N7", this.#policies(job, task.id)).policy;
1178
+ const live = job.tasks.filter((t) => t.id !== task.id && t.status !== "cancelled");
1179
+ const ctx = {
1180
+ goal: job.goal,
1181
+ acceptance: job.acceptance.map((a) => a.text),
1182
+ task: `${task.id} ${task.title}`,
1183
+ otherTasks: live.map((t) => `${t.id} ${t.title} (files: ${t.files.join(", ") || "none"})`),
1184
+ openFiles: new Set(live.filter((t) => !isDone(t)).flatMap((t) => t.files)),
1185
+ doneFiles: new Set(job.tasks.filter((t) => isDone(t) || t.id === task.id).flatMap((t) => t.files)),
1186
+ };
1187
+ const asked = policy.kind === "rule" || policy.kind === "fixed" ? undefined
1188
+ : await this.#decider.ask("N7", n7State(ctx, items), n7Questions(items), { localOnly: job.flags?.localOnly, job: job.id, task: task.id });
1189
+ // "N7": "fixed:yes" takes every follow-up as a task, "fixed:no" none.
1190
+ const verdicts = policy.kind === "fixed"
1191
+ ? items.map((f) => (policy.value === "no" ? { kind: "later", reason: "out_of_scope" } : f.files.length ? { kind: "task", priority: 3 } : { kind: "later", reason: "no_files" }))
1192
+ : triage(asked?.decision.answers ?? {}, items, ctx);
1193
+ for (const [i, item] of items.entries()) {
1194
+ const v = verdicts[i];
1195
+ if (v.kind === "planned") {
1196
+ this.#journal({ kind: "discovered", job: job.id, from: task.id, what: item.what, dropped: "already planned", decision: asked?.id });
1197
+ continue;
1198
+ }
1199
+ let reason = v.kind === "later" ? v.reason : undefined;
1200
+ // A follow-up is text a model wrote, so it passes the local guards like a goal before it can become a task.
1201
+ if (v.kind === "task") {
1202
+ const guard = await checkGuards(this.#decider, `${item.what}. ${item.why}`, job.id, task.id);
1203
+ if (guard.flagged.includes("sensitive") && !job.flags?.localOnly && this.#d.mode !== "cloud" && !this.#cloudWanted(job)) {
1204
+ job.flags = { ...job.flags, localOnly: true };
1205
+ this.#say(`a follow-up of ${task.id} looks sensitive: the rest of the job stays on this machine`);
1206
+ }
1207
+ if (guard.flagged.includes("injection"))
1208
+ reason = "flagged";
1209
+ else if (job.tasks.filter((t) => t.origin === "discovered").length >= discoveredCap(job))
1210
+ reason = "cap";
1211
+ }
1212
+ if (v.kind === "task" && !reason) {
1213
+ const added = addDiscovered(job, task, item, v.priority);
1214
+ if (added.task) {
1215
+ this.#journal({ kind: "discovered", job: job.id, task: added.task.id, from: task.id, what: item.what, priority: v.priority, decision: asked?.id });
1216
+ this.#say(`${added.task.id} added (found by ${task.id}, priority ${v.priority}): ${item.what}`, true);
1217
+ continue;
1218
+ }
1219
+ job.lessons.push(`follow-up of ${task.id} not added: ${added.errors.slice(0, 2).join("; ")}`);
1220
+ reason = "invalid";
1221
+ }
1222
+ job.later = [...(job.later ?? []), { ...item, from: task.id, reason: reason }];
1223
+ }
1224
+ task.followUps = [];
1225
+ saveJob(this.#d.project, job);
1226
+ }
1227
+ // The job is stalled: the planner rewrites the unfinished part; done tasks and their commits stay.
1228
+ async #replan(job) {
1229
+ moveJob(job, "replan");
1230
+ job.counters.replans++;
1231
+ const model = await this.#requiredModel(job, "plan", 0.7);
1232
+ if (!model)
1233
+ return;
1234
+ this.#say(`replanning (${job.counters.replans} of ${job.budget.replansMax}) with ${model.id}`);
1235
+ const s = await this.#plannerSession(job, model.id);
1236
+ let answer = await this.#ask(s.id, `${HEADER} replanning job ${job.id}\n\nThe user's job: ${job.goal}\n\n${replanFormat(job)}`);
1237
+ let r = answer.stopped || answer.timedOut ? { errors: ["the planner stopped"] } : applyReplan(job, answer.text);
1238
+ if (r.errors && !answer.stopped && !answer.timedOut) {
1239
+ 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.`);
1240
+ r = answer.stopped || answer.timedOut ? { errors: ["the planner stopped"] } : applyReplan(job, answer.text);
1241
+ }
1242
+ if (r.errors) {
1243
+ moveJob(job, "execute");
1244
+ return this.#stop(job, `the replan failed: ${r.errors.slice(0, 3).join("; ")}`);
1245
+ }
1246
+ const cut = job.tasks.filter((t) => !isDone(t) && t.status !== "cancelled");
1247
+ for (const t of cut)
1248
+ moveTask(t, "cancelled");
1249
+ const w = waves([...job.tasks.filter(isDone).map((t) => ({ ...t, dependsOn: t.dependsOn })), ...r.plan.tasks]);
1250
+ job.acceptance = [...r.plan.acceptance];
1251
+ for (const t of r.plan.tasks) {
1252
+ job.tasks.push({
1253
+ id: t.id, title: t.title, description: t.description, role: t.role, acceptance: [...t.acceptance], dependsOn: [...t.dependsOn],
1254
+ files: [...t.files], wave: w.get(t.id) ?? 0, status: "pending", attempts: 0, stages: [], signatures: [],
1255
+ priority: t.priority ?? 3, origin: "replan",
1256
+ });
1257
+ }
1258
+ job.counters.stalls = 0;
1259
+ job.lessons.push(`replanned: ${cut.map((t) => t.id).join(", ")} replaced by ${r.plan.tasks.map((t) => t.id).join(", ")}`);
1260
+ this.#journal({ kind: "replan", job: job.id, cancelled: cut.map((t) => t.id), added: r.plan.tasks.map((t) => t.id) });
1261
+ this.#say(`replanned: ${cut.map((t) => t.id).join(", ")} -> ${r.plan.tasks.map((t) => t.id).join(", ")}`);
1262
+ moveJob(job, "execute");
1263
+ }
1264
+ // N5 + N5b: one request classifies the task and sets its profile; the role may change to one that can do it.
1265
+ async #classify(job, task) {
1266
+ const policies = this.#policies(job, task.id);
1267
+ const acceptance = taskAcceptance(job, task);
1268
+ const skip = resolvePolicy("N5", policies).policy.kind === "rule";
1269
+ const memory = readMemory(this.#d.project);
1270
+ 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 });
1271
+ const profile = combine(task, acceptance, asked, policies, this.#d.skills ?? [], memory);
1272
+ if (profile.role !== task.role)
1273
+ this.#say(`${task.id}: role ${task.role} -> ${profile.role} (${profile.roleReason})`);
1274
+ task.role = profile.role;
1275
+ task.profile = profile;
1276
+ stage(task, "classify", "pass", profileText(profile));
1277
+ saveJob(this.#d.project, job);
1278
+ return profile;
1279
+ }
1280
+ // Worker turns until the task's checks pass: the watchdog's stops, the report, the gate, at most fixRounds fixes,
1281
+ // then the N9 ladder. Returns undefined when the task went to the user or was given up (escalated or blocked).
1282
+ async #untilGreen(job, task, work, checks, frozen) {
1283
+ const worktree = this.#worktree(job, task); // git work
1284
+ const dir = this.#dir(job, task); // the checks name the worker's own paths
1285
+ let lastDiff;
1286
+ let lastFailure;
1287
+ for (;;) {
1288
+ const answer = work.answer;
1289
+ if (answer.stopped?.kind === "handback") {
1290
+ // A checkpoint found the task itself unclear or blocked: no fresh try, the micromanager rethinks it.
1291
+ stage(task, "implement", "fail", answer.stopped.detail);
1292
+ await this.#escalate(job, task, answer.stopped.detail, "", "spec_ambiguous");
1293
+ return undefined;
1294
+ }
1295
+ if (answer.stopped) {
1296
+ // The watchdog stopped it: never resume that session.
1297
+ stage(task, "implement", "fail", `loop watchdog: ${answer.stopped.detail}`);
1298
+ 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)));
1299
+ if (!next)
1300
+ return undefined;
1301
+ [work, lastDiff, lastFailure] = [next, undefined, undefined];
1302
+ continue;
1303
+ }
1304
+ if (!answer.timedOut && refused(answer.text)) {
1305
+ // worker_refused: a safety-tuned model said no. One fresh session on a local uncensored model (design.md §10.2,
1306
+ // §21); until rulebook 3 not for a job the gate had flagged as possibly harmful, a guard the user dropped
1307
+ // because it judged the user's own work (2026-11-25).
1308
+ stage(task, "implement", "fail", `worker_refused: ${answer.text.slice(0, 200)}`);
1309
+ this.#journal({ kind: "watchdog", job: job.id, task: task.id, signal: "worker_refused", model: work.model.id });
1310
+ if (work.uncensored) {
1311
+ await this.#escalate(job, task, "even a local uncensored model refused", answer.text.slice(-1500), "refused");
1312
+ return undefined;
1313
+ }
1314
+ const next = await this.#nextRung(job, task, { ...work, fresh: false }, frozen, "the model refused the task", "", "too_hard", true);
1315
+ if (!next)
1316
+ return undefined;
1317
+ [work, lastDiff, lastFailure] = [next, undefined, undefined];
1318
+ continue;
1319
+ }
1320
+ const report = parseReport(answer.text);
1321
+ collectFollowUps(task, report.followUps);
1322
+ for (const l of report.learned)
1323
+ if (!(task.learned ?? []).includes(l))
1324
+ task.learned = [...(task.learned ?? []), l];
1325
+ stage(task, "implement", answer.timedOut ? "fail" : "pass", answer.timedOut ? "timed out" : `status ${report.status ?? "missing"}`);
1326
+ if (answer.timedOut) {
1327
+ const next = await this.#nextRung(job, task, work, frozen, "the worker timed out", "");
1328
+ if (!next)
1329
+ return undefined;
1330
+ [work, lastDiff, lastFailure] = [next, undefined, undefined];
1331
+ continue;
1332
+ }
1333
+ if (report.status === "BLOCKED" || report.status === "NEEDS_CONTEXT") {
1334
+ moveTask(task, "blocked");
1335
+ task.summary = report.open || report.text.slice(-500);
1336
+ this.#stop(job, `${task.id} needs the user: ${task.summary}`, task);
1337
+ return undefined;
1338
+ }
1339
+ moveTask(task, "gating");
1340
+ const results = [...(await runGate(worktree, checks, this.#exec, this.#checkTimeout(job), dir, { cancelled: () => Boolean(this.#d.cancelled?.()) }, await this.#gate(job, task, worktree, dir))), ...(await frozenCheck(worktree, frozen, this.#exec))];
1341
+ const failed = results.filter((r) => !r.passed);
1342
+ const changed = await changedFiles(worktree, this.#exec, task.worktreeRel ?? job.integrationRel ?? "");
1343
+ const outside = task.files.length ? changed.filter((f) => !task.files.includes(f) && !frozen.has(f)) : changed;
1344
+ stage(task, "gate", failed.length ? "fail" : "pass", `${results.length ? results.map((r) => `${r.command}: exit ${r.code}`).join("; ") : "no checks defined"}${unsandboxedNote(results)}`);
1345
+ saveNote(this.#d.project, job.id, task.id, noteText(task, report.text, results, outside));
1346
+ if (failed.length === 0) {
1347
+ // A gate that only reads exits 0 on an untouched tree, so passing it proves nothing: a worker that wrote
1348
+ // nothing, or died before writing, would otherwise merge as a success (live test, 2026-10-06). Reported apart
1349
+ // from a failing check, because the fix is different -- a passing check set and no diff means the task was
1350
+ // never done, not that it is broken.
1351
+ if (!changed.length) {
1352
+ moveTask(task, "blocked");
1353
+ 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.";
1354
+ this.#stop(job, `${task.id} finished without changing anything: ${task.summary}`, task);
1355
+ return undefined;
1356
+ }
1357
+ return work;
1358
+ }
1359
+ // N8: the same diff as the last round (the worker changed nothing) is a loop; the same failure is one when the
1360
+ // decision model says so, or without one. A loop skips the remaining fix rounds.
1361
+ const diff = createHash("sha1").update(await workingDiff(worktree, this.#exec)).digest("hex").slice(0, 12);
1362
+ // The directory the checks ran in travels with the failure: a check naming a file of the project says "No such
1363
+ // file or directory" without it, and the worker has no way to tell which tree it was run against.
1364
+ const failure = failed.map((f) => `$ ${f.command} (exit ${f.code}) [in ${dir}]\n${f.output.slice(-1500)}`).join("\n\n");
1365
+ const loop = diff === lastDiff || (failure === lastFailure && (await this.#inLoop(job, task, lastFailure, failure)));
1366
+ task.signatures.push(`diff:${diff}`);
1367
+ [lastDiff, lastFailure] = [diff, failure];
1368
+ task.attempts++;
1369
+ if (loop || task.attempts > (this.#d.fixRounds ?? FIX_ROUNDS)) {
1370
+ 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(", ")}`;
1371
+ const next = await this.#nextRung(job, task, work, frozen, why, failure);
1372
+ if (!next)
1373
+ return undefined;
1374
+ [work, lastDiff, lastFailure] = [next, undefined, undefined];
1375
+ continue;
1376
+ }
1377
+ moveTask(task, "fixing");
1378
+ this.#say(`${task.id}: ${failed.length} check(s) failed, fix round ${task.attempts}`);
1379
+ moveTask(task, "running");
1380
+ // fixPrompt is brief.ts's, and it takes the failures as they are; the directory goes in as part of the output.
1381
+ work.answer = await this.#ask(work.s.id, fixPrompt(failed.map((f) => ({ ...f, output: `checked in ${dir}\n${f.output}` }))));
1382
+ }
1383
+ }
1384
+ // N8 with the decision model: is a failure that came back unchanged a loop? Without an answer, yes.
1385
+ async #inLoop(job, task, before, now) {
1386
+ 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 });
1387
+ const a = asked.decision.answers.in_loop;
1388
+ return a?.type === "noul" ? a.noul >= NOUL_FLOOR : true;
1389
+ }
1390
+ // N9 (design.md §10.2): rung 1 is the fix rounds in the same session; rung 2 a fresh session on another model family
1391
+ // with a handoff note; rung 3 the escalation. A budget that is used up skips rung 2.
1392
+ async #nextRung(job, task, work, frozen, reason, details, hint = "too_hard", uncensored = work.uncensored ?? false) {
1393
+ const over = this.#overBudget(job);
1394
+ if (work.fresh || over) {
1395
+ await this.#escalate(job, task, over ?? reason, details, over ? "budget" : hint);
1396
+ return undefined;
1397
+ }
1398
+ const model = await this.#model(job, task.role, task.profile?.difficulty ?? 0.5, task.id, [this.#family(work.model.id)], task.profile?.vision, uncensored);
1399
+ if (!model.routed) {
1400
+ const why = uncensored
1401
+ ? `${reason}, and no local uncensored model is in the ${task.role} pool (${model.reason})`
1402
+ : `${reason}, and no model of the ${task.role} pool fits: ${model.reason}`;
1403
+ await this.#escalate(job, task, why, details, uncensored ? "refused" : hint);
1404
+ return undefined;
1405
+ }
1406
+ task.model = model.id;
1407
+ toRunning(task);
1408
+ task.attempts = 0;
1409
+ stage(task, "escalate", "skip", `rung 2: fresh session on ${model.id} after: ${reason}`);
1410
+ this.#say(`${task.id}: ${reason}; fresh session on ${model.id}`);
1411
+ const s = await this.#workerSession(job, task, model.id);
1412
+ const text = [
1413
+ brief(job, task, model.id, this.#dir(job, task), this.#skills("implement", task)),
1414
+ frozen.size ? greenNote([...frozen.keys()]) : "",
1415
+ handoffText(reason, details, await changedFiles(this.#worktree(job, task), this.#exec)),
1416
+ ].filter(Boolean).join("\n\n");
1417
+ return { s, model, answer: await this.#ask(s.id, text), fresh: true, uncensored };
1418
+ }
1419
+ // P3's red stage: a test worker writes the tests first, and they must fail before anything is built. Returns the
1420
+ // frozen test files with their hashes (empty: no red could be shown, the task goes on as P2), or undefined when
1421
+ // the task went to the user.
1422
+ async #red(job, task, checks) {
1423
+ const worktree = this.#worktree(job, task);
1424
+ const dir = this.#dir(job, task);
1425
+ const model = await this.#requiredModel(job, "test", task.profile?.difficulty ?? 0.5, task);
1426
+ if (!model)
1427
+ return undefined;
1428
+ const s = await this.#workerSession(job, task, model.id, "test");
1429
+ const testFiles = task.files.filter((f) => TEST_FILE.test(f));
1430
+ const answer = await this.#ask(s.id, `${brief(job, task, model.id, dir, this.#skills("red", task))}\n\n${redPrompt(task, testFiles)}`);
1431
+ if (answer.stopped || answer.timedOut) {
1432
+ stage(task, "red", "fail", answer.stopped ? `loop watchdog: ${answer.stopped.detail}` : "timed out");
1433
+ await this.#escalate(job, task, `the tests-first worker ${answer.stopped ? "was stopped by the loop watchdog" : "timed out"}`);
1434
+ return undefined;
1435
+ }
1436
+ const changed = await changedFiles(worktree, this.#exec);
1437
+ const tests = changed.filter((f) => TEST_FILE.test(f) && (testFiles.length === 0 || testFiles.includes(f)));
1438
+ const other = changed.filter((f) => !tests.includes(f));
1439
+ // Only tests in this stage: anything else the worker wrote is undone, the implementation comes after red.
1440
+ await revertFiles(worktree, other, this.#exec);
1441
+ if (tests.length === 0 || checks.length === 0) {
1442
+ stage(task, "red", "skip", tests.length === 0 ? "no tests written" : "no checks to show red with");
1443
+ this.#say(`${task.id}: no red stage (${tests.length === 0 ? "no tests written" : "no checks"}), going on as P2`);
1444
+ return new Map();
1445
+ }
1446
+ const results = await runGate(worktree, checks, this.#exec, this.#checkTimeout(job), dir, {}, await this.#gate(job, task, worktree, dir));
1447
+ if (results.every((r) => r.passed)) {
1448
+ stage(task, "red", "skip", "the new tests pass before the change, so they do not show the missing behaviour");
1449
+ this.#say(`${task.id}: the tests pass before the change; not frozen, going on as P2`);
1450
+ return new Map();
1451
+ }
1452
+ stage(task, "red", "pass", `${tests.join(", ")} fail before the change: ${results.filter((r) => !r.passed).map((r) => r.command).join(", ")}`);
1453
+ return hashFiles(worktree, tests, this.#exec);
1454
+ }
1455
+ // Two reviewers of other model families read the change in parallel (P2, P3; design.md §9): one against the
1456
+ // acceptance points, one against the repository's standards. Only findings with evidence and confidence block; what
1457
+ // they saw outside the task becomes a follow-up. A reviewer whose answer is not JSON after one reminder blocks
1458
+ // nothing.
1459
+ async #review(job, task, workerModel) {
1460
+ const diff = await workingDiff(this.#worktree(job, task), this.#exec);
1461
+ const worker = this.#family(workerModel);
1462
+ const noModel = (why) => ({ checks: [], fixes: [], blocking: [{ point: "review model", met: false, evidence: why, confidence: 100 }], outside: [], error: why });
1463
+ const specModel = await this.#requiredModel(job, "review", task.profile?.difficulty ?? 0.5, task, [worker], task.profile?.vision);
1464
+ if (!specModel)
1465
+ return noModel(job.lessons.at(-1) ?? "no review model");
1466
+ const standardsModel = await this.#requiredModel(job, "review", task.profile?.difficulty ?? 0.5, task, [worker, this.#family(specModel.id)], task.profile?.vision);
1467
+ if (!standardsModel)
1468
+ return noModel(job.lessons.at(-1) ?? "no review model");
1469
+ const skills = skillLine(this.#skills("review", task));
1470
+ const one = async (axis, first, prompt) => {
1471
+ let model = first;
1472
+ let s = await this.#workerSession(job, task, model, "review", TIER_STEPS.S);
1473
+ let answer = await this.#ask(s.id, [prompt, skills].filter(Boolean).join("\n\n"));
1474
+ if (answer.stopped?.kind === "stalled") {
1475
+ // The model stopped answering: once more on another family, so a hanging provider does not skip the review.
1476
+ const again = await this.#requiredModel(job, "review", task.profile?.difficulty ?? 0.5, task, [worker, this.#family(model)], task.profile?.vision);
1477
+ if (!again)
1478
+ return noModel(job.lessons.at(-1) ?? "no review model");
1479
+ model = again.id;
1480
+ this.#say(`${task.id}: the ${axis} reviewer stalled; again on ${model}`);
1481
+ s = await this.#workerSession(job, task, model, "review", TIER_STEPS.S);
1482
+ answer = await this.#ask(s.id, [prompt, skills].filter(Boolean).join("\n\n"));
1483
+ }
1484
+ const confidence = axis === "spec" ? 100 : 0;
1485
+ let 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);
1486
+ if (review.error && !answer.stopped && !answer.timedOut) {
1487
+ answer = await this.#ask(s.id, `${HEADER} Answer again with the JSON only.`);
1488
+ review = parseReview(answer.text, confidence);
1489
+ }
1490
+ saveNote(this.#d.project, job.id, `${task.id}.review-${axis}`, `# ${axis} review of ${task.id} by ${model}\n\n${answer.text}\n`);
1491
+ return review;
1492
+ };
1493
+ const spec = () => one("spec", specModel.id, reviewPrompt(job, task, taskAcceptance(job, task), diff));
1494
+ const standards = () => one("standards", standardsModel.id, standardsPrompt(job, task, diff));
1495
+ // omo-hybrid: the standards axis only for data or security risk, or when the config asks for it.
1496
+ const both = riskAtLeast(task.profile?.risk ?? "internal", "data_security") || resolvePolicy("N6.standards", this.#policies(job, task.id)).level !== undefined;
1497
+ const none = { checks: [], fixes: [], blocking: [], outside: [] };
1498
+ // A local device serves one model at a time, so local reviewers take turns (like P9 readers).
1499
+ const local = [specModel, standardsModel].every((m) => this.#d.registry.find((e) => e.id === m.id)?.location === "local");
1500
+ const [a, b] = !both ? [await spec(), none] : local ? [await spec(), await standards()] : await Promise.all([spec(), standards()]);
1501
+ const merged = mergeReviews(a, b);
1502
+ collectFollowUps(task, merged.outside);
1503
+ const advisory = merged.checks.filter((c) => !c.met && !merged.blocking.includes(c));
1504
+ if (advisory.length)
1505
+ stage(task, "review_notes", "skip", advisory.map((c) => `${c.point} (${c.confidence}): ${c.evidence}`).join("; ").slice(0, 500));
1506
+ return merged;
1507
+ }
1508
+ // P9: parallel readers, one synthesis written to docs/research/, and a citation check by code.
1509
+ async #research(job, task, model) {
1510
+ const worktree = this.#worktree(job, task);
1511
+ const dir = this.#dir(job, task);
1512
+ const n = readerCount(task.profile?.difficulty ?? 0.5);
1513
+ const read = async (i) => {
1514
+ const s = await this.#workerSession(job, task, model, "research");
1515
+ return this.#ask(s.id, [readerPrompt(job, task, i, n), skillLine(this.#skills("reader", task))].filter(Boolean).join("\n\n"));
1516
+ };
1517
+ // Readers run in parallel in the cloud; a local device serves one model at a time, so there they take turns.
1518
+ const local = this.#d.registry.find((m) => m.id === model)?.location === "local";
1519
+ const readers = [];
1520
+ if (local)
1521
+ for (let i = 0; i < n; i++)
1522
+ readers.push(await read(i));
1523
+ else
1524
+ readers.push(...(await Promise.all(Array.from({ length: n }, (_, i) => read(i)))));
1525
+ const answered = readers.filter((r) => !r.stopped && !r.timedOut && r.text).map((r) => r.text);
1526
+ readers.forEach((r, i) => saveNote(this.#d.project, job.id, `${task.id}.reader${i + 1}`, r.text || "(no answer)"));
1527
+ // Readers quote the web; a note that carries an injection never reaches the synthesis (E2b).
1528
+ const notes = [];
1529
+ for (const note of answered) {
1530
+ const score = await injectionScore(this.#decider, note, job.id, task.id);
1531
+ if (!injected(score))
1532
+ notes.push(note);
1533
+ else {
1534
+ this.#journal({ kind: "guard", job: job.id, task: task.id, guard: "injection", score, action: "reader note dropped" });
1535
+ job.lessons.push(`${task.id}: a research note was dropped, it looked like a prompt injection (${score.toFixed(2)})`);
1536
+ }
1537
+ }
1538
+ stage(task, "readers", notes.length ? "pass" : "fail", `${notes.length} of ${n} readers answered`);
1539
+ if (notes.length === 0)
1540
+ return await this.#escalate(job, task, "no research reader came back with findings");
1541
+ const path = researchPath(task);
1542
+ const writerModel = await this.#requiredModel(job, "write", task.profile?.difficulty ?? 0.5, task);
1543
+ if (!writerModel)
1544
+ return;
1545
+ const s = await this.#workerSession(job, task, writerModel.id, "write");
1546
+ let answer = await this.#ask(s.id, synthesisPrompt(job, task, path, notes));
1547
+ for (let round = 0;; round++) {
1548
+ if (answer.stopped || answer.timedOut)
1549
+ return await this.#escalate(job, task, `the synthesis ${answer.stopped ? "was stopped by the loop watchdog" : "timed out"}`);
1550
+ let doc = "";
1551
+ try {
1552
+ doc = readFileSync(join(dir, path), "utf8"); // the writer worked in the project directory, so the doc is there
1553
+ }
1554
+ catch {
1555
+ // checked below: no file means no citations
1556
+ }
1557
+ const check = citationCheck(doc, notes);
1558
+ 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`);
1559
+ if (check.ok)
1560
+ break;
1561
+ if (round >= 1)
1562
+ 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`}`);
1563
+ 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.`}`);
1564
+ }
1565
+ moveTask(task, "gating");
1566
+ const checks = [...new Set(taskAcceptance(job, task).map((a) => a.verify).filter((v) => Boolean(v)))];
1567
+ const failed = (await runGate(worktree, checks, this.#exec, this.#checkTimeout(job), dir, {}, await this.#gate(job, task, worktree, dir))).filter((r) => !r.passed);
1568
+ if (failed.length)
1569
+ return await this.#escalate(job, task, `checks fail after the research (in ${dir}): ${failed.map((f) => f.command).join(", ")}`);
1570
+ moveTask(task, "passed");
1571
+ task.summary = `research written to ${path}`;
1572
+ 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);
1573
+ moveTask(task, "merged");
1574
+ this.#say(`${task.id} researched${commit ? ` (${commit})` : ""}: ${path}`, true);
1575
+ }
1576
+ // The git worktree root of a task: its own in a parallel batch, else the job's. Git commands run here; a worktree is
1577
+ // always a checkout of the repository root, whatever the project is.
1578
+ #worktree(job, task) {
1579
+ return task.worktree ?? job.integrationWorktree;
1580
+ }
1581
+ // Where a task works: the worktree root plus the project's offset inside it, because the worker's paths, its tools and
1582
+ // its checks are all relative to the project directory, not to the repository root.
1583
+ #dir(job, task) {
1584
+ return taskDir(this.#worktree(job, task), task.worktreeRel ?? job.integrationRel ?? "");
1585
+ }
1586
+ #skills(stage, task) {
1587
+ return skillsFor(stage, task.profile, task.pipeline, this.#d.installedSkills ?? new Set());
1588
+ }
1589
+ // OpenCode 2.0.18's plugin session.create drops parentID, so these sessions are not children of the micromanager in
1590
+ // OpenCode's eyes. The metadata names it instead, for the clients that list sessions: oc-voice treats a session with
1591
+ // a parent there as a sub-agent and does not announce it as one of the user's own.
1592
+ #origin(job, task) {
1593
+ return this.#d.parentID ? { metadata: { micromanager: { parent: this.#d.parentID, job: job.id, ...(task ? { task: task.id } : {}) } } } : {};
1594
+ }
1595
+ async #plannerSession(job, model) {
1596
+ const s = await this.#d.session.create({
1597
+ ...(this.#d.parentID ? { parentID: this.#d.parentID } : {}),
1598
+ title: `plan ${job.id}`,
1599
+ agent: roleById("plan").agent,
1600
+ model: toModel(model),
1601
+ location: { directory: this.#d.project },
1602
+ ...this.#origin(job),
1603
+ });
1604
+ // A review of the plan must not run on the family that wrote it (src/plugin.ts reviewSubjects).
1605
+ job.plannerModel = model;
1606
+ job.plannerSession = s.id;
1607
+ this.#syncDiskNotes(job);
1608
+ saveJob(this.#d.project, job);
1609
+ this.#d.watch?.(s.id, 40);
1610
+ return s;
1611
+ }
1612
+ // Pattern 4 — the Blind Plan Council for high-complexity (N1) jobs: one cheap explore model reconnoitres the
1613
+ // project once, then 2-3 proposers (one per model family) draft plans in parallel, then a blind synthesis reads
1614
+ // them anonymized as "Proposal A / B / C" and returns one unified plan. It runs only on the first, unfettered plan
1615
+ // of a job whose triage scored it complex enough; anything less (or a plan pool with a single family) falls back to
1616
+ // the ordinary single-planner loop.
1617
+ async #councilPlan(job, basePrompt, feedback) {
1618
+ if ((job.triage?.complexity ?? 0) < 8)
1619
+ return undefined;
1620
+ if (feedback?.trim() || job.tasks.length !== 0)
1621
+ return undefined;
1622
+ const models = await this.#councilModels(job);
1623
+ if (models.length < 2)
1624
+ return undefined;
1625
+ // Step 1 — one cheap explore model reconnoitres the project once, shared by every proposer.
1626
+ let scoutNote = "";
1627
+ const scoutModel = await this.#model(job, "explore", 0.4);
1628
+ if (scoutModel.routed && scoutModel.id && !this.#isStopped(job)) {
1629
+ const s = await this.#d.session.create({
1630
+ ...(this.#d.parentID ? { parentID: this.#d.parentID } : {}),
1631
+ title: `scout ${job.id}`,
1632
+ agent: roleById("explore").agent,
1633
+ model: toModel(scoutModel.id),
1634
+ location: { directory: this.#d.project },
1635
+ ...this.#origin(job),
1636
+ });
1637
+ this.#d.watch?.(s.id, 40);
1638
+ const answer = await this.#ask(s.id, `${HEADER} scout ${job.id}: reconnoitre the project for this job, read-only.\n\nJob: ${job.goal}\n\nReturn a compact summary under 400 words in four labelled sections — FILES, ARCHITECTURE, CONSTRAINTS, TESTS — that a planner needs before it writes a plan. Change nothing.`);
1639
+ scoutNote = answer.stopped || answer.timedOut ? "" : answer.text;
1640
+ }
1641
+ // Step 2 — parallel, diverse proposals: every proposer answers from a distinct model family.
1642
+ const settled = await Promise.allSettled(models.map(async (m, i) => {
1643
+ if (this.#isStopped(job))
1644
+ return undefined;
1645
+ const s = await this.#d.session.create({
1646
+ ...(this.#d.parentID ? { parentID: this.#d.parentID } : {}),
1647
+ title: `council ${job.id} #${i + 1}`,
1648
+ agent: roleById("plan").agent,
1649
+ model: toModel(m),
1650
+ location: { directory: this.#d.project },
1651
+ ...this.#origin(job),
1652
+ });
1653
+ this.#d.watch?.(s.id, 40);
1654
+ const answer = await this.#ask(s.id, [
1655
+ basePrompt,
1656
+ scoutNote ? `Scout recon (shared by every proposal):\n${scoutNote}` : "",
1657
+ "Council draft mode: do NOT call plan_questions; output only a valid JSON plan matching the schema.",
1658
+ ].filter(Boolean).join("\n\n"));
1659
+ const parsed = answer.stopped || answer.timedOut ? { errors: ["the proposer was stopped or timed out"] } : parsePlan(answer.text);
1660
+ return parsed.plan ? { plan: parsed.plan, raw: answer.text } : undefined;
1661
+ }));
1662
+ const proposals = settled.flatMap((r) => (r.status === "fulfilled" && r.value?.plan ? [r.value] : []));
1663
+ if (this.#isStopped(job))
1664
+ return undefined;
1665
+ if (proposals.length === 0)
1666
+ return undefined;
1667
+ if (proposals.length === 1)
1668
+ return proposals[0].plan;
1669
+ // Step 3 — blind synthesis: the proposals are anonymized as A/B/C so the synthesizer never learns who wrote what.
1670
+ const letters = ["A", "B", "C"];
1671
+ const synthesisPrompt = [
1672
+ `${HEADER} ${proposals.length} independent plans for job ${job.id} were drafted. Judge them blindly and return one unified plan.`,
1673
+ scoutNote ? `Scout recon:\n${scoutNote}` : "",
1674
+ "Evaluate each proposal only by its own merits — architectural soundness, strictly disjoint `files` parallel lanes, no coupled same-file sequential splits, and verification coverage — then return one JSON plan matching the format.",
1675
+ ...proposals.map((p, i) => `--- Proposal ${letters[i]} ---\n${p.raw}`),
1676
+ PLAN_FORMAT,
1677
+ ].filter(Boolean).join("\n\n");
1678
+ const synth = await this.#plannerSession(job, models[0]);
1679
+ if (this.#isStopped(job))
1680
+ return undefined;
1681
+ const answer = await this.#ask(synth.id, synthesisPrompt);
1682
+ const parsed = answer.stopped || answer.timedOut ? { errors: ["the synthesis was stopped or timed out"] } : parsePlan(answer.text);
1683
+ if (parsed.plan) {
1684
+ this.#journal({ kind: "council", job: job.id, proposals: proposals.length, models: models.length });
1685
+ this.#say(`council: ${proposals.length} blind proposals synthesized`);
1686
+ return parsed.plan;
1687
+ }
1688
+ return proposals[0].plan;
1689
+ }
1690
+ // The distinct-family plan models for the council: the plan pool's hard tier, present in the registry and not
1691
+ // reported unreachable, one per family, at most three. Fewer than two families means the council cannot diversify
1692
+ // and the caller falls back to the single planner. The same local/uncensored boundary as route() applies: a
1693
+ // sensitive or uncensored job never proposes through a cloud or censored model.
1694
+ async #councilModels(job) {
1695
+ const plan = roleById("plan");
1696
+ const pool = chain(plan, this.#d.routing?.() ?? DEFAULT_ROUTING, "hard");
1697
+ const availability = await this.#d.availability?.().catch(() => undefined);
1698
+ // A sensitive job (localOnly) or an uncensored job must stay on this machine, exactly as route() enforces it in
1699
+ // registry.ts; an uncensored job also refuses a censored model. An id the registry does not know is not trusted
1700
+ // to stay local (route() routes only registry entries), so it is dropped under either flag.
1701
+ const local = job.flags?.localOnly || job.flags?.uncensored;
1702
+ const uncensored = job.flags?.uncensored;
1703
+ const seen = new Set();
1704
+ const out = [];
1705
+ for (const id of pool) {
1706
+ const entry = this.#d.registry.find((m) => m.id === id);
1707
+ if (entry?.disabled)
1708
+ continue;
1709
+ if (local && entry?.location !== "local")
1710
+ continue;
1711
+ if (uncensored && entry?.censored !== false)
1712
+ continue;
1713
+ if (availability?.get(id)?.reachable === false)
1714
+ continue;
1715
+ const fam = this.#family(id);
1716
+ if (seen.has(fam))
1717
+ continue;
1718
+ seen.add(fam);
1719
+ out.push(id);
1720
+ if (out.length >= 3)
1721
+ break;
1722
+ }
1723
+ return out;
1724
+ }
1725
+ // A worker session: the task's role unless a stage needs another (red: test, review, research readers), with the
1726
+ // profile's narrowed rights as the session's own permission rules (Phase A, A5).
1727
+ async #workerSession(job, task, model, role = task.role, steps) {
1728
+ const rules = role === task.role && task.profile ? narrowing(task.profile) : [];
1729
+ const s = await this.#d.session.create({
1730
+ ...(this.#d.parentID ? { parentID: this.#d.parentID } : {}),
1731
+ title: `${task.id} · ${roleById(role)?.agent ?? role} · ${task.title}`,
1732
+ agent: roleById(role)?.agent ?? "coder",
1733
+ model: toModel(model),
1734
+ location: { directory: this.#dir(job, task) },
1735
+ ...(rules.length ? { permissions: rules } : {}),
1736
+ ...this.#origin(job, task),
1737
+ });
1738
+ task.session = s.id;
1739
+ task.sessions = [...(task.sessions ?? []), s.id];
1740
+ this.#sessionModel.set(s.id, model);
1741
+ this.#d.onWorker?.(s.id, `${task.id} ${task.title}: ${task.description}`, rules);
1742
+ this.#d.watch?.(s.id, steps ?? MAX_STEPS);
1743
+ saveJob(this.#d.project, job);
1744
+ return s;
1745
+ }
1746
+ // N9 rung 3: the task stops, with a typed reason. A task that is too hard as planned does not stop the job: other
1747
+ // tasks go on and the job replans around it (stalls, design.md §10.2). Everything else needs the user.
1748
+ async #escalate(job, task, reason, details = "", hint = "too_hard") {
1749
+ let kind = hint;
1750
+ let decision;
1751
+ // N9 is opt-in ("N9": "auto"): the call site's reason type is good enough by default (omo-hybrid).
1752
+ const n9 = resolvePolicy("N9", this.#policies(job, task.id));
1753
+ if (hint !== "budget" && hint !== "refused" && n9.level !== undefined && n9.policy.kind === "auto") {
1754
+ const asked = await this.#decider.ask("N9", { 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)}` : ""}`) }, { reason: ESCALATE }, { localOnly: job.flags?.localOnly, job: job.id, task: task.id });
1755
+ decision = asked.id;
1756
+ const c = asked.decision.answers.reason;
1757
+ if (c?.type === "choice" && c.confidence >= CHOICE_FLOOR && c.choice in ESCALATION)
1758
+ kind = c.choice;
1759
+ }
1760
+ moveTask(task, "escalated");
1761
+ task.escalation = { kind, detail: reason };
1762
+ job.counters.stalls++;
1763
+ this.#journal({ kind: "escalation", job: job.id, task: task.id, reason, type: kind, decision });
1764
+ if (kind === "too_hard") {
1765
+ job.lessons.push(`${task.id} given up as planned: ${reason}`);
1766
+ this.#say(`${task.id} given up as planned (${reason}); the job goes on and replans around it`, true);
1767
+ if (job.rolling)
1768
+ this.#d.taskEnded?.(job, task);
1769
+ return;
1770
+ }
1771
+ this.#stop(job, `${task.id} (${kind.replace(/_/g, " ")}): ${reason}`, task);
1772
+ }
1773
+ async #verify(job) {
1774
+ moveJob(job, "verify");
1775
+ const checks = [...new Set(job.acceptance.map((a) => a.verify).filter((v) => Boolean(v)))];
1776
+ const results = await runGate(job.integrationWorktree, checks, this.#exec, this.#checkTimeout(job), taskDir(job.integrationWorktree, job.integrationRel ?? ""), {}, await this.#gate(job, undefined, job.integrationWorktree, taskDir(job.integrationWorktree, job.integrationRel ?? "")));
1777
+ const failed = results.filter((r) => !r.passed);
1778
+ if (failed.length > 0) {
1779
+ moveJob(job, "execute");
1780
+ return this.#stop(job, `the final checks fail: ${failed.map((f) => f.command).join(", ")}`);
1781
+ }
1782
+ moveJob(job, "integrate"); // the user merges, keeps or discards the branch
1783
+ this.#say(`all checks pass on ${job.integrationBranch}`);
1784
+ }
1785
+ async sessionUsage(sessionID) {
1786
+ return usage(await this.#d.session.context({ sessionID }));
1787
+ }
1788
+ }
1789
+ export function plannerPrompt(job, repos = [], rootIsRepo = false) {
1790
+ // The planning session's decisions and anything else decided with the user (plan feedback included).
1791
+ const decided = [...(job.designTree ? decisionsText(job.designTree) : []), ...job.decisions.map((d) => d.text)];
1792
+ const repoNote = repos.length === 0
1793
+ ? ""
1794
+ : rootIsRepo
1795
+ ? `This repository also contains nested repositories: ${repos.join(", ")}. Leave "repo" unset for tasks in the root repository, or set "repo" to one of those paths for tasks inside a nested repository; split a task that would need two repositories.`
1796
+ : `This folder holds several repositories: ${repos.join(", ")}. Give every task exactly one "repo" from that list; split a task that would need two.`;
1797
+ return `${HEADER} planning job ${job.id}
1798
+
1799
+ The user's job: ${job.goal}
1800
+ ${verbatimGoalLine(job.goal)}
1801
+ ${decided.length ? `\nDecided with the user (follow these; for assumed points, decide and say what you chose). Every decision must show up in
1802
+ the plan's tasks and acceptance points; a large job gets as many tasks as it needs:\n- ${decided.join("\n- ")}\n` : ""}
1803
+ Read as much of the project as you need (read, glob, grep); change nothing.
1804
+ Verify commands run from the project root in a fresh checkout of the current commit; use only commands that
1805
+ work there, such as the project's own test script.
1806
+ ${repoNote}
1807
+
1808
+ ${PLAN_FORMAT}${planModeRoles(job)}`;
1809
+ }
1810
+ // Back to running from wherever a task's last stage left it, for a fresh session (N9 rung 2).
1811
+ function toRunning(task) {
1812
+ if (task.status === "gating" || task.status === "reviewing")
1813
+ moveTask(task, "fixing");
1814
+ if (task.status !== "running")
1815
+ moveTask(task, "running");
1816
+ }
1817
+ // A worker's follow-ups over all its reports in this task, without repeats.
1818
+ function collectFollowUps(task, items) {
1819
+ if (items.length === 0)
1820
+ return;
1821
+ const seen = new Set((task.followUps ?? []).map((f) => f.what.toLowerCase()));
1822
+ task.followUps = [...(task.followUps ?? []), ...items.filter((f) => !seen.has(f.what.toLowerCase()))];
1823
+ }
1824
+ function noteText(task, report, results, outside) {
1825
+ return [
1826
+ `# ${task.id} ${task.title}`,
1827
+ "",
1828
+ "## Report",
1829
+ report || "(none)",
1830
+ "",
1831
+ "## Checks",
1832
+ ...(results.length ? results.map((r) => `$ ${r.command} (exit ${r.code})\n${r.output}`) : ["none defined"]),
1833
+ ...(outside.length ? ["", `## Changed outside the declared files`, outside.join(", ")] : []),
1834
+ "",
1835
+ ].join("\n");
1836
+ }
1837
+ // What the orchestrator learns when a delegated task ends (omo-hybrid): status and why, the worker's report, the
1838
+ // checks, and its follow-ups with a hint when another task already covers their files.
1839
+ export function taskReport(job, task, state = "the project's state directory") {
1840
+ const open = new Set(job.tasks.filter((t) => t.id !== task.id && !isDone(t) && t.status !== "cancelled").flatMap((t) => t.files));
1841
+ const gate = [...task.stages].reverse().find((s) => s.stage === "gate");
1842
+ 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" : ""}`);
1843
+ 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;
1844
+ return [
1845
+ `${task.id} ${task.title}: ${status}`,
1846
+ task.model ? ` ${task.role} on ${task.model}, ${task.pipeline ?? "P1"}` : "",
1847
+ gate ? ` checks: ${gate.evidence}` : "",
1848
+ task.status === "merged" && task.summary ? ` report: ${task.summary.replace(/\s+/g, " ").slice(-400)}` : "",
1849
+ follow.length ? ` follow-ups the worker found (yours to decide):\n${follow.join("\n")}` : "",
1850
+ task.sessions?.length ? ` sessions: ${task.sessions.join(", ")} (open one with: opencode -s <id>)` : "",
1851
+ ` notes: notes/${job.id}/${task.id}.md in ${state}`,
1852
+ ].filter(Boolean).join("\n");
1853
+ }
1854
+ export function summary(job) {
1855
+ const lines = job.tasks.map((t) => `- ${t.id} ${t.title}: ${t.status}${t.model ? ` (${t.role} on ${t.model}${t.pipeline ? `, ${t.pipeline}` : ""})` : ""}`);
1856
+ const head = `job ${job.id}: ${job.phase}${job.resumePhase ? ` (from ${job.resumePhase})` : ""}`;
1857
+ const branch = job.integrationBranch
1858
+ ? `\nbranch ${job.integrationBranch} in ${job.integrationWorktree}\nmerge: git merge ${job.integrationBranch} · discard: git worktree remove --force ${job.integrationWorktree} && git branch -D ${job.integrationBranch}`
1859
+ : "";
1860
+ const why = job.phase === "ask_user" && job.lessons.length ? `\nwhy: ${job.lessons[job.lessons.length - 1]}` : "";
1861
+ 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")}` : "";
1862
+ return `${head}\n${lines.join("\n")}${branch}${why}${later}`;
1863
+ }
1864
+ // The instruction to draft the design tree; the format is the one parseTree reads.
1865
+ export function draftInstruction(job) {
1866
+ return `[planning session ${job.id}] Before planning, the user's open decisions are settled in a planning session.
1867
+ Draft the design questions this job leaves open and send them with plan_questions (job "${job.id}", tree as a
1868
+ JSON list): [{ "id": "D1", "question": "...", "kind": "decision" | "fact" | "assumption", "dependsOn": [], "impact":
1869
+ "low" | "medium" | "high" }]. Decisions are what only the user can decide (behaviour, scope, interfaces, trade-offs);
1870
+ facts are what agents can look up; at most 25. Write every question open: never list possible answers or examples
1871
+ of answers in it. Do not ask the user anything in this turn, and do not call plan_job again.`;
1872
+ }
1873
+ // The project's top-level entries, as cheap context for triage.
1874
+ function topLevel(project) {
1875
+ try {
1876
+ return readdirSync(project).filter((f) => !f.startsWith(".")).slice(0, 40);
1877
+ }
1878
+ catch {
1879
+ return [];
1880
+ }
1881
+ }
1882
+ // A goal the same session failed to plan a short while ago: the micromanager reports that instead of starting the
1883
+ // same job again (live test: a looping local planner made it restart three times). "retry: <goal>" overrides.
1884
+ export function recentFailure(job, goal, now = Date.now(), windowMs = 30 * 60_000) {
1885
+ if (!job || job.phase !== "failed" || /^retry:/i.test(goal.trim()))
1886
+ return undefined;
1887
+ const same = job.goal.trim().toLowerCase() === goal.trim().toLowerCase();
1888
+ if (!same || now - Date.parse(job.updated) > windowMs)
1889
+ return undefined;
1890
+ const why = job.lessons.at(-1) ?? "unknown reason";
1891
+ 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>".`;
1892
+ }