kaizen-agent 1.61.5 → 1.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/README.md +2 -2
  2. package/agents/kaizen-builder.md +3 -0
  3. package/agents/kaizen-planner.md +3 -0
  4. package/agents/kaizen-reviewer.md +2 -0
  5. package/assets/kaizen-logo.png +0 -0
  6. package/assets/kaizen.ico +0 -0
  7. package/cli/__pycache__/computer-helper.cpython-314.pyc +0 -0
  8. package/cli/accounts.test.ts +126 -0
  9. package/cli/accounts.ts +116 -0
  10. package/cli/add-project.ts +4 -2
  11. package/cli/agent-prefs.test.ts +127 -0
  12. package/cli/agent-prefs.ts +106 -0
  13. package/cli/board.test.ts +4 -5
  14. package/cli/computer-helper.py +299 -0
  15. package/cli/computer.test.ts +155 -0
  16. package/cli/computer.ts +66 -0
  17. package/cli/dashboard.ts +14 -15
  18. package/cli/install.ts +67 -4
  19. package/cli/keep-awake.ts +30 -0
  20. package/cli/notes.test.ts +9 -0
  21. package/cli/project-tree.test.ts +1 -0
  22. package/cli/pty.test.ts +2 -1
  23. package/cli/pty.ts +6 -5
  24. package/cli/report.test.ts +59 -0
  25. package/cli/report.ts +62 -0
  26. package/cli/restart.test.ts +1 -0
  27. package/cli/settings.test.ts +21 -1
  28. package/cli/settings.ts +19 -11
  29. package/cli/setup.test.ts +2 -2
  30. package/cli/skills.test.ts +89 -0
  31. package/cli/skills.ts +112 -0
  32. package/cli/state.test.ts +46 -4
  33. package/cli/state.ts +127 -41
  34. package/cli/term-image.test.ts +23 -0
  35. package/cli/term-image.ts +26 -0
  36. package/cli/usage.test.ts +8 -2
  37. package/cli/usage.ts +8 -6
  38. package/cli/video.test.ts +5 -5
  39. package/cli/web-accept.test.ts +1 -0
  40. package/cli/web-decide.test.ts +1 -0
  41. package/cli/web-pr.test.ts +1 -0
  42. package/cli/web-skills.test.ts +32 -0
  43. package/cli/web-symlink.test.ts +1 -0
  44. package/cli/web.ts +179 -20
  45. package/cli/workers.test.ts +319 -0
  46. package/cli/workers.ts +380 -0
  47. package/cli/worktree.test.ts +21 -2
  48. package/cli/worktree.ts +21 -2
  49. package/package.json +1 -1
  50. package/skills/kaizen/config.default.yml +33 -1
  51. package/skills/kaizen/settings.md +1 -1
  52. package/skills/kaizen/skill.json +1 -0
  53. package/skills/kaizen/spec-build.md +22 -2
  54. package/skills/kaizen/spec-main.md +9 -0
  55. package/skills/kaizen/spec-plan.md +18 -1
  56. package/skills/kaizen/spec-review.md +4 -0
  57. package/skills/kaizen/spec.md +15 -0
  58. package/skills/kaizen-help/SKILL.md +1 -0
  59. package/skills/kaizen-help/skill.json +1 -0
  60. package/skills/media/kaizen-book/skill.json +1 -0
  61. package/skills/media/kaizen-deck/skill.json +1 -0
  62. package/skills/media/kaizen-video/skill.json +1 -0
  63. package/skills/optional/kaizen-computer/SKILL.md +38 -0
  64. package/skills/optional/kaizen-computer/skill.json +1 -0
  65. package/web/board/add-project.ts +3 -3
  66. package/web/board/agent-favicons.ts +9 -0
  67. package/web/board/agent-term.ts +1 -1
  68. package/web/board/api.ts +1 -1
  69. package/web/board/approvals.ts +1 -1
  70. package/web/board/cards.ts +50 -7
  71. package/web/board/dictation.ts +46 -3
  72. package/web/board/fixes.ts +1 -1
  73. package/web/board/home.ts +1 -1
  74. package/web/board/icebox.ts +1 -1
  75. package/web/board/keys.ts +5 -15
  76. package/web/board/onboarding.ts +1 -1
  77. package/web/board/panel.ts +24 -20
  78. package/web/board/phone.ts +4 -1
  79. package/web/board/run-view.ts +11 -6
  80. package/web/board/settings-accounts.ts +60 -0
  81. package/web/board/settings-agents.ts +102 -0
  82. package/web/board/settings-orchestration.ts +32 -0
  83. package/web/board/settings-pages.test.ts +5 -0
  84. package/web/board/settings-pages.ts +10 -4
  85. package/web/board/settings-skills.ts +47 -0
  86. package/web/board/settings-voice.test.ts +18 -0
  87. package/web/board/settings-voice.ts +28 -0
  88. package/web/board/settings.ts +40 -4
  89. package/web/board/terms.ts +2 -2
  90. package/web/board/update.ts +1 -1
  91. package/web/board/views.ts +1 -0
  92. package/web/board/ws-board.test.ts +6 -0
  93. package/web/board/ws-board.ts +2 -0
  94. package/web/board.html +21 -7
  95. package/web/board.js +134 -84
  96. package/web/notebook.js +2 -2
  97. package/web/notes.html +8 -6
  98. package/web/term.js +27 -27
  99. package/web/term.ts +25 -3
  100. package/web/video.html +7 -5
  101. package/web/video.js +2 -2
package/cli/skills.ts ADDED
@@ -0,0 +1,112 @@
1
+ // The skills kaizen ships: each folder under skills/ with a SKILL.md, plus an optional
2
+ // skill.json ({ title, group, needs, off_by_default }), so a new folder needs no change elsewhere.
3
+ // Turning one off removes kaizen's own links for this user; a real folder, or a link to
4
+ // anything else, under the same name stays. ~/.kaizen/skills-off.json keeps the choice.
5
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, readlinkSync, renameSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
6
+ import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
7
+
8
+ export type Skill = { id: string; rel: string; title: string; description: string; group: "core" | "media" | "optional"; needs: string[]; offByDefault: boolean };
9
+ export const SKILL_HOMES = [
10
+ { name: "Claude Code", dir: ".claude" }, { name: "Codex", dir: ".codex" }, { name: "Antigravity", dir: ".agents" },
11
+ { name: "OpenCode", dir: ".opencode" }, { name: "Cursor", dir: ".cursor" }, { name: "Gemini CLI", dir: ".gemini" },
12
+ ];
13
+
14
+ // Core by name, so a lost manifest or an edited off-list can never remove the workflow.
15
+ const CORE = ["kaizen", "kaizen-help"];
16
+
17
+ function frontMatter(text: string) {
18
+ const fm = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)?.[1] ?? "";
19
+ const d = /^description:[ \t]*(?:[>|][-+]?[ \t]*\r?\n)?([\s\S]*?)(?=\r?\n[A-Za-z_-]+:|(?![\s\S]))/m.exec(fm)?.[1] ?? "";
20
+ const line = d.replace(/\s+/g, " ").replace(/^["']|["']$/g, "").trim();
21
+ const first = /^.*?[.!?](?=\s|$)/.exec(line)?.[0] ?? line;
22
+ return first.length <= 200 ? first : first.slice(0, 200).replace(/\s+\S*$/, "") + "…";
23
+ }
24
+
25
+ export function bundledSkills(repo: string): Skill[] {
26
+ const root = join(repo, "skills");
27
+ const sub = (d: string) => (existsSync(join(root, d)) ? readdirSync(join(root, d)).map((n) => `${d}/${n}`) : []);
28
+ const rels = [...readdirSync(root), ...sub("media"), ...sub("optional")];
29
+ return rels.filter((rel) => existsSync(join(root, rel, "SKILL.md"))).map((rel) => {
30
+ let m: any = {};
31
+ try { m = JSON.parse(readFileSync(join(root, rel, "skill.json"), "utf8")); } catch { /* a folder alone is enough */ }
32
+ const group = CORE.includes(basename(rel)) ? "core" : m.group === "media" || rel.startsWith("media/") ? "media" : "optional";
33
+ return { id: basename(rel), rel, title: String(m.title ?? basename(rel)), description: frontMatter(readFileSync(join(root, rel, "SKILL.md"), "utf8")), group, needs: Array.isArray(m.needs) ? m.needs.map(String) : [], offByDefault: group !== "core" && m.off_by_default === true };
34
+ });
35
+ }
36
+
37
+ const offFile = (home: string) => join(home, ".kaizen", "skills-off.json");
38
+ export function skillsOff(home: string): string[] {
39
+ try { const v = JSON.parse(readFileSync(offFile(home), "utf8")); return Array.isArray(v) ? v.filter((x) => typeof x === "string") : []; } catch { return []; }
40
+ }
41
+
42
+ // A skill with off_by_default stays out until the user turns it on; ~/.kaizen/skills-on.json
43
+ // keeps that choice. `held` is the ones still waiting, whoever installs.
44
+ const onFile = (home: string) => join(home, ".kaizen", "skills-on.json");
45
+ export function skillsOn(home: string): string[] {
46
+ try { const v = JSON.parse(readFileSync(onFile(home), "utf8")); return Array.isArray(v) ? v.filter((x) => typeof x === "string") : []; } catch { return []; }
47
+ }
48
+ export const skillsHeld = (repo: string, home: string) => {
49
+ const on = skillsOn(home);
50
+ return bundledSkills(repo).filter((s) => s.offByDefault && !on.includes(s.id)).map((s) => s.id);
51
+ };
52
+
53
+ // What an install links. The off-list is the user's global choice: a project install is
54
+ // its own decision, and core is never off. `held` binds every install.
55
+ export const skillsToLink = (rels: string[], off: string[], global: boolean, held: string[] = []) =>
56
+ rels.filter((r) => CORE.includes(basename(r)) || (!held.includes(basename(r)) && (!global || !off.includes(basename(r)))));
57
+
58
+ const isLink = (p: string) => { try { return lstatSync(p).isSymbolicLink(); } catch { return false; } };
59
+ // Ours: a link into some kaizen clone's skills/<rel>, this one or the installed one.
60
+ function ours(p: string, rel: string) {
61
+ if (!isLink(p)) return false;
62
+ const raw = readlinkSync(p), target = resolve(isAbsolute(raw) ? raw : join(dirname(p), raw));
63
+ const tail = `${sep}skills${sep}${rel.split("/").join(sep)}`;
64
+ return target.endsWith(tail) && existsSync(join(target.slice(0, -tail.length), "cli", "install.ts"));
65
+ }
66
+
67
+ export function skillStatus(skill: Skill, home: string) {
68
+ return SKILL_HOMES.filter((h) => existsSync(join(home, h.dir))).map((h) => {
69
+ const p = join(home, h.dir, "skills", skill.id);
70
+ const present = existsSync(p) || isLink(p);
71
+ return { agent: h.name, state: !present ? "missing" : ours(p, skill.rel) ? "installed" : "other" };
72
+ });
73
+ }
74
+
75
+ // The clone the core link points at, so a restored link matches its neighbours.
76
+ function installedClone(home: string, repo: string) {
77
+ for (const h of SKILL_HOMES) {
78
+ const p = join(home, h.dir, "skills", "kaizen");
79
+ if (!ours(p, "kaizen")) continue;
80
+ const raw = readlinkSync(p);
81
+ return dirname(dirname(resolve(isAbsolute(raw) ? raw : dirname(p), raw)));
82
+ }
83
+ return repo;
84
+ }
85
+
86
+ // Returns an error, or null. Global links only: a project's own install is left alone.
87
+ // A skill off by default is turned on only with confirm, which the page sends after its warning.
88
+ export function setSkill(repo: string, home: string, id: string, on: boolean, confirm = false): string | null {
89
+ const skill = bundledSkills(repo).find((s) => s.id === id);
90
+ if (!skill) return "unknown skill";
91
+ if (skill.group === "core") return "Core skills can't be turned off";
92
+ if (on && skill.offByDefault && !confirm) return "confirm required";
93
+ const clone = installedClone(home, repo);
94
+ for (const h of SKILL_HOMES) {
95
+ if (!existsSync(join(home, h.dir))) continue;
96
+ const dir = join(home, h.dir, "skills"), p = join(dir, id);
97
+ if (!on) { if (ours(p, skill.rel)) unlinkSync(p); continue; }
98
+ if (existsSync(p) || isLink(p)) continue;
99
+ mkdirSync(dir, { recursive: true });
100
+ symlinkSync(join(clone, "skills", skill.rel), p, process.platform === "win32" ? "junction" : undefined);
101
+ }
102
+ const save = (file: string, list: Set<string>) => {
103
+ mkdirSync(join(home, ".kaizen"), { recursive: true });
104
+ writeFileSync(`${file}.tmp`, JSON.stringify([...list], null, 2));
105
+ renameSync(`${file}.tmp`, file);
106
+ };
107
+ const off = new Set(skillsOff(home));
108
+ on ? off.delete(id) : off.add(id);
109
+ save(offFile(home), off);
110
+ if (skill.offByDefault) { const list = new Set(skillsOn(home)); on ? list.add(id) : list.delete(id); save(onFile(home), list); }
111
+ return null;
112
+ }
package/cli/state.test.ts CHANGED
@@ -10,7 +10,7 @@ import {
10
10
  readRuns, readInbox, writeInbox, replaceIdea, moveIdea, abandonRun, runToIdea, allBacklog, backlog,
11
11
  requestTitle, statusOf, columnOf, parseItem, startedRuns, boardCards, parentOf, addCard, readArchive, setArchived,
12
12
  requestOf, agentFlags, plainModel, readNotes, writeNotes, manualCommand, parseNotes, formatNote, appendNote, saveAttachment,
13
- reviewFindings, pickFindings, fixPrompt, approvalPrompt, sessionLaunch, closeSessions, sweepSessions, readSessions, ownerOf, gitStatus, runGit, cardsGit, commitPush, commitStaged, stageFiles, suggestMessage, readCommit, findTerminal, nativePath, pruneRuns, unrechecked, notice, notifier, notifyArgs, winToastArgs, LOGO, type Card,
13
+ gitStatus, reviewFindings, pickFindings, fixPrompt, approvalPrompt, sessionLaunch, closeSessions, sweepSessions, readSessions, ownerOf, gitStatus, runGit, cardsGit, commitPush, commitStaged, stageFiles, suggestMessage, readCommit, findTerminal, nativePath, pruneRuns, unrechecked, notice, notifier, notifyArgs, winToastArgs, LOGO, type Card,
14
14
  } from "./state.ts";
15
15
 
16
16
  let state: string;
@@ -588,6 +588,29 @@ test("commitPush: commits the run's files only, pushes, and records it; the mess
588
588
  expect(cardsGit(join(root, ".kaizen"), ["r1"])).toEqual({}); // not a repo
589
589
  }, 60_000); // dozens of git calls, ~250ms each on Windows
590
590
 
591
+ test("runGit: a recorded commit rebased away still closes the run", () => {
592
+ const proj = mkdtempSync(join(tmpdir(), "kz-git-")), st = join(proj, ".kaizen"), run = join(st, "runs", "gone");
593
+ const sh = (...a: string[]) => Bun.spawnSync(["git", "-C", proj, ...a], { env: { ...process.env, GIT_COMMITTER_DATE: "2001-01-01T00:00:00Z" } });
594
+ const bare = proj + "-remote.git";
595
+ Bun.spawnSync(["git", "init", "-q", "--bare", bare]);
596
+ sh("init", "-q");
597
+ sh("remote", "add", "origin", bare);
598
+ for (const kv of [["user.name", "t"], ["user.email", "t@t"], ["commit.gpgsign", "false"], ["core.hooksPath", "/dev/null"]]) sh("config", ...kv);
599
+ mkdirSync(run, { recursive: true });
600
+ writeFileSync(join(proj, ".gitignore"), ".kaizen/\n");
601
+ writeFileSync(join(proj, "z.txt"), "1");
602
+ sh("add", "-A");
603
+ sh("commit", "-qm", "chore: z");
604
+ sh("push", "-qu", "origin", "HEAD");
605
+ writeFileSync(join(run, "03-impl.md"), "- `z.txt`: z\n");
606
+ writeFileSync(join(proj, "z.txt"), "2");
607
+ utimesSync(join(run, "03-impl.md"), new Date(Date.now() - 60_000), new Date(Date.now() - 60_000));
608
+ expect(runGit(st, "gone").files).toEqual([" M z.txt"]);
609
+ writeFileSync(join(run, "07-commit.md"), "commit: abc1234\npushed: no\n");
610
+ utimesSync(join(run, "07-commit.md"), new Date(Date.now() - 30_000), new Date(Date.now() - 30_000));
611
+ expect(runGit(st, "gone").files).toEqual([]);
612
+ });
613
+
591
614
  test("runGit, cardsGit: a run committed elsewhere is not offered the edits made since, nor another run's unpushed commit", () => {
592
615
  const root = mkdtempSync(join(tmpdir(), "kz-git-"));
593
616
  const bare = join(root, "remote.git"), proj = join(root, "proj"), st = join(proj, ".kaizen");
@@ -1497,7 +1520,7 @@ test("stageFiles, commitStaged, suggestMessage: only the run's files are staged,
1497
1520
  expect(stageFiles(st, "r1", "discard", ["new.txt"])).toBeNull();
1498
1521
  expect(existsSync(join(proj, "new.txt"))).toBe(false);
1499
1522
  expect(stageFiles(st, "r1", "discard", ["a.txt"])).toBeNull();
1500
- expect(readFileSync(join(proj, "a.txt"), "utf8")).toBe("one\ntwo\n");
1523
+ expect(readFileSync(join(proj, "a.txt"), "utf8").replace(/\r/g, "")).toBe("one\ntwo\n"); // git may check out CRLF on Windows
1501
1524
  expect(readFileSync(join(proj, "other.txt"), "utf8")).toBe("changed\n"); // not the run's, untouched
1502
1525
  writeFileSync(join(proj, "a.txt"), "one\nTWO\nthree\n");
1503
1526
  // Plain Commit: nothing staged, a stale list, another file staged by hand, all refused.
@@ -1510,7 +1533,8 @@ test("stageFiles, commitStaged, suggestMessage: only the run's files are staged,
1510
1533
  expect((commitStaged(st, "r1", "no type", ["a.txt"]) as any).why).toContain("Start the message with a type");
1511
1534
  // The sparkle: with no claude on PATH the message is built from the file names, and it passes the type check.
1512
1535
  const path = process.env.PATH;
1513
- process.env.PATH = "";
1536
+ // On Windows git needs its full PATH, so only folders holding claude go.
1537
+ process.env.PATH = process.platform === "win32" ? path!.split(";").filter((d) => !Bun.which("claude", { PATH: d })).join(";") : "";
1514
1538
  try {
1515
1539
  const m = await suggestMessage(st, "r1");
1516
1540
  expect(m).toEqual({ ok: true, message: "chore: update a.txt", ai: false });
@@ -1525,7 +1549,7 @@ test("stageFiles, commitStaged, suggestMessage: only the run's files are staged,
1525
1549
  expect(stageFiles(st, "r1", "discard", ["a.txt"])).toBe("Not this run's: a.txt");
1526
1550
  expect(readFileSync(join(proj, "a.txt"), "utf8")).toBe("junk\n");
1527
1551
  rmSync(root, { recursive: true, force: true });
1528
- });
1552
+ }, 30_000); // real git, many calls: Windows CI takes 6-8 s, and a timed-out test has its children killed
1529
1553
 
1530
1554
  test("runGit: a run owns the files its report lists as changed, not ones it only mentions", () => {
1531
1555
  const proj = mkdtempSync(join(tmpdir(), "kaizen-own-")), st = join(proj, ".kaizen"), g = (...a: string[]) => Bun.spawnSync(["git", "-C", proj, ...a]);
@@ -1565,3 +1589,21 @@ test("a committed run does not claim a file edited after its commit", () => {
1565
1589
  expect(after.r1).not.toBe("commit");
1566
1590
  rmSync(root, { recursive: true, force: true });
1567
1591
  });
1592
+
1593
+ test("a recheck closes a finding with \"closed\" or \"PASS\", never with FAIL", () => {
1594
+ const st = mkdtempSync(join(tmpdir(), "kz-find-")), d = join(st, "runs", "r");
1595
+ mkdirSync(join(d, "05-iterations"), { recursive: true });
1596
+ writeFileSync(join(d, "04-review.md"), "1. a: low: one\n2. b: low: two\n3. c: low: three\n");
1597
+ writeFileSync(join(d, "05-iterations", "01-recheck.md"), "Finding 1 PASS: ok\nFinding 2 closed\nFinding 3 FAIL: no\n");
1598
+ expect(reviewFindings(st, "r").map((f) => f.done)).toEqual([true, true, false]);
1599
+ });
1600
+
1601
+ test("a git that can't answer is not reported as no repo", () => {
1602
+ const dir = mkdtempSync(join(tmpdir(), "kz-nogit-")), path = process.env.PATH;
1603
+ expect(gitStatus(dir)).toEqual({ repo: false });
1604
+ // A stand-in git that dies with no answer, as a killed one does.
1605
+ writeFileSync(join(dir, "git"), "#!/bin/sh\nexit 137\n", { mode: 0o755 });
1606
+ writeFileSync(join(dir, "git.cmd"), "@exit /b 137\n");
1607
+ process.env.PATH = `${dir}${process.platform === "win32" ? ";" : ":"}${path}`;
1608
+ try { expect(gitStatus(dir)).toEqual({ repo: false, failed: true }); } finally { process.env.PATH = path; }
1609
+ });
package/cli/state.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  // Everything kaizen knows about a project's state, read from and written to the
2
2
  // `.kaizen/` directory. No terminal, no HTTP: the TUI (`dashboard.ts`) and the web
3
3
  // board (`web.ts`) both import this and draw it their own way.
4
+ import { readAccounts, resolveAccount, type Resolved } from "./accounts.ts";
5
+ import { agentEnabled, argsOf, commandOf, prefersBypass, readPrefs, withEnv } from "./agent-prefs.ts";
4
6
  import { existsSync, readFileSync, readdirSync, appendFileSync, writeFileSync, mkdirSync, statSync, realpathSync, rmSync, renameSync, copyFileSync, openSync, readSync, closeSync } from "node:fs";
5
7
  import { Database } from "bun:sqlite";
6
8
  import { join, dirname, sep, win32, posix } from "node:path";
@@ -12,7 +14,7 @@ import { codeDir, projectFromWorktree, wsOf } from "./worktree.ts";
12
14
  // symlink (/home -> var/home) would never compare equal to it.
13
15
  export const home = (() => { try { return realpathSync(homedir()); } catch { return homedir(); } })();
14
16
 
15
- export type Run = { id: string; stage: string; awaiting: string | null; moved: number; runner?: string; agent?: string; branch?: string; worktree?: string; workspace?: string; healed?: boolean };
17
+ export type Run = { id: string; iteration?: number; stage: string; awaiting: string | null; moved: number; runner?: string; agent?: string; branch?: string; worktree?: string; workspace?: string; healed?: boolean };
16
18
 
17
19
  export const KNOWN_AGENTS = [
18
20
  { name: "Claude Code", dir: ".claude", cmd: "claude" },
@@ -23,6 +25,24 @@ export const KNOWN_AGENTS = [
23
25
  { name: "Cursor", dir: ".cursor", cmd: "cursor" },
24
26
  ];
25
27
 
28
+ // Installed under its own or an overridden command, and not turned off in Settings.
29
+ // The account of a run's latest session of this tool, undefined when it has none. A run started
30
+ // on the normal login stays there ("") even after a default is set: its conversation lives there.
31
+ const runAccount = (st: string, run: string, cmd: string) => {
32
+ const idx = runIndex(st), recs = readSessions(st).filter((s) => s.cmd === cmd && ownerOf(st, s, idx) === run);
33
+ return recs.length ? recs[recs.length - 1]!.account ?? "" : undefined;
34
+ };
35
+ export const accountForRun = (projectDir: string, run: string | undefined, cmd: string, picked?: string) =>
36
+ resolveAccount(cmd, picked ?? (run ? runAccount(join(projectDir, ".kaizen"), run, cmd) : undefined));
37
+
38
+ // Only for a tool with accounts, so with none the Run form's data is as it always was.
39
+ const accountChoices = (cmd: string) => {
40
+ const a = readAccounts(), mine = a.accounts.filter((x) => x.tool === cmd);
41
+ return mine.length ? { accounts: mine.map((x) => ({ id: x.id, name: x.name })), defaultAccount: (a.default as Record<string, string>)[cmd] ?? "" } : {};
42
+ };
43
+
44
+ export const agentUsable = (cmd: string) => agentEnabled(cmd) && !!onPath(commandOf(cmd));
45
+
26
46
  export type Agent = { name: string; cmd: string; note?: string };
27
47
 
28
48
  // Each config.yml in the chain, project first: the first one that sets a key decides
@@ -39,18 +59,18 @@ export function detectDefaultAgent(projectDir: string, want?: string): Agent {
39
59
  }
40
60
  if (!want || want === "auto") return autoAgent(projectDir);
41
61
  const found = KNOWN_AGENTS.find((a) => a.cmd === want || a.name.toLowerCase() === want!.toLowerCase());
42
- if (found && onPath(found.cmd)) return found;
62
+ if (found && agentUsable(found.cmd)) return found;
43
63
  const a = autoAgent(projectDir);
44
- return { ...a, note: `${found?.name ?? want} is not installed; opened ${a.name} instead` };
64
+ return { ...a, note: `${found?.name ?? want} is ${found && !agentEnabled(found.cmd) ? "turned off" : "not installed"}; opened ${a.name} instead` };
45
65
  }
46
66
 
47
67
  function autoAgent(projectDir: string): Agent {
48
68
  for (const a of KNOWN_AGENTS) {
49
- if (existsSync(join(projectDir, a.dir)) && onPath(a.cmd)) return a;
69
+ if (existsSync(join(projectDir, a.dir)) && agentUsable(a.cmd)) return a;
50
70
  }
51
- if (onPath("claude")) return { name: "Claude Code", cmd: "claude" };
71
+ if (agentUsable("claude")) return { name: "Claude Code", cmd: "claude" };
52
72
  for (const a of KNOWN_AGENTS) {
53
- if (onPath(a.cmd)) return a;
73
+ if (agentUsable(a.cmd)) return a;
54
74
  }
55
75
  return { name: "Claude Code", cmd: "claude" };
56
76
  }
@@ -59,7 +79,7 @@ function autoAgent(projectDir: string): Agent {
59
79
  // agent:
60
80
  // codex: { model: gpt-5, effort: low }
61
81
  // Each tool spells the flag its own way; a tool not listed here takes none.
62
- const MODEL_FLAGS: Record<string, (m: string) => string[]> = {
82
+ export const MODEL_FLAGS: Record<string, (m: string) => string[]> = {
63
83
  claude: (m) => ["--model", m], agy: (m) => ["--model", m], codex: (m) => ["-m", m],
64
84
  gemini: (m) => ["-m", m], opencode: (m) => ["-m", m],
65
85
  };
@@ -110,12 +130,18 @@ export function agentFlags(projectDir: string, cmd: string, configText?: string,
110
130
  export function agentChoices(projectDir: string) {
111
131
  return {
112
132
  default: detectDefaultAgent(projectDir).cmd,
113
- agents: KNOWN_AGENTS.filter((a) => onPath(a.cmd)).map((a) => ({
114
- name: a.name, cmd: a.cmd, model: agentConfig(projectDir, a.cmd).model ?? "", models: !!MODEL_FLAGS[a.cmd], yolo: !!YOLO_FLAGS[a.cmd],
133
+ agents: KNOWN_AGENTS.filter((a) => agentUsable(a.cmd)).map((a) => ({
134
+ ...accountChoices(a.cmd), name: a.name, cmd: a.cmd, model: agentConfig(projectDir, a.cmd).model ?? "", models: !!MODEL_FLAGS[a.cmd], yolo: !!YOLO_FLAGS[a.cmd],
115
135
  })),
116
136
  };
117
137
  }
118
138
 
139
+ // The start of the line Settings previews: what a launch runs before its session and prompt.
140
+ export function launchPreview(projectDir: string, cmd: string, p = readPrefs()) {
141
+ const env = Object.keys(p.agents[cmd]?.env ?? {}).map((k) => `${k}=•••`);
142
+ return [...env, commandOf(cmd, p), ...agentFlags(projectDir, cmd), ...(prefersBypass(cmd, p) ? YOLO_FLAGS[cmd] ?? [] : []), ...argsOf(cmd, p)].join(" ");
143
+ }
144
+
119
145
  // One argument as a POSIX shell reads it literally: a prompt carries quotes, `$`,
120
146
  // backticks and, with notes, newlines.
121
147
  const shq = (a: string) => `'${a.replace(/'/g, `'\\''`)}'`;
@@ -338,10 +364,10 @@ export function nativePath(p: string) {
338
364
  }
339
365
 
340
366
  // One spelling per folder: no trailing slash, symlinks resolved when the folder exists
341
- // (Windows keeps nativePath's spelling), so a project never lists twice.
367
+ // on every platform, so a project never lists twice.
342
368
  export function canonPath(p: string) {
343
369
  p = nativePath(p);
344
- if (process.platform === "win32") return p;
370
+ if (process.platform === "win32") { try { return nativePath(realpathSync.native(p)); } catch { return p; } }
345
371
  if (p.length > 1) p = p.replace(/\/+$/, "") || "/";
346
372
  try { return realpathSync(p); } catch { return p; }
347
373
  }
@@ -425,7 +451,7 @@ export function readRuns(state: string): Run[] {
425
451
  try { moved = Math.max(moved, statSync(join(dir, id, "progress.md")).mtimeMs); } catch { /* no progress kept */ }
426
452
  // Done without the user's acceptance is not done: every reader sees it waiting on approval.
427
453
  const unapproved = s.stage === "done" && accepted(state, id).accept === "needs";
428
- const run = { id, stage: unapproved ? "review" : s.stage ?? "?", awaiting: unapproved ? "approvals.review" : s.awaiting ?? null, moved, runner: s.runner, agent: s.agent, branch: typeof s.branch === "string" ? s.branch : undefined, worktree: typeof s.worktree === "string" ? s.worktree : undefined, workspace: typeof s.workspace === "string" ? s.workspace : undefined, healed: unapproved || (s.healed === true && s.awaiting === "approvals.review") || undefined };
454
+ const run = { id, iteration: Number(s.iteration) || 0, stage: unapproved ? "review" : s.stage ?? "?", awaiting: unapproved ? "approvals.review" : s.awaiting ?? null, moved, runner: s.runner, agent: s.agent, branch: typeof s.branch === "string" ? s.branch : undefined, worktree: typeof s.worktree === "string" ? s.worktree : undefined, workspace: typeof s.workspace === "string" ? s.workspace : undefined, healed: unapproved || (s.healed === true && s.awaiting === "approvals.review") || undefined };
429
455
  lastRun.set(runDir, run);
430
456
  return [run];
431
457
  } catch { return existsSync(join(runDir, "state.json")) ? [lastRun.get(runDir)].filter((r): r is Run => !!r) : []; }
@@ -523,7 +549,7 @@ export function reviewFindings(state: string, id: string) {
523
549
  const closed = read("06-backlog.md").flatMap((l) => /^-\s*(?:done|rejected):\s*(.*)$/.exec(l)?.[1] ?? []);
524
550
  const iter = join(base, "05-iterations");
525
551
  const rechecked = new Set((existsSync(iter) ? readdirSync(iter) : []).filter((f) => f.endsWith("-recheck.md"))
526
- .flatMap((f) => [...readText(join(iter, f)).matchAll(/finding\s+(\d+)\W{1,8}closed/gi)].map((m) => Number(m[1]))));
552
+ .flatMap((f) => [...readText(join(iter, f)).matchAll(/finding\s+(\d+)\W{1,8}(?:closed|pass)\b/gi)].map((m) => Number(m[1]))));
527
553
  return lines.flatMap((l) => {
528
554
  const m = /^(\d+)\.\s+(.+)$/.exec(l);
529
555
  if (!m) return [];
@@ -749,6 +775,8 @@ export function markBacklogDone(state: string) {
749
775
  export type Card = {
750
776
  kind: "idea" | "run";
751
777
  id?: string; // runs only: the directory name
778
+ stage?: string; // runs only: the stage word
779
+ iteration?: number; // runs only: the fix round
752
780
  status: string; // what the legend calls this card
753
781
  text: string;
754
782
  state: string;
@@ -1251,7 +1279,7 @@ export function boardCards(states: string[], now: number): Card[] {
1251
1279
  const yolos = new Set(yoloRecs.length ? yoloRecs.map((s) => ownerOf(st, s, indexOf(st))) : []);
1252
1280
  for (const r of readRuns(st)) {
1253
1281
  next.push({
1254
- kind: "run", id: r.id, status: statusOf(r, now), text: short(r.id), state: st, where, column: columnOf(r.stage, r.awaiting), moved: r.moved,
1282
+ kind: "run", id: r.id, stage: r.stage, iteration: r.iteration, status: statusOf(r, now), text: short(r.id), state: st, where, column: columnOf(r.stage, r.awaiting), moved: r.moved,
1255
1283
  title: requestTitle(body(st, r.id)),
1256
1284
  awaiting: r.stage === "abandoned" ? null : r.awaiting,
1257
1285
  dim: r.stage === "abandoned",
@@ -1296,8 +1324,8 @@ export function projectOf(from: string) {
1296
1324
  : (from.endsWith(".kaizen") ? dirname(from) : from);
1297
1325
  }
1298
1326
 
1299
- export function manualCommand(projectDir: string, agentCmd: string, prompt: string, flags: string[] = []) {
1300
- const bin = [agentCmd, ...flags, ...(prompt ? PROMPT_FLAGS[agentCmd] ?? [] : [])].join(" ");
1327
+ export function manualCommand(projectDir: string, agentCmd: string, prompt: string, flags: string[] = [], env = "") {
1328
+ const bin = [...(env ? [env] : []), agentCmd, ...flags, ...(prompt ? PROMPT_FLAGS[agentCmd] ?? [] : [])].join(" ");
1301
1329
  // Pasted into whatever shell the user has. fish reads \' and \\ inside single
1302
1330
  // quotes as escapes, so ' and \ each go in double quotes, which sh and fish read alike.
1303
1331
  const q = (a: string) => `'${a.replace(/['\\]/g, (ch) => (ch === "'" ? `'"'"'` : `'"\\\\"'`))}'`;
@@ -1310,7 +1338,7 @@ export function manualCommand(projectDir: string, agentCmd: string, prompt: stri
1310
1338
  // project's state dir ({run, text, cmd, model, sessionId, started}) and `<key>.pid`, which
1311
1339
  // the agent writes itself. Only these are ever closed or resumed: a session the user
1312
1340
  // opened by hand has no record.
1313
- export type Session = { key: string; run: string | null; text: string; cmd: string; model?: string | null; yolo?: boolean; resumed?: boolean; sessionId: string | null; started: number };
1341
+ export type Session = { account?: string; key: string; run: string | null; text: string; cmd: string; model?: string | null; yolo?: boolean; resumed?: boolean; sessionId: string | null; started: number };
1314
1342
 
1315
1343
  // How each tool resumes a conversation by id. `start`: the tool takes an id kaizen
1316
1344
  // picks at launch. Without it the tool picks its own, and `find` reads it from the
@@ -1505,6 +1533,22 @@ export function keepAlive(projectDir: string): "off" | "tmux" {
1505
1533
  return "off";
1506
1534
  }
1507
1535
 
1536
+ export const accountEnv = (r: Resolved) => (r.dir ? [`${r.envVar}=${r.dir}`] : []);
1537
+ const stageEnv = (projectDir: string, run: string) => {
1538
+ try { const s = JSON.parse(readText(join(projectDir, ".kaizen", "runs", run, "state.json"))).stage; return /^\w+$/.test(s) ? [`KAIZEN_STAGE=${s}`] : []; } catch { return []; }
1539
+ };
1540
+
1541
+ // agent.heartbeat_minutes: how long a quiet agent has, in intervals of it, before its card says stale.
1542
+ export function heartbeatMinutes(text = existsSync(join(home, ".kaizen", "config.yml")) ? readText(join(home, ".kaizen", "config.yml")) : "") {
1543
+ const m = /^agent:\n(?:[ \t][^\n]*\n)*?[ \t]+heartbeat_minutes:[ \t]*["']?(\d+)/m.exec(text) || /^agent\.heartbeat_minutes:[ \t]*["']?(\d+)/m.exec(text);
1544
+ return Math.min(Math.max(Number(m?.[1] ?? 5), 1), 60);
1545
+ }
1546
+
1547
+ // agent.keep_awake: machine-wide, so only the global config. Same forms as keepAlive.
1548
+ export function keepAwake(text = existsSync(join(home, ".kaizen", "config.yml")) ? readText(join(home, ".kaizen", "config.yml")) : "") {
1549
+ return (/^agent:\n(?:[ \t][^\n]*\n)*?[ \t]+keep_awake:[ \t]*["']?([^"'\s]+)/m.exec(text) || /^agent\.keep_awake:[ \t]*["']?([^"'\s]+)/m.exec(text))?.[1] ?? "off";
1550
+ }
1551
+
1508
1552
  export function launchMode(projectDir: string): "card" | "terminal" {
1509
1553
  for (const t of configTexts(projectDir)) {
1510
1554
  const m = /^agent:\n(?:[ \t][^\n]*\n)*?[ \t]+launch:[ \t]*["']?([^"'\s]+)/m.exec(t) || /^agent\.launch:[ \t]*["']?([^"'\s]+)/m.exec(t);
@@ -1605,6 +1649,16 @@ export function sweepSessions(st: string) {
1605
1649
  // up here, once, and written back so no later record can claim it. None means a fresh
1606
1650
  // session, never a guess.
1607
1651
  // ponytail: a conversation that begins only after the tool's next launch here is given up (a fresh session), never handed to the wrong run; record a launch marker in the prompt if that bites
1652
+ // Session lookups read the tool's folder from the environment. A record made under an
1653
+ // account is looked up in that account's folder, for every caller.
1654
+ function inAccount<T>(cmd: string, account: string | undefined, fn: () => T): T {
1655
+ const r = account ? resolveAccount(cmd, account) : {};
1656
+ if (!r.envVar) return fn();
1657
+ const prior = process.env[r.envVar];
1658
+ process.env[r.envVar] = r.dir;
1659
+ try { return fn(); } finally { if (prior === undefined) delete process.env[r.envVar!]; else process.env[r.envVar!] = prior; }
1660
+ }
1661
+
1608
1662
  export function firstSession(st: string, id: string, cmd: string, cwd: string): Session | null {
1609
1663
  const f = SESSION_FLAGS[cmd];
1610
1664
  if (!f) return null;
@@ -1618,14 +1672,14 @@ export function firstSession(st: string, id: string, cmd: string, cwd: string):
1618
1672
  if (!s.sessionId && f.find) {
1619
1673
  // Before the tool's next launch here, any run's: from then on a conversation may be that launch's.
1620
1674
  const next = all.find((o) => o.cmd === cmd && o.started > s.started)?.started ?? Infinity;
1621
- const found = f.find(cwd, s.started, Math.min(next, s.started + FIND_WINDOW_MS), taken);
1675
+ const found = inAccount(cmd, s.account, () => f.find!(cwd, s.started, Math.min(next, s.started + FIND_WINDOW_MS), taken));
1622
1676
  if (!found) continue;
1623
1677
  taken.add(found);
1624
1678
  s.sessionId = found;
1625
1679
  const { key, ...rec } = s;
1626
1680
  try { writeFileSync(join(sessionsDir(st), key + ".json"), JSON.stringify(rec) + "\n"); } catch { /* found again next time */ }
1627
1681
  }
1628
- if (s.sessionId && f.has(cwd, s.sessionId)) return s;
1682
+ if (s.sessionId && inAccount(cmd, s.account, () => f.has(cwd, s.sessionId!))) return s;
1629
1683
  }
1630
1684
  return null;
1631
1685
  }
@@ -1645,7 +1699,7 @@ export function runAgent(st: string, id: string): { cmd: string; model: string |
1645
1699
  // The agent's argv for a launch, and its record. With a run, a decision: it resumes
1646
1700
  // the run's conversation when there is one. A project without a state dir gets no
1647
1701
  // record; making one here would shadow the user's.
1648
- export function sessionLaunch(projectDir: string, cmd: string, base: string[], prompt: string, text: string, run?: string, model?: string, yolo?: boolean) {
1702
+ export function sessionLaunch(projectDir: string, cmd: string, base: string[], prompt: string, text: string, run?: string, model?: string, yolo?: boolean, account?: string) {
1649
1703
  const st = join(projectDir, ".kaizen");
1650
1704
  if (!existsSync(st)) return { fullCmd: [...base, ...promptArgs(cmd, prompt)], key: undefined, pidFile: undefined, record: undefined };
1651
1705
  const f = SESSION_FLAGS[cmd];
@@ -1657,7 +1711,7 @@ export function sessionLaunch(projectDir: string, cmd: string, base: string[], p
1657
1711
  const key = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
1658
1712
  mkdirSync(sessionsDir(st), { recursive: true });
1659
1713
  const record = join(sessionsDir(st), key + ".json");
1660
- writeFileSync(record, JSON.stringify({ run: run ?? null, text, cmd, model: model ?? null, ...(yolo ? { yolo: true } : {}), ...(prev ? { resumed: true } : {}), sessionId, started: Date.now() }) + "\n");
1714
+ writeFileSync(record, JSON.stringify({ run: run ?? null, text, cmd, model: model ?? null, ...(yolo ? { yolo: true } : {}), ...(account ? { account } : {}), ...(prev ? { resumed: true } : {}), sessionId, started: Date.now() }) + "\n");
1661
1715
  return { fullCmd, key, pidFile: join(sessionsDir(st), key + ".pid"), record };
1662
1716
  }
1663
1717
 
@@ -1689,18 +1743,24 @@ export const CHILD_ENV = /^(CLAUDECODE|CLAUDE_PID|CLAUDE_CODE_(SESSION_ID|CHILD_
1689
1743
  // skill: start that skill instead of /kaizen (the Video page starts kaizen-video), in cwd:
1690
1744
  // a work folder that may not be a project, so it is not remembered as one. A session record is
1691
1745
  // written only where that folder has a .kaizen (a project place does; the library usually not).
1692
- export function launchRun(it: Item, from: string, run?: string, pick: { agent?: string; model?: string; yolo?: boolean; card?: boolean; onChange?: () => void; skill?: "kaizen-video"; cwd?: string; seed?: string } = {}): Launch {
1746
+ export function launchRun(it: Item, from: string, run?: string, pick: { agent?: string; account?: string; model?: string; yolo?: boolean; card?: boolean; onChange?: () => void; skill?: "kaizen-video"; cwd?: string; seed?: string } = {}): Launch {
1693
1747
  const projectDir = pick.cwd ?? projectOf(from);
1694
1748
  // The run will be born here; the board must know the dir or the idea never retires.
1695
1749
  if (!pick.cwd) remember(projectDir);
1696
1750
  const own = run && !pick.agent ? runAgent(join(projectDir, ".kaizen"), run) : null;
1697
1751
  const agent = detectDefaultAgent(projectDir, pick.agent ?? own?.cmd);
1698
- if (agent.cmd === "claude") trustFolder(projectDir);
1752
+ // Every agent is off, or the last resort is: nothing may start.
1753
+ if (!agentEnabled(agent.cmd)) return { ok: false, agent, prompt: "", projectDir, manual: "", why: `${agent.name} is turned off in Settings → Agents.` };
1754
+ if (pick.agent && agent.cmd !== pick.agent && !agentEnabled(pick.agent)) return { ok: false, agent, prompt: "", projectDir, manual: "", why: "That agent is turned off in Settings → Agents." };
1755
+ const prefs = readPrefs();
1756
+ const acct = accountForRun(projectDir, run, agent.cmd, pick.account);
1757
+ if (acct.error) return { ok: false, agent, prompt: "", projectDir, manual: "", why: acct.error };
1758
+ if (agent.cmd === "claude") trustFolder(projectDir, acct.dir ? join(acct.dir, ".claude.json") : undefined);
1699
1759
  // A board started inside a Claude Code session carries that session's identity. An
1700
1760
  // agent inheriting it runs as its child and keeps no transcript, so nothing to resume.
1701
1761
  for (const k of Object.keys(process.env)) if (CHILD_ENV.test(k)) delete process.env[k];
1702
1762
  // onPath, not Bun.which: the board may have taken a login shell's PATH after it started.
1703
- const agentBin = winShim(onPath(agent.cmd) ?? agent.cmd);
1763
+ const agentBin = winShim(onPath(commandOf(agent.cmd, prefs)) ?? commandOf(agent.cmd, prefs));
1704
1764
  // No text: a run's conversation reopened as it was, with nothing sent to it.
1705
1765
  // A skill other than kaizen: Claude Code takes it as a slash command; other agents are told to use it.
1706
1766
  const lead = !pick.skill ? "/kaizen" : agent.cmd === "claude" ? `/${pick.skill}` : `Use the ${pick.skill} skill.`;
@@ -1713,24 +1773,34 @@ export function launchRun(it: Item, from: string, run?: string, pick: { agent?:
1713
1773
  const yoloRecs = run && !pick.agent ? readSessions(st).filter((s) => s.yolo && s.cmd === agent.cmd) : [];
1714
1774
  const idx = yoloRecs.length ? runIndex(st) : undefined;
1715
1775
  const wasYolo = yoloRecs.some((s) => ownerOf(st, s, idx) === run);
1716
- const yolo = (wasYolo || (!!pick.yolo && agent.cmd === pick.agent)) && !!YOLO_FLAGS[agent.cmd];
1717
- const flags = [...agentFlags(projectDir, agent.cmd, undefined, model), ...(yolo ? YOLO_FLAGS[agent.cmd] : [])];
1776
+ // Settings' bypass takes the same road, so the session record and the card's mark follow.
1777
+ const yolo = (wasYolo || (!!pick.yolo && agent.cmd === pick.agent) || prefersBypass(agent.cmd, prefs)) && !!YOLO_FLAGS[agent.cmd];
1778
+ const flags = [...agentFlags(projectDir, agent.cmd, undefined, model), ...(yolo ? YOLO_FLAGS[agent.cmd] : []), ...argsOf(agent.cmd, prefs)];
1718
1779
  // The idea as its run's request will hold it: without the runner word in front.
1719
- const s = sessionLaunch(projectDir, agent.cmd, [agentBin, ...flags], prompt, it.text.replace(/^(lite|full|auto|plan)\s+/i, ""), run, model, yolo);
1720
- const manual = manualCommand(projectDir, agent.cmd, prompt, flags);
1780
+ // Session lookups read the tool's folder from the environment; for this launch it's the account's.
1781
+ const prior = acct.envVar ? process.env[acct.envVar] : undefined;
1782
+ if (acct.envVar) process.env[acct.envVar] = acct.dir;
1783
+ let s: ReturnType<typeof sessionLaunch>;
1784
+ try { s = sessionLaunch(projectDir, agent.cmd, [agentBin, ...flags], prompt, it.text.replace(/^(lite|full|auto|plan)\s+/i, ""), run, model, yolo, acct.account?.id); }
1785
+ finally { if (acct.envVar) { if (prior === undefined) delete process.env[acct.envVar]; else process.env[acct.envVar] = prior; } }
1786
+ const manual = manualCommand(projectDir, commandOf(agent.cmd, prefs), prompt, flags, acct.dir ? `${acct.envVar}=${shq(acct.dir)}` : "");
1787
+ // Only what is started carries env: the returned `cmd` reaches the page.
1788
+ // A run the board knows hears which one it is; a new run has no id yet and passes --run.
1789
+ const identity = (run || acct.dir) && process.platform !== "win32" ? ["env", ...(run ? [`KAIZEN_RUN_ID=${run}`, ...stageEnv(projectDir, run)] : []), ...accountEnv(acct)] : [];
1790
+ const started = [...identity, ...withEnv(s.fullCmd, agent.cmd, prefs)];
1721
1791
  const drop = () => { if (s.record) rmSync(s.record, { force: true }); };
1722
1792
 
1723
1793
  if (pick.card && ptySupported) {
1724
1794
  const key = s.key ?? `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
1725
1795
  try {
1726
- startPty(key, s.fullCmd, projectDir, s.pidFile, pick.onChange, { seed: pick.seed, tmux: keepAlive(projectDir) === "tmux" ? tmuxName(key) : undefined });
1796
+ startPty(key, started, projectDir, s.pidFile, pick.onChange, { seed: pick.seed, tmux: keepAlive(projectDir) === "tmux" ? tmuxName(key) : undefined });
1727
1797
  return { ok: true, agent, prompt, projectDir, cmd: s.fullCmd, pty: key };
1728
1798
  } catch (err: any) {
1729
1799
  drop();
1730
1800
  return { ok: false, agent, prompt, projectDir, manual, why: err?.message ?? String(err) };
1731
1801
  }
1732
1802
  }
1733
- const term = findTerminal(projectDir, s.fullCmd, s.pidFile);
1803
+ const term = findTerminal(projectDir, started, s.pidFile);
1734
1804
  if (!term) {
1735
1805
  drop();
1736
1806
  return {
@@ -1780,7 +1850,7 @@ export async function pidOnPort(port: number): Promise<number | null> {
1780
1850
  const gitOpts = () => ({ env: { ...process.env, GIT_TERMINAL_PROMPT: "0" }, stdin: "ignore" as const, timeout: 60_000, windowsHide: true });
1781
1851
  const gitDone = (code: number | null, stdout: string, stderr: string) => {
1782
1852
  const out = stdout.trimEnd(), err = stderr.trim();
1783
- return { ok: code === 0, out, why: (err || out).split("\n").pop() || "git did not finish" };
1853
+ return { ok: code === 0, code, out, why: (err || out).split("\n").pop() || "git did not finish" };
1784
1854
  };
1785
1855
  const NO_GIT = { ok: false, out: "", why: "git is not installed" };
1786
1856
  function git(dir: string, ...args: string[]) {
@@ -1798,16 +1868,20 @@ async function gitAsync(dir: string, ...args: string[]) {
1798
1868
  } catch { return NO_GIT; }
1799
1869
  }
1800
1870
 
1801
- export type GitStatus = { repo: false } | { repo: true; branch: string; remote: string; files: string[]; ahead: number; others?: number; shared?: string[]; unpushed?: Unpushed[]; rows?: GitRow[]; staged?: string[]; log?: LogLine[] };
1871
+ export type GitStatus = { repo: false; failed?: boolean } | { repo: true; branch: string; remote: string; files: string[]; ahead: number; others?: number; shared?: string[]; unpushed?: Unpushed[]; rows?: GitRow[]; staged?: string[]; log?: LogLine[] };
1802
1872
  // One of a run's changed files as the Source control tab lists it. A file with changes
1803
1873
  // both staged and not is listed in both groups, as git shows it.
1804
1874
  export type GitRow = { path: string; staged: boolean; code: string; add: number; del: number };
1805
1875
  export type LogLine = { sha: string; subject: string; refs: string; unpushed: boolean };
1806
1876
  type Unpushed = { sha: string; at: number; subject: string; files: string[] };
1807
1877
 
1878
+ const noRemote = (s: { failed?: boolean }) => (s.failed ? "git did not answer. Try again." : "This project has no git remote.");
1879
+
1808
1880
  // A project the board can commit for: a git work tree with somewhere to push.
1809
1881
  export function gitStatus(projectDir: string): GitStatus {
1810
- if (!git(projectDir, "rev-parse", "--is-inside-work-tree").ok) return { repo: false };
1882
+ // Only git's own answer (exit 128) means no repo: a killed or missing git says nothing about the folder.
1883
+ const inside = git(projectDir, "rev-parse", "--is-inside-work-tree");
1884
+ if (!inside.ok) return (inside as { code?: number | null }).code === 128 ? { repo: false } : { repo: false, failed: true };
1811
1885
  const remote = git(projectDir, "remote").out.split("\n")[0] ?? "";
1812
1886
  if (!remote) return { repo: false };
1813
1887
  // Every untracked file on its own line: a new directory is never committed whole.
@@ -1936,7 +2010,14 @@ export function healRuns(state: string): string[] {
1936
2010
  if (!existsSync(dir)) return [];
1937
2011
  return readdirSync(dir).filter((id) => {
1938
2012
  const file = join(dir, id, "state.json");
1939
- try { if (!/"stage":\s*"done"/.test(readText(file))) return false; } catch { return false; } // cheap: skip runs not done
2013
+ let text = "";
2014
+ try { text = readText(file); } catch { return false; }
2015
+ // Accepted after it was healed (the line was written just after `done`): it is done, nothing is waiting.
2016
+ if (/"healed":\s*true/.test(text) && gateOf(state, id) === "user") {
2017
+ setStage(file, (s) => { s.stage = "done"; s.awaiting = null; delete s.healed; return true; });
2018
+ return false;
2019
+ }
2020
+ if (!/"stage":\s*"done"/.test(text)) return false; // cheap: skip runs not done
1940
2021
  return accepted(state, id).accept === "needs" && setStage(file, (s) => {
1941
2022
  if (s.stage !== "done") return false;
1942
2023
  s.stage = "review"; s.awaiting = "approvals.review"; s.healed = true;
@@ -1959,11 +2040,15 @@ export function finishRun(state: string, id: string, userApproved = false): stri
1959
2040
  }
1960
2041
  const names = (report: string, path: string) => report.includes("`" + path + "`") || report.includes("`" + path + ":");
1961
2042
 
1962
- type Report = { id: string; text: string; named: string; at: number; sha?: string };
2043
+ type Report = { id: string; text: string; named: string; at: number; sha?: string; closed?: number };
1963
2044
  function runReports(state: string): Report[] {
1964
2045
  let ids: string[] = [];
1965
2046
  try { ids = readdirSync(join(state, "runs")); } catch {}
1966
- return ids.map((id) => ({ id, ...runReport(state, id), sha: readCommit(state, id)?.sha }));
2047
+ return ids.map((id) => {
2048
+ let closed = 0;
2049
+ try { closed = statSync(join(state, "runs", id, "07-commit.md")).mtimeMs; } catch { /* no record */ }
2050
+ return { id, ...runReport(state, id), sha: readCommit(state, id)?.sha, closed };
2051
+ });
1967
2052
  }
1968
2053
  // A run holds a path at time `t` when its report names it, was written by then, and no
1969
2054
  // other run naming it reported in between.
@@ -1980,7 +2065,8 @@ const editedAfter = (dir: string, p: string, t: number) => {
1980
2065
  try { return statSync(join(dir, p)).mtimeMs >= t + 1000; } catch { return false; }
1981
2066
  };
1982
2067
  const runFiles = (dir: string, changed: string[], mine: Report, rest: Report[]) => {
1983
- const sealed = commitTime(dir, mine.sha);
2068
+ // A rebased or landed commit has a new SHA, so the recorded one is unknown here: the record's own time stands in.
2069
+ const sealed = commitTime(dir, mine.sha) || (mine.sha && mine.closed) || 0;
1984
2070
  return changed.filter((l) => {
1985
2071
  const p = statusPath(l);
1986
2072
  return owns(mine, rest, p, Infinity) && !(lastCommit(dir, p) > mine.at) && !(sealed >= mine.at - 1000 && sealed > 0 && editedAfter(dir, p, sealed));
@@ -2084,7 +2170,7 @@ export function branchLog(dir: string, n: number, ahead = 0): LogLine[] {
2084
2170
  // Discard reverts the work tree side only, as Orca's does; an untracked file is deleted.
2085
2171
  export function stageFiles(state: string, id: string, op: "stage" | "unstage" | "discard", paths: string[]): string | null {
2086
2172
  const s = runGit(state, id);
2087
- if (!s.repo) return "This project has no git remote.";
2173
+ if (!s.repo) return noRemote(s);
2088
2174
  if (!paths.length) return "No files named.";
2089
2175
  const mine = new Map(s.files.map((l) => [statusPath(l), l]));
2090
2176
  const stray = paths.filter((p) => !mine.has(p));
@@ -2114,7 +2200,7 @@ export function stageFiles(state: string, id: string, op: "stage" | "unstage" |
2114
2200
  const HEADLESS_ENV = () => Object.fromEntries(Object.entries(process.env).filter(([k, v]) => v !== undefined && !CHILD_ENV.test(k))) as Record<string, string>;
2115
2201
  export async function suggestMessage(state: string, id: string): Promise<{ ok: true; message: string; ai: boolean } | { ok: false; why: string }> {
2116
2202
  const s = runGit(state, id);
2117
- if (!s.repo) return { ok: false, why: "This project has no git remote." };
2203
+ if (!s.repo) return { ok: false, why: noRemote(s) };
2118
2204
  if (!s.files.length) return { ok: false, why: "No changes to describe." };
2119
2205
  const dir = codeDir(dirname(state), id), rows = s.rows ?? [];
2120
2206
  const use = (s.staged?.length ? s.staged : [...new Set(rows.map((r) => r.path))]);
@@ -2143,7 +2229,7 @@ export async function suggestMessage(state: string, id: string): Promise<{ ok: t
2143
2229
  // for another run) is refused rather than swept into this run's commit.
2144
2230
  export function commitStaged(state: string, id: string, message: string, shown: string[]): { ok: true; sha: string } | { ok: false; why: string } {
2145
2231
  const dir = codeDir(dirname(state), id), s = runGit(state, id);
2146
- if (!s.repo) return { ok: false, why: "This project has no git remote." };
2232
+ if (!s.repo) return { ok: false, why: noRemote(s) };
2147
2233
  if (gateOf(state, id) === "needs") return { ok: false, why: "This run is not approved yet. Approve it first." };
2148
2234
  const staged = s.staged ?? [];
2149
2235
  if (!staged.length) return { ok: false, why: "Nothing is staged." };
@@ -2202,7 +2288,7 @@ const COMMIT_TYPE = new RegExp(`^(${COMMIT_TYPES.join("|")})(\\([^)\\n]+\\))?!?:
2202
2288
  export async function commitPush(state: string, id: string, message: string, shown: string[]): Promise<{ ok: true; sha: string } | { ok: false; why: string }> {
2203
2289
  const dir = codeDir(dirname(state), id);
2204
2290
  const s = runGit(state, id);
2205
- if (!s.repo) return { ok: false, why: "This project has no git remote." };
2291
+ if (!s.repo) return { ok: false, why: noRemote(s) };
2206
2292
  if (gateOf(state, id) === "needs") return { ok: false, why: "This run is not approved yet. Approve it first." };
2207
2293
  if (s.files.join("\n") !== shown.join("\n")) return { ok: false, why: "The changed files are no longer the ones shown. Look at the list again." };
2208
2294
  if (s.files.length) {