kaizen-agent 1.63.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.
- package/cli/handoff.test.ts +133 -0
- package/cli/handoff.ts +122 -0
- package/cli/install.ts +25 -2
- package/cli/pty.ts +16 -2
- package/cli/resources.test.ts +50 -0
- package/cli/resources.ts +113 -0
- package/cli/restart.test.ts +28 -1
- package/cli/settings.ts +3 -0
- package/cli/state.ts +8 -1
- package/cli/usage.test.ts +11 -0
- package/cli/web.ts +86 -5
- package/cli/workers.ts +11 -4
- package/cli/worktree.test.ts +174 -1
- package/cli/worktree.ts +190 -35
- package/package.json +1 -1
- package/skills/kaizen/config.default.yml +10 -0
- package/skills/kaizen/settings.md +3 -0
- package/skills/kaizen/spec-build.md +13 -0
- package/skills/kaizen/spec-main.md +13 -0
- package/web/board/cards.ts +1 -0
- package/web/board/git.ts +4 -4
- package/web/board/phone.ts +3 -5
- package/web/board/resources.ts +152 -0
- package/web/board/workspace.ts +2 -0
- package/web/board/ws-tabs.test.ts +8 -0
- package/web/board/ws-tabs.ts +8 -7
- package/web/board.html +13 -1
- package/web/board.js +99 -89
- package/web/notebook.js +23 -23
- package/web/notes.html +1 -0
- package/web/term.js +1 -1
- package/web/video.html +1 -0
- package/web/video.js +50 -50
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:
|
|
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
|
-
/**
|
|
56
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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,
|
|
79
|
-
const r = sh(["git", "cherry",
|
|
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
|
|
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
|
|
111
|
-
|
|
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
|
|
129
|
-
if (
|
|
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 =
|
|
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 (
|
|
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",
|
|
187
|
-
const landedNow = pr?.state === "MERGED" || (own.ok && Number(own.out) > 0 && landed(dir,
|
|
188
|
-
return { branch, base, upstream, landed: landedNow, gh:
|
|
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",
|
|
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
|
|
232
|
-
if (!
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
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
|
@@ -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).
|
|
@@ -26,6 +26,9 @@ 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 |
|
|
30
33
|
| `agent.model.<tool>` | the tool's own model name, or empty | Launch model for agy, codex, gemini, opencode, for every stage |
|
|
31
34
|
| `subagents.model` | `inherit`, `opus`, `sonnet`, `haiku` | Model the stage subagents run on (Claude Code only) |
|
|
@@ -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
|
package/web/board/cards.ts
CHANGED
|
@@ -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>`);
|
package/web/board/git.ts
CHANGED
|
@@ -61,14 +61,14 @@ function steps(c) {
|
|
|
61
61
|
why: files
|
|
62
62
|
? "Commit changes first"
|
|
63
63
|
: b && !b.upstream
|
|
64
|
-
? "Not published yet: Create PR pushes it"
|
|
64
|
+
? b.local ? "Lands by local merge: kaizen worktree land" : "Not published yet: Create PR pushes it"
|
|
65
65
|
: g.ahead > 0
|
|
66
66
|
? ""
|
|
67
67
|
: "Nothing to push",
|
|
68
68
|
},
|
|
69
69
|
];
|
|
70
70
|
if (!b) return s;
|
|
71
|
-
const noGh = b.gh ? "" : "Needs the GitHub CLI (gh) and a GitHub remote";
|
|
71
|
+
const noGh = b.local ? "Lands by local merge: kaizen worktree land" : b.gh ? "" : "Needs the GitHub CLI (gh) and a GitHub remote";
|
|
72
72
|
const prWhy =
|
|
73
73
|
noGh ||
|
|
74
74
|
(files
|
|
@@ -134,7 +134,7 @@ export function gitTab(c, refresh) {
|
|
|
134
134
|
rows = g.rows || [],
|
|
135
135
|
staged = rows.filter((r) => r.staged),
|
|
136
136
|
unstaged = rows.filter((r) => !r.staged),
|
|
137
|
-
target = b ? `origin/${b.base}` : `${g.remote}/${g.branch || "HEAD"}`;
|
|
137
|
+
target = b ? (b.local ? b.base : `origin/${b.base}`) : `${g.remote}/${g.branch || "HEAD"}`;
|
|
138
138
|
if (u.msg === undefined) u.msg = commitMsg(store.runDoc.impl) || c.title || c.text || "";
|
|
139
139
|
u.shut = u.shut || {};
|
|
140
140
|
// The main button: Stage all while nothing is staged, Commit once something is, else the
|
|
@@ -223,7 +223,7 @@ export function gitTab(c, refresh) {
|
|
|
223
223
|
: u.ask === "remove"
|
|
224
224
|
? html`<div class="gsec gform">
|
|
225
225
|
<div class="ghd">Remove the worktree and delete ${b.branch}?</div>
|
|
226
|
-
<div class="dim">Its work is on ${b.base}. The branch is deleted here and on GitHub.</div>
|
|
226
|
+
<div class="dim">Its work is on ${b.base}. The branch is deleted here${b.local ? "" : " and on GitHub"}.</div>
|
|
227
227
|
<div class="row"><button class="btn ghost" data-a="cancel">Cancel</button><button class="btn danger" data-a="go-remove">Remove workspace</button></div>
|
|
228
228
|
</div>`
|
|
229
229
|
: "";
|
package/web/board/phone.ts
CHANGED
|
@@ -5,7 +5,7 @@ import { runPopup } from "./cards.ts";
|
|
|
5
5
|
import { $, html, raw } from "./dom.ts";
|
|
6
6
|
import { cardHref, logo, railData, stateOf, subline, titleOf, usageChips, wsHref } from "./workspace.ts";
|
|
7
7
|
import { toast } from "./toast.ts";
|
|
8
|
-
import { agentStatus, wsKey, type Agent, type Status } from "./ws-tabs.ts";
|
|
8
|
+
import { agentStatus, wsKey, WORD, DOT, type Agent, type Status } from "./ws-tabs.ts";
|
|
9
9
|
|
|
10
10
|
export const isPhone = () => matchMedia("(max-width:640px)").matches;
|
|
11
11
|
|
|
@@ -31,9 +31,7 @@ function row(c, now: number) {
|
|
|
31
31
|
}
|
|
32
32
|
|
|
33
33
|
// Home's slider: one card per workspace with an agent open, those asking first.
|
|
34
|
-
const
|
|
35
|
-
const DOT: Record<Status, string> = { asking: "wait", working: "build", done: "done" };
|
|
36
|
-
const RANK: Record<Status, number> = { asking: 0, working: 1, done: 2 };
|
|
34
|
+
const RANK: Record<Status, number> = { conflict: 0, failed: 0, asking: 1, working: 2, done: 3 };
|
|
37
35
|
const agentIco = (a: Agent) => {
|
|
38
36
|
const id = "i-" + (a.agent || "").toLowerCase();
|
|
39
37
|
return raw(`<svg class="pag-ico" aria-hidden="true"><use href="#${document.getElementById(id) ? id : "i-ai"}"/></svg>`);
|
|
@@ -54,7 +52,7 @@ function agentCards(now: number) {
|
|
|
54
52
|
const asking = groups.filter((g) => g.rows[0].st === "asking").length;
|
|
55
53
|
const cards = groups.map(({ k, rows }) => {
|
|
56
54
|
const { a, st } = rows[0];
|
|
57
|
-
return html`<button type="button" class="pag${st === "asking" ? " ask" : ""}" data-group="${k}"><span class="pag-st"><i class="si ${DOT[st]}"></i>${rows.length > 1 ? rows.length + " agents" : WORD[st]}<span class="pag-icos">${rows.map((r) => agentIco(r.a))}</span></span><span class="pag-ws">${wsName(a)}</span><small>${projName(a.dir)}</small></button>`;
|
|
55
|
+
return html`<button type="button" class="pag${st === "asking" || DOT[st] === "fail" ? " ask" : ""}" data-group="${k}"><span class="pag-st"><i class="si ${DOT[st]}"></i>${rows.length > 1 ? rows.length + " agents" : WORD[st]}<span class="pag-icos">${rows.map((r) => agentIco(r.a))}</span></span><span class="pag-ws">${wsName(a)}</span><small>${projName(a.dir)}</small></button>`;
|
|
58
56
|
});
|
|
59
57
|
return html`<section class="psec2"><div class="pag-h"><h3>Agents${asking ? html`<span class="pag-n">${asking} asking</span>` : ""}</h3><button type="button" class="pag-new">New</button></div>${groups.length ? html`<div class="pslide">${cards}</div>` : html`<p class="pnote">No agents running.</p>`}</section>`;
|
|
60
58
|
}
|