From d78d6fc31b9a6207b1b6f3e4d2e789cbf8c2e6db Mon Sep 17 00:00:00 2001 From: alex Date: Mon, 30 Nov 2026 17:14:59 +0000 Subject: [PATCH] Add inline plans and the ultra tool --- src/config.ts | 14 ++ src/index.ts | 73 ++++++- src/persistence.ts | 2 +- src/runner.ts | 4 +- src/schemas.ts | 27 +++ src/ultra.ts | 113 +++++++++++ src/workflows.ts | 19 +- test/config.test.ts | 14 +- test/runner.test.ts | 5 +- test/ultra.test.ts | 453 ++++++++++++++++++++++++++++++++++++++++++++ 10 files changed, 713 insertions(+), 11 deletions(-) create mode 100644 src/ultra.ts create mode 100644 test/ultra.test.ts diff --git a/src/config.ts b/src/config.ts index a522cf9..e778f09 100644 --- a/src/config.ts +++ b/src/config.ts @@ -33,3 +33,17 @@ export function readMaxWorkflowItems(value: string | undefined): { value: number } return { value: parsed }; } + +/** + * Whether the ultra layer is enabled. + * + * `PI_SUBAGENT_ULTRA=off` removes the whole layer; anything else keeps the + * default (on), and an unrecognized value keeps the default with a warning. + * This is an extension-level switch, never a tool parameter the model controls. + */ +export function readUltraEnabled(value: string | undefined): { value: boolean; warning?: string } { + if (value === undefined || value === "") return { value: true }; + if (value === "on") return { value: true }; + if (value === "off") return { value: false }; + return { value: true, warning: `Invalid PI_SUBAGENT_ULTRA="${value}"; using on.` }; +} diff --git a/src/index.ts b/src/index.ts index f07ca9b..c71506d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -14,7 +14,7 @@ import { getAgentDir, } from "@earendil-works/pi-coding-agent"; import { Text } from "@earendil-works/pi-tui"; -import { readMaxWorkers, readMaxWorkflowItems } from "./config.ts"; +import { readMaxWorkers, readMaxWorkflowItems, readUltraEnabled } from "./config.ts"; import { SubagentDashboard } from "./dashboard.ts"; import { formatJob, formatJobList } from "./job-format.ts"; import { SubagentManager } from "./manager.ts"; @@ -29,10 +29,19 @@ import { renderSubagentResult, } from "./render.ts"; import { ProcessRunner } from "./runner.ts"; -import { SubagentJobsParams, SubagentParams, WorkflowParams, type SubagentParamsType, type WorkflowParamsType } from "./schemas.ts"; +import { + SubagentJobsParams, + SubagentParams, + UltraParams, + WorkflowParams, + type SubagentParamsType, + type UltraParamsType, + type WorkflowParamsType, +} from "./schemas.ts"; import { type JobSnapshot, type PreparedInvocation, type SubagentDetails, type SyncOutcome, type TaskRunner } from "./types.ts"; +import { formatUltraReviewCard, formatUltraStart, UltraDeclinedError } from "./ultra.ts"; import { formatWorkflowStart, parseWorkflowCommand, type WorkflowStartResult } from "./workflow.ts"; -import { loadWorkflow } from "./workflows.ts"; +import { loadWorkflow, parseInlineWorkflow } from "./workflows.ts"; function textResult(text: string, details?: unknown, isError?: boolean): AgentToolResult { return { content: [{ type: "text", text }], details, isError }; @@ -104,9 +113,10 @@ function jobResult(job: JobSnapshot): AgentToolResult<{ job: JobSnapshot }> { export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) { const workerConfig = readMaxWorkers(process.env.PI_SUBAGENT_MAX_WORKERS); const workflowItemsConfig = readMaxWorkflowItems(process.env.PI_SUBAGENT_WORKFLOW_MAX_ITEMS); + const ultraConfig = readUltraEnabled(process.env.PI_SUBAGENT_ULTRA); let currentContext: ExtensionContext | undefined; let activeDashboard: SubagentDashboard | undefined; - let configurationWarnings = [workerConfig.warning, workflowItemsConfig.warning].filter( + let configurationWarnings = [workerConfig.warning, workflowItemsConfig.warning, ultraConfig.warning].filter( (warning): warning is string => warning !== undefined, ); @@ -163,6 +173,32 @@ export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) { return manager.startWorkflow(prepared); } + /** + * The inline-plan start path. + * + * Parsing, validation, arg checks, caps, and project-agent confirmation all + * reuse the workflow path. Only the review card is ultra-specific: one + * confirmation after validation and before the manager creates a run, and + * only when the session has a UI. No UI (print/json) starts directly. + */ + async function startUltra( + request: Pick, + ctx: ExtensionContext, + ): Promise { + const effectiveCwd = path.resolve(ctx.cwd, request.cwd ?? "."); + const plan = parseInlineWorkflow(request.plan); + + const prepareContext: PrepareContext = { ...ctx, cwd: effectiveCwd }; + const prepared = await prepareWorkflowInvocation(plan, request.args ?? {}, prepareContext, { + approvedDirectories: approvedProjectDirs, + }); + if (prepareContext.hasUI) { + const card = formatUltraReviewCard(prepared); + if (!(await ctx.ui.confirm(card.title, card.message))) throw new UltraDeclinedError(plan.name); + } + return manager.startWorkflow(prepared); + } + pi.on("session_start", (_event, ctx) => { currentContext = ctx; manager.restore(extractJobSnapshots(ctx.sessionManager.getBranch())); @@ -335,6 +371,35 @@ export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) { }, }); + if (ultraConfig.value) { + pi.registerTool({ + name: "ultra", + label: "Ultra (inline plan)", + description: [ + "Author and start a one-off declarative workflow inline, in one call: a markdown plan with YAML frontmatter (name, description, optional args, steps) exactly like a workflow file, parsed by the same schema and validator and run by the same engine.", + "Use ultra when a task is larger than one agent can hold in context, when the same step must run across many items, when findings should be cross-checked by another agent before you see them, or when a one-off multi-step job needs fan-out and fan-in; use the workflow tool with a file under .pi/workflows when the plan is worth rerunning.", + "Plan shape: steps carry id, agent, task, optional needs, each ({steps..output}, fan-out over that output's nonblank lines), model, and cwd. The placeholders {args.}, {steps..output}, and {item} interpolate when a step is released. Declared args are all required and unknown args are rejected. Loops and conditionals are not expressible: chain separate runs instead. Authoring guidance lives in the workflow-authoring skill; read it rather than guessing field names.", + "Shapes the engine expresses well: fan-out then fan-in (each-step, then a step that needs it), adversarial verification (a verifier step that needs the producer), generate-and-filter (parallel producers, then a filter step), and a pre-expanded tournament bracket. Classify-and-act and loop-until-done are not expressible in one plan; run per-class or per-iteration plans from the parent. For a large run, start with a small slice first.", + "Validation is identical to file plans and happens before anything starts: structure, step-output references, declared arguments, the 64-step cap, the 256-children-per-run cap, and every step agent and cwd. Project-local agents referenced by an inline plan still hit the existing project-agent confirmation.", + "With a UI, one review card per start follows validation and precedes the run: it shows the plan, every step with its needs and fan-out source, the child-count estimate against the caps, and every named agent with its user or project source. Declining spawns nothing. No-UI (print/json) sessions never prompt and start directly. Review policy is the extension's, never a tool parameter.", + "Returns the run id and expanded plan; the run is an ordinary async job. Retrieve it with subagent_jobs { action: \"get\" | \"wait\", jobId }. Results are pull-based: completion never starts an automatic model turn. Children of an ultra run cannot dispatch further agents or runs. The run's journal records the plan with source \"inline\" and is its only persisted copy.", + ].join(" "), + parameters: UltraParams, + async execute(_toolCallId, params, _signal, _onUpdate, ctx) { + try { + const started = await startUltra(params, ctx); + return { content: [{ type: "text", text: formatUltraStart(started) }], details: started }; + } catch (error) { + return textResult(error instanceof Error ? error.message : String(error), undefined, true); + } + }, + renderResult(result) { + const text = result.content[0]; + return new Text(text?.type === "text" ? text.text : "(no output)", 0, 0); + }, + }); + } + async function showSubagents(ctx: ExtensionContext, jobId?: string): Promise { if (ctx.mode !== "tui") { ctx.ui.notify(jobId ? formatJob(manager.get(jobId)) : formatJobList(manager.list()), "info"); diff --git a/src/persistence.ts b/src/persistence.ts index e9d7b2c..cd21edf 100644 --- a/src/persistence.ts +++ b/src/persistence.ts @@ -96,7 +96,7 @@ function validPlan(value: unknown): boolean { return typeof value.name === "string" && typeof value.description === "string" && Array.isArray(value.args) && value.args.every((arg) => typeof arg === "string") - && (value.source === "user" || value.source === "project") + && (value.source === "user" || value.source === "project" || value.source === "inline") && typeof value.filePath === "string" && Array.isArray(value.steps) && value.steps.every(validPlanStep); } diff --git a/src/runner.ts b/src/runner.ts index 3e82933..08f6379 100644 --- a/src/runner.ts +++ b/src/runner.ts @@ -23,8 +23,8 @@ import { const DEFAULT_KILL_GRACE_MS = 5000; const DEFAULT_STDERR_LIMIT_BYTES = 64 * 1024; -/** Child sessions never delegate: no nested subagents and no nested workflow runs. */ -const EXCLUDED_CHILD_TOOLS = "subagent*,workflow"; +/** Child sessions never delegate: no nested subagents, workflow runs, or inline ultra runs. */ +const EXCLUDED_CHILD_TOOLS = "subagent*,workflow,ultra"; export interface ProcessInvocation { command: string; diff --git a/src/schemas.ts b/src/schemas.ts index c37d763..76c1cc7 100644 --- a/src/schemas.ts +++ b/src/schemas.ts @@ -115,3 +115,30 @@ export const WorkflowParams = Type.Object( ); export type WorkflowParamsType = Static; + +/** + * Parameters for the inline-plan start surface. + * + * `plan` is the same markdown document a workflow file is; `args` is validated + * against the plan's declared args exactly like a workflow start. Trust policy + * (review card, kill switch) lives in extension code, never here. + */ +export const UltraParams = Type.Object( + { + plan: Type.String({ + description: + "Inline workflow plan: markdown with YAML frontmatter (name, description, optional args, steps). The body is ignored.", + }), + args: Type.Optional( + Type.Record(Type.String(), Type.String(), { + description: 'Plan arguments as string key/value pairs, validated against the plan\'s declared args.', + }), + ), + cwd: Type.Optional( + Type.String({ description: "Working directory for the run and its steps. Default: the session cwd." }), + ), + }, + { description: "Start an inline declarative workflow run." }, +); + +export type UltraParamsType = Static; diff --git a/src/ultra.ts b/src/ultra.ts new file mode 100644 index 0000000..b5532ff --- /dev/null +++ b/src/ultra.ts @@ -0,0 +1,113 @@ +/** + * Inline-plan surface: the review card and the start result. + * + * The plan itself is parsed by the file-plan parser (`workflows.ts`), so the + * ultra tool adds policy and presentation only. Nothing here spawns a child or + * touches the manager; `index.ts` owns the start path. + */ + +import { readMaxWorkflowItems } from "./config.ts"; +import type { PreparedWorkflowInvocation, WorkflowStartResult } from "./workflow.ts"; +import { MAX_EXPANDED_CHILDREN, MAX_WORKFLOW_STEPS } from "./workflows.ts"; + +/** Thrown when the user declines the review card for an inline plan. */ +export class UltraDeclinedError extends Error { + readonly planName: string; + + constructor(planName: string) { + super(`Canceled: inline plan "${planName}" not approved.`); + this.name = "UltraDeclinedError"; + this.planName = planName; + } +} + +export interface UltraReviewCard { + title: string; + message: string; +} + +export interface UltraReviewOptions { + maxItemsPerEach?: number; + maxExpandedChildren?: number; +} + +function plural(count: number, singular: string, pluralForm = `${singular}s`): string { + return `${count} ${count === 1 ? singular : pluralForm}`; +} + +/** + * The pre-run review surface for an inline plan. + * + * Files have diffs; an inline plan has this card. It shows exactly what will + * run — every step, its needs and fan-out source, the child-count estimate + * against the caps, and every named agent with its user/project source. + */ +export function formatUltraReviewCard( + prepared: PreparedWorkflowInvocation, + options: UltraReviewOptions = {}, +): UltraReviewCard { + const steps = prepared.workflow.steps; + const maxItemsPerEach = + options.maxItemsPerEach ?? readMaxWorkflowItems(process.env.PI_SUBAGENT_WORKFLOW_MAX_ITEMS).value; + const maxExpandedChildren = options.maxExpandedChildren ?? MAX_EXPANDED_CHILDREN; + + const fanOutSteps = steps.filter((step) => step.each !== undefined).length; + const fixedSteps = steps.length - fanOutSteps; + const minimumChildren = fixedSteps + fanOutSteps; + const maximumChildren = fixedSteps + fanOutSteps * maxItemsPerEach; + + const lines = [ + `Inline plan "${prepared.workflow.plan.name}" — ${prepared.workflow.plan.description}`, + "", + `Steps (${steps.length} of ${MAX_WORKFLOW_STEPS} max):`, + ]; + for (const step of steps) { + const needs = step.needs.length > 0 ? step.needs.join(", ") : "none"; + const each = step.each !== undefined ? `; each: {steps.${step.each}.output}` : ""; + lines.push(`- ${step.id} (${step.prepared.agent.name}) — needs: ${needs}${each}`); + } + + lines.push(""); + if (fanOutSteps === 0) { + lines.push( + `Children: ${maximumChildren} (caps: ${maxItemsPerEach} items per each-step, ${maxExpandedChildren} children per run).`, + ); + } else { + lines.push( + `Children: ${minimumChildren}–${maximumChildren} estimated (${plural(fixedSteps, "fixed step")} + ${plural(fanOutSteps, "fan-out step")} × up to ${maxItemsPerEach} items). Caps: ${maxItemsPerEach} items per each-step, ${maxExpandedChildren} children per run.`, + ); + if (maximumChildren > maxExpandedChildren) { + lines.push( + `This plan can exceed the ${maxExpandedChildren}-child run cap once its fan-outs expand; the run fails before those children spawn.`, + ); + } + } + + lines.push("", "Agents:"); + const agents = new Set(); + for (const step of steps) { + agents.add(`${step.prepared.agent.name} (${step.prepared.agent.source})`); + } + for (const agent of agents) lines.push(`- ${agent}`); + + return { title: `Run inline plan "${prepared.workflow.plan.name}"?`, message: lines.join("\n") }; +} + +/** Human-readable start result for an inline-plan run. */ +export function formatUltraStart(result: WorkflowStartResult): string { + const lines = [ + `Started ultra run ${result.id} (${result.job.status}).`, + `Inline plan: ${result.plan.name} — ${result.plan.description}`, + `Steps (${result.plan.steps.length}):`, + ]; + for (const step of result.plan.steps) { + const needs = step.needs.length > 0 ? ` needs ${step.needs.join(", ")}` : ""; + const each = step.each !== undefined ? ` each {steps.${step.each}.output}` : ""; + lines.push(`- ${step.id} (${step.agent})${needs}${each}`); + } + lines.push( + `Use subagent_jobs { action: "get" | "wait", jobId: "${result.id}" } to retrieve it.`, + `The run's journal (plan source "inline") is the only persisted copy of this plan.`, + ); + return lines.join("\n"); +} diff --git a/src/workflows.ts b/src/workflows.ts index a6a7050..ff8c702 100644 --- a/src/workflows.ts +++ b/src/workflows.ts @@ -17,9 +17,16 @@ import { readMaxWorkflowItems } from "./config.ts"; export const MAX_WORKFLOW_STEPS = 64; export const MAX_EXPANDED_CHILDREN = 256; -export type WorkflowSource = "user" | "project"; +/** + * Where a plan came from. `inline` plans are authored at run time and have no + * file; their stable `filePath` below is provenance, not a path to read. + */ +export type WorkflowSource = "user" | "project" | "inline"; export type WorkflowScope = "user" | "project" | "both"; +/** Stable provenance literal for a plan with no file behind it. */ +export const INLINE_WORKFLOW_FILE_PATH = "ultra:inline"; + export interface WorkflowStep { id: string; agent: string; @@ -373,6 +380,16 @@ export function parseWorkflow(content: string, options: ParseWorkflowOptions): W return { name: rawName, description, args: declaredArgs, steps, source, filePath }; } +/** + * Parse a model-authored inline plan through the file-plan parser. + * + * One schema, one validator: the only difference from a file plan is the + * `source` provenance and the stable non-file `filePath` used in errors. + */ +export function parseInlineWorkflow(plan: string): WorkflowPlan { + return parseWorkflow(plan, { source: "inline", filePath: INLINE_WORKFLOW_FILE_PATH }); +} + function isDirectory(candidate: string): boolean { try { return fs.statSync(candidate).isDirectory(); diff --git a/test/config.test.ts b/test/config.test.ts index 3ce6616..95953e7 100644 --- a/test/config.test.ts +++ b/test/config.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { readMaxWorkflowItems, readMaxWorkers } from "../src/config.ts"; +import { readMaxWorkflowItems, readMaxWorkers, readUltraEnabled } from "../src/config.ts"; test("worker configuration defaults to 16 and accepts only integers from 1 through 32", () => { assert.deepEqual(readMaxWorkers(undefined), { value: 16 }); @@ -25,3 +25,15 @@ test("workflow item configuration defaults to 32 and accepts only integers from assert.match(result.warning ?? "", /PI_SUBAGENT_WORKFLOW_MAX_ITEMS/); } }); + +test("ultra defaults on, disables only on an explicit off, and warns on invalid values", () => { + assert.deepEqual(readUltraEnabled(undefined), { value: true }); + assert.deepEqual(readUltraEnabled(""), { value: true }); + assert.deepEqual(readUltraEnabled("on"), { value: true }); + assert.deepEqual(readUltraEnabled("off"), { value: false }); + for (const invalid of ["0", "false", "OFF", " maybe", "disabled"]) { + const result = readUltraEnabled(invalid); + assert.equal(result.value, true); + assert.match(result.warning ?? "", /PI_SUBAGENT_ULTRA/); + } +}); diff --git a/test/runner.test.ts b/test/runner.test.ts index 8262f85..f9ac902 100644 --- a/test/runner.test.ts +++ b/test/runner.test.ts @@ -206,7 +206,7 @@ test("child arguments exclude subagent and workflow tools and do not inherit thi "-p", "--no-session", "--exclude-tools", - "subagent*,workflow", + "subagent*,workflow,ultra", ]); assert.equal(captured[captured.indexOf("--model") + 1], "agent-model"); assert.equal(captured.includes("--thinking"), false); @@ -244,7 +244,7 @@ test("child arguments inherit the dispatch model and thinking only without an ex "-p", "--no-session", "--exclude-tools", - "subagent*,workflow", + "subagent*,workflow,ultra", ]); assert.equal(captured[captured.indexOf("--model") + 1], "dispatch-model"); assert.equal(captured[captured.indexOf("--thinking") + 1], "high"); @@ -274,6 +274,7 @@ test("child arguments omit optional model and thinking flags when nothing is con const excluded = captured[captured.indexOf("--exclude-tools") + 1].split(","); assert.ok(excluded.includes("subagent*"), "child cannot dispatch subagents"); assert.ok(excluded.includes("workflow"), "child cannot start workflow runs"); + assert.ok(excluded.includes("ultra"), "child cannot start inline ultra runs"); assert.equal(captured.at(-1), "Task: do the thing"); }); diff --git a/test/ultra.test.ts b/test/ultra.test.ts new file mode 100644 index 0000000..97b17bc --- /dev/null +++ b/test/ultra.test.ts @@ -0,0 +1,453 @@ +import assert from "node:assert/strict"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import test, { after } from "node:test"; +import type { AgentToolResult } from "@earendil-works/pi-agent-core"; +import type { ExtensionAPI, ExtensionToolContext } from "@earendil-works/pi-coding-agent"; +import fc from "fast-check"; +import { Value } from "typebox/value"; +import registerExtension from "../src/index.ts"; +import { extractWorkflowJournals, persistedWorkflowJournal, WORKFLOW_RUN_ENTRY } from "../src/persistence.ts"; +import { UltraParams } from "../src/schemas.ts"; +import type { WorkflowStartResult } from "../src/workflow.ts"; +import { + INLINE_WORKFLOW_FILE_PATH, + WorkflowValidationError, + parseInlineWorkflow, + parseWorkflow, +} from "../src/workflows.ts"; +import { FakeRunner } from "./helpers.ts"; + +const tempRoots: string[] = []; + +after(() => { + for (const root of tempRoots) fs.rmSync(root, { recursive: true, force: true }); +}); + +type Execute = ( + id: string, + params: any, + signal?: AbortSignal, + onUpdate?: unknown, + ctx?: ExtensionToolContext, +) => Promise>; + +interface Confirmation { + title: string; + message: string; +} + +interface HarnessOptions { + trusted?: boolean; + confirmResult?: boolean | boolean[]; +} + +async function harness(options: HarnessOptions = {}) { + const cwd = await fs.promises.mkdtemp(path.join(os.tmpdir(), "pi-subagent-ultra-")); + tempRoots.push(cwd); + const agentsDir = path.join(cwd, ".pi", "agents"); + await fs.promises.mkdir(agentsDir, { recursive: true }); + await fs.promises.writeFile( + path.join(agentsDir, "scout.md"), + "---\nname: scout\ndescription: Test project agent\n---\nTest prompt\n", + ); + + const runner = new FakeRunner(); + const tools = new Map(); + const events = new Map unknown>(); + const entries: unknown[] = []; + const notifications: string[] = []; + const confirmations: Confirmation[] = []; + const confirmAnswers = Array.isArray(options.confirmResult) ? [...options.confirmResult] : undefined; + const confirmFallback = typeof options.confirmResult === "boolean" ? options.confirmResult : true; + + const pi = { + registerTool(definition: { name: string; description?: string; execute: Execute }) { + tools.set(definition.name, definition); + }, + registerCommand() {}, + registerEntryRenderer() {}, + on(name: string, handler: (event: any, ctx: ExtensionToolContext) => unknown) { + events.set(name, handler); + }, + appendEntry(type: string, data: unknown) { + entries.push({ type: "custom", customType: type, data }); + }, + }; + registerExtension(pi as unknown as ExtensionAPI, runner); + + const ctx = { + cwd, + mode: "tui", + hasUI: true, + model: undefined, + thinkingLevel: undefined, + isProjectTrusted: () => options.trusted ?? true, + ui: { + confirm: async (title: string, message: string) => { + confirmations.push({ title, message }); + return confirmAnswers && confirmAnswers.length > 0 ? confirmAnswers.shift()! : confirmFallback; + }, + notify: (text: string) => { + notifications.push(text); + }, + setStatus: () => {}, + }, + sessionManager: { + getBranch: () => [], + getSessionId: () => "test-session", + }, + } as unknown as ExtensionToolContext; + + return { cwd, runner, tools, events, entries, notifications, confirmations, ctx }; +} + +function textOf(result: AgentToolResult): string { + return result.content[0]?.type === "text" ? result.content[0].text : ""; +} + +interface PlanOptions { + name?: string; + description?: string; + args?: string[]; +} + +function inlinePlan(steps: Array>, options: PlanOptions = {}): string { + const frontmatter = { + name: options.name ?? "test-plan", + description: options.description ?? "Test inline plan", + args: options.args ?? [], + steps, + }; + return `---\n${JSON.stringify(frontmatter, null, 2)}\n---\n\nInline notes.\n`; +} + +const SKETCH = `--- +name: audit-routes +description: Audit every route handler for missing auth checks +args: [glob] +steps: + - id: scan + agent: scout + task: List files matching {args.glob} under src/routes/, one per line. + - id: audit + agent: reviewer + each: {steps.scan.output} + task: Audit {item} for missing authentication checks. + needs: [scan] + model: sonnet + cwd: src/routes + - id: merge + agent: merger + task: Merge these findings into one ranked list: {steps.audit.output} + needs: [audit] +--- +Optional prose notes. +`; + +test("inline and file sources produce the same plan modulo provenance", () => { + const filePlan = parseWorkflow(SKETCH, { source: "project", filePath: "/repo/.pi/workflows/audit-routes.md" }); + const inline = parseInlineWorkflow(SKETCH); + assert.deepEqual(inline, { + ...filePlan, + source: "inline", + filePath: INLINE_WORKFLOW_FILE_PATH, + }); + assert.equal(inline.source, "inline"); + assert.equal(inline.filePath, "ultra:inline"); +}); + +test("property: identical content parses identically inline and from a file, modulo source/filePath", () => { + fc.assert( + fc.property(fc.oneof(fc.constant(SKETCH), fc.string({ maxLength: 400 })), (content) => { + let filePlan; + try { + filePlan = parseWorkflow(content, { source: "project", filePath: "/repo/.pi/workflows/test.md" }); + } catch (error) { + assert.ok(error instanceof WorkflowValidationError, `unexpected error: ${String(error)}`); + const fileMessage = error.message; + assert.throws( + () => parseInlineWorkflow(content), + (inlineError: unknown) => { + assert.ok(inlineError instanceof WorkflowValidationError); + assert.equal( + inlineError.message, + fileMessage.replace("/repo/.pi/workflows/test.md", INLINE_WORKFLOW_FILE_PATH), + ); + return true; + }, + ); + return; + } + + assert.deepEqual(parseInlineWorkflow(content), { + ...filePlan, + source: "inline", + filePath: INLINE_WORKFLOW_FILE_PATH, + }); + }), + { numRuns: 150 }, + ); +}); + +test("the review card names every step, fan-out source, agent source, and the caps", async () => { + const previousAgentDir = process.env.PI_CODING_AGENT_DIR; + const h = await harness(); + try { + const userDir = path.join(h.cwd, "user-agent-dir"); + fs.mkdirSync(path.join(userDir, "agents"), { recursive: true }); + fs.writeFileSync( + path.join(userDir, "agents", "global.md"), + "---\nname: global\ndescription: Global agent\n---\nYou are global.\n", + "utf-8", + ); + process.env.PI_CODING_AGENT_DIR = userDir; + + const plan = inlinePlan( + [ + { id: "scan", agent: "global", task: "scan {args.glob}" }, + { id: "audit", agent: "scout", task: "audit {item}", each: "{steps.scan.output}", needs: ["scan"] }, + { id: "merge", agent: "global", task: "merge {steps.audit.output}", needs: ["audit"] }, + ], + { name: "audit-routes", description: "Audit every route handler", args: ["glob"] }, + ); + + const result = await h.tools.get("ultra")!.execute( + "ultra", + { plan, args: { glob: "src/**" } }, + undefined, + undefined, + h.ctx, + ); + assert.notEqual(result.isError, true); + assert.equal(h.confirmations.length, 1); + + const card = h.confirmations[0]; + assert.match(card.title, /Run inline plan "audit-routes"\?/); + assert.match(card.message, /Inline plan "audit-routes" — Audit every route handler/); + assert.match(card.message, /- scan \(global\) — needs: none/); + assert.match(card.message, /- audit \(scout\) — needs: scan; each: \{steps\.scan\.output\}/); + assert.match(card.message, /- merge \(global\) — needs: audit/); + assert.match(card.message, /Children: 3–34 estimated \(2 fixed steps \+ 1 fan-out step × up to 32 items\)/); + assert.match(card.message, /Caps: 32 items per each-step, 256 children per run/); + assert.match(card.message, /Steps \(3 of 64 max\)/); + assert.match(card.message, /- global \(user\)/); + assert.match(card.message, /- scout \(project\)/); + + const started = result.details as WorkflowStartResult; + assert.equal(h.runner.calls.length, 1); + assert.equal(h.runner.calls[0].task.task, "scan src/**"); + const text = textOf(result); + assert.match(text, /Started ultra run job_\d+/); + assert.match(text, /Inline plan: audit-routes/); + assert.match(text, /The run's journal \(plan source "inline"\) is the only persisted copy of this plan\./); + assert.equal(h.entries.length, 0); + assert.ok(started.id); + } finally { + if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR; + else process.env.PI_CODING_AGENT_DIR = previousAgentDir; + await h.events.get("session_shutdown")?.({ type: "session_shutdown" }, h.ctx); + } +}); + +test("declining the review card returns an error and spawns nothing", async () => { + const h = await harness({ confirmResult: false }); + try { + const result = await h.tools.get("ultra")!.execute( + "ultra", + { plan: inlinePlan([{ id: "scan", agent: "scout", task: "scan" }]) }, + undefined, + undefined, + h.ctx, + ); + assert.equal(result.isError, true); + assert.match(textOf(result), /Canceled: inline plan "test-plan" not approved/); + assert.equal(h.confirmations.length, 1); + assert.equal(h.runner.calls.length, 0); + assert.equal(h.entries.length, 0); + } finally { + await fs.promises.rm(h.cwd, { recursive: true, force: true }); + } +}); + +test("no-UI sessions never prompt and start directly", async () => { + const h = await harness(); + try { + for (const mode of ["print", "json"]) { + const ctx = { ...h.ctx, hasUI: false, mode } as ExtensionToolContext; + const result = await h.tools.get("ultra")!.execute( + "ultra", + { plan: inlinePlan([{ id: "scan", agent: "scout", task: `scan in ${mode} mode` }]) }, + undefined, + undefined, + ctx, + ); + assert.notEqual(result.isError, true); + assert.equal(h.runner.calls.at(-1)?.task.task, `scan in ${mode} mode`); + } + assert.equal(h.confirmations.length, 0); + assert.equal(h.runner.calls.length, 2); + } finally { + await h.events.get("session_shutdown")?.({ type: "session_shutdown" }, h.ctx); + } +}); + +test("project agents referenced by an inline plan still hit the existing trust confirmation", async () => { + const h = await harness({ trusted: false, confirmResult: [true, true] }); + try { + const result = await h.tools.get("ultra")!.execute( + "ultra", + { plan: inlinePlan([{ id: "scan", agent: "scout", task: "scan" }]) }, + undefined, + undefined, + h.ctx, + ); + assert.notEqual(result.isError, true); + assert.equal(h.confirmations.length, 2); + assert.match(h.confirmations[0].message, /repo-controlled/); + assert.ok(h.confirmations[0].message.includes(path.join(h.cwd, ".pi", "agents"))); + assert.match(h.confirmations[1].title, /Run inline plan "test-plan"\?/); + assert.equal(h.runner.calls.length, 1); + } finally { + await h.events.get("session_shutdown")?.({ type: "session_shutdown" }, h.ctx); + } +}); + +test("declining project-agent trust aborts before the review card and any spawn", async () => { + const h = await harness({ trusted: false, confirmResult: [false] }); + try { + const result = await h.tools.get("ultra")!.execute( + "ultra", + { plan: inlinePlan([{ id: "scan", agent: "scout", task: "scan" }]) }, + undefined, + undefined, + h.ctx, + ); + assert.equal(result.isError, true); + assert.match(textOf(result), /not approved/); + assert.equal(h.confirmations.length, 1); + assert.equal(h.runner.calls.length, 0); + assert.equal(h.entries.length, 0); + } finally { + await fs.promises.rm(h.cwd, { recursive: true, force: true }); + } +}); + +test("malformed plans, unknown agents, argument violations, and cap violations fail before the card or any spawn", async () => { + const h = await harness(); + try { + const tooManySteps = inlinePlan( + Array.from({ length: 65 }, (_, index) => ({ id: `step_${index}`, agent: "scout", task: `task ${index}` })), + ); + const cases: Array<[string, Record, RegExp]> = [ + ["malformed", { plan: "no frontmatter here" }, /missing YAML frontmatter/], + ["unknown-agent", { plan: inlinePlan([{ id: "scan", agent: "ghost", task: "scan" }]) }, /Unknown agent: "ghost"/], + ["undeclared-arg", { plan: inlinePlan([{ id: "scan", agent: "scout", task: "scan {args.missing}" }]) }, /undeclared argument "missing"/], + ["missing-arg", { plan: inlinePlan([{ id: "scan", agent: "scout", task: "scan {args.glob}" }], { args: ["glob"] }) }, /missing required argument "glob"/], + ["unknown-arg", { plan: inlinePlan([{ id: "scan", agent: "scout", task: "scan {args.glob}" }], { args: ["glob"] }), args: { glob: "src/**", other: "x" } }, /unknown argument "other"/], + ["too-many-steps", { plan: tooManySteps }, /too many steps \(65\).*Max is 64/], + ]; + + for (const [label, request, expected] of cases) { + const result = await h.tools.get("ultra")!.execute("ultra", request, undefined, undefined, h.ctx); + assert.equal(result.isError, true, label); + assert.match(textOf(result), expected, label); + } + assert.equal(h.confirmations.length, 0); + assert.equal(h.runner.calls.length, 0); + assert.equal(h.entries.length, 0); + } finally { + await fs.promises.rm(h.cwd, { recursive: true, force: true }); + } +}); + +test("an inline-sourced run journals source inline and round-trips through the journal entry", async () => { + const h = await harness(); + try { + await h.events.get("session_start")?.({ type: "session_start", reason: "startup" }, h.ctx); + const result = await h.tools.get("ultra")!.execute( + "ultra", + { plan: inlinePlan([{ id: "scan", agent: "scout", task: "journal this run" }], { name: "journal-flow" }) }, + undefined, + undefined, + h.ctx, + ); + assert.notEqual(result.isError, true); + const started = result.details as WorkflowStartResult; + h.runner.complete("journal this run", "done"); + await new Promise((resolve) => setImmediate(resolve)); + const waited = await h.tools.get("subagent_jobs")!.execute( + "wait", + { action: "wait", jobId: started.id, timeoutSeconds: 1 }, + undefined, + undefined, + h.ctx, + ); + assert.equal((waited.details as any).job.status, "succeeded"); + + const journals = extractWorkflowJournals(h.entries); + assert.equal(journals.length, 1); + const journal = journals[0]; + assert.equal(journal.plan.source, "inline"); + assert.equal(journal.plan.filePath, INLINE_WORKFLOW_FILE_PATH); + assert.equal(journal.plan.name, "journal-flow"); + + const serialized = (entry: unknown) => JSON.parse(JSON.stringify(entry)); + const entry = serialized({ + type: "custom", + customType: WORKFLOW_RUN_ENTRY, + data: persistedWorkflowJournal("test-session", journal), + }); + assert.deepEqual(extractWorkflowJournals([entry]), [serialized(journal)]); + } finally { + await h.events.get("session_shutdown")?.({ type: "session_shutdown" }, h.ctx); + } +}); + +test("PI_SUBAGENT_ULTRA=off prevents ultra registration while the workflow surface stays", async () => { + const previous = process.env.PI_SUBAGENT_ULTRA; + process.env.PI_SUBAGENT_ULTRA = "off"; + const h = await harness(); + try { + assert.equal(h.tools.has("ultra"), false); + assert.equal(h.tools.has("workflow"), true); + } finally { + if (previous === undefined) delete process.env.PI_SUBAGENT_ULTRA; + else process.env.PI_SUBAGENT_ULTRA = previous; + } +}); + +test("an invalid PI_SUBAGENT_ULTRA value warns and keeps the default on", async () => { + const previous = process.env.PI_SUBAGENT_ULTRA; + process.env.PI_SUBAGENT_ULTRA = "sometimes"; + const h = await harness(); + try { + assert.equal(h.tools.has("ultra"), true); + await h.events.get("session_start")?.({ type: "session_start", reason: "startup" }, h.ctx); + assert.equal(h.notifications.length, 1); + assert.match(h.notifications[0], /PI_SUBAGENT_ULTRA="sometimes"/); + assert.match(h.notifications[0], /using on/); + } finally { + if (previous === undefined) delete process.env.PI_SUBAGENT_ULTRA; + else process.env.PI_SUBAGENT_ULTRA = previous; + await fs.promises.rm(h.cwd, { recursive: true, force: true }); + } +}); + +test("the ultra tool exposes plan/args/cwd and a token-budgeted description", async () => { + const h = await harness(); + try { + const tool = h.tools.get("ultra"); + assert.ok(tool); + assert.ok((tool.description?.length ?? Number.POSITIVE_INFINITY) < 6000); + assert.ok((tool.description?.length ?? 0) > 1000); + assert.equal(Value.Check(UltraParams, { plan: "---\nname: x\ndescription: d\nsteps: []\n---" }), true); + assert.equal(Value.Check(UltraParams, { plan: "p", args: { glob: "src/**" }, cwd: "." }), true); + assert.equal(Value.Check(UltraParams, {}), false); + assert.equal(Value.Check(UltraParams, { plan: 1 }), false); + assert.equal(Value.Check(UltraParams, { plan: "p", args: { glob: 1 } }), false); + } finally { + await fs.promises.rm(h.cwd, { recursive: true, force: true }); + } +});