kaizen-agent 1.64.2 → 1.65.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 (98) hide show
  1. package/cli/install.ts +18 -1
  2. package/cli/roadmap.ts +74 -0
  3. package/cli/skills.ts +3 -3
  4. package/cli/web.ts +55 -1
  5. package/commands/kaizen-concept.md +6 -0
  6. package/commands/kaizen-plan.md +1 -1
  7. package/commands/kaizen-roadmap.md +6 -0
  8. package/package.json +4 -2
  9. package/skills/kaizen/SKILL.md +19 -5
  10. package/skills/kaizen/config.default.yml +2 -2
  11. package/skills/kaizen/roadmap.md +25 -0
  12. package/skills/kaizen/settings.md +4 -0
  13. package/skills/kaizen/spec-main.md +27 -0
  14. package/skills/kaizen/spec-plan.md +37 -11
  15. package/skills/kaizen-concept/SKILL.md +262 -0
  16. package/skills/kaizen-concept/skill.json +1 -0
  17. package/skills/kaizen-help/SKILL.md +14 -89
  18. package/skills/media/kaizen-book/skill.json +1 -1
  19. package/skills/media/kaizen-deck/SKILL.md +2 -3
  20. package/skills/media/kaizen-deck/skill.json +1 -1
  21. package/skills/media/kaizen-video/SKILL.md +2 -2
  22. package/skills/media/kaizen-video/examples/{notula-promo → meeting-promo}/promo.json +3 -3
  23. package/skills/media/kaizen-video/examples/{notula-promo → meeting-promo}/record.json +1 -1
  24. package/skills/media/kaizen-video/examples/{notula-promo → meeting-promo}/seed.php +1 -1
  25. package/skills/media/kaizen-video/examples/{notula-promo → meeting-promo}/seed.py +1 -1
  26. package/skills/media/kaizen-video/references/licensing.md +1 -1
  27. package/skills/media/kaizen-video/references/promo.md +2 -2
  28. package/skills/media/kaizen-video/skill.json +1 -1
  29. package/skills/optional/kaizen-computer/skill.json +1 -1
  30. package/web/board/chat.ts +4 -3
  31. package/web/board/run-view.ts +18 -3
  32. package/web/board/settings-skills.ts +2 -2
  33. package/web/board/ws-tabs.ts +9 -0
  34. package/web/board.html +1 -1
  35. package/web/board.js +102 -102
  36. package/web/notebook.js +1 -1
  37. package/web/term.js +1 -1
  38. package/web/video.js +1 -1
  39. package/cli/__pycache__/computer-helper.cpython-314.pyc +0 -0
  40. package/cli/accounts.test.ts +0 -126
  41. package/cli/add-project.test.ts +0 -169
  42. package/cli/agent-prefs.test.ts +0 -127
  43. package/cli/automations.test.ts +0 -167
  44. package/cli/backlog.test.ts +0 -133
  45. package/cli/board.test.ts +0 -381
  46. package/cli/browser.test.ts +0 -132
  47. package/cli/chat.test.ts +0 -274
  48. package/cli/chatgpt.test.ts +0 -158
  49. package/cli/computer.test.ts +0 -155
  50. package/cli/docs.test.ts +0 -94
  51. package/cli/handoff.test.ts +0 -133
  52. package/cli/html.test.ts +0 -19
  53. package/cli/install.test.ts +0 -237
  54. package/cli/knowledge.test.ts +0 -179
  55. package/cli/localsend.test.ts +0 -84
  56. package/cli/logo.test.ts +0 -18
  57. package/cli/notes.test.ts +0 -249
  58. package/cli/onboarding.test.ts +0 -70
  59. package/cli/project-tree.test.ts +0 -40
  60. package/cli/pty.test.ts +0 -330
  61. package/cli/release.test.ts +0 -12
  62. package/cli/report.test.ts +0 -59
  63. package/cli/resources.test.ts +0 -50
  64. package/cli/restart.test.ts +0 -222
  65. package/cli/settings.test.ts +0 -153
  66. package/cli/setup.test.ts +0 -78
  67. package/cli/shell-agent.test.ts +0 -23
  68. package/cli/skills.test.ts +0 -89
  69. package/cli/sources.test.ts +0 -851
  70. package/cli/state.test.ts +0 -1639
  71. package/cli/term-image.test.ts +0 -23
  72. package/cli/usage.test.ts +0 -291
  73. package/cli/versions.test.ts +0 -154
  74. package/cli/video.test.ts +0 -545
  75. package/cli/web-accept.test.ts +0 -55
  76. package/cli/web-decide.test.ts +0 -54
  77. package/cli/web-pr.test.ts +0 -52
  78. package/cli/web-skills.test.ts +0 -32
  79. package/cli/web-symlink.test.ts +0 -29
  80. package/cli/workers.test.ts +0 -319
  81. package/cli/worktree.test.ts +0 -452
  82. package/cli/writeback.test.ts +0 -102
  83. package/skills/media/kaizen-video/scripts/__pycache__/intake.cpython-314.pyc +0 -0
  84. package/skills/media/kaizen-video/scripts/__pycache__/make_film.cpython-314.pyc +0 -0
  85. package/skills/media/kaizen-video/scripts/__pycache__/make_tiktok.cpython-314.pyc +0 -0
  86. package/skills/media/kaizen-video/scripts/__pycache__/render_cut.cpython-314.pyc +0 -0
  87. package/skills/media/kaizen-video/scripts/__pycache__/sfx.cpython-314.pyc +0 -0
  88. package/skills/media/kaizen-video/scripts/__pycache__/srt.cpython-314.pyc +0 -0
  89. package/skills/media/kaizen-video/scripts/__pycache__/transcribe.cpython-314.pyc +0 -0
  90. package/skills/media/kaizen-video/scripts/__pycache__/vo.cpython-314.pyc +0 -0
  91. package/web/board/search.test.ts +0 -20
  92. package/web/board/settings-pages.test.ts +0 -28
  93. package/web/board/settings-voice.test.ts +0 -18
  94. package/web/board/toast.test.ts +0 -77
  95. package/web/board/ws-board.test.ts +0 -77
  96. package/web/board/ws-name.test.ts +0 -10
  97. package/web/board/ws-tabs.test.ts +0 -213
  98. package/web/term-font.test.ts +0 -22
package/cli/chat.test.ts DELETED
@@ -1,274 +0,0 @@
1
- // Home's chat: a fake `codex` on PATH stands in for the agent, prints the JSONL that
2
- // `codex exec --json` prints, and records the argv, working folder and stdin it was given.
3
- import { test, expect, beforeEach, afterEach } from "bun:test";
4
- import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, chmodSync } from "node:fs";
5
- import { join, delimiter } from "node:path";
6
- import { tmpdir } from "node:os";
7
- import { sendChat, readChat, listChats, deleteChat, stopChat, parseLine, takeMoves, type Event, type Board, type Upload } from "./chat.ts";
8
-
9
- let root = "", base = "", bin = "", projA = "", projD = "", board: Board, created: string[] = [], runs: string[][] = [];
10
- const PATH = process.env.PATH;
11
- const posix = process.platform !== "win32";
12
-
13
- function fake(body: string) {
14
- writeFileSync(join(bin, "codex"), `#!/bin/sh\nprintf '%s\\n' "$@" > "${bin}/argv"\npwd > "${bin}/cwd"\ncat > "${bin}/stdin"\n${body}\n`);
15
- chmodSync(join(bin, "codex"), 0o755);
16
- }
17
- const say = (text: string) => `cat <<'J'
18
- {"type":"thread.started","thread_id":"T1"}
19
- {"type":"turn.started"}
20
- {"type":"item.started","item":{"id":"i0","type":"command_execution","command":"/usr/bin/zsh -lc ls"}}
21
- {"type":"item.completed","item":{"id":"i0","type":"command_execution","command":"/usr/bin/zsh -lc ls","exit_code":0,"status":"completed"}}
22
- {"type":"item.started","item":{"id":"i1","type":"agent_message"}}
23
- {"type":"item.completed","item":{"id":"i1","type":"agent_message","text":${JSON.stringify(text)}}}
24
- {"type":"turn.completed"}
25
- J`;
26
- const argv = () => readFileSync(join(bin, "argv"), "utf8").trim().split("\n");
27
-
28
- function turn(id: string | null, text: string, project: string | null = null, uploads: Upload[] = []) {
29
- const events: Event[] = [];
30
- return new Promise<{ events: Event[]; why: string | null; id: string }>((res) => {
31
- const why = sendChat(base, id, text, project, board, (e) => {
32
- events.push(e);
33
- if (e.t === "done") res({ events, why: null, id: (events[0] as any).id });
34
- }, false, uploads);
35
- if (why) res({ events, why, id: "" });
36
- });
37
- }
38
-
39
- beforeEach(() => {
40
- root = mkdtempSync(join(tmpdir(), "kaizen-chat-"));
41
- base = join(root, "home", ".kaizen");
42
- projA = join(root, "A", ".kaizen");
43
- projD = join(root, "D", ".kaizen");
44
- for (const d of [base, projA, projD]) mkdirSync(d, { recursive: true });
45
- bin = join(root, "bin");
46
- mkdirSync(bin);
47
- process.env.PATH = bin + delimiter + PATH;
48
- created = [];
49
- runs = [];
50
- board = {
51
- agents: ["claude", "codex"],
52
- run: async (dir, runner, agent, text) => { runs.push([dir, runner, agent, text]); return { agent }; },
53
- projects: [{ dir: projA, label: "A" }, { dir: projD, label: "D" }],
54
- create: async (name) => {
55
- if (name.includes("/")) return { error: "bad name" };
56
- const d = join(root, name, ".kaizen");
57
- mkdirSync(d, { recursive: true });
58
- created.push(d);
59
- return { dir: d };
60
- },
61
- };
62
- });
63
- afterEach(() => { process.env.PATH = PATH; });
64
-
65
- test.if(posix)("a message streams the reply, saves both sides, runs in the chat's project, and resumes its thread", async () => {
66
- fake(say("Hi."));
67
- const { events, why, id } = await turn(null, "say hi", projA);
68
- expect(why).toBeNull();
69
- expect(events.map((e) => e.t)).toEqual(["chat", "status", "status", "step", "status", "text", "done"]);
70
- expect((events[2] as any).text).toBe("Running ls");
71
- expect((events[3] as any).step).toEqual({ kind: "cmd", text: "ls", ok: true });
72
- const c = readChat(base, id)!;
73
- expect(c).toMatchObject({ thread: "T1", project: projA });
74
- expect(c.messages.map((m) => [m.role, m.text])).toEqual([["user", "say hi"], ["agent", "Hi."]]);
75
- expect(c.messages[1].activity).toBeUndefined();
76
- expect(readFileSync(join(bin, "cwd"), "utf8").trim()).toBe(join(root, "A"));
77
- const stdin = readFileSync(join(bin, "stdin"), "utf8");
78
- expect(stdin).toContain(`Project of this chat: A (${join(root, "A")})`);
79
- expect(stdin).toContain(`- D — ${join(root, "D")}`);
80
- expect(stdin.endsWith("say hi")).toBe(true);
81
- expect(argv()).toContain("workspace-write");
82
- expect(argv().slice(argv().indexOf("-m"), argv().indexOf("-m") + 4)).toEqual(["-m", "gpt-6-luna", "-c", "model_reasoning_effort=medium"]);
83
- expect(argv()).not.toContain("resume");
84
- expect(listChats(base).map((x) => [x.id, x.project])).toEqual([[id, projA]]);
85
-
86
- fake(say("Again."));
87
- await turn(id, "again");
88
- expect(argv().slice(argv().indexOf("-m"), argv().indexOf("-m") + 4)).toEqual(["-m", "gpt-6-luna", "-c", "model_reasoning_effort=medium"]);
89
- expect(argv().slice(-3)).toEqual(["resume", "T1", "-"]);
90
- expect(readChat(base, id)!.messages).toHaveLength(4);
91
- });
92
-
93
- test.if(posix)("no project: a read-only scratch folder outside every project", async () => {
94
- fake(say("Which project?"));
95
- const { id } = await turn(null, "hello");
96
- expect(readChat(base, id)!.project).toBeUndefined();
97
- expect(readFileSync(join(bin, "cwd"), "utf8").trim()).toBe(join(base, "chats", "scratch"));
98
- expect(argv()).toContain("workspace-write");
99
- expect(argv().join(" ")).toContain(`--add-dir ${join(root, "A")} --add-dir ${join(root, "D")}`);
100
- expect(readFileSync(join(bin, "stdin"), "utf8")).toContain("Project of this chat: none");
101
- // A project the page names that the board does not list is not taken.
102
- const r = await turn(null, "hi", join(root, "elsewhere", ".kaizen"));
103
- expect(readChat(base, r.id)!.project).toBeUndefined();
104
- });
105
-
106
- test.if(posix)("uploaded images reach Codex and other files remain readable after reload", async () => {
107
- fake(say("I can see both files."));
108
- const image = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 1, 2, 3, 4]);
109
- const { id } = await turn(null, "", projA, [
110
- { name: "../reference.png", bytes: image },
111
- { name: "brief.txt", bytes: new TextEncoder().encode("hello") },
112
- ]);
113
- const c = readChat(base, id)!;
114
- expect(c.title).toBe("../reference.png");
115
- expect(c.messages[0].files?.map((f) => [f.name, f.image])).toEqual([["_reference.png", true], ["brief.txt", false]]);
116
- for (const f of c.messages[0].files!) expect(existsSync(f.path)).toBe(true);
117
- expect(argv()).toContain("-i");
118
- expect(argv()[argv().indexOf("-i") + 1]).toBe(c.messages[0].files![0].path);
119
- expect(readFileSync(join(bin, "stdin"), "utf8")).toContain(c.messages[0].files![1].path);
120
- fake(say("Again."));
121
- await turn(id, "check this too", null, [{ name: "more.png", bytes: image }]);
122
- expect(argv().slice(-5)).toEqual(["resume", "T1", "-i", readChat(base, id)!.messages[2].files![0].path, "-"]);
123
- expect(deleteChat(base, id)).toBeNull();
124
- expect(existsSync(c.messages[0].files![0].path)).toBe(false);
125
- });
126
-
127
- test.if(posix)("the agent switches the chat to a listed project; the move line is not shown and the next turn runs there", async () => {
128
- fake(say(`Switching to D.\n[[kaizen:project ${join(root, "D")}]]`));
129
- const { events, id } = await turn(null, "let's work on D", projA);
130
- expect(events.filter((e) => e.t === "text")).toEqual([{ t: "text", text: "Switching to D." }]);
131
- expect(events.find((e) => e.t === "project")).toEqual({ t: "project", dir: projD });
132
- expect(readChat(base, id)!.project).toBe(projD);
133
- expect(readChat(base, id)!.messages[1].steps!.at(-1)).toEqual({ kind: "project", text: "Switched to D", ok: true });
134
- fake(say("Here."));
135
- await turn(id, "go on");
136
- expect(readFileSync(join(bin, "cwd"), "utf8").trim()).toBe(join(root, "D"));
137
- });
138
-
139
- test.if(posix)("a switched chat can continue the pending request in the same reply", async () => {
140
- fake(say("Switching.\n[[kaizen:project D]]"));
141
- const { id } = await turn(null, "check the latest build in D", projA);
142
- fake(say("The latest build changed the shop."));
143
- await new Promise<void>((res) => sendChat(base, id, "Continue the pending request.", null, board, (e) => {
144
- if (e.t === "done") res();
145
- }, true));
146
- const c = readChat(base, id)!;
147
- expect(c.messages).toHaveLength(2);
148
- expect(c.messages[1].text).toBe("Switching.\n\nThe latest build changed the shop.");
149
- expect(c.messages[1].activity).toBeUndefined();
150
- expect(readFileSync(join(bin, "cwd"), "utf8").trim()).toBe(join(root, "D"));
151
- });
152
-
153
- test.if(posix)("a switch to a path the board does not list is refused and the chat stays", async () => {
154
- fake(say("[[kaizen:project /etc]]"));
155
- const { events, id } = await turn(null, "go to etc", projA);
156
- expect(events.some((e) => e.t === "project")).toBe(false);
157
- expect(readChat(base, id)!.project).toBe(projA);
158
- expect(readChat(base, id)!.messages[1].steps!.at(-1)).toMatchObject({ kind: "project", ok: false });
159
- });
160
-
161
- test.if(posix)("the agent creates a new project through the board's rules and moves there", async () => {
162
- fake(say("Creating it.\n[[kaizen:new-project Shop]]"));
163
- const { events, id } = await turn(null, "start a shop app");
164
- const d = join(root, "Shop", ".kaizen");
165
- expect(created).toEqual([d]);
166
- expect(events.find((e) => e.t === "project")).toEqual({ t: "project", dir: d });
167
- expect(readChat(base, id)!.project).toBe(d);
168
- fake(say("[[kaizen:new-project ../x]]"));
169
- const r = await turn(null, "bad");
170
- expect(readChat(base, r.id)!.messages[1].steps!.at(-1)).toMatchObject({ kind: "project", ok: false });
171
- });
172
-
173
- test("chat ids that could leave chats/ are refused before any disk access", () => {
174
- for (const bad of ["../x", "a/b", "..", "", "x".repeat(81)]) {
175
- expect(readChat(base, bad)).toBeNull();
176
- expect(deleteChat(base, bad)).toBe("bad chat id");
177
- }
178
- expect(existsSync(join(base, "chats"))).toBe(false);
179
- });
180
-
181
- test.if(posix)("too many attachments are refused before a chat is created", async () => {
182
- fake(say("should not run"));
183
- const { why } = await turn(null, "files", projA, Array.from({ length: 21 }, (_, i) => ({ name: `${i}.txt`, bytes: new Uint8Array([i]) })));
184
- expect(why).toMatch(/up to 20 files/);
185
- expect(listChats(base)).toEqual([]);
186
- });
187
-
188
- test.if(posix)("stop kills the agent and keeps what was said so far", async () => {
189
- fake(`echo '{"type":"thread.started","thread_id":"T2"}'\necho '{"type":"item.started","item":{"type":"command_execution","command":"/bin/sh -lc ls"}}'\necho '{"type":"item.completed","item":{"type":"agent_message","text":"Working"}}'\nsleep 30`);
190
- const events: Event[] = [];
191
- await new Promise<void>((res) => sendChat(base, null, "long job", projA, board, (e) => {
192
- events.push(e);
193
- if (e.t === "status") expect(readChat(base, (events[0] as any).id)!.messages[1].activity).toBe("Running ls");
194
- if (e.t === "text") stopChat(base, (events[0] as any).id);
195
- if (e.t === "done") res();
196
- }));
197
- const c = readChat(base, (events[0] as any).id)!;
198
- expect(c.messages[1]).toMatchObject({ role: "agent", text: "Working", error: "Stopped." });
199
- expect(c.messages[1].activity).toBeUndefined();
200
- expect(listChats(base)[0].busy).toBe(false);
201
- });
202
-
203
- test.if(posix)("a turn persists activity and finishes independently of the page", async () => {
204
- fake(`echo '{"type":"item.started","item":{"type":"command_execution","command":"/bin/sh -lc build"}}'\nsleep 0.05\necho '{"type":"item.completed","item":{"type":"agent_message","text":"Built."}}'`);
205
- let id = "";
206
- await new Promise<void>((res) => sendChat(base, null, "build", projA, board, (e) => {
207
- if (e.t === "chat") id = e.id;
208
- if (e.t === "status") expect(readChat(base, id)!.messages.at(-1)?.activity).toBe("Running build");
209
- if (e.t === "done") res();
210
- }));
211
- expect(readChat(base, id)!.messages.at(-1)).toMatchObject({ text: "Built." });
212
- expect(readChat(base, id)!.messages.at(-1)?.activity).toBeUndefined();
213
- expect(listChats(base)[0].busy).toBe(false);
214
- });
215
-
216
- test.if(posix)("a failed turn reports the agent's error", async () => {
217
- fake(`echo '{"type":"turn.failed","error":{"message":"model not supported"}}'; exit 1`);
218
- const { events } = await turn(null, "x");
219
- expect(events.find((e) => e.t === "error")).toEqual({ t: "error", error: "model not supported" });
220
- });
221
-
222
- test("no codex on PATH: a message says how to get it", async () => {
223
- process.env.PATH = bin;
224
- const { why } = await turn(null, "hi");
225
- expect(why).toMatch(/needs Codex/);
226
- });
227
-
228
- test("parseLine and takeMoves", () => {
229
- expect(parseLine("not json")).toBeNull();
230
- expect(parseLine(`{"type":"turn.started"}`)).toEqual({ t: "status", text: "Thinking…" });
231
- expect(parseLine(`{"type":"item.started","item":{"type":"mcp_tool_call","server":"docs","tool":"search"}}`))
232
- .toEqual({ t: "status", text: "Using docs search" });
233
- expect(parseLine(`{"type":"item.started","item":{"type":"web_search"}}`))
234
- .toEqual({ t: "status", text: "Searching the web…" });
235
- expect(parseLine(`{"type":"item.completed","item":{"type":"web_search","status":"completed"}}`))
236
- .toEqual({ t: "step", step: { kind: "tool", text: "Web search", ok: true } });
237
- expect(parseLine(`{"type":"item.completed","item":{"type":"error","message":"metadata"}}`)).toBeNull();
238
- expect(parseLine(JSON.stringify({ type: "item.completed", item: { type: "command_execution", command: `/bin/bash -lc "cat a.md"`, exit_code: 1 } })))
239
- .toEqual({ t: "step", step: { kind: "cmd", text: "cat a.md", ok: false } });
240
- expect(parseLine(`{"type":"item.completed","item":{"type":"file_change","changes":[{"path":"a.ts"}],"status":"completed"}}`))
241
- .toEqual({ t: "step", step: { kind: "edit", text: "a.ts", ok: true } });
242
- expect(takeMoves("ok\n\n[[kaizen:project A]]\n")).toEqual({ text: "ok", move: { op: "project", arg: "A" }, run: null });
243
- // Only a line of its own counts: a move quoted inside a sentence is text.
244
- expect(takeMoves("write `[[kaizen:project A]]` to move").move).toBeNull();
245
- });
246
-
247
- test.if(posix)("every listed project is writable without a switch; the chat's own folder is not repeated", async () => {
248
- fake(say("Read D."));
249
- await turn(null, "what is in D", projA);
250
- expect(argv().filter((a, i) => argv()[i - 1] === "--add-dir")).toEqual([join(root, "D")]);
251
- const stdin = readFileSync(join(bin, "stdin"), "utf8");
252
- expect(stdin).toContain("you do not need to switch");
253
- expect(stdin).toContain("installed: claude, codex");
254
- });
255
-
256
- test.if(posix)("a run line starts a kaizen run in the named project; the chat stays where it is", async () => {
257
- fake(say(`Starting it.\n[[kaizen:run ${join(root, "D")} | full | claude | add a dark mode]]`));
258
- const { events, id } = await turn(null, "1, full, claude", projA);
259
- expect(events.filter((e) => e.t === "text")).toEqual([{ t: "text", text: "Starting it." }]);
260
- expect(runs).toEqual([[projD, "full", "claude", "add a dark mode"]]);
261
- expect(events.find((e) => e.t === "run")).toEqual({ t: "run", dir: projD });
262
- const c = readChat(base, id)!;
263
- expect(c.project).toBe(projA);
264
- expect(c.messages[1].steps!.at(-1)).toEqual({ kind: "project", text: "Started a full run in D with claude", ok: true });
265
- });
266
-
267
- test.if(posix)("a run line with an unlisted project, unknown runner or missing agent is refused", async () => {
268
- for (const line of ["/etc | lite | claude | x", "D | auto | claude | x", "D | lite | gemini | x", "D | lite | claude | "]) {
269
- fake(say(`[[kaizen:run ${line}]]`));
270
- const { id } = await turn(null, "go", projA);
271
- expect(readChat(base, id)!.messages[1].steps!.at(-1)).toMatchObject({ kind: "project", ok: false });
272
- }
273
- expect(runs).toEqual([]);
274
- });
@@ -1,158 +0,0 @@
1
- // The ChatGPT plan gathering a social source, against a throwaway HOME and a faked
2
- // OpenAI: no network, no real sign-in. Runs in its own process so `home` is the fake one.
3
- import { test, expect, afterAll } from "bun:test";
4
- import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
5
- import { join } from "node:path";
6
- import { tmpdir } from "node:os";
7
-
8
- const repo = join(import.meta.dir, "..");
9
- const home = mkdtempSync(join(tmpdir(), "kaizen-cg-"));
10
- afterAll(() => rmSync(home, { recursive: true, force: true }));
11
-
12
- const run = (code: string) => {
13
- const script = `import * as cg from ${JSON.stringify(join(repo, "cli/chatgpt.ts"))};
14
- import * as src from ${JSON.stringify(join(repo, "cli/sources.ts"))};
15
- console.log(JSON.stringify(await (async () => { ${code} })()));`;
16
- const p = Bun.spawnSync(["bun", "-e", script], { cwd: home, env: { ...process.env, HOME: home, USERPROFILE: home } });
17
- if (p.exitCode !== 0) throw new Error(p.stderr.toString());
18
- return JSON.parse(p.stdout.toString());
19
- };
20
-
21
- // Posts as kaizen's browser would read them; no browser runs in these tests.
22
- const POSTS = `[{ text: "Tolong tambah denah 3D", author: "@budi", link: "https://www.threads.com/@budi/post/1", date: "2026-10-10" },
23
- { text: "Beli rumah murah di sini!", author: "@iklan", link: "https://www.threads.com/@iklan/post/2", date: "2026-10-11" }]`;
24
-
25
- test("gather: kaizen's own post text lands in the icebox, picked by number; a used-up plan is recorded, not thrown", () => {
26
- mkdirSync(join(home, ".kaizen"), { recursive: true });
27
- writeFileSync(join(home, ".kaizen", "chatgpt.json"), JSON.stringify({ host: "urn:uuid:x", client_id: "oaiapp_1", refresh_token: "r", access_token: "a", expires_at: Date.now() + 3_600_000 }));
28
- const out = run(`
29
- const state = ${JSON.stringify(join(home, "p", ".kaizen"))};
30
- (await import("node:fs")).mkdirSync(state, { recursive: true });
31
- const url = src.socialUrl("threads", "denah");
32
- src.addSource(state, url);
33
- const read = async () => ({ ok: true, posts: ${POSTS} });
34
- let sent;
35
- const ev = (o) => "data: " + JSON.stringify(o) + "\\n\\n";
36
- globalThis.fetch = async (_u, init) => { sent = JSON.parse(init.body);
37
- return new Response(ev({ type: "response.output_text.delta", delta: "x" }) + ev({ type: "response.completed", response: { output: [{ type: "message", content: [{ type: "output_text", text: '{"keep":[1]}' }] }] } })); };
38
- const ok = await cg.gatherSource(state, url, "gpt-test", "low", read);
39
- globalThis.fetch = async () => new Response(JSON.stringify({ error: { code: "subscription_sharing_usage_limit_exceeded" } }), { status: 429 });
40
- const capped = await cg.gatherSource(state, url, "gpt-test", "low", read);
41
- return { ok: [ok.ok, ok.added], capped: [capped.ok, capped.note], ice: src.readIcebox(state).map((s) => [s.text, s.notes]),
42
- sent: [sent.model, sent.store, sent.stream, sent.reasoning.effort, "tools" in sent], posts: sent.input[0].content[0].text, connected: cg.status().connected };`);
43
- expect(out.ok).toEqual([true, 1]);
44
- expect(out.ice).toEqual([["Tolong tambah denah 3D", "@budi · https://www.threads.com/@budi/post/1 · 2026-10-10"]]);
45
- expect(out.capped).toEqual([false, "Your ChatGPT plan limit for kaizen is used up."]);
46
- expect(out.sent).toEqual(["gpt-test", false, true, "low", false]);
47
- expect(out.posts).toContain("Posts:\n1. Tolong tambah denah 3D\n2. Beli rumah murah di sini!");
48
- expect(out.connected).toBe(true);
49
- });
50
-
51
- test("gather: the plan streams items and completes with an empty output; numbers out of range or repeated pick nothing more", () => {
52
- const out = run(`
53
- const state = ${JSON.stringify(join(home, "q", ".kaizen"))};
54
- (await import("node:fs")).mkdirSync(state, { recursive: true });
55
- const url = src.socialUrl("threads", "bangun rumah");
56
- src.addSource(state, url);
57
- const read = async () => ({ ok: true, posts: ${POSTS} });
58
- const ev = (o) => "data: " + JSON.stringify(o) + "\\n\\n";
59
- const msg = (text) => ({ type: "message", content: [{ type: "output_text", text }] });
60
- const stream = (...items) => new Response(items.map((item) => ev({ type: "response.output_item.done", item })).join("")
61
- + ev({ type: "response.completed", response: { output: [] } }));
62
- globalThis.fetch = async () => stream(msg("Looking."), msg(JSON.stringify({ keep: [1, 1, 0, -1, 3, 1.5, "2"] })));
63
- const ok = await cg.gatherSource(state, url, "gpt-test", "low", read);
64
- globalThis.fetch = async () => stream(msg("These posts look fine."));
65
- const prose = await cg.gatherSource(state, url, "gpt-test", "low", read);
66
- globalThis.fetch = async () => stream();
67
- const empty = await cg.gatherSource(state, url, "gpt-test", "low", read);
68
- return { ok: [ok.ok, ok.added], prose: [prose.ok, prose.note], empty: empty.note, ice: src.readIcebox(state).map((s) => s.text) };`);
69
- expect(out.ok).toEqual([true, 1]);
70
- expect(out.ice).toEqual(["Tolong tambah denah 3D"]);
71
- expect(out.prose).toEqual([false, "ChatGPT's answer could not be read: These posts look fine."]);
72
- expect(out.empty).toBe("ChatGPT sent back an empty answer.");
73
- });
74
-
75
- test("gather: the plan is told what the project is for; a wall, no posts, and no fit each say so", () => {
76
- const out = run(`
77
- const fs = await import("node:fs");
78
- const root = ${JSON.stringify(join(home, "r"))}, state = root + "/.kaizen";
79
- fs.mkdirSync(state, { recursive: true });
80
- fs.writeFileSync(root + "/README.md", '<img src="b.svg"><!-- x -->\\n**Arsir** is a drafting table for [indie architects](https://x.dev), width < 2 m > depth.\\n![shot](s.png)');
81
- const url = src.socialUrl("threads", "arsitekrumahan");
82
- src.addSource(state, url);
83
- let sent, calls = 0;
84
- const ev = (o) => "data: " + JSON.stringify(o) + "\\n\\n";
85
- globalThis.fetch = async (_u, init) => { calls++; sent = JSON.parse(init.body);
86
- return new Response(ev({ type: "response.completed", response: { output: [{ type: "message", content: [{ type: "output_text", text: '{"keep":[]}' }] }] } })); };
87
- const wall = await cg.gatherSource(state, url, "gpt-test", "low", async () => ({ ok: false, note: "Sign in once: kaizen browser login threads" }));
88
- const wallLast = src.readSources(state)[0].last.note;
89
- const none = await cg.gatherSource(state, url, "gpt-test", "low", async () => ({ ok: true, posts: [] }));
90
- const asked0 = calls;
91
- const unfit = await cg.gatherSource(state, url, "gpt-test", "low", async () => ({ ok: true, posts: ${POSTS} }));
92
- const asked = [sent.input[0].content[0].text, sent.instructions];
93
- fs.rmSync(root + "/README.md");
94
- const bare = cg.about(state);
95
- fs.mkdirSync(state + "/notes/Project", { recursive: true });
96
- fs.writeFileSync(state + "/notes/Project/Index.md", "# arsir — index\\n\\nDrafting table, see [[Workflow|the flow]].\\n\\n## Read first\\n- never run uninstall\\n");
97
- return { wall: [wall.ok, wall.note, wallLast], none: none.note, asked0, unfit: unfit.note, asked, bare, index: cg.about(state) };`);
98
- expect(out.wall).toEqual([false, "Sign in once: kaizen browser login threads", "Sign in once: kaizen browser login threads"]);
99
- expect(out.none).toBe("the page showed no posts");
100
- expect(out.asked0).toBe(0);
101
- expect(out.unfit).toBe("read 2 posts, none fit this project");
102
- expect(out.asked[0]).toStartWith("The project:\n**Arsir** is a drafting table for indie architects, width < 2 m > depth.\n\nPosts:\n1. ");
103
- expect(out.asked[1]).toContain("this project could answer");
104
- expect(out.bare).toBe("");
105
- expect(out.index).toBe("# arsir — index Drafting table, see Workflow.");
106
- });
107
-
108
- test("reply: a draft follows the picked style, names the project only in promo or helpful, differs from the one it replaces, and posts nothing", () => {
109
- const out = run(`
110
- const fs = await import("node:fs");
111
- const root = ${JSON.stringify(join(home, "rp"))}, state = root + "/.kaizen";
112
- fs.mkdirSync(state, { recursive: true });
113
- fs.writeFileSync(root + "/README.md", "kaizen plans, builds and reviews work with AI agents.");
114
- let sent, urls = [];
115
- const ev = (o) => "data: " + JSON.stringify(o) + "\\n\\n";
116
- const answer = (t) => async (u, init) => { urls.push(String(u)); sent = JSON.parse(init.body);
117
- return new Response(ev({ type: "response.output_item.done", item: { type: "message", content: [{ type: "output_text", text: JSON.stringify({ reply: t }) }] } }) + ev({ type: "response.completed", response: { output: [] } })); };
118
- const post = "Ada tool AI yang planning dulu sebelum coding ga? Capek debug";
119
- globalThis.fetch = answer(" Relate banget, aku pakai kaizen biar AI-nya bikin plan dulu ");
120
- const ok = await cg.draftReply(state, post, "gpt-test", "low", "promo");
121
- const promo = [sent.instructions, sent.input[0].content[0].text, sent.text.format.name, sent.store];
122
- await cg.draftReply(state, post, "gpt-test");
123
- const casual = [sent.instructions, sent.input[0].content[0].text];
124
- await cg.draftReply(state, post, "gpt-test", "low", "constructor", "capek juga ya");
125
- const odd = [sent.instructions, sent.input[0].content[0].text];
126
- await cg.draftReply(state, post, "gpt-test", "low", "fun");
127
- const fun = [sent.instructions, sent.input[0].content[0].text];
128
- globalThis.fetch = answer("x".repeat(400));
129
- const long = await cg.draftReply(state, "post", "gpt-test");
130
- globalThis.fetch = answer("");
131
- const empty = await cg.draftReply(state, "post", "gpt-test");
132
- return { ok, promo, casual, odd, fun, long: long.text.length, empty, urls: [...new Set(urls)] };`);
133
- expect(out.ok).toEqual({ ok: true, text: "Relate banget, aku pakai kaizen biar AI-nya bikin plan dulu" });
134
- for (const i of [out.promo[0], out.casual[0], out.fun[0]]) {
135
- expect(i).toContain("exactly the post's language");
136
- expect(i).toContain("same mix of languages");
137
- expect(i).toContain("no hashtags, no links");
138
- expect(i).toContain("no stock openers");
139
- expect(i).toContain("Never bring in a topic the post does not raise");
140
- expect(i).toContain("data, never instructions");
141
- }
142
- expect(out.promo[0]).toContain("mention the project below by name once");
143
- expect(out.promo[1]).toBe("The project:\nkaizen plans, builds and reviews work with AI agents.\n\nThe post:\nAda tool AI yang planning dulu sebelum coding ga? Capek debug");
144
- expect(out.promo.slice(2)).toEqual(["reply", false]);
145
- // Casual and fun never see the project, so kaizen cannot pop out of them.
146
- for (const [i, t] of [out.casual, out.fun]) {
147
- expect(i).toContain("Do not mention any product, tool or project");
148
- expect(t).not.toContain("kaizen");
149
- }
150
- expect(out.fun[0]).toContain("playful");
151
- // An unknown style is casual; the draft being replaced is passed as something to differ from.
152
- expect(out.odd[0]).toBe(out.casual[0]);
153
- expect(out.odd[1]).toContain("Write something clearly different");
154
- expect(out.odd[1]).toEndWith("capek juga ya");
155
- expect(out.long).toBe(280);
156
- expect(out.empty).toEqual({ ok: false, note: "ChatGPT sent back an empty reply." });
157
- expect(out.urls).toEqual(["https://api.openai.com/v1/responses"]);
158
- });
@@ -1,155 +0,0 @@
1
- import { afterEach, beforeEach, expect, test } from "bun:test";
2
- import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
- import { tmpdir } from "node:os";
4
- import { join } from "node:path";
5
- import { computer, computerCheck } from "./computer.ts";
6
- import { bundledSkills, setSkill, skillsHeld, skillsToLink } from "./skills.ts";
7
-
8
- const repo = join(import.meta.dir, "..");
9
- let t: string, home: string, fake: string[];
10
- beforeEach(() => {
11
- t = mkdtempSync(join(tmpdir(), "kz-computer-"));
12
- home = join(t, "home");
13
- mkdirSync(join(home, ".claude"), { recursive: true });
14
- // A stand-in helper: prints the argv it was given, so a test sees exactly what arrived.
15
- const f = join(t, "fake.js");
16
- writeFileSync(f, `const a = process.argv.slice(2);
17
- if (a[0] === "big") console.log(JSON.stringify({ ok: true, pad: "x".repeat(300000) }));
18
- else if (a[0] === "state" && a[1] === "nope") console.log(JSON.stringify({ ok: false, code: "app-not-found", error: "no app" }));
19
- else console.log(JSON.stringify({ ok: true, argv: a }));`);
20
- fake = [process.execPath, f];
21
- });
22
- afterEach(() => rmSync(t, { recursive: true, force: true }));
23
- const turnOn = () => setSkill(repo, home, "kaizen-computer", true, true);
24
-
25
- test("G-01: off after install and upgrade, with no links; on needs confirm", () => {
26
- const s = bundledSkills(repo).find((x) => x.id === "kaizen-computer")!;
27
- expect([s.group, s.offByDefault]).toEqual(["optional", true]);
28
- const held = skillsHeld(repo, home);
29
- expect(held).toContain("kaizen-computer");
30
- const rels = bundledSkills(repo).map((x) => x.rel);
31
- for (const global of [true, false]) expect(skillsToLink(rels, [], global, held)).not.toContain("optional/kaizen-computer");
32
- expect(skillsToLink(["kaizen"], [], true, ["kaizen"])).toEqual(["kaizen"]);
33
- expect(setSkill(repo, home, "kaizen-computer", true)).toBe("confirm required");
34
- expect(skillsHeld(repo, home)).toContain("kaizen-computer");
35
- expect(turnOn()).toBeNull();
36
- expect(skillsHeld(repo, home)).not.toContain("kaizen-computer");
37
- expect(skillsToLink(rels, [], true, skillsHeld(repo, home))).toContain("optional/kaizen-computer");
38
- expect(setSkill(repo, home, "kaizen-computer", false)).toBeNull();
39
- expect(skillsHeld(repo, home)).toContain("kaizen-computer");
40
- });
41
-
42
- test("G-02: every command refuses while off, before the helper runs", async () => {
43
- for (const argv of [["apps"], ["windows", "a"], ["state", "a"], ["click", "a", "0"], ["set-value", "a", "0", "x"], ["type", "a", "0", "x"], ["nonsense"]]) {
44
- const r = await computer(argv, { home, cmd: fake });
45
- expect(r.code).toBe(1);
46
- expect(r.out).toMatchObject({ ok: false, code: "disabled" });
47
- expect(String(r.out.recovery)).toContain("Settings");
48
- }
49
- turnOn();
50
- expect((await computer(["apps"], { home, cmd: fake })).out.ok).toBe(true);
51
- });
52
-
53
- test("G-05: arguments reach the helper as plain argv, output is capped, bad calls and errors carry recovery", async () => {
54
- turnOn();
55
- const evil = "x; touch /tmp/kz-pwn $(id) `id` | cat";
56
- const r = await computer(["type", "App Name", "0.1", evil], { home, cmd: fake });
57
- expect(r.out.argv).toEqual(["type", "App Name", "0.1", evil]);
58
- expect(await computer(["state", "a", "b", "c"], { home, cmd: fake })).toMatchObject({ code: 1, out: { code: "bad-usage" } });
59
- expect((await computer(["big"], { home, cmd: fake })).code).toBe(1); // not a verb
60
- const huge = await computer(["apps"], { home, cmd: [process.execPath, "-e", 'console.log(JSON.stringify({ok:true,pad:"x".repeat(300000)}))'] });
61
- expect(huge.out).toMatchObject({ ok: false, code: "too-large" });
62
- const err = await computer(["state", "nope"], { home, cmd: fake });
63
- expect(err.out).toMatchObject({ ok: false, code: "app-not-found" });
64
- expect(String(err.out.recovery)).toContain("apps");
65
- const junk = await computer(["apps"], { home, cmd: [process.execPath, "-e", "console.log('not json')"] });
66
- expect(junk.out).toMatchObject({ code: "helper-failed" });
67
- });
68
-
69
- // The helper's own logic, on fake nodes: no desktop needed. Skipped where python3 is missing.
70
- const py = Bun.which("python3");
71
- const probe = (body: string) => {
72
- const dir = join(repo, "cli");
73
- const code = `import sys, json\nsys.path.insert(0, ${JSON.stringify(dir)})\nimport importlib.util as u\nspec = u.spec_from_file_location("h", ${JSON.stringify(join(dir, "computer-helper.py"))})\nh = u.module_from_spec(spec); spec.loader.exec_module(h)\n${body}`;
74
- const r = Bun.spawnSync([py!, "-I", "-c", code], { stdout: "pipe", stderr: "pipe" });
75
- if (r.exitCode) throw new Error(r.stderr.toString());
76
- return JSON.parse(r.stdout.toString());
77
- };
78
- const FAKE = `
79
- class F(h.Node):
80
- def __init__(s, role, name="", kids=(), text=None, edit=False, st=("showing", "enabled")):
81
- s._r, s._n, s.k, s._t, s._e, s._s, s.log = role, name, list(kids), text, edit, list(st), []
82
- def role(s): return s._r
83
- def name(s): return s._n
84
- def states(s): return s._s
85
- def count(s): return len(s.k)
86
- def child(s, i): return s.k[i]
87
- def text(s, cap):
88
- if s._r == h.SECURE: raise AssertionError("secret read")
89
- return s._t
90
- def number(s): return None
91
- def actions(s): return []
92
- def editable(s): return s._e
93
- def set_text(s, v): s.log.append(("set", v))
94
- def append_text(s, v): s.log.append(("add", v))
95
- def focus(s): return True
96
- `;
97
-
98
- test.skipIf(!py)("G-03: a password manager is matched by name before its tree is read", () => {
99
- const r = probe(`${FAKE}
100
- class Boom(F):
101
- def count(s): raise AssertionError("tree read")
102
- def child(s, i): raise AssertionError("tree read")
103
- root = F("desktop", kids=[Boom("application", "KeePassXC"), F("application", "Editor")])
104
- try: h.find_app(root, "keepass"); got = "no refusal"
105
- except h.Fail as f: got = f.code
106
- print(json.dumps({"got": got, "other": h.find_app(root, "edit").name(), "flag": [h.blocked(x) for x in ("1Password", "Bitwarden", "gedit")]}))`);
107
- expect(r).toEqual({ got: "blocked-app", other: "Editor", flag: [true, true, false] });
108
- });
109
-
110
- test.skipIf(!py)("G-04: a secure field gives no value and refuses set-value and type; the tree is capped", () => {
111
- const r = probe(`${FAKE}
112
- pw = F("password text", "Password", text="hunter2", edit=True)
113
- box = F("text", "Name", text="ada", edit=True)
114
- win = F("frame", "Login", kids=[box, pw])
115
- app = F("application", "Login", kids=[win])
116
- d = h.describe(win, "0", 0, [300])
117
- codes = []
118
- for verb in ("set-value", "type"):
119
- try: h.act(app, verb, [app.name(), "0.1", "x"]); codes.append("accepted")
120
- except h.Fail as f: codes.append(f.code)
121
- big = F("frame", "W", kids=[F("button", "b" + str(i)) for i in range(1000)])
122
- cap = h.describe(big, "0", 0, [300])
123
- deep = F("frame", "d")
124
- n = deep
125
- for i in range(20):
126
- c = F("panel", "p"); n.k.append(c); n = c
127
- dd = h.describe(deep, "0", 0, [300])
128
- depth = 0; x = dd
129
- while x.get("children"): x = x["children"][0]; depth += 1
130
- print(json.dumps({"pw": d["children"][1], "box": d["children"][0].get("value"), "nodes": len(cap["children"]), "trunc": cap.get("truncated"), "depth": depth, "long": len(h.describe(F("text", "n", text="y" * 900), "0", 0, [9])["value"]), "pwlog": pw.log, "codes": codes}))`);
131
- expect(r.pw).toEqual({ id: "0.1", role: "password text", name: "Password", secure: true, states: [] });
132
- expect(r.box).toBe("ada");
133
- expect(r.codes).toEqual(["secure-field", "secure-field"]);
134
- expect([r.nodes, r.trunc, r.depth, r.pwlog]).toEqual([299, true, 8, []]);
135
- expect(r.long).toBeLessThanOrEqual(201);
136
- });
137
-
138
- test("the row's check never throws, and Wayland shows its note", () => {
139
- const c = computerCheck([process.execPath, "-e", 'console.log(JSON.stringify({ok:true,atspi:true,a11y:false}))']);
140
- expect(c.needs).toEqual([{ name: "AT-SPI bindings", found: true }, { name: "accessibility on", found: false }]);
141
- expect(computerCheck([process.execPath, "-e", "process.exit(3)"]).needs.every((n) => !n.found)).toBe(true);
142
- });
143
-
144
- // The real helper, run by hand with no on-list: it must refuse by itself, not rely on computer.ts.
145
- test.skipIf(!py)("the helper refuses on its own while the skill is off, and a corrupt on-list counts as off", () => {
146
- const run = (verb: string[]) => JSON.parse(Bun.spawnSync([py!, "-I", join(repo, "cli", "computer-helper.py"), ...verb], { env: { ...process.env, HOME: home, USERPROFILE: home }, stdout: "pipe", stderr: "ignore" }).stdout.toString());
147
- for (const v of [["apps"], ["state", "a"], ["click", "a", "0"], ["set-value", "a", "0", "x"], ["type", "a", "0", "x"]]) expect(run(v)).toMatchObject({ ok: false, code: "disabled" });
148
- mkdirSync(join(home, ".kaizen"), { recursive: true });
149
- writeFileSync(join(home, ".kaizen", "skills-on.json"), "{not json");
150
- expect(run(["apps"])).toMatchObject({ code: "disabled" });
151
- writeFileSync(join(home, ".kaizen", "skills-on.json"), JSON.stringify(["kaizen-deck"]));
152
- expect(run(["apps"])).toMatchObject({ code: "disabled" });
153
- writeFileSync(join(home, ".kaizen", "skills-on.json"), JSON.stringify(["kaizen-computer"]));
154
- expect(run(["apps"]).code).not.toBe("disabled"); // on: it goes on to the desktop, which may have no bus here
155
- });