kaizen-agent 1.61.6 → 1.62.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 (107) hide show
  1. package/README.md +2 -2
  2. package/agents/kaizen-builder.md +3 -0
  3. package/agents/kaizen-planner.md +3 -0
  4. package/agents/kaizen-reviewer.md +2 -0
  5. package/assets/kaizen-logo.png +0 -0
  6. package/assets/kaizen.ico +0 -0
  7. package/cli/__pycache__/computer-helper.cpython-314.pyc +0 -0
  8. package/cli/accounts.test.ts +126 -0
  9. package/cli/accounts.ts +116 -0
  10. package/cli/add-project.ts +4 -2
  11. package/cli/agent-prefs.test.ts +127 -0
  12. package/cli/agent-prefs.ts +106 -0
  13. package/cli/board.test.ts +4 -5
  14. package/cli/computer-helper.py +299 -0
  15. package/cli/computer.test.ts +155 -0
  16. package/cli/computer.ts +66 -0
  17. package/cli/dashboard.ts +14 -15
  18. package/cli/install.ts +67 -4
  19. package/cli/keep-awake.ts +30 -0
  20. package/cli/project-tree.test.ts +1 -0
  21. package/cli/pty.test.ts +2 -1
  22. package/cli/pty.ts +6 -5
  23. package/cli/report.test.ts +59 -0
  24. package/cli/report.ts +62 -0
  25. package/cli/restart.test.ts +1 -0
  26. package/cli/settings.test.ts +21 -1
  27. package/cli/settings.ts +19 -11
  28. package/cli/setup.test.ts +2 -2
  29. package/cli/skills.test.ts +89 -0
  30. package/cli/skills.ts +112 -0
  31. package/cli/state.test.ts +46 -4
  32. package/cli/state.ts +127 -41
  33. package/cli/term-image.test.ts +23 -0
  34. package/cli/term-image.ts +26 -0
  35. package/cli/usage.test.ts +8 -2
  36. package/cli/usage.ts +8 -6
  37. package/cli/video.test.ts +5 -5
  38. package/cli/web-accept.test.ts +1 -0
  39. package/cli/web-decide.test.ts +1 -0
  40. package/cli/web-pr.test.ts +1 -0
  41. package/cli/web-skills.test.ts +32 -0
  42. package/cli/web-symlink.test.ts +1 -0
  43. package/cli/web.ts +179 -20
  44. package/cli/workers.test.ts +319 -0
  45. package/cli/workers.ts +380 -0
  46. package/cli/worktree.test.ts +21 -2
  47. package/cli/worktree.ts +21 -2
  48. package/package.json +1 -1
  49. package/skills/kaizen/config.default.yml +33 -1
  50. package/skills/kaizen/settings.md +1 -1
  51. package/skills/kaizen/skill.json +1 -0
  52. package/skills/kaizen/spec-build.md +22 -2
  53. package/skills/kaizen/spec-main.md +9 -0
  54. package/skills/kaizen/spec-plan.md +18 -1
  55. package/skills/kaizen/spec-review.md +4 -0
  56. package/skills/kaizen/spec.md +15 -0
  57. package/skills/kaizen-help/SKILL.md +1 -0
  58. package/skills/kaizen-help/skill.json +1 -0
  59. package/skills/media/kaizen-book/skill.json +1 -0
  60. package/skills/media/kaizen-deck/skill.json +1 -0
  61. package/skills/media/kaizen-video/scripts/__pycache__/intake.cpython-314.pyc +0 -0
  62. package/skills/media/kaizen-video/scripts/__pycache__/make_film.cpython-314.pyc +0 -0
  63. package/skills/media/kaizen-video/scripts/__pycache__/make_tiktok.cpython-314.pyc +0 -0
  64. package/skills/media/kaizen-video/scripts/__pycache__/render_cut.cpython-314.pyc +0 -0
  65. package/skills/media/kaizen-video/scripts/__pycache__/sfx.cpython-314.pyc +0 -0
  66. package/skills/media/kaizen-video/scripts/__pycache__/srt.cpython-314.pyc +0 -0
  67. package/skills/media/kaizen-video/scripts/__pycache__/transcribe.cpython-314.pyc +0 -0
  68. package/skills/media/kaizen-video/scripts/__pycache__/vo.cpython-314.pyc +0 -0
  69. package/skills/media/kaizen-video/skill.json +1 -0
  70. package/skills/optional/kaizen-computer/SKILL.md +38 -0
  71. package/skills/optional/kaizen-computer/skill.json +1 -0
  72. package/web/board/add-project.ts +3 -3
  73. package/web/board/agent-favicons.ts +9 -0
  74. package/web/board/agent-term.ts +1 -1
  75. package/web/board/api.ts +1 -1
  76. package/web/board/approvals.ts +1 -1
  77. package/web/board/cards.ts +50 -7
  78. package/web/board/dictation.ts +46 -3
  79. package/web/board/fixes.ts +1 -1
  80. package/web/board/home.ts +1 -1
  81. package/web/board/icebox.ts +1 -1
  82. package/web/board/keys.ts +5 -15
  83. package/web/board/onboarding.ts +1 -1
  84. package/web/board/panel.ts +24 -20
  85. package/web/board/phone.ts +4 -1
  86. package/web/board/run-view.ts +11 -6
  87. package/web/board/settings-accounts.ts +60 -0
  88. package/web/board/settings-agents.ts +102 -0
  89. package/web/board/settings-orchestration.ts +32 -0
  90. package/web/board/settings-pages.test.ts +5 -0
  91. package/web/board/settings-pages.ts +10 -4
  92. package/web/board/settings-skills.ts +47 -0
  93. package/web/board/settings-voice.test.ts +18 -0
  94. package/web/board/settings-voice.ts +28 -0
  95. package/web/board/settings.ts +40 -4
  96. package/web/board/terms.ts +2 -2
  97. package/web/board/update.ts +1 -1
  98. package/web/board/ws-board.test.ts +6 -0
  99. package/web/board/ws-board.ts +2 -0
  100. package/web/board.html +15 -3
  101. package/web/board.js +134 -84
  102. package/web/notebook.js +2 -2
  103. package/web/notes.html +3 -3
  104. package/web/term.js +27 -27
  105. package/web/term.ts +25 -3
  106. package/web/video.html +2 -2
  107. package/web/video.js +2 -2
package/cli/workers.ts ADDED
@@ -0,0 +1,380 @@
1
+ // Orchestration: one run split into workers, each in its own terminal, branch and folder.
2
+ // All of it lives in runs/<id>/workers.json. `kaizen worker` only writes requests into it;
3
+ // the board is the only thing that starts a worker, so no board running means none starts.
4
+ // Off by default: with it off no file is made and nothing here runs. Settings are read once,
5
+ // at `init`, and frozen into the file, so a change later never touches a run that is building.
6
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
7
+ import { homedir } from "node:os";
8
+ import { join } from "node:path";
9
+ import { argsOf, commandOf, readPrefs, withEnv, type Prefs } from "./agent-prefs.ts";
10
+ import { clip, reportBlocked, reportUnblock, validId } from "./report.ts";
11
+ import { read } from "./settings.ts";
12
+ import { accountEnv, accountForRun, agentFlags, agentUsable, detectDefaultAgent, MODEL_FLAGS, plainModel, promptArgs, readText, runAgent, YOLO_FLAGS } from "./state.ts";
13
+ import { branchOf, run as sh } from "./worktree.ts";
14
+
15
+ export type Status = "planned" | "requested" | "running" | "blocked" | "succeeded" | "failed" | "unverified" | "conflict" | "merged" | "stopped";
16
+ export type Worker = {
17
+ id: string; title: string; owns: string[]; after: string[]; status: Status; branch: string; worktree: string;
18
+ key?: string; bypass: boolean; agent?: string; model?: string; modelNote?: string; requested?: { agent?: string; model?: string };
19
+ phase?: string; blocked?: { question: string; options: string[] };
20
+ handback?: { outcome: string; summary: string; files: string[]; at: number }; requestedAt?: number;
21
+ };
22
+ export type Workers = {
23
+ v: 1; frozen: { max: number; permissions: "own" | "bypass"; model?: string; at: number }; workers: Worker[];
24
+ merge?: { status: "merged" | "conflict" | "failed"; sha0: string; conflicts?: string[]; why?: string };
25
+ };
26
+ export type Resolved = { on: boolean; max: number; permissions: "own" | "bypass"; model: string; why: string };
27
+ type Plan = { id: string; title: string; owns: string[]; after: string[] };
28
+
29
+ const git = (cwd: string, ...a: string[]) => sh(["git", ...a], cwd);
30
+ const runDir = (project: string, id: string) => join(project, ".kaizen", "runs", id);
31
+ const fileOf = (project: string, id: string) => join(runDir(project, id), "workers.json");
32
+ const stateOf = (project: string, id: string): any => {
33
+ try { return validId(id) ? JSON.parse(readText(join(runDir(project, id), "state.json"))) : null; } catch { return null; }
34
+ };
35
+
36
+ export function readWorkers(project: string, id: string): Workers | null {
37
+ try { const w = JSON.parse(readFileSync(fileOf(project, id), "utf8")); return w?.v === 1 && Array.isArray(w.workers) ? w : null; } catch { return null; }
38
+ }
39
+
40
+ // ponytail: mkdir lock, a real lock if workers ever exceed single digits.
41
+ function locked<T>(project: string, id: string, fn: () => T): T {
42
+ const lock = fileOf(project, id) + ".lock";
43
+ for (let i = 0; ; i++) {
44
+ try { mkdirSync(lock); break; } catch {
45
+ try { if (Date.now() - statSync(lock).mtimeMs > 10_000) rmSync(lock, { recursive: true }); } catch { /* gone */ }
46
+ if (i > 60) throw new Error("workers.json is locked: try again");
47
+ Bun.sleepSync(50);
48
+ }
49
+ }
50
+ try { return fn(); } finally { rmSync(lock, { recursive: true, force: true }); }
51
+ }
52
+
53
+ // Read, change, write under the lock. `fn` returns a refusal to write nothing.
54
+ function update(project: string, id: string, fn: (w: Workers) => string | void): string | null {
55
+ return locked(project, id, () => {
56
+ const w = readWorkers(project, id);
57
+ if (!w) return `no workers for ${id}: run \`kaizen worker init ${id}\``;
58
+ const why = fn(w);
59
+ if (why) return why;
60
+ const f = fileOf(project, id), tmp = `${f}.${process.pid}.tmp`;
61
+ writeFileSync(tmp, JSON.stringify(w, null, 2));
62
+ renameSync(tmp, f);
63
+ return null;
64
+ });
65
+ }
66
+
67
+ /** Whether this run may use workers, and with what. The run's own pick, then the project, then global, then off. */
68
+ export function resolve(project: string, id: string, plat: string = process.platform): Resolved {
69
+ const st = stateOf(project, id);
70
+ const texts = [join(project, ".kaizen", "config.yml"), join(homedir(), ".kaizen", "config.yml")].filter(existsSync).map(readText);
71
+ const pick = (k: string) => { for (const t of texts) { const v = read(t, k); if (v !== null) return v; } return null; };
72
+ const max = Math.min(6, Math.max(1, parseInt(pick("orchestration.max_workers") ?? "3", 10) || 3));
73
+ const permissions = pick("orchestration.permissions") === "bypass" ? "bypass" as const : "own" as const;
74
+ // The run's own agent's model name, or "" (inherit); a name that is not plain reads as inherit.
75
+ const cmd = runAgent(join(project, ".kaizen"), id)?.cmd ?? st?.agent, wm = typeof cmd === "string" && /^\w+$/.test(cmd) ? pick(`orchestration.worker_model.${cmd}`) : null;
76
+ const model = wm && plainModel(wm) ? wm : "";
77
+ const off = (why: string): Resolved => ({ on: false, max, permissions, model, why });
78
+ if (!st) return off(`no run ${clip(id, 80)}`);
79
+ const want = st.orchestration === "on" ? true : st.orchestration === "off" ? false : pick("orchestration.enabled") === "true";
80
+ if (!want) return off("orchestration is off: turn it on in Settings > Orchestration, or `kaizen worker set <run> on`");
81
+ if (plat === "win32") return off("workers do not run on Windows");
82
+ if (st.runner === "lite") return off("a lite run does not use workers");
83
+ if (!st.worktree || !st.branch || !existsSync(st.worktree)) return off("this run has no worktree: workers branch off the run's branch");
84
+ if (!Bun.which("git")) return off("git is not installed");
85
+ return { on: true, max, permissions, model, why: "" };
86
+ }
87
+
88
+ // A request older than this is the coordinator's abandoned wait: the board never acts on it.
89
+ const STALE_MS = 60_000;
90
+ const fresh = (x: Worker) => Date.now() - (x.requestedAt ?? 0) < STALE_MS;
91
+
92
+ const overlap = (a: string, b: string) => a === b || a.startsWith(b + "/") || b.startsWith(a + "/");
93
+ const norm = (p: string) => p.replace(/[`'"]/g, "").trim().replace(/^\.\//, "").replace(/(\/\*{1,2})?\/?$/, "");
94
+
95
+ /** The `## Workers` section of the plan: null when there is none. Lines: `w1 — title — owns: a, b — after: w0`. */
96
+ export function parsePlan(project: string, id: string): Plan[] | string | null {
97
+ let text: string;
98
+ try { text = readText(join(runDir(project, id), "01-plan.md")); } catch { return null; }
99
+ const sec = /^## Workers[ \t]*\n([\s\S]*?)(?=^## |(?![\s\S]))/m.exec(text);
100
+ if (!sec) return null;
101
+ const out: Plan[] = [];
102
+ for (const raw of sec[1]!.split("\n")) {
103
+ const line = raw.replace(/^\s*[-*]\s+/, "").trim();
104
+ if (!line || line.startsWith("<!--") || line.startsWith(">")) continue;
105
+ const [wid, title, ...rest] = line.split(/\s+[—–]\s+|\s+--\s+/).map((s) => s.trim());
106
+ if (!wid || !/^w\d{1,2}$/.test(wid)) return `"${clip(wid, 40)}" is not a worker id (w1, w2, ...) in the plan's ## Workers`;
107
+ if (out.some((x) => x.id === wid)) return `worker ${wid} is listed twice`;
108
+ const field = (k: string) => rest.find((r) => r.toLowerCase().startsWith(k + ":"))?.slice(k.length + 1).split(",").map(norm).filter(Boolean) ?? [];
109
+ const owns = field("owns"), after = field("after");
110
+ if (!title || !owns.length) return `${wid} needs a title and \`owns:\` paths`;
111
+ if (after.some((a) => !out.some((x) => x.id === a))) return `${wid} is after a worker that is not listed before it`;
112
+ out.push({ id: wid, title: clip(title, 120), owns, after });
113
+ }
114
+ return out.length ? out : null;
115
+ }
116
+
117
+ /**
118
+ * Starts orchestration for a run in its build stage: reads the approved split, checks it and freezes the
119
+ * settings. Off, or a plan with no split, writes nothing at all.
120
+ */
121
+ export function init(project: string, id: string, plat?: string): { ok: true; n: number } | { ok: false; why: string } {
122
+ const r = resolve(project, id, plat);
123
+ if (!r.on) return { ok: false, why: `${r.why}. Build it normally` };
124
+ const st = stateOf(project, id);
125
+ if (st.stage !== "build") return { ok: false, why: `the run is in stage ${st.stage}: workers start in build` };
126
+ if (readWorkers(project, id)) return { ok: false, why: `already set up: \`kaizen worker status --run ${id}\`` };
127
+ const plan = parsePlan(project, id);
128
+ if (plan === null) return { ok: false, why: "the plan has no ## Workers section. Build it normally" };
129
+ if (typeof plan === "string") return { ok: false, why: plan };
130
+ let approval = "";
131
+ try { approval = readText(join(runDir(project, id), "02-approval.md")); } catch { /* none */ }
132
+ if (!/^\s*workers:\s*approved\b/im.test(approval)) return { ok: false, why: "02-approval.md does not record the split as approved (a `workers: approved` line). Ask the user, or build it normally" };
133
+ if (plan.length < 2) return { ok: false, why: "a split needs at least two workers. Build it normally" };
134
+ if (plan.length > r.max) return { ok: false, why: `the plan has ${plan.length} workers and the most allowed is ${r.max}: change the plan or Settings > Orchestration` };
135
+ for (const [i, a] of plan.entries()) for (const b of plan.slice(i + 1)) {
136
+ const hit = a.owns.find((p) => b.owns.some((q) => overlap(p, q)));
137
+ if (hit) return { ok: false, why: `${a.id} and ${b.id} both own \`${hit}\`: split the files so no path has two owners` };
138
+ }
139
+ const w: Workers = {
140
+ v: 1, frozen: { max: r.max, permissions: r.permissions, model: r.model, at: Date.now() },
141
+ workers: plan.map((p) => ({ ...p, status: "planned", branch: `${branchOf(id)}-${p.id}`, worktree: join(project, ".kaizen", "wt", `${id}-${p.id}`), bypass: false })),
142
+ };
143
+ const f = fileOf(project, id);
144
+ locked(project, id, () => { writeFileSync(f + ".tmp", JSON.stringify(w, null, 2)); renameSync(f + ".tmp", f); });
145
+ return { ok: true, n: plan.length };
146
+ }
147
+
148
+ // The same check for the CLI's request and the board's start: never trust the file alone.
149
+ function startable(project: string, id: string, w: Workers, x: Worker, plat: string = process.platform): string | null {
150
+ const st = stateOf(project, id);
151
+ if (plat === "win32") return "workers do not run on Windows";
152
+ if (st?.stage !== "build") return `the run is in stage ${st?.stage}: workers run in build`;
153
+ if (w.workers.filter((o) => o !== x && o.status !== "planned").length + 1 > w.frozen.max) return `the most allowed is ${w.frozen.max} workers for this run`;
154
+ const unmet = x.after.find((a) => w.workers.find((o) => o.id === a)?.status !== "succeeded");
155
+ if (unmet) return `${unmet} must succeed first (it is ${w.workers.find((o) => o.id === unmet)?.status ?? "unknown"})`;
156
+ return null;
157
+ }
158
+
159
+ /** `kaizen worker start`: asks the board to open the worker, then waits for it to say running. */
160
+ export function requestStart(project: string, id: string, wid: string, waitMs = 30_000): { ok: boolean; why: string } {
161
+ const before = readWorkers(project, id)?.workers.find((x) => x.id === wid);
162
+ if (!before) return { ok: false, why: `no worker ${clip(wid, 20)}: \`kaizen worker status --run ${id}\`` };
163
+ if (before.status === "running") return { ok: true, why: `${wid} is already running` };
164
+ const why = update(project, id, (w) => {
165
+ const x = w.workers.find((o) => o.id === wid)!;
166
+ if (x.status !== "planned" && x.status !== "requested") return `${wid} is ${x.status}: only a planned worker starts`;
167
+ const bad = startable(project, id, w, x);
168
+ if (bad) return bad;
169
+ x.status = "requested"; x.requestedAt = Date.now();
170
+ });
171
+ if (why) return { ok: false, why };
172
+ const until = Date.now() + waitMs;
173
+ for (;;) {
174
+ const x = readWorkers(project, id)?.workers.find((o) => o.id === wid);
175
+ if (x && x.status !== "requested") return x.status === "running" ? { ok: true, why: `${wid} is running` } : { ok: false, why: `${wid} ${x.status}: ${x.handback?.summary ?? ""}` };
176
+ if (Date.now() >= until) {
177
+ update(project, id, (w) => { const o = w.workers.find((o) => o.id === wid); if (o?.status === "requested") o.status = "planned"; else return "moved on"; });
178
+ return { ok: false, why: "the board did not start it: is `kaizen web` running?" };
179
+ }
180
+ Bun.sleepSync(250);
181
+ }
182
+ }
183
+
184
+ export type Launch = { argv: string[]; title: string; bypass: boolean; agent: string; model?: string; cwd: string; env: Record<string, string>; trust?: string; modelNote?: string };
185
+
186
+ const brief = (project: string, id: string, x: Worker) =>
187
+ `You are worker ${x.id} of run ${id}: ${x.title}. You are alone in your own git worktree (${x.worktree}) on branch ${x.branch}. ` +
188
+ `Do this one task and own only these paths: ${x.owns.join(", ")}. Change nothing else. Read ${join(runDir(project, id), "01-plan.md")} for the plan. ` +
189
+ `Say where you are with: kaizen worker report phase "<text>". If you need the user, never ask in this chat: run kaizen worker report blocked "<question>" and wait. ` +
190
+ `When done, commit all your work on this branch, then run: kaizen worker report done --outcome succeeded --summary "<what you did>" --files <a,b>. ` +
191
+ `If you cannot finish, use --outcome failed. Do not merge, push or start other workers.`;
192
+
193
+ /**
194
+ * The launch line for one worker. Never reads the user's bypass preference: a worker is in bypass only
195
+ * when this run's frozen Orchestration permissions say so, and its tab says so too.
196
+ */
197
+ export function launchOf(project: string, id: string, x: Worker, permissions: "own" | "bypass", prefs: Prefs = readPrefs(), pick = ""): Launch | string {
198
+ const own = runAgent(join(project, ".kaizen"), id), st = stateOf(project, id);
199
+ const agent = detectDefaultAgent(project, own?.cmd ?? st?.agent);
200
+ if (!agentUsable(agent.cmd)) return `${agent.name} is not available: see Settings > Agents`;
201
+ // inherit keeps the run's own model; a pick goes through MODEL_FLAGS, so a tool with no model flag runs without one.
202
+ const picked = pick && plainModel(pick) ? pick : undefined;
203
+ const model = picked ?? (own?.cmd === agent.cmd && own.model && plainModel(own.model) ? own.model : undefined);
204
+ const acct = accountForRun(project, id, agent.cmd);
205
+ if (acct.error) return acct.error;
206
+ const bypass = permissions === "bypass" && !!YOLO_FLAGS[agent.cmd];
207
+ const flags = [...agentFlags(project, agent.cmd, undefined, model), ...(bypass ? YOLO_FLAGS[agent.cmd]! : []), ...argsOf(agent.cmd, prefs)];
208
+ const line = withEnv([commandOf(agent.cmd, prefs), ...flags, ...promptArgs(agent.cmd, brief(project, id, x))], agent.cmd, prefs);
209
+ return {
210
+ argv: acct.dir ? ["env", ...accountEnv(acct), ...line] : line, title: `Worker ${x.id}${bypass ? " · bypass" : ""}`, bypass, agent: agent.cmd,
211
+ model: picked ? (MODEL_FLAGS[agent.cmd] ? picked : undefined) : model ?? agentFlags(project, agent.cmd).join(" ").match(/\S+$/)?.[0], cwd: x.worktree,
212
+ modelNote: picked && !MODEL_FLAGS[agent.cmd] ? `${agent.name} takes no model flag: "${picked}" was ignored` : undefined,
213
+ env: { KAIZEN_RUN_ID: id, KAIZEN_WORKER: x.id }, trust: acct.dir ? join(acct.dir, ".claude.json") : undefined,
214
+ };
215
+ }
216
+
217
+ /** Board side: checks a requested worker, makes its branch and folder off the run's branch, returns how to launch it. */
218
+ export function startWorker(project: string, id: string, wid: string, prefs?: Prefs): { ok: true; launch: Launch } | { ok: false; why: string } {
219
+ const w = readWorkers(project, id), x = w?.workers.find((o) => o.id === wid), st = stateOf(project, id);
220
+ if (!w || !x || !st) return { ok: false, why: "no such worker" };
221
+ if (x.status !== "requested") return { ok: false, why: `${wid} is ${x.status}, not requested` };
222
+ if (!fresh(x)) return { ok: false, why: `${wid}'s request is stale: ask again with \`kaizen worker start ${wid}\`` };
223
+ const bad = startable(project, id, w, x);
224
+ if (bad) return { ok: false, why: bad };
225
+ const plan = parsePlan(project, id);
226
+ if (typeof plan === "string" || !plan?.some((p) => p.id === wid && p.owns.join() === x.owns.join())) return { ok: false, why: `${wid} is not in the plan's ## Workers` };
227
+ if (!st.worktree || !existsSync(st.worktree) || x.branch !== `${branchOf(id)}-${wid}`) return { ok: false, why: "the run has no worktree to branch from" };
228
+ const launch = launchOf(project, id, x, w.frozen.permissions, prefs, w.frozen.model);
229
+ if (typeof launch === "string") return { ok: false, why: launch };
230
+ if (!existsSync(x.worktree)) {
231
+ const have = git(project, "rev-parse", "--verify", "--quiet", `refs/heads/${x.branch}`).ok;
232
+ // A dependent worker starts from the worker it follows, so it sees that code; any further `after` workers are merged in.
233
+ const dep = x.after.map((a) => w.workers.find((o) => o.id === a)!.branch);
234
+ const add = git(project, "worktree", "add", ...(have ? [x.worktree, x.branch] : ["--no-track", "-b", x.branch, x.worktree, dep[0] ?? st.branch]));
235
+ if (!add.ok) return { ok: false, why: add.why };
236
+ if (!have) for (const b of dep.slice(1)) {
237
+ const m = git(x.worktree, "merge", "--no-edit", b);
238
+ if (!m.ok) { git(x.worktree, "merge", "--abort"); git(project, "worktree", "remove", "--force", x.worktree); git(project, "update-ref", "-d", `refs/heads/${x.branch}`); return { ok: false, why: `${wid} could not take ${b}: ${m.why}` }; }
239
+ }
240
+ }
241
+ return { ok: true, launch };
242
+ }
243
+
244
+ // A live worker gone quiet with no report: it may have finished and failed to say so.
245
+ export const workerStale = (x: { status: string; key?: string }, pty: { alive?: boolean; busy?: boolean; asking?: boolean; lastOut?: number } | null | undefined, now: number, minutes: number) =>
246
+ x.status === "running" && !!pty?.alive && !pty.busy && !pty.asking && now - (pty.lastOut ?? now) > 2 * minutes * 60_000;
247
+
248
+ export const markRunning = (project: string, id: string, wid: string, key: string, l: Launch) =>
249
+ update(project, id, (w) => {
250
+ const x = w.workers.find((o) => o.id === wid)!;
251
+ Object.assign(x, { status: "running", key, bypass: l.bypass, agent: l.agent, model: l.model, modelNote: l.modelNote, requested: { agent: l.agent, model: l.model } });
252
+ });
253
+
254
+ /** The board could not start it: the worker fails, with the reason where `start` and the card read it. */
255
+ export const failStart = (project: string, id: string, wid: string, why: string) =>
256
+ update(project, id, (w) => {
257
+ const x = w.workers.find((o) => o.id === wid)!;
258
+ x.status = "failed"; x.handback = { outcome: "failed", summary: clip(why, 300), files: [], at: Date.now() };
259
+ });
260
+
261
+ /** A worker still `running` or `blocked` whose terminal is gone, with no hand-back, is unverified. */
262
+ export function sweep(project: string, id: string, alive: (key: string) => boolean): boolean {
263
+ const w = readWorkers(project, id);
264
+ if (!w?.workers.some((x) => (x.status === "running" || x.status === "blocked") && !(x.key && alive(x.key)))) return false;
265
+ return !update(project, id, (m) => {
266
+ for (const x of m.workers) if ((x.status === "running" || x.status === "blocked") && !(x.key && alive(x.key)) && !x.handback) x.status = "unverified";
267
+ });
268
+ }
269
+
270
+ /** Runs of this project with a worker waiting for the board. */
271
+ export function requested(project: string): { id: string; wid: string }[] {
272
+ const dir = join(project, ".kaizen", "runs");
273
+ if (!existsSync(dir)) return [];
274
+ return readdirSync(dir).flatMap((id) => readWorkers(project, id)?.workers.filter((x) => x.status === "requested" && fresh(x)).map((x) => ({ id, wid: x.id })) ?? []);
275
+ }
276
+
277
+ /** A worker's own say: phase, blocked, unblock, done. Writes only that worker (and the run's blocker). */
278
+ export function report(project: string, id: string, wid: string, kind: string, a: { text?: string; options?: string[]; outcome?: string; summary?: string; files?: string[] } = {}): string | null {
279
+ const state = join(project, ".kaizen");
280
+ return update(project, id, (w) => {
281
+ const x = w.workers.find((o) => o.id === wid);
282
+ if (!x) return `no worker ${clip(wid, 20)}: \`kaizen worker status --run ${id}\``;
283
+ if (x.status !== "running" && x.status !== "blocked") return `${wid} is ${x.status}: only a running worker reports`;
284
+ if (kind === "phase" && a.text) { x.phase = clip(a.text, 120); return; }
285
+ if (kind === "blocked" && a.text) {
286
+ x.status = "blocked"; x.blocked = { question: clip(a.text, 300), options: (a.options ?? []).slice(0, 4).map((o) => clip(o, 80)) };
287
+ return reportBlocked(state, id, `${wid}: ${a.text}`, a.options ?? []) ?? undefined;
288
+ }
289
+ if (kind === "unblock") {
290
+ x.status = "running"; delete x.blocked;
291
+ if (!w.workers.some((o) => o.blocked)) reportUnblock(state, id);
292
+ return;
293
+ }
294
+ if (kind === "done") {
295
+ if (a.outcome !== "succeeded" && a.outcome !== "failed") return "outcome is succeeded or failed";
296
+ if (!a.summary) return "done needs --summary <text>";
297
+ if (git(x.worktree, "status", "--porcelain").out) return "uncommitted changes in your worktree: commit first, then report done";
298
+ x.status = a.outcome; delete x.blocked;
299
+ x.handback = { outcome: a.outcome, summary: clip(a.summary, 600), files: (a.files ?? []).slice(0, 200).map((f) => clip(f, 300)), at: Date.now() };
300
+ if (!w.workers.some((o) => o.blocked)) reportUnblock(state, id);
301
+ return;
302
+ }
303
+ return "report phase <text> | blocked <question> | unblock | done --outcome succeeded|failed --summary <text>";
304
+ });
305
+ }
306
+
307
+ const NEXT: Partial<Record<Status, string>> = {
308
+ planned: "start it: `kaizen worker start <wid>`", requested: "wait for the board, or check `kaizen web` is running", running: "wait for it to report done",
309
+ blocked: "answer it on the run's card, then it reports unblock", failed: "stop and tell the user; nothing is merged",
310
+ unverified: "its terminal ended without a hand-back: open its folder, check the work, and tell the user", conflict: "tell the user; resolve it by hand", stopped: "tell the user",
311
+ };
312
+
313
+ /** Merges every worker's branch into the run's own, in plan order, only when all succeeded. A conflict undoes all of it. */
314
+ export function merge(project: string, id: string): { ok: true; shas: string[]; left: string[] } | { ok: false; why: string } {
315
+ const w = readWorkers(project, id), st = stateOf(project, id);
316
+ if (!w || !st) return { ok: false, why: `no workers for ${id}: run \`kaizen worker init ${id}\`` };
317
+ if (w.workers.every((x) => x.status === "merged")) return { ok: false, why: "already merged" };
318
+ const not = w.workers.find((x) => x.status !== "succeeded");
319
+ if (not) return { ok: false, why: `${not.id} is ${not.status}, so nothing is merged: ${NEXT[not.status]?.replace("<wid>", not.id)}` };
320
+ const cwd = st.worktree as string;
321
+ if (!cwd || !existsSync(cwd)) return { ok: false, why: "the run has no worktree to merge into" };
322
+ if (git(cwd, "rev-parse", "--abbrev-ref", "HEAD").out !== st.branch) return { ok: false, why: `the run's worktree is not on ${st.branch}: check it out there first` };
323
+ if (git(cwd, "status", "--porcelain").out) return { ok: false, why: "the run's worktree has uncommitted changes: commit them first, then merge" };
324
+ // A branch may change only what its worker owns. Commits it took from the workers it follows are theirs, not its own.
325
+ for (const x of w.workers) {
326
+ const skip = x.after.flatMap((a) => ["^" + w.workers.find((o) => o.id === a)!.branch]);
327
+ const out = git(cwd, "log", "--no-merges", "--name-only", "--format=", x.branch, "^" + st.branch, ...skip).out.split("\n").filter(Boolean);
328
+ const stray = [...new Set(out)].filter((p) => !x.owns.some((o) => p === o || p.startsWith(o + "/")));
329
+ if (stray.length) return { ok: false, why: `${x.id} changed paths it does not own (${stray.slice(0, 5).join(", ")}): nothing is merged. Move those changes out of its branch, or tell the user` };
330
+ }
331
+ const sha0 = git(cwd, "rev-parse", "HEAD").out, shas: string[] = [];
332
+ for (const x of w.workers) {
333
+ const m = git(cwd, "merge", "--no-ff", "--no-edit", x.branch);
334
+ if (m.ok) { shas.push(git(cwd, "rev-parse", "HEAD").out); continue; }
335
+ // Conflict or any other refusal: the run's branch goes back to where it was, nothing partial stays.
336
+ const files = git(cwd, "diff", "--name-only", "--diff-filter=U").out.split("\n").filter(Boolean);
337
+ git(cwd, "merge", "--abort");
338
+ git(cwd, "reset", "--hard", sha0);
339
+ const why = files.length ? `${x.id} conflicts in ${files.join(", ")}` : `${x.id} would not merge: ${m.why}`;
340
+ update(project, id, (d) => {
341
+ if (files.length) d.workers.find((o) => o.id === x.id)!.status = "conflict";
342
+ d.merge = { status: files.length ? "conflict" : "failed", sha0, ...(files.length ? { conflicts: files } : { why: clip(m.why, 200) }) };
343
+ });
344
+ reportBlocked(join(project, ".kaizen"), id, `${why}. The run's branch is back at ${sha0.slice(0, 7)}; nothing is merged. Resolve it by hand.`);
345
+ return { ok: false, why: `${why}. The run's branch is back at ${sha0.slice(0, 7)}; nothing is merged` };
346
+ }
347
+ // Safe removal only, from the run's own folder so `-d` checks against its branch: `worktree remove` refuses a dirty folder and `branch -d` an unmerged branch.
348
+ const left: string[] = [];
349
+ for (const x of w.workers) {
350
+ const r = git(cwd, "worktree", "remove", x.worktree), b = git(cwd, "branch", "-d", x.branch);
351
+ if (!r.ok) left.push(`${x.id} folder ${x.worktree}: ${clip(r.why, 120)}`);
352
+ if (!b.ok) left.push(`${x.id} branch ${x.branch}: ${clip(b.why, 120)}`);
353
+ }
354
+ update(project, id, (d) => { for (const x of d.workers) x.status = "merged"; d.merge = { status: "merged", sha0 }; });
355
+ return { ok: true, shas, left };
356
+ }
357
+
358
+ /** `kaizen worker status` text. */
359
+ export function statusText(project: string, id: string): string {
360
+ const w = readWorkers(project, id);
361
+ if (!w) { const r = resolve(project, id); return r.on ? `no workers yet for ${id}: \`kaizen worker init ${id}\`` : r.why; }
362
+ return [
363
+ `max ${w.frozen.max} · permissions ${w.frozen.permissions} · model ${w.frozen.model || "inherit"} (frozen)`,
364
+ ...w.workers.map((x) => `${x.id} ${x.status}${x.bypass ? " · bypass" : ""} ${x.title}${x.phase ? ` · ${x.phase}` : ""}${x.blocked ? ` · asks: ${x.blocked.question}` : ""}${x.modelNote ? ` · ${x.modelNote}` : ""}${x.handback ? ` · ${x.handback.summary}` : ""}`),
365
+ ...(w.merge ? [`merge: ${w.merge.status}${w.merge.conflicts ? ` (${w.merge.conflicts.join(", ")})` : ""}`] : []),
366
+ ].join("\n");
367
+ }
368
+
369
+ /** `kaizen worker set <run> on|off|clear`: this run's own switch, in its state.json. */
370
+ export function setRun(project: string, id: string, to: string): string | null {
371
+ const f = join(runDir(project, id), "state.json"), s = stateOf(project, id);
372
+ if (!s) return `no run ${clip(id, 80)}`;
373
+ if (to !== "on" && to !== "off" && to !== "clear") return "kaizen worker set <run> on|off|clear";
374
+ if (readWorkers(project, id)) return "this run already has workers: its settings are frozen";
375
+ if (to === "clear") delete s.orchestration; else s.orchestration = to;
376
+ const tmp = `${f}.${process.pid}.tmp`;
377
+ writeFileSync(tmp, JSON.stringify(s));
378
+ renameSync(tmp, f);
379
+ return null;
380
+ }
@@ -1,9 +1,9 @@
1
1
  // A real bare remote, two clones and real git: the landing is only as good as git says.
2
2
  import { test, expect, beforeEach } from "bun:test";
3
- import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync } from "node:fs";
3
+ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, realpathSync } from "node:fs";
4
4
  import { join } from "node:path";
5
5
  import { tmpdir } from "node:os";
6
- import { startWorktree, landWorktree, codeDir, projectFromWorktree, run, runAsync, workspaces, workspacesNow, addWorktree, wsOf, adoptWorkspace, branchState, openPr, mergePr, removeWorktree, type Run, type AsyncRun } from "./worktree.ts";
6
+ import { linkTerm, linkedWs, startWorktree, landWorktree, codeDir, projectFromWorktree, run, runAsync, workspaces, workspacesNow, addWorktree, wsOf, adoptWorkspace, branchState, openPr, mergePr, removeWorktree, type Run, type AsyncRun } from "./worktree.ts";
7
7
 
8
8
  const ID = "2026-10-17-demo";
9
9
  // CI runners have no git identity, and landWorktree's rebase writes commits.
@@ -258,3 +258,22 @@ test("G-04 removeWorktree keeps unmerged work when nothing can prove it landed (
258
258
  expect(existsSync(w)).toBe(true);
259
259
  expect(g(project, "branch", "--list", `kaizen/${ID}`)).toContain(ID);
260
260
  });
261
+
262
+ test("a linked terminal shows its live run's worktree, then falls back", () => {
263
+ const p = realpathSync(mkdtempSync(join(tmpdir(), "kz-link-"))), state = join(p, ".kaizen"), id = "r1", wt = join(p, "wt");
264
+ mkdirSync(join(state, "runs", id), { recursive: true }); mkdirSync(wt);
265
+ const put = (s: object) => writeFileSync(join(state, "runs", id, "state.json"), JSON.stringify(s));
266
+ put({ stage: "build", worktree: wt });
267
+ linkTerm(state, "bad key", id);
268
+ linkTerm(state, "sh-0123abcd", id);
269
+ expect(linkedWs(state, "sh-0123abcd")).toBe(wt);
270
+ expect(linkedWs(state, "sh-ffffffff")).toBeNull(); // an unlinked terminal stays put
271
+ put({ stage: "done", worktree: wt });
272
+ expect(linkedWs(state, "sh-0123abcd")).toBeNull();
273
+ put({ stage: "abandoned", worktree: wt });
274
+ expect(linkedWs(state, "sh-0123abcd")).toBeNull();
275
+ put({ stage: "build", worktree: join(p, "gone") });
276
+ expect(linkedWs(state, "sh-0123abcd")).toBeNull();
277
+ put({ stage: "build" }); // a current-folder run has no worktree
278
+ expect(linkedWs(state, "sh-0123abcd")).toBeNull();
279
+ });
package/cli/worktree.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // One branch and one git worktree per run, so agents building at the same time never
2
2
  // share a working folder. Run notes stay in the project's .kaizen/runs/<id>/; only the
3
3
  // code lives in the worktree. Every git call is an argv array, never a shell string.
4
- import { existsSync, readFileSync, writeFileSync, rmSync, realpathSync } from "node:fs";
4
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync, realpathSync } from "node:fs";
5
5
  import { join, dirname, resolve, sep } from "node:path";
6
6
  import { branchesOf } from "./add-project.ts";
7
7
 
@@ -115,7 +115,8 @@ export function landWorktree(project: string, id: string, sh: Run = run,
115
115
  const pr = sh(["gh", "pr", "create", "--base", base, "--head", branch, "--title", subject, "--body", `Run ${id}.`], dir);
116
116
  // An existing pull request for the branch is fine: merge that one.
117
117
  const url = pr.ok ? pr.out.split("\n").pop() : undefined;
118
- if (!pr.ok && !/already exists/i.test(pr.why)) return { ok: false, why: `pull request failed: ${pr.why}; ${branch} is pushed` };
118
+ // gh prints the "already exists" line, then the URL, and `why` holds only the last line.
119
+ if (!pr.ok && !/already exists|\/pull\/\d+$/i.test(pr.why)) return { ok: false, why: `pull request failed: ${pr.why}; ${branch} is pushed` };
119
120
  const merge = sh(["gh", "pr", "merge", branch, "--rebase"], dir);
120
121
  if (!merge.ok) return { ok: false, why: `pull request not merged (${merge.why}); left open, worktree kept` };
121
122
  return finish("pr", url);
@@ -311,6 +312,24 @@ export const wsOf = (project: string, state: { worktree?: unknown; workspace?: u
311
312
  return typeof w === "string" ? real(w) : project;
312
313
  };
313
314
 
315
+ /** A board terminal's link to the run it started a worktree for: <state>/sessions/<key>.run holds the run id. */
316
+ const termFile = (state: string, key: string) => join(state, "sessions", `${key}.run`);
317
+ export const linkTerm = (state: string, key: string | undefined, id: string) => {
318
+ if (!key || !/^sh-[0-9a-f]{8}$/.test(key)) return;
319
+ mkdirSync(join(state, "sessions"), { recursive: true });
320
+ writeFileSync(termFile(state, key), id);
321
+ };
322
+ /** The worktree a linked terminal's live run is in; null when it has no link, the run ended, or the worktree is gone. */
323
+ export function linkedWs(state: string, key: string): string | null {
324
+ try {
325
+ const id = readFileSync(termFile(state, key), "utf8").trim();
326
+ const s = JSON.parse(readFileSync(join(state, "runs", id, "state.json"), "utf8"));
327
+ if (s.stage === "done" || s.stage === "abandoned") return null;
328
+ const project = dirname(state), w = wsOf(project, s);
329
+ return w === project ? null : w;
330
+ } catch { return null; }
331
+ }
332
+
314
333
  /**
315
334
  * `kaizen worktree start` run from inside one of the project's other workspaces: the run is
316
335
  * placed there (`workspace` in state.json) and no second worktree is made. It is not recorded
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kaizen-agent",
3
- "version": "1.61.6",
3
+ "version": "1.62.0",
4
4
  "description": "Staged workflow for AI agents — code, writing, research, operations: plan, human approval, build, independent review, bounded fix loop.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -106,7 +106,33 @@ git:
106
106
  # .kaizen/wt/, so runs and people working at the same time never share a folder. Done
107
107
  # lands the branch by pull request (gh) or a rebase and push. Ignored when the
108
108
  # project is not a git repository with a remote.
109
- worktree_per_run: true
109
+ # ask: the plan approval offers a new worktree or the current folder; auto mode takes
110
+ # a new worktree. true always makes one, false never does.
111
+ worktree_per_run: ask
112
+
113
+ orchestration:
114
+ # true: a plan may split into workers (a `## Workers` section you approve with the plan).
115
+ # Each worker is a real agent terminal on the board, in its own branch and folder; the
116
+ # run's build agent merges them when every one has succeeded. Off by default, and with it
117
+ # off nothing behaves differently. Needs the board running, a run worktree, a full (not
118
+ # lite) run, and Linux or macOS. A run's own `kaizen worker set <run> on|off` wins.
119
+ enabled: false
120
+ # Most workers one run may be split into (1-6). A run already building keeps the value it started with.
121
+ max_workers: 3
122
+ # own: each worker uses its agent's own permission prompts (your global bypass is NOT inherited).
123
+ # bypass: every worker skips every prompt; its tab and the run's card say so.
124
+ permissions: own
125
+ # Model each worker runs on, per tool, in that tool's own spelling (haiku for Claude Code,
126
+ # a gpt name for Codex). Empty: the run's own model, exactly as before. Only the run's own
127
+ # agent's value is used, frozen into the run when its build starts. Any name is accepted;
128
+ # the tool itself reports one it does not know. A tool with no model flag ignores it, and
129
+ # the worker's record in workers.json says so.
130
+ worker_model:
131
+ claude: ""
132
+ agy: ""
133
+ codex: ""
134
+ gemini: ""
135
+ opencode: ""
110
136
 
111
137
  ui:
112
138
  # Mouse in the TUI: click a row or card to select it, click it again to open or
@@ -153,6 +179,12 @@ agent:
153
179
  # a board restart or crash; the next board shows them again mid-step.
154
180
  # Linux and macOS with tmux installed; elsewhere it acts as off.
155
181
  keep_alive: off
182
+ # Stops idle sleep from the board. off | auto (while the board runs agents) | on
183
+ # (while the board is open). Linux and macOS; agents in an outside terminal don't count.
184
+ keep_awake: off
185
+ # Minutes between an agent's reports. Quiet for two of these with no terminal
186
+ # activity, its card says stale.
187
+ heartbeat_minutes: 5
156
188
  # Per-tool model and effort for the session the board launches, passed as that
157
189
  # tool's own flags (claude --model/--effort, agy --model/--effort, codex -m and
158
190
  # model_reasoning_effort, gemini -m, opencode -m). Model names are the tool's own:
@@ -25,7 +25,7 @@ nearest first, so a change lands globally unless this project keeps its own conf
25
25
  | `auto_fix.max_iterations` | `1`–`5` | Fix and recheck rounds before what is left is escalated |
26
26
  | `review.write_memory` | `true`, `false` | Let the reviewer append lessons to `memory.md` |
27
27
  | `git.auto_commit` | `true`, `false` | Commit the work when a run finishes |
28
- | `git.worktree_per_run` | `true`, `false` | Build each run on its own branch in its own worktree and land it by pull request |
28
+ | `git.worktree_per_run` | `ask`, `true`, `false` | Build each run on its own branch in its own worktree and land it by pull request; `ask` offers the choice at the plan approval |
29
29
  | `ui.mouse` | `false`, `true` | Click to select, click again to act; while on, the terminal cannot select text |
30
30
  | `subagents.model` | `inherit`, `opus`, `sonnet`, `haiku` | Model the stage subagents run on (Claude Code only) |
31
31
  | `subagents.effort` | `inherit`, `low`, `medium`, `high` | Reasoning effort for the stage subagents (Claude Code only) |
@@ -0,0 +1 @@
1
+ {"title": "Kaizen workflow", "group": "core", "needs": []}
@@ -39,8 +39,9 @@ Rules:
39
39
  folder there is no branch to make and no commit to skip, and that absence is not a
40
40
  finding.
41
41
 
42
- **Build on the run's own branch, where `git.worktree_per_run` is on** (the default, in a
43
- git repository with a remote). Right after `stage: "build"` is written and before the
42
+ **Build on the run's own branch, where `git.worktree_per_run` is `true`, or `ask` and the
43
+ plan approval chose a new worktree or the mode is `auto`** (in a git repository with a remote;
44
+ a chosen current folder skips this and builds in place). Right after `stage: "build"` is written and before the
44
45
  first edit, run `kaizen worktree start` with the run id from the project folder. It
45
46
  makes `.kaizen/wt/<id>` on the branch `kaizen/<id>`, cut from the remote default branch,
46
47
  and records `worktree` and `branch` in `state.json`. From then on every edit, test run
@@ -54,6 +55,25 @@ code in the same folder. If `kaizen worktree start` fails, say why and stop; do
54
55
  back to the project folder unasked. A run whose `state.json` has no `worktree` builds in
55
56
  place, exactly as before.
56
57
 
58
+ **Workers, only when the run has them.** When `01-plan.md` has a `## Workers` section and
59
+ `02-approval.md` says `workers: approved`, the build agent is the coordinator. Run
60
+ `kaizen worker init`: if it refuses, say why in `03-impl.md` and build the whole plan
61
+ yourself as usual. Otherwise run `kaizen worker start <wid>` for each worker whose
62
+ `after:` workers have succeeded (it asks the board to open the worker's own terminal, in
63
+ its own branch and folder; no board running means it says so and nothing starts), and
64
+ watch `kaizen worker status`. A worker owns only its paths, commits, and hands back with
65
+ `kaizen worker report done`. You never edit a worker's paths yourself. On any worker
66
+ that fails, blocks or ends unverified, stop and report it with the worker's id: do not
67
+ merge, and do not start the rest. When every worker has succeeded, run
68
+ `kaizen worker merge` in place of building the halves: it merges in plan order, and a
69
+ conflict undoes the whole merge and stops you with a blocker, so tell the user and wait.
70
+ Then the baseline, the gate and `03-impl.md` run on the merged branch as for any build.
71
+ A worker's terminal never starts in bypass unless Settings > Orchestration says so; the
72
+ setting is frozen in `workers.json` at init, which any local process can edit, so bypass
73
+ is visible (tab title and card) rather than guarded. A worker with `after:` branches off
74
+ the worker it follows; `merge` refuses a branch that changed paths outside its `owns:`,
75
+ and reports any worker folder or branch it could not remove.
76
+
57
77
  **Keep `progress.md` while you work.** Before the first change, write
58
78
  `runs/<id>/progress.md` with one line per bullet of the plan's Work list, in order:
59
79
  `- todo: <bullet text>`. Change a line's prefix to `- doing:` when you start that item
@@ -3,6 +3,15 @@
3
3
  Read with [`spec.md`](spec.md) (core: track, intake, resume). Backlog bookkeeping and
4
4
  the final approval. No subagent reads this file.
5
5
 
6
+ ---
7
+ ## Workers
8
+
9
+ Orchestration (`kaizen worker`, Settings > Orchestration) is off by default and is ignored
10
+ under `runner: lite`. The settings (including the worker model) are read once, when the build calls `kaizen worker init`,
11
+ and frozen into the run's `workers.json`: changing them afterwards changes nothing for a
12
+ run already building. At the plan approval, record the `Build with workers?` answer in
13
+ `02-approval.md` as `workers: approved` or `workers: declined`.
14
+
6
15
  ---
7
16
  ## Backlog
8
17
 
@@ -205,7 +205,10 @@ The planner reads code but writes none. Its plan must contain:
205
205
 
206
206
  8. **Risks** — what could break, what is irreversible, what needs a migration or a
207
207
  backup taken first.
208
- 9. **Open questions** — assumptions that survived the interview. If this list is
208
+ 9. **Open questions** — where `git.worktree_per_run` is `ask`, the mode is not `auto` and
209
+ the work is in a git repository with a remote, always `Q: Where should this run build?`
210
+ with `- New worktree (recommended) — its own branch` and `- Current folder — no branch`;
211
+ the answer goes in `02-approval.md`. Then the assumptions that survived the interview. If this list is
209
212
  non-empty, the approval must ask the user about it rather than defaulting. The
210
213
  board shows a waiting plan's questions as a pick list and sends the answers with
211
214
  its approval, so keep this shape: each question on its own line as
@@ -241,6 +244,20 @@ code, it is in the wrong section.
241
244
  A plan whose framing is longer than its steps is a plan that spent the run's budget
242
245
  explaining itself.
243
246
 
247
+ **Workers, only when on.** Run `kaizen worker config <run id>`. It prints `on`, or `off`
248
+ with the reason (off by default; also off for a lite run, a run with no worktree, and on
249
+ Windows). While it says off, the plan has no workers and nothing here applies. While it
250
+ says on, and the work really has two or more independent halves that touch different
251
+ files, add a `## Workers` section: one line per worker, in order,
252
+ `w1 — <title> — owns: <path>, <path> — after: w0` (`after:` only where one must wait for
253
+ another, and only on an earlier worker). Rules: at most the `max` that `config` prints;
254
+ every path is owned by exactly one worker (a folder owns what is under it, and two
255
+ workers never own the same path); each owns a whole piece it can finish and test alone.
256
+ Fewer than two independent halves is not a split: leave the section out. The approval
257
+ asks `Q: Build with workers?` with `yes` (recommended while the halves are clear) and
258
+ `no`; the main thread records the answer in `02-approval.md` as a line
259
+ `workers: approved` or `workers: declined`. Nothing is split without that line.
260
+
244
261
  ---
245
262
 
246
263
  ## Plan approval
@@ -11,6 +11,10 @@ reviewer's contract. The planner and builder do not read it.
11
11
  read), `03-impl.md`, and the work produced.
12
12
  **Output:** `04-review.md`.
13
13
 
14
+ **Where the run has a `workers.json`** in its folder, read it too. The code under review
15
+ is the merged branch. Any worker whose status is not `merged`, or a `merge` that is not
16
+ `merged`, is a finding at high severity: say which worker and what its status is.
17
+
14
18
  The track's third answer — *what would make it wrong* — is the reviewer's primary
15
19
  brief. It reads that first and hunts for it specifically.
16
20