kaizen-agent 1.63.0 → 1.64.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +10 -10
  2. package/agents/kaizen-planner.md +2 -2
  3. package/cli/backlog.test.ts +1 -1
  4. package/cli/board.test.ts +24 -24
  5. package/cli/dashboard.ts +15 -15
  6. package/cli/handoff.test.ts +133 -0
  7. package/cli/handoff.ts +122 -0
  8. package/cli/install.ts +31 -5
  9. package/cli/notes.test.ts +3 -3
  10. package/cli/notes.ts +1 -1
  11. package/cli/pty.ts +16 -2
  12. package/cli/resources.test.ts +50 -0
  13. package/cli/resources.ts +113 -0
  14. package/cli/restart.test.ts +28 -1
  15. package/cli/settings.ts +8 -5
  16. package/cli/sources.test.ts +32 -32
  17. package/cli/sources.ts +15 -15
  18. package/cli/state.test.ts +74 -51
  19. package/cli/state.ts +77 -49
  20. package/cli/usage.test.ts +11 -0
  21. package/cli/web.ts +139 -38
  22. package/cli/workers.ts +11 -4
  23. package/cli/worktree.test.ts +174 -1
  24. package/cli/worktree.ts +190 -35
  25. package/commands/kaizen-discover.md +1 -1
  26. package/package.json +1 -1
  27. package/skills/kaizen/README.md +2 -2
  28. package/skills/kaizen/SKILL.md +2 -2
  29. package/skills/kaizen/config.default.yml +32 -22
  30. package/skills/kaizen/discover.md +8 -8
  31. package/skills/kaizen/gather.md +2 -2
  32. package/skills/kaizen/settings.md +3 -0
  33. package/skills/kaizen/spec-build.md +13 -0
  34. package/skills/kaizen/spec-main.md +13 -0
  35. package/skills/kaizen/spec-plan.md +1 -1
  36. package/skills/kaizen/spec.md +1 -1
  37. package/skills/kaizen-help/SKILL.md +2 -2
  38. package/web/board/api.ts +10 -10
  39. package/web/board/cards.ts +47 -46
  40. package/web/board/git.ts +4 -4
  41. package/web/board/icebox.ts +14 -14
  42. package/web/board/keys.ts +3 -3
  43. package/web/board/labels.ts +2 -2
  44. package/web/board/live.ts +3 -3
  45. package/web/board/main.ts +1 -1
  46. package/web/board/markdown.ts +1 -1
  47. package/web/board/panel.ts +17 -17
  48. package/web/board/phone.ts +10 -12
  49. package/web/board/projects.ts +6 -6
  50. package/web/board/resources.ts +152 -0
  51. package/web/board/run-view.ts +5 -5
  52. package/web/board/search.ts +11 -11
  53. package/web/board/settings-cleanup.ts +42 -0
  54. package/web/board/settings-pages.ts +1 -1
  55. package/web/board/settings.ts +13 -0
  56. package/web/board/store.ts +1 -1
  57. package/web/board/{ideas.ts → tasks.ts} +22 -22
  58. package/web/board/terms.ts +3 -3
  59. package/web/board/views.ts +23 -12
  60. package/web/board/workspace.ts +9 -7
  61. package/web/board/ws-board-ui.ts +1 -1
  62. package/web/board/ws-board.test.ts +1 -1
  63. package/web/board/ws-board.ts +1 -1
  64. package/web/board/ws-tabs.test.ts +10 -2
  65. package/web/board/ws-tabs.ts +10 -9
  66. package/web/board.html +46 -34
  67. package/web/board.js +107 -97
  68. package/web/notebook.js +22 -22
  69. package/web/notebook.ts +5 -5
  70. package/web/notes-lib.ts +2 -2
  71. package/web/notes.html +12 -11
  72. package/web/term-font.test.ts +22 -0
  73. package/web/term-font.ts +30 -0
  74. package/web/term.js +38 -38
  75. package/web/term.ts +13 -2
  76. package/web/video.html +12 -11
  77. package/web/video.js +48 -48
package/README.md CHANGED
@@ -32,10 +32,10 @@
32
32
  | **Plan first** | The agent writes what it will do, and what *wrong* would look like, then waits for your approve or change. |
33
33
  | **A reviewer that starts cold** | A second agent reviews from the request, the plan and the diff only. It never saw the work, so it has nothing to defend. |
34
34
  | **A fix loop that ends** | Serious findings are fixed and re-checked, at most twice. The rest come to you; what is left goes to a backlog. |
35
- | **One board** | `kaizen web`: icebox, ideas, plan, build, review, fix, commit and push, in the browser or the terminal. |
36
- | **Requests from where they live** | Sheets, docs and social posts are gathered into an icebox, grouped, and promoted to ideas when you pick them. |
35
+ | **One workspace** | `kaizen web`: each run builds in its own worktree, with icebox, tasks, plan, build, review, fix, commit and push in one place, in the browser or the terminal. |
36
+ | **Requests from where they live** | Sheets, docs and social posts are gathered into an icebox, grouped, and promoted to tasks when you pick them. |
37
37
  | **A notebook agents read first** | An Obsidian-compatible vault under `.kaizen/notes/` that every stage reads before it plans or builds. |
38
- | **On your phone** | The board installs as a PWA over Tailscale. `kaizen setup` prints the QR code. |
38
+ | **On your phone** | kaizen installs as a PWA over Tailscale. `kaizen setup` prints the QR code. |
39
39
  | **Any agent, any session** | Every stage is a file in `.kaizen/runs/<id>/`, so another session or another tool can pick a run up. |
40
40
 
41
41
  </details>
@@ -61,8 +61,8 @@ None of this is a lack of intelligence. It is a missing workflow. Many assistant
61
61
  irm bun.sh/install.ps1 | iex; & "$env:USERPROFILE\.bun\bin\bunx.exe" kaizen-agent
62
62
  ```
63
63
  Already have Bun? `bunx kaizen-agent`.
64
- 2. **Run `kaizen setup`.** It walks you through your project, settings, the board and the phone app.
65
- 3. **Open the board** with `kaizen web`, or type `/kaizen <request>` in your agent.
64
+ 2. **Run `kaizen setup`.** It walks you through your project, settings, `kaizen web` and the phone app.
65
+ 3. **Open kaizen** with `kaizen web`, or type `/kaizen <request>` in your agent.
66
66
 
67
67
  <p align="center">
68
68
  <img src="https://raw.githubusercontent.com/hfadhlullah/kaizen/main/site/media/workspace.png" alt="The kaizen workspace: agent tabs, the app in a browser pane, and the plan waiting for review" width="100%">
@@ -74,7 +74,7 @@ None of this is a lack of intelligence. It is a missing workflow. Many assistant
74
74
  |---|---|
75
75
  | Runtime | [Bun](https://bun.sh) 1.1 or newer. The installer above gets it. |
76
76
  | Agent | Claude Code, Codex, Antigravity or Gemini CLI. Claude Code gets the full flow with separate subagents; the others run every stage in one session. |
77
- | Git | Needed for the board's commit and push. Optional otherwise. |
77
+ | Git | Needed for kaizen's commit and push. Optional otherwise. |
78
78
  | OS | macOS, Linux, Windows. |
79
79
  | Phone app | [Tailscale](https://tailscale.com/download) on the PC and the phone, same account. |
80
80
 
@@ -93,7 +93,7 @@ flowchart LR
93
93
  ```
94
94
 
95
95
  <p align="center">
96
- <img src="https://raw.githubusercontent.com/hfadhlullah/kaizen/main/assets/readme/architecture.png" alt="From idea to finished work: your idea, plan, build, a review in a separate context, a refine loop, and the finished app, document, video or game" width="100%">
96
+ <img src="https://raw.githubusercontent.com/hfadhlullah/kaizen/main/assets/readme/architecture.png" alt="From task to finished work: your task, plan, build, a review in a separate context, a refine loop, and the finished app, document, video or game" width="100%">
97
97
  </p>
98
98
 
99
99
  Each stage is its own agent with a clean context: planner, builder, reviewer. They never share a context window. The main thread owns the run's state in `.kaizen/runs/<id>/state.json`; the plan, the build notes, the review and every fix round are files beside it. Small changes take a short path in one session, so a typo does not cost a payroll change.
@@ -103,7 +103,7 @@ Each stage is its own agent with a clean context: planner, builder, reviewer. Th
103
103
  - Installs itself to `~/kaizen`, and keeps settings and the project list in `~/.kaizen/`.
104
104
  - Links its skills, agents and `/kaizen-*` commands into each agent it finds: `~/.claude`, `~/.codex`, `~/.agents`, `~/.gemini`. Re-running is safe.
105
105
  - Per project, `kaizen init` writes `.kaizen/` and, in a git repo, a `.gitignore` entry that keeps run state out of commits but keeps the `spec*.md` files and `config.yml`.
106
- - `kaizen web` serves the board on `127.0.0.1:7420`. After `kaizen setup` it is also reachable from your own Tailscale network, nothing wider; never use `tailscale funnel`.
106
+ - `kaizen web` serves kaizen on `127.0.0.1:7420`. After `kaizen setup` it is also reachable from your own Tailscale network, nothing wider; never use `tailscale funnel`.
107
107
  - `kaizen uninstall` removes the app and its links, and asks whether to keep your runs and settings (`--purge` deletes them too).
108
108
 
109
109
  ## Who it is for
@@ -114,10 +114,10 @@ Each stage is its own agent with a clean context: planner, builder, reviewer. Th
114
114
 
115
115
  ## Phone app
116
116
 
117
- The board is a PWA: installed from the browser, it opens full screen with the kaizen icon. It needs [Tailscale](https://tailscale.com/download) on this PC and on your phone, both signed in to the same account.
117
+ kaizen is a PWA: installed from the browser, it opens full screen with the kaizen icon. It needs [Tailscale](https://tailscale.com/download) on this PC and on your phone, both signed in to the same account.
118
118
 
119
119
  ```bash
120
- kaizen setup # guided: starts the board, runs tailscale serve, prints a QR code
120
+ kaizen setup # guided: starts `kaizen web`, runs tailscale serve, prints a QR code
121
121
  ```
122
122
 
123
123
  Scan the QR code with your phone camera, then **Add to Home screen** (iOS: Share menu; Android: browser menu, *Install app*).
@@ -78,7 +78,7 @@ The input will not be tidy, and it is not supposed to be. Expect thinking out lo
78
78
  half-formed sentences, a topic picked up and dropped, a correction three messages
79
79
  later, a request that contradicts something said earlier, an "oh and also" that
80
80
  turns out to be the most important constraint in the whole thing. This is how people
81
- actually work when the idea is still forming, and a workflow that only functions on
81
+ actually work when the task is still forming, and a workflow that only functions on
82
82
  well-specified input is a workflow that only functions after the person has already
83
83
  done the hard part themselves.
84
84
 
@@ -216,7 +216,7 @@ Write `01-plan.md` with exactly these sections:
216
216
 
217
217
  Write Track, Framing, Work list, Goal, Scope, Risks and Out of scope suggestions for a
218
218
  person deciding whether to approve, often on a narrow panel: everyday words, short
219
- sentences, one idea per bullet, things named by what the user sees rather than by
219
+ sentences, one task per bullet, things named by what the user sees rather than by
220
220
  function, file, CSS value or gate id. Code names, `path:line` and gate ids belong in
221
221
  Reuse, Steps and Verification, where the builder and reviewer need them exact. If a
222
222
  sentence only makes sense to someone who has read the code, it is in the wrong section.
@@ -1,4 +1,4 @@
1
- // Backlog items as cards in the board's Ideas column: numbering, hiding while a run
1
+ // Backlog items as cards in the board's Tasks column: numbering, hiding while a run
2
2
  // started from one lives, closing in place, and the board routes that drive them.
3
3
  import { test, expect } from "bun:test";
4
4
  import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, statSync } from "node:fs";
package/cli/board.test.ts CHANGED
@@ -21,7 +21,7 @@ test("Board badge counts each card needing input once and clears at zero", () =>
21
21
  { kind: "run", status: "running", pty: { alive: false, asking: true } },
22
22
  ];
23
23
  expect(waitingCount(cards)).toBe(2);
24
- // The Ideas link carries no count.
24
+ // The Tasks link carries no count.
25
25
  boardBadge(cards);
26
26
  expect(link.dataset.n).toBeUndefined();
27
27
  } finally {
@@ -219,33 +219,33 @@ test("card menu items: appropriate actions and distinct icons across phases", ()
219
219
  const actionOf = cards.slice(a0, cards.indexOf("\n\n", a0));
220
220
  const getItems = new Function("c", "archive", "S", `const ico = ${ico.toString()};\nconst decided = new Set(), answer = () => "";\n${actionOf}\nconst store = { S, menuKey: 1 };\nlet k = 1, items = [];\n${menuSnippet}\nreturn items;`);
221
221
 
222
- // Phase 0: Ideas (idea card)
223
- const idea = { kind: "idea", status: "idea", column: 0 };
224
- const ideaItems = getItems(idea, false, { projects: [] });
225
- expect(ideaItems.map((i: any) => i ? i[1] : null)).toEqual(["Run", "Edit", "Archive", null, "Reject", "Delete"]);
222
+ // Phase 0: Tasks (task card)
223
+ const task = { kind: "idea", status: "idea", column: 0 };
224
+ const taskItems = getItems(task, false, { projects: [] });
225
+ expect(taskItems.map((i: any) => i ? i[1] : null)).toEqual(["Run", "Edit", "Archive", null, "Reject", "Delete"]);
226
226
  // Move only when there is another project to move to.
227
- const moveItems = getItems({ ...idea, state: "/a" }, false, { projects: [{ dir: "/a" }, { dir: "/b" }] });
227
+ const moveItems = getItems({ ...task, state: "/a" }, false, { projects: [{ dir: "/a" }, { dir: "/b" }] });
228
228
  expect(moveItems.map((i: any) => i ? i[1] : null)).toEqual(["Run", "Edit", "Move to project", "Archive", null, "Reject", "Delete"]);
229
229
  expect(moveItems[2][2]).toBe(ico("ext"));
230
- expect(ideaItems[0][2]).toBe(ico("play"));
231
- expect(ideaItems[1][2]).toBe(ico("pen"));
232
- expect(ideaItems[2][2]).toBe(ico("archive"));
233
- expect(ideaItems[4][2]).toBe(ico("x"));
234
- expect(ideaItems[5][2]).toBe(ico("trash"));
235
-
236
- // Phase 1: Planning (starting idea)
237
- const startingIdea = { kind: "idea", status: "starting", column: 1 };
238
- const startItems = getItems(startingIdea, false);
230
+ expect(taskItems[0][2]).toBe(ico("play"));
231
+ expect(taskItems[1][2]).toBe(ico("pen"));
232
+ expect(taskItems[2][2]).toBe(ico("archive"));
233
+ expect(taskItems[4][2]).toBe(ico("x"));
234
+ expect(taskItems[5][2]).toBe(ico("trash"));
235
+
236
+ // Phase 1: Planning (starting task)
237
+ const startingTask = { kind: "idea", status: "starting", column: 1 };
238
+ const startItems = getItems(startingTask, false);
239
239
  expect(startItems.map((i: any) => i ? i[1] : null)).toEqual(["Open", "Run again", "Archive", null, "Remove"]);
240
240
 
241
- // Ideas column, Backlog tab: a run's leftover, run like an idea, rejected with a reason.
241
+ // Tasks column, Backlog tab: a run's leftover, run like a task, rejected with a reason.
242
242
  expect(getItems({ kind: "backlog", status: "idea", column: 0 }, false).map((i: any) => i ? i[1] : null)).toEqual(["Run", "Open its run", null, "Reject"]);
243
243
  expect(getItems({ kind: "backlog", status: "starting", column: 0 }, false)[0][1]).toBe("Run again");
244
244
 
245
245
  // Phase 1: Planning (run waiting for plan approval)
246
246
  const planWaiting = { kind: "run", status: "waiting", awaiting: "approvals.plan", column: 1 };
247
247
  const planItems = getItems(planWaiting, false);
248
- expect(planItems.map((i: any) => i ? i[1] : null)).toEqual(["Review plan", "Archive", "Back to idea"]);
248
+ expect(planItems.map((i: any) => i ? i[1] : null)).toEqual(["Review plan", "Archive", "Back to task"]);
249
249
  expect(planItems[0][2]).toBe(ico("open"));
250
250
  expect(planItems[1][2]).toBe(ico("archive"));
251
251
  expect(planItems[2][2]).toBe(ico("restore"));
@@ -281,13 +281,13 @@ test("card menu items: appropriate actions and distinct icons across phases", ()
281
281
  expect(archRun[0][2]).toBe(ico("restore"));
282
282
  expect(archRun[1][2]).toBe(ico("open"));
283
283
 
284
- const archIdea = getItems(idea, true);
285
- expect(archIdea.map((i: any) => i ? i[1] : null)).toEqual(["Restore", "Open", null, "Delete"]);
284
+ const archTask = getItems(task, true);
285
+ expect(archTask.map((i: any) => i ? i[1] : null)).toEqual(["Restore", "Open", null, "Delete"]);
286
286
  });
287
287
 
288
- // brief(): a one-line structured idea split for display only.
288
+ // brief(): a one-line structured task split for display only.
289
289
 
290
- test("a labelled idea splits into a head and one part per label", () => {
290
+ test("a labelled task splits into a head and one part per label", () => {
291
291
  const b = brief("Improve previews Problem: one dense block. Non-goals: no rewrites. Acceptance criteria: (1) scannable. (2) full text kept.");
292
292
  expect(b.head).toBe("Improve previews");
293
293
  expect(b.parts.map(p => p.label)).toEqual(["Problem", "Non-goals", "Acceptance criteria"]);
@@ -295,11 +295,11 @@ test("a labelled idea splits into a head and one part per label", () => {
295
295
  expect(md(`### ${b.parts[2].label}\n${b.parts[2].body}`)).toBe("<h3>Acceptance criteria</h3><ol><li>scannable.</li><li>full text kept.</li></ol>");
296
296
  });
297
297
 
298
- test("plain ideas, and a single label, are left whole", () => {
298
+ test("plain tasks, and a single label, are left whole", () => {
299
299
  for (const t of ["fix the typo in README", "Bug: clicking twice opens two panels"]) expect(brief(t)).toEqual({ head: t, parts: [] });
300
300
  });
301
301
 
302
- test("an idea that opens with a label heads with its first part", () => {
302
+ test("a task that opens with a label heads with its first part", () => {
303
303
  expect(brief("Goal: faster board. Scope: cards only.").head).toBe("Goal: faster board.");
304
304
  });
305
305
 
@@ -313,7 +313,7 @@ test("criteria not numbered from 1 keep their own numbers", () => {
313
313
  expect(brief("X Goal: g. Criteria: (2) two. (3) three.").parts[1].body).toBe("- (2) two.\n- (3) three.");
314
314
  });
315
315
 
316
- // pretty(): a one-line idea note splits into one paragraph per label.
316
+ // pretty(): a one-line task note splits into one paragraph per label.
317
317
  test("pretty splits a labelled plain line in a note by its labels", async () => {
318
318
  const { pretty } = await import("../web/board/chat.ts");
319
319
  const t = "Parent: run-x add a timezone. OPEN QUESTION (waiting on Johan): recalc old rows? Context: PR #452.";
package/cli/dashboard.ts CHANGED
@@ -8,7 +8,7 @@ import {
8
8
  searchRoots, knownProjects, remember, findProjects, locate,
9
9
  readRuns, healRuns, backlog, version, label, tilde, section, readFindings, parseItem, tidy, readBacklog, allBacklog,
10
10
  startedRuns, normalise, statusOf, columnOf, readInbox, writeInbox, notify, notice, notifier, short,
11
- abandonRun, replaceIdea, boardCards, launchRun, appendNote, parseNotes,
11
+ abandonRun, replaceTask, boardCards, launchRun, appendNote, parseNotes,
12
12
  gateOf,
13
13
  } from "./state.ts";
14
14
  import { WORDMARK } from "./look.ts";
@@ -128,7 +128,7 @@ export async function dashboard(
128
128
  { key: "projects", label: "All projects", hint: "every project kaizen knows about" },
129
129
  ] : []),
130
130
  ...(state ? [
131
- { key: "board", label: "Board", hint: "ideas and runs, by stage" },
131
+ { key: "board", label: "Board", hint: "tasks and runs, by stage" },
132
132
  { key: "runs", label: "Runs", hint: "every run, and what each is waiting on" },
133
133
  { key: "backlog", label: "Backlog", hint: "things to do later" },
134
134
  ] : []),
@@ -471,7 +471,7 @@ export async function dashboard(
471
471
 
472
472
  // ------------------------------------------------------------------ board
473
473
 
474
- // Ideas and runs on one screen, in stage columns. A run's stage belongs to
474
+ // Tasks and runs on one screen, in stage columns. A run's stage belongs to
475
475
  // kaizen and cannot be edited here -- a board that could drag one backwards
476
476
  // would be lying about what happened. The one exception is abandoning a run,
477
477
  // which is the user's decision either way.
@@ -588,7 +588,7 @@ export async function dashboard(
588
588
  const footer = (k?: Card) => {
589
589
  const acts = k?.kind === "idea"
590
590
  ? "n new e edit t note x reject d delete r run"
591
- : k ? "n new idea t note x abandon this run" : "n new idea";
591
+ : k ? "n new task t note x abandon this run" : "n new task";
592
592
  const scope = allProjects ? "a this project" : "a all projects";
593
593
  return ` ${c.dim("↑↓←→ move")} ${c.dim(acts)} ${c.dim(scope)} ${c.dim("q back")}\n`;
594
594
  };
@@ -604,7 +604,7 @@ export async function dashboard(
604
604
  ["waiting", `${c.amber("●")} ${c.red("waiting on you")}`],
605
605
  ["done", c.dim("○ done")],
606
606
  ["abandoned", c.dim("○ abandoned")],
607
- ["idea", c.dim("· idea")],
607
+ ["idea", c.dim("· task")],
608
608
  ];
609
609
  const parts = all.filter(([key]) => present.has(key)).map(([, text]) => text);
610
610
  return parts.length ? "\n " + parts.join(" ") + "\n" : "\n";
@@ -692,7 +692,7 @@ export async function dashboard(
692
692
 
693
693
  const target = current();
694
694
  if (key === "n") {
695
- const text = await promptLine("New idea", "");
695
+ const text = await promptLine("New task", "");
696
696
  if (text) {
697
697
  const st = target?.state ?? state!;
698
698
  writeInbox(st, [...readInbox(st), { status: "open", text }]);
@@ -720,17 +720,17 @@ export async function dashboard(
720
720
  draw(); continue;
721
721
  }
722
722
  if (key === "e") {
723
- const text = await promptLine("Edit idea", target.text);
724
- if (text) replaceIdea(target.state, target.text, { status: "open", text });
723
+ const text = await promptLine("Edit task", target.text);
724
+ if (text) replaceTask(target.state, target.text, { status: "open", text });
725
725
  } else if (key === "t" && target.status === "idea") {
726
726
  const line = await promptLine("Add a note", "");
727
727
  if (line) appendNote(target.state, { text: target.text }, line);
728
728
  } else if (key === "x") {
729
729
  const why = await promptLine(`Reject: ${target.text}`, "");
730
730
  // The spec requires a reason on a rejected item; no reason, no rejection.
731
- if (why) replaceIdea(target.state, target.text, { status: "rejected", text: `${target.text} | ${why}` });
731
+ if (why) replaceTask(target.state, target.text, { status: "rejected", text: `${target.text} | ${why}` });
732
732
  } else if (key === "d") {
733
- if (await confirm(`Delete "${cut(target.text, 40)}"?`)) replaceIdea(target.state, target.text, null);
733
+ if (await confirm(`Delete "${cut(target.text, 40)}"?`)) replaceTask(target.state, target.text, null);
734
734
  } else if (key === "r") {
735
735
  const mode = await pickMode();
736
736
  // "" is the default-mode choice, and must not leave a double space in
@@ -738,9 +738,9 @@ export async function dashboard(
738
738
  if (mode !== null) {
739
739
  const request = `${mode} ${target.text}`.trim();
740
740
  await outside(() => startBacklogItem({ ...parseItem(request), notes: target.notes }, target.state));
741
- // Without this the idea stays open forever and the board shows the
742
- // same work twice: once as an idea, once as the run it became.
743
- replaceIdea(target.state, target.text, { status: "started", text: target.text });
741
+ // Without this the task stays open forever and the board shows the
742
+ // same work twice: once as a task, once as the run it became.
743
+ replaceTask(target.state, target.text, { status: "started", text: target.text });
744
744
  }
745
745
  }
746
746
  refresh(); clamp(); draw();
@@ -789,7 +789,7 @@ export async function dashboard(
789
789
  if (!isClick(ev)) continue;
790
790
  const target = cardAt(ev.x, ev.y);
791
791
  if (!target) continue;
792
- // Click to select; click the selected card to act, which on an idea
792
+ // Click to select; click the selected card to act, which on a task
793
793
  // means the same thing r does.
794
794
  if (target.col === col && target.row === row) return done("r");
795
795
  col = target.col; row = target.row;
@@ -1111,7 +1111,7 @@ export async function dashboard(
1111
1111
  }
1112
1112
 
1113
1113
  const COLUMNS = [
1114
- { key: "idea", title: "IDEA" },
1114
+ { key: "idea", title: "TO DO" },
1115
1115
  { key: "plan", title: "PLANNING" },
1116
1116
  { key: "build", title: "BUILDING" },
1117
1117
  { key: "review", title: "REVIEW" },
@@ -0,0 +1,133 @@
1
+ import { test, expect, beforeEach } from "bun:test";
2
+ import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { move, awaitBoard, childDied, childQuiet, QUIET_MS, finish, markWoken, requestOpen, readHandoff, request, REQUEST_MS, started, wakeAction, wakeLine, type Handoff } from "./handoff.ts";
6
+ import { agentLine } from "./workers.ts";
7
+
8
+ const ID = "2026-11-01-x";
9
+ let state: string;
10
+ beforeEach(() => {
11
+ state = mkdtempSync(join(tmpdir(), "hand-"));
12
+ mkdirSync(join(state, "runs", ID), { recursive: true });
13
+ writeFileSync(join(state, "runs", ID, "state.json"), "{}");
14
+ });
15
+ const idle = { alive: true, busy: false, asking: false, typedAt: 0 };
16
+ const ended = (o: Partial<Handoff> = {}): Handoff => ({ status: "done", parent_terminal: "sh-1", at: 0, ...o });
17
+
18
+ test("G-04 outside a board terminal nothing is requested", () => {
19
+ expect(request(state, ID, undefined)).toBeNull();
20
+ expect(readHandoff(state, ID)).toBeNull();
21
+ });
22
+
23
+ test("G-04 no answer declines, so a late board opens nothing", async () => {
24
+ request(state, ID, "sh-1");
25
+ expect(await awaitBoard(state, ID, 30, 5)).toBe(false);
26
+ const h = readHandoff(state, ID)!;
27
+ expect(h.status).toBe("declined");
28
+ expect(requestOpen(h, h.at)).toBe(false);
29
+ });
30
+
31
+ test("G-04 an old request is not acted on", () => {
32
+ expect(requestOpen(ended({ status: "requested", at: 0 }), REQUEST_MS + 1)).toBe(false);
33
+ });
34
+
35
+ test("the board's answer ends the wait", async () => {
36
+ request(state, ID, "sh-1"); started(state, ID, "sh-2");
37
+ expect(await awaitBoard(state, ID, 30, 5)).toBe(true);
38
+ expect(readHandoff(state, ID)!.child_terminal).toBe("sh-2");
39
+ });
40
+
41
+ test("only a running handoff takes a result", () => {
42
+ expect(finish(state, ID, "done")).toContain("no handoff");
43
+ request(state, ID, "sh-1");
44
+ expect(finish(state, ID, "done")).toContain("requested");
45
+ started(state, ID, "sh-2");
46
+ expect(finish(state, ID, "blocked", "why")).toBeNull();
47
+ expect(finish(state, ID, "done")).not.toBeNull();
48
+ expect(readHandoff(state, ID)).toMatchObject({ status: "blocked", reason: "why" });
49
+ });
50
+
51
+ test("G-05 a wake is held while busy, asking or typing, then sent once", () => {
52
+ expect(wakeAction(ended(), { ...idle, busy: true }, 1e6)).toBe("wait");
53
+ expect(wakeAction(ended(), { ...idle, asking: true }, 1e6)).toBe("wait");
54
+ expect(wakeAction(ended(), { ...idle, typedAt: 1e6 - 1000 }, 1e6)).toBe("wait");
55
+ expect(wakeAction(ended(), idle, 1e6)).toBe("send");
56
+ expect(wakeAction(ended({ woken: true }), idle, 1e6)).toBe("none");
57
+ expect(wakeAction(ended({ status: "running" }), idle, 1e6)).toBe("none");
58
+ request(state, ID, "sh-1"); started(state, ID, "sh-2"); finish(state, ID, "done"); markWoken(state, ID);
59
+ expect(wakeAction(readHandoff(state, ID), idle, 1e6)).toBe("none");
60
+ });
61
+
62
+ test("G-06 a dead child fails, and a dead parent is reported, not typed at", () => {
63
+ expect(childDied(ended({ status: "running" }), false)).toBe(true);
64
+ expect(childDied(ended({ status: "running" }), true)).toBe(false);
65
+ expect(childDied(ended(), false)).toBe(false);
66
+ expect(wakeAction(ended({ status: "failed" }), idle, 1e6)).toBe("send");
67
+ expect(wakeAction(ended(), null, 1e6)).toBe("gone");
68
+ });
69
+
70
+ test("G-04 a second agent that already finished is not mistaken for no board", async () => {
71
+ request(state, ID, "sh-1"); started(state, ID, "sh-2"); finish(state, ID, "done");
72
+ expect(await awaitBoard(state, ID, 30, 5)).toBe(true);
73
+ });
74
+
75
+ test("G-05 the wake line reaches a real terminal, submitted", async () => {
76
+ const { startPty, submitPty, ptyTail } = await import("./pty.ts");
77
+ if (process.platform === "win32") return;
78
+ startPty("hand-wake", ["sh", "-c", "timeout 1 cat"], state);
79
+ submitPty("hand-wake", wakeLine(ID, ended()), 20);
80
+ await Bun.sleep(200);
81
+ expect(ptyTail("hand-wake")).toContain(`kaizen run ${ID}: the worktree agent ended (done)`);
82
+ });
83
+
84
+ test("G-07 the second agent never takes bypass", () => {
85
+ const project = join(state, "p");
86
+ mkdirSync(join(project, ".kaizen", "runs", ID), { recursive: true });
87
+ writeFileSync(join(project, ".kaizen", "runs", ID, "state.json"), JSON.stringify({ agent: "claude" }));
88
+ const l = agentLine(project, ID, "hi", "own");
89
+ if (typeof l !== "string") { expect(l.bypass).toBe(false); expect(l.argv.join(" ")).not.toContain("dangerously"); }
90
+ });
91
+
92
+ test("a silent child goes quiet, wakes the parent, and can still report", () => {
93
+ const pty = { alive: true, busy: false, asking: false, lastOut: 0 };
94
+ expect(childQuiet(ended({ status: "running" }), pty, QUIET_MS + 1)).toBe(true);
95
+ expect(childQuiet(ended({ status: "running" }), { ...pty, asking: true }, QUIET_MS + 1)).toBe(false);
96
+ expect(childQuiet(ended({ status: "running" }), pty, QUIET_MS - 1)).toBe(false);
97
+ expect(wakeAction(ended({ status: "quiet" }), idle, 1e6)).toBe("send");
98
+ request(state, ID, "sh-1"); started(state, ID, "sh-2");
99
+ move(state, ID, ["running"], { status: "quiet", woken: true });
100
+ expect(finish(state, ID, "done")).toBeNull();
101
+ expect(wakeAction(readHandoff(state, ID), idle, 1e6)).toBe("send");
102
+ });
103
+
104
+ test("cold 1: a second start never replaces a live agent", () => {
105
+ request(state, ID, "sh-1"); started(state, ID, "sh-2");
106
+ expect(request(state, ID, "sh-9")).toMatchObject({ status: "running", child_terminal: "sh-2" });
107
+ finish(state, ID, "blocked", "x");
108
+ expect(request(state, ID, "sh-9")).toMatchObject({ status: "requested", parent_terminal: "sh-9" });
109
+ });
110
+
111
+ test("cold 2: claim and decline cannot both win", async () => {
112
+ request(state, ID, "sh-1");
113
+ const claim = setTimeout(() => started(state, ID, "sh-2"), 5);
114
+ await Bun.sleep(10); clearTimeout(claim);
115
+ expect(await awaitBoard(state, ID, 0)).toBe(true);
116
+ writeFileSync(join(state, "runs", ID, "handoff.json"), JSON.stringify({ status: "declined", parent_terminal: "sh-1", at: 0 }));
117
+ expect(started(state, ID, "sh-3")).toBe(false);
118
+ });
119
+
120
+ test("cold 3: a stale board read cannot overwrite done", () => {
121
+ request(state, ID, "sh-1"); started(state, ID, "sh-2"); finish(state, ID, "done");
122
+ expect(move(state, ID, ["running", "quiet"], { status: "failed" })).toBe(false);
123
+ expect(readHandoff(state, ID)!.status).toBe("done");
124
+ });
125
+
126
+ test("cold 5: a quiet child that dies counts as dead", () => {
127
+ expect(childDied(ended({ status: "quiet" }), false)).toBe(true);
128
+ });
129
+
130
+ test("cold 7: a draft holds the wake", () => {
131
+ expect(wakeAction(ended(), { ...idle, draft: true, typedAt: 1e6 - 6000 }, 1e6)).toBe("held");
132
+ expect(wakeAction(ended(), { ...idle, draft: true, typedAt: 1e9 - 11 * 60_000 }, 1e9)).toBe("send");
133
+ });
package/cli/handoff.ts ADDED
@@ -0,0 +1,122 @@
1
+ // A worktree run handed to a second agent: the first agent stays with the user, the board opens
2
+ // the second in the worktree, and wakes the first when it ends. Its own file, not state.json,
3
+ // because agents hand-write state.json. The wake-up carries nothing: this file and the run's
4
+ // reports are the message, so a lost one costs only the nudge.
5
+ import { closeSync, existsSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+
8
+ export type Status = "requested" | "running" | "done" | "blocked" | "failed" | "declined" | "quiet";
9
+ export type Handoff = { status: Status; parent_terminal: string; child_terminal?: string; reason?: string; at: number; woken?: boolean };
10
+ export const REQUEST_MS = 10_000;
11
+ const QUIET_TYPING_MS = 5_000;
12
+ const DRAFT_MS = 10 * 60_000; // a draft untouched this long no longer holds the wake
13
+
14
+ const file = (state: string, id: string) => join(state, "runs", id, "handoff.json");
15
+
16
+ export function readHandoff(state: string, id: string): Handoff | null {
17
+ try { return JSON.parse(readFileSync(file(state, id), "utf8")); } catch { return null; }
18
+ }
19
+
20
+ export function writeHandoff(state: string, id: string, h: Handoff) {
21
+ const f = file(state, id), tmp = `${f}.${process.pid}.tmp`;
22
+ writeFileSync(tmp, JSON.stringify(h, null, 2));
23
+ renameSync(tmp, f);
24
+ }
25
+
26
+ // The CLI and the board both move this file, so every move holds a lock across its read and
27
+ // write and names the statuses it may leave: a stale reader changes nothing.
28
+ function locked<T>(state: string, id: string, fn: () => T): T {
29
+ const lock = `${file(state, id)}.lock`;
30
+ for (let i = 0; ; i++) {
31
+ try { closeSync(openSync(lock, "wx")); break; } catch (err) {
32
+ try { if (Date.now() - statSync(lock).mtimeMs > 5000) { rmSync(lock, { force: true }); continue; } } catch { /* just released */ }
33
+ if (i > 500) throw err;
34
+ Bun.sleepSync(2);
35
+ }
36
+ }
37
+ try { return fn(); } finally { rmSync(lock, { force: true }); }
38
+ }
39
+
40
+ /** Moves the handoff only if it is in one of `from`. True when it moved. */
41
+ export function move(state: string, id: string, from: Status[], set: Partial<Handoff>): boolean {
42
+ return locked(state, id, () => {
43
+ const h = readHandoff(state, id);
44
+ if (!h || !from.includes(h.status)) return false;
45
+ writeHandoff(state, id, { ...h, ...set, at: Date.now() });
46
+ return true;
47
+ });
48
+ }
49
+
50
+ /**
51
+ * Asks the board for the second agent. Null when this is no board terminal: build here. An
52
+ * agent already open, or a request still live, is returned as it is: never a second one.
53
+ */
54
+ export function request(state: string, id: string, term: string | undefined): Handoff | null {
55
+ if (!term || !existsSync(join(state, "runs", id, "state.json"))) return null;
56
+ return locked(state, id, () => {
57
+ const was = readHandoff(state, id);
58
+ if (was && (was.status === "running" || was.status === "quiet" || requestOpen(was, Date.now()))) return was;
59
+ const h: Handoff = { status: "requested", parent_terminal: term, at: Date.now() };
60
+ writeHandoff(state, id, h);
61
+ return h;
62
+ });
63
+ }
64
+
65
+ /**
66
+ * Waits for the board to answer. No answer declines the request, so a board that comes up
67
+ * later cannot open a second agent beside the one now building here. The decline can lose to
68
+ * the board's claim: then the agent is open, and this says so.
69
+ */
70
+ export async function awaitBoard(state: string, id: string, ms = REQUEST_MS, step = 200): Promise<boolean> {
71
+ const took = (s?: Status) => s === "running" || s === "quiet" || s === "done" || s === "blocked" || s === "failed";
72
+ const end = Date.now() + ms;
73
+ while (Date.now() < end) {
74
+ const s = readHandoff(state, id)?.status;
75
+ // A quick second agent may be finished by the time this looks: it still took the run.
76
+ if (took(s)) return true;
77
+ if (s !== "requested") return false;
78
+ await Bun.sleep(step);
79
+ }
80
+ if (move(state, id, ["requested"], { status: "declined", reason: "no board answered" })) return false;
81
+ return took(readHandoff(state, id)?.status);
82
+ }
83
+
84
+ /** The board's claim, made before anything launches: it loses to a decline, so no stray agent. */
85
+ export const started = (state: string, id: string, key: string) => move(state, id, ["requested"], { status: "running", child_terminal: key });
86
+ export const refused = (state: string, id: string, why: string) => move(state, id, ["requested"], { status: "declined", reason: why });
87
+
88
+ /** The second agent's last word. A repeat cannot rewrite the result; a report after `quiet` wakes the first agent again, since it is news. */
89
+ export function finish(state: string, id: string, status: "done" | "blocked", reason?: string): string | null {
90
+ const h = readHandoff(state, id);
91
+ if (!h) return "this run has no handoff";
92
+ return move(state, id, ["running", "quiet"], { status, reason, woken: false }) ? null : `the handoff is ${readHandoff(state, id)!.status}, not running`;
93
+ }
94
+
95
+ /** A request the board may still act on. An old one was declined or abandoned by its asker. */
96
+ export const requestOpen = (h: Handoff | null, now: number) => h?.status === "requested" && now - h.at < REQUEST_MS;
97
+
98
+ /** A live second agent silent this long, not working or asking: it may have ended without saying so. */
99
+ export const QUIET_MS = 20 * 60_000;
100
+ export const childQuiet = (h: Handoff | null, pty: { alive: boolean; busy: boolean; asking: boolean; lastOut?: number } | null, now: number) =>
101
+ h?.status === "running" && !!pty?.alive && !pty.busy && !pty.asking && now - (pty.lastOut ?? now) > QUIET_MS;
102
+
103
+ /** The child terminal ended without a report. */
104
+ export const childDied = (h: Handoff | null, alive: boolean) => (h?.status === "running" || h?.status === "quiet") && !alive;
105
+
106
+ type Term = { alive: boolean; busy: boolean; asking: boolean; typedAt: number; draft?: boolean } | null;
107
+ export type Wake = "wait" | "send" | "gone" | "held" | "none";
108
+
109
+ /** What to do about the first agent: send only into a live, idle terminal nobody is typing in. */
110
+ export function wakeAction(h: Handoff | null, parent: Term, now: number): Wake {
111
+ if (!h || h.woken || !["done", "blocked", "failed", "quiet"].includes(h.status)) return "none";
112
+ if (!parent?.alive) return "gone";
113
+ // Unsent text in its input box: a wake would submit that draft. The card speaks instead.
114
+ if (parent.draft && now - parent.typedAt < DRAFT_MS) return "held";
115
+ return parent.busy || parent.asking || now - parent.typedAt < QUIET_TYPING_MS ? "wait" : "send";
116
+ }
117
+
118
+ export const wakeLine = (id: string, h: Handoff) =>
119
+ `kaizen run ${id}: the worktree agent ended (${h.status}). Read .kaizen/runs/${id}/handoff.json, 03-impl.md and 04-review.md, then report to the user.`;
120
+
121
+ /** Marked before sending: a board restart between the two loses a nudge, never repeats one. */
122
+ export const markWoken = (state: string, id: string) => move(state, id, ["done", "blocked", "failed", "quiet"], { woken: true });
package/cli/install.ts CHANGED
@@ -249,7 +249,7 @@ if (Bun.argv[2] === "sources" || Bun.argv[2] === "gather" || Bun.argv[2] === "ic
249
249
  const waiting = c.dim(" new requests wait in the icebox — kaizen icebox");
250
250
  try {
251
251
  if (cmd === "icebox" && (op === "promote" || op === "dismiss")) {
252
- // Ids only on the command line. The idea's text, which an agent may have written
252
+ // Ids only on the command line. The task's text, which an agent may have written
253
253
  // from outside text, comes from a file and never through a shell.
254
254
  const ids = url.split(",").map((i) => i.trim()).filter(Boolean);
255
255
  const at = rest.indexOf("--text-file");
@@ -257,7 +257,7 @@ if (Bun.argv[2] === "sources" || Bun.argv[2] === "gather" || Bun.argv[2] === "ic
257
257
  const text = at >= 0 ? readFileSync(rest[at + 1]!, "utf8") : undefined;
258
258
  const why = op === "promote" ? src.promote(state, ids, text) : src.dismiss(state, ids);
259
259
  if (why) { console.log(`\n ${why}\n`); process.exit(1); }
260
- console.log(`\n ${op === "promote" ? "promoted to Ideas" : "dismissed"}: ${ids.join(", ")}\n ${where}\n`);
260
+ console.log(`\n ${op === "promote" ? "promoted to Tasks" : "dismissed"}: ${ids.join(", ")}\n ${where}\n`);
261
261
  } else if (cmd === "icebox") {
262
262
  const all = src.readIcebox(state);
263
263
  const fresh = all.filter((s) => s.status === "new");
@@ -562,30 +562,56 @@ if (wantSettings) {
562
562
  if (args.has("worktree")) {
563
563
  const [, verb = "", id = ""] = Bun.argv.slice(2).filter((a) => !a.startsWith("-"));
564
564
  const { locate } = await import("./state.ts");
565
- const { startWorktree, landWorktree, adoptWorkspace, linkTerm } = await import("./worktree.ts");
565
+ const { startWorktree, landRun, adoptWorkspace, linkTerm } = await import("./worktree.ts");
566
566
  const state = locate();
567
567
  if (!state || (verb !== "start" && verb !== "land")) { console.log("\n usage: kaizen worktree start|land <run-id>, in a project with .kaizen\n"); process.exit(1); }
568
568
  const project = dirname(state);
569
569
  // Started inside another workspace of the project (a board worktree): the run is placed there.
570
- const r = verb === "start" ? adoptWorkspace(project, id, process.cwd()) ?? startWorktree(project, id) : landWorktree(project, id);
570
+ const r = verb === "start" ? adoptWorkspace(project, id, process.cwd()) ?? startWorktree(project, id) : landRun(project, id, process.env.KAIZEN_TERM);
571
571
  if (r.ok && verb === "start") linkTerm(state, process.env.KAIZEN_TERM, id);
572
+ if ("warn" in r && r.warn) console.log(`\n warning: ${r.warn}`);
572
573
  console.log(r.ok ? `\n ${verb === "start" ? `worktree ready: ${(r as { path: string }).path}` : `landed by ${(r as { how: string }).how}`}\n` : `\n ${r.why}\n`);
573
574
  process.exit(r.ok ? 0 : 1);
574
575
  }
575
576
 
577
+ // A worktree run's second agent. `start` exits 3 for "build here": no board, or none answered.
578
+ if (args.has("handoff")) {
579
+ const [, verb = "", first = ""] = Bun.argv.slice(2).filter((a) => !a.startsWith("-"));
580
+ const { projectFromWorktree } = await import("./worktree.ts");
581
+ const h = await import("./handoff.ts");
582
+ // A worktree holds committed .kaizen spec copies, never the run: always the project's own.
583
+ const state = join(projectFromWorktree(process.cwd()), ".kaizen");
584
+ const usage = () => { console.log('\n usage: kaizen handoff start <run-id> | done | blocked "<reason>"\n'); process.exit(1); };
585
+ if (verb === "start") {
586
+ if (!first) usage();
587
+ const asked = h.request(state, first, process.env.KAIZEN_TERM);
588
+ if (!asked || !(await h.awaitBoard(state, first))) { console.log("\n no board terminal to hand to: build here, in the worktree\n"); process.exit(3); }
589
+ console.log("\n handed off: end your turn, the board wakes you when it ends\n");
590
+ process.exit(0);
591
+ }
592
+ const id = process.env.KAIZEN_RUN_ID;
593
+ if ((verb !== "done" && verb !== "blocked") || !id) usage();
594
+ const why = h.finish(state, id!, verb as "done" | "blocked", verb === "blocked" ? first : undefined);
595
+ console.log(why ? `\n ${why}\n` : `\n handoff ${verb}\n`);
596
+ process.exit(why ? 1 : 0);
597
+ }
598
+
576
599
  // Deleting runs is a job for code with a test, not for an agent with `rm`. Lists by
577
600
  // default; --yes is what deletes.
578
601
  if (args.has("prune")) {
579
- const { locate, pruneRuns } = await import("./state.ts");
602
+ const { locate, pruneRuns, pruneSessions } = await import("./state.ts");
580
603
  const { listSettings } = await import("./settings.ts");
581
604
  const state = locate();
582
605
  if (!state) { console.log("\n no .kaizen here\n"); process.exit(1); }
583
606
  const keep = Number(listSettings(await resolveRepoQuietly()).rows.find((r) => r.key === "state.keep_runs")?.value) || 20;
584
607
  const apply = args.has("--yes");
608
+ // Records first: run deletion would orphan more of them, and the listing must match what --yes deletes.
609
+ const records = pruneSessions(state, apply).length;
585
610
  const gone = pruneRuns(state, keep, apply);
586
611
  console.log(gone.length
587
612
  ? `\n ${apply ? "pruned" : "would prune"} ${gone.length} finished run(s), keeping the newest ${keep}:\n${gone.map((g) => ` ${g.id}${g.rescued ? c.dim(` ${g.rescued} open item(s) ${apply ? "moved" : "to move"} to backlog.md`) : ""}`).join("\n")}\n${apply ? "" : `\n ${c.dim("nothing deleted — run:")} ${c.accent("kaizen prune --yes")}\n`}`
588
613
  : `\n nothing to prune ${c.dim(`(${keep} finished runs are kept)`)}\n`);
614
+ if (records) console.log(` ${apply ? "pruned" : "would prune"} ${records} dead launch record(s) older than a week${apply ? "" : ` ${c.dim("— run:")} ${c.accent("kaizen prune --yes")}`}\n`);
589
615
  process.exit(0);
590
616
  }
591
617