kaizen-agent 1.53.0 → 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/state.test.ts CHANGED
@@ -10,7 +10,7 @@ import {
10
10
  readRuns, readInbox, writeInbox, replaceIdea, moveIdea, abandonRun, runToIdea, allBacklog, backlog,
11
11
  requestTitle, statusOf, columnOf, parseItem, startedRuns, boardCards, parentOf, addCard, readArchive, setArchived,
12
12
  requestOf, agentFlags, plainModel, readNotes, writeNotes, manualCommand, parseNotes, formatNote, appendNote, saveAttachment,
13
- reviewFindings, pickFindings, fixPrompt, approvalPrompt, sessionLaunch, closeSessions, sweepSessions, readSessions, ownerOf, CLOSE_GRACE_MS, gitStatus, runGit, cardsGit, commitPush, readCommit, findTerminal, nativePath, pruneRuns, unrechecked, notice, notifier, notifyArgs, LOGO, type Card,
13
+ reviewFindings, pickFindings, fixPrompt, approvalPrompt, sessionLaunch, closeSessions, sweepSessions, readSessions, ownerOf, CLOSE_GRACE_MS, gitStatus, runGit, cardsGit, commitPush, readCommit, findTerminal, nativePath, pruneRuns, unrechecked, notice, notifier, notifyArgs, winToastArgs, LOGO, type Card,
14
14
  } from "./state.ts";
15
15
 
16
16
  let state: string;
@@ -748,6 +748,15 @@ test("notice: plain words for what a run waits on, done, and nothing for the res
748
748
  expect(notifyArgs("x")).toEqual(["notify-send", "-a", "kaizen", "-i", LOGO, "kaizen", "x"]);
749
749
  });
750
750
 
751
+ test("winToastArgs carries the body base64, so a quote cannot end the PowerShell string", () => {
752
+ const body = "it's \"done\" — ~/acme\n$(rm)";
753
+ const a = winToastArgs(body);
754
+ expect(a[0]).toMatch(/WindowsPowerShell\\v1\.0\\powershell\.exe$/);
755
+ const b64 = /FromBase64String\('([^']+)'\)/.exec(a.at(-1)!)![1]!;
756
+ expect(Buffer.from(b64, "base64").toString("utf8")).toBe(body);
757
+ expect(a.at(-1)).not.toContain("rm)");
758
+ });
759
+
751
760
  test("notifier: only a run seen before, saying something new, and not a done the user just approved", () => {
752
761
  const due = notifier(), M = 60_000;
753
762
  expect(due("r", "a", false, 0)).toBe(false); // first load, or arrived already waiting
package/cli/state.ts CHANGED
@@ -998,11 +998,24 @@ export const LOGO = join(dirname(import.meta.dir), "assets", "kaizen-logo.png");
998
998
  export function notifyArgs(body: string) {
999
999
  return ["notify-send", "-a", "kaizen", ...(existsSync(LOGO) ? ["-i", LOGO] : []), "kaizen", body];
1000
1000
  }
1001
+ // Windows: a toast through PowerShell's WinRT bridge, under PowerShell's own app id
1002
+ // (an unregistered id shows nothing). Windows PowerShell 5.1, not pwsh: 7 has no WinRT
1003
+ // projection. The body travels base64 so no quote can break out. The toast's own sound plays.
1004
+ export function winToastArgs(body: string) {
1005
+ const b64 = Buffer.from(body, "utf8").toString("base64");
1006
+ const ps = `$t=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64}'));` +
1007
+ `[void][Windows.UI.Notifications.ToastNotificationManager,Windows.UI.Notifications,ContentType=WindowsRuntime];` +
1008
+ `$x=[Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02);` +
1009
+ `$n=$x.GetElementsByTagName('text');[void]$n.Item(0).AppendChild($x.CreateTextNode('kaizen'));[void]$n.Item(1).AppendChild($x.CreateTextNode($t));` +
1010
+ `[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe').Show([Windows.UI.Notifications.ToastNotification]::new($x))`;
1011
+ return [sysExe("WindowsPowerShell\\v1.0\\powershell.exe"), "-NoProfile", "-NonInteractive", "-Command", ps];
1012
+ }
1001
1013
  export function notify(body: string) {
1002
1014
  try {
1003
- if (!Bun.which("notify-send")) return;
1004
- Bun.spawn(notifyArgs(body), {
1005
- stdin: "ignore", stdout: "ignore", stderr: "ignore", detached: true,
1015
+ const win = process.platform === "win32";
1016
+ if (!win && !Bun.which("notify-send")) return;
1017
+ Bun.spawn(win ? winToastArgs(body) : notifyArgs(body), {
1018
+ stdin: "ignore", stdout: "ignore", stderr: "ignore", detached: true, windowsHide: true,
1006
1019
  }).unref();
1007
1020
  } catch { /* notifications are not worth an exception */ }
1008
1021
  }
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"]]);