kaizen-agent 1.60.1 → 1.61.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 (44) hide show
  1. package/cli/knowledge.ts +1 -1
  2. package/cli/notes.test.ts +2 -1
  3. package/cli/onboarding.test.ts +70 -0
  4. package/cli/onboarding.ts +63 -0
  5. package/cli/pty.test.ts +15 -1
  6. package/cli/pty.ts +14 -3
  7. package/cli/shell-agent.test.ts +23 -0
  8. package/cli/state.test.ts +105 -1
  9. package/cli/state.ts +157 -19
  10. package/cli/web-decide.test.ts +41 -0
  11. package/cli/web.ts +145 -27
  12. package/package.json +1 -1
  13. package/web/board/add-project.ts +14 -4
  14. package/web/board/api.ts +37 -4
  15. package/web/board/approvals.ts +6 -6
  16. package/web/board/badge.ts +6 -2
  17. package/web/board/cards.ts +4 -2
  18. package/web/board/fixes.ts +1 -1
  19. package/web/board/git.ts +171 -97
  20. package/web/board/live.ts +2 -1
  21. package/web/board/main.ts +2 -0
  22. package/web/board/onboarding.ts +223 -0
  23. package/web/board/panel.ts +24 -14
  24. package/web/board/run-view.ts +86 -7
  25. package/web/board/settings-pages.test.ts +19 -0
  26. package/web/board/settings-pages.ts +44 -0
  27. package/web/board/settings.ts +118 -62
  28. package/web/board/store.ts +4 -0
  29. package/web/board/update.ts +1 -1
  30. package/web/board/views.ts +5 -1
  31. package/web/board/workspace.ts +92 -3
  32. package/web/board/ws-name.test.ts +10 -0
  33. package/web/board/ws-tabs.test.ts +14 -1
  34. package/web/board/ws-tabs.ts +12 -1
  35. package/web/board.html +165 -21
  36. package/web/board.js +107 -104
  37. package/web/notebook.js +29 -24
  38. package/web/notebook.ts +1 -0
  39. package/web/notes.html +28 -10
  40. package/web/popup.html +2 -2
  41. package/web/term.js +20 -20
  42. package/web/term.ts +8 -3
  43. package/web/video.html +28 -10
  44. package/web/video.js +56 -51
package/cli/knowledge.ts CHANGED
@@ -45,7 +45,7 @@ export function secretReason(text: string): string {
45
45
  export function globalAllowed(projectDir: string): boolean {
46
46
  for (const f of [join(projectDir, ".kaizen", "config.yml"), join(homedir(), ".kaizen", "config.yml")]) {
47
47
  const t = read(f);
48
- const m = /^knowledge:\n(?:[ \t]+.*\n|[ \t]*#.*\n)*?[ \t]+global:[ \t]*["']?(\w+)/m.exec(t) || /^knowledge\.global:[ \t]*["']?(\w+)/m.exec(t);
48
+ const m = /^knowledge:\n(?:[ \t][^\n]*\n|[ \t]*#.*\n)*?[ \t]+global:[ \t]*["']?(\w+)/m.exec(t) || /^knowledge\.global:[ \t]*["']?(\w+)/m.exec(t);
49
49
  if (m) return m[1] !== "false";
50
50
  }
51
51
  return true;
package/cli/notes.test.ts CHANGED
@@ -204,10 +204,11 @@ test("the notebook's design tokens are the board's, line for line", () => {
204
204
  const block = (f: string) => {
205
205
  const s = readFileSync(join(root, "web", f), "utf8").split("\n");
206
206
  const at = s.findIndex((l) => l.startsWith(":root{--bg:"));
207
- return s.slice(at, at + 8).join("\n");
207
+ return s.slice(at, at + 11).join("\n");
208
208
  };
209
209
  expect(block("notes.html")).toBe(block("board.html"));
210
210
  expect(block("board.html")).toContain("data-theme=dark]{--shade");
211
+ expect(block("board.html")).toContain(":root[data-color=blue][data-theme=dark]{");
211
212
  const syms = (f: string) => readFileSync(join(root, "web", f), "utf8").split("\n").filter((l) => l.startsWith('<symbol id="s-')).join("\n");
212
213
  expect(syms("notes.html")).toBe(syms("board.html"));
213
214
  expect(syms("board.html").split("\n").length).toBe(7);
@@ -0,0 +1,70 @@
1
+ import { test, expect } from "bun:test";
2
+ import { mkdtempSync, readFileSync, writeFileSync, mkdirSync, realpathSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { tmpdir } from "node:os";
5
+ import { onboardingView, readOnboarding, writeOnboarding, installHelp, STEPS } from "./onboarding.ts";
6
+
7
+ const home = () => realpathSync(mkdtempSync(join(tmpdir(), "kz-onb-")));
8
+
9
+ test("a new user, with no project, is shown the flow", () => {
10
+ expect(onboardingView(home(), 0)).toEqual({ show: true, resume: false, step: 0, total: STEPS });
11
+ });
12
+
13
+ test("a board with any project never shows it, saved state or not", () => {
14
+ const h = home();
15
+ expect(onboardingView(h, 1)).toMatchObject({ show: false, resume: false });
16
+ writeOnboarding(h, { step: 1 });
17
+ expect(onboardingView(h, 2)).toMatchObject({ show: false, resume: false });
18
+ writeOnboarding(h, { outcome: "skipped" });
19
+ expect(onboardingView(h, 1)).toMatchObject({ show: false, resume: false });
20
+ });
21
+
22
+ test("skipped or left half done comes back as resume at the step reached; done and dismissed never do", () => {
23
+ const h = home();
24
+ writeOnboarding(h, { step: 2 });
25
+ expect(onboardingView(h, 0)).toMatchObject({ show: false, resume: true, step: 2 });
26
+ writeOnboarding(h, { outcome: "skipped" });
27
+ expect(onboardingView(h, 0)).toMatchObject({ resume: true, step: 2 });
28
+ writeOnboarding(h, { outcome: "dismissed" });
29
+ expect(onboardingView(h, 0)).toMatchObject({ show: false, resume: false });
30
+ writeOnboarding(h, { outcome: "done" });
31
+ expect(onboardingView(h, 0)).toMatchObject({ show: false, resume: false });
32
+ });
33
+
34
+ test("a flow opened but not advanced shows again rather than resuming", () => {
35
+ const h = home();
36
+ writeOnboarding(h, { step: 0 });
37
+ expect(onboardingView(h, 0)).toMatchObject({ show: true, resume: false });
38
+ });
39
+
40
+ test("writes merge, persist in the board's own file, and refuse anything else", () => {
41
+ const h = home();
42
+ expect(writeOnboarding(h, { step: 1 })).toEqual({ step: 1, outcome: null });
43
+ expect(writeOnboarding(h, { outcome: "skipped" })).toEqual({ step: 1, outcome: "skipped" });
44
+ expect(JSON.parse(readFileSync(join(h, ".kaizen", "onboarding.json"), "utf8"))).toEqual({ step: 1, outcome: "skipped" });
45
+ for (const bad of [{ step: -1 }, { step: STEPS }, { step: 1.5 }, { step: "1" }, { outcome: "finished" }, { outcome: 1 }])
46
+ expect(writeOnboarding(h, bad)).toEqual({ error: expect.any(String) });
47
+ expect(readOnboarding(h)).toEqual({ step: 1, outcome: "skipped" });
48
+ });
49
+
50
+ test("a corrupt file reads as never started, and the next write replaces it", () => {
51
+ const h = home();
52
+ mkdirSync(join(h, ".kaizen"));
53
+ writeFileSync(join(h, ".kaizen", "onboarding.json"), "{nope");
54
+ expect(readOnboarding(h)).toBeNull();
55
+ expect(onboardingView(h, 0)).toMatchObject({ show: true });
56
+ expect(writeOnboarding(h, { step: 1 })).toEqual({ step: 1, outcome: null });
57
+ });
58
+
59
+ test("installHelp covers every agent the step offers, with the same commands and pages as the installer", () => {
60
+ const src = readFileSync(join(import.meta.dir, "install.ts"), "utf8");
61
+ for (const win of [false, true]) {
62
+ const h = installHelp(win);
63
+ expect(Object.keys(h).sort()).toEqual(["agy", "claude", "codex", "gemini", "opencode"]);
64
+ for (const [cmd, x] of Object.entries(h)) {
65
+ expect(src).toContain(x.docs);
66
+ if (x.command) expect(src).toContain(x.command);
67
+ else expect(cmd).toBe("agy"); // only Antigravity has no command
68
+ }
69
+ }
70
+ });
@@ -0,0 +1,63 @@
1
+ // The board's first-run onboarding: where a user got to is kept in ~/.kaizen/onboarding.json, on the
2
+ // machine that runs the board, so a phone, a second browser and a fresh HOME each see the right thing.
3
+ // Pure and sync: web.ts adds the routes, the page draws it.
4
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
5
+ import { join } from "node:path";
6
+
7
+ export const STEPS = 3; // default agent, appearance, notifications; adding a project is the last button, not a step
8
+ export type Outcome = "done" | "skipped" | "dismissed" | null;
9
+ export type Saved = { step: number; outcome: Outcome };
10
+
11
+ const file = (home: string) => join(home, ".kaizen", "onboarding.json");
12
+ const OUTCOMES = ["done", "skipped", "dismissed", null];
13
+
14
+ export function readOnboarding(home: string): Saved | null {
15
+ try {
16
+ const d = JSON.parse(readFileSync(file(home), "utf8"));
17
+ const step = Number.isInteger(d?.step) ? Math.max(0, Math.min(STEPS - 1, d.step)) : 0;
18
+ return { step, outcome: OUTCOMES.includes(d?.outcome) ? d.outcome : null };
19
+ } catch {
20
+ return null;
21
+ }
22
+ }
23
+
24
+ // What the page does: `show` opens the flow now, `resume` offers to continue it. A board that already
25
+ // has a project is a board someone set up, so it never shows; nor does a finished or dismissed one.
26
+ export function onboardingView(home: string, projects: number) {
27
+ const s = readOnboarding(home);
28
+ const none = { show: false, resume: false, step: 0, total: STEPS };
29
+ if (s?.outcome === "done" || s?.outcome === "dismissed") return none;
30
+ if (projects > 0) return none;
31
+ if (!s) return { ...none, show: true };
32
+ if (s.outcome === "skipped" || s.step > 0) return { ...none, resume: true, step: s.step };
33
+ return { ...none, show: true };
34
+ }
35
+
36
+ // A page's progress: a step reached, an outcome, or both. Anything else is refused, never stored.
37
+ export function writeOnboarding(home: string, body: unknown): Saved | { error: string } {
38
+ const b = (body && typeof body === "object" ? body : {}) as Record<string, unknown>;
39
+ const cur = readOnboarding(home) ?? { step: 0, outcome: null };
40
+ if ("step" in b && !(Number.isInteger(b.step) && (b.step as number) >= 0 && (b.step as number) < STEPS)) return { error: "bad step" };
41
+ if ("outcome" in b && !OUTCOMES.includes(b.outcome as Outcome)) return { error: "bad outcome" };
42
+ const next: Saved = { step: "step" in b ? (b.step as number) : cur.step, outcome: "outcome" in b ? (b.outcome as Outcome) : cur.outcome };
43
+ const dir = join(home, ".kaizen");
44
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
45
+ const tmp = file(home) + ".tmp";
46
+ writeFileSync(tmp, JSON.stringify(next) + "\n");
47
+ renameSync(tmp, file(home));
48
+ return next;
49
+ }
50
+
51
+ // How to install each agent the board can set as its default, for the step that finds none on PATH.
52
+ // ponytail: the commands repeat the AGENTS table in install.ts (importing that file runs the installer);
53
+ // onboarding.test.ts fails when they drift. Antigravity and Cursor have a download page, not a command.
54
+ export function installHelp(win: boolean): Record<string, { command?: string; docs: string }> {
55
+ const npm = (pkg: string) => `npm install -g ${pkg}`;
56
+ return {
57
+ claude: { command: win ? "irm https://claude.ai/install.ps1 | iex" : "curl -fsSL https://claude.ai/install.sh | bash", docs: "https://docs.claude.com/en/docs/claude-code" },
58
+ codex: { command: npm("@openai/codex"), docs: "https://github.com/openai/codex" },
59
+ agy: { docs: "https://antigravity.google" },
60
+ opencode: { command: win ? npm("opencode-ai") : "curl -fsSL https://opencode.ai/install | bash", docs: "https://opencode.ai" },
61
+ gemini: { command: npm("@google/gemini-cli"), docs: "https://github.com/google-gemini/gemini-cli" },
62
+ };
63
+ }
package/cli/pty.test.ts CHANGED
@@ -5,7 +5,7 @@ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, realpa
5
5
  import { tmpdir } from "node:os";
6
6
  import { join } from "node:path";
7
7
  import { launchMode, closeSessions, readSessions, sweepSessions } from "./state.ts";
8
- import { loginEnv, startPty, writePty, attachPty, ptyState, exitPty, lastLine } from "./pty.ts";
8
+ import { loginEnv, startPty, writePty, submitPty, attachPty, ptyState, exitPty, lastLine } from "./pty.ts";
9
9
  import { conptyHost, innerCommand, resizeSeq } from "./conpty.ts";
10
10
 
11
11
  const root = realpathSync(mkdtempSync(join(tmpdir(), "kaizen-pty-")));
@@ -232,6 +232,20 @@ test.skipIf(process.platform !== "win32")("on Windows a card agent runs in a pse
232
232
  expect(ptyState(key)?.alive).toBe(false);
233
233
  }, 60_000);
234
234
 
235
+ test.skipIf(process.platform === "win32")("submit: Enter reaches the agent on its own, not in the text's burst", async () => {
236
+ const key = "submit-" + Date.now(), log = join(root, "chunks-" + key), script = join(root, "chunks.js");
237
+ writeFileSync(script, `process.stdin.setRawMode(true); process.stdin.on("data", (d) => require("fs").appendFileSync(${JSON.stringify(log)}, JSON.stringify(d.toString()) + "\\n")); console.log("ready");`);
238
+ const out: string[] = [];
239
+ startPty(key, [process.execPath, script], root);
240
+ attachPty(key, (d) => { if (d) out.push(d); });
241
+ for (let i = 0; i < 100 && !out.join("").includes("ready"); i++) await Bun.sleep(50);
242
+ submitPty(key, "hello", 100);
243
+ let chunks = "";
244
+ for (let i = 0; i < 40 && !chunks.includes("\\r"); i++) { await Bun.sleep(50); try { chunks = readFileSync(log, "utf8"); } catch { /* not yet */ } }
245
+ expect(chunks.trim().split("\n").map((l) => JSON.parse(l))).toEqual(["hello", "\r"]);
246
+ exitPty(key, 100);
247
+ });
248
+
235
249
  test("busy: on while the agent draws its working line, off once it goes quiet; other output is not work", async () => {
236
250
  const key = "busy-" + Date.now();
237
251
  startPty(key, ["sh", "-c", "for i in 1 2 3 4 5 6; do echo 'Thinking (3s · esc to interrupt)'; sleep 0.1; done; read l"], root);
package/cli/pty.ts CHANGED
@@ -21,6 +21,9 @@ const KEEP_MS = 10 * 60_000;
21
21
 
22
22
  const ptys = new Map<string, Pty>();
23
23
 
24
+ // A board started from a colourless place (an agent's shell, CI) carries NO_COLOR; its terminals show colour anyway.
25
+ export const colorEnv = (env: Record<string, string | undefined> = process.env) => { const { NO_COLOR: _, ...rest } = env; return rest; };
26
+
24
27
  // What the sidebar shows for an agent: the latest line the agent printed. Keystrokes are never kept,
25
28
  // and nothing is read while a question is open or within ECHO_MS of a keystroke: a terminal echoes
26
29
  // what is typed, so that line could be a password. Memory only.
@@ -115,14 +118,14 @@ export function startPty(key: string, cmd: string[], cwd: string, pidFile?: stri
115
118
  grab(p, tail, 0);
116
119
  // Only what came after the user's last keystroke: a question already answered may still be in the tail.
117
120
  const n = Math.min(4096, p.total - p.since);
118
- flag(p.exit === null && n > 0 && asking(p.out.join("").slice(-n)));
121
+ flag(p.exit === null && n > 0 && asking(tail.slice(-n)));
119
122
  }, QUIET_MS);
120
123
  };
121
124
  if (WIN) {
122
125
  const ps = winPs();
123
126
  p.proc = Bun.spawn([ps, "-NoProfile", "-NonInteractive", "-EncodedCommand", conptyHost()], {
124
127
  cwd,
125
- env: { ...process.env, KZ_PTY_CMD: innerCommand(ps, cmd), KZ_PTY_CWD: cwd, KZ_PTY_COLS: "120", KZ_PTY_ROWS: "32" },
128
+ env: { ...colorEnv(), KZ_PTY_CMD: innerCommand(ps, cmd), KZ_PTY_CWD: cwd, KZ_PTY_COLS: "120", KZ_PTY_ROWS: "32" },
126
129
  stdin: "pipe", stdout: "pipe", stderr: "pipe", windowsHide: true,
127
130
  });
128
131
  const read = async (s: ReadableStream<Uint8Array>) => {
@@ -134,7 +137,7 @@ export function startPty(key: string, cmd: string[], cwd: string, pidFile?: stri
134
137
  read(p.proc.stderr as ReadableStream<Uint8Array>).catch(() => {});
135
138
  } else p.proc = Bun.spawn(cmd, {
136
139
  cwd,
137
- env: { ...process.env, TERM: "xterm-256color", COLORTERM: "truecolor" },
140
+ env: { ...colorEnv(), TERM: "xterm-256color", COLORTERM: "truecolor" },
138
141
  terminal: { cols: 120, rows: 32, data: (_t, d) => push(dec.decode(d, { stream: true })) },
139
142
  });
140
143
  if (opts.tmux && cmd[0] === tmuxBin()) p.tmux = opts.tmux;
@@ -199,6 +202,14 @@ export function writePty(key: string, d: string) {
199
202
  send(p, d);
200
203
  }
201
204
 
205
+ // Text and Enter sent as one burst read as a paste to Claude Code and other TUIs: the Enter
206
+ // lands in the input as a newline and nothing submits. Enter follows on its own, after the
207
+ // paste window has closed.
208
+ export function submitPty(key: string, text: string, gap = 300) {
209
+ writePty(key, text);
210
+ setTimeout(() => writePty(key, "\r"), gap);
211
+ }
212
+
202
213
  const send = (p: Pty, d: string) => {
203
214
  if (!WIN) return p.proc.terminal?.write(d);
204
215
  try { (p.proc.stdin as Bun.FileSink).write(d); (p.proc.stdin as Bun.FileSink).flush(); } catch { /* host gone */ }
@@ -0,0 +1,23 @@
1
+ import { expect, test } from "bun:test";
2
+ import { shellAgent } from "./web.ts";
3
+ import { colorEnv } from "./pty.ts";
4
+
5
+ const procs = (m: Record<string, string>) => (path: string) => {
6
+ if (path in m) return m[path];
7
+ throw new Error("gone");
8
+ };
9
+
10
+ test("finds an agent below the shell, through a wrapper script", () => {
11
+ const read = procs({ "/proc/1/task/1/children": "2 ", "/proc/2/cmdline": "/bin/bash\0/home/u/.local/bin/claude\0--x\0", "/proc/2/task/2/children": "" });
12
+ expect(shellAgent(1, ["claude", "codex"], read)).toBe("claude");
13
+ });
14
+
15
+ test("a shell running something else, or already gone, has no agent", () => {
16
+ const read = procs({ "/proc/1/task/1/children": "2", "/proc/2/cmdline": "vim\0claude.md\0", "/proc/2/task/2/children": "" });
17
+ expect(shellAgent(1, ["claude"], read)).toBeUndefined();
18
+ expect(shellAgent(9, ["claude"], read)).toBeUndefined();
19
+ });
20
+
21
+ test("board terminals drop an inherited NO_COLOR", () => {
22
+ expect(colorEnv({ NO_COLOR: "1", PATH: "/bin" })).toEqual({ PATH: "/bin" });
23
+ });
package/cli/state.test.ts CHANGED
@@ -10,7 +10,7 @@ import {
10
10
  readRuns, readInbox, writeInbox, replaceIdea, moveIdea, abandonRun, runToIdea, allBacklog, backlog,
11
11
  requestTitle, statusOf, columnOf, parseItem, startedRuns, boardCards, parentOf, addCard, readArchive, setArchived,
12
12
  requestOf, agentFlags, plainModel, readNotes, writeNotes, manualCommand, parseNotes, formatNote, appendNote, saveAttachment,
13
- reviewFindings, pickFindings, fixPrompt, approvalPrompt, sessionLaunch, closeSessions, sweepSessions, readSessions, ownerOf, gitStatus, runGit, cardsGit, commitPush, readCommit, findTerminal, nativePath, pruneRuns, unrechecked, notice, notifier, notifyArgs, winToastArgs, LOGO, type Card,
13
+ reviewFindings, pickFindings, fixPrompt, approvalPrompt, sessionLaunch, closeSessions, sweepSessions, readSessions, ownerOf, gitStatus, runGit, cardsGit, commitPush, commitStaged, stageFiles, suggestMessage, readCommit, findTerminal, nativePath, pruneRuns, unrechecked, notice, notifier, notifyArgs, winToastArgs, LOGO, type Card,
14
14
  } from "./state.ts";
15
15
 
16
16
  let state: string;
@@ -396,6 +396,15 @@ test("notes log: append to a run and to an idea; attachments saved and made abso
396
396
  expect(saveAttachment(state, "2026-09-01-waiting", "b.txt", new Uint8Array([2]))).toMatch(/^runs\/2026-09-01-waiting\/attachments\//);
397
397
  });
398
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
+
399
408
  test("agentFlags: per-tool model and effort from the agent block, inline or nested", () => {
400
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`;
401
410
  expect(agentFlags("/p", "codex", cfg)).toEqual(["-m", "gpt-5", "-c", "model_reasoning_effort=low"]);
@@ -549,6 +558,13 @@ test("commitPush: commits the run's files only, pushes, and records it; the mess
549
558
  expect(Bun.spawnSync(["git", "-C", proj, "status", "--porcelain"]).stdout.toString()).toBe("A c.txt\n");
550
559
  expect(readCommit(st, "r1")).toEqual({ sha: r.sha, pushed: true });
551
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"));
552
568
 
553
569
  // Windows has no file named b*.txt, so the rest is for everywhere else.
554
570
  if (process.platform === "win32") return;
@@ -1441,3 +1457,91 @@ test("gate: a run marked done without acceptance reads, heals and finishes as re
1441
1457
  expect(row("2026-10-29-off").stage).toBe("done");
1442
1458
  rmSync(proj, { recursive: true, force: true });
1443
1459
  });
1460
+
1461
+ test("stageFiles, commitStaged, suggestMessage: only the run's files are staged, discarded or committed, and nothing is pushed", async () => {
1462
+ const root = mkdtempSync(join(tmpdir(), "kz-stage-"));
1463
+ const sh = (cwd: string, ...a: string[]) => Bun.spawnSync(["git", "-C", cwd, ...a]).stdout.toString().trim();
1464
+ const bare = join(root, "remote.git"), proj = join(root, "proj"), st = join(proj, ".kaizen");
1465
+ mkdirSync(join(st, "runs", "r1"), { recursive: true });
1466
+ Bun.spawnSync(["git", "init", "-q", "--bare", bare]);
1467
+ Bun.spawnSync(["git", "init", "-q", proj]);
1468
+ for (const kv of [["user.name", "t"], ["user.email", "t@t"], ["commit.gpgsign", "false"], ["core.hooksPath", "/dev/null"]]) sh(proj, "config", ...kv);
1469
+ sh(proj, "remote", "add", "origin", bare);
1470
+ writeFileSync(join(proj, ".gitignore"), ".kaizen/\n");
1471
+ writeFileSync(join(proj, "a.txt"), "one\ntwo\n");
1472
+ writeFileSync(join(proj, "other.txt"), "o\n");
1473
+ sh(proj, "add", ".");
1474
+ 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" } });
1475
+ writeFileSync(join(proj, "a.txt"), "one\nTWO\nthree\n");
1476
+ writeFileSync(join(proj, "new.txt"), "n\n");
1477
+ writeFileSync(join(proj, "other.txt"), "changed\n");
1478
+ writeFileSync(join(st, "runs", "r1", "03-impl.md"), "- `a.txt`\n- `new.txt`\n");
1479
+ // Reported a minute ago: after the init commit, before the run's own commit below
1480
+ // (a commit in the report's own second keeps the file offered).
1481
+ utimesSync(join(st, "runs", "r1", "03-impl.md"), new Date(Date.now() - 60000), new Date(Date.now() - 60000));
1482
+ const g = () => runGit(st, "r1") as any;
1483
+ expect(g().rows).toEqual([
1484
+ { path: "a.txt", staged: false, code: "M", add: 2, del: 1 },
1485
+ { path: "new.txt", staged: false, code: "U", add: 1, del: 0 },
1486
+ ]);
1487
+ expect(g().log).toEqual([{ sha: expect.any(String), subject: "init", refs: expect.stringContaining("HEAD"), unpushed: true }]);
1488
+ // Another run's file is refused whole, and nothing is staged.
1489
+ expect(stageFiles(st, "r1", "stage", ["a.txt", "other.txt"])).toBe("Not this run's: other.txt");
1490
+ expect(g().staged).toEqual([]);
1491
+ expect(stageFiles(st, "r1", "stage", ["a.txt"])).toBeNull();
1492
+ expect(g().staged).toEqual(["a.txt"]);
1493
+ expect(g().rows[0]).toEqual({ path: "a.txt", staged: true, code: "M", add: 2, del: 1 });
1494
+ expect(stageFiles(st, "r1", "unstage", ["a.txt"])).toBeNull();
1495
+ expect(g().staged).toEqual([]);
1496
+ // Discard: an untracked file is deleted, a tracked one goes back to the index.
1497
+ expect(stageFiles(st, "r1", "discard", ["new.txt"])).toBeNull();
1498
+ expect(existsSync(join(proj, "new.txt"))).toBe(false);
1499
+ expect(stageFiles(st, "r1", "discard", ["a.txt"])).toBeNull();
1500
+ expect(readFileSync(join(proj, "a.txt"), "utf8")).toBe("one\ntwo\n");
1501
+ expect(readFileSync(join(proj, "other.txt"), "utf8")).toBe("changed\n"); // not the run's, untouched
1502
+ writeFileSync(join(proj, "a.txt"), "one\nTWO\nthree\n");
1503
+ // Plain Commit: nothing staged, a stale list, another file staged by hand, all refused.
1504
+ expect(commitStaged(st, "r1", "fix: x", [])).toEqual({ ok: false, why: "Nothing is staged." });
1505
+ stageFiles(st, "r1", "stage", ["a.txt"]);
1506
+ expect(commitStaged(st, "r1", "fix: x", [])).toMatchObject({ ok: false });
1507
+ sh(proj, "add", "other.txt");
1508
+ expect((commitStaged(st, "r1", "fix: x", ["a.txt"]) as any).why).toContain("Other files are staged too: other.txt");
1509
+ sh(proj, "reset", "-q", "--", "other.txt");
1510
+ expect((commitStaged(st, "r1", "no type", ["a.txt"]) as any).why).toContain("Start the message with a type");
1511
+ // The sparkle: with no claude on PATH the message is built from the file names, and it passes the type check.
1512
+ const path = process.env.PATH;
1513
+ process.env.PATH = "";
1514
+ try {
1515
+ const m = await suggestMessage(st, "r1");
1516
+ expect(m).toEqual({ ok: true, message: "chore: update a.txt", ai: false });
1517
+ } finally { process.env.PATH = path; }
1518
+ const r = commitStaged(st, "r1", "fix: a", ["a.txt"]) as { ok: true; sha: string };
1519
+ expect(r.ok).toBe(true);
1520
+ expect(sh(proj, "show", "--name-only", "--format=%s", "HEAD")).toBe("fix: a\n\na.txt");
1521
+ expect(sh(bare, "rev-list", "--all", "--count")).toBe("0"); // not pushed
1522
+ expect(readCommit(st, "r1")).toEqual({ sha: r.sha, pushed: false });
1523
+ // Edits made after the run's commit are not the run's: discarding them is refused.
1524
+ writeFileSync(join(proj, "a.txt"), "junk\n");
1525
+ expect(stageFiles(st, "r1", "discard", ["a.txt"])).toBe("Not this run's: a.txt");
1526
+ expect(readFileSync(join(proj, "a.txt"), "utf8")).toBe("junk\n");
1527
+ rmSync(root, { recursive: true, force: true });
1528
+ });
1529
+
1530
+ test("runGit: a run owns the files its report lists as changed, not ones it only mentions", () => {
1531
+ const proj = mkdtempSync(join(tmpdir(), "kaizen-own-")), st = join(proj, ".kaizen"), g = (...a: string[]) => Bun.spawnSync(["git", "-C", proj, ...a]);
1532
+ g("init", "-q"); g("config", "user.email", "t@t"); g("config", "user.name", "t"); g("remote", "add", "origin", "https://example.invalid/r.git");
1533
+ for (const f of ["listed.txt", "mentioned.txt", "fixed.txt", "whole.txt", "script.txt", "kept.txt"]) writeFileSync(join(proj, f), "1\n");
1534
+ g("add", "."); g("commit", "-qm", "base", "--date=2000-01-01T00:00:00");
1535
+ Bun.spawnSync(["git", "-C", proj, "commit", "-q", "--amend", "--no-edit"], { env: { ...process.env, GIT_COMMITTER_DATE: "2000-01-01T00:00:00" } });
1536
+ for (const f of ["listed.txt", "mentioned.txt", "fixed.txt", "whole.txt", "script.txt", "kept.txt"]) writeFileSync(join(proj, f), "2\n");
1537
+ const a = join(st, "runs", "a"), b = join(st, "runs", "b");
1538
+ mkdirSync(join(a, "05-iterations"), { recursive: true }); mkdirSync(b, { recursive: true });
1539
+ writeFileSync(join(a, "state.json"), "{}"); writeFileSync(join(b, "state.json"), "{}");
1540
+ writeFileSync(join(a, "03-impl.md"), "## Changed\n- `listed.txt`\n\n## Scripts\n- `script.txt`\n\n## Left unchanged\n`kept.txt`\n\n## Deviations\n`mentioned.txt` is another session's.\n");
1541
+ writeFileSync(join(a, "05-iterations", "01-fix.md"), "# Fix\n- `fixed.txt`\n");
1542
+ writeFileSync(join(b, "03-impl.md"), "No headings here: `whole.txt`\n");
1543
+ const files = (id: string) => (runGit(st, id) as any).files.map((l: string) => l.slice(3));
1544
+ expect(files("a")).toEqual(["fixed.txt", "listed.txt", "script.txt"]);
1545
+ expect(files("b")).toEqual(["whole.txt"]);
1546
+ rmSync(proj, { recursive: true, force: true });
1547
+ });