kaizen-agent 1.62.0 → 1.64.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 (51) hide show
  1. package/cli/automations.test.ts +167 -0
  2. package/cli/automations.ts +298 -0
  3. package/cli/dashboard.ts +1 -7
  4. package/cli/handoff.test.ts +133 -0
  5. package/cli/handoff.ts +122 -0
  6. package/cli/install.test.ts +16 -0
  7. package/cli/install.ts +92 -191
  8. package/cli/look.ts +33 -0
  9. package/cli/pty.ts +16 -2
  10. package/cli/resources.test.ts +50 -0
  11. package/cli/resources.ts +113 -0
  12. package/cli/restart.test.ts +28 -1
  13. package/cli/settings.ts +6 -2
  14. package/cli/setup.test.ts +22 -2
  15. package/cli/setup.ts +101 -51
  16. package/cli/sources.ts +1 -1
  17. package/cli/state.test.ts +7 -0
  18. package/cli/state.ts +13 -2
  19. package/cli/usage.test.ts +11 -0
  20. package/cli/web.ts +134 -6
  21. package/cli/workers.ts +11 -4
  22. package/cli/worktree.test.ts +174 -1
  23. package/cli/worktree.ts +190 -35
  24. package/package.json +1 -1
  25. package/skills/kaizen/config.default.yml +17 -0
  26. package/skills/kaizen/settings.md +4 -0
  27. package/skills/kaizen/spec-build.md +13 -0
  28. package/skills/kaizen/spec-main.md +13 -0
  29. package/skills/kaizen-help/SKILL.md +1 -0
  30. package/skills/media/kaizen-deck/SKILL.md +21 -2
  31. package/skills/media/kaizen-deck/scripts/motion.py +99 -0
  32. package/web/board/cards.ts +1 -0
  33. package/web/board/git.ts +4 -4
  34. package/web/board/phone.ts +5 -5
  35. package/web/board/resources.ts +152 -0
  36. package/web/board/run-view.ts +107 -1
  37. package/web/board/search.ts +6 -0
  38. package/web/board/settings-automations.ts +71 -0
  39. package/web/board/settings-pages.test.ts +4 -0
  40. package/web/board/settings-pages.ts +2 -1
  41. package/web/board/settings.ts +10 -3
  42. package/web/board/workspace.ts +7 -1
  43. package/web/board/ws-tabs.test.ts +20 -1
  44. package/web/board/ws-tabs.ts +26 -7
  45. package/web/board.html +20 -3
  46. package/web/board.js +119 -88
  47. package/web/notebook.js +23 -23
  48. package/web/notes.html +1 -0
  49. package/web/term.js +1 -1
  50. package/web/video.html +1 -0
  51. package/web/video.js +49 -49
@@ -0,0 +1,167 @@
1
+ import { expect, test } from "bun:test";
2
+ import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { addRule, DAILY_CAP, dueSince, fire, nextRun, parseCron, patchRule, presetCron, promptOf, readHistory, readRules, runOf, shellArgv, shown, tickAutomations, type Rule } from "./automations.ts";
6
+
7
+ // Nothing here starts an agent or a terminal: every launch is the fake below.
8
+ const proj = () => { const d = mkdtempSync(join(tmpdir(), "kz-auto-")); const st = join(d, ".kaizen"); mkdirSync(join(st, "runs"), { recursive: true }); return st; };
9
+ const at = (y: number, mo: number, d: number, h = 0, mi = 0) => new Date(y, mo - 1, d, h, mi).getTime();
10
+ const spy = (ok = true) => { const calls: { it: any; from: string; pick: any }[] = []; return { calls, launch: ((it: any, from: string, _r: any, pick: any) => { calls.push({ it, from, pick }); return ok ? { ok: true } : { ok: false, why: "no terminal" }; }) as any }; };
11
+ const mk = (st: string, o: any = {}): Rule => { const r = addRule(st, { name: "n", text: "check things", kind: "hourly", time: "09:05", ...o }); if (typeof r === "string") throw new Error(r); return r; };
12
+ const run = (st: string, id: string, text: string, stage = "plan", awaiting?: string) => { mkdirSync(join(st, "runs", id), { recursive: true }); writeFileSync(join(st, "runs", id, "00-request.md"), text); writeFileSync(join(st, "runs", id, "state.json"), JSON.stringify({ stage, awaiting })); };
13
+
14
+ test("G-01 cron parse and next run", () => {
15
+ expect(nextRun("*/15 * * * *", at(2026, 1, 5, 10, 1))).toBe(at(2026, 1, 5, 10, 15));
16
+ expect(nextRun("0 9 * * 1-5", at(2026, 1, 9, 10))).toBe(at(2026, 1, 12, 9)); // Fri -> Mon
17
+ expect(nextRun("0 9 * * 0", at(2026, 1, 5))).toBe(at(2026, 1, 11, 9));
18
+ expect(nextRun("0 9 * * 7", at(2026, 1, 5))).toBe(at(2026, 1, 11, 9));
19
+ expect(nextRun("0 9 1,15 * 1", at(2026, 1, 2))).toBe(at(2026, 1, 5, 9)); // dom or dow
20
+ expect(nextRun("0 9 1-3 * *", at(2026, 1, 4))).toBe(at(2026, 2, 1, 9));
21
+ for (const bad of ["@daily", "0 9 * * mon", "61 * * * *", "0 0 ? * *", "* * * *", "0 0 L * *", "*/0 * * * *"]) expect(typeof parseCron(bad)).toBe("string");
22
+ expect(nextRun("0 0 31 2 *", Date.now())).toBeNull();
23
+ expect(typeof addRule(proj(), { name: "x", text: "abc", kind: "cron", cron: "0 0 31 2 *" })).toBe("string");
24
+ expect(presetCron("weekdays", "09:30", "mon")).toBe("30 9 * * 1-5");
25
+ expect(presetCron("weekly", "09:30", "fri")).toBe("30 9 * * 5");
26
+ expect(presetCron("hourly", "09:05", "")).toBe("5 * * * *");
27
+ // the minute walk keeps a daily time across a DST change (whatever the machine's zone does)
28
+ const a = nextRun("0 9 * * *", at(2026, 3, 7, 12))!, b = nextRun("0 9 * * *", at(2026, 11, 1, 12))!;
29
+ expect([new Date(a).getHours(), new Date(b).getHours()]).toEqual([9, 9]);
30
+ });
31
+
32
+ test("G-02/G-03 one fire per due minute, even from two boards", async () => {
33
+ const st = proj(), r = mk(st), s = spy(), due = at(2026, 1, 5, 9, 5);
34
+ const out = await Promise.all([fire(st, r, "scheduled", due, { launch: s.launch }), fire(st, r, "scheduled", due, { launch: s.launch })]);
35
+ expect(out.filter(Boolean).length).toBe(1);
36
+ expect(s.calls.length).toBe(1);
37
+ expect(readHistory(st).length).toBe(1);
38
+ expect(await fire(st, r, "scheduled", due, { launch: s.launch })).toBeNull();
39
+ });
40
+
41
+ test("G-04 grace: a short outage fires once, a long one is skipped, a new rule never fires for the past", async () => {
42
+ const st = proj(), r = mk(st), s = spy();
43
+ const base = r.last_fired_for;
44
+ await tickAutomations([st], { launch: s.launch, now: () => base + 30_000 });
45
+ expect(s.calls.length).toBe(0);
46
+ const st2 = proj(); const r2 = mk(st2, { kind: "daily", time: "09:00" }); const s2 = spy();
47
+ patchRule(st2, r2.id, (x) => ({ ...x, last_fired_for: at(2026, 1, 1) }));
48
+ await tickAutomations([st2], { launch: s2.launch, now: () => at(2026, 1, 4, 9, 30) }); // three days: only the last slot, 30 min old
49
+ expect(s2.calls.length).toBe(1);
50
+ const st3 = proj(); const r3 = mk(st3, { kind: "daily", time: "09:00" }); const s3 = spy();
51
+ patchRule(st3, r3.id, (x) => ({ ...x, last_fired_for: at(2026, 1, 1) }));
52
+ await tickAutomations([st3], { launch: s3.launch, now: () => at(2026, 1, 4, 23, 0) }); // 14 h > 12 h grace
53
+ expect(s3.calls.length).toBe(0);
54
+ expect(readHistory(st3)[0]!.status).toBe("skipped_missed");
55
+ await tickAutomations([st3], { launch: s3.launch, now: () => at(2026, 1, 4, 23, 1) });
56
+ expect(readHistory(st3).length).toBe(1);
57
+ });
58
+
59
+ test("G-05 overlap until the previous run is done", async () => {
60
+ const st = proj(), r = mk(st), s = spy();
61
+ const h1 = (await fire(st, r, "manual", 0, { launch: s.launch, now: () => 1_000_000 }))!;
62
+ expect(h1.status).toBe("launched");
63
+ run(st, "r1", `Request: x [automation n fire ${h1.fire}]`, "plan", "approvals.plan");
64
+ expect((await fire(st, r, "manual", 0, { launch: s.launch, now: () => 1_000_001 }))!.status).toBe("skipped_overlap");
65
+ run(st, "r1", `Request: x [automation n fire ${h1.fire}]`, "done");
66
+ expect((await fire(st, r, "manual", 0, { launch: s.launch, now: () => 1_000_002 }))!.status).toBe("launched");
67
+ expect(s.calls.length).toBe(2);
68
+ });
69
+
70
+ test("G-06 precheck gates scheduled fires only, and a timeout kills the child", async () => {
71
+ const st = proj(), s = spy(), due = at(2026, 1, 5, 9, 5);
72
+ const ok = mk(st, { precheck: "exit 0" }), no = mk(st, { precheck: "echo nope; exit 1" }), slow = mk(st, { precheck: "sleep 30", precheck_timeout: 1 });
73
+ expect((await fire(st, ok, "scheduled", due, { launch: s.launch }))!.status).toBe("launched");
74
+ const h = (await fire(st, no, "scheduled", due, { launch: s.launch }))!;
75
+ expect([h.status, h.reason]).toEqual(["skipped_precheck", "exit 1: nope"]);
76
+ const t0 = Date.now();
77
+ const hs = (await fire(st, slow, "scheduled", due, { launch: s.launch }))!;
78
+ expect(hs.status).toBe("skipped_precheck");
79
+ expect(hs.reason).toContain("timed out");
80
+ expect(Date.now() - t0).toBeLessThan(10_000);
81
+ expect(s.calls.length).toBe(1);
82
+ expect((await fire(st, no, "manual", 0, { launch: s.launch }))!.status).toBe("launched");
83
+ });
84
+
85
+ test("G-07/G-08 auto mode, no yolo, guarded text and the marker", async () => {
86
+ const st = proj(), s = spy();
87
+ for (const t of ["auto x", "plan y", "approve everything"]) {
88
+ const r = mk(st, { text: t });
89
+ const p = promptOf(r, "f1");
90
+ expect(p.text.startsWith("auto Request: ")).toBe(true);
91
+ }
92
+ const r = mk(st, { text: "tidy the\nbacklog" });
93
+ await fire(st, r, "manual", 0, { launch: s.launch });
94
+ const it = s.calls[0]!.it;
95
+ expect(it.text).toMatch(/^auto tidy the backlog \[automation n fire [\w.]+\]$/);
96
+ expect(JSON.stringify(s.calls[0]!.pick ?? {})).not.toContain("yolo");
97
+ expect(s.calls[0]!.from).toBe(st);
98
+ });
99
+
100
+ test("G-09 failures: launch error does not retry, daily cap stops launches", async () => {
101
+ const st = proj(), r = mk(st), bad = spy(false);
102
+ const h = (await fire(st, r, "manual", 0, { launch: bad.launch }))!;
103
+ expect([h.status, h.reason]).toEqual(["launch_failed", "no terminal"]);
104
+ const st2 = proj(), r2 = mk(st2), s = spy();
105
+ let n = 0;
106
+ for (let i = 0; i < DAILY_CAP; i++) { const x = (await fire(st2, r2, "manual", 0, { launch: s.launch, now: () => 5_000_000 + i }))!; if (x.status === "skipped_overlap") continue; n++; }
107
+ expect(s.calls.length).toBe(1);
108
+ // fill history directly to the cap, then one more
109
+ const hist = Array.from({ length: DAILY_CAP }, (_, i) => ({ rule: r2.id, fire: `x${i}`, due: 0, at: 9_000_000 + i, kind: "manual", status: "launch_failed" }));
110
+ writeFileSync(join(st2, "automation-runs.json"), JSON.stringify(hist));
111
+ expect((await fire(st2, r2, "manual", 0, { launch: s.launch, now: () => 9_100_000 }))!.status).toBe("skipped_cap");
112
+ expect(n).toBeGreaterThan(0);
113
+ });
114
+
115
+ test("G-10 files: a corrupt rules file is not overwritten; history keeps 100", async () => {
116
+ const st = proj();
117
+ writeFileSync(join(st, "automations.json"), "{nope");
118
+ expect(await tickAutomations([st], { launch: spy().launch })).toBe(false);
119
+ expect(readFileSync(join(st, "automations.json"), "utf8")).toBe("{nope");
120
+ expect(typeof addRule(st, { name: "x", text: "abc", kind: "hourly" })).toBe("string");
121
+ expect(() => readRules(st)).toThrow();
122
+ const st2 = proj(), r = mk(st2), s = spy();
123
+ for (let i = 0; i < 105; i++) await fire(st2, r, "manual", 0, { launch: s.launch, now: () => 1_000 + i * 2 * 86_400_000 }).catch(() => 0);
124
+ expect(readHistory(st2).length).toBeLessThanOrEqual(100);
125
+ });
126
+
127
+ test("G-11 a rule launches in its own project only", async () => {
128
+ const a = proj(), b = proj(), s = spy();
129
+ const r = mk(a);
130
+ await fire(a, r, "manual", 0, { launch: s.launch });
131
+ expect(s.calls[0]!.from).toBe(a);
132
+ expect(readHistory(b).length).toBe(0);
133
+ });
134
+
135
+ test("G-12 a history line follows its run", async () => {
136
+ const st = proj(), r = mk(st), s = spy();
137
+ const h = (await fire(st, r, "manual", 0, { launch: s.launch }))!;
138
+ expect(runOf(st, h.fire)).toBeNull();
139
+ expect(shown(st, h, h.at + 60_000).status).toBe("launched");
140
+ expect(shown(st, h, h.at + 16 * 60_000).status).toBe("launch_failed");
141
+ run(st, "r9", `auto Request: x [automation n fire ${h.fire}]`, "build");
142
+ expect(shown(st, h)).toEqual({ status: "running", run: "r9" });
143
+ expect(runOf(st, h.fire.slice(0, -1))).toBeNull(); // a longer id is not a prefix match
144
+ });
145
+
146
+ test("G-13 the module never approves, passes yolo or runs kaizen approve", () => {
147
+ const src = readFileSync(join(import.meta.dir, "automations.ts"), "utf8").split("\n").filter((l) => !l.trim().startsWith("//")).join("\n");
148
+ expect(src).not.toMatch(/yolo:|\bapprove\w*\(|kaizen approve|"\/approve/i);
149
+ expect(dueSince("* * * * *", 0, 0)).toBeNull();
150
+ });
151
+
152
+ test("fix: a launch that lost its marker still blocks for a day; a live terminal blocks a done run", async () => {
153
+ const st = proj(), r = mk(st), s = spy();
154
+ const h1 = (await fire(st, r, "manual", 0, { launch: s.launch, now: () => 1_000_000 }))!;
155
+ const t = h1.at + 2 * 3_600_000; // marker never reached 00-request.md, past the 15 minute mark
156
+ expect((await fire(st, r, "manual", 0, { launch: s.launch, now: () => t }))!.status).toBe("skipped_overlap");
157
+ const h = h1.at + 25 * 3_600_000;
158
+ expect((await fire(st, r, "manual", 0, { launch: s.launch, now: () => h }))!.status).toBe("launched");
159
+ const st2 = proj(), r2 = mk(st2), h2 = (await fire(st2, r2, "manual", 0, { launch: s.launch, now: () => 1_000_000 }))!;
160
+ run(st2, "r1", `Request: x [automation n fire ${h2.fire}]`, "done");
161
+ expect((await fire(st2, r2, "manual", 0, { launch: s.launch, now: () => 1_000_001, live: (_s, id) => id === "r1" }))!.status).toBe("skipped_overlap");
162
+ });
163
+
164
+ test("fix: the precheck shell per platform", () => {
165
+ expect(shellArgv("echo hi", true)).toEqual(["cmd", "/c", "echo hi"]);
166
+ expect(shellArgv("echo hi", false)).toEqual(["sh", "-c", "echo hi"]);
167
+ });
@@ -0,0 +1,298 @@
1
+ // Automations: a schedule that starts a kaizen run in one project. A fire goes through the
2
+ // same launchRun the board's Run button uses, in auto mode, so it runs every stage unattended
3
+ // (plan, build, review; approvals.review still holds unless auto_accept is on). Rules live in
4
+ // <state>/automations.json, history in <state>/automation-runs.json. Fires happen only while
5
+ // a board runs: its minute tick calls tickAutomations.
6
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
7
+ import { dirname, join } from "node:path";
8
+ import { agentEnabled } from "./agent-prefs.ts";
9
+ import { obeyed } from "./sources.ts";
10
+ import { CHILD_ENV, home, KNOWN_AGENTS, launchRun, type Item } from "./state.ts";
11
+
12
+ export const KINDS = ["hourly", "daily", "weekdays", "weekly", "cron"] as const;
13
+ export type Kind = (typeof KINDS)[number];
14
+ export type Rule = {
15
+ id: string; name: string; text: string; cron: string; kind: Kind; enabled: boolean;
16
+ agent?: string; precheck?: string; precheck_timeout: number; grace_minutes: number;
17
+ last_fired_for: number; created: number;
18
+ };
19
+ export type Status = "pending" | "launched" | "launch_failed" | "skipped_precheck" | "skipped_missed" | "skipped_overlap" | "skipped_cap" | "skipped_unavailable";
20
+ export type Hist = { rule: string; fire: string; due: number; at: number; kind: "scheduled" | "manual"; status: Status; reason?: string };
21
+
22
+ export const DAILY_CAP = 24;
23
+ const KEEP = 100, MIN = 60_000, STUCK = 15 * MIN;
24
+
25
+ // ---- cron: five fields, no names, no extensions
26
+ const LIMITS: [number, number][] = [[0, 59], [0, 23], [1, 31], [1, 12], [0, 7]];
27
+ type Cron = { sets: Set<number>[]; domStar: boolean; dowStar: boolean };
28
+
29
+ export function parseCron(text: string): Cron | string {
30
+ const f = text.trim().split(/\s+/);
31
+ if (f.length !== 5) return "A cron has five fields: minute hour day-of-month month day-of-week.";
32
+ const sets: Set<number>[] = [];
33
+ for (let i = 0; i < 5; i++) {
34
+ const [lo, hi] = LIMITS[i]!, set = new Set<number>();
35
+ for (const part of f[i]!.split(",")) {
36
+ const m = /^(?:(\*)|(\d+)(?:-(\d+))?)(?:\/(\d+))?$/.exec(part);
37
+ if (!m || (m[4] !== undefined && !+m[4]) || (m[1] === undefined && m[3] === undefined && m[4] !== undefined)) return `"${part}" is not allowed in field ${i + 1}: use *, numbers, lists, ranges and steps only.`;
38
+ const a = m[1] ? lo : +m[2]!, b = m[1] ? hi : m[3] !== undefined ? +m[3] : a;
39
+ if (a < lo || b > hi || a > b) return `"${part}" is out of range in field ${i + 1} (${lo}-${hi}).`;
40
+ for (let v = a; v <= b; v += m[4] ? +m[4] : 1) set.add(i === 4 && v === 7 ? 0 : v);
41
+ }
42
+ sets.push(set);
43
+ }
44
+ return { sets, domStar: f[2]!.startsWith("*"), dowStar: f[4]!.startsWith("*") };
45
+ }
46
+
47
+ const matches = (c: Cron, t: number) => {
48
+ const d = new Date(t), [mi, h, dom, mo, dow] = c.sets as [Set<number>, Set<number>, Set<number>, Set<number>, Set<number>];
49
+ if (!mi.has(d.getMinutes()) || !h.has(d.getHours()) || !mo.has(d.getMonth() + 1)) return false;
50
+ const a = dom.has(d.getDate()), b = dow.has(d.getDay());
51
+ // Standard cron: both day fields restricted means either one matching counts.
52
+ return c.domStar || c.dowStar ? a && b : a || b;
53
+ };
54
+ const floor = (t: number) => Math.floor(t / MIN) * MIN;
55
+ const YEAR = 366 * 1440;
56
+
57
+ // First matching minute after `after`, within a year; null when there is none.
58
+ // ponytail: walks minute by minute (simple and correct across DST); cheap enough for a save and a fire.
59
+ export function nextRun(cron: string, after: number): number | null {
60
+ const c = parseCron(cron);
61
+ if (typeof c === "string") return null;
62
+ for (let i = 1, t = floor(after); i <= YEAR; i++) if (matches(c, t + i * MIN)) return t + i * MIN;
63
+ return null;
64
+ }
65
+
66
+ // Latest matching minute in (after, now], looking back at most a year.
67
+ export function dueSince(cron: string, after: number, now: number): number | null {
68
+ const c = parseCron(cron);
69
+ if (typeof c === "string") return null;
70
+ let hit: number | null = null;
71
+ for (let t = Math.max(floor(after), floor(now) - YEAR * MIN) + MIN; t <= now; t += MIN) if (matches(c, t)) hit = t;
72
+ return hit;
73
+ }
74
+
75
+ const DAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
76
+ // A preset's cron from "HH:MM" (hourly uses the minute) and a weekday name or number.
77
+ export function presetCron(kind: Kind, time: string, day: string): string {
78
+ const m = /^(\d{1,2}):(\d{2})$/.exec(time.trim());
79
+ if (!m || +m[1]! > 23 || +m[2]! > 59) return "";
80
+ const d = DAYS.indexOf(day.slice(0, 3).toLowerCase());
81
+ const dow = d >= 0 ? d : /^[0-7]$/.test(day) ? day : "";
82
+ if (kind === "hourly") return `${+m[2]!} * * * *`;
83
+ if (kind === "daily") return `${+m[2]!} ${+m[1]!} * * *`;
84
+ if (kind === "weekdays") return `${+m[2]!} ${+m[1]!} * * 1-5`;
85
+ if (kind === "weekly") return dow === "" ? "" : `${+m[2]!} ${+m[1]!} * * ${dow}`;
86
+ return "";
87
+ }
88
+
89
+ // ---- files: temp then rename; a bad rules file stops writers instead of being replaced
90
+ const rulesFile = (st: string) => join(st, "automations.json");
91
+ const histFile = (st: string) => join(st, "automation-runs.json");
92
+ function save(file: string, data: unknown) {
93
+ mkdirSync(dirname(file), { recursive: true });
94
+ const tmp = `${file}.${process.pid}.tmp`;
95
+ writeFileSync(tmp, JSON.stringify(data, null, 2) + "\n");
96
+ renameSync(tmp, file);
97
+ }
98
+ function load<T>(file: string): T[] | null {
99
+ if (!existsSync(file)) return [];
100
+ try { const j = JSON.parse(readFileSync(file, "utf8")); return Array.isArray(j) ? j : null; } catch { return null; }
101
+ }
102
+ export function readRules(st: string): Rule[] {
103
+ const r = load<Rule>(rulesFile(st));
104
+ if (!r) throw new Error("automations.json is unreadable: fix or remove it.");
105
+ return r;
106
+ }
107
+ export const readHistory = (st: string): Hist[] => load<Hist>(histFile(st)) ?? [];
108
+ function writeHistory(st: string, h: Hist[]) {
109
+ // Keep the newest KEEP per rule.
110
+ const seen = new Map<string, number>(), out: Hist[] = [];
111
+ for (const x of [...h].sort((a, b) => b.at - a.at)) { const n = (seen.get(x.rule) ?? 0) + 1; seen.set(x.rule, n); if (n <= KEEP) out.push(x); }
112
+ if (load(histFile(st)) === null) renameSync(histFile(st), histFile(st) + ".bad");
113
+ save(histFile(st), out.reverse());
114
+ }
115
+ function note(st: string, x: Hist) {
116
+ const h = readHistory(st), i = h.findIndex((y) => y.fire === x.fire);
117
+ if (i >= 0) h[i] = x; else h.push(x);
118
+ writeHistory(st, h);
119
+ }
120
+
121
+ // ---- rules
122
+ const clip = (v: unknown, n: number) => String(v ?? "").trim().slice(0, n);
123
+ export type Input = { name?: unknown; text?: unknown; kind?: unknown; time?: unknown; day?: unknown; cron?: unknown; agent?: unknown; precheck?: unknown; precheck_timeout?: unknown; grace_minutes?: unknown };
124
+
125
+ // A rule's fields from what a person typed, or the reason it is refused.
126
+ function build(i: Input, base?: Rule): Omit<Rule, "id" | "enabled" | "last_fired_for" | "created"> | string {
127
+ const name = clip(i.name, 60).replace(/[\[\]\r\n]/g, " ").trim(), text = clip(i.text, 2000);
128
+ if (!name) return "Give the automation a name.";
129
+ if (text.length < 3) return "Write what the run should do.";
130
+ const kind = (i.kind ?? base?.kind) as Kind;
131
+ if (!KINDS.includes(kind)) return "Pick hourly, daily, weekdays, weekly or cron.";
132
+ const cron = kind === "cron" ? clip(i.cron, 100) : presetCron(kind, String(i.time ?? "09:00"), String(i.day ?? "mon"));
133
+ const c = parseCron(cron);
134
+ if (!cron || typeof c === "string") return typeof c === "string" ? c : "Pick a valid time (HH:MM) and day.";
135
+ if (nextRun(cron, Date.now()) === null) return "That schedule never runs.";
136
+ const agent = clip(i.agent, 40);
137
+ if (agent && !KNOWN_AGENTS.some((a) => a.cmd === agent)) return "Unknown agent.";
138
+ const grace = i.grace_minutes === undefined || i.grace_minutes === "" ? 720 : Number(i.grace_minutes);
139
+ if (!Number.isInteger(grace) || grace < 0 || grace > 10080) return "Grace is 0 to 10080 minutes.";
140
+ const to = i.precheck_timeout === undefined || i.precheck_timeout === "" ? 60 : Number(i.precheck_timeout);
141
+ if (!Number.isInteger(to) || to < 1 || to > 300) return "The check's time limit is 1 to 300 seconds.";
142
+ return { name, text, cron, kind, agent: agent || undefined, precheck: clip(i.precheck, 500) || undefined, precheck_timeout: to, grace_minutes: grace };
143
+ }
144
+
145
+ const guard = (st: string) => (st === join(home, ".kaizen") ? "Automations belong to one project: open a project first." : null);
146
+
147
+ export function addRule(st: string, i: Input): Rule | string {
148
+ const why = guard(st) ?? build(i);
149
+ if (typeof why === "string") return why;
150
+ let rules: Rule[];
151
+ try { rules = readRules(st); } catch (e: any) { return e.message; }
152
+ // A new automation never fires for the past.
153
+ const r: Rule = { ...why, id: Math.random().toString(36).slice(2, 8), enabled: true, last_fired_for: floor(Date.now()), created: Date.now() };
154
+ save(rulesFile(st), [...rules, r]);
155
+ return r;
156
+ }
157
+
158
+ export function patchRule(st: string, id: string, f: (r: Rule) => Rule | string): Rule | string {
159
+ const rules = readRules(st), i = rules.findIndex((r) => r.id === id);
160
+ if (i < 0) return "No such automation.";
161
+ const r = f(rules[i]!);
162
+ if (typeof r === "string") return r;
163
+ rules[i] = r;
164
+ save(rulesFile(st), rules);
165
+ return r;
166
+ }
167
+ export const updateRule = (st: string, id: string, i: Input) => patchRule(st, id, (r) => { const b = build(i, r); return typeof b === "string" ? b : { ...r, ...b, agent: b.agent, precheck: b.precheck, last_fired_for: floor(Date.now()) }; });
168
+ export const setEnabled = (st: string, id: string, on: boolean) => patchRule(st, id, (r) => ({ ...r, enabled: on, ...(on ? { last_fired_for: floor(Date.now()) } : {}) }));
169
+ export function removeRule(st: string, id: string) {
170
+ const rules = readRules(st);
171
+ if (!rules.some((r) => r.id === id)) return "No such automation.";
172
+ save(rulesFile(st), rules.filter((r) => r.id !== id));
173
+ writeHistory(st, readHistory(st).filter((h) => h.rule !== id));
174
+ return null;
175
+ }
176
+
177
+ // ---- run link: the run whose request holds the fire's marker
178
+ export type Live = { run: string; stage: string; awaiting?: string } | null;
179
+ export function runOf(st: string, fire: string): Live {
180
+ const re = new RegExp(`fire ${fire.replace(/[.]/g, "\\.")}(?![\\w.-])`);
181
+ try {
182
+ for (const run of readdirSync(join(st, "runs")).sort()) {
183
+ let hit = false;
184
+ try { hit = re.test(readFileSync(join(st, "runs", run, "00-request.md"), "utf8")); } catch { /* none yet */ }
185
+ if (!hit) continue;
186
+ let s: any = {};
187
+ try { s = JSON.parse(readFileSync(join(st, "runs", run, "state.json"), "utf8")); } catch { /* none yet */ }
188
+ return { run, stage: String(s.stage ?? "plan"), awaiting: s.awaiting ? String(s.awaiting) : undefined };
189
+ }
190
+ } catch { /* no runs */ }
191
+ return null;
192
+ }
193
+
194
+ // The status a history line shows: a launched fire reads from its run; one with no run after 15 minutes failed.
195
+ export function shown(st: string, h: Hist, now = Date.now()): { status: string; run?: string } {
196
+ if (h.status !== "launched" && h.status !== "pending") return { status: h.status };
197
+ const l = runOf(st, h.fire);
198
+ if (!l) return { status: now - h.at > STUCK ? "launch_failed" : h.status };
199
+ const s = l.stage === "done" || l.stage === "abandoned" ? l.stage : l.awaiting ? "awaiting_approval" : "running";
200
+ return { status: s, run: l.run };
201
+ }
202
+ // Open = still working. A launch whose run never shows the marker counts as open for a day (the agent may have dropped it), and a finished run whose terminal still lives is open too.
203
+ const open = (st: string, h: Hist, now: number, live?: Deps["live"]) => {
204
+ const v = shown(st, h, now);
205
+ if (v.run && live?.(st, v.run)) return true;
206
+ if (v.status === "launch_failed") return !runOf(st, h.fire) && now - h.at < 86_400_000 && (h.status === "launched" || h.status === "pending");
207
+ return v.status === "running" || v.status === "awaiting_approval" || v.status === "launched" || v.status === "pending";
208
+ };
209
+
210
+ // The command a precheck runs through: cmd on Windows, sh elsewhere.
211
+ export const shellArgv = (cmd: string, win = process.platform === "win32") => (win ? ["cmd", "/c", cmd] : ["sh", "-c", cmd]);
212
+
213
+ // ---- precheck
214
+ async function precheck(cmd: string, cwd: string, secs: number): Promise<string | null> {
215
+ const env = Object.fromEntries(Object.entries(process.env).filter(([k, v]) => v !== undefined && !CHILD_ENV.test(k))) as Record<string, string>;
216
+ const win = process.platform === "win32";
217
+ let p;
218
+ try { p = Bun.spawn(shellArgv(cmd, win), { cwd, env, stdin: "ignore", stdout: "pipe", stderr: "pipe", detached: !win }); }
219
+ catch (e: any) { return `could not start: ${e?.message ?? e}`; }
220
+ let late = false;
221
+ const timer = setTimeout(() => {
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 */ } }
224
+ }, secs * 1000);
225
+ const [out, err] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text()]);
226
+ const code = await p.exited;
227
+ clearTimeout(timer);
228
+ const tail = (out + err).trim().slice(-200);
229
+ if (late) return `timed out after ${secs}s${tail ? `: ${tail}` : ""}`;
230
+ return code === 0 ? null : `exit ${code}${tail ? `: ${tail}` : ""}`;
231
+ }
232
+
233
+ // ---- fire
234
+ export type Deps = { live?: (st: string, run: string) => boolean; launch?: typeof launchRun; now?: () => number; pick?: (st: string) => { card?: boolean; onChange?: () => void } };
235
+
236
+ // What the agent is started with: auto mode, the person's words behind the command-word guard, and the marker that ties the run to its history line.
237
+ export function promptOf(r: Rule, fire: string): Item {
238
+ const one = r.text.replace(/\s+/g, " ").trim();
239
+ const text = `auto ${obeyed(one) ? "Request: " : ""}${one} [automation ${r.name} fire ${fire}]`;
240
+ return { severity: null, where: null, text, raw: text };
241
+ }
242
+
243
+ // One fire of one rule. Scheduled fires are claimed by an atomic mkdir, so two boards on one machine start one run. Null when another board took it.
244
+ export async function fire(st: string, r: Rule, kind: "scheduled" | "manual", due: number, deps: Deps = {}): Promise<Hist | null> {
245
+ const now = deps.now ?? Date.now, t = now();
246
+ const id = kind === "scheduled" ? `${r.id}.${due / MIN}` : `${r.id}.m${t}`;
247
+ const base: Hist = { rule: r.id, fire: id, due, at: t, kind, status: "pending" };
248
+ const done = (status: Status, reason?: string) => { const h = { ...base, status, ...(reason ? { reason } : {}) }; note(st, h); return h; };
249
+ if (kind === "scheduled") {
250
+ if (!claimed(st, id)) return null;
251
+ }
252
+ if (r.agent && !agentEnabled(r.agent)) return done("skipped_unavailable", "That agent is turned off in Settings → Agents.");
253
+ const mine = readHistory(st).filter((h) => h.rule === r.id);
254
+ if (mine.filter((h) => ["pending", "launched", "launch_failed"].includes(h.status) && t - h.at < 86_400_000).length >= DAILY_CAP) return done("skipped_cap", `${DAILY_CAP} launches in the last day.`);
255
+ const last = mine.filter((h) => h.status === "launched" || h.status === "pending").sort((a, b) => b.at - a.at)[0];
256
+ if (last && open(st, last, t, deps.live)) return done("skipped_overlap", "The previous run of this automation is not finished.");
257
+ if (kind === "scheduled" && r.precheck) {
258
+ const why = await precheck(r.precheck, dirname(st), r.precheck_timeout);
259
+ if (why) return done("skipped_precheck", why);
260
+ }
261
+ note(st, base);
262
+ // Never yolo: Settings' bypass preference applies as for any launch.
263
+ const l = (deps.launch ?? launchRun)(promptOf(r, id), st, undefined, { agent: r.agent, ...deps.pick?.(st) });
264
+ return l.ok ? done("launched") : done("launch_failed", l.why);
265
+ }
266
+
267
+ // Every enabled rule of every state dir that is due now: one fire for the latest due minute, never one per missed slot.
268
+ export async function tickAutomations(states: string[], deps: Deps = {}) {
269
+ const now = (deps.now ?? Date.now)();
270
+ let changed = false;
271
+ for (const st of states) {
272
+ let rules: Rule[];
273
+ try { rules = readRules(st); } catch { continue; }
274
+ for (const r of rules) {
275
+ if (!r.enabled) continue;
276
+ const d = dueSince(r.cron, r.last_fired_for, now);
277
+ if (d === null) continue;
278
+ patchRule(st, r.id, (x) => (d > x.last_fired_for ? { ...x, last_fired_for: d } : x));
279
+ try {
280
+ if (now - d > r.grace_minutes * MIN) {
281
+ if (!claimed(st, `${r.id}.${d / MIN}`)) continue;
282
+ note(st, { rule: r.id, fire: `${r.id}.${d / MIN}`, due: d, at: now, kind: "scheduled", status: "skipped_missed", reason: "The board was not running within the grace time." });
283
+ changed = true;
284
+ } else if (await fire(st, r, "scheduled", d, deps)) changed = true;
285
+ } catch { /* the next due minute tries again */ }
286
+ }
287
+ try { prune(st, now); } catch { /* old claims stay */ }
288
+ }
289
+ return changed;
290
+ }
291
+ const claimed = (st: string, id: string) => {
292
+ try { mkdirSync(join(st, "automation-claims"), { recursive: true }); mkdirSync(join(st, "automation-claims", id)); return true; } catch { return false; }
293
+ };
294
+ // Claims older than 30 days go.
295
+ function prune(st: string, now: number) {
296
+ const dir = join(st, "automation-claims");
297
+ if (existsSync(dir)) for (const c of readdirSync(dir)) if (now - statSync(join(dir, c)).mtimeMs > 30 * 86_400_000) rmSync(join(dir, c), { recursive: true, force: true });
298
+ }
package/cli/dashboard.ts CHANGED
@@ -11,6 +11,7 @@ import {
11
11
  abandonRun, replaceIdea, boardCards, launchRun, appendNote, parseNotes,
12
12
  gateOf,
13
13
  } from "./state.ts";
14
+ import { WORDMARK } from "./look.ts";
14
15
  const rgb = (r: number, g: number, b: number, s: string) =>
15
16
  `\x1b[38;2;${r};${g};${b}m${s}\x1b[0m`;
16
17
 
@@ -39,13 +40,6 @@ const MARK = [
39
40
  "⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀",
40
41
  ];
41
42
 
42
- // Compact block wordmark (28 columns x 3 rows).
43
- const WORDMARK = [
44
- "█ █ ▄▀█ █ ▀▀█ █▀▀ █▄ █",
45
- "█▀▄ █▀█ █ ▄▀ ██▄ █ ▀█",
46
- "█ █ █ █ █ █▄▄ █▄▄ █ █",
47
- ];
48
-
49
43
  // ---------------------------------------------------------------- mouse
50
44
 
51
45
  // SGR reporting (1006), not X10: X10 encodes coordinates as single bytes and gives
@@ -0,0 +1,133 @@
1
+ import { test, expect, beforeEach } from "bun:test";
2
+ import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { move, awaitBoard, childDied, childQuiet, QUIET_MS, finish, markWoken, requestOpen, readHandoff, request, REQUEST_MS, started, wakeAction, wakeLine, type Handoff } from "./handoff.ts";
6
+ import { agentLine } from "./workers.ts";
7
+
8
+ const ID = "2026-11-01-x";
9
+ let state: string;
10
+ beforeEach(() => {
11
+ state = mkdtempSync(join(tmpdir(), "hand-"));
12
+ mkdirSync(join(state, "runs", ID), { recursive: true });
13
+ writeFileSync(join(state, "runs", ID, "state.json"), "{}");
14
+ });
15
+ const idle = { alive: true, busy: false, asking: false, typedAt: 0 };
16
+ const ended = (o: Partial<Handoff> = {}): Handoff => ({ status: "done", parent_terminal: "sh-1", at: 0, ...o });
17
+
18
+ test("G-04 outside a board terminal nothing is requested", () => {
19
+ expect(request(state, ID, undefined)).toBeNull();
20
+ expect(readHandoff(state, ID)).toBeNull();
21
+ });
22
+
23
+ test("G-04 no answer declines, so a late board opens nothing", async () => {
24
+ request(state, ID, "sh-1");
25
+ expect(await awaitBoard(state, ID, 30, 5)).toBe(false);
26
+ const h = readHandoff(state, ID)!;
27
+ expect(h.status).toBe("declined");
28
+ expect(requestOpen(h, h.at)).toBe(false);
29
+ });
30
+
31
+ test("G-04 an old request is not acted on", () => {
32
+ expect(requestOpen(ended({ status: "requested", at: 0 }), REQUEST_MS + 1)).toBe(false);
33
+ });
34
+
35
+ test("the board's answer ends the wait", async () => {
36
+ request(state, ID, "sh-1"); started(state, ID, "sh-2");
37
+ expect(await awaitBoard(state, ID, 30, 5)).toBe(true);
38
+ expect(readHandoff(state, ID)!.child_terminal).toBe("sh-2");
39
+ });
40
+
41
+ test("only a running handoff takes a result", () => {
42
+ expect(finish(state, ID, "done")).toContain("no handoff");
43
+ request(state, ID, "sh-1");
44
+ expect(finish(state, ID, "done")).toContain("requested");
45
+ started(state, ID, "sh-2");
46
+ expect(finish(state, ID, "blocked", "why")).toBeNull();
47
+ expect(finish(state, ID, "done")).not.toBeNull();
48
+ expect(readHandoff(state, ID)).toMatchObject({ status: "blocked", reason: "why" });
49
+ });
50
+
51
+ test("G-05 a wake is held while busy, asking or typing, then sent once", () => {
52
+ expect(wakeAction(ended(), { ...idle, busy: true }, 1e6)).toBe("wait");
53
+ expect(wakeAction(ended(), { ...idle, asking: true }, 1e6)).toBe("wait");
54
+ expect(wakeAction(ended(), { ...idle, typedAt: 1e6 - 1000 }, 1e6)).toBe("wait");
55
+ expect(wakeAction(ended(), idle, 1e6)).toBe("send");
56
+ expect(wakeAction(ended({ woken: true }), idle, 1e6)).toBe("none");
57
+ expect(wakeAction(ended({ status: "running" }), idle, 1e6)).toBe("none");
58
+ request(state, ID, "sh-1"); started(state, ID, "sh-2"); finish(state, ID, "done"); markWoken(state, ID);
59
+ expect(wakeAction(readHandoff(state, ID), idle, 1e6)).toBe("none");
60
+ });
61
+
62
+ test("G-06 a dead child fails, and a dead parent is reported, not typed at", () => {
63
+ expect(childDied(ended({ status: "running" }), false)).toBe(true);
64
+ expect(childDied(ended({ status: "running" }), true)).toBe(false);
65
+ expect(childDied(ended(), false)).toBe(false);
66
+ expect(wakeAction(ended({ status: "failed" }), idle, 1e6)).toBe("send");
67
+ expect(wakeAction(ended(), null, 1e6)).toBe("gone");
68
+ });
69
+
70
+ test("G-04 a second agent that already finished is not mistaken for no board", async () => {
71
+ request(state, ID, "sh-1"); started(state, ID, "sh-2"); finish(state, ID, "done");
72
+ expect(await awaitBoard(state, ID, 30, 5)).toBe(true);
73
+ });
74
+
75
+ test("G-05 the wake line reaches a real terminal, submitted", async () => {
76
+ const { startPty, submitPty, ptyTail } = await import("./pty.ts");
77
+ if (process.platform === "win32") return;
78
+ startPty("hand-wake", ["sh", "-c", "timeout 1 cat"], state);
79
+ submitPty("hand-wake", wakeLine(ID, ended()), 20);
80
+ await Bun.sleep(200);
81
+ expect(ptyTail("hand-wake")).toContain(`kaizen run ${ID}: the worktree agent ended (done)`);
82
+ });
83
+
84
+ test("G-07 the second agent never takes bypass", () => {
85
+ const project = join(state, "p");
86
+ mkdirSync(join(project, ".kaizen", "runs", ID), { recursive: true });
87
+ writeFileSync(join(project, ".kaizen", "runs", ID, "state.json"), JSON.stringify({ agent: "claude" }));
88
+ const l = agentLine(project, ID, "hi", "own");
89
+ if (typeof l !== "string") { expect(l.bypass).toBe(false); expect(l.argv.join(" ")).not.toContain("dangerously"); }
90
+ });
91
+
92
+ test("a silent child goes quiet, wakes the parent, and can still report", () => {
93
+ const pty = { alive: true, busy: false, asking: false, lastOut: 0 };
94
+ expect(childQuiet(ended({ status: "running" }), pty, QUIET_MS + 1)).toBe(true);
95
+ expect(childQuiet(ended({ status: "running" }), { ...pty, asking: true }, QUIET_MS + 1)).toBe(false);
96
+ expect(childQuiet(ended({ status: "running" }), pty, QUIET_MS - 1)).toBe(false);
97
+ expect(wakeAction(ended({ status: "quiet" }), idle, 1e6)).toBe("send");
98
+ request(state, ID, "sh-1"); started(state, ID, "sh-2");
99
+ move(state, ID, ["running"], { status: "quiet", woken: true });
100
+ expect(finish(state, ID, "done")).toBeNull();
101
+ expect(wakeAction(readHandoff(state, ID), idle, 1e6)).toBe("send");
102
+ });
103
+
104
+ test("cold 1: a second start never replaces a live agent", () => {
105
+ request(state, ID, "sh-1"); started(state, ID, "sh-2");
106
+ expect(request(state, ID, "sh-9")).toMatchObject({ status: "running", child_terminal: "sh-2" });
107
+ finish(state, ID, "blocked", "x");
108
+ expect(request(state, ID, "sh-9")).toMatchObject({ status: "requested", parent_terminal: "sh-9" });
109
+ });
110
+
111
+ test("cold 2: claim and decline cannot both win", async () => {
112
+ request(state, ID, "sh-1");
113
+ const claim = setTimeout(() => started(state, ID, "sh-2"), 5);
114
+ await Bun.sleep(10); clearTimeout(claim);
115
+ expect(await awaitBoard(state, ID, 0)).toBe(true);
116
+ writeFileSync(join(state, "runs", ID, "handoff.json"), JSON.stringify({ status: "declined", parent_terminal: "sh-1", at: 0 }));
117
+ expect(started(state, ID, "sh-3")).toBe(false);
118
+ });
119
+
120
+ test("cold 3: a stale board read cannot overwrite done", () => {
121
+ request(state, ID, "sh-1"); started(state, ID, "sh-2"); finish(state, ID, "done");
122
+ expect(move(state, ID, ["running", "quiet"], { status: "failed" })).toBe(false);
123
+ expect(readHandoff(state, ID)!.status).toBe("done");
124
+ });
125
+
126
+ test("cold 5: a quiet child that dies counts as dead", () => {
127
+ expect(childDied(ended({ status: "quiet" }), false)).toBe(true);
128
+ });
129
+
130
+ test("cold 7: a draft holds the wake", () => {
131
+ expect(wakeAction(ended(), { ...idle, draft: true, typedAt: 1e6 - 6000 }, 1e6)).toBe("held");
132
+ expect(wakeAction(ended(), { ...idle, draft: true, typedAt: 1e9 - 11 * 60_000 }, 1e9)).toBe("send");
133
+ });