kaizen-agent 1.59.2 → 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/add-project.test.ts +169 -0
- package/cli/add-project.ts +132 -0
- package/cli/board.test.ts +15 -0
- package/cli/chat.ts +1 -1
- package/cli/dashboard.ts +6 -2
- package/cli/install.test.ts +1 -1
- package/cli/install.ts +18 -9
- package/cli/pty.test.ts +89 -5
- package/cli/pty.ts +126 -9
- package/cli/restart.test.ts +169 -0
- package/cli/settings.test.ts +35 -0
- package/cli/settings.ts +69 -18
- package/cli/state.test.ts +119 -3
- package/cli/state.ts +171 -13
- package/cli/usage.test.ts +130 -1
- package/cli/web-accept.test.ts +54 -0
- package/cli/web-pr.test.ts +51 -0
- package/cli/web-symlink.test.ts +28 -0
- package/cli/web.ts +349 -100
- package/cli/worktree.test.ts +146 -1
- package/cli/worktree.ts +214 -4
- package/cli/writeback.ts +1 -1
- package/package.json +1 -1
- package/skills/kaizen/SKILL.md +5 -1
- package/skills/kaizen/config.default.yml +15 -2
- package/skills/kaizen/settings.md +1 -0
- package/skills/kaizen/spec-main.md +28 -2
- package/skills/kaizen-help/SKILL.md +1 -0
- package/web/board/add-project.ts +136 -0
- package/web/board/api.ts +1 -1
- package/web/board/badge.ts +5 -5
- package/web/board/cards.ts +11 -3
- package/web/board/context.ts +1 -0
- package/web/board/fixes.ts +3 -2
- package/web/board/git.ts +309 -60
- package/web/board/home.ts +7 -1
- package/web/board/ideas.ts +20 -3
- package/web/board/live.ts +1 -1
- package/web/board/main.ts +26 -9
- package/web/board/panel.ts +31 -16
- package/web/board/projects.ts +6 -85
- package/web/board/run-pick.ts +41 -0
- package/web/board/run-view.ts +286 -110
- package/web/board/search-match.ts +20 -0
- package/web/board/search.test.ts +20 -0
- package/web/board/search.ts +324 -0
- package/web/board/settings.ts +42 -5
- package/web/board/store.ts +3 -1
- package/web/board/toast.ts +4 -1
- package/web/board/views.ts +3 -1
- package/web/board/workspace.ts +127 -38
- package/web/board/ws-board-ui.ts +95 -0
- package/web/board/ws-board.test.ts +71 -0
- package/web/board/ws-board.ts +45 -0
- package/web/board/ws-tabs.test.ts +181 -0
- package/web/board/ws-tabs.ts +173 -0
- package/web/board.html +86 -36
- package/web/board.js +129 -44
- package/web/notebook.js +41 -24
- package/web/notes.html +26 -20
- package/web/term.js +1 -1
- package/web/video.html +26 -20
- package/web/video.js +76 -59
package/cli/worktree.test.ts
CHANGED
|
@@ -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, 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.
|
|
@@ -113,3 +113,148 @@ test("projectFromWorktree finds the project from inside a run's folder", () => {
|
|
|
113
113
|
expect(projectFromWorktree("/p/.kaizen/wt/2026-10-17-x/cli")).toBe("/p");
|
|
114
114
|
expect(projectFromWorktree("/p/cli")).toBe("/p/cli");
|
|
115
115
|
});
|
|
116
|
+
|
|
117
|
+
test("workspaces: the main checkout, then each worktree; a folder that is not git is one workspace", () => {
|
|
118
|
+
expect(addWorktree(project, "-x", idRun).ok).toBe(false);
|
|
119
|
+
expect(addWorktree(project, "bad..name", idRun)).toMatchObject({ ok: false });
|
|
120
|
+
const r = addWorktree(project, "feat/two", idRun);
|
|
121
|
+
expect(r.ok).toBe(true);
|
|
122
|
+
expect(existsSync(join(project, ".kaizen/wt/feat-two"))).toBe(true);
|
|
123
|
+
expect(addWorktree(project, "feat/two", idRun).ok).toBe(false); // folder exists
|
|
124
|
+
const ws = workspaces(project, idRun);
|
|
125
|
+
expect(ws[0]).toEqual({ path: project, branch: "main", main: true });
|
|
126
|
+
expect(ws.slice(1)).toEqual([{ path: (r as any).path, branch: "feat/two", main: false }]);
|
|
127
|
+
const plain = mkdtempSync(join(tmpdir(), "nogit-"));
|
|
128
|
+
expect(workspaces(plain, idRun)).toEqual([{ path: plain, branch: "", main: true }]);
|
|
129
|
+
// A run's workspace: its worktree while on disk, else the main checkout.
|
|
130
|
+
expect(wsOf(project, { worktree: (r as any).path })).toBe((r as any).path);
|
|
131
|
+
expect(wsOf(project, { worktree: join(project, ".kaizen/wt/gone") })).toBe(project);
|
|
132
|
+
expect(wsOf(project, {})).toBe(project);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
test("adoptWorkspace: a run started inside another workspace is placed there, with no worktree of its own", () => {
|
|
136
|
+
const r = addWorktree(project, "feat/two", idRun) as { path: string };
|
|
137
|
+
expect(adoptWorkspace(project, ID, project)).toBeNull(); // the main checkout: a normal start
|
|
138
|
+
mkdirSync(join(r.path, "sub"));
|
|
139
|
+
expect(adoptWorkspace(project, ID, join(r.path, "sub"))).toEqual({ ok: true, path: r.path });
|
|
140
|
+
expect(state().workspace).toBe(r.path);
|
|
141
|
+
expect(state().worktree).toBeUndefined(); // land must never remove a folder the user made
|
|
142
|
+
expect(wsOf(project, state())).toBe(r.path);
|
|
143
|
+
expect(codeDir(project, ID)).toBe(project);
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
test("workspacesNow: answers at once, refreshes git in the background, one call at a time", async () => {
|
|
147
|
+
const p = mkdtempSync(join(tmpdir(), "wsnow-"));
|
|
148
|
+
let calls = 0, done!: (o: { ok: boolean; out: string; why: string }) => void;
|
|
149
|
+
const slow = () => { calls++; return new Promise<any>((r) => (done = r)); };
|
|
150
|
+
expect(workspacesNow(p, slow)).toEqual([{ path: p, branch: "", main: true }]); // git still running
|
|
151
|
+
expect(workspacesNow(p, slow)).toEqual([{ path: p, branch: "", main: true }]);
|
|
152
|
+
expect(calls).toBe(1);
|
|
153
|
+
done({ ok: true, out: `worktree ${p}\nHEAD abc\nbranch refs/heads/dev`, why: "" });
|
|
154
|
+
await Bun.sleep(0);
|
|
155
|
+
expect(workspacesNow(p, slow)).toEqual([{ path: p, branch: "dev", main: true }]);
|
|
156
|
+
expect(calls).toBe(1);
|
|
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
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
// One branch and one git worktree per run, so agents building at the same time never
|
|
2
2
|
// share a working folder. Run notes stay in the project's .kaizen/runs/<id>/; only the
|
|
3
3
|
// code lives in the worktree. Every git call is an argv array, never a shell string.
|
|
4
|
-
import { existsSync, readFileSync, writeFileSync, rmSync } from "node:fs";
|
|
5
|
-
import { join, dirname } from "node:path";
|
|
4
|
+
import { existsSync, readFileSync, writeFileSync, rmSync, realpathSync } from "node:fs";
|
|
5
|
+
import { join, dirname, resolve, sep } from "node:path";
|
|
6
|
+
import { branchesOf } from "./add-project.ts";
|
|
6
7
|
|
|
7
8
|
export type Out = { ok: boolean; out: string; why: string };
|
|
8
9
|
export type Run = (cmd: string[], cwd: string) => Out;
|
|
@@ -73,8 +74,11 @@ export type Landed = { ok: true; how: "pr" | "push"; url?: string } | { ok: fals
|
|
|
73
74
|
|
|
74
75
|
// Whether every commit of the branch is on the base, by patch: a rebase-merge rewrites
|
|
75
76
|
// the hashes, so "is an ancestor" would say not landed for work that is.
|
|
76
|
-
|
|
77
|
-
|
|
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
|
+
};
|
|
78
82
|
|
|
79
83
|
/**
|
|
80
84
|
* Pushes the run's branch and lands it on the base: a pull request rebase-merged when
|
|
@@ -126,3 +130,209 @@ export function landWorktree(project: string, id: string, sh: Run = run,
|
|
|
126
130
|
}
|
|
127
131
|
return { ok: false, why: `${base} kept moving; push rejected twice. Worktree kept` };
|
|
128
132
|
}
|
|
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
|
+
|
|
246
|
+
export type Workspace = { path: string; branch: string; main: boolean };
|
|
247
|
+
const listed = new Map<string, { at: number; ws: Workspace[] }>();
|
|
248
|
+
const inside = (p: string, root: string) => p === root || p.startsWith(root + sep);
|
|
249
|
+
// One spelling per folder: git prints real paths, a tmp or 8.3 path may not be one.
|
|
250
|
+
const real = (p: string) => { try { return realpathSync.native(p); } catch { return resolve(p); } };
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* A project's workspaces: its main checkout first, then every other git worktree, from
|
|
254
|
+
* `git worktree list --porcelain`. A folder that is not a repository is one workspace.
|
|
255
|
+
* Prunable entries, and detached ones outside the project, are left out. Cached 10 s:
|
|
256
|
+
* /state asks for every known project on each tick.
|
|
257
|
+
*/
|
|
258
|
+
export function workspaces(project: string, sh: Run = run): Workspace[] {
|
|
259
|
+
const hit = listed.get(project);
|
|
260
|
+
if (hit && Date.now() - hit.at < 10_000) return hit.ws;
|
|
261
|
+
const ws = parseWorkspaces(project, existsSync(project) ? sh(["git", "worktree", "list", "--porcelain"], project) : null);
|
|
262
|
+
listed.set(project, { at: Date.now(), ws });
|
|
263
|
+
return ws;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** git off the event loop, with the same 120 s ceiling as run(). */
|
|
267
|
+
export const runAsync = async (cmd: string[], cwd: string): Promise<Out> => {
|
|
268
|
+
try {
|
|
269
|
+
const p = Bun.spawn(cmd, { cwd, env, stdin: "ignore", stdout: "pipe", stderr: "pipe", timeout: 120_000, windowsHide: true });
|
|
270
|
+
const [out, err] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text()]);
|
|
271
|
+
return { ok: (await p.exited) === 0, out: out.trimEnd(), why: err.trim() || `${cmd[0]} did not finish` };
|
|
272
|
+
} catch { return { ok: false, out: "", why: `${cmd[0]} is not installed` }; }
|
|
273
|
+
};
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* workspaces() for /state: never waits on git. A fresh cache answers; a stale one answers
|
|
277
|
+
* and refreshes in the background; none yet answers the one folder until git replies.
|
|
278
|
+
*/
|
|
279
|
+
const refreshing = new Set<string>();
|
|
280
|
+
export function workspacesNow(project: string, sh = runAsync): Workspace[] {
|
|
281
|
+
const hit = listed.get(project);
|
|
282
|
+
if (hit && Date.now() - hit.at < 10_000) return hit.ws;
|
|
283
|
+
if (!refreshing.has(project) && existsSync(project)) {
|
|
284
|
+
refreshing.add(project);
|
|
285
|
+
void sh(["git", "worktree", "list", "--porcelain"], project)
|
|
286
|
+
.then((r) => listed.set(project, { at: Date.now(), ws: parseWorkspaces(project, r) }))
|
|
287
|
+
.finally(() => refreshing.delete(project));
|
|
288
|
+
}
|
|
289
|
+
return hit?.ws ?? [{ path: project, branch: "", main: true }];
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function parseWorkspaces(project: string, r: Out | null): Workspace[] {
|
|
293
|
+
const main = { path: project, branch: "", main: true };
|
|
294
|
+
if (!r?.ok) return [main];
|
|
295
|
+
const all = r.out.split(/\n\s*\n/).map((b) => {
|
|
296
|
+
const l = b.split("\n"), v = (k: string) => l.find((x) => x === k || x.startsWith(k + " "))?.slice(k.length + 1);
|
|
297
|
+
return { path: real(v("worktree") ?? ""), branch: (v("branch") ?? "").replace(/^refs\/heads\//, ""), prunable: v("prunable") !== undefined, bare: v("bare") !== undefined };
|
|
298
|
+
});
|
|
299
|
+
// The first entry is the main checkout; the registered folder stands for it (it may sit below the root).
|
|
300
|
+
main.branch = all[0]?.branch ?? "";
|
|
301
|
+
return [main, ...all.slice(1).filter((w) => !w.prunable && !w.bare && w.path !== real(project) && existsSync(w.path) && (w.branch || inside(w.path, real(project))))
|
|
302
|
+
.map((w) => ({ path: w.path, branch: w.branch, main: false }))];
|
|
303
|
+
}
|
|
304
|
+
export const forgetWorkspaces = (project: string) => listed.delete(project);
|
|
305
|
+
/** How old the cached list is, in ms; Infinity when none. */
|
|
306
|
+
export const workspacesAge = (project: string) => { const hit = listed.get(project); return hit ? Date.now() - hit.at : Infinity; };
|
|
307
|
+
|
|
308
|
+
/** The workspace a run belongs to: its recorded worktree (or the workspace it was started in) while that is still on disk, else the main checkout. */
|
|
309
|
+
export const wsOf = (project: string, state: { worktree?: unknown; workspace?: unknown }) => {
|
|
310
|
+
const w = [state.worktree, state.workspace].find((x) => typeof x === "string" && existsSync(x));
|
|
311
|
+
return typeof w === "string" ? real(w) : project;
|
|
312
|
+
};
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* `kaizen worktree start` run from inside one of the project's other workspaces: the run is
|
|
316
|
+
* placed there (`workspace` in state.json) and no second worktree is made. It is not recorded
|
|
317
|
+
* as the run's `worktree`: land would then remove a folder and branch the user made.
|
|
318
|
+
*/
|
|
319
|
+
export function adoptWorkspace(project: string, id: string, here: string): { ok: true; path: string } | null {
|
|
320
|
+
if (!SLUG.test(id) || !existsSync(file(project, id))) return null;
|
|
321
|
+
const at = real(here), w = workspaces(project).find((x) => !x.main && x.path !== real(worktreeOf(project, id)) && inside(at, x.path));
|
|
322
|
+
if (!w) return null;
|
|
323
|
+
patchState(project, id, { workspace: w.path });
|
|
324
|
+
return { ok: true, path: w.path };
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** A new worktree for `branch` under <project>/.kaizen/wt/, the branch made off `base` (one of branchesOf's) or HEAD. */
|
|
328
|
+
export function addWorktree(project: string, branch: string, sh: Run = run, base?: string): { ok: true; path: string } | { ok: false; why: string } {
|
|
329
|
+
if (!branch || branch.startsWith("-") || branch.length > 200) return { ok: false, why: "not a branch name" };
|
|
330
|
+
if (!sh(["git", "rev-parse", "--is-inside-work-tree"], project).ok) return { ok: false, why: "not a git repository" };
|
|
331
|
+
if (!sh(["git", "check-ref-format", "--branch", branch], project).ok) return { ok: false, why: `"${branch}" is not a valid branch name` };
|
|
332
|
+
if (base !== undefined && (base.startsWith("-") || !branchesOf(project, sh).branches.includes(base))) return { ok: false, why: `"${base}" is not a branch of this project` };
|
|
333
|
+
const path = join(project, ".kaizen", "wt", branch.replace(/[^\w.-]+/g, "-").replace(/^\.+/, ""));
|
|
334
|
+
if (existsSync(path)) return { ok: false, why: "that worktree folder already exists" };
|
|
335
|
+
const add = sh(["git", "worktree", "add", ...(base ? ["--no-track"] : []), "-b", branch, "--", path, ...(base ? [base] : [])], project);
|
|
336
|
+
forgetWorkspaces(project);
|
|
337
|
+
return add.ok ? { ok: true, path: real(path) } : { ok: false, why: add.why };
|
|
338
|
+
}
|
package/cli/writeback.ts
CHANGED
|
@@ -9,7 +9,7 @@ import * as google from "./google.ts";
|
|
|
9
9
|
type Gh = (args: string[]) => Promise<{ code: number; err: string }>;
|
|
10
10
|
const runGh: Gh = async (args) => {
|
|
11
11
|
try {
|
|
12
|
-
const p = Bun.spawn(["gh", ...args], { stdout: "ignore", stderr: "pipe" });
|
|
12
|
+
const p = Bun.spawn(["gh", ...args], { stdout: "ignore", stderr: "pipe", windowsHide: true });
|
|
13
13
|
const err = await new Response(p.stderr).text();
|
|
14
14
|
return { code: await p.exited, err };
|
|
15
15
|
} catch { return { code: 127, err: "The gh command was not found. Install GitHub's CLI and run `gh auth login`." }; }
|
package/package.json
CHANGED
package/skills/kaizen/SKILL.md
CHANGED
|
@@ -140,6 +140,10 @@ an explicit `/kaizen approve` or a clear approval in conversation.
|
|
|
140
140
|
- `approvals.plan` — after the plan, before any code is written. On by default.
|
|
141
141
|
- `approvals.review` — after the review passes, before the work is called done. Off by
|
|
142
142
|
default: with `auto_fix` on, it mostly asks for approval of a report being read anyway.
|
|
143
|
+
When on, a run that changed files is done only once `02-approval.md` holds an
|
|
144
|
+
`accepted:` line (format in `spec-main.md`); `auto` stops here too unless
|
|
145
|
+
`auto_accept` is `true`. The board flags a run marked done without it and refuses
|
|
146
|
+
its commit.
|
|
143
147
|
- `approvals.each_file` — confirm each file edit individually. Off by default; slow.
|
|
144
148
|
|
|
145
149
|
A rejected approval is not a failure, and it is not always the same action. Two shapes:
|
|
@@ -178,7 +182,7 @@ Every iteration is written to `runs/<id>/05-iterations/` so the loop is auditabl
|
|
|
178
182
|
|
|
179
183
|
Each run keeps its own backlog at `runs/<id>/06-backlog.md`. You write it, in the main
|
|
180
184
|
thread, at two writes that already happen: `02-approval.md` at the plan approval
|
|
181
|
-
and `
|
|
185
|
+
and `kaizen done <id>` at the final approval (refused until the user has approved), and only with what the user asked to
|
|
182
186
|
backlog. Open findings, unverified checks and suggestions are offered, never filed by
|
|
183
187
|
themselves. No subagent writes it.
|
|
184
188
|
The full rules are in [`spec-main.md`](spec-main.md).
|
|
@@ -11,6 +11,10 @@ preset: medium
|
|
|
11
11
|
# plan-only | approve | auto | review-only
|
|
12
12
|
mode: approve
|
|
13
13
|
|
|
14
|
+
# With approvals.review on, a run that changed files waits for your approval at the
|
|
15
|
+
# end even in auto mode. true lets auto runs finish without it, marked auto-accepted.
|
|
16
|
+
auto_accept: false
|
|
17
|
+
|
|
14
18
|
approvals:
|
|
15
19
|
# Stop after the plan, before any code is written.
|
|
16
20
|
plan: true
|
|
@@ -135,11 +139,20 @@ agent:
|
|
|
135
139
|
# Where the web board runs the agent it launches.
|
|
136
140
|
# card - inside the board: the card's Terminal tab shows the agent live and
|
|
137
141
|
# takes your typing. The agent lives in the board's process, so
|
|
138
|
-
# stopping or
|
|
139
|
-
#
|
|
142
|
+
# stopping, upgrading or a crash of the board ends it; the next
|
|
143
|
+
# board starts it again in its card, in the same conversation, with
|
|
144
|
+
# its last screen and a line saying the step it was on was cut off.
|
|
145
|
+
# On Windows it runs in a ConPTY console that Windows PowerShell hosts.
|
|
140
146
|
# terminal - a new terminal window (or tmux/herdr tab) per launch.
|
|
141
147
|
# The terminal dashboard always opens terminal windows.
|
|
142
148
|
launch: card
|
|
149
|
+
# Card agents only: what happens to them when the board stops.
|
|
150
|
+
# off - they end and the next board starts them again (above).
|
|
151
|
+
# tmux - they run inside a hidden tmux session on kaizen's own tmux server
|
|
152
|
+
# (tmux -L kaizen, your own sessions untouched) and keep working through
|
|
153
|
+
# a board restart or crash; the next board shows them again mid-step.
|
|
154
|
+
# Linux and macOS with tmux installed; elsewhere it acts as off.
|
|
155
|
+
keep_alive: off
|
|
143
156
|
# Per-tool model and effort for the session the board launches, passed as that
|
|
144
157
|
# tool's own flags (claude --model/--effort, agy --model/--effort, codex -m and
|
|
145
158
|
# model_reasoning_effort, gemini -m, opencode -m). Model names are the tool's own:
|
|
@@ -18,6 +18,7 @@ nearest first, so a change lands globally unless this project keeps its own conf
|
|
|
18
18
|
| `review.executor` | `inline`, `subagent`, `ask` | Who reviews a lite run: this session, a cold reviewer agent, or ask before the review |
|
|
19
19
|
| `approvals.plan` | `true`, `false` | Stop and show the plan before anything is built |
|
|
20
20
|
| `approvals.review` | `true`, `false` | Stop after the review, before the run is called done |
|
|
21
|
+
| `auto_accept` | `false`, `true` | In `auto` mode, finish a run that changed files without the final approval (marked auto-accepted) |
|
|
21
22
|
| `approvals.each_file` | `true`, `false` | Confirm every individual edit |
|
|
22
23
|
| `auto_fix.enabled` | `true`, `false` | Fix findings without asking, or hand every one over |
|
|
23
24
|
| `auto_fix.min_severity` | `critical`, `high`, `medium`, `low` | How bad a finding must be to be fixed automatically |
|
|
@@ -133,7 +133,33 @@ whose changes leave every note true touches nothing and says so in one line.
|
|
|
133
133
|
|
|
134
134
|
## Final approval
|
|
135
135
|
|
|
136
|
-
Controlled by `approvals.review
|
|
136
|
+
Controlled by `approvals.review`. `auto` skips every stop before it, not this one, unless `auto_accept` is on.
|
|
137
|
+
|
|
138
|
+
**The gate is a stop, in every runner.** With `approvals.review` on, a run whose
|
|
139
|
+
`03-impl.md` names changed files is not done until `02-approval.md` holds an
|
|
140
|
+
acceptance line, exactly one of:
|
|
141
|
+
|
|
142
|
+
```
|
|
143
|
+
accepted: <ISO 8601 time> by user via board
|
|
144
|
+
accepted: <ISO 8601 time> by user via chat
|
|
145
|
+
accepted: <ISO 8601 time> auto (auto_accept)
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
The review ends by writing `stage: "review"`, `awaiting: "approvals.review"` and
|
|
149
|
+
stopping; never write `stage: "done"` in the same step as the review, and never from
|
|
150
|
+
`plan` or `build`. The board's Approve writes the `via board` line itself. On
|
|
151
|
+
`/kaizen approve` or a clear approval of this run in conversation ("approve", "looks
|
|
152
|
+
good, ship it"), finish with `kaizen done <id> --user-approved`, which appends the `via chat`
|
|
153
|
+
line and sets `done`. Without the user's yes run plain `kaizen done <id>`: it refuses and
|
|
154
|
+
tells you to ask. kaizen reads and rewrites a gate-on run marked `done` without the
|
|
155
|
+
`accepted:` line back to `review` / `approvals.review`, so setting `done` early only gets
|
|
156
|
+
it undone. The flag stops forgetting and shortcuts, not forgery. A request that only
|
|
157
|
+
names a later step, such as "commit and push", is not one: ask once whether it
|
|
158
|
+
approves the run. In `auto` mode the run stops there too ("finished, waiting for your
|
|
159
|
+
approval"), unless `auto_accept` is `true`: then append the `auto (auto_accept)` line
|
|
160
|
+
and set `done`. A run that changed no files, or runs with `approvals.review` off, may
|
|
161
|
+
go `done` without the line. A run marked `done` without it shows on the board as
|
|
162
|
+
"done, not approved", and its commit is refused until it is approved.
|
|
137
163
|
|
|
138
164
|
Report: what was built (for a code run, show its Preview proof), verification results, findings fixed, findings still open,
|
|
139
165
|
every criterion the reviewer answered `CANNOT VERIFY` with the check it says a human
|
|
@@ -167,7 +193,7 @@ in *Backlog* above. Check existing entries and do not append a duplicate. Builde
|
|
|
167
193
|
notes outside the approved scope are reported, but are not filed without an explicit
|
|
168
194
|
request.
|
|
169
195
|
|
|
170
|
-
|
|
196
|
+
Finish with `kaizen done <id>` once the user accepts (`--user-approved` for a yes given in chat); do not hand-write `stage: "done"`.
|
|
171
197
|
|
|
172
198
|
**Commit at done, when `git.auto_commit` is `true`.** Setting `stage: "done"` — the
|
|
173
199
|
user approving at review, or an `auto` run finishing — is then the ask to commit, under
|
|
@@ -28,6 +28,7 @@ anything.
|
|
|
28
28
|
| `/kaizen run` | Resume the current run and execute the approved plan |
|
|
29
29
|
| `/kaizen review [target]` | Review-only: audit existing code, no plan, no implementation |
|
|
30
30
|
| `/kaizen status` | List every run grouped waiting-on-you / in flight / done / abandoned, plus open backlog count |
|
|
31
|
+
| `kaizen done <id> [--user-approved]` | Finish a run; refused while the review gate waits on the user, `--user-approved` after a clear yes in chat |
|
|
31
32
|
| `/kaizen backlog` | Print open backlog items across all runs, grouped by source run, rescued items last under `Orphaned` |
|
|
32
33
|
| `/kaizen gather` | Read request sources kaizen cannot read by itself; their requests land in the icebox, nothing starts |
|
|
33
34
|
| `/kaizen discover` | Group what is in the icebox and promote the ideas you pick; nothing starts |
|