kaizen-agent 1.59.2 → 1.60.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/cli/add-project.test.ts +169 -0
  2. package/cli/add-project.ts +132 -0
  3. package/cli/board.test.ts +15 -0
  4. package/cli/chat.ts +1 -1
  5. package/cli/dashboard.ts +6 -2
  6. package/cli/install.test.ts +1 -1
  7. package/cli/install.ts +18 -9
  8. package/cli/pty.test.ts +82 -3
  9. package/cli/pty.ts +122 -6
  10. package/cli/restart.test.ts +169 -0
  11. package/cli/settings.test.ts +35 -0
  12. package/cli/settings.ts +69 -18
  13. package/cli/state.test.ts +119 -3
  14. package/cli/state.ts +171 -13
  15. package/cli/usage.test.ts +130 -1
  16. package/cli/web-accept.test.ts +54 -0
  17. package/cli/web-symlink.test.ts +28 -0
  18. package/cli/web.ts +320 -100
  19. package/cli/worktree.test.ts +43 -1
  20. package/cli/worktree.ts +97 -2
  21. package/cli/writeback.ts +1 -1
  22. package/package.json +1 -1
  23. package/skills/kaizen/SKILL.md +5 -1
  24. package/skills/kaizen/config.default.yml +15 -2
  25. package/skills/kaizen/settings.md +1 -0
  26. package/skills/kaizen/spec-main.md +28 -2
  27. package/skills/kaizen-help/SKILL.md +1 -0
  28. package/web/board/add-project.ts +136 -0
  29. package/web/board/api.ts +1 -1
  30. package/web/board/badge.ts +5 -5
  31. package/web/board/cards.ts +11 -3
  32. package/web/board/context.ts +1 -0
  33. package/web/board/fixes.ts +3 -2
  34. package/web/board/git.ts +2 -0
  35. package/web/board/home.ts +7 -1
  36. package/web/board/ideas.ts +20 -3
  37. package/web/board/live.ts +1 -1
  38. package/web/board/main.ts +26 -9
  39. package/web/board/panel.ts +18 -3
  40. package/web/board/projects.ts +6 -85
  41. package/web/board/run-pick.ts +41 -0
  42. package/web/board/run-view.ts +261 -106
  43. package/web/board/settings.ts +42 -5
  44. package/web/board/store.ts +3 -1
  45. package/web/board/toast.ts +4 -1
  46. package/web/board/views.ts +3 -1
  47. package/web/board/workspace.ts +125 -38
  48. package/web/board/ws-board-ui.ts +84 -0
  49. package/web/board/ws-board.test.ts +71 -0
  50. package/web/board/ws-board.ts +45 -0
  51. package/web/board/ws-tabs.test.ts +171 -0
  52. package/web/board/ws-tabs.ts +170 -0
  53. package/web/board.html +80 -36
  54. package/web/board.js +44 -43
  55. package/web/notebook.js +24 -25
  56. package/web/notes.html +25 -20
  57. package/web/term.js +1 -1
  58. package/web/video.html +25 -20
  59. package/web/video.js +56 -57
@@ -0,0 +1,169 @@
1
+ // The checks behind the board's "Add a project" sheet: every URL, path, branch and base
2
+ // a web page can send is tested here, and each refusal has a case.
3
+ import { test, expect } from "bun:test";
4
+ import { mkdtempSync, mkdirSync, writeFileSync, existsSync, realpathSync, readFileSync, symlinkSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ import { tmpdir } from "node:os";
7
+ import { gitUrl, destDir, cloneInto, branchesOf, winBad, dirSize, ignoreKaizen } from "./add-project.ts";
8
+ import { run, addWorktree, type Run } from "./worktree.ts";
9
+
10
+ const tmp = () => realpathSync(mkdtempSync(join(tmpdir(), "addp-")));
11
+
12
+ test("gitUrl accepts https, ssh and user@host:path, and names the repository", () => {
13
+ expect(gitUrl("https://github.com/o/repo.git")).toEqual({ url: "https://github.com/o/repo.git", name: "repo" });
14
+ expect(gitUrl(" https://gitlab.example.com:8443/g/sub/repo/ ")).toMatchObject({ name: "repo" });
15
+ expect(gitUrl("ssh://git@host.example/o/repo")).toMatchObject({ name: "repo" });
16
+ expect(gitUrl("git@github.com:o/repo.git")).toEqual({ url: "git@github.com:o/repo.git", name: "repo" });
17
+ });
18
+
19
+ test("gitUrl refuses options, helper transports, plain http, local paths, credentials and odd characters", () => {
20
+ for (const bad of [
21
+ "", " ", 5, null,
22
+ "--upload-pack=touch /tmp/x", "-oProxyCommand=id", "--help",
23
+ "ext::sh -c id", "ext::sh -c id%s", "fd::3", "file:///etc", "/etc/passwd", "./repo", "C:\\repo", "~/repo",
24
+ "http://github.com/o/r.git", "git://github.com/o/r.git", "ftp://h/o/r",
25
+ "https://github.com/o/r .git", "https://github.com/o/r\n--x", "https://github.com/o/r\0",
26
+ "https://user:pw@github.com/o/r.git",
27
+ "https://-evil.example/o/r.git", "ssh://-oProxyCommand=id/o/r", "ssh://git@-oProxyCommand=id/o/r",
28
+ "-oProxyCommand=id@host:o/r", "git@-bad:o/r", "git@host:/abs/path",
29
+ "https://github.com/o/../r.git", "https://github.com/", "https://github.com/o/.git", "https://github.com/o/..",
30
+ "https://github.com/o/r$(id)", "https://github.com/o/r;id", "https://github.com/o/r|id",
31
+ "https://" + "a".repeat(600) + "/r",
32
+ ]) expect(gitUrl(bad), String(bad)).toHaveProperty("error");
33
+ });
34
+
35
+ test("winBad: Windows device names and trailing dots, on every platform", () => {
36
+ for (const n of ["", ".", "..", "con", "NUL.txt", "COM1", "a.", "a ", "a:b", "a|b"]) expect(winBad(n), n).toBe(true);
37
+ for (const n of ["config", "my-project", "a.b", "com10"]) expect(winBad(n), n).toBe(false);
38
+ });
39
+
40
+ test("destDir: resolves ~ and relative paths; refuses root, home, kaizen/git folders, .., bad names and places below a project", () => {
41
+ const home = tmp();
42
+ expect(destDir("~/Projects/x", home)).toEqual({ dir: join(home, "Projects", "x") });
43
+ expect(destDir("x", home)).toEqual({ dir: join(home, "x") });
44
+ expect(destDir(join(home, "y"), home)).toEqual({ dir: join(home, "y") });
45
+ for (const bad of [
46
+ "", " ", 3, undefined, "/", "~", home, home + "/", "~/.kaizen/x", join(home, ".kaizen"),
47
+ "/tmp/a/../../etc", "../x", "~/a/../b", "~/x/.git/y", "~/x/.kaizen", "~/con", "~/a.", "x\0y", "~/" + "a/".repeat(600),
48
+ ]) expect(destDir(bad, home), String(bad)).toHaveProperty("error");
49
+ // Below a known project, or below a folder that has a .kaizen: a second .kaizen would shadow the first.
50
+ mkdirSync(join(home, "p", ".kaizen"), { recursive: true });
51
+ expect(destDir(join(home, "p", "sub"), home)).toMatchObject({ error: expect.stringContaining("inside the project") });
52
+ expect(destDir(join(home, "q", "sub"), home, [join(home, "q")])).toMatchObject({ error: expect.stringContaining("inside the project") });
53
+ expect(destDir(join(home, "p"), home, [join(home, "p")])).toEqual({ dir: join(home, "p") }); // the project itself is fine
54
+ expect(destDir(join(home, "other"), home, [join(home, "p")])).toEqual({ dir: join(home, "other") });
55
+ });
56
+
57
+ test("branchesOf lists local and origin branches, the current one, and the remote default first", () => {
58
+ const root = tmp(), remote = join(root, "r.git"), proj = join(root, "p");
59
+ const g = (cwd: string, ...a: string[]) => { const r = run(["git", "-c", "user.email=a@b.c", "-c", "user.name=t", ...a], cwd); if (!r.ok) throw new Error(r.why); return r.out; };
60
+ g(root, "init", "-q", "--bare", "-b", "main", remote);
61
+ g(root, "clone", "-q", remote, proj);
62
+ writeFileSync(join(proj, "a"), "a"); g(proj, "add", "a"); g(proj, "commit", "-qm", "a"); g(proj, "push", "-q", "origin", "HEAD:main");
63
+ g(proj, "remote", "set-head", "origin", "main");
64
+ g(proj, "checkout", "-q", "-b", "dev");
65
+ const b = branchesOf(proj);
66
+ expect(b.current).toBe("dev");
67
+ expect(b.def).toBe("origin/main");
68
+ expect(b.branches.sort()).toEqual(["dev", "main", "origin/main"]);
69
+ expect(branchesOf(root)).toEqual({ current: "", def: "", branches: [] }); // not a repository
70
+ const none: Run = () => ({ ok: false, out: "", why: "git is not installed" });
71
+ expect(branchesOf(proj, none).branches).toEqual([]);
72
+ // addWorktree with a base: the branch starts at the base's tip; unknown or option-like bases are refused.
73
+ const old = g(proj, "rev-parse", "origin/main");
74
+ writeFileSync(join(proj, "b"), "b"); g(proj, "add", "b"); g(proj, "commit", "-qm", "b");
75
+ expect(addWorktree(proj, "f1", run, "--detach")).toMatchObject({ ok: false });
76
+ expect(addWorktree(proj, "f1", run, "-x")).toMatchObject({ ok: false });
77
+ expect(addWorktree(proj, "f1", run, "nope")).toMatchObject({ ok: false });
78
+ expect(addWorktree(proj, "f1", run, "HEAD~1")).toMatchObject({ ok: false });
79
+ expect(existsSync(join(proj, ".kaizen/wt/f1"))).toBe(false);
80
+ const w = addWorktree(proj, "f1", run, "origin/main") as { path: string };
81
+ expect(w.ok).toBe(true);
82
+ expect(g(w.path, "rev-parse", "HEAD")).toBe(old);
83
+ expect(run(["git", "config", "--get", "branch.f1.remote"], w.path).out).toBe(""); // --no-track
84
+ });
85
+
86
+ test("cloneInto: argv is `git clone -- url to` with the protocol allow-list and no prompts; a failure removes what it made", async () => {
87
+ const seen: { cmd: string[]; env: any }[] = [];
88
+ const fake = (code: number) => (cmd: string[], o: any) => { seen.push({ cmd, env: o.env }); return { stderr: "fatal: nope\nfatal: gone", exited: Promise.resolve(code), kill() {} }; };
89
+ const dir = tmp(), to = join(dir, "r");
90
+ expect(await cloneInto("https://h.example/o/r.git", to, fake(0))).toEqual({ ok: true });
91
+ expect(seen[0]!.cmd).toEqual(["git", "clone", "--", "https://h.example/o/r.git", to]);
92
+ expect(seen[0]!.env.GIT_ALLOW_PROTOCOL).toBe("https:ssh");
93
+ expect(seen[0]!.env.GIT_TERMINAL_PROMPT).toBe("0");
94
+ // Failure: the last stderr line is the reason; a folder the call made goes, one that was there stays.
95
+ mkdirSync(to);
96
+ expect(await cloneInto("https://h.example/o/r.git", to, fake(128))).toEqual({ ok: false, why: "fatal: gone" });
97
+ expect(existsSync(to)).toBe(true);
98
+ const mine = join(dir, "mine");
99
+ const mk = (cmd: string[], o: any) => { mkdirSync(mine); return fake(1)(cmd, o); };
100
+ expect((await cloneInto("https://h.example/o/r.git", mine, mk)).ok).toBe(false);
101
+ expect(existsSync(mine)).toBe(false);
102
+ });
103
+
104
+ test("cloneInto against a real local repository (protocol list opened for the test only)", async () => {
105
+ const root = tmp(), src = join(root, "src"), to = join(root, "out");
106
+ const g = (cwd: string, ...a: string[]) => { const r = run(["git", "-c", "user.email=a@b.c", "-c", "user.name=t", ...a], cwd); if (!r.ok) throw new Error(r.why); };
107
+ mkdirSync(src); g(src, "init", "-q", "-b", "main"); writeFileSync(join(src, "f"), "x"); g(src, "add", "f"); g(src, "commit", "-qm", "f");
108
+ // The default protocols refuse a file path, the point of GIT_ALLOW_PROTOCOL.
109
+ expect((await cloneInto(src, to)).ok).toBe(false);
110
+ expect(existsSync(to)).toBe(false);
111
+ expect(await cloneInto(src, to, undefined, "file")).toEqual({ ok: true });
112
+ expect(readFileSync(join(to, "f"), "utf8")).toBe("x");
113
+ });
114
+
115
+ test("gitUrl refuses an ssh user that starts with a dash", () => {
116
+ expect(gitUrl("ssh://-oFoo@host.example/x/r.git")).toHaveProperty("error");
117
+ expect(gitUrl("-oFoo@host.example:x/r.git")).toHaveProperty("error");
118
+ expect(gitUrl("ssh://git@host.example/x/r.git")).toHaveProperty("url");
119
+ });
120
+
121
+ test("destDir: symlinks, case, the ~/.kaizen prefix and places outside home", () => {
122
+ const home = tmp(), out = tmp();
123
+ mkdirSync(join(home, "p", ".kaizen"), { recursive: true });
124
+ mkdirSync(join(home, "empty"));
125
+ symlinkSync(join(home, "empty"), join(home, "ln"));
126
+ expect(destDir(join(home, "ln"), home)).toMatchObject({ error: expect.stringContaining("symbolic link") });
127
+ // An existing folder is canonicalised, so a dir reached through a link into a project is still below it.
128
+ symlinkSync(join(home, "p"), join(home, "via"));
129
+ expect(destDir(join(home, "via", "sub"), home, [join(home, "p")])).toMatchObject({ error: expect.stringContaining("inside the project") });
130
+ for (const bad of ["~/X/.GIT/y", "~/x/.Kaizen", "~/.KAIZEN/x", "~/.kaizen/x"]) expect(destDir(bad, home), bad).toHaveProperty("error");
131
+ expect(destDir("~/.kaizenfoo", home)).toEqual({ dir: join(home, ".kaizenfoo") });
132
+ // Outside home: refused, unless under the Projects folder setting.
133
+ expect(destDir(join(out, "x"), home)).toMatchObject({ error: expect.stringContaining("inside your home") });
134
+ expect(destDir(join(out, "x"), home, [], out)).toEqual({ dir: join(out, "x") });
135
+ });
136
+
137
+ test("cloneInto: a clone that runs past the timeout or the size cap is killed (group) and what it made is removed", async () => {
138
+ const dir = tmp();
139
+ const hang = (made: string) => (cmd: string[], o: any) => {
140
+ let done!: (n: number) => void;
141
+ const exited = new Promise<number>((r) => (done = r));
142
+ mkdirSync(made);
143
+ return { stderr: "", exited, kill() { done(137); } };
144
+ };
145
+ const t = join(dir, "t");
146
+ expect(await cloneInto("https://h.example/o/r.git", t, hang(t), "https:ssh", 30, 1e9, 1e6)).toEqual({ ok: false, why: "git clone timed out" });
147
+ expect(existsSync(t)).toBe(false);
148
+ const c = join(dir, "c");
149
+ const r = await cloneInto("https://h.example/o/r.git", c, hang(c), "https:ssh", 60_000, 100, 10, () => 101);
150
+ expect(r).toMatchObject({ ok: false, why: expect.stringContaining("larger than") });
151
+ expect(existsSync(c)).toBe(false);
152
+ });
153
+
154
+ test("dirSize counts only .git/objects/pack", () => {
155
+ const d = tmp(), p = join(d, ".git", "objects", "pack");
156
+ mkdirSync(p, { recursive: true });
157
+ writeFileSync(join(p, "tmp_pack_x"), "x".repeat(100));
158
+ writeFileSync(join(d, "big.bin"), "y".repeat(5000));
159
+ expect(dirSize(d)).toBe(100);
160
+ expect(dirSize(join(d, "none"))).toBe(0);
161
+ });
162
+
163
+ test("ignoreKaizen writes the .kaizen rules once", () => {
164
+ const d = tmp();
165
+ expect(ignoreKaizen(d)).toBe(true);
166
+ expect(readFileSync(join(d, ".gitignore"), "utf8")).toContain(".kaizen/*");
167
+ expect(ignoreKaizen(d)).toBe(false);
168
+ expect(readFileSync(join(d, ".gitignore"), "utf8").match(/\.kaizen\/\*\n/g)!.length).toBe(1);
169
+ });
@@ -0,0 +1,132 @@
1
+ // What the board's "Add a project" sheet lets a web page ask for: clone a repository,
2
+ // create a folder, branch off a base. Everything here is a pure check or an argv call,
3
+ // so each refusal can be tested without a board. No shell string anywhere.
4
+ import { appendFileSync, existsSync, lstatSync, readdirSync, readFileSync, rmSync } from "node:fs";
5
+ import { basename, dirname, join, parse, resolve, sep } from "node:path";
6
+ import { canonPath, nativePath } from "./state.ts";
7
+ import { run, type Run } from "./worktree.ts";
8
+
9
+ // Windows' rules on every platform, so a project made here also opens there: no
10
+ // reserved device names (CON, NUL, COM1…), no trailing dot or space.
11
+ export const winBad = (n: string) => !n || n === "." || n === ".." || /[\\/:*?"<>|\x00-\x1f]/.test(n) || /[. ]$/.test(n)
12
+ || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i.test(n);
13
+
14
+ const HOST = /^[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?$/;
15
+ const REPO_PATH = /^[\w.\-~+%@/]+$/;
16
+
17
+ /**
18
+ * A git URL the board will clone: https:// or ssh:// or user@host:path, one token, no
19
+ * option-like start, no credentials in an https URL. Refuses ext::, file:, git://, http://
20
+ * and local paths. `name` is the repository's folder name.
21
+ */
22
+ export function gitUrl(raw: unknown): { url: string; name: string } | { error: string } {
23
+ const s = typeof raw === "string" ? raw.trim() : "";
24
+ const no = (why = "use an https:// or ssh git URL, e.g. https://github.com/owner/repo.git") => ({ error: why });
25
+ if (!s) return no("paste a git URL");
26
+ if (s.length > 500 || s.startsWith("-") || /[\s\x00-\x1f\x7f]/.test(s)) return no();
27
+ let host = "", path = "";
28
+ const u = s.match(/^(https|ssh):\/\/(?:([\w][\w.-]*)@)?([^/:@]+)(?::\d{1,5})?\/(.+)$/i);
29
+ const scp = s.match(/^\w[\w.-]*@([^/:@]+):(?!\/)(.+)$/);
30
+ if (u) {
31
+ if (u[1]!.toLowerCase() === "https" && u[2]) return no("leave credentials out of the URL");
32
+ [host, path] = [u[3]!, u[4]!];
33
+ } else if (scp) [host, path] = [scp[1]!, scp[2]!];
34
+ else return no();
35
+ if (!HOST.test(host) || !REPO_PATH.test(path) || path.split("/").includes("..")) return no();
36
+ const name = path.replace(/\/+$/, "").split("/").pop()!.replace(/\.git$/i, "");
37
+ return winBad(name) ? no("that URL does not name a repository") : { url: s, name };
38
+ }
39
+
40
+ /**
41
+ * A folder the board may create or register, from what the page typed (~ allowed,
42
+ * relative to home). Refuses the root, home itself, anything inside ~/.kaizen or a .git
43
+ * or .kaizen folder, a `..` in the text, a name Windows cannot hold, and a place below an
44
+ * existing project: a second .kaizen there would shadow the first one's runs. An existing
45
+ * symlink at the folder is refused and an existing folder is canonicalised first, so a link
46
+ * cannot smuggle a write into a project. Outside home only under `projects` (the Projects
47
+ * folder setting): the board never writes to /usr/local or another user's directory.
48
+ */
49
+ export function destDir(raw: unknown, home: string, known: string[] = [], projects = ""): { dir: string } | { error: string } {
50
+ const t = typeof raw === "string" ? raw.trim() : "";
51
+ if (!t || t.length > 1000 || t.includes("\0")) return { error: "name a folder" };
52
+ if (t.split(/[\\/]/).includes("..")) return { error: "a folder path cannot contain .." };
53
+ const p = resolve(home, nativePath(t.startsWith("~") ? home + t.slice(1) : t));
54
+ try { if (lstatSync(p).isSymbolicLink()) return { error: "that folder is a symbolic link; name the real folder" }; } catch { /* absent */ }
55
+ const dir = existsSync(p) ? canonPath(p) : join(canonPath(dirname(p)), basename(p)), h = canonPath(home);
56
+ if (parse(dir).root === dir || dir === h) return { error: "choose a folder of its own, not the root or your home" };
57
+ const parts = dir.toLowerCase().split(/[\\/]/), kz = join(h, ".kaizen").toLowerCase(), low = dir.toLowerCase();
58
+ if (low === kz || low.startsWith(kz + sep) || parts.includes(".git") || parts.includes(".kaizen")) return { error: "that folder is kaizen's or git's own" };
59
+ if (winBad(basename(dir))) return { error: `${basename(dir)} cannot be a folder name on Windows` };
60
+ const under = (r: string) => !!r && (dir === canonPath(r) || dir.startsWith(canonPath(r) + sep));
61
+ if (!under(h) && !under(projects)) return { error: "choose a folder inside your home, or set Settings → Projects folder (board.projects_dir) to allow another place" };
62
+ for (let a = dirname(dir); ; a = dirname(a)) {
63
+ if (known.includes(a) || (a !== h && existsSync(join(a, ".kaizen")))) return { error: `that folder is inside the project ${a}` };
64
+ if (dirname(a) === a) break;
65
+ }
66
+ return { dir };
67
+ }
68
+
69
+ export type Spawned = { stderr: unknown; exited: Promise<number>; kill: () => void; pid?: number };
70
+ type Spawn = (cmd: string[], o: Record<string, unknown>) => Spawned;
71
+ const spawn: Spawn = (cmd, o) => Bun.spawn(cmd, o as any) as unknown as Spawned;
72
+
73
+ /** Bytes in <d>/.git/objects/pack (incl. git's incoming tmp_pack files): a few stats, no tree walk. */
74
+ export function dirSize(d: string): number {
75
+ const p = join(d, ".git", "objects", "pack");
76
+ let n = 0;
77
+ try { for (const e of readdirSync(p)) try { n += lstatSync(join(p, e)).size; } catch { /* gone */ } } catch { /* not there yet */ }
78
+ return n;
79
+ }
80
+
81
+ /**
82
+ * `git clone -- url to`, argv only. GIT_ALLOW_PROTOCOL keeps a redirect or submodule from
83
+ * reaching ext:: or file:; never prompts; gives up after `ms` or once the folder passes
84
+ * `cap` bytes (checked every `tick` ms). git runs in its own process group so the kill
85
+ * reaches its ssh or remote-helper child too. A folder this call made is removed when the
86
+ * clone fails. `url` and `to` are already checked by gitUrl and destDir.
87
+ * The rest of the arguments are for tests.
88
+ */
89
+ export async function cloneInto(url: string, to: string, sp: Spawn = spawn, protocols = "https:ssh", ms = 300_000, cap = 2 * 1024 ** 3, tick = 2000, size = dirSize): Promise<{ ok: true } | { ok: false; why: string }> {
90
+ const existed = existsSync(to);
91
+ const p = sp(["git", "clone", "--", url, to], {
92
+ stdin: "ignore", stdout: "ignore", stderr: "pipe", windowsHide: true, detached: process.platform !== "win32",
93
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_ALLOW_PROTOCOL: protocols, GIT_SSH_COMMAND: process.env.GIT_SSH_COMMAND ?? "ssh -o BatchMode=yes" },
94
+ });
95
+ let stopped = "";
96
+ const stop = (why: string) => {
97
+ stopped ||= why;
98
+ try { if (p.pid && process.platform !== "win32") process.kill(-p.pid, "SIGKILL"); else p.kill(); } catch { p.kill(); }
99
+ };
100
+ const timer = setTimeout(() => stop("git clone timed out"), ms);
101
+ const watch = setInterval(() => { if (size(to) > cap) stop(`the repository is larger than ${Math.round(cap / 1024 ** 2)} MB`); }, tick);
102
+ let code = 1, err = "";
103
+ try { [err, code] = await Promise.all([new Response(p.stderr as any).text(), p.exited]); }
104
+ catch (e) { err = (e as Error).message; }
105
+ clearTimeout(timer); clearInterval(watch);
106
+ if (code === 0 && !stopped) return { ok: true };
107
+ if (!existed) rmSync(to, { recursive: true, force: true });
108
+ return { ok: false, why: stopped || err.trim().split("\n").filter(Boolean).pop() || "git clone failed" };
109
+ }
110
+
111
+ /** The .gitignore rules for a project's .kaizen/ (run state local, workflow files tracked), once. True when written. */
112
+ export function ignoreKaizen(dir: string): boolean {
113
+ const rules = ".kaizen/*\n!.kaizen/spec*.md\n!.kaizen/config.yml\n!.kaizen/notes/\n.kaizen/notes/*\n!.kaizen/notes/Project/\n";
114
+ const gi = join(dir, ".gitignore");
115
+ const current = existsSync(gi) ? readFileSync(gi, "utf8") : "";
116
+ if (current.includes(".kaizen/*")) return false;
117
+ appendFileSync(gi, (current && !current.endsWith("\n") ? "\n" : "") + "\n# kaizen run state\n" + rules);
118
+ return true;
119
+ }
120
+
121
+ export type Branches = { current: string; def: string; branches: string[] };
122
+ /** Local and origin branches of a project, its current one and the one a new workspace starts from. */
123
+ export function branchesOf(project: string, sh: Run = run): Branches {
124
+ const g = (...a: string[]) => sh(["git", ...a], project);
125
+ if (!g("rev-parse", "--is-inside-work-tree").ok) return { current: "", def: "", branches: [] };
126
+ const branches = g("for-each-ref", "--format=%(refname:short)", "refs/heads", "refs/remotes/origin").out.split("\n")
127
+ .filter((b) => b && b !== "origin" && b !== "origin/HEAD");
128
+ const current = g("symbolic-ref", "--short", "HEAD").out;
129
+ const head = g("symbolic-ref", "--short", "refs/remotes/origin/HEAD").out;
130
+ const def = [head, "main", "master", current].find((b) => b && branches.includes(b)) ?? current;
131
+ return { current, def, branches };
132
+ }
package/cli/board.test.ts CHANGED
@@ -350,3 +350,18 @@ test("new-idea picker never swaps a preset project for another when a choice is
350
350
  expect(startDir(["/a", "/b"], "/gone", false)).toBe("/a");
351
351
  expect(startDir([], null, false)).toBeNull();
352
352
  });
353
+
354
+ test("markStage records a stage terminal only inside an existing runs/<id>", async () => {
355
+ const { markStage, stagesOf } = await import("./web.ts");
356
+ const { mkdtempSync, mkdirSync, existsSync } = await import("node:fs");
357
+ const { tmpdir } = await import("node:os");
358
+ const dir = join(mkdtempSync(join(tmpdir(), "kz-stage-")), ".kaizen");
359
+ mkdirSync(join(dir, "runs", "r1"), { recursive: true });
360
+ markStage(dir, "r1", "plan", "k1");
361
+ markStage(dir, "r1", "impl", "k2");
362
+ expect(stagesOf(dir, "r1")).toEqual({ plan: "k1", impl: "k2" });
363
+ for (const id of [".", "..", "nope"]) markStage(dir, id, "plan", "x");
364
+ expect(existsSync(join(dir, "terminals.json"))).toBe(false);
365
+ expect(existsSync(join(dir, "runs", "terminals.json"))).toBe(false);
366
+ expect(existsSync(join(dir, "runs", "nope"))).toBe(false);
367
+ });
package/cli/chat.ts CHANGED
@@ -220,7 +220,7 @@ export function sendChat(base: string, id: string | null, text: string, project:
220
220
  const argv = [bin, "exec", "--json", "--skip-git-repo-check", "-s", "workspace-write", ...dirs,
221
221
  "-m", "gpt-6-luna", "-c", "model_reasoning_effort=medium", ...(chat.thread ? ["resume", chat.thread] : []), ...images, "-"];
222
222
  let p;
223
- try { p = Bun.spawn(argv, { cwd, env, stdin: "pipe", stdout: "pipe", stderr: "pipe" }); }
223
+ try { p = Bun.spawn(argv, { cwd, env, stdin: "pipe", stdout: "pipe", stderr: "pipe", windowsHide: true }); }
224
224
  catch (err: any) {
225
225
  reply.error = `Could not start codex: ${err?.message ?? err}`;
226
226
  delete reply.activity;
package/cli/dashboard.ts CHANGED
@@ -6,9 +6,10 @@ import {
6
6
  home, type Run, type Item, type Card, type InboxLine, type Status,
7
7
  KNOWN_AGENTS, detectDefaultAgent, findTerminal,
8
8
  searchRoots, knownProjects, remember, findProjects, locate,
9
- readRuns, backlog, version, label, tilde, section, readFindings, parseItem, tidy, readBacklog, allBacklog,
9
+ readRuns, healRuns, backlog, version, label, tilde, section, readFindings, parseItem, tidy, readBacklog, allBacklog,
10
10
  startedRuns, normalise, statusOf, columnOf, readInbox, writeInbox, notify, notice, notifier, short,
11
11
  abandonRun, replaceIdea, boardCards, launchRun, appendNote, parseNotes,
12
+ gateOf,
12
13
  } from "./state.ts";
13
14
  const rgb = (r: number, g: number, b: number, s: string) =>
14
15
  `\x1b[38;2;${r};${g};${b}m${s}\x1b[0m`;
@@ -360,6 +361,7 @@ export async function dashboard(
360
361
  async function runsView(from?: string) {
361
362
  for (;;) {
362
363
  const here = from ?? state!;
364
+ healRuns(here);
363
365
  const runs = readRuns(here);
364
366
  const now = Date.now();
365
367
  // The dot the board already uses, a four-letter word for anyone not reading
@@ -371,7 +373,9 @@ export async function dashboard(
371
373
  const word = { waiting: "wait", running: "run", stalled: "idle", done: "done", abandoned: "drop" }[status] ?? status;
372
374
  const mark = status === "waiting" ? c.amber(word.padEnd(4)) : c.dim(word.padEnd(4));
373
375
  // The mark already says done or dropped; repeating the stage beside it is noise.
374
- const tail = r.stage === "done" || r.stage === "abandoned" ? "" : (r.awaiting ?? r.stage);
376
+ const gate = r.stage === "done" ? gateOf(here, r.id) : null;
377
+ const tail = r.awaiting === "approvals.review" ? "needs your approval: board, or kaizen done <id> --user-approved" : gate === "auto" ? "auto-accepted"
378
+ : r.stage === "done" || r.stage === "abandoned" ? "" : (r.awaiting ?? r.stage);
375
379
  return `${dot} ${mark} ${short(r.id).padEnd(width)} ${c.dim(tail)}`;
376
380
  });
377
381
  const { index } = await pick(from ? `Runs — ${label(from)}` : "Runs", rows);
@@ -142,7 +142,7 @@ it("upgrade with npm unreachable says not upgraded, never up to date", () => {
142
142
  // initProject() runs only at the end of a full install, so its gitignore rules are read
143
143
  // from the source and handed to git: what git ignores is the only answer that counts.
144
144
  it("init's gitignore keeps run state and personal notes out, the docs vault in", () => {
145
- const src = readFileSync(script, "utf8");
145
+ const src = readFileSync(join(import.meta.dir, "add-project.ts"), "utf8");
146
146
  const rules = JSON.parse(src.match(/const rules = (".kaizen\/\*[^"]*");/)![1]!);
147
147
  const proj = mkdtempSync(join(tmpdir(), "kz-ignore-"));
148
148
  Bun.spawnSync(["git", "init", "-q", proj]);
package/cli/install.ts CHANGED
@@ -6,6 +6,7 @@ import {
6
6
  } from "node:fs";
7
7
  import { join, dirname, basename, resolve } from "node:path";
8
8
  import { homedir, tmpdir } from "node:os";
9
+ import { ignoreKaizen } from "./add-project.ts";
9
10
  import { applyPreset, detectPreset, PRESETS, type PresetName } from "./settings.ts";
10
11
 
11
12
  // The real path: process.cwd() is always physical, so a raw $HOME that crosses a
@@ -116,6 +117,19 @@ if (Bun.argv[2] === "card") {
116
117
  process.exit(0);
117
118
  }
118
119
 
120
+ // `kaizen done <run id> [--user-approved]`: how an agent finishes a run. Refuses while
121
+ // the review gate waits on the user; --user-approved is for a clear yes in chat.
122
+ if (Bun.argv[2] === "done") {
123
+ const { locate, finishRun } = await import("./state.ts");
124
+ const id = Bun.argv[3], flag = Bun.argv[4];
125
+ if (!id || (flag && flag !== "--user-approved")) { console.log(`\n kaizen done <run id> [--user-approved]\n`); process.exit(1); }
126
+ const state = locate() ?? join(home, ".kaizen");
127
+ const why = finishRun(state, id, flag === "--user-approved");
128
+ if (why) { console.log(`\n ${why}\n`); process.exit(1); }
129
+ console.log(`\n ${c.green("done")} ${id}\n`);
130
+ process.exit(0);
131
+ }
132
+
119
133
  // `kaizen remember …` / `kaizen recall …`: global knowledge, see cli/knowledge.ts.
120
134
  if (Bun.argv[2] === "remember" || Bun.argv[2] === "recall") {
121
135
  const { cli } = await import("./knowledge.ts");
@@ -458,11 +472,12 @@ if (wantSettings) {
458
472
  if (args.has("worktree")) {
459
473
  const [, verb = "", id = ""] = Bun.argv.slice(2).filter((a) => !a.startsWith("-"));
460
474
  const { locate } = await import("./state.ts");
461
- const { startWorktree, landWorktree } = await import("./worktree.ts");
475
+ const { startWorktree, landWorktree, adoptWorkspace } = await import("./worktree.ts");
462
476
  const state = locate();
463
477
  if (!state || (verb !== "start" && verb !== "land")) { console.log("\n usage: kaizen worktree start|land <run-id>, in a project with .kaizen\n"); process.exit(1); }
464
478
  const project = dirname(state);
465
- const r = verb === "start" ? startWorktree(project, id) : landWorktree(project, id);
479
+ // Started inside another workspace of the project (a board worktree): the run is placed there.
480
+ const r = verb === "start" ? adoptWorkspace(project, id, process.cwd()) ?? startWorktree(project, id) : landWorktree(project, id);
466
481
  console.log(r.ok ? `\n ${verb === "start" ? `worktree ready: ${(r as { path: string }).path}` : `landed by ${(r as { how: string }).how}`}\n` : `\n ${r.why}\n`);
467
482
  process.exit(r.ok ? 0 : 1);
468
483
  }
@@ -1156,13 +1171,7 @@ function initProject() {
1156
1171
  // Nothing to ignore where there is no git, so a plain folder gets no .gitignore.
1157
1172
  let ignored = false;
1158
1173
  if (existsSync(join(process.cwd(), ".git"))) {
1159
- const rules = ".kaizen/*\n!.kaizen/spec*.md\n!.kaizen/config.yml\n!.kaizen/notes/\n.kaizen/notes/*\n!.kaizen/notes/Project/\n";
1160
- const gi = join(process.cwd(), ".gitignore");
1161
- const current = existsSync(gi) ? readFileSync(gi, "utf8") : "";
1162
- if (!current.includes(".kaizen/*")) {
1163
- appendFileSync(gi, (current && !current.endsWith("\n") ? "\n" : "") + "\n# kaizen run state\n" + rules);
1164
- ignored = true;
1165
- }
1174
+ ignored = ignoreKaizen(process.cwd());
1166
1175
  }
1167
1176
  step(ignored ? "wrote .kaizen/ and the gitignore entry" : "wrote .kaizen/");
1168
1177
  writePointer();
package/cli/pty.test.ts CHANGED
@@ -5,7 +5,7 @@ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, realpa
5
5
  import { tmpdir } from "node:os";
6
6
  import { join } from "node:path";
7
7
  import { launchMode, closeSessions, readSessions, sweepSessions } from "./state.ts";
8
- import { loginEnv, startPty, writePty, attachPty, ptyState, exitPty } from "./pty.ts";
8
+ import { loginEnv, startPty, writePty, attachPty, ptyState, exitPty, lastLine } from "./pty.ts";
9
9
  import { conptyHost, innerCommand, resizeSeq } from "./conpty.ts";
10
10
 
11
11
  const root = realpathSync(mkdtempSync(join(tmpdir(), "kaizen-pty-")));
@@ -29,7 +29,7 @@ test.skipIf(process.platform === "win32")("the board runs the agent in the card:
29
29
  writeFileSync(join(st, "config.yml"), "agent:\n default: claude\n launch: card\n");
30
30
  writeFileSync(join(st, "inbox.md"), "# Inbox\n\n- open: say hello\n");
31
31
  // A stand-in for Claude Code: says how it was called, then echoes each line it is sent.
32
- writeFileSync(join(bin, "claude"), '#!/bin/sh\necho "args:$*"\nwhile read x; do echo "got:$x"; done\n', { mode: 0o755 });
32
+ writeFileSync(join(bin, "claude"), '#!/bin/sh\necho "args:$*"; echo "⏺ reply ready"\nwhile read x; do echo "got:$x"; done\n', { mode: 0o755 });
33
33
  // Started as a launcher starts it: a bare PATH, the agent reachable only through
34
34
  // the PATH the user's login shell builds.
35
35
  const sh = join(root, "loginsh");
@@ -39,7 +39,7 @@ test.skipIf(process.platform === "win32")("the board runs the agent in the card:
39
39
  const proc = Bun.spawn([process.execPath, join(repo, "cli", "install.ts"), "web", "--port", String(port), "--no-open", "--foreground"], {
40
40
  cwd: proj, stdout: "ignore", stderr: "ignore",
41
41
  env: { ...process.env, HOME: homeDir, USERPROFILE: homeDir, KAIZEN_HOME: repo, CLAUDE_CONFIG_DIR: join(homeDir, ".claude"),
42
- PATH: "/usr/bin:/bin", SHELL: sh, DISPLAY: "", WAYLAND_DISPLAY: "", TERMINAL: "", TMUX: "" },
42
+ PATH: "/usr/bin:/bin", KAIZEN_WEB_HOSTS: "remote.ts.net", SHELL: sh, DISPLAY: "", WAYLAND_DISPLAY: "", TERMINAL: "", TMUX: "" },
43
43
  });
44
44
  try {
45
45
  const at = `http://127.0.0.1:${port}`;
@@ -52,6 +52,18 @@ test.skipIf(process.platform === "win32")("the board runs the agent in the card:
52
52
  const card = ((await (await fetch(at + "/state")).json()) as any).cards.find((c: any) => c.text === "say hello");
53
53
  expect(card.pty).toMatchObject({ key: r.pty, alive: true, asking: false, all: [r.pty] });
54
54
 
55
+ // The agent's output line goes to a viewer on this machine only, never a tailnet host; nothing typed is in it.
56
+ const agentsOf = async (h?: string) => ((await (await fetch(at + "/state", { headers: h ? { host: h } : {} })).json()) as any).agents;
57
+ expect((await agentsOf())[0].last).toBe("reply ready");
58
+ const far = (await agentsOf("remote.ts.net"))[0];
59
+ expect(far.key).toBe(r.pty);
60
+ expect(far.last).toBeUndefined();
61
+ // Host 127.0.0.1 behind a proxy (tailscale serve adds these headers) gets no line either.
62
+ for (const h of ["x-forwarded-for", "tailscale-user-login"]) {
63
+ const via = ((await (await fetch(at + "/state", { headers: { [h]: "100.64.0.9" } })).json()) as any).agents[0];
64
+ expect(via.last).toBeUndefined();
65
+ }
66
+
55
67
  // G-01: no Origin, a foreign one, and another local port are all refused.
56
68
  const url = `${at}/pty?key=${r.pty}`, up = { upgrade: "websocket", connection: "Upgrade", "sec-websocket-version": "13", "sec-websocket-key": "dGhlIHNhbXBsZSBub25jZQ==" };
57
69
  expect((await fetch(url, { headers: up })).status).toBe(403);
@@ -229,3 +241,70 @@ test("busy: on while the agent prints, off once its output goes quiet", async ()
229
241
  expect(ptyState(key)).toMatchObject({ alive: true, busy: false });
230
242
  exitPty(key);
231
243
  });
244
+
245
+ test("lastLine: only the agent's own marked reply lines, never input", () => {
246
+ expect(lastLine("\x1b[2K\x1b[1;32m⏺ Done: fixed the bug\x1b[0m\r\n╭────╮\r\n│ ✻ │\r\n⠋ \r\n? for shortcuts\r\n✻ Thinking… (12s · esc to interrupt)")).toBe("Done: fixed the bug");
247
+ expect(lastLine("• Ran the tests, 12 pass")).toBe("Ran the tests, 12 pass");
248
+ expect(lastLine("✦ Updated the parser")).toBe("Updated the parser");
249
+ // Unmarked output (a plain shell, an unknown agent) gives nothing: the card shows status only.
250
+ expect(lastLine("Build passed\r\n12 pass 0 fail")).toBe("");
251
+ // Typed or pasted text is never shown, whatever the prompt looks like.
252
+ const leaks = [
253
+ "│ > hey there │",
254
+ "⏺ Done: fixed it\r\n╭──────╮\r\n│ > pasted-token-9 │\r\n│ ⏺ fake-token-9 │\r\n╰──────╯",
255
+ "❯ pasted-token-9",
256
+ "rzr@host:~$ export KEY=sk-secret-9",
257
+ "user@host ~/a b/c (main) $ export KEY=sk-secret-9",
258
+ "user@host ~/proj> sk-secret-9",
259
+ "PS C:\\Users\\me> sk-secret-9",
260
+ ">>> sk-secret-9",
261
+ "▌ sk-secret-9",
262
+ " ~/proj main sk-secret-9",
263
+ "sk-secret-9 continued in a later chunk",
264
+ ];
265
+ leaks.push("──────\r\n❯ please fix\r\n • sk-secret-9 token\r\n⏺ token-9 pasted\r\n──────\r\n");
266
+ for (const t of leaks) expect(lastLine(t)).not.toContain("secret-9"), expect(lastLine(t)).not.toContain("token-9");
267
+ // The newest marked line wins over older ones; a marked line with an unmarked line below it still counts.
268
+ expect(lastLine("⏺ Fixed issue # 42 in parser\r\nrzr@host:~$ sk-secret-9")).toBe("Fixed issue # 42 in parser");
269
+ // Output above the input rules is still read; a tool call shows its name, not its arguments.
270
+ expect(lastLine("⏺ Fixed the parser\r\n──────\r\n❯ next\r\n──────")).toBe("Fixed the parser");
271
+ expect(lastLine("⏺ Bash(curl -H 'Authorization: Bearer sk-secret-9')")).toBe("Bash");
272
+ expect(lastLine("╰───╯ ⠙ ✻")).toBe("");
273
+ expect(lastLine("⏺ " + "x".repeat(200)).length).toBe(80);
274
+ });
275
+
276
+ test("last: only the agent's output, never what was typed or echoed right after a keystroke", async () => {
277
+ const key = "last-" + Date.now();
278
+ startPty(key, ["sh", "-c", "echo '⏺ agent-said-this'; stty echo; read a; sleep 2; echo '⏺ later-agent-line'; sleep 5"], root);
279
+ await Bun.sleep(1000);
280
+ expect(ptyState(key)!.last).toBe("agent-said-this");
281
+ writePty(key, "hunter2-secret\r"); // the tty echoes it back at once
282
+ await Bun.sleep(1200);
283
+ expect(JSON.stringify(ptyState(key))).not.toContain("hunter2");
284
+ expect(ptyState(key)!.last).toBe("agent-said-this");
285
+ await Bun.sleep(2200);
286
+ expect(ptyState(key)!.last).toBe("later-agent-line");
287
+ expect(JSON.stringify(ptyState(key))).not.toContain("hunter2");
288
+ exitPty(key, 100);
289
+ });
290
+
291
+ test("last: a pasted token in the input box is never the last line, redraw or quiet read", async () => {
292
+ const key = "box-" + Date.now();
293
+ startPty(key, ["sh", "-c", "echo '⏺ agent-said-this'; sleep 2; printf '╭────╮\\n│ > pasted-token-9 │\\n╰────╯\\n'; sleep 3; printf '\\r│ > pasted-token-9 │\\n'; sleep 5"], root);
294
+ await Bun.sleep(2600);
295
+ expect(ptyState(key)!.last).toBe("agent-said-this");
296
+ await Bun.sleep(2400);
297
+ expect(JSON.stringify(ptyState(key))).not.toContain("pasted-token");
298
+ exitPty(key, 100);
299
+ }, 15000);
300
+
301
+ test("last: nothing is read while the terminal is asking", async () => {
302
+ const key = "ask-" + Date.now();
303
+ startPty(key, ["sh", "-c", "echo 'Do you want to proceed? (y/n)'; read a; echo ok-done-now; read b; sleep 5"], root);
304
+ for (let i = 0; i < 40 && !ptyState(key)!.asking; i++) await Bun.sleep(100);
305
+ expect(ptyState(key)!.asking).toBe(true);
306
+ writePty(key, "hunter2\r");
307
+ await Bun.sleep(1200);
308
+ expect(JSON.stringify(ptyState(key))).not.toContain("hunter2");
309
+ exitPty(key, 100);
310
+ });