import { execFileSync } from "node:child_process"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import type { ExtensionAPI, ExtensionCommandContext } from "@selesai/code"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { ENV_AGENT_DIR } from "../../config.ts"; import implementGoalExtension from "./index.ts"; import { emptyRoster, saveRoster } from "./roster.ts"; function harness(cwd: string, idle = true) { const commands = new Map[1]>(); const sendUserMessage = vi.fn(); const handlers = new Map unknown>(); const pi = { on: (name: string, handler: (event: unknown, ctx: unknown) => unknown) => handlers.set(name, handler), registerCommand: (name: string, command: Parameters[1]) => commands.set(name, command), getCommands: () => [ { name: "skill:plan-todo", source: "skill", sourceInfo: { path: join(cwd, "plan-todo/SKILL.md") } }, { name: "skill:plan-todo-implementer", source: "skill", sourceInfo: { path: join(cwd, "implementer/SKILL.md") } }, ], sendUserMessage, }; const ui = { notify: vi.fn(), select: vi.fn().mockResolvedValue(undefined), input: vi.fn().mockResolvedValue(undefined), confirm: vi.fn().mockResolvedValue(false), }; const hasUI = true; const ctx = { cwd, isIdle: () => idle, isProjectTrusted: () => true, hasUI, ui, modelRegistry: { getAvailable: () => [{ provider: "test", id: "model" }] }, } as unknown as ExtensionCommandContext; implementGoalExtension(pi as unknown as ExtensionAPI); const fire = (name: string, event: unknown) => handlers.get(name)!(event, ctx); return { commands, sendUserMessage, ui, fire, run: (name: string, args = "") => commands.get(name)!.handler(args, ctx) }; } describe("implement-goal commands", () => { let cwd: string; let taskDir: string; beforeEach(() => { cwd = mkdtempSync(join(tmpdir(), "implement-goal-index-")); vi.stubEnv(ENV_AGENT_DIR, join(cwd, "agent")); taskDir = join(cwd, ".selesai", "tasks", "6-demo"); mkdirSync(taskDir, { recursive: true }); writeFileSync(join(taskDir, "plan.md"), "# Plan\n"); writeFileSync(join(taskDir, "todo.md"), "# Todo\n"); }); afterEach(() => { vi.unstubAllEnvs(); rmSync(cwd, { recursive: true, force: true }); }); it("/plan sends the skill request and warns without sending for empty arguments", async () => { const h = harness(cwd); expect([...h.commands.keys()]).toEqual(["plan", "implement", "implement-models"]); await h.run("plan", "add X"); expect(h.sendUserMessage).toHaveBeenCalledExactlyOnceWith("/skill:plan-todo add X", { expandPromptTemplates: true }); h.sendUserMessage.mockClear(); await h.run("plan", " "); expect(h.sendUserMessage).not.toHaveBeenCalled(); expect(h.ui.notify).toHaveBeenCalledWith("Usage: /plan ", "warning"); }); it("/implement opens the picker with no roster and cancels without writing or sending", async () => { const h = harness(cwd); await h.run("implement"); expect(h.ui.select).toHaveBeenCalledWith("Save model list to?", expect.any(Array)); expect(h.ui.notify).toHaveBeenCalledWith("Cancelled: /implement needs a model list.", "info"); expect(existsSync(join(taskDir, "goal-brief.md"))).toBe(false); expect(h.sendUserMessage).not.toHaveBeenCalled(); expect(existsSync(join(cwd, "agent", "implement-models.json"))).toBe(false); }); it("/implement 6 writes the brief and starts a goal with a saved roster", async () => { const roster = emptyRoster(); roster.sections.cheap.push({ difficulty: 3, provider: "test", model: "model", effort: "off", concurrency: 1 }); saveRoster(join(cwd, "agent", "implement-models.json"), roster); const h = harness(cwd); await h.run("implement", "6"); const brief = readFileSync(join(taskDir, "goal-brief.md"), "utf8"); expect(brief).toContain(join(cwd, "implementer/SKILL.md")); expect(brief).toContain("test | model | off | 1"); expect(h.sendUserMessage).toHaveBeenCalledExactlyOnceWith( expect.stringMatching(/^\/goal Implement the plan in /), { expandPromptTemplates: true }, ); expect(h.sendUserMessage.mock.calls[0][0]).toContain(join(taskDir, "goal-brief.md")); expect(h.ui.select).not.toHaveBeenCalled(); }); it("/implement while busy stops before writing, opening the picker, or sending", async () => { const h = harness(cwd, false); await h.run("implement"); expect(h.ui.notify).toHaveBeenCalledWith("Wait for the current response to finish, then run /implement again.", "warning"); expect(existsSync(join(taskDir, "goal-brief.md"))).toBe(false); expect(h.ui.select).not.toHaveBeenCalled(); expect(h.sendUserMessage).not.toHaveBeenCalled(); }); it("offers the squash once the /implement goal completes", async () => { const git = (...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); git("init", "-q", "-b", "main"); git("-c", "user.email=t@example.com", "-c", "user.name=T", "commit", "-q", "--allow-empty", "-m", "base"); const roster = emptyRoster(); roster.sections.cheap.push({ difficulty: 3, provider: "test", model: "model", effort: "off", concurrency: 1 }); saveRoster(join(cwd, "agent", "implement-models.json"), roster); const h = harness(cwd); await h.run("implement", "6"); const statePath = join(cwd, ".git", "selesai-implement-run.json"); expect(existsSync(statePath)).toBe(true); git("-c", "user.email=t@example.com", "-c", "user.name=T", "commit", "-q", "--allow-empty", "-m", "wip: T01"); const goal = h.sendUserMessage.mock.calls[0][0].replace(/^\/goal /, ""); const complete = (text: string, details = { goal }) => ({ toolName: "goal_complete", isError: false, result: { content: [{ type: "text", text }], details } }); h.fire("tool_execution_end", complete("Goal completion rejected: summary is empty.")); h.fire("tool_execution_end", complete("Goal complete: done", { goal: "another goal" })); await h.fire("agent_end", {}); expect(h.ui.select).not.toHaveBeenCalled(); h.fire("tool_execution_end", complete("Goal complete: done")); await h.fire("agent_end", {}); expect(h.ui.select).toHaveBeenCalledOnce(); expect(h.ui.select.mock.calls[0][0]).toContain("wip: T01"); expect(existsSync(statePath)).toBe(false); }); });