import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent"; import { createTestSession as createHarnessSession, type TestSession, } from "@marcfargas/pi-test-harness"; import { afterEach, describe, expect, it, vi } from "vitest"; import { WorkflowSpecSchema } from "../spec.ts"; let t: TestSession | undefined; let root: string | undefined; afterEach(() => { t?.dispose(); if (root) rmSync(root, { recursive: true, force: true }); t = undefined; root = undefined; }); function ultraPath(): string { return fileURLToPath(new URL("../index.ts", import.meta.url)); } async function createTestSession(options: { extensions: string[]; cwd?: string; }): Promise { if (options.cwd) return createHarnessSession(options); root = mkdtempSync(join(tmpdir(), "ultra-harness-")); mkdirSync(join(root, ".pi"), { recursive: true }); writeFileSync( join(root, ".pi", "settings.json"), JSON.stringify({ ultra: { auto_enable: false } }), ); return createHarnessSession({ ...options, cwd: root }); } function saveWorkflow( session: TestSession, name: string, dynamicExtension?: string, ): void { const directory = join(session.cwd, ".pi", "workflows"); mkdirSync(directory, { recursive: true }); writeFileSync( join(directory, `${name}.json`), `${JSON.stringify({ name, phases: [ { id: "work", kind: "single", step: { summary: "Work", prompt: "Work", ...(dynamicExtension ? { dynamicExtensions: [dynamicExtension] } : {}), }, }, ], })}\n`, ); } function driveOverlay( ctx: ExtensionCommandContext, interact?: (overlay: { handleInput(data: string): void }) => void, ): void { Object.assign(ctx.ui, { custom: vi.fn( async ( factory: ( host: unknown, theme: unknown, keybindings: unknown, done: (value: unknown) => void, ) => { handleInput(data: string): void }, ) => new Promise((resolve) => { const overlay = factory( { requestRender: vi.fn() }, {}, { matches: () => false }, resolve, ); interact?.(overlay); }), ), }); } describe("ultra extension", () => { it("loads only the command and renderer in the real Pi runtime", async () => { const indexPath = ultraPath(); t = await createTestSession({ extensions: [indexPath] }); const [extension] = t.session.extensionRunner.extensions; expect(extension.path).toBe(indexPath); expect(extension.tools.has("run_workflow")).toBe(false); expect(readFileSync(indexPath, "utf8")).toContain( 'import("./implementation.ts")', ); expect(extension.commands.has("ultra")).toBe(true); expect(extension.commands.has("ultra-runs")).toBe(false); }); it("auto-enables the workflow tool when configured", async () => { root = mkdtempSync(join(tmpdir(), "ultra-auto-enable-")); mkdirSync(join(root, ".pi"), { recursive: true }); writeFileSync( join(root, ".pi", "settings.json"), JSON.stringify({ ultra: { auto_enable: true } }), ); t = await createTestSession({ cwd: root, extensions: [ultraPath()] }); const [extension] = t.session.extensionRunner.extensions; expect(extension.tools.has("run_workflow")).toBe(true); expect(t.session.getActiveToolNames()).toContain("run_workflow"); expect(t.session.systemPrompt).toContain("- run_workflow:"); }); it("completes subcommands first and saved workflows below run", async () => { t = await createTestSession({ extensions: [ultraPath()] }); const [extension] = t.session.extensionRunner.extensions; const complete = extension.commands.get("ultra").getArgumentCompletions; expect(extension.tools.has("run_workflow")).toBe(false); const subcommands = await complete(""); const workflows = await complete("run "); expect(extension.tools.has("run_workflow")).toBe(true); expect(t.session.getActiveToolNames()).not.toContain("run_workflow"); expect(subcommands.map((item: { value: string }) => item.value)).toEqual([ "exec", "run", ]); expect(workflows.map((item: { value: string }) => item.value)).toEqual( expect.arrayContaining(["run research", "run review"]), ); }); it("activates the workflow tool and notifies without starting a turn", async () => { t = await createTestSession({ extensions: [ultraPath()] }); const [extension] = t.session.extensionRunner.extensions; const beforeMessages = t.session.messages.length; const beforeNotifications = t.events.uiCallsFor("notify").length; expect(t.session.getActiveToolNames()).not.toContain("run_workflow"); expect(t.session.systemPrompt).not.toContain("- run_workflow:"); await extension.commands .get("ultra") .handler("", t.session.extensionRunner.createCommandContext()); expect(t.session.getActiveToolNames()).toContain("run_workflow"); expect(t.session.systemPrompt).toContain( "- run_workflow: Run one complete saved or inline multi-agent workflow and return its validated aggregate result.", ); expect(t.session.systemPrompt).toContain( "- Use run_workflow only when independent parallel work, staged agent handoffs, isolated specialist contexts, or a reusable purpose-built dynamic extension materially improve the result; otherwise work directly.", ); expect(t.session.systemPrompt).toContain( "- Use run_workflow builder phases for dynamic-extension discovery, creation, improvement, stale validation, or repair; known validated names may load directly in consumer steps.", ); expect(t.session.messages).toHaveLength(beforeMessages); const notifications = t.events.uiCallsFor("notify"); expect(notifications).toHaveLength(beforeNotifications + 1); expect(notifications.at(-1)?.args).toEqual([ "ultra: run_workflow tool enabled.", "info", ]); }); it("sends exec instructions as the visible user message that starts the turn", async () => { t = await createTestSession({ extensions: [ultraPath()] }); const [extension] = t.session.extensionRunner.extensions; const sendUserMessage = vi .spyOn(t.session, "sendUserMessage") .mockResolvedValue(); const beforeNotifications = t.events.uiCallsFor("notify").length; await extension.commands .get("ultra") .handler( "exec inspect this failure once", t.session.extensionRunner.createCommandContext(), ); expect(t.session.getActiveToolNames()).toContain("run_workflow"); expect(sendUserMessage).toHaveBeenCalledOnce(); const prompt = sendUserMessage.mock.calls[0]?.[0]; expect(prompt).toEqual(expect.any(String)); expect(prompt).toContain("# Authoring ultra workflows"); expect(prompt).toContain("# Ultra workflow spec reference"); expect(prompt).toContain("# User request\n\ninspect this failure once"); expect(prompt).not.toContain("The workflow tool is now available"); expect(t.events.uiCallsFor("notify")).toHaveLength(beforeNotifications); }); it("renders workflow progress as an overlay without replacing session content", async () => { t = await createTestSession({ extensions: [ultraPath()] }); const [extension] = t.session.extensionRunner.extensions; const ctx = t.session.extensionRunner.createCommandContext(); const custom = vi.fn().mockResolvedValue(null); Object.assign(ctx.ui, { custom }); await extension.commands .get("ultra") .handler("run review inspect scrolling", ctx); expect(custom).toHaveBeenCalledOnce(); expect(custom.mock.calls[0][1]).toEqual({ overlay: true, overlayOptions: { anchor: "bottom-left", width: "100%", maxHeight: "100%", }, }); }); it("surfaces workflow errors instead of misreporting them as user aborts", async () => { t = await createTestSession({ extensions: [ultraPath()] }); saveWorkflow(t, "runtime-error", "missing-live-capability"); const [extension] = t.session.extensionRunner.extensions; const ctx = t.session.extensionRunner.createCommandContext(); driveOverlay(ctx); await extension.commands.get("ultra").handler("run runtime-error", ctx); expect(t.events.uiCallsFor("notify").at(-1)?.args).toEqual([ 'ultra: dynamic extension "missing-live-capability" has no canonical revision. Run a builder with all four dynamic-extension tools.', "error", ]); }); it("reports confirmed whole-run cancellation as aborted while retaining its aggregate", async () => { t = await createTestSession({ extensions: [ultraPath()] }); saveWorkflow(t, "cancelled-run"); const [extension] = t.session.extensionRunner.extensions; const ctx = t.session.extensionRunner.createCommandContext(); driveOverlay(ctx, (overlay) => { overlay.handleInput("\u001b"); overlay.handleInput("\u001b"); }); await extension.commands.get("ultra").handler("run cancelled-run", ctx); expect(t.events.uiCallsFor("notify").at(-1)?.args).toEqual([ 'ultra: "cancelled-run" aborted.', "warning", ]); expect( t.events .uiCallsFor("notify") .some((call) => String(call.args[0]).includes("complete")), ).toBe(false); expect( t.session.messages.some( (message) => "customType" in message && message.customType === "ultra-result", ), ).toBe(true); }); it("refuses an unknown static sub-agent extension", async () => { t = await createTestSession({ extensions: [ultraPath()] }); mkdirSync(join(t.cwd, ".pi"), { recursive: true }); writeFileSync( join(t.cwd, ".pi", "settings.json"), JSON.stringify({ ultra: { subagentExtensions: ["missing-extension"] }, }), ); const [extension] = t.session.extensionRunner.extensions; await extension.commands .get("ultra") .handler("run review", t.session.extensionRunner.createCommandContext()); expect(t.events.uiCallsFor("notify").at(-1)?.args).toEqual([ "ultra: unknown sub-agent extension: missing-extension", "error", ]); }); it("starts research without knowing which extension supplies research tools", async () => { t = await createTestSession({ extensions: [ultraPath()] }); const [extension] = t.session.extensionRunner.extensions; const ctx = t.session.extensionRunner.createCommandContext(); const custom = vi.fn().mockResolvedValue(null); Object.assign(ctx.ui, { custom }); await extension.commands.get("ultra").handler("run research question", ctx); expect(custom).toHaveBeenCalledOnce(); expect( t.events .uiCallsFor("notify") .some((call) => String(call.args[0]).includes("unavailable tools")), ).toBe(false); }); it("discovers a workflow saved after the extension loaded without /reload", async () => { t = await createTestSession({ extensions: [ultraPath()] }); const [extension] = t.session.extensionRunner.extensions; const complete = () => extension.commands.get("ultra").getArgumentCompletions("run "); await complete(); const previousCwd = process.cwd(); try { process.chdir(t.cwd); const directory = join(t.cwd, ".pi", "workflows"); mkdirSync(directory, { recursive: true }); writeFileSync( join(directory, "fresh.json"), `${JSON.stringify({ name: "fresh", phases: [ { id: "p", kind: "single", step: { summary: "hi", prompt: "hi" } }, ], })}\n`, ); const items = await complete(); expect(items.map((item: { value: string }) => item.value)).toContain( "run fresh", ); } finally { process.chdir(previousCwd); } }); it("exposes the runtime workflow schema to tool callers", async () => { t = await createTestSession({ extensions: [ultraPath()] }); const [extension] = t.session.extensionRunner.extensions; await extension.commands.get("ultra").getArgumentCompletions(""); const tool = extension.tools.get("run_workflow").definition; const specSchema = tool.parameters.properties.spec; const stepSchema = specSchema.properties.phases.items.anyOf[0].properties.step; expect(tool.description).toBe( "Run one complete saved or inline Ultra multi-agent workflow. Use it when independent parallel work, staged agent handoffs, or isolated specialist contexts materially improve the result; otherwise work directly. It returns one aggregate of structured step results, validating each declared output schema.", ); expect(tool.promptSnippet).toBe( "Run one complete saved or inline multi-agent workflow and return its validated aggregate result.", ); expect(tool.promptGuidelines).toEqual([ "Use run_workflow only when independent parallel work, staged agent handoffs, isolated specialist contexts, or a reusable purpose-built dynamic extension materially improve the result; otherwise work directly.", "Use run_workflow builder phases for dynamic-extension discovery, creation, improvement, stale validation, or repair; known validated names may load directly in consumer steps.", "After run_workflow returns, synthesize its aggregate result into the user-facing response.", ]); expect(tool.parameters.properties.background).toBeUndefined(); expect(stepSchema.required).toContain("summary"); expect(stepSchema.properties.summary.description).toContain("progress-UI"); expect(JSON.parse(JSON.stringify(specSchema))).toEqual( JSON.parse(JSON.stringify(WorkflowSpecSchema)), ); }); });