kaizen-agent 1.70.0 → 1.71.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 (55) hide show
  1. package/README.md +2 -2
  2. package/cli/annotate-proxy.ts +5 -0
  3. package/cli/automations.ts +10 -3
  4. package/cli/browser.ts +1 -1
  5. package/cli/chat.ts +9 -1
  6. package/cli/chatgpt.ts +2 -1
  7. package/cli/docs.ts +1 -1
  8. package/cli/google.ts +2 -1
  9. package/cli/handoff.ts +1 -1
  10. package/cli/install.ts +28 -8
  11. package/cli/knowledge.ts +1 -1
  12. package/cli/notes.ts +10 -1
  13. package/cli/settings.ts +5 -1
  14. package/cli/sources.ts +3 -2
  15. package/cli/state.ts +43 -5
  16. package/cli/versions.ts +1 -1
  17. package/cli/video.ts +1 -1
  18. package/cli/web.ts +43 -27
  19. package/cli/workers.ts +20 -7
  20. package/cli/worktree.ts +55 -15
  21. package/package.json +1 -1
  22. package/skills/kaizen/SKILL.md +12 -8
  23. package/skills/kaizen/config.default.yml +18 -2
  24. package/skills/kaizen/settings.md +3 -1
  25. package/skills/kaizen/spec-build.md +13 -2
  26. package/skills/kaizen/spec-main.md +2 -0
  27. package/skills/kaizen-help/SKILL.md +1 -0
  28. package/skills/media/kaizen-game/SKILL.md +96 -0
  29. package/skills/media/kaizen-game/assets/gdd.css +12 -0
  30. package/skills/media/kaizen-game/references/build.md +81 -0
  31. package/skills/media/kaizen-game/references/content.md +32 -0
  32. package/skills/media/kaizen-game/references/design.md +81 -0
  33. package/skills/media/kaizen-game/references/ship.md +34 -0
  34. package/skills/media/kaizen-game/references/verify.md +33 -0
  35. package/skills/media/kaizen-game/scripts/check.sh +13 -0
  36. package/skills/media/kaizen-game/scripts/frames.mjs +34 -0
  37. package/skills/media/kaizen-game/scripts/gdd-pdf.mjs +19 -0
  38. package/skills/media/kaizen-game/scripts/pw.mjs +18 -0
  39. package/skills/media/kaizen-game/scripts/serve.mjs +53 -0
  40. package/skills/media/kaizen-game/scripts/serve.test.mjs +18 -0
  41. package/skills/media/kaizen-game/scripts/setup.sh +9 -0
  42. package/skills/media/kaizen-game/scripts/smoke.mjs +40 -0
  43. package/skills/media/kaizen-game/skill.json +1 -0
  44. package/web/board/icebox.ts +6 -3
  45. package/web/board/markdown.ts +7 -2
  46. package/web/board/run-view.ts +1 -1
  47. package/web/board/settings-orchestration.ts +1 -1
  48. package/web/board/settings-pages.ts +1 -0
  49. package/web/board/settings-skills.ts +1 -0
  50. package/web/board/settings.ts +2 -2
  51. package/web/board.js +70 -70
  52. package/web/notebook.js +1 -1
  53. package/web/term.js +48 -48
  54. package/web/term.ts +16 -4
  55. package/web/video.js +1 -1
package/cli/web.ts CHANGED
@@ -16,7 +16,7 @@ import { readReport, signalOf } from "./report.ts";
16
16
  import { MAX_IMAGE, saveImage } from "./term-image.ts";
17
17
  import { bundledSkills, setSkill, skillsHeld, skillsOff, skillStatus } from "./skills.ts";
18
18
  import { accountEnv, accountForRun, agentUsable, CHILD_ENV, heartbeatMinutes, keepAwake, launchPreview, trustFolder, YOLO_FLAGS } from "./state.ts";
19
- import { agentLine, failStart, markRunning, readWorkers, requested, startWorker, sweep, workerStale } from "./workers.ts";
19
+ import { agentLine, failStart, handoffModel, markRunning, readWorkers, requested, startWorker, sweep, workerStale } from "./workers.ts";
20
20
  import { childDied, childQuiet, markWoken, move, requestOpen, readHandoff, refused, started, wakeAction, wakeLine, type Handoff } from "./handoff.ts";
21
21
  import { processTable, storage, systemMemory, treeRss, type Root } from "./resources.ts";
22
22
  import { attachPty, frames, writePty, submitPty, resizePty, exitPty, killPty, panePid, ptyState, ptyKeys, adoptLoginEnv, startPty, ptySupported, detachPty, ptyTail, ptyTmux, tmuxAlive, RESUMED } from "./pty.ts";
@@ -287,7 +287,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
287
287
  const sameOrigin = (req: Request) => {
288
288
  const origin = req.headers.get("origin");
289
289
  let same = !origin;
290
- try { if (origin) { const o = new URL(origin); same = o.host === req.headers.get("host") || extraHosts.has(o.hostname); } } catch { /* bad origin */ }
290
+ try { if (origin) { const o = new URL(origin); same = o.host === req.headers.get("host"); } } catch { /* bad origin */ }
291
291
  return same;
292
292
  };
293
293
  // One-time token for turning an off-by-default skill on; each GET /skills mints a new one. It stops
@@ -502,7 +502,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
502
502
  const cwd = codeDir(project, id), key = "sh-" + crypto.randomUUID().slice(0, 8);
503
503
  const prompt = `/kaizen run ${id}. You are the worktree agent of this run: the project is ${project}, its run files are in ${join(dir, "runs", id)}, and you work in ${cwd}. ` +
504
504
  `Build, review and run the fix loop as the spec says. Do not run kaizen done or land. When finished run: kaizen handoff done. If you cannot go on run: kaizen handoff blocked "<reason>".`;
505
- const l = cwd === project ? "the run has no worktree" : agentLine(project, id, prompt, "own");
505
+ const l = cwd === project ? "the run has no worktree" : agentLine(project, id, prompt, "own", undefined, handoffModel(project, id));
506
506
  if (typeof l === "string") { refused(dir, id, l); changed(); return; }
507
507
  if (!started(dir, id, key)) return; // declined meanwhile: the first agent is building
508
508
  for (const k of Object.keys(process.env)) if (CHILD_ENV.test(k)) delete process.env[k];
@@ -711,6 +711,9 @@ export async function web(repoDir: string, opts: Opts = {}) {
711
711
  // arrives with that hostname in Host, and gets nothing.
712
712
  const hostname = (req.headers.get("host") ?? "").toLowerCase().replace(/:\d+$/, "");
713
713
  if (hostname !== "127.0.0.1" && hostname !== "localhost" && !extraHosts.has(hostname)) return new Response("forbidden", { status: 403 });
714
+ // `tailscale serve` stamps every tailnet request with the caller's login; `tailscale funnel` (the
715
+ // public internet) does not. A tailnet name reached without it is not a tailnet peer.
716
+ if (hostname.endsWith(".ts.net") && !req.headers.get("tailscale-user-login")) return new Response("forbidden", { status: 403 });
714
717
  if (req.method !== "GET") { stateGen++; gitGen++; }
715
718
  const url = new URL(req.url);
716
719
  const path = url.pathname;
@@ -762,7 +765,10 @@ export async function web(repoDir: string, opts: Opts = {}) {
762
765
  // board when no window shows it) and close the popup. Hyprland moves windows;
763
766
  // elsewhere only the popup opens and closes.
764
767
  if (req.method === "POST" && (path === "/popup/open" || path === "/popup/board")) {
768
+ const refused = strict(req);
769
+ if (refused) return refused;
765
770
  const body = await req.json().catch(() => ({}));
771
+ if (body?.id != null && !/^(?!\.+$)[\w.-]+$/.test(String(body.id))) return bad("bad id");
766
772
  const chat = (...a: string[]) => Bun.spawn([process.execPath, join(import.meta.dir, "install.ts"), "chat", "--port", String(new URL(req.url).port || DEFAULT_PORT), ...a], { stdout: "ignore", stderr: "ignore", windowsHide: true }).exited;
767
773
  const hypr = !!process.env.HYPRLAND_INSTANCE_SIGNATURE && !!Bun.which("hyprctl");
768
774
  const json = async (cmd: string) => await Bun.$`hyprctl ${cmd} -j`.quiet().nothrow().json().catch(() => null);
@@ -779,7 +785,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
779
785
  if ((await Bun.$`hyprctl dispatch ${lua}`.quiet().nothrow().text()).trim() !== "ok") await Bun.$`hyprctl dispatch ${legacy}`.quiet().nothrow();
780
786
  };
781
787
  if (path === "/popup/open") {
782
- const id = typeof body.id === "string" && /^[\w.-]+$/.test(body.id) ? body.id : "";
788
+ const id = typeof body.id === "string" && /^(?!\.+$)[\w.-]+$/.test(body.id) ? body.id : "";
783
789
  await chat("--show", ...(id ? ["--chat", id] : []));
784
790
  if (w) await dispatch(`hl.dsp.window.move({ workspace = "special:kaizen", follow = false, window = "${w}" })`, ["movetoworkspacesilent", `special:kaizen,${w}`]);
785
791
  // Typing goes to the popup, not to whatever was under the hidden board.
@@ -908,7 +914,9 @@ export async function web(repoDir: string, opts: Opts = {}) {
908
914
  if (!sameOrigin(req)) return bad("cross-origin request refused", 403);
909
915
  if (!/^image\//i.test(req.headers.get("content-type") ?? "")) return bad("image body expected", 415);
910
916
  if (Number(req.headers.get("content-length") ?? 0) > MAX_IMAGE) return bad("image too large", 413);
911
- const saved = saveImage(new Uint8Array(await req.arrayBuffer()));
917
+ const bytes = new Uint8Array(await req.arrayBuffer());
918
+ if (bytes.length > MAX_IMAGE) return bad("image too large", 413); // a chunked body has no content-length
919
+ const saved = saveImage(bytes);
912
920
  return saved ? json({ path: saved }) : bad("not an image", 415);
913
921
  }
914
922
  if (req.method === "POST" && path === "/shell") {
@@ -1215,6 +1223,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
1215
1223
  let u: URL;
1216
1224
  try { u = new URL(String(body.url ?? "")); } catch { return bad("not a url"); }
1217
1225
  if (!/^https?:$/.test(u.protocol) || !isLoopback(u)) return bad("only a localhost address", 400);
1226
+ // Not the board itself: a proxy to it would forward /pty with an Origin rewritten to the board's own.
1227
+ if (u.port === (new URL(req.url).port || "80")) return bad("that is the board's own port", 400);
1218
1228
  try {
1219
1229
  const px = openProxy(u);
1220
1230
  return json({ ok: true, origin: px.origin, token: px.token, url: px.origin + u.pathname + u.search + u.hash });
@@ -1232,7 +1242,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1232
1242
  if (path === "/annotate/format") return json({ ok: true, text: annMarkdown(notes, level, comps) });
1233
1243
  const dir = canonState(String(body.dir ?? ""));
1234
1244
  const id = String(body.id ?? "");
1235
- if (!states(true).includes(dir) || dir === join(home, ".kaizen") || !/^[\w.-]+$/.test(id)) return bad("choose a run", 404);
1245
+ if (!states(true).includes(dir) || dir === join(home, ".kaizen") || !/^(?!\.+$)[\w.-]+$/.test(id)) return bad("choose a run", 404);
1236
1246
  const live = liveAgent(dir, id);
1237
1247
  if (!live) return bad("this run has no agent open to send to", 409);
1238
1248
  const crops = saveCrops(dir, id, notes);
@@ -1433,7 +1443,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1433
1443
  if (req.method === "GET" && path.startsWith("/run/")) {
1434
1444
  const id = decodeURIComponent(path.slice(5));
1435
1445
  const dir = qdir() ?? state;
1436
- if (!dir || !states(true).includes(dir) || !/^[\w.-]+$/.test(id)) return bad("no such run", 404);
1446
+ if (!dir || !states(true).includes(dir) || !/^(?!\.+$)[\w.-]+$/.test(id)) return bad("no such run", 404);
1437
1447
  const base = join(dir, "runs", id);
1438
1448
  if (!existsSync(base)) return bad("no such run", 404);
1439
1449
  const read = (f: string) => existsSync(join(base, f)) ? readText(join(base, f)) : null;
@@ -1803,11 +1813,12 @@ export async function web(repoDir: string, opts: Opts = {}) {
1803
1813
  const dir = qdir() ?? state;
1804
1814
  const p = url.searchParams.get("p") ?? "";
1805
1815
  if (!dir || !states(true).includes(dir)) return bad("unknown state dir", 404);
1806
- if (!/^(runs\/[\w.-]+\/)?attachments\/[\w.-]+$/.test(p)) return bad("bad path");
1816
+ if (!/^(runs\/[\w.-]+\/)?attachments\/(?!\.+$)[\w.-]+$/.test(p)) return bad("bad path");
1807
1817
  const f = join(dir, p);
1808
1818
  if (!existsSync(f)) return bad("no such file", 404);
1809
1819
  // no-cache: a revise retakes a screenshot under the same name, and the browser must ask again.
1810
- return new Response(Bun.file(f), { headers: { "cache-control": "private, no-cache" } });
1820
+ // sandbox + nosniff: an attached .html/.svg opened directly must run nothing on the board origin.
1821
+ return new Response(Bun.file(f), { headers: { "cache-control": "private, no-cache", "content-security-policy": "sandbox", "x-content-type-options": "nosniff" } });
1811
1822
  }
1812
1823
 
1813
1824
  // An icebox image, sent on to a link read fresh from its source: the one kept
@@ -1844,13 +1855,14 @@ export async function web(repoDir: string, opts: Opts = {}) {
1844
1855
  return c ? json({ ...c, busy: chatBusy(base, c.id) }) : bad("no such chat", 404);
1845
1856
  }
1846
1857
  if (req.method !== "POST") return bad("method not allowed", 405);
1847
- if (!local(req)) return bad("cross-origin write refused", 403);
1858
+ // sameOrigin, not local(): a multipart form is a simple request any page can send, and a chat starts an agent.
1859
+ if (!sameOrigin(req)) return bad("cross-origin write refused", 403);
1848
1860
  let body: any;
1849
1861
  let uploads: ChatUpload[] = [];
1850
1862
  if (path === "/chat" && req.headers.get("content-type")?.startsWith("multipart/form-data")) {
1851
1863
  if (Number(req.headers.get("content-length")) > 320 * 1024 * 1024) return bad("attachments too large", 413);
1852
1864
  let form: FormData;
1853
- try { form = await req.formData(); } catch { return bad("form data expected"); }
1865
+ try { form = await req.formData(); } catch { return bad("form data expected"); } // the per-file and total caps below also cover a chunked body
1854
1866
  const files = form.getAll("files");
1855
1867
  if (files.length > 20 || files.some((f) => !(f instanceof File) || f.size > 100 * 1024 * 1024) || files.reduce((n, f) => n + (f instanceof File ? f.size : 0), 0) > 300 * 1024 * 1024) return bad("up to 20 files, 100 MB each and 300 MB total", 413);
1856
1868
  body = { id: form.get("id"), text: form.get("text") ?? "", project: form.get("project") };
@@ -1900,7 +1912,10 @@ export async function web(repoDir: string, opts: Opts = {}) {
1900
1912
  }
1901
1913
 
1902
1914
  if (req.method === "POST") {
1903
- if (!local(req)) return bad("cross-origin write refused", 403);
1915
+ // strict, not local(): this block starts agents (/run yolo, /fix, /shell-like ops), so a
1916
+ // page on another local port or a text/plain no-cors POST must not reach it.
1917
+ const refused = strict(req);
1918
+ if (refused) return refused;
1904
1919
  let body: any;
1905
1920
  try { body = await req.json(); } catch { return bad("json body expected"); }
1906
1921
  for (const k of ["dir", "to"]) if (typeof body?.[k] === "string" && body[k]) body[k] = canonState(body[k]);
@@ -2209,7 +2224,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
2209
2224
  if (path === "/archive") {
2210
2225
  const archived = body.archived !== false;
2211
2226
  if (typeof body.id === "string") {
2212
- if (!/^[\w.-]+$/.test(body.id)) return bad("bad run id");
2227
+ if (!/^(?!\.+$)[\w.-]+$/.test(body.id)) return bad("bad run id");
2213
2228
  setArchived(dir, body.id, archived);
2214
2229
  } else if (typeof body.text === "string") {
2215
2230
  const text = body.text.trim();
@@ -2227,7 +2242,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
2227
2242
  // from the message so the note carries its own attachments.
2228
2243
  if (path === "/note") {
2229
2244
  const id = typeof body.id === "string" ? body.id : null;
2230
- if (id !== null && !/^[\w.-]+$/.test(id)) return bad("bad run id");
2245
+ if (id !== null && !/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
2246
+ if (id !== null && !existsSync(join(dir, "runs", id, "state.json"))) return bad("no such run", 404); // no attachments folder for a run that is not there
2231
2247
  const text = typeof body.text === "string" ? body.text.trim() : "";
2232
2248
  const files: { name: string; data: string }[] = Array.isArray(body.files) ? body.files : [];
2233
2249
  let total = 0;
@@ -2246,7 +2262,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
2246
2262
 
2247
2263
  if (path === "/notes") {
2248
2264
  const id = String(body.id ?? "");
2249
- if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
2265
+ if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
2250
2266
  const failed = writeNotes(dir, id, String(body.text ?? ""));
2251
2267
  changed();
2252
2268
  return failed ? bad(failed, 404) : json({ ok: true });
@@ -2271,7 +2287,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
2271
2287
  // global state dir: $HOME may be a repository, and it is not the run's project.
2272
2288
  if (path === "/commit") {
2273
2289
  const id = String(body.id ?? "");
2274
- if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
2290
+ if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
2275
2291
  if (dir === join(home, ".kaizen")) return bad("no project to commit", 409);
2276
2292
  let run: any;
2277
2293
  try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return bad("no such run", 404); }
@@ -2287,7 +2303,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
2287
2303
  // takes and only on the run's own files (stageFiles refuses any other path).
2288
2304
  if (path === "/stage") {
2289
2305
  const id = String(body.id ?? "");
2290
- if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
2306
+ if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
2291
2307
  if (dir === join(home, ".kaizen")) return bad("no project", 409);
2292
2308
  let run: any;
2293
2309
  try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return bad("no such run", 404); }
@@ -2302,7 +2318,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
2302
2318
  // The sparkle button: a commit message for the run's files, written from their diff.
2303
2319
  if (path === "/commit-message") {
2304
2320
  const id = String(body.id ?? "");
2305
- if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
2321
+ if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
2306
2322
  if (dir === join(home, ".kaizen")) return bad("no project", 409);
2307
2323
  const r = await suggestMessage(dir, id);
2308
2324
  return r.ok ? json(r) : bad(r.why, 409);
@@ -2312,7 +2328,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
2312
2328
  // request, merge it, then remove the worktree once its work is on the base.
2313
2329
  if (path === "/pr") {
2314
2330
  const id = String(body.id ?? "");
2315
- if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
2331
+ if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
2316
2332
  // One step per run at a time: a second tab's Merge or Remove waits its turn.
2317
2333
  const lock = `${dir}\0${id}`;
2318
2334
  if (prBusy.has(lock)) return bad("Another git step is running on this run. Try again when it finishes.", 409);
@@ -2339,7 +2355,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
2339
2355
  // not there. Only numbers the review itself holds reach the prompt.
2340
2356
  if (path === "/fix") {
2341
2357
  const id = String(body.id ?? "");
2342
- if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
2358
+ if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
2343
2359
  if (dir === join(home, ".kaizen")) return bad("no project to fix in", 409);
2344
2360
  let run: any;
2345
2361
  try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return bad("no such run", 404); }
@@ -2371,7 +2387,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
2371
2387
  // the approval it saw: one already answered elsewhere is not answered twice.
2372
2388
  if (path === "/decide") {
2373
2389
  const id = String(body.id ?? "");
2374
- if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
2390
+ if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
2375
2391
  if (dir === join(home, ".kaizen")) return bad("no project to run in", 409);
2376
2392
  let run: any;
2377
2393
  try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return bad("no such run", 404); }
@@ -2416,7 +2432,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
2416
2432
  // only, no agent is started.
2417
2433
  if (path === "/accept") {
2418
2434
  const id = String(body.id ?? "");
2419
- if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
2435
+ if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
2420
2436
  if (gateOf(dir, id) !== "needs") return bad("this run is not waiting on your approval", 409);
2421
2437
  // Only a finished-but-unapproved run: a genuine review goes through /decide.
2422
2438
  let st: any = {};
@@ -2432,7 +2448,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
2432
2448
  // Start a run's agent again after it ended mid-stage (resumeRun).
2433
2449
  if (path === "/resume") {
2434
2450
  const id = String(body.id ?? "");
2435
- if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
2451
+ if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
2436
2452
  if (dir === join(home, ".kaizen")) return bad("no project to run in", 409);
2437
2453
  const r = resumeRun(dir, id);
2438
2454
  if ("error" in r) return bad(r.error, r.status);
@@ -2443,7 +2459,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
2443
2459
 
2444
2460
  if (path === "/to-task" || path === "/to-idea") { // /to-idea: the old name, kept for open tabs
2445
2461
  const id = String(body.id ?? "");
2446
- if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
2462
+ if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
2447
2463
  const failed = runToTask(dir, id);
2448
2464
  changed();
2449
2465
  return failed ? bad(failed, 409) : json({ ok: true });
@@ -2452,7 +2468,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
2452
2468
  if (path === "/abort") {
2453
2469
  const id = String(body.id ?? "");
2454
2470
  const why = String(body.why ?? "").trim() || "abandoned from the web";
2455
- if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
2471
+ if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
2456
2472
  const failed = abandonRun(dir, id, why);
2457
2473
  changed();
2458
2474
  return failed ? bad(failed, 409) : json({ ok: true });
@@ -2676,9 +2692,9 @@ export async function openApp(url: string, profile?: string) {
2676
2692
  }
2677
2693
 
2678
2694
  async function openDefault(url: string) {
2679
- // `start` is a cmd builtin, not a program, so it has to go through cmd.
2695
+ // Not `cmd /c start`: cmd splits a URL at `&`, `|` or `^` and would run what follows.
2680
2696
  if (process.platform === "win32") {
2681
- try { await Bun.$`${cmdExe()} /c start "" ${url}`.quiet(); return true; } catch { return false; }
2697
+ try { await Bun.spawn(["rundll32", "url.dll,FileProtocolHandler", url], { stdout: "ignore", stderr: "ignore", windowsHide: true }).exited; return true; } catch { return false; }
2682
2698
  }
2683
2699
  const opener = process.platform === "darwin" ? "open" : "xdg-open";
2684
2700
  if (!Bun.which(opener)) return false;
package/cli/workers.ts CHANGED
@@ -9,8 +9,8 @@ import { join } from "node:path";
9
9
  import { argsOf, commandOf, readPrefs, withEnv, type Prefs } from "./agent-prefs.ts";
10
10
  import { clip, reportBlocked, reportUnblock, validId } from "./report.ts";
11
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";
12
+ import { accountEnv, accountForRun, agentFlags, agentUsable, detectDefaultAgent, MODEL_FLAGS, plainModel, promptArgs, readText, runAgent, subagentEnv, YOLO_FLAGS } from "./state.ts";
13
+ import { branchFor, branchOf, run as sh } from "./worktree.ts";
14
14
 
15
15
  export type Status = "planned" | "requested" | "running" | "blocked" | "succeeded" | "failed" | "unverified" | "conflict" | "merged" | "stopped";
16
16
  export type Worker = {
@@ -42,7 +42,7 @@ function locked<T>(project: string, id: string, fn: () => T): T {
42
42
  const lock = fileOf(project, id) + ".lock";
43
43
  for (let i = 0; ; i++) {
44
44
  try { mkdirSync(lock); break; } catch {
45
- try { if (Date.now() - statSync(lock).mtimeMs > 10_000) rmSync(lock, { recursive: true }); } catch { /* gone */ }
45
+ try { if (Date.now() - statSync(lock).mtimeMs > 10_000) { const aside = `${lock}.${process.pid}.${i}.stale`; renameSync(lock, aside); rmSync(aside, { recursive: true, force: true }); } } catch { /* gone */ }
46
46
  if (i > 60) throw new Error("workers.json is locked: try again");
47
47
  Bun.sleepSync(50);
48
48
  }
@@ -200,6 +200,17 @@ export function launchOf(project: string, id: string, x: Worker, permissions: "o
200
200
  return { ...l, title: `Worker ${x.id}${l.bypass ? " · bypass" : ""}`, cwd: x.worktree, env: { KAIZEN_RUN_ID: id, KAIZEN_WORKER: x.id } };
201
201
  }
202
202
 
203
+ /** The model for this run's handoff agent: agent.handoff_model.<the run's tool>, project first. "": the run's own. */
204
+ export function handoffModel(project: string, id: string): string {
205
+ const cmd = runAgent(join(project, ".kaizen"), id)?.cmd ?? stateOf(project, id)?.agent;
206
+ if (typeof cmd !== "string" || !/^\w+$/.test(cmd)) return "";
207
+ for (const f of [join(project, ".kaizen", "config.yml"), join(homedir(), ".kaizen", "config.yml")]) {
208
+ const v = existsSync(f) ? read(readText(f), `agent.handoff_model.${cmd}`) : null;
209
+ if (v) return plainModel(v) ? v : "";
210
+ }
211
+ return "";
212
+ }
213
+
203
214
  /** The run's agent as a command line with `prompt`. Shared with the handoff; the caller names the terminal. */
204
215
  export function agentLine(project: string, id: string, prompt: string, permissions: "own" | "bypass", prefs: Prefs = readPrefs(), pick = ""): Omit<Launch, "title" | "cwd" | "env"> | string {
205
216
  const own = runAgent(join(project, ".kaizen"), id), st = stateOf(project, id);
@@ -213,8 +224,10 @@ export function agentLine(project: string, id: string, prompt: string, permissio
213
224
  const bypass = permissions === "bypass" && !!YOLO_FLAGS[agent.cmd];
214
225
  const flags = [...agentFlags(project, agent.cmd, undefined, model), ...(bypass ? YOLO_FLAGS[agent.cmd]! : []), ...argsOf(agent.cmd, prefs)];
215
226
  const line = withEnv([commandOf(agent.cmd, prefs), ...flags, ...promptArgs(agent.cmd, prompt)], agent.cmd, prefs);
227
+ // Windows has no env command: there only an account, as before, gets one.
228
+ const vars = [...(process.platform !== "win32" ? subagentEnv(project, agent.cmd) : []), ...accountEnv(acct)];
216
229
  return {
217
- argv: acct.dir ? ["env", ...accountEnv(acct), ...line] : line, bypass, agent: agent.cmd,
230
+ argv: vars.length ? ["env", ...vars, ...line] : line, bypass, agent: agent.cmd,
218
231
  model: picked ? (MODEL_FLAGS[agent.cmd] ? picked : undefined) : model ?? agentFlags(project, agent.cmd).join(" ").match(/\S+$/)?.[0],
219
232
  modelNote: picked && !MODEL_FLAGS[agent.cmd] ? `${agent.name} takes no model flag: "${picked}" was ignored` : undefined,
220
233
  trust: acct.dir ? join(acct.dir, ".claude.json") : undefined,
@@ -238,7 +251,7 @@ export function startWorker(project: string, id: string, wid: string, prefs?: Pr
238
251
  const have = git(project, "rev-parse", "--verify", "--quiet", `refs/heads/${x.branch}`).ok;
239
252
  // A dependent worker starts from the worker it follows, so it sees that code; any further `after` workers are merged in.
240
253
  const dep = x.after.map((a) => w.workers.find((o) => o.id === a)!.branch);
241
- const add = git(project, "worktree", "add", ...(have ? [x.worktree, x.branch] : ["--no-track", "-b", x.branch, x.worktree, dep[0] ?? st.branch]));
254
+ const add = git(project, "worktree", "add", ...(have ? [x.worktree, x.branch] : ["--no-track", "-b", x.branch, x.worktree, dep[0] ?? branchFor(project, id)]));
242
255
  if (!add.ok) return { ok: false, why: add.why };
243
256
  if (!have) for (const b of dep.slice(1)) {
244
257
  const m = git(x.worktree, "merge", "--no-edit", b);
@@ -326,12 +339,12 @@ export function merge(project: string, id: string): { ok: true; shas: string[];
326
339
  if (not) return { ok: false, why: `${not.id} is ${not.status}, so nothing is merged: ${NEXT[not.status]?.replace("<wid>", not.id)}` };
327
340
  const cwd = st.worktree as string;
328
341
  if (!cwd || !existsSync(cwd)) return { ok: false, why: "the run has no worktree to merge into" };
329
- 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` };
342
+ if (git(cwd, "rev-parse", "--abbrev-ref", "HEAD").out !== branchFor(project, id)) return { ok: false, why: `the run's worktree is not on ${branchFor(project, id)}: check it out there first` };
330
343
  if (git(cwd, "status", "--porcelain").out) return { ok: false, why: "the run's worktree has uncommitted changes: commit them first, then merge" };
331
344
  // A branch may change only what its worker owns. Commits it took from the workers it follows are theirs, not its own.
332
345
  for (const x of w.workers) {
333
346
  const skip = x.after.flatMap((a) => ["^" + w.workers.find((o) => o.id === a)!.branch]);
334
- const out = git(cwd, "log", "--no-merges", "--name-only", "--format=", x.branch, "^" + st.branch, ...skip).out.split("\n").filter(Boolean);
347
+ const out = git(cwd, "log", "--no-merges", "--name-only", "--format=", x.branch, "^" + branchFor(project, id), ...skip).out.split("\n").filter(Boolean);
335
348
  const stray = [...new Set(out)].filter((p) => !x.owns.some((o) => p === o || p.startsWith(o + "/")));
336
349
  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` };
337
350
  }
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, mkdirSync, readFileSync, writeFileSync, rmSync, renameSync, realpathSync } from "node:fs";
4
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync, rmSync, renameSync, realpathSync } from "node:fs";
5
5
  import { join, dirname, resolve, sep } from "node:path";
6
6
  import { homedir } from "node:os";
7
7
  import { branchesOf } from "./add-project.ts";
@@ -23,6 +23,34 @@ export const run: Run = (cmd, cwd, ms = 120_000) => {
23
23
  const git = (cwd: string, ...a: string[]) => run(["git", ...a], cwd);
24
24
 
25
25
  export const branchOf = (id: string) => `kaizen/${id}`;
26
+ // A branch name that is safe as a git argument and a refs/heads path: no leading dash, no "..", no "//", no spaces.
27
+ const SAFE_BRANCH = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/;
28
+ const safeBranch = (b: unknown): b is string => typeof b === "string" && SAFE_BRANCH.test(b) && !b.includes("..") && !b.includes("//") && !/[/.]$/.test(b) && !b.endsWith(".lock");
29
+ /** The branch a run really has: the one its state.json records (a run made by hand, on a feature branch), else kaizen/<id>.
30
+ * Never the base it lands on (the remote default, the feature base, HEAD): landing and cleanup delete this branch. */
31
+ export function branchFor(project: string, id: string): string {
32
+ try {
33
+ const b = JSON.parse(readFileSync(join(project, ".kaizen", "runs", id, "state.json"), "utf8")).branch;
34
+ if (safeBranch(b) && b !== "HEAD" && b !== localBase(project, id) && b !== baseOf(project)) return b;
35
+ } catch { /* no state: the default */ }
36
+ return branchOf(id);
37
+ }
38
+
39
+ /** Another run that still uses this run's branch or worktree (runs made by hand on one feature branch share both):
40
+ * neither is ours to remove while it does. */
41
+ function sharer(project: string, id: string, branch: string, dir: string): string | null {
42
+ const runs = join(project, ".kaizen", "runs");
43
+ let names: string[] = [];
44
+ try { names = readdirSync(runs); } catch { return null; }
45
+ for (const n of names) {
46
+ if (n === id) continue;
47
+ try {
48
+ const o = JSON.parse(readFileSync(join(runs, n, "state.json"), "utf8"));
49
+ if (typeof o.worktree === "string" && o.worktree && existsSync(o.worktree) && (o.worktree === dir || o.branch === branch)) return n;
50
+ } catch { /* not a run */ }
51
+ }
52
+ return null;
53
+ }
26
54
  export const worktreeOf = (project: string, id: string) => join(project, ".kaizen", "wt", id);
27
55
 
28
56
  const file = (project: string, id: string) => join(project, ".kaizen", "runs", id, "state.json");
@@ -37,7 +65,8 @@ function patchState(project: string, id: string, set: Record<string, unknown>) {
37
65
  export function codeDir(project: string, id: string): string {
38
66
  try {
39
67
  const w = JSON.parse(readFileSync(file(project, id), "utf8")).worktree;
40
- if (typeof w === "string" && existsSync(w)) return w;
68
+ // Only a folder under <project>/.kaizen/wt/: a hand-written state.json must not aim land or cleanup at another checkout.
69
+ if (typeof w === "string" && existsSync(w) && resolve(w).startsWith(join(resolve(project), ".kaizen", "wt") + sep)) return w;
41
70
  } catch { /* no state, no worktree */ }
42
71
  return project;
43
72
  }
@@ -64,9 +93,10 @@ const baseRef = (project: string, id: string) => localBase(project, id) ?? `orig
64
93
  /**
65
94
  * Makes the run's worktree and branch and records both. Off the remote default branch, or,
66
95
  * when the project is on another branch, off that local branch, unpushed commits included,
67
- * recorded as `base_branch`. `warn` names uncommitted changes, which a worktree never carries.
96
+ * recorded as `base_branch`. `fromDefault` (a side run) always cuts from the remote default
97
+ * branch, whatever the project is on. `warn` names uncommitted changes, which a worktree never carries.
68
98
  */
69
- export function startWorktree(project: string, id: string): { ok: true; path: string; branch: string; warn?: string } | { ok: false; why: string } {
99
+ export function startWorktree(project: string, id: string, fromDefault = false): { ok: true; path: string; branch: string; warn?: string } | { ok: false; why: string } {
70
100
  if (!SLUG.test(id)) return { ok: false, why: `"${id}" is not a run id` };
71
101
  if (!existsSync(file(project, id))) return { ok: false, why: "no such run" };
72
102
  if (!git(project, "rev-parse", "--is-inside-work-tree").ok) return { ok: false, why: "not a git repository" };
@@ -75,7 +105,7 @@ export function startWorktree(project: string, id: string): { ok: true; path: st
75
105
  if (!git(project, "remote").out) return { ok: false, why: "no git remote to branch from" };
76
106
  const f = git(project, "fetch", "origin");
77
107
  if (!f.ok) return { ok: false, why: `fetch failed: ${f.why}` };
78
- const here = git(project, "symbolic-ref", "--short", "-q", "HEAD"), feature = here.ok && here.out && here.out !== baseOf(project) ? here.out : null;
108
+ const here = git(project, "symbolic-ref", "--short", "-q", "HEAD"), feature = !fromDefault && here.ok && here.out && here.out !== baseOf(project) ? here.out : null;
79
109
  const base = feature ?? `origin/${baseOf(project)}`;
80
110
  const exists = git(project, "rev-parse", "--verify", "--quiet", `refs/heads/${branch}`).ok;
81
111
  const add = git(project, "worktree", "add", ...(exists ? [path, branch] : [path, "--no-track", "-b", branch, base]));
@@ -92,11 +122,17 @@ type Failed = Extract<Landed, { ok: false }>;
92
122
  // The project's own config over the global one; the defaults are safe: nothing auto-resolves.
93
123
  // Read here because settings.ts loads state.ts, which loads this file.
94
124
  const readGit = (text: string, key: string) => {
95
- const m = new RegExp(`^git:[^\\n]*\\n(?:(?:[ \\t]+[^\\n]*|)\\n)*?[ \\t]+${key}:[ \\t]*([^\\n]*)`, "m").exec(text.replace(/\r\n/g, "\n"));
125
+ const m = new RegExp(`^git:[^\\n]*\\n(?:(?:[ \\t][^\\n]*)?\\n)*?[ \\t]+${key}:[ \\t]*([^\\n]*)`, "m").exec(text.replace(/\r\n/g, "\n"));
96
126
  return m ? m[1]!.split(" #")[0]!.trim().replace(/^["']|["']$/g, "") : null;
97
127
  };
128
+ // A command run through `sh -c`: a project's config.yml that git tracks came with a clone, so it may not set one.
129
+ const COMMAND_KEYS = new Set(["land_check", "rebuild_on_land"]);
130
+ const tracked = (project: string, f: string) => {
131
+ try { return Bun.spawnSync(["git", "-C", project, "ls-files", "--error-unmatch", f], { stdout: "ignore", stderr: "ignore", windowsHide: true }).exitCode === 0; } catch { return false; }
132
+ };
98
133
  const gitSetting = (project: string, key: string, fallback: string) => {
99
134
  for (const f of [join(project, ".kaizen", "config.yml"), join(homedir(), ".kaizen", "config.yml")]) {
135
+ if (COMMAND_KEYS.has(key) && f.startsWith(project) && tracked(project, f)) continue;
100
136
  try { const v = readGit(readFileSync(f, "utf8"), key); if (v !== null) return v; } catch { /* no such file */ }
101
137
  }
102
138
  return fallback;
@@ -208,7 +244,7 @@ export function landWorktree(project: string, id: string, sh: Run = run,
208
244
  // gh only knows GitHub: any other remote lands by rebase and push.
209
245
  hasGh = !!Bun.which("gh") && /github\.com/.test(git(project, "remote", "get-url", "origin").out)): Landed {
210
246
  if (!SLUG.test(id)) return { ok: false, why: `"${id}" is not a run id` };
211
- const dir = codeDir(project, id), branch = branchOf(id);
247
+ const dir = codeDir(project, id), branch = branchFor(project, id);
212
248
  if (dir === project) return { ok: false, why: "this run has no worktree" };
213
249
  const clean = (d: string) => !sh(["git", "status", "--porcelain"], d).out;
214
250
  if (!clean(dir)) return { ok: false, why: "the worktree has uncommitted changes; commit them first" };
@@ -227,9 +263,10 @@ export function landWorktree(project: string, id: string, sh: Run = run,
227
263
  const m = sh(["git", "merge", "--no-edit", branch], project);
228
264
  if (!m.ok) { sh(["git", "merge", "--abort"], project); return { ok: false, kind: "conflict", why: `merge into ${feature} failed: ${m.why}; worktree kept` }; }
229
265
  }
266
+ if (sharer(project, id, branch, dir)) return { ok: true, how: "merge" }; // merged; another run still uses the worktree and branch
230
267
  const rm = git(project, "worktree", "remove", "--force", dir);
231
268
  if (!rm.ok) return { ok: false, why: `merged, but the worktree stays: ${rm.why}` };
232
- git(project, "branch", "-D", branch);
269
+ git(project, "branch", "-D", "--", branch);
233
270
  patchState(project, id, { worktree: null, branch: null });
234
271
  return { ok: true, how: "merge" };
235
272
  }
@@ -237,11 +274,12 @@ export function landWorktree(project: string, id: string, sh: Run = run,
237
274
  const finish = (how: "pr" | "push", url?: string): Landed => {
238
275
  git(project, "fetch", "origin");
239
276
  if (!landed(dir, `origin/${base}`, branch)) return { ok: false, why: `${how === "pr" ? "the pull request" : "the push"} went through but ${branch} is not on ${base} yet; worktree kept` };
277
+ if (sharer(project, id, branch, dir)) return { ok: true, how, url }; // landed; another run still uses the worktree and branch
240
278
  // The worktree is clean (checked above); --force is only for the untracked node_modules link.
241
279
  const rm = git(project, "worktree", "remove", "--force", dir);
242
280
  if (!rm.ok) return { ok: false, why: `landed, but the worktree stays: ${rm.why}` };
243
- git(project, "branch", "-D", branch);
244
- git(project, "push", "origin", "--delete", branch);
281
+ git(project, "branch", "-D", "--", branch);
282
+ git(project, "push", "origin", "--delete", "--", branch);
245
283
  patchState(project, id, { worktree: null, branch: null });
246
284
  return { ok: true, how, url };
247
285
  };
@@ -314,7 +352,7 @@ export function branchState(project: string, id: string, changed: () => void = (
314
352
  if (!SLUG.test(id)) return null;
315
353
  const dir = codeDir(project, id);
316
354
  if (dir === project) return null; // committed in the project's own checkout: no branch of its own
317
- const branch = branchOf(id), base = baseOfRun(project, id), ref = baseRef(project, id);
355
+ const branch = branchFor(project, id), base = baseOfRun(project, id), ref = baseRef(project, id);
318
356
  // A feature base may never have been pushed: it lands by local merge, with no pull request.
319
357
  const gh = hasGh && !localBase(project, id);
320
358
  const upstream = sh(["git", "rev-parse", "--abbrev-ref", `${branch}@{u}`], dir).ok;
@@ -339,7 +377,7 @@ export function branchState(project: string, id: string, changed: () => void = (
339
377
  /** Pushes the branch, then opens its pull request against the base. */
340
378
  export async function openPr(project: string, id: string, title: string, body: string, draft: boolean, sh: Run = run, ash: AsyncRun = runAsync, hasGh = onGithub(project)): Promise<{ ok: true; pr: Pr } | { ok: false; why: string }> {
341
379
  if (!SLUG.test(id)) return { ok: false, why: `"${id}" is not a run id` };
342
- const dir = codeDir(project, id), branch = branchOf(id);
380
+ const dir = codeDir(project, id), branch = branchFor(project, id);
343
381
  if (dir === project) return { ok: false, why: "This run has no branch of its own." };
344
382
  if (localBase(project, id)) return { ok: false, why: "This run lands by a local merge into its branch, with no pull request." };
345
383
  if (!hasGh) return { ok: false, why: "Pull requests need the GitHub CLI (gh) and a GitHub remote." };
@@ -358,7 +396,7 @@ export async function openPr(project: string, id: string, title: string, body: s
358
396
  /** Merges the run's pull request by rebase, as `kaizen land` does. The worktree stays. */
359
397
  export async function mergePr(project: string, id: string, sh: Run = run, ash: AsyncRun = runAsync, hasGh = onGithub(project)): Promise<{ ok: true } | { ok: false; why: string }> {
360
398
  if (!SLUG.test(id)) return { ok: false, why: `"${id}" is not a run id` };
361
- const dir = codeDir(project, id), branch = branchOf(id);
399
+ const dir = codeDir(project, id), branch = branchFor(project, id);
362
400
  if (dir === project) return { ok: false, why: "This run has no branch of its own." };
363
401
  if (localBase(project, id)) return { ok: false, why: "This run lands by a local merge: run kaizen worktree land." };
364
402
  if (!hasGh) return { ok: false, why: "Merging needs the GitHub CLI (gh) and a GitHub remote." };
@@ -375,8 +413,10 @@ export async function mergePr(project: string, id: string, sh: Run = run, ash: A
375
413
  */
376
414
  export async function removeWorktree(project: string, id: string, sh: Run = run, ash: AsyncRun = runAsync): Promise<{ ok: true } | { ok: false; why: string }> {
377
415
  if (!SLUG.test(id)) return { ok: false, why: `"${id}" is not a run id` };
378
- const dir = codeDir(project, id), branch = branchOf(id);
416
+ const dir = codeDir(project, id), branch = branchFor(project, id);
379
417
  if (dir === project) return { ok: false, why: "This run has no worktree." };
418
+ const other = sharer(project, id, branch, dir);
419
+ if (other) return { ok: false, why: `The run ${other} still uses this worktree and branch. Remove them from the last run that uses them.` };
380
420
  if (sh(["git", "status", "--porcelain"], dir).out) return { ok: false, why: "The worktree has uncommitted changes. Commit or discard them first." };
381
421
  const feature = localBase(project, id), base = feature ?? baseOf(project), ref = baseRef(project, id);
382
422
  if (!feature) {
@@ -390,7 +430,7 @@ export async function removeWorktree(project: string, id: string, sh: Run = run,
390
430
  if (!rm.ok) return { ok: false, why: rm.why };
391
431
  // Every commit is on the base by patch, so -D loses nothing a rebase-merge rewrote.
392
432
  sh(["git", "branch", "-D", "--", branch], project);
393
- if (!feature) await ash(["git", "push", "origin", "--delete", branch], project); // best effort: GitHub may have deleted it
433
+ if (!feature) await ash(["git", "push", "origin", "--delete", "--", branch], project); // best effort: GitHub may have deleted it
394
434
  prs.delete(prKey(project, id));
395
435
  patchState(project, id, { worktree: null, branch: null });
396
436
  clearLand(project, id);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kaizen-agent",
3
- "version": "1.70.0",
3
+ "version": "1.71.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": {
@@ -117,7 +117,7 @@ This is a judgement, not a threshold to enforce: fifty lines that change how mon
117
117
  rounded are not a small change. Say which path you took (short or full) and why, in one line, when the
118
118
  run starts.
119
119
 
120
- **Follow-ups are runs too.** Both runners record the same artifacts: `01-plan.md`, `03-impl.md`, `04-review.md`, and a final `state.json` — `lite` and `full` differ only in who executes the stages. A message the user sends later in the same session is judged by what it asks: a question, explanation or chat is answered, no run; a request to change or produce something is building, so it goes through the flow. While the previous run has not reached `done` (including awaiting its final approval), the change is a revise of that run, recorded in `02-approval.md`. After `done` or `abandoned`, ask the user before opening a new run — AskUserQuestion with *open a follow-up run*, *answer without a run*, *cancel* — and create nothing under `runs/` until they pick the first. An explicit `/kaizen <request>` is that answer already. The new run's `00-request.md` is the user's words verbatim, then a line `Follow-up of: <previous run id>`; where those words only answer a question ("Plan 2b next"), put one line naming the work first — the board titles the card from it. Never reopen a finished run. When unsure whether a message asks for a change, ask once.
120
+ **Follow-ups are runs too.** Both runners record the same artifacts: `01-plan.md`, `03-impl.md`, `04-review.md`, and a final `state.json` — `lite` and `full` differ only in who executes the stages. A message the user sends later in the same session is judged by what it asks: a question, explanation or chat is answered, no run; a request to change or produce something is building, so it goes through the flow. While the previous run has not reached `done` (including awaiting its final approval), a change to that run's own work is a revise of it, recorded in `02-approval.md` ("make the new panel narrower" while that panel is being built). A request for something else while a run is in flight (a bug in another area found mid-feature, an unrelated fix) asks first, AskUserQuestion: *Side run: new worktree off the default branch, built by a second agent* (recommended), *Side run: new worktree off the default branch, built in this session* (in the side run's own worktree, never the other run's folder), *Revise the current run*, *Answer without a run*; create nothing under `runs/` until a side run is picked. **A side run** is a new run, started like any other with its own fresh `state.json`: never copy another run's `state.json`, and never carry over its `worktree`, `branch`, `workspace`, `session`, `base_branch` or `base_sha`. Its `00-request.md` ends with `Follow-up of: <the run in flight>`. Plan it and take its plan approval as usual, then run `kaizen worktree start <id> --default` from the project folder or any worktree: it cuts `kaizen/<id>` from the remote default branch and never places the run in the folder you are in. For the second agent, run `kaizen handoff start <id>` as `spec-build.md` says. This works under `lite` and `full` alike. Either way, go back to the run in flight; the side run never changes it. After `done` or `abandoned`, ask the user before opening a new run — AskUserQuestion with *open a follow-up run*, *answer without a run*, *cancel* — and create nothing under `runs/` until they pick the first. An explicit `/kaizen <request>` is that answer already. The new run's `00-request.md` is the user's words verbatim, then a line `Follow-up of: <previous run id>`; where those words only answer a question ("Plan 2b next"), put one line naming the work first — the board titles the card from it. Never reopen a finished run. When unsure whether a message asks for a change, ask once.
121
121
 
122
122
  ## Modes
123
123
 
@@ -251,7 +251,9 @@ final report, so nobody reads a same-session review as an independent one.
251
251
  session at a time) runs as `lite` whatever the setting, following
252
252
  [`adapters.md`](adapters.md); do not fake subagents.
253
253
 
254
- - `runner: lite` — do not call the Agent tool, except for the review as below. You run
254
+ - `runner: lite` — do not call the Agent tool, except for the review as below. Handing a
255
+ worktree run to a second agent with `kaizen handoff start` is not the Agent tool and is
256
+ allowed under `lite` too (`spec-build.md`). Otherwise you run
255
257
  plan, build and review yourself, as *Who runs the stages* says; the stage table below
256
258
  still applies, and you are the agent for every row.
257
259
  Read `spec-build.md` before building and `spec-main.md` before moving the run to
@@ -283,12 +285,14 @@ the choice at the plan approval. Building inline does not make the review less
283
285
  independent: the reviewer is a separate agent in every case, and never sees the
284
286
  conversation the work happened in.
285
287
 
286
- `subagents.model` and `subagents.effort` apply to every stage dispatched this way, including a lite run's reviewer under `review.executor: subagent`.
287
- Pass `model` on the Agent call when it is not `inherit`. Effort has no call-time
288
- knob: when it is not `inherit`, make sure the frontmatter of the agent's definition
289
- (`~/.claude/agents/kaizen-<stage>.md`, or the project's `.claude/agents/` copy)
290
- carries `effort: <value>` — edit or add that one line, nothing else — before the
291
- first dispatch of the run. `inherit` means leave the file alone.
288
+ Each stage subagent's model comes from `subagents.<stage>` (`planner`, `builder`,
289
+ `reviewer`), else `subagents.model`; the builder's value covers the fix rounds and the
290
+ reviewer's the rechecks. This holds for every stage dispatched this way, a lite run's
291
+ reviewer under `review.executor: subagent` included. Before each dispatch run
292
+ `kaizen model <stage>` and pass what it prints as `model` on the Agent call; `inherit`
293
+ means pass none. `subagents.effort` has no call-time knob: a session kaizen launches
294
+ already carries it, and the stage's model, in its environment. Never write `model:` or
295
+ `effort:` into an agent definition file: those files are shared by every project.
292
296
 
293
297
  After a subagent returns, update `state.json` yourself in the main thread, with `kaizen state` from 1.69.0, by hand before that (`spec.md`, Stage 0). Subagents
294
298
  report; the main thread owns the state machine.
@@ -169,8 +169,14 @@ subagents:
169
169
  # opus | sonnet | haiku - pin it. A cheaper model for the builder is the usual
170
170
  # reason to touch this; the reviewer on a cheaper model finds less.
171
171
  model: inherit
172
+ # One stage on its own model, ahead of `model` above: default | opus | sonnet | haiku.
173
+ # The builder also runs the fix rounds, the reviewer the rechecks.
174
+ planner: default
175
+ builder: default
176
+ reviewer: default
172
177
  # Reasoning effort for the stage subagents: inherit | low | medium | high.
173
- # Set through the agent definition's frontmatter.
178
+ # A Claude Code session kaizen launches carries model and effort as the defaults its
179
+ # subagents start from (CLAUDE_CODE_SUBAGENT_MODEL, CLAUDE_CODE_SUBAGENT_EFFORT).
174
180
  effort: inherit
175
181
 
176
182
  agent:
@@ -207,8 +213,18 @@ agent:
207
213
  # (while kaizen is open). Linux and macOS; agents in an outside terminal don't count.
208
214
  keep_awake: off
209
215
  # The model each tool launches with, the tool's own name. Empty: its default.
210
- # Claude Code's stage subagents use subagents.model instead.
216
+ # Claude Code's stage subagents use subagents.model, and inherit this when it is inherit.
211
217
  model:
218
+ claude: ""
219
+ agy: ""
220
+ codex: ""
221
+ gemini: ""
222
+ opencode: ""
223
+ # The model of the second agent a worktree run hands its build, review and fix loop to
224
+ # (`kaizen handoff start`), per tool, in the tool's own spelling. Empty: the run's own
225
+ # model. Claude's handoff agent still runs its stage subagents on subagents.*.
226
+ handoff_model:
227
+ claude: ""
212
228
  agy: ""
213
229
  codex: ""
214
230
  gemini: ""