@omacode/micromanager 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +27 -2
  3. package/evolver/mm_evolve/__init__.py +1 -0
  4. package/evolver/mm_evolve/entry.py +3 -0
  5. package/evolver/mm_evolve/evaluator.py +119 -0
  6. package/evolver/mm_evolve/llm.py +76 -0
  7. package/evolver/mm_evolve/run.py +89 -0
  8. package/evolver/mm_evolve/spec.py +62 -0
  9. package/evolver/pyproject.toml +21 -0
  10. package/evolver/uv.lock +772 -0
  11. package/package.json +55 -4
  12. package/skills/THIRD_PARTY.md +58 -0
  13. package/skills/code-review/SKILL.md +46 -0
  14. package/skills/deliberate/SKILL.md +39 -0
  15. package/skills/diagnosing-bugs/SKILL.md +75 -0
  16. package/skills/receiving-code-review/SKILL.md +36 -0
  17. package/skills/research/SKILL.md +18 -0
  18. package/skills/tdd/SKILL.md +56 -0
  19. package/skills/tdd/mocking.md +59 -0
  20. package/skills/tdd/tests.md +77 -0
  21. package/skills/verification-before-completion/SKILL.md +50 -0
  22. package/src/agenda.ts +56 -0
  23. package/src/agents.ts +74 -0
  24. package/src/ask.ts +243 -0
  25. package/src/backends.ts +144 -0
  26. package/src/backlog.ts +436 -0
  27. package/src/bench.ts +163 -0
  28. package/src/board.ts +1 -0
  29. package/src/brief.ts +151 -0
  30. package/src/browser.ts +624 -0
  31. package/src/budget.ts +73 -0
  32. package/src/catalog.ts +214 -0
  33. package/src/checkchange.ts +180 -0
  34. package/src/checkpoint.ts +99 -0
  35. package/src/cli.ts +117 -0
  36. package/src/compact.ts +162 -0
  37. package/src/config.ts +340 -0
  38. package/src/context/capture.ts +1 -0
  39. package/src/context/digest.ts +1 -0
  40. package/src/context/embed.ts +1 -0
  41. package/src/context/index.ts +2 -0
  42. package/src/context/ledger.ts +1 -0
  43. package/src/context/manager.ts +1 -0
  44. package/src/context/memory.ts +1 -0
  45. package/src/context/policy.ts +1 -0
  46. package/src/context/prices.ts +1 -0
  47. package/src/context/recall.ts +1 -0
  48. package/src/context/rules.ts +1 -0
  49. package/src/context/search.ts +1 -0
  50. package/src/context/status.ts +1 -0
  51. package/src/context/store.ts +1 -0
  52. package/src/context/summary.ts +1 -0
  53. package/src/context/tokens.ts +1 -0
  54. package/src/context/tools.ts +1 -0
  55. package/src/continuation.ts +122 -0
  56. package/src/contract.ts +342 -0
  57. package/src/contractround.ts +225 -0
  58. package/src/control.ts +1 -0
  59. package/src/dataset.ts +133 -0
  60. package/src/decide.ts +690 -0
  61. package/src/eval.ts +66 -0
  62. package/src/evolver.ts +369 -0
  63. package/src/followups.ts +50 -0
  64. package/src/forms.ts +191 -0
  65. package/src/gate.ts +90 -0
  66. package/src/grants.ts +239 -0
  67. package/src/graph.ts +74 -0
  68. package/src/guard/index.ts +1 -0
  69. package/src/guard/wire.ts +1 -0
  70. package/src/helpers.ts +105 -0
  71. package/src/hooks.ts +199 -0
  72. package/src/integration.ts +4 -0
  73. package/src/jev.ts +141 -0
  74. package/src/journal.ts +1 -0
  75. package/src/look.ts +390 -0
  76. package/src/memory.ts +1 -0
  77. package/src/native.ts +2455 -0
  78. package/src/nogit.ts +112 -0
  79. package/src/outcomes.ts +210 -0
  80. package/src/pick.ts +112 -0
  81. package/src/pipelines.ts +252 -0
  82. package/src/plan.ts +449 -0
  83. package/src/plugin.ts +3187 -0
  84. package/src/policy.ts +84 -0
  85. package/src/pools.ts +1 -0
  86. package/src/profile.ts +186 -0
  87. package/src/progress.ts +1 -0
  88. package/src/redact.ts +1 -0
  89. package/src/registry.ts +207 -0
  90. package/src/roles.ts +1 -0
  91. package/src/routing.ts +1 -0
  92. package/src/runner.ts +1506 -0
  93. package/src/sandbox.ts +4 -0
  94. package/src/scheduler.ts +200 -0
  95. package/src/session.ts +269 -0
  96. package/src/shell/decide.ts +1 -0
  97. package/src/shell/index.ts +2 -0
  98. package/src/shell/sandbox.ts +1 -0
  99. package/src/shell/wire.ts +1 -0
  100. package/src/skills.ts +111 -0
  101. package/src/state.ts +1 -0
  102. package/src/store.ts +1 -0
  103. package/src/switcher.ts +1 -0
  104. package/src/tools.ts +480 -0
  105. package/src/trials.ts +247 -0
  106. package/src/usage.ts +1 -0
  107. package/src/wait.ts +180 -0
  108. package/src/watchdog.ts +498 -0
  109. package/src/worktree/git.ts +378 -0
package/src/tools.ts ADDED
@@ -0,0 +1,480 @@
1
+ // The micromanager's tools (Phase A, A3: custom tools work, with text content as their result). Only the micromanager
2
+ // agent may use them; every other agent gets a refusal, and the context hook hides them from other agents.
3
+ // A role agent can still reach them through the code-mode execute tool; the nested call carries the caller's
4
+ // agent (Phase E spike), so the same check refuses it. A call without an agent is refused too.
5
+ //
6
+ // The descriptions here are also how the orchestrator learns what it may do: the micromanager's own system prompt
7
+ // (src/roles.ts micromanagerSystem) names stop_job and plan_job only, so every control below carries its own rule
8
+ // (when to use it, what it refuses, what it leaves behind) in the line the model always sees.
9
+
10
+ import type { Job } from "./state.ts"
11
+ import type { ToolContext, ToolDraft } from "@omacode/core/tools"
12
+ export type { ToolContext, ToolDraft }
13
+
14
+ export const TOOL_IDS = [
15
+ "list_tasks", "plan_job", "plan_questions", "run_job", "job_status", "stop_job",
16
+ // The controls a run showed were missing: one task at a time, the job branch, the worktrees behind it, and a vouch.
17
+ "steer_task", "stop_task", "merge_job", "discard_job", "request_access",
18
+ // A worker's paused permission request, answered (src/ask.ts).
19
+ "answer_permission",
20
+ // Checkpoints: the job branch back to an earlier state, and the last merge_job taken back.
21
+ "rewind_job", "undo_merge",
22
+ // An earlier session's open job, made this session's.
23
+ "take_over_job",
24
+ // The micromanager's todo list, kept in its job (src/native.ts todo).
25
+ "todo",
26
+ // What "better" means for a task with no fixed end (src/contract.ts).
27
+ "contract",
28
+ // Jobs that wait, in the project (src/backlog.ts).
29
+ "backlog",
30
+ // A writer's request to change a check, decided (src/checkchange.ts).
31
+ "decide_change",
32
+ // A fitness contract worked out with the user before it measures anyone (src/contractround.ts).
33
+ "contract_round",
34
+ // OpenEvolve on one block of code, measured by a frozen contract (src/evolver.ts).
35
+ "evolve_task",
36
+ ] as const
37
+
38
+ // The tool draft of ctx.tool.transform, as far as this file uses it.
39
+ export interface Handlers {
40
+ tasks(id: string, ctx: ToolContext): Promise<string>
41
+ plan(goal: string, ctx: ToolContext): Promise<string>
42
+ questions(job: string, tree: string, ctx: ToolContext): Promise<string>
43
+ run(job: string, note: string, ctx: ToolContext): Promise<string>
44
+ status(job: string, ctx: ToolContext): Promise<string>
45
+ stop(job: string, ctx: ToolContext): Promise<string>
46
+ steer(id: string, text: string, ctx: ToolContext): Promise<string>
47
+ stopTask(id: string, ctx: ToolContext): Promise<string>
48
+ merge(job: string, ack: string, ctx: ToolContext): Promise<string>
49
+ discard(job: string, ack: string, ctx: ToolContext): Promise<string>
50
+ access(path: string, why: string, ctx: ToolContext): Promise<string>
51
+ permission(id: string, decision: string, note: string, ctx: ToolContext): Promise<string>
52
+ rewind(job: string, to: string, ack: string, ctx: ToolContext): Promise<string>
53
+ undoMerge(job: string, ack: string, ctx: ToolContext): Promise<string>
54
+ takeOver(job: string, ctx: ToolContext): Promise<string>
55
+ todo(items: string, ctx: ToolContext): Promise<string>
56
+ contract(job: string, json: string, ctx: ToolContext): Promise<string>
57
+ backlog(action: string, slug: string, value: string, ctx: ToolContext): Promise<string>
58
+ decideChange(id: string, decision: string, note: string, ctx: ToolContext): Promise<string>
59
+ contractRound(job: string, goal: string, input: string, ctx: ToolContext): Promise<string>
60
+ evolve(job: string, json: string, ctx: ToolContext): Promise<string>
61
+ }
62
+
63
+ export function installTools(draft: ToolDraft, handlers: Handlers, agent = "micromanager", runnerSession: (id: string) => boolean = () => false): string[] {
64
+ // A schema must come from the server's own Effect instance (Phase 0), so it is built from a built-in tool's.
65
+ const read = draft.get("read")
66
+ const str = read?.input?.fields?.path
67
+ if (!read?.input?.mapFields || !str) throw new Error("the built-in read tool has no input schema to build from")
68
+ const input = (...names: string[]) => read.input!.mapFields!(() => Object.fromEntries(names.map((n) => [n, str])))
69
+ const guarded = (fn: (values: string[], ctx: ToolContext) => Promise<string>, ...names: string[]) =>
70
+ async (args: Record<string, unknown>, ctx: ToolContext) => {
71
+ if (ctx?.agent !== agent || (ctx.sessionID !== undefined && runnerSession(ctx.sessionID))) return { content: `Only the ${agent} agent may use this tool.` }
72
+ try {
73
+ return { content: await fn(names.map((n) => String(args?.[n] ?? "")), ctx ?? {}) }
74
+ } catch (err) {
75
+ return { content: `failed: ${err instanceof Error ? err.message : String(err)}` }
76
+ }
77
+ }
78
+ draft.add({
79
+ id: "list_tasks",
80
+ name: "list_tasks",
81
+ description: "The tasks you started in this session with their status, worker session and branch, or with a task id its stages (checks, merge) and summary.",
82
+ input: input("id"),
83
+ execute: guarded(([id], ctx) => handlers.tasks(id!, ctx), "id"),
84
+ })
85
+ draft.add({
86
+ id: "plan_job",
87
+ name: "plan_job",
88
+ description: "For a large or unclear job only (most work goes to workers through the subagent tool): a planner reads the project and writes a full plan with acceptance points, which the user approves before run_job. With the user's goal: checks it and plans it, or opens a planning session when the user asked to plan it together. With a job id as goal: continues that job. When a plan waits for the user's go and they want changes, call it with their change request as goal: the planner writes the plan again with it. Changes nothing.",
89
+ input: input("goal"),
90
+ execute: guarded(([goal], ctx) => handlers.plan(goal!, ctx), "goal"),
91
+ })
92
+ draft.add({
93
+ id: "plan_questions",
94
+ name: "plan_questions",
95
+ description: "Send the design questions of a planning session (or new ones found later) for a job: tree is a JSON list of { id, question, kind, dependsOn, impact }. Returns the one question to ask the user next.",
96
+ input: input("job", "tree"),
97
+ execute: guarded(([job, tree], ctx) => handlers.questions(job!, tree!, ctx), "job", "tree"),
98
+ })
99
+ draft.add({
100
+ id: "run_job",
101
+ name: "run_job",
102
+ description: "Run a planned job after the user said go, or resume a paused one. Takes the job id from plan_job; note is the user's answer when the job stopped for them (their words, or empty). Answers with the planned tasks to start now: start each with the subagent tool exactly as listed, in one message. Later [micromanager] job notes name the next ones as workers end; do not wait or poll.",
103
+ input: input("job", "note"),
104
+ execute: guarded(([job, note], ctx) => handlers.run(job!, note!, ctx), "job", "note"),
105
+ })
106
+ draft.add({
107
+ id: "job_status",
108
+ name: "job_status",
109
+ description: "Show the queue and an ASCII board of a job: each task with its state, role, model and what it does now, the usage, and what was found but not done. Show the board to the user in a code block as it is. An empty job id shows the newest job.",
110
+ input: input("job"),
111
+ execute: guarded(([job], ctx) => handlers.status(job!, ctx), "job"),
112
+ })
113
+ draft.add({
114
+ id: "stop_job",
115
+ name: "stop_job",
116
+ description: "Stop a job when the user asks: the running worker is interrupted, and the job pauses; run_job resumes it later. A waiting job leaves the queue. An empty job id stops the running job.",
117
+ input: input("job"),
118
+ execute: guarded(([job], ctx) => handlers.stop(job!, ctx), "job"),
119
+ })
120
+ draft.add({
121
+ id: "steer_task",
122
+ name: "steer_task",
123
+ description: "Send a note to a worker that is still running, without interrupting it: id is a task id (list_tasks), text is what the worker should know, in a sentence. The note reaches it as a system block at its next turn, so it finishes what it is doing first. Use it when the user changes their mind about a task, or when a report tells you what to fix next. A worker that already ended cannot be steered: the answer then names its sessionID to continue it with the subagent tool.",
124
+ input: input("id", "text"),
125
+ execute: guarded(([id, text], ctx) => handlers.steer(id!, text!, ctx), "id", "text"),
126
+ })
127
+ draft.add({
128
+ id: "stop_task",
129
+ name: "stop_task",
130
+ description: "Stop one task's worker and leave the rest of the job running; use it when the user says one worker is stuck, wrong or not needed any more. Its worktree and whatever it wrote stay exactly where they are, and the answer names them, so nothing is lost. When it was the last running task, the job ends like a stopped one.",
131
+ input: input("id"),
132
+ execute: guarded(([id], ctx) => handlers.stopTask(id!, ctx), "id"),
133
+ })
134
+ draft.add({
135
+ id: "merge_job",
136
+ name: "merge_job",
137
+ description: "Bring a finished job's branch into the user's checkout, the one write you may make there. It shows the commits that would land, refuses a checkout with uncommitted changes and a job with unfinished or failed tasks (ack then carries the user's own words that this is fine), and merges fast-forward only. It never forces, resets or throws work away: without a fast-forward it says so and leaves the checkout as it was. Afterwards discard_job drops the branch and its worktrees.",
138
+ input: input("job", "ack"),
139
+ execute: guarded(([job, ack], ctx) => handlers.merge(job!, ack!, ctx), "job", "ack"),
140
+ })
141
+ draft.add({
142
+ id: "discard_job",
143
+ name: "discard_job",
144
+ description: "Give a job's branch and worktrees back to git: git worktree remove --force and git branch -D for each of them. Without ack it only lists what it would delete; with the user's words in ack it deletes that and reports what went and what stayed. Your checkout and every file in it are never touched. Use it when the user does not want the job's work any more, or after merge_job.",
145
+ input: input("job", "ack"),
146
+ execute: guarded(([job, ack], ctx) => handlers.discard(job!, ack!, ctx), "job", "ack"),
147
+ })
148
+ draft.add({
149
+ id: "request_access",
150
+ name: "request_access",
151
+ description: "Vouch that a worker of this job legitimately needs a path outside the project: path with its full path, why in one sentence for the user. From then on a worker that only reads may read it without asking again; writing there still goes to the user. A path the plugin refuses by default — the user's keys, credentials, home and the system directories — is not a refusal but a question: calling this with one returns the question to put to the user word for word, and their answer on the next turn opens it for this job or leaves it closed. End your turn after showing it.",
152
+ input: input("path", "why"),
153
+ execute: guarded(([path, why], ctx) => handlers.access(path!, why!, ctx), "path", "why"),
154
+ })
155
+ draft.add({
156
+ id: "answer_permission",
157
+ name: "answer_permission",
158
+ description: "Answer a worker's paused permission request (a note \"[micromanager] A…: worker … is paused\" names it). id: the A-number. decision: once (let this call run), job (also this exact request for the rest of the job) or refuse. note: for a refusal, why, in one sentence for the worker. Allow only what clearly serves the worker's task and reaches nothing outside the project; anything else is the user's to decide, and a hard rule always is.",
159
+ input: input("id", "decision", "note"),
160
+ execute: guarded(([id, decision, note], ctx) => handlers.permission(id!, decision!, note!, ctx), "id", "decision", "note"),
161
+ })
162
+ draft.add({
163
+ id: "rewind_job",
164
+ name: "rewind_job",
165
+ description: "Move a job's branch back to a checkpoint: \"start\", the state after a merged task (\"T3\"), or \"before-rewind-<n>\" (a rewind undone). job: the job id, or empty for this session's job. to: empty lists the checkpoints and changes nothing. Without ack it shows what would leave the branch and which unfinished tasks would be given up, and changes nothing; with ack (the user's own words, repeated) it moves the branch, keeps the old tip as before-rewind-<n>, and deletes the unfinished tasks' worktrees. Refused while a worker of the job runs. The user's checkout is never touched (undo_merge).",
166
+ input: input("job", "to", "ack"),
167
+ execute: guarded(([job, to, ack], ctx) => handlers.rewind(job!, to!, ack!, ctx), "job", "to", "ack"),
168
+ })
169
+ draft.add({
170
+ id: "take_over_job",
171
+ name: "take_over_job",
172
+ description: "Make an earlier micromanager session's open job this session's, after the user chose to continue it: new workers land on its branch, its unfinished workers are continued with the subagent tool and their sessionID, and their notes and permission requests come here. job: the job id the plugin's note named. Refused when this session started a job of its own already.",
173
+ input: input("job"),
174
+ execute: guarded(([job], ctx) => handlers.takeOver(job!, ctx), "job"),
175
+ })
176
+ draft.add({
177
+ id: "todo",
178
+ name: "todo",
179
+ description: "Your todo list, kept in your job so it is never lost: write down the tasks you mean to start before you start them, and start each later with the subagent tool and the prompt line \"Task: T… · job-…\" (plus anything to add below it); the plugin fills in its brief, files and checks. items: a JSON list of {\"title\", \"agent\" (a role agent, coder if left out), \"files\" (what a writer may change, comma separated), \"checks\" (shell commands, one per line), \"after\" ([task ids it waits for, e.g. [\"T1\", \"T2\"]]), \"brief\" (what the worker needs to know), \"replaces\" ([ids of failed or stopped tasks it does over, e.g. [\"T19\"], or [\"job-…/T18\"] for one of an older job])}; an entry {\"drop\": [\"T5\"]} removes open todos that are not needed any more. Empty: it only shows the list. When a worker ends, a note names the todos that can start.",
180
+ input: input("items"),
181
+ execute: guarded(([items], ctx) => handlers.todo(items!, ctx), "items"),
182
+ })
183
+ draft.add({
184
+ id: "contract",
185
+ name: "contract",
186
+ description: "Define what \"better\" means before a writer works on a task with no fixed end (make X faster, smaller, more reliable): such a writer is refused without one. json: {\"goal\": what the work is for, in words; \"evaluator\": a shell command that prints one line MM_SCORE {\"scores\": {\"<name>\": <number>, …}} (exit 0; anything else counts as an invalid result); \"scores\": [{\"name\", \"direction\": \"min\"|\"max\", \"noise\": 0.05}] (the first decides, the next break ties inside its noise band); \"guards\": [{\"name\", \"direction\", \"tolerance\": 0.2}] (measured values that may not get worse than today by more than that share: they close the ways to raise a score without improving the goal); \"corpus\": {\"visible\": [paths it measures on]}; \"repeats\": runs per measurement, the median counts (3 for timings); \"timeoutSeconds\"; \"stop\": {\"evaluations\": n, \"seconds\": s}}. With \"id\": \"C1\" it changes that contract (a new version). The plugin measures the baseline on the job's branch now and answers with it; a writer is then measured with a line \"Contract: C1\" in its prompt (or \"contract\" in its todo). job: empty for this session's job.",
187
+ input: input("job", "json"),
188
+ execute: guarded(([job, json], ctx) => handlers.contract(job!, json!, ctx), "job", "json"),
189
+ })
190
+ draft.add({
191
+ id: "backlog",
192
+ name: "backlog",
193
+ description: "The project's backlog: jobs that wait, one file each in .micromanager/backlog/ (the user commits them). action \"list\" shows them in the order they run; \"show\" with slug shows one; \"add\" with value a JSON object {\"title\", \"kind\": \"build\"|\"fix\"|\"optimize\", \"goal\", \"acceptance\": [{\"text\", \"verify\"}], \"checks\": [shell commands], \"fitness\": a contract as the contract tool takes it, \"order\", \"status\": \"draft\"|\"ready\"} writes a new one (add only what the user asked to keep for later); \"set\" with slug and value \"status=ready\" or \"order=10\" changes one; \"publish\" with slug hands you the form that asks the user whether to make it a GitHub issue (only where the user opted the repository in). In an opted-in repository the list also shows its issues labelled micromanager, as gh-<number>. A job's follow-ups that no task took up become drafts by themselves when the job is merged or discarded. Start an item with plan_job and the goal \"backlog:<slug>\", or write its tasks as todos.",
194
+ input: input("action", "slug", "value"),
195
+ execute: guarded(([action, slug, value], ctx) => handlers.backlog(action!, slug!, value!, ctx), "action", "slug", "value"),
196
+ })
197
+ draft.add({
198
+ id: "evolve_task",
199
+ name: "evolve_task",
200
+ description: "Improve one block of code by evolution (OpenEvolve) instead of a worker: many small model-written variants, each measured by a frozen fitness contract, the best one merged through the usual checks. Suits a single function or block, even one whose contract measures in minutes (give the contract a quick stage then, so most variants are judged in seconds); not a change across many files, and not a search for parameter values. json: {\"contract\": \"C1\" (frozen), \"file\": the file, \"block\": the function's name or a line range like \"12-40\" (ask an explorer which block it is), \"checks\": [shell commands that must still pass, e.g. the tests], \"iterations\": how many variants (default 30)}. It runs in the background in the sandbox; job_status shows its progress, and a note comes when it ends. job: empty for this session's job.",
201
+ input: input("job", "json"),
202
+ execute: guarded(([job, json], ctx) => handlers.evolve(job!, json!, ctx), "job", "json"),
203
+ })
204
+ draft.add({
205
+ id: "contract_round",
206
+ name: "contract_round",
207
+ description: "Work out a fitness contract with the user before any writer is measured against it; a writer's \"Contract: C…\" line is refused until its contract is frozen. With goal (what to make better) and no input: answers with the prompt for a planner that drafts the contract. With input the planner's contract JSON (or a draft's id, \"C1\"): stores it, measures its baseline, and answers with the form for the user's preferences. The plugin goes on by itself from the user's answers: the red team (a coder you start with the line \"Red team: C… · job-…\"), the loopholes to close, the baseline check, the freeze; follow the notes it gives you. job: empty for this session's job.",
208
+ input: input("job", "goal", "input"),
209
+ execute: guarded(([job, goal, inp], ctx) => handlers.contractRound(job!, goal!, inp!, ctx), "job", "goal", "input"),
210
+ })
211
+ draft.add({
212
+ id: "decide_change",
213
+ name: "decide_change",
214
+ description: "Decide a worker's request to change a check or a frozen test (a note \"[micromanager] K…: worker … asks to change …\" names it). id: the K-number. decision: accept (the plugin applies the proposed change, freezes it again and gives it to every attempt of the task) or refuse (it stays as it is for this job). note: why, in one sentence for the worker. Accept a check that is wrong in itself; refuse one that only fails because the work is not done. A request the note says only the user decides goes to them with its form instead.",
215
+ input: input("id", "decision", "note"),
216
+ execute: guarded(([id, decision, note], ctx) => handlers.decideChange(id!, decision!, note!, ctx), "id", "decision", "note"),
217
+ })
218
+ draft.add({
219
+ id: "undo_merge",
220
+ name: "undo_merge",
221
+ description: "Take back the last merge_job of a job: the user's checkout goes back to where it was before that merge. Only while the checkout is exactly where the merge left it and has no uncommitted changes. job: the job id, or empty for this session's job. Without ack it shows which commits would leave the checkout and changes nothing; with ack (the user's own words, repeated) it moves it back. The commits stay on the job branch; merge_job brings them back.",
222
+ input: input("job", "ack"),
223
+ execute: guarded(([job, ack], ctx) => handlers.undoMerge(job!, ack!, ctx), "job", "ack"),
224
+ })
225
+ return [...TOOL_IDS]
226
+ }
227
+
228
+ // A worker's last step (src/native.ts): the plugin runs the task's checks, commits and merges. Only the sessions of
229
+ // writers the micromanager started may use it; the context hook hides it from every other session.
230
+ export const FINISH_ID = "finish_task"
231
+
232
+ export function installFinishTool(draft: ToolDraft, finish: (summary: string, ctx: ToolContext) => Promise<string>, writer: (sessionID: string) => boolean): void {
233
+ const read = draft.get("read")
234
+ const str = read?.input?.fields?.path
235
+ if (!read?.input?.mapFields || !str) throw new Error("the built-in read tool has no input schema to build from")
236
+ draft.add({
237
+ id: FINISH_ID,
238
+ name: FINISH_ID,
239
+ description: "Call this when your change is done: the plugin runs the task's checks in your directory, commits and merges your change. summary: what you changed, in two lines. If it answers with failures, fix them and call it again; once it says merged, end with your short report.",
240
+ input: read.input.mapFields(() => ({ summary: str })),
241
+ execute: async (args: Record<string, unknown>, ctx: ToolContext) => {
242
+ if (!ctx?.sessionID || !writer(ctx.sessionID)) return { content: "Only a worker that changes files for the micromanager may use this tool." }
243
+ try {
244
+ return { content: await finish(String(args?.summary ?? ""), ctx) }
245
+ } catch (err) {
246
+ return { content: `failed: ${err instanceof Error ? err.message : String(err)}` }
247
+ }
248
+ },
249
+ })
250
+ }
251
+
252
+ // An explorer's code graph (src/graph.ts): who calls, uses or imports what, from the syntax tree. Only explorers the
253
+ // micromanager started with a graph may use it; the context hook hides it from every other session.
254
+ export const GRAPH_ID = "code_graph"
255
+
256
+ export function installGraphTool(draft: ToolDraft, ask: (args: { action: string; symbol: string; to: string }, ctx: ToolContext) => Promise<string>, allowed: (sessionID: string) => boolean): void {
257
+ const read = draft.get("read")
258
+ const str = read?.input?.fields?.path
259
+ if (!read?.input?.mapFields || !str) throw new Error("the built-in read tool has no input schema to build from")
260
+ draft.add({
261
+ id: GRAPH_ID,
262
+ name: GRAPH_ID,
263
+ description: "Ask the code graph of your directory, built from the syntax tree of every file. action: explain (a symbol: where it is defined, what calls it, what it calls), affected (what depends on a symbol, two levels deep), path (how symbol reaches to), query (symbols whose names match the words in symbol). symbol: a function, class, method or file name, e.g. instruction_language or server.py. to: the second symbol for path, else empty. Use it before grep for any who-calls or what-uses question.",
264
+ input: read.input.mapFields(() => ({ action: str, symbol: str, to: str })),
265
+ execute: async (args: Record<string, unknown>, ctx: ToolContext) => {
266
+ if (!ctx?.sessionID || !allowed(ctx.sessionID)) return { content: "Only an explorer of the micromanager may use this tool." }
267
+ try {
268
+ return { content: await ask({ action: String(args?.action ?? ""), symbol: String(args?.symbol ?? ""), to: String(args?.to ?? "") }, ctx) }
269
+ } catch (err) {
270
+ return { content: `failed: ${err instanceof Error ? err.message : String(err)}` }
271
+ }
272
+ },
273
+ })
274
+ }
275
+
276
+ // A writer's helpers (src/helpers.ts): an explorer or a researcher answers one question while the writer waits. Only the
277
+ // writers the micromanager started may use them; the context hook hides them from every other session, the helpers
278
+ // themselves included, so a helper never asks a helper.
279
+ export const HELPER_IDS = { explore: "explore", research: "research" } as const
280
+
281
+ export function installHelperTools(draft: ToolDraft, ask: (role: "explore" | "research", question: string, ctx: ToolContext) => Promise<string>, allowed: (sessionID: string) => boolean): void {
282
+ const read = draft.get("read")
283
+ const str = read?.input?.fields?.path
284
+ if (!read?.input?.mapFields || !str) throw new Error("the built-in read tool has no input schema to build from")
285
+ const descriptions = {
286
+ explore: "Ask an explorer one question about the code and wait for its answer: who calls or uses something, where a thing is defined, how a part works, what the history says. It reads your directory as it is now, your uncommitted change included. Use it for a question that would take you many reads; for one file, read it yourself. question: one question in a sentence. At most 3 helpers per task.",
287
+ research: "Ask a researcher one question that needs the web and wait for its answer: an API's documentation, a library's behaviour, an error message, a current version. It cites its sources. question: one question in a sentence. At most 3 helpers per task.",
288
+ }
289
+ for (const role of ["explore", "research"] as const) {
290
+ draft.add({
291
+ id: HELPER_IDS[role],
292
+ name: HELPER_IDS[role],
293
+ description: descriptions[role],
294
+ input: read.input.mapFields(() => ({ question: str })),
295
+ execute: async (args: Record<string, unknown>, ctx: ToolContext) => {
296
+ if (!ctx?.sessionID || !allowed(ctx.sessionID)) return { content: "Only a worker that changes files for the micromanager may ask a helper." }
297
+ try {
298
+ return { content: await ask(role, String(args?.question ?? ""), ctx) }
299
+ } catch (err) {
300
+ return { content: `failed: ${err instanceof Error ? err.message : String(err)}` }
301
+ }
302
+ },
303
+ })
304
+ }
305
+ }
306
+
307
+ // A worker's request for a variable or a host its sandbox keeps from it (src/grants.ts). The call waits until it is
308
+ // decided: at once for what the plugin or Jev decides, up to ten minutes for the user's form. Every worker of the
309
+ // micromanager may ask for a variable; only writers and researchers for a host. The context hook hides each tool from
310
+ // every other session.
311
+ export const GRANT_IDS = { env: "request_env", network: "request_network" } as const
312
+
313
+ export function installGrantTools(draft: ToolDraft, request: (kind: "env" | "network", name: string, why: string, ctx: ToolContext) => Promise<string>, allowed: (kind: "env" | "network", sessionID: string) => boolean): void {
314
+ const read = draft.get("read")
315
+ const str = read?.input?.fields?.path
316
+ if (!read?.input?.mapFields || !str) throw new Error("the built-in read tool has no input schema to build from")
317
+ const tools = {
318
+ env: { field: "name", description: "Ask for an environment variable your shell commands do not get: they start with a cleaned environment (PATH, HOME, locale and the usual toolchain variables only). Use it when a command fails because a variable is not set, e.g. DATABASE_URL for the integration tests. name: the variable's name only; you never see its value. why: what needs it, in one sentence for the user. The call waits until it is decided, up to ten minutes when the user has to answer; once granted, every command you start has it." },
319
+ network: { field: "domain", description: "Ask for a host your shell commands cannot reach: they reach the package registries only. Use it when a command fails to connect, e.g. a build that downloads from github.com. domain: the host, like api.example.com (or *.example.com), without scheme or path. why: what needs it, in one sentence for the user. The call waits until it is decided, up to ten minutes when the user has to answer." },
320
+ }
321
+ for (const kind of ["env", "network"] as const) {
322
+ const { field, description } = tools[kind]
323
+ draft.add({
324
+ id: GRANT_IDS[kind],
325
+ name: GRANT_IDS[kind],
326
+ description,
327
+ input: read.input.mapFields(() => ({ [field]: str, why: str })),
328
+ execute: async (args: Record<string, unknown>, ctx: ToolContext) => {
329
+ if (!ctx?.sessionID || !allowed(kind, ctx.sessionID)) return { content: "Only a worker of the micromanager may use this tool." }
330
+ try {
331
+ return { content: await request(kind, String(args?.[field] ?? "").trim(), String(args?.why ?? "").trim(), ctx) }
332
+ } catch (err) {
333
+ return { content: `failed: ${err instanceof Error ? err.message : String(err)}` }
334
+ }
335
+ },
336
+ })
337
+ }
338
+ }
339
+
340
+ // A visual worker's eyes (src/look.ts): a page, an svg or an image of its directory as a picture, rendered by the
341
+ // plugin outside the sandbox. The context hook hides it from every session that is no designer of the micromanager.
342
+ export const LOOK_ID = "look"
343
+
344
+ export function installLookTool(draft: ToolDraft, look: (args: Record<string, string>, ctx: ToolContext) => Promise<{ text: string; image?: { data: Buffer; mime: string } }>, allowed: (sessionID: string) => boolean): void {
345
+ const read = draft.get("read")
346
+ const str = read?.input?.fields?.path
347
+ if (!read?.input?.mapFields || !str) throw new Error("the built-in read tool has no input schema to build from")
348
+ const fields = ["path", "url", "width", "height", "full", "settle"] as const
349
+ draft.add({
350
+ id: LOOK_ID,
351
+ name: LOOK_ID,
352
+ description: "See your work as a picture. path: a page (.html), an svg, an image, or a directory with an index.html, relative to your directory; or url: a page on a host this job may reach. width: the window width in px (default 1280; try 390 for a phone). height: the window height (default 800). full: false for only the first screen instead of the whole page. settle: milliseconds to wait after fonts load for animations or late layout (default 300, at most 10000). A page is served from its own directory, so a built dist/ page's absolute /assets/... paths resolve correctly; build first if the project has a build step. Every field must be given: pass \"\" for the ones you do not need.",
353
+ input: read.input.mapFields(() => Object.fromEntries(fields.map((f) => [f, str]))),
354
+ execute: async (args: Record<string, unknown>, ctx: ToolContext) => {
355
+ if (!ctx?.sessionID || !allowed(ctx.sessionID)) return { content: "Only a designer of the micromanager may use this tool." }
356
+ try {
357
+ const r = await look(Object.fromEntries(fields.map((f) => [f, String(args?.[f] ?? "")])), ctx)
358
+ if (!r.image) return { content: r.text }
359
+ const ext = r.image.mime.split("/")[1] ?? "png"
360
+ return { content: [{ type: "text", text: r.text }, { type: "file", uri: `data:${r.image.mime};base64,${r.image.data.toString("base64")}`, mime: r.image.mime, name: `look.${ext}` }] }
361
+ } catch (err) {
362
+ return { content: `failed: ${err instanceof Error ? err.message : String(err)}` }
363
+ }
364
+ },
365
+ })
366
+ }
367
+
368
+ // A visual worker's hands (src/browser.ts): a real Playwright browser on the host, driven by a list of steps, so a
369
+ // worker can click, fill and route through the page it built and record the run. Same boundary as look: the page comes
370
+ // from the worker's own directory, the hosts are the job's, and no worker code runs as host JavaScript.
371
+ export const BROWSER_ID = "playwright"
372
+
373
+ export interface BrowserRun {
374
+ readonly text: string
375
+ readonly images: readonly { readonly data: Buffer; readonly mime: string }[]
376
+ readonly artifacts: readonly string[]
377
+ }
378
+
379
+ export function installBrowserTool(draft: ToolDraft, run: (args: Record<string, string>, ctx: ToolContext) => Promise<BrowserRun>, allowed: (sessionID: string) => boolean): void {
380
+ const read = draft.get("read")
381
+ const str = read?.input?.fields?.path
382
+ if (!read?.input?.mapFields || !str) throw new Error("the built-in read tool has no input schema to build from")
383
+ const fields = ["path", "url", "steps", "video", "width", "height", "full", "settle", "timeout", "out", "device", "format"] as const
384
+ draft.add({
385
+ id: BROWSER_ID,
386
+ name: BROWSER_ID,
387
+ description:
388
+ "Drive your page in a real Playwright browser on the host and watch it work. Start with path: a page or a directory with an index.html in your directory (built first), or url: a host this job may reach. steps: a JSON array, one action per object, in order — " +
389
+ '{"goto":"/route"}, {"click":"text=Save"}, {"dblclick":sel}, {"hover":sel}, {"focus":sel}, {"fill":[sel,text]}, {"type":[sel,text]}, {"press":[sel,key]}, {"select":[sel,value]}, {"check":sel}, {"uncheck":sel}, {"upload":[sel,path]}, ' +
390
+ '{"waitFor":sel}, {"waitHidden":sel}, {"waitText":[sel,text]}, {"sleep":ms}, {"idle":ms}, {"scroll":[x,y]}, {"wheel":[dx,dy]}, {"scrollTo":sel}, {"viewport":[w,h]}, {"eval":"js expression"}, {"shot":"name.png"} or {"shot":[sel,"name.png"]}, {"pdf":"name.pdf"}, {"back":true}, {"forward":true}, {"reload":true}. ' +
391
+ "Selectors are Playwright's: css, text=Save, role=button, [data-testid=x]. video: true (or yes) records the whole run; you get keyframes, the user gets the WebM (format: mp4 converts it). " +
392
+ "width, height: the window (default 1280x800; 390 is a phone). full: false for only the first screen. settle: ms after each load (default 300). timeout: seconds for the whole run (default 120). " +
393
+ "out: a directory in your directory to keep the files (default: the job's media folder, never committed). device: a Playwright device name such as \"iPhone 13\". " +
394
+ "Every field must be given: pass \"\" for the ones you do not need. The tool reports console errors, failed requests, eval results and the files; screenshots and video keyframes come back as pictures.",
395
+ input: read.input.mapFields(() => Object.fromEntries(fields.map((f) => [f, str]))),
396
+ execute: async (args: Record<string, unknown>, ctx: ToolContext) => {
397
+ if (!ctx?.sessionID || !allowed(ctx.sessionID)) return { content: "Only a designer of the micromanager may use this tool." }
398
+ try {
399
+ const r = await run(Object.fromEntries(fields.map((f) => [f, String(args?.[f] ?? "")])), ctx)
400
+ const content: Record<string, unknown>[] = [{ type: "text", text: r.text }]
401
+ for (const image of r.images) {
402
+ const ext = image.mime.split("/")[1] ?? "png"
403
+ content.push({ type: "file", uri: `data:${image.mime};base64,${image.data.toString("base64")}`, mime: image.mime, name: `shot-${content.length}.${ext}` })
404
+ }
405
+ return { content }
406
+ } catch (err) {
407
+ return { content: `failed: ${err instanceof Error ? err.message : String(err)}` }
408
+ }
409
+ },
410
+ })
411
+ }
412
+
413
+ // A writer's request to have a check or a frozen test changed (src/checkchange.ts): it never changes them itself. The
414
+ // call waits until the micromanager, a reviewer or the user decided it. The context hook hides it from every session
415
+ // that is no native writer.
416
+ export const CHECK_CHANGE_ID = "request_check_change"
417
+
418
+ export function installCheckChangeTool(draft: ToolDraft, request: (args: Record<string, string>, ctx: ToolContext) => Promise<string>, allowed: (sessionID: string) => boolean): void {
419
+ const read = draft.get("read")
420
+ const str = read?.input?.fields?.path
421
+ if (!read?.input?.mapFields || !str) throw new Error("the built-in read tool has no input schema to build from")
422
+ const fields = ["kind", "target", "problem", "evidence", "proposal"] as const
423
+ draft.add({
424
+ id: CHECK_CHANGE_ID,
425
+ name: CHECK_CHANGE_ID,
426
+ description: "Ask for a change to one of your checks or frozen tests when it is wrong itself; never change or get around it yourself. kind: check_bug (a wrong path, a typo, a command that cannot run here), test_contradicts_spec (the test expects what the task says not to do), spec_incomplete (the task did not think of this case; the user decides), contract (the fitness contract; the user decides). target: the check command or the file's path. problem: what is wrong, in a sentence. evidence: the output or the line of the task that shows it; \"too hard\" is no evidence. proposal: the new command, or a unified diff of the file (for a contract, its JSON). The call waits for the decision, up to twenty minutes. Twice per task at most, and a refused change stays refused.",
427
+ input: read.input.mapFields(() => Object.fromEntries(fields.map((f) => [f, str]))),
428
+ execute: async (args: Record<string, unknown>, ctx: ToolContext) => {
429
+ if (!ctx?.sessionID || !allowed(ctx.sessionID)) return { content: "Only a worker that changes files for the micromanager may use this tool." }
430
+ try {
431
+ return { content: await request(Object.fromEntries(fields.map((f) => [f, String(args?.[f] ?? "").trim()])), ctx) }
432
+ } catch (err) {
433
+ return { content: `failed: ${err instanceof Error ? err.message : String(err)}` }
434
+ }
435
+ },
436
+ })
437
+ }
438
+
439
+ // A worker's wait (src/wait.ts): block until a process ends, a file holds what the worker waits for, or a paused
440
+ // permission request is answered. It runs nothing, so it needs no permission of its own, and it saves the worker the
441
+ // poll loop that asks for the permission layer again every time. Every worker of the micromanager may use it; the
442
+ // context hook hides it from every other session.
443
+ export const WAIT_ID = "wait"
444
+
445
+ export function installWaitTool(draft: ToolDraft, wait: (args: Record<string, string>, ctx: ToolContext) => Promise<string>, allowed: (sessionID: string) => boolean): void {
446
+ const read = draft.get("read")
447
+ const str = read?.input?.fields?.path
448
+ if (!read?.input?.mapFields || !str) throw new Error("the built-in read tool has no input schema to build from")
449
+ const fields = ["id", "pid", "file", "match", "line", "timeout"] as const
450
+ draft.add({
451
+ id: WAIT_ID,
452
+ name: WAIT_ID,
453
+ description:
454
+ "Block instead of polling: wait until a process ends, a file holds what you wait for, or a paused permission request is answered. It runs nothing, so it asks for no permission, and it ends the poll loop that asks for the permission layer again every time. " +
455
+ "pid: the process id to wait for, until it is gone. " +
456
+ "file: a file or log to watch, in your worktree or in your own TMPDIR. match: the text to wait for in it. line: the line count to wait for. " +
457
+ "id: a paused permission request (\"A1\") or a short label of one; with no id it waits for your own request when you have one. It ends when the request is answered, refused or dropped, and the answer is told to you. " +
458
+ "timeout: how long to wait, in seconds (\"60\", \"2m\"); the default is 60 seconds and the longest is 10 minutes. " +
459
+ "Every field must be given: pass \"\" for the ones you do not need. It returns what happened, how long it waited and, on a timeout, what it was watching.",
460
+ input: read.input.mapFields(() => Object.fromEntries(fields.map((f) => [f, str]))),
461
+ execute: async (args: Record<string, unknown>, ctx: ToolContext) => {
462
+ if (!ctx?.sessionID || !allowed(ctx.sessionID)) return { content: "Only a worker of the micromanager may use this tool." }
463
+ try {
464
+ return { content: await wait(Object.fromEntries(fields.map((f) => [f, String(args?.[f] ?? "").trim()])), ctx) }
465
+ } catch (err) {
466
+ return { content: `failed: ${err instanceof Error ? err.message : String(err)}` }
467
+ }
468
+ },
469
+ })
470
+ }
471
+
472
+ // The plan as the micromanager shows it to the user.
473
+ export function planText(job: Job): string {
474
+ const acceptance = job.acceptance.map((a) => `- ${a.id}: ${a.text}${a.verify ? ` (check: ${a.verify})` : ""}`)
475
+ const tasks = job.tasks.map((t) =>
476
+ `- ${t.id} [${t.role}] ${t.title}${t.dependsOn.length ? ` (after ${t.dependsOn.join(", ")})` : ""}` +
477
+ `${t.files.length ? `\n files: ${t.files.join(", ")}` : ""}\n covers: ${t.acceptance.join(", ")}${t.description ? `\n ${t.description}` : ""}`,
478
+ )
479
+ return [`job ${job.id} (${job.phase})`, `goal: ${job.goal}`, "", "acceptance:", ...acceptance, "", "tasks:", ...tasks].join("\n")
480
+ }