kaizen-agent 1.67.0 → 1.69.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.
package/README.md CHANGED
@@ -52,6 +52,8 @@ None of this is a lack of intelligence. It is a missing workflow. Many assistant
52
52
 
53
53
  ## Install
54
54
 
55
+ Prefer a window of its own? [Download the desktop app](https://kaizen.sarahdigital.id/#desktop) for macOS, Windows or Linux.
56
+
55
57
  1. **Install** on macOS or Linux:
56
58
  ```bash
57
59
  curl -fsSL https://bun.sh/install | bash && ~/.bun/bin/bunx kaizen-agent
package/cli/install.ts CHANGED
@@ -26,6 +26,23 @@ const force = args.has("--force");
26
26
  const verbose = args.has("--verbose");
27
27
  const interactive = process.stdin.isTTY && !check && !upgrade && !args.has("--yes");
28
28
 
29
+ // Every top-level word kaizen dispatches on. Anything else used to fall through to the
30
+ // installer, so a typo or a command from a newer kaizen reinstalled instead of failing.
31
+ // cli/install-unknown.test.ts fails if a dispatched word is missing here.
32
+ const COMMANDS = ["automation", "help", "init", "browser", "card", "chat", "computer", "config", "docs", "done", "gather", "handoff",
33
+ "icebox", "issue", "prune", "recall", "related", "remember", "report", "roadmap", "settings", "setup", "sources",
34
+ "state", "stats", "uninstall", "upgrade", "version", "web", "worker", "worktree"];
35
+ const first = Bun.argv[2];
36
+ const commandList = ` commands: ${COMMANDS.join(", ")}\n plain \`kaizen\` opens the board; \`kaizen --yes\` installs; \`kaizen init\` sets up this folder\n`;
37
+ if (first && !first.startsWith("-") && !COMMANDS.includes(first)) {
38
+ console.log(`\n unknown command "${first}"\n\n${commandList}`);
39
+ process.exit(1);
40
+ }
41
+ if (first === "help") { console.log(`\n${commandList}`); process.exit(0); }
42
+ // `kaizen init` (README) has always run the installer, which sets up the project folder;
43
+ // keep that, and set up this folder even when it is not a git root.
44
+ if (first === "init") args.add("--init-project");
45
+
29
46
  function parsePresetArg(): PresetName | null {
30
47
  for (const a of Bun.argv.slice(2)) {
31
48
  if (a.startsWith("--preset=")) {
@@ -228,6 +245,35 @@ if (Bun.argv[2] === "done") {
228
245
  process.exit(0);
229
246
  }
230
247
 
248
+ // `kaizen state <run id> key=value ...`: set stage, awaiting, iteration (or any other key)
249
+ // in a run's state.json in one atomic write, refusing words no board understands.
250
+ if (Bun.argv[2] === "state") {
251
+ const { locate, setRunState } = await import("./state.ts");
252
+ const [id, ...pairs] = Bun.argv.slice(3);
253
+ if (!id) { console.log(`\n kaizen state <run id> key=value [key=value ...]\n`); process.exit(1); }
254
+ const why = setRunState(locate() ?? join(home, ".kaizen"), id, pairs);
255
+ if (why) { console.log(`\n ${why}\n`); process.exit(1); }
256
+ console.log(`\n ${id}: ${pairs.join(" ")}\n`);
257
+ process.exit(0);
258
+ }
259
+
260
+ // `kaizen stats [<run id>] [--json]` and `kaizen related <path...>`: read-only, cli/stats.ts.
261
+ if (Bun.argv[2] === "stats" || Bun.argv[2] === "related") {
262
+ const { locate } = await import("./state.ts");
263
+ const { statsText, related } = await import("./stats.ts");
264
+ const state = locate() ?? join(home, ".kaizen");
265
+ const rest = Bun.argv.slice(3), json = rest.includes("--json"), words = rest.filter((a) => a !== "--json");
266
+ if (Bun.argv[2] === "stats") {
267
+ const out = statsText(state, words[0], json);
268
+ console.log(out);
269
+ process.exit(out.startsWith("no run ") ? 1 : 0);
270
+ }
271
+ if (!words.length) { console.log(`\n kaizen related <path> [<path> ...]\n`); process.exit(1); }
272
+ const r = related(state, words);
273
+ console.log(json ? JSON.stringify(r, null, 2) : r.length ? r.map((x) => `${x.id} — ${x.title}${x.open ? ` — ${x.open} open backlog` : ""}`).join("\n") : "Related: none");
274
+ process.exit(0);
275
+ }
276
+
231
277
  // `kaizen remember …` / `kaizen recall …`: global knowledge, see cli/knowledge.ts.
232
278
  if (Bun.argv[2] === "remember" || Bun.argv[2] === "recall") {
233
279
  const { cli } = await import("./knowledge.ts");
package/cli/knowledge.ts CHANGED
@@ -17,6 +17,21 @@ import { homedir } from "node:os";
17
17
  export const TRACKS = ["code", "writing", "communication", "operations", "research", "preferences"];
18
18
  // preferences.md is the user's to write by hand in v1: taste is never inferred from work.
19
19
  const WRITABLE = TRACKS.filter((t) => t !== "preferences");
20
+ // Planners describe a track in their own words (spec.md: no fixed taxonomy), so the
21
+ // stored label drifts: `software` and `code` name the same work. Map the label, never
22
+ // the inference. A mix ("code+writing") takes its first known part.
23
+ const ALIAS: Record<string, string> = {
24
+ software: "code", app: "code", web: "code", cli: "code", feature: "code", bugfix: "code",
25
+ docs: "writing", documentation: "writing", book: "writing",
26
+ marketing: "communication", copy: "communication",
27
+ ops: "operations", devops: "operations", release: "operations",
28
+ analysis: "research", operational: "operations",
29
+ };
30
+ export function trackOf(t: string): string {
31
+ // Free-form labels ("code: ci flake", "software-enhancement") lead with their kind.
32
+ const parts = t.toLowerCase().split(/[^a-z]+/).filter(Boolean).map((p) => ALIAS[p] ?? p);
33
+ return parts.find((p) => TRACKS.includes(p)) ?? t.toLowerCase().trim();
34
+ }
20
35
  export const SESSION_HEADER = "Past experience from other projects (kaizen recall) — verify before applying, project rules win:";
21
36
  // A session hook only injects lines that share at least one tool with the project.
22
37
  const SESSION_MIN_SCORE = 2;
@@ -75,6 +90,7 @@ export type Remembered = { ok: true; line: string; n: number; similar: string[]
75
90
  // Appends by default; replaces a line only when told which one. It never judges two
76
91
  // lessons the same itself: it hands back the same-tag lines for the caller to decide.
77
92
  export function remember(o: { track: string; tags: string; text: string; applies: string; source: string; replace?: number; projectDir: string }): Remembered {
93
+ o = { ...o, track: trackOf(o.track) };
78
94
  if (!WRITABLE.includes(o.track)) return { ok: false, why: o.track === "preferences" ? "preferences are written by hand, not by remember" : `unknown track "${o.track}" (${WRITABLE.join(", ")})` };
79
95
  if (!globalAllowed(o.projectDir)) return { ok: false, why: "knowledge.global is false for this project; nothing written" };
80
96
  const tags = tagsOf(o.tags);
@@ -112,7 +128,7 @@ export function remember(o: { track: string; tags: string; text: string; applies
112
128
  export function recall(o: { track?: string; tags?: string; query?: string; limit?: number; min?: number }): string[] {
113
129
  const want = tagsOf(o.tags ?? "");
114
130
  const words = (o.query ?? "").toLowerCase().split(/\W+/).filter((w) => w.length > 2);
115
- const tracks = o.track ? [o.track] : TRACKS;
131
+ const tracks = o.track ? [trackOf(o.track)] : TRACKS;
116
132
  const scored = tracks.flatMap((t) => lines(t)).map((l) => {
117
133
  const bare = l.tags.map((t) => t.split("@")[0]);
118
134
  // An exact tag (bun@1.2) outranks the same tool at another version (bun@1.1).
@@ -193,7 +209,7 @@ export function cli(argv: string[], cwd = process.cwd()): number {
193
209
  if (rest.includes("--session")) { process.stdout.write(sessionText(cwd)); return 0; }
194
210
  const track = flag("--track"), tags = flag("--tags"), query = flag("--query"), limit = Number(flag("--limit") ?? 20);
195
211
  if (!Number.isInteger(limit) || limit < 1) { console.log("--limit must be a whole number above 0"); return 1; }
196
- if (track && !TRACKS.includes(track)) { console.log(`unknown track "${track}"`); return 1; }
212
+ if (track && !TRACKS.includes(trackOf(track))) { console.log(`unknown track "${track}"`); return 1; }
197
213
  const out = recall({ track, tags, query: query ?? rest.join(" "), limit });
198
214
  console.log(out.length ? out.join("\n") : "Recalled: none");
199
215
  return 0;
package/cli/onboarding.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
5
5
  import { join } from "node:path";
6
6
 
7
- export const STEPS = 3; // default agent, appearance, notifications; adding a project is the last button, not a step
7
+ export const STEPS = 4; // default agent, appearance, notifications, phone; adding a project is the last button, not a step
8
8
  export type Outcome = "done" | "skipped" | "dismissed" | null;
9
9
  export type Saved = { step: number; outcome: Outcome };
10
10
 
@@ -0,0 +1,96 @@
1
+ // Settings → Mobile and the onboarding phone step: what `kaizen setup` does for the phone,
2
+ // as board routes. GET says where this computer stands, POST connects or logs in.
3
+ import { qrMatrix } from "./qr.ts";
4
+ import { addWebHost, webHosts } from "./state.ts";
5
+
6
+ export type PhoneState = {
7
+ state: "missing" | "login" | "ready" | "connected";
8
+ account: string; // the Tailscale login the phone must use too
9
+ url: string; // the phone address, once connected
10
+ phones: { name: string; online: boolean }[];
11
+ qr: string; // svg, once connected
12
+ };
13
+
14
+ // From `tailscale status --json` (null when the command is not there) and the saved board names.
15
+ export function phoneState(json: string | null, hosts: Set<string>): PhoneState {
16
+ const out: PhoneState = { state: "missing", account: "", url: "", phones: [], qr: "" };
17
+ if (json === null) return out;
18
+ let s: any;
19
+ try { s = JSON.parse(json); } catch { return { ...out, state: "login" }; }
20
+ const name = String(s?.Self?.DNSName ?? "").replace(/\.$/, "").toLowerCase();
21
+ out.account = String(s?.User?.[s?.Self?.UserID]?.LoginName ?? "");
22
+ out.phones = Object.values<any>(s?.Peer ?? {})
23
+ .filter((p) => /^(ios|android)$/i.test(p?.OS ?? ""))
24
+ // Android reports "localhost" as its host name: the tailnet's name for it says more.
25
+ .map((p) => ({ name: String(p.HostName && p.HostName !== "localhost" ? p.HostName : String(p.DNSName ?? "").split(".")[0] || "phone"), online: !!p.Online }));
26
+ if (s?.BackendState !== "Running" || !name) return { ...out, state: "login" };
27
+ if (!hosts.has(name)) return { ...out, state: "ready" };
28
+ const url = `https://${name}`;
29
+ let qr = "";
30
+ try { qr = qrSvg(url); } catch { /* a name too long for the code: the address still shows */ }
31
+ return { ...out, state: "connected", url, qr };
32
+ }
33
+
34
+ // Dark modules on white with a four-module quiet zone, so it scans in a dark theme too.
35
+ export function qrSvg(text: string): string {
36
+ const g = qrMatrix(text), q = 4, n = g.length + 2 * q;
37
+ let d = "";
38
+ g.forEach((row, y) => row.forEach((on, x) => { if (on) d += `M${x + q} ${y + q}h1v1h-1z`; }));
39
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${n} ${n}" shape-rendering="crispEdges"><rect width="${n}" height="${n}" fill="#fff"/><path d="${d}" fill="#000"/></svg>`;
40
+ }
41
+
42
+ const OPERATOR = /operator|root|access denied|permission/i;
43
+ const PERMISSION = "Tailscale needs permission once. Run sudo tailscale set --operator=$USER in a terminal, then try again.";
44
+
45
+ type Run = (argv: string[]) => Promise<{ ok: boolean; out: string; err: string }>;
46
+
47
+ const run: Run = async (argv) => {
48
+ try {
49
+ const p = Bun.spawn(argv, { stdout: "pipe", stderr: "pipe", timeout: 10_000, windowsHide: true });
50
+ const [out, err] = [await new Response(p.stdout).text(), await new Response(p.stderr).text()];
51
+ return { ok: (await p.exited) === 0, out, err };
52
+ } catch { return { ok: false, out: "", err: "tailscale is not installed" }; }
53
+ };
54
+
55
+ export async function readPhone(r: Run = run): Promise<PhoneState> {
56
+ const s = await r(["tailscale", "status", "--json"]);
57
+ // Logged out, `status` exits non-zero but still prints JSON; not installed, it prints nothing.
58
+ return phoneState(s.out.trim() ? s.out : s.err === "tailscale is not installed" ? null : "", webHosts());
59
+ }
60
+
61
+ // Shares the board on the tailnet (never funnel) and saves its name, as `kaizen setup` does.
62
+ export async function connectPhone(port: number, r: Run = run): Promise<PhoneState | { error: string }> {
63
+ const now = await readPhone(r);
64
+ if (now.state === "missing" || now.state === "login") return now;
65
+ const s = await r(["tailscale", "serve", "--bg", `127.0.0.1:${port}`]);
66
+ if (!s.ok) {
67
+ const msg = s.err + s.out;
68
+ return { error: OPERATOR.test(msg) ? PERMISSION : msg.trim().split("\n")[0] || "tailscale serve failed" };
69
+ }
70
+ const name = (await r(["tailscale", "status", "--json"])).out;
71
+ try { addWebHost(String(JSON.parse(name).Self.DNSName).replace(/\.$/, "")); } catch { return { error: "Tailscale stopped while connecting" }; }
72
+ return readPhone(r);
73
+ }
74
+
75
+ // `tailscale login` prints the sign-in page and waits for it; the page is all the board needs.
76
+ export async function loginUrl(): Promise<{ url: string } | { error: string }> {
77
+ let p: ReturnType<typeof Bun.spawn>;
78
+ try { p = Bun.spawn(["tailscale", "login"], { stdout: "pipe", stderr: "pipe", windowsHide: true }); }
79
+ catch { return { error: "tailscale is not installed" }; }
80
+ let text = "";
81
+ const page = (s: ReadableStream<Uint8Array>) => (async () => {
82
+ const dec = new TextDecoder();
83
+ for await (const chunk of s) {
84
+ text += dec.decode(chunk);
85
+ const m = /https:\/\/login\.tailscale\.com\/\S+/.exec(text);
86
+ if (m) return m[0];
87
+ }
88
+ return new Promise<string>(() => {}); // this stream ended without one: the other or the timer decides
89
+ })();
90
+ const found = await Promise.race([page(p.stdout as ReadableStream<Uint8Array>), page(p.stderr as ReadableStream<Uint8Array>), new Promise<string>((ok) => setTimeout(() => ok(""), 8000))]);
91
+ // Left running when it printed a page: it finishes the login once the user signs in.
92
+ if (found) return { url: found };
93
+ p.kill();
94
+ if ((await readPhone()).state !== "login") return { url: "" }; // it logged in without a page
95
+ return { error: OPERATOR.test(text) ? PERMISSION : "Open the Tailscale app on this computer and log in there." };
96
+ }
package/cli/pty.ts CHANGED
@@ -141,7 +141,7 @@ export function startPty(key: string, cmd: string[], cwd: string, pidFile?: stri
141
141
  env: { ...colorEnv(), ...opts.env, TERM: "xterm-256color", COLORTERM: "truecolor", KAIZEN_BOARD_PID: String(process.pid) },
142
142
  terminal: { cols: 120, rows: 32, data: (_t, d) => push(dec.decode(d, { stream: true })) },
143
143
  });
144
- if (opts.tmux && cmd[0] === tmuxBin()) p.tmux = opts.tmux;
144
+ if (opts.tmux && tmuxOk()) p.tmux = opts.tmux;
145
145
  ptys.set(key, p);
146
146
  if (pidFile) writeFileSync(pidFile, String(p.proc.pid));
147
147
  // A tmux-kept agent's PID is the pane's, not the client's: the client is gone after a
@@ -274,8 +274,30 @@ export const tmuxOk = () => !!tmuxBin();
274
274
  export const tmuxName = (key: string) => `kz-${key.replace(/[^\w-]/g, "_")}`;
275
275
  // PATH from this board, not the tmux server's own: the server keeps the environment of
276
276
  // whichever board started it.
277
- export const tmuxCmd = (name: string, cmd: string[]) => [tmuxBin()!, ...TMUX, "new-session", "-A", "-s", name, "-x", "120", "-y", "32", "-e", `PATH=${process.env.PATH ?? ""}`, ...cmd,
277
+ // Its own systemd scope where there is a user manager: a board run as a unit (kaizen-web.service)
278
+ // shares that unit's cgroup, and stopping or restarting the unit killed the whole cgroup,
279
+ // tmux server included, so the agents kept for the next board went with it. Probed once;
280
+ // no systemd-run, or no user bus (a container, a bare SSH login), runs tmux as before.
281
+ // It does not outlive logout without lingering (`loginctl enable-linger`): the user
282
+ // manager and all its scopes stop then.
283
+ let scoped: string[] | undefined;
284
+ export const scopeCmd = () => {
285
+ if (scoped) return scoped;
286
+ const run = process.platform === "linux" ? Bun.which("systemd-run") : null;
287
+ const cmd = run ? [run, "--user", "--scope", "--quiet", "--collect"] : [];
288
+ try { scoped = run && Bun.spawnSync([...cmd, "true"], { stdin: "ignore", stdout: "ignore", stderr: "ignore", timeout: 3000 }).exitCode === 0 ? cmd : []; } catch { scoped = []; }
289
+ return scoped;
290
+ };
291
+ // tmux draws on the alternate screen, which has no scrollback, so the card could not scroll
292
+ // back and a wheel reached the agent as arrow keys. mouse on: the wheel scrolls tmux's own
293
+ // history (copy-mode) instead, and a plain drag selects into tmux's buffer, so copying to
294
+ // the clipboard takes Shift+drag. Without the alternate screen (smcup@) a burst of output
295
+ // is redrawn as one screen and the lines between were lost, so that was not used.
296
+ // history-limit before new-session: a pane takes the limit it was created with.
297
+ export const tmuxCmd = (name: string, cmd: string[]) => [...scopeCmd(), tmuxBin()!, ...TMUX, "start-server", ";", "set", "-g", "history-limit", "10000",
298
+ ";", "new-session", "-A", "-s", name, "-x", "120", "-y", "32", "-e", `PATH=${process.env.PATH ?? ""}`, ...cmd,
278
299
  ";", "set", "-g", "status", "off", ";", "set", "-g", "prefix", "None", ";", "set", "-g", "escape-time", "0",
300
+ ";", "set", "-g", "mouse", "on", ";", "unbind", "-n", "MouseDown3Pane", ";", "unbind", "-n", "M-MouseDown3Pane",
279
301
  ";", "set", "-as", "terminal-features", ",xterm-256color:RGB"];
280
302
  export const attachCmd = (name: string) => [tmuxBin()!, ...TMUX, "attach-session", "-t", name];
281
303
  const tmux = (...a: string[]) => {
package/cli/settings.ts CHANGED
@@ -112,7 +112,7 @@ const SETTINGS: Setting[] = [
112
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"] },
113
113
  { key: "agent.default", label: "Default agent", group: "Agents", values: ["auto", "claude", "codex", "agy", "opencode", "gemini"], help: "" },
114
114
  { key: "agent.launch", label: "Where agents run", group: "Agents", values: ["card", "terminal"], help: "" },
115
- { key: "agent.keep_alive", label: "Keep agents through a kaizen restart", group: "Agents", values: ["off", "tmux"], help: "tmux: Linux and macOS with tmux installed", when: ["agent.launch", "card"] },
115
+ { key: "agent.keep_alive", label: "Keep agents through a kaizen restart", group: "Agents", values: ["off", "tmux"], help: "tmux: Linux and macOS with tmux installed. The wheel scrolls tmux history; Shift+drag copies", when: ["agent.launch", "card"] },
116
116
  { key: "agent.keep_awake", label: "Keep computer awake", group: "Board", values: ["off", "auto", "on"], help: "auto: while kaizen runs agents · on: while kaizen 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
118
  { key: "subagents.model", label: "Claude Code", group: "Agents", values: ["inherit", "opus", "sonnet", "haiku"], help: "Its stage subagents: planner, builder, reviewer", when: ["runner", "full"] },
@@ -120,6 +120,8 @@ const SETTINGS: Setting[] = [
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
+ { key: "auto_guard.max_files", label: "Auto mode: stop above this many changed files", group: "Auto-fix", values: ["10", "25", "50", "0"], help: "0 turns the check off" },
124
+ { key: "auto_guard.stop_on", label: "Auto mode: stop on an open finding at", group: "Auto-fix", values: ["critical", "high", "medium", "low", "off"], help: "" },
123
125
  { key: "git.auto_commit", label: "Commit when done", group: "Git", values: ["false", "true"], help: "Never pushes" },
124
126
  { key: "git.worktree_per_run", label: "Branch and folder per run", group: "Git", values: ["ask", "true", "false"], help: "" },
125
127
  { 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" },
package/cli/state.ts CHANGED
@@ -2035,6 +2035,39 @@ function setStage(file: string, change: (s: any) => boolean): boolean {
2035
2035
  return true;
2036
2036
  } catch { return false; }
2037
2037
  }
2038
+ // `kaizen state <id> key=value ...`: the one writer agents use for a run's state.json,
2039
+ // so stage and awaiting can only take the words every reader knows (spec.md, Stage 0).
2040
+ // `done` is refused: finishing goes through finishRun, which checks the review gate.
2041
+ const STAGES = ["plan", "build", "review", "abandoned"];
2042
+ const AWAITING = [null, "approvals.plan", "approvals.review", "approvals.each_file", "findings"];
2043
+ export function setRunState(state: string, id: string, pairs: string[]): string | null {
2044
+ const file = join(state, "runs", id, "state.json");
2045
+ if (!existsSync(file)) return `no run ${id} under ${state}`;
2046
+ if (!pairs.length) return "nothing to set: pass key=value";
2047
+ const set: Record<string, unknown> = {};
2048
+ for (const p of pairs) {
2049
+ const i = p.indexOf("=");
2050
+ if (i < 1) return `not key=value: ${p}`;
2051
+ const k = p.slice(0, i), raw = p.slice(i + 1);
2052
+ const v = raw === "null" ? null : raw;
2053
+ if (k === "id" || k === "updated") return `${k} is not set by hand`;
2054
+ if (k === "stage" && v === "done") return "stage done: use kaizen done <id>, which checks the final approval";
2055
+ if (k === "stage" && !STAGES.includes(String(v))) return `stage must be one of ${STAGES.join(", ")} (done: kaizen done)`;
2056
+ if (k === "awaiting" && !AWAITING.includes(v as any)) return `awaiting must be null or one of ${AWAITING.slice(1).join(", ")}`;
2057
+ if (k === "iteration") { if (!/^\d+$/.test(raw)) return "iteration must be a whole number"; set[k] = Number(raw); continue; }
2058
+ set[k] = v;
2059
+ }
2060
+ let now: any = null;
2061
+ if (!setStage(file, (s) => { Object.assign(s, set); now = s; return true; })) return `state.json for ${id} changed while writing or is not valid JSON; read it and retry`;
2062
+ if ("stage" in set || "awaiting" in set) logStage(state, id, now.stage, now.awaiting);
2063
+ return null;
2064
+ }
2065
+ // runs/<id>/stages.log: one line per stage or awaiting change, `<iso> <stage> <awaiting|->`.
2066
+ // File mtimes cannot time stages (02-approval.md gains its accepted line at done), so
2067
+ // `kaizen stats` reads this. Only writes through kaizen state / kaizen done are logged.
2068
+ export function logStage(state: string, id: string, stage: string, awaiting: string | null) {
2069
+ try { appendFileSync(join(state, "runs", id, "stages.log"), `${new Date().toISOString()} ${stage} ${awaiting ?? "-"}\n`); } catch { /* timing is best effort */ }
2070
+ }
2038
2071
  // Rewrites runs an agent marked done without acceptance (gate on) to review /
2039
2072
  // approvals.review; returns the ids. Not part of readRuns: reads stay pure (mtime is liveness).
2040
2073
  export function healRuns(state: string): string[] {
@@ -2067,7 +2100,7 @@ export function finishRun(state: string, id: string, userApproved = false): stri
2067
2100
  const why = recordAcceptance(state, id, "chat");
2068
2101
  if (why) return why;
2069
2102
  }
2070
- setStage(file, (s) => { s.stage = "done"; s.awaiting = null; delete s.healed; return true; });
2103
+ if (setStage(file, (s) => { s.stage = "done"; s.awaiting = null; delete s.healed; return true; })) logStage(state, id, "done", null);
2071
2104
  return null;
2072
2105
  }
2073
2106
  const names = (report: string, path: string) => report.includes("`" + path + "`") || report.includes("`" + path + ":");
package/cli/stats.ts ADDED
@@ -0,0 +1,172 @@
1
+ // `kaizen stats [<id>] [--json]` and `kaizen related <path...>`: read-only views over
2
+ // the files every run already writes. Nothing here writes, so old runs get stats too.
3
+ // Stage times come from runs/<id>/stages.log (written by kaizen state / kaizen done), not
4
+ // file mtimes: files are rewritten later in a run, so their times say nothing per stage.
5
+ // A run with no log (every run before it existed) shows "–".
6
+ import { readFileSync, readdirSync, statSync, existsSync, openSync, readSync, closeSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { homedir } from "node:os";
9
+ import { changedPaths, projectOf } from "./state.ts";
10
+ import { trackOf } from "./knowledge.ts";
11
+
12
+ const read = (f: string) => { try { return readFileSync(f, "utf8"); } catch { return ""; } };
13
+ const mtime = (f: string) => { try { return statSync(f).mtimeMs; } catch { return 0; } };
14
+
15
+ export type RunStat = {
16
+ id: string; stage: string; track: string; runner: string; mode: string;
17
+ reviewed: boolean; fixed: boolean; unverified: boolean;
18
+ plan: number | null; wait: number | null; build: number | null; review: number | null;
19
+ };
20
+
21
+ export function runStat(state: string, id: string): RunStat | null {
22
+ const dir = join(state, "runs", id);
23
+ let s: any;
24
+ try { s = JSON.parse(read(join(dir, "state.json"))); } catch { return null; }
25
+ const t = (f: string) => mtime(join(dir, f));
26
+ let iters: string[] = [];
27
+ try { iters = readdirSync(join(dir, "05-iterations")); } catch { /* none */ }
28
+ return {
29
+ id, stage: String(s.stage ?? "?"), track: s.track ? trackOf(String(s.track)) : "?",
30
+ runner: String(s.runner ?? "?"), mode: String(s.mode ?? "?"),
31
+ reviewed: existsSync(join(dir, "04-review.md")),
32
+ fixed: iters.length > 0,
33
+ unverified: /CANNOT VERIFY/.test(read(join(dir, "04-review.md"))),
34
+ ...stageTimes(read(join(dir, "stages.log")), t("00-request.md")),
35
+ };
36
+ }
37
+
38
+ // Each interval between log lines is charged to the state at its start: waiting when
39
+ // awaiting is set, else the stage. The interval before the first line is planning,
40
+ // from the request's write (00-request.md is written once, at intake).
41
+ export function stageTimes(log: string, start: number) {
42
+ const out = { plan: null as number | null, wait: null as number | null, build: null as number | null, review: null as number | null };
43
+ const rows = log.split("\n").map((l) => l.trim().split(/\s+/)).filter((r) => r.length >= 3 && !isNaN(Date.parse(r[0]!)))
44
+ .map(([at, stage, awaiting]) => ({ at: Date.parse(at!), stage: stage!, waiting: awaiting !== "-" }));
45
+ if (!rows.length) return out;
46
+ // Only a log that starts at plan or build covers planning; one that starts later (the
47
+ // run began on an older kaizen, or by hand) has an unknown gap, left uncounted.
48
+ const lead = start && start <= rows[0]!.at && (rows[0]!.stage === "plan" || rows[0]!.stage === "build");
49
+ const seq = lead ? [{ at: start, stage: "plan", waiting: false }, ...rows] : rows;
50
+ for (let i = 0; i + 1 < seq.length; i++) {
51
+ const a = seq[i]!, d = seq[i + 1]!.at - a.at;
52
+ if (d < 0 || a.stage === "done" || a.stage === "abandoned") continue;
53
+ const k = a.waiting ? "wait" : (a.stage as keyof typeof out);
54
+ if (k in out) out[k] = (out[k] ?? 0) + d;
55
+ }
56
+ return out;
57
+ }
58
+
59
+ export function allStats(state: string): RunStat[] {
60
+ let ids: string[] = [];
61
+ try { ids = readdirSync(join(state, "runs")); } catch { return []; }
62
+ return ids.sort().map((id) => runStat(state, id)).filter((r): r is RunStat => !!r);
63
+ }
64
+
65
+ const median = (xs: number[]) => {
66
+ if (!xs.length) return null;
67
+ const s = [...xs].sort((a, b) => a - b), m = s.length >> 1;
68
+ return s.length % 2 ? s[m]! : (s[m - 1]! + s[m]!) / 2;
69
+ };
70
+ const count = (rs: RunStat[], k: keyof RunStat) => rs.reduce((o, r) => { const v = String(r[k]); o[v] = (o[v] ?? 0) + 1; return o; }, {} as Record<string, number>);
71
+
72
+ export function summary(rs: RunStat[]) {
73
+ const reviewed = rs.filter((r) => r.reviewed);
74
+ const med = (k: "plan" | "wait" | "build" | "review") => median(rs.map((r) => r[k]).filter((v): v is number => v !== null));
75
+ return {
76
+ runs: rs.length,
77
+ stage: count(rs, "stage"), track: count(rs, "track"), runner: count(rs, "runner"), mode: count(rs, "mode"),
78
+ reviewed: reviewed.length,
79
+ fixed: rs.filter((r) => r.fixed).length,
80
+ unverified: rs.filter((r) => r.unverified).length,
81
+ timed: rs.filter((r) => r.plan !== null || r.build !== null).length,
82
+ median: { plan: med("plan"), wait: med("wait"), build: med("build"), review: med("review") },
83
+ };
84
+ }
85
+
86
+ // Tokens a Claude run used, from its session log: `~/.claude/projects/*/<session>.jsonl`.
87
+ // One session can carry several runs, so only lines inside [from, to] count.
88
+ export type Tokens = { input: number; output: number; cacheRead: number; cacheWrite: number; turns: number };
89
+ export function sessionLog(session: string, home = homedir()): string | null {
90
+ const root = join(home, ".claude", "projects");
91
+ let dirs: string[] = [];
92
+ try { dirs = readdirSync(root); } catch { return null; }
93
+ for (const d of dirs) { const f = join(root, d, `${session}.jsonl`); if (existsSync(f)) return f; }
94
+ return null;
95
+ }
96
+ export function tokensIn(file: string, from: number, to: number): Tokens {
97
+ const t: Tokens = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, turns: 0 };
98
+ // Streamed in chunks: a long session log runs to hundreds of MB.
99
+ const fd = openSync(file, "r"), buf = Buffer.alloc(1 << 20);
100
+ let rest = "";
101
+ const line = (l: string) => {
102
+ if (!l.includes('"usage"')) return;
103
+ let j: any;
104
+ try { j = JSON.parse(l); } catch { return; }
105
+ const at = Date.parse(j.timestamp ?? ""), u = j.message?.usage;
106
+ if (!u || !(at >= from && at <= to)) return;
107
+ t.input += u.input_tokens ?? 0; t.output += u.output_tokens ?? 0;
108
+ t.cacheRead += u.cache_read_input_tokens ?? 0; t.cacheWrite += u.cache_creation_input_tokens ?? 0;
109
+ t.turns++;
110
+ };
111
+ try {
112
+ for (let n; (n = readSync(fd, buf, 0, buf.length, null)) > 0;) {
113
+ const parts = (rest + buf.toString("utf8", 0, n)).split("\n");
114
+ rest = parts.pop()!;
115
+ parts.forEach(line);
116
+ }
117
+ line(rest);
118
+ } finally { closeSync(fd); }
119
+ return t;
120
+ }
121
+ export function runTokens(state: string, id: string, home = homedir()): Tokens | null {
122
+ const dir = join(state, "runs", id);
123
+ let s: any;
124
+ try { s = JSON.parse(read(join(dir, "state.json"))); } catch { return null; }
125
+ if (!s.session || (s.agent && s.agent !== "claude")) return null;
126
+ const log = sessionLog(String(s.session), home);
127
+ if (!log) return null;
128
+ const from = mtime(join(dir, "00-request.md")), to = Date.parse(s.updated ?? "") || mtime(join(dir, "state.json"));
129
+ return from ? tokensIn(log, from, to) : null;
130
+ }
131
+
132
+ // Earlier runs whose report names any of these paths as changed, newest first.
133
+ export function related(state: string, paths: string[], limit = 5): { id: string; title: string; open: number }[] {
134
+ const want = new Set(paths.map((p) => p.replace(/^\.\//, "")));
135
+ const project = projectOf(state);
136
+ let ids: string[] = [];
137
+ try { ids = readdirSync(join(state, "runs")).sort().reverse(); } catch { return []; }
138
+ const out: { id: string; title: string; open: number }[] = [];
139
+ for (const id of ids) {
140
+ const dir = join(state, "runs", id), impl = read(join(dir, "03-impl.md"));
141
+ if (!impl || !changedPaths(impl, project).some((p) => want.has(p))) continue;
142
+ const title = read(join(dir, "00-request.md")).split("\n").find((l) => l.trim())?.replace(/^#+\s*/, "").slice(0, 90) ?? "";
143
+ const open = (read(join(dir, "06-backlog.md")).match(/^- open:/gm) ?? []).length;
144
+ out.push({ id, title, open });
145
+ if (out.length >= limit) break;
146
+ }
147
+ return out;
148
+ }
149
+
150
+ const dur = (ms: number | null) => ms === null ? "–" : ms < 3.6e6 ? `${Math.round(ms / 6e4)}m` : `${(ms / 3.6e6).toFixed(1)}h`;
151
+ const pct = (n: number, d: number) => (d ? `${Math.round((100 * n) / d)}%` : "–");
152
+ const kv = (o: Record<string, number>) => Object.entries(o).sort((a, b) => b[1] - a[1]).map(([k, v]) => `${k} ${v}`).join(", ");
153
+
154
+ export function statsText(state: string, id?: string, json = false): string {
155
+ if (id) {
156
+ const r = runStat(state, id);
157
+ if (!r) return `no run ${id}`;
158
+ const t = runTokens(state, id);
159
+ if (json) return JSON.stringify({ ...r, tokens: t }, null, 2);
160
+ const tok = t ? `${t.input + t.cacheWrite + t.cacheRead} in (${t.cacheRead} from cache), ${t.output} out, ${t.turns} turns` : "n/a";
161
+ return [`${r.id} ${r.stage} · ${r.track} · ${r.runner} · ${r.mode}`,
162
+ `plan ${dur(r.plan)} · waiting for approval ${dur(r.wait)} · build ${dur(r.build)} · review ${dur(r.review)} (from stages.log)`,
163
+ `fix round: ${r.fixed ? "yes" : "no"} · CANNOT VERIFY: ${r.unverified ? "yes" : "no"}`,
164
+ `tokens: ${tok}`].join("\n");
165
+ }
166
+ const s = summary(allStats(state));
167
+ if (json) return JSON.stringify(s, null, 2);
168
+ return [`${s.runs} runs — ${kv(s.stage)}`,
169
+ `track: ${kv(s.track)}`, `runner: ${kv(s.runner)} · mode: ${kv(s.mode)}`,
170
+ `fix round: ${s.fixed} of ${s.reviewed} reviewed (${pct(s.fixed, s.reviewed)}) · CANNOT VERIFY in ${s.unverified} reviews (${pct(s.unverified, s.reviewed)})`,
171
+ `median: plan ${dur(s.median.plan)} · waiting for approval ${dur(s.median.wait)} · build ${dur(s.median.build)} · review ${dur(s.median.review)} (runs with a stages.log: ${s.timed})`].join("\n");
172
+ }
package/cli/web.ts CHANGED
@@ -29,6 +29,7 @@ import * as google from "./google.ts";
29
29
  import { writeBacks } from "./writeback.ts";
30
30
  import { postLink, sendReply } from "./browser.ts";
31
31
  import { tailnetName } from "./setup.ts";
32
+ import { connectPhone, loginUrl, readPhone } from "./phone-setup.ts";
32
33
  import { listNotes, saveNote, renameNote, deleteNote, boardIndex, linksTo } from "./notes.ts";
33
34
  import * as video from "./video.ts";
34
35
  import * as auto from "./automations.ts";
@@ -84,6 +85,19 @@ const served = (f: string) => installed() === VERSION && existsSync(f) ? readTex
84
85
  // Loopback hosts only; shared by /open-url and /frameable so the board is never a way to reach other sites.
85
86
  const isLoopback = (u: URL) => ["localhost", "127.0.0.1", "[::1]"].includes(u.hostname);
86
87
 
88
+ // The Preview button: the workspace's own `dev` (or `start`) script from package.json, run with
89
+ // the package manager its lockfile names. Never a command from the page or a run's text.
90
+ export function devCommand(dir: string): string[] | null {
91
+ let scripts: Record<string, unknown> = {};
92
+ try { scripts = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")).scripts ?? {}; } catch { return null; }
93
+ const name = ["dev", "start"].find((n) => typeof scripts[n] === "string");
94
+ if (!name) return null;
95
+ const pm = existsSync(join(dir, "bun.lock")) || existsSync(join(dir, "bun.lockb")) ? "bun"
96
+ : existsSync(join(dir, "pnpm-lock.yaml")) ? "pnpm"
97
+ : existsSync(join(dir, "yarn.lock")) ? "yarn" : "npm";
98
+ return [pm, "run", name];
99
+ }
100
+
87
101
  // From `ss -ltnpH`: the ports listened on by a process whose working folder is inside ws.
88
102
  export function devPorts(ss: string, cwdOf: (pid: string) => string, ws: string): number[] {
89
103
  const ports = new Set<number>();
@@ -944,11 +958,24 @@ export async function web(repoDir: string, opts: Opts = {}) {
944
958
  if (typeof body.ws !== "string" || !(known() || (workspacesAge(cwd) > 1000 && (forgetWorkspaces(cwd), known())))) return bad("not a workspace of this project", 400);
945
959
  cwd = body.ws;
946
960
  }
961
+ let dev = false;
962
+ if (body.dev === true) {
963
+ const d = devCommand(cwd);
964
+ if (!d) return bad("no dev or start script in this folder's package.json", 404);
965
+ // Already running from this board in this folder: that terminal, not a second server.
966
+ const up = [...shells.values()].find((x) => x.ws === cwd && x.title === "dev server" && ptyState(x.key)?.alive);
967
+ if (up) return json(up);
968
+ // Through a login shell, so nvm/asdf/bun on the user's PATH resolve as in their terminal.
969
+ // Every word comes from the fixed lists in devCommand(), never from the request.
970
+ cmd = process.platform === "win32" ? ["cmd.exe", "/c", ...d] : [process.env.SHELL || "sh", "-lc", d.join(" ")];
971
+ dev = true;
972
+ }
947
973
  for (const k of shells.keys()) if (!ptyState(k)?.alive) shells.delete(k);
948
974
  if ([...shells.values()].filter((x) => x.dir === dir).length >= SHELL_CAP) return bad(`at most ${SHELL_CAP} terminals per project: close one first`, 429);
949
975
  const key = "sh-" + crypto.randomUUID().slice(0, 8);
950
- const title = agent ? KNOWN_AGENTS.find((k) => k.cmd === agent)!.name + (bypass ? " · bypass" : "") : "shell";
951
- const pid = startPty(key, cmd, cwd, undefined, changed, { env: { KAIZEN_TERM: key } });
976
+ const title = dev ? "dev server" : agent ? KNOWN_AGENTS.find((k) => k.cmd === agent)!.name + (bypass ? " · bypass" : "") : "shell";
977
+ // A dev server it starts lets a phone in: Vite refuses a host it does not know (the tailnet name).
978
+ const pid = startPty(key, cmd, cwd, undefined, changed, { env: { KAIZEN_TERM: key, ...(dev ? { __VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS: ".ts.net" } : {}) } });
952
979
  // The run workspace that opened it (its card key), so each run keeps its own centre.
953
980
  shells.set(key, { key, dir, title, agent, run: runKey, ws: cwd, pid });
954
981
  changed();
@@ -1097,7 +1124,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
1097
1124
  const p = Bun.spawn(["ss", "-ltnpH"], { stdout: "pipe", stderr: "ignore", timeout: 3000 });
1098
1125
  out = await new Response(p.stdout).text();
1099
1126
  } catch { return json([]); }
1100
- return json(devPorts(out, (pid) => { try { return readlinkSync(`/proc/${pid}/cwd`); } catch { return ""; } }, ws));
1127
+ // Never the board itself: `kaizen web` started inside the workspace listens there too.
1128
+ return json(devPorts(out, (pid) => { try { return readlinkSync(`/proc/${pid}/cwd`); } catch { return ""; } }, ws).filter((p) => p !== port));
1101
1129
  }
1102
1130
  // A phone on the tailnet cannot reach this computer's localhost. Serves that loopback port
1103
1131
  // to the tailnet (`tailscale serve --https=<port>`, never funnel) and answers the address
@@ -1121,9 +1149,18 @@ export async function web(repoDir: string, opts: Opts = {}) {
1121
1149
  };
1122
1150
  const name = tailnetName((await run(["tailscale", "status", "--json"])).out);
1123
1151
  if (!name) return json({ ok: false, error: "Tailscale is not running on this computer" });
1124
- const s = await run(["tailscale", "serve", "--bg", `--https=${port}`, `${u.protocol}//127.0.0.1:${port}`]);
1152
+ // Vite and others listen on [::1] only: serve the loopback address that answers.
1153
+ const answers = async (h: string) => { try { await fetch(`${u.protocol}//${h}:${port}/`, { redirect: "manual", signal: AbortSignal.timeout(1500) }); return true; } catch { return false; } };
1154
+ const target = (await answers("127.0.0.1")) ? "127.0.0.1" : (await answers("[::1]")) ? "[::1]" : "127.0.0.1";
1155
+ const s = await run(["tailscale", "serve", "--bg", `--https=${port}`, `${u.protocol}//${target}:${port}`]);
1125
1156
  if (!s.ok) return json({ ok: false, error: /operator|root/i.test(s.err + s.out) ? "Tailscale needs permission once: run sudo tailscale set --operator=$USER on the computer running kaizen" : (s.err || s.out).trim().split("\n")[0] });
1126
- return json({ ok: true, url: `https://${name}:${port}${u.pathname}${u.search}${u.hash}` });
1157
+ // A dev server the agent started itself may still refuse the tailnet name: say how to allow it.
1158
+ let hint = "";
1159
+ try {
1160
+ const r = await fetch(`${u.protocol}//${target}:${port}/`, { headers: { host: `${name}:${port}` }, redirect: "manual", signal: AbortSignal.timeout(3000) });
1161
+ if (r.status === 403 && /allowedHosts|not allowed/i.test(await r.text())) hint = "The dev server refuses this address. Add allowedHosts: [\".ts.net\"] under server in vite.config, or stop it and tap Preview: kaizen starts it allowed.";
1162
+ } catch {}
1163
+ return json({ ok: true, url: `https://${name}:${port}${u.pathname}${u.search}${u.hash}`, hint });
1127
1164
  }
1128
1165
  // Whether a page may be framed: X-Frame-Options or a CSP frame-ancestors that is not
1129
1166
  // "*" says no. The browser hides that behind its own error page, so the localhost tab
@@ -1159,6 +1196,19 @@ export async function web(repoDir: string, opts: Opts = {}) {
1159
1196
  }
1160
1197
  return json(usageCache);
1161
1198
  }
1199
+ // Settings → Mobile and the onboarding phone step: where Tailscale stands, connect, log in.
1200
+ if (path === "/phone/setup") {
1201
+ if (!local(req)) return bad("cross-origin request refused", 403);
1202
+ if (req.method === "GET") return json(await readPhone());
1203
+ if (req.method !== "POST") return bad("method not allowed", 405);
1204
+ const refused = strict(req);
1205
+ if (refused) return refused;
1206
+ let body: any;
1207
+ try { body = await req.json(); } catch { return bad("json body expected"); }
1208
+ if (body?.do === "connect") return json(await connectPhone(port));
1209
+ if (body?.do === "login") return json(await loginUrl());
1210
+ return bad("do: connect or login");
1211
+ }
1162
1212
  if (req.method === "GET" && path === "/phone") {
1163
1213
  // Async: a hung tailscale must not stall every terminal socket on this event loop.
1164
1214
  let out = "";