kaizen-agent 1.58.1 → 1.59.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/cli/board.test.ts CHANGED
@@ -21,12 +21,9 @@ test("Board badge counts each card needing input once and clears at zero", () =>
21
21
  { kind: "run", status: "running", pty: { alive: false, asking: true } },
22
22
  ];
23
23
  expect(waitingCount(cards)).toBe(2);
24
+ // The Ideas link carries no count.
24
25
  boardBadge(cards);
25
- expect(link.dataset.n).toBe("2");
26
- expect(link.label).toBe("Ideas: 2 waiting on you");
27
- boardBadge([]);
28
26
  expect(link.dataset.n).toBeUndefined();
29
- expect(link.label).toBe("Ideas: every idea and run, filtered");
30
27
  } finally {
31
28
  globalThis.document = previous;
32
29
  }
package/cli/pty.test.ts CHANGED
@@ -4,7 +4,7 @@ import { test, expect } from "bun:test";
4
4
  import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, realpathSync, rmSync, utimesSync } from "node:fs";
5
5
  import { tmpdir } from "node:os";
6
6
  import { join } from "node:path";
7
- import { launchMode, closeSessions, readSessions, sweepSessions, CLOSE_GRACE_MS } from "./state.ts";
7
+ import { launchMode, closeSessions, readSessions, sweepSessions } from "./state.ts";
8
8
  import { loginEnv, startPty, writePty, attachPty, ptyState, exitPty } from "./pty.ts";
9
9
  import { conptyHost, innerCommand, resizeSeq } from "./conpty.ts";
10
10
 
@@ -50,7 +50,7 @@ test.skipIf(process.platform === "win32")("the board runs the agent in the card:
50
50
  expect(r.ok).toBe(true);
51
51
  expect(r.pty).toMatch(/^[\w-]+$/);
52
52
  const card = ((await (await fetch(at + "/state")).json()) as any).cards.find((c: any) => c.text === "say hello");
53
- expect(card.pty).toEqual({ key: r.pty, alive: true, asking: false, all: [r.pty] });
53
+ expect(card.pty).toMatchObject({ key: r.pty, alive: true, asking: false, all: [r.pty] });
54
54
 
55
55
  // G-01: no Origin, a foreign one, and another local port are all refused.
56
56
  const url = `${at}/pty?key=${r.pty}`, up = { upgrade: "websocket", connection: "Upgrade", "sec-websocket-version": "13", "sec-websocket-key": "dGhlIHNhbXBsZSBub25jZQ==" };
@@ -153,49 +153,20 @@ test.skipIf(process.platform === "win32")("a board started from a launcher takes
153
153
  expect(pwd).not.toBe("/elsewhere");
154
154
  });
155
155
 
156
- test.skipIf(process.platform === "win32")("the done sweep keeps a session the user typed into after the run finished", async () => {
156
+ test.skipIf(process.platform === "win32")("the sweep leaves a done run's agent running", async () => {
157
157
  const st = join(root, "typed", ".kaizen"), ses = join(st, "sessions"), runDir = join(st, "runs", "r1");
158
158
  mkdirSync(ses, { recursive: true });
159
159
  mkdirSync(runDir, { recursive: true });
160
160
  writeFileSync(join(st, "config.yml"), "agent:\n close: on\n");
161
- const done = (at: number) => {
162
- writeFileSync(join(runDir, "state.json"), JSON.stringify({ id: "r1", stage: "done", awaiting: null }));
163
- utimesSync(join(runDir, "state.json"), new Date(at), new Date(at));
164
- };
165
- const launch = (key: string) => {
166
- writeFileSync(join(ses, key + ".json"), JSON.stringify({ run: "r1", text: "x", cmd: "sh", sessionId: null, started: 0 }));
167
- return startPty(key, ["sh", "-c", "while read l; do echo got:$l; done"], root, join(ses, key + ".pid"));
168
- };
169
- const alive = (pid: number) => { try { process.kill(pid, 0); return true; } catch { return false; } };
170
- const gone = async (pid: number) => { for (let i = 0; i < 50 && alive(pid); i++) await Bun.sleep(30); return !alive(pid); };
171
-
172
- // Untouched since the run finished: closed once the grace is over.
173
- const idle = launch("idle");
161
+ writeFileSync(join(runDir, "state.json"), JSON.stringify({ id: "r1", stage: "done", awaiting: null }));
162
+ utimesSync(join(runDir, "state.json"), new Date(0), new Date(0));
163
+ writeFileSync(join(ses, "idle.json"), JSON.stringify({ run: "r1", text: "x", cmd: "sh", sessionId: null, started: 0 }));
164
+ const idle = startPty("idle", ["sh", "-c", "while read l; do echo got:$l; done"], root, join(ses, "idle.pid"));
174
165
  await Bun.sleep(200);
175
- done(Date.now() + 10_000);
176
- sweepSessions(st, Date.now() + 10_000 + CLOSE_GRACE_MS);
177
- expect(await gone(idle)).toBe(true);
178
-
179
- // Typed into after the run finished: the user's now, left open.
180
- done(Date.now() - 60_000);
181
- const used = launch("used");
182
- await Bun.sleep(200);
183
- writePty("used", "hi\r");
184
- await Bun.sleep(200);
185
- sweepSessions(st, Date.now() + CLOSE_GRACE_MS);
186
- await Bun.sleep(200);
187
- expect(alive(used)).toBe(true);
188
- process.kill(used, "SIGTERM");
189
-
190
- // Only looked at: the page's focus and query answers reach the tty but are not typing.
191
- done(Date.now() - 60_000);
192
- const looked = launch("looked");
193
- await Bun.sleep(200);
194
- writePty("looked", "\x1b[I\x1b[O\x1b[?0u\x1b[<64;10;5M\x1bP>|xterm.js(6.0)\x1b\\");
166
+ sweepSessions(st);
195
167
  await Bun.sleep(200);
196
- expect(ptyState("looked")!.typed).toBe(0);
197
- sweepSessions(st, Date.now() + CLOSE_GRACE_MS);
198
- expect(await gone(looked)).toBe(true);
168
+ expect(() => process.kill(idle, 0)).not.toThrow();
169
+ process.kill(idle, "SIGTERM");
199
170
  });
200
171
 
201
172
  test.skipIf(process.platform === "win32")("exitPty types /exit, and ends an agent that ignores it", async () => {
@@ -248,3 +219,13 @@ test.skipIf(process.platform !== "win32")("on Windows a card agent runs in a pse
248
219
  for (let i = 0; i < 100 && ptyState(key)?.alive; i++) await Bun.sleep(100);
249
220
  expect(ptyState(key)?.alive).toBe(false);
250
221
  }, 60_000);
222
+
223
+ test("busy: on while the agent prints, off once its output goes quiet", async () => {
224
+ const key = "busy-" + Date.now();
225
+ startPty(key, ["sh", "-c", "for i in 1 2 3 4 5 6; do echo tick; sleep 0.1; done; read l"], root);
226
+ await Bun.sleep(250);
227
+ expect(ptyState(key)!.busy).toBe(true);
228
+ await Bun.sleep(1800);
229
+ expect(ptyState(key)).toMatchObject({ alive: true, busy: false });
230
+ exitPty(key);
231
+ });
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; quiet?: Timer; total: number; since: number; typed: 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 };
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.
@@ -48,16 +48,21 @@ export const ptySupported = WIN || typeof (Bun as any).Terminal === "function";
48
48
  // onChange: called when the agent ends or starts or stops asking, so the board can redraw.
49
49
  export function startPty(key: string, cmd: string[], cwd: string, pidFile?: string, onChange?: () => void): number {
50
50
  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, total: 0, since: 0, typed: 0, onChange };
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 };
52
52
  const flag = (v: boolean) => { if (p.asking !== v) { p.asking = v; onChange?.(); } };
53
+ // busy: output in the last QUIET_MS. A working agent redraws its spinner many times a second,
54
+ // so a quiet terminal is one waiting at its prompt.
55
+ const work = (v: boolean) => { if (p.busy !== v) { p.busy = v; onChange?.(); } };
53
56
  const push = (d: string) => {
54
57
  p.out.push(d);
55
58
  p.size += d.length;
56
59
  p.total += d.length;
57
60
  while (p.size > CAP && p.out.length > 1) p.size -= p.out.shift()!.length;
58
61
  for (const f of p.listeners) f(d);
62
+ work(p.exit === null);
59
63
  clearTimeout(p.quiet);
60
64
  p.quiet = setTimeout(() => {
65
+ work(false);
61
66
  // Only what came after the user's last keystroke: a question already answered may still be in the tail.
62
67
  const n = Math.min(4096, p.total - p.since);
63
68
  flag(p.exit === null && n > 0 && asking(p.out.join("").slice(-n)));
@@ -88,6 +93,7 @@ export function startPty(key: string, cmd: string[], cwd: string, pidFile?: stri
88
93
  p.exit = code;
89
94
  clearTimeout(p.quiet);
90
95
  p.asking = false;
96
+ p.busy = false;
91
97
  for (const f of p.listeners) f(null);
92
98
  p.listeners.clear();
93
99
  try { p.proc.terminal?.close(); } catch { /* already closed */ }
@@ -118,7 +124,6 @@ export function writePty(key: string, d: string) {
118
124
  const p = ptys.get(key);
119
125
  if (!p || p.exit !== null) return;
120
126
  if (d.replace(REPORT, "")) {
121
- p.typed = Date.now();
122
127
  p.since = p.total;
123
128
  if (p.asking) { p.asking = false; p.onChange?.(); }
124
129
  }
@@ -151,7 +156,7 @@ export const ptyKeys = () => [...ptys.keys()];
151
156
 
152
157
  export const ptyState = (key: string) => {
153
158
  const p = ptys.get(key);
154
- return p ? { alive: p.exit === null, exit: p.exit, asking: p.asking, typed: p.typed } : null;
159
+ return p ? { alive: p.exit === null, exit: p.exit, asking: p.asking, busy: p.busy } : null;
155
160
  };
156
161
 
157
162
  // The environment the user's login shell builds: PATH and anything exported in their
package/cli/state.test.ts CHANGED
@@ -10,7 +10,7 @@ import {
10
10
  readRuns, readInbox, writeInbox, replaceIdea, moveIdea, abandonRun, runToIdea, allBacklog, backlog,
11
11
  requestTitle, statusOf, columnOf, parseItem, startedRuns, boardCards, parentOf, addCard, readArchive, setArchived,
12
12
  requestOf, agentFlags, plainModel, readNotes, writeNotes, manualCommand, parseNotes, formatNote, appendNote, saveAttachment,
13
- reviewFindings, pickFindings, fixPrompt, approvalPrompt, sessionLaunch, closeSessions, sweepSessions, readSessions, ownerOf, CLOSE_GRACE_MS, gitStatus, runGit, cardsGit, commitPush, readCommit, findTerminal, nativePath, pruneRuns, unrechecked, notice, notifier, notifyArgs, winToastArgs, LOGO, type Card,
13
+ reviewFindings, pickFindings, fixPrompt, approvalPrompt, sessionLaunch, closeSessions, sweepSessions, readSessions, ownerOf, gitStatus, runGit, cardsGit, commitPush, readCommit, findTerminal, nativePath, pruneRuns, unrechecked, notice, notifier, notifyArgs, winToastArgs, LOGO, type Card,
14
14
  } from "./state.ts";
15
15
 
16
16
  let state: string;
@@ -49,6 +49,20 @@ test("readRuns: newest first, mtime as moved", () => {
49
49
  expect(runs[0]!.moved).toBeLessThan(Date.now() - 3600_000);
50
50
  });
51
51
 
52
+ test("readRuns keeps a run visible during a partial state write", () => {
53
+ const file = join(state, "runs", "2026-09-03-stale", "state.json");
54
+ const saved = readFileSync(file);
55
+ readRuns(state);
56
+ try {
57
+ writeFileSync(file, '{"stage":');
58
+ expect(readRuns(state).some((r) => r.id === "2026-09-03-stale" && r.stage === "build")).toBe(true);
59
+ } finally {
60
+ writeFileSync(file, saved);
61
+ const then = new Date(Date.now() - 2 * 3600_000);
62
+ utimesSync(file, then, then);
63
+ }
64
+ });
65
+
52
66
  test("statusOf: waiting beats stage, mtime decides running vs stalled", () => {
53
67
  const now = Date.now();
54
68
  const [stale, done, waiting] = readRuns(state);
@@ -1102,39 +1116,17 @@ test.skipIf(process.platform === "win32")("closeSessions ends only the run's own
1102
1116
  expect(alive(procs.other)).toBe(true);
1103
1117
  writeFileSync(join(st, "config.yml"), "agent:\n default: claude\n close: on\n");
1104
1118
 
1105
- // The sweep: run b done within the grace keeps its window, past it loses it.
1119
+ // The sweep: a done run keeps its window; only a PID file whose process is gone is dropped.
1106
1120
  newRun(p, "2026-10-01-b", "/kaizen b", { stage: "done", awaiting: null });
1107
- sweepSessions(st, Date.now());
1121
+ sweepSessions(st);
1108
1122
  await Bun.sleep(100);
1109
1123
  expect(alive(procs.other)).toBe(true);
1110
- sweepSessions(st, Date.now() + CLOSE_GRACE_MS);
1111
- expect(await procs.other.exited).not.toBe(0);
1112
- expect(alive(procs.later)).toBe(true); // run a is still waiting
1113
- // A PID file whose process is gone is dropped by the sweep, whatever its run is doing.
1114
1124
  writeFileSync(join(dir, "dead2.json"), JSON.stringify({ run: "2026-10-01-a", text: "a", cmd: "kzagent", sessionId: null, started: 0 }));
1115
1125
  writeFileSync(join(dir, "dead2.pid"), "999999\n");
1116
- sweepSessions(st, Date.now());
1126
+ sweepSessions(st);
1117
1127
  expect(existsSync(join(dir, "dead2.pid"))).toBe(false);
1118
1128
  expect(existsSync(join(dir, "dead2.json"))).toBe(true);
1119
1129
  expect(existsSync(join(dir, "later.pid"))).toBe(true);
1120
-
1121
- // A fix launched on a done run, after it last moved, is doing the work: kept.
1122
- const fix = start("fix", { run: "2026-10-01-b", started: Date.now() + 1000 });
1123
- procs.fix = fix;
1124
- for (let i = 0; i < 100 && !existsSync(join(dir, "fix.pid")); i++) await Bun.sleep(20);
1125
- sweepSessions(st, Date.now() + 2 * CLOSE_GRACE_MS);
1126
- await Bun.sleep(100);
1127
- expect(alive(fix)).toBe(true);
1128
-
1129
- // An abandoned run is left to abandonRun; the sweep does not close it, even a
1130
- // session launched long before the run last moved.
1131
- const gone = start("gone", { started: 0 });
1132
- procs.gone = gone;
1133
- for (let i = 0; i < 100 && !existsSync(join(dir, "gone.pid")); i++) await Bun.sleep(20);
1134
- writeFileSync(join(st, "runs", "2026-10-01-a", "state.json"), JSON.stringify({ stage: "abandoned", awaiting: null }));
1135
- sweepSessions(st, Date.now() + 2 * CLOSE_GRACE_MS);
1136
- await Bun.sleep(100);
1137
- expect(alive(gone)).toBe(true);
1138
1130
  } finally {
1139
1131
  for (const pr of Object.values(procs)) pr.kill();
1140
1132
  }
@@ -1290,6 +1282,12 @@ test("requestTitle: drops the launch command, keeps the first sentence, caps at
1290
1282
  expect(requestTitle("x".repeat(200)).length).toBe(90);
1291
1283
  });
1292
1284
 
1285
+ test("requestTitle: a follow-up opened from an approval question titles from its work, not the question", () => {
1286
+ const q = '# Request (verbatim)\n\nQuestion asked at the final approval of a: "Next run?"\nAnswer: "Plan 2b next"\n\nFollow-up of: a\n';
1287
+ expect(requestTitle(q)).toBe("Plan 2b next");
1288
+ expect(requestTitle(q + "Roadmap line: 2. Accounts & access — OTP\n")).toBe("Accounts & access — OTP");
1289
+ });
1290
+
1293
1291
  test("parent/child: a Parent line links a run and an idea to the run that filed them", () => {
1294
1292
  expect(parentOf("do x\nFollow-up of: 2026-01-01-a.")).toBe("2026-01-01-a");
1295
1293
  expect(parentOf(" [2026-10-18 20:57] Parent: 2026-01-01-a")).toBe("2026-01-01-a");
package/cli/state.ts CHANGED
@@ -3,9 +3,9 @@
3
3
  // board (`web.ts`) both import this and draw it their own way.
4
4
  import { existsSync, readFileSync, readdirSync, appendFileSync, writeFileSync, mkdirSync, statSync, realpathSync, rmSync, renameSync, copyFileSync, openSync, readSync, closeSync } from "node:fs";
5
5
  import { Database } from "bun:sqlite";
6
- import { join, dirname, win32, posix } from "node:path";
6
+ import { join, dirname, sep, win32, posix } from "node:path";
7
7
  import { homedir, arch, cpus, release, totalmem, version as osVersion } from "node:os";
8
- import { startPty, ptySupported, ptyState } from "./pty.ts";
8
+ import { startPty, ptySupported } from "./pty.ts";
9
9
  import { codeDir, projectFromWorktree } from "./worktree.ts";
10
10
 
11
11
  // The real path: process.cwd() is always physical, so a raw $HOME that crosses a
@@ -395,14 +395,18 @@ export function locate() {
395
395
  }
396
396
  }
397
397
 
398
+ const lastRun = new Map<string, Run>();
398
399
  export function readRuns(state: string): Run[] {
399
400
  const dir = join(state, "runs");
400
401
  if (!existsSync(dir)) return [];
401
402
  // readdir order is the filesystem's, not the alphabet's; ids start with the date,
402
403
  // so sorting is what makes "newest first" true everywhere.
403
- return readdirSync(dir).sort().flatMap((id) => {
404
+ const ids = readdirSync(dir).sort();
405
+ for (const file of lastRun.keys()) if (file.startsWith(dir + sep) && !ids.includes(file.slice(dir.length + 1))) lastRun.delete(file);
406
+ return ids.flatMap((id) => {
407
+ const runDir = join(dir, id);
404
408
  try {
405
- const file = join(dir, id, "state.json");
409
+ const file = join(runDir, "state.json");
406
410
  const s = JSON.parse(readText(file));
407
411
  // When the run last moved. Kaizen records no liveness signal, so the file's
408
412
  // own mtime is the evidence that anything is still working on it, along with
@@ -410,8 +414,10 @@ export function readRuns(state: string): Run[] {
410
414
  let moved = 0;
411
415
  try { moved = statSync(file).mtimeMs; } catch { /* vanished mid-read */ }
412
416
  try { moved = Math.max(moved, statSync(join(dir, id, "progress.md")).mtimeMs); } catch { /* no progress kept */ }
413
- return [{ id, stage: s.stage ?? "?", awaiting: s.awaiting ?? null, moved, runner: s.runner, agent: s.agent, branch: typeof s.branch === "string" ? s.branch : undefined }];
414
- } catch { return []; }
417
+ const run = { id, stage: s.stage ?? "?", awaiting: s.awaiting ?? null, moved, runner: s.runner, agent: s.agent, branch: typeof s.branch === "string" ? s.branch : undefined };
418
+ lastRun.set(runDir, run);
419
+ return [run];
420
+ } catch { return existsSync(join(runDir, "state.json")) ? [lastRun.get(runDir)].filter((r): r is Run => !!r) : []; }
415
421
  }).reverse();
416
422
  }
417
423
 
@@ -1133,11 +1139,17 @@ export function setArchived(state: string, id: string, archived: boolean) {
1133
1139
  // The request's first real line: not a heading, not a label ending in a colon,
1134
1140
  // quote marker dropped. Long enough to recognise the run, short enough for a card.
1135
1141
  export function requestTitle(text: string) {
1136
- const line = text.split("\n")
1142
+ let line = text.split("\n")
1137
1143
  .map((l) => l.replace(/^>\s*/, "").trim())
1138
1144
  .filter((l) => l && !l.startsWith("#"))
1139
1145
  .slice(0, 6)
1140
1146
  .find((l) => l && !l.endsWith(":") && !/^---/.test(l)) ?? "";
1147
+ // A follow-up opened from an approval question starts with the question; the work is
1148
+ // its roadmap line, else the answer.
1149
+ if (/^Question asked at\b/i.test(line)) {
1150
+ const pick = (k: string) => text.match(new RegExp(`^${k}:\\s*(.+)$`, "im"))?.[1].trim().replace(/^"(.*)"$/, "$1");
1151
+ line = (pick("Roadmap line") || pick("Answer") || line).replace(/^\d+\.\s+/, "");
1152
+ }
1141
1153
  // Drop the command that launched it, keep the first sentence: a card reads, it does not quote.
1142
1154
  const first = line.replace(/^\/kaizen(?:-\w+)?\s+(?:(?:lite|full|auto|plan)\s+)?/i, "").split(/(?<=[.!?])\s/)[0];
1143
1155
  return first.length > 90 ? first.slice(0, 89).trimEnd() + "…" : first;
@@ -1377,7 +1389,6 @@ function opencodeRows(sql: string, ...args: (string | number)[]): string[] {
1377
1389
  } catch { return []; }
1378
1390
  }
1379
1391
 
1380
- export const CLOSE_GRACE_MS = 60_000;
1381
1392
  const sessionsDir = (st: string) => join(st, "sessions");
1382
1393
 
1383
1394
  export function readSessions(st: string): Session[] {
@@ -1531,40 +1542,11 @@ export function closeSessions(st: string, id: string, opts: { before?: number }
1531
1542
  } catch { return 0; }
1532
1543
  }
1533
1544
 
1534
- // The board's minute sweep: sessions of runs done for longer than the grace, so the
1535
- // final summary can still be read first. Only sessions launched before the run last
1536
- // moved: a fix started on a done run leaves it done until that agent writes, and is
1537
- // the one doing the work. Abandoned runs are closed by abandonRun, not here.
1538
- export function sweepSessions(st: string, now: number) {
1539
- try {
1540
- const live = openSessions(st);
1541
- if (!live.length || !closeEnabled(dirname(st))) return;
1542
- const runs = new Map(readRuns(st).map((r) => [r.id, r])), idx = runIndex(st);
1543
- for (const s of live) {
1544
- const r = runs.get(ownerOf(st, s, idx) ?? "");
1545
- if (r && r.stage === "done" && s.started <= r.moved && now - r.moved >= CLOSE_GRACE_MS && !typedSince(st, s, r.moved)) closeOne(st, s);
1546
- }
1547
- } catch { /* the next sweep tries again */ }
1548
- }
1549
-
1550
- // Whether the user typed into the session's terminal after `t`: its tty's access time
1551
- // moves when input is read. Such a session is the user's now, not the run's to close.
1552
- // No tty (Windows, a stranger's PID): false, so the sweep closes as before.
1553
- // A board card's session is judged by its keystrokes: the page's terminal answers the
1554
- // agent's focus and query reports on that tty too, which moved its time on every look.
1555
- function typedSince(st: string, s: Session, t: number): boolean {
1556
- const card = ptyState(s.key);
1557
- if (card) return card.typed > t;
1558
- try {
1559
- if (process.platform === "win32") return false;
1560
- const pid = parseInt(readText(join(sessionsDir(st), s.key + ".pid")));
1561
- const ps = onPath("ps");
1562
- if (!(pid > 0) || !ps || !isSession(pid, s)) return false;
1563
- const tty = Bun.spawnSync([ps, "-o", "tty=", "-p", String(pid)], { stdin: "ignore", timeout: 5000 }).stdout.toString().trim();
1564
- if (!tty || tty === "?" || tty === "??") return false;
1565
- // The kernel stamps tty times in 8-second steps, rounded down.
1566
- return statSync(join("/dev", tty)).atimeMs > t - 8000;
1567
- } catch { return false; }
1545
+ // The board's minute sweep: drops the PID files of sessions that have ended. A done
1546
+ // run's agent is left running; the user closes it, a decision replaces it, or
1547
+ // abandonRun ends it.
1548
+ export function sweepSessions(st: string) {
1549
+ try { openSessions(st); } catch { /* the next sweep tries again */ }
1568
1550
  }
1569
1551
 
1570
1552
  // The run's conversation to continue: its first recorded one, on this tool, whose
package/cli/usage.test.ts CHANGED
@@ -44,7 +44,10 @@ test("claudeUsage: maps the windows; a failure is an error that never carries th
44
44
 
45
45
  test("phonePeers: online, offline, no phone, not running", () => {
46
46
  const st = (peers: object, state = "Running") => JSON.stringify({ BackendState: state, Peer: peers });
47
- expect(phonePeers(st({ a: { OS: "iOS", HostName: "iphone", Online: true }, b: { OS: "linux", Online: true } }))).toEqual({ running: true, phones: [{ name: "iphone", online: true }] });
47
+ expect(phonePeers(st({ a: { OS: "iOS", HostName: "iphone", Online: true }, b: { OS: "linux", HostName: "pc", DNSName: "pc.tail1.ts.net.", Online: true } }))).toEqual({ running: true, phones: [{ name: "iphone", online: true }], computers: [{ name: "pc", dns: "pc.tail1.ts.net", os: "linux", online: true }], self: null });
48
+ const me = JSON.stringify({ BackendState: "Running", Self: { OS: "linux", HostName: "me", DNSName: "me.ts.net." }, Peer: { m: { OS: "macOS", HostName: "mac", Online: false } } });
49
+ expect(phonePeers(me).self).toEqual({ name: "me", dns: "me.ts.net", os: "linux", online: true });
50
+ expect(phonePeers(me).computers).toEqual([{ name: "mac", dns: "", os: "macOS", online: false }]);
48
51
  expect(phonePeers(st({ a: { OS: "android", HostName: "pixel", Online: false } })).phones).toEqual([{ name: "pixel", online: false }]);
49
52
  expect(phonePeers(st({ b: { OS: "windows", Online: true } })).phones).toEqual([]);
50
53
  expect(phonePeers(st({}, "Stopped")).running).toBe(false);
package/cli/usage.ts CHANGED
@@ -57,10 +57,16 @@ export async function claudeUsage(home: string, get: typeof fetch = fetch): Prom
57
57
  }
58
58
 
59
59
  // Phones on the tailnet from `tailscale status --json`: iOS and Android peers.
60
- export function phonePeers(json: string): { running: boolean; phones: { name: string; online: boolean }[] } {
60
+ export type Computer = { name: string; dns: string; os: string; online: boolean };
61
+ export function phonePeers(json: string): { running: boolean; phones: { name: string; online: boolean }[]; computers: Computer[]; self: Computer | null } {
61
62
  try {
62
63
  const s = JSON.parse(json);
63
- const phones = Object.values<any>(s?.Peer ?? {}).filter((p) => /^(ios|android)$/i.test(p?.OS ?? "")).map((p) => ({ name: String(p.HostName ?? p.DNSName ?? ""), online: !!p.Online }));
64
- return { running: s?.BackendState === "Running", phones };
65
- } catch { return { running: false, phones: [] }; }
64
+ const peers = Object.values<any>(s?.Peer ?? {});
65
+ const isPhone = (p) => /^(ios|android)$/i.test(p?.OS ?? "");
66
+ const phones = peers.filter(isPhone).map((p) => ({ name: String(p.HostName ?? p.DNSName ?? ""), online: !!p.Online }));
67
+ // The other computers on the tailnet: the phone's Home lists them, a tap opens their board.
68
+ const comp = (p, online = !!p.Online): Computer => ({ name: String(p.HostName ?? ""), dns: String(p.DNSName ?? "").replace(/\.$/, ""), os: String(p.OS ?? ""), online });
69
+ const computers = peers.filter((p) => p?.OS && !isPhone(p)).map((p) => comp(p));
70
+ return { running: s?.BackendState === "Running", phones, computers, self: s?.Self ? comp(s.Self, true) : null };
71
+ } catch { return { running: false, phones: [], computers: [], self: null }; }
66
72
  }
package/cli/web.ts CHANGED
@@ -309,7 +309,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
309
309
  if (!st.alive && (c.status === "done" || c.status === "abandoned")) return undefined;
310
310
  // Every agent session the run has had on this board, for the workspace's Agent tabs.
311
311
  const all = keys.filter((k) => ptyState(k)?.alive || k === key);
312
- return { key, alive: st.alive, asking: st.asking, all };
312
+ return { key, alive: st.alive, asking: st.asking, busy: st.busy, all };
313
313
  };
314
314
  };
315
315
  const watchers: FSWatcher[] = [];
@@ -340,7 +340,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
340
340
  let ticks = 0;
341
341
  const poll = setInterval(() => {
342
342
  // Once a minute: windows of runs finished or abandoned past the grace are closed.
343
- if (++ticks % 30 === 0) for (const dir of states(true)) sweepSessions(dir, Date.now());
343
+ if (++ticks % 30 === 0) for (const dir of states(true)) sweepSessions(dir);
344
344
  // A project registered since start (a run launched into a fresh dir) gets a watcher too.
345
345
  const now = states(true).join("\n"); if (now !== seen) { seen = now; watchAll(); }
346
346
  const fp = fingerprint(); if (fp !== last) { last = fp; changed(); }
@@ -729,7 +729,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
729
729
  await p.exited;
730
730
  } catch { return json({ tailscale: false }); }
731
731
  const r = phonePeers(out);
732
- return json({ tailscale: r.running, phones: r.phones.length, online: r.phones.some((x) => x.online) });
732
+ return json({ tailscale: r.running, phones: r.phones.length, online: r.phones.some((x) => x.online), self: r.self, computers: r.computers });
733
733
  }
734
734
 
735
735
  // Every note of one project, text included: search, tags and backlinks are the page's.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kaizen-agent",
3
- "version": "1.58.1",
3
+ "version": "1.59.0",
4
4
  "description": "Staged workflow for AI agents — code, writing, research, operations: plan, human approval, build, independent review, bounded fix loop.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -114,7 +114,7 @@ This is a judgement, not a threshold to enforce: fifty lines that change how mon
114
114
  rounded are not a small change. Say which path you took (short or full) and why, in one line, when the
115
115
  run starts.
116
116
 
117
- **Follow-ups are runs too.** Both runners record the same artifacts: `01-plan.md`, `03-impl.md`, `04-review.md`, and a final `state.json` — `lite` and `full` differ only in who executes the stages. A message the user sends later in the same session is judged by what it asks: a question, explanation or chat is answered, no run; a request to change or produce something is building, so it goes through the flow. While the previous run has not reached `done` (including awaiting its final approval), the change is a revise of that run, recorded in `02-approval.md`. After `done` or `abandoned`, ask the user before opening a new run — AskUserQuestion with *open a follow-up run*, *answer without a run*, *cancel* — and create nothing under `runs/` until they pick the first. An explicit `/kaizen <request>` is that answer already. The new run's `00-request.md` is the user's words verbatim, then a line `Follow-up of: <previous run id>`. Never reopen a finished run. When unsure whether a message asks for a change, ask once.
117
+ **Follow-ups are runs too.** Both runners record the same artifacts: `01-plan.md`, `03-impl.md`, `04-review.md`, and a final `state.json` — `lite` and `full` differ only in who executes the stages. A message the user sends later in the same session is judged by what it asks: a question, explanation or chat is answered, no run; a request to change or produce something is building, so it goes through the flow. While the previous run has not reached `done` (including awaiting its final approval), the change is a revise of that run, recorded in `02-approval.md`. After `done` or `abandoned`, ask the user before opening a new run — AskUserQuestion with *open a follow-up run*, *answer without a run*, *cancel* — and create nothing under `runs/` until they pick the first. An explicit `/kaizen <request>` is that answer already. The new run's `00-request.md` is the user's words verbatim, then a line `Follow-up of: <previous run id>`; where those words only answer a question ("Plan 2b next"), put one line naming the work first — the board titles the card from it. Never reopen a finished run. When unsure whether a message asks for a change, ask once.
118
118
 
119
119
  ## Modes
120
120
 
@@ -127,10 +127,10 @@ agent:
127
127
  # Default coding agent to launch from dashboard backlog (auto | claude | codex | agy | opencode | gemini).
128
128
  # auto picks Claude Code if installed, otherwise the first agent found on PATH.
129
129
  default: auto
130
- # on: a board decision ends the run's waiting session before continuing its
131
- # conversation, and abandoned or done runs (after 1 minute) have theirs ended.
132
- # Only sessions the board or dashboard launched are touched. off: nothing is
133
- # ended, and a resumed conversation opens beside the window still waiting.
130
+ # on: a board decision ends the run's waiting session once the new one continuing
131
+ # its conversation is open, and abandoning a run ends its session. A done run's
132
+ # session is left open. Only sessions the board or dashboard launched are touched.
133
+ # off: nothing is ended, and a resumed conversation opens beside the window still waiting.
134
134
  close: on
135
135
  # Where the web board runs the agent it launches.
136
136
  # card - inside the board: the card's Terminal tab shows the agent live and
@@ -146,7 +146,7 @@ round of questions here is cheaper than a rejected plan.
146
146
 
147
147
  **Short work is not skipped.** Even a one-line change gets `01-plan.md` and `04-review.md`, so the run moves through every stage. Keep them brief and run under `runner: lite`; a `high`+ finding still enters the fix loop, on that same runner.
148
148
 
149
- **Follow-ups are runs too.** Both runners record the same artifacts: `01-plan.md`, `03-impl.md`, `04-review.md`, and a final `state.json` — `lite` and `full` differ only in who executes the stages. A message the user sends later in the same session is judged by what it asks: a question, explanation or chat is answered, no run; a request to change or produce something is building, so it goes through the flow. While the previous run has not reached `done` (including awaiting its final approval), the change is a revise of that run, recorded in `02-approval.md`. After `done` or `abandoned`, ask the user before opening a new run — AskUserQuestion with *open a follow-up run*, *answer without a run*, *cancel* — and create nothing under `runs/` until they pick the first. An explicit `/kaizen <request>` is that answer already. The new run's `00-request.md` is the user's words verbatim, then a line `Follow-up of: <previous run id>`. Never reopen a finished run. When unsure whether a message asks for a change, ask once.
149
+ **Follow-ups are runs too.** Both runners record the same artifacts: `01-plan.md`, `03-impl.md`, `04-review.md`, and a final `state.json` — `lite` and `full` differ only in who executes the stages. A message the user sends later in the same session is judged by what it asks: a question, explanation or chat is answered, no run; a request to change or produce something is building, so it goes through the flow. While the previous run has not reached `done` (including awaiting its final approval), the change is a revise of that run, recorded in `02-approval.md`. After `done` or `abandoned`, ask the user before opening a new run — AskUserQuestion with *open a follow-up run*, *answer without a run*, *cancel* — and create nothing under `runs/` until they pick the first. An explicit `/kaizen <request>` is that answer already. The new run's `00-request.md` is the user's words verbatim, then a line `Follow-up of: <previous run id>`; where those words only answer a question ("Plan 2b next"), put one line naming the work first — the board titles the card from it. Never reopen a finished run. When unsure whether a message asks for a change, ask once.
150
150
 
151
151
  ---
152
152
 
package/web/board/api.ts CHANGED
@@ -20,8 +20,10 @@ let before: Map<string, [number, boolean]> | null = null;
20
20
  // This page's project, sent with each request: the server keeps none, so another
21
21
  // tab or a phone picking a project never moves this one.
22
22
  export const dirHeader = () => (store.dir ? { "x-kz-dir": store.dir } : {});
23
+ let latestLoad = 0;
23
24
  // quiet: the server said something changed, nobody asked for a redraw.
24
25
  export async function load(quiet) {
26
+ const current = ++latestLoad;
25
27
  let r;
26
28
  try {
27
29
  r = await fetch("/state" + (store.all ? "?all=1" : ""), { headers: dirHeader() });
@@ -29,8 +31,10 @@ export async function load(quiet) {
29
31
  toast(GONE);
30
32
  return;
31
33
  }
34
+ const next = await r.json();
35
+ if (current !== latestLoad) return;
32
36
  const was = store.openKey && store.S.cards.find((x) => key(x) === store.openKey);
33
- store.S = await r.json();
37
+ store.S = next;
34
38
  if (!store.all) void refreshBoardBadge();
35
39
  // Home follows a project switch without the board importing it.
36
40
  dispatchEvent(new Event("kz-state"));
@@ -11,14 +11,6 @@ export const onBoardCards = (f: typeof onCards) => { onCards = f; };
11
11
  export function boardBadge(cards: BadgeCard[], projects?: unknown[]) {
12
12
  generation++;
13
13
  onCards?.(cards, projects);
14
- // The waiting-on-you count sits on Ideas, the page that lists every run and idea.
15
- const a = document.querySelector<HTMLElement>('.rail a[data-view="ideas"]');
16
- if (!a) return;
17
- const n = waitingCount(cards);
18
- if (n) a.dataset.n = String(n);
19
- else delete a.dataset.n;
20
- a.title = n ? `Ideas: ${n} waiting on you` : "Ideas: every idea and run, filtered";
21
- a.setAttribute("aria-label", a.title);
22
14
  }
23
15
 
24
16
  let generation = 0;
@@ -770,18 +770,18 @@ export function render() {
770
770
  }
771
771
  const clearable = ci === 4 && !archive && list.length;
772
772
  const olderThan = (days) => list.filter((c) => store.S.now - (c.moved || store.S.now) > days * d);
773
- // The Ideas column is titled by its two tabs, icons with their counts: ideas, or the
773
+ // The Ideas column is titled by its two tabs, icons without counts: ideas, or the
774
774
  // runs' leftovers. On Backlog a filter icon narrows it to one severity.
775
775
  const tabbed = ci === 0 && !archive,
776
776
  nb = tabbed ? backlogList().filter((c) => !only || store.shown.has(c.state)) : [];
777
777
  const title = tabbed
778
778
  ? `<span class="itabs" role="tablist" aria-label="Ideas column">${[
779
- ["ideas", "Ideas", `<svg><use href="#s-idea"/></svg>`, cs.filter((c) => c.column === 0).length],
780
- ["backlog", "Backlog: what finished runs left undone", ico("clock"), nb.length],
779
+ ["ideas", "Ideas", `<svg><use href="#s-idea"/></svg>`],
780
+ ["backlog", "Backlog: what finished runs left undone", ico("clock")],
781
781
  ]
782
782
  .map(
783
- ([v, l, svg, k]) =>
784
- `<button role="tab" aria-selected="${String(ideasTab === v)}" data-t="${v}" title="${l}" aria-label="${l}, ${k}">${svg}${ideasTab === v ? `<b>${l.split(":")[0]}</b>` : ""}<i>${k}</i></button>`,
783
+ ([v, l, svg]) =>
784
+ `<button role="tab" aria-selected="${String(ideasTab === v)}" data-t="${v}" title="${l}" aria-label="${l}">${svg}${ideasTab === v ? `<b>${l.split(":")[0]}</b>` : ""}</button>`,
785
785
  )
786
786
  .join("")}</span>`
787
787
  : `${name}<i>${list.length || ""}</i>`;
@@ -7,6 +7,7 @@ import { $, html, ico, raw } from "./dom.ts";
7
7
  import { age, NAMES } from "./labels.ts";
8
8
  import { key, runPopup } from "./cards.ts";
9
9
  import { openWorkspace } from "./run-view.ts";
10
+ import { open } from "./panel.ts";
10
11
  import { refreshBoardBadge } from "./badge.ts";
11
12
  import { cardHref, drawSources, logo, railData, srcIcon, stateOf, titleOf } from "./workspace.ts";
12
13
 
@@ -112,6 +113,7 @@ function draw() {
112
113
  hx.querySelectorAll<HTMLElement>("[data-show]").forEach((b) => (b.onclick = () => ((f.show = b.dataset.show!), (hx.innerHTML = ""), draw())));
113
114
  $("ideas-ref").onclick = () => (void drawSources(true), void refreshBoardBadge());
114
115
  box.querySelectorAll<HTMLElement>("button.go").forEach((b) => (b.onclick = () => act(rows[+b.dataset.i!])));
116
+ box.querySelectorAll<HTMLElement>("tbody tr").forEach((tr, i) => (tr.onclick = (e) => !(e.target as Element).closest("button") && detail(rows[i])));
115
117
  shownRows = rows;
116
118
  sel = Math.max(0, Math.min(sel, rows.length - 1));
117
119
  mark();
@@ -129,6 +131,15 @@ function act(c) {
129
131
  runPopup(here);
130
132
  }
131
133
 
134
+ // A row's own click: the card's detail panel over this page. Another project's card goes
135
+ // through the board's deep link, which opens the same panel there.
136
+ function detail(c) {
137
+ const here = store.S.cards.find((x) => key(x) === key(c));
138
+ if (here) return open(here);
139
+ const e = encodeURIComponent;
140
+ location.href = `/?all=1&dir=${e(c.state)}&${c.kind === "run" ? "run=" + e(c.id) : "idea=" + e(c.text)}`;
141
+ }
142
+
132
143
  function mark() {
133
144
  const trs = [...document.querySelectorAll<HTMLElement>("#ideasv tbody tr")];
134
145
  trs.forEach((tr, i) => tr.classList.toggle("kb", i === sel));
@@ -12,6 +12,8 @@ import { ICON, WORD, need } from "./labels.ts";
12
12
  import { attach, brief, md, planQuestions, preview, progress } from "./markdown.ts";
13
13
  import { toast } from "./toast.ts";
14
14
  import { go, view } from "./views.ts";
15
+ import { isPhone } from "./phone.ts";
16
+ import { openWorkspace } from "./run-view.ts";
15
17
 
16
18
  // ---- detail panel
17
19
  // A run's tabs, its phases in board order. A card opens on its column's tab.
@@ -38,8 +40,10 @@ const readable = (t) =>
38
40
  .join(" "),
39
41
  );
40
42
  export function open(c, keepTab) {
43
+ // A phone has no board: a card opens as its run workspace, which docks this panel.
44
+ if (isPhone() && view !== "run") return void openWorkspace(c);
41
45
  // The run workspace docks this panel at its right: it stays there.
42
- if (view !== "board" && view !== "run") go("board", true);
46
+ if (view !== "board" && view !== "run" && view !== "ideas") go("board", true);
43
47
  stopDictation(true); // the panel body is about to be replaced
44
48
  fixOff.clear();
45
49
  store.openKey = key(c);
@@ -365,7 +369,7 @@ export async function toggleArchive(c, archived) {
365
369
  load();
366
370
  }
367
371
  export function close() {
368
- if (view !== "board" && view !== "run") return;
372
+ if (view !== "board" && view !== "run" && view !== "ideas") return;
369
373
  const k = store.openKey;
370
374
  stopDictation(true);
371
375
  termStop();