kaizen-agent 1.71.0 → 1.72.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli/install.ts CHANGED
@@ -30,7 +30,7 @@ const interactive = process.stdin.isTTY && !check && !upgrade && !args.has("--ye
30
30
  // installer, so a typo or a command from a newer kaizen reinstalled instead of failing.
31
31
  // cli/install-unknown.test.ts fails if a dispatched word is missing here.
32
32
  const COMMANDS = ["automation", "help", "init", "browser", "card", "chat", "computer", "config", "docs", "done", "gather", "handoff",
33
- "icebox", "issue", "model", "preview", "prune", "recall", "related", "remember", "report", "roadmap", "settings", "setup", "sources",
33
+ "icebox", "issue", "model", "preflight", "preview", "prune", "recall", "related", "remember", "report", "roadmap", "settings", "setup", "sources",
34
34
  "state", "stats", "uninstall", "upgrade", "version", "web", "worker", "worktree"];
35
35
  const first = Bun.argv[2];
36
36
  const commandList = ` commands: ${COMMANDS.join(", ")}\n plain \`kaizen\` opens the board; \`kaizen --yes\` installs; \`kaizen init\` sets up this folder\n`;
@@ -302,6 +302,20 @@ if (Bun.argv[2] === "model") {
302
302
  process.exit(0);
303
303
  }
304
304
 
305
+ // `kaizen preflight <run-id>`: the look at the repo before a push or merge (cli/preflight.ts).
306
+ // Exit 0 clean, 2 stopped: an agent then asks the user before landing.
307
+ if (Bun.argv[2] === "preflight") {
308
+ const id = Bun.argv[3] ?? "";
309
+ const { locate } = await import("./state.ts");
310
+ const state = locate();
311
+ if (!state || !id) { console.log("\n usage: kaizen preflight <run-id>, in a project with .kaizen\n"); process.exit(1); }
312
+ const { preflight, report, writePreflight } = await import("./preflight.ts");
313
+ const p = await preflight(dirname(state), id);
314
+ writePreflight(dirname(state), id, p, p.clean ? "clean" : "stopped");
315
+ console.log(`\n${report(p)}\n${p.clean ? "" : "\n Stopped: ask the user what to do (rebase first, wait for CI, land the other one first, go ahead anyway).\n Only after go ahead: kaizen worktree land " + id + " --checked\n"}`);
316
+ process.exit(p.clean ? 0 : 2);
317
+ }
318
+
305
319
  if (Bun.argv[2] === "docs") {
306
320
  if (Bun.argv.length !== 4 || Bun.argv[3] !== "lint") { console.log("\n kaizen docs lint\n"); process.exit(1); }
307
321
  const { locate } = await import("./state.ts");
@@ -527,15 +541,6 @@ if (args.has("setup")) {
527
541
  process.exit(0);
528
542
  }
529
543
 
530
- // Nothing to install into. kaizen is a workflow an agent runs; on its own it does
531
- // nothing, so send them to the agent first rather than laying out files no reader
532
- // will ever load. Settings need no agent, and an agent script must not get this and exit 0.
533
- // The board is exempt too: it starts with no agent and its own setup helps pick one
534
- // (the desktop app on a fresh machine runs exactly this).
535
- if (!found(home).length && !args.has("--force") && !wantSettings && !wantWeb) {
536
- if (!(await noAgent())) process.exit(0);
537
- }
538
-
539
544
  // Returns true once an agent is installed and found, so the kaizen install goes on.
540
545
  async function noAgent(): Promise<boolean> {
541
546
  console.log(` ${c.bold("No AI coding agent found on this machine.")}\n`);
@@ -651,11 +656,21 @@ if (args.has("worktree")) {
651
656
  const { locate } = await import("./state.ts");
652
657
  const { startWorktree, landRun, adoptWorkspace, linkTerm } = await import("./worktree.ts");
653
658
  const state = locate();
654
- if (!state || (verb !== "start" && verb !== "land")) { console.log("\n usage: kaizen worktree start [--default] | land <run-id>, in a project with .kaizen\n"); process.exit(1); }
659
+ if (!state || (verb !== "start" && verb !== "land")) { console.log("\n usage: kaizen worktree start [--default] | land [--checked] <run-id>, in a project with .kaizen\n"); process.exit(1); }
655
660
  const project = dirname(state);
656
661
  // Started inside another workspace of the project (a board worktree): the run is placed there.
657
662
  // --default is a side run: its own worktree off the default branch, never another run's folder.
658
663
  const side = args.has("--default");
664
+ // Landing looks at the rest of the repo first; --checked is the user's go-ahead after a stop.
665
+ if (verb === "land") {
666
+ const { preflight, report, writePreflight } = await import("./preflight.ts");
667
+ const p = await preflight(project, id);
668
+ writePreflight(project, id, p, p.clean ? "clean" : args.has("--checked") ? "go ahead (user)" : "stopped");
669
+ if (!p.clean && !args.has("--checked")) {
670
+ console.log(`\n${report(p)}\n\n Stopped before landing; nothing was pushed or merged. Ask the user, then after a go-ahead: kaizen worktree land ${id} --checked\n`);
671
+ process.exit(2);
672
+ }
673
+ }
659
674
  const r = verb === "start" ? (side ? null : adoptWorkspace(project, id, process.cwd())) ?? startWorktree(project, id, side) : landRun(project, id, process.env.KAIZEN_TERM);
660
675
  // A side run never relinks the asking terminal: it stays with the run it was on.
661
676
  if (r.ok && verb === "start" && !side) linkTerm(state, process.env.KAIZEN_TERM, id);
@@ -832,6 +847,17 @@ if (wantWeb) {
832
847
  process.exit(0);
833
848
  }
834
849
 
850
+ // Nothing to install into. kaizen is a workflow an agent runs; on its own it does
851
+ // nothing, so send them to the agent first rather than laying out files no reader
852
+ // will ever load. Only the install and the bare dashboard below are guarded: every
853
+ // subcommand above (worktree, handoff, prune, chat…) runs without an agent, since an agent
854
+ // script must never get this and exit 0 having done nothing (CI has none). The board is
855
+ // exempt too: it starts with no agent and its own setup helps pick one (the desktop app
856
+ // on a fresh machine runs exactly this).
857
+ if (!found(home).length && !args.has("--force") && !wantSettings && !wantWeb) {
858
+ if (!(await noAgent())) process.exit(0);
859
+ }
860
+
835
861
  // Bare `kaizen` on a machine where it is already installed is not an install --
836
862
  // show what the project is doing instead, and offer the things you would have
837
863
  // opened a terminal for.
@@ -0,0 +1,149 @@
1
+ // `kaizen preflight <run-id>`: the look at the rest of the repo before kaizen pushes to a
2
+ // base branch or merges into it. It reports and never acts: no rebase, merge, push or close.
3
+ // Stops (clean: false) on: the branch behind its base, this landing's CI failed or still
4
+ // running, the base's CI failed, or another open PR / unmerged branch / run in flight that
5
+ // changes the same files. What it cannot check (no remote, no gh, offline) is a note, never
6
+ // a stop. Files matched by `git.generated` (the web bundles) are a note too: a land rebuilds them.
7
+ import { existsSync, readdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { runGit } from "./state.ts";
10
+ import { baseOfRun, branchFor, codeDir, generatedOf, localBase, onGithub, run, runAsync, type AsyncRun, type Out, type Run } from "./worktree.ts";
11
+
12
+ export type Issue = { kind: "behind" | "ci-failed" | "ci-running" | "base-failed" | "pr-overlap" | "branch-overlap"; what: string; files?: string[] };
13
+ export type Preflight = { clean: boolean; issues: Issue[]; notes: string[]; files: string[]; base: string; branch: string };
14
+
15
+ // ponytail: 20 PRs and 20 branches, each a git or gh call; a repo with more says so in a note.
16
+ const CAP = 20;
17
+ const GH_MS = 20_000;
18
+ const SLUG = /^\d{4}-\d{2}-\d{2}-[a-z0-9][a-z0-9-]*$/;
19
+
20
+ const lines = (o: Out) => (o.ok ? o.out.split("\n").map((l) => l.trim()).filter(Boolean) : []);
21
+ // gh can hang on a slow network; past GH_MS its answer is a note, not a wait.
22
+ const timed = (p: Promise<Out>): Promise<Out> =>
23
+ Promise.race([p, new Promise<Out>((r) => setTimeout(() => r({ ok: false, out: "", why: "timed out" }), GH_MS))]);
24
+ const json = (o: Out): any => { try { return o.ok ? JSON.parse(o.out) : null; } catch { return null; } };
25
+
26
+ // A check list from `gh pr view --json statusCheckRollup` or `gh run list`: failed, running, or fine.
27
+ function ciState(checks: any[]): "failed" | "running" | "ok" | "none" {
28
+ if (!Array.isArray(checks) || !checks.length) return "none";
29
+ let running = false;
30
+ for (const c of checks) {
31
+ const done = String(c.conclusion ?? c.state ?? "").toUpperCase(), st = String(c.status ?? "").toUpperCase();
32
+ if (/^(FAILURE|FAILED|ERROR|CANCELLED|TIMED_OUT|ACTION_REQUIRED|STARTUP_FAILURE)$/.test(done)) return "failed";
33
+ if (/^(IN_PROGRESS|QUEUED|PENDING|WAITING|REQUESTED|EXPECTED)$/.test(st) || done === "PENDING" || (!done && st !== "COMPLETED")) running = true;
34
+ }
35
+ return running ? "running" : "ok";
36
+ }
37
+
38
+ export async function preflight(project: string, id: string, o: { extraFiles?: string[]; sh?: Run; ash?: AsyncRun; hasGh?: boolean } = {}): Promise<Preflight> {
39
+ const sh = o.sh ?? run, ash = o.ash ?? runAsync;
40
+ const dir = codeDir(project, id), own = dir !== project;
41
+ const here = sh(["git", "symbolic-ref", "--short", "-q", "HEAD"], dir).out;
42
+ const branch = own ? branchFor(project, id) : here;
43
+ const base = baseOfRun(project, id);
44
+ const done = (notes: string[], issues: Issue[] = [], files: string[] = []): Preflight => ({ clean: !issues.length, issues, notes, files, base, branch });
45
+ if (localBase(project, id)) return done([`lands by a local merge into ${base}: nothing is pushed`]);
46
+ if (!lines(sh(["git", "remote"], project)).includes("origin")) return done(["no remote: nothing to compare"]);
47
+
48
+ const notes: string[] = [], issues: Issue[] = [];
49
+ if (!(await ash(["git", "fetch", "-q", "origin"], project)).ok) notes.push("offline: compared with the last fetch");
50
+ const baseRef = `origin/${base}`;
51
+ if (!sh(["git", "rev-parse", "--verify", "--quiet", `refs/remotes/${baseRef}`], project).ok) return done([...notes, `the remote has no ${base} yet: nothing to compare`]);
52
+
53
+ const behind = Number(sh(["git", "rev-list", "--count", `HEAD..${baseRef}`], dir).out) || 0;
54
+ if (behind > 0) issues.push({ kind: "behind", what: `${branch || "HEAD"} is ${behind} commit${behind === 1 ? "" : "s"} behind ${baseRef}: rebase first` });
55
+
56
+ const gen = generatedOf(project);
57
+ // What this land carries: its commits not on the base, plus, for a run with no worktree
58
+ // (it commits and pushes in the project folder), the run's own changed files not yet committed.
59
+ const pending = own ? [] : (() => { try { return runGit(join(project, ".kaizen"), id).rows?.map((r) => r.path) ?? []; } catch { return []; } })();
60
+ const files = [...new Set([...lines(sh(["git", "diff", "--name-only", `${baseRef}...HEAD`], dir)), ...pending, ...(o.extraFiles ?? [])])].sort();
61
+ const mine = new Set(files);
62
+ const genTouched = new Set<string>();
63
+ // The files another piece of work shares with this landing; generated ones only noted.
64
+ const shared = (theirs: string[]) => {
65
+ const both = theirs.filter((f) => mine.has(f));
66
+ both.filter(gen).forEach((f) => genTouched.add(f));
67
+ return both.filter((f) => !gen(f));
68
+ };
69
+
70
+ const gh = o.hasGh ?? onGithub(project);
71
+ const skip = new Set<string>(); // branches already compared as an open PR
72
+ const direct = !own && branch === base; // the board's Commit & push on the base itself
73
+ const [view, baseRuns, open] = gh
74
+ ? await Promise.all([
75
+ direct ? Promise.resolve(null) : timed(ash(["gh", "pr", "view", branch, "--json", "number,statusCheckRollup"], project)),
76
+ timed(ash(["gh", "run", "list", "--branch", base, "--limit", "1", "--json", "status,conclusion,name"], project)),
77
+ timed(ash(["gh", "pr", "list", "--state", "open", "--base", base, "--limit", String(CAP + 1), "--json", "number,title,headRefName,files"], project)),
78
+ ])
79
+ : [null, null, null];
80
+ if (!gh) notes.push("CI and open pull requests not checked: needs gh and a GitHub remote");
81
+
82
+ if (gh) {
83
+ const pr = view && json(view);
84
+ if (!direct && !pr) notes.push(`no pull request for ${branch} yet: its CI is checked once it has one`);
85
+ const ci = pr ? ciState(pr.statusCheckRollup) : "none";
86
+ if (ci === "failed") issues.push({ kind: "ci-failed", what: `CI failed on #${pr.number}` });
87
+ if (ci === "running") issues.push({ kind: "ci-running", what: `CI is still running on #${pr.number}` });
88
+ const last = baseRuns && json(baseRuns);
89
+ if (baseRuns && !baseRuns.ok) notes.push(`${base}'s CI not checked: ${baseRuns.why}`);
90
+ const bci = Array.isArray(last) ? ciState(last) : "none";
91
+ if (bci === "failed") issues.push({ kind: "base-failed", what: `${base}'s last CI run failed` });
92
+ if (bci === "running" && direct) issues.push({ kind: "ci-running", what: `${base}'s CI is still running` });
93
+ const prs: any[] = (open && json(open)) || [];
94
+ if (open && !open.ok) notes.push(`open pull requests not checked: ${open.why}`);
95
+ if (prs.length > CAP) notes.push(`more than ${CAP} open pull requests: only the first ${CAP} were compared`);
96
+ for (const p of prs.slice(0, CAP)) {
97
+ if (p.headRefName === branch) continue;
98
+ const both = shared((p.files ?? []).map((f: any) => String(f.path)));
99
+ if (both.length) issues.push({ kind: "pr-overlap", what: `#${p.number} ${p.headRefName} (${String(p.title).slice(0, 60)}) also changes ${both.length} of these files`, files: both });
100
+ }
101
+ prs.forEach((p) => skip.add(`origin/${p.headRefName}`));
102
+ }
103
+
104
+ // Unmerged remote branches, and the branches of runs still in flight; an open PR's branch was compared above.
105
+ const refs = lines(sh(["git", "for-each-ref", "refs/remotes/origin", "--format=%(refname:short)"], project))
106
+ .filter((r) => r !== "origin" && r !== "origin/HEAD" && r !== baseRef && r !== `origin/${branch}` && !skip.has(r));
107
+ const runs = inFlight(project, id).filter((b) => b !== branch && !refs.includes(`origin/${b}`) && !skip.has(`origin/${b}`));
108
+ const all = [...refs, ...runs];
109
+ if (all.length > CAP) notes.push(`more than ${CAP} other branches: only the first ${CAP} were compared`);
110
+ for (const ref of all.slice(0, CAP)) {
111
+ const cherry = sh(["git", "cherry", baseRef, ref], project);
112
+ if (!cherry.ok || !cherry.out.split("\n").some((l) => l.startsWith("+"))) continue; // merged, or unreadable
113
+ const both = shared(lines(sh(["git", "diff", "--name-only", `${baseRef}...${ref}`], project)));
114
+ if (both.length) issues.push({ kind: "branch-overlap", what: `${ref.replace(/^origin\//, "")} (not merged) also changes ${both.length} of these files`, files: both });
115
+ }
116
+ if (genTouched.size) notes.push(`other work also changes generated files (${[...genTouched].join(", ")}): a land rebuilds them`);
117
+ return done([...notes], issues, files);
118
+ }
119
+ // Local branches of other runs whose stage is still open and that have a worktree.
120
+ function inFlight(project: string, id: string): string[] {
121
+ const dir = join(project, ".kaizen", "runs");
122
+ if (!existsSync(dir)) return [];
123
+ return readdirSync(dir).filter((r) => r !== id && SLUG.test(r)).flatMap((r) => {
124
+ try {
125
+ const s = JSON.parse(readFileSync(join(dir, r, "state.json"), "utf8"));
126
+ return s.stage !== "done" && s.stage !== "abandoned" && s.worktree && typeof s.branch === "string" ? [s.branch] : [];
127
+ } catch { return []; }
128
+ });
129
+ }
130
+
131
+ /** The report as plain lines, for the terminal and for `preflight.md`. */
132
+ export function report(p: Preflight): string {
133
+ const out = [`${p.clean ? "clean" : "stopped"}: ${p.branch || "HEAD"} → ${p.base}`];
134
+ for (const i of p.issues) out.push(`- ${i.what}${i.files ? `: ${i.files.slice(0, 8).join(", ")}${i.files.length > 8 ? `, +${i.files.length - 8} more` : ""}` : ""}`);
135
+ for (const n of p.notes) out.push(` note: ${n}`);
136
+ return out.join("\n");
137
+ }
138
+
139
+ /** `runs/<id>/preflight.md`: what was found and what was decided, appended per land. */
140
+ export function writePreflight(project: string, id: string, p: Preflight, decision: "clean" | "go ahead (user)" | "stopped") {
141
+ if (!SLUG.test(id)) return;
142
+ const f = join(project, ".kaizen", "runs", id, "preflight.md");
143
+ if (!existsSync(join(project, ".kaizen", "runs", id))) return;
144
+ let prev = "";
145
+ try { prev = readFileSync(f, "utf8"); } catch { prev = "# Preflight\n"; }
146
+ const tmp = `${f}.${process.pid}.tmp`;
147
+ writeFileSync(tmp, `${prev.trimEnd()}\n\n## ${new Date().toISOString()}\ndecision: ${decision}\n\n${report(p)}\n`);
148
+ renameSync(tmp, f);
149
+ }
package/cli/rea.ts ADDED
@@ -0,0 +1,199 @@
1
+ // REA (npm `rea-agents`, github.com/morluto/rea): reverse-engineering tools as an MCP server,
2
+ // turned on from Settings → Skills. Kaizen never writes an agent's config itself: REA's own
3
+ // `setup`, `uninstall` and `doctor` do, through `npx` pinned to an exact version. Kaizen keeps
4
+ // only its switch in ~/.kaizen/rea.json and reads agent configs to see what is registered.
5
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { SKILL_HOMES } from "./skills.ts";
8
+
9
+ export type Run = (argv: string[]) => Promise<{ ok: boolean; out: string }>;
10
+ export type Reg = { client: string; version: string | null };
11
+ export type Saved = { on: boolean; version: string; clients: string[] };
12
+
13
+ const VERSION = /^\d+\.\d+\.\d+$/;
14
+ export const okVersion = (v: unknown): v is string => typeof v === "string" && VERSION.test(v);
15
+
16
+ // The agent home folders kaizen knows (SKILL_HOMES) and their REA client ids.
17
+ const CLIENT: Record<string, string> = { ".claude": "claude_code", ".codex": "codex", ".agents": "antigravity", ".opencode": "opencode", ".cursor": "cursor", ".gemini": "gemini_cli" };
18
+ export const reaClients = (home: string) => SKILL_HOMES.filter((h) => existsSync(join(home, h.dir)) && CLIENT[h.dir]).map((h) => ({ agent: h.name, client: CLIENT[h.dir]! }));
19
+
20
+ const npx = process.platform === "win32" ? "npx.cmd" : "npx";
21
+ const npm = process.platform === "win32" ? "npm.cmd" : "npm";
22
+ const pkg = (version: string) => `rea-agents@${version}`;
23
+
24
+ // Up to 5 minutes: a first npx run downloads REA (about 50 MB). A missing npx is a failure, not a throw.
25
+ export const run: Run = async (argv) => {
26
+ try {
27
+ const p = Bun.spawn(argv, { stdout: "pipe", stderr: "pipe", stdin: "ignore", windowsHide: true });
28
+ const timer = setTimeout(() => p.kill(), 5 * 60_000);
29
+ const [out, err, code] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text(), p.exited]);
30
+ clearTimeout(timer);
31
+ return { ok: code === 0, out: out || err };
32
+ } catch (e: any) { return { ok: false, out: `${argv[0]} not found: ${e?.message ?? e}` }; }
33
+ };
34
+
35
+ // REA prints one JSON document with --json; anything before it is noise.
36
+ export function parse(out: string): any {
37
+ const at = out.indexOf("{");
38
+ try { return JSON.parse(at < 0 ? out : out.slice(at)); } catch { return null; }
39
+ }
40
+
41
+ // The files a setup plan names: any string under a path-like key, deduplicated.
42
+ export function planFiles(j: any): string[] {
43
+ const found = new Set<string>();
44
+ const walk = (v: any, key = "") => {
45
+ if (typeof v === "string") { if (/(^|_)(path|file|target|config)s?$/i.test(key) && /[\\/]/.test(v)) found.add(v); return; }
46
+ if (Array.isArray(v)) return v.forEach((x) => walk(x, key));
47
+ if (v && typeof v === "object") for (const [k, x] of Object.entries(v)) walk(x, k);
48
+ };
49
+ walk(j);
50
+ return [...found];
51
+ }
52
+
53
+ // What doctor says is missing: every check object that failed, by its name or message.
54
+ export function doctorMissing(j: any): string[] {
55
+ const out = new Set<string>();
56
+ const walk = (v: any) => {
57
+ if (Array.isArray(v)) return v.forEach(walk);
58
+ if (!v || typeof v !== "object") return;
59
+ const bad = v.ok === false || v.passed === false || /^(fail|failed|error|missing)$/i.test(String(v.status ?? ""));
60
+ if (bad && (v.name || v.id || v.message)) out.add(String(v.name ?? v.id ?? v.message).slice(0, 80));
61
+ for (const x of Object.values(v)) if (x && typeof x === "object") walk(x);
62
+ };
63
+ if (j) for (const k of ["scope_checks", "informational_checks", "providerInspections", "checks"]) walk(j[k]);
64
+ return [...out];
65
+ }
66
+
67
+ // Where each client keeps REA's entry. Read only, to show the switch and the installed
68
+ // version without running npx; REA itself writes them. A missing file is simply "not here".
69
+ const CONFIGS: Record<string, (home: string) => string[]> = {
70
+ claude_code: (h) => [join(process.env.CLAUDE_CONFIG_DIR ?? h, ".claude.json")],
71
+ codex: (h) => [join(process.env.CODEX_HOME ?? join(h, ".codex"), "config.toml")],
72
+ gemini_cli: (h) => [join(h, ".gemini", "settings.json")],
73
+ antigravity: (h) => [join(h, ".gemini", "antigravity", "mcp_config.json")],
74
+ cursor: (h) => [join(h, ".cursor", "mcp.json")],
75
+ opencode: (h) => [join(h, ".config", "opencode", "opencode.json"), join(h, ".config", "opencode", "opencode.jsonc")],
76
+ };
77
+ export function reaRegistered(home: string): Reg[] {
78
+ return reaClients(home).flatMap(({ client }) => {
79
+ for (const f of CONFIGS[client]!(home)) {
80
+ let t: string;
81
+ try { t = readFileSync(f, "utf8"); } catch { continue; }
82
+ const v = /rea-agents@(\d+\.\d+\.\d+)/.exec(t)?.[1];
83
+ // A pinned npx entry gives the version; a global install (`"command": "rea"`) only the
84
+ // server's key: a JSON `"rea": {` or a TOML `[mcp_servers.rea]`.
85
+ if (v || /["']rea["']\s*:\s*\{/.test(t) || /^\[mcp_servers\.rea\]/m.test(t)) return [{ client, version: v ?? null }];
86
+ }
87
+ return [];
88
+ });
89
+ }
90
+
91
+ const file = (home: string) => join(home, ".kaizen", "rea.json");
92
+ export function reaSaved(home: string): Saved | null {
93
+ try {
94
+ const j = JSON.parse(readFileSync(file(home), "utf8"));
95
+ return j && j.on === true && okVersion(j.version) && Array.isArray(j.clients) ? { on: true, version: j.version, clients: j.clients.filter((c: unknown) => typeof c === "string") } : null;
96
+ } catch { return null; }
97
+ }
98
+ function save(home: string, s: Saved | null) {
99
+ if (!s) return rmSync(file(home), { force: true });
100
+ mkdirSync(join(home, ".kaizen"), { recursive: true });
101
+ writeFileSync(file(home) + ".tmp", JSON.stringify(s, null, 2));
102
+ renameSync(file(home) + ".tmp", file(home));
103
+ }
104
+
105
+ const validClients = (home: string, clients: string[]) => {
106
+ const known = new Set(reaClients(home).map((c) => c.client));
107
+ return clients.length > 0 && clients.every((c) => known.has(c));
108
+ };
109
+ const clientArgs = (clients: string[]) => clients.flatMap((c) => ["--client", c]);
110
+ // REA's own words when a step did not go through: its message, else the first line it printed.
111
+ const reason = (j: any, out: string) => String(j?.message ?? j?.error ?? j?.reason ?? (out.trim().split("\n")[0] || "REA did not answer")).slice(0, 300);
112
+
113
+ export async function reaLatest(sh: Run = run): Promise<string | null> {
114
+ const r = await sh([npm, "view", "rea-agents", "version"]);
115
+ const v = r.out.trim().split("\n").pop()?.trim();
116
+ return r.ok && okVersion(v) ? v : null;
117
+ }
118
+
119
+ // The dry run: what `setup` would change, nothing written.
120
+ export async function reaPlan(home: string, version: string, clients: string[], sh: Run = run) {
121
+ if (!okVersion(version) || !validClients(home, clients)) return { ok: false as const, why: "no REA version or agent to set up" };
122
+ const r = await sh([npx, "-y", pkg(version), "setup", ...clientArgs(clients), "--dry-run", "--json"]);
123
+ const j = parse(r.out);
124
+ if (!r.ok || !j || j.status !== "planned") return { ok: false as const, why: reason(j, r.out) };
125
+ return { ok: true as const, version, clients, files: planFiles(j) };
126
+ }
127
+
128
+ // Applies a plan the user saw. Saved only when REA says it is done.
129
+ export async function reaApply(home: string, version: string, clients: string[], sh: Run = run) {
130
+ if (!okVersion(version) || !validClients(home, clients)) return { ok: false as const, why: "no REA version or agent to set up" };
131
+ const r = await sh([npx, "-y", pkg(version), "setup", ...clientArgs(clients), "--yes", "--json"]);
132
+ const j = parse(r.out);
133
+ if (!r.ok || !j || /^(needs_confirmation|needs_human|cancelled|planned)$/.test(String(j.status)) || j.reason === "conflict") return { ok: false as const, why: reason(j, r.out) };
134
+ save(home, { on: true, version, clients });
135
+ return { ok: true as const, version };
136
+ }
137
+
138
+ // Off: REA's own uninstall, whoever set REA up. What it leaves (a Claude local or profile
139
+ // registration, which REA does not touch) is named with the command that removes it.
140
+ export async function reaRemove(home: string, sh: Run = run) {
141
+ const version = reaSaved(home)?.version ?? reaRegistered(home).find((r) => r.version)?.version ?? (await reaLatest(sh));
142
+ if (!okVersion(version)) return { ok: false as const, why: "can't tell which REA to run: npm is unreachable" };
143
+ const r = await sh([npx, "-y", pkg(version), "uninstall", "--json"]);
144
+ if (!r.ok) return { ok: false as const, why: reason(parse(r.out), r.out) };
145
+ save(home, null);
146
+ const left = reaRegistered(home).map((x) => x.client);
147
+ return { ok: true as const, left, ...(left.includes("claude_code") ? { hint: "claude mcp remove --scope user rea" } : {}) };
148
+ }
149
+
150
+ // Doctor runs npx, so it is cached and never awaited by the page: the first look starts it.
151
+ const doctorCache = new Map<string, { at: number; p: Promise<{ healthy: boolean; missing: string[] } | null>; v?: { healthy: boolean; missing: string[] } | null }>();
152
+ export function reaDoctor(version: string, sh: Run = run, now = Date.now()) {
153
+ const hit = doctorCache.get(version);
154
+ if (hit && now - hit.at < 10 * 60_000) return hit.v;
155
+ const entry: { at: number; p: Promise<any>; v?: any } = { at: now, p: Promise.resolve(null) };
156
+ entry.p = sh([npx, "-y", pkg(version), "doctor", "--json"]).then((r) => {
157
+ const j = parse(r.out);
158
+ entry.v = j ? { healthy: j.healthy === true, missing: doctorMissing(j) } : null;
159
+ return entry.v;
160
+ });
161
+ doctorCache.set(version, entry);
162
+ return hit?.v;
163
+ }
164
+ export const forgetDoctor = () => doctorCache.clear();
165
+
166
+ const latestCache = { at: 0, v: null as string | null, p: null as Promise<string | null> | null };
167
+ function cachedLatest(sh: Run, now: number) {
168
+ if (now - latestCache.at > 60 * 60_000 && !latestCache.p) {
169
+ latestCache.p = reaLatest(sh).then((v) => { latestCache.v = v; latestCache.at = Date.now(); latestCache.p = null; return v; });
170
+ }
171
+ return latestCache.v;
172
+ }
173
+ export const forgetLatest = () => { latestCache.at = 0; latestCache.v = null; latestCache.p = null; };
174
+
175
+ const newer = (a: string, b: string) => {
176
+ const x = a.split(".").map(Number), y = b.split(".").map(Number);
177
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i]! > y[i]!;
178
+ return false;
179
+ };
180
+
181
+ // The row on Settings → Skills. Off and never set up: no npx, no npm, nothing run.
182
+ export function reaRow(home: string, sh: Run = run, now = Date.now()) {
183
+ const saved = reaSaved(home), reg = reaRegistered(home);
184
+ const on = !!saved || reg.length > 0;
185
+ const installed = saved?.version ?? reg.find((r) => r.version)?.version ?? null;
186
+ const latest = on ? cachedLatest(sh, now) : null;
187
+ const doc = on && installed ? reaDoctor(installed, sh, now) : null;
188
+ const regd = new Set(reg.map((r) => r.client));
189
+ const note = !on ? undefined
190
+ : `REA ${installed ?? "(version unknown)"}${!saved ? " · set up outside kaizen" : ""}${latest && installed && newer(latest, installed) ? ` · ${latest} available` : ""}${doc === undefined ? " · checking what it needs…" : ""}`;
191
+ return {
192
+ id: "rea", title: "Reverse engineering (REA)", group: "optional", offByDefault: true, status: "beta",
193
+ description: "Lets agents study apps, binaries, packages and file formats whose source isn't here, through REA's MCP tools.",
194
+ off: !on, needs: (doc?.missing ?? []).map((name) => ({ name, found: false })),
195
+ agents: reaClients(home).map((c) => ({ agent: c.agent, state: regd.has(c.client) ? "installed" : "missing" })),
196
+ ...(note ? { note } : {}),
197
+ rea: { installed, latest, update: !!(latest && installed && newer(latest, installed)), outside: on && !saved, clients: reaClients(home).map((c) => c.client) },
198
+ };
199
+ }
package/cli/web.ts CHANGED
@@ -15,6 +15,7 @@ import { ACCOUNT_VAR, accountDir, addAccount, readAccounts, renameAccount, signe
15
15
  import { readReport, signalOf } from "./report.ts";
16
16
  import { MAX_IMAGE, saveImage } from "./term-image.ts";
17
17
  import { bundledSkills, setSkill, skillsHeld, skillsOff, skillStatus } from "./skills.ts";
18
+ import * as rea from "./rea.ts";
18
19
  import { accountEnv, accountForRun, agentUsable, CHILD_ENV, heartbeatMinutes, keepAwake, launchPreview, trustFolder, YOLO_FLAGS } from "./state.ts";
19
20
  import { agentLine, failStart, handoffModel, markRunning, readWorkers, requested, startWorker, sweep, workerStale } from "./workers.ts";
20
21
  import { childDied, childQuiet, markWoken, move, requestOpen, readHandoff, refused, started, wakeAction, wakeLine, type Handoff } from "./handoff.ts";
@@ -293,6 +294,27 @@ export async function web(repoDir: string, opts: Opts = {}) {
293
294
  // One-time token for turning an off-by-default skill on; each GET /skills mints a new one. It stops
294
295
  // an agent switching itself on by accident, not a local process that reads the board's own page.
295
296
  let skillToken = "";
297
+ // A preflight that stopped a land: its one-time go-ahead, per run and step, and what it found.
298
+ const preflights = new Map<string, { token: string; p: import("./preflight.ts").Preflight }>();
299
+ // Runs the preflight before a push or merge. null: go on. Otherwise the 409 to send back.
300
+ const gatePreflight = async (dir: string, id: string, op: string, override: unknown, extraFiles: string[] = []) => {
301
+ const { preflight, writePreflight } = await import("./preflight.ts");
302
+ const project = dirname(dir), k = `${dir}\0${id}\0${op}`, held = preflights.get(k);
303
+ if (held && typeof override === "string" && override === held.token) {
304
+ preflights.delete(k);
305
+ writePreflight(project, id, held.p, "go ahead (user)");
306
+ return null;
307
+ }
308
+ preflights.delete(k);
309
+ const p = await preflight(project, id, { extraFiles });
310
+ writePreflight(project, id, p, p.clean ? "clean" : "stopped");
311
+ if (p.clean) return null;
312
+ const token = crypto.randomUUID();
313
+ preflights.set(k, { token, p });
314
+ return json({ ok: false, why: "Stopped before landing: other work needs a look first.", preflight: { issues: p.issues, notes: p.notes, base: p.base, branch: p.branch }, token }, 409);
315
+ };
316
+ // REA: a plan the page showed, bound to its one-time token. Only that plan is ever applied.
317
+ let reaPending: { token: string; version: string; clients: string[] } | null = null;
296
318
  const strict = (req: Request) => {
297
319
  if (!sameOrigin(req)) return bad("cross-origin request refused", 403);
298
320
  if (!/^application\/json\b/i.test(req.headers.get("content-type") ?? "")) return bad("json body expected", 415);
@@ -1613,7 +1635,41 @@ export async function web(repoDir: string, opts: Opts = {}) {
1613
1635
  skillToken = crypto.randomUUID();
1614
1636
  // The desktop-control skill shows what this machine lacks, from the helper's own check.
1615
1637
  const check = bundledSkills(repoDir).some((s) => s.id === "kaizen-computer") ? (await import("./computer.ts")).computerCheck() : null;
1616
- return json({ token: skillToken, skills: bundledSkills(repoDir).map((s) => ({ ...s, off: off.includes(s.id), agents: skillStatus(s, home), needs: [...s.needs.map((n) => ({ name: n, found: !!onPath(n) })), ...(s.id === "kaizen-computer" && check ? check.needs : [])], ...(s.id === "kaizen-computer" && check ? { note: check.note } : {}) })) });
1638
+ return json({ token: skillToken, skills: [...bundledSkills(repoDir).map((s) => ({ ...s, off: off.includes(s.id), agents: skillStatus(s, home), needs: [...s.needs.map((n) => ({ name: n, found: !!onPath(n) })), ...(s.id === "kaizen-computer" && check ? check.needs : [])], ...(s.id === "kaizen-computer" && check ? { note: check.note } : {}) })), rea.reaRow(home)] });
1639
+ }
1640
+
1641
+ // REA's switch. `plan` runs REA's dry run and hands back a token; `apply` sets up exactly
1642
+ // that plan and only with that token; `off` runs REA's uninstall. Kaizen writes no agent config.
1643
+ if (path === "/rea" && req.method === "POST") {
1644
+ const refused = strict(req);
1645
+ if (refused) return refused;
1646
+ let body: any;
1647
+ try { body = await req.json(); } catch { return bad("json body expected"); }
1648
+ if (body?.step === "plan") {
1649
+ reaPending = null;
1650
+ const version = await rea.reaLatest();
1651
+ if (!version) return bad("can't reach npm to find REA's version");
1652
+ const want = body?.update === true ? rea.reaSaved(home)?.clients ?? rea.reaRegistered(home).map((r) => r.client) : rea.reaClients(home).map((c) => c.client);
1653
+ const p = await rea.reaPlan(home, version, want);
1654
+ if (!p.ok) return bad(p.why);
1655
+ reaPending = { token: crypto.randomUUID(), version: p.version, clients: p.clients };
1656
+ return json({ token: reaPending.token, version: p.version, clients: p.clients, files: p.files });
1657
+ }
1658
+ if (body?.step === "apply") {
1659
+ const plan = reaPending;
1660
+ reaPending = null;
1661
+ if (!plan || body?.confirm !== true || body?.token !== plan.token) return bad("confirm required");
1662
+ const r = await rea.reaApply(home, plan.version, plan.clients);
1663
+ rea.forgetDoctor(); rea.forgetLatest();
1664
+ return r.ok ? json({ ok: true, version: r.version }) : bad(r.why);
1665
+ }
1666
+ if (body?.step === "off") {
1667
+ reaPending = null;
1668
+ const r = await rea.reaRemove(home);
1669
+ rea.forgetDoctor(); rea.forgetLatest();
1670
+ return r.ok ? json(r) : bad(r.why);
1671
+ }
1672
+ return bad("step: plan, apply or off");
1617
1673
  }
1618
1674
 
1619
1675
  // Per user, so no scope. A saved environment value is never in either answer.
@@ -2293,6 +2349,11 @@ export async function web(repoDir: string, opts: Opts = {}) {
2293
2349
  try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return bad("no such run", 404); }
2294
2350
  if (run.stage !== "done" && run.awaiting !== "approvals.review") return bad("this run is not finished", 409);
2295
2351
  const files = Array.isArray(body.files) ? body.files.map(String) : [];
2352
+ // A run with no worktree pushes the project's own branch, the base itself: that push is a land.
2353
+ if (body.push !== false && codeDir(dirname(dir), id) === dirname(dir)) {
2354
+ const stop = await gatePreflight(dir, id, "push", body.override, files);
2355
+ if (stop) return stop;
2356
+ }
2296
2357
  // `push: false` is the tab's plain Commit: what is staged, nothing pushed.
2297
2358
  const r = body.push === false ? commitStaged(dir, id, String(body.message ?? ""), files) : await commitPush(dir, id, String(body.message ?? ""), files);
2298
2359
  changed();
@@ -2338,6 +2399,12 @@ export async function web(repoDir: string, opts: Opts = {}) {
2338
2399
  if (run.stage !== "done" && run.awaiting !== "approvals.review") return bad("this run is not finished", 409);
2339
2400
  const project = dirname(dir);
2340
2401
  if (body.op !== "remove" && gateOf(dir, id) === "needs") return bad("This run is not approved yet. Approve it first.", 409);
2402
+ if (body.op === "create" || body.op === "merge") {
2403
+ prBusy.add(lock);
2404
+ let stop: Response | null;
2405
+ try { stop = await gatePreflight(dir, id, body.op, body.override); } finally { prBusy.delete(lock); }
2406
+ if (stop) return stop;
2407
+ }
2341
2408
  prBusy.add(lock);
2342
2409
  let r: { ok: boolean };
2343
2410
  try {
package/cli/worktree.ts CHANGED
@@ -77,16 +77,16 @@ export const projectFromWorktree = (dir: string) => {
77
77
  return m ? m[1]! : dir;
78
78
  };
79
79
 
80
- const baseOf = (project: string) => {
80
+ export const baseOf = (project: string) => {
81
81
  const head = git(project, "symbolic-ref", "--short", "refs/remotes/origin/HEAD");
82
82
  return head.ok ? head.out.replace(/^origin\//, "") : "main";
83
83
  };
84
84
 
85
85
  /** The feature branch a run was cut from and lands on, or null for the remote default branch. */
86
- const localBase = (project: string, id: string): string | null => {
86
+ export const localBase = (project: string, id: string): string | null => {
87
87
  try { const b = JSON.parse(readFileSync(file(project, id), "utf8")).base_branch; return typeof b === "string" && b ? b : null; } catch { return null; }
88
88
  };
89
- const baseOfRun = (project: string, id: string) => localBase(project, id) ?? baseOf(project);
89
+ export const baseOfRun = (project: string, id: string) => localBase(project, id) ?? baseOf(project);
90
90
  // The ref that proves a run's work is on its base: local for a feature branch, which may never be pushed.
91
91
  const baseRef = (project: string, id: string) => localBase(project, id) ?? `origin/${baseOf(project)}`;
92
92
 
@@ -137,6 +137,11 @@ const gitSetting = (project: string, key: string, fallback: string) => {
137
137
  }
138
138
  return fallback;
139
139
  };
140
+ /** `git.generated`: the paths a land may take from the base and rebuild (the web bundles here). */
141
+ export function generatedOf(project: string) {
142
+ const globs = gitSetting(project, "generated", "").split(/[\s,]+/).filter(Boolean).map((p) => new Bun.Glob(p));
143
+ return (p: string) => globs.some((g) => g.match(p));
144
+ }
140
145
  const LONG = 30 * 60_000; // a project's check or rebuild may outlast a git call
141
146
  const shell = (cmd: string) => ["sh", "-c", cmd];
142
147
 
@@ -162,8 +167,7 @@ function rebaseOnto(project: string, dir: string, ref: string, sh: Run): Failed
162
167
  const behind = sh(["git", "rev-list", "--count", `HEAD..${ref}`], dir);
163
168
  if (!behind.ok) return { ok: false, kind: "merge", why: `cannot compare with ${ref}: ${behind.why}` };
164
169
  if (Number(behind.out) === 0) return null;
165
- const globs = gitSetting(project, "generated", "").split(/[\s,]+/).filter(Boolean).map((p) => new Bun.Glob(p));
166
- const generated = (p: string) => globs.some((g) => g.match(p));
170
+ const generated = generatedOf(project);
167
171
  const giveUp = (why: string, paths?: string[]): Failed => {
168
172
  sh(["git", "rebase", "--abort"], dir);
169
173
  return { ok: false, kind: "conflict", why: `${why}; worktree kept`, ...(paths ? { paths } : {}) };
@@ -325,7 +329,7 @@ export type AsyncRun = (cmd: string[], cwd: string) => Promise<Out>;
325
329
 
326
330
  // gh only knows GitHub. Asked once per project: the remote does not change under a board.
327
331
  const githubs = new Map<string, boolean>();
328
- const onGithub = (project: string) => {
332
+ export const onGithub = (project: string) => {
329
333
  let v = githubs.get(project);
330
334
  if (v === undefined) githubs.set(project, (v = !!Bun.which("gh") && /github\.com/.test(git(project, "remote", "get-url", "origin").out)));
331
335
  return v;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kaizen-agent",
3
- "version": "1.71.0",
3
+ "version": "1.72.0",
4
4
  "description": "Staged workflow for AI agents — code, writing, research, operations: plan, human approval, build, independent review, bounded fix loop.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -216,6 +216,19 @@ once the default branch holds the work. A conflict or an unmerged pull request l
216
216
  everything in place: report its message as printed and let the user decide. The run is
217
217
  `done` once approved; whether the work landed is reported, not hidden.
218
218
 
219
+ **Preflight before anything lands.** Before any push to a base branch (`git push` of the
220
+ default branch, the board's Commit & push of a run with no worktree), any `gh pr merge`,
221
+ and any `kaizen worktree land`, run `kaizen preflight <id>` from the project folder (1.72.0
222
+ and later; `kaizen worktree land` also runs it itself). It compares the repo with the
223
+ remote and never changes anything: is the branch behind its base, is this landing's CI or
224
+ the base's CI failed or still running, does another open pull request, unmerged branch or
225
+ run in flight change the same files. Exit 0: land as above. Exit 2: nothing is pushed or
226
+ merged; show the user what it printed as a pick list — *rebase first*, *wait for CI*,
227
+ *land the other one first*, *go ahead anyway*, *stop* — and act only on the answer. Only
228
+ after *go ahead anyway* run `kaizen worktree land <id> --checked` (or the push or merge the
229
+ user asked for). What it could not check (no remote, no `gh`, offline) prints as a note
230
+ and does not stop it. The report and the decision are appended to `runs/<id>/preflight.md`.
231
+
219
232
  **Open findings are offered by number.** List them with the reviewer's numbering
220
233
  intact, with `CANNOT VERIFY` criteria after them, and let the user name what to fix and
221
234
  what to backlog — "fix 2, backlog 5". A number not named is not touched and not filed;
@@ -50,7 +50,10 @@ returns is cited with its limitations, as *the track* in `spec.md` already requi
50
50
  REA not connected: ask instead
51
51
  `Q: REA isn't installed — set it up first?`, with `help me install it` (recommended
52
52
  where how it works inside decides the design), `I'll install it myself` and `skip
53
- REA`. On *help me install it* the main thread follows REA's own setup: it runs
53
+ REA`. *I'll install it myself* first names the kaizen board's switch: Settings → Skills →
54
+ *Reverse engineering (REA)*, which runs the same dry run, setup and pin for every
55
+ installed agent after the user confirms, and later updates or removes it. On *help me
56
+ install it* the main thread follows REA's own setup: it runs
54
57
  `npx -y rea-agents@<version> doctor --client <client> --json` — the version pinned,
55
58
  as REA's own guide pins it, taken from `npm view rea-agents version` and shown to the
56
59
  user; the client from the run's `agent` (`claude` → `claude_code`, `codex` → `codex`,