kaizen-agent 1.60.0 → 1.60.2
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/knowledge.ts +1 -1
- package/cli/onboarding.test.ts +70 -0
- package/cli/onboarding.ts +63 -0
- package/cli/pty.test.ts +7 -2
- package/cli/pty.ts +5 -4
- package/cli/state.test.ts +86 -1
- package/cli/state.ts +140 -8
- package/cli/web-decide.test.ts +41 -0
- package/cli/web-pr.test.ts +51 -0
- package/cli/web.ts +150 -23
- package/cli/worktree.test.ts +104 -1
- package/cli/worktree.ts +117 -2
- package/package.json +1 -1
- package/web/board/api.ts +37 -4
- package/web/board/approvals.ts +6 -6
- package/web/board/badge.ts +6 -2
- package/web/board/cards.ts +4 -2
- package/web/board/fixes.ts +1 -1
- package/web/board/git.ts +382 -61
- package/web/board/live.ts +2 -1
- package/web/board/main.ts +2 -0
- package/web/board/onboarding.ts +223 -0
- package/web/board/panel.ts +36 -26
- package/web/board/run-view.ts +93 -9
- package/web/board/search-match.ts +20 -0
- package/web/board/search.test.ts +20 -0
- package/web/board/search.ts +324 -0
- package/web/board/store.ts +2 -0
- package/web/board/workspace.ts +94 -3
- package/web/board/ws-board-ui.ts +12 -1
- package/web/board/ws-tabs.test.ts +11 -1
- package/web/board/ws-tabs.ts +4 -1
- package/web/board.html +124 -16
- package/web/board.js +127 -45
- package/web/notebook.js +46 -23
- package/web/notes.html +18 -6
- package/web/term.js +20 -20
- package/web/term.ts +8 -3
- package/web/video.html +18 -6
- package/web/video.js +78 -55
package/cli/web.ts
CHANGED
|
@@ -5,7 +5,7 @@ import { join, dirname, resolve, sep, basename } from "node:path";
|
|
|
5
5
|
import {
|
|
6
6
|
home, type Item, type Card, boardCards, knownProjects, remember, canonPath, locate, label, tilde, searchRoots, findProjects,
|
|
7
7
|
readInbox, writeInbox, replaceIdea, moveIdea, abandonRun, runToIdea, launchRun, parseItem, agentChoices, onPath, projectOf, KNOWN_AGENTS, plainModel, short, setArchived, writeNotes,
|
|
8
|
-
appendNote, saveAttachment, pidOnPort, readText, cmdExe, sysExe, powershellExe, runGit, cardsGit, readCommit, commitPush, notice, notifier, LOGO,
|
|
8
|
+
appendNote, saveAttachment, pidOnPort, readText, cmdExe, sysExe, powershellExe, runGit, cardsGit, readCommit, commitPush, commitStaged, stageFiles, suggestMessage, notice, notifier, LOGO,
|
|
9
9
|
reviewFindings, pickFindings, backlogCards, backlogItem, startedBacklog, closeBacklog, markBacklogDone, fixPrompt, approvalPrompt, canApproveAwaiting, gateOf, recordAcceptance, healRuns, finishRun, nativePath, closeSessions, sweepSessions, issueUrl,
|
|
10
10
|
launchMode, readSessions, ownerOf, runIndex, resumePrompt, runAgent, firstSession, webHosts,
|
|
11
11
|
} from "./state.ts";
|
|
@@ -22,7 +22,7 @@ import * as video from "./video.ts";
|
|
|
22
22
|
import * as localsend from "./localsend.ts";
|
|
23
23
|
import * as hermes from "./hermes.ts";
|
|
24
24
|
import { listChats, readChat, sendChat, stopChat, deleteChat, okId as okChatId, busy as chatBusy, type Event as ChatEvent, type Upload as ChatUpload } from "./chat.ts";
|
|
25
|
-
import { workspaces, workspacesNow, forgetWorkspaces, workspacesAge, addWorktree, run } from "./worktree.ts";
|
|
25
|
+
import { workspaces, workspacesNow, forgetWorkspaces, workspacesAge, addWorktree, runAsync, run, branchState, openPr, mergePr, removeWorktree } from "./worktree.ts";
|
|
26
26
|
import { gitUrl, destDir, winBad, cloneInto, branchesOf, ignoreKaizen } from "./add-project.ts";
|
|
27
27
|
|
|
28
28
|
const PAGE = join(dirname(import.meta.dir), "web", "board.html");
|
|
@@ -253,7 +253,17 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
253
253
|
let usageCache: Usage[] = [];
|
|
254
254
|
let usageAt = 0;
|
|
255
255
|
let pending: ReturnType<typeof setTimeout> | null = null;
|
|
256
|
+
const prBusy = new Set<string>();
|
|
257
|
+
// /state costs ~250 ms of this one thread on a big board (git status per project), and
|
|
258
|
+
// every open tab asks at once on each change, stalling terminal output for all of them.
|
|
259
|
+
// A reply is shared until something changes; a git mark for a few seconds, since
|
|
260
|
+
// nothing watches the working trees anyway. Any write request drops both.
|
|
261
|
+
let stateGen = 0;
|
|
262
|
+
const stateCache = new Map<string, { gen: string; at: number; body: string }>();
|
|
263
|
+
const gitCache = new Map<string, { at: number; ids: string; marks: Record<string, string>; dues: Record<string, "commit" | "push"> }>();
|
|
264
|
+
const STATE_MS = 1000, GIT_MS = 5000;
|
|
256
265
|
const changed = () => {
|
|
266
|
+
stateGen++;
|
|
257
267
|
if (pending) return;
|
|
258
268
|
pending = setTimeout(() => {
|
|
259
269
|
pending = null;
|
|
@@ -263,6 +273,13 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
263
273
|
// agent.launch: card runs what this board launches inside the board, shown on the card.
|
|
264
274
|
const inCard = (dir: string) => ({ card: launchMode(projectOf(dir)) === "card", onChange: changed });
|
|
265
275
|
|
|
276
|
+
// The agent open in a run's card, the newest when there are several: what the user sees
|
|
277
|
+
// working. Everything sent to a run goes here before any new agent is started.
|
|
278
|
+
const liveAgent = (dir: string, id: string) => {
|
|
279
|
+
const idx = runIndex(dir);
|
|
280
|
+
return readSessions(dir).filter((s) => ptyState(s.key)?.alive && ownerOf(dir, s, idx) === id).sort((a, b) => a.started - b.started).pop();
|
|
281
|
+
};
|
|
282
|
+
|
|
266
283
|
// Start a run's agent again after it ended mid-stage (crashed, closed, a stalled run, or
|
|
267
284
|
// the board restarting for an upgrade), in the conversation it had where the tool can
|
|
268
285
|
// resume one. A run waiting for a decision, or done, gets its conversation back with
|
|
@@ -272,7 +289,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
272
289
|
let run: any;
|
|
273
290
|
try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return { error: "no such run", status: 404 }; }
|
|
274
291
|
if (run.stage === "abandoned") return { error: "this run was abandoned", status: 409 };
|
|
275
|
-
if (
|
|
292
|
+
if (liveAgent(dir, id)) return { error: "its agent is still running in its card", status: 409 };
|
|
276
293
|
const quiet = run.stage === "done" || !!run.awaiting;
|
|
277
294
|
const own = quiet ? runAgent(dir, id) : null;
|
|
278
295
|
if (quiet && !(own && firstSession(dir, id, own.cmd, projectOf(dir)))) return { error: "no conversation of this run to resume", status: 409 };
|
|
@@ -359,7 +376,10 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
359
376
|
// run's state.json, about a second on a board of 400 runs.
|
|
360
377
|
const ptyOf = (cards: Card[]) => {
|
|
361
378
|
const live = new Set(ptyKeys());
|
|
362
|
-
if (!live.size) return () => undefined;
|
|
379
|
+
if (!live.size) return Object.assign(() => undefined, { cmd: (_k: string) => undefined as string | undefined });
|
|
380
|
+
// Which agent each live terminal runs, from the session records: a run being born has no tag for it yet.
|
|
381
|
+
const cmdOf = new Map<string, string>();
|
|
382
|
+
for (const d of new Set(cards.map((c) => c.state))) for (const s of readSessions(d)) if (live.has(s.key) && s.cmd) cmdOf.set(s.key, s.cmd);
|
|
363
383
|
const runs = new Map<string, string[]>();
|
|
364
384
|
const planKeys = new Set(ideaPty.values());
|
|
365
385
|
for (const d of new Set(cards.filter((c) => c.kind === "run").map((c) => c.state))) {
|
|
@@ -373,7 +393,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
373
393
|
runs.set(k, [...(runs.get(k) ?? []), s.key]); // oldest first: the newest is the card's
|
|
374
394
|
}
|
|
375
395
|
}
|
|
376
|
-
return (c: Card) => {
|
|
396
|
+
return Object.assign((c: Card) => {
|
|
377
397
|
const keys = c.kind === "run" ? runs.get(`${c.state}\0${c.id}`) ?? [] : [ideaPty.get(`${c.state}\0${c.text}`)].filter((k): k is string => !!k && live.has(k));
|
|
378
398
|
const key = keys.at(-1);
|
|
379
399
|
if (!key) return undefined;
|
|
@@ -382,8 +402,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
382
402
|
if (!st.alive && (c.status === "done" || c.status === "abandoned")) return undefined;
|
|
383
403
|
// Every agent session the run has had on this board, for the workspace's Agent tabs.
|
|
384
404
|
const all = keys.filter((k) => ptyState(k)?.alive || k === key);
|
|
385
|
-
return { key, alive: st.alive, asking: st.asking, busy: st.busy, all, stages: c.kind === "run" ? stagesOf(c.state, c.id!) : undefined };
|
|
386
|
-
};
|
|
405
|
+
return { key, alive: st.alive, asking: st.asking, busy: st.busy, all, agent: cmdOf.get(key), stages: c.kind === "run" ? stagesOf(c.state, c.id!) : undefined };
|
|
406
|
+
}, { cmd: (k: string) => cmdOf.get(k) });
|
|
387
407
|
};
|
|
388
408
|
const watchers: FSWatcher[] = [];
|
|
389
409
|
const watchAll = () => {
|
|
@@ -522,6 +542,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
522
542
|
// arrives with that hostname in Host, and gets nothing.
|
|
523
543
|
const hostname = (req.headers.get("host") ?? "").toLowerCase().replace(/:\d+$/, "");
|
|
524
544
|
if (hostname !== "127.0.0.1" && hostname !== "localhost" && !extraHosts.has(hostname)) return new Response("forbidden", { status: 403 });
|
|
545
|
+
if (req.method !== "GET") { stateGen++; gitCache.clear(); }
|
|
525
546
|
const url = new URL(req.url);
|
|
526
547
|
const path = url.pathname;
|
|
527
548
|
const qdir = () => { const v = url.searchParams.get("dir"); return v == null ? v : canonState(v); };
|
|
@@ -777,6 +798,27 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
777
798
|
changed();
|
|
778
799
|
return json(r);
|
|
779
800
|
}
|
|
801
|
+
// The rail's right-click menu on a worktree: update (fast-forward pull) or delete it.
|
|
802
|
+
// Only an exact non-main path from this project's own worktree list; argv arrays.
|
|
803
|
+
if (req.method === "POST" && path === "/workspace") {
|
|
804
|
+
const refused = strict(req);
|
|
805
|
+
if (refused) return refused;
|
|
806
|
+
let body: any;
|
|
807
|
+
try { body = await req.json(); } catch { return bad("json body expected"); }
|
|
808
|
+
const dir = canonState(String(body.dir ?? ""));
|
|
809
|
+
if (!states(true).includes(dir) || dir === join(home, ".kaizen")) return bad("choose a project", 404);
|
|
810
|
+
const project = projectOf(dir);
|
|
811
|
+
forgetWorkspaces(project);
|
|
812
|
+
const w = workspaces(project).find((x) => x.path === body.ws);
|
|
813
|
+
if (!w || w.main) return bad("not a worktree of this project", 400);
|
|
814
|
+
const r = body.op === "update" ? await runAsync(["git", "pull", "--ff-only"], w.path)
|
|
815
|
+
: body.op === "delete" ? await runAsync(["git", "worktree", "remove", "--", w.path], project)
|
|
816
|
+
: null;
|
|
817
|
+
if (!r) return bad("unknown op", 400);
|
|
818
|
+
forgetWorkspaces(project);
|
|
819
|
+
changed();
|
|
820
|
+
return r.ok ? json({ ok: true, out: r.out }) : bad(r.why, 409);
|
|
821
|
+
}
|
|
780
822
|
// The rail's + sheet. Each of these starts git, makes a folder or registers one, so
|
|
781
823
|
// they take /worktree's guards and read their paths from the raw body (the generic
|
|
782
824
|
// POST block below would normalise a `..` away before destDir sees it).
|
|
@@ -991,22 +1033,31 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
991
1033
|
return !root || d === state || (fold(p).startsWith(inside)
|
|
992
1034
|
&& (!isGroup(p) || filled(d) || fold(dirname(p)) !== fold(root)));
|
|
993
1035
|
});
|
|
1036
|
+
// What an agent printed goes only to a viewer on this machine, not to a tailnet host or a phone.
|
|
1037
|
+
const ip = srv.requestIP(req)?.address ?? "";
|
|
1038
|
+
const loopback = (hostname === "127.0.0.1" || hostname === "localhost") && /^(127\.|::1$|::ffff:127\.)/.test(ip)
|
|
1039
|
+
&& !["x-forwarded-for", "x-forwarded-host", "forwarded", "tailscale-user-login", "tailscale-user-name"].some((h) => req.headers.has(h));
|
|
1040
|
+
// Agents' status and last line change without an event, so they are part of what a reply is valid for.
|
|
1041
|
+
const gen = `${stateGen} ${ptyKeys().map((k) => { const s = ptyState(k)!; return `${k}:${s.alive}:${s.asking}:${s.busy}:${s.at}`; }).join()}`;
|
|
1042
|
+
const cacheKey = `${all}\0${state}\0${loopback}`, hit = stateCache.get(cacheKey);
|
|
1043
|
+
if (hit?.gen === gen && Date.now() - hit.at < STATE_MS) return new Response(hit.body, { headers: { "content-type": "application/json" } });
|
|
994
1044
|
for (const d of dirs) healRuns(d);
|
|
995
1045
|
const cards = boardCards(dirs, Date.now()), pty = ptyOf(cards);
|
|
996
1046
|
// The git mark, for the cards whose panel offers commit and push: one status per project.
|
|
997
1047
|
const marks = new Map<string, Record<string, string>>(), dues = new Map<string, Record<string, "commit" | "push">>();
|
|
998
1048
|
const markable = (c: Card) => c.kind === "run" && !c.archived && (c.status === "done" || c.awaiting === "approvals.review") && c.state !== join(home, ".kaizen");
|
|
999
|
-
for (const d of new Set(cards.filter(markable).map((c) => c.state)))
|
|
1000
|
-
|
|
1049
|
+
for (const d of new Set(cards.filter(markable).map((c) => c.state))) {
|
|
1050
|
+
const ids = cards.filter((c) => markable(c) && c.state === d).map((c) => c.id!), idKey = ids.join("\n"), had = gitCache.get(d);
|
|
1051
|
+
if (had?.ids === idKey && Date.now() - had.at < GIT_MS) { marks.set(d, had.marks); dues.set(d, had.dues); continue; }
|
|
1052
|
+
const due: Record<string, "commit" | "push"> = {}, mark = cardsGit(d, ids, due);
|
|
1053
|
+
marks.set(d, mark); dues.set(d, due);
|
|
1054
|
+
gitCache.set(d, { at: Date.now(), ids: idKey, marks: mark, dues: due });
|
|
1055
|
+
}
|
|
1001
1056
|
// Open findings the panel's Fix findings form would offer, on the same runs.
|
|
1002
1057
|
const openFindings = (c: Card) => c.kind === "run" && !c.archived && (c.status === "done" || c.awaiting === "findings" || c.awaiting === "approvals.review") && c.state !== join(home, ".kaizen")
|
|
1003
1058
|
? reviewFindings(c.state, c.id!).filter((f) => !f.done).length || undefined : undefined;
|
|
1004
1059
|
// The agents open now, for the sidebar cards: one list per tick, from the cards' sessions and the board's agent
|
|
1005
1060
|
// shells. ws is as the card or shell has it; the page resolves it to a listed workspace. Ended agents are left out.
|
|
1006
|
-
// What an agent printed goes only to a viewer on this machine, not to a tailnet host or a phone.
|
|
1007
|
-
const ip = srv.requestIP(req)?.address ?? "";
|
|
1008
|
-
const loopback = (hostname === "127.0.0.1" || hostname === "localhost") && /^(127\.|::1$|::ffff:127\.)/.test(ip)
|
|
1009
|
-
&& !["x-forwarded-for", "x-forwarded-host", "forwarded", "tailscale-user-login", "tailscale-user-name"].some((h) => req.headers.has(h));
|
|
1010
1061
|
const agents: any[] = [], seenKey = new Set<string>(), ptys = cards.map(pty);
|
|
1011
1062
|
const addAgent = (key: string, dir: string, ws: string | undefined, cmd: string | undefined, run?: string) => {
|
|
1012
1063
|
const st = seenKey.has(key) ? null : ptyState(key);
|
|
@@ -1016,10 +1067,10 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
1016
1067
|
agents.push({ key, dir, ws, agent: cmd, name, run, asking: st.asking, busy: st.busy, born: st.born, ...(loopback ? { last: st.last || undefined, at: st.at || undefined } : {}) });
|
|
1017
1068
|
};
|
|
1018
1069
|
for (const x of shells.values()) if (x.agent) addAgent(x.key, x.dir, x.ws, x.agent, x.run);
|
|
1019
|
-
cards.forEach((c, i) => { for (const k of ptys[i]?.all ?? []) addAgent(k, c.state, c.ws, KNOWN_AGENTS.find((a) => c.tags?.includes(a.cmd))?.cmd, c.kind === "run" ? c.id : undefined); });
|
|
1070
|
+
cards.forEach((c, i) => { for (const k of ptys[i]?.all ?? []) addAgent(k, c.state, c.ws, pty.cmd(k) ?? KNOWN_AGENTS.find((a) => c.tags?.includes(a.cmd))?.cmd, c.kind === "run" ? c.id : undefined); });
|
|
1020
1071
|
const entry = (d: string) => ({ dir: d, label: label(d), logo: !!projectLogo(d),
|
|
1021
1072
|
workspaces: d === join(home, ".kaizen") ? [{ path: d, branch: "", main: true }] : workspacesNow(projectOf(d)) });
|
|
1022
|
-
|
|
1073
|
+
const body = JSON.stringify({
|
|
1023
1074
|
project, all, dir: state,
|
|
1024
1075
|
// Each project's workspaces (git worktrees, or the one folder); the global queue is its own one.
|
|
1025
1076
|
projects: picker.map(entry),
|
|
@@ -1032,6 +1083,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
1032
1083
|
backlog: backlogCards(dirs).map((b) => ({ ...b, starting: backlogLaunched.has(`${b.state}\0${b.source}#${b.n}`) || undefined })),
|
|
1033
1084
|
now: Date.now(),
|
|
1034
1085
|
});
|
|
1086
|
+
stateCache.set(cacheKey, { gen, at: Date.now(), body });
|
|
1087
|
+
return new Response(body, { headers: { "content-type": "application/json" } });
|
|
1035
1088
|
}
|
|
1036
1089
|
|
|
1037
1090
|
if (req.method === "GET" && path.startsWith("/run/")) {
|
|
@@ -1052,6 +1105,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
1052
1105
|
findings: dir === join(home, ".kaizen") ? [] : reviewFindings(dir, id),
|
|
1053
1106
|
// The global state dir sits in $HOME, which is not a project to commit.
|
|
1054
1107
|
commit: readCommit(dir, id), git: dir === join(home, ".kaizen") ? { repo: false } : runGit(dir, id),
|
|
1108
|
+
// The run's own branch and pull request, for the Git tab; null when it has no worktree.
|
|
1109
|
+
branch: dir === join(home, ".kaizen") ? null : branchState(dirname(dir), id, changed),
|
|
1055
1110
|
});
|
|
1056
1111
|
}
|
|
1057
1112
|
|
|
@@ -1085,6 +1140,22 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
1085
1140
|
return Response.redirect(issueUrl({ title: url.searchParams.get("title") ?? "", what: url.searchParams.get("what") ?? "" }), 302);
|
|
1086
1141
|
}
|
|
1087
1142
|
|
|
1143
|
+
// First-run onboarding: where this machine's user got to, and what the page offers to pick from.
|
|
1144
|
+
// Only the board's own file is written; the choices themselves go through /settings.
|
|
1145
|
+
if (path === "/onboarding" && (req.method === "GET" || req.method === "POST")) {
|
|
1146
|
+
const { onboardingView, writeOnboarding, installHelp } = await import("./onboarding.ts");
|
|
1147
|
+
if (req.method === "POST") {
|
|
1148
|
+
if (!local(req)) return bad("cross-origin write refused", 403);
|
|
1149
|
+
let body: any;
|
|
1150
|
+
try { body = await req.json(); } catch { return bad("json body expected"); }
|
|
1151
|
+
const r = writeOnboarding(home, body);
|
|
1152
|
+
return "error" in r ? bad(r.error) : json(r);
|
|
1153
|
+
}
|
|
1154
|
+
const projects = states(true).filter((d) => d !== join(home, ".kaizen")).length;
|
|
1155
|
+
const ch = agentChoices(repoDir);
|
|
1156
|
+
return json({ ...onboardingView(home, projects), default: ch.default, installed: ch.agents.map((a) => a.cmd), agents: KNOWN_AGENTS.map((a) => ({ cmd: a.cmd, name: a.name })), install: installHelp(process.platform === "win32") });
|
|
1157
|
+
}
|
|
1158
|
+
|
|
1088
1159
|
if (req.method === "GET" && path === "/agents") {
|
|
1089
1160
|
const dir = qdir();
|
|
1090
1161
|
if (!dir || !states(true).includes(dir)) return bad("unknown state dir", 404);
|
|
@@ -1724,7 +1795,60 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
1724
1795
|
let run: any;
|
|
1725
1796
|
try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return bad("no such run", 404); }
|
|
1726
1797
|
if (run.stage !== "done" && run.awaiting !== "approvals.review") return bad("this run is not finished", 409);
|
|
1727
|
-
const
|
|
1798
|
+
const files = Array.isArray(body.files) ? body.files.map(String) : [];
|
|
1799
|
+
// `push: false` is the tab's plain Commit: what is staged, nothing pushed.
|
|
1800
|
+
const r = body.push === false ? commitStaged(dir, id, String(body.message ?? ""), files) : await commitPush(dir, id, String(body.message ?? ""), files);
|
|
1801
|
+
changed();
|
|
1802
|
+
return json(r, r.ok ? 200 : 409);
|
|
1803
|
+
}
|
|
1804
|
+
|
|
1805
|
+
// The Source control tab's stage, unstage and discard, on the same runs /commit
|
|
1806
|
+
// takes and only on the run's own files (stageFiles refuses any other path).
|
|
1807
|
+
if (path === "/stage") {
|
|
1808
|
+
const id = String(body.id ?? "");
|
|
1809
|
+
if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
|
|
1810
|
+
if (dir === join(home, ".kaizen")) return bad("no project", 409);
|
|
1811
|
+
let run: any;
|
|
1812
|
+
try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return bad("no such run", 404); }
|
|
1813
|
+
if (run.stage !== "done" && run.awaiting !== "approvals.review") return bad("this run is not finished", 409);
|
|
1814
|
+
const op = body.op;
|
|
1815
|
+
if (op !== "stage" && op !== "unstage" && op !== "discard") return bad("unknown op");
|
|
1816
|
+
const why = stageFiles(dir, id, op, Array.isArray(body.paths) ? body.paths.map(String) : []);
|
|
1817
|
+
changed();
|
|
1818
|
+
return why ? bad(why, 409) : json({ ok: true });
|
|
1819
|
+
}
|
|
1820
|
+
|
|
1821
|
+
// The sparkle button: a commit message for the run's files, written from their diff.
|
|
1822
|
+
if (path === "/commit-message") {
|
|
1823
|
+
const id = String(body.id ?? "");
|
|
1824
|
+
if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
|
|
1825
|
+
if (dir === join(home, ".kaizen")) return bad("no project", 409);
|
|
1826
|
+
const r = await suggestMessage(dir, id);
|
|
1827
|
+
return r.ok ? json(r) : bad(r.why, 409);
|
|
1828
|
+
}
|
|
1829
|
+
|
|
1830
|
+
// The Git tab's later steps, on the same runs /commit takes: open the branch's pull
|
|
1831
|
+
// request, merge it, then remove the worktree once its work is on the base.
|
|
1832
|
+
if (path === "/pr") {
|
|
1833
|
+
const id = String(body.id ?? "");
|
|
1834
|
+
if (!/^[\w.-]+$/.test(id)) return bad("bad run id");
|
|
1835
|
+
// One step per run at a time: a second tab's Merge or Remove waits its turn.
|
|
1836
|
+
const lock = `${dir}\0${id}`;
|
|
1837
|
+
if (prBusy.has(lock)) return bad("Another git step is running on this run. Try again when it finishes.", 409);
|
|
1838
|
+
if (dir === join(home, ".kaizen")) return bad("no project", 409);
|
|
1839
|
+
let run: any;
|
|
1840
|
+
try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return bad("no such run", 404); }
|
|
1841
|
+
if (run.stage !== "done" && run.awaiting !== "approvals.review") return bad("this run is not finished", 409);
|
|
1842
|
+
const project = dirname(dir);
|
|
1843
|
+
if (body.op !== "remove" && gateOf(dir, id) === "needs") return bad("This run is not approved yet. Approve it first.", 409);
|
|
1844
|
+
prBusy.add(lock);
|
|
1845
|
+
let r: { ok: boolean };
|
|
1846
|
+
try {
|
|
1847
|
+
r = body.op === "create" ? await openPr(project, id, String(body.title ?? ""), String(body.body ?? ""), body.draft === true)
|
|
1848
|
+
: body.op === "merge" ? await mergePr(project, id)
|
|
1849
|
+
: body.op === "remove" ? await removeWorktree(project, id)
|
|
1850
|
+
: { ok: false as const, why: "unknown op" };
|
|
1851
|
+
} finally { prBusy.delete(lock); }
|
|
1728
1852
|
changed();
|
|
1729
1853
|
return json(r, r.ok ? 200 : 409);
|
|
1730
1854
|
}
|
|
@@ -1744,7 +1868,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
1744
1868
|
const text = fixPrompt(id, nums);
|
|
1745
1869
|
// An agent already open in this run's card takes the fix there, busy or not:
|
|
1746
1870
|
// the text queues in it, and no second agent opens beside it.
|
|
1747
|
-
const live =
|
|
1871
|
+
const live = liveAgent(dir, id);
|
|
1748
1872
|
if (live) {
|
|
1749
1873
|
writePty(live.key, text + "\r");
|
|
1750
1874
|
markStage(dir, id, "review", live.key);
|
|
@@ -1787,12 +1911,15 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
1787
1911
|
if (answers !== undefined && (run.awaiting !== "approvals.plan" || body.why !== undefined || !Array.isArray(answers)
|
|
1788
1912
|
|| !answers.length || answers.length > 20 || answers.some((a: unknown) => typeof a !== "string" || !a.trim()))) return bad("bad answers");
|
|
1789
1913
|
const text = approvalPrompt(id, run.awaiting, body.why === undefined ? undefined : String(body.why), answers);
|
|
1790
|
-
// The
|
|
1791
|
-
//
|
|
1792
|
-
//
|
|
1914
|
+
// The agent already open in this run's card takes the decision there, as it takes
|
|
1915
|
+
// a fix: no second tab of the same conversation. With none, the run's conversation
|
|
1916
|
+
// continues in one new window, and then the idle one ends. A failed launch leaves
|
|
1917
|
+
// it open, since the decision went nowhere.
|
|
1918
|
+
const live = liveAgent(dir, id);
|
|
1793
1919
|
const before = Date.now();
|
|
1794
|
-
const r = launchRun({ severity: null, where: null, text, raw: text }, dir, id, inCard(dir));
|
|
1795
|
-
if (
|
|
1920
|
+
const r = live ? { ok: true as const, pty: live.key, agent: live.cmd, reused: true } : launchRun({ severity: null, where: null, text, raw: text }, dir, id, inCard(dir));
|
|
1921
|
+
if (live) writePty(live.key, text + "\r");
|
|
1922
|
+
else if (r.ok) closeSessions(dir, id, { before });
|
|
1796
1923
|
// The plan's approval starts the build; fixing open findings is the review stage again.
|
|
1797
1924
|
if (r.ok) markStage(dir, id, run.awaiting === "approvals.plan" ? "impl" : run.awaiting === "findings" ? "review" : "", r.pty);
|
|
1798
1925
|
// Approving the review as-is is the user's acceptance, on record before the
|
|
@@ -1800,7 +1927,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
1800
1927
|
if (r.ok && body.why === undefined && (run.awaiting === "approvals.review" || run.awaiting === "findings")) recordAcceptance(dir, id, "board");
|
|
1801
1928
|
changed();
|
|
1802
1929
|
return json(r.ok
|
|
1803
|
-
? { ok: true, agent: r.agent, pty: r.pty }
|
|
1930
|
+
? { ok: true, agent: r.agent, pty: r.pty, ...(live ? { reused: true } : {}) }
|
|
1804
1931
|
: { ok: false, why: r.why, manual: r.manual, agent: r.agent }, r.ok ? 200 : 500);
|
|
1805
1932
|
}
|
|
1806
1933
|
|
package/cli/worktree.test.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { test, expect, beforeEach } from "bun:test";
|
|
|
3
3
|
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync } from "node:fs";
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { tmpdir } from "node:os";
|
|
6
|
-
import { startWorktree, landWorktree, codeDir, projectFromWorktree, run, workspaces, workspacesNow, addWorktree, wsOf, adoptWorkspace, type Run } from "./worktree.ts";
|
|
6
|
+
import { startWorktree, landWorktree, codeDir, projectFromWorktree, run, runAsync, workspaces, workspacesNow, addWorktree, wsOf, adoptWorkspace, branchState, openPr, mergePr, removeWorktree, type Run, type AsyncRun } from "./worktree.ts";
|
|
7
7
|
|
|
8
8
|
const ID = "2026-10-17-demo";
|
|
9
9
|
// CI runners have no git identity, and landWorktree's rebase writes commits.
|
|
@@ -155,3 +155,106 @@ test("workspacesNow: answers at once, refreshes git in the background, one call
|
|
|
155
155
|
expect(workspacesNow(p, slow)).toEqual([{ path: p, branch: "dev", main: true }]);
|
|
156
156
|
expect(calls).toBe(1);
|
|
157
157
|
});
|
|
158
|
+
|
|
159
|
+
// ---- the Git tab (2026-10-30-run-git-tab)
|
|
160
|
+
|
|
161
|
+
// gh faked, git real: GitHub is never asked, the branch and the worktree are real.
|
|
162
|
+
const fakeGh = (answer: (cmd: string[], cwd: string) => { ok: boolean; out: string; why: string }) => {
|
|
163
|
+
const calls: string[][] = [];
|
|
164
|
+
const ash: AsyncRun = async (cmd, cwd) => {
|
|
165
|
+
if (cmd[0] !== "gh") return runAsync(cmd[0] === "git" ? ["git", "-c", "user.email=a@b.c", "-c", "user.name=t", ...cmd.slice(1)] : cmd, cwd);
|
|
166
|
+
calls.push(cmd);
|
|
167
|
+
return answer(cmd, cwd);
|
|
168
|
+
};
|
|
169
|
+
return { ash, calls };
|
|
170
|
+
};
|
|
171
|
+
const ghRun: Run = (cmd, cwd) => { if (cmd[0] === "gh") throw new Error("gh run on the request path"); return idRun(cmd, cwd); };
|
|
172
|
+
const tick = () => new Promise((r) => setTimeout(r, 50));
|
|
173
|
+
|
|
174
|
+
test("G-03 branchState never asks GitHub on the request path and shows the PR once the look lands", async () => {
|
|
175
|
+
const id = "2026-10-30-look";
|
|
176
|
+
mkdirSync(join(project, ".kaizen/runs", id), { recursive: true });
|
|
177
|
+
writeFileSync(join(project, ".kaizen/runs", id, "state.json"), JSON.stringify({ id, stage: "done" }));
|
|
178
|
+
startWorktree(project, id);
|
|
179
|
+
const pr = { number: 7, url: "https://github.com/x/y/pull/7", state: "OPEN", isDraft: false };
|
|
180
|
+
const { ash, calls } = fakeGh(() => ({ ok: true, out: JSON.stringify(pr), why: "" }));
|
|
181
|
+
let changed = 0;
|
|
182
|
+
const first = branchState(project, id, () => changed++, ghRun, ash, true)!;
|
|
183
|
+
expect(first).toMatchObject({ branch: `kaizen/${id}`, base: "main", upstream: false, landed: false, pr: null, checking: true });
|
|
184
|
+
await tick();
|
|
185
|
+
expect(calls.map((c) => c.slice(0, 4).join(" "))).toEqual([`gh pr view kaizen/${id}`]);
|
|
186
|
+
expect(changed).toBe(1);
|
|
187
|
+
const again = branchState(project, id, () => changed++, ghRun, ash, true)!;
|
|
188
|
+
expect(again.pr).toEqual({ number: 7, url: pr.url, state: "OPEN", draft: false });
|
|
189
|
+
expect(again.checking).toBe(false);
|
|
190
|
+
await tick();
|
|
191
|
+
expect(calls.length).toBe(1); // cached: no second look inside 30 s
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
test("G-02 a run with no worktree has no branch state; one with no commits of its own is not landed", () => {
|
|
195
|
+
expect(branchState(project, ID, () => {}, ghRun, runAsync, false)).toBeNull();
|
|
196
|
+
startWorktree(project, ID);
|
|
197
|
+
expect(branchState(project, ID, () => {}, ghRun, runAsync, false)!.landed).toBe(false);
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
test("G-06 openPr pushes, then creates the PR with title and body as separate arguments", async () => {
|
|
201
|
+
const w = (startWorktree(project, ID) as { path: string }).path;
|
|
202
|
+
commit(w, "run.txt", "mine");
|
|
203
|
+
const { ash, calls } = fakeGh((cmd) => cmd[2] === "view"
|
|
204
|
+
? { ok: true, out: JSON.stringify({ number: 3, url: "u", state: "OPEN", isDraft: true }), why: "" }
|
|
205
|
+
: { ok: true, out: "u", why: "" });
|
|
206
|
+
const r = await openPr(project, ID, "feat: a; rm -rf /", "Run x.\n$(id)", true, idRun, ash, true);
|
|
207
|
+
expect(r).toEqual({ ok: true, pr: { number: 3, url: "u", state: "OPEN", draft: true } });
|
|
208
|
+
expect(calls[0]).toEqual(["gh", "pr", "create", "--base", "main", "--head", `kaizen/${ID}`, "--title", "feat: a; rm -rf /", "--body", "Run x.\n$(id)", "--draft"]);
|
|
209
|
+
expect(g(project, "ls-remote", "--heads", "origin", `kaizen/${ID}`)).toContain(ID); // pushed first
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
test("G-06 openPr refuses a dirty worktree, no gh, an empty title, and a run without a branch", async () => {
|
|
213
|
+
const { ash, calls } = fakeGh(() => ({ ok: true, out: "", why: "" }));
|
|
214
|
+
expect((await openPr(project, ID, "t", "", false, idRun, ash, true)).ok).toBe(false); // no worktree
|
|
215
|
+
const w = (startWorktree(project, ID) as { path: string }).path;
|
|
216
|
+
expect((await openPr(project, ID, "t", "", false, idRun, ash, false)).ok).toBe(false);
|
|
217
|
+
expect((await openPr(project, ID, " ", "", false, idRun, ash, true)).ok).toBe(false);
|
|
218
|
+
writeFileSync(join(w, "dirty.txt"), "x");
|
|
219
|
+
const r = await openPr(project, ID, "t", "", false, idRun, ash, true);
|
|
220
|
+
expect(r).toEqual({ ok: false, why: "Commit the changes first." });
|
|
221
|
+
expect(calls).toEqual([]);
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
test("G-06 mergePr merges by rebase with the branch name", async () => {
|
|
225
|
+
startWorktree(project, ID);
|
|
226
|
+
const { ash, calls } = fakeGh(() => ({ ok: true, out: "", why: "" }));
|
|
227
|
+
expect(await mergePr(project, ID, idRun, ash, true)).toEqual({ ok: true });
|
|
228
|
+
expect(calls).toEqual([["gh", "pr", "merge", `kaizen/${ID}`, "--rebase"]]);
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
test("G-04 removeWorktree refuses dirty or unlanded work and cleans up once it is on the base", async () => {
|
|
232
|
+
const w = (startWorktree(project, ID) as { path: string }).path;
|
|
233
|
+
commit(w, "run.txt", "mine");
|
|
234
|
+
writeFileSync(join(w, "wip.txt"), "x");
|
|
235
|
+
expect((await removeWorktree(project, ID, idRun)).ok).toBe(false);
|
|
236
|
+
g(w, "add", "wip.txt"); g(w, "commit", "-qm", "feat: wip");
|
|
237
|
+
const unlanded = await removeWorktree(project, ID, idRun);
|
|
238
|
+
expect(unlanded.ok).toBe(false);
|
|
239
|
+
expect(existsSync(w)).toBe(true);
|
|
240
|
+
// GitHub's rebase-merge, by hand: the work reaches main under new hashes.
|
|
241
|
+
commit(other, "theirs.txt", "x"); g(other, "push", "-q", "origin", "HEAD:main");
|
|
242
|
+
g(w, "fetch", "-q", "origin"); g(w, "rebase", "-q", "origin/main"); g(w, "push", "-q", "origin", "HEAD:main");
|
|
243
|
+
g(w, "push", "-q", "origin", `HEAD:refs/heads/kaizen/${ID}`);
|
|
244
|
+
expect(await removeWorktree(project, ID, idRun)).toEqual({ ok: true });
|
|
245
|
+
expect(existsSync(w)).toBe(false);
|
|
246
|
+
expect(g(project, "branch", "--list", `kaizen/${ID}`)).toBe("");
|
|
247
|
+
expect(g(project, "ls-remote", "--heads", "origin", `kaizen/${ID}`)).toBe("");
|
|
248
|
+
expect(state().worktree).toBeUndefined();
|
|
249
|
+
expect(state().branch).toBeUndefined();
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
test("G-04 removeWorktree keeps unmerged work when nothing can prove it landed (no origin)", async () => {
|
|
253
|
+
const w = (startWorktree(project, ID) as { path: string }).path;
|
|
254
|
+
commit(w, "run.txt", "mine");
|
|
255
|
+
g(project, "remote", "remove", "origin");
|
|
256
|
+
const r = await removeWorktree(project, ID, idRun);
|
|
257
|
+
expect(r.ok).toBe(false);
|
|
258
|
+
expect(existsSync(w)).toBe(true);
|
|
259
|
+
expect(g(project, "branch", "--list", `kaizen/${ID}`)).toContain(ID);
|
|
260
|
+
});
|
package/cli/worktree.ts
CHANGED
|
@@ -74,8 +74,11 @@ export type Landed = { ok: true; how: "pr" | "push"; url?: string } | { ok: fals
|
|
|
74
74
|
|
|
75
75
|
// Whether every commit of the branch is on the base, by patch: a rebase-merge rewrites
|
|
76
76
|
// the hashes, so "is an ancestor" would say not landed for work that is.
|
|
77
|
-
|
|
78
|
-
|
|
77
|
+
// 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);
|
|
80
|
+
return r.ok && r.out.split("\n").every((l) => !l.startsWith("+"));
|
|
81
|
+
};
|
|
79
82
|
|
|
80
83
|
/**
|
|
81
84
|
* Pushes the run's branch and lands it on the base: a pull request rebase-merged when
|
|
@@ -128,6 +131,118 @@ export function landWorktree(project: string, id: string, sh: Run = run,
|
|
|
128
131
|
return { ok: false, why: `${base} kept moving; push rejected twice. Worktree kept` };
|
|
129
132
|
}
|
|
130
133
|
|
|
134
|
+
// ---- the Git tab: a run's branch, its pull request and its cleanup, one step at a time
|
|
135
|
+
|
|
136
|
+
export type Pr = { number: number; url: string; state: "OPEN" | "MERGED" | "CLOSED"; draft: boolean };
|
|
137
|
+
export type Branch = { branch: string; base: string; upstream: boolean; landed: boolean; gh: boolean; pr: Pr | null; checking: boolean };
|
|
138
|
+
// The calls that wait on a network (push, fetch, gh): never on the board server's thread.
|
|
139
|
+
export type AsyncRun = (cmd: string[], cwd: string) => Promise<Out>;
|
|
140
|
+
|
|
141
|
+
// gh only knows GitHub. Asked once per project: the remote does not change under a board.
|
|
142
|
+
const githubs = new Map<string, boolean>();
|
|
143
|
+
const onGithub = (project: string) => {
|
|
144
|
+
let v = githubs.get(project);
|
|
145
|
+
if (v === undefined) githubs.set(project, (v = !!Bun.which("gh") && /github\.com/.test(git(project, "remote", "get-url", "origin").out)));
|
|
146
|
+
return v;
|
|
147
|
+
};
|
|
148
|
+
// One look at GitHub per run every 30 s, in the background; the panel shows the last answer.
|
|
149
|
+
const prs = new Map<string, { at: number; pr: Pr | null }>();
|
|
150
|
+
const looking = new Set<string>();
|
|
151
|
+
const prKey = (project: string, id: string) => `${project}\0${id}`;
|
|
152
|
+
const PR_JSON = ["--json", "number,url,state,isDraft"];
|
|
153
|
+
const parsePr = (r: Out): Pr | null => {
|
|
154
|
+
if (!r.ok) return null; // no pull request for the branch yet
|
|
155
|
+
try {
|
|
156
|
+
const j = JSON.parse(r.out);
|
|
157
|
+
return { number: j.number, url: j.url, state: j.state, draft: !!j.isDraft };
|
|
158
|
+
} catch { return null; }
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* What the Git tab shows for a run on its own branch: the branch against the base, and its
|
|
163
|
+
* pull request as last seen. A stale or missing answer starts one background `gh` look and
|
|
164
|
+
* calls `changed` when it lands, so the panel refreshes; the request never waits on GitHub.
|
|
165
|
+
*/
|
|
166
|
+
export function branchState(project: string, id: string, changed: () => void = () => {}, sh: Run = run, ash: AsyncRun = runAsync, hasGh = onGithub(project)): Branch | null {
|
|
167
|
+
if (!SLUG.test(id)) return null;
|
|
168
|
+
const dir = codeDir(project, id);
|
|
169
|
+
if (dir === project) return null; // committed in the project's own checkout: no branch of its own
|
|
170
|
+
const branch = branchOf(id), base = baseOf(project);
|
|
171
|
+
const upstream = sh(["git", "rev-parse", "--abbrev-ref", `${branch}@{u}`], dir).ok;
|
|
172
|
+
const k = prKey(project, id), hit = prs.get(k);
|
|
173
|
+
if (hasGh && (!hit || Date.now() - hit.at >= 30_000) && !looking.has(k)) {
|
|
174
|
+
looking.add(k);
|
|
175
|
+
void ash(["gh", "pr", "view", branch, ...PR_JSON], dir).then((r) => {
|
|
176
|
+
looking.delete(k);
|
|
177
|
+
const pr = parsePr(r);
|
|
178
|
+
const was = prs.get(k);
|
|
179
|
+
prs.set(k, { at: Date.now(), pr });
|
|
180
|
+
if (JSON.stringify(was?.pr ?? null) !== JSON.stringify(pr) || !was) changed();
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
const pr = hit?.pr ?? null;
|
|
184
|
+
// Landed counts only work that is on the base: a branch with no commits of its own is not "merged".
|
|
185
|
+
const own = sh(["git", "rev-list", "--count", `origin/${base}..${branch}`], dir);
|
|
186
|
+
const landedNow = pr?.state === "MERGED" || (own.ok && Number(own.out) > 0 && landed(dir, base, branch, sh));
|
|
187
|
+
return { branch, base, upstream, landed: landedNow, gh: hasGh, pr, checking: hasGh && !hit };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Pushes the branch, then opens its pull request against the base. */
|
|
191
|
+
export async function openPr(project: string, id: string, title: string, body: string, draft: boolean, sh: Run = run, ash: AsyncRun = runAsync, hasGh = onGithub(project)): Promise<{ ok: true; pr: Pr } | { ok: false; why: string }> {
|
|
192
|
+
if (!SLUG.test(id)) return { ok: false, why: `"${id}" is not a run id` };
|
|
193
|
+
const dir = codeDir(project, id), branch = branchOf(id);
|
|
194
|
+
if (dir === project) return { ok: false, why: "This run has no branch of its own." };
|
|
195
|
+
if (!hasGh) return { ok: false, why: "Pull requests need the GitHub CLI (gh) and a GitHub remote." };
|
|
196
|
+
if (!title.trim()) return { ok: false, why: "A pull request needs a title." };
|
|
197
|
+
if (sh(["git", "status", "--porcelain"], dir).out) return { ok: false, why: "Commit the changes first." };
|
|
198
|
+
const push = await ash(["git", "push", "-u", "origin", branch], dir);
|
|
199
|
+
if (!push.ok) return { ok: false, why: `Push of ${branch} failed: ${push.why}` };
|
|
200
|
+
const r = await ash(["gh", "pr", "create", "--base", baseOf(project), "--head", branch, "--title", title.trim(), "--body", body, ...(draft ? ["--draft"] : [])], dir);
|
|
201
|
+
// An existing pull request for the branch is fine: show that one.
|
|
202
|
+
if (!r.ok && !/already exists/i.test(r.why)) return { ok: false, why: `Pull request failed: ${r.why}` };
|
|
203
|
+
const pr = parsePr(await ash(["gh", "pr", "view", branch, ...PR_JSON], dir));
|
|
204
|
+
prs.set(prKey(project, id), { at: Date.now(), pr });
|
|
205
|
+
return pr ? { ok: true, pr } : { ok: false, why: "The pull request was made, but gh cannot find it yet. Look again in a moment." };
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** Merges the run's pull request by rebase, as `kaizen land` does. The worktree stays. */
|
|
209
|
+
export async function mergePr(project: string, id: string, sh: Run = run, ash: AsyncRun = runAsync, hasGh = onGithub(project)): Promise<{ ok: true } | { ok: false; why: string }> {
|
|
210
|
+
if (!SLUG.test(id)) return { ok: false, why: `"${id}" is not a run id` };
|
|
211
|
+
const dir = codeDir(project, id), branch = branchOf(id);
|
|
212
|
+
if (dir === project) return { ok: false, why: "This run has no branch of its own." };
|
|
213
|
+
if (!hasGh) return { ok: false, why: "Merging needs the GitHub CLI (gh) and a GitHub remote." };
|
|
214
|
+
const r = await ash(["gh", "pr", "merge", branch, "--rebase"], dir);
|
|
215
|
+
prs.delete(prKey(project, id));
|
|
216
|
+
if (!r.ok) return { ok: false, why: `Not merged: ${r.why}` };
|
|
217
|
+
await ash(["git", "fetch", "origin"], project); // so "landed" sees the merge at once
|
|
218
|
+
return { ok: true };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Removes the run's worktree and branch once its work is on the base. Refused while the
|
|
223
|
+
* worktree has changes or any commit of the branch is not on the base, so nothing is lost.
|
|
224
|
+
*/
|
|
225
|
+
export async function removeWorktree(project: string, id: string, sh: Run = run, ash: AsyncRun = runAsync): Promise<{ ok: true } | { ok: false; why: string }> {
|
|
226
|
+
if (!SLUG.test(id)) return { ok: false, why: `"${id}" is not a run id` };
|
|
227
|
+
const dir = codeDir(project, id), branch = branchOf(id);
|
|
228
|
+
if (dir === project) return { ok: false, why: "This run has no worktree." };
|
|
229
|
+
if (sh(["git", "status", "--porcelain"], dir).out) return { ok: false, why: "The worktree has uncommitted changes. Commit or discard them first." };
|
|
230
|
+
const f = await ash(["git", "fetch", "origin"], project);
|
|
231
|
+
if (!f.ok) return { ok: false, why: `Could not fetch origin, so nothing proves the work is on the base: ${f.why}` };
|
|
232
|
+
const base = baseOf(project);
|
|
233
|
+
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.` };
|
|
234
|
+
if (!landed(dir, base, branch, sh)) return { ok: false, why: `${branch} has commits that are not on ${base} yet. Merge its pull request first.` };
|
|
235
|
+
// Clean (checked above); --force is only for the untracked node_modules link.
|
|
236
|
+
const rm = sh(["git", "worktree", "remove", "--force", dir], project);
|
|
237
|
+
if (!rm.ok) return { ok: false, why: rm.why };
|
|
238
|
+
// Every commit is on the base by patch, so -D loses nothing a rebase-merge rewrote.
|
|
239
|
+
sh(["git", "branch", "-D", "--", branch], project);
|
|
240
|
+
await ash(["git", "push", "origin", "--delete", branch], project); // best effort: GitHub may have deleted it
|
|
241
|
+
prs.delete(prKey(project, id));
|
|
242
|
+
patchState(project, id, { worktree: null, branch: null });
|
|
243
|
+
return { ok: true };
|
|
244
|
+
}
|
|
245
|
+
|
|
131
246
|
export type Workspace = { path: string; branch: string; main: boolean };
|
|
132
247
|
const listed = new Map<string, { at: number; ws: Workspace[] }>();
|
|
133
248
|
const inside = (p: string, root: string) => p === root || p.startsWith(root + sep);
|
package/package.json
CHANGED