kaizen-agent 1.59.1 → 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 (60) 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/phone.ts +26 -3
  41. package/web/board/projects.ts +6 -85
  42. package/web/board/run-pick.ts +41 -0
  43. package/web/board/run-view.ts +261 -104
  44. package/web/board/settings.ts +42 -5
  45. package/web/board/store.ts +3 -1
  46. package/web/board/toast.ts +4 -1
  47. package/web/board/views.ts +6 -2
  48. package/web/board/workspace.ts +125 -38
  49. package/web/board/ws-board-ui.ts +84 -0
  50. package/web/board/ws-board.test.ts +71 -0
  51. package/web/board/ws-board.ts +45 -0
  52. package/web/board/ws-tabs.test.ts +171 -0
  53. package/web/board/ws-tabs.ts +170 -0
  54. package/web/board.html +92 -43
  55. package/web/board.js +44 -43
  56. package/web/notebook.js +24 -25
  57. package/web/notes.html +26 -21
  58. package/web/term.js +1 -1
  59. package/web/video.html +26 -21
  60. package/web/video.js +56 -57
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 = { 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 };
14
+ type Pty = { 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 };
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.
@@ -21,6 +21,17 @@ const KEEP_MS = 10 * 60_000;
21
21
 
22
22
  const ptys = new Map<string, Pty>();
23
23
 
24
+ // What the sidebar shows for an agent: the latest line the agent printed. Keystrokes are never kept,
25
+ // and nothing is read while a question is open or within ECHO_MS of a keystroke: a terminal echoes
26
+ // what is typed, so that line could be a password. Memory only.
27
+ const ECHO_MS = 1500;
28
+ const grab = (p: Pty, text: string, every: number) => {
29
+ const now = Date.now();
30
+ if (p.asking || now - p.typedAt < ECHO_MS || now - p.lastAt < every) return;
31
+ const l = lastLine(text);
32
+ if (l) { p.last = l; p.lastAt = now; }
33
+ };
34
+
24
35
  // A question the agent stopped on: Claude Code's and Codex's approval and choice prompts.
25
36
  // ponytail: screen-text heuristic, misses a prompt worded otherwise; read agent hooks if that bites.
26
37
  const ASK = /Would you like to|Do you want to|[❯›>] ?1\. |Type something|\(y\/n\)|\[y\/N\]|Press enter to/i;
@@ -38,7 +49,37 @@ export const asking = (screen: string) => {
38
49
  return q >= 0 && q > lastAt(WORK, t);
39
50
  };
40
51
  // How long output stays still before the screen is read for a question.
41
- const QUIET_MS = 700;
52
+ export const QUIET_MS = 700;
53
+ // The latest meaningful line of some terminal output, for the sidebar card: escape sequences, box
54
+ // drawing, spinners and the TUI's own footer lines out. "" when nothing readable is left.
55
+ // ponytail: screen-text heuristic over raw chunks; a TUI that repaints oddly shows an older line.
56
+ const CHROME = new RegExp(WORK.source + "|\\? for shortcuts|shift\\+tab|ctrl\\+[a-z]|\\besc to\\b|tokens\\)|bypass permissions", "i");
57
+ // Only the agent's own reply lines, never a guess about what is input: a line counts only when it
58
+ // starts with a reply marker the agent draws itself (Claude Code "⏺", Codex "•", Gemini "✦").
59
+ // Typed or pasted text never starts with one, so nothing typed can be shown; a plain shell or an
60
+ // unknown agent gives "" and its card shows status only. Lines inside an input box (╰ … ╭, read
61
+ // bottom-up) or between two horizontal rules are skipped as well; a tool call shows its name only.
62
+ // ponytail: the marker list is per agent; an agent that changes its marker shows status only.
63
+ const REPLY = /^[⏺•✦]\s+(.*)$/;
64
+ export const lastLine = (t: string) => {
65
+ const s = t.replace(/\x1b\[[0-9;?]*[A-Za-z]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[()][0-9A-Za-z]/g, " ");
66
+ let box = false,
67
+ rule = false;
68
+ for (const line of s.split(/[\r\n]+/).reverse()) {
69
+ const raw = line.replace(/[\x00-\x1f\x7f]/g, " ").trim();
70
+ if (box) { if (raw.startsWith("╭")) box = false; continue; }
71
+ if (raw.startsWith("╰") && !/[\p{L}\p{N}]/u.test(raw)) { box = true; continue; }
72
+ // An input area drawn between two horizontal rules (newer Claude Code, no box): skip up to the rule above.
73
+ if (/^─{3,}$/.test(raw.replace(/\s/g, ""))) { rule = !rule; continue; }
74
+ if (rule) continue;
75
+ const m = REPLY.exec(raw);
76
+ if (!m) continue;
77
+ // A tool call shows only its name: "Bash(curl … Bearer sk-…)" -> "Bash", never its arguments.
78
+ const l = m[1].replace(/^([\w .-]{1,40})\(.*$/, "$1").replace(/[\u2500-\u259f\u2800-\u28ff✻✶✳✢✽✺●○◐◑◒◓⏺⎿⏵▪▫■□]/g, " ").replace(/\s+/g, " ").trim();
79
+ if (/[\p{L}\p{N}].*[\p{L}\p{N}].*[\p{L}\p{N}]/u.test(l) && !CHROME.test(l)) return l.slice(0, 80);
80
+ }
81
+ return "";
82
+ };
42
83
  // Bun gained pseudo-terminals in 1.3.5; an older one spawns without a tty, so it
43
84
  // keeps opening terminal windows.
44
85
  export const ptySupported = WIN || typeof (Bun as any).Terminal === "function";
@@ -46,9 +87,14 @@ export const ptySupported = WIN || typeof (Bun as any).Terminal === "function";
46
87
  // Starts cmd in a new pseudo-terminal under `key` and returns its PID. pidFile gets
47
88
  // that PID, the agent's own, so closeSessions can end it like any launched session.
48
89
  // onChange: called when the agent ends or starts or stops asking, so the board can redraw.
49
- export function startPty(key: string, cmd: string[], cwd: string, pidFile?: string, onChange?: () => void): number {
90
+ // seed: what the card showed before the board restarted, replayed ahead of the new output.
91
+ // tmux: run cmd inside a tmux session of that name on kaizen's own server (tmuxCmd), which
92
+ // outlives the board; null where tmux cannot be used, and the agent runs plainly.
93
+ export function startPty(key: string, cmd: string[], cwd: string, pidFile?: string, onChange?: () => void, opts: { seed?: string; tmux?: string; attach?: boolean } = {}): number {
50
94
  const dec = new TextDecoder();
51
- const p: Pty = { proc: null as unknown as Bun.Subprocess, out: [], size: 0, listeners: new Set(), exit: null, asking: false, busy: false, total: 0, since: 0, onChange };
95
+ const p: Pty = { proc: null as unknown as Bun.Subprocess, out: opts.seed ? [opts.seed] : [], size: opts.seed?.length ?? 0, listeners: new Set(), exit: null, asking: false, busy: false, total: 0, since: 0, onChange, last: "", lastAt: 0, typedAt: 0, born: Date.now() };
96
+ // attach: the session already runs (kept from a board before this one); only a client is started.
97
+ if (opts.tmux && tmuxOk()) cmd = opts.attach ? attachCmd(opts.tmux) : tmuxCmd(opts.tmux, cmd);
52
98
  const flag = (v: boolean) => { if (p.asking !== v) { p.asking = v; onChange?.(); } };
53
99
  // busy: output in the last QUIET_MS. A working agent redraws its spinner many times a second,
54
100
  // so a quiet terminal is one waiting at its prompt.
@@ -60,9 +106,12 @@ export function startPty(key: string, cmd: string[], cwd: string, pidFile?: stri
60
106
  while (p.size > CAP && p.out.length > 1) p.size -= p.out.shift()!.length;
61
107
  for (const f of p.listeners) f(d);
62
108
  work(p.exit === null);
109
+ grab(p, d, 1000);
63
110
  clearTimeout(p.quiet);
64
111
  p.quiet = setTimeout(() => {
65
112
  work(false);
113
+ const tail = p.out.slice(-8).join("").slice(-4096);
114
+ grab(p, tail, 0);
66
115
  // Only what came after the user's last keystroke: a question already answered may still be in the tail.
67
116
  const n = Math.min(4096, p.total - p.since);
68
117
  flag(p.exit === null && n > 0 && asking(p.out.join("").slice(-n)));
@@ -87,8 +136,22 @@ export function startPty(key: string, cmd: string[], cwd: string, pidFile?: stri
87
136
  env: { ...process.env, TERM: "xterm-256color", COLORTERM: "truecolor" },
88
137
  terminal: { cols: 120, rows: 32, data: (_t, d) => push(dec.decode(d, { stream: true })) },
89
138
  });
139
+ if (opts.tmux && cmd[0] === tmuxBin()) p.tmux = opts.tmux;
90
140
  ptys.set(key, p);
91
141
  if (pidFile) writeFileSync(pidFile, String(p.proc.pid));
142
+ // A tmux-kept agent's PID is the pane's, not the client's: the client is gone after a
143
+ // board restart, and its arguments never name the agent, so closeSessions would not
144
+ // know an attached client for the run's agent and could not end it.
145
+ if (pidFile && p.tmux) {
146
+ const name = p.tmux;
147
+ (async () => {
148
+ for (let i = 0; i < 40 && p.exit === null; i++) {
149
+ const pane = panePid(name);
150
+ if (pane) { try { writeFileSync(pidFile, String(pane)); } catch { /* record gone */ } return; }
151
+ await Bun.sleep(50);
152
+ }
153
+ })();
154
+ }
92
155
  p.proc.exited.then((code) => {
93
156
  p.exit = code;
94
157
  clearTimeout(p.quiet);
@@ -97,6 +160,10 @@ export function startPty(key: string, cmd: string[], cwd: string, pidFile?: stri
97
160
  for (const f of p.listeners) f(null);
98
161
  p.listeners.clear();
99
162
  try { p.proc.terminal?.close(); } catch { /* already closed */ }
163
+ // What the agent started and left behind (a test run, a dev server) goes with it. The
164
+ // pty made it a session and group leader, so its group id is its PID; a tmux client's
165
+ // group holds only the client, never the tmux server the agent runs under.
166
+ if (!WIN) { try { process.kill(-p.proc.pid, "SIGTERM"); } catch { /* group already empty */ } }
100
167
  // Dropped: pages showing it (the Terminal page) refresh, or its tile lingers until some other change.
101
168
  setTimeout(() => { if (ptys.get(key) === p) { ptys.delete(key); onChange?.(); } }, KEEP_MS).unref();
102
169
  onChange?.();
@@ -125,6 +192,7 @@ export function writePty(key: string, d: string) {
125
192
  if (!p || p.exit !== null) return;
126
193
  if (d.replace(REPORT, "")) {
127
194
  p.since = p.total;
195
+ p.typedAt = Date.now();
128
196
  if (p.asking) { p.asking = false; p.onChange?.(); }
129
197
  }
130
198
  send(p, d);
@@ -142,10 +210,58 @@ export function exitPty(key: string, grace = 5000): boolean {
142
210
  if (!p || p.exit !== null) return false;
143
211
  send(p, "\x1b");
144
212
  setTimeout(() => send(p, "/exit\r"), 100);
145
- setTimeout(() => { if (p.exit === null) p.proc.kill(); }, grace).unref();
213
+ setTimeout(() => {
214
+ if (p.exit === null) { if (WIN) p.proc.kill(); else { try { process.kill(-p.proc.pid, "SIGKILL"); } catch { p.proc.kill(); } } }
215
+ if (p.tmux) killTmux(p.tmux);
216
+ }, grace).unref();
217
+ return true;
218
+ }
219
+
220
+ // The board stopping with a tmux-kept agent: only its client ends, the agent keeps running
221
+ // in kaizen's tmux server, and the next board attaches to it (attachCmd).
222
+ export function detachPty(key: string): boolean {
223
+ const p = ptys.get(key);
224
+ if (!p || p.exit !== null || !p.tmux) return false;
225
+ p.proc.kill();
146
226
  return true;
147
227
  }
148
228
 
229
+ // The last n characters the session printed, from a line start, for the next board to show.
230
+ export function ptyTail(key: string, n = 64 * 1024): string | null {
231
+ const p = ptys.get(key);
232
+ if (!p || !p.out.length) return null;
233
+ const t = p.out.join("").slice(-n);
234
+ return t.length < n ? t : t.slice(t.indexOf("\n") + 1);
235
+ }
236
+ export const ptyTmux = (key: string) => ptys.get(key)?.tmux ?? null;
237
+
238
+ // The line a resumed card shows below what the agent printed before the board restarted.
239
+ export const RESUMED = "\r\n\x1b[0m\x1b[2m— board restarted · agent resumed · the step it was on was cut off —\x1b[0m\r\n";
240
+
241
+ // tmux keep-alive (agent.keep_alive: tmux). A server of kaizen's own (-L kaizen) with no
242
+ // user config (-f /dev/null), so the user's sessions and key bindings are never touched:
243
+ // no status bar, no prefix key, Escape passed at once. Not on Windows, which has no tmux.
244
+ const TMUX = ["-L", "kaizen", "-f", "/dev/null"];
245
+ const tmuxBin = () => (WIN ? null : Bun.which("tmux"));
246
+ export const tmuxOk = () => !!tmuxBin();
247
+ export const tmuxName = (key: string) => `kz-${key.replace(/[^\w-]/g, "_")}`;
248
+ // PATH from this board, not the tmux server's own: the server keeps the environment of
249
+ // whichever board started it.
250
+ export const tmuxCmd = (name: string, cmd: string[]) => [tmuxBin()!, ...TMUX, "new-session", "-A", "-s", name, "-x", "120", "-y", "32", "-e", `PATH=${process.env.PATH ?? ""}`, ...cmd,
251
+ ";", "set", "-g", "status", "off", ";", "set", "-g", "prefix", "None", ";", "set", "-g", "escape-time", "0",
252
+ ";", "set", "-as", "terminal-features", ",xterm-256color:RGB"];
253
+ export const attachCmd = (name: string) => [tmuxBin()!, ...TMUX, "attach-session", "-t", name];
254
+ const tmux = (...a: string[]) => {
255
+ const bin = tmuxBin();
256
+ try { return !!bin && Bun.spawnSync([bin, ...TMUX, ...a], { stdin: "ignore", stdout: "ignore", stderr: "ignore", timeout: 3000 }).exitCode === 0; } catch { return false; }
257
+ };
258
+ export const tmuxAlive = (name: string) => tmux("has-session", "-t", `=${name}`);
259
+ export const panePid = (name: string): number | null => {
260
+ const bin = tmuxBin();
261
+ try { return bin ? Number(Bun.spawnSync([bin, ...TMUX, "display-message", "-p", "-t", `=${name}:`, "#{pane_pid}"], { stdin: "ignore", stderr: "ignore", timeout: 3000 }).stdout.toString().trim()) || null : null; } catch { return null; }
262
+ };
263
+ export const killTmux = (name: string) => tmux("kill-session", "-t", `=${name}`);
264
+
149
265
  export function resizePty(key: string, cols: number, rows: number) {
150
266
  const p = ptys.get(key);
151
267
  const c = Math.max(10, Math.min(500, cols | 0)), r = Math.max(5, Math.min(300, rows | 0));
@@ -156,7 +272,7 @@ export const ptyKeys = () => [...ptys.keys()];
156
272
 
157
273
  export const ptyState = (key: string) => {
158
274
  const p = ptys.get(key);
159
- return p ? { alive: p.exit === null, exit: p.exit, asking: p.asking, busy: p.busy } : null;
275
+ return p ? { 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 } : null;
160
276
  };
161
277
 
162
278
  // The environment the user's login shell builds: PATH and anything exported in their
@@ -0,0 +1,169 @@
1
+ // A board that stops or dies with agents running in their cards: the next board starts
2
+ // them again (once, after a crash) with their last screen, ends what they left behind,
3
+ // and with agent.keep_alive: tmux attaches to the same agent instead.
4
+ import { test, expect } from "bun:test";
5
+ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, realpathSync } from "node:fs";
6
+ import { tmpdir } from "node:os";
7
+ import { join } from "node:path";
8
+ import { startPty, exitPty, ptyState, tmuxOk, tmuxName, tmuxAlive, killTmux, detachPty, attachPty, panePid } from "./pty.ts";
9
+ import { keepAlive } from "./state.ts";
10
+
11
+ const root = realpathSync(mkdtempSync(join(tmpdir(), "kaizen-restart-")));
12
+ const posix = process.platform !== "win32";
13
+ const gone = async (pid: number) => { for (let i = 0; i < 100; i++) { try { process.kill(pid, 0); await Bun.sleep(30); } catch { return true; } } return false; };
14
+
15
+ test("agent.keep_alive: off unless the config chain says tmux", () => {
16
+ const p = join(root, "keep");
17
+ mkdirSync(join(p, ".kaizen"), { recursive: true });
18
+ writeFileSync(join(p, ".kaizen", "config.yml"), "agent:\n launch: card\n # kept\n keep_alive: tmux\n");
19
+ expect(keepAlive(p)).toBe("tmux");
20
+ writeFileSync(join(p, ".kaizen", "config.yml"), "agent.keep_alive: off\n");
21
+ expect(keepAlive(p)).toBe("off");
22
+ });
23
+
24
+ // G-04: what the agent started goes with it, whether it is ended or ends by itself.
25
+ test.skipIf(!posix)("an ended card agent takes the processes it started with it", async () => {
26
+ for (const [key, how] of [["kids-ended", "ended"], ["kids-exit", "exit"]] as const) {
27
+ const pidFile = join(root, `${key}.child`);
28
+ // nohup: the pty's hangup alone would not end it, as with a dev server.
29
+ startPty(key, ["sh", "-c", `nohup sleep 300 >/dev/null 2>&1 & echo $! > ${pidFile}; read l; read l`], root);
30
+ for (let i = 0; i < 100 && !existsSync(pidFile); i++) await Bun.sleep(20);
31
+ const child = Number(readFileSync(pidFile, "utf8"));
32
+ if (how === "ended") exitPty(key, 200);
33
+ else { const { writePty } = await import("./pty.ts"); writePty(key, "a\r"); writePty(key, "b\r"); }
34
+ for (let i = 0; i < 100 && ptyState(key)!.alive; i++) await Bun.sleep(30);
35
+ expect(await gone(child)).toBe(true);
36
+ }
37
+ });
38
+
39
+ // G-06: a kept agent outlives its client, a new client sees it, closing ends it; the
40
+ // user's own tmux server is never asked anything.
41
+ test.skipIf(!posix || !tmuxOk())("tmux keep-alive: detach keeps the agent, attach shows it, exit ends it", async () => {
42
+ const name = tmuxName(`t${Date.now()}`), mark = join(root, "tmux.count");
43
+ const pidFile = join(root, "kept.pid"), argsOf = (pid: number) => Bun.spawnSync(["ps", "-o", "args=", "-p", String(pid)]).stdout.toString();
44
+ // The board's PATH reaches the agent even though the tmux server may be older than it.
45
+ process.env.PATH = `/kz-path-mark:${process.env.PATH}`;
46
+ startPty("kept", ["sh", "-c", `echo $PATH > ${mark}.path; i=0; while true; do i=$((i+1)); echo $i > ${mark}; echo tick$i; sleep 0.1; done`], root, pidFile, undefined, { tmux: name });
47
+ process.env.PATH = process.env.PATH.replace("/kz-path-mark:", "");
48
+ try {
49
+ for (let i = 0; i < 100 && !existsSync(mark); i++) await Bun.sleep(30);
50
+ expect(readFileSync(`${mark}.path`, "utf8")).toContain("/kz-path-mark");
51
+ // The pid file holds the agent in the pane, so closeSessions knows it (isSession reads its args).
52
+ for (let i = 0; i < 50 && Number(readFileSync(pidFile, "utf8")) !== panePid(name); i++) await Bun.sleep(30);
53
+ expect(Number(readFileSync(pidFile, "utf8"))).toBe(panePid(name)!);
54
+ expect(argsOf(panePid(name)!)).toContain("tick$i");
55
+ expect(detachPty("kept")).toBe(true);
56
+ for (let i = 0; i < 100 && ptyState("kept")!.alive; i++) await Bun.sleep(30);
57
+ expect(ptyState("kept")!.alive).toBe(false);
58
+ expect(tmuxAlive(name)).toBe(true);
59
+ const before = Number(readFileSync(mark, "utf8"));
60
+ await Bun.sleep(400);
61
+ expect(Number(readFileSync(mark, "utf8"))).toBeGreaterThan(before); // kept working with no client
62
+ startPty("kept2", [], root, pidFile, undefined, { tmux: name, attach: true });
63
+ let seen = "";
64
+ attachPty("kept2", (d) => { if (d) seen += d; });
65
+ for (let i = 0; i < 100 && !/tick\d+/.test(seen); i++) await Bun.sleep(30);
66
+ expect(seen).toMatch(/tick\d+/);
67
+ // Reattached: still the agent's PID, never the new client's.
68
+ for (let i = 0; i < 50 && !argsOf(Number(readFileSync(pidFile, "utf8"))).includes("tick$i"); i++) await Bun.sleep(30);
69
+ expect(argsOf(Number(readFileSync(pidFile, "utf8")))).toContain("tick$i");
70
+ exitPty("kept2", 200);
71
+ for (let i = 0; i < 100 && tmuxAlive(name); i++) await Bun.sleep(30);
72
+ expect(tmuxAlive(name)).toBe(false);
73
+ // Only kaizen's own server: the default socket never got this session.
74
+ expect(Bun.spawnSync(["tmux", "has-session", "-t", `=${name}`], { stderr: "ignore" }).exitCode).not.toBe(0);
75
+ } finally { killTmux(name); }
76
+ });
77
+
78
+ // G-01, G-02, G-09: the real board, stopped and killed, with a fake agent in a card.
79
+ test.skipIf(!posix)("a stopped or crashed board resumes its card agents, once after a crash, showing the last screen", async () => {
80
+ const homeDir = join(root, "home"), proj = join(homeDir, "a"), st = join(proj, ".kaizen"), bin = join(root, "bin");
81
+ for (const d of [st, join(homeDir, ".kaizen"), join(homeDir, ".claude"), bin]) mkdirSync(d, { recursive: true });
82
+ writeFileSync(join(homeDir, ".kaizen", "projects"), proj + "\n");
83
+ writeFileSync(join(st, "config.yml"), "agent:\n default: claude\n launch: card\n");
84
+ writeFileSync(join(bin, "claude"), '#!/bin/sh\necho "args:$*"\nwhile read x; do echo "got:$x"; done\n', { mode: 0o755 });
85
+ const repo = join(import.meta.dir, "..");
86
+ const port = 20000 + Math.floor(Math.random() * 20000), at = `http://127.0.0.1:${port}`;
87
+ let out = "";
88
+ const board = () => {
89
+ const p = Bun.spawn([process.execPath, join(repo, "cli", "install.ts"), "web", "--port", String(port), "--no-open", "--foreground"], {
90
+ cwd: proj, stdout: "pipe", stderr: "ignore",
91
+ env: { ...process.env, HOME: homeDir, USERPROFILE: homeDir, KAIZEN_HOME: repo, CLAUDE_CONFIG_DIR: join(homeDir, ".claude"),
92
+ PATH: `${bin}:/usr/bin:/bin`, SHELL: "/bin/false", DISPLAY: "", WAYLAND_DISPLAY: "", TERMINAL: "", TMUX: "" },
93
+ });
94
+ (async () => { for await (const c of p.stdout) out += new TextDecoder().decode(c); })();
95
+ return p;
96
+ };
97
+ const up = async () => { for (let i = 0; ; i++) { try { await fetch(at + "/state"); return; } catch { if (i > 150) throw new Error("board did not start"); await Bun.sleep(50); } } };
98
+ const screen = async (key: string, re: RegExp) => {
99
+ let seen = "";
100
+ const ws = new WebSocket(`${at}/pty?key=${key}`.replace("http", "ws"), { headers: { origin: at } } as any);
101
+ ws.onmessage = (e) => { seen += String(e.data); };
102
+ await new Promise((ok, no) => { ws.onopen = ok; ws.onerror = no; });
103
+ for (let i = 0; i < 100 && !re.test(seen); i++) await Bun.sleep(30);
104
+ ws.close();
105
+ return seen;
106
+ };
107
+ const liveKey = async () => ((await (await fetch(at + "/state")).json()) as any).cards.find((c: any) => c.id === "r1")?.pty?.key as string | undefined;
108
+
109
+ let b = board();
110
+ try {
111
+ await up();
112
+ const r = await (await fetch(at + "/run", { method: "POST", body: JSON.stringify({ dir: st, text: "say hello" }) })).json() as any;
113
+ expect(r.ok).toBe(true);
114
+ // The run that launch became, in its build stage, with its conversation on disk.
115
+ mkdirSync(join(st, "runs", "r1"), { recursive: true });
116
+ writeFileSync(join(st, "runs", "r1", "00-request.md"), "say hello\n");
117
+ writeFileSync(join(st, "runs", "r1", "state.json"), JSON.stringify({ id: "r1", stage: "build", awaiting: null }));
118
+ const sid = JSON.parse(readFileSync(join(st, "sessions", r.pty + ".json"), "utf8")).sessionId;
119
+ const tr = join(homeDir, ".claude", "projects", proj.replace(/[^A-Za-z0-9]/g, "-"));
120
+ mkdirSync(tr, { recursive: true });
121
+ writeFileSync(join(tr, sid + ".jsonl"), "{}\n");
122
+ const ws = new WebSocket(`${at}/pty?key=${r.pty}`.replace("http", "ws"), { headers: { origin: at } } as any);
123
+ await new Promise((ok, no) => { ws.onopen = ok; ws.onerror = no; });
124
+ ws.send(JSON.stringify({ t: "i", d: "first-screen\r" }));
125
+ await screen(r.pty, /got:first-screen/);
126
+ const agent = Number(readFileSync(join(st, "sessions", r.pty + ".pid"), "utf8"));
127
+
128
+ // An orderly stop (systemd, Ctrl-C): the agent is ended, the list and screen kept.
129
+ b.kill("SIGTERM");
130
+ await b.exited;
131
+ expect(await gone(agent)).toBe(true);
132
+ const list = JSON.parse(readFileSync(join(homeDir, ".kaizen", "resume-after-upgrade.json"), "utf8"));
133
+ expect(list).toMatchObject({ crash: false, list: [{ key: r.pty, run: "r1" }] });
134
+
135
+ b = board();
136
+ await up();
137
+ const k2 = await liveKey();
138
+ expect(k2).toBeTruthy();
139
+ const seen = await screen(k2!, new RegExp(`--resume ${sid}`));
140
+ expect(seen).toMatch(/got:first-screen[\s\S]*board restarted · agent resumed[\s\S]*--resume/);
141
+ expect(out).toMatch(/resumed r1/);
142
+
143
+ // A crash: no stop runs, yet the list kept current while it ran resumes it once.
144
+ await Bun.sleep(3500);
145
+ b.kill("SIGKILL");
146
+ await b.exited;
147
+ expect(JSON.parse(readFileSync(join(homeDir, ".kaizen", "resume-after-upgrade.json"), "utf8")).crash).toBe(true);
148
+ out = "";
149
+ b = board();
150
+ await up();
151
+ expect(await liveKey()).toBeTruthy();
152
+ expect(out).toMatch(/resumed r1/);
153
+ // Dying again right after that resume: the next board leaves it on its Resume button.
154
+ await Bun.sleep(3500);
155
+ expect(JSON.parse(readFileSync(join(homeDir, ".kaizen", "resume-after-upgrade.json"), "utf8")).list[0].resumed).toBeGreaterThan(0);
156
+ b.kill("SIGKILL");
157
+ await b.exited;
158
+ out = "";
159
+ b = board();
160
+ await up();
161
+ await Bun.sleep(300);
162
+ expect(out).toMatch(/not resuming r1/);
163
+ expect(await liveKey()).toBeFalsy();
164
+ } finally {
165
+ b.kill("SIGKILL");
166
+ // The fake agents of the killed boards: ended so nothing outlives the test.
167
+ Bun.spawnSync(["pkill", "-f", `${bin}/claude`]);
168
+ }
169
+ }, 40_000);
@@ -96,3 +96,38 @@ test("a low-preset config saved before review.executor existed still reads as lo
96
96
  expect(old).not.toContain("executor: inline\n # Let");
97
97
  expect(detectPreset(old, text)).toBe("low");
98
98
  });
99
+
100
+ test("a project scope reads over All projects, starts its own file empty, and resets a key back", () => {
101
+ const other = join(home, "Projects", "other");
102
+ mkdirSync(join(other, ".kaizen"), { recursive: true });
103
+ writeFileSync(join(home, ".kaizen", "projects"), `${project}\n${other}\n`);
104
+ const r = inProject(`
105
+ const at = (p, k) => listSettings(repo, p).rows.find((r) => r.key === k);
106
+ const other = ${JSON.stringify(other)};
107
+ setSetting(repo, "git.auto_commit", "true", null);
108
+ const before = at(other, "git.auto_commit");
109
+ setSetting(repo, "git.auto_commit", "false", other);
110
+ const file = (await Bun.file(other + "/.kaizen/config.yml").text());
111
+ const own = at(other, "git.auto_commit");
112
+ const global = at(null, "git.auto_commit");
113
+ const board = setSetting(repo, "board.open", "app", other) && at(null, "board.open").value;
114
+ const { resetSetting } = await import(${JSON.stringify(join(repo, "cli/settings.ts"))});
115
+ resetSetting(repo, "git.auto_commit", other);
116
+ const after = at(other, "git.auto_commit"), left = await Bun.file(other + "/.kaizen/config.yml").text();
117
+ await Bun.write(other + "/.kaizen/config.yml", "# my team's git rules\\ngit:\\n # mine\\n auto_commit: true\\n");
118
+ resetSetting(repo, "git.auto_commit", other);
119
+ const kept = await Bun.file(other + "/.kaizen/config.yml").text();
120
+ return { kept, before, file, own, global, board, after, left };
121
+ `);
122
+ expect(r.before).toMatchObject({ value: "true" });
123
+ expect(r.before.own).toBeUndefined();
124
+ expect(r.file).not.toContain("runner:");
125
+ expect(r.file).not.toContain("preset:");
126
+ expect(r.own).toMatchObject({ value: "false", own: true });
127
+ expect(r.global.value).toBe("true");
128
+ expect(r.global.overrides).toContainEqual({ label: "other", value: "false" });
129
+ expect(r.board).toBe("app");
130
+ expect(r.after).toMatchObject({ value: "true" });
131
+ expect(r.left).not.toContain("auto_commit");
132
+ expect(r.kept).toBe("# my team's git rules\ngit:\n # mine\n");
133
+ });
package/cli/settings.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  // Full-screen settings browser for .kaizen/config.yml.
2
2
  // Arrow keys move and change; every change is written straight to the file.
3
3
  import { existsSync, writeFileSync, copyFileSync, mkdirSync } from "node:fs";
4
- import { join, dirname } from "node:path";
4
+ import { join, dirname, basename } from "node:path";
5
5
  import { homedir } from "node:os";
6
- import { readText } from "./state.ts";
6
+ import { readText, knownProjects } from "./state.ts";
7
7
 
8
8
  // `text` is a value typed rather than chosen: a path. It has no values to cycle.
9
9
  // `when`: the row only has an effect while that other key holds that value; both
@@ -72,12 +72,14 @@ export const PRESETS: Record<PresetName, {
72
72
  },
73
73
  };
74
74
 
75
- export function detectPreset(text: string, defaults?: string): PresetName | "custom" {
75
+ // `fallbacks`: where a key the text does not set comes from, first match wins.
76
+ export function detectPreset(text: string, ...fallbacks: (string | undefined)[]): PresetName | "custom" {
76
77
  for (const name of ["low", "medium", "ultra"] as const) {
77
78
  const p = PRESETS[name];
78
79
  let match = true;
79
80
  for (const [k, expected] of Object.entries(p.settings)) {
80
- const actual = read(text, k) ?? (defaults ? read(defaults, k) : null);
81
+ let actual = read(text, k);
82
+ for (const f of fallbacks) if (actual === null && f) actual = read(f, k);
81
83
  if (actual !== expected) {
82
84
  match = false;
83
85
  break;
@@ -102,13 +104,15 @@ const SETTINGS: Setting[] = [
102
104
  { key: "preset", label: "Preset", group: "Preset", values: ["low", "medium", "ultra", "custom"], help: "" },
103
105
  { key: "mode", label: "Run mode", group: "Approvals", values: ["approve", "auto", "plan-only", "review-only"], help: "" },
104
106
  { key: "approvals.plan", label: "Approve the plan first", group: "Approvals", values: ["true", "false"], help: "", when: ["mode", "approve"] },
105
- { key: "approvals.review", label: "Approve after review", group: "Approvals", values: ["true", "false"], help: "", when: ["mode", "approve"] },
107
+ { key: "approvals.review", label: "Approve after review", group: "Approvals", values: ["true", "false"], help: "In auto mode too: a run that changed files waits for your approval unless auto_accept is on" },
108
+ { key: "auto_accept", label: "Auto runs skip final approval", group: "Approvals", values: ["false", "true"], help: "true: an auto run that changed files finishes without waiting, marked auto-accepted", when: ["mode", "auto"] },
106
109
  { key: "approvals.each_file", label: "Confirm every file edit", group: "Approvals", values: ["true", "false"], help: "", when: ["mode", "approve"] },
107
110
  { key: "runner", label: "Stage isolation", group: "Agents", values: ["full", "lite"], help: "full: separate agent per stage. lite: one session" },
108
111
  { key: "build.executor", label: "Who builds", group: "Agents", values: ["subagent", "inline", "ask"], help: "subagent: its own agent · inline: this session · ask: pick at plan approval", when: ["runner", "full"] },
109
112
  { key: "review.executor", label: "Reviewer", group: "Agents", values: ["inline", "subagent", "ask"], help: "subagent: its own cold agent · inline: this session · ask: pick before review", when: ["runner", "lite"] },
110
113
  { key: "agent.default", label: "Tool the board launches", group: "Agents", values: ["auto", "claude", "codex", "agy", "opencode", "gemini"], help: "" },
111
114
  { key: "agent.launch", label: "Where the board runs agents", group: "Agents", values: ["card", "terminal"], help: "" },
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"] },
112
116
  { key: "subagents.model", label: "Model for subagents", group: "Agents", values: ["inherit", "opus", "sonnet", "haiku"], help: "Planner, builder, reviewer", when: ["runner", "full"] },
113
117
  { key: "subagents.effort", label: "Effort for subagents", group: "Agents", values: ["inherit", "low", "medium", "high"], help: "Planner, builder, reviewer", when: ["runner", "full"] },
114
118
  { key: "auto_fix.enabled", label: "Fix findings automatically", group: "Auto-fix", values: ["true", "false"], help: "" },
@@ -133,16 +137,31 @@ const SETTINGS: Setting[] = [
133
137
 
134
138
  // The same rows and the same write the TUI uses, for `kaizen web`'s settings panel:
135
139
  // one place decides what a setting is called, what it may be, and how it is saved.
136
- export function listSettings(repoRoot: string) {
137
- const file = locate();
140
+ // `project`: undefined resolves from the cwd as the TUI does; null is All projects
141
+ // (~/.kaizen/config.yml); a folder is that project's own .kaizen/config.yml, read over
142
+ // the global file. Board rows are global in every scope.
143
+ export function listSettings(repoRoot: string, project?: string | null) {
144
+ const file = scopeFile(project);
138
145
  const defaults = readText(join(repoRoot, "skills/kaizen/config.default.yml"));
139
146
  const load = (f: string) => existsSync(f) ? readText(f) : "";
140
147
  const text = load(file), board = load(globalFile());
141
- const preset = detectPreset(text, defaults);
142
- const rows = SETTINGS.map((s) => ({
143
- ...s,
144
- value: s.key === "preset" ? preset : (read(s.group === "Board" ? board : text, s.key) || read(defaults, s.key)) ?? s.values[0] ?? "",
145
- }));
148
+ const scoped = typeof project === "string";
149
+ const base = scoped ? board : "";
150
+ const preset = detectPreset(text, base, defaults);
151
+ // All projects: the projects whose own config sets a key to something else, since
152
+ // that value, not the one shown, is what their runs use.
153
+ const others = project === null
154
+ ? knownProjects().map((d) => ({ label: basename(d), text: load(join(d, ".kaizen", "config.yml")) })).filter((o) => o.text)
155
+ : [];
156
+ const rows = SETTINGS.map((s) => {
157
+ const value = s.key === "preset" ? preset : (read(s.group === "Board" ? board : text, s.key) ?? (s.group === "Board" ? null : read(base, s.key)) ?? read(defaults, s.key)) ?? s.values[0] ?? "";
158
+ const local = s.group !== "Board" && s.key !== "preset";
159
+ return {
160
+ ...s, value,
161
+ ...(scoped && local && read(text, s.key) !== null ? { own: true } : {}),
162
+ ...(others.length && local ? { overrides: others.flatMap((o) => { const v = read(o.text, s.key); return v !== null && v !== value ? [{ label: o.label, value: v }] : []; }) } : {}),
163
+ };
164
+ });
146
165
  const valueOf = (k: string) => rows.find((r) => r.key === k)?.value ?? null;
147
166
  return { file: tilde(file), rows: rows.map((r) => ({ ...r, idle: idle(r, valueOf) })) };
148
167
  }
@@ -153,12 +172,15 @@ function idle(s: Setting, valueOf: (key: string) => string | null) {
153
172
  return `No effect unless ${SETTINGS.find((x) => x.key === s.when![0])!.label} is ${s.when[1] === "true" ? "on" : s.when[1]}`;
154
173
  }
155
174
 
156
- export function setSetting(repoRoot: string, key: string, value: string) {
175
+ export function setSetting(repoRoot: string, key: string, value: string, project?: string | null) {
157
176
  const s = SETTINGS.find((x) => x.key === key);
158
177
  if (!s || !(s.text || s.values.includes(value))) return { error: "unknown setting or value" };
159
- const file = fileFor(s);
178
+ const file = fileFor(s, project);
160
179
  const defaultsPath = join(repoRoot, "skills/kaizen/config.default.yml");
161
- if (!existsSync(file)) { mkdirSync(dirname(file), { recursive: true }); copyFileSync(defaultsPath, file); }
180
+ // A project's own file starts empty: a copy of the defaults would pin every key in
181
+ // it, and later global changes would stop reaching that project.
182
+ const sparse = typeof project === "string" && file !== globalFile();
183
+ if (!existsSync(file)) { mkdirSync(dirname(file), { recursive: true }); sparse ? writeFileSync(file, "") : copyFileSync(defaultsPath, file); }
162
184
  const defaults = readText(defaultsPath);
163
185
  const text = readText(file);
164
186
  let updated: string;
@@ -167,7 +189,11 @@ export function setSetting(repoRoot: string, key: string, value: string) {
167
189
  updated = applyPreset(text, value as PresetName, defaults);
168
190
  } else {
169
191
  updated = write(text, key, value, defaults);
170
- updated = write(updated, "preset", detectPreset(updated, defaults), defaults);
192
+ // A project that never chose a preset does not get one written for it.
193
+ if (!sparse || read(updated, "preset") !== null) {
194
+ const g = existsSync(globalFile()) ? readText(globalFile()) : "";
195
+ updated = write(updated, "preset", detectPreset(updated, sparse ? g : "", defaults), defaults);
196
+ }
171
197
  if (read(updated, key) !== value) return { error: `${key} did not save; edit ${tilde(file)} by hand` };
172
198
  }
173
199
  if (key === "board.chat_hotkey" && !HOTKEY.test(value)) return { error: "keys are words joined by +, e.g. SUPER + ALT + SPACE" };
@@ -176,6 +202,27 @@ export function setSetting(repoRoot: string, key: string, value: string) {
176
202
  return { ok: true };
177
203
  }
178
204
 
205
+ // Takes a key out of a project's own config, so the global value applies again. The
206
+ // comment lines right above it go too, but only those the defaults carry for this key
207
+ // (what insert() wrote with it): a section comment of the user's own stays.
208
+ export function resetSetting(repoRoot: string, key: string, project: string) {
209
+ const s = SETTINGS.find((x) => x.key === key);
210
+ if (!s || s.group === "Board") return { error: "unknown setting or a board setting" };
211
+ const file = scopeFile(project);
212
+ if (!existsSync(file)) return { ok: true };
213
+ const { lines, index } = lineOf(readText(file), key);
214
+ if (index < 0) return { ok: true };
215
+ const defaults = readText(join(repoRoot, "skills/kaizen/config.default.yml")).split("\n");
216
+ const { index: at } = lineOf(defaults.join("\n"), key);
217
+ const own = new Set<string>();
218
+ for (let i = at - 1; at >= 0 && i >= 0 && /^\s*#/.test(defaults[i]!); i--) own.add(defaults[i]!.trim());
219
+ let from = index;
220
+ while (from > 0 && /^\s*#/.test(lines[from - 1]!) && own.has(lines[from - 1]!.trim())) from--;
221
+ lines.splice(from, index - from + 1);
222
+ writeFileSync(file, lines.join("\n"));
223
+ return { ok: true };
224
+ }
225
+
179
226
  const c = {
180
227
  dim: (s: string) => `\x1b[2m${s}\x1b[0m`,
181
228
  bold: (s: string) => `\x1b[1m${s}\x1b[0m`,
@@ -411,8 +458,12 @@ function globalFile() {
411
458
  // how often it gathers), not a project. They always live in the global config:
412
459
  // a project's own config.yml, often committed to its repo, would otherwise hide
413
460
  // them the moment the board moves into that project.
414
- function fileFor(s: Setting) {
415
- return s.group === "Board" ? globalFile() : locate();
461
+ function fileFor(s: Setting, project?: string | null) {
462
+ return s.group === "Board" ? globalFile() : scopeFile(project);
463
+ }
464
+
465
+ function scopeFile(project?: string | null) {
466
+ return project === undefined ? locate() : project === null ? globalFile() : join(project, ".kaizen", "config.yml");
416
467
  }
417
468
 
418
469
  // Read and write a dotted key by walking indentation, so the comment above every