kaizen-agent 1.70.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.
Files changed (60) hide show
  1. package/README.md +2 -2
  2. package/cli/annotate-proxy.ts +5 -0
  3. package/cli/automations.ts +10 -3
  4. package/cli/browser.ts +1 -1
  5. package/cli/chat.ts +9 -1
  6. package/cli/chatgpt.ts +2 -1
  7. package/cli/docs.ts +1 -1
  8. package/cli/google.ts +2 -1
  9. package/cli/handoff.ts +1 -1
  10. package/cli/install.ts +63 -17
  11. package/cli/knowledge.ts +1 -1
  12. package/cli/notes.ts +10 -1
  13. package/cli/preflight.ts +149 -0
  14. package/cli/rea.ts +199 -0
  15. package/cli/settings.ts +5 -1
  16. package/cli/sources.ts +3 -2
  17. package/cli/state.ts +43 -5
  18. package/cli/versions.ts +1 -1
  19. package/cli/video.ts +1 -1
  20. package/cli/web.ts +111 -28
  21. package/cli/workers.ts +20 -7
  22. package/cli/worktree.ts +65 -21
  23. package/package.json +1 -1
  24. package/skills/kaizen/SKILL.md +12 -8
  25. package/skills/kaizen/config.default.yml +18 -2
  26. package/skills/kaizen/settings.md +3 -1
  27. package/skills/kaizen/spec-build.md +13 -2
  28. package/skills/kaizen/spec-main.md +15 -0
  29. package/skills/kaizen/spec-plan.md +4 -1
  30. package/skills/kaizen-help/SKILL.md +2 -0
  31. package/skills/media/kaizen-game/SKILL.md +96 -0
  32. package/skills/media/kaizen-game/assets/gdd.css +12 -0
  33. package/skills/media/kaizen-game/references/build.md +81 -0
  34. package/skills/media/kaizen-game/references/content.md +32 -0
  35. package/skills/media/kaizen-game/references/design.md +81 -0
  36. package/skills/media/kaizen-game/references/ship.md +34 -0
  37. package/skills/media/kaizen-game/references/verify.md +33 -0
  38. package/skills/media/kaizen-game/scripts/check.sh +13 -0
  39. package/skills/media/kaizen-game/scripts/frames.mjs +34 -0
  40. package/skills/media/kaizen-game/scripts/gdd-pdf.mjs +19 -0
  41. package/skills/media/kaizen-game/scripts/pw.mjs +18 -0
  42. package/skills/media/kaizen-game/scripts/serve.mjs +53 -0
  43. package/skills/media/kaizen-game/scripts/serve.test.mjs +18 -0
  44. package/skills/media/kaizen-game/scripts/setup.sh +9 -0
  45. package/skills/media/kaizen-game/scripts/smoke.mjs +40 -0
  46. package/skills/media/kaizen-game/skill.json +1 -0
  47. package/web/board/git.ts +23 -6
  48. package/web/board/icebox.ts +6 -3
  49. package/web/board/markdown.ts +7 -2
  50. package/web/board/run-view.ts +1 -1
  51. package/web/board/settings-orchestration.ts +1 -1
  52. package/web/board/settings-pages.ts +1 -0
  53. package/web/board/settings-skills.ts +28 -2
  54. package/web/board/settings.ts +2 -2
  55. package/web/board.html +1 -1
  56. package/web/board.js +96 -82
  57. package/web/notebook.js +1 -1
  58. package/web/term.js +48 -48
  59. package/web/term.ts +16 -4
  60. package/web/video.js +1 -1
package/README.md CHANGED
@@ -28,7 +28,7 @@
28
28
 
29
29
  | | |
30
30
  |---|---|
31
- | **Any kind of work** | Each run works out what it is making (code, writing, communication, operations, research) and plans, builds and reviews it in those terms. Videos and decks go through the bundled `kaizen-video` (films from scratch, or editing your own footage) and `kaizen-deck` skills; books go through `kaizen-book` (interview, writing, proofreading, then an e-book reader plus colour and black-and-white print PDFs). |
31
+ | **Any kind of work** | Each run works out what it is making (code, writing, communication, operations, research) and plans, builds and reviews it in those terms. Videos and decks go through the bundled `kaizen-video` (films from scratch, or editing your own footage) and `kaizen-deck` skills; books go through `kaizen-book` (interview, writing, proofreading, then an e-book reader plus colour and black-and-white print PDFs); browser games go through `kaizen-game` (beta: brief, concepts, GDD, build, real-input play-throughs and frame timing, a public review link). |
32
32
  | **Plan first** | The agent writes what it will do, and what *wrong* would look like, then waits for your approve or change. |
33
33
  | **A reviewer that starts cold** | A second agent reviews from the request, the plan and the diff only. It never saw the work, so it has nothing to defend. |
34
34
  | **A fix loop that ends** | Serious findings are fixed and re-checked, at most twice. The rest come to you; what is left goes to a backlog. |
@@ -143,7 +143,7 @@ bun run cli/install.ts # install from this checkout
143
143
  | Path | What it is |
144
144
  |---|---|
145
145
  | `cli/` | The installer and the runtime behind every `kaizen` command: `install.ts` (the CLI), `state.ts` (runs), `web.ts` (board server), `dashboard.ts` (terminal board), `sources.ts`, `settings.ts`, `notes.ts`. Tests beside them. |
146
- | `skills/` | The workflow as Agent Skills folders: `kaizen/` (`SKILL.md`, the `spec-*.md` stage contracts, `adapters.md`, `config.default.yml`), `kaizen-help/`, and `media/` with `kaizen-deck/`, `kaizen-video/`, `kaizen-book/`. |
146
+ | `skills/` | The workflow as Agent Skills folders: `kaizen/` (`SKILL.md`, the `spec-*.md` stage contracts, `adapters.md`, `config.default.yml`), `kaizen-help/`, and `media/` with `kaizen-deck/`, `kaizen-video/`, `kaizen-book/`, `kaizen-game/`. |
147
147
  | `agents/` | The Claude Code subagents: `kaizen-planner`, `kaizen-builder`, `kaizen-reviewer`. |
148
148
  | `commands/` | The `/kaizen-*` slash commands, one file each. |
149
149
  | `web/` | The board and notebook front end: `board.html`, `notes.html`, `notebook.ts`. |
@@ -59,6 +59,11 @@ export function openProxy(target: URL): Proxy {
59
59
  }
60
60
  const path = url.pathname + url.search;
61
61
 
62
+ // The Origin below is rewritten to the target's, so a foreign page could pass for the dev
63
+ // server's own page; only a page this proxy served (or no Origin at all) gets through.
64
+ const inbound = req.headers.get("origin");
65
+ if (inbound) { let same = false; try { same = new URL(inbound).host === req.headers.get("host"); } catch { /* bad origin */ } if (!same) return new Response("cross-origin request refused", { status: 403 }); }
66
+
62
67
  if (req.headers.get("upgrade")?.toLowerCase() === "websocket") {
63
68
  const protocols = (req.headers.get("sec-websocket-protocol") ?? "").split(",").map((s) => s.trim()).filter(Boolean);
64
69
  const wsUrl = upstream(good, path);
@@ -215,14 +215,21 @@ async function precheck(cmd: string, cwd: string, secs: number): Promise<string
215
215
  const env = Object.fromEntries(Object.entries(process.env).filter(([k, v]) => v !== undefined && !CHILD_ENV.test(k))) as Record<string, string>;
216
216
  const win = process.platform === "win32";
217
217
  let p;
218
- try { p = Bun.spawn(shellArgv(cmd, win), { cwd, env, stdin: "ignore", stdout: "pipe", stderr: "pipe", detached: !win }); }
218
+ try { p = Bun.spawn(shellArgv(cmd, win), { cwd, env, stdin: "ignore", stdout: "pipe", stderr: "pipe", detached: !win, windowsHide: true }); }
219
219
  catch (e: any) { return `could not start: ${e?.message ?? e}`; }
220
220
  let late = false;
221
221
  const timer = setTimeout(() => {
222
222
  late = true;
223
- try { if (win) Bun.spawn(["taskkill", "/T", "/F", "/PID", String(p.pid)], { stdout: "ignore", stderr: "ignore" }); else process.kill(-p.pid, "SIGKILL"); } catch { try { p.kill(9); } catch { /* gone */ } }
223
+ try { if (win) Bun.spawn(["taskkill", "/T", "/F", "/PID", String(p.pid)], { stdout: "ignore", stderr: "ignore", windowsHide: true }); else process.kill(-p.pid, "SIGKILL"); } catch { try { p.kill(9); } catch { /* gone */ } }
224
224
  }, secs * 1000);
225
- const [out, err] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text()]);
225
+ // Only the last 4 KB of each stream is kept: a noisy precheck must not fill memory.
226
+ const tailOf = async (s: ReadableStream<Uint8Array>) => {
227
+ let t = "";
228
+ const dec = new TextDecoder();
229
+ for await (const c of s) t = (t + dec.decode(c, { stream: true })).slice(-4096);
230
+ return t;
231
+ };
232
+ const [out, err] = await Promise.all([tailOf(p.stdout), tailOf(p.stderr)]);
226
233
  const code = await p.exited;
227
234
  clearTimeout(timer);
228
235
  const tail = (out + err).trim().slice(-200);
package/cli/browser.ts CHANGED
@@ -177,7 +177,7 @@ export async function browse<T>(use: (page: Page) => Promise<T>): Promise<T | {
177
177
  rmSync(join(dir, "DevToolsActivePort"), { force: true });
178
178
  // env passed explicitly: without it Bun hands the child its startup env, not process.env as it is now.
179
179
  const proc = Bun.spawn([exe, "--headless=new", `--user-data-dir=${dir}`, "--remote-debugging-address=127.0.0.1", "--remote-debugging-port=0",
180
- "--no-first-run", "--no-default-browser-check", "--window-size=1280,2000", "about:blank"], { env: process.env, stdout: "ignore", stderr: "ignore" });
180
+ "--no-first-run", "--no-default-browser-check", "--window-size=1280,2000", "about:blank"], { env: process.env, stdout: "ignore", stderr: "ignore", windowsHide: true });
181
181
  let page: Page | null = null;
182
182
  try {
183
183
  let port = "";
package/cli/chat.ts CHANGED
@@ -200,6 +200,11 @@ export function sendChat(base: string, id: string | null, text: string, project:
200
200
  let files: Attachment[] = [];
201
201
  try { if (uploads.length) files = saveUploads(base, chat.id, uploads); }
202
202
  catch (err: any) { return `Could not save attachment: ${err?.message ?? err}`; }
203
+ // A run starts only after the agent offered the lite/full choice in an earlier reply and the user
204
+ // answered it: a directive written in the same turn that read a file or issue cannot start one alone.
205
+ const before = reuseReply ? chat.messages.slice(0, -1) : chat.messages;
206
+ const offer = [...before].reverse().find((m) => m.role === "agent");
207
+ const offered = !!offer && /\blite\b/i.test(offer.text) && /\bfull\b/i.test(offer.text);
203
208
  if (!reuseReply) chat.messages.push({ role: "user", text, ...(files.length ? { files } : {}), at: now });
204
209
  const reply: Msg = reuseReply ? chat.messages.at(-1)! : { role: "agent", text: "", steps: [], at: now };
205
210
  if (!reuseReply) chat.messages.push(reply);
@@ -275,7 +280,10 @@ export function sendChat(base: string, id: string | null, text: string, project:
275
280
  reply.error = err || `codex exited with code ${code}`;
276
281
  emit({ t: "error", error: reply.error });
277
282
  }
278
- if (run && !stopped) await startRun(reply, run, board, emit);
283
+ if (run && !stopped) {
284
+ if (offered) await startRun(reply, run, board, emit);
285
+ else { const s: Step = { kind: "project", text: "Not started: ask me to pick lite or full first", ok: false }; reply.steps!.push(s); emit({ t: "step", step: s }); }
286
+ }
279
287
  if (move && !stopped) await moveChat(chat, reply, move, board, emit);
280
288
  } finally {
281
289
  delete reply.activity;
package/cli/chatgpt.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  // so Gather needs no agent. Kaizen is a locally hosted open-source app, which OpenAI
3
3
  // lets register itself on the first sign-in: no client secret, no API key.
4
4
  // https://developers.openai.com/siwc/token-sharing-open-source
5
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
5
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
6
6
  import { dirname, join } from "node:path";
7
7
  import { home } from "./state.ts";
8
8
  import { ingest, record, setLast, type Result } from "./sources.ts";
@@ -29,6 +29,7 @@ function save(c: Creds) {
29
29
  mkdirSync(join(home, ".kaizen"), { recursive: true });
30
30
  const tmp = FILE() + ".tmp";
31
31
  writeFileSync(tmp, JSON.stringify(c, null, 2) + "\n", { mode: 0o600 });
32
+ chmodSync(tmp, 0o600); // a stale .tmp keeps its old mode otherwise
32
33
  renameSync(tmp, FILE());
33
34
  }
34
35
 
package/cli/docs.ts CHANGED
@@ -3,7 +3,7 @@ import { join, relative, resolve, sep } from "node:path";
3
3
  import { wikilinks, boardLink, resolve as resolveNote } from "../web/notes-lib.ts";
4
4
 
5
5
  const git = (root: string, args: string[]) => {
6
- const p = Bun.spawnSync(["git", ...args], { cwd: root });
6
+ const p = Bun.spawnSync(["git", ...args], { cwd: root, windowsHide: true });
7
7
  return p.exitCode === 0 ? p.stdout.toString() : null;
8
8
  };
9
9
 
package/cli/google.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  // gathered from. The user brings their own OAuth client (Desktop app type, Sheets API
3
3
  // on): a client secret shipped in an open-source app would be shared by every install.
4
4
  // Tokens stay in ~/.kaizen/google.json, owner-only, and go to Google hosts only.
5
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
5
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
6
6
  import { join } from "node:path";
7
7
  import { home } from "./state.ts";
8
8
 
@@ -19,6 +19,7 @@ function save(c: Creds) {
19
19
  mkdirSync(join(home, ".kaizen"), { recursive: true });
20
20
  const tmp = FILE() + ".tmp";
21
21
  writeFileSync(tmp, JSON.stringify(c, null, 2) + "\n", { mode: 0o600 });
22
+ chmodSync(tmp, 0o600); // a stale .tmp keeps its old mode otherwise
22
23
  renameSync(tmp, FILE());
23
24
  }
24
25
 
package/cli/handoff.ts CHANGED
@@ -29,7 +29,7 @@ function locked<T>(state: string, id: string, fn: () => T): T {
29
29
  const lock = `${file(state, id)}.lock`;
30
30
  for (let i = 0; ; i++) {
31
31
  try { closeSync(openSync(lock, "wx")); break; } catch (err) {
32
- try { if (Date.now() - statSync(lock).mtimeMs > 5000) { rmSync(lock, { force: true }); continue; } } catch { /* just released */ }
32
+ try { if (Date.now() - statSync(lock).mtimeMs > 5000) { const aside = `${lock}.${process.pid}.${i}.stale`; renameSync(lock, aside); rmSync(aside, { force: true }); continue; } } catch { /* just released */ }
33
33
  if (i > 500) throw err;
34
34
  Bun.sleepSync(2);
35
35
  }
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", "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`;
@@ -291,12 +291,37 @@ if (Bun.argv[2] === "remember" || Bun.argv[2] === "recall") {
291
291
  process.exit(cli(Bun.argv.slice(2)));
292
292
  }
293
293
 
294
+ // `kaizen model <stage>`: the model to pass on the Agent call for that stage's subagent,
295
+ // resolved from subagents.<stage> then subagents.model. `inherit`: pass none.
296
+ if (Bun.argv[2] === "model") {
297
+ const { SUBAGENT_STAGES: STAGES, subagentModel } = await import("./state.ts");
298
+ const { projectFromWorktree } = await import("./worktree.ts");
299
+ const stage = Bun.argv[3] as (typeof STAGES)[number] | undefined;
300
+ if (stage && !STAGES.includes(stage)) { console.log(`\n usage: kaizen model [${STAGES.join(" | ")}]\n`); process.exit(1); }
301
+ console.log(subagentModel(projectFromWorktree(process.cwd()), stage) ?? "inherit");
302
+ process.exit(0);
303
+ }
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
+
294
319
  if (Bun.argv[2] === "docs") {
295
320
  if (Bun.argv.length !== 4 || Bun.argv[3] !== "lint") { console.log("\n kaizen docs lint\n"); process.exit(1); }
296
321
  const { locate } = await import("./state.ts");
297
322
  const { lintDocs } = await import("./docs.ts");
298
323
  const state = locate();
299
- const gitRoot = Bun.which("git") ? Bun.spawnSync(["git", "rev-parse", "--show-toplevel"], { cwd: process.cwd() }) : null;
324
+ const gitRoot = Bun.which("git") ? Bun.spawnSync(["git", "rev-parse", "--show-toplevel"], { cwd: process.cwd(), windowsHide: true }) : null;
300
325
  const repo = gitRoot?.exitCode === 0 ? gitRoot.stdout.toString().trim() : "";
301
326
  const root = repo && existsSync(join(repo, ".kaizen")) ? repo : state ? dirname(state) : null;
302
327
  const problems = root ? lintDocs(root) : ["no kaizen project found"];
@@ -459,7 +484,7 @@ async function removeEverything() {
459
484
  // as written, so a KAIZEN_HOME that reaches ~/kaizen through a link is refused too.
460
485
  // A clone holds no ignored files unless someone used it (.kaizen/ is ignored), and
461
486
  // no commits that are not on a remote.
462
- const install = process.env.KAIZEN_HOME ?? join(home, "kaizen");
487
+ const install = process.env.KAIZEN_HOME || join(home, "kaizen");
463
488
  const git = async (...a: string[]) => {
464
489
  try { return (await Bun.$`git -C ${install} ${a}`.quiet().text()).trim(); } catch { return null; }
465
490
  };
@@ -516,15 +541,6 @@ if (args.has("setup")) {
516
541
  process.exit(0);
517
542
  }
518
543
 
519
- // Nothing to install into. kaizen is a workflow an agent runs; on its own it does
520
- // nothing, so send them to the agent first rather than laying out files no reader
521
- // will ever load. Settings need no agent, and an agent script must not get this and exit 0.
522
- // The board is exempt too: it starts with no agent and its own setup helps pick one
523
- // (the desktop app on a fresh machine runs exactly this).
524
- if (!found(home).length && !args.has("--force") && !wantSettings && !wantWeb) {
525
- if (!(await noAgent())) process.exit(0);
526
- }
527
-
528
544
  // Returns true once an agent is installed and found, so the kaizen install goes on.
529
545
  async function noAgent(): Promise<boolean> {
530
546
  console.log(` ${c.bold("No AI coding agent found on this machine.")}\n`);
@@ -640,11 +656,24 @@ if (args.has("worktree")) {
640
656
  const { locate } = await import("./state.ts");
641
657
  const { startWorktree, landRun, adoptWorkspace, linkTerm } = await import("./worktree.ts");
642
658
  const state = locate();
643
- if (!state || (verb !== "start" && verb !== "land")) { console.log("\n usage: kaizen worktree start|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); }
644
660
  const project = dirname(state);
645
661
  // Started inside another workspace of the project (a board worktree): the run is placed there.
646
- const r = verb === "start" ? adoptWorkspace(project, id, process.cwd()) ?? startWorktree(project, id) : landRun(project, id, process.env.KAIZEN_TERM);
647
- if (r.ok && verb === "start") linkTerm(state, process.env.KAIZEN_TERM, id);
662
+ // --default is a side run: its own worktree off the default branch, never another run's folder.
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
+ }
674
+ const r = verb === "start" ? (side ? null : adoptWorkspace(project, id, process.cwd())) ?? startWorktree(project, id, side) : landRun(project, id, process.env.KAIZEN_TERM);
675
+ // A side run never relinks the asking terminal: it stays with the run it was on.
676
+ if (r.ok && verb === "start" && !side) linkTerm(state, process.env.KAIZEN_TERM, id);
648
677
  if ("warn" in r && r.warn) console.log(`\n warning: ${r.warn}`);
649
678
  console.log(r.ok ? `\n ${verb === "start" ? `worktree ready: ${(r as { path: string }).path}` : `landed by ${(r as { how: string }).how}`}\n` : `\n ${r.why}\n`);
650
679
  process.exit(r.ok ? 0 : 1);
@@ -818,6 +847,17 @@ if (wantWeb) {
818
847
  process.exit(0);
819
848
  }
820
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
+
821
861
  // Bare `kaizen` on a machine where it is already installed is not an install --
822
862
  // show what the project is doing instead, and offer the things you would have
823
863
  // opened a terminal for.
@@ -943,7 +983,7 @@ const targets = found(root);
943
983
  async function resolveRepoQuietly() {
944
984
  const here = dirname(import.meta.dir);
945
985
  if (existsSync(join(here, ".git"))) return here;
946
- return process.env.KAIZEN_HOME ?? join(home, "kaizen");
986
+ return process.env.KAIZEN_HOME || join(home, "kaizen");
947
987
  }
948
988
 
949
989
  async function resolveRepo() {
@@ -1034,6 +1074,8 @@ function sameFile(a: string, b: string) {
1034
1074
  try { return readFileSync(a).equals(readFileSync(b)); } catch { return false; }
1035
1075
  }
1036
1076
 
1077
+ const sansEffort = (p: string) => { try { return readFileSync(p, "utf8").replace(/^effort:.*\r?\n/m, ""); } catch { return null; } };
1078
+
1037
1079
  function linkState(src: string, dest: string) {
1038
1080
  try {
1039
1081
  const st = lstatSync(dest);
@@ -1041,6 +1083,10 @@ function linkState(src: string, dest: string) {
1041
1083
  // A copied link on Windows is a real file; it is ours as long as it still
1042
1084
  // matches the source, and stale once the source changes.
1043
1085
  if (isWindows && st.isFile()) return sameFile(src, dest) ? "linked" : "stale";
1086
+ // An older workflow told the agent to write `effort:` into its agent file, which
1087
+ // turned the link into a copy. Still ours when that line is the only difference.
1088
+ const mine = st.isFile() ? sansEffort(src) : null;
1089
+ if (mine !== null && mine === sansEffort(dest)) return "stale";
1044
1090
  return "occupied";
1045
1091
  }
1046
1092
  // Compared by where they lead, not by spelling: a junction reads back with a
@@ -1300,7 +1346,7 @@ async function runUpgrade(repoDir: string) {
1300
1346
  return lines;
1301
1347
  }
1302
1348
 
1303
- function installDir() { return process.env.KAIZEN_HOME ?? join(home, "kaizen"); }
1349
+ function installDir() { return process.env.KAIZEN_HOME || join(home, "kaizen"); }
1304
1350
 
1305
1351
  // A folder someone develops kaizen in must never be replaced by a release: a git
1306
1352
  // checkout KAIZEN_HOME points at, or any checkout holding commits on no remote.
package/cli/knowledge.ts CHANGED
@@ -60,7 +60,7 @@ export function secretReason(text: string): string {
60
60
  export function globalAllowed(projectDir: string): boolean {
61
61
  for (const f of [join(projectDir, ".kaizen", "config.yml"), join(homedir(), ".kaizen", "config.yml")]) {
62
62
  const t = read(f);
63
- const m = /^knowledge:\n(?:[ \t][^\n]*\n|[ \t]*#.*\n)*?[ \t]+global:[ \t]*["']?(\w+)/m.exec(t) || /^knowledge\.global:[ \t]*["']?(\w+)/m.exec(t);
63
+ const m = /^knowledge:\n(?:[ \t][^\n]*\n|#[^\n]*\n)*?[ \t]+global:[ \t]*["']?(\w+)/m.exec(t) || /^knowledge\.global:[ \t]*["']?(\w+)/m.exec(t);
64
64
  if (m) return m[1] !== "false";
65
65
  }
66
66
  return true;
package/cli/notes.ts CHANGED
@@ -29,7 +29,16 @@ function fileOf(state: string, name: unknown) {
29
29
  if (!n) return null;
30
30
  const root = resolve(notesDir(state));
31
31
  const f = resolve(root, n + ".md");
32
- return f.startsWith(root + sep) ? { name: n, file: f } : null;
32
+ if (!f.startsWith(root + sep)) return null;
33
+ // A symlinked folder (tracked in git, so a cloned repo can ship one) must not carry a
34
+ // write out of notes/: the nearest existing ancestor has to resolve inside it.
35
+ if (existsSync(root)) try {
36
+ let a = dirname(f);
37
+ while (!existsSync(a)) a = dirname(a);
38
+ const real = realpathSync(a), realRoot = realpathSync(root);
39
+ if (real !== realRoot && !real.startsWith(realRoot + sep)) return null;
40
+ } catch { return null; }
41
+ return { name: n, file: f };
33
42
  }
34
43
 
35
44
  // ponytail: the whole vault is read on every list; fine for hundreds of notes, send
@@ -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
+ }