kaizen-agent 1.59.2 → 1.60.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli/add-project.test.ts +169 -0
- package/cli/add-project.ts +132 -0
- package/cli/board.test.ts +15 -0
- package/cli/chat.ts +1 -1
- package/cli/dashboard.ts +6 -2
- package/cli/install.test.ts +1 -1
- package/cli/install.ts +18 -9
- package/cli/pty.test.ts +89 -5
- package/cli/pty.ts +126 -9
- package/cli/restart.test.ts +169 -0
- package/cli/settings.test.ts +35 -0
- package/cli/settings.ts +69 -18
- package/cli/state.test.ts +119 -3
- package/cli/state.ts +171 -13
- package/cli/usage.test.ts +130 -1
- package/cli/web-accept.test.ts +54 -0
- package/cli/web-pr.test.ts +51 -0
- package/cli/web-symlink.test.ts +28 -0
- package/cli/web.ts +349 -100
- package/cli/worktree.test.ts +146 -1
- package/cli/worktree.ts +214 -4
- package/cli/writeback.ts +1 -1
- package/package.json +1 -1
- package/skills/kaizen/SKILL.md +5 -1
- package/skills/kaizen/config.default.yml +15 -2
- package/skills/kaizen/settings.md +1 -0
- package/skills/kaizen/spec-main.md +28 -2
- package/skills/kaizen-help/SKILL.md +1 -0
- package/web/board/add-project.ts +136 -0
- package/web/board/api.ts +1 -1
- package/web/board/badge.ts +5 -5
- package/web/board/cards.ts +11 -3
- package/web/board/context.ts +1 -0
- package/web/board/fixes.ts +3 -2
- package/web/board/git.ts +309 -60
- package/web/board/home.ts +7 -1
- package/web/board/ideas.ts +20 -3
- package/web/board/live.ts +1 -1
- package/web/board/main.ts +26 -9
- package/web/board/panel.ts +31 -16
- package/web/board/projects.ts +6 -85
- package/web/board/run-pick.ts +41 -0
- package/web/board/run-view.ts +286 -110
- 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/settings.ts +42 -5
- package/web/board/store.ts +3 -1
- package/web/board/toast.ts +4 -1
- package/web/board/views.ts +3 -1
- package/web/board/workspace.ts +127 -38
- package/web/board/ws-board-ui.ts +95 -0
- package/web/board/ws-board.test.ts +71 -0
- package/web/board/ws-board.ts +45 -0
- package/web/board/ws-tabs.test.ts +181 -0
- package/web/board/ws-tabs.ts +173 -0
- package/web/board.html +86 -36
- package/web/board.js +129 -44
- package/web/notebook.js +41 -24
- package/web/notes.html +26 -20
- package/web/term.js +1 -1
- package/web/video.html +26 -20
- package/web/video.js +76 -59
package/cli/state.test.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// State module against a throwaway .kaizen/. Nothing here spawns a terminal: the
|
|
2
2
|
// launch path is covered only up to the command it would run.
|
|
3
3
|
import { test, expect, beforeAll, afterAll } from "bun:test";
|
|
4
|
-
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, utimesSync, existsSync, readdirSync, realpathSync } from "node:fs";
|
|
4
|
+
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, utimesSync, existsSync, readdirSync, realpathSync, symlinkSync } from "node:fs";
|
|
5
5
|
import { join, dirname } from "node:path";
|
|
6
6
|
import { tmpdir } from "node:os";
|
|
7
7
|
import { issueUrl, systemInfo, scrubHome, REPO_URL, home as realHome, trustFolder } from "./state.ts";
|
|
@@ -516,7 +516,9 @@ test("commitPush: commits the run's files only, pushes, and records it; the mess
|
|
|
516
516
|
const files = () => (runGit(st, "r1") as any).files as string[];
|
|
517
517
|
expect(files()).toEqual(["?? .gitignore", "?? a.txt"]);
|
|
518
518
|
// The card's mark: the run with changed files is pending; one with none and no record says nothing.
|
|
519
|
-
|
|
519
|
+
const due1: Record<string, "commit" | "push"> = {};
|
|
520
|
+
expect(cardsGit(st, ["r1", "nope"], due1)).toEqual({ r1: "pending" });
|
|
521
|
+
expect(due1).toEqual({ r1: "commit" });
|
|
520
522
|
// An earlier run that named the same file is not offered it: the later report has it.
|
|
521
523
|
mkdirSync(join(st, "runs", "r0"));
|
|
522
524
|
writeFileSync(join(st, "runs", "r0", "03-impl.md"), "- `a.txt`: z\n");
|
|
@@ -564,7 +566,9 @@ test("commitPush: commits the run's files only, pushes, and records it; the mess
|
|
|
564
566
|
expect(readCommit(st, "r1")!.pushed).toBe(false);
|
|
565
567
|
expect(sh(proj, "show", "--name-only", "--format=", "HEAD")).toBe("b*.txt");
|
|
566
568
|
expect(runGit(st, "r1")).toMatchObject({ files: [], ahead: 1, others: 2 });
|
|
567
|
-
|
|
569
|
+
const due2: Record<string, "commit" | "push"> = {};
|
|
570
|
+
expect(cardsGit(st, ["r1"], due2)).toEqual({ r1: "pending" }); // committed, not pushed
|
|
571
|
+
expect(due2).toEqual({ r1: "push" });
|
|
568
572
|
expect(cardsGit(join(root, ".kaizen"), ["r1"])).toEqual({}); // not a repo
|
|
569
573
|
}, 60_000); // dozens of git calls, ~250ms each on Windows
|
|
570
574
|
|
|
@@ -827,6 +831,25 @@ console.log(JSON.stringify([require("node:fs").readFileSync(REGISTRY, "utf8"), k
|
|
|
827
831
|
} finally { rmSync(home, { recursive: true, force: true }); }
|
|
828
832
|
});
|
|
829
833
|
|
|
834
|
+
test("the project registry lists one folder once: trailing slash and symlink spellings collapse, the file is not rewritten", () => {
|
|
835
|
+
const home = mkdtempSync(join(tmpdir(), "kz-home-")), proj = join(home, "shop");
|
|
836
|
+
mkdirSync(proj);
|
|
837
|
+
symlinkSync(proj, join(home, "link"));
|
|
838
|
+
mkdirSync(join(home, ".kaizen"));
|
|
839
|
+
const dup = `${proj}\n${proj}/\n${join(home, "link")}\n`;
|
|
840
|
+
writeFileSync(join(home, ".kaizen", "projects"), dup);
|
|
841
|
+
const script = `const { remember, knownProjects, REGISTRY } = await import(${JSON.stringify(join(dirname(import.meta.path), "state.ts"))});
|
|
842
|
+
remember(${JSON.stringify(join(home, "link") + "/")});
|
|
843
|
+
console.log(JSON.stringify([knownProjects(), require("node:fs").readFileSync(REGISTRY, "utf8")]));`;
|
|
844
|
+
try {
|
|
845
|
+
const p = Bun.spawnSync(["bun", "-e", script], { cwd: home, env: { ...process.env, HOME: home, USERPROFILE: home } });
|
|
846
|
+
if (p.exitCode !== 0) throw new Error(p.stderr.toString());
|
|
847
|
+
const [list, file] = JSON.parse(p.stdout.toString());
|
|
848
|
+
expect(list).toEqual([realpathSync(proj)]);
|
|
849
|
+
expect(file).toBe(dup); // already known: nothing appended, nothing rewritten
|
|
850
|
+
} finally { rmSync(home, { recursive: true, force: true }); }
|
|
851
|
+
});
|
|
852
|
+
|
|
830
853
|
test("files saved with CRLF (PowerShell, autocrlf clones) read the same as LF", () => {
|
|
831
854
|
const lf = join(mkdtempSync(join(tmpdir(), "kz-")), ".kaizen"), crlf = join(mkdtempSync(join(tmpdir(), "kz-")), ".kaizen");
|
|
832
855
|
const files = {
|
|
@@ -1325,3 +1348,96 @@ test("winShim swaps an npm .cmd shim for the .ps1 beside it, so a multi-line pro
|
|
|
1325
1348
|
expect(winShim("C:\\npm\\codex.CMD", () => false)).toBe("C:\\npm\\codex.CMD");
|
|
1326
1349
|
expect(winShim("C:\\bin\\claude.exe", () => true)).toBe("C:\\bin\\claude.exe");
|
|
1327
1350
|
});
|
|
1351
|
+
|
|
1352
|
+
test("final-approval gate: changed files need an accepted: line once approvals.review is on", async () => {
|
|
1353
|
+
const { gateOf, acceptance, recordAcceptance, changedPaths } = stateModule;
|
|
1354
|
+
const proj = mkdtempSync(join(tmpdir(), "kz-gate-")), st = join(proj, ".kaizen");
|
|
1355
|
+
mkdirSync(join(proj, "cli"), { recursive: true });
|
|
1356
|
+
writeFileSync(join(proj, "cli", "a.ts"), "");
|
|
1357
|
+
const mk = (id: string, s: object, impl?: string, approval?: string) => {
|
|
1358
|
+
const d = join(st, "runs", id);
|
|
1359
|
+
mkdirSync(d, { recursive: true });
|
|
1360
|
+
writeFileSync(join(d, "state.json"), JSON.stringify(s));
|
|
1361
|
+
if (impl) writeFileSync(join(d, "03-impl.md"), impl);
|
|
1362
|
+
if (approval) writeFileSync(join(d, "02-approval.md"), approval);
|
|
1363
|
+
};
|
|
1364
|
+
const impl = "## Changed\n- `cli/a.ts:12` — the fix\n- ran `bun test`, see `missing/file.ts`\n";
|
|
1365
|
+
expect(changedPaths(impl, proj)).toEqual(["cli/a.ts"]); // only paths that exist; commands ignored
|
|
1366
|
+
mkdirSync(st, { recursive: true });
|
|
1367
|
+
writeFileSync(join(st, "config.yml"), "approvals:\n plan: true\n review: true\n");
|
|
1368
|
+
mk("2026-10-28-old", { stage: "done" }, impl); // before the gate: never flagged
|
|
1369
|
+
mk("2026-10-29-none", { stage: "done" }, "## Changed\nnothing\n"); // no files: free to finish
|
|
1370
|
+
mk("2026-10-29-needs", { stage: "done" }, impl, "plan approved\naccepted: soon, the user said\n");
|
|
1371
|
+
mk("2026-10-29-auto", { stage: "done" }, impl, "accepted: 2026-10-29T10:00:00Z auto (auto_accept)\n");
|
|
1372
|
+
mk("2026-10-29-build", { stage: "build" }, impl);
|
|
1373
|
+
expect(gateOf(st, "2026-10-28-old")).toBeNull();
|
|
1374
|
+
expect(gateOf(st, "2026-10-29-none")).toBeNull();
|
|
1375
|
+
expect(gateOf(st, "2026-10-29-build")).toBeNull();
|
|
1376
|
+
expect(gateOf(st, "2026-10-29-needs")).toBe("needs"); // a prose line does not count
|
|
1377
|
+
expect(gateOf(st, "2026-10-29-auto")).toBe("auto");
|
|
1378
|
+
expect(boardCards([st], Date.now()).find((c) => c.id === "2026-10-29-needs")).toMatchObject({ status: "waiting", awaiting: "approvals.review" });
|
|
1379
|
+
expect(notice({ kind: "run", text: "x", where: "p", status: "done", accept: "needs" } as Card)).toContain("done, not approved");
|
|
1380
|
+
expect(recordAcceptance(st, "2026-10-29-needs", "board")).toBeNull();
|
|
1381
|
+
expect(acceptance(st, "2026-10-29-needs")).toBe("user");
|
|
1382
|
+
expect(recordAcceptance(st, "2026-10-29-needs", "chat")).toBe("That run is already approved.");
|
|
1383
|
+
expect(gateOf(st, "2026-10-29-needs")).toBe("user");
|
|
1384
|
+
// Hand-edited shapes still read as on: a column-0 comment, CRLF, quotes, a trailing comment.
|
|
1385
|
+
mk("2026-10-29-shapes", { stage: "done" }, impl);
|
|
1386
|
+
writeFileSync(join(st, "config.yml"), 'approvals: # stops\r\n# the final one\r\n plan: true\r\n\r\n review: "true" # yes\r\n');
|
|
1387
|
+
expect(gateOf(st, "2026-10-29-shapes")).toBe("needs");
|
|
1388
|
+
writeFileSync(join(st, "config.yml"), "approvals: {plan: true, review: false}\n");
|
|
1389
|
+
expect(gateOf(st, "2026-10-29-shapes")).toBeNull();
|
|
1390
|
+
// A file only mentioned outside the change list does not count; a name with spaces does.
|
|
1391
|
+
mkdirSync(join(proj, "notes"), { recursive: true });
|
|
1392
|
+
writeFileSync(join(proj, "notes", "Release and testing.md"), "");
|
|
1393
|
+
expect(changedPaths("## Changed\n- `notes/Release and testing.md`\n\n## Verification\nread `cli/a.ts`\n", proj)).toEqual(["notes/Release and testing.md"]);
|
|
1394
|
+
// The user's pick: with approvals.review off, nothing is gated.
|
|
1395
|
+
mk("2026-10-29-off", { stage: "done" }, impl);
|
|
1396
|
+
writeFileSync(join(st, "config.yml"), "approvals:\n review: false\n");
|
|
1397
|
+
expect(gateOf(st, "2026-10-29-off")).toBeNull();
|
|
1398
|
+
writeFileSync(join(st, "config.yml"), "approvals:\n review: true\n");
|
|
1399
|
+
expect(await commitPush(st, "2026-10-29-off", "fix: x", [])).toMatchObject({ ok: false });
|
|
1400
|
+
});
|
|
1401
|
+
|
|
1402
|
+
test("gate: a run marked done without acceptance reads, heals and finishes as review", () => {
|
|
1403
|
+
const { readRuns, healRuns, finishRun, gateOf } = stateModule;
|
|
1404
|
+
const proj = mkdtempSync(join(tmpdir(), "kz-heal-")), st = join(proj, ".kaizen");
|
|
1405
|
+
mkdirSync(join(proj, "cli"), { recursive: true });
|
|
1406
|
+
writeFileSync(join(proj, "cli", "a.ts"), "");
|
|
1407
|
+
const impl = "## Changed\n- `cli/a.ts`\n";
|
|
1408
|
+
const mk = (id: string, approval?: string, i = impl) => {
|
|
1409
|
+
const d = join(st, "runs", id);
|
|
1410
|
+
mkdirSync(d, { recursive: true });
|
|
1411
|
+
writeFileSync(join(d, "state.json"), JSON.stringify({ stage: "done" }));
|
|
1412
|
+
writeFileSync(join(d, "03-impl.md"), i);
|
|
1413
|
+
if (approval) writeFileSync(join(d, "02-approval.md"), approval);
|
|
1414
|
+
};
|
|
1415
|
+
const stageOf = (id: string) => JSON.parse(readFileSync(join(st, "runs", id, "state.json"), "utf8"));
|
|
1416
|
+
mkdirSync(st, { recursive: true });
|
|
1417
|
+
writeFileSync(join(st, "config.yml"), "approvals:\n review: true\n");
|
|
1418
|
+
mk("2026-10-29-needs"); mk("2026-10-29-ok", "accepted: 2026-10-29T10:00:00Z by user via board\n");
|
|
1419
|
+
mk("2026-10-29-none", undefined, "nothing\n"); mk("2026-10-28-old");
|
|
1420
|
+
const row = (id: string) => readRuns(st).find((r) => r.id === id)!;
|
|
1421
|
+
expect(row("2026-10-29-needs")).toMatchObject({ stage: "review", awaiting: "approvals.review" });
|
|
1422
|
+
for (const id of ["2026-10-29-ok", "2026-10-29-none", "2026-10-28-old"]) expect(row(id).stage).toBe("done");
|
|
1423
|
+
expect(stageOf("2026-10-29-needs").stage).toBe("done"); // reads stay pure
|
|
1424
|
+
expect(healRuns(st)).toEqual(["2026-10-29-needs"]);
|
|
1425
|
+
expect(stageOf("2026-10-29-needs")).toMatchObject({ stage: "review", awaiting: "approvals.review" });
|
|
1426
|
+
expect(healRuns(st)).toEqual([]); // idempotent
|
|
1427
|
+
expect(stageOf("2026-10-29-needs").healed).toBe(true);
|
|
1428
|
+
expect(row("2026-10-29-needs").healed).toBe(true);
|
|
1429
|
+
expect(gateOf(st, "2026-10-29-needs")).toBe("needs");
|
|
1430
|
+
expect(finishRun(st, "2026-10-29-needs")).toContain("--user-approved");
|
|
1431
|
+
expect(stageOf("2026-10-29-needs").stage).toBe("review");
|
|
1432
|
+
expect(finishRun(st, "2026-10-29-needs", true)).toBeNull();
|
|
1433
|
+
expect(readFileSync(join(st, "runs", "2026-10-29-needs", "02-approval.md"), "utf8")).toContain("by user via chat");
|
|
1434
|
+
expect(stageOf("2026-10-29-needs")).toMatchObject({ stage: "done", awaiting: null });
|
|
1435
|
+
expect(stageOf("2026-10-29-needs").healed).toBeUndefined();
|
|
1436
|
+
expect(row("2026-10-29-needs").stage).toBe("done");
|
|
1437
|
+
expect(finishRun(st, "2026-10-29-none")).toBeNull(); // nothing changed: free to finish
|
|
1438
|
+
// Gate off: a done run stays done.
|
|
1439
|
+
writeFileSync(join(st, "config.yml"), "approvals:\n review: false\n");
|
|
1440
|
+
mk("2026-10-29-off");
|
|
1441
|
+
expect(row("2026-10-29-off").stage).toBe("done");
|
|
1442
|
+
rmSync(proj, { recursive: true, force: true });
|
|
1443
|
+
});
|
package/cli/state.ts
CHANGED
|
@@ -5,14 +5,14 @@ import { existsSync, readFileSync, readdirSync, appendFileSync, writeFileSync, m
|
|
|
5
5
|
import { Database } from "bun:sqlite";
|
|
6
6
|
import { join, dirname, sep, win32, posix } from "node:path";
|
|
7
7
|
import { homedir, arch, cpus, release, totalmem, version as osVersion } from "node:os";
|
|
8
|
-
import { startPty, ptySupported } from "./pty.ts";
|
|
9
|
-
import { codeDir, projectFromWorktree } from "./worktree.ts";
|
|
8
|
+
import { startPty, ptySupported, killTmux, tmuxName } from "./pty.ts";
|
|
9
|
+
import { codeDir, projectFromWorktree, wsOf } from "./worktree.ts";
|
|
10
10
|
|
|
11
11
|
// The real path: process.cwd() is always physical, so a raw $HOME that crosses a
|
|
12
12
|
// symlink (/home -> var/home) would never compare equal to it.
|
|
13
13
|
export const home = (() => { try { return realpathSync(homedir()); } catch { return homedir(); } })();
|
|
14
14
|
|
|
15
|
-
export type Run = { id: string; stage: string; awaiting: string | null; moved: number; runner?: string; agent?: string; branch?: string };
|
|
15
|
+
export type Run = { id: string; stage: string; awaiting: string | null; moved: number; runner?: string; agent?: string; branch?: string; worktree?: string; workspace?: string; healed?: boolean };
|
|
16
16
|
|
|
17
17
|
export const KNOWN_AGENTS = [
|
|
18
18
|
{ name: "Claude Code", dir: ".claude", cmd: "claude" },
|
|
@@ -324,7 +324,7 @@ export function knownProjects(): string[] {
|
|
|
324
324
|
return readText(REGISTRY).split("\n")
|
|
325
325
|
.map((l) => l.trim())
|
|
326
326
|
.filter((l) => l && !l.startsWith("#"))
|
|
327
|
-
.map(
|
|
327
|
+
.map(canonPath)
|
|
328
328
|
.filter((d, i, all) => all.indexOf(d) === i);
|
|
329
329
|
}
|
|
330
330
|
|
|
@@ -337,11 +337,20 @@ export function nativePath(p: string) {
|
|
|
337
337
|
return win32.resolve(p.replace(/^\/([a-zA-Z])(?=\/|$)/, "$1:/")).replace(/^[a-z]:/, (d) => d.toUpperCase());
|
|
338
338
|
}
|
|
339
339
|
|
|
340
|
+
// One spelling per folder: no trailing slash, symlinks resolved when the folder exists
|
|
341
|
+
// (Windows keeps nativePath's spelling), so a project never lists twice.
|
|
342
|
+
export function canonPath(p: string) {
|
|
343
|
+
p = nativePath(p);
|
|
344
|
+
if (process.platform === "win32") return p;
|
|
345
|
+
if (p.length > 1) p = p.replace(/\/+$/, "") || "/";
|
|
346
|
+
try { return realpathSync(p); } catch { return p; }
|
|
347
|
+
}
|
|
348
|
+
|
|
340
349
|
// Never fails the command that triggered it: a read-only home is not a reason for a
|
|
341
350
|
// dashboard to stop opening.
|
|
342
351
|
export function remember(projectDir: string) {
|
|
343
352
|
try {
|
|
344
|
-
projectDir =
|
|
353
|
+
projectDir = canonPath(projectDir);
|
|
345
354
|
if (knownProjects().includes(projectDir)) return;
|
|
346
355
|
mkdirSync(dirname(REGISTRY), { recursive: true });
|
|
347
356
|
appendFileSync(REGISTRY, projectDir + "\n");
|
|
@@ -414,7 +423,9 @@ export function readRuns(state: string): Run[] {
|
|
|
414
423
|
let moved = 0;
|
|
415
424
|
try { moved = statSync(file).mtimeMs; } catch { /* vanished mid-read */ }
|
|
416
425
|
try { moved = Math.max(moved, statSync(join(dir, id, "progress.md")).mtimeMs); } catch { /* no progress kept */ }
|
|
417
|
-
|
|
426
|
+
// Done without the user's acceptance is not done: every reader sees it waiting on approval.
|
|
427
|
+
const unapproved = s.stage === "done" && accepted(state, id).accept === "needs";
|
|
428
|
+
const run = { id, stage: unapproved ? "review" : s.stage ?? "?", awaiting: unapproved ? "approvals.review" : s.awaiting ?? null, moved, runner: s.runner, agent: s.agent, branch: typeof s.branch === "string" ? s.branch : undefined, worktree: typeof s.worktree === "string" ? s.worktree : undefined, workspace: typeof s.workspace === "string" ? s.workspace : undefined, healed: unapproved || (s.healed === true && s.awaiting === "approvals.review") || undefined };
|
|
418
429
|
lastRun.set(runDir, run);
|
|
419
430
|
return [run];
|
|
420
431
|
} catch { return existsSync(join(runDir, "state.json")) ? [lastRun.get(runDir)].filter((r): r is Run => !!r) : []; }
|
|
@@ -751,10 +762,13 @@ export type Card = {
|
|
|
751
762
|
title?: string; // runs only: first line of the request
|
|
752
763
|
archived: boolean; // hidden from the board unless asked for
|
|
753
764
|
branch?: string; // runs only: the run's own branch while it has a worktree
|
|
765
|
+
ws?: string; // runs only: its workspace folder (worktree, else the project)
|
|
754
766
|
tags?: string[]; // runs only: runner, agent, "yolo", "unrechecked"
|
|
755
767
|
notes?: string; // inbox notes, or runs/<id>/notes.md
|
|
756
768
|
parent?: string; // the run this card was filed from
|
|
757
769
|
children?: string[]; // runs only: runs that name this one as parent
|
|
770
|
+
healed?: boolean; // runs only: finished by an agent, never approved; Approve finishes it, no agent
|
|
771
|
+
accept?: "needs" | "auto"; // done runs only: changed files with no acceptance, or auto-accepted
|
|
758
772
|
};
|
|
759
773
|
|
|
760
774
|
// A `Parent: <run id>` line (or the older `Follow-up of: <run id>`) in a request or
|
|
@@ -979,7 +993,7 @@ const NEED: Record<string, string> = {
|
|
|
979
993
|
};
|
|
980
994
|
export function notice(c: Card): string | null {
|
|
981
995
|
if (c.kind !== "run") return null;
|
|
982
|
-
const what = c.awaiting ? NEED[c.awaiting] ?? `waiting on ${c.awaiting}` : c.status === "done" ? "done" : null;
|
|
996
|
+
const what = c.awaiting ? NEED[c.awaiting] ?? `waiting on ${c.awaiting}` : c.status === "done" ? (c.accept === "needs" ? "done, not approved" : "done") : null;
|
|
983
997
|
return what && `${c.text} — ${what}\n${c.where}`;
|
|
984
998
|
}
|
|
985
999
|
|
|
@@ -1158,6 +1172,24 @@ export function requestTitle(text: string) {
|
|
|
1158
1172
|
// Every card on the board, for the state dirs asked for. Retirement of an idea is
|
|
1159
1173
|
// checked against every known project's runs, not just these: an idea in the global
|
|
1160
1174
|
// inbox becomes a run in whichever project the agent was started in.
|
|
1175
|
+
// The gate reads a done run's reports on every refresh: kept per run until one of the
|
|
1176
|
+
// files it reads changes (stat only), so a project of many done runs costs no reads.
|
|
1177
|
+
const gates = new Map<string, { at: string; g: ReturnType<typeof gateOf> }>();
|
|
1178
|
+
const accepted = (st: string, id: string): { accept?: "needs" | "auto" } => {
|
|
1179
|
+
if (id.slice(0, 10) < GATE_FROM) return {};
|
|
1180
|
+
const base = join(st, "runs", id), project = projectOf(st);
|
|
1181
|
+
const its = join(base, "05-iterations");
|
|
1182
|
+
let fixes: string[] = [];
|
|
1183
|
+
try { fixes = readdirSync(its).map((n) => join(its, n)); } catch {}
|
|
1184
|
+
// ponytail: a listed file deleted or created later is not in the key; it is seen at the
|
|
1185
|
+
// next write to any file here.
|
|
1186
|
+
const at = [join(base, "state.json"), join(base, "02-approval.md"), join(base, "03-impl.md"), ...fixes,
|
|
1187
|
+
join(project, ".kaizen", "config.yml"), join(home, ".kaizen", "config.yml")]
|
|
1188
|
+
.map((f) => { try { return statSync(f).mtimeMs; } catch { return 0; } }).join();
|
|
1189
|
+
let hit = gates.get(base);
|
|
1190
|
+
if (!hit || hit.at !== at) gates.set(base, (hit = { at, g: gateOf(st, id) }));
|
|
1191
|
+
return hit.g === "needs" || hit.g === "auto" ? { accept: hit.g } : {};
|
|
1192
|
+
};
|
|
1161
1193
|
export function boardCards(states: string[], now: number): Card[] {
|
|
1162
1194
|
const next: Card[] = [];
|
|
1163
1195
|
// One read per request file; both the retirement check and the card title come
|
|
@@ -1225,9 +1257,13 @@ export function boardCards(states: string[], now: number): Card[] {
|
|
|
1225
1257
|
dim: r.stage === "abandoned",
|
|
1226
1258
|
archived: archive.has(r.id),
|
|
1227
1259
|
branch: r.branch,
|
|
1260
|
+
// The workspace it is in: its worktree while that exists, else the main checkout.
|
|
1261
|
+
ws: st === join(home, ".kaizen") ? st : wsOf(projectOf(st), r),
|
|
1228
1262
|
tags: [r.runner, r.agent, yolos.has(r.id) ? "yolo" : undefined, unrechecked(st, r.id) ? "unrechecked" : undefined].filter((t): t is string => !!t),
|
|
1229
1263
|
notes: readNotes(st, r.id) || undefined,
|
|
1230
1264
|
parent: parentOf(body(st, r.id)),
|
|
1265
|
+
...(r.healed ? { healed: true } : {}),
|
|
1266
|
+
...(r.stage === "done" ? accepted(st, r.id) : {}),
|
|
1231
1267
|
});
|
|
1232
1268
|
}
|
|
1233
1269
|
}
|
|
@@ -1460,6 +1496,15 @@ export function closeEnabled(projectDir: string) {
|
|
|
1460
1496
|
}
|
|
1461
1497
|
|
|
1462
1498
|
// agent.launch in the config chain: where the web board runs what it launches.
|
|
1499
|
+
// agent.keep_alive: tmux keeps a card's agent in a tmux session that outlives the board.
|
|
1500
|
+
export function keepAlive(projectDir: string): "off" | "tmux" {
|
|
1501
|
+
for (const t of configTexts(projectDir)) {
|
|
1502
|
+
const m = /^agent:\n(?:[ \t]+.*\n)*?[ \t]+keep_alive:[ \t]*["']?([^"'\s]+)/m.exec(t) || /^agent\.keep_alive:[ \t]*["']?([^"'\s]+)/m.exec(t);
|
|
1503
|
+
if (m) return m[1] === "tmux" ? "tmux" : "off";
|
|
1504
|
+
}
|
|
1505
|
+
return "off";
|
|
1506
|
+
}
|
|
1507
|
+
|
|
1463
1508
|
export function launchMode(projectDir: string): "card" | "terminal" {
|
|
1464
1509
|
for (const t of configTexts(projectDir)) {
|
|
1465
1510
|
const m = /^agent:\n(?:[ \t]+.*\n)*?[ \t]+launch:[ \t]*["']?([^"'\s]+)/m.exec(t) || /^agent\.launch:[ \t]*["']?([^"'\s]+)/m.exec(t);
|
|
@@ -1509,7 +1554,13 @@ function closeOne(st: string, s: Session): boolean {
|
|
|
1509
1554
|
const kids = Bun.spawnSync([powershellExe(), "-NoProfile", "-NonInteractive", "-Command", `(Get-CimInstance Win32_Process -Filter 'ParentProcessId=${pid}').ProcessId`], { stdin: "ignore", stderr: "ignore", timeout: 10000, windowsHide: true }).stdout.toString().match(/\d+/g) ?? [];
|
|
1510
1555
|
// No children (a launch from before this): the PowerShell itself, as before.
|
|
1511
1556
|
for (const k of kids.length ? kids : [String(pid)]) Bun.spawnSync([sysExe("taskkill.exe"), "/T", "/F", "/PID", k], { stdin: "ignore", stdout: "ignore", stderr: "ignore", timeout: 5000, windowsHide: true });
|
|
1512
|
-
} else
|
|
1557
|
+
} else {
|
|
1558
|
+
// The whole group: an agent in a card or terminal leads its own, and what it
|
|
1559
|
+
// started (a test run, a dev server) would otherwise outlive it.
|
|
1560
|
+
try { process.kill(-pid, "SIGTERM"); } catch { process.kill(pid, "SIGTERM"); }
|
|
1561
|
+
// A tmux-kept agent: the PID is only its client.
|
|
1562
|
+
killTmux(tmuxName(s.key));
|
|
1563
|
+
}
|
|
1513
1564
|
closed = true;
|
|
1514
1565
|
}
|
|
1515
1566
|
} catch { /* already gone */ }
|
|
@@ -1638,7 +1689,7 @@ export const CHILD_ENV = /^(CLAUDECODE|CLAUDE_PID|CLAUDE_CODE_(SESSION_ID|CHILD_
|
|
|
1638
1689
|
// skill: start that skill instead of /kaizen (the Video page starts kaizen-video), in cwd:
|
|
1639
1690
|
// a work folder that may not be a project, so it is not remembered as one. A session record is
|
|
1640
1691
|
// written only where that folder has a .kaizen (a project place does; the library usually not).
|
|
1641
|
-
export function launchRun(it: Item, from: string, run?: string, pick: { agent?: string; model?: string; yolo?: boolean; card?: boolean; onChange?: () => void; skill?: "kaizen-video"; cwd?: string } = {}): Launch {
|
|
1692
|
+
export function launchRun(it: Item, from: string, run?: string, pick: { agent?: string; model?: string; yolo?: boolean; card?: boolean; onChange?: () => void; skill?: "kaizen-video"; cwd?: string; seed?: string } = {}): Launch {
|
|
1642
1693
|
const projectDir = pick.cwd ?? projectOf(from);
|
|
1643
1694
|
// The run will be born here; the board must know the dir or the idea never retires.
|
|
1644
1695
|
if (!pick.cwd) remember(projectDir);
|
|
@@ -1672,7 +1723,7 @@ export function launchRun(it: Item, from: string, run?: string, pick: { agent?:
|
|
|
1672
1723
|
if (pick.card && ptySupported) {
|
|
1673
1724
|
const key = s.key ?? `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
1674
1725
|
try {
|
|
1675
|
-
startPty(key, s.fullCmd, projectDir, s.pidFile, pick.onChange);
|
|
1726
|
+
startPty(key, s.fullCmd, projectDir, s.pidFile, pick.onChange, { seed: pick.seed, tmux: keepAlive(projectDir) === "tmux" ? tmuxName(key) : undefined });
|
|
1676
1727
|
return { ok: true, agent, prompt, projectDir, cmd: s.fullCmd, pty: key };
|
|
1677
1728
|
} catch (err: any) {
|
|
1678
1729
|
drop();
|
|
@@ -1784,6 +1835,111 @@ function runReport(state: string, id: string) {
|
|
|
1784
1835
|
for (const f of [join(base, "03-impl.md"), ...fixes]) try { text += readText(f) + "\n"; at = Math.max(at, statSync(f).mtimeMs); } catch {}
|
|
1785
1836
|
return { text, at };
|
|
1786
1837
|
}
|
|
1838
|
+
// The final-approval gate. A run that changed files is only accepted by an
|
|
1839
|
+
// `accepted:` line in its 02-approval.md, written by the board's Approve, by the main
|
|
1840
|
+
// thread on an approval in chat, or by an auto run under auto_accept. Agents can still
|
|
1841
|
+
// write `stage: done` themselves; the gate makes that visible and refuses the commit.
|
|
1842
|
+
// Runs started before GATE_FROM are never flagged.
|
|
1843
|
+
export const GATE_FROM = "2026-10-29";
|
|
1844
|
+
const ACCEPTED = /^accepted: \S+ (by user via (board|chat)|auto \(auto_accept\))\s*$/m;
|
|
1845
|
+
// The files a report names in backticks that exist in the project: the same
|
|
1846
|
+
// convention the board commits by.
|
|
1847
|
+
// Only the sections that list changes ("## Changed", "### What changed", "## Files"),
|
|
1848
|
+
// so a file a report merely mentions elsewhere does not count; a report with no such
|
|
1849
|
+
// heading is read whole.
|
|
1850
|
+
const changeSections = (report: string) => {
|
|
1851
|
+
const parts = report.split(/^(?=#{2,3} )/m).filter((p) => /^#{2,3} .*(chang|files)/i.test(p));
|
|
1852
|
+
return parts.length ? parts.join("\n") : report;
|
|
1853
|
+
};
|
|
1854
|
+
export function changedPaths(report: string, projectDir: string): string[] {
|
|
1855
|
+
const out = new Set<string>();
|
|
1856
|
+
for (const m of changeSections(report).matchAll(/`([^`\n]+)`/g)) {
|
|
1857
|
+
const p = m[1].replace(/:\d+(-\d+)?$/, "");
|
|
1858
|
+
if (/[/.]/.test(p) && !p.startsWith("/") && !p.includes("..") && !/^https?:/.test(p) && existsSync(join(projectDir, p))) out.add(p);
|
|
1859
|
+
}
|
|
1860
|
+
return [...out];
|
|
1861
|
+
}
|
|
1862
|
+
export function acceptance(state: string, id: string): "user" | "auto" | null {
|
|
1863
|
+
try {
|
|
1864
|
+
const m = ACCEPTED.exec(readText(join(state, "runs", id, "02-approval.md")));
|
|
1865
|
+
return m ? (m[1].startsWith("auto") ? "auto" : "user") : null;
|
|
1866
|
+
} catch { return null; }
|
|
1867
|
+
}
|
|
1868
|
+
export function recordAcceptance(state: string, id: string, via: "board" | "chat" | "auto"): string | null {
|
|
1869
|
+
if (acceptance(state, id)) return "That run is already approved.";
|
|
1870
|
+
const who = via === "auto" ? "auto (auto_accept)" : `by user via ${via}`;
|
|
1871
|
+
appendFileSync(join(state, "runs", id, "02-approval.md"), `\naccepted: ${new Date().toISOString()} ${who}\n`);
|
|
1872
|
+
return null;
|
|
1873
|
+
}
|
|
1874
|
+
// The first config.yml in the chain that sets approvals.review; off when none does,
|
|
1875
|
+
// as in config.default.yml.
|
|
1876
|
+
function reviewGateOn(projectDir: string): boolean {
|
|
1877
|
+
for (const t of configTexts(projectDir)) {
|
|
1878
|
+
// Comments, CRLF and quotes are what a hand-edited file holds; none may switch the gate off.
|
|
1879
|
+
const clean = t.replace(/\r/g, "").split("\n").map((l) => l.replace(/(^|\s)#.*$/, "").trimEnd()).filter(Boolean).join("\n") + "\n";
|
|
1880
|
+
const m = /^approvals:\n(?:[ \t]+.*\n)*?[ \t]+review:[ \t]*["']?(true|false)["']?$/m.exec(clean);
|
|
1881
|
+
if (m) return m[1] === "true";
|
|
1882
|
+
const flow = /^approvals:[ \t]*\{[^}]*\breview:[ \t]*["']?(true|false)/m.exec(clean);
|
|
1883
|
+
if (flow) return flow[1] === "true";
|
|
1884
|
+
}
|
|
1885
|
+
return false;
|
|
1886
|
+
}
|
|
1887
|
+
// "needs": changed files, no acceptance, and the gate is on. Null where the gate does
|
|
1888
|
+
// not apply: an older run, a run not marked done, one that changed nothing.
|
|
1889
|
+
export function gateOf(state: string, id: string): "needs" | "user" | "auto" | null {
|
|
1890
|
+
if (id.slice(0, 10) < GATE_FROM) return null;
|
|
1891
|
+
let run: any;
|
|
1892
|
+
try { run = JSON.parse(readText(join(state, "runs", id, "state.json"))); } catch { return null; }
|
|
1893
|
+
if (run.stage !== "done" && run.awaiting !== "approvals.review") return null;
|
|
1894
|
+
const projectDir = projectOf(state);
|
|
1895
|
+
if (!changedPaths(runReport(state, id).text, codeDir(projectDir, id)).length) return null;
|
|
1896
|
+
const a = acceptance(state, id);
|
|
1897
|
+
if (a) return a;
|
|
1898
|
+
return reviewGateOn(projectDir) ? "needs" : null;
|
|
1899
|
+
}
|
|
1900
|
+
// Atomic state.json edit (tmp + rename); skipped if the file changed since it was read.
|
|
1901
|
+
// Limit: a write landing between the mtime check and the rename is lost, and two writes
|
|
1902
|
+
// inside one mtime tick look like none; heal is idempotent, so a lost write is rare and re-done.
|
|
1903
|
+
function setStage(file: string, change: (s: any) => boolean): boolean {
|
|
1904
|
+
try {
|
|
1905
|
+
const before = statSync(file).mtimeMs, s = JSON.parse(readText(file));
|
|
1906
|
+
if (!change(s)) return false;
|
|
1907
|
+
s.updated = new Date().toISOString();
|
|
1908
|
+
const tmp = file + `.${process.pid}.tmp`;
|
|
1909
|
+
writeFileSync(tmp, JSON.stringify(s, null, 2) + "\n");
|
|
1910
|
+
if (statSync(file).mtimeMs !== before) { rmSync(tmp, { force: true }); return false; } // an agent wrote meanwhile
|
|
1911
|
+
renameSync(tmp, file);
|
|
1912
|
+
return true;
|
|
1913
|
+
} catch { return false; }
|
|
1914
|
+
}
|
|
1915
|
+
// Rewrites runs an agent marked done without acceptance (gate on) to review /
|
|
1916
|
+
// approvals.review; returns the ids. Not part of readRuns: reads stay pure (mtime is liveness).
|
|
1917
|
+
export function healRuns(state: string): string[] {
|
|
1918
|
+
const dir = join(state, "runs");
|
|
1919
|
+
if (!existsSync(dir)) return [];
|
|
1920
|
+
return readdirSync(dir).filter((id) => {
|
|
1921
|
+
const file = join(dir, id, "state.json");
|
|
1922
|
+
try { if (!/"stage":\s*"done"/.test(readText(file))) return false; } catch { return false; } // cheap: skip runs not done
|
|
1923
|
+
return accepted(state, id).accept === "needs" && setStage(file, (s) => {
|
|
1924
|
+
if (s.stage !== "done") return false;
|
|
1925
|
+
s.stage = "review"; s.awaiting = "approvals.review"; s.healed = true;
|
|
1926
|
+
return true;
|
|
1927
|
+
});
|
|
1928
|
+
});
|
|
1929
|
+
}
|
|
1930
|
+
// The one way to finish a run. Refuses while the gate says the user has not approved;
|
|
1931
|
+
// userApproved records the acceptance first. An agent can still forge the flag: this stops shortcuts, not malice.
|
|
1932
|
+
export function finishRun(state: string, id: string, userApproved = false): string | null {
|
|
1933
|
+
const file = join(state, "runs", id, "state.json");
|
|
1934
|
+
if (!existsSync(file)) return `No run ${id}.`;
|
|
1935
|
+
if (gateOf(state, id) === "needs") {
|
|
1936
|
+
if (!userApproved) return `Run ${id} changed files and the user has not approved it. Ask the user; on a clear yes run: kaizen done ${id} --user-approved`;
|
|
1937
|
+
const why = recordAcceptance(state, id, "chat");
|
|
1938
|
+
if (why) return why;
|
|
1939
|
+
}
|
|
1940
|
+
setStage(file, (s) => { s.stage = "done"; s.awaiting = null; delete s.healed; return true; });
|
|
1941
|
+
return null;
|
|
1942
|
+
}
|
|
1787
1943
|
const names = (report: string, path: string) => report.includes("`" + path + "`") || report.includes("`" + path + ":");
|
|
1788
1944
|
|
|
1789
1945
|
type Report = { id: string; text: string; at: number; sha?: string };
|
|
@@ -1869,16 +2025,17 @@ export function readCommit(state: string, id: string): { sha: string; pushed: bo
|
|
|
1869
2025
|
// The card's git mark for each run asked about, by the rules of the panel's button
|
|
1870
2026
|
// (`gitBtn` in web/board/git.ts): one project status and one read of the reports for
|
|
1871
2027
|
// the lot. A run with nothing to say either way gets no entry.
|
|
1872
|
-
|
|
2028
|
+
// `due`, when given, is filled with what a pending run still needs: "commit" (changed files) or "push" (committed, ahead).
|
|
2029
|
+
export function cardsGit(state: string, ids: string[], due: Record<string, "commit" | "push"> = {}): Record<string, "pending" | "pushed"> {
|
|
1873
2030
|
const dir = dirname(state), s = gitStatus(dir), out: Record<string, "pending" | "pushed"> = {};
|
|
1874
2031
|
if (!s.repo) return out;
|
|
1875
2032
|
const all = runReports(state), ahead = aheadBy(s, all);
|
|
1876
2033
|
for (const id of ids) {
|
|
1877
2034
|
const mine = all.find((r) => r.id === id) ?? { id, text: "", at: 0 }, k = readCommit(state, id);
|
|
1878
2035
|
const files = runFiles(dir, s.files, mine, all.filter((o) => o.id !== id)).length;
|
|
1879
|
-
if (files) out[id] = "pending";
|
|
2036
|
+
if (files) out[id] = "pending", due[id] = "commit";
|
|
1880
2037
|
else if (k?.pushed) out[id] = "pushed";
|
|
1881
|
-
else if (ahead(id) > 0) out[id] = "pending";
|
|
2038
|
+
else if (ahead(id) > 0) out[id] = "pending", due[id] = "push";
|
|
1882
2039
|
else if (k || mine.text) out[id] = "pushed";
|
|
1883
2040
|
}
|
|
1884
2041
|
return out;
|
|
@@ -1896,6 +2053,7 @@ export async function commitPush(state: string, id: string, message: string, sho
|
|
|
1896
2053
|
const dir = codeDir(dirname(state), id);
|
|
1897
2054
|
const s = runGit(state, id);
|
|
1898
2055
|
if (!s.repo) return { ok: false, why: "This project has no git remote." };
|
|
2056
|
+
if (gateOf(state, id) === "needs") return { ok: false, why: "This run is not approved yet. Approve it first." };
|
|
1899
2057
|
if (s.files.join("\n") !== shown.join("\n")) return { ok: false, why: "The changed files are no longer the ones shown. Look at the list again." };
|
|
1900
2058
|
if (s.files.length) {
|
|
1901
2059
|
if (!message.trim()) return { ok: false, why: "A commit message is required." };
|
package/cli/usage.test.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// The footer's usage and phone readers, and the run workspace's /shell route on a real
|
|
2
2
|
// board: guarded like /pty, an agent only from the known list, a pwd in the project.
|
|
3
3
|
import { test, expect } from "bun:test";
|
|
4
|
-
import { mkdtempSync, mkdirSync, writeFileSync, realpathSync, utimesSync } from "node:fs";
|
|
4
|
+
import { mkdtempSync, mkdirSync, writeFileSync, realpathSync, utimesSync, rmSync, readFileSync, symlinkSync, existsSync } from "node:fs";
|
|
5
5
|
import { tmpdir } from "node:os";
|
|
6
6
|
import { join } from "node:path";
|
|
7
7
|
import { codexUsage, claudeUsage, phonePeers } from "./usage.ts";
|
|
@@ -64,6 +64,7 @@ test.skipIf(process.platform === "win32")("/shell: foreign origin, unknown proje
|
|
|
64
64
|
writeFileSync(sh, '#!/bin/sh\necho "pwd:$(pwd)"\nwhile read x; do echo "got:$x"; done\n', { mode: 0o755 });
|
|
65
65
|
// Some agent must exist for the board to start; not claude or codex, so /usage has none.
|
|
66
66
|
writeFileSync(join(bin, "gemini"), "#!/bin/sh\n", { mode: 0o755 });
|
|
67
|
+
symlinkSync(Bun.which("git")!, join(bin, "git"));
|
|
67
68
|
const port = 20000 + Math.floor(Math.random() * 20000);
|
|
68
69
|
const repo = join(import.meta.dir, "..");
|
|
69
70
|
// PATH without tailscale, claude or codex: /phone and /usage must still answer.
|
|
@@ -105,10 +106,127 @@ test.skipIf(process.platform === "win32")("/shell: foreign origin, unknown proje
|
|
|
105
106
|
expect((await open({ url: "http://localhost:3000/" }, at, "text/plain")).status).toBe(415);
|
|
106
107
|
expect((await open({ url: "file:///etc/passwd" }, at)).status).toBe(400);
|
|
107
108
|
expect((await open({ url: "javascript:alert(1)" }, at)).status).toBe(400);
|
|
109
|
+
expect((await open({ url: "https://example.com/" }, at)).status).toBe(400); // loopback only
|
|
110
|
+
expect((await open({ url: "http://localhost.evil.test/" }, at)).status).toBe(400);
|
|
108
111
|
// /frameable: board pages only, http(s) only; the answer is a boolean (or null when unreachable).
|
|
109
112
|
expect((await fetch(`${at}/frameable?url=${encodeURIComponent(at + "/")}`, { headers: { origin: "https://evil.example" } })).status).toBe(403);
|
|
110
113
|
expect((await fetch(`${at}/frameable?url=${encodeURIComponent("file:///etc/passwd")}`)).status).toBe(400);
|
|
114
|
+
expect((await fetch(`${at}/frameable?url=${encodeURIComponent("http://example.com/")}`)).status).toBe(400);
|
|
111
115
|
expect(await (await fetch(`${at}/frameable?url=${encodeURIComponent(at + "/")}`)).json()).toEqual({ frameable: true });
|
|
116
|
+
// A loopback page that redirects elsewhere is unknown, and the target is never fetched.
|
|
117
|
+
let hit = 0;
|
|
118
|
+
const far = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: () => { hit++; return new Response("x"); } });
|
|
119
|
+
const hop = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: () => Response.redirect(`http://127.0.0.1:${far.port}/`, 302) });
|
|
120
|
+
expect(await (await fetch(`${at}/frameable?url=${encodeURIComponent(`http://127.0.0.1:${hop.port}/`)}`)).json()).toEqual({ frameable: null });
|
|
121
|
+
expect(hit).toBe(0);
|
|
122
|
+
far.stop(true); hop.stop(true);
|
|
123
|
+
|
|
124
|
+
// A workspace folder only from the project's own list (no git on this PATH: the project folder alone).
|
|
125
|
+
expect((await post({ dir: st, ws: root }, at)).status).toBe(400);
|
|
126
|
+
expect((await post({ dir: st, ws: join(proj, "..", "a", "..") }, at)).status).toBe(400);
|
|
127
|
+
expect((await post({ dir: st, ws: ["x"] }, at)).status).toBe(400);
|
|
128
|
+
// /worktree: the same guards; a folder that is not a repository gets none.
|
|
129
|
+
const wt = (body: object, origin?: string) => fetch(at + "/worktree", { method: "POST", headers: { "content-type": "application/json", ...(origin ? { origin } : {}) }, body: JSON.stringify(body) });
|
|
130
|
+
expect((await wt({ dir: st, branch: "x" }, "http://localhost:3000")).status).toBe(403);
|
|
131
|
+
expect((await wt({ dir: join(homeDir, ".kaizen"), branch: "x" })).status).toBe(404);
|
|
132
|
+
expect((await wt({ dir: st, branch: "x" })).status).toBe(400);
|
|
133
|
+
// The rail's + sheet: /add-project, /new-project and /clone start git or make folders, so /worktree's guards and validated input.
|
|
134
|
+
const sheet = (route: string, body: object, origin?: string, type = "application/json") => fetch(at + route, { method: "POST", headers: { "content-type": type, ...(origin ? { origin } : {}) }, body: JSON.stringify(body) });
|
|
135
|
+
const bodies: [string, object][] = [["/add-project", { path: join(homeDir, "z") }], ["/new-project", { name: "z" }], ["/clone", { url: "https://127.0.0.1:1/z.git" }]];
|
|
136
|
+
for (const [route, b] of bodies) {
|
|
137
|
+
expect((await sheet(route, b, "http://localhost:3000")).status).toBe(403);
|
|
138
|
+
expect((await sheet(route, b, "https://evil.example")).status).toBe(403);
|
|
139
|
+
expect((await sheet(route, b, at, "text/plain")).status).toBe(415);
|
|
140
|
+
expect((await sheet(route, b, at, "application/x-www-form-urlencoded")).status).toBe(415);
|
|
141
|
+
}
|
|
142
|
+
expect(existsSync(join(homeDir, "z"))).toBe(false);
|
|
143
|
+
// Bad paths: root, home, ~/.kaizen, .., kaizen's own folders, below an existing project.
|
|
144
|
+
for (const path of ["/", homeDir, "~", "~/.kaizen/x", homeDir + "/../etc", "/tmp/a/../../etc", join(proj, "sub"), join(proj, ".kaizen", "wt", "x"), "", "x\0y"]) {
|
|
145
|
+
expect((await sheet("/add-project", { path })).status, path).toBe(400);
|
|
146
|
+
if (!path) continue; // no `to` means the default folder, for these two
|
|
147
|
+
expect((await sheet("/new-project", { name: "n", to: path })).status, path).toBe(400);
|
|
148
|
+
expect((await sheet("/clone", { url: "https://127.0.0.1:1/z.git", to: path })).status, path).toBe(400);
|
|
149
|
+
}
|
|
150
|
+
expect((await sheet("/add-project", { path: join(homeDir, "missing") })).status).toBe(400); // not a folder
|
|
151
|
+
expect((await sheet("/add-project", { path: 5 })).status).toBe(400);
|
|
152
|
+
expect((await sheet("/new-project", { name: "con" })).status).toBe(400);
|
|
153
|
+
// Bad clone URLs: nothing runs, nothing is made.
|
|
154
|
+
for (const url of ["--upload-pack=touch /tmp/kz-pwn", "ext::sh -c id", "file:///etc", "http://example.com/o/r.git", "/etc", "https://example.com/o/r with space", 7, undefined]) {
|
|
155
|
+
expect((await sheet("/clone", { url, to: join(homeDir, "c1") })).status, String(url)).toBe(400);
|
|
156
|
+
}
|
|
157
|
+
expect(existsSync(join(homeDir, "c1")) || existsSync("/tmp/kz-pwn")).toBe(false);
|
|
158
|
+
// Bad branch, base, project.
|
|
159
|
+
expect((await wt({ dir: st, branch: "-x" })).status).toBe(400);
|
|
160
|
+
expect((await wt({ dir: st, branch: "a..b" })).status).toBe(400);
|
|
161
|
+
expect((await wt({ dir: st, branch: "x y", base: "main" })).status).toBe(400);
|
|
162
|
+
expect((await wt({ dir: st, branch: "x", base: "-x" })).status).toBe(400);
|
|
163
|
+
expect((await wt({ dir: join(root, "elsewhere", ".kaizen"), branch: "x", base: "main" })).status).toBe(404);
|
|
164
|
+
expect((await fetch(`${at}/branches?dir=${encodeURIComponent(join(root, "elsewhere", ".kaizen"))}`)).status).toBe(404);
|
|
165
|
+
expect((await fetch(`${at}/branches?dir=${encodeURIComponent(join(homeDir, ".kaizen"))}`)).status).toBe(404);
|
|
166
|
+
expect(await (await fetch(`${at}/branches?dir=${encodeURIComponent(st)}`)).json()).toEqual({ current: "", def: "", branches: [] }); // not a repository
|
|
167
|
+
// Happy paths in the scratch home: an existing folder registers once; a new project gets .kaizen and git.
|
|
168
|
+
const reg = () => readFileSync(join(homeDir, ".kaizen", "projects"), "utf8").split("\n").filter(Boolean);
|
|
169
|
+
mkdirSync(join(homeDir, "b"));
|
|
170
|
+
const add1 = await (await sheet("/add-project", { path: join(homeDir, "b") })).json() as any;
|
|
171
|
+
expect(add1).toMatchObject({ ok: true, dir: join(homeDir, "b", ".kaizen"), already: false });
|
|
172
|
+
expect(existsSync(join(homeDir, "b", ".kaizen"))).toBe(true);
|
|
173
|
+
expect(reg().filter((l) => l === join(homeDir, "b"))).toHaveLength(1);
|
|
174
|
+
expect(((await (await sheet("/add-project", { path: join(homeDir, "b") })).json()) as any).already).toBe(true);
|
|
175
|
+
expect(reg().filter((l) => l === join(homeDir, "b"))).toHaveLength(1);
|
|
176
|
+
const newp = await (await sheet("/new-project", { name: "d", to: join(homeDir, "d") })).json() as any;
|
|
177
|
+
expect(newp).toMatchObject({ ok: true, dir: join(homeDir, "d", ".kaizen"), git: true });
|
|
178
|
+
expect(existsSync(join(homeDir, "d", ".git")) && existsSync(join(homeDir, "d", ".kaizen"))).toBe(true);
|
|
179
|
+
expect((await sheet("/new-project", { name: "d", to: join(homeDir, "d") })).status).toBe(409);
|
|
180
|
+
const plain = await (await sheet("/new-project", { name: "e", to: join(homeDir, "e"), git: false })).json() as any;
|
|
181
|
+
expect(existsSync(join(homeDir, "e", ".git"))).toBe(false);
|
|
182
|
+
expect(plain.git).toBeUndefined();
|
|
183
|
+
// A clone that cannot connect (nothing listens on port 1): 500, and no folder left behind.
|
|
184
|
+
expect((await sheet("/clone", { url: "https://127.0.0.1:1/z.git", to: join(homeDir, "f") })).status).toBe(500);
|
|
185
|
+
expect(existsSync(join(homeDir, "f"))).toBe(false);
|
|
186
|
+
expect(await (await sheet("/clone", { url: "git@github.com:o/r.git", check: true })).json()).toMatchObject({ ok: true, name: "r" });
|
|
187
|
+
// /state: each card's workspace; a run whose worktree is gone falls back to the main checkout.
|
|
188
|
+
mkdirSync(join(st, "runs", "r2"), { recursive: true });
|
|
189
|
+
writeFileSync(join(st, "runs", "r2", "state.json"), JSON.stringify({ id: "r2", stage: "plan", awaiting: "approvals.plan", worktree: join(proj, ".kaizen", "wt", "gone") }));
|
|
190
|
+
const S = await (await fetch(at + "/state?all=1")).json() as any;
|
|
191
|
+
expect(S.cards.find((c: any) => c.id === "r2")?.ws).toBe(proj);
|
|
192
|
+
expect(S.projects.find((p: any) => p.dir === st)?.workspaces).toEqual([{ path: proj, branch: "", main: true }]);
|
|
193
|
+
rmSync(join(st, "runs", "r2"), { recursive: true });
|
|
194
|
+
// Projects folder set: the global queue is not in the picker, yet its waiting run still gets a rail row.
|
|
195
|
+
const g = join(homeDir, ".kaizen");
|
|
196
|
+
writeFileSync(join(g, "config.yml"), readFileSync(join(repo, "skills", "kaizen", "config.default.yml"), "utf8").replace('projects_dir: ""', "projects_dir: ~/Projects"));
|
|
197
|
+
mkdirSync(join(g, "runs", "g1"), { recursive: true });
|
|
198
|
+
writeFileSync(join(g, "runs", "g1", "state.json"), JSON.stringify({ id: "g1", stage: "plan", awaiting: "approvals.plan" }));
|
|
199
|
+
const G = await (await fetch(at + "/state?all=1")).json() as any;
|
|
200
|
+
expect(G.cards.find((c: any) => c.id === "g1")?.ws).toBe(g);
|
|
201
|
+
expect(G.projects.some((p: any) => p.dir === g)).toBe(false);
|
|
202
|
+
expect(G.rail.find((p: any) => p.dir === g)?.workspaces).toEqual([{ path: g, branch: "", main: true }]);
|
|
203
|
+
rmSync(join(g, "runs"), { recursive: true });
|
|
204
|
+
rmSync(join(g, "config.yml"));
|
|
205
|
+
|
|
206
|
+
const inWs = await post({ dir: st, ws: proj }, at);
|
|
207
|
+
expect(inWs.status).toBe(200);
|
|
208
|
+
const made = (await inWs.json()) as any;
|
|
209
|
+
expect(made.ws).toBe(proj); // the tab lists a workspace's shells by it
|
|
210
|
+
await fetch(at + "/pty/exit", { method: "POST", body: JSON.stringify({ key: made.key }) });
|
|
211
|
+
for (let i = 0; i < 100; i++) { if (!((await (await fetch(`${at}/shells`)).json()) as any[]).length) break; await Bun.sleep(50); }
|
|
212
|
+
// A worktree made after the board cached the list (above) is let in, not refused for 10 s.
|
|
213
|
+
const g0 = (...a: string[]) => Bun.spawnSync(["git", "-c", "user.name=t", "-c", "user.email=t@t", ...a], { cwd: proj });
|
|
214
|
+
g0("init", "-q", "-b", "main"); g0("commit", "-q", "--allow-empty", "-m", "x");
|
|
215
|
+
const fresh = join(proj, ".kaizen", "wt", "late");
|
|
216
|
+
expect(g0("worktree", "add", "-q", "-b", "late", fresh).exitCode).toBe(0);
|
|
217
|
+
await Bun.sleep(1100); // the recheck waits for a cache older than 1 s
|
|
218
|
+
const late = await post({ dir: st, ws: fresh }, at);
|
|
219
|
+
expect(late.status).toBe(200);
|
|
220
|
+
await fetch(at + "/pty/exit", { method: "POST", body: JSON.stringify({ key: ((await late.json()) as any).key }) });
|
|
221
|
+
for (let i = 0; i < 100; i++) { if (!((await (await fetch(`${at}/shells`)).json()) as any[]).length) break; await Bun.sleep(50); }
|
|
222
|
+
// A burst of bad workspace paths runs git at most once.
|
|
223
|
+
const log = join(root, "git.log");
|
|
224
|
+
rmSync(join(bin, "git")); writeFileSync(join(bin, "git"), `#!/bin/sh\necho "$*" >> ${log}\nexec ${Bun.which("git")} "$@"\n`, { mode: 0o755 });
|
|
225
|
+
await Bun.sleep(1100);
|
|
226
|
+
for (let i = 0; i < 10; i++) expect((await post({ dir: st, ws: join(proj, "nope" + i) }, at)).status).toBe(400);
|
|
227
|
+
expect((existsSync(log) ? readFileSync(log, "utf8") : "").split("\n").filter((l) => l.startsWith("worktree list")).length).toBeLessThanOrEqual(1);
|
|
228
|
+
rmSync(join(bin, "git")); symlinkSync(Bun.which("git")!, join(bin, "git"));
|
|
229
|
+
rmSync(join(proj, ".git"), { recursive: true, force: true }); rmSync(join(proj, ".kaizen", "wt"), { recursive: true, force: true });
|
|
112
230
|
|
|
113
231
|
const r = await post({ dir: st }, at);
|
|
114
232
|
expect(r.status).toBe(200);
|
|
@@ -129,6 +247,17 @@ test.skipIf(process.platform === "win32")("/shell: foreign origin, unknown proje
|
|
|
129
247
|
for (let i = 0; i < 100; i++) { if (!((await (await fetch(`${at}/shells`)).json()) as any[]).length) break; await Bun.sleep(50); }
|
|
130
248
|
expect(await (await fetch(`${at}/shells`)).json()).toEqual([]);
|
|
131
249
|
|
|
250
|
+
// /state lists the open agents once (not plain shells); an ended one drops out.
|
|
251
|
+
writeFileSync(join(bin, "gemini"), '#!/bin/sh\necho "✦ Reading the parser source"\nread x\n', { mode: 0o755 });
|
|
252
|
+
const ag = (await (await post({ dir: st, agent: "gemini" }, at)).json()) as any, pl = (await (await post({ dir: st }, at)).json()) as any;
|
|
253
|
+
let A: any[] = [];
|
|
254
|
+
for (let i = 0; i < 60 && !A[0]?.last; i++) { await Bun.sleep(100); A = ((await (await fetch(at + "/state?all=1")).json()) as any).agents; }
|
|
255
|
+
expect(A.map((x) => x.key)).toEqual([ag.key]);
|
|
256
|
+
expect(A[0]).toMatchObject({ dir: st, agent: "gemini", name: "Gemini", asking: false, last: "Reading the parser source" });
|
|
257
|
+
for (const k of [ag.key, pl.key]) await fetch(at + "/pty/exit", { method: "POST", body: JSON.stringify({ key: k }) });
|
|
258
|
+
for (let i = 0; i < 100; i++) { if (!((await (await fetch(`${at}/shells`)).json()) as any[]).length) break; await Bun.sleep(50); }
|
|
259
|
+
expect(((await (await fetch(at + "/state?all=1")).json()) as any).agents).toEqual([]);
|
|
260
|
+
|
|
132
261
|
// At most 8 live terminals per project.
|
|
133
262
|
const keys: string[] = [];
|
|
134
263
|
for (let i = 0; i < 8; i++) { const x = await post({ dir: st }, at); expect(x.status).toBe(200); keys.push(((await x.json()) as any).key); }
|