kaizen-agent 1.63.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.
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";
@@ -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");
@@ -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.
@@ -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(),
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
+ });