kaizen-agent 1.62.0 → 1.64.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/cli/automations.test.ts +167 -0
  2. package/cli/automations.ts +298 -0
  3. package/cli/dashboard.ts +1 -7
  4. package/cli/handoff.test.ts +133 -0
  5. package/cli/handoff.ts +122 -0
  6. package/cli/install.test.ts +16 -0
  7. package/cli/install.ts +92 -191
  8. package/cli/look.ts +33 -0
  9. package/cli/pty.ts +16 -2
  10. package/cli/resources.test.ts +50 -0
  11. package/cli/resources.ts +113 -0
  12. package/cli/restart.test.ts +28 -1
  13. package/cli/settings.ts +6 -2
  14. package/cli/setup.test.ts +22 -2
  15. package/cli/setup.ts +101 -51
  16. package/cli/sources.ts +1 -1
  17. package/cli/state.test.ts +7 -0
  18. package/cli/state.ts +13 -2
  19. package/cli/usage.test.ts +11 -0
  20. package/cli/web.ts +134 -6
  21. package/cli/workers.ts +11 -4
  22. package/cli/worktree.test.ts +174 -1
  23. package/cli/worktree.ts +190 -35
  24. package/package.json +1 -1
  25. package/skills/kaizen/config.default.yml +17 -0
  26. package/skills/kaizen/settings.md +4 -0
  27. package/skills/kaizen/spec-build.md +13 -0
  28. package/skills/kaizen/spec-main.md +13 -0
  29. package/skills/kaizen-help/SKILL.md +1 -0
  30. package/skills/media/kaizen-deck/SKILL.md +21 -2
  31. package/skills/media/kaizen-deck/scripts/motion.py +99 -0
  32. package/web/board/cards.ts +1 -0
  33. package/web/board/git.ts +4 -4
  34. package/web/board/phone.ts +5 -5
  35. package/web/board/resources.ts +152 -0
  36. package/web/board/run-view.ts +107 -1
  37. package/web/board/search.ts +6 -0
  38. package/web/board/settings-automations.ts +71 -0
  39. package/web/board/settings-pages.test.ts +4 -0
  40. package/web/board/settings-pages.ts +2 -1
  41. package/web/board/settings.ts +10 -3
  42. package/web/board/workspace.ts +7 -1
  43. package/web/board/ws-tabs.test.ts +20 -1
  44. package/web/board/ws-tabs.ts +26 -7
  45. package/web/board.html +20 -3
  46. package/web/board.js +119 -88
  47. package/web/notebook.js +23 -23
  48. package/web/notes.html +1 -0
  49. package/web/term.js +1 -1
  50. package/web/video.html +1 -0
  51. package/web/video.js +49 -49
package/cli/pty.ts CHANGED
@@ -11,7 +11,7 @@ const WIN = process.platform === "win32";
11
11
  // Windows PowerShell, which every Windows has, both hosts the console and runs the agent in it.
12
12
  const winPs = () => join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
13
13
 
14
- type Pty = { lastOut?: number; proc: Bun.Subprocess; out: string[]; size: number; listeners: Set<(d: string | null) => void>; exit: number | null; asking: boolean; busy: boolean; quiet?: Timer; total: number; since: number; onChange?: () => void; tmux?: string; last: string; lastAt: number; typedAt: number; born: number };
14
+ type Pty = { lastOut?: number; proc: Bun.Subprocess; out: string[]; size: number; listeners: Set<(d: string | null) => void>; exit: number | null; asking: boolean; busy: boolean; quiet?: Timer; total: number; since: number; onChange?: () => void; tmux?: string; last: string; lastAt: number; typedAt: number; born: number; draft?: boolean };
15
15
 
16
16
  // What a page attaching late gets replayed. A full-screen tool redraws often, so the
17
17
  // tail of its output is enough to rebuild the screen.
@@ -198,6 +198,9 @@ export function writePty(key: string, d: string) {
198
198
  if (d.replace(REPORT, "")) {
199
199
  p.since = p.total;
200
200
  p.typedAt = Date.now();
201
+ // Text typed and not yet submitted. Keys and escape sequences leave no text; Enter, Esc and Ctrl-C end it.
202
+ if (/[\r\n\x03]/.test(d) || d === "\x1b") p.draft = false;
203
+ else if (!d.startsWith("\x1b") && /[^\x00-\x1f\x7f]/.test(d)) p.draft = true;
201
204
  if (p.asking) { p.asking = false; p.onChange?.(); }
202
205
  }
203
206
  send(p, d);
@@ -230,6 +233,17 @@ export function exitPty(key: string, grace = 5000): boolean {
230
233
  return true;
231
234
  }
232
235
 
236
+ // The resource monitor's Kill: at once, with no /exit first, which a plain shell would only
237
+ // print an error for. The whole group goes (see the note above); a tmux agent with its session.
238
+ export function killPty(key: string): boolean {
239
+ const p = ptys.get(key);
240
+ if (!p || p.exit !== null) return false;
241
+ if (p.tmux) killTmux(p.tmux);
242
+ if (WIN) p.proc.kill();
243
+ else { try { process.kill(-p.proc.pid, "SIGKILL"); } catch { p.proc.kill(); } }
244
+ return true;
245
+ }
246
+
233
247
  // The board stopping with a tmux-kept agent: only its client ends, the agent keeps running
234
248
  // in kaizen's tmux server, and the next board attaches to it (attachCmd).
235
249
  export function detachPty(key: string): boolean {
@@ -285,7 +299,7 @@ export const ptyKeys = () => [...ptys.keys()];
285
299
 
286
300
  export const ptyState = (key: string) => {
287
301
  const p = ptys.get(key);
288
- return p ? { pid: p.proc.pid, alive: p.exit === null, exit: p.exit, asking: p.asking, busy: p.busy, total: p.total, last: p.last, at: p.lastAt, born: p.born, lastOut: p.lastOut } : null;
302
+ return p ? { pid: p.proc.pid, alive: p.exit === null, exit: p.exit, asking: p.asking, busy: p.busy, total: p.total, last: p.last, at: p.lastAt, born: p.born, lastOut: p.lastOut, typedAt: p.typedAt, draft: !!p.draft } : null;
289
303
  };
290
304
 
291
305
  // The environment the user's login shell builds: PATH and anything exported in their
@@ -0,0 +1,50 @@
1
+ import { expect, it } from "bun:test";
2
+ import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { folderSize, measure, parsePs, systemMemory, treeRss } from "./resources.ts";
6
+
7
+ it("reads available memory, so page cache is not shown as used", () => {
8
+ const m = systemMemory("MemTotal: 1 kB\nMemAvailable: 1024 kB\n");
9
+ expect(m.total - m.used).toBe(1024 * 1024);
10
+ });
11
+
12
+ it("adds a process tree once, whichever roots reach it", () => {
13
+ const t = parsePs(" 1 0 10\n 2 1 20\n 3 2 30\n 4 1 40\njunk\n 9 0 90\n");
14
+ expect(t).toHaveLength(5);
15
+ expect(treeRss(t, [2])).toBe(50 * 1024);
16
+ expect(treeRss(t, [1, 2, 3])).toBe(100 * 1024);
17
+ expect(treeRss(t, [777])).toBe(0);
18
+ });
19
+
20
+ const scratch = () => mkdtempSync(join(tmpdir(), "kz-res-"));
21
+
22
+ it("does not follow symlinks", async () => {
23
+ const d = scratch();
24
+ try {
25
+ mkdirSync(join(d, "a")); mkdirSync(join(d, "big"));
26
+ writeFileSync(join(d, "big", "f"), Buffer.alloc(1 << 20));
27
+ const before = await folderSize(join(d, "a"));
28
+ symlinkSync(join(d, "big"), join(d, "a", "link"));
29
+ expect(await folderSize(join(d, "a"))).toBeLessThan(before + 65536);
30
+ expect(await folderSize(join(d, "big"))).toBeGreaterThanOrEqual(1 << 20);
31
+ } finally { rmSync(d, { recursive: true, force: true }); }
32
+ });
33
+
34
+ it("counts a real folder once and a nested root only in its own row", async () => {
35
+ const d = scratch();
36
+ try {
37
+ mkdirSync(join(d, "inst", ".kaizen"), { recursive: true });
38
+ writeFileSync(join(d, "inst", ".kaizen", "f"), Buffer.alloc(1 << 20));
39
+ symlinkSync(join(d, "inst", ".kaizen"), join(d, "alias"));
40
+ const r = await measure([
41
+ { name: "inst", dir: "", path: join(d, "inst"), kind: "install" },
42
+ { name: "p", dir: "x", path: join(d, "inst", ".kaizen"), kind: "project" },
43
+ { name: "again", dir: "y", path: join(d, "alias"), kind: "project" },
44
+ { name: "gone", dir: "z", path: join(d, "missing"), kind: "project" },
45
+ ]);
46
+ expect(r.rows.map((x) => x.name)).toEqual(["p", "inst"]);
47
+ expect(r.rows[1].bytes).toBeLessThan(1 << 20);
48
+ expect(r.total).toBe(r.rows[0].bytes + r.rows[1].bytes);
49
+ } finally { rmSync(d, { recursive: true, force: true }); }
50
+ });
@@ -0,0 +1,113 @@
1
+ // What the footer's resource monitor reports: memory for the machine, for kaizen and per
2
+ // terminal, and the disk kaizen takes. Apart from cli/web.ts so the parsing and the walk
3
+ // can be tested without a board. Read only: nothing here kills or deletes.
4
+ import { freemem, totalmem } from "node:os";
5
+ import { readFileSync, realpathSync } from "node:fs";
6
+ import { lstat, readdir } from "node:fs/promises";
7
+ import { join } from "node:path";
8
+
9
+ export function systemMemory(meminfo?: string) {
10
+ const total = totalmem();
11
+ let free = freemem();
12
+ // freemem() on Linux leaves out the page cache, which would read as a nearly full machine.
13
+ try {
14
+ const text = meminfo ?? readFileSync("/proc/meminfo", "utf8");
15
+ const kb = /^MemAvailable:\s+(\d+) kB/m.exec(text);
16
+ if (kb) free = Number(kb[1]) * 1024;
17
+ } catch { /* not Linux */ }
18
+ return { total, used: Math.max(0, total - free) };
19
+ }
20
+
21
+ export type Proc = { pid: number; ppid: number; rss: number };
22
+
23
+ export function parsePs(out: string): Proc[] {
24
+ return out.split("\n").flatMap((l) => {
25
+ const m = /^\s*(\d+)\s+(\d+)\s+(\d+)\s*$/.exec(l);
26
+ return m ? [{ pid: Number(m[1]), ppid: Number(m[2]), rss: Number(m[3]) * 1024 }] : [];
27
+ });
28
+ }
29
+
30
+ // Every process with its parent and memory; null where there is no ps (Windows), so a
31
+ // caller shows "not known" rather than zero.
32
+ export async function processTable(): Promise<Proc[] | null> {
33
+ if (process.platform === "win32") return null;
34
+ try {
35
+ const p = Bun.spawn(["ps", "-axo", "pid=,ppid=,rss="], { stdout: "pipe", stderr: "ignore", windowsHide: true });
36
+ const out = await new Response(p.stdout).text();
37
+ return (await p.exited) === 0 ? parsePs(out) : null;
38
+ } catch { return null; }
39
+ }
40
+
41
+ // Memory of these processes and all their descendants, each counted once however many
42
+ // roots reach it. Resident sizes add shared pages more than once, so it runs a little high.
43
+ export function treeRss(table: Proc[], roots: number[]): number {
44
+ const kids = new Map<number, Proc[]>(), byPid = new Map(table.map((p) => [p.pid, p]));
45
+ for (const p of table) (kids.get(p.ppid) ?? kids.set(p.ppid, []).get(p.ppid)!).push(p);
46
+ const seen = new Set<number>(), todo = [...roots];
47
+ let sum = 0;
48
+ while (todo.length) {
49
+ const pid = todo.pop()!;
50
+ if (seen.has(pid)) continue;
51
+ seen.add(pid);
52
+ sum += byPid.get(pid)?.rss ?? 0;
53
+ for (const k of kids.get(pid) ?? []) todo.push(k.pid);
54
+ }
55
+ return sum;
56
+ }
57
+
58
+ const real = (p: string) => { try { return realpathSync(p); } catch { return null; } };
59
+
60
+ // Bytes on disk under a folder. lstat, so a symlink counts as itself and is never followed;
61
+ // a folder in `skip` (real paths) belongs to another row. Every await hands the one thread
62
+ // back, so a large tree slows the scan and not the board.
63
+ export async function folderSize(path: string, skip: Set<string> = new Set()): Promise<number> {
64
+ let sum = 0;
65
+ const todo = [path];
66
+ while (todo.length) {
67
+ const dir = todo.pop()!;
68
+ if (skip.has(dir)) continue;
69
+ let names: string[];
70
+ try { names = await readdir(dir); } catch { continue; }
71
+ for (let i = 0; i < names.length; i += 64) {
72
+ const stats = await Promise.all(names.slice(i, i + 64).map(async (n) => {
73
+ try { const s = await lstat(join(dir, n)); return { p: join(dir, n), s }; } catch { return null; }
74
+ }));
75
+ for (const e of stats) {
76
+ if (!e) continue;
77
+ sum += e.s.blocks ? e.s.blocks * 512 : e.s.size;
78
+ if (e.s.isDirectory()) todo.push(e.p);
79
+ }
80
+ }
81
+ }
82
+ return sum;
83
+ }
84
+
85
+ export type Root = { name: string; dir: string; path: string; kind: "home" | "install" | "project" };
86
+ export type StorageRow = Omit<Root, "path"> & { bytes: number };
87
+
88
+ // One row per real folder, and no folder counted inside another row: a checkout that is
89
+ // both the install and a registered project gives its .kaizen to the project row.
90
+ export async function measure(roots: Root[]): Promise<{ total: number; rows: StorageRow[] }> {
91
+ const seen = new Map<string, Root>();
92
+ for (const r of roots) { const p = real(r.path); if (p && !seen.has(p)) seen.set(p, r); }
93
+ const rows: StorageRow[] = [];
94
+ for (const [p, r] of seen) {
95
+ const skip = new Set([...seen.keys()].filter((o) => o !== p));
96
+ rows.push({ name: r.name, dir: r.dir, kind: r.kind, bytes: await folderSize(p, skip) });
97
+ }
98
+ rows.sort((a, b) => b.bytes - a.bytes);
99
+ return { total: rows.reduce((n, r) => n + r.bytes, 0), rows };
100
+ }
101
+
102
+ const FRESH = 5 * 60_000;
103
+ let result: { total: number; rows: StorageRow[]; at: number } | null = null;
104
+ let scanning = false;
105
+
106
+ // Never waits: starts a scan when the last is old (or on refresh) and answers with what it has.
107
+ export function storage(roots: () => Root[], refresh = false) {
108
+ if (!scanning && (refresh || !result || Date.now() - result.at > FRESH)) {
109
+ scanning = true;
110
+ void measure(roots()).then((r) => { result = { ...r, at: Date.now() }; }).catch(() => {}).finally(() => { scanning = false; });
111
+ }
112
+ return { ...(result ?? { total: 0, rows: [], at: 0 }), scanning };
113
+ }
@@ -5,8 +5,9 @@ import { test, expect } from "bun:test";
5
5
  import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, realpathSync } from "node:fs";
6
6
  import { tmpdir } from "node:os";
7
7
  import { join } from "node:path";
8
- import { startPty, exitPty, ptyState, tmuxOk, tmuxName, tmuxAlive, killTmux, detachPty, attachPty, panePid } from "./pty.ts";
8
+ import { startPty, exitPty, killPty, ptyState, tmuxOk, tmuxName, tmuxAlive, killTmux, detachPty, attachPty, panePid } from "./pty.ts";
9
9
  import { keepAlive } from "./state.ts";
10
+ import { processTable, treeRss } from "./resources.ts";
10
11
 
11
12
  const root = realpathSync(mkdtempSync(join(tmpdir(), "kaizen-restart-")));
12
13
  const posix = process.platform !== "win32";
@@ -193,3 +194,29 @@ console.log("up");`);
193
194
  expect(version).toBe(JSON.parse(readFileSync(join(import.meta.dir, "..", "package.json"), "utf8")).version);
194
195
  } finally { fresh.kill("SIGKILL"); old.kill("SIGKILL"); }
195
196
  }, 20000);
197
+
198
+ test("killPty ends the terminal's whole group at once, and only that terminal", async () => {
199
+ if (!posix) return;
200
+ const file = (n: string) => join(root, n + ".pid");
201
+ for (const k of ["kill-a", "kill-b"]) startPty(k, ["sh", "-c", `sleep 300 & echo $! > ${file(k)}; wait`], root);
202
+ for (let i = 0; i < 100 && !(existsSync(file("kill-a")) && existsSync(file("kill-b"))); i++) await Bun.sleep(20);
203
+ const a = Number(readFileSync(file("kill-a"), "utf8")), b = Number(readFileSync(file("kill-b"), "utf8"));
204
+ expect(killPty("kill-a")).toBe(true);
205
+ expect(await gone(a)).toBe(true);
206
+ expect(() => process.kill(b, 0)).not.toThrow();
207
+ expect(killPty("no-such")).toBe(false);
208
+ killPty("kill-b");
209
+ expect(await gone(b)).toBe(true);
210
+ });
211
+
212
+ test.skipIf(!posix || !tmuxOk())("a tmux-kept terminal is measured from its pane and killed with its session", async () => {
213
+ const name = tmuxName("res-" + process.pid);
214
+ startPty("res-tmux", ["sleep", "60"], root, undefined, undefined, { tmux: name });
215
+ let pane: number | null = null;
216
+ for (let i = 0; i < 100 && !(pane = panePid(name)); i++) await Bun.sleep(30);
217
+ expect(pane).toBeGreaterThan(0);
218
+ expect(treeRss((await processTable())!, [pane!])).toBeGreaterThan(0);
219
+ expect(killPty("res-tmux")).toBe(true);
220
+ for (let i = 0; i < 100 && tmuxAlive(name); i++) await Bun.sleep(30);
221
+ expect(tmuxAlive(name)).toBe(false);
222
+ });
package/cli/settings.ts CHANGED
@@ -115,17 +115,21 @@ const SETTINGS: Setting[] = [
115
115
  { key: "agent.keep_alive", label: "Keep agents through a board restart", group: "Agents", values: ["off", "tmux"], help: "tmux: Linux and macOS with tmux installed", when: ["agent.launch", "card"] },
116
116
  { key: "agent.keep_awake", label: "Keep computer awake", group: "Board", values: ["off", "auto", "on"], help: "auto: while the board runs agents · on: while the board is open. Linux and macOS" },
117
117
  { key: "agent.heartbeat_minutes", label: "Agent heartbeat", group: "Board", values: ["2", "5", "10", "30"], help: "Minutes. A card says stale after two quiet intervals" },
118
- { key: "subagents.model", label: "Model for subagents", group: "Agents", values: ["inherit", "opus", "sonnet", "haiku"], help: "Planner, builder, reviewer", when: ["runner", "full"] },
119
- { key: "subagents.effort", label: "Effort for subagents", group: "Agents", values: ["inherit", "low", "medium", "high"], help: "Planner, builder, reviewer", when: ["runner", "full"] },
118
+ { key: "subagents.model", label: "Claude Code", group: "Agents", values: ["inherit", "opus", "sonnet", "haiku"], help: "Its stage subagents: planner, builder, reviewer", when: ["runner", "full"] },
119
+ { key: "subagents.effort", label: "Claude Code effort", group: "Agents", values: ["inherit", "low", "medium", "high"], help: "Planner, builder, reviewer", when: ["runner", "full"] },
120
120
  { key: "auto_fix.enabled", label: "Fix findings automatically", group: "Auto-fix", values: ["true", "false"], help: "" },
121
121
  { key: "auto_fix.min_severity", label: "Lowest severity to fix", group: "Auto-fix", values: ["critical", "high", "medium", "low"], help: "", when: ["auto_fix.enabled", "true"] },
122
122
  { key: "auto_fix.max_iterations", label: "Max fix rounds", group: "Auto-fix", values: ["1", "2", "3", "4", "5"], help: "", when: ["auto_fix.enabled", "true"] },
123
123
  { key: "git.auto_commit", label: "Commit when done", group: "Git", values: ["false", "true"], help: "Never pushes" },
124
124
  { key: "git.worktree_per_run", label: "Branch and folder per run", group: "Git", values: ["ask", "true", "false"], help: "" },
125
+ { key: "git.generated", label: "Generated files", group: "Git", values: [], text: true, help: "Path patterns, space-separated. A land takes the base's side on conflict. Empty: none" },
126
+ { key: "git.rebuild_on_land", label: "Rebuild after resolving", group: "Git", values: [], text: true, help: "Command that remakes the generated files. Empty: none" },
127
+ { key: "git.land_check", label: "Check before landing", group: "Git", values: [], text: true, help: "After a rebase that pulled commits. auto: the test script in package.json · off · or a command" },
125
128
  { key: "orchestration.enabled", label: "Build with workers", group: "Orchestration", values: ["false", "true"], help: "Off by default. A plan may split into workers, each in its own terminal and folder. Linux and macOS only" },
126
129
  { key: "orchestration.max_workers", label: "Max workers per run", group: "Orchestration", values: ["1", "2", "3", "4", "5", "6"], help: "Total per run", when: ["orchestration.enabled", "true"] },
127
130
  { key: "orchestration.permissions", label: "Worker permissions", group: "Orchestration", values: ["own", "bypass"], help: "own: each agent's own prompts. Bypass skips every prompt in every worker", when: ["orchestration.enabled", "true"] },
128
131
  // One per tool that takes a model flag; a run freezes its own agent's. Empty: the run's own model.
132
+ ...KNOWN_AGENTS.filter((a) => MODEL_FLAGS[a.cmd] && a.cmd !== "claude").map((a): Setting => ({ key: `agent.model.${a.cmd}`, label: `Model: ${a.name}`, group: "Agents", values: [], text: true, help: "The tool's own model name, for every stage: it runs them in one session. Empty: its own default" })),
129
133
  ...KNOWN_AGENTS.filter((a) => MODEL_FLAGS[a.cmd]).map((a): Setting => ({ key: `orchestration.worker_model.${a.cmd}`, label: `Worker model: ${a.name}`, group: "Orchestration", values: [], text: true, help: "The tool's own model name. Empty: the run's own model", when: ["orchestration.enabled", "true"] })),
130
134
  { key: "review.write_memory", label: "Remember lessons", group: "Project", values: ["true", "false"], help: "" },
131
135
  { key: "review.memory_max_lines", label: "Memory size cap", group: "Project", values: ["50", "100", "200", "400"], help: "" },
package/cli/setup.test.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  import { test, expect } from "bun:test";
2
- import { mkdtempSync, rmSync, existsSync, readdirSync } from "node:fs";
2
+ import { mkdtempSync, mkdirSync, rmSync, existsSync, readdirSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import { qrMatrix, qr } from "./qr.ts";
6
- import { tailnetName } from "./setup.ts";
6
+ import { projectStep, tailnetName } from "./setup.ts";
7
+ import { banner } from "./look.ts";
7
8
 
8
9
  test("qr: right size per version, finder squares in three corners, deterministic", () => {
9
10
  const a = qrMatrix("https://pc.tail1234.ts.net"); // 26 bytes: version 2, 25 modules
@@ -56,3 +57,22 @@ test("web-hosts: names are normalized, deduped and merged with the env var", asy
56
57
  expect(JSON.parse(await new Response(p.stdout).text())).toEqual(["env.ts.net", "pc.tail1.ts.net"]);
57
58
  } finally { rmSync(homeDir, { recursive: true, force: true }); }
58
59
  });
60
+
61
+ test("projectStep: home asks, a repository offers its root, an owned folder is left alone", () => {
62
+ const h = mkdtempSync(join(tmpdir(), "kaizen-step-"));
63
+ try {
64
+ const sub = join(h, "app", "src"), plain = join(h, "plain");
65
+ mkdirSync(join(h, "app", ".git"), { recursive: true }); mkdirSync(sub); mkdirSync(plain);
66
+ expect(projectStep(h, h)).toBeNull();
67
+ expect(projectStep(sub, h)).toEqual({ offer: join(h, "app"), git: true });
68
+ expect(projectStep(plain, h)).toEqual({ offer: plain, git: false });
69
+ mkdirSync(join(h, "app", ".kaizen"));
70
+ expect(projectStep(sub, h)).toEqual({ ready: true });
71
+ } finally { rmSync(h, { recursive: true, force: true }); }
72
+ });
73
+
74
+ test("banner: the K alone, and no hard-coded colour", () => {
75
+ const plain = (s: string) => s.replace(/\x1b\[[0-9;]*m/g, "");
76
+ expect(plain(banner())).not.toContain("█▀▄ █▀█");
77
+ expect(banner()).not.toContain("38;2");
78
+ });
package/cli/setup.ts CHANGED
@@ -1,18 +1,20 @@
1
1
  // `kaizen setup`: the walk after install — a project, the settings, the board, the
2
- // phone. Every step can be skipped, and nothing changes without an answer.
3
- import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
4
- import { join, resolve } from "node:path";
2
+ // phone. Enter takes the first choice at every step; nothing changes without an answer.
3
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
4
+ import { basename, join, resolve } from "node:path";
5
5
  import { addWebHost, home, remember } from "./state.ts";
6
6
  import { applyPreset, detectPreset } from "./settings.ts";
7
7
  import { qr } from "./qr.ts";
8
+ import { nextSteps } from "./look.ts";
8
9
 
9
10
  const PORT = 7420;
11
+ const TAILSCALE = "https://tailscale.com/download";
10
12
  const INSTALL = join(import.meta.dir, "install.ts");
11
13
 
12
14
  export type Ui = {
13
15
  select: <T>(q: string, o: { label: string; hint: string; value: T }[]) => Promise<T>;
14
16
  ask: (q: string) => string | null;
15
- c: Record<"dim" | "bold" | "cyan" | "green", (s: string) => string>;
17
+ c: Record<"dim" | "bold" | "accent" | "green", (s: string) => string>;
16
18
  };
17
19
 
18
20
  // The DNS name `tailscale status --json` reports for this machine, or null when
@@ -25,22 +27,26 @@ export function tailnetName(json: string): string | null {
25
27
  } catch { return null; }
26
28
  }
27
29
 
28
- // A folder already inside a project (.git or .kaizen on the way up to home).
29
- function inProject(dir: string) {
30
- for (let d = dir; d !== home; ) {
31
- if (existsSync(join(d, ".git")) || existsSync(join(d, ".kaizen"))) return true;
30
+ // What the project step should do from `dir`: nothing when kaizen already owns it,
31
+ // offer the git root or the folder itself, or null at home, where it has to ask.
32
+ export function projectStep(dir: string, homeDir: string): { ready: true } | { offer: string; git: boolean } | null {
33
+ if (dir === homeDir) return null;
34
+ let git = "";
35
+ for (let d = dir; d !== homeDir; ) {
36
+ if (existsSync(join(d, ".kaizen"))) return { ready: true };
37
+ if (!git && existsSync(join(d, ".git"))) git = d;
32
38
  const up = resolve(d, "..");
33
- if (up === d) return false;
39
+ if (up === d) break;
34
40
  d = up;
35
41
  }
36
- return false;
42
+ return { offer: git || dir, git: !!git };
37
43
  }
38
44
 
39
45
  export function manual() {
40
46
  return `
41
47
  kaizen setup needs a terminal. By hand:
42
48
  kaizen settings pick a preset
43
- kaizen web the board
49
+ kaizen web the Kaizen App
44
50
  tailscale serve --bg 127.0.0.1:${PORT} phone, then add the name it prints to ~/.kaizen/web-hosts
45
51
  `;
46
52
  }
@@ -50,59 +56,103 @@ export async function setup(ui: Ui) {
50
56
  const out = (s = "") => console.log(s);
51
57
  const run = (cmd: string[], cwd?: string) => Bun.spawnSync(cmd, { cwd, stdin: "inherit", stdout: "inherit", stderr: "inherit" }).exitCode === 0;
52
58
 
53
- out(`\n ${c.bold("kaizen setup")} ${c.dim("three short steps, each can be skipped")}`);
59
+ const project = projectStep(process.cwd(), home);
60
+ const needsProject = !(project && "ready" in project);
61
+ const tailnetNow = () => {
62
+ try { return tailnetName(Bun.spawnSync(["tailscale", "status", "--json"]).stdout.toString()); } catch { return null; /* not installed */ }
63
+ };
64
+ let tailnet = tailnetNow();
65
+ const total = 3 + (needsProject ? 1 : 0);
66
+ let n = 0;
67
+ const title = (name: string) => `Step ${++n} of ${total}: ${name}`;
54
68
 
55
- // 1 -- project
56
- if (!inProject(process.cwd())) {
57
- out(`\n ${c.bold("1 Project")} ${c.dim("kaizen keeps its runs in a .kaizen/ folder inside your project")}`);
69
+ out(`\n ${c.bold("kaizen setup")} ${c.dim("Press Enter to take the first choice. Nothing changes without an answer.")}`);
70
+
71
+ const initProject = (dir: string) => {
72
+ const r = Bun.spawnSync([process.execPath, INSTALL, "--yes", "--init-project"], { cwd: dir });
73
+ if (r.exitCode === 0 && existsSync(join(dir, ".kaizen"))) { remember(dir); out(` ${c.green("+")} ${dir} is ready`); }
74
+ else out(` ${c.dim(`Could not set up ${dir}. Run kaizen setup from inside it to try again.`)}`);
75
+ };
76
+
77
+ // Project
78
+ if (project && "offer" in project) {
79
+ const { offer, git } = project;
80
+ const yes = { label: "Yes", hint: "kaizen keeps its work here: a .kaizen folder, a CLAUDE.md line", value: true };
81
+ const no = { label: "Skip", hint: "the first /kaizen run does it", value: false };
82
+ // Yes leads only in a repository: setup may be running in any folder at all.
83
+ if (await select(title(`Set up kaizen in the ${basename(offer)} folder?`), git ? [yes, no] : [no, yes])) initProject(offer);
84
+ } else if (!project) {
85
+ out(`\n ${c.bold(title("Your project"))}`);
58
86
  for (let tries = 0; tries < 2; tries++) {
59
- const typed = ui.ask(" Project folder (Enter to skip): ")?.trim();
87
+ const typed = ui.ask(" Folder of a project, or Enter to skip: ")?.trim();
60
88
  if (!typed) break;
61
89
  const dir = resolve(typed.replace(/^~(?=$|[\\/])/, home));
62
- if (dir === home || !existsSync(dir) || !statSync(dir).isDirectory()) { out(` ${c.dim(`${typed}: not a folder`)}`); continue; }
63
- const r = Bun.spawnSync([process.execPath, INSTALL, "--yes", "--init-project"], { cwd: dir });
64
- if (r.exitCode === 0 && existsSync(join(dir, ".kaizen"))) { remember(dir); out(` ${c.green("+")} set up ${dir}`); }
65
- else out(` ${c.dim(`could not set up ${dir}`)}`);
90
+ if (dir === home || !existsSync(dir) || !statSync(dir).isDirectory()) { out(` ${c.dim(`${typed} is not a project folder`)}`); continue; }
91
+ initProject(dir);
66
92
  break;
67
93
  }
68
94
  }
69
95
 
70
- // 2 -- settings
96
+ // Settings
71
97
  const defaults = readFileSync(join(import.meta.dir, "..", "skills/kaizen/config.default.yml"), "utf8");
72
98
  const file = join(home, ".kaizen", "config.yml");
73
99
  const current = existsSync(file) ? readFileSync(file, "utf8") : defaults;
74
100
  const now = detectPreset(current, defaults);
75
- const preset = await select(`2 Settings (now: ${now})`, [
76
- { label: "Keep", hint: "leave them as they are", value: null },
77
- { label: "Medium", hint: "balanced — subagents, plan approval, auto-fix high/critical", value: "medium" as const },
78
- { label: "Low", hint: "inline and manual — lite runner, manual approvals, no auto-fix", value: "low" as const },
79
- { label: "Ultra", hint: "autonomous — auto mode, auto-fix all findings", value: "ultra" as const },
80
- ]);
81
- if (preset) { writeFileSync(file, applyPreset(current, preset, defaults)); out(` ${c.green("+")} ${preset} preset in ~/.kaizen/config.yml`); }
82
- out(` ${c.dim("every setting: kaizen settings, or the gear on the board")}`);
101
+ const presets = [
102
+ { label: "Medium (recommended)", hint: "you approve the plan; serious findings get fixed for you", value: "medium" as const },
103
+ { label: "Low", hint: "cheapest; you approve every step", value: "low" as const },
104
+ { label: "Ultra", hint: "runs on its own and fixes every finding", value: "ultra" as const },
105
+ ];
106
+ // What is set now leads, so Enter keeps it.
107
+ const options = [
108
+ { label: `Keep ${now}`, hint: "your current settings", value: null },
109
+ ...presets.filter((p) => p.value !== now),
110
+ ];
111
+ const preset = await select(title("How much should kaizen ask you?"), options);
112
+ if (preset) {
113
+ mkdirSync(join(home, ".kaizen"), { recursive: true });
114
+ writeFileSync(file, applyPreset(current, preset, defaults));
115
+ out(` ${c.green("+")} ${preset} is set`);
116
+ }
83
117
 
84
- // 3 -- board
85
- out(`\n ${c.bold("3 Board")}`);
86
- run([process.execPath, INSTALL, "web", "--daemon"]);
118
+ // Kaizen App
119
+ if (await select(title("Open the Kaizen App?"), [
120
+ { label: "Yes", hint: "see your work in the browser, on this computer only", value: true },
121
+ { label: "Later", hint: "run kaizen web", value: false },
122
+ ])) run([process.execPath, INSTALL, "web", "--daemon"]);
87
123
 
88
- // 4 -- phone
89
- out(`\n ${c.bold("4 Phone")} ${c.dim("the board on your phone, over Tailscale")}`);
90
- let name: string | null = null;
91
- try { name = tailnetName(Bun.spawnSync(["tailscale", "status", "--json"]).stdout.toString()); } catch { /* not installed */ }
92
- if (!name) {
93
- out(` Tailscale is not running here. Install it on this PC and your phone (${c.cyan("https://tailscale.com/download")}),`);
94
- out(` sign in on both, then run ${c.cyan("kaizen setup")} again.\n`);
95
- return;
96
- }
97
- const yes = await select(`Run tailscale serve so your phone can reach the board?`, [
124
+ // Phone
125
+ if (await select(title("Use the Kaizen App on your phone?"), [
98
126
  { label: "Not now", hint: "nothing changes", value: false },
99
- { label: "Yes", hint: `tailscale serve --bg 127.0.0.1:${PORT} — private to your tailnet`, value: true },
100
- ]);
101
- if (!yes) { out(); return; }
102
- if (!run(["tailscale", "serve", "--bg", `127.0.0.1:${PORT}`])) { out(` ${c.dim("tailscale serve failed — see its message above")}\n`); return; }
103
- addWebHost(name);
104
- const url = `https://${name}`;
105
- out(`\n${qr(url)}\n\n Scan with your phone camera, or open ${c.cyan(url)}`);
106
- out(` Then choose Add to Home screen: it opens full screen with the kaizen icon.`);
107
- out(` ${c.dim("Anyone on your tailnet who can reach this PC can drive your agents; restrict it with Tailscale ACLs.")}\n`);
127
+ { label: "Yes", hint: "private to your own devices, through Tailscale", value: true },
128
+ ])) {
129
+ if (!tailnet) {
130
+ out(`\n The phone connects through Tailscale, a free private network.`);
131
+ out(` 1 Install it on this computer: ${c.accent(TAILSCALE)}`);
132
+ out(` 2 Install it on your phone too, from the same link`);
133
+ out(` 3 Sign in on both with the same account`);
134
+ }
135
+ while (!tailnet) {
136
+ if (!await select("Tailscale ready on both?", [
137
+ { label: "Check again", hint: "see if Tailscale is running here", value: true },
138
+ { label: "Skip for now", hint: "run kaizen setup when it is ready", value: false },
139
+ ])) break;
140
+ tailnet = tailnetNow();
141
+ if (!tailnet) out(` ${c.dim("Tailscale is not running on this computer yet.")}`);
142
+ else out(` ${c.green("+")} Tailscale is running`);
143
+ }
144
+ if (tailnet && run(["tailscale", "serve", "--bg", `127.0.0.1:${PORT}`])) {
145
+ addWebHost(tailnet);
146
+ const url = `https://${tailnet}`;
147
+ out(`\n${qr(url)}\n\n Scan with your phone camera, or open ${c.accent(url)}`);
148
+ out(` Then choose Add to Home screen: it opens full screen with the kaizen icon.`);
149
+ out(` ${c.dim("Anyone on your tailnet who can reach this PC can drive your agents; restrict it with Tailscale ACLs.")}`);
150
+ } else if (tailnet) out(` ${c.dim("tailscale serve failed; see its message above")}`);
151
+ }
152
+
153
+ // Failing to make a shortcut must not spoil a finished setup; web prints what happened.
154
+ // From the install, not this file: under bunx this file is a temp copy that goes away.
155
+ const installed = join(process.env.KAIZEN_HOME ?? join(home, "kaizen"), "cli", "install.ts");
156
+ run([process.execPath, existsSync(installed) ? installed : INSTALL, "web", "--shortcut"]);
157
+ out(nextSteps());
108
158
  }
package/cli/sources.ts CHANGED
@@ -135,7 +135,7 @@ const isCommand = (t: string) => COMMANDS.has((/[a-z][a-z-]*/i.exec(t.split(" ")
135
135
  // drops a `<where> - <severity> -` or `<severity>:` lead and every backtick. The
136
136
  // check is on that final text, whatever parseItem did to get there; the kind the
137
137
  // user chose, when it is still in front, is theirs and set aside.
138
- const obeyed = (t: string) => isCommand(t) || ["", "full ", "lite "].some((kind) => {
138
+ export const obeyed = (t: string) => isCommand(t) || ["", "full ", "lite "].some((kind) => {
139
139
  const sent = parseItem(kind + t).text;
140
140
  return isCommand(kind && sent.startsWith(kind) ? sent.slice(kind.length) : sent);
141
141
  });
package/cli/state.test.ts CHANGED
@@ -1607,3 +1607,10 @@ test("a git that can't answer is not reported as no repo", () => {
1607
1607
  process.env.PATH = `${dir}${process.platform === "win32" ? ";" : ":"}${path}`;
1608
1608
  try { expect(gitStatus(dir)).toEqual({ repo: false, failed: true }); } finally { process.env.PATH = path; }
1609
1609
  });
1610
+
1611
+ test("a tool's Settings model reaches its launch flag, ahead of a hand-written block", () => {
1612
+ expect(agentFlags("/x", "codex", 'agent:\n default: auto\n model:\n agy: ""\n codex: gpt-x\n')).toEqual(["-m", "gpt-x"]);
1613
+ expect(agentFlags("/x", "agy", 'agent:\n model:\n agy: ""\n codex: gpt-x\n')).toEqual([]);
1614
+ expect(agentFlags("/x", "codex", "agent:\n codex: { model: old, effort: low }\n model:\n codex: new\n")).toEqual(["-m", "new", "-c", "model_reasoning_effort=low"]);
1615
+ expect(agentFlags("/x", "codex", "agent:\n codex: { model: old }\n")).toEqual(["-m", "old"]);
1616
+ });
package/cli/state.ts CHANGED
@@ -112,7 +112,11 @@ function agentConfig(projectDir: string, cmd: string, configText?: string) {
112
112
  let block: RegExpExecArray | null = null;
113
113
  for (const t of configText === undefined ? configTexts(projectDir) : [configText]) if ((block = re.exec(t))) break;
114
114
  const get = (k: string) => block && new RegExp(`\\b${k}:[ \\t]*["']?([^"',}\\s]+)`).exec(block[1])?.[1];
115
- return { model: get("model") || undefined, effort: get("effort") || undefined };
115
+ // Settings' row (agent.model.<tool>) wins over a hand-written block.
116
+ const row = new RegExp(`^agent:\\n(?:[ \\t#][^\\n]*\\n|\\n)*?[ \\t]+model:[ \\t]*\\n(?:[ \\t]{3,}[^\\n]*\\n)*?[ \\t]{3,}${cmd}:[ \\t]*["']?([^"'\\s#]+)`, "m");
117
+ let set: string | undefined;
118
+ for (const t of configText === undefined ? configTexts(projectDir) : [configText]) if ((set = row.exec(t)?.[1])) break;
119
+ return { model: set || get("model") || undefined, effort: get("effort") || undefined };
116
120
  }
117
121
 
118
122
  // `model`: a per-run pick, in place of the configured one. Effort stays configured.
@@ -772,9 +776,15 @@ export function markBacklogDone(state: string) {
772
776
 
773
777
  // ---------------------------------------------------------------- board data
774
778
 
779
+ export type Land = { kind: "conflict" | "check" | "merge"; why: string; paths?: string[]; term?: string; at?: number };
780
+ const readLand = (st: string, id: string): Land | undefined => {
781
+ try { const l = JSON.parse(readFileSync(join(st, "runs", id, "land.json"), "utf8")); return typeof l?.kind === "string" ? l : undefined; } catch { return undefined; }
782
+ };
775
783
  export type Card = {
776
784
  kind: "idea" | "run";
777
785
  id?: string; // runs only: the directory name
786
+ handoff?: string; // runs only: how a handoff ended, when its first agent is gone
787
+ land?: Land; // runs only: what stopped the last land (land.json)
778
788
  stage?: string; // runs only: the stage word
779
789
  iteration?: number; // runs only: the fix round
780
790
  status: string; // what the legend calls this card
@@ -1021,7 +1031,7 @@ const NEED: Record<string, string> = {
1021
1031
  };
1022
1032
  export function notice(c: Card): string | null {
1023
1033
  if (c.kind !== "run") return null;
1024
- const what = c.awaiting ? NEED[c.awaiting] ?? `waiting on ${c.awaiting}` : c.status === "done" ? (c.accept === "needs" ? "done, not approved" : "done") : null;
1034
+ const what = c.land ? (c.land.kind === "conflict" ? `conflict: ${c.land.paths?.join(", ") || c.land.why}` : `land failed: ${c.land.why}`) : c.handoff ? `the worktree agent ended (${c.handoff}): tell the first agent, or review it here` : c.awaiting ? NEED[c.awaiting] ?? `waiting on ${c.awaiting}` : c.status === "done" ? (c.accept === "needs" ? "done, not approved" : "done") : null;
1025
1035
  return what && `${c.text} — ${what}\n${c.where}`;
1026
1036
  }
1027
1037
 
@@ -1291,6 +1301,7 @@ export function boardCards(states: string[], now: number): Card[] {
1291
1301
  notes: readNotes(st, r.id) || undefined,
1292
1302
  parent: parentOf(body(st, r.id)),
1293
1303
  ...(r.healed ? { healed: true } : {}),
1304
+ ...((land) => land ? { land } : {})(readLand(st, r.id)),
1294
1305
  ...(r.stage === "done" ? accepted(st, r.id) : {}),
1295
1306
  });
1296
1307
  }
package/cli/usage.test.ts CHANGED
@@ -82,6 +82,17 @@ test.skipIf(process.platform === "win32")("/shell: foreign origin, unknown proje
82
82
  expect((await post({ dir: st }, "http://localhost:3000")).status).toBe(403);
83
83
  // A simple (no-preflight) POST body type.
84
84
  expect((await post({ dir: st }, at, "text/plain")).status).toBe(415);
85
+ const kill = (body: object, origin?: string, type = "application/json") => fetch(at + "/pty/kill", { method: "POST", headers: { "content-type": type, ...(origin ? { origin } : {}) }, body: JSON.stringify(body) });
86
+ expect((await kill({ key: "x" }, "https://evil.example")).status).toBe(403);
87
+ expect((await kill({ key: "x" }, at, "text/plain")).status).toBe(415);
88
+ expect((await kill({ key: "no-such" }, at)).status).toBe(404);
89
+ expect((await kill({ key: "../x" }, at)).status).toBe(404);
90
+ const res = await (await fetch(at + "/resources")).json();
91
+ expect(res.system.total).toBeGreaterThan(0);
92
+ expect(res.kaizen).toBeGreaterThan(0);
93
+ const disk = await fetch(at + "/resources/storage");
94
+ expect(disk.status).toBe(200);
95
+ expect(typeof (await disk.json()).scanning).toBe("boolean");
85
96
  expect((await post({ dir: join(root, "elsewhere", ".kaizen") })).status).toBe(404);
86
97
  expect((await post({ dir: join(homeDir, ".kaizen") })).status).toBe(404);
87
98
  expect((await post({ dir: st, agent: "rm -rf /" })).status).toBe(400);