kaizen-agent 1.62.0 → 1.64.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 (51) hide show
  1. package/cli/automations.test.ts +167 -0
  2. package/cli/automations.ts +298 -0
  3. package/cli/dashboard.ts +1 -7
  4. package/cli/handoff.test.ts +133 -0
  5. package/cli/handoff.ts +122 -0
  6. package/cli/install.test.ts +16 -0
  7. package/cli/install.ts +92 -191
  8. package/cli/look.ts +33 -0
  9. package/cli/pty.ts +16 -2
  10. package/cli/resources.test.ts +50 -0
  11. package/cli/resources.ts +113 -0
  12. package/cli/restart.test.ts +28 -1
  13. package/cli/settings.ts +6 -2
  14. package/cli/setup.test.ts +22 -2
  15. package/cli/setup.ts +101 -51
  16. package/cli/sources.ts +1 -1
  17. package/cli/state.test.ts +7 -0
  18. package/cli/state.ts +13 -2
  19. package/cli/usage.test.ts +11 -0
  20. package/cli/web.ts +134 -6
  21. package/cli/workers.ts +11 -4
  22. package/cli/worktree.test.ts +174 -1
  23. package/cli/worktree.ts +190 -35
  24. package/package.json +1 -1
  25. package/skills/kaizen/config.default.yml +17 -0
  26. package/skills/kaizen/settings.md +4 -0
  27. package/skills/kaizen/spec-build.md +13 -0
  28. package/skills/kaizen/spec-main.md +13 -0
  29. package/skills/kaizen-help/SKILL.md +1 -0
  30. package/skills/media/kaizen-deck/SKILL.md +21 -2
  31. package/skills/media/kaizen-deck/scripts/motion.py +99 -0
  32. package/web/board/cards.ts +1 -0
  33. package/web/board/git.ts +4 -4
  34. package/web/board/phone.ts +5 -5
  35. package/web/board/resources.ts +152 -0
  36. package/web/board/run-view.ts +107 -1
  37. package/web/board/search.ts +6 -0
  38. package/web/board/settings-automations.ts +71 -0
  39. package/web/board/settings-pages.test.ts +4 -0
  40. package/web/board/settings-pages.ts +2 -1
  41. package/web/board/settings.ts +10 -3
  42. package/web/board/workspace.ts +7 -1
  43. package/web/board/ws-tabs.test.ts +20 -1
  44. package/web/board/ws-tabs.ts +26 -7
  45. package/web/board.html +20 -3
  46. package/web/board.js +119 -88
  47. package/web/notebook.js +23 -23
  48. package/web/notes.html +1 -0
  49. package/web/term.js +1 -1
  50. package/web/video.html +1 -0
  51. package/web/video.js +49 -49
package/cli/worktree.ts CHANGED
@@ -1,19 +1,20 @@
1
1
  // One branch and one git worktree per run, so agents building at the same time never
2
2
  // share a working folder. Run notes stay in the project's .kaizen/runs/<id>/; only the
3
3
  // code lives in the worktree. Every git call is an argv array, never a shell string.
4
- import { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync, realpathSync } from "node:fs";
4
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync, renameSync, realpathSync } from "node:fs";
5
5
  import { join, dirname, resolve, sep } from "node:path";
6
+ import { homedir } from "node:os";
6
7
  import { branchesOf } from "./add-project.ts";
7
8
 
8
9
  export type Out = { ok: boolean; out: string; why: string };
9
- export type Run = (cmd: string[], cwd: string) => Out;
10
+ export type Run = (cmd: string[], cwd: string, ms?: number) => Out;
10
11
 
11
12
  const SLUG = /^\d{4}-\d{2}-\d{2}-[a-z0-9][a-z0-9-]*$/;
12
13
  const env = { ...process.env, GIT_TERMINAL_PROMPT: "0" };
13
14
 
14
- export const run: Run = (cmd, cwd) => {
15
+ export const run: Run = (cmd, cwd, ms = 120_000) => {
15
16
  try {
16
- const r = Bun.spawnSync(cmd, { cwd, env, stdin: "ignore", timeout: 120_000, windowsHide: true });
17
+ const r = Bun.spawnSync(cmd, { cwd, env, stdin: "ignore", timeout: ms, windowsHide: true });
17
18
  const out = r.stdout.toString().trimEnd(), err = r.stderr.toString().trim();
18
19
  return { ok: r.exitCode === 0, out, why: (err || out).split("\n").pop() || `${cmd[0]} did not finish` };
19
20
  } catch { return { ok: false, out: "", why: `${cmd[0]} is not installed` }; }
@@ -52,8 +53,20 @@ const baseOf = (project: string) => {
52
53
  return head.ok ? head.out.replace(/^origin\//, "") : "main";
53
54
  };
54
55
 
55
- /** Makes the run's worktree and branch off the remote default branch and records both. */
56
- export function startWorktree(project: string, id: string): { ok: true; path: string; branch: string } | { ok: false; why: string } {
56
+ /** The feature branch a run was cut from and lands on, or null for the remote default branch. */
57
+ const localBase = (project: string, id: string): string | null => {
58
+ try { const b = JSON.parse(readFileSync(file(project, id), "utf8")).base_branch; return typeof b === "string" && b ? b : null; } catch { return null; }
59
+ };
60
+ const baseOfRun = (project: string, id: string) => localBase(project, id) ?? baseOf(project);
61
+ // The ref that proves a run's work is on its base: local for a feature branch, which may never be pushed.
62
+ const baseRef = (project: string, id: string) => localBase(project, id) ?? `origin/${baseOf(project)}`;
63
+
64
+ /**
65
+ * Makes the run's worktree and branch and records both. Off the remote default branch, or,
66
+ * when the project is on another branch, off that local branch, unpushed commits included,
67
+ * recorded as `base_branch`. `warn` names uncommitted changes, which a worktree never carries.
68
+ */
69
+ export function startWorktree(project: string, id: string): { ok: true; path: string; branch: string; warn?: string } | { ok: false; why: string } {
57
70
  if (!SLUG.test(id)) return { ok: false, why: `"${id}" is not a run id` };
58
71
  if (!existsSync(file(project, id))) return { ok: false, why: "no such run" };
59
72
  if (!git(project, "rev-parse", "--is-inside-work-tree").ok) return { ok: false, why: "not a git repository" };
@@ -62,21 +75,126 @@ export function startWorktree(project: string, id: string): { ok: true; path: st
62
75
  if (!git(project, "remote").out) return { ok: false, why: "no git remote to branch from" };
63
76
  const f = git(project, "fetch", "origin");
64
77
  if (!f.ok) return { ok: false, why: `fetch failed: ${f.why}` };
65
- const base = `origin/${baseOf(project)}`;
78
+ const here = git(project, "symbolic-ref", "--short", "-q", "HEAD"), feature = here.ok && here.out && here.out !== baseOf(project) ? here.out : null;
79
+ const base = feature ?? `origin/${baseOf(project)}`;
66
80
  const exists = git(project, "rev-parse", "--verify", "--quiet", `refs/heads/${branch}`).ok;
67
81
  const add = git(project, "worktree", "add", ...(exists ? [path, branch] : [path, "--no-track", "-b", branch, base]));
68
82
  if (!add.ok) return { ok: false, why: add.why };
69
- patchState(project, id, { worktree: path, branch });
70
- return { ok: true, path, branch };
83
+ patchState(project, id, { worktree: path, branch, ...(feature ? { base_branch: feature, base_sha: git(project, "rev-parse", "HEAD").out } : {}) });
84
+ const dirty = feature ? git(project, "status", "--porcelain").out : "";
85
+ return { ok: true, path, branch, ...(dirty ? { warn: `uncommitted changes in ${feature} are not in the worktree:\n${dirty}` } : {}) };
86
+ }
87
+
88
+ export type LandKind = "conflict" | "check" | "merge";
89
+ export type Landed = { ok: true; how: "pr" | "push" | "merge"; url?: string } | { ok: false; why: string; kind?: LandKind; paths?: string[] };
90
+ type Failed = Extract<Landed, { ok: false }>;
91
+
92
+ // The project's own config over the global one; the defaults are safe: nothing auto-resolves.
93
+ // Read here because settings.ts loads state.ts, which loads this file.
94
+ const readGit = (text: string, key: string) => {
95
+ const m = new RegExp(`^git:[^\\n]*\\n(?:(?:[ \\t]+[^\\n]*|)\\n)*?[ \\t]+${key}:[ \\t]*([^\\n]*)`, "m").exec(text.replace(/\r\n/g, "\n"));
96
+ return m ? m[1]!.split(" #")[0]!.trim().replace(/^["']|["']$/g, "") : null;
97
+ };
98
+ const gitSetting = (project: string, key: string, fallback: string) => {
99
+ for (const f of [join(project, ".kaizen", "config.yml"), join(homedir(), ".kaizen", "config.yml")]) {
100
+ try { const v = readGit(readFileSync(f, "utf8"), key); if (v !== null) return v; } catch { /* no such file */ }
101
+ }
102
+ return fallback;
103
+ };
104
+ const LONG = 30 * 60_000; // a project's check or rebuild may outlast a git call
105
+ const shell = (cmd: string) => ["sh", "-c", cmd];
106
+
107
+ /** The command `git.land_check` stands for in `dir`, or null for none. */
108
+ function landCheck(project: string, dir: string): string | null {
109
+ const v = gitSetting(project, "land_check", "auto");
110
+ if (v === "off" || v === "") return null;
111
+ if (v !== "auto") return v;
112
+ try {
113
+ const t = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")).scripts?.test;
114
+ if (typeof t !== "string" || /no test specified/.test(t)) return null;
115
+ return existsSync(join(dir, "bun.lock")) || existsSync(join(dir, "bun.lockb")) ? "bun run test" : "npm test";
116
+ } catch { return null; }
117
+ }
118
+
119
+ /**
120
+ * Rebases the worktree onto `ref`. Conflicts only in `git.generated` paths take the base's
121
+ * side and are rebuilt in one commit; anything else aborts, leaving the branch as it was.
122
+ * A failed rebuild or check puts the branch back too, so a retry runs the check again.
123
+ */
124
+ function rebaseOnto(project: string, dir: string, ref: string, sh: Run): Failed | null {
125
+ const before = sh(["git", "rev-parse", "HEAD"], dir).out;
126
+ const behind = sh(["git", "rev-list", "--count", `HEAD..${ref}`], dir);
127
+ if (!behind.ok) return { ok: false, kind: "merge", why: `cannot compare with ${ref}: ${behind.why}` };
128
+ if (Number(behind.out) === 0) return null;
129
+ const globs = gitSetting(project, "generated", "").split(/[\s,]+/).filter(Boolean).map((p) => new Bun.Glob(p));
130
+ const generated = (p: string) => globs.some((g) => g.match(p));
131
+ const giveUp = (why: string, paths?: string[]): Failed => {
132
+ sh(["git", "rebase", "--abort"], dir);
133
+ return { ok: false, kind: "conflict", why: `${why}; worktree kept`, ...(paths ? { paths } : {}) };
134
+ };
135
+ const rebuild = gitSetting(project, "rebuild_on_land", "");
136
+ let resolved = false, rb = sh(["git", "rebase", ref], dir);
137
+ while (!rb.ok) {
138
+ const paths = sh(["git", "diff", "--name-only", "--diff-filter=U"], dir).out.split("\n").filter(Boolean);
139
+ if (!paths.length) return giveUp(`rebase onto ${ref} stopped: ${rb.why}`);
140
+ // With nothing to rebuild it, taking the base's side would drop the branch's change.
141
+ const real = rebuild ? paths.filter((p) => !generated(p)) : paths;
142
+ if (real.length) return giveUp(`rebase onto ${ref} conflicts in ${real.join(", ")}`, real);
143
+ // In a rebase "ours" is the base. A file deleted on the base has no such side: not routine.
144
+ if (!sh(["git", "checkout", "--ours", "--", ...paths], dir).ok || !sh(["git", "add", "--", ...paths], dir).ok) return giveUp(`could not resolve ${paths.join(", ")}`, paths);
145
+ resolved = true;
146
+ // A commit that changed only generated files has nothing left.
147
+ const empty = sh(["git", "diff", "--cached", "--quiet"], dir).ok;
148
+ rb = sh(empty ? ["git", "rebase", "--skip"] : ["git", "-c", "core.editor=true", "rebase", "--continue"], dir);
149
+ }
150
+ const back = (why: string): Failed => { sh(["git", "reset", "--hard", before], dir); return { ok: false, kind: "check", why: `${why}; branch put back, worktree kept` }; };
151
+ if (resolved && rebuild) {
152
+ const b = sh(shell(rebuild), dir, LONG);
153
+ if (!b.ok) return back(`rebuild failed: ${b.why}`);
154
+ const made = sh(["git", "ls-files", "-m", "-o", "--exclude-standard"], dir).out.split("\n").filter(generated);
155
+ if (made.length) {
156
+ sh(["git", "add", "--", ...made], dir);
157
+ const c = sh(["git", "commit", "-qm", "chore: rebuild generated files"], dir);
158
+ if (!c.ok) return back(`rebuild commit failed: ${c.why}`);
159
+ }
160
+ sh(["git", "reset", "--hard", "HEAD"], dir);
161
+ }
162
+ const check = landCheck(project, dir);
163
+ if (check) {
164
+ const c = sh(shell(check), dir, LONG);
165
+ if (!c.ok) return back(`check failed (${check}): ${c.why}`);
166
+ sh(["git", "reset", "--hard", "HEAD"], dir); // a check that rewrites tracked files is not the work
167
+ }
168
+ return null;
71
169
  }
72
170
 
73
- export type Landed = { ok: true; how: "pr" | "push"; url?: string } | { ok: false; why: string };
171
+ /** Pushes the run's own branch; a rebased one replaces its pushed self under a lease. Never the base. */
172
+ function pushBranch(dir: string, branch: string, sh: Run) {
173
+ const old = sh(["git", "rev-parse", "--verify", "--quiet", `refs/remotes/origin/${branch}`], dir);
174
+ const rewrote = old.ok && old.out && !sh(["git", "merge-base", "--is-ancestor", old.out, "HEAD"], dir).ok;
175
+ return sh(["git", "push", ...(rewrote ? [`--force-with-lease=refs/heads/${branch}:${old.out}`] : []), "-u", "origin", `HEAD:refs/heads/${branch}`], dir);
176
+ }
177
+
178
+ const landFile = (project: string, id: string) => join(project, ".kaizen", "runs", id, "land.json");
179
+ const clearLand = (project: string, id: string) => rmSync(landFile(project, id), { force: true });
180
+
181
+ /** `kaizen worktree land`: lands, then leaves what stopped it on the run for the board. */
182
+ export function landRun(project: string, id: string, term?: string): Landed {
183
+ const r = landWorktree(project, id);
184
+ if (r.ok) clearLand(project, id);
185
+ else if (SLUG.test(id) && codeDir(project, id) !== project) { // no worktree: nothing is mid-land
186
+ const f = landFile(project, id), tmp = `${f}.${process.pid}.tmp`;
187
+ writeFileSync(tmp, JSON.stringify({ kind: r.kind ?? "merge", why: r.why, ...(r.paths ? { paths: r.paths } : {}), ...(term ? { term } : {}), at: Date.now() }));
188
+ renameSync(tmp, f);
189
+ }
190
+ return r;
191
+ }
74
192
 
75
193
  // Whether every commit of the branch is on the base, by patch: a rebase-merge rewrites
76
194
  // the hashes, so "is an ancestor" would say not landed for work that is.
77
195
  // A cherry that fails (no origin, no origin/<base>) proves nothing: not landed.
78
- const landed = (dir: string, base: string, branch: string, sh: Run = run) => {
79
- const r = sh(["git", "cherry", `origin/${base}`, branch], dir);
196
+ const landed = (dir: string, ref: string, branch: string, sh: Run = run) => {
197
+ const r = sh(["git", "cherry", ref, branch], dir);
80
198
  return r.ok && r.out.split("\n").every((l) => !l.startsWith("+"));
81
199
  };
82
200
 
@@ -94,10 +212,31 @@ export function landWorktree(project: string, id: string, sh: Run = run,
94
212
  if (dir === project) return { ok: false, why: "this run has no worktree" };
95
213
  const clean = (d: string) => !sh(["git", "status", "--porcelain"], d).out;
96
214
  if (!clean(dir)) return { ok: false, why: "the worktree has uncommitted changes; commit them first" };
215
+ const feature = localBase(project, id);
216
+ if (feature) {
217
+ // Never push, stash or switch: the project folder may be in use. Anything but a clean merge stops here.
218
+ const on = sh(["git", "symbolic-ref", "--short", "-q", "HEAD"], project).out;
219
+ if (on !== feature) return { ok: false, why: `the project folder is on ${on || "a detached HEAD"}, not ${feature}; switch to it and land again. Worktree kept` };
220
+ // Nothing was built: keep the branch rather than call that landed.
221
+ const tip = sh(["git", "rev-parse", branch], project).out, from = JSON.parse(readFileSync(file(project, id), "utf8")).base_sha;
222
+ if (tip && tip === from) return { ok: false, why: `${branch} has no commits of its own; worktree kept` };
223
+ // Already merged (a retry after the worktree would not go): only the cleanup is left.
224
+ if (!sh(["git", "merge-base", "--is-ancestor", branch, "HEAD"], project).ok) {
225
+ const stop = rebaseOnto(project, dir, feature, sh);
226
+ if (stop) return stop;
227
+ const m = sh(["git", "merge", "--no-edit", branch], project);
228
+ if (!m.ok) { sh(["git", "merge", "--abort"], project); return { ok: false, kind: "conflict", why: `merge into ${feature} failed: ${m.why}; worktree kept` }; }
229
+ }
230
+ const rm = git(project, "worktree", "remove", "--force", dir);
231
+ if (!rm.ok) return { ok: false, why: `merged, but the worktree stays: ${rm.why}` };
232
+ git(project, "branch", "-D", branch);
233
+ patchState(project, id, { worktree: null, branch: null });
234
+ return { ok: true, how: "merge" };
235
+ }
97
236
  const base = baseOf(project);
98
237
  const finish = (how: "pr" | "push", url?: string): Landed => {
99
238
  git(project, "fetch", "origin");
100
- if (!landed(dir, base, branch)) return { ok: false, why: `${how === "pr" ? "the pull request" : "the push"} went through but ${branch} is not on ${base} yet; worktree kept` };
239
+ if (!landed(dir, `origin/${base}`, branch)) return { ok: false, why: `${how === "pr" ? "the pull request" : "the push"} went through but ${branch} is not on ${base} yet; worktree kept` };
101
240
  // The worktree is clean (checked above); --force is only for the untracked node_modules link.
102
241
  const rm = git(project, "worktree", "remove", "--force", dir);
103
242
  if (!rm.ok) return { ok: false, why: `landed, but the worktree stays: ${rm.why}` };
@@ -107,35 +246,42 @@ export function landWorktree(project: string, id: string, sh: Run = run,
107
246
  return { ok: true, how, url };
108
247
  };
109
248
 
110
- const push = sh(["git", "push", "-u", "origin", branch], dir);
111
- if (!push.ok) return { ok: false, why: `push of ${branch} failed: ${push.why}` };
249
+ const ref = `origin/${base}`;
250
+ const fetched = sh(["git", "fetch", "--prune", "origin"], dir);
251
+ if (!fetched.ok) return { ok: false, kind: "merge", why: `fetch failed: ${fetched.why}` };
252
+ // A retry after the merge went through: only the cleanup is left, and a rebase would empty the branch.
253
+ if (Number(sh(["git", "rev-list", "--count", `${ref}..${branch}`], dir).out) > 0 && landed(dir, ref, branch, sh)) return finish("push");
112
254
 
113
255
  if (hasGh) {
256
+ const stop = rebaseOnto(project, dir, ref, sh);
257
+ if (stop) return stop;
258
+ const push = pushBranch(dir, branch, sh);
259
+ if (!push.ok) return { ok: false, kind: "merge", why: `push of ${branch} failed: ${push.why}` };
114
260
  const subject = git(dir, "log", "-1", "--format=%s").out;
115
261
  const pr = sh(["gh", "pr", "create", "--base", base, "--head", branch, "--title", subject, "--body", `Run ${id}.`], dir);
116
262
  // An existing pull request for the branch is fine: merge that one.
117
263
  const url = pr.ok ? pr.out.split("\n").pop() : undefined;
118
264
  // gh prints the "already exists" line, then the URL, and `why` holds only the last line.
119
- if (!pr.ok && !/already exists|\/pull\/\d+$/i.test(pr.why)) return { ok: false, why: `pull request failed: ${pr.why}; ${branch} is pushed` };
265
+ if (!pr.ok && !/already exists|\/pull\/\d+$/i.test(pr.why)) return { ok: false, kind: "merge", why: `pull request failed: ${pr.why}; ${branch} is pushed` };
120
266
  const merge = sh(["gh", "pr", "merge", branch, "--rebase"], dir);
121
- if (!merge.ok) return { ok: false, why: `pull request not merged (${merge.why}); left open, worktree kept` };
267
+ if (!merge.ok) return { ok: false, kind: "merge", why: `pull request not merged (${merge.why}); left open, worktree kept` };
122
268
  return finish("pr", url);
123
269
  }
124
270
 
125
271
  for (let i = 0; i < 2; i++) {
126
- const f = sh(["git", "fetch", "origin"], dir);
127
- if (!f.ok) return { ok: false, why: `fetch failed: ${f.why}` };
128
- const rb = sh(["git", "rebase", `origin/${base}`], dir);
129
- if (!rb.ok) { sh(["git", "rebase", "--abort"], dir); return { ok: false, why: `rebase onto ${base} conflicts: ${rb.why}; worktree kept` }; }
272
+ const f = sh(["git", "fetch", "--prune", "origin"], dir);
273
+ if (!f.ok) return { ok: false, kind: "merge", why: `fetch failed: ${f.why}` };
274
+ const stop = rebaseOnto(project, dir, ref, sh);
275
+ if (stop) return stop;
130
276
  if (sh(["git", "push", "origin", `HEAD:${base}`], dir).ok) return finish("push");
131
277
  }
132
- return { ok: false, why: `${base} kept moving; push rejected twice. Worktree kept` };
278
+ return { ok: false, kind: "merge", why: `${base} kept moving; push rejected twice. Worktree kept` };
133
279
  }
134
280
 
135
281
  // ---- the Git tab: a run's branch, its pull request and its cleanup, one step at a time
136
282
 
137
283
  export type Pr = { number: number; url: string; state: "OPEN" | "MERGED" | "CLOSED"; draft: boolean };
138
- export type Branch = { branch: string; base: string; upstream: boolean; landed: boolean; gh: boolean; pr: Pr | null; checking: boolean };
284
+ export type Branch = { branch: string; base: string; local?: boolean; upstream: boolean; landed: boolean; gh: boolean; pr: Pr | null; checking: boolean };
139
285
  // The calls that wait on a network (push, fetch, gh): never on the board server's thread.
140
286
  export type AsyncRun = (cmd: string[], cwd: string) => Promise<Out>;
141
287
 
@@ -168,10 +314,12 @@ export function branchState(project: string, id: string, changed: () => void = (
168
314
  if (!SLUG.test(id)) return null;
169
315
  const dir = codeDir(project, id);
170
316
  if (dir === project) return null; // committed in the project's own checkout: no branch of its own
171
- const branch = branchOf(id), base = baseOf(project);
317
+ const branch = branchOf(id), base = baseOfRun(project, id), ref = baseRef(project, id);
318
+ // A feature base may never have been pushed: it lands by local merge, with no pull request.
319
+ const gh = hasGh && !localBase(project, id);
172
320
  const upstream = sh(["git", "rev-parse", "--abbrev-ref", `${branch}@{u}`], dir).ok;
173
321
  const k = prKey(project, id), hit = prs.get(k);
174
- if (hasGh && (!hit || Date.now() - hit.at >= 30_000) && !looking.has(k)) {
322
+ if (gh && (!hit || Date.now() - hit.at >= 30_000) && !looking.has(k)) {
175
323
  looking.add(k);
176
324
  void ash(["gh", "pr", "view", branch, ...PR_JSON], dir).then((r) => {
177
325
  looking.delete(k);
@@ -183,9 +331,9 @@ export function branchState(project: string, id: string, changed: () => void = (
183
331
  }
184
332
  const pr = hit?.pr ?? null;
185
333
  // Landed counts only work that is on the base: a branch with no commits of its own is not "merged".
186
- const own = sh(["git", "rev-list", "--count", `origin/${base}..${branch}`], dir);
187
- const landedNow = pr?.state === "MERGED" || (own.ok && Number(own.out) > 0 && landed(dir, base, branch, sh));
188
- return { branch, base, upstream, landed: landedNow, gh: hasGh, pr, checking: hasGh && !hit };
334
+ const own = sh(["git", "rev-list", "--count", `${ref}..${branch}`], dir);
335
+ const landedNow = pr?.state === "MERGED" || (own.ok && Number(own.out) > 0 && landed(dir, ref, branch, sh));
336
+ return { branch, base, local: !!localBase(project, id), upstream, landed: landedNow, gh: gh, pr, checking: gh && !hit };
189
337
  }
190
338
 
191
339
  /** Pushes the branch, then opens its pull request against the base. */
@@ -193,12 +341,13 @@ export async function openPr(project: string, id: string, title: string, body: s
193
341
  if (!SLUG.test(id)) return { ok: false, why: `"${id}" is not a run id` };
194
342
  const dir = codeDir(project, id), branch = branchOf(id);
195
343
  if (dir === project) return { ok: false, why: "This run has no branch of its own." };
344
+ if (localBase(project, id)) return { ok: false, why: "This run lands by a local merge into its branch, with no pull request." };
196
345
  if (!hasGh) return { ok: false, why: "Pull requests need the GitHub CLI (gh) and a GitHub remote." };
197
346
  if (!title.trim()) return { ok: false, why: "A pull request needs a title." };
198
347
  if (sh(["git", "status", "--porcelain"], dir).out) return { ok: false, why: "Commit the changes first." };
199
348
  const push = await ash(["git", "push", "-u", "origin", branch], dir);
200
349
  if (!push.ok) return { ok: false, why: `Push of ${branch} failed: ${push.why}` };
201
- const r = await ash(["gh", "pr", "create", "--base", baseOf(project), "--head", branch, "--title", title.trim(), "--body", body, ...(draft ? ["--draft"] : [])], dir);
350
+ const r = await ash(["gh", "pr", "create", "--base", baseOfRun(project, id), "--head", branch, "--title", title.trim(), "--body", body, ...(draft ? ["--draft"] : [])], dir);
202
351
  // An existing pull request for the branch is fine: show that one.
203
352
  if (!r.ok && !/already exists/i.test(r.why)) return { ok: false, why: `Pull request failed: ${r.why}` };
204
353
  const pr = parsePr(await ash(["gh", "pr", "view", branch, ...PR_JSON], dir));
@@ -211,6 +360,7 @@ export async function mergePr(project: string, id: string, sh: Run = run, ash: A
211
360
  if (!SLUG.test(id)) return { ok: false, why: `"${id}" is not a run id` };
212
361
  const dir = codeDir(project, id), branch = branchOf(id);
213
362
  if (dir === project) return { ok: false, why: "This run has no branch of its own." };
363
+ if (localBase(project, id)) return { ok: false, why: "This run lands by a local merge: run kaizen worktree land." };
214
364
  if (!hasGh) return { ok: false, why: "Merging needs the GitHub CLI (gh) and a GitHub remote." };
215
365
  const r = await ash(["gh", "pr", "merge", branch, "--rebase"], dir);
216
366
  prs.delete(prKey(project, id));
@@ -228,19 +378,22 @@ export async function removeWorktree(project: string, id: string, sh: Run = run,
228
378
  const dir = codeDir(project, id), branch = branchOf(id);
229
379
  if (dir === project) return { ok: false, why: "This run has no worktree." };
230
380
  if (sh(["git", "status", "--porcelain"], dir).out) return { ok: false, why: "The worktree has uncommitted changes. Commit or discard them first." };
231
- const f = await ash(["git", "fetch", "origin"], project);
232
- if (!f.ok) return { ok: false, why: `Could not fetch origin, so nothing proves the work is on the base: ${f.why}` };
233
- const base = baseOf(project);
234
- if (!sh(["git", "rev-parse", "--verify", "--quiet", `origin/${base}`], project).ok) return { ok: false, why: `origin/${base} does not exist, so nothing proves the work is on it.` };
235
- if (!landed(dir, base, branch, sh)) return { ok: false, why: `${branch} has commits that are not on ${base} yet. Merge its pull request first.` };
381
+ const feature = localBase(project, id), base = feature ?? baseOf(project), ref = baseRef(project, id);
382
+ if (!feature) {
383
+ const f = await ash(["git", "fetch", "origin"], project);
384
+ if (!f.ok) return { ok: false, why: `Could not fetch origin, so nothing proves the work is on the base: ${f.why}` };
385
+ }
386
+ if (!sh(["git", "rev-parse", "--verify", "--quiet", ref], project).ok) return { ok: false, why: `${ref} does not exist, so nothing proves the work is on it.` };
387
+ if (!landed(dir, ref, branch, sh)) return { ok: false, why: `${branch} has commits that are not on ${base} yet. Merge its pull request first.` };
236
388
  // Clean (checked above); --force is only for the untracked node_modules link.
237
389
  const rm = sh(["git", "worktree", "remove", "--force", dir], project);
238
390
  if (!rm.ok) return { ok: false, why: rm.why };
239
391
  // Every commit is on the base by patch, so -D loses nothing a rebase-merge rewrote.
240
392
  sh(["git", "branch", "-D", "--", branch], project);
241
- await ash(["git", "push", "origin", "--delete", branch], project); // best effort: GitHub may have deleted it
393
+ if (!feature) await ash(["git", "push", "origin", "--delete", branch], project); // best effort: GitHub may have deleted it
242
394
  prs.delete(prKey(project, id));
243
395
  patchState(project, id, { worktree: null, branch: null });
396
+ clearLand(project, id);
244
397
  return { ok: true };
245
398
  }
246
399
 
@@ -319,6 +472,8 @@ export const linkTerm = (state: string, key: string | undefined, id: string) =>
319
472
  mkdirSync(join(state, "sessions"), { recursive: true });
320
473
  writeFileSync(termFile(state, key), id);
321
474
  };
475
+ /** The first agent of a handed-off run stays where it is: its tab does not follow the worktree. */
476
+ export const unlinkTerm = (state: string, key: string) => { rmSync(termFile(state, key), { force: true }); };
322
477
  /** The worktree a linked terminal's live run is in; null when it has no link, the run ended, or the worktree is gone. */
323
478
  export function linkedWs(state: string, key: string): string | null {
324
479
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kaizen-agent",
3
- "version": "1.62.0",
3
+ "version": "1.64.0",
4
4
  "description": "Staged workflow for AI agents — code, writing, research, operations: plan, human approval, build, independent review, bounded fix loop.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -109,6 +109,16 @@ git:
109
109
  # ask: the plan approval offers a new worktree or the current folder; auto mode takes
110
110
  # a new worktree. true always makes one, false never does.
111
111
  worktree_per_run: ask
112
+ # Landing rebases the branch onto its base first. Path patterns, space-separated, of
113
+ # files safe to take from the base on a conflict; any other conflict stops the land.
114
+ # Empty: nothing is resolved automatically. Needs rebuild_on_land: without it a
115
+ # conflict stops the land, since nothing would remake the file.
116
+ generated: ""
117
+ # Command that remakes the generated files, run once when any was resolved.
118
+ rebuild_on_land: ""
119
+ # Runs after a rebase that pulled commits; failing stops the land.
120
+ # auto: the test script in package.json, if any. off: none. Anything else: a command.
121
+ land_check: auto
112
122
 
113
123
  orchestration:
114
124
  # true: a plan may split into workers (a `## Workers` section you approve with the plan).
@@ -182,6 +192,13 @@ agent:
182
192
  # Stops idle sleep from the board. off | auto (while the board runs agents) | on
183
193
  # (while the board is open). Linux and macOS; agents in an outside terminal don't count.
184
194
  keep_awake: off
195
+ # The model each tool launches with, the tool's own name. Empty: its default.
196
+ # Claude Code's stage subagents use subagents.model instead.
197
+ model:
198
+ agy: ""
199
+ codex: ""
200
+ gemini: ""
201
+ opencode: ""
185
202
  # Minutes between an agent's reports. Quiet for two of these with no terminal
186
203
  # activity, its card says stale.
187
204
  heartbeat_minutes: 5
@@ -26,7 +26,11 @@ nearest first, so a change lands globally unless this project keeps its own conf
26
26
  | `review.write_memory` | `true`, `false` | Let the reviewer append lessons to `memory.md` |
27
27
  | `git.auto_commit` | `true`, `false` | Commit the work when a run finishes |
28
28
  | `git.worktree_per_run` | `ask`, `true`, `false` | Build each run on its own branch in its own worktree and land it by pull request; `ask` offers the choice at the plan approval |
29
+ | `git.generated` | text | Space-separated path patterns a land may take from the base on a conflict; empty resolves nothing |
30
+ | `git.rebuild_on_land` | text | Command that remakes generated files after they were resolved |
31
+ | `git.land_check` | `auto`, `off`, or a command | Runs after a rebase that pulled commits; a failure stops the land |
29
32
  | `ui.mouse` | `false`, `true` | Click to select, click again to act; while on, the terminal cannot select text |
33
+ | `agent.model.<tool>` | the tool's own model name, or empty | Launch model for agy, codex, gemini, opencode, for every stage |
30
34
  | `subagents.model` | `inherit`, `opus`, `sonnet`, `haiku` | Model the stage subagents run on (Claude Code only) |
31
35
  | `subagents.effort` | `inherit`, `low`, `medium`, `high` | Reasoning effort for the stage subagents (Claude Code only) |
32
36
  | `sources.every` | `off`, `1h`, `6h`, `24h` | How often the web board checks request sources for new requests, into the icebox, while it runs |
@@ -55,6 +55,19 @@ code in the same folder. If `kaizen worktree start` fails, say why and stop; do
55
55
  back to the project folder unasked. A run whose `state.json` has no `worktree` builds in
56
56
  place, exactly as before.
57
57
 
58
+ **Hand the build to a second agent, when the run gets a worktree.** The agent the user is
59
+ talking to stays with them. Before `kaizen worktree start`, it writes into `02-approval.md`
60
+ every decision made in chat that the plan lacks: the second agent never sees the chat. After
61
+ it, it runs `kaizen handoff start <id>`. Exit 0: say the worktree agent is building, and end
62
+ the turn; the board types a one-line pointer into this terminal when that agent ends. Exit
63
+ 3: no board terminal or none answered, so build here in the worktree as above. The second
64
+ agent reads the run's files, runs build, review and the fix loop in the worktree, under the
65
+ same rules (it is the coordinator if the plan has approved workers), and ends with
66
+ `kaizen handoff done` or `kaizen handoff blocked "<reason>"`. It never runs `kaizen done`
67
+ or `kaizen worktree land`. It takes no bypass from Orchestration. `runs/<id>/handoff.json`
68
+ is written only by these commands and the board. A worktree cut while the project is on a
69
+ branch other than the default is cut from that local branch and records `base_branch`.
70
+
58
71
  **Workers, only when the run has them.** When `01-plan.md` has a `## Workers` section and
59
72
  `02-approval.md` says `workers: approved`, the build agent is the coordinator. Run
60
73
  `kaizen worker init`: if it refuses, say why in `03-impl.md` and build the whole plan
@@ -90,6 +90,19 @@ subagents at all.
90
90
 
91
91
  ---
92
92
 
93
+ ## After a handoff
94
+
95
+ Woken by the line `kaizen run <id>: the worktree agent ended (...)`, or asked about the run,
96
+ read `state.json`, `handoff.json`, `03-impl.md` and `04-review.md`, whatever the line says:
97
+ it is a pointer, not a result. `done`: report what changed, the checks and open findings,
98
+ then take the final approval and land as usual; in `auto` carry on without stopping.
99
+ `blocked`, `failed` or `quiet`: say why and what is left, and keep the worktree. `quiet` means the second agent went silent and may still report; `kaizen handoff start <id>` opens a new one on the same worktree. A run with
100
+ `base_branch` lands by a local merge into that branch, with no push; if the project folder
101
+ is on another branch or the merge conflicts, `kaizen worktree land` says so and keeps the
102
+
103
+ Landing rebases the branch onto its base first, in every land path: a conflict only in `git.generated` paths takes the base's side and runs `git.rebuild_on_land`, any other conflict aborts and keeps the worktree, and a rebase that pulled commits runs `git.land_check`. A branch already pushed is replaced with `--force-with-lease`, on `kaizen/<id>` only. A failure is written to `runs/<id>/land.json` and cleared on success; the board shows it as `Conflict` or `Land failed` with a red `!`.
104
+ worktree, so tell the user.
105
+
93
106
  ## Preview gate
94
107
 
95
108
  Before setting `stage: "review"` after a build, in either runner, open `03-impl.md` and
@@ -33,6 +33,7 @@ anything.
33
33
  | `/kaizen gather` | Read request sources kaizen cannot read by itself; their requests land in the icebox, nothing starts |
34
34
  | `/kaizen discover` | Group what is in the icebox and promote the ideas you pick; nothing starts |
35
35
  | `/kaizen docs [lint]` | Write or refresh the project's docs vault in the notebook, which agents read first; `lint` only reports what is stale, broken or uncovered |
36
+ | `kaizen automation list\|add\|run <id>\|pause <id>\|resume <id>\|rm <id>\|runs <id>` | Schedules that start an unattended auto-mode run in this project (hourly, daily, weekdays, weekly or cron; optional precheck). Fires only while a board runs |
36
37
  | `kaizen worker init\|start <wid>\|status\|config\|merge\|set <run> on\|off` | Orchestration (off by default): split a run into workers, each in its own board terminal and folder. `kaizen worker report` is for the workers themselves |
37
38
  | `/kaizen approve` | Approve whatever the current run is waiting on |
38
39
  | `/kaizen reject <reason>` | Reject it; the reason decides revise (back to planner) vs kill (abandon) |
@@ -51,10 +51,29 @@ Run `scripts/check.sh` first on a new machine.
51
51
  For anything the helpers do not cover (triptych, recap timeline, stat rows) use
52
52
  `d.slide()`, `d.kicker()`, `d.headline()`, `d.body()` and see build.js / build-features.js
53
53
  in the reference project.
54
- 7. **QA:** `./qa.sh build-<name>.js`, look at every printed sheet (or send them to the user), fix, repeat. Clean `qa/` after.
55
- 8. **Report:** file path, the story in one line per slide, every placeholder left, every
54
+ 7. **Motion (when asked for animation or transitions):** copy in `scripts/motion.py` and run
55
+ `python3 motion.py Deck.pptx Deck-motion.pptx`, then QA the result. See "Brand theme and motion" below.
56
+ 8. **QA:** `./qa.sh build-<name>.js`, look at every printed sheet (or send them to the user), fix, repeat. Clean `qa/` after.
57
+ 9. **Report:** file path, the story in one line per slide, every placeholder left, every
56
58
  claim the user must verify, and what was deliberately left out.
57
59
 
60
+ ## Brand theme and motion
61
+
62
+ **Follow the user's brand when they name one.** Asked to match a landing page or site, read its CSS and
63
+ markup first, and use its colors, type, shapes and exact words instead of ink and gold. Pass them through the
64
+ `makeDeck` branding options, or build with `d.slide()`. Write new copy only for what the source lacks
65
+ (a researched problem, a contact slide), and say which lines are yours. Sales decks end on contact: name,
66
+ company, site, and a QR code. Do not put decks in the project repo.
67
+
68
+ **Transitions and animation:** `motion.py` adds fade and push transitions and automatic entrance fades. Name
69
+ shapes `a<N>-...` with `objectName` so the same N appears together; unnamed shapes appear one by one.
70
+
71
+ **Product footage is MP4, never GIF.** GIFs may not play in presentation apps. Render clips from real footage
72
+ with the `hyperframes` skill, then embed with
73
+ `slide.addMedia({ type: "video", path, cover: "data:image/png;base64,...", x, y, w, h })`.
74
+ `cover` must be base64. `motion.py` makes the first video on each slide autoplay, muted and looping. Renders
75
+ and QA sheets cannot show motion, so report it as unplayed until someone runs the slideshow.
76
+
58
77
  ## Agent notes (Claude Code, Codex, Gemini CLI, OpenCode, Cursor…)
59
78
  Steps name capabilities, not tools. Where your agent lacks one:
60
79
  - **web fetch** (finding stock photos, sources): ask the user for photos/links instead.
@@ -0,0 +1,99 @@
1
+ #!/usr/bin/env python3
2
+ """Add slide transitions, entrance fades and video autoplay to a built .pptx.
3
+
4
+ Usage: python3 motion.py in.pptx out.pptx
5
+
6
+ Shapes appear on their own, with no clicks. Name shapes `a<N>-anything`
7
+ (objectName in pptxgenjs) to control the order: the same N fades in together.
8
+ A slide with no such names fades its shapes in one after another.
9
+ Embedded videos play on slide entry, muted and looping.
10
+ """
11
+ import re
12
+ import struct
13
+ import sys
14
+ import zipfile
15
+
16
+ TRANSITIONS = ['<p:transition spd="med"><p:fade/></p:transition>',
17
+ '<p:transition spd="med"><p:push dir="l"/></p:transition>']
18
+ STAGGER_MS = 350
19
+ FADE_MS = 600
20
+
21
+
22
+ def mp4_ms(data):
23
+ """Duration from the mp4 mvhd box."""
24
+ i = data.find(b"mvhd")
25
+ if i < 0:
26
+ return 60000
27
+ if data[i + 4] == 1:
28
+ scale, length = struct.unpack(">IQ", data[i + 24:i + 36])
29
+ else:
30
+ scale, length = struct.unpack(">II", data[i + 16:i + 24])
31
+ return max(1, length * 1000 // scale)
32
+
33
+
34
+ def fade(ids, sid, group):
35
+ target = f'<p:tgtEl><p:spTgt spid="{sid}"/></p:tgtEl>'
36
+ return (f'<p:par><p:cTn id="{next(ids)}" presetID="10" presetClass="entr" presetSubtype="0" fill="hold" nodeType="withEffect">'
37
+ f'<p:stCondLst><p:cond delay="{200 + group * STAGGER_MS}"/></p:stCondLst><p:childTnLst>'
38
+ f'<p:set><p:cBhvr><p:cTn id="{next(ids)}" dur="1" fill="hold"><p:stCondLst><p:cond delay="0"/></p:stCondLst></p:cTn>{target}'
39
+ '<p:attrNameLst><p:attrName>style.visibility</p:attrName></p:attrNameLst></p:cBhvr><p:to><p:strVal val="visible"/></p:to></p:set>'
40
+ f'<p:animEffect transition="in" filter="fade"><p:cBhvr><p:cTn id="{next(ids)}" dur="{FADE_MS}"/>{target}</p:cBhvr></p:animEffect>'
41
+ '</p:childTnLst></p:cTn></p:par>')
42
+
43
+
44
+ def play(ids, sid, ms):
45
+ return (f'<p:par><p:cTn id="{next(ids)}" presetID="1" presetClass="mediacall" presetSubtype="0" fill="hold" nodeType="withEffect">'
46
+ '<p:stCondLst><p:cond delay="0"/></p:stCondLst><p:childTnLst><p:cmd type="call" cmd="playFrom(0.0)"><p:cBhvr>'
47
+ f'<p:cTn id="{next(ids)}" dur="{ms}" fill="hold"/><p:tgtEl><p:spTgt spid="{sid}"/></p:tgtEl></p:cBhvr></p:cmd>'
48
+ '</p:childTnLst></p:cTn></p:par>')
49
+
50
+
51
+ def timing(xml, video_ms):
52
+ ids = iter(range(4, 100000))
53
+ named = [(sid, int(g)) for sid, g in re.findall(r'<p:cNvPr id="(\d+)" name="a(\d+)-', xml)]
54
+ if not named:
55
+ found = re.findall(r'<p:(?:sp|pic)>.*?<p:cNvPr id="(\d+)"', xml, re.S)
56
+ named = [(sid, n) for n, sid in enumerate(found)]
57
+ video = next((re.search(r'<p:cNvPr id="(\d+)"', pic)[1]
58
+ for pic in re.findall(r"<p:pic>.*?</p:pic>", xml, re.S) if "videoFile" in pic), None)
59
+ if not named and not video:
60
+ return ""
61
+ inner = next(ids)
62
+ effects = "".join(fade(ids, sid, group) for sid, group in named)
63
+ media = ""
64
+ if video and video_ms:
65
+ effects += play(ids, video, video_ms)
66
+ media = (f'<p:video><p:cMediaNode vol="0"><p:cTn id="{next(ids)}" repeatCount="indefinite" fill="hold" display="0">'
67
+ f'<p:stCondLst><p:cond delay="indefinite"/></p:stCondLst></p:cTn><p:tgtEl><p:spTgt spid="{video}"/></p:tgtEl>'
68
+ '</p:cMediaNode></p:video>')
69
+ slide = '<p:tgtEl><p:sldTgt/></p:tgtEl>'
70
+ return ('<p:timing><p:tnLst><p:par><p:cTn id="1" dur="indefinite" restart="never" nodeType="tmRoot"><p:childTnLst>'
71
+ '<p:seq concurrent="1" nextAc="seek"><p:cTn id="2" dur="indefinite" nodeType="mainSeq"><p:childTnLst>'
72
+ '<p:par><p:cTn id="3" fill="hold"><p:stCondLst><p:cond delay="indefinite"/><p:cond evt="onBegin" delay="0"><p:tn val="2"/></p:cond></p:stCondLst><p:childTnLst>'
73
+ f'<p:par><p:cTn id="{inner}" fill="hold"><p:stCondLst><p:cond delay="0"/></p:stCondLst><p:childTnLst>{effects}</p:childTnLst></p:cTn></p:par>'
74
+ '</p:childTnLst></p:cTn></p:par></p:childTnLst></p:cTn>'
75
+ f'<p:prevCondLst><p:cond evt="onPrev" delay="0">{slide}</p:cond></p:prevCondLst>'
76
+ f'<p:nextCondLst><p:cond evt="onNext" delay="0">{slide}</p:cond></p:nextCondLst></p:seq>'
77
+ f'{media}</p:childTnLst></p:cTn></p:par></p:tnLst></p:timing>')
78
+
79
+
80
+ def main(src, dst):
81
+ with zipfile.ZipFile(src) as zin, zipfile.ZipFile(dst, "w", zipfile.ZIP_DEFLATED) as zout:
82
+ for item in zin.infolist():
83
+ data = zin.read(item)
84
+ m = re.fullmatch(r"ppt/slides/slide(\d+)\.xml", item.filename)
85
+ if m:
86
+ rels = zin.read(f"ppt/slides/_rels/slide{m[1]}.xml.rels").decode()
87
+ # ponytail: one video per slide; a second one stays click-to-play
88
+ mp4 = re.search(r"media/([^\"]+\.mp4)", rels)
89
+ ms = mp4_ms(zin.read("ppt/media/" + mp4[1])) if mp4 else 0
90
+ xml = data.decode()
91
+ add = TRANSITIONS[int(m[1]) % 2] + timing(xml, ms)
92
+ data = xml.replace("</p:clrMapOvr>", "</p:clrMapOvr>" + add, 1).encode()
93
+ zout.writestr(item, data)
94
+
95
+
96
+ if __name__ == "__main__":
97
+ if len(sys.argv) != 3:
98
+ sys.exit(__doc__)
99
+ main(sys.argv[1], sys.argv[2])
@@ -133,6 +133,7 @@ function card(c) {
133
133
  // Orchestration: only a run that has workers carries them, so any other card is unchanged.
134
134
  const wk: { id: string; status: string; bypass: boolean }[] = c.workers || [];
135
135
  if (wk.length) chips.push(html`<span class="chip" title="${wk.map((x) => `${x.id} ${x.status}${x.bypass ? " (bypass)" : ""}`).join(", ")}">${wk.length} workers</span>`);
136
+ if (c.land) marks.push(html`<span class="mk bad" title="${c.land.why}">! ${c.land.kind === "conflict" ? "Conflict" : "Land failed"}</span>`);
136
137
  if (c.signal === "blocked") marks.push(mk("i-ask", `Waiting on you: ${c.blocked?.question ?? ""}`, " warn ask"));
137
138
  else if (c.signal === "stale") marks.push(html`<span class="mk warn" title="The agent has gone quiet: no report and no terminal activity">stale</span>`);
138
139
  else if (c.signal === "unverified") marks.push(html`<span class="mk warn" title="The agent ended without finishing this stage properly">unverified</span>`);