kaizen-agent 1.64.3 → 1.66.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 (82) hide show
  1. package/cli/install.ts +13 -2
  2. package/cli/roadmap.ts +74 -0
  3. package/cli/skills.ts +1 -1
  4. package/cli/web.ts +64 -2
  5. package/commands/kaizen-concept.md +6 -0
  6. package/commands/kaizen-roadmap.md +6 -0
  7. package/package.json +4 -2
  8. package/skills/kaizen/SKILL.md +12 -0
  9. package/skills/kaizen/roadmap.md +25 -0
  10. package/skills/kaizen/spec-main.md +27 -0
  11. package/skills/kaizen/spec-plan.md +37 -11
  12. package/skills/kaizen-concept/SKILL.md +416 -0
  13. package/skills/kaizen-concept/skill.json +1 -0
  14. package/skills/kaizen-concept/ux-rules.md +272 -0
  15. package/skills/kaizen-help/SKILL.md +2 -0
  16. package/web/board/chat.ts +4 -3
  17. package/web/board/run-view.ts +18 -3
  18. package/web/board/ws-tabs.ts +9 -0
  19. package/web/board.js +102 -102
  20. package/web/notebook.js +1 -1
  21. package/web/term.js +1 -1
  22. package/web/video.js +1 -1
  23. package/cli/__pycache__/computer-helper.cpython-314.pyc +0 -0
  24. package/cli/accounts.test.ts +0 -126
  25. package/cli/add-project.test.ts +0 -169
  26. package/cli/agent-prefs.test.ts +0 -127
  27. package/cli/automations.test.ts +0 -167
  28. package/cli/backlog.test.ts +0 -133
  29. package/cli/board.test.ts +0 -381
  30. package/cli/browser.test.ts +0 -132
  31. package/cli/chat.test.ts +0 -274
  32. package/cli/chatgpt.test.ts +0 -158
  33. package/cli/computer.test.ts +0 -155
  34. package/cli/docs.test.ts +0 -94
  35. package/cli/handoff.test.ts +0 -133
  36. package/cli/html.test.ts +0 -19
  37. package/cli/install.test.ts +0 -237
  38. package/cli/knowledge.test.ts +0 -179
  39. package/cli/localsend.test.ts +0 -84
  40. package/cli/logo.test.ts +0 -18
  41. package/cli/notes.test.ts +0 -249
  42. package/cli/onboarding.test.ts +0 -70
  43. package/cli/project-tree.test.ts +0 -40
  44. package/cli/pty.test.ts +0 -330
  45. package/cli/release.test.ts +0 -12
  46. package/cli/report.test.ts +0 -59
  47. package/cli/resources.test.ts +0 -50
  48. package/cli/restart.test.ts +0 -222
  49. package/cli/settings.test.ts +0 -168
  50. package/cli/setup.test.ts +0 -78
  51. package/cli/shell-agent.test.ts +0 -23
  52. package/cli/skills.test.ts +0 -95
  53. package/cli/sources.test.ts +0 -851
  54. package/cli/state.test.ts +0 -1639
  55. package/cli/term-image.test.ts +0 -23
  56. package/cli/usage.test.ts +0 -291
  57. package/cli/versions.test.ts +0 -154
  58. package/cli/video.test.ts +0 -545
  59. package/cli/web-accept.test.ts +0 -55
  60. package/cli/web-decide.test.ts +0 -54
  61. package/cli/web-pr.test.ts +0 -52
  62. package/cli/web-skills.test.ts +0 -32
  63. package/cli/web-symlink.test.ts +0 -29
  64. package/cli/workers.test.ts +0 -319
  65. package/cli/worktree.test.ts +0 -452
  66. package/cli/writeback.test.ts +0 -102
  67. package/skills/media/kaizen-video/scripts/__pycache__/intake.cpython-314.pyc +0 -0
  68. package/skills/media/kaizen-video/scripts/__pycache__/make_film.cpython-314.pyc +0 -0
  69. package/skills/media/kaizen-video/scripts/__pycache__/make_tiktok.cpython-314.pyc +0 -0
  70. package/skills/media/kaizen-video/scripts/__pycache__/render_cut.cpython-314.pyc +0 -0
  71. package/skills/media/kaizen-video/scripts/__pycache__/sfx.cpython-314.pyc +0 -0
  72. package/skills/media/kaizen-video/scripts/__pycache__/srt.cpython-314.pyc +0 -0
  73. package/skills/media/kaizen-video/scripts/__pycache__/transcribe.cpython-314.pyc +0 -0
  74. package/skills/media/kaizen-video/scripts/__pycache__/vo.cpython-314.pyc +0 -0
  75. package/web/board/search.test.ts +0 -20
  76. package/web/board/settings-pages.test.ts +0 -28
  77. package/web/board/settings-voice.test.ts +0 -18
  78. package/web/board/toast.test.ts +0 -77
  79. package/web/board/ws-board.test.ts +0 -77
  80. package/web/board/ws-name.test.ts +0 -10
  81. package/web/board/ws-tabs.test.ts +0 -213
  82. package/web/term-font.test.ts +0 -22
package/cli/state.test.ts DELETED
@@ -1,1639 +0,0 @@
1
- // State module against a throwaway .kaizen/. Nothing here spawns a terminal: the
2
- // launch path is covered only up to the command it would run.
3
- import { test, expect, beforeAll, afterAll } from "bun:test";
4
- import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, utimesSync, existsSync, readdirSync, realpathSync, symlinkSync } from "node:fs";
5
- import { join, dirname } from "node:path";
6
- import { tmpdir } from "node:os";
7
- import { issueUrl, systemInfo, scrubHome, REPO_URL, home as realHome, trustFolder } from "./state.ts";
8
- import * as stateModule from "./state.ts";
9
- import {
10
- readRuns, readInbox, writeInbox, replaceTask, moveTask, abandonRun, runToTask, allBacklog, backlog,
11
- requestTitle, statusOf, columnOf, parseItem, startedRuns, boardCards, parentOf, addCard, readArchive, setArchived,
12
- requestOf, agentFlags, plainModel, readNotes, writeNotes, manualCommand, parseNotes, formatNote, appendNote, saveAttachment,
13
- gitStatus, reviewFindings, pickFindings, fixPrompt, approvalPrompt, sessionLaunch, closeSessions, sweepSessions, readSessions, ownerOf, gitStatus, runGit, cardsGit, commitPush, commitStaged, stageFiles, suggestMessage, readCommit, findTerminal, nativePath, pruneRuns, pruneSessions, unrechecked, notice, notifier, notifyArgs, winToastArgs, LOGO, type Card,
14
- } from "./state.ts";
15
-
16
- let state: string;
17
- const run = (id: string, s: object, request = "") => {
18
- const dir = join(state, "runs", id);
19
- mkdirSync(dir, { recursive: true });
20
- writeFileSync(join(dir, "state.json"), JSON.stringify(s));
21
- if (request) writeFileSync(join(dir, "00-request.md"), request);
22
- return dir;
23
- };
24
-
25
- beforeAll(() => {
26
- state = join(mkdtempSync(join(tmpdir(), "kaizen-")), ".kaizen");
27
- mkdirSync(state, { recursive: true });
28
- writeInbox(state, [
29
- { status: "open", text: "add oauth login" },
30
- { status: "open", text: "retry failed webhooks" },
31
- { status: "started", text: "nightly digest" },
32
- { status: "rejected", text: "gantt view | not this product" },
33
- ]);
34
- run("2026-09-01-waiting", { stage: "plan", awaiting: "approvals.plan" }, "# Request\n\nAdd OAuth login\n");
35
- run("2026-09-02-done", { stage: "done", awaiting: null }, "# Request\n\nRename cli flags\n");
36
- const old = run("2026-09-03-stale", { stage: "build", awaiting: null });
37
- const then = new Date(Date.now() - 2 * 3600_000);
38
- utimesSync(join(old, "state.json"), then, then);
39
- writeFileSync(join(state, "runs", "2026-09-02-done", "06-backlog.md"),
40
- "# Backlog\n\n- open: `cli/x.ts:12`: low: first thing. Fix: do it.\n- done: closed one | run y\n- open: plain item\n");
41
- writeFileSync(join(state, "backlog.md"), "- open: orphaned item\n");
42
- });
43
- afterAll(() => rmSync(join(state, ".."), { recursive: true, force: true }));
44
-
45
- test("readRuns: newest first, mtime as moved", () => {
46
- const runs = readRuns(state);
47
- expect(runs.map((r) => r.id)).toEqual(["2026-09-03-stale", "2026-09-02-done", "2026-09-01-waiting"]);
48
- expect(runs[2]!.awaiting).toBe("approvals.plan");
49
- expect(runs[0]!.moved).toBeLessThan(Date.now() - 3600_000);
50
- });
51
-
52
- test("readRuns keeps a run visible during a partial state write", () => {
53
- const file = join(state, "runs", "2026-09-03-stale", "state.json");
54
- const saved = readFileSync(file);
55
- readRuns(state);
56
- try {
57
- writeFileSync(file, '{"stage":');
58
- expect(readRuns(state).some((r) => r.id === "2026-09-03-stale" && r.stage === "build")).toBe(true);
59
- } finally {
60
- writeFileSync(file, saved);
61
- const then = new Date(Date.now() - 2 * 3600_000);
62
- utimesSync(file, then, then);
63
- }
64
- });
65
-
66
- test("statusOf: waiting beats stage, mtime decides running vs stalled", () => {
67
- const now = Date.now();
68
- const [stale, done, waiting] = readRuns(state);
69
- expect(statusOf(waiting!, now)).toBe("waiting");
70
- expect(statusOf(done!, now)).toBe("done");
71
- expect(statusOf(stale!, now)).toBe("stalled");
72
- expect(statusOf({ ...stale!, moved: now }, now)).toBe("running");
73
- expect(statusOf({ ...stale!, stage: "abandoned", awaiting: "x" }, now)).toBe("abandoned");
74
- // A builder ticking progress.md is moving, though state.json is old.
75
- const progress = join(state, "runs", "2026-09-03-stale", "progress.md");
76
- writeFileSync(progress, "- doing: step 2\n");
77
- try { expect(statusOf(readRuns(state)[0]!, now)).toBe("running"); } finally { rmSync(progress); }
78
- expect(statusOf(readRuns(state)[0]!, now)).toBe("stalled");
79
- });
80
-
81
- test("columnOf: every stage word lands somewhere", () => {
82
- expect(["plan", "build", "review", "done", "abandoned", "weird"].map((s) => columnOf(s))).toEqual([1, 2, 3, 4, 4, 1]);
83
- expect(columnOf("implement", "approvals.review")).toBe(3);
84
- expect(columnOf("implement", "findings")).toBe(3);
85
- expect(columnOf("implement", "approvals.each_file")).toBe(2);
86
- expect(columnOf("plan", "approvals.plan")).toBe(1);
87
- });
88
-
89
- test("inbox round-trips and ignores malformed lines", () => {
90
- writeFileSync(join(state, "inbox.md"), readFileSync(join(state, "inbox.md"), "utf8") + "not an item\n");
91
- expect(readInbox(state).map((l) => l.status)).toEqual(["open", "open", "started", "rejected"]);
92
- });
93
-
94
- test("inbox reads a bullet typed by hand as an open task", () => {
95
- const dir = mkdtempSync(join(tmpdir(), "kz-inbox-"));
96
- writeFileSync(join(dir, "inbox.md"), "# Tasks\n- Add dark mode\n* [ ] Faster search\n- done: shipped\n a note\n");
97
- expect(readInbox(dir).map((l) => [l.status, l.text, l.notes])).toEqual([
98
- ["open", "Add dark mode", undefined],
99
- ["open", "Faster search", undefined],
100
- ["done", "shipped", "a note"],
101
- ]);
102
- rmSync(dir, { recursive: true, force: true });
103
- });
104
-
105
- test("boardCards: task retired once a run's request contains it; started task sits in planning", () => {
106
- const cards = boardCards([state], Date.now());
107
- const tasks = cards.filter((k) => k.kind === "idea").map((k) => [k.text, k.column, k.status]);
108
- expect(tasks).toEqual([["retry failed webhooks", 0, "idea"], ["nightly digest", 1, "starting"]]);
109
- const runs = cards.filter((k) => k.kind === "run").map((k) => [k.id, k.column, k.status]);
110
- expect(runs).toEqual([["2026-09-03-stale", 2, "stalled"], ["2026-09-02-done", 4, "done"], ["2026-09-01-waiting", 1, "waiting"]]);
111
- });
112
-
113
- test("boardCards: a started task stays until its run has a state.json", () => {
114
- const dir = join(mkdtempSync(join(tmpdir(), "kaizen-")), ".kaizen");
115
- const r = join(dir, "runs", "2026-01-01-new");
116
- mkdirSync(r, { recursive: true });
117
- writeInbox(dir, [{ status: "started", text: "full release" }]);
118
- writeFileSync(join(r, "00-request.md"), "full release\n");
119
- const cards = () => boardCards([dir], Date.now()).map((k) => k.kind);
120
- expect(cards()).toEqual(["idea"]);
121
- writeFileSync(join(r, "state.json"), JSON.stringify({ id: "2026-01-01-new", stage: "plan", awaiting: null }));
122
- expect(cards()).toEqual(["run"]);
123
- rmSync(join(dir, ".."), { recursive: true, force: true });
124
- });
125
-
126
- test("boardCards: a started task retires into the run its launch's session wrote, however reworded", () => {
127
- const dir = join(mkdtempSync(join(tmpdir(), "kaizen-")), ".kaizen");
128
- const r = join(dir, "runs", "2026-01-01-reworded");
129
- mkdirSync(r, { recursive: true });
130
- mkdirSync(join(dir, "sessions"));
131
- writeInbox(dir, [{ status: "started", text: "revision" }]);
132
- writeFileSync(join(r, "00-request.md"), "- add a form for the icebox\n");
133
- writeFileSync(join(dir, "sessions", "1-a.json"), JSON.stringify({ run: null, text: "revision", cmd: "claude", sessionId: "abc", started: Date.now() }));
134
- const cards = () => boardCards([dir], Date.now()).map((k) => k.kind);
135
- writeFileSync(join(r, "state.json"), JSON.stringify({ id: "2026-01-01-reworded", stage: "build", awaiting: null }));
136
- expect(cards()).toEqual(["idea", "run"]);
137
- writeFileSync(join(r, "state.json"), JSON.stringify({ id: "2026-01-01-reworded", stage: "build", awaiting: null, session: "abc" }));
138
- expect(cards()).toEqual(["run"]);
139
- rmSync(join(dir, ".."), { recursive: true, force: true });
140
- });
141
-
142
- test("boardCards: a run older than the task does not retire it", () => {
143
- const dir = join(mkdtempSync(join(tmpdir(), "kaizen-")), ".kaizen");
144
- const r = join(dir, "runs", "2026-01-01-old");
145
- mkdirSync(r, { recursive: true });
146
- writeFileSync(join(r, "state.json"), JSON.stringify({ id: "2026-01-01-old", stage: "done", awaiting: null }));
147
- writeFileSync(join(r, "00-request.md"), "fix this bugs\n");
148
- const then = new Date(Date.now() - 3600_000);
149
- utimesSync(join(r, "00-request.md"), then, then);
150
- writeInbox(dir, [{ status: "open", text: "fix this bugs" }]);
151
- expect(readFileSync(join(dir, "inbox.md"), "utf8")).toMatch(/- open: fix this bugs <!-- added:\d+ -->/);
152
- expect(readInbox(dir)[0]!.text).toBe("fix this bugs");
153
- const tasks = () => boardCards([dir], Date.now()).filter((k) => k.kind === "idea").map((k) => k.text);
154
- expect(tasks()).toEqual(["fix this bugs"]);
155
- // Rewriting keeps the stamp, so an edit to notes does not make it vanish.
156
- writeInbox(dir, readInbox(dir).map((l) => ({ status: l.status, text: l.text, notes: "n" })));
157
- expect(tasks()).toEqual(["fix this bugs"]);
158
- // A run started after it retires it as before.
159
- utimesSync(join(r, "00-request.md"), new Date(), new Date(Date.now() + 5000));
160
- expect(tasks()).toEqual([]);
161
- // Re-adding the same words while an old line holds them is a new task with its
162
- // own stamp, not the old line's (or no) stamp.
163
- writeFileSync(join(dir, "inbox.md"), "- done: fix this bugs\n");
164
- writeInbox(dir, [...readInbox(dir), { status: "open", text: "fix this bugs" }]);
165
- utimesSync(join(r, "00-request.md"), then, then);
166
- expect(tasks()).toEqual(["fix this bugs"]);
167
-
168
- rmSync(join(dir, ".."), { recursive: true, force: true });
169
- });
170
-
171
- test("replaceTask edits, rejects, deletes by text", () => {
172
- replaceTask(state, "retry failed webhooks", { status: "open", text: "retry failed webhooks twice" });
173
- expect(readInbox(state).some((l) => l.text === "retry failed webhooks twice")).toBe(true);
174
- replaceTask(state, "retry failed webhooks twice", { status: "rejected", text: "retry failed webhooks twice | no" });
175
- replaceTask(state, "nightly digest", null);
176
- expect(readInbox(state).map((l) => l.status)).toEqual(["open", "rejected", "rejected"]);
177
- });
178
-
179
- test("abandonRun: flips stage, clears awaiting, records the reason, refuses twice", () => {
180
- expect(abandonRun(state, "2026-09-01-waiting", "changed my mind")).toBeNull();
181
- const s = JSON.parse(readFileSync(join(state, "runs", "2026-09-01-waiting", "state.json"), "utf8"));
182
- expect([s.stage, s.awaiting]).toEqual(["abandoned", null]);
183
- expect(readFileSync(join(state, "runs", "2026-09-01-waiting", "02-approval.md"), "utf8")).toContain("changed my mind");
184
- expect(abandonRun(state, "2026-09-01-waiting", "again")).toMatch(/already/);
185
- });
186
-
187
- test("backlog: open items only, orphanage last, count matches", () => {
188
- const groups = allBacklog(state);
189
- expect(groups.map((g) => g.run)).toEqual(["2026-09-02-done", "Orphaned"]);
190
- expect(groups[0]!.items.length).toBe(2);
191
- expect(backlog(state)).toBe(3);
192
- });
193
-
194
- test("backlog: an abandoned run's items are neither listed nor counted", () => {
195
- const dir = join(state, "runs", "2026-09-03-dropped");
196
- mkdirSync(dir, { recursive: true });
197
- writeFileSync(join(dir, "state.json"), JSON.stringify({ id: "2026-09-03-dropped", stage: "abandoned" }));
198
- writeFileSync(join(dir, "06-backlog.md"), "- open: never happening\n");
199
- expect(allBacklog(state).some((g) => g.run === "2026-09-03-dropped")).toBe(false);
200
- expect(backlog(state)).toBe(3);
201
- rmSync(dir, { recursive: true });
202
- });
203
-
204
- test("runToTask: a planning run goes back to its task, newer than the run", () => {
205
- const id = "2026-09-04-planning", dir = join(state, "runs", id);
206
- mkdirSync(dir, { recursive: true });
207
- writeFileSync(join(dir, "state.json"), JSON.stringify({ id, stage: "plan", awaiting: "approvals.plan" }));
208
- writeFileSync(join(dir, "00-request.md"), "/kaizen lite export invoices as csv\n");
209
- const then = new Date(Date.now() - 30_000);
210
- utimesSync(join(dir, "00-request.md"), then, then);
211
- writeInbox(state, [...readInbox(state), { status: "started", text: "export invoices", added: Date.now() - 60_000 }, { status: "started", text: "export invoices as csv", notes: "see #12", added: Date.now() - 60_000 }]);
212
- expect(runToTask(state, id)).toBeNull();
213
- expect(JSON.parse(readFileSync(join(dir, "state.json"), "utf8")).stage).toBe("abandoned");
214
- const cards = boardCards([state], Date.now());
215
- expect(cards.find((c) => c.kind === "idea" && c.text === "export invoices as csv")).toMatchObject({ status: "idea", notes: "see #12" });
216
- expect(cards.find((c) => c.kind === "run" && c.id === id)?.archived).toBe(true);
217
- expect(readInbox(state).filter((l) => l.text === "export invoices as csv").length).toBe(1);
218
- expect(readInbox(state).find((l) => l.text === "export invoices")?.status).toBe("started");
219
- expect(runToTask(state, id)).toMatch(/planning/);
220
- writeFileSync(join(dir, "state.json"), JSON.stringify({ id, stage: "plan" }));
221
- rmSync(join(dir, "00-request.md"));
222
- expect(runToTask(state, id)).toMatch(/no request/);
223
- replaceTask(state, "export invoices", null);
224
- setArchived(state, id, false);
225
- rmSync(dir, { recursive: true });
226
- });
227
-
228
- test("abandonRun refuses a done run", () => {
229
- expect(abandonRun(state, "2026-09-02-done", "late")).toMatch(/already done/);
230
- });
231
-
232
- test("parseItem: finding line splits into where, severity, text", () => {
233
- const it = parseItem("`cli/x.ts:12`: low: first thing. Fix: do it.");
234
- expect([it.where, it.severity, it.text]).toEqual(["x.ts:12", "low", "first thing."]);
235
- expect(parseItem("plain item").severity).toBeNull();
236
- });
237
-
238
- test("parseItem: severity written as a range, a tag in brackets, or a numbered line", () => {
239
- const sev = (s: string) => parseItem(s).severity;
240
- expect(parseItem("cli/a.ts:4-9, cli/b.ts:2: high: crashes. Fix: catch.")).toMatchObject({ severity: "high", where: "b.ts:2", text: "crashes." });
241
- expect(sev("bot/x.ts `ctxNow` - low - no test")).toBe("low");
242
- expect(parseItem("1. low — defaults are Bahasa")).toMatchObject({ severity: "low", where: null });
243
- expect(sev("Finding 1 (medium) — proxy checks host only")).toBe("medium");
244
- expect(sev("Tech Lead turn per item; watch cost. (review finding 3, low)")).toBe("low");
245
- expect(sev("[low] Test for ptyOf")).toBe("low");
246
- expect(sev("Crane top may touch low (2.2 m) storeys")).toBeNull();
247
- expect(sev("add dark mode (low priority)")).toBeNull();
248
- expect(sev("the price is too low")).toBeNull();
249
- });
250
-
251
- test("reviewFindings: numbered lines under Findings, closed by the backlog; the prompt names only what was picked", () => {
252
- const dir = join(state, "runs", "2026-09-02-done");
253
- writeFileSync(join(dir, "04-review.md"),
254
- "# Review\n\n1. not a finding, above the heading\n\n## Findings\n\n1. a.ts:1: high: one. Fix: x.\n2. b.ts:2: low: two.\n3. c.ts:3: low: three.\n\n## Notes\n\n4. not a finding either\n");
255
- const before = readFileSync(join(dir, "06-backlog.md"), "utf8");
256
- writeFileSync(join(dir, "06-backlog.md"), before + "- done: 1. a.ts:1: high: one, reworded | fixed in iteration 1\n- rejected: c.ts:3: low: three. | not worth it\n- open: 2. b.ts:2: low: two.\n");
257
- expect(reviewFindings(state, "2026-09-02-done").map((f) => [f.n, f.done])).toEqual([[1, true], [2, false], [3, true]]);
258
- expect(reviewFindings(state, "2026-09-02-done")[1]!.text).toBe("b.ts:2: low: two.");
259
- expect(reviewFindings(state, "2026-09-03-stale")).toEqual([]);
260
- expect(pickFindings(state, "2026-09-02-done", [2])).toEqual([2]);
261
- for (const bad of [[2, 99], [1], ["2"], [], "2", undefined]) expect(pickFindings(state, "2026-09-02-done", bad)).toBeNull();
262
- // Sub-headings stay inside the section; a recheck closes a finding before the backlog does.
263
- writeFileSync(join(dir, "06-backlog.md"), before);
264
- writeFileSync(join(dir, "04-review.md"), "## Findings\n\n### High\n\n1. a.ts:1: high: one.\n\n### Low\n\n2. b.ts:2: low: two.\n\n## Gate\n\n3. no\n");
265
- mkdirSync(join(dir, "05-iterations"), { recursive: true });
266
- writeFileSync(join(dir, "05-iterations", "01-recheck.md"), "**Finding 1 — closed.** Proven.\n\n**Finding 2 — still open**, by choice.\n");
267
- expect(reviewFindings(state, "2026-09-02-done").map((f) => [f.n, f.done])).toEqual([[1, true], [2, false]]);
268
- rmSync(join(dir, "05-iterations"), { recursive: true });
269
- expect(fixPrompt("2026-09-02-done", [2])).toStartWith("run 2026-09-02-done: fix finding 2 from");
270
- expect(fixPrompt("x", [2, 5])).toContain("fix findings 2, 5 from");
271
- });
272
-
273
- test("approvalPrompt: approve or revise, the comment kept on one line", () => {
274
- expect(approvalPrompt("r", "approvals.plan")).toBe("run r: the plan is approved from the board. Record it in 02-approval.md and build it, first asking any of its open questions still unanswered.");
275
- expect(approvalPrompt("r", "approvals.review", " ")).toContain("approved from the board at the final approval");
276
- const p = approvalPrompt("r", "approvals.plan", " drop step 3,\n\tkeep \"the rest\" ");
277
- expect(p).toContain('to revise: "drop step 3, keep "the rest"".');
278
- expect(p).toContain("revise 01-plan.md");
279
- expect(p).not.toContain("\n");
280
- expect(approvalPrompt("r", "approvals.review")).toContain("commit and push this run's changed files only");
281
- expect(approvalPrompt("r", "findings")).toContain("commit and push");
282
- expect(approvalPrompt("r", "approvals.review")).toContain("kaizen worktree land");
283
- expect(approvalPrompt("r", "approvals.review", "rename it")).not.toContain("push");
284
- expect(approvalPrompt("r", "approvals.plan")).not.toContain("push");
285
- expect(approvalPrompt("r", "approvals.review", "rename it")).toContain('final approval: "rename it". Record it in 02-approval.md, change the work');
286
- });
287
-
288
- test("final approval can explicitly accept a run still awaiting findings", () => {
289
- expect(stateModule.canApproveAwaiting("approvals.plan")).toBe(true);
290
- expect(stateModule.canApproveAwaiting("approvals.review")).toBe(true);
291
- expect(stateModule.canApproveAwaiting("findings")).toBe(true);
292
- expect(stateModule.canApproveAwaiting("building")).toBe(false);
293
- expect(approvalPrompt("r", "findings")).toContain("run as-is at the findings gate");
294
- expect(approvalPrompt("r", "findings")).toContain("leave every remaining finding open");
295
- });
296
-
297
- test("approvalPrompt: a plan's answers numbered on one line", () => {
298
- const p = approvalPrompt("r", "approvals.plan", undefined, ["Where? — Footer", "Chip?\n — No; keep it\tsmall"]);
299
- expect(p).toBe("run r: the plan is approved from the board, with answers to its open questions: 1) Where? — Footer; 2) Chip? — No; keep it small. Record them in 02-approval.md and build the plan with them.");
300
- expect(approvalPrompt("r", "approvals.plan", "redo it", ["x"])).toContain("to revise");
301
- });
302
-
303
- test("startedRuns: normalised request bodies", () => {
304
- expect(startedRuns(state).sort()).toEqual(["# request add oauth login", "# request rename cli flags"]);
305
- });
306
-
307
- test("archive: a run is listed, hidden by flag, never moved", () => {
308
- setArchived(state, "2026-09-02-done", true);
309
- expect([...readArchive(state)]).toEqual(["2026-09-02-done"]);
310
- const card = boardCards([state], Date.now()).find((k) => k.id === "2026-09-02-done")!;
311
- expect([card.archived, card.column]).toEqual([true, 4]);
312
- setArchived(state, "2026-09-02-done", false);
313
- expect(readArchive(state).size).toBe(0);
314
- expect(boardCards([state], Date.now()).find((k) => k.id === "2026-09-02-done")!.archived).toBe(false);
315
- });
316
-
317
- test("archive: a task keeps its line with status archived", () => {
318
- writeInbox(state, [{ status: "open", text: "park this", notes: "kept" }, { status: "archived", text: "parked zq7" }]);
319
- const tasks = boardCards([state], Date.now()).filter((k) => k.kind === "idea");
320
- expect(tasks.map((k) => [k.text, k.archived])).toEqual([["park this", false], ["parked zq7", true]]);
321
- });
322
-
323
- test("notes: indented lines under a bullet round-trip; a legacy file is untouched", () => {
324
- const legacy = "# Inbox\n\nIdeas with no run yet. One line each, same format as a run's backlog.\n\n- open: a\n- rejected: b | why\n";
325
- writeFileSync(join(state, "inbox.md"), legacy);
326
- writeInbox(state, readInbox(state));
327
- expect(readFileSync(join(state, "inbox.md"), "utf8")).toBe(legacy);
328
- writeInbox(state, [{ status: "open", text: "with notes", notes: "see https://x.y/z\ncli/state.ts:12 | not a reason" }, { status: "open", text: "plain zq8" }]);
329
- const [a, b] = readInbox(state);
330
- expect(a).toMatchObject({ status: "open", text: "with notes", notes: "see https://x.y/z\ncli/state.ts:12 | not a reason" });
331
- expect(b).toMatchObject({ status: "open", text: "plain zq8" });
332
- });
333
-
334
- test("notes: survive reject and started; edit can replace or clear them", () => {
335
- replaceTask(state, "with notes", { status: "started", text: "with notes" });
336
- expect(readInbox(state)[0]!.notes).toContain("https://x.y/z");
337
- replaceTask(state, "with notes", { status: "rejected", text: "with notes | no" });
338
- expect(readInbox(state)[0]!.notes).toContain("https://x.y/z");
339
- replaceTask(state, "plain zq8", { status: "open", text: "plain zq8", notes: "" });
340
- expect(readInbox(state)[1]!.notes).toBeUndefined();
341
- expect(boardCards([state], Date.now()).find((k) => k.text === "plain zq8")!.notes).toBeUndefined();
342
- });
343
-
344
- test("notes: the prompt is text, blank line, notes; still one quoted argument", () => {
345
- expect(requestOf("/kaizen do x")).toBe("/kaizen do x");
346
- expect(requestOf("/kaizen do x", "l1\nl2\n")).toBe("/kaizen do x\n\nl1\nl2");
347
- const cmd = manualCommand("/p", "claude", requestOf("/kaizen do x", "l1"));
348
- if (process.platform !== "win32") {
349
- expect(cmd).toBe("cd '/p' && claude '/kaizen do x\n\nl1'");
350
- // Pasted into a shell, outside text must stay text.
351
- // ' and \ sit in double quotes: fish reads \' inside single quotes as an escape.
352
- const hostile = "a $(x) `y` 'z' a\\' $(touch canary) \\'b \\";
353
- const pasted = manualCommand("/p", "printf %s", hostile);
354
- expect(pasted).toBe(`cd '/p' && printf %s 'a $(x) \`y\` '"'"'z'"'"' a'"\\\\"''"'"' $(touch canary) '"\\\\"''"'"'b '"\\\\"''`);
355
- expect(pasted.replace(/'[^'\\]*'|"['\\]+"/g, "")).toBe("cd && printf %s "); // only '…' without \ or ', and "'" or "\\"
356
- for (const sh of ["/bin/sh", "bash", "zsh"].filter((s) => Bun.which(s))) {
357
- expect(Bun.spawnSync([sh, "-c", pasted.replace("cd '/p'", "cd /")]).stdout.toString()).toBe(hostile);
358
- }
359
- }
360
- });
361
-
362
- test("notes: a run's notes.md is read beside it, written only for a real run", () => {
363
- expect(writeNotes(state, "2026-09-09-nope", "x")).toBe("no such run");
364
- expect(writeNotes(state, "2026-09-01-waiting", " ref: docs/a.md ")).toBeNull();
365
- expect(readNotes(state, "2026-09-01-waiting")).toBe("ref: docs/a.md\n");
366
- expect(boardCards([state], Date.now()).find((k) => k.id === "2026-09-01-waiting")!.notes).toBe("ref: docs/a.md\n");
367
- writeNotes(state, "2026-09-01-waiting", "");
368
- expect(readNotes(state, "2026-09-01-waiting")).toBe("");
369
- });
370
-
371
- test("notes log: stamped entries, continuation lines, unstamped preamble", () => {
372
- const src = "hand written\n[2026-09-14 10:00] first\n more\n[2026-09-14 10:05] ![shot](attachments/a.png)\n";
373
- expect(parseNotes(src)).toEqual([
374
- { at: "", text: "hand written" },
375
- { at: "2026-09-14 10:00", text: "first\nmore" },
376
- { at: "2026-09-14 10:05", text: "![shot](attachments/a.png)" },
377
- ]);
378
- expect(formatNote("a\nb", "2026-09-14 10:00")).toBe("[2026-09-14 10:00] a\n b");
379
- });
380
-
381
- test("notes log: append to a run and to a task; attachments saved and made absolute in the prompt", () => {
382
- expect(appendNote(state, { id: "2026-09-01-waiting" }, "run note")).toBeNull();
383
- expect(parseNotes(readNotes(state, "2026-09-01-waiting")).map((n) => n.text)).toEqual(["run note"]);
384
- writeInbox(state, [{ status: "open", text: "chatty zq6" }]);
385
- expect(appendNote(state, { text: "chatty zq6" }, "one")).toBeNull();
386
- expect(appendNote(state, { text: "chatty zq6" }, "two\nlines")).toBeNull();
387
- expect(appendNote(state, { text: "nope zq6" }, "x")).toBe("no such task");
388
- expect(parseNotes(readInbox(state)[0]!.notes!).map((n) => n.text)).toEqual(["one", "two\nlines"]);
389
- const rel = saveAttachment(state, null, "../evil name.png", new Uint8Array([1]));
390
- expect(rel).toMatch(/^attachments\/\w+-_evil_name\.png$/);
391
- expect(requestOf("x", `![s](${rel})`, state)).toBe(`x\n\n![s](${join(state, rel)})`);
392
- // The New task form's path: task first, then its files as a note; a plain file reaches the run by absolute path.
393
- const doc = saveAttachment(state, null, "spec.pdf", new Uint8Array([3]));
394
- expect(appendNote(state, { text: "chatty zq6" }, `[spec.pdf](${doc})`)).toBeNull();
395
- expect(requestOf("/kaizen chatty zq6", readInbox(state)[0]!.notes, state)).toContain(`[spec.pdf](${join(state, doc)})`);
396
- expect(saveAttachment(state, "2026-09-01-waiting", "b.txt", new Uint8Array([2]))).toMatch(/^runs\/2026-09-01-waiting\/attachments\//);
397
- });
398
-
399
- test("agentFlags reads a long, commented agent block with no entry for the tool in milliseconds", () => {
400
- // The block-skipping pattern once backtracked for seconds per call here, and a board that listed its
401
- // agents on every page load stopped answering.
402
- const cfg = "agent:\n default: claude\n" + " # a long comment about what this setting does and when\n".repeat(150) + " close: on\n";
403
- const t = performance.now();
404
- for (const cmd of ["claude", "codex", "agy", "gemini", "opencode"]) expect(agentFlags("/p", cmd, cfg)).toEqual([]);
405
- expect(performance.now() - t).toBeLessThan(500);
406
- });
407
-
408
- test("agentFlags: per-tool model and effort from the agent block, inline or nested", () => {
409
- const cfg = `agent:\n default: auto\n codex: { model: gpt-5, effort: low }\n claude:\n model: sonnet\n effort: low\n gemini:\n model: "gemini-2.5-pro"\n`;
410
- expect(agentFlags("/p", "codex", cfg)).toEqual(["-m", "gpt-5", "-c", "model_reasoning_effort=low"]);
411
- expect(agentFlags("/p", "claude", cfg)).toEqual(["--model", "sonnet", "--effort", "low"]);
412
- expect(agentFlags("/p", "gemini", cfg)).toEqual(["-m", "gemini-2.5-pro"]);
413
- expect(agentFlags("/p", "agy", cfg)).toEqual([]);
414
- expect(agentFlags("/p", "codex", "agent:\n default: codex\n")).toEqual([]);
415
- });
416
-
417
- test("plainModel: a typed model reaches launch lines only as a plain name", () => {
418
- for (const m of ["opus", "gpt-5.1", "gemini-2.5-pro", "anthropic/claude-sonnet-4", "o3:high", "x@y"]) expect(plainModel(m)).toBe(true);
419
- for (const m of ["", "x; rm -rf ~", "$(id)", "`id`", "a b", "'q'", "\"q\"", "opus[1m]", "-rf", "x".repeat(81)]) expect(plainModel(m)).toBe(false);
420
- });
421
-
422
- test("each tool gets the opening prompt the way it takes one: agy -i, opencode --prompt, the rest bare", () => {
423
- const p = mkdtempSync(join(tmpdir(), "kz-")); // no .kaizen: no session record
424
- const argv = (cmd: string) => sessionLaunch(p, cmd, [cmd], "/kaizen x", "x").fullCmd;
425
- expect(argv("agy")).toEqual(["agy", "-i", "/kaizen x"]);
426
- expect(argv("opencode")).toEqual(["opencode", "--prompt", "/kaizen x"]);
427
- expect(argv("codex")).toEqual(["codex", "/kaizen x"]);
428
- expect(argv("gemini")).toEqual(["gemini", "/kaizen x"]);
429
- if (process.platform !== "win32") expect(manualCommand("/p", "agy", "/kaizen x", ["--model", "m"])).toBe("cd '/p' && agy --model m -i '/kaizen x'");
430
- });
431
-
432
- test.skipIf(process.platform === "win32")("agent choice: project then global config, a note for a missing tool, a pick, and a run keeps its own", () => {
433
- // The global config sits at the home bound at import, so this runs in a child with a scratch HOME.
434
- const home = mkdtempSync(join(tmpdir(), "kz-home-")), bin = mkdtempSync(join(tmpdir(), "kz-bin-"));
435
- for (const t of ["claude", "codex"]) writeFileSync(join(bin, t), "#!/bin/sh\nexit 0\n", { mode: 0o755 });
436
- const script = `const S = await import(${JSON.stringify(join(dirname(import.meta.path), "state.ts"))});
437
- const fs = require("node:fs"), { join } = require("node:path");
438
- const P = join(process.env.HOME, "proj"), st = join(P, ".kaizen"), G = join(process.env.HOME, ".kaizen");
439
- fs.mkdirSync(join(st, "runs", "r1"), { recursive: true }); fs.mkdirSync(G, { recursive: true });
440
- fs.writeFileSync(join(G, "config.yml"), "agent:\\n default: codex\\n codex: { model: gpt-5, effort: low }\\n");
441
- fs.writeFileSync(join(st, "config.yml"), "mode: approve\\n");
442
- const out = { chain: [S.detectDefaultAgent(P).cmd, S.agentFlags(P, "codex")] };
443
- fs.writeFileSync(join(st, "config.yml"), "agent:\\n default: claude\\n codex:\\n model: o3\\n");
444
- out.project = [S.detectDefaultAgent(P).cmd, S.agentFlags(P, "codex")];
445
- out.missing = S.detectDefaultAgent(P, "gemini");
446
- out.pick = [S.detectDefaultAgent(P, "codex").cmd, S.agentFlags(P, "codex", undefined, "gpt-5.1")];
447
- out.choices = S.agentChoices(P);
448
- // No terminal on PATH or display in env: the launch fails and hands back its manual line.
449
- const task = { severity: null, where: null, text: "x", raw: "x" };
450
- // macOS always drives Terminal.app, which would open a real window: Linux only.
451
- if (process.platform === "linux") out.yolo = [S.launchRun(task, P, undefined, { agent: "codex", yolo: true }), S.launchRun(task, P, undefined, { agent: "codex" }), S.launchRun(task, P, undefined, { agent: "gemini", yolo: true })].map((r) => [r.ok, r.agent.cmd, /--dangerously-bypass|--dangerously-skip|--yolo/.test(r.manual)]);
452
- fs.writeFileSync(join(st, "runs", "r1", "state.json"), JSON.stringify({ agent: "codex" }));
453
- out.fromState = S.runAgent(st, "r1");
454
- S.sessionLaunch(P, "codex", ["codex"], "/kaizen x", "x", "r1", "gpt-5.1");
455
- out.fromRecord = S.runAgent(st, "r1");
456
- out.tags = [S.boardCards([st], Date.now()).find((c) => c.id === "r1")?.tags];
457
- S.sessionLaunch(P, "codex", ["codex"], "/kaizen x", "x", "r1", undefined, true);
458
- out.tags.push(S.boardCards([st], Date.now()).find((c) => c.id === "r1")?.tags);
459
- console.log(JSON.stringify(out));`;
460
- try {
461
- const p = Bun.spawnSync(["bun", "-e", script], { cwd: home, env: { ...process.env, HOME: home, PATH: bin + ":" + dirname(process.execPath), DISPLAY: "", WAYLAND_DISPLAY: "", TERMINAL: "", TMUX: "", HERDR_ENV: "" } });
462
- if (p.exitCode !== 0) throw new Error(p.stderr.toString());
463
- expect(JSON.parse(p.stdout.toString())).toEqual({
464
- // A project config.yml with no agent block leaves the global one in force.
465
- chain: ["codex", ["-m", "gpt-5", "-c", "model_reasoning_effort=low"]],
466
- project: ["claude", ["-m", "o3"]],
467
- missing: { name: "Claude Code", cmd: "claude", note: "Gemini CLI is not installed; opened Claude Code instead" },
468
- pick: ["codex", ["-m", "gpt-5.1"]],
469
- choices: { default: "claude", agents: [
470
- { name: "Claude Code", cmd: "claude", model: "", models: true, yolo: true },
471
- { name: "Codex", cmd: "codex", model: "o3", models: true, yolo: true },
472
- ] },
473
- // Yolo adds the tool's bypass flag only when asked for, and not to a fallback tool.
474
- ...(process.platform === "linux" ? { yolo: [[false, "codex", true], [false, "codex", false], [false, "claude", false]] } : {}),
475
- tags: [["codex"], ["codex", "yolo"]],
476
- fromState: { cmd: "codex", model: null },
477
- fromRecord: { cmd: "codex", model: "gpt-5.1" },
478
- });
479
- } finally { rmSync(home, { recursive: true, force: true }); rmSync(bin, { recursive: true, force: true }); }
480
- });
481
-
482
- test("boardCards: a short task is not retired by a request that merely contains the word", () => {
483
- const dir = join(mkdtempSync(join(tmpdir(), "kz-")), ".kaizen");
484
- mkdirSync(join(dir, "runs", "2026-09-01-a"), { recursive: true });
485
- writeFileSync(join(dir, "runs", "2026-09-01-a", "state.json"), JSON.stringify({ id: "2026-09-01-a", stage: "plan", awaiting: null }));
486
- writeFileSync(join(dir, "runs", "2026-09-01-a", "00-request.md"), "# Request\n\n> /kaizen lite add retry\n\nDone means the tests pass.\n");
487
- writeInbox(dir, [{ status: "open", text: "test" }, { status: "open", text: "add retry" }]);
488
- expect(boardCards([dir], Date.now()).filter((k) => k.kind === "idea").map((k) => k.text)).toEqual(["test"]);
489
- });
490
-
491
- test("boardCards: the done column is newest-moved first, the rest keep their place", () => {
492
- const dir = join(mkdtempSync(join(tmpdir(), "kz-")), ".kaizen");
493
- const at = (id: string, stage: string, hoursAgo: number) => {
494
- mkdirSync(join(dir, "runs", id), { recursive: true });
495
- writeFileSync(join(dir, "runs", id, "state.json"), JSON.stringify({ stage, awaiting: null }));
496
- const t = new Date(Date.now() - hoursAgo * 3600_000);
497
- utimesSync(join(dir, "runs", id, "state.json"), t, t);
498
- };
499
- at("2026-09-01-a", "done", 1); at("2026-09-02-b", "done", 3); at("2026-09-03-c", "abandoned", 2);
500
- at("2026-09-04-d", "build", 9); at("2026-09-05-e", "done", 0);
501
- const ids = boardCards([dir], Date.now()).map((k) => k.id);
502
- // Unsorted this is e, d, c, b, a: d keeps slot two, the four finished runs reorder around it.
503
- expect(ids).toEqual(["2026-09-05-e", "2026-09-04-d", "2026-09-01-a", "2026-09-03-c", "2026-09-02-b"]);
504
- });
505
-
506
- test("commitPush: commits the run's files only, pushes, and records it; the message never meets a shell", async () => {
507
- const root = mkdtempSync(join(tmpdir(), "kz-git-"));
508
- const sh = (cwd: string, ...a: string[]) => Bun.spawnSync(["git", "-C", cwd, ...a]).stdout.toString().trim();
509
- expect(gitStatus(root)).toEqual({ repo: false });
510
- const bare = join(root, "remote.git"), proj = join(root, "proj"), st = join(proj, ".kaizen");
511
- mkdirSync(join(st, "runs", "r1"), { recursive: true });
512
- Bun.spawnSync(["git", "init", "-q", "--bare", bare]);
513
- Bun.spawnSync(["git", "init", "-q", proj]);
514
- for (const kv of [["user.name", "t"], ["user.email", "t@t"], ["commit.gpgsign", "false"], ["core.hooksPath", "/dev/null"]]) sh(proj, "config", ...kv);
515
- expect(gitStatus(proj)).toEqual({ repo: false }); // a repo with nowhere to push
516
- sh(proj, "remote", "add", "origin", bare);
517
- writeFileSync(join(proj, ".gitignore"), ".kaizen/\n");
518
- writeFileSync(join(proj, "a.txt"), "a");
519
- // Another run's file, staged by hand: the report does not name it, so it stays out.
520
- writeFileSync(join(proj, "c.txt"), "c");
521
- sh(proj, "add", "c.txt");
522
- expect((gitStatus(proj) as any).files.length).toBe(3);
523
- expect(runGit(st, "r1")).toMatchObject({ files: [], others: 3 }); // no report, no files
524
- writeFileSync(join(st, "runs", "r1", "03-impl.md"), "## Changed\n\n- `.gitignore`: x\n- `a.txt:1`: y\n- c.txt and `c.txt.bak` are not named\n");
525
- const files = () => (runGit(st, "r1") as any).files as string[];
526
- expect(files()).toEqual(["?? .gitignore", "?? a.txt"]);
527
- // The card's mark: the run with changed files is pending; one with none and no record says nothing.
528
- const due1: Record<string, "commit" | "push"> = {};
529
- expect(cardsGit(st, ["r1", "nope"], due1)).toEqual({ r1: "pending" });
530
- expect(due1).toEqual({ r1: "commit" });
531
- // An earlier run that named the same file is not offered it: the later report has it.
532
- mkdirSync(join(st, "runs", "r0"));
533
- writeFileSync(join(st, "runs", "r0", "03-impl.md"), "- `a.txt`: z\n");
534
- utimesSync(join(st, "runs", "r0", "03-impl.md"), new Date(1000), new Date(1000));
535
- expect(runGit(st, "r0")).toMatchObject({ files: [], others: 3 });
536
- // The later run is told the file holds the earlier run's work too.
537
- expect(runGit(st, "r1")).toMatchObject({ shared: ["a.txt: r0"] });
538
- expect(await commitPush(st, "r1", "m", ["?? a.txt"])).toMatchObject({ ok: false }); // not the list that was shown
539
- expect(sh(proj, "rev-list", "--all", "--count")).toBe("0"); // and nothing was committed
540
- expect(await commitPush(st, "r1", " ", files())).toEqual({ ok: false, why: "A commit message is required." });
541
- // A subject with no type is refused before anything is staged.
542
- for (const untyped of ["add the thing", "feature: x", "fix:no space", "note\n\nfix: in the body"])
543
- expect((await commitPush(st, "r1", untyped, files()) as { why: string }).why).toContain("Start the message with a type");
544
- expect(sh(proj, "rev-list", "--all", "--count")).toBe("0");
545
- expect(sh(proj, "diff", "--cached", "--name-only")).toBe("c.txt"); // only what was staged by hand
546
- const msg = 'fix(web)!: $(touch pwned); "q" `id`', text = "what changed\nand why";
547
- let ticked = false;
548
- setTimeout(() => { ticked = true; }, 0);
549
- const r = await commitPush(st, "r1", `${msg}\n\n${text}`, files()) as { ok: true; sha: string };
550
- expect(r.ok).toBe(true);
551
- expect(ticked).toBe(true); // the push did not hold the event loop
552
- expect(sh(proj, "log", "-1", "--format=%s")).toBe(msg);
553
- expect(sh(proj, "log", "-1", "--format=%b")).toBe(text);
554
- expect(existsSync(join(proj, "pwned"))).toBe(false);
555
- expect(sh(bare, "rev-parse", "--short", "HEAD")).toBe(r.sha);
556
- expect(runGit(st, "r1")).toMatchObject({ files: [], ahead: 0, others: 1, shared: [] });
557
- expect(sh(proj, "show", "--name-only", "--format=", "HEAD")).toBe(".gitignore\na.txt");
558
- expect(Bun.spawnSync(["git", "-C", proj, "status", "--porcelain"]).stdout.toString()).toBe("A c.txt\n");
559
- expect(readCommit(st, "r1")).toEqual({ sha: r.sha, pushed: true });
560
- expect(cardsGit(st, ["r1", "r0", "nope"])).toEqual({ r1: "pushed", r0: "pushed" }); // r0: no record, but its file is in; c.txt still changed is not its business
561
- // A done run whose report is touched after its commit is not offered later changes to its files.
562
- writeFileSync(join(st, "runs", "r1", "state.json"), JSON.stringify({ stage: "done", updated: "2000-01-01T00:00:00Z" }));
563
- utimesSync(join(st, "runs", "r1", "03-impl.md"), new Date(Date.now() + 60000), new Date(Date.now() + 60000));
564
- writeFileSync(join(proj, "a.txt"), "a2");
565
- expect(runGit(st, "r1")).toMatchObject({ files: [] });
566
- writeFileSync(join(proj, "a.txt"), "a");
567
- rmSync(join(st, "runs", "r1", "state.json"));
568
-
569
- // Windows has no file named b*.txt, so the rest is for everywhere else.
570
- if (process.platform === "win32") return;
571
- // A push that fails leaves a record that says so.
572
- sh(proj, "remote", "set-url", "origin", join(root, "gone.git"));
573
- // A fix round's report names files too, and a name with a star in it is not a pattern.
574
- mkdirSync(join(st, "runs", "r1", "05-iterations"));
575
- writeFileSync(join(st, "runs", "r1", "05-iterations", "01-fix.md"), "- `b*.txt`: fixed\n");
576
- writeFileSync(join(proj, "b*.txt"), "b");
577
- writeFileSync(join(proj, "bb.txt"), "b");
578
- expect(files()).toEqual(["?? b*.txt"]);
579
- const f = await commitPush(st, "r1", "chore: second", files()) as { ok: false; why: string };
580
- expect(f.ok).toBe(false);
581
- expect(f.why).toContain("not pushed");
582
- expect(readCommit(st, "r1")!.pushed).toBe(false);
583
- expect(sh(proj, "show", "--name-only", "--format=", "HEAD")).toBe("b*.txt");
584
- expect(runGit(st, "r1")).toMatchObject({ files: [], ahead: 1, others: 2 });
585
- const due2: Record<string, "commit" | "push"> = {};
586
- expect(cardsGit(st, ["r1"], due2)).toEqual({ r1: "pending" }); // committed, not pushed
587
- expect(due2).toEqual({ r1: "push" });
588
- expect(cardsGit(join(root, ".kaizen"), ["r1"])).toEqual({}); // not a repo
589
- }, 60_000); // dozens of git calls, ~250ms each on Windows
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
-
614
- test("runGit, cardsGit: a run committed elsewhere is not offered the edits made since, nor another run's unpushed commit", () => {
615
- const root = mkdtempSync(join(tmpdir(), "kz-git-"));
616
- const bare = join(root, "remote.git"), proj = join(root, "proj"), st = join(proj, ".kaizen");
617
- // Commit times pinned (seconds since the epoch), so each sits where the test says.
618
- const sh = (cwd: string, at: number | null, ...a: string[]) => Bun.spawnSync(["git", "-C", cwd, ...a], { env: { ...process.env, ...(at ? { GIT_COMMITTER_DATE: `@${at} +0000`, GIT_AUTHOR_DATE: `@${at} +0000` } : {}) } }).stdout.toString().trim();
619
- const report = (id: string, text: string, at: number) => {
620
- mkdirSync(join(st, "runs", id), { recursive: true });
621
- writeFileSync(join(st, "runs", id, "03-impl.md"), text);
622
- utimesSync(join(st, "runs", id, "03-impl.md"), new Date(at * 1000), new Date(at * 1000));
623
- };
624
- Bun.spawnSync(["git", "init", "-q", "--bare", bare]);
625
- Bun.spawnSync(["git", "init", "-q", proj]);
626
- for (const kv of [["user.name", "t"], ["user.email", "t@t"], ["commit.gpgsign", "false"], ["core.hooksPath", "/dev/null"]]) sh(proj, null, "config", ...kv);
627
- sh(proj, null, "remote", "add", "origin", bare);
628
- writeFileSync(join(proj, ".gitignore"), ".kaizen/\n");
629
- writeFileSync(join(proj, "x.txt"), "1");
630
- report("old", "- `x.txt`: x\n", 1000);
631
- sh(proj, null, "add", "-A");
632
- sh(proj, 2000, "commit", "-qm", "feat: x");
633
- sh(proj, null, "push", "-qu", "origin", "HEAD");
634
- // Edited again after the run's commit, by someone with no run of their own.
635
- writeFileSync(join(proj, "x.txt"), "2");
636
- expect(runGit(st, "old")).toMatchObject({ files: [], ahead: 0, others: 1 });
637
- expect(cardsGit(st, ["old"])).toEqual({ old: "pushed" });
638
- // Another run's commit, not pushed: the branch is ahead, the old run is not.
639
- writeFileSync(join(proj, "y.txt"), "y");
640
- report("new", "- `y.txt`: y\n", 3000);
641
- sh(proj, null, "add", "y.txt");
642
- sh(proj, 4000, "commit", "-qm", "feat: y");
643
- expect(runGit(st, "old")).toMatchObject({ files: [], ahead: 0 });
644
- expect(runGit(st, "new")).toMatchObject({ files: [], ahead: 1 });
645
- expect(cardsGit(st, ["old", "new"])).toEqual({ old: "pushed", new: "pending" });
646
- // The old run reporting again after its commit: the edit is its work after all.
647
- report("old", "- `x.txt`: x, again\n", 5000);
648
- expect((runGit(st, "old") as any).files).toEqual([" M x.txt"]);
649
- // A commit no run's report names still gets a push: from the run that reported last by then.
650
- const commit = (f: string, at: number, msg: string) => { writeFileSync(join(proj, f), f); sh(proj, null, "add", f); sh(proj, at, "commit", "-qm", msg); };
651
- commit("z.txt", 6000, "chore: z");
652
- expect(runGit(st, "old")).toMatchObject({ ahead: 1 });
653
- expect(runGit(st, "new")).toMatchObject({ ahead: 1 });
654
- // A run whose report holds the commit's subject as a line owns it, over the file count.
655
- report("new", "- `y.txt`: y\n\n## Commit\nchore: z\n", 3000);
656
- expect(runGit(st, "old")).toMatchObject({ ahead: 0 });
657
- expect(runGit(st, "new")).toMatchObject({ ahead: 2 });
658
- // Both runs name the file; without a subject or SHA the newer report wins.
659
- report("old", "- `x.txt`: x, again\n- `y.txt`: shared\n", 5000);
660
- report("new", "- `y.txt`: shared\n\n## Commit\nchore: z\n", 5500);
661
- writeFileSync(join(proj, "y.txt"), "shared change");
662
- sh(proj, null, "add", "y.txt");
663
- sh(proj, 7000, "commit", "-qm", "fix: shared");
664
- expect(runGit(st, "old")).toMatchObject({ ahead: 0 });
665
- expect(runGit(st, "new")).toMatchObject({ ahead: 2 });
666
- const sha = sh(proj, null, "rev-parse", "--short", "HEAD");
667
- writeFileSync(join(st, "runs", "old", "07-commit.md"), `commit: ${sha}\npushed: no\n`);
668
- expect(runGit(st, "old")).toMatchObject({ ahead: 1 });
669
- expect(runGit(st, "new")).toMatchObject({ ahead: 1 });
670
- expect(cardsGit(st, ["old", "new"])).toEqual({ old: "pending", new: "pending" });
671
- }, 60_000);
672
-
673
- test.skipIf(process.platform === "win32")("findTerminal: a running herdr wins, then tmux, else neither; the prompt stays one literal argument", () => {
674
- const bin = mkdtempSync(join(tmpdir(), "kz-bin-"));
675
- const stub = (name: string, code: number) => writeFileSync(join(bin, name), `#!/bin/sh\nexit ${code}\n`, { mode: 0o755 });
676
- const keys = ["PATH", "HERDR_ENV", "TMUX", "TERMINAL"];
677
- const saved = keys.map((k) => process.env[k]);
678
- try {
679
- process.env.PATH = bin;
680
- for (const k of keys.slice(1)) delete process.env[k];
681
- const prompt = `/kaizen it's "q" $HOME \`id\`\n\nnote`;
682
- const full = ["/usr/bin/claude", "--model", "opus", prompt];
683
- expect(findTerminal("/p", full)?.cmd[0] ?? "none").not.toMatch(/^(sh|tmux)$/); // neither installed (none: no terminal, as on CI)
684
- stub("herdr", 1); stub("tmux", 1);
685
- expect(findTerminal("/p", full)?.cmd[0] ?? "none").not.toMatch(/^(sh|tmux)$/); // installed, no server
686
- process.env.TMUX = "/tmp/x,1,0"; process.env.HERDR_ENV = "1";
687
- expect(findTerminal("/p", full)?.cmd[0] ?? "none").not.toMatch(/^(sh|tmux)$/); // stale env from a server since stopped
688
- delete process.env.TMUX; delete process.env.HERDR_ENV; stub("tmux", 0);
689
- const t = findTerminal("/p", full)!; // outside it, server up
690
- expect(t.cmd.slice(0, 4)).toEqual(["tmux", "new-window", "-c", "/p"]);
691
- stub("herdr", 0);
692
- const h = findTerminal("/p", full)!;
693
- expect([h.cmd[0], h.cmd[1], h.cmd[4], h.detached]).toEqual(["sh", "-c", "/p", false]);
694
- expect(h.cmd[2]).toContain(`pane run "$p" "exec sh $f"`); // exec: the tab closes with the agent
695
- expect(h.cmd[2]).toContain("[ $s = 127 ] || exit $s"); // ...unless it never started
696
- expect(t.cmd.slice(4)).toEqual(full); // argv: tmux runs it without its default-shell
697
- const back = Bun.spawnSync(["/bin/sh", "-c", `printf '%s\\n' ${h.cmd[5]}`]).stdout.toString();
698
- expect(back).toBe(full.join("\n") + "\n");
699
- } finally {
700
- keys.forEach((k, i) => (saved[i] === undefined ? delete process.env[k] : (process.env[k] = saved[i])));
701
- rmSync(bin, { recursive: true, force: true });
702
- }
703
- });
704
-
705
- test("nativePath on Windows reads the spellings Git Bash writes into the projects registry as one folder", () => {
706
- const platform = Object.getOwnPropertyDescriptor(process, "platform")!;
707
- try {
708
- Object.defineProperty(process, "platform", { value: "win32" });
709
- for (const p of ["/c/Users/me/proj", "C:/Users/me/proj", "c:\\Users\\me\\proj\\", "C:\\Users\\me\\proj"])
710
- expect(nativePath(p)).toBe("C:\\Users\\me\\proj");
711
- expect(nativePath("/d")).toBe("D:\\");
712
- Object.defineProperty(process, "platform", { value: "linux" });
713
- expect(nativePath("/c/Users/me")).toBe("/c/Users/me"); // elsewhere a path is left alone
714
- } finally { Object.defineProperty(process, "platform", platform); }
715
- });
716
-
717
- test("findTerminal on macOS opens $TERMINAL as an app; iTerm through a script", () => {
718
- const keys = ["PATH", "TERMINAL", "TMUX", "HERDR_ENV"];
719
- const saved = keys.map((k) => process.env[k]);
720
- const platform = Object.getOwnPropertyDescriptor(process, "platform")!;
721
- try {
722
- Object.defineProperty(process, "platform", { value: "darwin" });
723
- process.env.PATH = mkdtempSync(join(tmpdir(), "kz-empty-"));
724
- delete process.env.TMUX; delete process.env.HERDR_ENV;
725
- process.env.TERMINAL = "Ghostty";
726
- expect(findTerminal("/p", ["claude", "x"])!.cmd).toEqual(["open", "-na", "Ghostty", "--args", "--working-directory=/p", "-e", "claude", "x"]);
727
- process.env.TERMINAL = "iTerm";
728
- const i = findTerminal("/p", ["claude", "x"])!;
729
- expect(i.cmd[2]).toContain('create window with default profile command');
730
- expect(i.cmd.slice(4)).toEqual(["'/p'", "'claude' 'x'"]);
731
- } finally {
732
- Object.defineProperty(process, "platform", platform);
733
- keys.forEach((k, i) => (saved[i] === undefined ? delete process.env[k] : (process.env[k] = saved[i])));
734
- }
735
- });
736
-
737
- test("findTerminal on Windows names cmd and PowerShell by full path, so a PATH without System32 still launches", () => {
738
- const keys = ["PATH", "ComSpec", "SystemRoot", "windir"];
739
- const saved = keys.map((k) => process.env[k]);
740
- const platform = Object.getOwnPropertyDescriptor(process, "platform")!;
741
- try {
742
- Object.defineProperty(process, "platform", { value: "win32" });
743
- process.env.PATH = mkdtempSync(join(tmpdir(), "kz-empty-"));
744
- for (const k of keys.slice(1)) delete process.env[k];
745
- process.env.SystemRoot = "D:\\Win";
746
- const t = findTerminal("C:\\p", ["claude", "/kaizen x"])!;
747
- expect(t.cmd[0]).toBe("D:\\Win\\System32\\cmd.exe");
748
- expect(t.cmd[6]).toBe("D:\\Win\\System32\\WindowsPowerShell\\v1.0\\powershell.exe");
749
- process.env.ComSpec = "E:\\cmd.exe";
750
- expect(findTerminal("C:\\p", ["claude"])!.cmd[0]).toBe("E:\\cmd.exe");
751
- // A running herdr: a tab, and the run typed into it as one encoded line. The fake
752
- // is a shell script, which real Windows cannot run with ComSpec pointed elsewhere.
753
- if (platform.value === "win32") return;
754
- writeFileSync(join(process.env.PATH, "herdr"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });
755
- const h = findTerminal("C:\\p", ["claude", "/kaizen it's\nnote"])!;
756
- expect([h.cmd[0], h.cmd[1], h.cmd[2], h.detached]).toEqual(["D:\\Win\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", "-NoProfile", "-EncodedCommand", false]);
757
- const launch = Buffer.from(h.cmd[3], "base64").toString("utf16le");
758
- expect(launch).toContain("tab create --cwd 'C:\\p' --label kaizen --focus");
759
- const typed = /pane run \$Matches\[1\] '(.*)' \}/.exec(launch)![1].replace(/''/g, "'");
760
- expect(typed).not.toContain("\n");
761
- expect(typed).toEndWith("; exit"); // the tab closes with the run
762
- const run = Buffer.from(typed.split(" -EncodedCommand ")[1].replace(/; exit$/, ""), "base64").toString("utf16le");
763
- expect(run).toBe("Set-Location 'C:\\p'; & 'claude' '/kaizen it''s\nnote'");
764
- } finally {
765
- Object.defineProperty(process, "platform", platform);
766
- keys.forEach((k, i) => (saved[i] === undefined ? delete process.env[k] : (process.env[k] = saved[i])));
767
- }
768
- });
769
-
770
- test("prune: only finished runs beyond keep go, open items are rescued, a dry run deletes nothing", () => {
771
- const st = join(mkdtempSync(join(tmpdir(), "kaizen-prune-")), ".kaizen");
772
- const mk = (id: string, stage: string, backlog = "") => {
773
- const dir = join(st, "runs", id);
774
- mkdirSync(dir, { recursive: true });
775
- writeFileSync(join(dir, "state.json"), JSON.stringify({ stage, awaiting: null }));
776
- if (backlog) writeFileSync(join(dir, "06-backlog.md"), backlog);
777
- };
778
- mk("2026-01-01-old-build", "build"); // oldest of all, not finished
779
- mk("2026-01-02-old-review", "review");
780
- mk("2026-01-03-old-plan", "plan");
781
- mk("2026-01-04-done", "done", "- open: keep me\n- done: closed | x\n");
782
- mk("2026-01-05-abandoned", "abandoned", "- open: not open work\n");
783
- mk("2026-01-06-done", "done");
784
- mk("2026-01-07-done", "done");
785
- writeFileSync(join(st, "backlog.md"), "- open: already here"); // no trailing newline
786
-
787
- expect(pruneRuns(st, 2).map((g) => g.id)).toEqual(["2026-01-04-done", "2026-01-05-abandoned"]);
788
- expect(readdirSync(join(st, "runs")).length).toBe(7); // dry run
789
-
790
- expect(pruneRuns(st, 2, true)).toEqual([{ id: "2026-01-04-done", rescued: 1 }, { id: "2026-01-05-abandoned", rescued: 0 }]);
791
- expect(readdirSync(join(st, "runs")).sort()).toEqual(
792
- ["2026-01-01-old-build", "2026-01-02-old-review", "2026-01-03-old-plan", "2026-01-06-done", "2026-01-07-done"]);
793
- expect(readFileSync(join(st, "backlog.md"), "utf8")).toBe("- open: already here\n- open: keep me | from 2026-01-04-done\n");
794
- expect(pruneRuns(st, 2, true)).toEqual([]);
795
- rmSync(dirname(st), { recursive: true, force: true });
796
- });
797
-
798
- test("unrechecked: the last fix with no recheck beside it", () => {
799
- const dir = run("2026-09-04-fixes", { stage: "done", awaiting: null });
800
- expect(unrechecked(state, "2026-09-04-fixes")).toBe(false);
801
- mkdirSync(join(dir, "05-iterations"));
802
- writeFileSync(join(dir, "05-iterations", "01-fix.md"), "");
803
- expect(unrechecked(state, "2026-09-04-fixes")).toBe(true);
804
- writeFileSync(join(dir, "05-iterations", "01-recheck.md"), "");
805
- expect(unrechecked(state, "2026-09-04-fixes")).toBe(false);
806
- writeFileSync(join(dir, "05-iterations", "02-fix.md"), "");
807
- expect(boardCards([state], Date.now()).find((c) => c.id === "2026-09-04-fixes")!.tags).toContain("unrechecked");
808
- rmSync(dir, { recursive: true, force: true });
809
- });
810
-
811
- test("notice: plain words for what a run waits on, done, and nothing for the rest", () => {
812
- const c = (o: Partial<Card>): Card => ({ kind: "run", status: "waiting", text: "payroll", state: "", where: "~/acme", column: 1, awaiting: null, dim: false, archived: false, ...o });
813
- expect(notice(c({ awaiting: "approvals.plan" }))).toBe("payroll — plan needs your approval\n~/acme");
814
- for (const a of ["approvals.plan", "approvals.review", "approvals.each_file", "findings"]) expect(notice(c({ awaiting: a }))).not.toContain("waiting on");
815
- expect(notice(c({ awaiting: "something.new" }))).toBe("payroll — waiting on something.new\n~/acme");
816
- expect(notice(c({ status: "done" }))).toBe("payroll — done\n~/acme");
817
- for (const o of [{ status: "running" }, { status: "abandoned" }, { kind: "idea" as const, status: "idea" }]) expect(notice(c(o))).toBeNull();
818
- expect(notifyArgs("x")).toEqual(["notify-send", "-a", "kaizen", "-i", LOGO, "kaizen", "x"]);
819
- });
820
-
821
- test("winToastArgs carries the body base64, so a quote cannot end the PowerShell string", () => {
822
- const body = "it's \"done\" — ~/acme\n$(rm)";
823
- const a = winToastArgs(body);
824
- expect(a[0]).toMatch(/WindowsPowerShell\\v1\.0\\powershell\.exe$/);
825
- const b64 = /FromBase64String\('([^']+)'\)/.exec(a.at(-1)!)![1]!;
826
- expect(Buffer.from(b64, "base64").toString("utf8")).toBe(body);
827
- expect(a.at(-1)).not.toContain("rm)");
828
- });
829
-
830
- test("notifier: only a run seen before, saying something new, and not a done the user just approved", () => {
831
- const due = notifier(), M = 60_000;
832
- expect(due("r", "a", false, 0)).toBe(false); // first load, or arrived already waiting
833
- expect(due("r", "a", false, 1)).toBe(false); // still waiting
834
- expect(due("r", "b", false, 2)).toBe(true); // waiting on something else now
835
- expect(due("r", "d", true, 3 * M)).toBe(false); // approved: waiting straight to done
836
- expect(due("s", null, false, 0)).toBe(false);
837
- expect(due("s", "a", false, 1)).toBe(true); // started waiting
838
- expect(due("s", null, false, 2)).toBe(false); // approved, back to work
839
- expect(due("s", "d", true, 3)).toBe(false); // ...and done in a second write
840
- expect(due("t", "a", false, 0)).toBe(false);
841
- expect(due("t", null, false, 1)).toBe(false);
842
- expect(due("t", "d", true, 2 * M)).toBe(true); // finished on its own, long after the last wait
843
- expect(due("u", null, false, 0)).toBe(false);
844
- expect(due("u", "d", true, 1)).toBe(true); // never waited
845
- // web.ts writes the function into the page over this marker; without it the board throws on load.
846
- expect(notifier.toString()).toStartWith("function notifier(");
847
- expect(readFileSync(join(import.meta.dir, "..", "web", "board.html"), "utf8")).toContain("(/*notifier*/)()");
848
- });
849
-
850
- test("files written by Windows PowerShell, with a byte order mark, still read: the run shows, the first task is a task", () => {
851
- const st = join(mkdtempSync(join(tmpdir(), "kaizen-bom-")), ".kaizen");
852
- mkdirSync(join(st, "runs", "r1"), { recursive: true });
853
- writeFileSync(join(st, "runs", "r1", "state.json"), "" + JSON.stringify({ id: "r1", stage: "plan", awaiting: "approvals.plan" }));
854
- writeFileSync(join(st, "inbox.md"), "- open: first task\n");
855
- expect(readRuns(st).map((r) => [r.id, r.stage])).toEqual([["r1", "plan"]]);
856
- expect(readInbox(st)).toEqual([{ status: "open", text: "first task" }]);
857
- });
858
-
859
- test("remember on Windows stores one spelling per folder, the one knownProjects returns", () => {
860
- // REGISTRY is bound to the home at import, so this runs in a child with a scratch HOME.
861
- const home = mkdtempSync(join(tmpdir(), "kz-home-"));
862
- const script = `Object.defineProperty(process, "platform", { value: "win32" });
863
- const { remember, knownProjects, REGISTRY } = await import(${JSON.stringify(join(dirname(import.meta.path), "state.ts"))});
864
- remember("c:\\\\p"); remember("C:\\\\p"); remember("/c/p");
865
- console.log(JSON.stringify([require("node:fs").readFileSync(REGISTRY, "utf8"), knownProjects()]));`;
866
- try {
867
- const p = Bun.spawnSync(["bun", "-e", script], { cwd: home, env: { ...process.env, HOME: home, USERPROFILE: home } });
868
- if (p.exitCode !== 0) throw new Error(p.stderr.toString());
869
- expect(JSON.parse(p.stdout.toString())).toEqual(["C:\\p\n", ["C:\\p"]]);
870
- } finally { rmSync(home, { recursive: true, force: true }); }
871
- });
872
-
873
- test("the project registry lists one folder once: trailing slash and symlink spellings collapse, the file is not rewritten", () => {
874
- const home = mkdtempSync(join(tmpdir(), "kz-home-")), proj = join(home, "shop");
875
- mkdirSync(proj);
876
- symlinkSync(proj, join(home, "link"));
877
- mkdirSync(join(home, ".kaizen"));
878
- const dup = `${proj}\n${proj}/\n${join(home, "link")}\n`;
879
- writeFileSync(join(home, ".kaizen", "projects"), dup);
880
- const script = `const { remember, knownProjects, REGISTRY } = await import(${JSON.stringify(join(dirname(import.meta.path), "state.ts"))});
881
- remember(${JSON.stringify(join(home, "link") + "/")});
882
- console.log(JSON.stringify([knownProjects(), require("node:fs").readFileSync(REGISTRY, "utf8")]));`;
883
- try {
884
- const p = Bun.spawnSync(["bun", "-e", script], { cwd: home, env: { ...process.env, HOME: home, USERPROFILE: home } });
885
- if (p.exitCode !== 0) throw new Error(p.stderr.toString());
886
- const [list, file] = JSON.parse(p.stdout.toString());
887
- expect(list).toEqual([realpathSync(proj)]);
888
- expect(file).toBe(dup); // already known: nothing appended, nothing rewritten
889
- } finally { rmSync(home, { recursive: true, force: true }); }
890
- });
891
-
892
- test("files saved with CRLF (PowerShell, autocrlf clones) read the same as LF", () => {
893
- const lf = join(mkdtempSync(join(tmpdir(), "kz-")), ".kaizen"), crlf = join(mkdtempSync(join(tmpdir(), "kz-")), ".kaizen");
894
- const files = {
895
- "config.yml": "agent:\n default: claude\n claude: { model: opus, effort: high }\n",
896
- "inbox.md": "# Inbox\n\n- open: add retry\n- rejected: drop cache\n",
897
- "runs/2026-10-01-a/state.json": JSON.stringify({ stage: "build", status: "running" }, null, 2) + "\n",
898
- "runs/2026-10-01-a/00-request.md": "# Request\n\n> /kaizen add retry\n",
899
- };
900
- for (const [dir, eol] of [[lf, "\n"], [crlf, "\r\n"]] as const)
901
- for (const [f, text] of Object.entries(files)) {
902
- mkdirSync(dirname(join(dir, f)), { recursive: true });
903
- writeFileSync(join(dir, f), text.replace(/\n/g, eol));
904
- }
905
- expect(agentFlags(dirname(crlf), "claude")).toEqual(["--model", "opus", "--effort", "high"]);
906
- expect(readInbox(crlf)).toEqual(readInbox(lf));
907
- const runs = (s: string) => readRuns(s).map(({ moved, ...r }) => ({ ...r, dir: undefined }));
908
- expect(runs(crlf)).toEqual(runs(lf));
909
- });
910
-
911
- // A project whose agent sessions are recorded: close on, one run asked for "tidy logs".
912
- const sessionProject = () => {
913
- const p = mkdtempSync(join(tmpdir(), "kz-sess-"));
914
- mkdirSync(join(p, ".kaizen", "runs"), { recursive: true });
915
- writeFileSync(join(p, ".kaizen", "config.yml"), "agent:\n default: claude\n close: on\n");
916
- return p;
917
- };
918
- const newRun = (p: string, id: string, request: string, s: object = { stage: "plan", awaiting: "approvals.plan" }) => {
919
- mkdirSync(join(p, ".kaizen", "runs", id), { recursive: true });
920
- writeFileSync(join(p, ".kaizen", "runs", id, "00-request.md"), `# Request (verbatim)\n\n${request}\n`);
921
- writeFileSync(join(p, ".kaizen", "runs", id, "state.json"), JSON.stringify(s));
922
- };
923
-
924
- test("sessionLaunch: claude gets a conversation id, a decision resumes it while its transcript exists, codex starts fresh", () => {
925
- const p = sessionProject(), st = join(p, ".kaizen");
926
- const saved = process.env.CLAUDE_CONFIG_DIR;
927
- process.env.CLAUDE_CONFIG_DIR = mkdtempSync(join(tmpdir(), "kz-claude-"));
928
- try {
929
- const task = sessionLaunch(p, "claude", ["/bin/claude", "--model", "opus"], "/kaizen tidy logs", "tidy logs");
930
- const [rec] = readSessions(st);
931
- expect(rec.sessionId).toMatch(/^[0-9a-f-]{36}$/);
932
- expect(task.fullCmd).toEqual(["/bin/claude", "--session-id", rec.sessionId!, "--model", "opus", "/kaizen tidy logs"]);
933
- expect(task.pidFile).toBe(join(st, "sessions", rec.key + ".pid"));
934
- newRun(p, "2026-10-01-tidy-logs", "/kaizen tidy logs");
935
- expect(ownerOf(st, rec)).toBe("2026-10-01-tidy-logs");
936
-
937
- // No transcript on disk: a fresh session, with an id of its own.
938
- const fresh = sessionLaunch(p, "claude", ["/bin/claude"], "/kaizen run x: approved", "run x: approved", "2026-10-01-tidy-logs");
939
- expect(fresh.fullCmd[1]).toBe("--session-id");
940
- expect(fresh.fullCmd[2]).not.toBe(rec.sessionId);
941
-
942
- const t = join(process.env.CLAUDE_CONFIG_DIR, "projects", p.replace(/[^A-Za-z0-9]/g, "-"));
943
- mkdirSync(t, { recursive: true });
944
- writeFileSync(join(t, `${rec.sessionId}.jsonl`), "{}\n");
945
- const back = sessionLaunch(p, "claude", ["/bin/claude"], "/kaizen run x: approved", "run x: approved", "2026-10-01-tidy-logs");
946
- expect(back.fullCmd).toEqual(["/bin/claude", "--resume", rec.sessionId!, "/kaizen run x: approved"]);
947
- expect(readSessions(st).filter((r) => r.run === "2026-10-01-tidy-logs" && r.sessionId === rec.sessionId)).toHaveLength(1);
948
-
949
- // Another tool's record never resumes; codex takes no id at launch.
950
- expect(sessionLaunch(p, "codex", ["/bin/codex"], "/kaizen run x: approved", "x", "2026-10-01-tidy-logs").fullCmd).toEqual(["/bin/codex", "/kaizen run x: approved"]);
951
- } finally {
952
- saved === undefined ? delete process.env.CLAUDE_CONFIG_DIR : (process.env.CLAUDE_CONFIG_DIR = saved);
953
- }
954
- // A folder with no state dir gets no record, and no .kaizen made for one.
955
- const bare = mkdtempSync(join(tmpdir(), "kz-bare-"));
956
- expect(sessionLaunch(bare, "claude", ["claude"], "/kaizen x", "x")).toMatchObject({ fullCmd: ["claude", "/kaizen x"], pidFile: undefined });
957
- expect(existsSync(join(bare, ".kaizen"))).toBe(false);
958
- });
959
-
960
- test("ownerOf: a task's session belongs to the first run created after it, not an older one with the same words", () => {
961
- const p = sessionProject(), st = join(p, ".kaizen");
962
- newRun(p, "2026-09-01-old", "/kaizen fix the login page");
963
- const rec = { key: "k", run: null, text: "fix the login page", cmd: "claude", sessionId: null, started: Date.now() + 5000 };
964
- expect(ownerOf(st, rec)).toBe(null);
965
- expect(ownerOf(st, { ...rec, started: 0 })).toBe("2026-09-01-old");
966
- expect(ownerOf(st, { ...rec, run: "2026-10-01-x" })).toBe("2026-10-01-x");
967
- });
968
-
969
- test("ownerOf: a run that recorded the launch's session id owns it, however its request is worded", () => {
970
- const p = sessionProject(), st = join(p, ".kaizen");
971
- newRun(p, "2026-10-02-reworded", "/kaizen something else entirely");
972
- const f = join(st, "runs", "2026-10-02-reworded", "state.json");
973
- writeFileSync(f, JSON.stringify({ ...JSON.parse(readFileSync(f, "utf8")), session: "abc" }));
974
- const rec = { key: "k", run: null, text: "open it on my phone", cmd: "claude", sessionId: "abc", started: Date.now() };
975
- expect(ownerOf(st, rec)).toBe("2026-10-02-reworded");
976
- expect(ownerOf(st, { ...rec, sessionId: "other" })).toBe(null);
977
- });
978
-
979
- test("ownerOf: a conversation that opens a follow-up run moves to it, even from a decision on its parent", () => {
980
- const p = sessionProject(), st = join(p, ".kaizen");
981
- const tag = (id: string, more: object = {}) => {
982
- const f = join(st, "runs", id, "state.json");
983
- writeFileSync(f, JSON.stringify({ ...JSON.parse(readFileSync(f, "utf8")), session: "abc", ...more }));
984
- };
985
- const rec = { key: "k", run: null, text: "tidy logs", cmd: "claude", sessionId: "abc", started: Date.now() - 2000 };
986
- newRun(p, "2026-10-01-parent", "/kaizen tidy logs");
987
- tag("2026-10-01-parent");
988
- expect(ownerOf(st, rec)).toBe("2026-10-01-parent");
989
- // A parent still in flight keeps its terminal.
990
- newRun(p, "2026-10-02-child", "/kaizen rotate them too\nFollow-up of: 2026-10-01-parent");
991
- tag("2026-10-02-child");
992
- expect(ownerOf(st, rec)).toBe("2026-10-01-parent");
993
- expect(ownerOf(st, { ...rec, run: "2026-10-01-parent" })).toBe("2026-10-01-parent");
994
- tag("2026-10-01-parent", { stage: "done", awaiting: null });
995
- expect(ownerOf(st, rec)).toBe("2026-10-02-child");
996
- expect(ownerOf(st, { ...rec, run: "2026-10-01-parent" })).toBe("2026-10-02-child");
997
- // A decision launched after both: the run it names, as before.
998
- expect(ownerOf(st, { ...rec, run: "2026-10-01-parent", started: Date.now() + 5000 })).toBe("2026-10-01-parent");
999
-
1000
- // The parent's next decision still continues the conversation the child took over.
1001
- const saved = process.env.CLAUDE_CONFIG_DIR;
1002
- process.env.CLAUDE_CONFIG_DIR = mkdtempSync(join(tmpdir(), "kz-claude-"));
1003
- try {
1004
- mkdirSync(join(st, "sessions"), { recursive: true });
1005
- const { key, ...body } = rec;
1006
- writeFileSync(join(st, "sessions", key + ".json"), JSON.stringify(body) + "\n");
1007
- const t = join(process.env.CLAUDE_CONFIG_DIR, "projects", p.replace(/[^A-Za-z0-9]/g, "-"));
1008
- mkdirSync(t, { recursive: true });
1009
- writeFileSync(join(t, "abc.jsonl"), "{}\n");
1010
- expect(sessionLaunch(p, "claude", ["/bin/claude"], "/kaizen run x", "x", "2026-10-01-parent").fullCmd.slice(0, 3)).toEqual(["/bin/claude", "--resume", "abc"]);
1011
- } finally {
1012
- saved === undefined ? delete process.env.CLAUDE_CONFIG_DIR : (process.env.CLAUDE_CONFIG_DIR = saved);
1013
- }
1014
- });
1015
-
1016
- test("findTerminal records the agent's PID: a POSIX wrapper that execs it, a PowerShell prefix on Windows", () => {
1017
- const keys = ["PATH", "HERDR_ENV", "TMUX", "TERMINAL", "SystemRoot", "windir", "ComSpec"];
1018
- const saved = keys.map((k) => process.env[k]);
1019
- const platform = Object.getOwnPropertyDescriptor(process, "platform")!;
1020
- const bin = mkdtempSync(join(tmpdir(), "kz-bin-"));
1021
- try {
1022
- process.env.PATH = bin;
1023
- for (const k of keys.slice(1)) delete process.env[k];
1024
- writeFileSync(join(bin, "tmux"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });
1025
- if (process.platform !== "win32") {
1026
- const t = findTerminal("/p", ["claude", "/kaizen x"], "/s/k.pid")!;
1027
- expect(t.cmd.slice(4)).toEqual(["sh", "-c", 'echo $$ > "$0"; exec "$@"', "/s/k.pid", "claude", "/kaizen x"]);
1028
- }
1029
- Object.defineProperty(process, "platform", { value: "win32" });
1030
- process.env.SystemRoot = "D:\\Win";
1031
- const w = findTerminal("C:\\p", ["claude", "/kaizen x"], "C:\\p\\.kaizen\\sessions\\k.pid")!;
1032
- const ps = Buffer.from(w.cmd.at(-1)!, "base64").toString("utf16le");
1033
- expect(ps).toBe("$PID | Set-Content -LiteralPath 'C:\\p\\.kaizen\\sessions\\k.pid'; Set-Location 'C:\\p'; & 'claude' '/kaizen x'; if (-not (Test-Path -LiteralPath 'C:\\p\\.kaizen\\sessions\\k.pid')) { exit 0 }");
1034
- } finally {
1035
- Object.defineProperty(process, "platform", platform);
1036
- keys.forEach((k, i) => (saved[i] === undefined ? delete process.env[k] : (process.env[k] = saved[i])));
1037
- rmSync(bin, { recursive: true, force: true });
1038
- }
1039
- });
1040
-
1041
- test.skipIf(process.platform === "win32")("sessionLaunch: gemini, codex, agy and opencode resume the run's own conversation, found in each tool's own files", () => {
1042
- // agy's files sit under the home bound at import, so this runs in a child with a scratch HOME.
1043
- const home = mkdtempSync(join(tmpdir(), "kz-home-"));
1044
- const script = `const S = await import(${JSON.stringify(join(dirname(import.meta.path), "state.ts"))});
1045
- const fs = require("node:fs"), { join, dirname } = require("node:path"), { Database } = require("bun:sqlite");
1046
- const H = process.env.HOME, P = join(H, "proj"), st = join(P, ".kaizen"), out = {};
1047
- const put = (f, t) => { fs.mkdirSync(dirname(f), { recursive: true }); fs.writeFileSync(f, t); };
1048
- for (const r of ["r1", "r2", "r3"]) { put(join(st, "runs", r, "00-request.md"), "x"); put(join(st, "runs", r, "state.json"), "{}"); }
1049
- const go = (cmd, run = "r1", base = [cmd]) => S.sessionLaunch(P, cmd, base, "/kaizen x", "x", run).fullCmd;
1050
- const iso = (ms) => new Date(ms).toISOString();
1051
-
1052
- // gemini: its id is picked at launch, resumed once its chat file exists.
1053
- const g1 = go("gemini"), gid = g1[2];
1054
- out.gemini = [g1[1], go("gemini")[1], go("gemini")[2] === gid];
1055
- put(join(H, ".gemini", "tmp", "proj", "chats", "session-2026-10-15T10-00-" + gid.slice(0, 8) + ".jsonl"), "{}");
1056
- out.gemini.push(go("gemini"));
1057
-
1058
- // codex: its own id, read from the rollout the launch began in this folder.
1059
- const now = Date.now(), d = new Date(now);
1060
- const day = join(H, ".codex", "sessions", String(d.getFullYear()), String(d.getMonth() + 1).padStart(2, "0"), String(d.getDate()).padStart(2, "0"));
1061
- const roll = (id, t, cwd) => put(join(day, "rollout-x-" + id + ".jsonl"), JSON.stringify({ timestamp: iso(t), type: "session_meta", payload: { id, cwd, base_instructions: { text: "y".repeat(9000) } } }) + "\\n");
1062
- const A = "00000000-0000-7000-8000-00000000000a", B = "00000000-0000-7000-8000-00000000000b";
1063
- roll("00000000-0000-7000-8000-0000000000e0", now - 60_000, P); // before any launch
1064
- go("codex", "r3"); // its agent never began one
1065
- await Bun.sleep(10);
1066
- const c1 = go("codex");
1067
- await Bun.sleep(10);
1068
- roll("00000000-0000-7000-8000-0000000000e1", Date.now(), join(H, "else")); // another folder
1069
- roll(A, Date.now(), P);
1070
- await Bun.sleep(10);
1071
- go("codex", "r2");
1072
- await Bun.sleep(10);
1073
- roll(B, Date.now(), P);
1074
- await Bun.sleep(10);
1075
- // r3, asked first, never takes r1's or r2's: a conversation begun after the tool's next launch is not its.
1076
- const r3 = go("codex", "r3");
1077
- out.codex = [c1, go("codex", "r1", ["codex", "-m", "gpt-5"]), go("codex", "r2"), r3];
1078
-
1079
- // agy: the conversation database created after the launch with this folder in its metadata.
1080
- go("agy");
1081
- const conv = join(H, ".gemini", "antigravity-cli", "conversations");
1082
- const agyDb = (id, folder) => {
1083
- fs.mkdirSync(conv, { recursive: true });
1084
- const d = new Database(join(conv, id + ".db"));
1085
- d.run("create table trajectory_metadata_blob (id text, data blob)");
1086
- d.run("insert into trajectory_metadata_blob values ('main', ?)", [Buffer.from("\\n'file://" + folder + "\\x12'file://" + folder + "\\x1a")]);
1087
- d.close();
1088
- };
1089
- agyDb("agy-else", join(H, "else"));
1090
- agyDb("agy-sibling", P + "-bot"); // a folder whose name starts with this one
1091
- put(join(conv, "agy-broken.db"), "not a database");
1092
- out.agy = [go("agy")];
1093
- agyDb("agy-mine", P);
1094
- out.agy.push(go("agy"));
1095
-
1096
- // opencode: a broken database is a fresh session; a real one names the conversation.
1097
- go("opencode");
1098
- put(join(H, ".local", "share", "opencode", "opencode.db"), "not a database");
1099
- out.opencode = [go("opencode")];
1100
- fs.rmSync(join(H, ".local", "share", "opencode", "opencode.db"));
1101
- const db = new Database(join(H, ".local", "share", "opencode", "opencode.db"));
1102
- db.run("create table session (id text primary key, directory text, time_created integer, parent_id text)");
1103
- const t = Date.now();
1104
- for (const [id, dir, at, parent] of [["ses_old", P, t - 60_000, null], ["ses_child", P, t, "ses_x"], ["ses_else", join(H, "else"), t, null], ["ses_mine", P, t + 1, null]]) db.run("insert into session values (?, ?, ?, ?)", [id, dir, at, parent]);
1105
- db.close();
1106
- out.opencode.push(go("opencode"));
1107
- console.log(JSON.stringify(out));`;
1108
- try {
1109
- const p = Bun.spawnSync(["bun", "-e", script], { cwd: home, env: { ...process.env, HOME: home, CODEX_HOME: "", XDG_DATA_HOME: "", GEMINI_CLI_HOME: "", CLAUDE_CONFIG_DIR: "" } });
1110
- if (p.exitCode !== 0) throw new Error(p.stderr.toString());
1111
- const out = JSON.parse(p.stdout.toString());
1112
- const [startFlag, freshFlag, sameId, gResume] = out.gemini;
1113
- expect([startFlag, freshFlag, sameId]).toEqual(["--session-id", "--session-id", false]);
1114
- expect(gResume[1]).toBe("--resume");
1115
- expect(out.codex).toEqual([
1116
- ["codex", "/kaizen x"],
1117
- ["codex", "resume", "00000000-0000-7000-8000-00000000000a", "-m", "gpt-5", "/kaizen x"],
1118
- ["codex", "resume", "00000000-0000-7000-8000-00000000000b", "/kaizen x"],
1119
- ["codex", "/kaizen x"],
1120
- ]);
1121
- expect(out.agy).toEqual([["agy", "-i", "/kaizen x"], ["agy", "--conversation", "agy-mine", "-i", "/kaizen x"]]);
1122
- expect(out.opencode).toEqual([["opencode", "--prompt", "/kaizen x"], ["opencode", "--session", "ses_mine", "--prompt", "/kaizen x"]]);
1123
- } finally {
1124
- rmSync(home, { recursive: true, force: true });
1125
- }
1126
- });
1127
-
1128
- test.skipIf(process.platform === "win32")("closeSessions still ends a codex launch whose id was read from its files afterwards", async () => {
1129
- const p = sessionProject(), st = join(p, ".kaizen"), dir = join(st, "sessions");
1130
- newRun(p, "2026-10-01-a", "/kaizen a");
1131
- mkdirSync(dir, { recursive: true });
1132
- // Launched as `codex <prompt>`: the id found later is not in its arguments.
1133
- writeFileSync(join(dir, "c.json"), JSON.stringify({ run: "2026-10-01-a", text: "a", cmd: "codex", sessionId: "found-later", started: Date.now() - 5000 }));
1134
- const pr = Bun.spawn(["sh", "-c", 'echo $$ > "$0"; exec "$@"', join(dir, "c.pid"), "sh", "-c", "sleep 30; :", "codex"], { stdout: "ignore", stderr: "ignore" });
1135
- for (let i = 0; i < 100 && !existsSync(join(dir, "c.pid")); i++) await Bun.sleep(20);
1136
- try {
1137
- expect(closeSessions(st, "2026-10-01-a")).toBe(1);
1138
- expect(await pr.exited).not.toBe(0);
1139
- } finally {
1140
- pr.kill();
1141
- }
1142
- });
1143
-
1144
- test.skipIf(process.platform === "win32")("closeSessions ends only the run's own live sessions launched before the decision", async () => {
1145
- const p = sessionProject(), st = join(p, ".kaizen"), dir = join(st, "sessions");
1146
- newRun(p, "2026-10-01-a", "/kaizen a");
1147
- mkdirSync(dir, { recursive: true });
1148
- // A stand-in agent through the real wrapper: `kzagent <id>` in its arguments, as
1149
- // `claude --session-id <id>` would be. `; :` keeps sh from exec'ing sleep itself.
1150
- const start = (key: string, rec: object) => {
1151
- writeFileSync(join(dir, key + ".json"), JSON.stringify({ run: "2026-10-01-a", text: "a", cmd: "kzagent", sessionId: "sid-" + key, started: Date.now() - 5000, ...rec }));
1152
- return Bun.spawn(["sh", "-c", 'echo $$ > "$0"; exec "$@"', join(dir, key + ".pid"), "sh", "-c", "sleep 30; :", "kzagent", "sid-" + key], { stdout: "ignore", stderr: "ignore" });
1153
- };
1154
- // Killed by a signal, a process keeps exitCode null; signalCode says it died.
1155
- const alive = (pr: ReturnType<typeof Bun.spawn>) => pr.exitCode === null && pr.signalCode === null;
1156
- const procs: Record<string, ReturnType<typeof Bun.spawn>> = {
1157
- mine: start("mine", {}),
1158
- later: start("later", { started: Date.now() - 1000 }), // the decision's own successor: after `before` below
1159
- stranger: start("stranger", { cmd: "notkzagent" }), // a PID that is not this agent
1160
- other: start("other", { run: "2026-10-01-b" }), // another run's
1161
- };
1162
- for (let i = 0; i < 100 && Object.keys(procs).some((k) => !existsSync(join(dir, k + ".pid"))); i++) await Bun.sleep(20);
1163
- writeFileSync(join(dir, "dead.json"), JSON.stringify({ run: "2026-10-01-a", text: "a", cmd: "kzagent", sessionId: null, started: 0 }));
1164
- writeFileSync(join(dir, "dead.pid"), "999999\n");
1165
- try {
1166
- expect(closeSessions(st, "2026-10-01-a", { before: Date.now() - 3000 })).toBe(1);
1167
- expect(await procs.mine.exited).not.toBe(0);
1168
- for (const k of ["later", "stranger", "other"] as const) expect(alive(procs[k])).toBe(true);
1169
- expect(existsSync(join(dir, "mine.pid"))).toBe(false);
1170
- expect(existsSync(join(dir, "mine.json"))).toBe(true); // its conversation id is still needed
1171
- expect(existsSync(join(dir, "dead.pid"))).toBe(false);
1172
- expect(existsSync(join(dir, "later.pid"))).toBe(true);
1173
- expect(existsSync(join(dir, "stranger.pid"))).toBe(false); // its number is held by something else: dropped, not killed
1174
-
1175
- // Off: nothing is ended.
1176
- writeFileSync(join(st, "config.yml"), "agent:\n default: claude\n close: off\n");
1177
- expect(closeSessions(st, "2026-10-01-b")).toBe(0);
1178
- expect(alive(procs.other)).toBe(true);
1179
- writeFileSync(join(st, "config.yml"), "agent:\n default: claude\n close: on\n");
1180
-
1181
- // The sweep: a done run keeps its window; only a PID file whose process is gone is dropped.
1182
- newRun(p, "2026-10-01-b", "/kaizen b", { stage: "done", awaiting: null });
1183
- sweepSessions(st);
1184
- await Bun.sleep(100);
1185
- expect(alive(procs.other)).toBe(true);
1186
- writeFileSync(join(dir, "dead2.json"), JSON.stringify({ run: "2026-10-01-a", text: "a", cmd: "kzagent", sessionId: null, started: 0 }));
1187
- writeFileSync(join(dir, "dead2.pid"), "999999\n");
1188
- sweepSessions(st);
1189
- expect(existsSync(join(dir, "dead2.pid"))).toBe(false);
1190
- expect(existsSync(join(dir, "dead2.json"))).toBe(true);
1191
- expect(existsSync(join(dir, "later.pid"))).toBe(true);
1192
- } finally {
1193
- for (const pr of Object.values(procs)) pr.kill();
1194
- }
1195
- });
1196
-
1197
- test("abandonRun closes the run's recorded sessions", () => {
1198
- const p = sessionProject(), st = join(p, ".kaizen");
1199
- newRun(p, "2026-10-01-z", "/kaizen z");
1200
- mkdirSync(join(st, "sessions"));
1201
- writeFileSync(join(st, "sessions", "k.json"), JSON.stringify({ run: "2026-10-01-z", text: "z", cmd: "kzagent", sessionId: null, started: 0 }));
1202
- writeFileSync(join(st, "sessions", "k.pid"), "999999\n");
1203
- expect(abandonRun(st, "2026-10-01-z", "no")).toBe(null);
1204
- expect(existsSync(join(st, "sessions", "k.pid"))).toBe(false);
1205
- });
1206
-
1207
- // The folder dialog cannot be opened in a test, but its script can be checked without
1208
- // showing it: compiled on a Mac, parsed on Windows. Elsewhere only the shape is pinned.
1209
- test("folder dialog: each platform's script is well formed", async () => {
1210
- const { folderDialog } = await import("./web.ts");
1211
- const mac = folderDialog("darwin")!, win = folderDialog("win32")!;
1212
- expect(mac.slice(0, 3)).toEqual(["osascript", "-e", "activate"]);
1213
- expect(win.at(-1)).toContain("FolderBrowserDialog");
1214
- if (process.platform === "darwin") {
1215
- const out = join(mkdtempSync(join(tmpdir(), "kaizen-osa-")), "x.scpt");
1216
- expect(Bun.spawnSync(["osacompile", ...mac.slice(1), "-o", out]).exitCode).toBe(0);
1217
- }
1218
- if (process.platform === "win32") {
1219
- const check = `$e=$null;[void][System.Management.Automation.Language.Parser]::ParseInput($env:KZ_PS,[ref]$null,[ref]$e);exit $e.Count`;
1220
- expect(Bun.spawnSync([win[0], "-NoProfile", "-Command", check], { env: { ...process.env, KZ_PS: win.at(-1)! } }).exitCode).toBe(0);
1221
- }
1222
- });
1223
-
1224
- test("issueUrl prefills the bug form's fields, without the home path", () => {
1225
- const u = new URL(issueUrl({ title: "boom", what: `ENOENT ${realHome}/Projects/x/.kaizen/state.json` }));
1226
- expect(`${u.origin}${u.pathname}`).toBe(`${REPO_URL}/issues/new`);
1227
- expect(u.searchParams.get("what")).toBe("ENOENT ~/Projects/x/.kaizen/state.json");
1228
- expect(u.searchParams.get("env")).toBe(systemInfo());
1229
- // Every key but GitHub's own must be a field id in the form, or it is dropped silently.
1230
- const ids = [...readFileSync(join(import.meta.dir, "..", ".github", "ISSUE_TEMPLATE", "bug.yml"), "utf8").matchAll(/^\s+id: (\S+)/gm)].map((m) => m[1]);
1231
- for (const k of u.searchParams.keys()) if (!["template", "title", "body"].includes(k)) expect(ids).toContain(k);
1232
- // Without the form on GitHub only `body` is read, so it must hold the machine too.
1233
- expect(u.searchParams.get("body")).toContain(systemInfo());
1234
- expect(u.searchParams.get("body")).toContain("ENOENT ~/Projects/x/.kaizen/state.json");
1235
- expect(systemInfo()).toMatch(/^kaizen: .+\nOS: .+\nCPU: .+\nRAM: \d+ GB\nbun: /);
1236
- });
1237
-
1238
- test("issueUrl stays under GitHub's URL limit for a huge error", () => {
1239
- const u = issueUrl({ title: "x".repeat(500), what: "é".repeat(20000) });
1240
- expect(u.length).toBeLessThan(8000);
1241
- expect(new URL(u).searchParams.get("what")).toContain("…(cut)");
1242
- });
1243
-
1244
- test("scrubHome hides a Windows home however the error spells it", () => {
1245
- const h = ["C:\\Users\\Firman"];
1246
- expect(scrubHome(`open C:\\Users\\Firman\\x, "c:\\\\users\\\\firman\\\\y", C:/Users/Firman/z`, h, true))
1247
- .toBe(`open ~\\x, "~\\\\y", ~/z`);
1248
- // Case matters off Windows: /home/Ann is not /home/ann.
1249
- expect(scrubHome("/home/ann/a /home/Ann/b", ["/home/ann"], false)).toBe("~/a /home/Ann/b");
1250
- });
1251
-
1252
- test("trustFolder: marks the repo root trusted in a temp config, keeps the rest, survives a bad file", () => {
1253
- const t = mkdtempSync(join(tmpdir(), "kz-trust-"));
1254
- const repo = join(t, "repo"), sub = join(repo, "sub"), plain = join(t, "plain");
1255
- mkdirSync(sub, { recursive: true }); mkdirSync(plain);
1256
- Bun.spawnSync(["git", "init", "-q", repo]);
1257
- const cfg = join(t, ".claude.json");
1258
- const key = (p: string) => process.platform === "win32" ? p.replace(/\\/g, "/") : p; // Claude Code's spelling
1259
- writeFileSync(cfg, JSON.stringify({ keep: 1, projects: { [key(plain)]: { x: 2 } } }));
1260
- trustFolder(sub, cfg);
1261
- trustFolder(plain, cfg);
1262
- const d = JSON.parse(readFileSync(cfg, "utf8"));
1263
- expect(d.keep).toBe(1);
1264
- expect(d.projects[key(realpathSync.native(repo))]).toEqual({ hasTrustDialogAccepted: true });
1265
- expect(d.projects[key(plain)]).toEqual({ x: 2, hasTrustDialogAccepted: true });
1266
- writeFileSync(cfg, "{bad");
1267
- trustFolder(plain, cfg);
1268
- expect(readFileSync(cfg, "utf8")).toBe("{bad");
1269
- rmSync(t, { recursive: true, force: true });
1270
- });
1271
-
1272
- test("moveTask carries notes and linked attachments, leaves the old inbox without it", () => {
1273
- const root = mkdtempSync(join(tmpdir(), "kaizen-mv-"));
1274
- const a = join(root, "a", ".kaizen"), b = join(root, "b", ".kaizen");
1275
- mkdirSync(join(a, "attachments"), { recursive: true });
1276
- writeFileSync(join(a, "attachments", "x-shot.png"), "png");
1277
- writeInbox(a, [{ status: "open", text: "keep" }, { status: "open", text: "go", notes: "see [shot](attachments/x-shot.png)" }]);
1278
- expect(moveTask(a, a, "go")).toBe("already in that project");
1279
- expect(moveTask(a, b, "nope")).toBe("no such task");
1280
- expect(moveTask(a, b, "go")).toBeNull();
1281
- expect(readInbox(a).map((l) => l.text)).toEqual(["keep"]);
1282
- expect(readInbox(b)).toMatchObject([{ status: "open", text: "go", notes: "see [shot](attachments/x-shot.png)" }]);
1283
- expect(readFileSync(join(b, "attachments", "x-shot.png"), "utf8")).toBe("png");
1284
- writeInbox(a, [{ status: "open", text: "go" }]);
1285
- expect(moveTask(a, b, "go")).toBe("that project already has this task");
1286
- rmSync(root, { recursive: true, force: true });
1287
- });
1288
-
1289
- test("newer: an update is offered only for a strictly later release", async () => {
1290
- const { newer } = await import("./web.ts");
1291
- expect(newer("1.31.0", "1.30.0")).toBe(true);
1292
- expect(newer("1.30.0", "1.4.0")).toBe(true);
1293
- expect(newer("1.30.0", "1.30.0")).toBe(false);
1294
- expect(newer("1.4.0", "1.30.0")).toBe(false);
1295
- expect(newer("2.0", "1.99.9")).toBe(true);
1296
- });
1297
-
1298
- // The real server in a scratch home. Only refusals: a same-origin POST would run a real upgrade.
1299
- test("the board refuses an upgrade from another origin", async () => {
1300
- const homeDir = mkdtempSync(join(tmpdir(), "kaizen-upd-"));
1301
- for (const d of [join(homeDir, ".kaizen"), join(homeDir, ".claude")]) mkdirSync(d, { recursive: true });
1302
- const port = 20000 + Math.floor(Math.random() * 20000), repo = join(import.meta.dir, "..");
1303
- const proc = Bun.spawn([process.execPath, join(repo, "cli", "install.ts"), "web", "--port", String(port), "--no-open", "--foreground"], {
1304
- cwd: homeDir, env: { ...process.env, HOME: homeDir, USERPROFILE: homeDir, KAIZEN_HOME: repo, KAIZEN_WEB_HOSTS: "" }, stdout: "ignore", stderr: "ignore",
1305
- });
1306
- try {
1307
- const at = `http://127.0.0.1:${port}`;
1308
- for (let i = 0; ; i++) { try { await fetch(at + "/state"); break; } catch { if (i > 100) throw new Error("board did not start"); await Bun.sleep(50); } }
1309
- expect((await (await fetch(at + "/settings")).json()).phoneUrls).toEqual([]);
1310
- const r = await fetch(at + "/upgrade", { method: "POST", headers: { origin: "https://evil.example" } });
1311
- expect(r.status).toBe(403);
1312
- } finally { proc.kill(); await proc.exited; rmSync(homeDir, { recursive: true, force: true }); }
1313
- });
1314
-
1315
- // KAIZEN_WEB_HOSTS (tailscale serve): the listed host gets in, any other is still refused.
1316
- test("the board answers only the hosts listed in KAIZEN_WEB_HOSTS or web-hosts", async () => {
1317
- const homeDir = mkdtempSync(join(tmpdir(), "kaizen-hosts-"));
1318
- for (const d of [join(homeDir, ".kaizen"), join(homeDir, ".claude")]) mkdirSync(d, { recursive: true });
1319
- const port = 20000 + Math.floor(Math.random() * 20000), repo = join(import.meta.dir, "..");
1320
- const proc = Bun.spawn([process.execPath, join(repo, "cli", "install.ts"), "web", "--port", String(port), "--no-open", "--foreground"], {
1321
- cwd: homeDir, env: { ...process.env, HOME: homeDir, USERPROFILE: homeDir, KAIZEN_HOME: repo, KAIZEN_WEB_HOSTS: " PC.tail1234.ts.net:443 , bad@pc.tail1234.ts.net " }, stdout: "ignore", stderr: "ignore",
1322
- });
1323
- try {
1324
- const at = `http://127.0.0.1:${port}`;
1325
- for (let i = 0; ; i++) { try { await fetch(at + "/state"); break; } catch { if (i > 100) throw new Error("board did not start"); await Bun.sleep(50); } }
1326
- expect((await (await fetch(at + "/settings")).json()).phoneUrls).toEqual(["https://pc.tail1234.ts.net"]);
1327
- expect((await fetch(at + "/state", { headers: { host: "pc.tail1234.ts.net" } })).status).toBe(200);
1328
- expect((await fetch(at + "/state", { headers: { host: "evil.example" } })).status).toBe(403);
1329
- expect((await fetch(at + "/state", { headers: { host: "other.tail1234.ts.net" } })).status).toBe(403);
1330
- // ~/.kaizen/web-hosts (written by `kaizen setup`) is read per request: no restart.
1331
- writeFileSync(join(homeDir, ".kaizen", "web-hosts"), "# phone\nOther.tail1234.ts.net\n");
1332
- expect((await (await fetch(at + "/settings")).json()).phoneUrls).toEqual(["https://pc.tail1234.ts.net", "https://other.tail1234.ts.net"]);
1333
- expect((await fetch(at + "/state", { headers: { host: "other.tail1234.ts.net" } })).status).toBe(200);
1334
- expect((await fetch(at + "/state", { headers: { host: "evil.example" } })).status).toBe(403);
1335
- expect((await fetch(at + "/upgrade", { method: "POST", headers: { origin: "https://evil.example" } })).status).toBe(403);
1336
- const m = await fetch(at + "/manifest.webmanifest");
1337
- expect(m.status).toBe(200);
1338
- expect((await m.json()).display).toBe("standalone");
1339
- } finally { proc.kill(); await proc.exited; rmSync(homeDir, { recursive: true, force: true }); }
1340
- });
1341
-
1342
- test("requestTitle: drops the launch command, keeps the first sentence, caps at 90", () => {
1343
- expect(requestTitle("/kaizen lite simplify the card. Then more words")).toBe("simplify the card.");
1344
- expect(requestTitle("x".repeat(200)).length).toBe(90);
1345
- });
1346
-
1347
- test("requestTitle: a follow-up opened from an approval question titles from its work, not the question", () => {
1348
- const q = '# Request (verbatim)\n\nQuestion asked at the final approval of a: "Next run?"\nAnswer: "Plan 2b next"\n\nFollow-up of: a\n';
1349
- expect(requestTitle(q)).toBe("Plan 2b next");
1350
- expect(requestTitle(q + "Roadmap line: 2. Accounts & access — OTP\n")).toBe("Accounts & access — OTP");
1351
- });
1352
-
1353
- test("parent/child: a Parent line links a run and a task to the run that filed them", () => {
1354
- expect(parentOf("do x\nFollow-up of: 2026-01-01-a.")).toBe("2026-01-01-a");
1355
- expect(parentOf(" [2026-10-18 20:57] Parent: 2026-01-01-a")).toBe("2026-01-01-a");
1356
- expect(parentOf("no parent here")).toBeUndefined();
1357
- const st = join(mkdtempSync(join(tmpdir(), "kaizen-pc-")), ".kaizen");
1358
- for (const [id, req] of [["2026-01-01-a", "parent work"], ["2026-01-02-b", "child work\nParent: 2026-01-01-a"]]) {
1359
- mkdirSync(join(st, "runs", id), { recursive: true });
1360
- writeFileSync(join(st, "runs", id, "00-request.md"), req + "\n");
1361
- writeFileSync(join(st, "runs", id, "state.json"), JSON.stringify({ stage: "done", awaiting: null }));
1362
- }
1363
- writeFileSync(join(st, "inbox.md"), "# Inbox\n\n- open: follow-on task\n Parent: 2026-01-01-a\n");
1364
- const cards = boardCards([st], Date.now());
1365
- expect(cards.find((k) => k.id === "2026-01-01-a")!.children).toEqual(["2026-01-02-b"]);
1366
- expect(cards.find((k) => k.id === "2026-01-02-b")!.parent).toBe("2026-01-01-a");
1367
- expect(cards.find((k) => k.kind === "idea")!.parent).toBe("2026-01-01-a");
1368
- // The done child is noted in its parent once, however often the board refreshes.
1369
- boardCards([st], Date.now());
1370
- expect(readFileSync(join(st, "runs", "2026-01-01-a", "notes.md"), "utf8").match(/Child 2026-01-02-b done: child work/g)!.length).toBe(1);
1371
- // card add: no run in flight, so a parent must be named.
1372
- expect(addCard(st, "next thing")).toMatch(/no run in flight/);
1373
- writeFileSync(join(st, "runs", "2026-01-02-b", "state.json"), JSON.stringify({ stage: "build", awaiting: null }));
1374
- expect(addCard(st, "next thing")).toEqual({ parent: "2026-01-02-b" });
1375
- expect(addCard(st, "next thing")).toMatch(/already/);
1376
- expect(addCard(st, "other", "nope")).toMatch(/no such run/);
1377
- addCard(st, "titled", "2026-01-02-b", "the details\nline two");
1378
- expect(readInbox(st).find((l) => l.text === "titled")?.notes).toContain("Parent: 2026-01-02-b\nthe details");
1379
- expect(boardCards([st], Date.now()).find((k) => k.text === "next thing")!.parent).toBe("2026-01-02-b");
1380
- rmSync(dirname(st), { recursive: true, force: true });
1381
- });
1382
-
1383
- test("winShim swaps an npm .cmd shim for the .ps1 beside it, so a multi-line prompt survives", () => {
1384
- const { winShim } = stateModule;
1385
- const has = (p: string) => p === "C:\\npm\\claude.ps1";
1386
- expect(winShim("C:\\npm\\claude.cmd", has)).toBe("C:\\npm\\claude.ps1");
1387
- expect(winShim("C:\\npm\\codex.CMD", () => false)).toBe("C:\\npm\\codex.CMD");
1388
- expect(winShim("C:\\bin\\claude.exe", () => true)).toBe("C:\\bin\\claude.exe");
1389
- });
1390
-
1391
- test("final-approval gate: changed files need an accepted: line once approvals.review is on", async () => {
1392
- const { gateOf, acceptance, recordAcceptance, changedPaths } = stateModule;
1393
- const proj = mkdtempSync(join(tmpdir(), "kz-gate-")), st = join(proj, ".kaizen");
1394
- mkdirSync(join(proj, "cli"), { recursive: true });
1395
- writeFileSync(join(proj, "cli", "a.ts"), "");
1396
- const mk = (id: string, s: object, impl?: string, approval?: string) => {
1397
- const d = join(st, "runs", id);
1398
- mkdirSync(d, { recursive: true });
1399
- writeFileSync(join(d, "state.json"), JSON.stringify(s));
1400
- if (impl) writeFileSync(join(d, "03-impl.md"), impl);
1401
- if (approval) writeFileSync(join(d, "02-approval.md"), approval);
1402
- };
1403
- const impl = "## Changed\n- `cli/a.ts:12` — the fix\n- ran `bun test`, see `missing/file.ts`\n";
1404
- expect(changedPaths(impl, proj)).toEqual(["cli/a.ts"]); // only paths that exist; commands ignored
1405
- mkdirSync(st, { recursive: true });
1406
- writeFileSync(join(st, "config.yml"), "approvals:\n plan: true\n review: true\n");
1407
- mk("2026-10-28-old", { stage: "done" }, impl); // before the gate: never flagged
1408
- mk("2026-10-29-none", { stage: "done" }, "## Changed\nnothing\n"); // no files: free to finish
1409
- mk("2026-10-29-needs", { stage: "done" }, impl, "plan approved\naccepted: soon, the user said\n");
1410
- mk("2026-10-29-auto", { stage: "done" }, impl, "accepted: 2026-10-29T10:00:00Z auto (auto_accept)\n");
1411
- mk("2026-10-29-build", { stage: "build" }, impl);
1412
- expect(gateOf(st, "2026-10-28-old")).toBeNull();
1413
- expect(gateOf(st, "2026-10-29-none")).toBeNull();
1414
- expect(gateOf(st, "2026-10-29-build")).toBeNull();
1415
- expect(gateOf(st, "2026-10-29-needs")).toBe("needs"); // a prose line does not count
1416
- expect(gateOf(st, "2026-10-29-auto")).toBe("auto");
1417
- expect(boardCards([st], Date.now()).find((c) => c.id === "2026-10-29-needs")).toMatchObject({ status: "waiting", awaiting: "approvals.review" });
1418
- expect(notice({ kind: "run", text: "x", where: "p", status: "done", accept: "needs" } as Card)).toContain("done, not approved");
1419
- expect(recordAcceptance(st, "2026-10-29-needs", "board")).toBeNull();
1420
- expect(acceptance(st, "2026-10-29-needs")).toBe("user");
1421
- expect(recordAcceptance(st, "2026-10-29-needs", "chat")).toBe("That run is already approved.");
1422
- expect(gateOf(st, "2026-10-29-needs")).toBe("user");
1423
- // Hand-edited shapes still read as on: a column-0 comment, CRLF, quotes, a trailing comment.
1424
- mk("2026-10-29-shapes", { stage: "done" }, impl);
1425
- writeFileSync(join(st, "config.yml"), 'approvals: # stops\r\n# the final one\r\n plan: true\r\n\r\n review: "true" # yes\r\n');
1426
- expect(gateOf(st, "2026-10-29-shapes")).toBe("needs");
1427
- writeFileSync(join(st, "config.yml"), "approvals: {plan: true, review: false}\n");
1428
- expect(gateOf(st, "2026-10-29-shapes")).toBeNull();
1429
- // A file only mentioned outside the change list does not count; a name with spaces does.
1430
- mkdirSync(join(proj, "notes"), { recursive: true });
1431
- writeFileSync(join(proj, "notes", "Release and testing.md"), "");
1432
- expect(changedPaths("## Changed\n- `notes/Release and testing.md`\n\n## Verification\nread `cli/a.ts`\n", proj)).toEqual(["notes/Release and testing.md"]);
1433
- // The user's pick: with approvals.review off, nothing is gated.
1434
- mk("2026-10-29-off", { stage: "done" }, impl);
1435
- writeFileSync(join(st, "config.yml"), "approvals:\n review: false\n");
1436
- expect(gateOf(st, "2026-10-29-off")).toBeNull();
1437
- writeFileSync(join(st, "config.yml"), "approvals:\n review: true\n");
1438
- expect(await commitPush(st, "2026-10-29-off", "fix: x", [])).toMatchObject({ ok: false });
1439
- });
1440
-
1441
- test("gate: a run marked done without acceptance reads, heals and finishes as review", () => {
1442
- const { readRuns, healRuns, finishRun, gateOf } = stateModule;
1443
- const proj = mkdtempSync(join(tmpdir(), "kz-heal-")), st = join(proj, ".kaizen");
1444
- mkdirSync(join(proj, "cli"), { recursive: true });
1445
- writeFileSync(join(proj, "cli", "a.ts"), "");
1446
- const impl = "## Changed\n- `cli/a.ts`\n";
1447
- const mk = (id: string, approval?: string, i = impl) => {
1448
- const d = join(st, "runs", id);
1449
- mkdirSync(d, { recursive: true });
1450
- writeFileSync(join(d, "state.json"), JSON.stringify({ stage: "done" }));
1451
- writeFileSync(join(d, "03-impl.md"), i);
1452
- if (approval) writeFileSync(join(d, "02-approval.md"), approval);
1453
- };
1454
- const stageOf = (id: string) => JSON.parse(readFileSync(join(st, "runs", id, "state.json"), "utf8"));
1455
- mkdirSync(st, { recursive: true });
1456
- writeFileSync(join(st, "config.yml"), "approvals:\n review: true\n");
1457
- mk("2026-10-29-needs"); mk("2026-10-29-ok", "accepted: 2026-10-29T10:00:00Z by user via board\n");
1458
- mk("2026-10-29-none", undefined, "nothing\n"); mk("2026-10-28-old");
1459
- const row = (id: string) => readRuns(st).find((r) => r.id === id)!;
1460
- expect(row("2026-10-29-needs")).toMatchObject({ stage: "review", awaiting: "approvals.review" });
1461
- for (const id of ["2026-10-29-ok", "2026-10-29-none", "2026-10-28-old"]) expect(row(id).stage).toBe("done");
1462
- expect(stageOf("2026-10-29-needs").stage).toBe("done"); // reads stay pure
1463
- expect(healRuns(st)).toEqual(["2026-10-29-needs"]);
1464
- expect(stageOf("2026-10-29-needs")).toMatchObject({ stage: "review", awaiting: "approvals.review" });
1465
- expect(healRuns(st)).toEqual([]); // idempotent
1466
- expect(stageOf("2026-10-29-needs").healed).toBe(true);
1467
- expect(row("2026-10-29-needs").healed).toBe(true);
1468
- expect(gateOf(st, "2026-10-29-needs")).toBe("needs");
1469
- expect(finishRun(st, "2026-10-29-needs")).toContain("--user-approved");
1470
- expect(stageOf("2026-10-29-needs").stage).toBe("review");
1471
- expect(finishRun(st, "2026-10-29-needs", true)).toBeNull();
1472
- expect(readFileSync(join(st, "runs", "2026-10-29-needs", "02-approval.md"), "utf8")).toContain("by user via chat");
1473
- expect(stageOf("2026-10-29-needs")).toMatchObject({ stage: "done", awaiting: null });
1474
- expect(stageOf("2026-10-29-needs").healed).toBeUndefined();
1475
- expect(row("2026-10-29-needs").stage).toBe("done");
1476
- expect(finishRun(st, "2026-10-29-none")).toBeNull(); // nothing changed: free to finish
1477
- // Gate off: a done run stays done.
1478
- writeFileSync(join(st, "config.yml"), "approvals:\n review: false\n");
1479
- mk("2026-10-29-off");
1480
- expect(row("2026-10-29-off").stage).toBe("done");
1481
- rmSync(proj, { recursive: true, force: true });
1482
- });
1483
-
1484
- test("stageFiles, commitStaged, suggestMessage: only the run's files are staged, discarded or committed, and nothing is pushed", async () => {
1485
- const root = mkdtempSync(join(tmpdir(), "kz-stage-"));
1486
- const sh = (cwd: string, ...a: string[]) => Bun.spawnSync(["git", "-C", cwd, ...a]).stdout.toString().trim();
1487
- const bare = join(root, "remote.git"), proj = join(root, "proj"), st = join(proj, ".kaizen");
1488
- mkdirSync(join(st, "runs", "r1"), { recursive: true });
1489
- Bun.spawnSync(["git", "init", "-q", "--bare", bare]);
1490
- Bun.spawnSync(["git", "init", "-q", proj]);
1491
- for (const kv of [["user.name", "t"], ["user.email", "t@t"], ["commit.gpgsign", "false"], ["core.hooksPath", "/dev/null"]]) sh(proj, "config", ...kv);
1492
- sh(proj, "remote", "add", "origin", bare);
1493
- writeFileSync(join(proj, ".gitignore"), ".kaizen/\n");
1494
- writeFileSync(join(proj, "a.txt"), "one\ntwo\n");
1495
- writeFileSync(join(proj, "other.txt"), "o\n");
1496
- sh(proj, "add", ".");
1497
- Bun.spawnSync(["git", "-C", proj, "commit", "-qm", "init"], { env: { ...process.env, GIT_COMMITTER_DATE: "2000-01-01T00:00:00Z", GIT_AUTHOR_DATE: "2000-01-01T00:00:00Z" } });
1498
- writeFileSync(join(proj, "a.txt"), "one\nTWO\nthree\n");
1499
- writeFileSync(join(proj, "new.txt"), "n\n");
1500
- writeFileSync(join(proj, "other.txt"), "changed\n");
1501
- writeFileSync(join(st, "runs", "r1", "03-impl.md"), "- `a.txt`\n- `new.txt`\n");
1502
- // Reported a minute ago: after the init commit, before the run's own commit below
1503
- // (a commit in the report's own second keeps the file offered).
1504
- utimesSync(join(st, "runs", "r1", "03-impl.md"), new Date(Date.now() - 60000), new Date(Date.now() - 60000));
1505
- const g = () => runGit(st, "r1") as any;
1506
- expect(g().rows).toEqual([
1507
- { path: "a.txt", staged: false, code: "M", add: 2, del: 1 },
1508
- { path: "new.txt", staged: false, code: "U", add: 1, del: 0 },
1509
- ]);
1510
- expect(g().log).toEqual([{ sha: expect.any(String), subject: "init", refs: expect.stringContaining("HEAD"), unpushed: true }]);
1511
- // Another run's file is refused whole, and nothing is staged.
1512
- expect(stageFiles(st, "r1", "stage", ["a.txt", "other.txt"])).toBe("Not this run's: other.txt");
1513
- expect(g().staged).toEqual([]);
1514
- expect(stageFiles(st, "r1", "stage", ["a.txt"])).toBeNull();
1515
- expect(g().staged).toEqual(["a.txt"]);
1516
- expect(g().rows[0]).toEqual({ path: "a.txt", staged: true, code: "M", add: 2, del: 1 });
1517
- expect(stageFiles(st, "r1", "unstage", ["a.txt"])).toBeNull();
1518
- expect(g().staged).toEqual([]);
1519
- // Discard: an untracked file is deleted, a tracked one goes back to the index.
1520
- expect(stageFiles(st, "r1", "discard", ["new.txt"])).toBeNull();
1521
- expect(existsSync(join(proj, "new.txt"))).toBe(false);
1522
- expect(stageFiles(st, "r1", "discard", ["a.txt"])).toBeNull();
1523
- expect(readFileSync(join(proj, "a.txt"), "utf8").replace(/\r/g, "")).toBe("one\ntwo\n"); // git may check out CRLF on Windows
1524
- expect(readFileSync(join(proj, "other.txt"), "utf8")).toBe("changed\n"); // not the run's, untouched
1525
- writeFileSync(join(proj, "a.txt"), "one\nTWO\nthree\n");
1526
- // Plain Commit: nothing staged, a stale list, another file staged by hand, all refused.
1527
- expect(commitStaged(st, "r1", "fix: x", [])).toEqual({ ok: false, why: "Nothing is staged." });
1528
- stageFiles(st, "r1", "stage", ["a.txt"]);
1529
- expect(commitStaged(st, "r1", "fix: x", [])).toMatchObject({ ok: false });
1530
- sh(proj, "add", "other.txt");
1531
- expect((commitStaged(st, "r1", "fix: x", ["a.txt"]) as any).why).toContain("Other files are staged too: other.txt");
1532
- sh(proj, "reset", "-q", "--", "other.txt");
1533
- expect((commitStaged(st, "r1", "no type", ["a.txt"]) as any).why).toContain("Start the message with a type");
1534
- // The sparkle: with no claude on PATH the message is built from the file names, and it passes the type check.
1535
- const path = 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(";") : "";
1538
- try {
1539
- const m = await suggestMessage(st, "r1");
1540
- expect(m).toEqual({ ok: true, message: "chore: update a.txt", ai: false });
1541
- } finally { process.env.PATH = path; }
1542
- const r = commitStaged(st, "r1", "fix: a", ["a.txt"]) as { ok: true; sha: string };
1543
- expect(r.ok).toBe(true);
1544
- expect(sh(proj, "show", "--name-only", "--format=%s", "HEAD")).toBe("fix: a\n\na.txt");
1545
- expect(sh(bare, "rev-list", "--all", "--count")).toBe("0"); // not pushed
1546
- expect(readCommit(st, "r1")).toEqual({ sha: r.sha, pushed: false });
1547
- // Edits made after the run's commit are not the run's: discarding them is refused.
1548
- writeFileSync(join(proj, "a.txt"), "junk\n");
1549
- expect(stageFiles(st, "r1", "discard", ["a.txt"])).toBe("Not this run's: a.txt");
1550
- expect(readFileSync(join(proj, "a.txt"), "utf8")).toBe("junk\n");
1551
- rmSync(root, { recursive: true, force: true });
1552
- }, 30_000); // real git, many calls: Windows CI takes 6-8 s, and a timed-out test has its children killed
1553
-
1554
- test("runGit: a run owns the files its report lists as changed, not ones it only mentions", () => {
1555
- const proj = mkdtempSync(join(tmpdir(), "kaizen-own-")), st = join(proj, ".kaizen"), g = (...a: string[]) => Bun.spawnSync(["git", "-C", proj, ...a]);
1556
- g("init", "-q"); g("config", "user.email", "t@t"); g("config", "user.name", "t"); g("remote", "add", "origin", "https://example.invalid/r.git");
1557
- for (const f of ["listed.txt", "mentioned.txt", "fixed.txt", "whole.txt", "script.txt", "kept.txt"]) writeFileSync(join(proj, f), "1\n");
1558
- g("add", "."); g("commit", "-qm", "base", "--date=2000-01-01T00:00:00");
1559
- Bun.spawnSync(["git", "-C", proj, "commit", "-q", "--amend", "--no-edit"], { env: { ...process.env, GIT_COMMITTER_DATE: "2000-01-01T00:00:00" } });
1560
- for (const f of ["listed.txt", "mentioned.txt", "fixed.txt", "whole.txt", "script.txt", "kept.txt"]) writeFileSync(join(proj, f), "2\n");
1561
- const a = join(st, "runs", "a"), b = join(st, "runs", "b");
1562
- mkdirSync(join(a, "05-iterations"), { recursive: true }); mkdirSync(b, { recursive: true });
1563
- writeFileSync(join(a, "state.json"), "{}"); writeFileSync(join(b, "state.json"), "{}");
1564
- writeFileSync(join(a, "03-impl.md"), "## Changed\n- `listed.txt`\n\n## Scripts\n- `script.txt`\n\n## Left unchanged\n`kept.txt`\n\n## Deviations\n`mentioned.txt` is another session's.\n");
1565
- writeFileSync(join(a, "05-iterations", "01-fix.md"), "# Fix\n- `fixed.txt`\n");
1566
- writeFileSync(join(b, "03-impl.md"), "No headings here: `whole.txt`\n");
1567
- const files = (id: string) => (runGit(st, id) as any).files.map((l: string) => l.slice(3));
1568
- expect(files("a")).toEqual(["fixed.txt", "listed.txt", "script.txt"]);
1569
- expect(files("b")).toEqual(["whole.txt"]);
1570
- rmSync(proj, { recursive: true, force: true });
1571
- });
1572
-
1573
- test("a committed run does not claim a file edited after its commit", () => {
1574
- const root = mkdtempSync(join(tmpdir(), "kz-seal-")), st = join(root, ".kaizen"), run = join(st, "runs", "r1");
1575
- mkdirSync(run, { recursive: true });
1576
- const ago = (s: number) => Math.floor(Date.now() / 1000) - s;
1577
- const sh = (at: number, ...a: string[]) => Bun.spawnSync(["git", "-c", "user.name=t", "-c", "user.email=t@t", ...a], { cwd: root, env: { ...process.env, GIT_AUTHOR_DATE: `${at} +0000`, GIT_COMMITTER_DATE: `${at} +0000` } }).stdout.toString().trim();
1578
- sh(ago(300), "init", "-q"); sh(ago(300), "remote", "add", "origin", "https://example.com/x.git");
1579
- writeFileSync(join(root, "a.txt"), "1"); sh(ago(300), "add", "a.txt"); sh(ago(300), "commit", "-qm", "init");
1580
- writeFileSync(join(run, "03-impl.md"), "## Changed\n- `a.txt`: edit\n");
1581
- utimesSync(join(run, "03-impl.md"), ago(200), ago(200));
1582
- writeFileSync(join(root, "b.txt"), "1"); sh(ago(100), "add", "b.txt"); sh(ago(100), "commit", "-qm", "the run");
1583
- writeFileSync(join(root, "a.txt"), "2");
1584
- const before: Record<string, string> = {}, after: Record<string, string> = {};
1585
- cardsGit(st, ["r1"], before as any);
1586
- expect(before.r1).toBe("commit"); // no commit recorded: still the run's
1587
- writeFileSync(join(run, "07-commit.md"), `commit: ${sh(ago(0), "rev-parse", "--short", "HEAD")}\npushed: no\n`);
1588
- cardsGit(st, ["r1"], after as any);
1589
- expect(after.r1).not.toBe("commit");
1590
- rmSync(root, { recursive: true, force: true });
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
- });
1610
-
1611
- test("a tool's Settings model reaches its launch flag, ahead of a hand-written block", () => {
1612
- expect(agentFlags("/x", "codex", 'agent:\n default: auto\n model:\n agy: ""\n codex: gpt-x\n')).toEqual(["-m", "gpt-x"]);
1613
- expect(agentFlags("/x", "agy", 'agent:\n model:\n agy: ""\n codex: gpt-x\n')).toEqual([]);
1614
- expect(agentFlags("/x", "codex", "agent:\n codex: { model: old, effort: low }\n model:\n codex: new\n")).toEqual(["-m", "new", "-c", "model_reasoning_effort=low"]);
1615
- expect(agentFlags("/x", "codex", "agent:\n codex: { model: old }\n")).toEqual(["-m", "old"]);
1616
- });
1617
-
1618
- test("pruneSessions drops only old records nothing can use, with their files", () => {
1619
- const st = join(mkdtempSync(join(tmpdir(), "kz-prunes-")), ".kaizen");
1620
- const now = Date.now(), old = now - 8 * 864e5, sessions = join(st, "sessions");
1621
- mkdirSync(sessions, { recursive: true });
1622
- const run = (id: string, state: string) => { mkdirSync(join(st, "runs", id), { recursive: true }); writeFileSync(join(st, "runs", id, "state.json"), state); };
1623
- run("gave-up", '{"stage":"abandoned"}'); run("finished", '{"stage":"done"}'); run("going", '{"stage":"build"}'); run("garbled", "{");
1624
- const rec = (key: string, r: string | null, started = old) => writeFileSync(join(sessions, key + ".json"), JSON.stringify({ run: r, text: key, cmd: "claude", sessionId: null, started }));
1625
- rec("abandoned", "gave-up"); rec("unowned", null); rec("missing", "pruned-away");
1626
- writeFileSync(join(sessions, "abandoned.run"), "gave-up");
1627
- rec("done", "finished"); rec("flight", "going"); rec("unreadable", "garbled"); rec("young", null, now - 6 * 864e5); rec("live", null);
1628
- writeFileSync(join(sessions, "live.pid"), String(process.pid));
1629
- const dead = ["abandoned", "missing", "unowned"];
1630
- // This test process stands in for the agent: its record names bun, or the PID reads as a stranger's.
1631
- writeFileSync(join(sessions, "live.json"), JSON.stringify({ run: null, text: "live", cmd: "bun", sessionId: null, started: old }));
1632
-
1633
- expect(pruneSessions(st, false, now).map((g) => g.key + ":" + g.reason).sort()).toEqual(["abandoned:abandoned", "missing:gone", "unowned:unowned"]);
1634
- expect(readdirSync(sessions)).toContain("abandoned.json");
1635
- expect(pruneSessions(st, true, now).map((g) => g.key).sort()).toEqual(dead);
1636
- expect(readdirSync(sessions).filter((f) => f.endsWith(".json")).sort()).toEqual(["done.json", "flight.json", "live.json", "unreadable.json", "young.json"]);
1637
- expect(readdirSync(sessions)).not.toContain("abandoned.run");
1638
- rmSync(dirname(st), { recursive: true, force: true });
1639
- });