kaizen-agent 1.56.1 → 1.58.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.
package/cli/board.test.ts CHANGED
@@ -4,10 +4,57 @@ import { readFileSync } from "node:fs";
4
4
  import { join, dirname } from "node:path";
5
5
  import { md, progress, planQuestions, brief } from "../web/board/markdown.ts";
6
6
  import { draft, undraft } from "../web/board/drafts.ts";
7
+ import { boardBadge, refreshBoardBadge, waitingCount } from "../web/board/badge.ts";
7
8
 
8
9
  const html = readFileSync(join(dirname(import.meta.dir), "web", "board.html"), "utf8");
9
10
  const cards = readFileSync(join(dirname(import.meta.dir), "web", "board", "cards.ts"), "utf8");
10
11
 
12
+ test("Board badge counts each card needing input once and clears at zero", () => {
13
+ const link = { dataset: {} as Record<string, string>, title: "Board", label: "", setAttribute(_key: string, value: string) { this.label = value; } };
14
+ const previous = globalThis.document;
15
+ (globalThis as any).document = { querySelector: () => link };
16
+ try {
17
+ const cards = [
18
+ { kind: "run", status: "waiting", pty: { alive: true, asking: true } },
19
+ { kind: "idea", status: "idea", pty: { alive: true, asking: true } },
20
+ { kind: "run", status: "waiting", archived: true },
21
+ { kind: "run", status: "running", pty: { alive: false, asking: true } },
22
+ ];
23
+ expect(waitingCount(cards)).toBe(2);
24
+ boardBadge(cards);
25
+ expect(link.dataset.n).toBe("2");
26
+ expect(link.label).toBe("Ideas: 2 waiting on you");
27
+ boardBadge([]);
28
+ expect(link.dataset.n).toBeUndefined();
29
+ expect(link.label).toBe("Ideas: every idea and run, filtered");
30
+ } finally {
31
+ globalThis.document = previous;
32
+ }
33
+ });
34
+
35
+ test("Board badge coalesces overlapping updates and shows the latest count", async () => {
36
+ const link = { dataset: {} as Record<string, string>, title: "Board", setAttribute() {} };
37
+ const previousDocument = globalThis.document, previousFetch = globalThis.fetch;
38
+ (globalThis as any).document = { querySelector: () => link };
39
+ let release!: () => void, calls = 0;
40
+ globalThis.fetch = (async () => {
41
+ const n = ++calls;
42
+ if (n === 1) await new Promise<void>((resolve) => { release = resolve; });
43
+ return { ok: true, json: async () => ({ cards: n === 1 ? [{ kind: "run", status: "waiting" }] : [] }) } as Response;
44
+ }) as typeof fetch;
45
+ try {
46
+ const first = refreshBoardBadge(), second = refreshBoardBadge();
47
+ expect(calls).toBe(1);
48
+ release();
49
+ await Promise.all([first, second]);
50
+ expect(calls).toBe(2);
51
+ expect(link.dataset.n).toBeUndefined();
52
+ } finally {
53
+ globalThis.document = previousDocument;
54
+ globalThis.fetch = previousFetch;
55
+ }
56
+ });
57
+
11
58
  test("Settings rechecks an existing update alert and clears or refreshes it", async () => {
12
59
  const classes = new Set<string>();
13
60
  const link = { classList: { toggle(name: string, on: boolean) { on ? classes.add(name) : classes.delete(name); } }, title: "Settings" };
@@ -297,3 +344,12 @@ test("md() renders italic and two-space hard breaks, and leaves globs in code al
297
344
  expect(md("`*.ts` and `*.md`, a * b * c")).toBe("<p><code>*.ts</code> and <code>*.md</code>, a * b * c</p>");
298
345
  expect(md("one \ntwo\nthree")).toBe("<p>one<br>two three</p>");
299
346
  });
347
+
348
+ test("new-idea picker never swaps a preset project for another when a choice is required", async () => {
349
+ const { startDir } = await import("../web/board/labels.ts");
350
+ expect(startDir(["/a", "/b"], "/b", true)).toBe("/b");
351
+ expect(startDir(["/a", "/b"], "/gone", true)).toBeNull();
352
+ expect(startDir(["/a", "/b"], null, true)).toBeNull();
353
+ expect(startDir(["/a", "/b"], "/gone", false)).toBe("/a");
354
+ expect(startDir([], null, false)).toBeNull();
355
+ });
@@ -0,0 +1,92 @@
1
+ import { test, expect } from "bun:test";
2
+ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, utimesSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { tmpdir } from "node:os";
5
+ import { lintDocs } from "./docs.ts";
6
+
7
+ const fixture = (updated = "2026-10-28") => {
8
+ const root = mkdtempSync(join(tmpdir(), "kz-docs-lint-"));
9
+ const vault = join(root, ".kaizen", "notes", "Project");
10
+ mkdirSync(vault, { recursive: true });
11
+ writeFileSync(join(root, "app.ts"), "export const app = 1;\n");
12
+ writeFileSync(join(vault, "Index.md"), `---\ndescription: Index\ntags: [project, index]\nupdated: ${updated}\n---\n# Index\n[[App]]\n`);
13
+ writeFileSync(join(vault, "App.md"), `---\ndescription: App\ntags: [project, app]\nsources: [app.ts]\nupdated: ${updated}\n---\n# App\n`);
14
+ return { root, vault, cleanup: () => rmSync(root, { recursive: true, force: true }) };
15
+ };
16
+
17
+ test("clean vault, nested CLI invocation, and no writes", () => {
18
+ const f = fixture();
19
+ try {
20
+ const nested = join(f.root, "inside"); mkdirSync(nested);
21
+ const before = readFileSync(join(f.vault, "App.md"));
22
+ const p = Bun.spawnSync([process.execPath, join(import.meta.dir, "install.ts"), "docs", "lint"], { cwd: nested });
23
+ expect(p.exitCode).toBe(0);
24
+ expect(p.stdout.toString()).toContain("docs lint: clean");
25
+ expect(readFileSync(join(f.vault, "App.md"))).toEqual(before);
26
+ expect(lintDocs(f.root)).toEqual([]);
27
+ } finally { f.cleanup(); }
28
+ });
29
+
30
+ test("reports links, metadata, missing and uncovered sources, and long Index", () => {
31
+ const f = fixture();
32
+ try {
33
+ writeFileSync(join(f.vault, "Index.md"), `---\ndescription: Index\ntags: [project, index]\nupdated: 2026-10-28\n---\n# Index\n[[App]]\n${"line\n".repeat(54)}`);
34
+ writeFileSync(join(f.vault, "App.md"), "---\ndescription: App\ntags: [project, app]\nsources: [gone.ts]\n---\n# App\n[[Missing]] `[[code]]` [[run:x]]\n");
35
+ writeFileSync(join(f.vault, "Unlisted.md"), "# unlisted\n");
36
+ const found = lintDocs(f.root).join("\n");
37
+ for (const s of ["under 60 lines", "broken link [[Missing]]", "missing updated", "missing source gone.ts", "uncovered: app.ts", "not listed in Index.md", "missing description", "missing sources"]) expect(found).toContain(s);
38
+ expect(found).not.toContain("[[code]]");
39
+ expect(found).not.toContain("[[run:x]]");
40
+ } finally { f.cleanup(); }
41
+ });
42
+
43
+ test("outside git, same-day source mtimes are covered and later ones are stale", () => {
44
+ const f = fixture("2020-01-01");
45
+ try {
46
+ const file = join(f.root, "app.ts");
47
+ utimesSync(file, new Date("2020-01-01T10:00:00"), new Date("2020-01-01T10:00:00"));
48
+ expect(lintDocs(f.root)).toEqual([]);
49
+ utimesSync(file, new Date("2020-01-02T10:00:00"), new Date("2020-01-02T10:00:00"));
50
+ expect(lintDocs(f.root)).toContain("Project/App.md: stale (sources changed after 2020-01-01)");
51
+ } finally { f.cleanup(); }
52
+ });
53
+
54
+ test.skipIf(!Bun.which("git"))("git history detects stale notes; generated and binary files do not require coverage", () => {
55
+ const f = fixture("2020-01-01");
56
+ try {
57
+ const run = (args: string[], env = process.env) => Bun.spawnSync(["git", ...args], { cwd: f.root, env });
58
+ expect(run(["init", "-q"]).exitCode).toBe(0);
59
+ writeFileSync(join(f.root, "app.js"), "built\n");
60
+ writeFileSync(join(f.root, "picture.png"), "binary\n");
61
+ expect(run(["add", "."]).exitCode).toBe(0);
62
+ expect(run(["-c", "user.name=T", "-c", "user.email=t@example.com", "commit", "-qm", "initial"], { ...process.env, GIT_AUTHOR_DATE: "2020-01-01T10:00:00+0000", GIT_COMMITTER_DATE: "2020-01-01T10:00:00+0000" }).exitCode).toBe(0);
63
+ expect(lintDocs(f.root)).toEqual([]);
64
+ const nested = join(f.root, "inside"); mkdirSync(nested);
65
+ expect(Bun.spawnSync([process.execPath, join(import.meta.dir, "install.ts"), "docs", "lint"], { cwd: nested }).exitCode).toBe(0);
66
+ const worktree = join(f.root, ".kaizen", "wt", "lint");
67
+ expect(run(["worktree", "add", "-qb", "lint-branch", worktree]).exitCode).toBe(0);
68
+ const worktreeNote = join(worktree, ".kaizen", "notes", "Project", "App.md");
69
+ writeFileSync(worktreeNote, readFileSync(worktreeNote, "utf8") + "[[Broken]]\n");
70
+ const fromWorktree = Bun.spawnSync([process.execPath, join(import.meta.dir, "install.ts"), "docs", "lint"], { cwd: worktree });
71
+ expect(fromWorktree.exitCode).toBe(1);
72
+ expect(fromWorktree.stdout.toString()).toContain("broken link [[Broken]]");
73
+ writeFileSync(join(f.root, "app.ts"), "export const app = 2;\n");
74
+ expect(run(["add", "app.ts"]).exitCode).toBe(0);
75
+ expect(run(["-c", "user.name=T", "-c", "user.email=t@example.com", "commit", "-qm", "later"], { ...process.env, GIT_AUTHOR_DATE: "2020-01-02T10:00:00+0000", GIT_COMMITTER_DATE: "2020-01-02T10:00:00+0000" }).exitCode).toBe(0);
76
+ expect(lintDocs(f.root)).toContain("Project/App.md: stale (sources changed after 2020-01-01)");
77
+ } finally { f.cleanup(); }
78
+ });
79
+
80
+ test("missing vault and unsupported CLI arguments fail clearly", () => {
81
+ const root = mkdtempSync(join(tmpdir(), "kz-docs-none-"));
82
+ try {
83
+ expect(lintDocs(root)).toContain("missing Project/Index.md (run /kaizen docs first)");
84
+ mkdirSync(join(root, ".kaizen"));
85
+ const absent = Bun.spawnSync([process.execPath, join(import.meta.dir, "install.ts"), "docs", "lint"], { cwd: root });
86
+ expect(absent.exitCode).toBe(1);
87
+ expect(absent.stdout.toString()).toContain("missing Project/Index.md");
88
+ const p = Bun.spawnSync([process.execPath, join(import.meta.dir, "install.ts"), "docs", "other"], { cwd: root });
89
+ expect(p.exitCode).toBe(1);
90
+ expect(p.stdout.toString()).toContain("kaizen docs lint");
91
+ } finally { rmSync(root, { recursive: true, force: true }); }
92
+ });
package/cli/docs.ts ADDED
@@ -0,0 +1,84 @@
1
+ import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
2
+ import { join, relative, resolve, sep } from "node:path";
3
+ import { wikilinks, boardLink, resolve as resolveNote } from "../web/notes-lib.ts";
4
+
5
+ const git = (root: string, args: string[]) => {
6
+ const p = Bun.spawnSync(["git", ...args], { cwd: root });
7
+ return p.exitCode === 0 ? p.stdout.toString() : null;
8
+ };
9
+
10
+ const walk = (dir: string, prefix = ""): string[] => {
11
+ if (!existsSync(dir)) return [];
12
+ return readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
13
+ const name = prefix ? `${prefix}/${e.name}` : e.name;
14
+ return e.isDirectory() ? walk(join(dir, e.name), name) : e.isFile() ? [name] : [];
15
+ });
16
+ };
17
+
18
+ const sourceFile = (root: string, path: string) => {
19
+ if (path.startsWith(".kaizen/") || /(^|\/)(node_modules|vendor|dist|build|coverage|\.next|public\/quran)(\/|$)/.test(path)) return false;
20
+ if (/(^|\/)(bun\.lock|package-lock\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock|poetry\.lock)$/.test(path)) return false;
21
+ if (/\.(png|jpe?g|gif|webp|ico|svg|mp[34]|ogg|wav|pdf|woff2?|ttf|otf|zip|gz|exe|dll|so|db|sqlite|map)$/i.test(path)) return false;
22
+ if (/\.js$/.test(path) && (existsSync(join(root, path.replace(/\.js$/, ".ts"))) || existsSync(join(root, path.slice(0, -3))))) return false;
23
+ return true;
24
+ };
25
+
26
+ export function lintDocs(root: string): string[] {
27
+ const vault = join(root, ".kaizen", "notes", "Project");
28
+ if (!existsSync(join(vault, "Index.md"))) return ["missing Project/Index.md (run /kaizen docs first)"];
29
+ const errors: string[] = [];
30
+ const names = walk(vault).filter((p) => p.endsWith(".md")).map((p) => p.slice(0, -3));
31
+ const index = readFileSync(join(vault, "Index.md"), "utf8");
32
+ if (index.split(/\r?\n/).length - Number(index.endsWith("\n")) >= 60) errors.push("Project/Index.md: must be under 60 lines");
33
+ const listed = new Set(wikilinks(index).filter((w) => !boardLink(w)).map((w) => resolveNote(w.name, names)).filter(Boolean));
34
+ const covered: { path: string; directory: boolean }[] = [];
35
+ const inGit = !!Bun.which("git") && git(root, ["rev-parse", "--show-toplevel"]) !== null;
36
+ for (const name of names) {
37
+ const file = join(vault, `${name}.md`);
38
+ const text = readFileSync(file, "utf8");
39
+ const front = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text)?.[1] ?? "";
40
+ const field = (key: string) => new RegExp(`^${key}:[ \\t]*(.*)$`, "m").exec(front)?.[1]?.trim();
41
+ for (const w of wikilinks(text)) if (!boardLink(w) && !resolveNote(w.name, names)) errors.push(`Project/${name}.md: broken link [[${w.target}]]`);
42
+ if (name.startsWith("Archive/")) continue;
43
+ if (name !== "Index" && name !== "Log" && !listed.has(name)) errors.push(`Project/${name}.md: not listed in Index.md`);
44
+ for (const key of ["description", "tags", "updated", ...((name === "Index" || name === "Log") ? [] : ["sources"])])
45
+ if (!field(key)) errors.push(`Project/${name}.md: missing ${key}`);
46
+ if (name === "Index" || name === "Log") continue;
47
+ const date = field("updated");
48
+ if (date && !/^\d{4}-\d{2}-\d{2}$/.test(date)) errors.push(`Project/${name}.md: invalid updated date`);
49
+ const raw = field("sources");
50
+ if (!raw) continue;
51
+ if (!/^\[.*\]$/.test(raw)) { errors.push(`Project/${name}.md: sources must be a list`); continue; }
52
+ const sources = raw.slice(1, -1).split(",").map((s) => s.trim().replace(/^['"]|['"]$/g, "")).filter(Boolean);
53
+ if (!sources.length) errors.push(`Project/${name}.md: empty sources`);
54
+ for (const path of sources) {
55
+ const absolute = resolve(root, path);
56
+ if (!absolute.startsWith(resolve(root) + sep) || !existsSync(absolute) || !realpathSync(absolute).startsWith(realpathSync(root) + sep)) { errors.push(`Project/${name}.md: missing source ${path}`); continue; }
57
+ covered.push({ path: relative(root, absolute).replaceAll("\\", "/"), directory: statSync(absolute).isDirectory() });
58
+ }
59
+ if (date && /^\d{4}-\d{2}-\d{2}$/.test(date) && sources.length) {
60
+ const paths = sources.filter((p) => { const f = resolve(root, p); return f.startsWith(resolve(root) + sep) && existsSync(f) && realpathSync(f).startsWith(realpathSync(root) + sep); });
61
+ const later = `${date} 23:59:59`;
62
+ let stale = false;
63
+ if (inGit) {
64
+ const history = git(root, ["log", `--after=${later}`, "--format=", "--name-only", "--", ...paths.map((p) => `:(literal)${p}`)]);
65
+ const dirty = git(root, ["ls-files", "-m", "-d", "-o", "--exclude-standard", "-z", "--", ...paths.map((p) => `:(literal)${p}`)]);
66
+ if (history === null || dirty === null) errors.push(`Project/${name}.md: git history check failed`);
67
+ stale = !!history?.trim();
68
+ stale ||= (dirty ?? "").split("\0").some((p) => p && (existsSync(join(root, p)) ? statSync(join(root, p)).mtimeMs : Date.now()) > new Date(`${date}T23:59:59`).getTime());
69
+ } else stale = paths.some((p) => {
70
+ const f = resolve(root, p);
71
+ return (statSync(f).isDirectory() ? walk(f).map((x) => join(f, x)) : [f]).some((x) => statSync(x).mtimeMs > new Date(`${date}T23:59:59`).getTime());
72
+ });
73
+ if (stale) errors.push(`Project/${name}.md: stale (sources changed after ${date})`);
74
+ }
75
+ }
76
+ const tracked = inGit ? git(root, ["ls-files", "-z"]) : null;
77
+ if (inGit && tracked === null) errors.push("git source listing failed");
78
+ const files = inGit ? (tracked ?? "").split("\0").filter(Boolean) : walk(root);
79
+ for (const path of files) {
80
+ if (!sourceFile(root, path) || covered.some((c) => path === c.path || (c.directory && path.startsWith(c.path + "/")))) continue;
81
+ errors.push(`uncovered: ${path}`);
82
+ }
83
+ return errors.sort();
84
+ }
package/cli/install.ts CHANGED
@@ -122,6 +122,19 @@ if (Bun.argv[2] === "remember" || Bun.argv[2] === "recall") {
122
122
  process.exit(cli(Bun.argv.slice(2)));
123
123
  }
124
124
 
125
+ if (Bun.argv[2] === "docs") {
126
+ if (Bun.argv.length !== 4 || Bun.argv[3] !== "lint") { console.log("\n kaizen docs lint\n"); process.exit(1); }
127
+ const { locate } = await import("./state.ts");
128
+ const { lintDocs } = await import("./docs.ts");
129
+ const state = locate();
130
+ const gitRoot = Bun.which("git") ? Bun.spawnSync(["git", "rev-parse", "--show-toplevel"], { cwd: process.cwd() }) : null;
131
+ const repo = gitRoot?.exitCode === 0 ? gitRoot.stdout.toString().trim() : "";
132
+ const root = repo && existsSync(join(repo, ".kaizen")) ? repo : state ? dirname(state) : null;
133
+ const problems = root ? lintDocs(root) : ["no kaizen project found"];
134
+ console.log(problems.length ? `\n${problems.map((p) => ` ${p}`).join("\n")}\n\n ${problems.length} docs lint finding(s)\n` : "\n docs lint: clean\n");
135
+ process.exit(problems.length ? 1 : 0);
136
+ }
137
+
125
138
  if (Bun.argv[2] === "sources" || Bun.argv[2] === "gather" || Bun.argv[2] === "icebox") {
126
139
  const { locate, label } = await import("./state.ts");
127
140
  const src = await import("./sources.ts");
@@ -0,0 +1,39 @@
1
+ import { test, expect } from "bun:test";
2
+ import { mkdtempSync, mkdirSync, writeFileSync, symlinkSync, rmSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { tmpdir } from "node:os";
5
+
6
+ test("project tree and text preview stay inside a registered project", async () => {
7
+ const home = mkdtempSync(join(tmpdir(), "kaizen-tree-"));
8
+ const project = join(home, "project");
9
+ mkdirSync(join(home, ".kaizen"));
10
+ mkdirSync(join(project, ".kaizen"), { recursive: true });
11
+ mkdirSync(join(project, "src"));
12
+ writeFileSync(join(home, ".kaizen", "projects"), project + "\n");
13
+ writeFileSync(join(project, "src", "good.txt"), "<script>alert(1)</script>\n");
14
+ writeFileSync(join(project, "binary.dat"), Buffer.from([0, 1, 2]));
15
+ writeFileSync(join(project, "big.txt"), "x".repeat(65537));
16
+ writeFileSync(join(project, ".secret"), "hidden");
17
+ symlinkSync(join(home, ".kaizen", "projects"), join(project, "link"));
18
+ const port = 20000 + Math.floor(Math.random() * 20000);
19
+ const repo = join(import.meta.dir, "..");
20
+ const proc = Bun.spawn([process.execPath, join(repo, "cli", "install.ts"), "web", "--port", String(port), "--no-open", "--foreground"], {
21
+ cwd: project, env: { ...process.env, HOME: home, USERPROFILE: home, KAIZEN_HOME: repo }, stdout: "ignore", stderr: "ignore",
22
+ });
23
+ try {
24
+ const base = `http://127.0.0.1:${port}`;
25
+ for (let i = 0; ; i++) { try { await fetch(base + "/state"); break; } catch { if (i > 100) throw new Error("board did not start"); await Bun.sleep(50); } }
26
+ const get = (route: string, path: string, dir = join(project, ".kaizen")) => fetch(base + route + "?dir=" + encodeURIComponent(dir) + "&path=" + encodeURIComponent(path));
27
+ const root = await (await get("/project-tree", "")).json() as any;
28
+ expect(root.entries.map((e: any) => e.name)).toContain("src");
29
+ expect(root.entries.map((e: any) => e.name)).not.toContain(".secret");
30
+ expect(root.entries.map((e: any) => e.name)).not.toContain("link");
31
+ expect((await (await get("/project-text", "src/good.txt")).json()).content).toBe("<script>alert(1)</script>\n");
32
+ for (const path of ["../.kaizen/projects", "/etc/passwd", "C:/Windows/win.ini", ".secret", "link", "src/../../.secret"]) expect((await get("/project-text", path)).status).toBeGreaterThanOrEqual(400);
33
+ for (const path of ["binary.dat", "big.txt"]) expect((await get("/project-text", path)).status).toBe(415);
34
+ expect((await get("/project-tree", "", join(home, "elsewhere", ".kaizen"))).status).toBe(404);
35
+ const download = await fetch(base + "/project-text?dir=" + encodeURIComponent(join(project, ".kaizen")) + "&path=src%2Fgood.txt&download=1");
36
+ expect(download.headers.get("content-type")).toContain("text/plain");
37
+ expect(download.headers.get("content-disposition")).toContain("attachment");
38
+ } finally { proc.kill(); await proc.exited; rmSync(home, { recursive: true, force: true }); }
39
+ });
package/cli/pty.test.ts CHANGED
@@ -50,7 +50,7 @@ test.skipIf(process.platform === "win32")("the board runs the agent in the card:
50
50
  expect(r.ok).toBe(true);
51
51
  expect(r.pty).toMatch(/^[\w-]+$/);
52
52
  const card = ((await (await fetch(at + "/state")).json()) as any).cards.find((c: any) => c.text === "say hello");
53
- expect(card.pty).toEqual({ key: r.pty, alive: true, asking: false });
53
+ expect(card.pty).toEqual({ key: r.pty, alive: true, asking: false, all: [r.pty] });
54
54
 
55
55
  // G-01: no Origin, a foreign one, and another local port are all refused.
56
56
  const url = `${at}/pty?key=${r.pty}`, up = { upgrade: "websocket", connection: "Upgrade", "sec-websocket-version": "13", "sec-websocket-key": "dGhlIHNhbXBsZSBub25jZQ==" };
package/cli/state.test.ts CHANGED
@@ -598,6 +598,19 @@ test("runGit, cardsGit: a run committed elsewhere is not offered the edits made
598
598
  report("new", "- `y.txt`: y\n\n## Commit\nchore: z\n", 3000);
599
599
  expect(runGit(st, "old")).toMatchObject({ ahead: 0 });
600
600
  expect(runGit(st, "new")).toMatchObject({ ahead: 2 });
601
+ // Both runs name the file; without a subject or SHA the newer report wins.
602
+ report("old", "- `x.txt`: x, again\n- `y.txt`: shared\n", 5000);
603
+ report("new", "- `y.txt`: shared\n\n## Commit\nchore: z\n", 5500);
604
+ writeFileSync(join(proj, "y.txt"), "shared change");
605
+ sh(proj, null, "add", "y.txt");
606
+ sh(proj, 7000, "commit", "-qm", "fix: shared");
607
+ expect(runGit(st, "old")).toMatchObject({ ahead: 0 });
608
+ expect(runGit(st, "new")).toMatchObject({ ahead: 2 });
609
+ const sha = sh(proj, null, "rev-parse", "--short", "HEAD");
610
+ writeFileSync(join(st, "runs", "old", "07-commit.md"), `commit: ${sha}\npushed: no\n`);
611
+ expect(runGit(st, "old")).toMatchObject({ ahead: 1 });
612
+ expect(runGit(st, "new")).toMatchObject({ ahead: 1 });
613
+ expect(cardsGit(st, ["old", "new"])).toEqual({ old: "pending", new: "pending" });
601
614
  }, 60_000);
602
615
 
603
616
  test.skipIf(process.platform === "win32")("findTerminal: a running herdr wins, then tmux, else neither; the prompt stays one literal argument", () => {
@@ -1234,11 +1247,12 @@ test("the board refuses an upgrade from another origin", async () => {
1234
1247
  for (const d of [join(homeDir, ".kaizen"), join(homeDir, ".claude")]) mkdirSync(d, { recursive: true });
1235
1248
  const port = 20000 + Math.floor(Math.random() * 20000), repo = join(import.meta.dir, "..");
1236
1249
  const proc = Bun.spawn([process.execPath, join(repo, "cli", "install.ts"), "web", "--port", String(port), "--no-open", "--foreground"], {
1237
- cwd: homeDir, env: { ...process.env, HOME: homeDir, USERPROFILE: homeDir, KAIZEN_HOME: repo }, stdout: "ignore", stderr: "ignore",
1250
+ cwd: homeDir, env: { ...process.env, HOME: homeDir, USERPROFILE: homeDir, KAIZEN_HOME: repo, KAIZEN_WEB_HOSTS: "" }, stdout: "ignore", stderr: "ignore",
1238
1251
  });
1239
1252
  try {
1240
1253
  const at = `http://127.0.0.1:${port}`;
1241
1254
  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); } }
1255
+ expect((await (await fetch(at + "/settings")).json()).phoneUrls).toEqual([]);
1242
1256
  const r = await fetch(at + "/upgrade", { method: "POST", headers: { origin: "https://evil.example" } });
1243
1257
  expect(r.status).toBe(403);
1244
1258
  } finally { proc.kill(); await proc.exited; rmSync(homeDir, { recursive: true, force: true }); }
@@ -1250,16 +1264,18 @@ test("the board answers only the hosts listed in KAIZEN_WEB_HOSTS or web-hosts",
1250
1264
  for (const d of [join(homeDir, ".kaizen"), join(homeDir, ".claude")]) mkdirSync(d, { recursive: true });
1251
1265
  const port = 20000 + Math.floor(Math.random() * 20000), repo = join(import.meta.dir, "..");
1252
1266
  const proc = Bun.spawn([process.execPath, join(repo, "cli", "install.ts"), "web", "--port", String(port), "--no-open", "--foreground"], {
1253
- cwd: homeDir, env: { ...process.env, HOME: homeDir, USERPROFILE: homeDir, KAIZEN_HOME: repo, KAIZEN_WEB_HOSTS: " PC.tail1234.ts.net:443 , " }, stdout: "ignore", stderr: "ignore",
1267
+ cwd: homeDir, env: { ...process.env, HOME: homeDir, USERPROFILE: homeDir, KAIZEN_HOME: repo, KAIZEN_WEB_HOSTS: " PC.tail1234.ts.net:443 , bad@pc.tail1234.ts.net " }, stdout: "ignore", stderr: "ignore",
1254
1268
  });
1255
1269
  try {
1256
1270
  const at = `http://127.0.0.1:${port}`;
1257
1271
  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); } }
1272
+ expect((await (await fetch(at + "/settings")).json()).phoneUrls).toEqual(["https://pc.tail1234.ts.net"]);
1258
1273
  expect((await fetch(at + "/state", { headers: { host: "pc.tail1234.ts.net" } })).status).toBe(200);
1259
1274
  expect((await fetch(at + "/state", { headers: { host: "evil.example" } })).status).toBe(403);
1260
1275
  expect((await fetch(at + "/state", { headers: { host: "other.tail1234.ts.net" } })).status).toBe(403);
1261
1276
  // ~/.kaizen/web-hosts (written by `kaizen setup`) is read per request: no restart.
1262
1277
  writeFileSync(join(homeDir, ".kaizen", "web-hosts"), "# phone\nOther.tail1234.ts.net\n");
1278
+ expect((await (await fetch(at + "/settings")).json()).phoneUrls).toEqual(["https://pc.tail1234.ts.net", "https://other.tail1234.ts.net"]);
1263
1279
  expect((await fetch(at + "/state", { headers: { host: "other.tail1234.ts.net" } })).status).toBe(200);
1264
1280
  expect((await fetch(at + "/state", { headers: { host: "evil.example" } })).status).toBe(403);
1265
1281
  expect((await fetch(at + "/upgrade", { method: "POST", headers: { origin: "https://evil.example" } })).status).toBe(403);
package/cli/state.ts CHANGED
@@ -741,6 +741,7 @@ export type Card = {
741
741
  dim: boolean;
742
742
  moved?: number; // runs only: state.json mtime
743
743
  added?: number; // ideas only: when the inbox line first appeared (ms)
744
+ inboxIndex?: number; // ideas only: line in the project's inbox
744
745
  title?: string; // runs only: first line of the request
745
746
  archived: boolean; // hidden from the board unless asked for
746
747
  branch?: string; // runs only: the run's own branch while it has a worktree
@@ -916,7 +917,7 @@ export function formatNote(text: string, at = stamp()) {
916
917
 
917
918
  // Append one entry: to runs/<id>/notes.md for a run, or under the idea's inbox
918
919
  // bullet. Attachments arrive as markdown links already written into text.
919
- export function appendNote(state: string, target: { id: string } | { text: string }, text: string): string | null {
920
+ export function appendNote(state: string, target: { id: string } | { text: string; index?: number }, text: string): string | null {
920
921
  if (!text.trim()) return "empty note";
921
922
  if ("id" in target) {
922
923
  if (!existsSync(join(state, "runs", target.id, "state.json"))) return "no such run";
@@ -924,8 +925,8 @@ export function appendNote(state: string, target: { id: string } | { text: strin
924
925
  return null;
925
926
  }
926
927
  const lines = readInbox(state);
927
- const at = lines.findIndex((l) => l.status === "open" && l.text === target.text);
928
- if (at < 0) return "no such idea";
928
+ const at = target.index === undefined ? lines.findIndex((l) => l.status === "open" && l.text === target.text) : target.index;
929
+ if (lines[at]?.status !== "open" || lines[at]?.text !== target.text) return "no such idea";
929
930
  const prev = lines[at]!.notes;
930
931
  lines[at] = { ...lines[at]!, notes: (prev ? prev + "\n" : "") + formatNote(text) };
931
932
  writeInbox(state, lines);
@@ -1073,12 +1074,13 @@ export function runToIdea(st: string, id: string): string | null {
1073
1074
  return null;
1074
1075
  }
1075
1076
 
1076
- export function replaceIdea(state: string, text: string, next: InboxLine | null) {
1077
+ export function replaceIdea(state: string, text: string, next: InboxLine | null, index?: number) {
1077
1078
  const lines = readInbox(state);
1078
- const at = lines.findIndex((l) => (l.status === "open" || l.status === "started") && l.text === text);
1079
- if (at < 0) return; // changed underneath us; the redraw will show why
1079
+ const at = index === undefined ? lines.findIndex((l) => (l.status === "open" || l.status === "started") && l.text === text) : index;
1080
+ if (!lines[at] || !["open", "started"].includes(lines[at]!.status) || lines[at]!.text !== text) return false;
1080
1081
  if (next) lines[at] = { notes: lines[at]!.notes, ...next }; else lines.splice(at, 1);
1081
1082
  writeInbox(state, lines);
1083
+ return true;
1082
1084
  }
1083
1085
 
1084
1086
  // An open idea, notes and all, from one project's inbox to another's. Files its notes
@@ -1179,7 +1181,7 @@ export function boardCards(states: string[], now: number): Card[] {
1179
1181
  for (const st of states) {
1180
1182
  const where = label(st);
1181
1183
  const archive = readArchive(st);
1182
- for (const it of readInbox(st)) {
1184
+ for (const [inboxIndex, it] of readInbox(st).entries()) {
1183
1185
  if (it.status !== "open" && it.status !== "started" && it.status !== "archived") continue;
1184
1186
  // Retired once any run's request contains this text -- whoever started it.
1185
1187
  // Checking `started` items only would leave every idea acted on outside the
@@ -1196,8 +1198,8 @@ export function boardCards(states: string[], now: number): Card[] {
1196
1198
  const after = (r: { at: number }) => !it.added || r.at >= it.added - 2000;
1197
1199
  if (it.status === "started" ? requests.some((r) => after(r) && r.text.includes(t)) || launchedInto(st, t) : lines.some((l) => after(l) && (l.text === t || l.text.endsWith(" " + t)))) continue;
1198
1200
  next.push(it.status === "started"
1199
- ? { kind: "idea", status: "starting", text: it.text, state: st, where, column: 1, awaiting: null, dim: true, archived: false, notes: it.notes, parent: parentOf(it.notes) }
1200
- : { kind: "idea", status: "idea", text: it.text, state: st, where, column: 0, awaiting: null, dim: false, archived: it.status === "archived", notes: it.notes, parent: parentOf(it.notes), added: it.added });
1201
+ ? { kind: "idea", status: "starting", text: it.text, state: st, where, column: 1, awaiting: null, dim: true, archived: false, notes: it.notes, parent: parentOf(it.notes), inboxIndex }
1202
+ : { kind: "idea", status: "idea", text: it.text, state: st, where, column: 0, awaiting: null, dim: false, archived: it.status === "archived", notes: it.notes, parent: parentOf(it.notes), added: it.added, inboxIndex });
1201
1203
  }
1202
1204
  // Runs started in Yolo. Only yolo records are matched to runs, so a project that
1203
1205
  // never used it pays one directory read.
@@ -1764,7 +1766,7 @@ async function gitAsync(dir: string, ...args: string[]) {
1764
1766
  }
1765
1767
 
1766
1768
  export type GitStatus = { repo: false } | { repo: true; branch: string; remote: string; files: string[]; ahead: number; others?: number; shared?: string[]; unpushed?: Unpushed[] };
1767
- type Unpushed = { at: number; subject: string; files: string[] };
1769
+ type Unpushed = { sha: string; at: number; subject: string; files: string[] };
1768
1770
 
1769
1771
  // A project the board can commit for: a git work tree with somewhere to push.
1770
1772
  export function gitStatus(projectDir: string): GitStatus {
@@ -1778,9 +1780,9 @@ export function gitStatus(projectDir: string): GitStatus {
1778
1780
  const ahead = up.ok ? Number(up.out) : git(projectDir, "rev-parse", "HEAD").ok ? 1 : 0;
1779
1781
  // Each commit not on the remote yet, with its files: a run is ahead only by its own.
1780
1782
  const unpushed = up.ok && ahead > 0
1781
- ? git(projectDir, "log", "@{u}..HEAD", "--format=%x00%ct %s", "--name-only").out.split("\0").slice(1).map((c) => {
1782
- const [head, ...files] = c.trim().split("\n"), sp = head.indexOf(" ");
1783
- return { at: Number(head.slice(0, sp)) * 1000, subject: head.slice(sp + 1).trim(), files: files.filter(Boolean) };
1783
+ ? git(projectDir, "log", "@{u}..HEAD", "--format=%x00%H %ct %s", "--name-only").out.split("\0").slice(1).map((c) => {
1784
+ const [head, ...files] = c.trim().split("\n"), [sha, at, ...subject] = head.split(" ");
1785
+ return { sha, at: Number(at) * 1000, subject: subject.join(" ").trim(), files: files.filter(Boolean) };
1784
1786
  })
1785
1787
  : undefined;
1786
1788
  return { repo: true, branch: git(projectDir, "branch", "--show-current").out, remote, files: st ? st.split("\n") : [], ahead, ...(unpushed ? { unpushed } : {}) };
@@ -1802,11 +1804,11 @@ function runReport(state: string, id: string) {
1802
1804
  }
1803
1805
  const names = (report: string, path: string) => report.includes("`" + path + "`") || report.includes("`" + path + ":");
1804
1806
 
1805
- type Report = { id: string; text: string; at: number };
1807
+ type Report = { id: string; text: string; at: number; sha?: string };
1806
1808
  function runReports(state: string): Report[] {
1807
1809
  let ids: string[] = [];
1808
1810
  try { ids = readdirSync(join(state, "runs")); } catch {}
1809
- return ids.map((id) => ({ id, ...runReport(state, id) }));
1811
+ return ids.map((id) => ({ id, ...runReport(state, id), sha: readCommit(state, id)?.sha }));
1810
1812
  }
1811
1813
  // A run holds a path at time `t` when its report names it, was written by then, and no
1812
1814
  // other run naming it reported in between.
@@ -1822,7 +1824,7 @@ const runFiles = (dir: string, changed: string[], mine: Report, rest: Report[])
1822
1824
  });
1823
1825
  // How many unpushed commits each run has, worked out once for every run. A commit is
1824
1826
  // one run's, so a wide commit is not pinned on every old run that once touched a file
1825
- // in it: the run whose report holds its subject (the `## Commit` message), else, of
1827
+ // in it: the run whose record holds its SHA, then the report holding its subject, else, of
1826
1828
  // the runs that reported by then (to the end of that second, since commit times are
1827
1829
  // whole seconds), the one naming most of its paths, the latest on a tie. One naming
1828
1830
  // none, a merge or a hand commit, goes to the run that reported last, so some run
@@ -1832,8 +1834,10 @@ function aheadBy(s: GitStatus & { repo: true }, all: Report[]): (id: string) =>
1832
1834
  if (!s.unpushed) return () => s.ahead;
1833
1835
  const n = new Map<string, number>();
1834
1836
  for (const c of s.unpushed) {
1837
+ // Only a unique commit prefix is exact; old or ambiguous records use the fallback.
1838
+ let best = all.find((r) => r.sha && /^[0-9a-f]{4,40}$/i.test(r.sha) && c.sha.startsWith(r.sha) && s.unpushed!.filter((x) => x.sha.startsWith(r.sha!)).length === 1);
1835
1839
  // The subject as a line of its own: a short one ("wip") is not found inside prose.
1836
- let best = c.subject ? all.find((r) => r.text.split("\n").some((l) => l.trim() === c.subject)) : undefined;
1840
+ if (!best) best = c.subject ? all.find((r) => r.text.split("\n").some((l) => l.trim() === c.subject)) : undefined;
1837
1841
  if (!best) {
1838
1842
  let most = -1;
1839
1843
  for (const r of all) {