kaizen-agent 1.61.6 → 1.63.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 (120) hide show
  1. package/README.md +2 -2
  2. package/agents/kaizen-builder.md +3 -0
  3. package/agents/kaizen-planner.md +3 -0
  4. package/agents/kaizen-reviewer.md +2 -0
  5. package/assets/kaizen-logo.png +0 -0
  6. package/assets/kaizen.ico +0 -0
  7. package/cli/__pycache__/computer-helper.cpython-314.pyc +0 -0
  8. package/cli/accounts.test.ts +126 -0
  9. package/cli/accounts.ts +116 -0
  10. package/cli/add-project.ts +4 -2
  11. package/cli/agent-prefs.test.ts +127 -0
  12. package/cli/agent-prefs.ts +106 -0
  13. package/cli/automations.test.ts +167 -0
  14. package/cli/automations.ts +298 -0
  15. package/cli/board.test.ts +4 -5
  16. package/cli/computer-helper.py +299 -0
  17. package/cli/computer.test.ts +155 -0
  18. package/cli/computer.ts +66 -0
  19. package/cli/dashboard.ts +15 -22
  20. package/cli/install.test.ts +16 -0
  21. package/cli/install.ts +134 -193
  22. package/cli/keep-awake.ts +30 -0
  23. package/cli/look.ts +33 -0
  24. package/cli/project-tree.test.ts +1 -0
  25. package/cli/pty.test.ts +2 -1
  26. package/cli/pty.ts +6 -5
  27. package/cli/report.test.ts +59 -0
  28. package/cli/report.ts +62 -0
  29. package/cli/restart.test.ts +1 -0
  30. package/cli/settings.test.ts +21 -1
  31. package/cli/settings.ts +22 -13
  32. package/cli/setup.test.ts +24 -4
  33. package/cli/setup.ts +101 -51
  34. package/cli/skills.test.ts +89 -0
  35. package/cli/skills.ts +112 -0
  36. package/cli/sources.ts +1 -1
  37. package/cli/state.test.ts +53 -4
  38. package/cli/state.ts +132 -42
  39. package/cli/term-image.test.ts +23 -0
  40. package/cli/term-image.ts +26 -0
  41. package/cli/usage.test.ts +8 -2
  42. package/cli/usage.ts +8 -6
  43. package/cli/video.test.ts +5 -5
  44. package/cli/web-accept.test.ts +1 -0
  45. package/cli/web-decide.test.ts +1 -0
  46. package/cli/web-pr.test.ts +1 -0
  47. package/cli/web-skills.test.ts +32 -0
  48. package/cli/web-symlink.test.ts +1 -0
  49. package/cli/web.ts +227 -21
  50. package/cli/workers.test.ts +319 -0
  51. package/cli/workers.ts +380 -0
  52. package/cli/worktree.test.ts +21 -2
  53. package/cli/worktree.ts +21 -2
  54. package/package.json +1 -1
  55. package/skills/kaizen/config.default.yml +40 -1
  56. package/skills/kaizen/settings.md +2 -1
  57. package/skills/kaizen/skill.json +1 -0
  58. package/skills/kaizen/spec-build.md +22 -2
  59. package/skills/kaizen/spec-main.md +9 -0
  60. package/skills/kaizen/spec-plan.md +18 -1
  61. package/skills/kaizen/spec-review.md +4 -0
  62. package/skills/kaizen/spec.md +15 -0
  63. package/skills/kaizen-help/SKILL.md +2 -0
  64. package/skills/kaizen-help/skill.json +1 -0
  65. package/skills/media/kaizen-book/skill.json +1 -0
  66. package/skills/media/kaizen-deck/SKILL.md +21 -2
  67. package/skills/media/kaizen-deck/scripts/motion.py +99 -0
  68. package/skills/media/kaizen-deck/skill.json +1 -0
  69. package/skills/media/kaizen-video/scripts/__pycache__/intake.cpython-314.pyc +0 -0
  70. package/skills/media/kaizen-video/scripts/__pycache__/make_film.cpython-314.pyc +0 -0
  71. package/skills/media/kaizen-video/scripts/__pycache__/make_tiktok.cpython-314.pyc +0 -0
  72. package/skills/media/kaizen-video/scripts/__pycache__/render_cut.cpython-314.pyc +0 -0
  73. package/skills/media/kaizen-video/scripts/__pycache__/sfx.cpython-314.pyc +0 -0
  74. package/skills/media/kaizen-video/scripts/__pycache__/srt.cpython-314.pyc +0 -0
  75. package/skills/media/kaizen-video/scripts/__pycache__/transcribe.cpython-314.pyc +0 -0
  76. package/skills/media/kaizen-video/scripts/__pycache__/vo.cpython-314.pyc +0 -0
  77. package/skills/media/kaizen-video/skill.json +1 -0
  78. package/skills/optional/kaizen-computer/SKILL.md +38 -0
  79. package/skills/optional/kaizen-computer/skill.json +1 -0
  80. package/web/board/add-project.ts +3 -3
  81. package/web/board/agent-favicons.ts +9 -0
  82. package/web/board/agent-term.ts +1 -1
  83. package/web/board/api.ts +1 -1
  84. package/web/board/approvals.ts +1 -1
  85. package/web/board/cards.ts +50 -7
  86. package/web/board/dictation.ts +46 -3
  87. package/web/board/fixes.ts +1 -1
  88. package/web/board/home.ts +1 -1
  89. package/web/board/icebox.ts +1 -1
  90. package/web/board/keys.ts +5 -15
  91. package/web/board/onboarding.ts +1 -1
  92. package/web/board/panel.ts +24 -20
  93. package/web/board/phone.ts +6 -1
  94. package/web/board/run-view.ts +118 -7
  95. package/web/board/search.ts +6 -0
  96. package/web/board/settings-accounts.ts +60 -0
  97. package/web/board/settings-agents.ts +102 -0
  98. package/web/board/settings-automations.ts +71 -0
  99. package/web/board/settings-orchestration.ts +32 -0
  100. package/web/board/settings-pages.test.ts +9 -0
  101. package/web/board/settings-pages.ts +11 -4
  102. package/web/board/settings-skills.ts +47 -0
  103. package/web/board/settings-voice.test.ts +18 -0
  104. package/web/board/settings-voice.ts +28 -0
  105. package/web/board/settings.ts +48 -5
  106. package/web/board/terms.ts +2 -2
  107. package/web/board/update.ts +1 -1
  108. package/web/board/workspace.ts +5 -1
  109. package/web/board/ws-board.test.ts +6 -0
  110. package/web/board/ws-board.ts +2 -0
  111. package/web/board/ws-tabs.test.ts +12 -1
  112. package/web/board/ws-tabs.ts +18 -0
  113. package/web/board.html +22 -5
  114. package/web/board.js +156 -85
  115. package/web/notebook.js +22 -22
  116. package/web/notes.html +3 -3
  117. package/web/term.js +27 -27
  118. package/web/term.ts +25 -3
  119. package/web/video.html +2 -2
  120. package/web/video.js +31 -31
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; 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 };
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.
@@ -94,7 +94,7 @@ export const ptySupported = WIN || typeof (Bun as any).Terminal === "function";
94
94
  // seed: what the card showed before the board restarted, replayed ahead of the new output.
95
95
  // tmux: run cmd inside a tmux session of that name on kaizen's own server (tmuxCmd), which
96
96
  // outlives the board; null where tmux cannot be used, and the agent runs plainly.
97
- export function startPty(key: string, cmd: string[], cwd: string, pidFile?: string, onChange?: () => void, opts: { seed?: string; tmux?: string; attach?: boolean } = {}): number {
97
+ export function startPty(key: string, cmd: string[], cwd: string, pidFile?: string, onChange?: () => void, opts: { seed?: string; tmux?: string; attach?: boolean; env?: Record<string, string> } = {}): number {
98
98
  const dec = new TextDecoder();
99
99
  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() };
100
100
  // attach: the session already runs (kept from a board before this one); only a client is started.
@@ -105,6 +105,7 @@ export function startPty(key: string, cmd: string[], cwd: string, pidFile?: stri
105
105
  const work = (v: boolean) => { if (p.busy !== v) { p.busy = v; onChange?.(); } };
106
106
  const push = (d: string) => {
107
107
  p.out.push(d);
108
+ p.lastOut = Date.now();
108
109
  p.size += d.length;
109
110
  p.total += d.length;
110
111
  while (p.size > CAP && p.out.length > 1) p.size -= p.out.shift()!.length;
@@ -125,7 +126,7 @@ export function startPty(key: string, cmd: string[], cwd: string, pidFile?: stri
125
126
  const ps = winPs();
126
127
  p.proc = Bun.spawn([ps, "-NoProfile", "-NonInteractive", "-EncodedCommand", conptyHost()], {
127
128
  cwd,
128
- env: { ...colorEnv(), KAIZEN_BOARD_PID: String(process.pid), KZ_PTY_CMD: innerCommand(ps, cmd), KZ_PTY_CWD: cwd, KZ_PTY_COLS: "120", KZ_PTY_ROWS: "32" },
129
+ env: { ...colorEnv(), ...opts.env, KAIZEN_BOARD_PID: String(process.pid), KZ_PTY_CMD: innerCommand(ps, cmd), KZ_PTY_CWD: cwd, KZ_PTY_COLS: "120", KZ_PTY_ROWS: "32" },
129
130
  stdin: "pipe", stdout: "pipe", stderr: "pipe", windowsHide: true,
130
131
  });
131
132
  const read = async (s: ReadableStream<Uint8Array>) => {
@@ -137,7 +138,7 @@ export function startPty(key: string, cmd: string[], cwd: string, pidFile?: stri
137
138
  read(p.proc.stderr as ReadableStream<Uint8Array>).catch(() => {});
138
139
  } else p.proc = Bun.spawn(cmd, {
139
140
  cwd,
140
- env: { ...colorEnv(), TERM: "xterm-256color", COLORTERM: "truecolor", KAIZEN_BOARD_PID: String(process.pid) },
141
+ env: { ...colorEnv(), ...opts.env, TERM: "xterm-256color", COLORTERM: "truecolor", KAIZEN_BOARD_PID: String(process.pid) },
141
142
  terminal: { cols: 120, rows: 32, data: (_t, d) => push(dec.decode(d, { stream: true })) },
142
143
  });
143
144
  if (opts.tmux && cmd[0] === tmuxBin()) p.tmux = opts.tmux;
@@ -284,7 +285,7 @@ export const ptyKeys = () => [...ptys.keys()];
284
285
 
285
286
  export const ptyState = (key: string) => {
286
287
  const p = ptys.get(key);
287
- 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 } : null;
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;
288
289
  };
289
290
 
290
291
  // The environment the user's login shell builds: PATH and anything exported in their
@@ -0,0 +1,59 @@
1
+ import { afterEach, beforeEach, expect, test } from "bun:test";
2
+ import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { readReport, reportBlocked, reportDone, reportPhase, reportUnblock, signalOf, stateOf } from "./report.ts";
6
+
7
+ let st: string;
8
+ beforeEach(() => {
9
+ st = mkdtempSync(join(tmpdir(), "kz-report-"));
10
+ mkdirSync(join(st, "runs", "r1"), { recursive: true });
11
+ writeFileSync(join(st, "runs", "r1", "state.json"), "{}");
12
+ });
13
+ afterEach(() => rmSync(st, { recursive: true, force: true }));
14
+ const now = 1e12, old = now - 11 * 60_000, build = { stage: "build", awaiting: null };
15
+
16
+ test("no report and no board terminal: no signal, so the card is as before", () => {
17
+ expect(signalOf(build, null, undefined, now, 5)).toBeNull();
18
+ expect(signalOf(build, null, { alive: true }, now, 5)).toBeNull();
19
+ });
20
+ test("an ended terminal with no hand-back for this stage and round is unverified, report or none", () => {
21
+ const h = (stage: string, iteration = 0) => ({ at: old, handback: { stage, iteration, outcome: "succeeded" as const, summary: "", files: [] } });
22
+ expect(signalOf(build, null, { alive: false }, now, 5)).toBe("unverified");
23
+ expect(signalOf(build, { at: old }, { alive: false }, now, 5)).toBe("unverified");
24
+ expect(signalOf(build, h("plan"), { alive: false }, now, 5)).toBe("unverified");
25
+ expect(signalOf(build, h("build"), { alive: false }, now, 5)).toBeNull();
26
+ expect(signalOf({ ...build, iteration: 1 }, h("build"), { alive: false }, now, 5)).toBe("unverified");
27
+ expect(signalOf({ ...build, iteration: 1 }, h("build", 1), { alive: false }, now, 5)).toBeNull();
28
+ expect(signalOf({ stage: "plan" }, null, { alive: false }, now, 5)).toBeNull();
29
+ expect(signalOf({ stage: "done" }, { at: old }, { alive: false }, now, 5)).toBeNull();
30
+ });
31
+ test("stale needs a live, silent board terminal", () => {
32
+ expect(signalOf(build, { at: old }, { alive: true, busy: true }, now, 5)).toBeNull();
33
+ expect(signalOf(build, { at: old }, { alive: true, asking: true }, now, 5)).toBeNull();
34
+ expect(signalOf(build, { at: old }, { alive: true, lastOut: now - 60_000 }, now, 5)).toBeNull();
35
+ expect(signalOf(build, { at: old }, undefined, now, 5)).toBeNull();
36
+ expect(signalOf(build, { at: old }, { alive: true, lastOut: old }, now, 5)).toBe("stale");
37
+ });
38
+ test("blocked shows until cleared, is bounded, and a hand-back clears it", () => {
39
+ reportBlocked(st, "r1", "x".repeat(900) + "\n<b>", ["a", "b", "c", "d", "e"]);
40
+ const r = readReport(st, "r1")!;
41
+ expect(r.blocked!.question.length).toBe(300);
42
+ expect(r.blocked!.options.length).toBe(4);
43
+ expect(signalOf({ stage: "build", awaiting: "approvals.plan" }, r, undefined, now, 5)).toBe("blocked");
44
+ reportUnblock(st, "r1");
45
+ expect(readReport(st, "r1")!.blocked).toBeUndefined();
46
+ reportBlocked(st, "r1", "q");
47
+ expect(reportDone(st, "r1", "build", "maybe", "s", [])).toBeTruthy();
48
+ expect(reportDone(st, "r1", "build", "failed", "s", ["a.ts"])).toBeNull();
49
+ expect(readReport(st, "r1")!.blocked).toBeUndefined();
50
+ });
51
+ test("an id can't leave the state dir", () => {
52
+ for (const id of ["../x", "a/b", "..", "nope", "/etc"]) expect(reportPhase(st, id, "x")).toBeTruthy();
53
+ expect(existsSync(join(st, "report.json"))).toBe(false);
54
+ expect(reportPhase(st, "r1", "building")).toBeNull();
55
+ });
56
+ test("from a worktree, reports go to the project's state dir", () => {
57
+ expect(stateOf("/p/.kaizen/wt/r1/cli", "/p/.kaizen/wt/r1/.kaizen")).toBe("/p/.kaizen");
58
+ expect(stateOf("/p", "/p/.kaizen")).toBe("/p/.kaizen");
59
+ });
package/cli/report.ts ADDED
@@ -0,0 +1,62 @@
1
+ // What an agent says about its own run: runs/<id>/report.json, written by `kaizen report`.
2
+ // A file, so it works with no board up, in any tool, with no secret to hand out.
3
+ // The board reads it; a run with no report behaves exactly as before.
4
+ import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
5
+ import { join } from "node:path";
6
+
7
+ export type Handback = { stage: string; iteration?: number; outcome: "succeeded" | "failed"; summary: string; files: string[] };
8
+ export type Report = { phase?: string; at: number; blocked?: { question: string; options: string[] }; handback?: Handback };
9
+ export type Signal = "blocked" | "stale" | "unverified" | null;
10
+
11
+ export const clip = (s: unknown, n: number) => String(s ?? "").replace(/[\0-\x1f\x7f]+/g, " ").trim().slice(0, n);
12
+ export const validId = (id: string) => /^[A-Za-z0-9][\w.-]{0,127}$/.test(id) && !id.includes("..");
13
+
14
+ // A worktree carries its own committed .kaizen with no runs: the project's holds them.
15
+ export const stateOf = (cwd: string, found: string | null) => /^(.*[\\/]\.kaizen)[\\/]wt[\\/]/.exec(cwd)?.[1] ?? found;
16
+
17
+ export function readReport(state: string, id: string): Report | null {
18
+ try {
19
+ const r = JSON.parse(readFileSync(join(state, "runs", id, "report.json"), "utf8"));
20
+ return r && typeof r.at === "number" ? r : null;
21
+ } catch { return null; }
22
+ }
23
+
24
+ function write(state: string, id: string, patch: (r: Report) => void): string | null {
25
+ if (!validId(id) || !existsSync(join(state, "runs", id, "state.json"))) return `no run ${clip(id, 80)}`;
26
+ const r = readReport(state, id) ?? { at: 0 };
27
+ patch(r);
28
+ r.at = Date.now();
29
+ const file = join(state, "runs", id, "report.json"), tmp = `${file}.${process.pid}.tmp`;
30
+ writeFileSync(tmp, JSON.stringify(r, null, 2));
31
+ renameSync(tmp, file);
32
+ return null;
33
+ }
34
+
35
+ export const reportPhase = (state: string, id: string, text: string) => write(state, id, (r) => { r.phase = clip(text, 120); });
36
+ export const reportBlocked = (state: string, id: string, question: string, options: string[] = []) =>
37
+ write(state, id, (r) => { r.blocked = { question: clip(question, 300), options: options.slice(0, 4).map((o) => clip(o, 80)) }; });
38
+ export const reportUnblock = (state: string, id: string) => write(state, id, (r) => { delete r.blocked; });
39
+ export function reportDone(state: string, id: string, stage: string, outcome: string, summary: string, files: string[]) {
40
+ if (outcome !== "succeeded" && outcome !== "failed") return "outcome is succeeded or failed";
41
+ let iteration = 0;
42
+ try { iteration = Number(JSON.parse(readFileSync(join(state, "runs", id, "state.json"), "utf8")).iteration) || 0; } catch { /* write() reports it */ }
43
+ return write(state, id, (r) => { r.handback = { stage: clip(stage, 20), iteration, outcome, summary: clip(summary, 600), files: files.slice(0, 200).map((f) => clip(f, 300)) }; delete r.blocked; });
44
+ }
45
+
46
+ // What the card shows. `pty` is the board's terminal for the run; without one the agent
47
+ // runs elsewhere, so nothing here can tell quiet from dead and no signal is given. A
48
+ // terminal that ended mid-stage is unverified, report or none, and each fix round owes its
49
+ // own hand-back.
50
+ type RunView = { stage?: string; awaiting?: string | null; iteration?: number };
51
+ type PtyView = { alive?: boolean; busy?: boolean; asking?: boolean; lastOut?: number };
52
+ export function signalOf(run: RunView, r: Report | null, pty: PtyView | undefined, now: number, minutes: number): Signal {
53
+ if (run.stage === "done" || run.stage === "abandoned") return null;
54
+ if (r?.blocked) return "blocked";
55
+ if (run.awaiting || !pty) return null;
56
+ if (!pty.alive) {
57
+ const h = r?.handback;
58
+ return (run.stage === "build" || run.stage === "review") && !(h?.stage === run.stage && (h.iteration ?? 0) === (run.iteration ?? 0)) ? "unverified" : null;
59
+ }
60
+ if (!r || pty.busy || pty.asking) return null;
61
+ return now - Math.max(r.at, pty.lastOut ?? 0) > 2 * minutes * 60_000 ? "stale" : null;
62
+ }
@@ -180,6 +180,7 @@ process.on("SIGTERM", () => setTimeout(() => process.exit(0), 1500));
180
180
  console.log("up");`);
181
181
  const old = Bun.spawn([process.execPath, script], { stdout: "pipe" });
182
182
  await new Response(old.stdout).body!.getReader().read();
183
+ mkdirSync(join(home, ".claude"), { recursive: true }); // an agent, or `kaizen web` stops at its no-agent notice
183
184
  const fresh = Bun.spawn([process.execPath, join(import.meta.dir, "install.ts"), "web", "--port", String(port), "--no-open", "--foreground"], {
184
185
  cwd: home, env: { ...process.env, HOME: home, USERPROFILE: home }, stdin: "ignore", stdout: "ignore", stderr: "ignore",
185
186
  });
@@ -6,7 +6,7 @@ import { test, expect, beforeAll, afterAll } from "bun:test";
6
6
  import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, copyFileSync, rmSync } from "node:fs";
7
7
  import { join, dirname } from "node:path";
8
8
  import { tmpdir } from "node:os";
9
- import { applyPreset, detectPreset } from "./settings.ts";
9
+ import { applyPreset, detectPreset, read } from "./settings.ts";
10
10
 
11
11
  const repo = join(dirname(import.meta.path), "..");
12
12
  const defaults = join(repo, "skills/kaizen/config.default.yml");
@@ -131,3 +131,23 @@ test("a project scope reads over All projects, starts its own file empty, and re
131
131
  expect(r.left).not.toContain("auto_commit");
132
132
  expect(r.kept).toBe("# my team's git rules\ngit:\n # mine\n");
133
133
  });
134
+
135
+ test("the orchestration keys read at their exact nesting, off by default, comments between lines allowed", () => {
136
+ const d = readFileSync(defaults, "utf8");
137
+ expect(["enabled", "max_workers", "permissions", "worker_model.claude", "worker_model.codex"].map((k) => read(d, `orchestration.${k}`))).toEqual(["false", "3", "own", "", ""]);
138
+ const mine = "orchestration:\n # why\n enabled: true # on\n\n # a comment\n max_workers: 2\n";
139
+ expect([read(mine, "orchestration.enabled"), read(mine, "orchestration.max_workers"), read(mine, "orchestration.permissions")]).toEqual(["true", "2", null]);
140
+ expect(read("git:\n enabled: true\n", "orchestration.enabled")).toBeNull();
141
+ });
142
+
143
+ test("a worker model written into a config that has no such block lands under orchestration, not a second header", () => {
144
+ const file = join(project, ".kaizen", "config.yml"), keep = readFileSync(file, "utf8");
145
+ try {
146
+ writeFileSync(file, "orchestration:\n enabled: true\n");
147
+ expect(inProject(`return setSetting(repo, "orchestration.worker_model.claude", "haiku")`)).toEqual({ ok: true });
148
+ const text = readFileSync(file, "utf8");
149
+ expect((text.match(/^orchestration:/gm) ?? []).length).toBe(1);
150
+ expect(read(text, "orchestration.worker_model.claude")).toBe("haiku");
151
+ expect(read(text, "orchestration.enabled")).toBe("true");
152
+ } finally { writeFileSync(file, keep); }
153
+ });
package/cli/settings.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  import { existsSync, writeFileSync, copyFileSync, mkdirSync } from "node:fs";
4
4
  import { join, dirname, basename } from "node:path";
5
5
  import { homedir } from "node:os";
6
- import { readText, knownProjects } from "./state.ts";
6
+ import { readText, knownProjects, KNOWN_AGENTS, MODEL_FLAGS } 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
@@ -50,7 +50,7 @@ export const PRESETS: Record<PresetName, {
50
50
  "auto_fix.min_severity": "low",
51
51
  "auto_fix.max_iterations": "2",
52
52
  "git.auto_commit": "false",
53
- "git.worktree_per_run": "true",
53
+ "git.worktree_per_run": "ask",
54
54
  },
55
55
  },
56
56
  ultra: {
@@ -113,13 +113,21 @@ const SETTINGS: Setting[] = [
113
113
  { key: "agent.default", label: "Tool the board launches", group: "Agents", values: ["auto", "claude", "codex", "agy", "opencode", "gemini"], help: "" },
114
114
  { key: "agent.launch", label: "Where the board runs agents", group: "Agents", values: ["card", "terminal"], help: "" },
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
- { key: "subagents.model", label: "Model for subagents", group: "Agents", values: ["inherit", "opus", "sonnet", "haiku"], help: "Planner, builder, reviewer", when: ["runner", "full"] },
117
- { key: "subagents.effort", label: "Effort for subagents", group: "Agents", values: ["inherit", "low", "medium", "high"], help: "Planner, builder, reviewer", when: ["runner", "full"] },
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
+ { 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: "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"] },
118
120
  { key: "auto_fix.enabled", label: "Fix findings automatically", group: "Auto-fix", values: ["true", "false"], help: "" },
119
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"] },
120
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"] },
121
123
  { key: "git.auto_commit", label: "Commit when done", group: "Git", values: ["false", "true"], help: "Never pushes" },
122
- { key: "git.worktree_per_run", label: "Branch and folder per run", group: "Git", values: ["true", "false"], help: "" },
124
+ { key: "git.worktree_per_run", label: "Branch and folder per run", group: "Git", values: ["ask", "true", "false"], help: "" },
125
+ { 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
+ { 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
+ { 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
+ // One per tool that takes a model flag; a run freezes its own agent's. Empty: the run's own model.
129
+ ...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" })),
130
+ ...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"] })),
123
131
  { key: "review.write_memory", label: "Remember lessons", group: "Project", values: ["true", "false"], help: "" },
124
132
  { key: "review.memory_max_lines", label: "Memory size cap", group: "Project", values: ["50", "100", "200", "400"], help: "" },
125
133
  { key: "state.keep_runs", label: "Runs to keep", group: "Project", values: ["5", "10", "20", "50"], help: "" },
@@ -485,7 +493,7 @@ function lineOf(text: string, key: string) {
485
493
  return { lines, index: from - 1, indent: depth - 2 };
486
494
  }
487
495
 
488
- function read(text: string, key: string) {
496
+ export function read(text: string, key: string) {
489
497
  const { lines, index } = lineOf(text, key);
490
498
  if (index < 0) return null;
491
499
  const v = lines[index]!.split(":").slice(1).join(":").split("#")[0]!.trim();
@@ -530,16 +538,17 @@ function insert(text: string, key: string, shown: string, defaults: string) {
530
538
  return [...lines, "", ...block, ""].join("\n");
531
539
  }
532
540
 
533
- // Nested: put it under its parent if the parent is there, else write the parent too.
534
- const parent = parts.slice(0, -1).join(".");
535
- const { index: pi } = lineOf(text, parent);
536
- if (pi < 0) {
541
+ // Nested: put it under the deepest parent that is there, writing the missing ones too.
542
+ let k = parts.length - 1;
543
+ while (k > 0 && lineOf(text, parts.slice(0, k).join(".")).index < 0) k--;
544
+ const add = [...parts.slice(k, -1).map((p, i) => `${" ".repeat((k + i) * 2)}${p}:`), ...block];
545
+ if (k === 0) {
537
546
  while (lines.length && !lines[lines.length - 1]!.trim()) lines.pop();
538
- return [...lines, "", `${parts[0]}:`, ...block, ""].join("\n");
547
+ return [...lines, "", ...add, ""].join("\n");
539
548
  }
540
- let end = pi + 1;
549
+ let end = lineOf(text, parts.slice(0, k).join(".")).index + 1;
541
550
  while (end < lines.length && (/^\s+\S/.test(lines[end]!) || !lines[end]!.trim())) end++;
542
- lines.splice(end, 0, ...block);
551
+ lines.splice(end, 0, ...add);
543
552
  return lines.join("\n");
544
553
  }
545
554
 
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
@@ -38,8 +39,8 @@ test("kaizen setup without a terminal prints the manual steps and writes nothing
38
39
  const out = await new Response(p.stdout).text();
39
40
  expect(await p.exited).toBe(0);
40
41
  expect(out).toContain("tailscale serve --bg 127.0.0.1:7420");
41
- // Bun keeps its own cache in HOME (~/.bun); only what kaizen writes counts.
42
- expect(readdirSync(homeDir).filter((n) => n !== ".bun")).toEqual([]);
42
+ // Bun's cache (~/.bun) and macOS's ~/Library land in HOME; only what kaizen writes counts.
43
+ expect(readdirSync(homeDir).filter((n) => n !== ".bun" && !(process.platform === "darwin" && n === "Library"))).toEqual([]);
43
44
  expect(existsSync(join(homeDir, ".kaizen"))).toBe(false);
44
45
  } finally { rmSync(homeDir, { recursive: true, force: true }); }
45
46
  });
@@ -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
  }