import { afterEach, describe, expect, it } from "bun:test"; import * as fs from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; let completionText = '{"updates":[]}'; let completionTexts: string[] = []; let completionCalls = 0; const { default: pulse, parsePulseArgs, quotePulseArg, __setPulseModelClient, } = await import("../index.ts"); __setPulseModelClient({ complete: (async () => { completionCalls++; return { content: [ { type: "text", text: completionTexts.shift() ?? completionText }, ], }; }) as never, getModel: ((provider: string, id: string) => ({ provider, id })) as never, }); let tmp = ""; function cwd(): string { tmp = fs.mkdtempSync(path.join(os.tmpdir(), "pulse-index-")); return tmp; } function write(root: string, rel: string, text = rel): void { const p = path.join(root, rel); fs.mkdirSync(path.dirname(p), { recursive: true }); fs.writeFileSync(p, text); } function writeConfig(root: string, config: unknown): void { write(root, ".pi/pulse.json", JSON.stringify(config, null, 2)); } function harness(root: string) { const commands = new Map(); const events = new Map(); const notifications: Array<{ message: string; level: string }> = []; const statuses: Array<{ key: string; value: string | undefined }> = []; const confirmations: string[] = []; const editors: Array<{ title: string; prefill: string }> = []; const entries: any[] = []; let confirmResult = true; let editorResult: string | undefined; const ctx: any = { cwd: root, model: { provider: "test", id: "model" }, ui: { notify(message: string, level: string) { notifications.push({ message, level }); }, setStatus(key: string, value: string | undefined) { statuses.push({ key, value }); }, async confirm(title: string, message: string) { confirmations.push(`${title}\n${message}`); return confirmResult; }, async editor(title: string, prefill: string) { editors.push({ title, prefill }); return editorResult; }, }, modelRegistry: { async getApiKeyAndHeaders() { return { ok: true, apiKey: "test-key" }; }, }, sessionManager: { getBranch() { return entries; }, }, isIdle() { return true; }, }; const pi: any = { _cwd: root, registerCommand(name: string, command: unknown) { commands.set(name, command); }, on(name: string, handler: unknown) { events.set(name, handler); }, appendEntry(customType: string, data: unknown) { entries.push({ type: "custom", customType, data }); }, }; pulse(pi); return { commands, events, ctx, notifications, statuses, confirmations, editors, entries, setConfirmResult(value: boolean) { confirmResult = value; }, setEditorResult(value: string | undefined) { editorResult = value; }, }; } afterEach(() => { completionText = '{"updates":[]}'; completionTexts = []; completionCalls = 0; __setPulseModelClient({ complete: (async () => { completionCalls++; return { content: [ { type: "text", text: completionTexts.shift() ?? completionText }, ], }; }) as never, getModel: ((provider: string, id: string) => ({ provider, id })) as never, }); if (tmp) fs.rmSync(tmp, { recursive: true, force: true }); tmp = ""; }); describe("pulse argument parsing", () => { it("supports quoted paths with spaces", () => { expect(parsePulseArgs('add "my file.md" keep concise')).toEqual([ "add", "my file.md", "keep", "concise", ]); expect(quotePulseArg("my file.md")).toBe('"my file.md"'); }); }); describe("pulse command UX", () => { it("adds and removes quoted paths with spaces", async () => { const root = cwd(); write(root, "my file.md", "doc"); writeConfig(root, { documents: [] }); const h = harness(root); expect( h.commands.get("pulse").getArgumentCompletions("add my"), ).toContainEqual({ value: 'add "my file.md"', label: "my file.md" }); await h.commands .get("pulse") .handler('add "my file.md" keep concise', h.ctx); expect( JSON.parse(fs.readFileSync(path.join(root, ".pi/pulse.json"), "utf8")) .documents, ).toEqual([{ path: "my file.md", instruction: "keep concise" }]); await h.commands.get("pulse").handler('remove "my file.md"', h.ctx); expect( JSON.parse(fs.readFileSync(path.join(root, ".pi/pulse.json"), "utf8")) .documents, ).toEqual([]); }); it("reports missing auth instead of saying nothing to update", async () => { const root = cwd(); write(root, "README.md", "doc"); writeConfig(root, { documents: [{ path: "README.md" }] }); const h = harness(root); h.ctx.modelRegistry.getApiKeyAndHeaders = async () => ({ ok: false }); await h.commands.get("pulse").handler("force", h.ctx); expect( h.notifications.some( (n) => n.message.includes("missing auth") && n.level === "warning", ), ).toBe(true); expect( h.notifications.some((n) => n.message.includes("nothing to update")), ).toBe(false); }); it("does not expose terminal controls in completions", () => { const root = cwd(); write(root, "bad\u001b[31m.md", "doc"); writeConfig(root, { documents: [{ path: "bad\u001b[31m.md" }] }); const h = harness(root); const add = h.commands.get("pulse").getArgumentCompletions("add ") ?? []; expect(add.some((item: any) => String(item.value).includes("\u001b"))).toBe( false, ); expect(add.some((item: any) => String(item.label).includes("\u001b"))).toBe( false, ); const remove = h.commands.get("pulse").getArgumentCompletions("remove bad") ?? []; expect( remove.some((item: any) => String(item.value).includes("\u001b")), ).toBe(false); expect( remove.some((item: any) => String(item.label).includes("\u001b")), ).toBe(false); }); }); describe("pulse updater", () => { it("applies valid model proposals without injecting the main system prompt", async () => { const root = cwd(); write(root, "README.md", "old"); writeConfig(root, { documents: [{ path: "README.md" }] }); completionText = JSON.stringify({ updates: [{ path: "README.md", content: "new", summary: "refreshed" }], }); const h = harness(root); await h.commands.get("pulse").handler("force", h.ctx); expect(fs.readFileSync(path.join(root, "README.md"), "utf8")).toBe("new"); expect(h.events.has("before_agent_start")).toBe(false); expect( h.notifications.some((n) => n.message.includes("updated 1 doc")), ).toBe(true); }); it("rejects model proposals for untracked paths", async () => { const root = cwd(); write(root, "README.md", "old"); write(root, ".env", "secret"); writeConfig(root, { documents: [{ path: "README.md" }] }); completionText = JSON.stringify({ updates: [{ path: ".env", content: "stolen", summary: "bad" }], }); const h = harness(root); await h.commands.get("pulse").handler("force", h.ctx); expect(fs.readFileSync(path.join(root, ".env"), "utf8")).toBe("secret"); expect( h.notifications.some( (n) => n.message.includes("invalid update proposal") && n.level === "warning", ), ).toBe(true); }); it("retries invalid JSON before aborting", async () => { const root = cwd(); write(root, "README.md", "old"); writeConfig(root, { documents: [{ path: "README.md" }] }); completionTexts = [ "not json", JSON.stringify({ updates: [{ path: "README.md", content: "new", summary: "fixed json" }], }), ]; const h = harness(root); await h.commands.get("pulse").handler("force", h.ctx); expect(completionCalls).toBe(2); expect(fs.readFileSync(path.join(root, "README.md"), "utf8")).toBe("new"); }); it("supports confirm apply mode", async () => { const root = cwd(); write(root, "README.md", "old"); writeConfig(root, { apply: "confirm", documents: [{ path: "README.md" }] }); completionText = JSON.stringify({ updates: [{ path: "README.md", content: "new", summary: "needs review" }], }); const h = harness(root); h.setConfirmResult(false); await h.commands.get("pulse").handler("force", h.ctx); expect(fs.readFileSync(path.join(root, "README.md"), "utf8")).toBe("old"); expect(h.confirmations[0]).toContain("Apply 1 doc update"); expect(h.notifications.some((n) => n.message === "Pulse: skipped")).toBe( true, ); }); it("supports review apply mode", async () => { const root = cwd(); write(root, "README.md", "old"); writeConfig(root, { apply: "review", documents: [{ path: "README.md" }] }); completionText = JSON.stringify({ updates: [{ path: "README.md", content: "new", summary: "reviewed" }], }); const h = harness(root); h.setEditorResult("reviewed content"); await h.commands.get("pulse").handler("force", h.ctx); expect(h.editors).toEqual([{ title: "Pulse: README.md", prefill: "new" }]); expect(fs.readFileSync(path.join(root, "README.md"), "utf8")).toBe( "reviewed content", ); }); it("runs a ready auto-sync on agent_end without session-start noise", async () => { const realNow = Date.now; let now = 0; Date.now = () => now; try { const root = cwd(); write(root, "README.md", "old"); writeConfig(root, { documents: [{ path: "README.md" }] }); completionText = JSON.stringify({ updates: [{ path: "README.md", content: "new", summary: "auto" }], }); const h = harness(root); await h.events.get("session_start")({}, h.ctx); expect(h.notifications).toEqual([]); await h.events.get("tool_execution_end")( { toolName: "edit", isError: false }, h.ctx, ); now = 6 * 60 * 1000; await h.events.get("agent_end")({}, h.ctx); expect(fs.readFileSync(path.join(root, "README.md"), "utf8")).toBe("new"); expect( h.notifications.some((n) => n.message.includes("updated 1 doc")), ).toBe(true); expect(h.entries.at(-1)).toEqual({ type: "custom", customType: "pulse-state", data: { version: 1, lastRunAt: now, lastRunReason: "changes", lastResult: "updated 1", }, }); await h.events.get("session_shutdown")({}, h.ctx); } finally { Date.now = realNow; } }); it("restores persisted last status on session_start", async () => { const root = cwd(); write(root, "README.md", "old"); writeConfig(root, { documents: [{ path: "README.md" }] }); const h = harness(root); h.entries.push({ type: "custom", customType: "pulse-state", data: { version: 1, lastRunAt: 123, lastRunReason: "periodic", lastResult: "up to date", }, }); await h.events.get("session_start")({}, h.ctx); await h.commands.get("pulse").handler("status", h.ctx); expect( h.notifications.some((n) => n.message.includes("last: up to date (periodic)"), ), ).toBe(true); }); });