kaizen-agent 1.53.1 → 1.54.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.
@@ -16,7 +16,10 @@ path this run will read or change, flat. The builder and the reviewer read that
16
16
  instead of searching the material a second and third time, so a path you leave out is
17
17
  work done twice. Read `00-request.md` from it, `notes.md`
18
18
  beside it if it exists (context the user attached from the board; treat it as part of
19
- the request), and `.kaizen/memory.md` if it exists, before touching the codebase.
19
+ the request), and `.kaizen/memory.md` if it exists, before touching the codebase. Then run
20
+ `kaizen recall --track <track> --tags <stack tags> --query "<words from the request>"`
21
+ for lessons learned in other projects, and end the Framing with `Recalled:` as
22
+ `spec-plan.md` says.
20
23
 
21
24
  **You do not write code.** No source edits, no installs, no migrations, no
22
25
  `git` state changes. The only file you write is `01-plan.md` in the run directory.
@@ -152,6 +152,11 @@ Every stage of every future run reads this file, so it is capped (default 100 li
152
152
  now wrong, already enforced by a test or lint rule, or restated by a newer line. A
153
153
  memory file that only grows stops being read.
154
154
 
155
+ Lessons that hold beyond this project go to global knowledge through `kaizen remember`, under
156
+ the rules in *Global knowledge* in `spec-review.md`: only past its four tests (reusable, high-signal,
157
+ evidenced, new — recall before saving), generalized, with `--applies` naming the evidence, never the
158
+ `preferences` track, every attempt listed in `04-review.md` `## Remembered`.
159
+
155
160
  ## Report back
156
161
 
157
162
  Return the verdict line, the critical and high findings, and every `CANNOT VERIFY`
package/cli/chat.test.ts CHANGED
@@ -180,8 +180,8 @@ test("chat ids that could leave chats/ are refused before any disk access", () =
180
180
 
181
181
  test.if(posix)("too many attachments are refused before a chat is created", async () => {
182
182
  fake(say("should not run"));
183
- const { why } = await turn(null, "files", projA, Array.from({ length: 6 }, (_, i) => ({ name: `${i}.txt`, bytes: new Uint8Array([i]) })));
184
- expect(why).toMatch(/up to 5 files/);
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
185
  expect(listChats(base)).toEqual([]);
186
186
  });
187
187
 
package/cli/chat.ts CHANGED
@@ -187,7 +187,7 @@ export function sendChat(base: string, id: string | null, text: string, project:
187
187
  if (live.has(key)) return "this chat is still working";
188
188
  const chat = c;
189
189
  if (reuseReply && chat.messages.at(-1)?.role !== "agent") return "no reply to continue";
190
- if (uploads.length > 5 || uploads.some((u) => !u.name || u.bytes.length > 10 * 1024 * 1024) || uploads.reduce((n, u) => n + u.bytes.length, 0) > 20 * 1024 * 1024) return "up to 5 files, 10 MB each and 20 MB total";
190
+ if (uploads.length > 20 || uploads.some((u) => !u.name || u.bytes.length > 100 * 1024 * 1024) || uploads.reduce((n, u) => n + u.bytes.length, 0) > 300 * 1024 * 1024) return "up to 20 files, 100 MB each and 300 MB total";
191
191
  // A project that left the board since: the chat goes on without one.
192
192
  if (chat.project && !board.projects.some((p) => p.dir === chat.project)) chat.project = undefined;
193
193
  let files: Attachment[] = [];
package/cli/install.ts CHANGED
@@ -116,6 +116,12 @@ if (Bun.argv[2] === "card") {
116
116
  process.exit(0);
117
117
  }
118
118
 
119
+ // `kaizen remember …` / `kaizen recall …`: global knowledge, see cli/knowledge.ts.
120
+ if (Bun.argv[2] === "remember" || Bun.argv[2] === "recall") {
121
+ const { cli } = await import("./knowledge.ts");
122
+ process.exit(cli(Bun.argv.slice(2)));
123
+ }
124
+
119
125
  if (Bun.argv[2] === "sources" || Bun.argv[2] === "gather" || Bun.argv[2] === "icebox") {
120
126
  const { locate, label } = await import("./state.ts");
121
127
  const src = await import("./sources.ts");
@@ -284,6 +290,10 @@ async function removeEverything() {
284
290
  else drop(install);
285
291
  drop(join(process.env.BUN_INSTALL ?? join(home, ".bun"), "bin", "kaizen.cmd"));
286
292
  drop(join(home, ".local", "bin", "kaizen"));
293
+ {
294
+ const { removeSessionHook } = await import("./knowledge.ts");
295
+ if (removeSessionHook(join(home, ".claude", "settings.json"))) gone.push("the kaizen recall hook in ~/.claude/settings.json");
296
+ }
287
297
  await clearBunxCache();
288
298
 
289
299
  if (purge) {
@@ -1011,6 +1021,15 @@ if (targets.length === 1) {
1011
1021
  console.log(` ${c.dim("if their directory exists when you install.")}`);
1012
1022
  }
1013
1023
 
1024
+ // Global knowledge reaches plain Claude Code sessions through a SessionStart hook
1025
+ // that prints only the lessons matching the project's stack (cli/knowledge.ts).
1026
+ if (!args.has("--project") && targets.some((a) => a.name === "Claude Code")) {
1027
+ const { addSessionHook } = await import("./knowledge.ts");
1028
+ const r = addSessionHook(join(home, ".claude", "settings.json"));
1029
+ if (r === "added") step(`added the kaizen recall session hook to ${tilde(join(home, ".claude", "settings.json"))}`);
1030
+ else if (r) step(c.dim(r));
1031
+ }
1032
+
1014
1033
  // ---------------------------------------------------------------- repo setup
1015
1034
 
1016
1035
  if (!args.has("--project")) installLauncher();
@@ -1140,7 +1159,7 @@ function initProject() {
1140
1159
  // ("add a discount cap") does not reach kaizen unless the project says it should.
1141
1160
  // One line in the agent instructions is what makes it the default here.
1142
1161
  function writePointer() {
1143
- 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\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`;
1162
+ 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`;
1144
1163
 
1145
1164
  for (const name of ["CLAUDE.md", "AGENTS.md"]) {
1146
1165
  const f = join(process.cwd(), name);
@@ -0,0 +1,179 @@
1
+ // Global knowledge, driven through the real CLI entry with a scratch HOME. Every
2
+ // spawn gets an env built from nothing but PATH, so no test can reach the real
3
+ // ~/.kaizen/knowledge or ~/.claude/settings.json.
4
+ import { test, expect, afterAll } from "bun:test";
5
+ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, statSync, rmSync } from "node:fs";
6
+ import { join, dirname } from "node:path";
7
+ import { tmpdir, homedir } from "node:os";
8
+ import { secretReason, addSessionHook, removeSessionHook, SESSION_HEADER } from "./knowledge.ts";
9
+
10
+ const script = join(dirname(import.meta.path), "install.ts");
11
+ const realKnowledge = join(homedir(), ".kaizen", "knowledge");
12
+ const realMtime = existsSync(realKnowledge) ? statSync(realKnowledge).mtimeMs : -1;
13
+ const roots: string[] = [];
14
+ afterAll(() => roots.forEach((r) => rmSync(r, { recursive: true, force: true })));
15
+
16
+ const scratch = () => {
17
+ const root = mkdtempSync(join(tmpdir(), "kz-knowledge-"));
18
+ roots.push(root);
19
+ const home = join(root, "home");
20
+ mkdirSync(home);
21
+ const project = (name: string, files: Record<string, string> = {}) => {
22
+ const d = join(root, name);
23
+ mkdirSync(join(d, ".kaizen"), { recursive: true });
24
+ for (const [f, t] of Object.entries(files)) { mkdirSync(dirname(join(d, f)), { recursive: true }); writeFileSync(join(d, f), t); }
25
+ return d;
26
+ };
27
+ const kz = (cwd: string, ...a: string[]) => {
28
+ const p = Bun.spawnSync([process.execPath, script, ...a], { cwd, env: { PATH: process.env.PATH ?? "", HOME: home, USERPROFILE: home, TMPDIR: root } });
29
+ return { code: p.exitCode, out: p.stdout.toString() + p.stderr.toString() };
30
+ };
31
+ const file = (track: string) => { try { return readFileSync(join(home, ".kaizen", "knowledge", `${track}.md`), "utf8"); } catch { return ""; } };
32
+ return { root, home, project, kz, file };
33
+ };
34
+ const lesson = (...extra: string[]) => ["remember", "--track", "code", "--tags", "bun,testing", "--applies", "bun>=1.1; not node", "--run", "r1", ...extra];
35
+
36
+ test("secret check rejects keys, credentials, emails, IPs and private hosts", () => {
37
+ for (const t of ["use sk-abcdefghijklmnop", "ghp_abcdefghijklmnopqrst", "-----BEGIN RSA PRIVATE KEY", "set password=hunter22", "mail ops@example.com",
38
+ "server at 10.1.2.3", "db.acme.internal is slow", "token: abcdefABCDEF0123456789abcdefABCDEF01"]) expect(secretReason(t)).not.toBe("");
39
+ for (const t of ["bun test --bail stops at the first failing file", "127.0.0.1 binds loopback only", "see https://bun.sh/docs/cli/test"]) expect(secretReason(t)).toBe("");
40
+ });
41
+
42
+ test("a rejected lesson leaves the file unchanged and says why", () => {
43
+ const s = scratch(), a = s.project("a");
44
+ const r = s.kz(a, ...lesson("connect to 192.168.1.20 first"));
45
+ expect(r.code).toBe(1);
46
+ expect(r.out).toContain("rejected (secret check)");
47
+ expect(s.file("code")).toBe("");
48
+ });
49
+
50
+ test("applies, tags, source and the track are required; preferences are not writable", () => {
51
+ const s = scratch(), a = s.project("a");
52
+ expect(s.kz(a, "remember", "--track", "code", "--tags", "bun", "--run", "r1", "x").out).toContain("--applies is required");
53
+ expect(s.kz(a, "remember", "--track", "code", "--applies", "y", "--run", "r1", "x").out).toContain("--tags is required");
54
+ expect(s.kz(a, "remember", "--track", "code", "--tags", "bun", "--applies", "y", "x").out).toContain("--source");
55
+ expect(s.kz(a, "remember", "--track", "preferences", "--tags", "tone", "--applies", "y", "--run", "r1", "x").out).toContain("written by hand");
56
+ expect(s.file("preferences")).toBe("");
57
+ });
58
+
59
+ test("appends a same-tag lesson instead of merging, and lists the existing one", () => {
60
+ const s = scratch(), a = s.project("a");
61
+ expect(s.kz(a, ...lesson("spawnSync throws when the binary is not on PATH")).code).toBe(0);
62
+ const r = s.kz(a, ...lesson("Bun.spawnSync raises if the executable is missing"));
63
+ expect(r.code).toBe(0);
64
+ expect(r.out).toContain("Same-tag lessons");
65
+ expect(r.out).toContain("spawnSync throws when the binary");
66
+ const body = s.file("code");
67
+ expect(body).toContain("spawnSync throws when the binary");
68
+ expect(body).toContain("Bun.spawnSync raises");
69
+ expect(body).toMatch(/\(applies: bun>=1\.1; not node\) — \d{4}-\d{2}-\d{2} · a\/r1/);
70
+ });
71
+
72
+ test("run from a subfolder, remember uses the project's opt-out and name", () => {
73
+ const s = scratch();
74
+ const off = s.project("client", { ".kaizen/config.yml": "knowledge:\n global: false\n" });
75
+ mkdirSync(join(off, ".kaizen", "runs", "r1"), { recursive: true });
76
+ expect(s.kz(join(off, ".kaizen", "runs", "r1"), ...lesson("from the run dir")).code).toBe(1);
77
+ expect(s.file("code")).toBe("");
78
+ const a = s.project("project-a");
79
+ mkdirSync(join(a, "src", "deep"), { recursive: true });
80
+ expect(s.kz(join(a, "src", "deep"), ...lesson("from a subfolder")).code).toBe(0);
81
+ expect(s.file("code")).toContain("· project-a/r1");
82
+ });
83
+
84
+ test("multi-line --applies stays one line, bad tags and limits are refused", () => {
85
+ const s = scratch(), a = s.project("a");
86
+ expect(s.kz(a, "remember", "--track", "code", "--tags", "bun", "--applies", "bun>=1.1\nlinux", "--run", "r1", "one line please").code).toBe(0);
87
+ expect(s.kz(a, "recall", "--tags", "bun").out).toContain("(applies: bun>=1.1 linux)");
88
+ expect(s.kz(a, "remember", "--track", "code", "--tags", "bun]x", "--applies", "y", "--run", "r1", "x").out).toContain('tag "bun]x"');
89
+ expect(s.kz(a, "recall", "--tags", "bun", "--limit", "abc").code).toBe(1);
90
+ const before = s.file("code");
91
+ expect(s.kz(a, "remember", "--track", "code", "--tags", "bun", "--applies", "y", "--source", "p/r1\nstray", "x").code).toBe(1);
92
+ expect(s.file("code")).toBe(before);
93
+ const spaced = s.project("my app");
94
+ expect(s.kz(spaced, "remember", "--track", "code", "--tags", "bun", "--applies", "y", "--run", "r1", "spaced folder").code).toBe(0);
95
+ expect(s.file("code")).toContain("· my-app/r1");
96
+ });
97
+
98
+ test("--replace rewrites only the named line", () => {
99
+ const s = scratch(), a = s.project("a");
100
+ s.kz(a, ...lesson("first lesson about bun tests"));
101
+ s.kz(a, "remember", "--track", "code", "--tags", "go", "--applies", "go>=1.21", "--run", "r1", "second lesson about go");
102
+ const n = s.file("code").split("\n").findIndex((l) => l.includes("first lesson")) + 1;
103
+ expect(s.kz(a, ...lesson("--replace", String(n), "rewritten bun lesson")).code).toBe(0);
104
+ const body = s.file("code");
105
+ expect(body).not.toContain("first lesson");
106
+ expect(body).toContain("rewritten bun lesson");
107
+ expect(body).toContain("second lesson about go");
108
+ expect(s.kz(a, ...lesson("--replace", "1", "x")).out).toContain("not a lesson");
109
+ });
110
+
111
+ test("versions in tags keep lessons apart, recall matches text words and honours the limit", () => {
112
+ const s = scratch(), a = s.project("a");
113
+ s.kz(a, "remember", "--track", "code", "--tags", "bun@1.1", "--applies", "bun 1.1 only", "--run", "r1", "lockfile is binary bun.lockb");
114
+ s.kz(a, "remember", "--track", "code", "--tags", "bun@1.2", "--applies", "bun>=1.2", "--run", "r1", "lockfile is text bun.lock");
115
+ const body = s.file("code");
116
+ expect(body).toContain("binary bun.lockb");
117
+ expect(body).toContain("text bun.lock");
118
+ expect(s.kz(a, "recall", "--tags", "bun@1.2").out.split("\n")[0]).toContain("bun@1.2");
119
+ s.kz(a, "remember", "--track", "code", "--tags", "ci", "--applies", "any runner", "--run", "r1", "flaky snapshot diffs come from locale-dependent dates");
120
+ expect(s.kz(a, "recall", "--query", "why are snapshot tests flaky").out).toContain("locale-dependent");
121
+ expect(s.kz(a, "recall", "--tags", "bun", "--limit", "1").out.trim().split("\n")).toHaveLength(1);
122
+ expect(s.kz(a, "recall", "--tags", "elixir").out.trim()).toBe("Recalled: none");
123
+ });
124
+
125
+ test("session hook merge keeps other hooks, is idempotent, leaves invalid JSON alone, removes only ours", () => {
126
+ const s = scratch(), f = join(s.home, ".claude", "settings.json");
127
+ mkdirSync(dirname(f), { recursive: true });
128
+ const theirs = { model: "x", hooks: { SessionStart: [{ hooks: [{ type: "command", command: "echo hi" }] }] } };
129
+ writeFileSync(f, JSON.stringify(theirs));
130
+ expect(addSessionHook(f)).toBe("added");
131
+ const once = readFileSync(f, "utf8");
132
+ expect(addSessionHook(f)).toBe("");
133
+ expect(readFileSync(f, "utf8")).toBe(once);
134
+ const j = JSON.parse(once);
135
+ expect(j.model).toBe("x");
136
+ expect(JSON.stringify(j)).toContain("echo hi");
137
+ expect(JSON.stringify(j)).toContain("recall --session");
138
+ expect(removeSessionHook(f)).toBe(true);
139
+ expect(JSON.parse(readFileSync(f, "utf8"))).toEqual(theirs);
140
+ writeFileSync(f, "{ not json");
141
+ expect(addSessionHook(f)).toContain("not valid JSON");
142
+ expect(readFileSync(f, "utf8")).toBe("{ not json");
143
+ });
144
+
145
+ test("acceptance: saved in A, recalled and injected in B, opt-out A' writes nothing", () => {
146
+ const s = scratch();
147
+ const a = s.project("project-a");
148
+ const saved = s.kz(a, "remember", "--track", "code", "--tags", "bun,testing", "--applies", "bun>=1.1", "--run", "2026-10-27-x",
149
+ "bun test --bail stops at the first failing file, not the first failing test");
150
+ expect(saved.code).toBe(0);
151
+ expect(saved.out).toContain("Remembered (global):");
152
+
153
+ const b = s.project("project-b", { "package.json": JSON.stringify({ devDependencies: { typescript: "5" } }), "bun.lock": "" });
154
+ const found = s.kz(b, "recall", "--track", "code", "--tags", "bun", "--query", "make tests stop early");
155
+ expect(found.out).toContain("--bail stops at the first failing file");
156
+ expect(found.out).toContain("project-a/2026-10-27-x");
157
+ const hook = s.kz(b, "recall", "--session");
158
+ expect(hook.out.startsWith(SESSION_HEADER)).toBe(true);
159
+ expect(hook.out).toContain("--bail");
160
+ // A project with no matching stack gets nothing injected, not a fallback.
161
+ const py = s.project("project-py", { "requirements.txt": "flask\n" });
162
+ expect(s.kz(py, "recall", "--session").out).toBe("");
163
+
164
+ const before = s.file("code");
165
+ const secret = s.project("project-a2", { ".kaizen/config.yml": "knowledge:\n # client work\n global: false\n" });
166
+ const refused = s.kz(secret, "remember", "--track", "code", "--tags", "bun", "--applies", "bun", "--run", "r9", "a lesson from client work");
167
+ expect(refused.code).toBe(1);
168
+ expect(refused.out).toContain("knowledge.global is false");
169
+ expect(s.file("code")).toBe(before);
170
+ expect(s.kz(secret, "recall", "--tags", "bun").out).toContain("--bail");
171
+
172
+ // The global switch turns it off everywhere; a project can switch it back on.
173
+ writeFileSync(join(s.home, ".kaizen", "config.yml"), "knowledge:\n global: false\n");
174
+ expect(s.kz(a, "remember", "--track", "code", "--tags", "bun", "--applies", "bun", "--run", "r2", "global off").code).toBe(1);
175
+ const on = s.project("project-on", { ".kaizen/config.yml": "knowledge:\n global: true\n" });
176
+ expect(s.kz(on, "remember", "--track", "code", "--tags", "bun", "--applies", "bun", "--run", "r3", "project overrides global").code).toBe(0);
177
+
178
+ expect(existsSync(realKnowledge) ? statSync(realKnowledge).mtimeMs : -1).toBe(realMtime);
179
+ });
@@ -0,0 +1,216 @@
1
+ // Global knowledge: engineering lessons that hold beyond the project they were
2
+ // learned in, one Markdown file per track under ~/.kaizen/knowledge/.
3
+ //
4
+ // `remember` and `recall` are the stable interface. Callers (the reviewer, the
5
+ // planner, the SessionStart hook, Codex) only rely on their flags and on the line
6
+ // format below; the ranking inside recall() can become FTS5 or hybrid retrieval
7
+ // later without any of them changing.
8
+ //
9
+ // Line format, one lesson per line:
10
+ // - [tag,tag@1.2] lesson text (applies: …) — YYYY-MM-DD · project/run-id
11
+ //
12
+ // No imports from state.ts: this module stays usable on its own (tests, bun -e).
13
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, appendFileSync } from "node:fs";
14
+ import { join, basename, dirname } from "node:path";
15
+ import { homedir } from "node:os";
16
+
17
+ export const TRACKS = ["code", "writing", "communication", "operations", "research", "preferences"];
18
+ // preferences.md is the user's to write by hand in v1: taste is never inferred from work.
19
+ const WRITABLE = TRACKS.filter((t) => t !== "preferences");
20
+ export const SESSION_HEADER = "Past experience from other projects (kaizen recall) — verify before applying, project rules win:";
21
+ // A session hook only injects lines that share at least one tool with the project.
22
+ const SESSION_MIN_SCORE = 2;
23
+
24
+ // Read at call time so a scratch HOME (tests) or KAIZEN_KNOWLEDGE_DIR applies.
25
+ export const knowledgeDir = () => process.env.KAIZEN_KNOWLEDGE_DIR || join(homedir(), ".kaizen", "knowledge");
26
+ const fileOf = (track: string) => join(knowledgeDir(), `${track}.md`);
27
+ const read = (f: string) => { try { return readFileSync(f, "utf8"); } catch { return ""; } };
28
+
29
+ // Rejects, never redacts: a lesson that needs editing is the reviewer's to reword.
30
+ export function secretReason(text: string): string {
31
+ const checks: [RegExp, string][] = [
32
+ [/\b(sk-[A-Za-z0-9_-]{8,}|ghp_[A-Za-z0-9]{8,}|github_pat_\w{8,}|AKIA[0-9A-Z]{12,}|xox[bp]-[\w-]{8,}|AIza[\w-]{20,})/, "looks like an API key"],
33
+ [/-----BEGIN [A-Z ]*PRIVATE KEY/, "contains a private key"],
34
+ [/\b(api[_-]?key|token|secret|password|passwd)\s*[:=]\s*\S{4,}/i, "assigns a credential"],
35
+ [/[A-Za-z0-9+/=_-]{32,}/, "contains a long key-like string"],
36
+ [/[\w.+-]+@[\w-]+(\.[\w-]+)*\.[A-Za-z]{2,}\b/, "contains an email address"],
37
+ [/\b(?!127\.0\.0\.1\b|0\.0\.0\.0\b)(\d{1,3}\.){3}\d{1,3}\b/, "contains an IP address"],
38
+ [/\b[\w-]+(\.[\w-]+)*\.(local|internal|lan|corp|home\.arpa)\b/i, "names a private host"],
39
+ ];
40
+ for (const [re, why] of checks) if (re.test(text)) return why;
41
+ return "";
42
+ }
43
+
44
+ // The opt-out, project config first, then global; the first file that sets it decides.
45
+ export function globalAllowed(projectDir: string): boolean {
46
+ for (const f of [join(projectDir, ".kaizen", "config.yml"), join(homedir(), ".kaizen", "config.yml")]) {
47
+ const t = read(f);
48
+ const m = /^knowledge:\n(?:[ \t]+.*\n|[ \t]*#.*\n)*?[ \t]+global:[ \t]*["']?(\w+)/m.exec(t) || /^knowledge\.global:[ \t]*["']?(\w+)/m.exec(t);
49
+ if (m) return m[1] !== "false";
50
+ }
51
+ return true;
52
+ }
53
+
54
+ type Line = { n: number; tags: string[]; text: string; date: string; raw: string };
55
+ const LINE = /^- \[([^\]]*)\] (.*) — (\d{4}-\d{2}-\d{2}) · (.+)$/;
56
+ function lines(track: string): Line[] {
57
+ return read(fileOf(track)).split("\n").flatMap((raw, i) => {
58
+ const m = LINE.exec(raw);
59
+ return m ? [{ n: i + 1, tags: m[1].split(",").map((t) => t.trim().toLowerCase()).filter(Boolean), text: m[2], date: m[3], raw }] : [];
60
+ });
61
+ }
62
+ const tagsOf = (s: string) => s.split(",").map((t) => t.trim().toLowerCase()).filter(Boolean);
63
+
64
+ // The project a command runs in: the nearest folder above cwd holding .kaizen/, so a
65
+ // reviewer calling from runs/<id>/ or src/ still gets its project's opt-out and name.
66
+ export function projectOf(cwd: string): string {
67
+ for (let d = cwd; ; d = dirname(d)) {
68
+ if (existsSync(join(d, ".kaizen"))) return d;
69
+ if (dirname(d) === d) return cwd;
70
+ }
71
+ }
72
+
73
+ export type Remembered = { ok: true; line: string; n: number; similar: string[] } | { ok: false; why: string };
74
+
75
+ // Appends by default; replaces a line only when told which one. It never judges two
76
+ // lessons the same itself: it hands back the same-tag lines for the caller to decide.
77
+ export function remember(o: { track: string; tags: string; text: string; applies: string; source: string; replace?: number; projectDir: string }): Remembered {
78
+ 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
+ if (!globalAllowed(o.projectDir)) return { ok: false, why: "knowledge.global is false for this project; nothing written" };
80
+ const tags = tagsOf(o.tags);
81
+ if (!tags.length) return { ok: false, why: "--tags is required" };
82
+ const bad = tags.find((t) => !/^[a-z0-9][a-z0-9._@+\/-]*$/.test(t));
83
+ if (bad) return { ok: false, why: `tag "${bad}" may only hold letters, digits and . _ @ + / -` };
84
+ const applies = o.applies.replace(/\s+/g, " ").trim();
85
+ if (!applies) return { ok: false, why: "--applies is required: say where the lesson holds (versions, platform, limits)" };
86
+ if (!/^[^\s\/]+\/[^\s]+$/.test(o.source.trim())) return { ok: false, why: "--source must be <project>/<run id>" };
87
+ const text = o.text.replace(/\s+/g, " ").trim();
88
+ if (!text) return { ok: false, why: "the lesson text is empty" };
89
+ const why = secretReason(`${o.tags} ${text} ${applies}`);
90
+ if (why) return { ok: false, why: `rejected (secret check): ${why}` };
91
+
92
+ const line = `- [${tags.join(",")}] ${text} (applies: ${applies}) — ${new Date().toISOString().slice(0, 10)} · ${o.source.trim()}`;
93
+ const before = lines(o.track);
94
+ const similar = before.filter((l) => l.tags.some((t) => tags.includes(t)) && l.n !== o.replace).map((l) => `${l.n}: ${l.raw}`);
95
+ const f = fileOf(o.track);
96
+ mkdirSync(knowledgeDir(), { recursive: true });
97
+ if (o.replace !== undefined) {
98
+ if (!before.some((l) => l.n === o.replace)) return { ok: false, why: `line ${o.replace} is not a lesson in ${o.track}.md` };
99
+ const all = read(f).split("\n");
100
+ all[o.replace - 1] = line;
101
+ writeFileSync(f, all.join("\n"));
102
+ return { ok: true, line, n: o.replace, similar };
103
+ }
104
+ const cur = read(f);
105
+ const head = cur ? (cur.endsWith("\n") ? "" : "\n") : `# Global knowledge — ${o.track}\n\n`;
106
+ appendFileSync(f, head + line + "\n");
107
+ return { ok: true, line, n: (cur + head).split("\n").length, similar };
108
+ }
109
+
110
+ // ponytail: keyword scoring (3 per shared tag, 2 for another version, 1 per query word in the text), linear
111
+ // scan; swap for FTS5 here when tag matching visibly misses lessons.
112
+ export function recall(o: { track?: string; tags?: string; query?: string; limit?: number; min?: number }): string[] {
113
+ const want = tagsOf(o.tags ?? "");
114
+ const words = (o.query ?? "").toLowerCase().split(/\W+/).filter((w) => w.length > 2);
115
+ const tracks = o.track ? [o.track] : TRACKS;
116
+ const scored = tracks.flatMap((t) => lines(t)).map((l) => {
117
+ const bare = l.tags.map((t) => t.split("@")[0]);
118
+ // An exact tag (bun@1.2) outranks the same tool at another version (bun@1.1).
119
+ const tagScore = want.reduce((n, w) => n + (l.tags.includes(w) ? 3 : bare.includes(w.split("@")[0]) ? 2 : 0), 0);
120
+ const text = l.text.toLowerCase();
121
+ return { l, score: tagScore + words.filter((w) => text.includes(w)).length };
122
+ });
123
+ return scored.filter((s) => s.score >= (o.min ?? 1))
124
+ .sort((a, b) => b.score - a.score || b.l.date.localeCompare(a.l.date))
125
+ .slice(0, o.limit ?? 20).map((s) => s.l.raw);
126
+ }
127
+
128
+ // What a project is made of, read from its manifests: the tags a session recalls by.
129
+ export function stackTags(dir: string): string[] {
130
+ const tags = new Set<string>();
131
+ const has = (f: string) => existsSync(join(dir, f));
132
+ if (has("package.json")) {
133
+ tags.add("node");
134
+ try {
135
+ const p = JSON.parse(read(join(dir, "package.json")));
136
+ for (const k of Object.keys({ ...p.dependencies, ...p.devDependencies })) tags.add(k.toLowerCase());
137
+ } catch { /* a broken package.json still says node */ }
138
+ }
139
+ if (has("bun.lock") || has("bun.lockb") || has("bunfig.toml")) tags.add("bun");
140
+ if (has("go.mod")) tags.add("go");
141
+ if (has("Cargo.toml")) tags.add("rust");
142
+ if (has("pyproject.toml") || has("requirements.txt")) tags.add("python");
143
+ if (has("Gemfile")) tags.add("ruby");
144
+ return [...tags];
145
+ }
146
+
147
+ // The SessionStart hook's output: matching lessons only, or nothing at all.
148
+ export function sessionText(dir: string): string {
149
+ const tags = stackTags(dir);
150
+ if (!tags.length) return "";
151
+ const hit = recall({ track: "code", tags: tags.join(","), limit: 20, min: SESSION_MIN_SCORE });
152
+ return hit.length ? `${SESSION_HEADER}\n${hit.join("\n")}\n` : "";
153
+ }
154
+
155
+ export const hookCommand = () => process.platform === "win32" ? "kaizen.cmd recall --session" : "kaizen recall --session";
156
+
157
+ // Merge into ~/.claude/settings.json without touching anything else. Invalid JSON is
158
+ // left byte-identical: the user's config is never rewritten from a guess.
159
+ export function addSessionHook(settings: string): string {
160
+ const cur = read(settings);
161
+ let s: any;
162
+ try { s = cur.trim() ? JSON.parse(cur) : {}; } catch { return `${settings} is not valid JSON; session hook not added`; }
163
+ const cmd = hookCommand();
164
+ s.hooks ??= {};
165
+ s.hooks.SessionStart ??= [];
166
+ if (JSON.stringify(s.hooks.SessionStart).includes(cmd)) return "";
167
+ s.hooks.SessionStart.push({ hooks: [{ type: "command", command: cmd }] });
168
+ mkdirSync(join(settings, ".."), { recursive: true });
169
+ writeFileSync(settings, JSON.stringify(s, null, 2) + "\n");
170
+ return "added";
171
+ }
172
+
173
+ export function removeSessionHook(settings: string): boolean {
174
+ const cur = read(settings);
175
+ let s: any;
176
+ try { s = JSON.parse(cur); } catch { return false; }
177
+ const list = s?.hooks?.SessionStart;
178
+ if (!Array.isArray(list)) return false;
179
+ const ours = (h: any) => typeof h?.command === "string" && h.command.endsWith("recall --session") && /^kaizen(\.cmd)? /.test(h.command);
180
+ const kept = list.map((m: any) => ({ ...m, hooks: (m.hooks ?? []).filter((h: any) => !ours(h)) })).filter((m: any) => m.hooks.length);
181
+ if (kept.length === list.length && JSON.stringify(kept) === JSON.stringify(list)) return false;
182
+ if (kept.length) s.hooks.SessionStart = kept; else delete s.hooks.SessionStart;
183
+ if (!Object.keys(s.hooks).length) delete s.hooks;
184
+ writeFileSync(settings, JSON.stringify(s, null, 2) + "\n");
185
+ return true;
186
+ }
187
+
188
+ // CLI: `kaizen remember …` / `kaizen recall …`. Returns the exit code.
189
+ export function cli(argv: string[], cwd = process.cwd()): number {
190
+ const [cmd, ...rest] = argv;
191
+ const flag = (name: string) => { const i = rest.indexOf(name); return i >= 0 ? rest.splice(i, 2)[1] : undefined; };
192
+ if (cmd === "recall") {
193
+ if (rest.includes("--session")) { process.stdout.write(sessionText(cwd)); return 0; }
194
+ const track = flag("--track"), tags = flag("--tags"), query = flag("--query"), limit = Number(flag("--limit") ?? 20);
195
+ 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; }
197
+ const out = recall({ track, tags, query: query ?? rest.join(" "), limit });
198
+ console.log(out.length ? out.join("\n") : "Recalled: none");
199
+ return 0;
200
+ }
201
+ if (cmd === "remember") {
202
+ const track = flag("--track") ?? "", tags = flag("--tags") ?? "", applies = flag("--applies") ?? "";
203
+ const project = projectOf(cwd);
204
+ const run = flag("--run"), source = flag("--source") ?? (run ? `${basename(project).replace(/\s+/g, "-")}/${run}` : "");
205
+ const rep = flag("--replace");
206
+ const r = remember({ track, tags, applies, source, text: rest.join(" "), replace: rep ? Number(rep) : undefined, projectDir: project });
207
+ if (!r.ok) { console.log(r.why); return 1; }
208
+ console.log(`Remembered (global): ${r.line}`);
209
+ if (r.similar.length) console.log(`Same-tag lessons already in ${track}.md (replace one with --replace <n> if this says the same thing):\n${r.similar.join("\n")}`);
210
+ return 0;
211
+ }
212
+ console.log(`kaizen remember --track <${WRITABLE.join("|")}> --tags a,b@1.2 --applies "<where it holds>" (--run <run id> | --source <project>/<run>) [--replace <n>] "<lesson>"
213
+ kaizen recall [--track <track>] [--tags a,b] [--query "<words>"] [--limit 20]
214
+ kaizen recall --session`);
215
+ return 1;
216
+ }
package/cli/video.test.ts CHANGED
@@ -171,7 +171,7 @@ test("a failed step stops the job and keeps the script's output; a cancel kills
171
171
 
172
172
  // The real server in a scratch home: the routes, the project check, and the
173
173
  // cross-origin refusal every write goes through.
174
- test("the board serves the Video page and its routes, and refuses writes from other sites", async () => {
174
+ test("the board serves sound assets and the Video page, and refuses unsafe paths and writes", async () => {
175
175
  const homeDir = mkdtempSync(join(tmpdir(), "kaizen-video-home-"));
176
176
  for (const d of [join(homeDir, ".kaizen"), join(homeDir, ".claude"), join(homeDir, "a", ".kaizen")]) mkdirSync(d, { recursive: true });
177
177
  writeFileSync(join(homeDir, ".kaizen", "projects"), join(homeDir, "a") + "\n");
@@ -187,6 +187,11 @@ test("the board serves the Video page and its routes, and refuses writes from ot
187
187
  for (let i = 0; ; i++) { try { await fetch(at + "/state"); break; } catch { if (i > 100) throw new Error("board did not start"); await Bun.sleep(50); } }
188
188
  expect((await fetch(at + "/video")).headers.get("content-type")).toContain("text/html");
189
189
  expect((await fetch(at + "/video.js")).status).toBe(200);
190
+ const sound = await fetch(at + "/sounds/Bellatrix.mp3");
191
+ expect(sound.headers.get("content-type")).toBe("audio/mpeg");
192
+ expect(new TextDecoder().decode((await sound.arrayBuffer()).slice(0, 3))).toBe("ID3");
193
+ expect((await fetch(at + "/sounds/Missing.mp3")).status).toBe(404);
194
+ expect((await fetch(at + "/sounds/%2e%2e%2fBellatrix.mp3")).status).toBe(404);
190
195
  const list = await (await fetch(at + "/video/list")).json() as any;
191
196
  expect(list.places.map((p: any) => p.label)).toEqual(["library"]);
192
197
  expect(list.videos.map((v: any) => [v.name, v.place, v.where]).sort()).toEqual([["demo", 0, "library"], ["talk", 0, "library"]]);
package/cli/web.ts CHANGED
@@ -25,6 +25,7 @@ import { listChats, readChat, sendChat, stopChat, deleteChat, okId as okChatId,
25
25
  const PAGE = join(dirname(import.meta.dir), "web", "board.html");
26
26
  // The board's script: web/board/*.ts, bundled into one file by `bun run build:web`.
27
27
  const BOARD_JS = join(dirname(import.meta.dir), "web", "board.js");
28
+ const SOUNDS_DIR = join(dirname(import.meta.dir), "web", "sounds");
28
29
  // The notebook: its page, and the CodeMirror bundle `bun run build:web` commits beside it.
29
30
  const NOTES_PAGE = join(dirname(import.meta.dir), "web", "notes.html");
30
31
  const ICO = join(dirname(import.meta.dir), "assets", "kaizen.ico");
@@ -399,6 +400,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
399
400
  function serve(port: number) { return Bun.serve({
400
401
  hostname: "127.0.0.1",
401
402
  port,
403
+ // Local only, so attachments may be large: Bun's 128 MB default would cut them.
404
+ maxRequestBodySize: 512 * 1024 * 1024,
402
405
  // Bun drops a request after 10s idle by default. A slow /state (git status in a
403
406
  // big repo, on Windows) then comes back as nothing, and the page shows an empty
404
407
  // board. Loopback only, so nothing waits on us but our own page.
@@ -443,6 +446,13 @@ export async function web(repoDir: string, opts: Opts = {}) {
443
446
  return new Response(body, { headers: { "content-type": "application/javascript; charset=utf-8", "cache-control": "no-store" } });
444
447
  }
445
448
 
449
+ if (req.method === "GET" && path.startsWith("/sounds/")) {
450
+ const name = /^\/sounds\/([A-Za-z]+)\.mp3$/.exec(path)?.[1];
451
+ const file = name && join(SOUNDS_DIR, `${name}.mp3`);
452
+ if (!file || !existsSync(file)) return new Response("not found", { status: 404 });
453
+ return new Response(Bun.file(file), { headers: { "content-type": "audio/mpeg", "cache-control": "public, max-age=86400" } });
454
+ }
455
+
446
456
  if (req.method === "GET" && (path === "/notebook" || path === "/notebook.js")) {
447
457
  const [f, type] = path === "/notebook" ? [NOTES_PAGE, "text/html; charset=utf-8"] : [NOTES_JS, "application/javascript; charset=utf-8"];
448
458
  const body = served(f);
@@ -921,11 +931,11 @@ export async function web(repoDir: string, opts: Opts = {}) {
921
931
  let body: any;
922
932
  let uploads: ChatUpload[] = [];
923
933
  if (path === "/chat" && req.headers.get("content-type")?.startsWith("multipart/form-data")) {
924
- if (Number(req.headers.get("content-length")) > 28 * 1024 * 1024) return bad("attachments too large", 413);
934
+ if (Number(req.headers.get("content-length")) > 320 * 1024 * 1024) return bad("attachments too large", 413);
925
935
  let form: FormData;
926
936
  try { form = await req.formData(); } catch { return bad("form data expected"); }
927
937
  const files = form.getAll("files");
928
- if (files.length > 5 || files.some((f) => !(f instanceof File) || f.size > 10 * 1024 * 1024) || files.reduce((n, f) => n + (f instanceof File ? f.size : 0), 0) > 20 * 1024 * 1024) return bad("up to 5 files, 10 MB each and 20 MB total", 413);
938
+ if (files.length > 20 || files.some((f) => !(f instanceof File) || f.size > 100 * 1024 * 1024) || files.reduce((n, f) => n + (f instanceof File ? f.size : 0), 0) > 300 * 1024 * 1024) return bad("up to 20 files, 100 MB each and 300 MB total", 413);
929
939
  body = { id: form.get("id"), text: form.get("text") ?? "", project: form.get("project") };
930
940
  uploads = await Promise.all(files.map(async (f) => ({ name: (f as File).name, bytes: new Uint8Array(await (f as File).arrayBuffer()) })));
931
941
  } else try { body = await req.json(); } catch { return bad("json body expected"); }
@@ -1213,7 +1223,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1213
1223
  // Files added with a hand-written icebox item: saved beside the state, linked in its notes.
1214
1224
  const iceFiles = (state: string, files: unknown) => {
1215
1225
  const fs: { name: string; data: string }[] = Array.isArray(files) ? files : [];
1216
- if (fs.reduce((t, f) => t + (f.data?.length ?? 0), 0) > 20_000_000) throw new Error("attachments over 15MB");
1226
+ if (fs.reduce((t, f) => t + (f.data?.length ?? 0), 0) > 400_000_000) throw new Error("attachments over 300MB");
1217
1227
  return fs.map((f) => {
1218
1228
  const rel = saveAttachment(state, null, String(f.name ?? "file"), Buffer.from(String(f.data).replace(/^data:[^,]*,/, ""), "base64"));
1219
1229
  return (/\.(png|jpe?g|gif|webp|svg)$/i.test(rel) ? "!" : "") + `[${String(f.name ?? "file")}](${rel})`;
@@ -1336,7 +1346,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1336
1346
  const files: { name: string; data: string }[] = Array.isArray(body.files) ? body.files : [];
1337
1347
  let total = 0;
1338
1348
  for (const f of files) total += (f.data?.length ?? 0);
1339
- if (total > 20_000_000) return bad("attachments over 15MB");
1349
+ if (total > 400_000_000) return bad("attachments over 300MB");
1340
1350
  const links = files.map((f) => {
1341
1351
  const bytes = Buffer.from(String(f.data).replace(/^data:[^,]*,/, ""), "base64");
1342
1352
  const rel = saveAttachment(dir, id, String(f.name ?? "file"), bytes).replace(/\\/g, "/");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kaizen-agent",
3
- "version": "1.53.1",
3
+ "version": "1.54.0",
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": {
@@ -32,6 +32,9 @@ continue from the stage it names. Never advance a run whose `awaiting` field is
32
32
  non-null without a recorded human decision in `02-approval.md` — another tool or
33
33
  session may be mid-run.
34
34
 
35
+ Before non-trivial work, run `kaizen recall --track <track> --query "<topic>"` and
36
+ treat what it returns as past experience from other projects to verify, not as rules.
37
+
35
38
  Codex has no separate subagents, so run the stages sequentially in one session,
36
39
  but keep them clean: start each stage by reading only that stage's declared inputs
37
40
  from its stage file, and write its artifact before moving on. When reviewing, judge the
@@ -73,6 +73,12 @@ review:
73
73
  # prunes stale or superseded lessons before appending rather than growing the file.
74
74
  memory_max_lines: 100
75
75
 
76
+ knowledge:
77
+ # Lessons that hold beyond one project go to ~/.kaizen/knowledge/<track>.md through
78
+ # `kaizen remember`; planners and Claude Code sessions read them with `kaizen recall`.
79
+ # false: this project never writes there (recall still reads). For confidential work.
80
+ global: true
81
+
76
82
  backlog:
77
83
  # Capture work explicitly deferred, unresolved findings after the bounded fix loop,
78
84
  # and verification the user still needs to settle.
@@ -136,7 +136,9 @@ Controlled by `approvals.review`, skipped in `auto`.
136
136
  Report: what was built (for a code run, show its Preview proof), verification results, findings fixed, findings still open,
137
137
  every criterion the reviewer answered `CANNOT VERIFY` with the check it says a human
138
138
  must make, anything the builder noted as out of scope, and the notes the *Docs gate*
139
- touched. Where the run used `runner: lite` and reviewed inline (`review.executor: inline`), say
139
+ touched, and the `## Remembered` lines from `04-review.md` verbatim, so what the run
140
+ saved to memory and to global knowledge is visible without opening a file (deleting
141
+ or editing a line in `~/.kaizen/knowledge/` is the undo). Where the run used `runner: lite` and reviewed inline (`review.executor: inline`), say
140
142
  so in that report — the reviewer saw the work, and nobody should read a same-session
141
143
  review as an independent one because the output looked the same.
142
144
  Later build requests in the same session follow *Follow-ups are runs too* in [`spec.md`](spec.md): a revise of this run until it is `done`, then a new linked run.