kaizen-agent 1.70.0 → 1.71.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 (55) 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 +28 -8
  11. package/cli/knowledge.ts +1 -1
  12. package/cli/notes.ts +10 -1
  13. package/cli/settings.ts +5 -1
  14. package/cli/sources.ts +3 -2
  15. package/cli/state.ts +43 -5
  16. package/cli/versions.ts +1 -1
  17. package/cli/video.ts +1 -1
  18. package/cli/web.ts +43 -27
  19. package/cli/workers.ts +20 -7
  20. package/cli/worktree.ts +55 -15
  21. package/package.json +1 -1
  22. package/skills/kaizen/SKILL.md +12 -8
  23. package/skills/kaizen/config.default.yml +18 -2
  24. package/skills/kaizen/settings.md +3 -1
  25. package/skills/kaizen/spec-build.md +13 -2
  26. package/skills/kaizen/spec-main.md +2 -0
  27. package/skills/kaizen-help/SKILL.md +1 -0
  28. package/skills/media/kaizen-game/SKILL.md +96 -0
  29. package/skills/media/kaizen-game/assets/gdd.css +12 -0
  30. package/skills/media/kaizen-game/references/build.md +81 -0
  31. package/skills/media/kaizen-game/references/content.md +32 -0
  32. package/skills/media/kaizen-game/references/design.md +81 -0
  33. package/skills/media/kaizen-game/references/ship.md +34 -0
  34. package/skills/media/kaizen-game/references/verify.md +33 -0
  35. package/skills/media/kaizen-game/scripts/check.sh +13 -0
  36. package/skills/media/kaizen-game/scripts/frames.mjs +34 -0
  37. package/skills/media/kaizen-game/scripts/gdd-pdf.mjs +19 -0
  38. package/skills/media/kaizen-game/scripts/pw.mjs +18 -0
  39. package/skills/media/kaizen-game/scripts/serve.mjs +53 -0
  40. package/skills/media/kaizen-game/scripts/serve.test.mjs +18 -0
  41. package/skills/media/kaizen-game/scripts/setup.sh +9 -0
  42. package/skills/media/kaizen-game/scripts/smoke.mjs +40 -0
  43. package/skills/media/kaizen-game/skill.json +1 -0
  44. package/web/board/icebox.ts +6 -3
  45. package/web/board/markdown.ts +7 -2
  46. package/web/board/run-view.ts +1 -1
  47. package/web/board/settings-orchestration.ts +1 -1
  48. package/web/board/settings-pages.ts +1 -0
  49. package/web/board/settings-skills.ts +1 -0
  50. package/web/board/settings.ts +2 -2
  51. package/web/board.js +70 -70
  52. package/web/notebook.js +1 -1
  53. package/web/term.js +48 -48
  54. package/web/term.ts +16 -4
  55. 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", "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,23 @@ 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
+
294
305
  if (Bun.argv[2] === "docs") {
295
306
  if (Bun.argv.length !== 4 || Bun.argv[3] !== "lint") { console.log("\n kaizen docs lint\n"); process.exit(1); }
296
307
  const { locate } = await import("./state.ts");
297
308
  const { lintDocs } = await import("./docs.ts");
298
309
  const state = locate();
299
- const gitRoot = Bun.which("git") ? Bun.spawnSync(["git", "rev-parse", "--show-toplevel"], { cwd: process.cwd() }) : null;
310
+ const gitRoot = Bun.which("git") ? Bun.spawnSync(["git", "rev-parse", "--show-toplevel"], { cwd: process.cwd(), windowsHide: true }) : null;
300
311
  const repo = gitRoot?.exitCode === 0 ? gitRoot.stdout.toString().trim() : "";
301
312
  const root = repo && existsSync(join(repo, ".kaizen")) ? repo : state ? dirname(state) : null;
302
313
  const problems = root ? lintDocs(root) : ["no kaizen project found"];
@@ -459,7 +470,7 @@ async function removeEverything() {
459
470
  // as written, so a KAIZEN_HOME that reaches ~/kaizen through a link is refused too.
460
471
  // A clone holds no ignored files unless someone used it (.kaizen/ is ignored), and
461
472
  // no commits that are not on a remote.
462
- const install = process.env.KAIZEN_HOME ?? join(home, "kaizen");
473
+ const install = process.env.KAIZEN_HOME || join(home, "kaizen");
463
474
  const git = async (...a: string[]) => {
464
475
  try { return (await Bun.$`git -C ${install} ${a}`.quiet().text()).trim(); } catch { return null; }
465
476
  };
@@ -640,11 +651,14 @@ if (args.has("worktree")) {
640
651
  const { locate } = await import("./state.ts");
641
652
  const { startWorktree, landRun, adoptWorkspace, linkTerm } = await import("./worktree.ts");
642
653
  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); }
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); }
644
655
  const project = dirname(state);
645
656
  // 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);
657
+ // --default is a side run: its own worktree off the default branch, never another run's folder.
658
+ const side = args.has("--default");
659
+ const r = verb === "start" ? (side ? null : adoptWorkspace(project, id, process.cwd())) ?? startWorktree(project, id, side) : landRun(project, id, process.env.KAIZEN_TERM);
660
+ // A side run never relinks the asking terminal: it stays with the run it was on.
661
+ if (r.ok && verb === "start" && !side) linkTerm(state, process.env.KAIZEN_TERM, id);
648
662
  if ("warn" in r && r.warn) console.log(`\n warning: ${r.warn}`);
649
663
  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
664
  process.exit(r.ok ? 0 : 1);
@@ -943,7 +957,7 @@ const targets = found(root);
943
957
  async function resolveRepoQuietly() {
944
958
  const here = dirname(import.meta.dir);
945
959
  if (existsSync(join(here, ".git"))) return here;
946
- return process.env.KAIZEN_HOME ?? join(home, "kaizen");
960
+ return process.env.KAIZEN_HOME || join(home, "kaizen");
947
961
  }
948
962
 
949
963
  async function resolveRepo() {
@@ -1034,6 +1048,8 @@ function sameFile(a: string, b: string) {
1034
1048
  try { return readFileSync(a).equals(readFileSync(b)); } catch { return false; }
1035
1049
  }
1036
1050
 
1051
+ const sansEffort = (p: string) => { try { return readFileSync(p, "utf8").replace(/^effort:.*\r?\n/m, ""); } catch { return null; } };
1052
+
1037
1053
  function linkState(src: string, dest: string) {
1038
1054
  try {
1039
1055
  const st = lstatSync(dest);
@@ -1041,6 +1057,10 @@ function linkState(src: string, dest: string) {
1041
1057
  // A copied link on Windows is a real file; it is ours as long as it still
1042
1058
  // matches the source, and stale once the source changes.
1043
1059
  if (isWindows && st.isFile()) return sameFile(src, dest) ? "linked" : "stale";
1060
+ // An older workflow told the agent to write `effort:` into its agent file, which
1061
+ // turned the link into a copy. Still ours when that line is the only difference.
1062
+ const mine = st.isFile() ? sansEffort(src) : null;
1063
+ if (mine !== null && mine === sansEffort(dest)) return "stale";
1044
1064
  return "occupied";
1045
1065
  }
1046
1066
  // Compared by where they lead, not by spelling: a junction reads back with a
@@ -1300,7 +1320,7 @@ async function runUpgrade(repoDir: string) {
1300
1320
  return lines;
1301
1321
  }
1302
1322
 
1303
- function installDir() { return process.env.KAIZEN_HOME ?? join(home, "kaizen"); }
1323
+ function installDir() { return process.env.KAIZEN_HOME || join(home, "kaizen"); }
1304
1324
 
1305
1325
  // A folder someone develops kaizen in must never be replaced by a release: a git
1306
1326
  // 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
package/cli/settings.ts CHANGED
@@ -117,6 +117,9 @@ const SETTINGS: Setting[] = [
117
117
  { key: "agent.heartbeat_minutes", label: "Agent heartbeat", group: "Board", values: ["2", "5", "10", "30"], help: "Minutes. A card says stale after two quiet intervals" },
118
118
  { key: "subagents.model", label: "Claude Code", group: "Agents", values: ["inherit", "opus", "sonnet", "haiku"], help: "Its stage subagents: planner, builder, reviewer", when: ["runner", "full"] },
119
119
  { key: "subagents.effort", label: "Claude Code effort", group: "Agents", values: ["inherit", "low", "medium", "high"], help: "Planner, builder, reviewer", when: ["runner", "full"] },
120
+ { key: "subagents.planner", label: "Claude Code planner", group: "Agents", values: ["default", "opus", "sonnet", "haiku"], help: "default: the model above", when: ["runner", "full"] },
121
+ { key: "subagents.builder", label: "Claude Code builder", group: "Agents", values: ["default", "opus", "sonnet", "haiku"], help: "Also runs the fix rounds. default: the model above", when: ["runner", "full"] },
122
+ { key: "subagents.reviewer", label: "Claude Code reviewer", group: "Agents", values: ["default", "opus", "sonnet", "haiku"], help: "Also runs the rechecks. default: the model above", when: ["runner", "full"] },
120
123
  { key: "auto_fix.enabled", label: "Fix findings automatically", group: "Auto-fix", values: ["true", "false"], help: "" },
121
124
  { key: "auto_fix.min_severity", label: "Lowest severity to fix", group: "Auto-fix", values: ["critical", "high", "medium", "low"], help: "", when: ["auto_fix.enabled", "true"] },
122
125
  { key: "auto_fix.max_iterations", label: "Max fix rounds", group: "Auto-fix", values: ["1", "2", "3", "4", "5"], help: "", when: ["auto_fix.enabled", "true"] },
@@ -131,7 +134,8 @@ const SETTINGS: Setting[] = [
131
134
  { key: "orchestration.max_workers", label: "Max workers per run", group: "Orchestration", values: ["1", "2", "3", "4", "5", "6"], help: "Total per run", when: ["orchestration.enabled", "true"] },
132
135
  { key: "orchestration.permissions", label: "Worker permissions", group: "Orchestration", values: ["own", "bypass"], help: "own: each agent's own prompts. Bypass skips every prompt in every worker", when: ["orchestration.enabled", "true"] },
133
136
  // One per tool that takes a model flag; a run freezes its own agent's. Empty: the run's own model.
134
- ...KNOWN_AGENTS.filter((a) => MODEL_FLAGS[a.cmd] && a.cmd !== "claude").map((a): Setting => ({ key: `agent.model.${a.cmd}`, label: `Model: ${a.name}`, group: "Agents", values: [], text: true, help: "The tool's own model name, for every stage: it runs them in one session. Empty: its own default" })),
137
+ ...KNOWN_AGENTS.filter((a) => MODEL_FLAGS[a.cmd]).map((a): Setting => ({ key: `agent.model.${a.cmd}`, label: `Model: ${a.name}`, group: "Agents", values: [], text: true, help: a.cmd === "claude" ? "The session kaizen launches, and every stage subagent left on inherit. Empty: its own default" : "The tool's own model name, for every stage: it runs them in one session. Empty: its own default" })),
138
+ ...KNOWN_AGENTS.filter((a) => MODEL_FLAGS[a.cmd]).map((a): Setting => ({ key: `agent.handoff_model.${a.cmd}`, label: `Handoff model: ${a.name}`, group: "Agents", values: [], text: true, help: "The second agent a worktree run hands off to. Empty: the run's own model" })),
135
139
  ...KNOWN_AGENTS.filter((a) => MODEL_FLAGS[a.cmd]).map((a): Setting => ({ key: `orchestration.worker_model.${a.cmd}`, label: `Worker model: ${a.name}`, group: "Orchestration", values: [], text: true, help: "The tool's own model name. Empty: the run's own model", when: ["orchestration.enabled", "true"] })),
136
140
  { key: "review.write_memory", label: "Remember lessons", group: "Project", values: ["true", "false"], help: "" },
137
141
  { key: "review.memory_max_lines", label: "Memory size cap", group: "Project", values: ["50", "100", "200", "400"], help: "" },
package/cli/sources.ts CHANGED
@@ -361,10 +361,11 @@ function isPrivate(addr: string): boolean {
361
361
  if (isIP(a) === 4) {
362
362
  const [x, y] = a.split(".").map(Number) as [number, number];
363
363
  return x === 0 || x === 10 || x === 127 || (x === 172 && y >= 16 && y <= 31) || (x === 192 && y === 168)
364
- || (x === 169 && y === 254) || (x === 100 && y >= 64 && y <= 127);
364
+ || (x === 169 && y === 254) || (x === 100 && y >= 64 && y <= 127)
365
+ || (x === 192 && y === 0 && a.startsWith("192.0.0.")) || (x === 198 && (y === 18 || y === 19)) || x >= 224; // protocol block, benchmarking, multicast, reserved, broadcast
365
366
  }
366
367
  if (isIP(a) !== 6) return true; // not an address at all
367
- return a === "::1" || a === "::" || /^fe[89ab]/.test(a) || /^f[cd]/.test(a);
368
+ return a === "::1" || a === "::" || /^fe[89ab]/.test(a) || /^f[cd]/.test(a) || /^ff/.test(a) || a.startsWith("64:ff9b:");
368
369
  }
369
370
 
370
371
  type Lookup = (host: string, opts: { all: true }) => Promise<{ address: string }[]>;
package/cli/state.ts CHANGED
@@ -129,6 +129,39 @@ export function agentFlags(projectDir: string, cmd: string, configText?: string,
129
129
  ];
130
130
  }
131
131
 
132
+ // subagents.<key> through the config chain, project first. inherit, default and empty
133
+ // count as unset, so they fall through to the next file.
134
+ function subagentSetting(projectDir: string, key: string): string | null {
135
+ const re = new RegExp(`^subagents:\\n(?:[ \\t#][^\\n]*\\n|\\n)*?[ \\t]+${key}:[ \\t]*["']?([^"'\\s#]*)`, "m");
136
+ for (const t of configTexts(projectDir)) {
137
+ const v = re.exec(t)?.[1];
138
+ if (v && v !== "inherit" && v !== "default") return v;
139
+ }
140
+ return null;
141
+ }
142
+
143
+ export type SubagentStage = "planner" | "builder" | "reviewer";
144
+ export const SUBAGENT_STAGES: SubagentStage[] = ["planner", "builder", "reviewer"];
145
+
146
+ // The model a Claude Code stage subagent runs on: its own subagents.<stage>, else
147
+ // subagents.model. Null: inherit the session's.
148
+ export function subagentModel(projectDir: string, stage?: SubagentStage): string | null {
149
+ const v = (stage && subagentSetting(projectDir, stage)) || subagentSetting(projectDir, "model");
150
+ return v && plainModel(v) ? v : null;
151
+ }
152
+
153
+ // What a Claude Code launch carries so its subagents get subagents.model and .effort
154
+ // even when the agent forgets to pass them. Claude Code reads these as defaults: a model
155
+ // on the Agent call, or a model:/effort: line in the agent file, still wins.
156
+ export function subagentEnv(projectDir: string, cmd: string): string[] {
157
+ if (cmd !== "claude") return [];
158
+ const m = subagentModel(projectDir), e = subagentSetting(projectDir, "effort");
159
+ return [
160
+ ...(m ? [`CLAUDE_CODE_SUBAGENT_MODEL=${m}`] : []),
161
+ ...(e && /^(low|medium|high|xhigh|max)$/.test(e) ? [`CLAUDE_CODE_SUBAGENT_EFFORT=${e}`] : []),
162
+ ];
163
+ }
164
+
132
165
  // What the board's Run form offers: the installed tools, the one it would pick, and
133
166
  // each one's configured model to start the field from.
134
167
  export function agentChoices(projectDir: string) {
@@ -1580,7 +1613,7 @@ function isSession(pid: number, s: Session): boolean | null {
1580
1613
  }
1581
1614
  const ps = onPath("ps");
1582
1615
  if (!ps) return null;
1583
- const m = /^\s*(\S+)\s+(.*)$/.exec(Bun.spawnSync([ps, "-o", "etime=,args=", "-p", String(pid)], { stdin: "ignore", timeout: 5000 }).stdout.toString().trim());
1616
+ const m = /^\s*(\S+)\s+(.*)$/.exec(Bun.spawnSync([ps, "-o", "etime=,args=", "-p", String(pid)], { stdin: "ignore", timeout: 5000, windowsHide: true }).stdout.toString().trim());
1584
1617
  if (!m) return null;
1585
1618
  // etime is [[dd-]hh:]mm:ss
1586
1619
  const [d, rest] = m[1].includes("-") ? m[1].split("-") : ["0", m[1]];
@@ -1753,15 +1786,18 @@ export function sessionLaunch(projectDir: string, cmd: string, base: string[], p
1753
1786
  // time, in Claude's own config. Best effort: any failure just means Claude asks.
1754
1787
  export function trustFolder(dir: string, cfg = join(process.env.CLAUDE_CONFIG_DIR ?? homedir(), ".claude.json")) {
1755
1788
  try {
1756
- const top = Bun.spawnSync(["git", "-C", dir, "rev-parse", "--show-toplevel"], { stderr: "ignore" });
1789
+ const top = Bun.spawnSync(["git", "-C", dir, "rev-parse", "--show-toplevel"], { stderr: "ignore", windowsHide: true });
1757
1790
  // Claude Code keys its projects with forward slashes on Windows, as git prints them.
1758
1791
  const found = top.success ? top.stdout.toString().trim() || dir : dir;
1759
1792
  const root = process.platform === "win32" ? found.replace(/\\/g, "/") : found;
1760
1793
  const d = JSON.parse(readFileSync(cfg, "utf8"));
1761
1794
  if (d.projects?.[root]?.hasTrustDialogAccepted) return;
1795
+ // A repo that brings its own hooks, MCP servers or settings is the case the dialog is for: let Claude ask.
1796
+ if ([".mcp.json", join(".claude", "settings.json"), join(".claude", "settings.local.json")].some((x) => existsSync(join(root, x)))) return;
1762
1797
  d.projects ??= {};
1763
1798
  d.projects[root] = { ...d.projects[root], hasTrustDialogAccepted: true };
1764
- writeFileSync(cfg + ".tmp", JSON.stringify(d, null, 2));
1799
+ // Keep the file's own mode: it holds account data, and a fresh .tmp would take the umask's.
1800
+ writeFileSync(cfg + ".tmp", JSON.stringify(d, null, 2), { mode: statSync(cfg).mode & 0o777 });
1765
1801
  renameSync(cfg + ".tmp", cfg);
1766
1802
  } catch { /* Claude asks as before */ }
1767
1803
  }
@@ -1818,7 +1854,8 @@ export function launchRun(it: Item, from: string, run?: string, pick: { agent?:
1818
1854
  const manual = manualCommand(projectDir, commandOf(agent.cmd, prefs), prompt, flags, acct.dir ? `${acct.envVar}=${shq(acct.dir)}` : "");
1819
1855
  // Only what is started carries env: the returned `cmd` reaches the page.
1820
1856
  // A run the board knows hears which one it is; a new run has no id yet and passes --run.
1821
- const identity = (run || acct.dir) && process.platform !== "win32" ? ["env", ...(run ? [`KAIZEN_RUN_ID=${run}`, ...stageEnv(projectDir, run)] : []), ...accountEnv(acct)] : [];
1857
+ const vars = [...(run ? [`KAIZEN_RUN_ID=${run}`, ...stageEnv(projectDir, run)] : []), ...subagentEnv(projectDir, agent.cmd), ...accountEnv(acct)];
1858
+ const identity = vars.length && process.platform !== "win32" ? ["env", ...vars] : [];
1822
1859
  const started = [...identity, ...withEnv(s.fullCmd, agent.cmd, prefs)];
1823
1860
  const drop = () => { if (s.record) rmSync(s.record, { force: true }); };
1824
1861
 
@@ -1934,7 +1971,8 @@ export function gitStatus(projectDir: string): GitStatus {
1934
1971
  // The path of a `git status --porcelain` line; for a rename, the new one.
1935
1972
  // ponytail: only the surrounding quotes are undone, so a name git escapes (non-ASCII,
1936
1973
  // a quote, a backslash) never matches a report; read `status -z` if that comes up.
1937
- const statusPath = (line: string) => line.slice(3).split(" -> ").pop()!.replace(/^"|"$/g, "");
1974
+ // " -> " separates a rename or copy only; an untracked file may be named `a -> b`.
1975
+ const statusPath = (line: string) => (/[RC]/.test(line.slice(0, 2)) ? line.slice(3).split(" -> ").pop()! : line.slice(3)).replace(/^"|"$/g, "");
1938
1976
 
1939
1977
  // What a run reported changing: 03-impl.md and its fix rounds, the parts of them that
1940
1978
  // list changes (`named`), and when the newest of them was written.
package/cli/versions.ts CHANGED
@@ -42,7 +42,7 @@ function writeStore(place: string, name: string, s: Store) {
42
42
  // Returns { value } when it ran, null when another holder had the lock.
43
43
  function locked<T>(place: string, name: string, fn: () => T): { value: T } | null {
44
44
  const lock = join(place, "videos", name, ".versions.lock");
45
- try { if (Date.now() - statSync(lock).mtimeMs > 60_000) unlinkSync(lock); } catch { /* none */ }
45
+ try { if (Date.now() - statSync(lock).mtimeMs > 60_000) { const aside = `${lock}.${process.pid}.stale`; renameSync(lock, aside); unlinkSync(aside); } } catch { /* none */ }
46
46
  let fd: number;
47
47
  try { fd = openSync(lock, "wx"); } catch { return null; }
48
48
  try { return { value: fn() }; } finally { closeSync(fd); try { unlinkSync(lock); } catch { /* gone */ } }
package/cli/video.ts CHANGED
@@ -63,7 +63,7 @@ function seconds(f: string): number | null {
63
63
  let key: string;
64
64
  try { key = `${f}:${statSync(f).mtimeMs}`; } catch { return null; }
65
65
  if (!probed.has(key)) {
66
- const r = spawnSync("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", f], { encoding: "utf8" });
66
+ const r = spawnSync("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", f], { encoding: "utf8", windowsHide: true });
67
67
  const n = parseFloat(r.stdout ?? "");
68
68
  probed.set(key, Number.isFinite(n) ? Math.round(n) : null);
69
69
  }