kaizen-agent 1.60.2 → 1.61.1

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/notes.test.ts CHANGED
@@ -204,10 +204,11 @@ test("the notebook's design tokens are the board's, line for line", () => {
204
204
  const block = (f: string) => {
205
205
  const s = readFileSync(join(root, "web", f), "utf8").split("\n");
206
206
  const at = s.findIndex((l) => l.startsWith(":root{--bg:"));
207
- return s.slice(at, at + 8).join("\n");
207
+ return s.slice(at, at + 11).join("\n");
208
208
  };
209
209
  expect(block("notes.html")).toBe(block("board.html"));
210
210
  expect(block("board.html")).toContain("data-theme=dark]{--shade");
211
+ expect(block("board.html")).toContain(":root[data-color=blue][data-theme=dark]{");
211
212
  const syms = (f: string) => readFileSync(join(root, "web", f), "utf8").split("\n").filter((l) => l.startsWith('<symbol id="s-')).join("\n");
212
213
  expect(syms("notes.html")).toBe(syms("board.html"));
213
214
  expect(syms("board.html").split("\n").length).toBe(7);
package/cli/pty.test.ts CHANGED
@@ -5,7 +5,7 @@ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, realpa
5
5
  import { tmpdir } from "node:os";
6
6
  import { join } from "node:path";
7
7
  import { launchMode, closeSessions, readSessions, sweepSessions } from "./state.ts";
8
- import { loginEnv, startPty, writePty, attachPty, ptyState, exitPty, lastLine } from "./pty.ts";
8
+ import { loginEnv, startPty, writePty, submitPty, attachPty, ptyState, exitPty, lastLine } from "./pty.ts";
9
9
  import { conptyHost, innerCommand, resizeSeq } from "./conpty.ts";
10
10
 
11
11
  const root = realpathSync(mkdtempSync(join(tmpdir(), "kaizen-pty-")));
@@ -232,6 +232,20 @@ test.skipIf(process.platform !== "win32")("on Windows a card agent runs in a pse
232
232
  expect(ptyState(key)?.alive).toBe(false);
233
233
  }, 60_000);
234
234
 
235
+ test.skipIf(process.platform === "win32")("submit: Enter reaches the agent on its own, not in the text's burst", async () => {
236
+ const key = "submit-" + Date.now(), log = join(root, "chunks-" + key), script = join(root, "chunks.js");
237
+ writeFileSync(script, `process.stdin.setRawMode(true); process.stdin.on("data", (d) => require("fs").appendFileSync(${JSON.stringify(log)}, JSON.stringify(d.toString()) + "\\n")); console.log("ready");`);
238
+ const out: string[] = [];
239
+ startPty(key, [process.execPath, script], root);
240
+ attachPty(key, (d) => { if (d) out.push(d); });
241
+ for (let i = 0; i < 100 && !out.join("").includes("ready"); i++) await Bun.sleep(50);
242
+ submitPty(key, "hello", 100);
243
+ let chunks = "";
244
+ for (let i = 0; i < 40 && !chunks.includes("\\r"); i++) { await Bun.sleep(50); try { chunks = readFileSync(log, "utf8"); } catch { /* not yet */ } }
245
+ expect(chunks.trim().split("\n").map((l) => JSON.parse(l))).toEqual(["hello", "\r"]);
246
+ exitPty(key, 100);
247
+ });
248
+
235
249
  test("busy: on while the agent draws its working line, off once it goes quiet; other output is not work", async () => {
236
250
  const key = "busy-" + Date.now();
237
251
  startPty(key, ["sh", "-c", "for i in 1 2 3 4 5 6; do echo 'Thinking (3s · esc to interrupt)'; sleep 0.1; done; read l"], root);
package/cli/pty.ts CHANGED
@@ -21,6 +21,9 @@ const KEEP_MS = 10 * 60_000;
21
21
 
22
22
  const ptys = new Map<string, Pty>();
23
23
 
24
+ // A board started from a colourless place (an agent's shell, CI) carries NO_COLOR; its terminals show colour anyway.
25
+ export const colorEnv = (env: Record<string, string | undefined> = process.env) => { const { NO_COLOR: _, ...rest } = env; return rest; };
26
+
24
27
  // What the sidebar shows for an agent: the latest line the agent printed. Keystrokes are never kept,
25
28
  // and nothing is read while a question is open or within ECHO_MS of a keystroke: a terminal echoes
26
29
  // what is typed, so that line could be a password. Memory only.
@@ -122,7 +125,7 @@ export function startPty(key: string, cmd: string[], cwd: string, pidFile?: stri
122
125
  const ps = winPs();
123
126
  p.proc = Bun.spawn([ps, "-NoProfile", "-NonInteractive", "-EncodedCommand", conptyHost()], {
124
127
  cwd,
125
- env: { ...process.env, KZ_PTY_CMD: innerCommand(ps, cmd), KZ_PTY_CWD: cwd, KZ_PTY_COLS: "120", KZ_PTY_ROWS: "32" },
128
+ env: { ...colorEnv(), KZ_PTY_CMD: innerCommand(ps, cmd), KZ_PTY_CWD: cwd, KZ_PTY_COLS: "120", KZ_PTY_ROWS: "32" },
126
129
  stdin: "pipe", stdout: "pipe", stderr: "pipe", windowsHide: true,
127
130
  });
128
131
  const read = async (s: ReadableStream<Uint8Array>) => {
@@ -134,7 +137,7 @@ export function startPty(key: string, cmd: string[], cwd: string, pidFile?: stri
134
137
  read(p.proc.stderr as ReadableStream<Uint8Array>).catch(() => {});
135
138
  } else p.proc = Bun.spawn(cmd, {
136
139
  cwd,
137
- env: { ...process.env, TERM: "xterm-256color", COLORTERM: "truecolor" },
140
+ env: { ...colorEnv(), TERM: "xterm-256color", COLORTERM: "truecolor" },
138
141
  terminal: { cols: 120, rows: 32, data: (_t, d) => push(dec.decode(d, { stream: true })) },
139
142
  });
140
143
  if (opts.tmux && cmd[0] === tmuxBin()) p.tmux = opts.tmux;
@@ -199,6 +202,14 @@ export function writePty(key: string, d: string) {
199
202
  send(p, d);
200
203
  }
201
204
 
205
+ // Text and Enter sent as one burst read as a paste to Claude Code and other TUIs: the Enter
206
+ // lands in the input as a newline and nothing submits. Enter follows on its own, after the
207
+ // paste window has closed.
208
+ export function submitPty(key: string, text: string, gap = 300) {
209
+ writePty(key, text);
210
+ setTimeout(() => writePty(key, "\r"), gap);
211
+ }
212
+
202
213
  const send = (p: Pty, d: string) => {
203
214
  if (!WIN) return p.proc.terminal?.write(d);
204
215
  try { (p.proc.stdin as Bun.FileSink).write(d); (p.proc.stdin as Bun.FileSink).flush(); } catch { /* host gone */ }
@@ -0,0 +1,23 @@
1
+ import { expect, test } from "bun:test";
2
+ import { shellAgent } from "./web.ts";
3
+ import { colorEnv } from "./pty.ts";
4
+
5
+ const procs = (m: Record<string, string>) => (path: string) => {
6
+ if (path in m) return m[path];
7
+ throw new Error("gone");
8
+ };
9
+
10
+ test("finds an agent below the shell, through a wrapper script", () => {
11
+ const read = procs({ "/proc/1/task/1/children": "2 ", "/proc/2/cmdline": "/bin/bash\0/home/u/.local/bin/claude\0--x\0", "/proc/2/task/2/children": "" });
12
+ expect(shellAgent(1, ["claude", "codex"], read)).toBe("claude");
13
+ });
14
+
15
+ test("a shell running something else, or already gone, has no agent", () => {
16
+ const read = procs({ "/proc/1/task/1/children": "2", "/proc/2/cmdline": "vim\0claude.md\0", "/proc/2/task/2/children": "" });
17
+ expect(shellAgent(1, ["claude"], read)).toBeUndefined();
18
+ expect(shellAgent(9, ["claude"], read)).toBeUndefined();
19
+ });
20
+
21
+ test("board terminals drop an inherited NO_COLOR", () => {
22
+ expect(colorEnv({ NO_COLOR: "1", PATH: "/bin" })).toEqual({ PATH: "/bin" });
23
+ });
package/cli/state.test.ts CHANGED
@@ -1526,3 +1526,22 @@ test("stageFiles, commitStaged, suggestMessage: only the run's files are staged,
1526
1526
  expect(readFileSync(join(proj, "a.txt"), "utf8")).toBe("junk\n");
1527
1527
  rmSync(root, { recursive: true, force: true });
1528
1528
  });
1529
+
1530
+ test("runGit: a run owns the files its report lists as changed, not ones it only mentions", () => {
1531
+ const proj = mkdtempSync(join(tmpdir(), "kaizen-own-")), st = join(proj, ".kaizen"), g = (...a: string[]) => Bun.spawnSync(["git", "-C", proj, ...a]);
1532
+ g("init", "-q"); g("config", "user.email", "t@t"); g("config", "user.name", "t"); g("remote", "add", "origin", "https://example.invalid/r.git");
1533
+ for (const f of ["listed.txt", "mentioned.txt", "fixed.txt", "whole.txt", "script.txt", "kept.txt"]) writeFileSync(join(proj, f), "1\n");
1534
+ g("add", "."); g("commit", "-qm", "base", "--date=2000-01-01T00:00:00");
1535
+ Bun.spawnSync(["git", "-C", proj, "commit", "-q", "--amend", "--no-edit"], { env: { ...process.env, GIT_COMMITTER_DATE: "2000-01-01T00:00:00" } });
1536
+ for (const f of ["listed.txt", "mentioned.txt", "fixed.txt", "whole.txt", "script.txt", "kept.txt"]) writeFileSync(join(proj, f), "2\n");
1537
+ const a = join(st, "runs", "a"), b = join(st, "runs", "b");
1538
+ mkdirSync(join(a, "05-iterations"), { recursive: true }); mkdirSync(b, { recursive: true });
1539
+ writeFileSync(join(a, "state.json"), "{}"); writeFileSync(join(b, "state.json"), "{}");
1540
+ writeFileSync(join(a, "03-impl.md"), "## Changed\n- `listed.txt`\n\n## Scripts\n- `script.txt`\n\n## Left unchanged\n`kept.txt`\n\n## Deviations\n`mentioned.txt` is another session's.\n");
1541
+ writeFileSync(join(a, "05-iterations", "01-fix.md"), "# Fix\n- `fixed.txt`\n");
1542
+ writeFileSync(join(b, "03-impl.md"), "No headings here: `whole.txt`\n");
1543
+ const files = (id: string) => (runGit(st, id) as any).files.map((l: string) => l.slice(3));
1544
+ expect(files("a")).toEqual(["fixed.txt", "listed.txt", "script.txt"]);
1545
+ expect(files("b")).toEqual(["whole.txt"]);
1546
+ rmSync(proj, { recursive: true, force: true });
1547
+ });
package/cli/state.ts CHANGED
@@ -1830,13 +1830,14 @@ export function gitStatus(projectDir: string): GitStatus {
1830
1830
  // a quote, a backslash) never matches a report; read `status -z` if that comes up.
1831
1831
  const statusPath = (line: string) => line.slice(3).split(" -> ").pop()!.replace(/^"|"$/g, "");
1832
1832
 
1833
- // What a run reported changing: 03-impl.md and its fix rounds, and when the newest
1834
- // of them was written.
1833
+ // What a run reported changing: 03-impl.md and its fix rounds, the parts of them that
1834
+ // list changes (`named`), and when the newest of them was written.
1835
1835
  function runReport(state: string, id: string) {
1836
1836
  const base = join(state, "runs", id), its = join(base, "05-iterations");
1837
1837
  const fixes = existsSync(its) ? readdirSync(its).filter((n) => n.endsWith("-fix.md")).map((n) => join(its, n)) : [];
1838
- let text = "", at = 0;
1839
- for (const f of [join(base, "03-impl.md"), ...fixes]) try { text += readText(f) + "\n"; at = Math.max(at, statSync(f).mtimeMs); } catch {}
1838
+ let text = "", named = "", at = 0;
1839
+ // Sections are cut per file, so one report's headings never decide for another.
1840
+ for (const f of [join(base, "03-impl.md"), ...fixes]) try { const t = readText(f); text += t + "\n"; named += ownSections(t) + "\n"; at = Math.max(at, statSync(f).mtimeMs); } catch {}
1840
1841
  // A finished run did no work after it was done: a report touched later (a rewrite, a
1841
1842
  // docs pass) would otherwise read as newer than the commit holding its work, and the
1842
1843
  // run would be offered the next run's changes.
@@ -1844,7 +1845,7 @@ function runReport(state: string, id: string) {
1844
1845
  const st = JSON.parse(readText(join(base, "state.json"))), done = Date.parse(st.updated);
1845
1846
  if (st.stage === "done" && done) at = Math.min(at, done);
1846
1847
  } catch {}
1847
- return { text, at };
1848
+ return { text, named, at };
1848
1849
  }
1849
1850
  // The final-approval gate. A run that changed files is only accepted by an
1850
1851
  // `accepted:` line in its 02-approval.md, written by the board's Approve, by the main
@@ -1862,6 +1863,11 @@ const changeSections = (report: string) => {
1862
1863
  const parts = report.split(/^(?=#{2,3} )/m).filter((p) => /^#{2,3} .*(chang|files)/i.test(p));
1863
1864
  return parts.length ? parts.join("\n") : report;
1864
1865
  };
1866
+ // What may name a run's own files: the report without the sections known to talk about
1867
+ // other things. Dropping known headings, not keeping known ones: a section with an
1868
+ // unusual name stays in, since hiding real work is the worse mistake.
1869
+ const NOT_CHANGES = /deviat|verif|preview|how to test|commit|gate|unchanged|not changed|no change|not done|undone|skipped|out of scope|notes/i;
1870
+ const ownSections = (report: string) => report.split(/^(?=#{2,3} )/m).filter((p) => !(/^#{2,3} /.test(p) && NOT_CHANGES.test(p.split("\n")[0]))).join("");
1865
1871
  export function changedPaths(report: string, projectDir: string): string[] {
1866
1872
  const out = new Set<string>();
1867
1873
  for (const m of changeSections(report).matchAll(/`([^`\n]+)`/g)) {
@@ -1953,7 +1959,7 @@ export function finishRun(state: string, id: string, userApproved = false): stri
1953
1959
  }
1954
1960
  const names = (report: string, path: string) => report.includes("`" + path + "`") || report.includes("`" + path + ":");
1955
1961
 
1956
- type Report = { id: string; text: string; at: number; sha?: string };
1962
+ type Report = { id: string; text: string; named: string; at: number; sha?: string };
1957
1963
  function runReports(state: string): Report[] {
1958
1964
  let ids: string[] = [];
1959
1965
  try { ids = readdirSync(join(state, "runs")); } catch {}
@@ -1962,7 +1968,7 @@ function runReports(state: string): Report[] {
1962
1968
  // A run holds a path at time `t` when its report names it, was written by then, and no
1963
1969
  // other run naming it reported in between.
1964
1970
  const owns = (mine: Report, rest: Report[], p: string, t: number) =>
1965
- names(mine.text, p) && mine.at <= t && !rest.some((r) => r.at > mine.at && r.at <= t && names(r.text, p));
1971
+ names(mine.named, p) && mine.at <= t && !rest.some((r) => r.at > mine.at && r.at <= t && names(r.named, p));
1966
1972
  const lastCommit = (dir: string, p: string) => Number(git(dir, "--literal-pathspecs", "log", "-1", "--format=%ct", "--", p).out) * 1000;
1967
1973
  // A changed file is the run's unless it was committed after the report: then the run's
1968
1974
  // work in it is in, and what changed since is someone else's. A commit in the same
@@ -1991,7 +1997,7 @@ function aheadBy(s: GitStatus & { repo: true }, all: Report[]): (id: string) =>
1991
1997
  let most = -1;
1992
1998
  for (const r of all) {
1993
1999
  if (!r.text || r.at > c.at + 999) continue;
1994
- const k = c.files.filter((p) => names(r.text, p)).length;
2000
+ const k = c.files.filter((p) => names(r.named, p)).length;
1995
2001
  if (k > most || (k === most && r.at > best!.at)) { best = r; most = k; }
1996
2002
  }
1997
2003
  }
@@ -2011,13 +2017,13 @@ function aheadBy(s: GitStatus & { repo: true }, all: Report[]): (id: string) =>
2011
2017
  export function runGit(state: string, id: string): GitStatus {
2012
2018
  const dir = codeDir(dirname(state), id), s = gitStatus(dir);
2013
2019
  if (!s.repo) return s;
2014
- const all = runReports(state), mine = all.find((r) => r.id === id) ?? { id, text: "", at: 0 };
2020
+ const all = runReports(state), mine = all.find((r) => r.id === id) ?? { id, text: "", named: "", at: 0 };
2015
2021
  const rest = all.filter((o) => o.id !== id);
2016
2022
  const files = runFiles(dir, s.files, mine, rest);
2017
2023
  const shared = files.flatMap((l) => {
2018
2024
  const p = statusPath(l);
2019
2025
  const since = lastCommit(dir, p);
2020
- const who = rest.filter((r) => r.at > since && names(r.text, p)).map((r) => short(r.id));
2026
+ const who = rest.filter((r) => r.at > since && names(r.named, p)).map((r) => short(r.id));
2021
2027
  return who.length ? [`${p}: ${who.join(", ")}`] : [];
2022
2028
  });
2023
2029
  const { unpushed, ...base } = s;
@@ -2163,7 +2169,7 @@ export function cardsGit(state: string, ids: string[], due: Record<string, "comm
2163
2169
  if (!s.repo) return out;
2164
2170
  const all = runReports(state), ahead = aheadBy(s, all);
2165
2171
  for (const id of ids) {
2166
- const mine = all.find((r) => r.id === id) ?? { id, text: "", at: 0 }, k = readCommit(state, id);
2172
+ const mine = all.find((r) => r.id === id) ?? { id, text: "", named: "", at: 0 }, k = readCommit(state, id);
2167
2173
  const files = runFiles(dir, s.files, mine, all.filter((o) => o.id !== id)).length;
2168
2174
  if (files) out[id] = "pending", due[id] = "commit";
2169
2175
  else if (k?.pushed) out[id] = "pushed";
package/cli/web.ts CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  reviewFindings, pickFindings, backlogCards, backlogItem, startedBacklog, closeBacklog, markBacklogDone, fixPrompt, approvalPrompt, canApproveAwaiting, gateOf, recordAcceptance, healRuns, finishRun, nativePath, closeSessions, sweepSessions, issueUrl,
10
10
  launchMode, readSessions, ownerOf, runIndex, resumePrompt, runAgent, firstSession, webHosts,
11
11
  } from "./state.ts";
12
- import { attachPty, writePty, resizePty, exitPty, ptyState, ptyKeys, adoptLoginEnv, startPty, ptySupported, detachPty, ptyTail, ptyTmux, tmuxAlive, RESUMED } from "./pty.ts";
12
+ import { attachPty, writePty, submitPty, resizePty, exitPty, ptyState, ptyKeys, adoptLoginEnv, startPty, ptySupported, detachPty, ptyTail, ptyTmux, tmuxAlive, RESUMED } from "./pty.ts";
13
13
  import { claudeUsage, codexUsage, phonePeers, type Usage } from "./usage.ts";
14
14
  import { readSources, addSource, removeSource, moveSource, setCategory, setWriteback, setPaused, readIcebox, promote, dismiss, restore, addItem, markDone, markReplied, gatherSource, freshImages, gatherAll, gatherDirs, due, socialUrl, socialOf } from "./sources.ts";
15
15
  import { projectLogo, LOGO_TYPES } from "./logo.ts";
@@ -1007,7 +1007,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1007
1007
  if (req.method === "GET" && path === "/manifest.webmanifest") {
1008
1008
  return new Response(JSON.stringify({
1009
1009
  name: "kaizen", short_name: "kaizen", start_url: "/", scope: "/", display: "standalone",
1010
- background_color: "#0c162f", theme_color: "#0c162f",
1010
+ background_color: "#121212", theme_color: "#121212",
1011
1011
  icons: [{ src: "/logo.png", sizes: "1024x1024", type: "image/png", purpose: "any" }],
1012
1012
  }), { headers: { "content-type": "application/manifest+json" } });
1013
1013
  }
@@ -1066,7 +1066,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
1066
1066
  const name = KNOWN_AGENTS.find((k) => k.cmd === cmd)?.name.split(" ")[0] ?? "Agent";
1067
1067
  agents.push({ key, dir, ws, agent: cmd, name, run, asking: st.asking, busy: st.busy, born: st.born, ...(loopback ? { last: st.last || undefined, at: st.at || undefined } : {}) });
1068
1068
  };
1069
- for (const x of shells.values()) if (x.agent) addAgent(x.key, x.dir, x.ws, x.agent, x.run);
1069
+ // A plain shell counts too while an agent typed into it runs there.
1070
+ for (const x of shells.values()) { const cmd = x.agent || (x.pid ? shellAgent(x.pid, KNOWN_AGENTS.map((k) => k.cmd)) : undefined); if (cmd) addAgent(x.key, x.dir, x.ws, cmd, x.run); }
1070
1071
  cards.forEach((c, i) => { for (const k of ptys[i]?.all ?? []) addAgent(k, c.state, c.ws, pty.cmd(k) ?? KNOWN_AGENTS.find((a) => c.tags?.includes(a.cmd))?.cmd, c.kind === "run" ? c.id : undefined); });
1071
1072
  const entry = (d: string) => ({ dir: d, label: label(d), logo: !!projectLogo(d),
1072
1073
  workspaces: d === join(home, ".kaizen") ? [{ path: d, branch: "", main: true }] : workspacesNow(projectOf(d)) });
@@ -1870,7 +1871,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1870
1871
  // the text queues in it, and no second agent opens beside it.
1871
1872
  const live = liveAgent(dir, id);
1872
1873
  if (live) {
1873
- writePty(live.key, text + "\r");
1874
+ submitPty(live.key, text);
1874
1875
  markStage(dir, id, "review", live.key);
1875
1876
  changed();
1876
1877
  return json({ ok: true, pty: live.key, reused: true });
@@ -1918,7 +1919,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1918
1919
  const live = liveAgent(dir, id);
1919
1920
  const before = Date.now();
1920
1921
  const r = live ? { ok: true as const, pty: live.key, agent: live.cmd, reused: true } : launchRun({ severity: null, where: null, text, raw: text }, dir, id, inCard(dir));
1921
- if (live) writePty(live.key, text + "\r");
1922
+ if (live) submitPty(live.key, text);
1922
1923
  else if (r.ok) closeSessions(dir, id, { before });
1923
1924
  // The plan's approval starts the build; fixing open findings is the review stage again.
1924
1925
  if (r.ok) markStage(dir, id, run.awaiting === "approvals.plan" ? "impl" : run.awaiting === "findings" ? "review" : "", r.pty);
@@ -2060,6 +2061,25 @@ export function sessionLive(id: string): boolean {
2060
2061
  return false;
2061
2062
  }
2062
2063
 
2064
+ // The known agent running below a board shell, by walking its child processes. A wrapper script
2065
+ // shows as `bash <path>/claude`, so the first two arguments are checked. Linux only; elsewhere undefined.
2066
+ const procRead = (path: string) => readFileSync(path, "utf8");
2067
+ export function shellAgent(root: number, known: string[], read: (path: string) => string = procRead): string | undefined {
2068
+ const todo = [root];
2069
+ for (let n = 0; todo.length && n < 200; n++) {
2070
+ const pid = todo.shift()!;
2071
+ try {
2072
+ if (pid !== root) {
2073
+ const argv = read(`/proc/${pid}/cmdline`).split("\0").slice(0, 2).map((a) => a.split("/").pop() ?? "");
2074
+ const hit = known.find((k) => argv.includes(k));
2075
+ if (hit) return hit;
2076
+ }
2077
+ todo.push(...read(`/proc/${pid}/task/${pid}/children`).split(" ").filter(Boolean).map(Number));
2078
+ } catch { /* it ended, or no /proc */ }
2079
+ }
2080
+ return undefined;
2081
+ }
2082
+
2063
2083
  // Whether Claude Code session `id` runs as process `root` or under it: Claude Code records
2064
2084
  // each running session as ~/.claude/sessions/<pid>.json; /proc gives the parent chain.
2065
2085
  // Linux only; elsewhere false, and the run view says the session runs elsewhere.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kaizen-agent",
3
- "version": "1.60.2",
3
+ "version": "1.61.1",
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": {
@@ -3,6 +3,7 @@
3
3
  // Every call is a JSON POST to the board; the server validates paths, URLs and refs again.
4
4
  import { html, modal } from "./dom.ts";
5
5
  import { gitProjects, wsHref } from "./workspace.ts";
6
+ import { branchSlug } from "./ws-tabs.ts";
6
7
 
7
8
  type Start = "folder" | "clone" | "create" | "ws";
8
9
  const SEP = (p: string) => (p.includes("\\") ? "\\" : "/");
@@ -44,6 +45,7 @@ export function openAdd(opts: { dir?: string | null; start?: Start } = {}) {
44
45
 
45
46
  const draw = (v: Start | "menu") => {
46
47
  const ws = gitProjects();
48
+ dl.classList.toggle("wsnew", v === "ws");
47
49
  if (v === "menu") {
48
50
  form.innerHTML = html`<b>Add a project</b><small class="att">Add a project to get started with kaizen.</small><button type="button" class="btn opt" data-go="folder"><b>Existing folder</b><small>A project, a Git repo, or any folder</small></button><small class="att">Other ways to add</small><button type="button" class="btn opt" data-go="clone"><b>Clone from URL</b><small>Clone a remote Git repository</small></button><button type="button" class="btn opt" data-go="create"><b>Create new project</b><small>Start from an empty folder</small></button>${ws.length ? html`<button type="button" class="btn opt" data-go="ws"><b>New workspace</b><small>A branch in its own folder, in a project you have</small></button>` : ""}<div class="row"><button type="button" class="btn ghost" data-a="x">Cancel</button></div>`.toString();
49
51
  form.querySelectorAll<HTMLElement>("[data-go]").forEach((b) => (b.onclick = () => draw(b.dataset.go as Start)));
@@ -106,11 +108,13 @@ export function openAdd(opts: { dir?: string | null; start?: Start } = {}) {
106
108
  landed(r.d.dir, r.d.git === false ? "Project created, but git init failed" : "Project created");
107
109
  };
108
110
  } else {
109
- // New workspace: a project (git ones), a branch name and the branch it starts from.
111
+ // New workspace, after Orca's composer: one name box, the start branch on its label row, Advanced for an exact branch.
110
112
  const cur = ws.some((p) => p.dir === opts.dir) ? opts.dir : ws[0]?.dir;
111
- form.innerHTML = html`<b>New workspace</b><small class="att">A new branch in its own folder under .kaizen/wt/.</small><label class="att">Project<select name="project" aria-label="Project">${ws.map((p) => html`<option value="${p.dir}"${p.dir === cur ? " selected" : ""}>${p.name}</option>`)}</select></label><label class="att">Branch name<input name="branch" placeholder="feature/my-branch" aria-label="Branch name" autocomplete="off" spellcheck="false" required></label><label class="att">Base branch<select name="base" aria-label="Base branch"></select></label>${foot("Create workspace")}`.toString();
112
- field("branch").focus();
113
+ const mod = /Mac/.test(navigator.platform) ? "⌘" : "Ctrl";
114
+ form.innerHTML = html`<b>New workspace</b><label class="att">Project<select name="project" aria-label="Project">${ws.map((p) => html`<option value="${p.dir}"${p.dir === cur ? " selected" : ""}>${p.name}</option>`)}</select></label><div class="wsfrom"><span class="att" id="wsfl">Create from <i>[Optional]</i></span><label class="wsbase">from <select name="base" aria-label="Start from branch"></select></label></div><input name="name" placeholder="What is this workspace for?" aria-labelledby="wsfl" autocomplete="off" spellcheck="false"><details class="wsadv"><summary>Advanced</summary><label class="att">Branch name<input name="branch" placeholder="feature/my-branch" aria-label="Branch name" autocomplete="off" spellcheck="false"></label></details><small class="att err" role="alert"></small><div class="row">${back}<button type="button" class="btn ghost" data-a="x">Cancel</button><button class="btn pri" data-a="go">Create workspace</button><kbd class="wskey" aria-hidden="true">${mod} ↵</kbd></div>`.toString();
115
+ field("name").focus();
113
116
  const sel = form.elements.namedItem("base") as HTMLSelectElement;
117
+ field("name").oninput = () => (field("branch").placeholder = branchSlug(field("name").value) || "feature/my-branch");
114
118
  const bases = async () => {
115
119
  const r = await call("/branches?dir=" + encodeURIComponent(field("project").value));
116
120
  const { def = "", branches = [] } = r.ok ? r.d : {};
@@ -118,12 +122,18 @@ export function openAdd(opts: { dir?: string | null; start?: Start } = {}) {
118
122
  };
119
123
  (form.elements.namedItem("project") as HTMLSelectElement).onchange = bases;
120
124
  bases();
125
+ form.onkeydown = (e) => {
126
+ if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) e.preventDefault(), form.requestSubmit();
127
+ };
121
128
  form.onsubmit = async (e) => {
122
129
  e.preventDefault();
123
130
  const dir = field("project").value;
124
131
  const b = form.querySelector<HTMLButtonElement>("[data-a=go]")!;
132
+ if (b.disabled) return;
133
+ say("");
134
+ const branch = field("branch").value.trim() || branchSlug(field("name").value) || "workspace-" + Math.random().toString(36).slice(2, 6);
125
135
  busy(b, true, "Creating...", "Create workspace");
126
- const r = await call("/worktree", { dir, branch: field("branch").value.trim(), base: sel.value || undefined });
136
+ const r = await call("/worktree", { dir, branch, base: sel.value || undefined });
127
137
  busy(b, false, "", "Create workspace");
128
138
  r.ok ? (dl.close(), (location.href = wsHref(dir, r.d.path))) : say(r.d.error);
129
139
  };
@@ -19,7 +19,7 @@ import { load, post } from "./api.ts";
19
19
  import { attach, md, preview } from "./markdown.ts";
20
20
  import { layout } from "./terms.ts";
21
21
  import { cardHref, markCurrent, railData, stateOf, titleOf, wsHref, wsOfCard } from "./workspace.ts";
22
- import { type Node, awaiting, chosen, finished, historyOf, leaves, liveIn, loopbackUrl, migrate, pickable, prune, reviewing, stageTabs, toOpen, wsKey } from "./ws-tabs.ts";
22
+ import { type Node, awaiting, chosen, finished, historyOf, leaves, liveIn, loopbackUrl, migrate, newRun, pickable, prune, reviewing, stageTabs, toOpen, wsKey } from "./ws-tabs.ts";
23
23
  import { drawPick, hidePick, initPick, setOpen } from "./run-pick.ts";
24
24
  import { age } from "./labels.ts";
25
25
  import { go } from "./views.ts";
@@ -105,8 +105,10 @@ function tabs(): Tab[] {
105
105
  const named = (a?: string) => agents.find((x) => x.cmd === a)?.name ?? "Agent";
106
106
  const live = wsCards(),
107
107
  liveKeys = new Set(live.map(key));
108
+ // A finished run's agent that is still open keeps its tab, as the sidebar keeps it.
109
+ const open = store.S.cards.filter((c) => c.state === ctx!.dir && wsOfCard(c) === ctx!.ws && !liveKeys.has(key(c)) && c.pty?.alive);
108
110
  // Each live run's terminals: its stage terminals ("Build · Claude"), other sessions, shells, the waiting note.
109
- for (const c of live) {
111
+ for (const c of [...live, ...open]) {
110
112
  const k = key(c),
111
113
  runAgent = AGENTS.find((a) => a === c.pty?.agent) ?? AGENTS.find((a) => c.tags?.includes(a)) ?? undefined;
112
114
  for (const t of stageTabs(c, named(runAgent))) out.push({ id: "agent:" + t.key, kind: "agent", agent: runAgent, title: t.title, key: t.key });
@@ -173,6 +175,7 @@ export async function showRunView(nav = false) {
173
175
  // Each workspace has its own centre: switching unmounts this one's panes (its shells keep running on the server).
174
176
  if (fresh) (stopPanes(), (card = null), (ctx = { dir, ws, k }));
175
177
  if (fresh && !was.has(k)) was.set(k, new Set(mineNow().filter(reviewing).map(key))); // what is already in review does not open the Browser
178
+ if (fresh) seenRuns.set(k, new Set(mineNow().map(key))); // what is here on arrival is not new
176
179
  // The header titles a phone's workspace: the run, else the branch.
177
180
  const w = railData().projects?.find((x) => x.dir === dir)?.workspaces?.find((x) => x.path === ws);
178
181
  document.querySelector(".hdr h1")!.textContent = want ? titleOf(want) : w?.branch || ws.split(/[\\/]/).pop() || "Workspace";
@@ -277,8 +280,19 @@ function draw() {
277
280
  // The run panel (#panel) stays docked on the right of the centre and shows one run: the one picked
278
281
  // in its header (run-pick.ts), first the run waiting on you, else the newest. A pick is sticky; a
279
282
  // run that starts waiting later does not replace it: the picker's trigger and, with the panel
280
- // collapsed, the panel button show a dot. With no run the panel is parked.
283
+ // collapsed, the panel button show a dot. Only a run created during the visit takes the pick
284
+ // (followNew). With no run the panel is parked.
281
285
  const picked = new Map<string, string>();
286
+ // Every card seen in the workspace this visit. It only grows, so a restored run or a /state tick
287
+ // missing cards never reads as new.
288
+ const seenRuns = new Map<string, Set<string>>();
289
+ function followNew() {
290
+ const seen = ctx && seenRuns.get(ctx.k);
291
+ if (!seen) return;
292
+ const c = newRun(pickable(store.S.cards, ctx!.dir, ctx!.ws, wsOfCard), seen, key);
293
+ for (const m of mineNow()) seen.add(key(m));
294
+ if (c) picked.set(ctx!.k, key(c));
295
+ }
282
296
  let pickOpen = false;
283
297
  // Shows a run in the panel (a picker row, a History row); the centre stays as it is.
284
298
  const pickRun = (k: string) => (picked.set(ctx!.k, k), draw()); // the sidebar count asked for the picker dropped down
@@ -862,7 +876,8 @@ function initSheet() {
862
876
  if (y0 === null) return;
863
877
  if (scrolled(e.target)) return void (y0 = null);
864
878
  dy = e.touches[0].clientY - y0;
865
- if (dy <= 0) return void (p.style.translate = "");
879
+ // A finger drifts a few pixels in a tap; taking those as a drag would cancel its click.
880
+ if (dy <= 10) return void (p.style.translate = "");
866
881
  e.preventDefault();
867
882
  p.style.transition = "none";
868
883
  p.style.translate = `0 ${dy}px`;
@@ -929,6 +944,7 @@ export function initRunView() {
929
944
  // A /state change: new or ended sessions, the card's own state. Panes stay mounted.
930
945
  addEventListener("kz-state", () => {
931
946
  void autoBrowse();
947
+ followNew();
932
948
  if (ctx && document.body.classList.contains("runv")) void showRunView();
933
949
  });
934
950
  }
@@ -0,0 +1,19 @@
1
+ import { expect, test } from "bun:test";
2
+ import { readFileSync } from "node:fs";
3
+ import { placeOf, SETTINGS_NAV } from "./settings-pages.ts";
4
+
5
+ const pages = new Set(SETTINGS_NAV.flatMap(([, ps]) => ps.map((p) => p.id)));
6
+ const keys = [...readFileSync(new URL("../../cli/settings.ts", import.meta.url), "utf8").matchAll(/\{ key: "([\w.]+)", label:/g)].map((m) => m[1]);
7
+
8
+ test("every setting lands on a real page, under a named subsection", () => {
9
+ expect(keys.length).toBeGreaterThan(30);
10
+ for (const k of keys) {
11
+ const [page, sub] = placeOf(k);
12
+ expect(pages.has(page)).toBe(true);
13
+ expect([k, sub === "Other"]).toEqual([k, false]);
14
+ }
15
+ });
16
+
17
+ test("a setting not placed yet falls back to General", () => {
18
+ expect(placeOf("new.thing")).toEqual(["general", "Other"]);
19
+ });
@@ -0,0 +1,44 @@
1
+ // Settings' sidebar, grouped as Orca's is. Only the page knows this: a setting's `group`
2
+ // in cli/settings.ts still decides its scope and the TUI's headings.
3
+ export type SettingsPage = { id: string; title: string; desc: string; ico: string };
4
+ export const SETTINGS_NAV: [string, SettingsPage[]][] = [
5
+ ["AI Capabilities", [
6
+ { id: "agents", title: "Agents", desc: "Which tool runs, and who does each stage.", ico: "ai" },
7
+ { id: "voice", title: "Voice", desc: "Speech-to-text dictation, run in the browser.", ico: "mic" },
8
+ ]],
9
+ ["Set Up", [
10
+ { id: "general", title: "General", desc: "Which settings you are editing, folders, and maintenance.", ico: "gear" },
11
+ { id: "integrations", title: "Integrations", desc: "Request sources and your Google account.", ico: "link" },
12
+ { id: "mobile", title: "Mobile", desc: "Open this board from your phone.", ico: "send" },
13
+ ]],
14
+ ["Workflows", [
15
+ { id: "approvals", title: "Approvals", desc: "Where a run stops and waits for you.", ico: "check" },
16
+ { id: "autofix", title: "Auto-fix", desc: "What happens to review findings.", ico: "bug" },
17
+ { id: "git", title: "Git & Source Control", desc: "Branches and commits for each run.", ico: "pen" },
18
+ { id: "terminal", title: "Terminal", desc: "The terminal dashboard.", ico: "term" },
19
+ ]],
20
+ ["Interface", [
21
+ { id: "appearance", title: "Appearance", desc: "Theme, color and motion in this browser.", ico: "note" },
22
+ { id: "notifications", title: "Notifications", desc: "Notices and sounds in this browser.", ico: "clock" },
23
+ { id: "shortcuts", title: "Shortcuts", desc: "Keyboard shortcuts for common actions.", ico: "kbd" },
24
+ ]],
25
+ ];
26
+ // First match wins: [key pattern, page, subsection].
27
+ const PLACES: [RegExp, string, string][] = [
28
+ [/^preset$/, "agents", "Defaults"],
29
+ [/^(runner|build\.|review\.executor|agent\.|subagents\.)/, "agents", "Agents"],
30
+ [/^dictation\./, "voice", "Dictation"],
31
+ [/^sources\./, "integrations", "Request sources"],
32
+ [/^(mode|approvals\.|auto_accept)/, "approvals", "Approvals"],
33
+ [/^auto_fix\./, "autofix", "Auto-fix"],
34
+ [/^git\./, "git", "Git"],
35
+ [/^ui\./, "terminal", "Terminal"],
36
+ [/^board\.chat_hotkey$/, "shortcuts", "Shortcuts"],
37
+ [/^board\./, "general", "Board"],
38
+ [/^(review\.|state\.)/, "general", "Project"],
39
+ ];
40
+ // A setting nobody has placed yet still shows, on General.
41
+ export const placeOf = (key: string): [string, string] => {
42
+ const p = PLACES.find(([re]) => re.test(key));
43
+ return p ? [p[1], p[2]] : ["general", "Other"];
44
+ };