kaizen-agent 1.62.0 → 1.64.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 (51) hide show
  1. package/cli/automations.test.ts +167 -0
  2. package/cli/automations.ts +298 -0
  3. package/cli/dashboard.ts +1 -7
  4. package/cli/handoff.test.ts +133 -0
  5. package/cli/handoff.ts +122 -0
  6. package/cli/install.test.ts +16 -0
  7. package/cli/install.ts +92 -191
  8. package/cli/look.ts +33 -0
  9. package/cli/pty.ts +16 -2
  10. package/cli/resources.test.ts +50 -0
  11. package/cli/resources.ts +113 -0
  12. package/cli/restart.test.ts +28 -1
  13. package/cli/settings.ts +6 -2
  14. package/cli/setup.test.ts +22 -2
  15. package/cli/setup.ts +101 -51
  16. package/cli/sources.ts +1 -1
  17. package/cli/state.test.ts +7 -0
  18. package/cli/state.ts +13 -2
  19. package/cli/usage.test.ts +11 -0
  20. package/cli/web.ts +134 -6
  21. package/cli/workers.ts +11 -4
  22. package/cli/worktree.test.ts +174 -1
  23. package/cli/worktree.ts +190 -35
  24. package/package.json +1 -1
  25. package/skills/kaizen/config.default.yml +17 -0
  26. package/skills/kaizen/settings.md +4 -0
  27. package/skills/kaizen/spec-build.md +13 -0
  28. package/skills/kaizen/spec-main.md +13 -0
  29. package/skills/kaizen-help/SKILL.md +1 -0
  30. package/skills/media/kaizen-deck/SKILL.md +21 -2
  31. package/skills/media/kaizen-deck/scripts/motion.py +99 -0
  32. package/web/board/cards.ts +1 -0
  33. package/web/board/git.ts +4 -4
  34. package/web/board/phone.ts +5 -5
  35. package/web/board/resources.ts +152 -0
  36. package/web/board/run-view.ts +107 -1
  37. package/web/board/search.ts +6 -0
  38. package/web/board/settings-automations.ts +71 -0
  39. package/web/board/settings-pages.test.ts +4 -0
  40. package/web/board/settings-pages.ts +2 -1
  41. package/web/board/settings.ts +10 -3
  42. package/web/board/workspace.ts +7 -1
  43. package/web/board/ws-tabs.test.ts +20 -1
  44. package/web/board/ws-tabs.ts +26 -7
  45. package/web/board.html +20 -3
  46. package/web/board.js +119 -88
  47. package/web/notebook.js +23 -23
  48. package/web/notes.html +1 -0
  49. package/web/term.js +1 -1
  50. package/web/video.html +1 -0
  51. package/web/video.js +49 -49
package/cli/web.ts CHANGED
@@ -16,8 +16,10 @@ 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 { failStart, markRunning, readWorkers, requested, startWorker, sweep, workerStale } from "./workers.ts";
20
- import { attachPty, writePty, submitPty, resizePty, exitPty, ptyState, ptyKeys, adoptLoginEnv, startPty, ptySupported, detachPty, ptyTail, ptyTmux, tmuxAlive, RESUMED } from "./pty.ts";
19
+ import { agentLine, failStart, markRunning, readWorkers, requested, startWorker, sweep, workerStale } from "./workers.ts";
20
+ import { childDied, childQuiet, markWoken, move, requestOpen, readHandoff, refused, started, wakeAction, wakeLine, type Handoff } from "./handoff.ts";
21
+ import { processTable, storage, systemMemory, treeRss, type Root } from "./resources.ts";
22
+ import { attachPty, writePty, submitPty, resizePty, exitPty, killPty, panePid, ptyState, ptyKeys, adoptLoginEnv, startPty, ptySupported, detachPty, ptyTail, ptyTmux, tmuxAlive, RESUMED } from "./pty.ts";
21
23
  import { snapshot, snapWorker } from "./state-snap.ts";
22
24
  import { claudeUsage, claudeUsageAt, codexUsage, codexUsageAt, phonePeers, type Usage } from "./usage.ts";
23
25
  import { readSources, addSource, removeSource, moveSource, setCategory, setWriteback, setPaused, readIcebox, promote, dismiss, restore, addItem, markDone, markReplied, gatherSource, freshImages, gatherAll, gatherDirs, due, socialUrl, socialOf } from "./sources.ts";
@@ -28,10 +30,11 @@ import { writeBacks } from "./writeback.ts";
28
30
  import { postLink, sendReply } from "./browser.ts";
29
31
  import { listNotes, saveNote, renameNote, deleteNote, boardIndex, linksTo } from "./notes.ts";
30
32
  import * as video from "./video.ts";
33
+ import * as auto from "./automations.ts";
31
34
  import * as localsend from "./localsend.ts";
32
35
  import * as hermes from "./hermes.ts";
33
36
  import { listChats, readChat, sendChat, stopChat, deleteChat, okId as okChatId, busy as chatBusy, type Event as ChatEvent, type Upload as ChatUpload } from "./chat.ts";
34
- import { workspaces, workspacesNow, forgetWorkspaces, workspacesAge, addWorktree, linkedWs, runAsync, run, branchState, openPr, mergePr, removeWorktree } from "./worktree.ts";
37
+ import { workspaces, workspacesNow, forgetWorkspaces, workspacesAge, addWorktree, linkedWs, unlinkTerm, codeDir, runAsync, run, branchState, openPr, mergePr, removeWorktree } from "./worktree.ts";
35
38
  import { gitUrl, destDir, winBad, cloneInto, branchesOf, ignoreKaizen } from "./add-project.ts";
36
39
 
37
40
  const PAGE = join(dirname(import.meta.dir), "web", "board.html");
@@ -75,6 +78,8 @@ const served = (f: string) => installed() === VERSION && existsSync(f) ? readTex
75
78
  // Loopback hosts only; shared by /open-url and /frameable so the board is never a way to reach other sites.
76
79
  const isLoopback = (u: URL) => ["localhost", "127.0.0.1", "[::1]"].includes(u.hostname);
77
80
 
81
+ // A run whose launched terminal is still alive (automations treat it as open).
82
+ const runLive = (dir: string, id: string) => Object.values(stagesOf(dir, id)).some((k) => !!ptyState(k)?.alive);
78
83
  export const stagesOf = (dir: string, id: string): Record<string, string> => { try { return JSON.parse(readText(join(dir, "runs", id, "terminals.json"))) ?? {}; } catch { return {}; } };
79
84
  export const markStage = (dir: string, id: string, stage: string, key?: string) => {
80
85
  if (!stage || !key || !id || /^\.+$/.test(id)) return;
@@ -435,6 +440,40 @@ export async function web(repoDir: string, opts: Opts = {}) {
435
440
  return { key, alive: st.alive, asking: st.asking, busy: st.busy, lastOut: st.lastOut, all, agent: cmdOf.get(key), stages: c.kind === "run" ? stagesOf(c.state, c.id!) : undefined };
436
441
  }, { cmd: (k: string) => cmdOf.get(k) });
437
442
  };
443
+ // A worktree run's second agent: opened on request, watched, and its end told to the first.
444
+ const tendHandoff = (dir: string, project: string, id: string) => {
445
+ const h = readHandoff(dir, id);
446
+ if (!h) return;
447
+ // Its own catch: a fault here must read as a fault, not as "no board".
448
+ try { tendOne(dir, project, id, h); } catch (err: any) {
449
+ console.error(`handoff ${id}: ${err?.stack ?? err}`);
450
+ if (h.status === "requested") refused(dir, id, `the board failed: ${err?.message ?? err}`);
451
+ }
452
+ };
453
+ const tendOne = (dir: string, project: string, id: string, h: Handoff) => {
454
+ if (requestOpen(h, Date.now())) {
455
+ const cwd = codeDir(project, id), key = "sh-" + crypto.randomUUID().slice(0, 8);
456
+ 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}. ` +
457
+ `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>".`;
458
+ const l = cwd === project ? "the run has no worktree" : agentLine(project, id, prompt, "own");
459
+ if (typeof l === "string") { refused(dir, id, l); changed(); return; }
460
+ if (!started(dir, id, key)) return; // declined meanwhile: the first agent is building
461
+ for (const k of Object.keys(process.env)) if (CHILD_ENV.test(k)) delete process.env[k];
462
+ if (l.agent === "claude") trustFolder(cwd, l.trust);
463
+ try {
464
+ const pid = startPty(key, l.argv, cwd, undefined, changed, { env: { KAIZEN_RUN_ID: id, KAIZEN_TERM: key } });
465
+ shells.set(key, { key, dir, title: `Build ${id}`, agent: l.agent, run: `run:${dir}:${id}`, ws: cwd, pid });
466
+ unlinkTerm(dir, h.parent_terminal);
467
+ } catch (err: any) { move(dir, id, ["running"], { status: "failed", reason: err?.message ?? String(err) }); }
468
+ changed();
469
+ return;
470
+ }
471
+ const child = ptyState(h.child_terminal ?? "");
472
+ if (childDied(h, !!child?.alive)) { move(dir, id, ["running", "quiet"], { status: "failed", reason: child ? "the worktree agent's terminal ended without a report" : "the board restarted and the worktree agent stopped; run kaizen handoff start again to continue" }); changed(); return; }
473
+ if (childQuiet(h, child, Date.now())) { move(dir, id, ["running"], { status: "quiet", reason: "the worktree agent has gone quiet without a report" }); changed(); return; }
474
+ const now = readHandoff(dir, id), parent = ptyState(h.parent_terminal);
475
+ if (wakeAction(now, parent ? { ...parent, typedAt: parent.typedAt ?? 0 } : null, Date.now()) === "send") { markWoken(dir, id); submitPty(h.parent_terminal, wakeLine(id, now!)); changed(); }
476
+ };
438
477
  // Orchestration: the only place a worker's terminal starts. A worker asks for it in workers.json
439
478
  // (`kaizen worker start`); with the mode off no such file exists, so this finds nothing.
440
479
  // startWorker re-checks the stage, the frozen settings, the count and the plan before anything runs.
@@ -460,7 +499,10 @@ export async function web(repoDir: string, opts: Opts = {}) {
460
499
  }
461
500
  try {
462
501
  const runs = join(dir, "runs");
463
- for (const id of existsSync(runs) ? readdirSync(runs) : []) if (sweep(project, id, (k) => !!ptyState(k)?.alive)) changed();
502
+ for (const id of existsSync(runs) ? readdirSync(runs) : []) {
503
+ if (sweep(project, id, (k) => !!ptyState(k)?.alive)) changed();
504
+ tendHandoff(dir, project, id);
505
+ }
464
506
  } catch { /* the next tick tries again */ }
465
507
  }
466
508
  };
@@ -542,6 +584,15 @@ export async function web(repoDir: string, opts: Opts = {}) {
542
584
  busy = false;
543
585
  }, 60_000);
544
586
 
587
+ // Automations: a due rule starts a run in its own project. Own busy flag; a fire may wait on a precheck.
588
+ let autoBusy = false;
589
+ const automate = setInterval(async () => {
590
+ if (autoBusy) return;
591
+ autoBusy = true;
592
+ try { if (await auto.tickAutomations(states(true).filter((d) => d !== join(home, ".kaizen")), { pick: inCard, live: runLive })) changed(); } catch { /* the next tick tries again */ }
593
+ autoBusy = false;
594
+ }, 60_000);
595
+
545
596
  // Done requests are reported back to their sources here, on the board's own clock: a
546
597
  // page load only reads, so opening the Icebox never closes an issue.
547
598
  const loop = setInterval(async () => {
@@ -785,6 +836,19 @@ export async function web(repoDir: string, opts: Opts = {}) {
785
836
  if (!/^[\w-]+$/.test(key) || !ptyState(key)) return bad("no such terminal", 404);
786
837
  return json({ ok: exitPty(key) });
787
838
  }
839
+ // The resource monitor's Kill: ends the process at once, so /shell's guards, and only
840
+ // a live terminal this board holds. A pid never comes from the page.
841
+ if (req.method === "POST" && path === "/pty/kill") {
842
+ const refused = strict(req);
843
+ if (refused) return refused;
844
+ let body: any;
845
+ try { body = await req.json(); } catch { return bad("json body expected"); }
846
+ const key = String(body.key ?? "");
847
+ if (!/^[\w-]+$/.test(key) || !ptyState(key)?.alive) return bad("no such terminal", 404);
848
+ const ok = killPty(key);
849
+ changed();
850
+ return json({ ok });
851
+ }
788
852
 
789
853
  // A plain shell, or a bare Claude/Codex session, in a project folder: the run
790
854
  // workspace's + menu. Code execution, so local() as for every write, a registered
@@ -963,6 +1027,30 @@ export async function web(repoDir: string, opts: Opts = {}) {
963
1027
  for (const k of shells.keys()) if (!ptyState(k)?.alive) shells.delete(k);
964
1028
  return json([...shells.values()].filter((s) => !dir || s.dir === dir).map(shown));
965
1029
  }
1030
+ // The footer's resource monitor. Storage answers at once from the last scan; see storage().
1031
+ if (req.method === "GET" && path === "/resources") {
1032
+ const table = await processTable(), sessions = states(true).flatMap((st) => readSessions(st).map((s) => ({ ...s, st })));
1033
+ const roots: number[] = [process.pid];
1034
+ const terminals = ptyKeys().filter((k) => ptyState(k)?.alive).map((key) => {
1035
+ const sh = shells.get(key), s = sessions.find((x) => x.key === key);
1036
+ const cmd = sh?.agent || s?.cmd || "", st = sh?.dir ?? s?.st ?? "";
1037
+ const t = shown({ key, dir: st, run: sh?.run ?? "", ws: sh?.ws ?? (st ? projectOf(st) : undefined) });
1038
+ // A tmux-kept agent lives under kaizen's tmux server, not under the board.
1039
+ const tmux = ptyTmux(key), pid = (tmux ? panePid(tmux) : null) ?? ptyState(key)!.pid;
1040
+ roots.push(pid);
1041
+ return { key, title: sh?.title ?? (KNOWN_AGENTS.find((a) => a.cmd === cmd)?.name ?? (cmd || "terminal")), agent: cmd, dir: st, ws: t.ws ?? "", project: st ? basename(projectOf(st)) : "", rss: table ? treeRss(table, [pid]) : null };
1042
+ });
1043
+ return json({ system: systemMemory(), kaizen: table ? treeRss(table, roots) : process.memoryUsage().rss, terminals });
1044
+ }
1045
+ if (req.method === "GET" && path === "/resources/storage") {
1046
+ const data = join(home, ".kaizen");
1047
+ const roots = (): Root[] => [
1048
+ { name: "Kaizen data", dir: "", path: data, kind: "home" },
1049
+ { name: "Kaizen install", dir: "", path: resolve(import.meta.dir, ".."), kind: "install" },
1050
+ ...knownProjects().map((d) => ({ name: basename(d), dir: join(d, ".kaizen"), path: join(d, ".kaizen"), kind: "project" as const })),
1051
+ ];
1052
+ return json(storage(roots, url.searchParams.has("refresh")));
1053
+ }
966
1054
  // The localhost tab's "Open in browser": a Chromium app window on this computer, for
967
1055
  // localhost pages that refuse to be framed. Launches a process, so /shell's guards, and only a
968
1056
  // loopback http(s) address, passed as one --app= argument, never a shell string.
@@ -1145,6 +1233,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
1145
1233
  // A plain shell counts too while an agent typed into it runs there.
1146
1234
  for (const raw of shells.values()) { const x = shown(raw), cmd = x.agent || (x.pid ? shellAgent(x.pid, KNOWN_AGENTS.map((k) => k.cmd)) : undefined); if (cmd) addAgent(x.key, x.dir, x.ws, cmd, x.run); }
1147
1235
  cards.forEach((c, i) => { for (const k of ptys[i]?.all ?? []) addAgent(k, c.state, c.ws, pty.cmd(k) ?? KNOWN_AGENTS.find((a) => c.tags?.includes(a.cmd))?.cmd, c.kind === "run" ? c.id : undefined); });
1236
+ // A failed land marks the run's agents, and the terminal that ran it (often the first agent, in another workspace).
1237
+ for (const c of cards) if (c.land) for (const a of agents) if ((a.dir === c.state && a.run === c.id) || a.key === c.land.term) a.land = c.land.kind;
1148
1238
  const entry = (d: string) => ({ dir: d, label: label(d), logo: !!projectLogo(d),
1149
1239
  workspaces: d === join(home, ".kaizen") ? [{ path: d, branch: "", main: true }] : workspacesNow(projectOf(d)) });
1150
1240
  const body = JSON.stringify({
@@ -1161,7 +1251,10 @@ export async function web(repoDir: string, opts: Opts = {}) {
1161
1251
  const signal = signalOf(c, rep, ptys[i] as any, Date.now(), beat);
1162
1252
  // Only a run that has workers.json carries `workers`: any other card is as it was.
1163
1253
  const ws = c.kind === "run" && c.id ? readWorkers(projectOf(c.state), c.id) : null;
1164
- return { ...c, notice: notice(c), ...extra[i], pty: ptys[i], signal, ...(ws ? { workers: ws.workers.map((x) => ({ id: x.id, title: x.title, status: workerStale(x, x.key ? ptyState(x.key) : null, Date.now(), beat) ? "stale" : x.status, bypass: x.bypass })), ...(ws.merge && ws.merge.status !== "merged" ? { workersMerge: ws.merge.status } : {}) } : {}), ...(rep?.phase ? { phase: rep.phase } : {}), ...(signal === "blocked" ? { blocked: rep!.blocked } : {}) };
1254
+ // No terminal left to wake: the card says so, and approval works here as for any run.
1255
+ const hand = c.kind === "run" && c.id ? readHandoff(c.state, c.id) : null, parentPty = hand ? ptyState(hand.parent_terminal) : null;
1256
+ const unwoken = wakeAction(hand, parentPty ? { ...parentPty, typedAt: parentPty.typedAt ?? 0 } : null, Date.now()), orphan = unwoken === "gone" || unwoken === "held";
1257
+ return { ...c, notice: notice(orphan ? { ...c, handoff: hand!.status } : c), ...extra[i], pty: ptys[i], signal, ...(ws ? { workers: ws.workers.map((x) => ({ id: x.id, title: x.title, status: workerStale(x, x.key ? ptyState(x.key) : null, Date.now(), beat) ? "stale" : x.status, bypass: x.bypass })), ...(ws.merge && ws.merge.status !== "merged" ? { workersMerge: ws.merge.status } : {}) } : {}), ...(rep?.phase ? { phase: rep.phase } : {}), ...(signal === "blocked" ? { blocked: rep!.blocked } : {}) };
1165
1258
  }),
1166
1259
  backlog: backlog.map((b) => ({ ...b, starting: backlogLaunched.has(`${b.state}\0${b.source}#${b.n}`) || undefined })),
1167
1260
  now: Date.now(),
@@ -1271,6 +1364,41 @@ export async function web(repoDir: string, opts: Opts = {}) {
1271
1364
  return json({ accounts: rows, windows: process.platform === "win32", ...(added ? { added } : {}) });
1272
1365
  }
1273
1366
 
1367
+ if (path === "/automations" && (req.method === "GET" || req.method === "POST")) {
1368
+ if (!state || state === join(home, ".kaizen")) return json({ error: "Open a project first." }, 404);
1369
+ let rules: auto.Rule[];
1370
+ try { rules = auto.readRules(state); } catch (e: any) { return bad(e.message, 500); }
1371
+ if (req.method === "POST") {
1372
+ const refused = strict(req);
1373
+ if (refused) return refused;
1374
+ let body: any;
1375
+ try { body = await req.json(); } catch { return bad("json body expected"); }
1376
+ const id = String(body.id ?? "");
1377
+ let r: unknown = null;
1378
+ if (body.op === "create") r = auto.addRule(state, body);
1379
+ else if (body.op === "update") r = auto.updateRule(state, id, body);
1380
+ else if (body.op === "pause" || body.op === "resume") r = auto.setEnabled(state, id, body.op === "resume");
1381
+ else if (body.op === "delete") r = auto.removeRule(state, id);
1382
+ else if (body.op === "run") {
1383
+ const rule = rules.find((x) => x.id === id);
1384
+ if (!rule) return bad("No such automation.", 404);
1385
+ const h = await auto.fire(state, rule, "manual", Date.now(), { pick: inCard, live: runLive });
1386
+ changed();
1387
+ return json({ ok: h?.status === "launched", status: h?.status, why: h?.reason }, 200);
1388
+ } else return bad("unknown op");
1389
+ if (typeof r === "string") return bad(r);
1390
+ changed();
1391
+ rules = auto.readRules(state);
1392
+ }
1393
+ const hist = auto.readHistory(state);
1394
+ const now = Date.now();
1395
+ return json({
1396
+ zone: Intl.DateTimeFormat().resolvedOptions().timeZone, cap: auto.DAILY_CAP, project: label(state),
1397
+ agents: KNOWN_AGENTS.filter((a) => agentEnabled(a.cmd)).map((a) => ({ cmd: a.cmd, name: a.name })),
1398
+ rules: rules.map((r) => ({ ...r, next: auto.nextRun(r.cron, now), history: hist.filter((h) => h.rule === r.id).sort((a, b) => b.at - a.at).slice(0, 20).map((h) => ({ ...h, ...auto.shown(state, h, now) })) })),
1399
+ });
1400
+ }
1401
+
1274
1402
  if (path === "/skills" && (req.method === "GET" || req.method === "POST")) {
1275
1403
  if (req.method === "POST") {
1276
1404
  const refused = strict(req);
@@ -2197,7 +2325,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
2197
2325
  const live = ptyKeys().some((k) => ptyState(k)?.alive);
2198
2326
  saveLive();
2199
2327
  awake.stop();
2200
- clearInterval(poll); clearInterval(ping); clearInterval(gather); clearInterval(loop); clearInterval(keepList);
2328
+ clearInterval(poll); clearInterval(ping); clearInterval(gather); clearInterval(automate); clearInterval(loop); clearInterval(keepList);
2201
2329
  for (const w of watchers) { try { w.close(); } catch { /* gone */ } }
2202
2330
  setTimeout(() => { server.stop(true); resolve(); }, live ? 400 : 0);
2203
2331
  };
package/cli/workers.ts CHANGED
@@ -195,6 +195,13 @@ const brief = (project: string, id: string, x: Worker) =>
195
195
  * when this run's frozen Orchestration permissions say so, and its tab says so too.
196
196
  */
197
197
  export function launchOf(project: string, id: string, x: Worker, permissions: "own" | "bypass", prefs: Prefs = readPrefs(), pick = ""): Launch | string {
198
+ const l = agentLine(project, id, brief(project, id, x), permissions, prefs, pick);
199
+ if (typeof l === "string") return l;
200
+ return { ...l, title: `Worker ${x.id}${l.bypass ? " · bypass" : ""}`, cwd: x.worktree, env: { KAIZEN_RUN_ID: id, KAIZEN_WORKER: x.id } };
201
+ }
202
+
203
+ /** The run's agent as a command line with `prompt`. Shared with the handoff; the caller names the terminal. */
204
+ export function agentLine(project: string, id: string, prompt: string, permissions: "own" | "bypass", prefs: Prefs = readPrefs(), pick = ""): Omit<Launch, "title" | "cwd" | "env"> | string {
198
205
  const own = runAgent(join(project, ".kaizen"), id), st = stateOf(project, id);
199
206
  const agent = detectDefaultAgent(project, own?.cmd ?? st?.agent);
200
207
  if (!agentUsable(agent.cmd)) return `${agent.name} is not available: see Settings > Agents`;
@@ -205,12 +212,12 @@ export function launchOf(project: string, id: string, x: Worker, permissions: "o
205
212
  if (acct.error) return acct.error;
206
213
  const bypass = permissions === "bypass" && !!YOLO_FLAGS[agent.cmd];
207
214
  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);
215
+ const line = withEnv([commandOf(agent.cmd, prefs), ...flags, ...promptArgs(agent.cmd, prompt)], agent.cmd, prefs);
209
216
  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,
217
+ argv: acct.dir ? ["env", ...accountEnv(acct), ...line] : line, bypass, agent: agent.cmd,
218
+ model: picked ? (MODEL_FLAGS[agent.cmd] ? picked : undefined) : model ?? agentFlags(project, agent.cmd).join(" ").match(/\S+$/)?.[0],
212
219
  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,
220
+ trust: acct.dir ? join(acct.dir, ".claude.json") : undefined,
214
221
  };
215
222
  }
216
223
 
@@ -3,7 +3,8 @@ import { test, expect, beforeEach } from "bun:test";
3
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 { linkTerm, linkedWs, startWorktree, landWorktree, codeDir, projectFromWorktree, run, runAsync, workspaces, workspacesNow, addWorktree, wsOf, adoptWorkspace, branchState, openPr, mergePr, removeWorktree, type Run, type AsyncRun } from "./worktree.ts";
6
+ import { notice } from "./state.ts";
7
+ import { linkTerm, linkedWs, startWorktree, landWorktree, landRun, codeDir, projectFromWorktree, run, runAsync, workspaces, workspacesNow, addWorktree, wsOf, adoptWorkspace, branchState, openPr, mergePr, removeWorktree, type Run, type AsyncRun } from "./worktree.ts";
7
8
 
8
9
  const ID = "2026-10-17-demo";
9
10
  // CI runners have no git identity, and landWorktree's rebase writes commits.
@@ -277,3 +278,175 @@ test("a linked terminal shows its live run's worktree, then falls back", () => {
277
278
  put({ stage: "build" }); // a current-folder run has no worktree
278
279
  expect(linkedWs(state, "sh-0123abcd")).toBeNull();
279
280
  });
281
+
282
+ const feature = () => { g(project, "switch", "-qc", "feature-x"); commit(project, "f.txt", "unpushed"); };
283
+
284
+ test("G-02 on a feature branch the worktree holds unpushed commits and lands by a local merge", () => {
285
+ feature();
286
+ const r = startWorktree(project, ID);
287
+ expect(r.ok).toBe(true);
288
+ expect(state().base_branch).toBe("feature-x");
289
+ expect(existsSync(join(state().worktree, "f.txt"))).toBe(true);
290
+ commit(state().worktree, "b.txt", "b");
291
+ const dir = state().worktree;
292
+ expect(landWorktree(project, ID, idRun)).toMatchObject({ ok: true, how: "merge" });
293
+ expect(existsSync(join(project, "b.txt"))).toBe(true);
294
+ expect(existsSync(dir)).toBe(false);
295
+ expect(run(["git", "rev-parse", "--verify", "--quiet", "refs/remotes/origin/feature-x"], project).ok).toBe(false);
296
+ });
297
+
298
+ test("G-03 a conflict, or the project on another branch, keeps the worktree and branch", () => {
299
+ feature();
300
+ startWorktree(project, ID);
301
+ const dir = state().worktree;
302
+ commit(dir, "f.txt", "theirs"); commit(project, "f.txt", "ours");
303
+ const c = landWorktree(project, ID, idRun);
304
+ expect(c.ok).toBe(false);
305
+ expect(g(project, "status", "--porcelain").includes("U")).toBe(false);
306
+ g(project, "switch", "-q", "main");
307
+ const o = landWorktree(project, ID, idRun);
308
+ expect(!o.ok && o.why).toContain("feature-x");
309
+ expect(existsSync(dir)).toBe(true);
310
+ expect(run(["git", "rev-parse", "--verify", "--quiet", "refs/heads/kaizen/" + ID], project).ok).toBe(true);
311
+ });
312
+
313
+ test("G-02 uncommitted changes on the feature branch are warned about", () => {
314
+ feature(); writeFileSync(join(project, "wip.txt"), "wip");
315
+ const r = startWorktree(project, ID);
316
+ expect(r.ok && r.warn).toContain("wip.txt");
317
+ });
318
+
319
+ test("G-01 on the default branch no base_branch is recorded", () => {
320
+ startWorktree(project, ID);
321
+ expect(state().base_branch).toBeUndefined();
322
+ });
323
+
324
+ test("land again after a merge whose cleanup failed only cleans up", () => {
325
+ feature(); startWorktree(project, ID);
326
+ commit(state().worktree, "b.txt", "b");
327
+ g(project, "merge", "--no-edit", "kaizen/" + ID);
328
+ const head = g(project, "rev-parse", "HEAD");
329
+ expect(landWorktree(project, ID, idRun)).toMatchObject({ ok: true, how: "merge" });
330
+ expect(g(project, "rev-parse", "HEAD")).toBe(head);
331
+ });
332
+
333
+ test("cold 6: a run with no commits is not landed, and a feature base offers no pull request", async () => {
334
+ feature(); startWorktree(project, ID);
335
+ const r = landWorktree(project, ID, idRun);
336
+ expect(!r.ok && r.why).toContain("no commits");
337
+ expect(existsSync(state().worktree)).toBe(true);
338
+ const b = branchState(project, ID, () => {}, idRun, runAsync, true)!;
339
+ expect(b).toMatchObject({ base: "feature-x", local: true, gh: false });
340
+ expect((await openPr(project, ID, "t", "b", false, idRun, runAsync, true)).ok).toBe(false);
341
+ });
342
+
343
+ // ---- land: rebase first, resolve only what is generated, record what stops it
344
+ const land = () => landWorktree(project, ID, idRun, false);
345
+ const cfg = (t: string) => writeFileSync(join(project, ".kaizen/config.yml"), t);
346
+ const upstream = (f: string, t: string) => { commit(other, f, t); g(other, "pull", "-q", "--rebase", "origin", "main"); g(other, "push", "-q", "origin", "HEAD:main"); };
347
+ const wt = () => state().worktree as string;
348
+
349
+ test("L-01 a stale branch that was never pushed lands with no force", () => {
350
+ startWorktree(project, ID); commit(wt(), "b.txt", "b"); upstream("c.txt", "c");
351
+ const seen: string[][] = [];
352
+ const r = landWorktree(project, ID, (c, d, m) => (seen.push(c), idRun(c, d, m)), false);
353
+ expect(r.ok).toBe(true);
354
+ expect(seen.flat().join(" ")).not.toContain("force");
355
+ expect(g(other, "ls-remote", "origin", "main")).toBeTruthy();
356
+ });
357
+
358
+ test("L-02 conflicts only in generated files land, rebuilt in one commit", () => {
359
+ cfg('git:\n generated: "*.js"\n rebuild_on_land: "echo rebuilt > app.js"\n land_check: off\n');
360
+ commit(project, "app.js", "0"); g(project, "push", "-q", "origin", "HEAD:main"); g(other, "pull", "-q", "origin", "main");
361
+ startWorktree(project, ID); writeFileSync(join(wt(), "app.js"), "mine"); writeFileSync(join(wt(), "b.txt"), "b"); g(wt(), "add", "."); g(wt(), "commit", "-qm", "feat: b");
362
+ upstream("app.js", "theirs");
363
+ expect(land().ok).toBe(true);
364
+ g(other, "pull", "-q", "origin", "main");
365
+ expect(readFileSync(join(other, "app.js"), "utf8").trim()).toBe("rebuilt");
366
+ expect(g(other, "log", "--format=%s", "-3")).toContain("chore: rebuild generated files");
367
+ expect(readFileSync(join(other, "b.txt"), "utf8")).toBe("b");
368
+ });
369
+
370
+ test("L-03 any other conflict aborts with branch, worktree and commits intact; default settings resolve nothing", () => {
371
+ startWorktree(project, ID); commit(wt(), "a.txt", "mine"); const tip = g(wt(), "rev-parse", "HEAD");
372
+ upstream("a.txt", "theirs");
373
+ const r = land();
374
+ expect(r).toMatchObject({ ok: false, kind: "conflict", paths: ["a.txt"] });
375
+ expect(g(wt(), "rev-parse", "HEAD")).toBe(tip);
376
+ expect(g(wt(), "status", "--porcelain")).toBe("");
377
+ expect(existsSync(wt())).toBe(true);
378
+ });
379
+
380
+ test("L-04 a failing check stops the land and puts the branch back; off and no pulled commits skip it", () => {
381
+ cfg('git:\n land_check: "exit 3"\n');
382
+ startWorktree(project, ID); commit(wt(), "b.txt", "b"); const tip = g(wt(), "rev-parse", "HEAD");
383
+ upstream("c.txt", "c");
384
+ expect(land()).toMatchObject({ ok: false, kind: "check" });
385
+ expect(g(wt(), "rev-parse", "HEAD")).toBe(tip);
386
+ cfg('git:\n land_check: off\n');
387
+ expect(land().ok).toBe(true);
388
+ });
389
+
390
+ test("L-04b no pulled commits skip the check", () => {
391
+ cfg('git:\n land_check: "exit 3"\n');
392
+ startWorktree(project, ID); commit(wt(), "b.txt", "b");
393
+ expect(land().ok).toBe(true);
394
+ });
395
+
396
+ test("L-05 merge=union keeps both lines of the log", () => {
397
+ commit(project, ".gitattributes", "Log.md merge=union\n"); commit(project, "Log.md", "0\n"); g(project, "push", "-q", "origin", "HEAD:main"); g(other, "pull", "-q", "origin", "main");
398
+ startWorktree(project, ID); commit(wt(), "Log.md", "0\nmine\n"); upstream("Log.md", "0\ntheirs\n");
399
+ expect(land().ok).toBe(true);
400
+ g(other, "pull", "-q", "origin", "main");
401
+ const log = readFileSync(join(other, "Log.md"), "utf8");
402
+ expect(log).toContain("mine"); expect(log).toContain("theirs");
403
+ });
404
+
405
+ test("L-06 a rebased pushed branch force pushes under a lease, on its own branch only", () => {
406
+ startWorktree(project, ID); commit(wt(), "b.txt", "b"); g(wt(), "push", "-q", "origin", `HEAD:refs/heads/kaizen/${ID}`); upstream("c.txt", "c");
407
+ const pushes: string[][] = [];
408
+ const r = landWorktree(project, ID, (c, d, m) => { if (c.includes("push")) pushes.push(c); return c.includes("gh") ? { ok: true, out: "", why: "" } : idRun(c, d, m); }, true);
409
+ const forced = pushes.filter((p) => p.some((a) => a.includes("force")));
410
+ expect(forced.length).toBe(1);
411
+ expect(forced[0]!.some((a) => a.startsWith(`--force-with-lease=refs/heads/kaizen/${ID}:`))).toBe(true);
412
+ expect(forced[0]!.at(-1)).toBe(`HEAD:refs/heads/kaizen/${ID}`);
413
+ expect(r.ok).toBe(false); // the stub gh merged nothing
414
+ });
415
+
416
+ test("L-07 land.json records a failure and clears on success", () => {
417
+ startWorktree(project, ID); commit(wt(), "a.txt", "mine");
418
+ const f = join(project, ".kaizen/runs", ID, "land.json");
419
+ writeFileSync(f, JSON.stringify({ kind: "conflict", why: "old" }));
420
+ const r = landRun(project, ID);
421
+ // No git identity in CI matters only for a rebase; nothing was pulled here.
422
+ expect(r.ok).toBe(true);
423
+ expect(existsSync(f)).toBe(false);
424
+ });
425
+
426
+ test("L-08 land.json holds what stopped the land, and the board card reads it", () => {
427
+ // landRun uses the plain runner: give this repo the identity CI lacks.
428
+ g(project, "config", "user.email", "a@b.c"); g(project, "config", "user.name", "t");
429
+ startWorktree(project, ID); commit(wt(), "a.txt", "mine"); upstream("a.txt", "theirs");
430
+ expect(landRun(project, ID, "sh-12345678").ok).toBe(false);
431
+ const l = JSON.parse(readFileSync(join(project, ".kaizen/runs", ID, "land.json"), "utf8"));
432
+ expect(l).toMatchObject({ kind: "conflict", paths: ["a.txt"], term: "sh-12345678" });
433
+ expect(notice({ kind: "run", text: "x", where: "p", status: "done", land: l } as any)).toBe("x — conflict: a.txt\np");
434
+ });
435
+
436
+ test("L-09 generated conflict with no rebuild command stops the land", () => {
437
+ cfg('git:\n generated: "*.js"\n land_check: off\n');
438
+ commit(project, "app.js", "0"); g(project, "push", "-q", "origin", "HEAD:main"); g(other, "pull", "-q", "origin", "main");
439
+ startWorktree(project, ID); commit(wt(), "app.js", "mine"); const tip = g(wt(), "rev-parse", "HEAD"); upstream("app.js", "theirs");
440
+ expect(land()).toMatchObject({ ok: false, kind: "conflict", paths: ["app.js"] });
441
+ expect(g(wt(), "rev-parse", "HEAD")).toBe(tip);
442
+ });
443
+
444
+ test("L-10 a failure with no kind replaces an old Conflict; a run with no worktree records nothing", () => {
445
+ const f = join(project, ".kaizen/runs", ID, "land.json");
446
+ expect(landRun(project, ID).ok).toBe(false);
447
+ expect(existsSync(f)).toBe(false);
448
+ startWorktree(project, ID); writeFileSync(f, JSON.stringify({ kind: "conflict", why: "old" }));
449
+ writeFileSync(join(wt(), "dirty.txt"), "x");
450
+ expect(landRun(project, ID).ok).toBe(false);
451
+ expect(JSON.parse(readFileSync(f, "utf8")).kind).toBe("merge");
452
+ });