kaizen-agent 1.60.0 → 1.60.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.
package/cli/pty.test.ts CHANGED
@@ -232,14 +232,19 @@ test.skipIf(process.platform !== "win32")("on Windows a card agent runs in a pse
232
232
  expect(ptyState(key)?.alive).toBe(false);
233
233
  }, 60_000);
234
234
 
235
- test("busy: on while the agent prints, off once its output goes quiet", async () => {
235
+ test("busy: on while the agent draws its working line, off once it goes quiet; other output is not work", async () => {
236
236
  const key = "busy-" + Date.now();
237
- startPty(key, ["sh", "-c", "for i in 1 2 3 4 5 6; do echo tick; sleep 0.1; done; read l"], root);
237
+ startPty(key, ["sh", "-c", "for i in 1 2 3 4 5 6; do echo 'Thinking (3s · esc to interrupt)'; sleep 0.1; done; read l"], root);
238
238
  await Bun.sleep(250);
239
239
  expect(ptyState(key)!.busy).toBe(true);
240
240
  await Bun.sleep(1800);
241
241
  expect(ptyState(key)).toMatchObject({ alive: true, busy: false });
242
242
  exitPty(key);
243
+ const idle = "idle-" + Date.now();
244
+ startPty(idle, ["sh", "-c", "for i in 1 2 3 4 5 6; do echo statusline; sleep 0.1; done; read l"], root);
245
+ await Bun.sleep(250);
246
+ expect(ptyState(idle)!.busy).toBe(false);
247
+ exitPty(idle);
243
248
  });
244
249
 
245
250
  test("lastLine: only the agent's own marked reply lines, never input", () => {
package/cli/pty.ts CHANGED
@@ -42,6 +42,7 @@ const ASK = /Would you like to|Do you want to|[❯›>] ?1\. |Type something|\(y
42
42
  // redraw of the answered prompt or prompt-like words in its output would otherwise keep it "asking".
43
43
  // Not a bare "Esc to cancel": Claude Code's own question footer says that.
44
44
  const WORK = /\(\d+m? ?\d*s [·•]|esc to interrupt|\(esc to cancel, \d|esc interrupt/gi;
45
+ const WORKING = new RegExp(WORK.source, "i");
45
46
  const lastAt = (re: RegExp, t: string) => { let i = -1; for (const m of t.matchAll(re)) i = m.index!; return i; };
46
47
  export const asking = (screen: string) => {
47
48
  const t = screen.replace(/\x1b\[[0-9;?]*[A-Za-z]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[()][0-9A-Za-z]/g, " ");
@@ -96,8 +97,8 @@ export function startPty(key: string, cmd: string[], cwd: string, pidFile?: stri
96
97
  // attach: the session already runs (kept from a board before this one); only a client is started.
97
98
  if (opts.tmux && tmuxOk()) cmd = opts.attach ? attachCmd(opts.tmux) : tmuxCmd(opts.tmux, cmd);
98
99
  const flag = (v: boolean) => { if (p.asking !== v) { p.asking = v; onChange?.(); } };
99
- // busy: output in the last QUIET_MS. A working agent redraws its spinner many times a second,
100
- // so a quiet terminal is one waiting at its prompt.
100
+ // busy: the agent's working line (WORK) drawn in the last QUIET_MS. A working agent redraws it many
101
+ // times a second; other output (a status-line refresh, a repaint on resize or focus) is not work.
101
102
  const work = (v: boolean) => { if (p.busy !== v) { p.busy = v; onChange?.(); } };
102
103
  const push = (d: string) => {
103
104
  p.out.push(d);
@@ -105,7 +106,7 @@ export function startPty(key: string, cmd: string[], cwd: string, pidFile?: stri
105
106
  p.total += d.length;
106
107
  while (p.size > CAP && p.out.length > 1) p.size -= p.out.shift()!.length;
107
108
  for (const f of p.listeners) f(d);
108
- work(p.exit === null);
109
+ if (WORKING.test(d)) work(p.exit === null);
109
110
  grab(p, d, 1000);
110
111
  clearTimeout(p.quiet);
111
112
  p.quiet = setTimeout(() => {
@@ -0,0 +1,51 @@
1
+ import { expect, test } from "bun:test";
2
+ import { mkdtempSync, mkdirSync, realpathSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+
6
+ // The Git tab's /pr takes the runs /commit takes: finished (or at the final approval),
7
+ // never the global state dir, and create/merge only once the final approval is given.
8
+ test.skipIf(process.platform === "win32")("board /pr refuses unfinished, unapproved and global runs", async () => {
9
+ const home = realpathSync(mkdtempSync(join(tmpdir(), "kz-pr-")));
10
+ const proj = join(home, "proj"), st = join(proj, ".kaizen");
11
+ mkdirSync(join(proj, "cli"), { recursive: true });
12
+ writeFileSync(join(proj, "cli", "a.ts"), "");
13
+ mkdirSync(join(home, ".kaizen", "runs", "2026-10-30-global"), { recursive: true });
14
+ writeFileSync(join(home, ".kaizen", "runs", "2026-10-30-global", "state.json"), JSON.stringify({ stage: "done" }));
15
+ writeFileSync(join(home, ".kaizen", "projects"), proj + "\n");
16
+ const mk = (id: string, state: object) => {
17
+ const d = join(st, "runs", id);
18
+ mkdirSync(d, { recursive: true });
19
+ writeFileSync(join(d, "state.json"), JSON.stringify(state));
20
+ writeFileSync(join(d, "03-impl.md"), "## Changed\n- `cli/a.ts`\n");
21
+ };
22
+ mkdirSync(st, { recursive: true });
23
+ writeFileSync(join(st, "config.yml"), "approvals:\n review: true\n");
24
+ mk("2026-10-30-building", { stage: "build" });
25
+ mk("2026-10-30-unapproved", { stage: "done" }); // done with changed files, no accepted: line
26
+ const port = 20000 + Math.floor(Math.random() * 20000);
27
+ const p = Bun.spawn([process.execPath, join(import.meta.dir, "install.ts"), "web", "--foreground", "--no-open", "--port", String(port)],
28
+ { env: { ...process.env, HOME: home, USERPROFILE: home, KAIZEN_HOME: join(home, "kz") }, stdout: "ignore", stderr: "ignore" });
29
+ try {
30
+ const base = `http://127.0.0.1:${port}`;
31
+ for (let i = 0; i < 100; i++) { try { if ((await fetch(base + "/")).ok) break; } catch { /* not up yet */ } await Bun.sleep(100); }
32
+ const pr = async (dir: string, id: string, op: string) => {
33
+ const r = await fetch(base + "/pr", { method: "POST", headers: { origin: base, "content-type": "application/json" }, body: JSON.stringify({ dir, id, op, title: "feat: x" }) });
34
+ return { status: r.status, body: await r.json() };
35
+ };
36
+ for (const op of ["create", "merge", "remove"]) {
37
+ expect((await pr(st, "2026-10-30-building", op)).status).toBe(409);
38
+ expect((await pr(join(home, ".kaizen"), "2026-10-30-global", op)).status).toBe(409);
39
+ }
40
+ for (const op of ["create", "merge"]) {
41
+ const r = await pr(st, "2026-10-30-unapproved", op);
42
+ expect(r.status).toBe(409);
43
+ expect(JSON.stringify(r.body)).toContain("not approved");
44
+ }
45
+ // remove is not gated on the approval, but a run with no worktree has nothing to remove.
46
+ const rm = await pr(st, "2026-10-30-unapproved", "remove");
47
+ expect(rm.status).toBe(409);
48
+ expect(JSON.stringify(rm.body)).toContain("no worktree");
49
+ expect((await pr(st, "../x", "create")).status).toBe(400);
50
+ } finally { p.kill(); }
51
+ }, 30000);
package/cli/web.ts CHANGED
@@ -22,7 +22,7 @@ import * as video from "./video.ts";
22
22
  import * as localsend from "./localsend.ts";
23
23
  import * as hermes from "./hermes.ts";
24
24
  import { listChats, readChat, sendChat, stopChat, deleteChat, okId as okChatId, busy as chatBusy, type Event as ChatEvent, type Upload as ChatUpload } from "./chat.ts";
25
- import { workspaces, workspacesNow, forgetWorkspaces, workspacesAge, addWorktree, run } from "./worktree.ts";
25
+ import { workspaces, workspacesNow, forgetWorkspaces, workspacesAge, addWorktree, run, branchState, openPr, mergePr, removeWorktree } from "./worktree.ts";
26
26
  import { gitUrl, destDir, winBad, cloneInto, branchesOf, ignoreKaizen } from "./add-project.ts";
27
27
 
28
28
  const PAGE = join(dirname(import.meta.dir), "web", "board.html");
@@ -253,6 +253,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
253
253
  let usageCache: Usage[] = [];
254
254
  let usageAt = 0;
255
255
  let pending: ReturnType<typeof setTimeout> | null = null;
256
+ const prBusy = new Set<string>();
256
257
  const changed = () => {
257
258
  if (pending) return;
258
259
  pending = setTimeout(() => {
@@ -1052,6 +1053,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
1052
1053
  findings: dir === join(home, ".kaizen") ? [] : reviewFindings(dir, id),
1053
1054
  // The global state dir sits in $HOME, which is not a project to commit.
1054
1055
  commit: readCommit(dir, id), git: dir === join(home, ".kaizen") ? { repo: false } : runGit(dir, id),
1056
+ // The run's own branch and pull request, for the Git tab; null when it has no worktree.
1057
+ branch: dir === join(home, ".kaizen") ? null : branchState(dirname(dir), id, changed),
1055
1058
  });
1056
1059
  }
1057
1060
 
@@ -1729,6 +1732,32 @@ export async function web(repoDir: string, opts: Opts = {}) {
1729
1732
  return json(r, r.ok ? 200 : 409);
1730
1733
  }
1731
1734
 
1735
+ // The Git tab's later steps, on the same runs /commit takes: open the branch's pull
1736
+ // request, merge it, then remove the worktree once its work is on the base.
1737
+ if (path === "/pr") {
1738
+ const id = String(body.id ?? "");
1739
+ if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
1740
+ // One step per run at a time: a second tab's Merge or Remove waits its turn.
1741
+ const lock = `${dir}\0${id}`;
1742
+ if (prBusy.has(lock)) return bad("Another git step is running on this run. Try again when it finishes.", 409);
1743
+ if (dir === join(home, ".kaizen")) return bad("no project", 409);
1744
+ let run: any;
1745
+ try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return bad("no such run", 404); }
1746
+ if (run.stage !== "done" && run.awaiting !== "approvals.review") return bad("this run is not finished", 409);
1747
+ const project = dirname(dir);
1748
+ if (body.op !== "remove" && gateOf(dir, id) === "needs") return bad("This run is not approved yet. Approve it first.", 409);
1749
+ prBusy.add(lock);
1750
+ let r: { ok: boolean };
1751
+ try {
1752
+ r = body.op === "create" ? await openPr(project, id, String(body.title ?? ""), String(body.body ?? ""), body.draft === true)
1753
+ : body.op === "merge" ? await mergePr(project, id)
1754
+ : body.op === "remove" ? await removeWorktree(project, id)
1755
+ : { ok: false as const, why: "unknown op" };
1756
+ } finally { prBusy.delete(lock); }
1757
+ changed();
1758
+ return json(r, r.ok ? 200 : 409);
1759
+ }
1760
+
1732
1761
  // Fix picked findings, on the same runs /commit takes and for the same reason
1733
1762
  // never in the global state dir: the agent starts in a project, and the run is
1734
1763
  // not there. Only numbers the review itself holds reach the prompt.
@@ -3,7 +3,7 @@ import { test, expect, beforeEach } from "bun:test";
3
3
  import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync } from "node:fs";
4
4
  import { join } from "node:path";
5
5
  import { tmpdir } from "node:os";
6
- import { startWorktree, landWorktree, codeDir, projectFromWorktree, run, workspaces, workspacesNow, addWorktree, wsOf, adoptWorkspace, type Run } from "./worktree.ts";
6
+ import { startWorktree, landWorktree, codeDir, projectFromWorktree, run, runAsync, workspaces, workspacesNow, addWorktree, wsOf, adoptWorkspace, branchState, openPr, mergePr, removeWorktree, type Run, type AsyncRun } from "./worktree.ts";
7
7
 
8
8
  const ID = "2026-10-17-demo";
9
9
  // CI runners have no git identity, and landWorktree's rebase writes commits.
@@ -155,3 +155,106 @@ test("workspacesNow: answers at once, refreshes git in the background, one call
155
155
  expect(workspacesNow(p, slow)).toEqual([{ path: p, branch: "dev", main: true }]);
156
156
  expect(calls).toBe(1);
157
157
  });
158
+
159
+ // ---- the Git tab (2026-10-30-run-git-tab)
160
+
161
+ // gh faked, git real: GitHub is never asked, the branch and the worktree are real.
162
+ const fakeGh = (answer: (cmd: string[], cwd: string) => { ok: boolean; out: string; why: string }) => {
163
+ const calls: string[][] = [];
164
+ const ash: AsyncRun = async (cmd, cwd) => {
165
+ if (cmd[0] !== "gh") return runAsync(cmd[0] === "git" ? ["git", "-c", "user.email=a@b.c", "-c", "user.name=t", ...cmd.slice(1)] : cmd, cwd);
166
+ calls.push(cmd);
167
+ return answer(cmd, cwd);
168
+ };
169
+ return { ash, calls };
170
+ };
171
+ const ghRun: Run = (cmd, cwd) => { if (cmd[0] === "gh") throw new Error("gh run on the request path"); return idRun(cmd, cwd); };
172
+ const tick = () => new Promise((r) => setTimeout(r, 50));
173
+
174
+ test("G-03 branchState never asks GitHub on the request path and shows the PR once the look lands", async () => {
175
+ const id = "2026-10-30-look";
176
+ mkdirSync(join(project, ".kaizen/runs", id), { recursive: true });
177
+ writeFileSync(join(project, ".kaizen/runs", id, "state.json"), JSON.stringify({ id, stage: "done" }));
178
+ startWorktree(project, id);
179
+ const pr = { number: 7, url: "https://github.com/x/y/pull/7", state: "OPEN", isDraft: false };
180
+ const { ash, calls } = fakeGh(() => ({ ok: true, out: JSON.stringify(pr), why: "" }));
181
+ let changed = 0;
182
+ const first = branchState(project, id, () => changed++, ghRun, ash, true)!;
183
+ expect(first).toMatchObject({ branch: `kaizen/${id}`, base: "main", upstream: false, landed: false, pr: null, checking: true });
184
+ await tick();
185
+ expect(calls.map((c) => c.slice(0, 4).join(" "))).toEqual([`gh pr view kaizen/${id}`]);
186
+ expect(changed).toBe(1);
187
+ const again = branchState(project, id, () => changed++, ghRun, ash, true)!;
188
+ expect(again.pr).toEqual({ number: 7, url: pr.url, state: "OPEN", draft: false });
189
+ expect(again.checking).toBe(false);
190
+ await tick();
191
+ expect(calls.length).toBe(1); // cached: no second look inside 30 s
192
+ });
193
+
194
+ test("G-02 a run with no worktree has no branch state; one with no commits of its own is not landed", () => {
195
+ expect(branchState(project, ID, () => {}, ghRun, runAsync, false)).toBeNull();
196
+ startWorktree(project, ID);
197
+ expect(branchState(project, ID, () => {}, ghRun, runAsync, false)!.landed).toBe(false);
198
+ });
199
+
200
+ test("G-06 openPr pushes, then creates the PR with title and body as separate arguments", async () => {
201
+ const w = (startWorktree(project, ID) as { path: string }).path;
202
+ commit(w, "run.txt", "mine");
203
+ const { ash, calls } = fakeGh((cmd) => cmd[2] === "view"
204
+ ? { ok: true, out: JSON.stringify({ number: 3, url: "u", state: "OPEN", isDraft: true }), why: "" }
205
+ : { ok: true, out: "u", why: "" });
206
+ const r = await openPr(project, ID, "feat: a; rm -rf /", "Run x.\n$(id)", true, idRun, ash, true);
207
+ expect(r).toEqual({ ok: true, pr: { number: 3, url: "u", state: "OPEN", draft: true } });
208
+ expect(calls[0]).toEqual(["gh", "pr", "create", "--base", "main", "--head", `kaizen/${ID}`, "--title", "feat: a; rm -rf /", "--body", "Run x.\n$(id)", "--draft"]);
209
+ expect(g(project, "ls-remote", "--heads", "origin", `kaizen/${ID}`)).toContain(ID); // pushed first
210
+ });
211
+
212
+ test("G-06 openPr refuses a dirty worktree, no gh, an empty title, and a run without a branch", async () => {
213
+ const { ash, calls } = fakeGh(() => ({ ok: true, out: "", why: "" }));
214
+ expect((await openPr(project, ID, "t", "", false, idRun, ash, true)).ok).toBe(false); // no worktree
215
+ const w = (startWorktree(project, ID) as { path: string }).path;
216
+ expect((await openPr(project, ID, "t", "", false, idRun, ash, false)).ok).toBe(false);
217
+ expect((await openPr(project, ID, " ", "", false, idRun, ash, true)).ok).toBe(false);
218
+ writeFileSync(join(w, "dirty.txt"), "x");
219
+ const r = await openPr(project, ID, "t", "", false, idRun, ash, true);
220
+ expect(r).toEqual({ ok: false, why: "Commit the changes first." });
221
+ expect(calls).toEqual([]);
222
+ });
223
+
224
+ test("G-06 mergePr merges by rebase with the branch name", async () => {
225
+ startWorktree(project, ID);
226
+ const { ash, calls } = fakeGh(() => ({ ok: true, out: "", why: "" }));
227
+ expect(await mergePr(project, ID, idRun, ash, true)).toEqual({ ok: true });
228
+ expect(calls).toEqual([["gh", "pr", "merge", `kaizen/${ID}`, "--rebase"]]);
229
+ });
230
+
231
+ test("G-04 removeWorktree refuses dirty or unlanded work and cleans up once it is on the base", async () => {
232
+ const w = (startWorktree(project, ID) as { path: string }).path;
233
+ commit(w, "run.txt", "mine");
234
+ writeFileSync(join(w, "wip.txt"), "x");
235
+ expect((await removeWorktree(project, ID, idRun)).ok).toBe(false);
236
+ g(w, "add", "wip.txt"); g(w, "commit", "-qm", "feat: wip");
237
+ const unlanded = await removeWorktree(project, ID, idRun);
238
+ expect(unlanded.ok).toBe(false);
239
+ expect(existsSync(w)).toBe(true);
240
+ // GitHub's rebase-merge, by hand: the work reaches main under new hashes.
241
+ commit(other, "theirs.txt", "x"); g(other, "push", "-q", "origin", "HEAD:main");
242
+ g(w, "fetch", "-q", "origin"); g(w, "rebase", "-q", "origin/main"); g(w, "push", "-q", "origin", "HEAD:main");
243
+ g(w, "push", "-q", "origin", `HEAD:refs/heads/kaizen/${ID}`);
244
+ expect(await removeWorktree(project, ID, idRun)).toEqual({ ok: true });
245
+ expect(existsSync(w)).toBe(false);
246
+ expect(g(project, "branch", "--list", `kaizen/${ID}`)).toBe("");
247
+ expect(g(project, "ls-remote", "--heads", "origin", `kaizen/${ID}`)).toBe("");
248
+ expect(state().worktree).toBeUndefined();
249
+ expect(state().branch).toBeUndefined();
250
+ });
251
+
252
+ test("G-04 removeWorktree keeps unmerged work when nothing can prove it landed (no origin)", async () => {
253
+ const w = (startWorktree(project, ID) as { path: string }).path;
254
+ commit(w, "run.txt", "mine");
255
+ g(project, "remote", "remove", "origin");
256
+ const r = await removeWorktree(project, ID, idRun);
257
+ expect(r.ok).toBe(false);
258
+ expect(existsSync(w)).toBe(true);
259
+ expect(g(project, "branch", "--list", `kaizen/${ID}`)).toContain(ID);
260
+ });
package/cli/worktree.ts CHANGED
@@ -74,8 +74,11 @@ export type Landed = { ok: true; how: "pr" | "push"; url?: string } | { ok: fals
74
74
 
75
75
  // Whether every commit of the branch is on the base, by patch: a rebase-merge rewrites
76
76
  // the hashes, so "is an ancestor" would say not landed for work that is.
77
- const landed = (dir: string, base: string, branch: string) =>
78
- git(dir, "cherry", `origin/${base}`, branch).out.split("\n").every((l) => !l.startsWith("+"));
77
+ // A cherry that fails (no origin, no origin/<base>) proves nothing: not landed.
78
+ const landed = (dir: string, base: string, branch: string, sh: Run = run) => {
79
+ const r = sh(["git", "cherry", `origin/${base}`, branch], dir);
80
+ return r.ok && r.out.split("\n").every((l) => !l.startsWith("+"));
81
+ };
79
82
 
80
83
  /**
81
84
  * Pushes the run's branch and lands it on the base: a pull request rebase-merged when
@@ -128,6 +131,118 @@ export function landWorktree(project: string, id: string, sh: Run = run,
128
131
  return { ok: false, why: `${base} kept moving; push rejected twice. Worktree kept` };
129
132
  }
130
133
 
134
+ // ---- the Git tab: a run's branch, its pull request and its cleanup, one step at a time
135
+
136
+ export type Pr = { number: number; url: string; state: "OPEN" | "MERGED" | "CLOSED"; draft: boolean };
137
+ export type Branch = { branch: string; base: string; upstream: boolean; landed: boolean; gh: boolean; pr: Pr | null; checking: boolean };
138
+ // The calls that wait on a network (push, fetch, gh): never on the board server's thread.
139
+ export type AsyncRun = (cmd: string[], cwd: string) => Promise<Out>;
140
+
141
+ // gh only knows GitHub. Asked once per project: the remote does not change under a board.
142
+ const githubs = new Map<string, boolean>();
143
+ const onGithub = (project: string) => {
144
+ let v = githubs.get(project);
145
+ if (v === undefined) githubs.set(project, (v = !!Bun.which("gh") && /github\.com/.test(git(project, "remote", "get-url", "origin").out)));
146
+ return v;
147
+ };
148
+ // One look at GitHub per run every 30 s, in the background; the panel shows the last answer.
149
+ const prs = new Map<string, { at: number; pr: Pr | null }>();
150
+ const looking = new Set<string>();
151
+ const prKey = (project: string, id: string) => `${project}\0${id}`;
152
+ const PR_JSON = ["--json", "number,url,state,isDraft"];
153
+ const parsePr = (r: Out): Pr | null => {
154
+ if (!r.ok) return null; // no pull request for the branch yet
155
+ try {
156
+ const j = JSON.parse(r.out);
157
+ return { number: j.number, url: j.url, state: j.state, draft: !!j.isDraft };
158
+ } catch { return null; }
159
+ };
160
+
161
+ /**
162
+ * What the Git tab shows for a run on its own branch: the branch against the base, and its
163
+ * pull request as last seen. A stale or missing answer starts one background `gh` look and
164
+ * calls `changed` when it lands, so the panel refreshes; the request never waits on GitHub.
165
+ */
166
+ export function branchState(project: string, id: string, changed: () => void = () => {}, sh: Run = run, ash: AsyncRun = runAsync, hasGh = onGithub(project)): Branch | null {
167
+ if (!SLUG.test(id)) return null;
168
+ const dir = codeDir(project, id);
169
+ if (dir === project) return null; // committed in the project's own checkout: no branch of its own
170
+ const branch = branchOf(id), base = baseOf(project);
171
+ const upstream = sh(["git", "rev-parse", "--abbrev-ref", `${branch}@{u}`], dir).ok;
172
+ const k = prKey(project, id), hit = prs.get(k);
173
+ if (hasGh && (!hit || Date.now() - hit.at >= 30_000) && !looking.has(k)) {
174
+ looking.add(k);
175
+ void ash(["gh", "pr", "view", branch, ...PR_JSON], dir).then((r) => {
176
+ looking.delete(k);
177
+ const pr = parsePr(r);
178
+ const was = prs.get(k);
179
+ prs.set(k, { at: Date.now(), pr });
180
+ if (JSON.stringify(was?.pr ?? null) !== JSON.stringify(pr) || !was) changed();
181
+ });
182
+ }
183
+ const pr = hit?.pr ?? null;
184
+ // Landed counts only work that is on the base: a branch with no commits of its own is not "merged".
185
+ const own = sh(["git", "rev-list", "--count", `origin/${base}..${branch}`], dir);
186
+ const landedNow = pr?.state === "MERGED" || (own.ok && Number(own.out) > 0 && landed(dir, base, branch, sh));
187
+ return { branch, base, upstream, landed: landedNow, gh: hasGh, pr, checking: hasGh && !hit };
188
+ }
189
+
190
+ /** Pushes the branch, then opens its pull request against the base. */
191
+ export async function openPr(project: string, id: string, title: string, body: string, draft: boolean, sh: Run = run, ash: AsyncRun = runAsync, hasGh = onGithub(project)): Promise<{ ok: true; pr: Pr } | { ok: false; why: string }> {
192
+ if (!SLUG.test(id)) return { ok: false, why: `"${id}" is not a run id` };
193
+ const dir = codeDir(project, id), branch = branchOf(id);
194
+ if (dir === project) return { ok: false, why: "This run has no branch of its own." };
195
+ if (!hasGh) return { ok: false, why: "Pull requests need the GitHub CLI (gh) and a GitHub remote." };
196
+ if (!title.trim()) return { ok: false, why: "A pull request needs a title." };
197
+ if (sh(["git", "status", "--porcelain"], dir).out) return { ok: false, why: "Commit the changes first." };
198
+ const push = await ash(["git", "push", "-u", "origin", branch], dir);
199
+ if (!push.ok) return { ok: false, why: `Push of ${branch} failed: ${push.why}` };
200
+ const r = await ash(["gh", "pr", "create", "--base", baseOf(project), "--head", branch, "--title", title.trim(), "--body", body, ...(draft ? ["--draft"] : [])], dir);
201
+ // An existing pull request for the branch is fine: show that one.
202
+ if (!r.ok && !/already exists/i.test(r.why)) return { ok: false, why: `Pull request failed: ${r.why}` };
203
+ const pr = parsePr(await ash(["gh", "pr", "view", branch, ...PR_JSON], dir));
204
+ prs.set(prKey(project, id), { at: Date.now(), pr });
205
+ return pr ? { ok: true, pr } : { ok: false, why: "The pull request was made, but gh cannot find it yet. Look again in a moment." };
206
+ }
207
+
208
+ /** Merges the run's pull request by rebase, as `kaizen land` does. The worktree stays. */
209
+ export async function mergePr(project: string, id: string, sh: Run = run, ash: AsyncRun = runAsync, hasGh = onGithub(project)): Promise<{ ok: true } | { ok: false; why: string }> {
210
+ if (!SLUG.test(id)) return { ok: false, why: `"${id}" is not a run id` };
211
+ const dir = codeDir(project, id), branch = branchOf(id);
212
+ if (dir === project) return { ok: false, why: "This run has no branch of its own." };
213
+ if (!hasGh) return { ok: false, why: "Merging needs the GitHub CLI (gh) and a GitHub remote." };
214
+ const r = await ash(["gh", "pr", "merge", branch, "--rebase"], dir);
215
+ prs.delete(prKey(project, id));
216
+ if (!r.ok) return { ok: false, why: `Not merged: ${r.why}` };
217
+ await ash(["git", "fetch", "origin"], project); // so "landed" sees the merge at once
218
+ return { ok: true };
219
+ }
220
+
221
+ /**
222
+ * Removes the run's worktree and branch once its work is on the base. Refused while the
223
+ * worktree has changes or any commit of the branch is not on the base, so nothing is lost.
224
+ */
225
+ export async function removeWorktree(project: string, id: string, sh: Run = run, ash: AsyncRun = runAsync): Promise<{ ok: true } | { ok: false; why: string }> {
226
+ if (!SLUG.test(id)) return { ok: false, why: `"${id}" is not a run id` };
227
+ const dir = codeDir(project, id), branch = branchOf(id);
228
+ if (dir === project) return { ok: false, why: "This run has no worktree." };
229
+ if (sh(["git", "status", "--porcelain"], dir).out) return { ok: false, why: "The worktree has uncommitted changes. Commit or discard them first." };
230
+ const f = await ash(["git", "fetch", "origin"], project);
231
+ if (!f.ok) return { ok: false, why: `Could not fetch origin, so nothing proves the work is on the base: ${f.why}` };
232
+ const base = baseOf(project);
233
+ if (!sh(["git", "rev-parse", "--verify", "--quiet", `origin/${base}`], project).ok) return { ok: false, why: `origin/${base} does not exist, so nothing proves the work is on it.` };
234
+ if (!landed(dir, base, branch, sh)) return { ok: false, why: `${branch} has commits that are not on ${base} yet. Merge its pull request first.` };
235
+ // Clean (checked above); --force is only for the untracked node_modules link.
236
+ const rm = sh(["git", "worktree", "remove", "--force", dir], project);
237
+ if (!rm.ok) return { ok: false, why: rm.why };
238
+ // Every commit is on the base by patch, so -D loses nothing a rebase-merge rewrote.
239
+ sh(["git", "branch", "-D", "--", branch], project);
240
+ await ash(["git", "push", "origin", "--delete", branch], project); // best effort: GitHub may have deleted it
241
+ prs.delete(prKey(project, id));
242
+ patchState(project, id, { worktree: null, branch: null });
243
+ return { ok: true };
244
+ }
245
+
131
246
  export type Workspace = { path: string; branch: string; main: boolean };
132
247
  const listed = new Map<string, { at: number; ws: Workspace[] }>();
133
248
  const inside = (p: string, root: string) => p === root || p.startsWith(root + sep);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kaizen-agent",
3
- "version": "1.60.0",
3
+ "version": "1.60.1",
4
4
  "description": "Staged workflow for AI agents — code, writing, research, operations: plan, human approval, build, independent review, bounded fix loop.",
5
5
  "type": "module",
6
6
  "bin": {