kaizen-agent 1.63.0 → 1.64.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +10 -10
  2. package/agents/kaizen-planner.md +2 -2
  3. package/cli/backlog.test.ts +1 -1
  4. package/cli/board.test.ts +24 -24
  5. package/cli/dashboard.ts +15 -15
  6. package/cli/handoff.test.ts +133 -0
  7. package/cli/handoff.ts +122 -0
  8. package/cli/install.ts +31 -5
  9. package/cli/notes.test.ts +3 -3
  10. package/cli/notes.ts +1 -1
  11. package/cli/pty.ts +16 -2
  12. package/cli/resources.test.ts +50 -0
  13. package/cli/resources.ts +113 -0
  14. package/cli/restart.test.ts +28 -1
  15. package/cli/settings.ts +8 -5
  16. package/cli/sources.test.ts +32 -32
  17. package/cli/sources.ts +15 -15
  18. package/cli/state.test.ts +74 -51
  19. package/cli/state.ts +77 -49
  20. package/cli/usage.test.ts +11 -0
  21. package/cli/web.ts +139 -38
  22. package/cli/workers.ts +11 -4
  23. package/cli/worktree.test.ts +174 -1
  24. package/cli/worktree.ts +190 -35
  25. package/commands/kaizen-discover.md +1 -1
  26. package/package.json +1 -1
  27. package/skills/kaizen/README.md +2 -2
  28. package/skills/kaizen/SKILL.md +2 -2
  29. package/skills/kaizen/config.default.yml +32 -22
  30. package/skills/kaizen/discover.md +8 -8
  31. package/skills/kaizen/gather.md +2 -2
  32. package/skills/kaizen/settings.md +3 -0
  33. package/skills/kaizen/spec-build.md +13 -0
  34. package/skills/kaizen/spec-main.md +13 -0
  35. package/skills/kaizen/spec-plan.md +1 -1
  36. package/skills/kaizen/spec.md +1 -1
  37. package/skills/kaizen-help/SKILL.md +2 -2
  38. package/web/board/api.ts +10 -10
  39. package/web/board/cards.ts +47 -46
  40. package/web/board/git.ts +4 -4
  41. package/web/board/icebox.ts +14 -14
  42. package/web/board/keys.ts +3 -3
  43. package/web/board/labels.ts +2 -2
  44. package/web/board/live.ts +3 -3
  45. package/web/board/main.ts +1 -1
  46. package/web/board/markdown.ts +1 -1
  47. package/web/board/panel.ts +17 -17
  48. package/web/board/phone.ts +10 -12
  49. package/web/board/projects.ts +6 -6
  50. package/web/board/resources.ts +152 -0
  51. package/web/board/run-view.ts +5 -5
  52. package/web/board/search.ts +11 -11
  53. package/web/board/settings-cleanup.ts +42 -0
  54. package/web/board/settings-pages.ts +1 -1
  55. package/web/board/settings.ts +13 -0
  56. package/web/board/store.ts +1 -1
  57. package/web/board/{ideas.ts → tasks.ts} +22 -22
  58. package/web/board/terms.ts +3 -3
  59. package/web/board/views.ts +23 -12
  60. package/web/board/workspace.ts +9 -7
  61. package/web/board/ws-board-ui.ts +1 -1
  62. package/web/board/ws-board.test.ts +1 -1
  63. package/web/board/ws-board.ts +1 -1
  64. package/web/board/ws-tabs.test.ts +10 -2
  65. package/web/board/ws-tabs.ts +10 -9
  66. package/web/board.html +46 -34
  67. package/web/board.js +107 -97
  68. package/web/notebook.js +22 -22
  69. package/web/notebook.ts +5 -5
  70. package/web/notes-lib.ts +2 -2
  71. package/web/notes.html +12 -11
  72. package/web/term-font.test.ts +22 -0
  73. package/web/term-font.ts +30 -0
  74. package/web/term.js +38 -38
  75. package/web/term.ts +13 -2
  76. package/web/video.html +12 -11
  77. package/web/video.js +48 -48
package/cli/web.ts CHANGED
@@ -6,18 +6,20 @@ import { existsSync, readdirSync, statSync, lstatSync, realpathSync, readFileSyn
6
6
  import { join, dirname, resolve, sep, basename } from "node:path";
7
7
  import {
8
8
  home, type Item, type Card, knownProjects, remember, canonPath, locate, label, tilde, searchRoots, findProjects,
9
- readInbox, writeInbox, replaceIdea, moveIdea, abandonRun, runToIdea, launchRun, parseItem, agentChoices, onPath, projectOf, KNOWN_AGENTS, plainModel, short, setArchived, writeNotes,
9
+ readInbox, writeInbox, replaceTask, moveTask, abandonRun, runToTask, launchRun, parseItem, agentChoices, onPath, projectOf, KNOWN_AGENTS, plainModel, short, setArchived, writeNotes,
10
10
  appendNote, saveAttachment, pidOnPort, readText, cmdExe, sysExe, powershellExe, runGit, readCommit, commitPush, commitStaged, stageFiles, suggestMessage, notice, notifier, LOGO,
11
11
  reviewFindings, pickFindings, backlogItem, startedBacklog, closeBacklog, markBacklogDone, fixPrompt, approvalPrompt, canApproveAwaiting, gateOf, recordAcceptance, healRuns, finishRun, nativePath, closeSessions, sweepSessions, issueUrl,
12
- launchMode, readSessions, ownerOf, runIndex, resumePrompt, runAgent, firstSession, webHosts,
12
+ launchMode, pruneRuns, pruneSessions, readSessions, ownerOf, runIndex, resumePrompt, runAgent, firstSession, webHosts,
13
13
  } from "./state.ts";
14
14
  import { ACCOUNT_VAR, accountDir, addAccount, readAccounts, renameAccount, signedIn, removeAccount, resolveAccount, setDefaultAccount } from "./accounts.ts";
15
15
  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";
@@ -32,7 +34,7 @@ import * as auto from "./automations.ts";
32
34
  import * as localsend from "./localsend.ts";
33
35
  import * as hermes from "./hermes.ts";
34
36
  import { listChats, readChat, sendChat, stopChat, deleteChat, okId as okChatId, busy as chatBusy, type Event as ChatEvent, type Upload as ChatUpload } from "./chat.ts";
35
- 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";
36
38
  import { gitUrl, destDir, winBad, cloneInto, branchesOf, ignoreKaizen } from "./add-project.ts";
37
39
 
38
40
  const PAGE = join(dirname(import.meta.dir), "web", "board.html");
@@ -342,7 +344,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
342
344
 
343
345
  // Runs whose in-card agent was live when the board stopped (Settings' Update, Ctrl-C,
344
346
  // systemd) or died: the agents end with the old board, so the new one starts them
345
- // again (resumeRun). Each entry keeps its session key, so an idea whose run had not
347
+ // again (resumeRun). Each entry keeps its session key, so a task whose run had not
346
348
  // written state.json yet is matched to its run by the new board, once that run exists.
347
349
  // On a stop the agents are ended here, not left to the board's exit, so none outlives
348
350
  // it beside its resumed self; a tmux-kept one is only detached and is attached again.
@@ -367,7 +369,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
367
369
  return;
368
370
  }
369
371
  // Which project and run each session belongs to, found once: a run owns its session
370
- // for good, so only new sessions and ideas' ones send the walk through every project.
372
+ // for good, so only new sessions and tasks' ones send the walk through every project.
371
373
  // A key no project records (a Terminal page shell) is looked for once.
372
374
  for (const m of [owners, written, autoResumed]) for (const k of m.keys()) if (!live.has(k)) m.delete(k);
373
375
  for (const k of unrecorded) if (!live.has(k)) unrecorded.delete(k);
@@ -398,10 +400,10 @@ export async function web(repoDir: string, opts: Opts = {}) {
398
400
  };
399
401
  // ponytail: a 3s tick, so a crash loses up to 3s of screen; hook push() if that matters.
400
402
  const keepList = setInterval(() => saveLive(true), 3000);
401
- // An idea's session, until its run exists and owns it (ownerOf).
402
- const ideaPty = new Map<string, string>();
403
+ // A task's session, until its run exists and owns it (ownerOf).
404
+ const taskPty = new Map<string, string>();
403
405
  // Backlog items this board launched whose run has not written its state.json yet:
404
- // shown as starting, like a started idea. Forgotten on restart; the card then offers Run again.
406
+ // shown as starting, like a started task. Forgotten on restart; the card then offers Run again.
405
407
  const backlogLaunched = new Set<string>();
406
408
  // The card's newest in-card session, live or recently ended. Sessions are only read
407
409
  // while this board has any, so /state costs nothing more for terminal launches.
@@ -414,20 +416,20 @@ export async function web(repoDir: string, opts: Opts = {}) {
414
416
  const cmdOf = new Map<string, string>();
415
417
  for (const d of new Set(cards.map((c) => c.state))) for (const s of readSessions(d)) if (live.has(s.key) && s.cmd) cmdOf.set(s.key, s.cmd);
416
418
  const runs = new Map<string, string[]>();
417
- const planKeys = new Set(ideaPty.values());
419
+ const planKeys = new Set(taskPty.values());
418
420
  for (const d of new Set(cards.filter((c) => c.kind === "run").map((c) => c.state))) {
419
421
  const ids = runIndex(d);
420
422
  for (const s of readSessions(d))
421
423
  if (live.has(s.key)) {
422
424
  const owner = ownerOf(d, s, ids);
423
425
  const k = `${d}\0${owner}`;
424
- // The idea's agent that began this run is its plan terminal: recorded once the run exists.
426
+ // The task's agent that began this run is its plan terminal: recorded once the run exists.
425
427
  if (owner && planKeys.has(s.key) && !stagesOf(d, owner).plan) markStage(d, owner, "plan", s.key);
426
428
  runs.set(k, [...(runs.get(k) ?? []), s.key]); // oldest first: the newest is the card's
427
429
  }
428
430
  }
429
431
  return Object.assign((c: Card) => {
430
- const keys = c.kind === "run" ? runs.get(`${c.state}\0${c.id}`) ?? [] : [ideaPty.get(`${c.state}\0${c.text}`)].filter((k): k is string => !!k && live.has(k));
432
+ const keys = c.kind === "run" ? runs.get(`${c.state}\0${c.id}`) ?? [] : [taskPty.get(`${c.state}\0${c.text}`)].filter((k): k is string => !!k && live.has(k));
431
433
  const key = keys.at(-1);
432
434
  if (!key) return undefined;
433
435
  const st = ptyState(key)!;
@@ -438,6 +440,40 @@ export async function web(repoDir: string, opts: Opts = {}) {
438
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 };
439
441
  }, { cmd: (k: string) => cmdOf.get(k) });
440
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
+ };
441
477
  // Orchestration: the only place a worker's terminal starts. A worker asks for it in workers.json
442
478
  // (`kaizen worker start`); with the mode off no such file exists, so this finds nothing.
443
479
  // startWorker re-checks the stage, the frozen settings, the count and the plan before anything runs.
@@ -463,7 +499,10 @@ export async function web(repoDir: string, opts: Opts = {}) {
463
499
  }
464
500
  try {
465
501
  const runs = join(dir, "runs");
466
- 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
+ }
467
506
  } catch { /* the next tick tries again */ }
468
507
  }
469
508
  };
@@ -797,6 +836,19 @@ export async function web(repoDir: string, opts: Opts = {}) {
797
836
  if (!/^[\w-]+$/.test(key) || !ptyState(key)) return bad("no such terminal", 404);
798
837
  return json({ ok: exitPty(key) });
799
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
+ }
800
852
 
801
853
  // A plain shell, or a bare Claude/Codex session, in a project folder: the run
802
854
  // workspace's + menu. Code execution, so local() as for every write, a registered
@@ -975,6 +1027,30 @@ export async function web(repoDir: string, opts: Opts = {}) {
975
1027
  for (const k of shells.keys()) if (!ptyState(k)?.alive) shells.delete(k);
976
1028
  return json([...shells.values()].filter((s) => !dir || s.dir === dir).map(shown));
977
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
+ }
978
1054
  // The localhost tab's "Open in browser": a Chromium app window on this computer, for
979
1055
  // localhost pages that refuse to be framed. Launches a process, so /shell's guards, and only a
980
1056
  // loopback http(s) address, passed as one --app= argument, never a shell string.
@@ -1074,7 +1150,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1074
1150
  } catch { return bad("file not found", 404); }
1075
1151
  }
1076
1152
 
1077
- // What a note can link to on this project's board: runs, findings, backlog, ideas.
1153
+ // What a note can link to on this project's board: runs, findings, backlog, tasks.
1078
1154
  if (req.method === "GET" && path === "/links") {
1079
1155
  const dir = qdir() ?? state ?? join(home, ".kaizen");
1080
1156
  if (!states(true).includes(dir)) return bad("unknown state dir", 404);
@@ -1157,6 +1233,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
1157
1233
  // A plain shell counts too while an agent typed into it runs there.
1158
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); }
1159
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;
1160
1238
  const entry = (d: string) => ({ dir: d, label: label(d), logo: !!projectLogo(d),
1161
1239
  workspaces: d === join(home, ".kaizen") ? [{ path: d, branch: "", main: true }] : workspacesNow(projectOf(d)) });
1162
1240
  const body = JSON.stringify({
@@ -1173,7 +1251,10 @@ export async function web(repoDir: string, opts: Opts = {}) {
1173
1251
  const signal = signalOf(c, rep, ptys[i] as any, Date.now(), beat);
1174
1252
  // Only a run that has workers.json carries `workers`: any other card is as it was.
1175
1253
  const ws = c.kind === "run" && c.id ? readWorkers(projectOf(c.state), c.id) : null;
1176
- 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 } : {}) };
1177
1258
  }),
1178
1259
  backlog: backlog.map((b) => ({ ...b, starting: backlogLaunched.has(`${b.state}\0${b.source}#${b.n}`) || undefined })),
1179
1260
  now: Date.now(),
@@ -1283,6 +1364,26 @@ export async function web(repoDir: string, opts: Opts = {}) {
1283
1364
  return json({ accounts: rows, windows: process.platform === "win32", ...(added ? { added } : {}) });
1284
1365
  }
1285
1366
 
1367
+ // Settings → General → Cleanup: what `kaizen prune` would remove from this page's project,
1368
+ // one kind at a time. Deletion is decided here, on the current files, not on the page's counts.
1369
+ if (path === "/cleanup" && (req.method === "GET" || req.method === "POST")) {
1370
+ if (!state) return bad("no project", 404);
1371
+ const { listSettings } = await import("./settings.ts");
1372
+ const keep = Number(listSettings(repoDir, dirname(state)).rows.find((r) => r.key === "state.keep_runs")?.value) || 20;
1373
+ if (req.method === "POST") {
1374
+ if (!local(req)) return bad("cross-origin write refused", 403);
1375
+ let body: any;
1376
+ try { body = await req.json(); } catch { return bad("json body expected"); }
1377
+ if (body.what === "records") return json({ removed: pruneSessions(state, true).length });
1378
+ if (body.what === "runs") return json({ removed: pruneRuns(state, keep, true).length });
1379
+ return bad("unknown cleanup");
1380
+ }
1381
+ const records = { abandoned: 0, unowned: 0, gone: 0 };
1382
+ for (const r of pruneSessions(state)) records[r.reason]++;
1383
+ const runs = pruneRuns(state, keep);
1384
+ return json({ project, keep, records, runs: runs.length, rescued: runs.reduce((n, r) => n + r.rescued, 0) });
1385
+ }
1386
+
1286
1387
  if (path === "/automations" && (req.method === "GET" || req.method === "POST")) {
1287
1388
  if (!state || state === join(home, ".kaizen")) return json({ error: "Open a project first." }, 404);
1288
1389
  let rules: auto.Rule[];
@@ -1599,7 +1700,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1599
1700
  return "error" in r ? { error: r.error } : { dir: (r as { dir: string }).dir };
1600
1701
  },
1601
1702
  agents: KNOWN_AGENTS.filter((a) => agentUsable(a.cmd)).map((a) => a.cmd),
1602
- // As POST /run starts an idea, without one on the inbox.
1703
+ // As POST /run starts a task, without one on the inbox.
1603
1704
  run: async (d: string, runner: "lite" | "full", agent: string, text: string) => {
1604
1705
  const r = launchRun(parseItem(`${runner} ${text}`), d, undefined, { agent, ...inCard(d) });
1605
1706
  changed();
@@ -1720,7 +1821,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1720
1821
  return json({ ok: true, added: knownProjects().length - before });
1721
1822
  }
1722
1823
 
1723
- // No project here means the global inbox, which is where the TUI puts ideas too.
1824
+ // No project here means the global inbox, which is where the TUI puts tasks too.
1724
1825
  let dir: string = body.dir ?? state ?? join(home, ".kaizen");
1725
1826
  // Choosing a folder from the projects folder is what sets it up: an empty
1726
1827
  // .kaizen, which the first run fills in. Only folders the board offered.
@@ -1751,32 +1852,32 @@ export async function web(repoDir: string, opts: Opts = {}) {
1751
1852
 
1752
1853
  if (path === "/inbox") {
1753
1854
  const text = String(body.text ?? "").trim();
1754
- // Absent means untouched; an empty string clears. replaceIdea keeps the
1855
+ // Absent means untouched; an empty string clears. replaceTask keeps the
1755
1856
  // old notes for any op that does not send them.
1756
1857
  const notes = typeof body.notes === "string" ? body.notes.trim() : undefined;
1757
1858
  if (body.op === "add") {
1758
- if (!text) return bad("empty idea");
1859
+ if (!text) return bad("empty task");
1759
1860
  writeInbox(dir, [...readInbox(dir), { status: "open", text, notes }]);
1760
1861
  } else if (body.op === "edit") {
1761
1862
  const next = String(body.next ?? "").trim();
1762
- if (!text || !next) return bad("empty idea");
1763
- replaceIdea(dir, text, notes === undefined ? { status: "open", text: next } : { status: "open", text: next, notes });
1863
+ if (!text || !next) return bad("empty task");
1864
+ replaceTask(dir, text, notes === undefined ? { status: "open", text: next } : { status: "open", text: next, notes });
1764
1865
  } else if (body.op === "reject") {
1765
1866
  const why = String(body.reason ?? "").trim();
1766
1867
  if (!why) return bad("a rejection needs a reason");
1767
- replaceIdea(dir, text, { status: "rejected", text: `${text} | ${why}` });
1868
+ replaceTask(dir, text, { status: "rejected", text: `${text} | ${why}` });
1768
1869
  } else if (body.op === "delete") {
1769
- replaceIdea(dir, text, null);
1870
+ replaceTask(dir, text, null);
1770
1871
  } else if (body.op === "move") {
1771
1872
  if (typeof body.to !== "string" || !states(true).includes(body.to)) return bad("unknown state dir", 404);
1772
- const why = moveIdea(dir, body.to, text);
1773
- if (why) return bad(why, why === "no such idea" ? 404 : 409);
1873
+ const why = moveTask(dir, body.to, text);
1874
+ if (why) return bad(why, why === "no such task" ? 404 : 409);
1774
1875
  } else return bad("unknown op");
1775
1876
  changed();
1776
1877
  return json({ ok: true });
1777
1878
  }
1778
1879
 
1779
- // Request sources. Gathering fills the icebox and nothing else: no idea is
1880
+ // Request sources. Gathering fills the icebox and nothing else: no task is
1780
1881
  // made and no run starts here.
1781
1882
  if (path === "/sources") {
1782
1883
  // A social source arrives as a platform and what to follow; the link is built here.
@@ -1844,8 +1945,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
1844
1945
  return (/\.(png|jpe?g|gif|webp|svg)$/i.test(rel) ? "!" : "") + `[${String(f.name ?? "file")}](${rel})`;
1845
1946
  });
1846
1947
  };
1847
- // The icebox: the only way gathered text becomes an idea, one explicit click
1848
- // (or agent call) at a time. An idea is made; no run starts.
1948
+ // The icebox: the only way gathered text becomes a task, one explicit click
1949
+ // (or agent call) at a time. A task is made; no run starts.
1849
1950
  if (path === "/icebox") {
1850
1951
  if (typeof body.dir !== "string" || !states(true).includes(body.dir)) return bad("say which project's icebox this is");
1851
1952
  const ids = Array.isArray(body.ids) ? body.ids.filter((i: unknown) => typeof i === "string") : [];
@@ -1893,12 +1994,12 @@ export async function web(repoDir: string, opts: Opts = {}) {
1893
1994
  if (path === "/run") {
1894
1995
  const text = String(body.text ?? "").trim();
1895
1996
  const kind = body.kind === "full" || body.kind === "lite" ? body.kind : "";
1896
- if (!text && !body.backlog) return bad("empty idea");
1997
+ if (!text && !body.backlog) return bad("empty task");
1897
1998
  const agent = typeof body.agent === "string" && body.agent ? body.agent : undefined;
1898
1999
  if (agent && !KNOWN_AGENTS.some((a) => a.cmd === agent)) return bad("unknown agent");
1899
2000
  const model = typeof body.model === "string" ? body.model.trim() : "";
1900
2001
  if (model && !plainModel(model)) return bad("A model name is letters, digits and . : / @ _ - only");
1901
- // A backlog item runs as an idea would, its text read here from the file, never
2002
+ // A backlog item runs as a task would, its text read here from the file, never
1902
2003
  // from the page. The request names its source, which is how the board finds the
1903
2004
  // line again: to hide the card while the run lives, and to close it when done.
1904
2005
  if (body.backlog) {
@@ -1918,14 +2019,14 @@ export async function web(repoDir: string, opts: Opts = {}) {
1918
2019
  : { ok: false, why: r.why, manual: r.manual, agent: r.agent }, r.ok ? 200 : 500);
1919
2020
  }
1920
2021
  const it: Item = parseItem(`${kind} ${text}`.trim());
1921
- // A `started` idea may be run again: the terminal the first launch opened
2022
+ // A `started` task may be run again: the terminal the first launch opened
1922
2023
  // can come up empty, and nothing else tells the board a run never began.
1923
2024
  it.notes = readInbox(dir).find((l) => (l.status === "open" || l.status === "started") && l.text === text)?.notes;
1924
2025
  const r = launchRun(it, dir, undefined, { agent, account: typeof body.account === "string" ? body.account : undefined, model: model || undefined, yolo: body.yolo === true, ...inCard(dir) });
1925
- if (r.ok) replaceIdea(dir, text, { status: "started", text });
2026
+ if (r.ok) replaceTask(dir, text, { status: "started", text });
1926
2027
  if (r.ok && r.pty) {
1927
- for (const [k, v] of ideaPty) if (!ptyState(v)) ideaPty.delete(k); // sessions already dropped
1928
- ideaPty.set(`${dir}\0${text}`, r.pty);
2028
+ for (const [k, v] of taskPty) if (!ptyState(v)) taskPty.delete(k); // sessions already dropped
2029
+ taskPty.set(`${dir}\0${text}`, r.pty);
1929
2030
  }
1930
2031
  changed();
1931
2032
  return json(r.ok
@@ -1944,7 +2045,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1944
2045
  const text = body.text.trim();
1945
2046
  const lines = readInbox(dir);
1946
2047
  const at = lines.findIndex((l) => l.text === text && (archived ? l.status === "open" : l.status === "archived"));
1947
- if (at < 0) return bad("no such idea", 404);
2048
+ if (at < 0) return bad("no such task", 404);
1948
2049
  lines[at] = { ...lines[at]!, status: archived ? "archived" : "open" };
1949
2050
  writeInbox(dir, lines);
1950
2051
  } else return bad("id or text required");
@@ -2170,10 +2271,10 @@ export async function web(repoDir: string, opts: Opts = {}) {
2170
2271
  : { ok: false, why: r.why, manual: r.manual, agent: r.agent }, r.ok ? 200 : 500);
2171
2272
  }
2172
2273
 
2173
- if (path === "/to-idea") {
2274
+ if (path === "/to-task" || path === "/to-idea") { // /to-idea: the old name, kept for open tabs
2174
2275
  const id = String(body.id ?? "");
2175
2276
  if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
2176
- const failed = runToIdea(dir, id);
2277
+ const failed = runToTask(dir, id);
2177
2278
  changed();
2178
2279
  return failed ? bad(failed, 409) : json({ ok: true });
2179
2280
  }
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
+ });