kaizen-agent 1.59.2 → 1.60.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.
Files changed (63) hide show
  1. package/cli/add-project.test.ts +169 -0
  2. package/cli/add-project.ts +132 -0
  3. package/cli/board.test.ts +15 -0
  4. package/cli/chat.ts +1 -1
  5. package/cli/dashboard.ts +6 -2
  6. package/cli/install.test.ts +1 -1
  7. package/cli/install.ts +18 -9
  8. package/cli/pty.test.ts +89 -5
  9. package/cli/pty.ts +126 -9
  10. package/cli/restart.test.ts +169 -0
  11. package/cli/settings.test.ts +35 -0
  12. package/cli/settings.ts +69 -18
  13. package/cli/state.test.ts +119 -3
  14. package/cli/state.ts +171 -13
  15. package/cli/usage.test.ts +130 -1
  16. package/cli/web-accept.test.ts +54 -0
  17. package/cli/web-pr.test.ts +51 -0
  18. package/cli/web-symlink.test.ts +28 -0
  19. package/cli/web.ts +349 -100
  20. package/cli/worktree.test.ts +146 -1
  21. package/cli/worktree.ts +214 -4
  22. package/cli/writeback.ts +1 -1
  23. package/package.json +1 -1
  24. package/skills/kaizen/SKILL.md +5 -1
  25. package/skills/kaizen/config.default.yml +15 -2
  26. package/skills/kaizen/settings.md +1 -0
  27. package/skills/kaizen/spec-main.md +28 -2
  28. package/skills/kaizen-help/SKILL.md +1 -0
  29. package/web/board/add-project.ts +136 -0
  30. package/web/board/api.ts +1 -1
  31. package/web/board/badge.ts +5 -5
  32. package/web/board/cards.ts +11 -3
  33. package/web/board/context.ts +1 -0
  34. package/web/board/fixes.ts +3 -2
  35. package/web/board/git.ts +309 -60
  36. package/web/board/home.ts +7 -1
  37. package/web/board/ideas.ts +20 -3
  38. package/web/board/live.ts +1 -1
  39. package/web/board/main.ts +26 -9
  40. package/web/board/panel.ts +31 -16
  41. package/web/board/projects.ts +6 -85
  42. package/web/board/run-pick.ts +41 -0
  43. package/web/board/run-view.ts +286 -110
  44. package/web/board/search-match.ts +20 -0
  45. package/web/board/search.test.ts +20 -0
  46. package/web/board/search.ts +324 -0
  47. package/web/board/settings.ts +42 -5
  48. package/web/board/store.ts +3 -1
  49. package/web/board/toast.ts +4 -1
  50. package/web/board/views.ts +3 -1
  51. package/web/board/workspace.ts +127 -38
  52. package/web/board/ws-board-ui.ts +95 -0
  53. package/web/board/ws-board.test.ts +71 -0
  54. package/web/board/ws-board.ts +45 -0
  55. package/web/board/ws-tabs.test.ts +181 -0
  56. package/web/board/ws-tabs.ts +173 -0
  57. package/web/board.html +86 -36
  58. package/web/board.js +129 -44
  59. package/web/notebook.js +41 -24
  60. package/web/notes.html +26 -20
  61. package/web/term.js +1 -1
  62. package/web/video.html +26 -20
  63. package/web/video.js +76 -59
package/cli/web.ts CHANGED
@@ -3,15 +3,15 @@
3
3
  import { existsSync, readdirSync, statSync, lstatSync, realpathSync, readFileSync, watch, appendFileSync, mkdirSync, cpSync, rmSync, writeFileSync, type FSWatcher } from "node:fs";
4
4
  import { join, dirname, resolve, sep, basename } from "node:path";
5
5
  import {
6
- home, type Item, type Card, boardCards, knownProjects, remember, locate, label, tilde, searchRoots, findProjects,
6
+ home, type Item, type Card, boardCards, knownProjects, remember, canonPath, locate, label, tilde, searchRoots, findProjects,
7
7
  readInbox, writeInbox, replaceIdea, moveIdea, abandonRun, runToIdea, launchRun, parseItem, agentChoices, onPath, projectOf, KNOWN_AGENTS, plainModel, short, setArchived, writeNotes,
8
8
  appendNote, saveAttachment, pidOnPort, readText, cmdExe, sysExe, powershellExe, runGit, cardsGit, readCommit, commitPush, notice, notifier, LOGO,
9
- reviewFindings, pickFindings, backlogCards, backlogItem, startedBacklog, closeBacklog, markBacklogDone, fixPrompt, approvalPrompt, canApproveAwaiting, nativePath, closeSessions, sweepSessions, issueUrl,
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 } from "./pty.ts";
12
+ import { attachPty, writePty, 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
- import { readSources, addSource, removeSource, moveSource, setCategory, setWriteback, setPaused, readIcebox, promote, dismiss, restore, addItem, githubRepo, markDone, markReplied, gatherSource, freshImages, gatherAll, gatherDirs, due, socialUrl, socialOf } from "./sources.ts";
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";
16
16
  import * as chatgpt from "./chatgpt.ts";
17
17
  import * as google from "./google.ts";
@@ -22,6 +22,8 @@ import * as video from "./video.ts";
22
22
  import * as localsend from "./localsend.ts";
23
23
  import * as hermes from "./hermes.ts";
24
24
  import { listChats, readChat, sendChat, stopChat, deleteChat, okId as okChatId, busy as chatBusy, type Event as ChatEvent, type Upload as ChatUpload } from "./chat.ts";
25
+ import { workspaces, workspacesNow, forgetWorkspaces, workspacesAge, addWorktree, run, branchState, openPr, mergePr, removeWorktree } from "./worktree.ts";
26
+ import { gitUrl, destDir, winBad, cloneInto, branchesOf, ignoreKaizen } from "./add-project.ts";
25
27
 
26
28
  const PAGE = join(dirname(import.meta.dir), "web", "board.html");
27
29
  // The board's script: web/board/*.ts, bundled into one file by `bun run build:web`.
@@ -60,6 +62,17 @@ const served = (f: string) => installed() === VERSION && existsSync(f) ? readTex
60
62
 
61
63
  // A board answers at url and runs the installed version. A board from before the
62
64
  // version header sends none, so it counts as stale too.
65
+ // Which terminal the board launched for which stage of a run (plan, impl, review): runs/<id>/terminals.json.
66
+ // Loopback hosts only; shared by /open-url and /frameable so the board is never a way to reach other sites.
67
+ const isLoopback = (u: URL) => ["localhost", "127.0.0.1", "[::1]"].includes(u.hostname);
68
+
69
+ export const stagesOf = (dir: string, id: string): Record<string, string> => { try { return JSON.parse(readText(join(dir, "runs", id, "terminals.json"))) ?? {}; } catch { return {}; } };
70
+ export const markStage = (dir: string, id: string, stage: string, key?: string) => {
71
+ if (!stage || !key || !id || /^\.+$/.test(id)) return;
72
+ try { if (!statSync(join(dir, "runs", id)).isDirectory()) return; } catch { return; } // only an existing runs/<id>
73
+ try { writeFileSync(join(dir, "runs", id, "terminals.json"), JSON.stringify({ ...stagesOf(dir, id), [stage]: key })); } catch { /* the run dir is gone */ }
74
+ };
75
+
63
76
  export async function current(url: string) {
64
77
  const r = await fetch(url, { signal: AbortSignal.timeout(1500) }).catch(() => null);
65
78
  return !!r?.ok && r.headers.get("x-kaizen-version") === VERSION;
@@ -165,29 +178,38 @@ export async function web(repoDir: string, opts: Opts = {}) {
165
178
  };
166
179
 
167
180
  // New project…: a folder in the Projects folder setting (else ~/Projects) or at `to`,
168
- // empty or new, with .kaizen, registered. check: only say where it would go.
169
- async function makeProject(name: string, t = "", check = false): Promise<{ dir: string } | { to: string } | { error: string; status?: number }> {
170
- // Windows' rules on every platform, so a project made here also opens there:
171
- // no reserved device names (CON, NUL, COM1…), no trailing dot or space.
172
- const winBad = (n: string) => !n || /[\\/:*?"<>|\x00-\x1f]/.test(n) || /[. ]$/.test(n)
173
- || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i.test(n);
174
- const to = t ? resolve(home, nativePath(t.startsWith("~") ? home + t.slice(1) : t))
175
- : join((await projectsRoot()) || join(home, "Projects"), name);
181
+ // empty or new, with .kaizen (and a git repository when asked), registered.
182
+ // check: only say where it would go.
183
+ async function makeProject(name: string, t = "", check = false, git = false): Promise<{ dir: string; git?: boolean } | { to: string } | { error: string; status?: number }> {
184
+ const dflt = join((await projectsRoot()) || join(home, "Projects"), name);
176
185
  // The page asks while the name is typed: "con" on the way to "config" is no error yet.
177
- if (check) return { to };
186
+ if (check) return { to: t ? resolve(home, nativePath(t.startsWith("~") ? home + t.slice(1) : t)) : dflt };
178
187
  if (winBad(name)) return { error: "name the project: a folder name, without / \\ : * ? \" < > |, not ending in a dot or space, and not CON, NUL, COM1 or the like" };
179
- if (winBad(basename(to))) return { error: `${basename(to)} cannot be a folder name on Windows` };
188
+ const d = destDir(t || dflt, home, knownProjects(), await projectsRoot());
189
+ if ("error" in d) return { error: d.error };
190
+ const to = d.dir;
180
191
  let used = false;
181
192
  try { used = readdirSync(to).length > 0; } catch (e) { used = existsSync(to); }
182
193
  if (used) return { error: `${to} already exists and is not empty`, status: 409 };
183
194
  // A drive that is not there, a read-only folder, a path too long: said in a toast, not a crash.
184
195
  try { mkdirSync(join(to, ".kaizen"), { recursive: true }); }
185
196
  catch (e) { return { error: `could not create ${to}: ${(e as Error).message}` }; }
197
+ // A failed git init leaves a project without a repository: said, not rolled back.
198
+ const inited = git ? run(["git", "init", "-q", "--", to], to).ok : undefined;
199
+ if (inited) try { ignoreKaizen(to); } catch { /* the project still works */ }
186
200
  remember(to);
187
201
  changed();
188
- return { dir: join(to, ".kaizen") };
202
+ return { dir: join(to, ".kaizen"), ...(git ? { git: inited } : {}) };
189
203
  }
190
204
 
205
+ // Settings' scope, named by a project's state dir or "all": the project folder, null
206
+ // for All projects (~/.kaizen/config.yml), false for a folder the board does not know.
207
+ // No scope at all keeps the old resolution from the board's cwd, for older callers.
208
+ const settingsScope = (s: string | null) =>
209
+ !s ? undefined : s === "all" ? null : s !== join(home, ".kaizen") && states(true).includes(canonState(s)) ? dirname(canonState(s)) : false as const;
210
+
211
+ // An incoming state dir in the registry's spelling (symlinks resolved), so a symlinked project still matches.
212
+ const canonState = (d: string) => { const c = join(canonPath(dirname(d)), basename(d)); return c !== d && states(true).includes(c) ? c : d; };
191
213
  const states = (all: boolean, cur = boardState) => (all || !cur
192
214
  ? [...knownProjects().map((d) => join(d, ".kaizen")), join(home, ".kaizen")]
193
215
  : [cur]
@@ -226,11 +248,12 @@ export async function web(repoDir: string, opts: Opts = {}) {
226
248
  // works and a slow poll where it does not.
227
249
  const clients = new Set<ReadableStreamDefaultController>();
228
250
  // Shells the board started (POST /shell), by /pty key; dead ones drop on the next /shells.
229
- const shells = new Map<string, { key: string; dir: string; title: string; agent: string; run: string; pid?: number }>();
251
+ const shells = new Map<string, { key: string; dir: string; title: string; agent: string; run: string; ws?: string; pid?: number }>();
230
252
  const SHELL_CAP = 8;
231
253
  let usageCache: Usage[] = [];
232
254
  let usageAt = 0;
233
255
  let pending: ReturnType<typeof setTimeout> | null = null;
256
+ const prBusy = new Set<string>();
234
257
  const changed = () => {
235
258
  if (pending) return;
236
259
  pending = setTimeout(() => {
@@ -256,29 +279,76 @@ export async function web(repoDir: string, opts: Opts = {}) {
256
279
  if (quiet && !(own && firstSession(dir, id, own.cmd, projectOf(dir)))) return { error: "no conversation of this run to resume", status: 409 };
257
280
  const text = quiet ? "" : resumePrompt(id);
258
281
  const before = Date.now();
259
- const r = launchRun({ severity: null, where: null, text, raw: text }, dir, id, inCard(dir));
282
+ // What the card showed before the board went away (saveLive), then a line saying so.
283
+ const idx = runIndex(dir);
284
+ const prev = readSessions(dir).filter((s) => ownerOf(dir, s, idx) === id && existsSync(tailOf(s.key))).pop();
285
+ let seed: string | undefined;
286
+ try { if (prev) seed = readText(tailOf(prev.key)) + RESUMED; } catch { /* shown without it */ }
287
+ const r = launchRun({ severity: null, where: null, text, raw: text }, dir, id, { ...inCard(dir), seed });
260
288
  if (r.ok) closeSessions(dir, id, { before });
289
+ if (r.ok && prev) rmSync(tailOf(prev.key), { force: true });
261
290
  changed();
262
291
  return r;
263
292
  };
264
293
 
265
- // Runs whose in-card agent was live when Settings' Update restarted the board: the
266
- // agents end with the old board, so the new one starts them again (resumeRun). Each
267
- // entry keeps its session key, so an idea whose run had not written state.json yet is
268
- // matched to its run by the new board, once that run exists. The agents are ended here,
269
- // not left to the board's exit, so none outlives it beside its resumed self.
294
+ // Runs whose in-card agent was live when the board stopped (Settings' Update, Ctrl-C,
295
+ // systemd) or died: the agents end with the old board, so the new one starts them
296
+ // again (resumeRun). Each entry keeps its session key, so an idea whose run had not
297
+ // written state.json yet is matched to its run by the new board, once that run exists.
298
+ // On a stop the agents are ended here, not left to the board's exit, so none outlives
299
+ // it beside its resumed self; a tmux-kept one is only detached and is attached again.
300
+ // While the board runs the list is kept current (crash: true), so a board that died
301
+ // without stopping leaves it too. Each card's last screen goes beside it (tailOf).
270
302
  const RESUME_LIST = join(home, ".kaizen", "resume-after-upgrade.json");
271
- const saveLive = () => {
303
+ const TAILS = join(home, ".kaizen", "pty");
304
+ const tailOf = (key: string) => join(TAILS, `${key}.log`);
305
+ type Live = { dir: string; key: string; run: string | null; tmux?: string; resumed?: number };
306
+ // Sessions this board started again after a crash, and when: written into the list so
307
+ // a board that dies again within CRASH_AGAIN_MS does not start them a third time.
308
+ const autoResumed = new Map<string, number>();
309
+ const CRASH_AGAIN_MS = 120_000;
310
+ const written = new Map<string, number>();
311
+ const owners = new Map<string, { dir: string; run: string | null }>(), unrecorded = new Set<string>();
312
+ let stopping = false, lastList = "";
313
+ const saveLive = (crash = false) => {
314
+ if (stopping) return;
272
315
  const live = new Set(ptyKeys().filter((k) => ptyState(k)?.alive));
273
- if (!live.size) return;
274
- const list: { dir: string; key: string; run: string | null }[] = [];
275
- for (const d of states(true)) {
276
- const idx = runIndex(d);
277
- for (const s of readSessions(d)) if (live.has(s.key)) list.push({ dir: d, key: s.key, run: ownerOf(d, s, idx) });
316
+ if (!live.size) {
317
+ if (crash && lastList) { rmSync(RESUME_LIST, { force: true }); lastList = ""; }
318
+ return;
319
+ }
320
+ // Which project and run each session belongs to, found once: a run owns its session
321
+ // for good, so only new sessions and ideas' ones send the walk through every project.
322
+ // A key no project records (a Terminal page shell) is looked for once.
323
+ for (const m of [owners, written, autoResumed]) for (const k of m.keys()) if (!live.has(k)) m.delete(k);
324
+ for (const k of unrecorded) if (!live.has(k)) unrecorded.delete(k);
325
+ if ([...live].some((k) => !unrecorded.has(k) && !owners.get(k)?.run)) {
326
+ for (const d of states(true)) {
327
+ const idx = runIndex(d);
328
+ for (const s of readSessions(d)) if (live.has(s.key) && !owners.get(s.key)?.run) owners.set(s.key, { dir: d, run: ownerOf(d, s, idx) });
329
+ }
330
+ for (const k of live) if (!owners.has(k)) unrecorded.add(k);
278
331
  }
279
- try { writeFileSync(RESUME_LIST, JSON.stringify({ at: Date.now(), list })); } catch { /* nothing resumes; the card offers Resume */ }
280
- for (const k of live) exitPty(k, 200);
332
+ const list: Live[] = [...live].flatMap((key) => {
333
+ const o = owners.get(key);
334
+ return o ? [{ dir: o.dir, key, run: o.run, ...(ptyTmux(key) ? { tmux: ptyTmux(key)! } : {}), ...(autoResumed.has(key) ? { resumed: autoResumed.get(key) } : {}) }] : [];
335
+ });
336
+ try {
337
+ mkdirSync(TAILS, { recursive: true });
338
+ for (const { key } of list) {
339
+ const total = ptyState(key)!.total, t = written.get(key) === total ? null : ptyTail(key);
340
+ if (t) { writeFileSync(tailOf(key), t); written.set(key, total); }
341
+ }
342
+ const body = JSON.stringify(list);
343
+ if (!crash || body !== lastList) writeFileSync(RESUME_LIST, JSON.stringify({ at: Date.now(), crash, list }));
344
+ lastList = body;
345
+ } catch { /* nothing resumes; the card offers Resume */ }
346
+ if (crash) return;
347
+ stopping = true;
348
+ for (const k of live) if (!detachPty(k)) exitPty(k, 200);
281
349
  };
350
+ // ponytail: a 3s tick, so a crash loses up to 3s of screen; hook push() if that matters.
351
+ const keepList = setInterval(() => saveLive(true), 3000);
282
352
  // An idea's session, until its run exists and owns it (ownerOf).
283
353
  const ideaPty = new Map<string, string>();
284
354
  // Backlog items this board launched whose run has not written its state.json yet:
@@ -292,11 +362,15 @@ export async function web(repoDir: string, opts: Opts = {}) {
292
362
  const live = new Set(ptyKeys());
293
363
  if (!live.size) return () => undefined;
294
364
  const runs = new Map<string, string[]>();
365
+ const planKeys = new Set(ideaPty.values());
295
366
  for (const d of new Set(cards.filter((c) => c.kind === "run").map((c) => c.state))) {
296
367
  const ids = runIndex(d);
297
368
  for (const s of readSessions(d))
298
369
  if (live.has(s.key)) {
299
- const k = `${d}\0${ownerOf(d, s, ids)}`;
370
+ const owner = ownerOf(d, s, ids);
371
+ const k = `${d}\0${owner}`;
372
+ // The idea's agent that began this run is its plan terminal: recorded once the run exists.
373
+ if (owner && planKeys.has(s.key) && !stagesOf(d, owner).plan) markStage(d, owner, "plan", s.key);
300
374
  runs.set(k, [...(runs.get(k) ?? []), s.key]); // oldest first: the newest is the card's
301
375
  }
302
376
  }
@@ -309,7 +383,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
309
383
  if (!st.alive && (c.status === "done" || c.status === "abandoned")) return undefined;
310
384
  // Every agent session the run has had on this board, for the workspace's Agent tabs.
311
385
  const all = keys.filter((k) => ptyState(k)?.alive || k === key);
312
- return { key, alive: st.alive, asking: st.asking, busy: st.busy, all };
386
+ return { key, alive: st.alive, asking: st.asking, busy: st.busy, all, stages: c.kind === "run" ? stagesOf(c.state, c.id!) : undefined };
313
387
  };
314
388
  };
315
389
  const watchers: FSWatcher[] = [];
@@ -451,7 +525,9 @@ export async function web(repoDir: string, opts: Opts = {}) {
451
525
  if (hostname !== "127.0.0.1" && hostname !== "localhost" && !extraHosts.has(hostname)) return new Response("forbidden", { status: 403 });
452
526
  const url = new URL(req.url);
453
527
  const path = url.pathname;
454
- const asked = req.headers.get("x-kz-dir");
528
+ const qdir = () => { const v = url.searchParams.get("dir"); return v == null ? v : canonState(v); };
529
+ const asked0 = req.headers.get("x-kz-dir");
530
+ const asked = asked0 && canonState(asked0);
455
531
  const state = asked && states(true).includes(asked) ? asked : boardState;
456
532
  const project = state ? label(state) : null;
457
533
 
@@ -630,7 +706,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
630
706
  if (!ptySupported) return bad("terminals need a newer Bun", 501);
631
707
  let body: any;
632
708
  try { body = await req.json(); } catch { return bad("json body expected"); }
633
- const dir = String(body.dir ?? "");
709
+ const dir = canonState(String(body.dir ?? ""));
634
710
  if (!states(true).includes(dir) || dir === join(home, ".kaizen")) return bad("choose a project", 404);
635
711
  let cmd: string[];
636
712
  let agent = "";
@@ -668,24 +744,99 @@ export async function web(repoDir: string, opts: Opts = {}) {
668
744
  agent = a.cmd;
669
745
  cmd = [a.cmd];
670
746
  } else cmd = process.platform === "win32" ? [powershellExe()] : [process.env.SHELL || "sh", "-l"];
747
+ // A workspace folder: only an exact path from this project's own `git worktree list`.
748
+ let cwd = projectOf(dir);
749
+ if (body.ws != null) {
750
+ // A miss rechecks past a cache older than 1 s: a worktree made since is real, and a
751
+ // burst of bad paths runs git at most once a second.
752
+ const known = () => workspaces(cwd).some((w) => w.path === body.ws);
753
+ if (typeof body.ws !== "string" || !(known() || (workspacesAge(cwd) > 1000 && (forgetWorkspaces(cwd), known())))) return bad("not a workspace of this project", 400);
754
+ cwd = body.ws;
755
+ }
671
756
  for (const k of shells.keys()) if (!ptyState(k)?.alive) shells.delete(k);
672
757
  if ([...shells.values()].filter((x) => x.dir === dir).length >= SHELL_CAP) return bad(`at most ${SHELL_CAP} terminals per project: close one first`, 429);
673
758
  const key = "sh-" + crypto.randomUUID().slice(0, 8);
674
759
  const title = agent ? KNOWN_AGENTS.find((k) => k.cmd === agent)!.name : "shell";
675
- const pid = startPty(key, cmd, projectOf(dir), undefined, changed);
760
+ const pid = startPty(key, cmd, cwd, undefined, changed);
676
761
  // The run workspace that opened it (its card key), so each run keeps its own centre.
677
- shells.set(key, { key, dir, title, agent, run: runKey, pid });
762
+ shells.set(key, { key, dir, title, agent, run: runKey, ws: cwd, pid });
678
763
  changed();
679
764
  return json(shells.get(key));
680
765
  }
766
+ // The rail's + on a project: a new worktree and branch under <project>/.kaizen/wt/.
767
+ // Runs git, so /shell's guards; the branch name is checked by git check-ref-format
768
+ // and every call is an argv array.
769
+ if (req.method === "POST" && path === "/worktree") {
770
+ const refused = strict(req);
771
+ if (refused) return refused;
772
+ let body: any;
773
+ try { body = await req.json(); } catch { return bad("json body expected"); }
774
+ const dir = canonState(String(body.dir ?? ""));
775
+ if (!states(true).includes(dir) || dir === join(home, ".kaizen")) return bad("choose a project", 404);
776
+ const r = addWorktree(projectOf(dir), String(body.branch ?? "").trim(), undefined, typeof body.base === "string" && body.base.trim() ? body.base.trim() : undefined);
777
+ if (!r.ok) return bad(r.why);
778
+ changed();
779
+ return json(r);
780
+ }
781
+ // The rail's + sheet. Each of these starts git, makes a folder or registers one, so
782
+ // they take /worktree's guards and read their paths from the raw body (the generic
783
+ // POST block below would normalise a `..` away before destDir sees it).
784
+ if (req.method === "POST" && (path === "/new-project" || path === "/clone" || path === "/add-project")) {
785
+ const refused = strict(req);
786
+ if (refused) return refused;
787
+ let body: any;
788
+ try { body = await req.json(); } catch { return bad("json body expected"); }
789
+ if (!body || typeof body !== "object") return bad("json body expected");
790
+ const text = (k: string) => typeof body[k] === "string" ? body[k].trim() : "";
791
+ if (path === "/new-project") {
792
+ const r = await makeProject(text("name"), text("to"), !!body.check, body.git !== false);
793
+ return "error" in r ? bad(r.error, r.status) : json({ ok: true, ...r });
794
+ }
795
+ if (path === "/add-project") {
796
+ const d = destDir(text("path"), home, knownProjects(), await projectsRoot());
797
+ if ("error" in d) return bad(d.error);
798
+ let isDir = false;
799
+ try { isDir = statSync(d.dir).isDirectory(); } catch { /* absent */ }
800
+ if (!isDir) return bad(`${d.dir} is not a folder`);
801
+ const already = knownProjects().includes(d.dir);
802
+ try { mkdirSync(join(d.dir, ".kaizen"), { recursive: true }); }
803
+ catch (e) { return bad(`could not set up ${d.dir}: ${(e as Error).message}`); }
804
+ remember(d.dir);
805
+ changed();
806
+ return json({ ok: true, dir: join(d.dir, ".kaizen"), already });
807
+ }
808
+ // /clone: any https or ssh git URL, into a folder that is new or empty.
809
+ const g = gitUrl(body.url);
810
+ if ("error" in g) return bad(g.error);
811
+ const root = (await projectsRoot()) || join(home, "Projects");
812
+ const d = destDir(text("to") || join(root, g.name), home, knownProjects(), root);
813
+ if ("error" in d) return bad(d.error);
814
+ const to = d.dir;
815
+ if (body.check) return json({ ok: true, to, name: g.name });
816
+ let used = false;
817
+ try { used = readdirSync(to).length > 0; } catch (e) { used = existsSync(to); }
818
+ if (used) return bad(`${to} already exists and is not empty`, 409);
819
+ const c = await cloneInto(g.url, to);
820
+ if (!c.ok) return bad(c.why, 500);
821
+ mkdirSync(join(to, ".kaizen"), { recursive: true });
822
+ remember(to);
823
+ changed();
824
+ return json({ ok: true, dir: join(to, ".kaizen") });
825
+ }
826
+ // The branches a new workspace can start from, for a project the board knows.
827
+ if (req.method === "GET" && path === "/branches") {
828
+ const dir = canonState(url.searchParams.get("dir") ?? "");
829
+ if (!states(true).includes(dir) || dir === join(home, ".kaizen")) return bad("choose a project", 404);
830
+ return json(branchesOf(projectOf(dir)));
831
+ }
681
832
  if (req.method === "GET" && path === "/shells") {
682
- const dir = url.searchParams.get("dir");
833
+ const dir = qdir();
683
834
  for (const k of shells.keys()) if (!ptyState(k)?.alive) shells.delete(k);
684
835
  return json([...shells.values()].filter((s) => !dir || s.dir === dir));
685
836
  }
686
837
  // The localhost tab's "Open in browser": a Chromium app window on this computer, for
687
- // sites that refuse to be framed. Launches a process, so /shell's guards, and only an
688
- // http(s) address, passed as one --app= argument, never a shell string.
838
+ // localhost pages that refuse to be framed. Launches a process, so /shell's guards, and only a
839
+ // loopback http(s) address, passed as one --app= argument, never a shell string.
689
840
  if (req.method === "POST" && path === "/open-url") {
690
841
  const refused = strict(req);
691
842
  if (refused) return refused;
@@ -694,6 +845,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
694
845
  let u: URL;
695
846
  try { u = new URL(String(body.url ?? "")); } catch { return bad("not a url"); }
696
847
  if (!/^https?:$/.test(u.protocol)) return bad("only an http(s) address", 400);
848
+ // Loopback only: the board must not be a way to open arbitrary sites on this computer.
849
+ if (!isLoopback(u)) return bad("only a localhost address", 400);
697
850
  return json({ ok: await openApp(u.href, join(home, ".kaizen", "app-window")) });
698
851
  }
699
852
  // Whether a page may be framed: X-Frame-Options or a CSP frame-ancestors that is not
@@ -705,8 +858,10 @@ export async function web(repoDir: string, opts: Opts = {}) {
705
858
  let u: URL;
706
859
  try { u = new URL(url.searchParams.get("url") ?? ""); } catch { return bad("not a url"); }
707
860
  if (!/^https?:$/.test(u.protocol)) return bad("only an http(s) address", 400);
861
+ if (!isLoopback(u)) return bad("only a localhost address", 400);
708
862
  try {
709
- const r = await fetch(u.href, { redirect: "follow", signal: AbortSignal.timeout(4000) });
863
+ const r = await fetch(u.href, { redirect: "manual", signal: AbortSignal.timeout(4000) });
864
+ if (r.status >= 300 && r.status < 400) return json({ frameable: null }); // never follow: a redirect could lead off localhost
710
865
  r.body?.cancel().catch(() => {});
711
866
  const xfo = (r.headers.get("x-frame-options") ?? "").trim();
712
867
  const fa = /frame-ancestors([^;]*)/i.exec(r.headers.get("content-security-policy") ?? "")?.[1].trim() ?? "";
@@ -742,13 +897,13 @@ export async function web(repoDir: string, opts: Opts = {}) {
742
897
 
743
898
  // Every note of one project, text included: search, tags and backlinks are the page's.
744
899
  if (req.method === "GET" && path === "/vault") {
745
- const dir = url.searchParams.get("dir") ?? state ?? join(home, ".kaizen");
900
+ const dir = qdir() ?? state ?? join(home, ".kaizen");
746
901
  if (!states(true).includes(dir)) return bad("unknown state dir", 404);
747
902
  return json({ dir, notes: listNotes(dir) });
748
903
  }
749
904
 
750
905
  if (req.method === "GET" && (path === "/project-tree" || path === "/project-text")) {
751
- const treeState = url.searchParams.get("dir") ?? state;
906
+ const treeState = qdir() ?? state;
752
907
  if (!treeState || !states(true).includes(treeState) || treeState === join(home, ".kaizen")) return bad("choose a project", 404);
753
908
  const rel = url.searchParams.get("path") ?? "";
754
909
  const parts = rel ? rel.split("/") : [];
@@ -780,7 +935,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
780
935
 
781
936
  // What a note can link to on this project's board: runs, findings, backlog, ideas.
782
937
  if (req.method === "GET" && path === "/links") {
783
- const dir = url.searchParams.get("dir") ?? state ?? join(home, ".kaizen");
938
+ const dir = qdir() ?? state ?? join(home, ".kaizen");
784
939
  if (!states(true).includes(dir)) return bad("unknown state dir", 404);
785
940
  return json(boardIndex(dir));
786
941
  }
@@ -800,7 +955,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
800
955
  // A project's own logo, for the project pickers: only a known project, only the fixed
801
956
  // names in LOGOS, sandboxed so an SVG opened directly runs nothing on this origin.
802
957
  if (req.method === "GET" && path === "/project-logo") {
803
- const dir = url.searchParams.get("dir") ?? "";
958
+ const dir = qdir() ?? "";
804
959
  const f = states(true).includes(dir) ? projectLogo(dir) : null;
805
960
  if (!f) return bad("no logo", 404);
806
961
  const ext = f.slice(f.lastIndexOf(".") + 1).toLowerCase();
@@ -837,20 +992,44 @@ export async function web(repoDir: string, opts: Opts = {}) {
837
992
  return !root || d === state || (fold(p).startsWith(inside)
838
993
  && (!isGroup(p) || filled(d) || fold(dirname(p)) !== fold(root)));
839
994
  });
995
+ for (const d of dirs) healRuns(d);
840
996
  const cards = boardCards(dirs, Date.now()), pty = ptyOf(cards);
841
997
  // The git mark, for the cards whose panel offers commit and push: one status per project.
842
- const marks = new Map<string, Record<string, string>>();
998
+ const marks = new Map<string, Record<string, string>>(), dues = new Map<string, Record<string, "commit" | "push">>();
843
999
  const markable = (c: Card) => c.kind === "run" && !c.archived && (c.status === "done" || c.awaiting === "approvals.review") && c.state !== join(home, ".kaizen");
844
1000
  for (const d of new Set(cards.filter(markable).map((c) => c.state)))
845
- marks.set(d, cardsGit(d, cards.filter((c) => markable(c) && c.state === d).map((c) => c.id!)));
1001
+ marks.set(d, cardsGit(d, cards.filter((c) => markable(c) && c.state === d).map((c) => c.id!), dues.set(d, {}).get(d)));
846
1002
  // Open findings the panel's Fix findings form would offer, on the same runs.
847
1003
  const openFindings = (c: Card) => c.kind === "run" && !c.archived && (c.status === "done" || c.awaiting === "findings" || c.awaiting === "approvals.review") && c.state !== join(home, ".kaizen")
848
1004
  ? reviewFindings(c.state, c.id!).filter((f) => !f.done).length || undefined : undefined;
1005
+ // The agents open now, for the sidebar cards: one list per tick, from the cards' sessions and the board's agent
1006
+ // shells. ws is as the card or shell has it; the page resolves it to a listed workspace. Ended agents are left out.
1007
+ // What an agent printed goes only to a viewer on this machine, not to a tailnet host or a phone.
1008
+ const ip = srv.requestIP(req)?.address ?? "";
1009
+ const loopback = (hostname === "127.0.0.1" || hostname === "localhost") && /^(127\.|::1$|::ffff:127\.)/.test(ip)
1010
+ && !["x-forwarded-for", "x-forwarded-host", "forwarded", "tailscale-user-login", "tailscale-user-name"].some((h) => req.headers.has(h));
1011
+ const agents: any[] = [], seenKey = new Set<string>(), ptys = cards.map(pty);
1012
+ const addAgent = (key: string, dir: string, ws: string | undefined, cmd: string | undefined, run?: string) => {
1013
+ const st = seenKey.has(key) ? null : ptyState(key);
1014
+ if (!st?.alive) return;
1015
+ seenKey.add(key);
1016
+ const name = KNOWN_AGENTS.find((k) => k.cmd === cmd)?.name.split(" ")[0] ?? "Agent";
1017
+ 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 } : {}) });
1018
+ };
1019
+ for (const x of shells.values()) if (x.agent) addAgent(x.key, x.dir, x.ws, x.agent, x.run);
1020
+ cards.forEach((c, i) => { for (const k of ptys[i]?.all ?? []) addAgent(k, c.state, c.ws, KNOWN_AGENTS.find((a) => c.tags?.includes(a.cmd))?.cmd, c.kind === "run" ? c.id : undefined); });
1021
+ const entry = (d: string) => ({ dir: d, label: label(d), logo: !!projectLogo(d),
1022
+ workspaces: d === join(home, ".kaizen") ? [{ path: d, branch: "", main: true }] : workspacesNow(projectOf(d)) });
849
1023
  return json({
850
1024
  project, all, dir: state,
851
- projects: picker.map((d) => ({ dir: d, label: label(d), logo: !!projectLogo(d) })),
1025
+ // Each project's workspaces (git worktrees, or the one folder); the global queue is its own one.
1026
+ projects: picker.map(entry),
1027
+ // Dirs with a card the picker leaves out (the global queue, a project outside the
1028
+ // Projects folder): the rail still needs their workspaces so a waiting run shows.
1029
+ rail: [...new Set(cards.map((c) => c.state))].filter((d) => !picker.includes(d)).map(entry),
852
1030
  fresh: unset.map((d) => ({ dir: join(d, ".kaizen"), label: tilde(d) })),
853
- cards: cards.map((c) => ({ ...c, notice: notice(c), git: markable(c) ? marks.get(c.state)?.[c.id!] : undefined, open: openFindings(c), pty: pty(c) })),
1031
+ agents,
1032
+ cards: cards.map((c, i) => ({ ...c, notice: notice(c), git: markable(c) ? marks.get(c.state)?.[c.id!] : undefined, gitDue: markable(c) ? dues.get(c.state)?.[c.id!] : undefined, open: openFindings(c), pty: ptys[i] })),
854
1033
  backlog: backlogCards(dirs).map((b) => ({ ...b, starting: backlogLaunched.has(`${b.state}\0${b.source}#${b.n}`) || undefined })),
855
1034
  now: Date.now(),
856
1035
  });
@@ -858,7 +1037,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
858
1037
 
859
1038
  if (req.method === "GET" && path.startsWith("/run/")) {
860
1039
  const id = decodeURIComponent(path.slice(5));
861
- const dir = url.searchParams.get("dir") ?? state;
1040
+ const dir = qdir() ?? state;
862
1041
  if (!dir || !states(true).includes(dir) || !/^[\w.-]+$/.test(id)) return bad("no such run", 404);
863
1042
  const base = join(dir, "runs", id);
864
1043
  if (!existsSync(base)) return bad("no such run", 404);
@@ -874,13 +1053,15 @@ export async function web(repoDir: string, opts: Opts = {}) {
874
1053
  findings: dir === join(home, ".kaizen") ? [] : reviewFindings(dir, id),
875
1054
  // The global state dir sits in $HOME, which is not a project to commit.
876
1055
  commit: readCommit(dir, id), git: dir === join(home, ".kaizen") ? { repo: false } : runGit(dir, id),
1056
+ // The run's own branch and pull request, for the Git tab; null when it has no worktree.
1057
+ branch: dir === join(home, ".kaizen") ? null : branchState(dirname(dir), id, changed),
877
1058
  });
878
1059
  }
879
1060
 
880
1061
  if (req.method === "GET" && path === "/sources") {
881
1062
  // One project's sources, or with no dir every known project's: each entry
882
1063
  // says which project it belongs to. Nothing is assumed from where the board started.
883
- const dir = url.searchParams.get("dir");
1064
+ const dir = qdir();
884
1065
  if (dir && !states(true).includes(dir)) return bad("unknown state dir", 404);
885
1066
  const sources = [], icebox = [], dismissed = [], failed = [];
886
1067
  for (const d of dir ? [dir] : states(true)) {
@@ -908,14 +1089,20 @@ export async function web(repoDir: string, opts: Opts = {}) {
908
1089
  }
909
1090
 
910
1091
  if (req.method === "GET" && path === "/agents") {
911
- const dir = url.searchParams.get("dir");
1092
+ const dir = qdir();
912
1093
  if (!dir || !states(true).includes(dir)) return bad("unknown state dir", 404);
913
1094
  return json(agentChoices(projectOf(dir)));
914
1095
  }
915
1096
 
916
1097
  if (req.method === "GET" && path === "/settings") {
917
1098
  const { listSettings } = await import("./settings.ts");
918
- const cfg = listSettings(repoDir);
1099
+ const scope = settingsScope(url.searchParams.get("scope"));
1100
+ if (scope === false) return bad("unknown project", 404);
1101
+ const cfg = listSettings(repoDir, scope);
1102
+ Object.assign(cfg, {
1103
+ scope: scope ? join(scope, ".kaizen") : "all",
1104
+ projects: states(true).filter((d) => d !== join(home, ".kaizen")).map((d) => ({ dir: d, label: label(d) })),
1105
+ });
919
1106
  Object.assign(cfg, { phoneUrls: [...webHosts()].filter((h) => /^[a-z0-9-]+(?:\.[a-z0-9-]+)*\.ts\.net$/.test(h)).map((h) => `https://${h}`) });
920
1107
  // Connected, the model is chosen from what the plan offers rather than typed.
921
1108
  const m = cfg.rows.find((r) => r.key === "sources.model");
@@ -1029,8 +1216,13 @@ export async function web(repoDir: string, opts: Opts = {}) {
1029
1216
  if (!local(req)) return bad("cross-origin write refused", 403);
1030
1217
  let body: any;
1031
1218
  try { body = await req.json(); } catch { return bad("json body expected"); }
1032
- const { setSetting } = await import("./settings.ts");
1033
- const r = setSetting(repoDir, String(body.key ?? ""), String(body.value ?? ""));
1219
+ const { setSetting, resetSetting } = await import("./settings.ts");
1220
+ const scope = settingsScope(body.scope == null ? null : String(body.scope));
1221
+ if (body.reset && typeof scope !== "string") return bad("only a project's own value can be reset");
1222
+ if (scope === false) return bad("unknown project", 404);
1223
+ const r = body.reset
1224
+ ? resetSetting(repoDir, String(body.key ?? ""), scope as string)
1225
+ : setSetting(repoDir, String(body.key ?? ""), String(body.value ?? ""), scope);
1034
1226
  return "error" in r ? bad(r.error) : json(r);
1035
1227
  }
1036
1228
 
@@ -1043,7 +1235,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1043
1235
  if (!cmd) return bad("No folder dialog found: install zenity or kdialog, or type the path");
1044
1236
  picking = true;
1045
1237
  try {
1046
- const p = Bun.spawn(cmd, { stdin: "ignore", stdout: "pipe", stderr: "pipe" });
1238
+ const p = Bun.spawn(cmd, { stdin: "ignore", stdout: "pipe", stderr: "pipe", windowsHide: true });
1047
1239
  const [out, err, code] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text(), p.exited]);
1048
1240
  // osascript ends a folder with "/"; a bare root (/, C:\) keeps its own.
1049
1241
  const picked = /^([A-Za-z]:)?[\\/]$/.test(out.trim()) ? out.trim() : out.trim().replace(/[\\/]+$/, "");
@@ -1059,7 +1251,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1059
1251
  // Attachments only, never a run's own files: the path must sit under an
1060
1252
  // attachments/ directory of a known state dir, with no way back up.
1061
1253
  if (req.method === "GET" && path === "/file") {
1062
- const dir = url.searchParams.get("dir") ?? state;
1254
+ const dir = qdir() ?? state;
1063
1255
  const p = url.searchParams.get("p") ?? "";
1064
1256
  if (!dir || !states(true).includes(dir)) return bad("unknown state dir", 404);
1065
1257
  if (!/^(runs\/[\w.-]+\/)?attachments\/[\w.-]+$/.test(p)) return bad("bad path");
@@ -1072,7 +1264,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1072
1264
  // An icebox image, sent on to a link read fresh from its source: the one kept
1073
1265
  // since the gather may have expired. Only an https link the item holds is followed.
1074
1266
  if (req.method === "GET" && path === "/ice-image") {
1075
- const dir = url.searchParams.get("dir") ?? "";
1267
+ const dir = qdir() ?? "";
1076
1268
  if (!states(true).includes(dir)) return bad("unknown state dir", 404);
1077
1269
  const u = (await freshImages(dir, url.searchParams.get("id") ?? ""))[Number(url.searchParams.get("i"))];
1078
1270
  if (!u || !/^https:\/\//.test(u)) return bad("no such image", 404);
@@ -1162,6 +1354,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1162
1354
  if (!local(req)) return bad("cross-origin write refused", 403);
1163
1355
  let body: any;
1164
1356
  try { body = await req.json(); } catch { return bad("json body expected"); }
1357
+ for (const k of ["dir", "to"]) if (typeof body?.[k] === "string" && body[k]) body[k] = canonState(body[k]);
1165
1358
 
1166
1359
  // The Video page: a place by index, a video folder by name, both checked in video.ts.
1167
1360
  if (path.startsWith("/video/")) {
@@ -1249,49 +1442,14 @@ export async function web(repoDir: string, opts: Opts = {}) {
1249
1442
  return json({ ok: true, added: knownProjects().length - before });
1250
1443
  }
1251
1444
 
1252
- // A new, empty project: a folder in the projects folder (else ~/Projects), or
1253
- // where the page names, set up at once. /find only sees folders that already
1254
- // have a .kaizen, so a folder made by hand never shows there.
1255
- if (path === "/new-project") {
1256
- const r = await makeProject(typeof body.name === "string" ? body.name.trim() : "", typeof body.to === "string" ? body.to.trim() : "", !!body.check);
1257
- return "error" in r ? bad(r.error, r.status) : json({ ok: true, ...r });
1258
- }
1259
-
1260
- // Clone a GitHub repository into the projects folder (else ~/Projects) and
1261
- // set it up as a project. Arguments go to git as an array: no shell.
1262
- if (path === "/clone") {
1263
- const link = typeof body.url === "string" ? body.url.trim() : "";
1264
- const name = githubRepo(link);
1265
- if (!name) return bad("paste a GitHub link: https://github.com/owner/repo or git@github.com:owner/repo.git");
1266
- const root = (await projectsRoot()) || join(home, "Projects");
1267
- // The page may name the folder: typed (~ allowed, relative to home) or picked.
1268
- // A new one is made, parents too; an empty one is used; anything else refused.
1269
- let to = join(root, name);
1270
- if (typeof body.to === "string" && body.to.trim()) {
1271
- const t = body.to.trim();
1272
- to = resolve(home, nativePath(t.startsWith("~") ? home + t.slice(1) : t));
1273
- }
1274
- if (body.check) return json({ ok: true, to, name });
1275
- let used = false;
1276
- try { used = readdirSync(to).length > 0; } catch (e) { used = existsSync(to); }
1277
- if (used) return bad(`${to} already exists and is not empty`, 409);
1278
- mkdirSync(to, { recursive: true });
1279
- const p = Bun.spawn(["git", "clone", "--", link, to], { stdin: "ignore", stdout: "ignore", stderr: "pipe", env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_SSH_COMMAND: process.env.GIT_SSH_COMMAND ?? "ssh -o BatchMode=yes" }, windowsHide: true });
1280
- const [err, code] = await Promise.all([new Response(p.stderr).text(), p.exited]);
1281
- if (code !== 0) return bad(err.trim().split("\n").filter(Boolean).pop() || "git clone failed", 500);
1282
- mkdirSync(join(to, ".kaizen"), { recursive: true });
1283
- remember(to);
1284
- changed();
1285
- return json({ ok: true, dir: join(to, ".kaizen") });
1286
- }
1287
-
1288
1445
  // No project here means the global inbox, which is where the TUI puts ideas too.
1289
- const dir: string = body.dir ?? state ?? join(home, ".kaizen");
1446
+ let dir: string = body.dir ?? state ?? join(home, ".kaizen");
1290
1447
  // Choosing a folder from the projects folder is what sets it up: an empty
1291
1448
  // .kaizen, which the first run fills in. Only folders the board offered.
1292
1449
  if (path === "/cd" && dir === join(dirname(dir), ".kaizen") && (await fresh()).includes(dirname(dir))) {
1293
1450
  mkdirSync(dir, { recursive: true });
1294
1451
  remember(dirname(dir));
1452
+ dir = canonState(dir);
1295
1453
  }
1296
1454
  if (!dir || !states(true).includes(dir)) return bad("unknown state dir", 404);
1297
1455
 
@@ -1574,6 +1732,32 @@ export async function web(repoDir: string, opts: Opts = {}) {
1574
1732
  return json(r, r.ok ? 200 : 409);
1575
1733
  }
1576
1734
 
1735
+ // The Git tab's later steps, on the same runs /commit takes: open the branch's pull
1736
+ // request, merge it, then remove the worktree once its work is on the base.
1737
+ if (path === "/pr") {
1738
+ const id = String(body.id ?? "");
1739
+ if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
1740
+ // One step per run at a time: a second tab's Merge or Remove waits its turn.
1741
+ const lock = `${dir}\0${id}`;
1742
+ if (prBusy.has(lock)) return bad("Another git step is running on this run. Try again when it finishes.", 409);
1743
+ if (dir === join(home, ".kaizen")) return bad("no project", 409);
1744
+ let run: any;
1745
+ try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return bad("no such run", 404); }
1746
+ if (run.stage !== "done" && run.awaiting !== "approvals.review") return bad("this run is not finished", 409);
1747
+ const project = dirname(dir);
1748
+ if (body.op !== "remove" && gateOf(dir, id) === "needs") return bad("This run is not approved yet. Approve it first.", 409);
1749
+ prBusy.add(lock);
1750
+ let r: { ok: boolean };
1751
+ try {
1752
+ r = body.op === "create" ? await openPr(project, id, String(body.title ?? ""), String(body.body ?? ""), body.draft === true)
1753
+ : body.op === "merge" ? await mergePr(project, id)
1754
+ : body.op === "remove" ? await removeWorktree(project, id)
1755
+ : { ok: false as const, why: "unknown op" };
1756
+ } finally { prBusy.delete(lock); }
1757
+ changed();
1758
+ return json(r, r.ok ? 200 : 409);
1759
+ }
1760
+
1577
1761
  // Fix picked findings, on the same runs /commit takes and for the same reason
1578
1762
  // never in the global state dir: the agent starts in a project, and the run is
1579
1763
  // not there. Only numbers the review itself holds reach the prompt.
@@ -1587,11 +1771,20 @@ export async function web(repoDir: string, opts: Opts = {}) {
1587
1771
  const nums = pickFindings(dir, id, body.nums);
1588
1772
  if (!nums) return bad("pick open findings of this review");
1589
1773
  const text = fixPrompt(id, nums);
1774
+ // An agent already open in this run's card takes the fix there, busy or not:
1775
+ // the text queues in it, and no second agent opens beside it.
1776
+ const live = readSessions(dir).find((s) => ptyState(s.key)?.alive && ownerOf(dir, s) === id);
1777
+ if (live) {
1778
+ writePty(live.key, text + "\r");
1779
+ markStage(dir, id, "review", live.key);
1780
+ changed();
1781
+ return json({ ok: true, pty: live.key, reused: true });
1782
+ }
1590
1783
  // The run's conversation picks the fix up, and once that window is open the
1591
1784
  // waiting one ends. A failed launch leaves it: the decision has nowhere else.
1592
1785
  const before = Date.now();
1593
1786
  const r = launchRun({ severity: null, where: null, text, raw: text }, dir, id, inCard(dir));
1594
- if (r.ok) closeSessions(dir, id, { before });
1787
+ if (r.ok) (closeSessions(dir, id, { before }), markStage(dir, id, "review", r.pty));
1595
1788
  changed();
1596
1789
  return json(r.ok
1597
1790
  ? { ok: true, agent: r.agent, pty: r.pty }
@@ -1606,6 +1799,16 @@ export async function web(repoDir: string, opts: Opts = {}) {
1606
1799
  if (dir === join(home, ".kaizen")) return bad("no project to run in", 409);
1607
1800
  let run: any;
1608
1801
  try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return bad("no such run", 404); }
1802
+ // A healed run (done by its agent, never approved) has no agent to continue: approving
1803
+ // it is /accept's record + finish, for any caller; a revise has nothing to send back to.
1804
+ if (run.healed === true && body.awaiting === "approvals.review") {
1805
+ if (body.why !== undefined) return bad("this run is already finished: approve or archive it", 409);
1806
+ const why = recordAcceptance(dir, id, "board");
1807
+ if (why) return bad(why, 409);
1808
+ finishRun(dir, id);
1809
+ changed();
1810
+ return json({ ok: true });
1811
+ }
1609
1812
  if (!canApproveAwaiting(run.awaiting) || run.awaiting !== body.awaiting) return bad("this run is not waiting on that approval", 409);
1610
1813
  if (run.awaiting === "findings" && body.why !== undefined) return bad("open findings can only be approved as-is or fixed individually", 409);
1611
1814
  if (body.why !== undefined && !String(body.why).trim()) return bad("a revise needs a comment");
@@ -1619,12 +1822,34 @@ export async function web(repoDir: string, opts: Opts = {}) {
1619
1822
  const before = Date.now();
1620
1823
  const r = launchRun({ severity: null, where: null, text, raw: text }, dir, id, inCard(dir));
1621
1824
  if (r.ok) closeSessions(dir, id, { before });
1825
+ // The plan's approval starts the build; fixing open findings is the review stage again.
1826
+ if (r.ok) markStage(dir, id, run.awaiting === "approvals.plan" ? "impl" : run.awaiting === "findings" ? "review" : "", r.pty);
1827
+ // Approving the review as-is is the user's acceptance, on record before the
1828
+ // agent marks the run done; a revise is not.
1829
+ if (r.ok && body.why === undefined && (run.awaiting === "approvals.review" || run.awaiting === "findings")) recordAcceptance(dir, id, "board");
1622
1830
  changed();
1623
1831
  return json(r.ok
1624
1832
  ? { ok: true, agent: r.agent, pty: r.pty }
1625
1833
  : { ok: false, why: r.why, manual: r.manual, agent: r.agent }, r.ok ? 200 : 500);
1626
1834
  }
1627
1835
 
1836
+ // Approve a run an agent marked done without the user's acceptance (healed): the line
1837
+ // only, no agent is started.
1838
+ if (path === "/accept") {
1839
+ const id = String(body.id ?? "");
1840
+ if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
1841
+ if (gateOf(dir, id) !== "needs") return bad("this run is not waiting on your approval", 409);
1842
+ // Only a finished-but-unapproved run: a genuine review goes through /decide.
1843
+ let st: any = {};
1844
+ try { st = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch {}
1845
+ if (st.stage !== "done" && st.healed !== true) return bad("this run is in review: approve it with the review's Approve", 409);
1846
+ const why = recordAcceptance(dir, id, "board");
1847
+ if (why) return bad(why, 409);
1848
+ finishRun(dir, id);
1849
+ changed();
1850
+ return json({ ok: true });
1851
+ }
1852
+
1628
1853
  // Start a run's agent again after it ended mid-stage (resumeRun).
1629
1854
  if (path === "/resume") {
1630
1855
  const id = String(body.id ?? "");
@@ -1660,22 +1885,38 @@ export async function web(repoDir: string, opts: Opts = {}) {
1660
1885
  }); }
1661
1886
 
1662
1887
  // Read once and removed first, so a board that fails to start one does not retry it
1663
- // forever. A list older than an hour is from an upgrade whose board never came back
1664
- // (a failed Windows hand-off): too late to pick its runs up unasked.
1888
+ // forever. A stop's list older than an hour is from an upgrade whose board never came
1889
+ // back (a failed Windows hand-off): too late to pick its runs up unasked. A crash's
1890
+ // list is current to the last few seconds of the board that wrote it, however old.
1891
+ // Every agent starts again in its card, never in a window: a board set to open
1892
+ // terminals leaves those runs on their Resume button.
1665
1893
  if (existsSync(RESUME_LIST)) {
1666
- let saved: { at?: number; list?: { dir: string; key: string; run: string | null }[] } = {};
1894
+ let saved: { at?: number; crash?: boolean; list?: Live[] } = {};
1667
1895
  try { saved = JSON.parse(readText(RESUME_LIST)); } catch { /* unreadable: nothing to resume */ }
1668
1896
  rmSync(RESUME_LIST, { force: true });
1669
1897
  const done = new Set<string>();
1670
- for (const { dir, key, run } of Date.now() - (saved.at ?? 0) < 3600_000 ? saved.list ?? [] : []) {
1898
+ for (const { dir, key, run, tmux, resumed } of saved.crash || Date.now() - (saved.at ?? 0) < 3600_000 ? saved.list ?? [] : []) {
1899
+ // Kept in tmux and still there: the same agent, mid-step, shown in its card again.
1900
+ if (tmux && tmuxAlive(tmux)) {
1901
+ try {
1902
+ startPty(key, [], projectOf(dir), join(dir, "sessions", `${key}.pid`), changed, { tmux, attach: true });
1903
+ console.log(` reattached ${run ?? key}`);
1904
+ continue;
1905
+ } catch { /* started again below */ }
1906
+ }
1671
1907
  const s = run ? null : readSessions(dir).find((x) => x.key === key);
1672
1908
  const id = run ?? (s ? ownerOf(dir, s) : null);
1673
1909
  if (!id || done.has(`${dir}\0${id}`)) continue;
1674
1910
  done.add(`${dir}\0${id}`);
1911
+ if (saved.crash && resumed && Date.now() - resumed < CRASH_AGAIN_MS) { console.log(` not resuming ${id}: the board died again right after resuming it`); continue; }
1912
+ if (launchMode(projectOf(dir)) !== "card") continue;
1675
1913
  const r = resumeRun(dir, id);
1914
+ if (saved.crash && "pty" in r && r.pty) autoResumed.set(r.pty, Date.now());
1676
1915
  console.log(` ${"error" in r || !r.ok ? "could not resume" : "resumed"} ${id}${"error" in r ? ` (${r.error})` : !r.ok ? ` (${r.why})` : ""}`);
1677
1916
  }
1678
1917
  }
1918
+ // Last screens nothing picked up: a run left on its Resume button keeps its own a day.
1919
+ try { for (const f of readdirSync(TAILS)) if (Date.now() - statSync(join(TAILS, f)).mtimeMs > 86_400_000) rmSync(join(TAILS, f), { force: true }); } catch { /* no folder yet */ }
1679
1920
 
1680
1921
  const url = `http://127.0.0.1:${server.port}/`;
1681
1922
  console.log(`\n kaizen web ${url}`);
@@ -1684,7 +1925,15 @@ export async function web(repoDir: string, opts: Opts = {}) {
1684
1925
  if (opts.open !== false) await openApp(url);
1685
1926
 
1686
1927
  await new Promise<void>((resolve) => {
1687
- const stop = () => { clearInterval(poll); clearInterval(ping); clearInterval(gather); clearInterval(loop); for (const w of watchers) { try { w.close(); } catch { /* gone */ } } server.stop(true); resolve(); };
1928
+ // The card agents are listed for the next board and ended (saveLive); the short wait
1929
+ // lets each take its /exit, or be ended with what it started, before this process goes.
1930
+ const stop = () => {
1931
+ const live = ptyKeys().some((k) => ptyState(k)?.alive);
1932
+ saveLive();
1933
+ clearInterval(poll); clearInterval(ping); clearInterval(gather); clearInterval(loop); clearInterval(keepList);
1934
+ for (const w of watchers) { try { w.close(); } catch { /* gone */ } }
1935
+ setTimeout(() => { server.stop(true); resolve(); }, live ? 400 : 0);
1936
+ };
1688
1937
  process.on("SIGINT", stop);
1689
1938
  process.on("SIGTERM", stop);
1690
1939
  });