kaizen-agent 1.68.0 → 1.69.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -52,6 +52,8 @@ None of this is a lack of intelligence. It is a missing workflow. Many assistant
52
52
 
53
53
  ## Install
54
54
 
55
+ Prefer a window of its own? [Download the desktop app](https://kaizen.sarahdigital.id/#desktop) for macOS, Windows or Linux.
56
+
55
57
  1. **Install** on macOS or Linux:
56
58
  ```bash
57
59
  curl -fsSL https://bun.sh/install | bash && ~/.bun/bin/bunx kaizen-agent
package/cli/install.ts CHANGED
@@ -26,6 +26,23 @@ const force = args.has("--force");
26
26
  const verbose = args.has("--verbose");
27
27
  const interactive = process.stdin.isTTY && !check && !upgrade && !args.has("--yes");
28
28
 
29
+ // Every top-level word kaizen dispatches on. Anything else used to fall through to the
30
+ // installer, so a typo or a command from a newer kaizen reinstalled instead of failing.
31
+ // cli/install-unknown.test.ts fails if a dispatched word is missing here.
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",
34
+ "state", "stats", "uninstall", "upgrade", "version", "web", "worker", "worktree"];
35
+ const first = Bun.argv[2];
36
+ const commandList = ` commands: ${COMMANDS.join(", ")}\n plain \`kaizen\` opens the board; \`kaizen --yes\` installs; \`kaizen init\` sets up this folder\n`;
37
+ if (first && !first.startsWith("-") && !COMMANDS.includes(first)) {
38
+ console.log(`\n unknown command "${first}"\n\n${commandList}`);
39
+ process.exit(1);
40
+ }
41
+ if (first === "help") { console.log(`\n${commandList}`); process.exit(0); }
42
+ // `kaizen init` (README) has always run the installer, which sets up the project folder;
43
+ // keep that, and set up this folder even when it is not a git root.
44
+ if (first === "init") args.add("--init-project");
45
+
29
46
  function parsePresetArg(): PresetName | null {
30
47
  for (const a of Bun.argv.slice(2)) {
31
48
  if (a.startsWith("--preset=")) {
@@ -228,6 +245,46 @@ if (Bun.argv[2] === "done") {
228
245
  process.exit(0);
229
246
  }
230
247
 
248
+ // `kaizen state <run id> key=value ...`: set stage, awaiting, iteration (or any other key)
249
+ // in a run's state.json in one atomic write, refusing words no board understands.
250
+ if (Bun.argv[2] === "state") {
251
+ const { locate, setRunState } = await import("./state.ts");
252
+ const [id, ...pairs] = Bun.argv.slice(3);
253
+ if (!id) { console.log(`\n kaizen state <run id> key=value [key=value ...]\n`); process.exit(1); }
254
+ const why = setRunState(locate() ?? join(home, ".kaizen"), id, pairs);
255
+ if (why) { console.log(`\n ${why}\n`); process.exit(1); }
256
+ console.log(`\n ${id}: ${pairs.join(" ")}\n`);
257
+ process.exit(0);
258
+ }
259
+
260
+ // `kaizen stats [<run id>] [--json]` and `kaizen related <path...>`: read-only, cli/stats.ts.
261
+ if (Bun.argv[2] === "stats" || Bun.argv[2] === "related") {
262
+ const { locate } = await import("./state.ts");
263
+ const { statsText, related } = await import("./stats.ts");
264
+ const state = locate() ?? join(home, ".kaizen");
265
+ const rest = Bun.argv.slice(3), json = rest.includes("--json"), words = rest.filter((a) => a !== "--json");
266
+ if (Bun.argv[2] === "stats") {
267
+ const out = statsText(state, words[0], json);
268
+ console.log(out);
269
+ process.exit(out.startsWith("no run ") ? 1 : 0);
270
+ }
271
+ if (!words.length) { console.log(`\n kaizen related <path> [<path> ...]\n`); process.exit(1); }
272
+ const r = related(state, words);
273
+ console.log(json ? JSON.stringify(r, null, 2) : r.length ? r.map((x) => `${x.id} — ${x.title}${x.open ? ` — ${x.open} open backlog` : ""}`).join("\n") : "Related: none");
274
+ process.exit(0);
275
+ }
276
+
277
+ // `kaizen preview <url|image>`: shows what an agent changed in the board's Browser tab, see cli/preview.ts.
278
+ if (Bun.argv[2] === "preview") {
279
+ const { locate } = await import("./state.ts");
280
+ const { setPreview } = await import("./preview.ts");
281
+ const state = locate();
282
+ const arg = Bun.argv[3] ?? "";
283
+ const why = !arg ? "kaizen preview <localhost url | screenshot.png>" : !state ? "no kaizen project here" : setPreview(state, arg, process.cwd());
284
+ console.log(why ? `\n ${why}\n` : `\n ${c.green("ok")} the open kaizen board shows it: a page in Browser, a screenshot in Preview\n`);
285
+ process.exit(why ? 1 : 0);
286
+ }
287
+
231
288
  // `kaizen remember …` / `kaizen recall …`: global knowledge, see cli/knowledge.ts.
232
289
  if (Bun.argv[2] === "remember" || Bun.argv[2] === "recall") {
233
290
  const { cli } = await import("./knowledge.ts");
@@ -1172,12 +1229,20 @@ function initProject() {
1172
1229
  // ("add a discount cap") does not reach kaizen unless the project says it should.
1173
1230
  // One line in the agent instructions is what makes it the default here.
1174
1231
  function writePointer() {
1175
- const block = `\n## Kaizen workflow\n\nNon-trivial work in this repository follows the staged workflow in\n\`.kaizen/spec.md\`: plan, human approval, build, independent review, bounded fix\nloop. Invoke the \`kaizen\` skill for it — do not carry the stages out inline.\n\nA run costs several times what the same change costs in one session, so spend it\nwhere being wrong is expensive: money, data loss, a migration or anything else hard\nto undo, work a customer sees, or a part of the system nobody has read in a year.\n\nWork where being wrong is cheap and obvious does not start a run. Answering a\nquestion, reading code, a one-line fix, a rename the compiler checks — do those\ndirectly. When it is genuinely unclear, ask rather than assuming the expensive path.\n\nBefore non-trivial work, run \`kaizen recall --track <track> --query "<topic>"\` and\ntreat what it returns as past experience from other projects to verify, not as rules.\n\nRun state lives in \`.kaizen/runs/<id>/\`. Read \`state.json\` first and continue from\nthe stage it names; never advance a run whose \`awaiting\` field is non-null without a\nrecorded human decision.\n`;
1232
+ const block = `\n## Kaizen workflow\n\nNon-trivial work in this repository follows the staged workflow in\n\`.kaizen/spec.md\`: plan, human approval, build, independent review, bounded fix\nloop. Invoke the \`kaizen\` skill for it — do not carry the stages out inline.\n\nA run costs several times what the same change costs in one session, so spend it\nwhere being wrong is expensive: money, data loss, a migration or anything else hard\nto undo, work a customer sees, or a part of the system nobody has read in a year.\n\nWork where being wrong is cheap and obvious does not start a run. Answering a\nquestion, reading code, a one-line fix, a rename the compiler checks — do those\ndirectly. When it is genuinely unclear, ask rather than assuming the expensive path.\n\nBefore non-trivial work, run \`kaizen recall --track <track> --query "<topic>"\` and\ntreat what it returns as past experience from other projects to verify, not as rules.\n\nAfter you change something a person can look at (a page, an app screen, a UI), show it\nbefore saying done: start the app\'s dev server if it is not running, then run\n\`kaizen preview <localhost url>\` (or \`kaizen preview <screenshot.png>\` for a static result).\nA page opens in the kaizen board\'s Browser tab and a screenshot in its Preview tab, never a new browser window.\n\nRun state lives in \`.kaizen/runs/<id>/\`. Read \`state.json\` first and continue from\nthe stage it names; never advance a run whose \`awaiting\` field is non-null without a\nrecorded human decision.\n`;
1176
1233
 
1177
1234
  for (const name of ["CLAUDE.md", "AGENTS.md"]) {
1178
1235
  const f = join(process.cwd(), name);
1179
1236
  const current = existsSync(f) ? readFileSync(f, "utf8") : "";
1180
- if (current.includes("## Kaizen workflow")) continue;
1237
+ if (current.includes("## Kaizen workflow")) {
1238
+ // Projects set up before `kaizen preview` get its paragraph on the next init.
1239
+ if (!current.includes("kaizen preview")) {
1240
+ const para = block.slice(block.indexOf("After you change something"), block.indexOf("Run state lives"));
1241
+ writeFileSync(f, current.replace("\nRun state lives in", "\n" + para + "Run state lives in"));
1242
+ step(`added the preview line to ${name}`);
1243
+ }
1244
+ continue;
1245
+ }
1181
1246
  if (!current && name === "AGENTS.md") continue; // do not create one that was never there
1182
1247
  const text = current ? (current.endsWith("\n") ? "" : "\n") + block : block.slice(1);
1183
1248
  appendFileSync(f, text);
package/cli/knowledge.ts CHANGED
@@ -17,6 +17,21 @@ import { homedir } from "node:os";
17
17
  export const TRACKS = ["code", "writing", "communication", "operations", "research", "preferences"];
18
18
  // preferences.md is the user's to write by hand in v1: taste is never inferred from work.
19
19
  const WRITABLE = TRACKS.filter((t) => t !== "preferences");
20
+ // Planners describe a track in their own words (spec.md: no fixed taxonomy), so the
21
+ // stored label drifts: `software` and `code` name the same work. Map the label, never
22
+ // the inference. A mix ("code+writing") takes its first known part.
23
+ const ALIAS: Record<string, string> = {
24
+ software: "code", app: "code", web: "code", cli: "code", feature: "code", bugfix: "code",
25
+ docs: "writing", documentation: "writing", book: "writing",
26
+ marketing: "communication", copy: "communication",
27
+ ops: "operations", devops: "operations", release: "operations",
28
+ analysis: "research", operational: "operations",
29
+ };
30
+ export function trackOf(t: string): string {
31
+ // Free-form labels ("code: ci flake", "software-enhancement") lead with their kind.
32
+ const parts = t.toLowerCase().split(/[^a-z]+/).filter(Boolean).map((p) => ALIAS[p] ?? p);
33
+ return parts.find((p) => TRACKS.includes(p)) ?? t.toLowerCase().trim();
34
+ }
20
35
  export const SESSION_HEADER = "Past experience from other projects (kaizen recall) — verify before applying, project rules win:";
21
36
  // A session hook only injects lines that share at least one tool with the project.
22
37
  const SESSION_MIN_SCORE = 2;
@@ -75,6 +90,7 @@ export type Remembered = { ok: true; line: string; n: number; similar: string[]
75
90
  // Appends by default; replaces a line only when told which one. It never judges two
76
91
  // lessons the same itself: it hands back the same-tag lines for the caller to decide.
77
92
  export function remember(o: { track: string; tags: string; text: string; applies: string; source: string; replace?: number; projectDir: string }): Remembered {
93
+ o = { ...o, track: trackOf(o.track) };
78
94
  if (!WRITABLE.includes(o.track)) return { ok: false, why: o.track === "preferences" ? "preferences are written by hand, not by remember" : `unknown track "${o.track}" (${WRITABLE.join(", ")})` };
79
95
  if (!globalAllowed(o.projectDir)) return { ok: false, why: "knowledge.global is false for this project; nothing written" };
80
96
  const tags = tagsOf(o.tags);
@@ -112,7 +128,7 @@ export function remember(o: { track: string; tags: string; text: string; applies
112
128
  export function recall(o: { track?: string; tags?: string; query?: string; limit?: number; min?: number }): string[] {
113
129
  const want = tagsOf(o.tags ?? "");
114
130
  const words = (o.query ?? "").toLowerCase().split(/\W+/).filter((w) => w.length > 2);
115
- const tracks = o.track ? [o.track] : TRACKS;
131
+ const tracks = o.track ? [trackOf(o.track)] : TRACKS;
116
132
  const scored = tracks.flatMap((t) => lines(t)).map((l) => {
117
133
  const bare = l.tags.map((t) => t.split("@")[0]);
118
134
  // An exact tag (bun@1.2) outranks the same tool at another version (bun@1.1).
@@ -193,7 +209,7 @@ export function cli(argv: string[], cwd = process.cwd()): number {
193
209
  if (rest.includes("--session")) { process.stdout.write(sessionText(cwd)); return 0; }
194
210
  const track = flag("--track"), tags = flag("--tags"), query = flag("--query"), limit = Number(flag("--limit") ?? 20);
195
211
  if (!Number.isInteger(limit) || limit < 1) { console.log("--limit must be a whole number above 0"); return 1; }
196
- if (track && !TRACKS.includes(track)) { console.log(`unknown track "${track}"`); return 1; }
212
+ if (track && !TRACKS.includes(trackOf(track))) { console.log(`unknown track "${track}"`); return 1; }
197
213
  const out = recall({ track, tags, query: query ?? rest.join(" "), limit });
198
214
  console.log(out.length ? out.join("\n") : "Recalled: none");
199
215
  return 0;
package/cli/preview.ts ADDED
@@ -0,0 +1,29 @@
1
+ // `kaizen preview <url|image>`: tells the board's own Browser tab what the agent just
2
+ // changed. It only writes <state>/preview.json; the open board polls GET /preview and
3
+ // frames the page itself. This never launches a browser, so with no board open nothing opens.
4
+ import { copyFileSync, existsSync, mkdirSync, writeFileSync } from "node:fs";
5
+ import { basename, extname, join, resolve } from "node:path";
6
+
7
+ export type Preview = { url?: string; image?: string; ws: string; at: number };
8
+
9
+ const IMG = /^\.(png|jpe?g|gif|webp)$/i;
10
+ const LOOPBACK = /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?(\/|$)/;
11
+
12
+ // Returns an error message, or null once preview.json is written.
13
+ export function setPreview(state: string, arg: string, cwd: string): string | null {
14
+ const p: Preview = { ws: resolve(cwd), at: Date.now() };
15
+ if (/^https?:\/\//i.test(arg)) {
16
+ if (!LOOPBACK.test(arg)) return "only a localhost address (the dev server), e.g. http://localhost:3000";
17
+ p.url = arg;
18
+ } else {
19
+ const f = resolve(cwd, arg);
20
+ if (!existsSync(f) || !IMG.test(extname(f))) return "give a localhost URL or a png/jpg/gif/webp screenshot that exists";
21
+ // Under attachments/, where the board's /file route already serves from.
22
+ const name = `preview-${p.at}${extname(f).toLowerCase()}`;
23
+ mkdirSync(join(state, "attachments"), { recursive: true });
24
+ copyFileSync(f, join(state, "attachments", name));
25
+ p.image = `attachments/${basename(name)}`;
26
+ }
27
+ writeFileSync(join(state, "preview.json"), JSON.stringify(p));
28
+ return null;
29
+ }
package/cli/settings.ts CHANGED
@@ -120,6 +120,8 @@ const SETTINGS: Setting[] = [
120
120
  { key: "auto_fix.enabled", label: "Fix findings automatically", group: "Auto-fix", values: ["true", "false"], help: "" },
121
121
  { 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
122
  { key: "auto_fix.max_iterations", label: "Max fix rounds", group: "Auto-fix", values: ["1", "2", "3", "4", "5"], help: "", when: ["auto_fix.enabled", "true"] },
123
+ { key: "auto_guard.max_files", label: "Auto mode: stop above this many changed files", group: "Auto-fix", values: ["10", "25", "50", "0"], help: "0 turns the check off" },
124
+ { key: "auto_guard.stop_on", label: "Auto mode: stop on an open finding at", group: "Auto-fix", values: ["critical", "high", "medium", "low", "off"], help: "" },
123
125
  { key: "git.auto_commit", label: "Commit when done", group: "Git", values: ["false", "true"], help: "Never pushes" },
124
126
  { key: "git.worktree_per_run", label: "Branch and folder per run", group: "Git", values: ["ask", "true", "false"], help: "" },
125
127
  { key: "git.generated", label: "Generated files", group: "Git", values: [], text: true, help: "Path patterns, space-separated. A land takes the base's side on conflict. Empty: none" },
package/cli/state.ts CHANGED
@@ -2035,6 +2035,39 @@ function setStage(file: string, change: (s: any) => boolean): boolean {
2035
2035
  return true;
2036
2036
  } catch { return false; }
2037
2037
  }
2038
+ // `kaizen state <id> key=value ...`: the one writer agents use for a run's state.json,
2039
+ // so stage and awaiting can only take the words every reader knows (spec.md, Stage 0).
2040
+ // `done` is refused: finishing goes through finishRun, which checks the review gate.
2041
+ const STAGES = ["plan", "build", "review", "abandoned"];
2042
+ const AWAITING = [null, "approvals.plan", "approvals.review", "approvals.each_file", "findings"];
2043
+ export function setRunState(state: string, id: string, pairs: string[]): string | null {
2044
+ const file = join(state, "runs", id, "state.json");
2045
+ if (!existsSync(file)) return `no run ${id} under ${state}`;
2046
+ if (!pairs.length) return "nothing to set: pass key=value";
2047
+ const set: Record<string, unknown> = {};
2048
+ for (const p of pairs) {
2049
+ const i = p.indexOf("=");
2050
+ if (i < 1) return `not key=value: ${p}`;
2051
+ const k = p.slice(0, i), raw = p.slice(i + 1);
2052
+ const v = raw === "null" ? null : raw;
2053
+ if (k === "id" || k === "updated") return `${k} is not set by hand`;
2054
+ if (k === "stage" && v === "done") return "stage done: use kaizen done <id>, which checks the final approval";
2055
+ if (k === "stage" && !STAGES.includes(String(v))) return `stage must be one of ${STAGES.join(", ")} (done: kaizen done)`;
2056
+ if (k === "awaiting" && !AWAITING.includes(v as any)) return `awaiting must be null or one of ${AWAITING.slice(1).join(", ")}`;
2057
+ if (k === "iteration") { if (!/^\d+$/.test(raw)) return "iteration must be a whole number"; set[k] = Number(raw); continue; }
2058
+ set[k] = v;
2059
+ }
2060
+ let now: any = null;
2061
+ if (!setStage(file, (s) => { Object.assign(s, set); now = s; return true; })) return `state.json for ${id} changed while writing or is not valid JSON; read it and retry`;
2062
+ if ("stage" in set || "awaiting" in set) logStage(state, id, now.stage, now.awaiting);
2063
+ return null;
2064
+ }
2065
+ // runs/<id>/stages.log: one line per stage or awaiting change, `<iso> <stage> <awaiting|->`.
2066
+ // File mtimes cannot time stages (02-approval.md gains its accepted line at done), so
2067
+ // `kaizen stats` reads this. Only writes through kaizen state / kaizen done are logged.
2068
+ export function logStage(state: string, id: string, stage: string, awaiting: string | null) {
2069
+ try { appendFileSync(join(state, "runs", id, "stages.log"), `${new Date().toISOString()} ${stage} ${awaiting ?? "-"}\n`); } catch { /* timing is best effort */ }
2070
+ }
2038
2071
  // Rewrites runs an agent marked done without acceptance (gate on) to review /
2039
2072
  // approvals.review; returns the ids. Not part of readRuns: reads stay pure (mtime is liveness).
2040
2073
  export function healRuns(state: string): string[] {
@@ -2067,7 +2100,7 @@ export function finishRun(state: string, id: string, userApproved = false): stri
2067
2100
  const why = recordAcceptance(state, id, "chat");
2068
2101
  if (why) return why;
2069
2102
  }
2070
- setStage(file, (s) => { s.stage = "done"; s.awaiting = null; delete s.healed; return true; });
2103
+ if (setStage(file, (s) => { s.stage = "done"; s.awaiting = null; delete s.healed; return true; })) logStage(state, id, "done", null);
2071
2104
  return null;
2072
2105
  }
2073
2106
  const names = (report: string, path: string) => report.includes("`" + path + "`") || report.includes("`" + path + ":");
package/cli/stats.ts ADDED
@@ -0,0 +1,172 @@
1
+ // `kaizen stats [<id>] [--json]` and `kaizen related <path...>`: read-only views over
2
+ // the files every run already writes. Nothing here writes, so old runs get stats too.
3
+ // Stage times come from runs/<id>/stages.log (written by kaizen state / kaizen done), not
4
+ // file mtimes: files are rewritten later in a run, so their times say nothing per stage.
5
+ // A run with no log (every run before it existed) shows "–".
6
+ import { readFileSync, readdirSync, statSync, existsSync, openSync, readSync, closeSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { homedir } from "node:os";
9
+ import { changedPaths, projectOf } from "./state.ts";
10
+ import { trackOf } from "./knowledge.ts";
11
+
12
+ const read = (f: string) => { try { return readFileSync(f, "utf8"); } catch { return ""; } };
13
+ const mtime = (f: string) => { try { return statSync(f).mtimeMs; } catch { return 0; } };
14
+
15
+ export type RunStat = {
16
+ id: string; stage: string; track: string; runner: string; mode: string;
17
+ reviewed: boolean; fixed: boolean; unverified: boolean;
18
+ plan: number | null; wait: number | null; build: number | null; review: number | null;
19
+ };
20
+
21
+ export function runStat(state: string, id: string): RunStat | null {
22
+ const dir = join(state, "runs", id);
23
+ let s: any;
24
+ try { s = JSON.parse(read(join(dir, "state.json"))); } catch { return null; }
25
+ const t = (f: string) => mtime(join(dir, f));
26
+ let iters: string[] = [];
27
+ try { iters = readdirSync(join(dir, "05-iterations")); } catch { /* none */ }
28
+ return {
29
+ id, stage: String(s.stage ?? "?"), track: s.track ? trackOf(String(s.track)) : "?",
30
+ runner: String(s.runner ?? "?"), mode: String(s.mode ?? "?"),
31
+ reviewed: existsSync(join(dir, "04-review.md")),
32
+ fixed: iters.length > 0,
33
+ unverified: /CANNOT VERIFY/.test(read(join(dir, "04-review.md"))),
34
+ ...stageTimes(read(join(dir, "stages.log")), t("00-request.md")),
35
+ };
36
+ }
37
+
38
+ // Each interval between log lines is charged to the state at its start: waiting when
39
+ // awaiting is set, else the stage. The interval before the first line is planning,
40
+ // from the request's write (00-request.md is written once, at intake).
41
+ export function stageTimes(log: string, start: number) {
42
+ const out = { plan: null as number | null, wait: null as number | null, build: null as number | null, review: null as number | null };
43
+ const rows = log.split("\n").map((l) => l.trim().split(/\s+/)).filter((r) => r.length >= 3 && !isNaN(Date.parse(r[0]!)))
44
+ .map(([at, stage, awaiting]) => ({ at: Date.parse(at!), stage: stage!, waiting: awaiting !== "-" }));
45
+ if (!rows.length) return out;
46
+ // Only a log that starts at plan or build covers planning; one that starts later (the
47
+ // run began on an older kaizen, or by hand) has an unknown gap, left uncounted.
48
+ const lead = start && start <= rows[0]!.at && (rows[0]!.stage === "plan" || rows[0]!.stage === "build");
49
+ const seq = lead ? [{ at: start, stage: "plan", waiting: false }, ...rows] : rows;
50
+ for (let i = 0; i + 1 < seq.length; i++) {
51
+ const a = seq[i]!, d = seq[i + 1]!.at - a.at;
52
+ if (d < 0 || a.stage === "done" || a.stage === "abandoned") continue;
53
+ const k = a.waiting ? "wait" : (a.stage as keyof typeof out);
54
+ if (k in out) out[k] = (out[k] ?? 0) + d;
55
+ }
56
+ return out;
57
+ }
58
+
59
+ export function allStats(state: string): RunStat[] {
60
+ let ids: string[] = [];
61
+ try { ids = readdirSync(join(state, "runs")); } catch { return []; }
62
+ return ids.sort().map((id) => runStat(state, id)).filter((r): r is RunStat => !!r);
63
+ }
64
+
65
+ const median = (xs: number[]) => {
66
+ if (!xs.length) return null;
67
+ const s = [...xs].sort((a, b) => a - b), m = s.length >> 1;
68
+ return s.length % 2 ? s[m]! : (s[m - 1]! + s[m]!) / 2;
69
+ };
70
+ const count = (rs: RunStat[], k: keyof RunStat) => rs.reduce((o, r) => { const v = String(r[k]); o[v] = (o[v] ?? 0) + 1; return o; }, {} as Record<string, number>);
71
+
72
+ export function summary(rs: RunStat[]) {
73
+ const reviewed = rs.filter((r) => r.reviewed);
74
+ const med = (k: "plan" | "wait" | "build" | "review") => median(rs.map((r) => r[k]).filter((v): v is number => v !== null));
75
+ return {
76
+ runs: rs.length,
77
+ stage: count(rs, "stage"), track: count(rs, "track"), runner: count(rs, "runner"), mode: count(rs, "mode"),
78
+ reviewed: reviewed.length,
79
+ fixed: rs.filter((r) => r.fixed).length,
80
+ unverified: rs.filter((r) => r.unverified).length,
81
+ timed: rs.filter((r) => r.plan !== null || r.build !== null).length,
82
+ median: { plan: med("plan"), wait: med("wait"), build: med("build"), review: med("review") },
83
+ };
84
+ }
85
+
86
+ // Tokens a Claude run used, from its session log: `~/.claude/projects/*/<session>.jsonl`.
87
+ // One session can carry several runs, so only lines inside [from, to] count.
88
+ export type Tokens = { input: number; output: number; cacheRead: number; cacheWrite: number; turns: number };
89
+ export function sessionLog(session: string, home = homedir()): string | null {
90
+ const root = join(home, ".claude", "projects");
91
+ let dirs: string[] = [];
92
+ try { dirs = readdirSync(root); } catch { return null; }
93
+ for (const d of dirs) { const f = join(root, d, `${session}.jsonl`); if (existsSync(f)) return f; }
94
+ return null;
95
+ }
96
+ export function tokensIn(file: string, from: number, to: number): Tokens {
97
+ const t: Tokens = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, turns: 0 };
98
+ // Streamed in chunks: a long session log runs to hundreds of MB.
99
+ const fd = openSync(file, "r"), buf = Buffer.alloc(1 << 20);
100
+ let rest = "";
101
+ const line = (l: string) => {
102
+ if (!l.includes('"usage"')) return;
103
+ let j: any;
104
+ try { j = JSON.parse(l); } catch { return; }
105
+ const at = Date.parse(j.timestamp ?? ""), u = j.message?.usage;
106
+ if (!u || !(at >= from && at <= to)) return;
107
+ t.input += u.input_tokens ?? 0; t.output += u.output_tokens ?? 0;
108
+ t.cacheRead += u.cache_read_input_tokens ?? 0; t.cacheWrite += u.cache_creation_input_tokens ?? 0;
109
+ t.turns++;
110
+ };
111
+ try {
112
+ for (let n; (n = readSync(fd, buf, 0, buf.length, null)) > 0;) {
113
+ const parts = (rest + buf.toString("utf8", 0, n)).split("\n");
114
+ rest = parts.pop()!;
115
+ parts.forEach(line);
116
+ }
117
+ line(rest);
118
+ } finally { closeSync(fd); }
119
+ return t;
120
+ }
121
+ export function runTokens(state: string, id: string, home = homedir()): Tokens | null {
122
+ const dir = join(state, "runs", id);
123
+ let s: any;
124
+ try { s = JSON.parse(read(join(dir, "state.json"))); } catch { return null; }
125
+ if (!s.session || (s.agent && s.agent !== "claude")) return null;
126
+ const log = sessionLog(String(s.session), home);
127
+ if (!log) return null;
128
+ const from = mtime(join(dir, "00-request.md")), to = Date.parse(s.updated ?? "") || mtime(join(dir, "state.json"));
129
+ return from ? tokensIn(log, from, to) : null;
130
+ }
131
+
132
+ // Earlier runs whose report names any of these paths as changed, newest first.
133
+ export function related(state: string, paths: string[], limit = 5): { id: string; title: string; open: number }[] {
134
+ const want = new Set(paths.map((p) => p.replace(/^\.\//, "")));
135
+ const project = projectOf(state);
136
+ let ids: string[] = [];
137
+ try { ids = readdirSync(join(state, "runs")).sort().reverse(); } catch { return []; }
138
+ const out: { id: string; title: string; open: number }[] = [];
139
+ for (const id of ids) {
140
+ const dir = join(state, "runs", id), impl = read(join(dir, "03-impl.md"));
141
+ if (!impl || !changedPaths(impl, project).some((p) => want.has(p))) continue;
142
+ const title = read(join(dir, "00-request.md")).split("\n").find((l) => l.trim())?.replace(/^#+\s*/, "").slice(0, 90) ?? "";
143
+ const open = (read(join(dir, "06-backlog.md")).match(/^- open:/gm) ?? []).length;
144
+ out.push({ id, title, open });
145
+ if (out.length >= limit) break;
146
+ }
147
+ return out;
148
+ }
149
+
150
+ const dur = (ms: number | null) => ms === null ? "–" : ms < 3.6e6 ? `${Math.round(ms / 6e4)}m` : `${(ms / 3.6e6).toFixed(1)}h`;
151
+ const pct = (n: number, d: number) => (d ? `${Math.round((100 * n) / d)}%` : "–");
152
+ const kv = (o: Record<string, number>) => Object.entries(o).sort((a, b) => b[1] - a[1]).map(([k, v]) => `${k} ${v}`).join(", ");
153
+
154
+ export function statsText(state: string, id?: string, json = false): string {
155
+ if (id) {
156
+ const r = runStat(state, id);
157
+ if (!r) return `no run ${id}`;
158
+ const t = runTokens(state, id);
159
+ if (json) return JSON.stringify({ ...r, tokens: t }, null, 2);
160
+ const tok = t ? `${t.input + t.cacheWrite + t.cacheRead} in (${t.cacheRead} from cache), ${t.output} out, ${t.turns} turns` : "n/a";
161
+ return [`${r.id} ${r.stage} · ${r.track} · ${r.runner} · ${r.mode}`,
162
+ `plan ${dur(r.plan)} · waiting for approval ${dur(r.wait)} · build ${dur(r.build)} · review ${dur(r.review)} (from stages.log)`,
163
+ `fix round: ${r.fixed ? "yes" : "no"} · CANNOT VERIFY: ${r.unverified ? "yes" : "no"}`,
164
+ `tokens: ${tok}`].join("\n");
165
+ }
166
+ const s = summary(allStats(state));
167
+ if (json) return JSON.stringify(s, null, 2);
168
+ return [`${s.runs} runs — ${kv(s.stage)}`,
169
+ `track: ${kv(s.track)}`, `runner: ${kv(s.runner)} · mode: ${kv(s.mode)}`,
170
+ `fix round: ${s.fixed} of ${s.reviewed} reviewed (${pct(s.fixed, s.reviewed)}) · CANNOT VERIFY in ${s.unverified} reviews (${pct(s.unverified, s.reviewed)})`,
171
+ `median: plan ${dur(s.median.plan)} · waiting for approval ${dur(s.median.wait)} · build ${dur(s.median.build)} · review ${dur(s.median.review)} (runs with a stages.log: ${s.timed})`].join("\n");
172
+ }
package/cli/web.ts CHANGED
@@ -1112,6 +1112,13 @@ export async function web(repoDir: string, opts: Opts = {}) {
1112
1112
  if (!isLoopback(u)) return bad("only a localhost address", 400);
1113
1113
  return json({ ok: await openApp(u.href, join(home, ".kaizen", "app-window")) });
1114
1114
  }
1115
+ // What `kaizen preview` last wrote for this state dir (cli/preview.ts); the board's Browser tab polls it.
1116
+ if (req.method === "GET" && path === "/preview") {
1117
+ if (!local(req)) return bad("cross-origin request refused", 403);
1118
+ const dir = qdir() ?? state;
1119
+ if (!dir || !states(true).includes(dir)) return bad("unknown state dir", 404);
1120
+ try { return json(JSON.parse(readFileSync(join(dir, "preview.json"), "utf8"))); } catch { return json({}); }
1121
+ }
1115
1122
  // The loopback ports this workspace's own processes listen on (its dev server), so the
1116
1123
  // Browser opens the run's app and not another project's on the Preview's port. Linux only
1117
1124
  // (ss + /proc); elsewhere the answer is empty and the Preview's address is used.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kaizen-agent",
3
- "version": "1.68.0",
3
+ "version": "1.69.1",
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": {
@@ -110,9 +110,8 @@ A tool that charges the same for a typo and a payroll change gets turned off for
110
110
  files or fifty lines, run the stages in this session (`runner: lite`, below)
111
111
  rather than dispatching them. Keep the plan and review brief, then apply the same
112
112
  bounded fix loop to review findings. Small size does not leave a finding for a later
113
- run when it can be fixed within this one.
114
-
115
- **Short work still gets a run.** A one-line change is not skipped past the stages: the card on the board moves through plan, build and review like any other. Run it with `runner: lite` and the short path above — a brief plan, the build, a short review — so the cost stays small and the run stays visible.
113
+ run when it can be fixed within this one. Even a one-line change gets a run this way,
114
+ so its card still moves through plan, build and review.
116
115
 
117
116
  This is a judgement, not a threshold to enforce: fifty lines that change how money is
118
117
  rounded are not a small change. Say which path you took (short or full) and why, in one line, when the
@@ -128,7 +127,8 @@ Set by `mode` in config, overridable per invocation.
128
127
  - **`approve`** (default) — stop at every approval enabled in config and wait for an
129
128
  explicit human decision.
130
129
  - **`auto`** — run every stage back to back with no approval, report at the end. The fix
131
- loop still respects `max_iterations`.
130
+ loop still respects `max_iterations`, and `auto_guard` stops a run that changed too
131
+ many files or kept a serious finding (*Auto guard* in `spec-main.md`).
132
132
  - **`review-only`** — skip plan and implementation, run the reviewer against existing
133
133
  code or a diff.
134
134
 
@@ -247,19 +247,13 @@ final report, so nobody reads a same-session review as an independent one.
247
247
 
248
248
  ## Running a stage
249
249
 
250
- **If the tool you are running in has no subagents** — Codex, and anything else that
251
- runs one session at a time — do not try to fake them. Run the stages sequentially in
252
- the one session, following [`adapters.md`](adapters.md): start each stage by reading
253
- only its declared inputs, write its artifact before moving on, and when reviewing,
254
- judge the work on its own terms rather than defending the reasoning you used writing
255
- it. Everything else in this file holds unchanged.
256
-
257
- **Check `runner` first.**
250
+ **Check `runner` first.** A tool with no subagents (Codex, anything that runs one
251
+ session at a time) runs as `lite` whatever the setting, following
252
+ [`adapters.md`](adapters.md); do not fake subagents.
258
253
 
259
- - `runner: lite` — do not call the Agent tool, except for the review as below. You run plan, build and review
260
- yourself, in that order, reading only each stage's declared inputs and writing its
261
- artifact before starting the next. The stage table below still applies; you are the
262
- agent for every row.
254
+ - `runner: lite` — do not call the Agent tool, except for the review as below. You run
255
+ plan, build and review yourself, as *Who runs the stages* says; the stage table below
256
+ still applies, and you are the agent for every row.
263
257
  Read `spec-build.md` before building and `spec-main.md` before moving the run to
264
258
  `review`: being the main thread does not excuse a stage its contract. Its *Preview
265
259
  gate* holds in full — a result that shows on a screen needs a real screenshot under
@@ -296,7 +290,7 @@ knob: when it is not `inherit`, make sure the frontmatter of the agent's definit
296
290
  carries `effort: <value>` — edit or add that one line, nothing else — before the
297
291
  first dispatch of the run. `inherit` means leave the file alone.
298
292
 
299
- After a subagent returns, update `state.json` yourself in the main thread. Subagents
293
+ After a subagent returns, update `state.json` yourself in the main thread, with `kaizen state` from 1.69.0, by hand before that (`spec.md`, Stage 0). Subagents
300
294
  report; the main thread owns the state machine.
301
295
  Before moving any run from `build` to `review`, under either runner, apply the
302
296
  *Preview gate* in [`spec-main.md`](spec-main.md): no `## Preview` with a screenshot
@@ -351,28 +345,10 @@ shown automatically.
351
345
  state.json
352
346
  ```
353
347
 
354
- `state.json` is the resume point, and records the runner and the agent the run started with, so a
355
- run picked up later keeps the shape it was reviewed under rather than silently
356
- changing because a setting moved:
357
-
358
- ```json
359
- {
360
- "id": "2026-09-02-add-oauth",
361
- "mode": "approve",
362
- "runner": "full",
363
- "agent": "claude",
364
- "stage": "review",
365
- "awaiting": "approvals.review",
366
- "iteration": 1,
367
- "updated": "2026-09-02T14:31:00+07:00"
368
- }
369
- ```
370
-
371
- Every run writes all nine keys, from intake on: `id`, `mode`, `runner`, `agent`,
372
- `track`, `stage`, `awaiting`, `iteration` (0 until the fix loop runs), `updated`. Where
373
- the environment has `CLAUDE_CODE_SESSION_ID`, also `session` with its value: without it
374
- a card launched from the board can stay stuck in planning beside its own run. The
375
- legal values of `stage` and `awaiting` are in [`spec.md`](spec.md).
348
+ `state.json` is the resume point. Its keys (all nine from intake on, plus `session`
349
+ where `CLAUDE_CODE_SESSION_ID` is set, and `review_executor` on a lite run), their legal
350
+ values, and why `runner` and `agent` are frozen at intake are in *Stage 0* of
351
+ [`spec.md`](spec.md), with when to write it through `kaizen state` (1.69.0 and later) and when by hand.
376
352
 
377
353
  In a git repository, `init` also adds a gitignore entry that ignores run state but
378
354
  keeps the workflow: it ignores `.kaizen/*` and un-ignores `.kaizen/spec*.md` and
@@ -62,6 +62,16 @@ auto_fix:
62
62
  # knob in the file. A third round rarely closes what two could not.
63
63
  max_iterations: 2
64
64
 
65
+ # Stops for auto mode only (mode: auto); approve mode already stops at every approval.
66
+ # Auto runs every stage back to back, so these are what bring a runaway run back to you:
67
+ # the run stops at the final approval with the reason instead of finishing.
68
+ auto_guard:
69
+ # Stop when the build changed more files than this. 0 turns this check off.
70
+ max_files: 25
71
+ # Stop when a finding at or above this severity is still open after the fix loop.
72
+ # critical | high | medium | low | off
73
+ stop_on: high
74
+
65
75
  review:
66
76
  # Who reviews a lite run. Only read when runner is lite; under full the reviewer is
67
77
  # always its own agent.
@@ -137,7 +137,7 @@ files its report names, so a changed path written any other way is left out of t
137
137
  commit, and a backticked path the run did not change is taken into it. Report failures honestly; a false claim of
138
138
  success poisons the review stage, which trusts this report.
139
139
 
140
- **A `## Preview` section says how to see the result.** For an app or service: the
140
+ **A `## Preview` section says how to see the result.** Where the result shows on a screen, also run `kaizen preview <localhost url | screenshot.png>` so the board shows it (a page in Browser, a screenshot in Preview) (never a new browser window). For an app or service: the
141
141
  commands to start it locally and the URL to open, copied from the material's own README
142
142
  where one exists. An app with a dev server: leave it running when the build ends
143
143
  (started in the background, its log in a file), and write its full `http://localhost:<port>`
@@ -209,6 +209,12 @@ be run, opened, or read by someone, doing so is part of building it: the suite r
209
209
  the page opened and clicked, the runbook walked start to finish, the copy read aloud.
210
210
  A gate item whose evidence is an argument that the code should work is a `FAIL`.
211
211
 
212
+ Then check the request itself, as the reviewer will: each requirement in the verbatim
213
+ request and its *done* and *wrong* lines in `00-request.md` that no `G-nn` covers gets a
214
+ line `R PASS: <what was tried and what came back>` or `R FAIL: <what>`. The reviewer
215
+ writes its own criteria cold and trusts none of these; they exist so a gap the plan
216
+ missed is found here instead of costing a fix round.
217
+
212
218
  The stage does not hand off with a `FAIL` standing. Fix it and re-run the gate, or —
213
219
  if it cannot be fixed inside the plan's scope — stop and report, exactly as with an
214
220
  impossible step. A `FAIL` carried into review wastes the reviewer's pass on something
@@ -153,6 +153,18 @@ whose changes leave every note true touches nothing and says so in one line.
153
153
 
154
154
  ---
155
155
 
156
+ ## Auto guard
157
+
158
+ Only in `auto` mode. After the fix loop ends and before the final approval, check
159
+ `auto_guard` from config: the build changed more files than `max_files` (count the
160
+ changed paths `03-impl.md` names; `0` turns this off), or a finding at or above
161
+ `stop_on` is still open (`off` turns this off). Either way, stop: `kaizen state <id>
162
+ awaiting=approvals.review` (by hand before 1.69.0), and tell the user in one line which
163
+ check fired. The run then waits for an explicit accept as in *Final approval*, even with
164
+ `auto_accept` on. Neither check fires in `approve` mode, which already stops.
165
+
166
+ ---
167
+
156
168
  ## Final approval
157
169
 
158
170
  Controlled by `approvals.review`. `auto` skips every stop before it, not this one, unless `auto_accept` is on.
@@ -14,7 +14,10 @@ notes it lists for areas the request touches — the output of
14
14
  `kaizen recall --track <track> --tags <stack tags> --query "<words from the request>"`
15
15
  — past experience from other projects, to verify against this one, never binding
16
16
  like project rules; the Framing ends with `Recalled: <n> lessons; used: <the lines it
17
- relied on>` or `Recalled: none` — and the existing material —
17
+ relied on>` or `Recalled: none` — the output of `kaizen related <the File manifest's
18
+ paths>` (1.69.0 and later): earlier runs that changed those files, whose plans, findings
19
+ and open backlog may bear on this one; the Framing adds `Related: <ids it used>` or
20
+ `Related: none` — and the existing material —
18
21
  the codebase, the manuscript, the current campaign, whatever this run builds on.
19
22
  **Output:** `01-plan.md`.
20
23
 
@@ -207,6 +210,13 @@ The planner reads code but writes none. Its plan must contain:
207
210
  Reviewer severity `medium`.
208
211
  - **lock** — consistency with what is already there. Reviewer severity `low`.
209
212
 
213
+ End every item with `— proof: <how>`: the test or command to run, the screenshot to
214
+ take, the source to check a claim against, the person who reads it. The builder
215
+ produces that proof and the reviewer re-runs it, so a check nobody can run is found
216
+ at the approval rather than as `CANNOT VERIFY` after the build. Where the only proof
217
+ needs something no agent has (a live account, a real device, taste), say so in the
218
+ proof: it is a human check from the start.
219
+
210
220
  Phrase every item so the answer is yes or no. "Handles errors well" is not a gate
211
221
  item; "every new query path has a covering test" is. A tier fixes the severity
212
222
  before the reviewer has an opinion, which is what stops the same class of problem