From 3aabfb2e636992083faf357aa08554e01439b5ea Mon Sep 17 00:00:00 2001 From: alex Date: Thu, 26 Nov 2026 19:18:02 +0000 Subject: [PATCH] Execute workflow plans as DAG jobs on the manager --- src/manager.ts | 192 ++++++++++++++++- src/prepare.ts | 196 ++++++++++++++---- src/runner.ts | 7 +- src/types.ts | 20 +- src/workflow.ts | 187 +++++++++++++++++ test/runner.test.ts | 23 +++ test/workflow-run.test.ts | 366 +++++++++++++++++++++++++++++++++ test/workflow-template.test.ts | 71 +++++++ 8 files changed, 1012 insertions(+), 50 deletions(-) create mode 100644 src/workflow.ts create mode 100644 test/workflow-run.test.ts create mode 100644 test/workflow-template.test.ts diff --git a/src/manager.ts b/src/manager.ts index fdff3a7..b65f692 100644 --- a/src/manager.ts +++ b/src/manager.ts @@ -2,6 +2,7 @@ import { truncateUtf8Head } from "./output.ts"; import { emptyUsage, isTerminalJob, + isTerminalTask, type InvocationMode, type JobSnapshot, type JobStatus, @@ -16,6 +17,13 @@ import { type SyncOutcome, type SyncRunOptions, } from "./types.ts"; +import { + interpolateWorkflowTask, + workflowRunConcurrency, + type PreparedWorkflowInvocation, + type WorkflowRunSpec, + type WorkflowStartResult, +} from "./workflow.ts"; const DEFAULT_MAX_WORKERS = 4; const DEFAULT_MAX_ACTIVE_JOBS = 64; @@ -29,6 +37,8 @@ interface InternalTask { snapshot: TaskSnapshot; controller?: AbortController; result?: RunResult; + /** A workflow step submitted to the FIFO, whether or not a worker picked it up yet. */ + submitted?: boolean; } interface Execution { @@ -43,6 +53,7 @@ interface Execution { errorMessage?: string; isAsync: boolean; cancelRequested: boolean; + workflow?: WorkflowRunSpec; onUpdate?: (outcome: SyncOutcome) => void; completion?: Promise; } @@ -73,6 +84,7 @@ function initialTask(prepared: PreparedTask, now: number): InternalTask { task: prepared.task, cwd: prepared.cwd, step: prepared.step, + stepId: prepared.stepId, status: "queued", exitCode: null, messages: [], @@ -86,6 +98,7 @@ function initialTask(prepared: PreparedTask, now: number): InternalTask { task: prepared.task, cwd: prepared.cwd, step: prepared.step, + stepId: prepared.stepId, status: "queued", exitCode: null, output: "", @@ -127,6 +140,25 @@ export class SubagentManager { } startAsync(request: PreparedInvocation): JobSnapshot { + return this.snapshot(this.startAsyncExecution(request)); + } + + /** + * Start a workflow run. Async-only: the caller gets the run id and the + * expanded plan immediately, then uses the ordinary job surface to wait. + */ + startWorkflow(request: PreparedWorkflowInvocation): WorkflowStartResult { + const concurrency = workflowRunConcurrency(this.maxWorkers); + if (concurrency < 1) { + throw new Error( + `Workflow runs require at least 2 workers (the per-run cap is maxWorkers - 1); PI_SUBAGENT_MAX_WORKERS is ${this.maxWorkers}.`, + ); + } + const execution = this.startAsyncExecution(request); + return { id: execution.id, job: this.snapshot(execution), plan: request.workflow.expandedPlan }; + } + + private startAsyncExecution(request: PreparedInvocation): Execution { if (!this.accepting) throw new Error("Subagent manager is shutting down"); const active = Array.from(this.jobs.values()).filter((job) => job.isAsync && !isTerminalJob(job.status)).length; if (active >= this.maxActiveJobs) throw new Error(`Too many active async jobs (${active}); maximum is ${this.maxActiveJobs}`); @@ -135,7 +167,7 @@ export class SubagentManager { execution.errorMessage = error instanceof Error ? error.message : String(error); this.finalize(execution, "failed"); }); - return this.snapshot(execution); + return execution; } async runSync(request: PreparedInvocation, options: SyncRunOptions = {}): Promise { @@ -330,6 +362,16 @@ export class SubagentManager { scheduled.task.result = this.cancelledResult(scheduled.task); scheduled.resolve(scheduled.task.result); } + if (execution.request.mode === "workflow") { + // Steps held back by the DAG or the run cap were never submitted to + // the FIFO; cancellation is still terminal for every one of them. + for (const task of execution.tasks) { + if (task.snapshot.status !== "queued") continue; + task.snapshot.status = "cancelled"; + task.snapshot.finishedAt = this.now(); + task.result = this.cancelledResult(task); + } + } for (const task of execution.tasks) { if (task.snapshot.status === "running") task.controller?.abort(); } @@ -345,6 +387,7 @@ export class SubagentManager { task: task.prepared.task, cwd: task.prepared.cwd, step: task.prepared.step, + stepId: task.prepared.stepId, exitCode: null, messages: [], output: "", @@ -368,6 +411,9 @@ export class SubagentManager { isAsync, cancelRequested: false, }; + if (request.mode === "workflow") { + execution.workflow = (request as PreparedWorkflowInvocation).workflow; + } this.activeExecutions.add(execution); if (isAsync) { this.jobs.set(id, execution); @@ -387,6 +433,10 @@ export class SubagentManager { this.finalize(execution, results.some(failed) ? "failed" : "succeeded"); return; } + if (execution.request.mode === "workflow") { + await this.executeWorkflow(execution); + return; + } let previous = ""; for (let index = 0; index < execution.request.tasks.length; index++) { if (index > 0) { @@ -410,6 +460,143 @@ export class SubagentManager { this.finalize(execution, "succeeded"); } + private async executeWorkflow(execution: Execution): Promise { + const spec = execution.workflow; + if (!spec) { + execution.errorMessage = "Workflow run is missing its plan"; + this.finalize(execution, "failed"); + return; + } + + const taskByStep = new Map(); + for (const task of execution.tasks) { + if (task.prepared.stepId) taskByStep.set(task.prepared.stepId, task); + } + const concurrency = workflowRunConcurrency(this.maxWorkers); + const inFlight = new Map>(); + + while (true) { + for (const [stepId] of inFlight) { + const task = taskByStep.get(stepId); + if (!task || isTerminalTask(task.snapshot.status)) inFlight.delete(stepId); + } + + if (isTerminalJob(execution.status)) return; + if (execution.cancelRequested) { + if (inFlight.size === 0) { + this.finalize(execution, "cancelled"); + return; + } + await Promise.race(inFlight.values()); + continue; + } + + if (this.propagateWorkflowSkips(execution, spec, taskByStep)) this.emit(execution); + + if (execution.tasks.every((task) => isTerminalTask(task.snapshot.status))) { + const outcome = execution.tasks.some((task) => task.snapshot.status === "failed") ? "failed" : "succeeded"; + this.finalize(execution, outcome); + return; + } + + if (this.releaseWorkflowSteps(execution, spec, taskByStep, inFlight, concurrency)) this.emit(execution); + + if (inFlight.size === 0) { + // A validated DAG plus a complete skip cascade always leaves a + // releasable or running step. Failing loudly beats hanging. + throw new Error(`Workflow run ${execution.id} stalled with no releasable steps.`); + } + + await Promise.race(inFlight.values()); + } + } + + private propagateWorkflowSkips( + execution: Execution, + spec: WorkflowRunSpec, + taskByStep: Map, + ): boolean { + let changed = false; + let pass = true; + while (pass) { + pass = false; + for (const step of spec.steps) { + const task = taskByStep.get(step.id); + if (!task || task.snapshot.status !== "queued" || task.submitted) continue; + const deadNeed = step.needs.some((need) => { + const needTask = taskByStep.get(need); + return Boolean( + needTask && + isTerminalTask(needTask.snapshot.status) && + needTask.snapshot.status !== "succeeded", + ); + }); + if (!deadNeed) continue; + const result = this.skippedResult(task); + task.snapshot.status = "skipped"; + task.snapshot.finishedAt = this.now(); + task.snapshot.errorMessage = result.errorMessage; + task.result = result; + changed = true; + pass = true; + } + } + return changed; + } + + private releaseWorkflowSteps( + execution: Execution, + spec: WorkflowRunSpec, + taskByStep: Map, + inFlight: Map>, + concurrency: number, + ): boolean { + let slots = concurrency - inFlight.size; + if (slots <= 0) return false; + let released = false; + + for (const step of spec.steps) { + if (slots <= 0) break; + const task = taskByStep.get(step.id); + if (!task || task.snapshot.status !== "queued" || task.submitted) continue; + const needsSucceeded = step.needs.every( + (need) => taskByStep.get(need)?.snapshot.status === "succeeded", + ); + if (!needsSucceeded) continue; + + const outputs = new Map(); + for (const need of step.needs) outputs.set(need, taskByStep.get(need)?.snapshot.output ?? ""); + const brief = interpolateWorkflowTask(step.template, { args: spec.args, outputs }); + task.prepared = { ...step.prepared, task: brief, stepId: step.id }; + task.snapshot.task = brief; + if (task.result) task.result = { ...task.result, task: brief, stepId: step.id }; + task.submitted = true; + inFlight.set(step.id, this.schedule(execution, task).then(() => undefined)); + released = true; + slots--; + } + + return released; + } + + private skippedResult(task: InternalTask): RunResult { + return { + agent: task.prepared.agent.name, + agentSource: task.prepared.agent.source, + task: task.prepared.task, + cwd: task.prepared.cwd, + step: task.prepared.step, + stepId: task.prepared.stepId, + exitCode: null, + messages: [], + output: "", + stderr: "", + usage: emptyUsage(), + status: "skipped", + errorMessage: "Skipped because a required step did not succeed", + }; + } + private schedule(execution: Execution, task: InternalTask): Promise { return new Promise((resolve) => { this.queue.push({ execution, task, resolve }); @@ -469,6 +656,7 @@ export class SubagentManager { task: task.prepared.task, cwd: task.prepared.cwd, step: task.prepared.step, + stepId: task.prepared.stepId, exitCode: 1, messages: [], output: "", @@ -486,6 +674,8 @@ export class SubagentManager { private applyResult(execution: Execution, task: InternalTask, result: RunResult): void { task.result = execution.isAsync ? { ...result, messages: [] } : result; + task.result.step = task.prepared.step; + task.result.stepId = task.prepared.stepId; if (task.snapshot.status === "interrupted") { task.result.status = "interrupted"; return; diff --git a/src/prepare.ts b/src/prepare.ts index bcec2ed..0f0bd0a 100644 --- a/src/prepare.ts +++ b/src/prepare.ts @@ -18,6 +18,14 @@ import type { ExtensionToolContext } from "@earendil-works/pi-coding-agent"; import { type AgentScope, discoverAgents } from "./agents.ts"; import type { SubagentParamsType } from "./schemas.ts"; import type { DispatchDefaults, PreparedInvocation, PreparedTask } from "./types.ts"; +import { + expandWorkflowPlan, + validateWorkflowArgs, + validateWorkflowRunShape, + type PreparedWorkflowInvocation, + type PreparedWorkflowStep, +} from "./workflow.ts"; +import { validateWorkflowExpansion, type WorkflowPlan } from "./workflows.ts"; const MAX_PARALLEL_TASKS = 8; @@ -183,6 +191,76 @@ function resolveTaskCwd(baseCwd: string, itemCwd: string | undefined): string { return resolved; } +function resolvePreparedTask( + agentName: string, + taskText: string, + itemCwd: string | undefined, + baseCwd: string, + agentScope: AgentScope, +): { task: PreparedTask; projectAgentsDir: string | null } { + const cwd = resolveTaskCwd(baseCwd, itemCwd); + + // Discovery is per task: agents are a property of the task's effective + // working directory, not of the caller's cwd. + const discovery = discoverAgents(cwd, agentScope); + const agent = discovery.agents.find((candidate) => candidate.name === agentName); + if (!agent) { + const available = discovery.agents.map((candidate) => `"${candidate.name}"`).join(", ") || "none"; + throw new InvalidInvocationError(`Unknown agent: "${agentName}". Available agents: ${available}.`); + } + + return { + task: { agent, task: taskText, cwd }, + projectAgentsDir: agent.source === "project" ? discovery.projectAgentsDir : null, + }; +} + +function collectProjectAgent( + projectAgentsByDir: Map>, + task: PreparedTask, + projectAgentsDir: string | null, +): void { + if (!projectAgentsDir) return; + const names = projectAgentsByDir.get(projectAgentsDir) ?? new Set(); + names.add(task.agent.name); + projectAgentsByDir.set(projectAgentsDir, names); +} + +/** Confirm every distinct repo-controlled agent source before anything starts. */ +async function confirmProjectAgentSources( + projectAgentsByDir: Map>, + ctx: PrepareContext, + agentScope: AgentScope, + confirmProjectAgents: boolean, +): Promise { + const projectAgentsDirs = Array.from(projectAgentsByDir.keys()); + const trustedDiscovery = ctx.isProjectTrusted() ? discoverAgents(ctx.cwd, agentScope) : null; + const trustedProjectAgentsDir = trustedDiscovery?.projectAgentsDir + ? fs.realpathSync(trustedDiscovery.projectAgentsDir) + : undefined; + + if (agentScope !== "user" && confirmProjectAgents && ctx.hasUI && projectAgentsDirs.length > 0) { + for (const directory of projectAgentsDirs) { + if (trustedProjectAgentsDir && fs.realpathSync(directory) === trustedProjectAgentsDir) continue; + const agents = Array.from(projectAgentsByDir.get(directory) ?? []); + const approved = await ctx.ui.confirm( + "Run project-local agents?", + `Agents: ${agents.join(", ")}\nSource: ${directory}\n\nProject agent prompts are repo-controlled. Only continue for repositories you trust.`, + ); + if (!approved) throw new ProjectAgentDeclinedError(directory, agents); + } + } + + return projectAgentsDirs; +} + +function dispatchDefaultsFor(ctx: PrepareContext): DispatchDefaults { + return { + model: ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined, + thinkingLevel: ctx.thinkingLevel, + }; +} + /** * Prepare a subagent invocation. * @@ -202,51 +280,18 @@ export async function prepareInvocation( for (let index = 0; index < request.items.length; index++) { const item = request.items[index]; - const cwd = resolveTaskCwd(ctx.cwd, item.cwd); - - // Discovery is per task: agents are a property of the task's effective - // working directory, not of the caller's cwd. - const discovery = discoverAgents(cwd, agentScope); - const agent = discovery.agents.find((candidate) => candidate.name === item.agent); - if (!agent) { - const available = discovery.agents.map((candidate) => `"${candidate.name}"`).join(", ") || "none"; - throw new InvalidInvocationError(`Unknown agent: "${item.agent}". Available agents: ${available}.`); - } - - if (agent.source === "project" && discovery.projectAgentsDir) { - const names = projectAgentsByDir.get(discovery.projectAgentsDir) ?? new Set(); - names.add(agent.name); - projectAgentsByDir.set(discovery.projectAgentsDir, names); - } - - const task: PreparedTask = { agent, task: item.task, cwd }; - if (request.mode === "chain") task.step = index + 1; - tasks.push(task); + const resolved = resolvePreparedTask(item.agent, item.task, item.cwd, ctx.cwd, agentScope); + collectProjectAgent(projectAgentsByDir, resolved.task, resolved.projectAgentsDir); + if (request.mode === "chain") resolved.task.step = index + 1; + tasks.push(resolved.task); } - const projectAgentsDirs = Array.from(projectAgentsByDir.keys()); - const confirmProjectAgents = params.confirmProjectAgents ?? true; - const trustedDiscovery = ctx.isProjectTrusted() ? discoverAgents(ctx.cwd, agentScope) : null; - const trustedProjectAgentsDir = trustedDiscovery?.projectAgentsDir - ? fs.realpathSync(trustedDiscovery.projectAgentsDir) - : undefined; - - if (agentScope !== "user" && confirmProjectAgents && ctx.hasUI && projectAgentsDirs.length > 0) { - for (const directory of projectAgentsDirs) { - if (trustedProjectAgentsDir && fs.realpathSync(directory) === trustedProjectAgentsDir) continue; - const agents = Array.from(projectAgentsByDir.get(directory) ?? []); - const approved = await ctx.ui.confirm( - "Run project-local agents?", - `Agents: ${agents.join(", ")}\nSource: ${directory}\n\nProject agent prompts are repo-controlled. Only continue for repositories you trust.`, - ); - if (!approved) throw new ProjectAgentDeclinedError(directory, agents); - } - } - - const dispatchDefaults: DispatchDefaults = { - model: ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined, - thinkingLevel: ctx.thinkingLevel, - }; + const projectAgentsDirs = await confirmProjectAgentSources( + projectAgentsByDir, + ctx, + agentScope, + params.confirmProjectAgents ?? true, + ); return { mode: request.mode, @@ -254,6 +299,69 @@ export async function prepareInvocation( agentScope, projectAgentsDir: projectAgentsDirs[0] ?? null, projectAgentsDirs, - dispatchDefaults, + dispatchDefaults: dispatchDefaultsFor(ctx), + }; +} + +export interface PrepareWorkflowOptions { + /** Agent directories a workflow may resolve. Default: both, project over user. */ + agentScope?: AgentScope; + /** Prompt before running repo-controlled agents. Default: true. */ + confirmProjectAgents?: boolean; +} + +/** + * Prepare a workflow run: validate arguments and run shape, resolve every + * step's agent and cwd, and confirm repo-controlled sources. All failures + * happen before the manager creates a job, so no child can spawn. + */ +export async function prepareWorkflowInvocation( + plan: WorkflowPlan, + args: Readonly>, + ctx: PrepareContext, + options: PrepareWorkflowOptions = {}, +): Promise { + validateWorkflowRunShape(plan); + const resolvedArgs = validateWorkflowArgs(plan, args); + validateWorkflowExpansion(plan, {}); + + const agentScope = options.agentScope ?? "both"; + const projectAgentsByDir = new Map>(); + const steps: PreparedWorkflowStep[] = plan.steps.map((step) => { + const resolved = resolvePreparedTask(step.agent, step.task, step.cwd, ctx.cwd, agentScope); + const prepared: PreparedTask = { + ...resolved.task, + stepId: step.id, + model: step.model, + }; + collectProjectAgent(projectAgentsByDir, prepared, resolved.projectAgentsDir); + return { + id: step.id, + needs: [...step.needs], + template: step.task, + prepared, + }; + }); + + const projectAgentsDirs = await confirmProjectAgentSources( + projectAgentsByDir, + ctx, + agentScope, + options.confirmProjectAgents ?? true, + ); + + return { + mode: "workflow", + tasks: steps.map((step) => step.prepared), + agentScope, + projectAgentsDir: projectAgentsDirs[0] ?? null, + projectAgentsDirs, + dispatchDefaults: dispatchDefaultsFor(ctx), + workflow: { + plan, + args: resolvedArgs, + steps, + expandedPlan: expandWorkflowPlan(plan), + }, }; } diff --git a/src/runner.ts b/src/runner.ts index 749ff9e..2f7d900 100644 --- a/src/runner.ts +++ b/src/runner.ts @@ -235,13 +235,14 @@ export class ProcessRunner implements TaskRunner { task: task.task, cwd: task.cwd, step: task.step, + stepId: task.stepId, exitCode: 0, messages: [], output: "", stderr: "", stderrTruncated: false, usage: emptyUsage(), - model: task.agent.model ?? defaults.model, + model: task.model ?? task.agent.model ?? defaults.model, }; let tempDir: string | undefined; @@ -262,8 +263,8 @@ export class ProcessRunner implements TaskRunner { private buildArgs(task: PreparedTask, defaults: DispatchDefaults, promptPath: string | undefined): string[] { const args: string[] = ["--mode", "json", "-p", "--no-session", "--exclude-tools", "subagent*"]; - const inheritsDispatchConfig = !task.agent.model; - const model = task.agent.model ?? defaults.model; + const inheritsDispatchConfig = !task.model && !task.agent.model; + const model = task.model ?? task.agent.model ?? defaults.model; if (model) args.push("--model", model); if (inheritsDispatchConfig && defaults.thinkingLevel) args.push("--thinking", defaults.thinkingLevel); if (task.agent.tools && task.agent.tools.length > 0) args.push("--tools", task.agent.tools.join(",")); diff --git a/src/types.ts b/src/types.ts index 3007e6e..61663a5 100644 --- a/src/types.ts +++ b/src/types.ts @@ -2,9 +2,9 @@ import type { ThinkingLevel } from "@earendil-works/pi-agent-core"; import type { Message } from "@earendil-works/pi-ai"; import type { AgentConfig, AgentScope } from "./agents.ts"; -export type InvocationMode = "single" | "parallel" | "chain"; +export type InvocationMode = "single" | "parallel" | "chain" | "workflow"; export type JobStatus = "queued" | "running" | "cancelling" | "succeeded" | "failed" | "cancelled" | "interrupted"; -export type TaskStatus = "queued" | "running" | "succeeded" | "failed" | "cancelled" | "interrupted"; +export type TaskStatus = "queued" | "running" | "succeeded" | "failed" | "skipped" | "cancelled" | "interrupted"; export interface DispatchDefaults { model?: string; @@ -16,6 +16,9 @@ export interface PreparedTask { task: string; cwd: string; step?: number; + stepId?: string; + /** Per-step model override (step -> agent -> parent precedence). */ + model?: string; } export interface PreparedInvocation { @@ -43,6 +46,7 @@ export interface RunResult { task: string; cwd: string; step?: number; + stepId?: string; exitCode: number | null; messages: Message[]; output: string; @@ -71,6 +75,7 @@ export interface TaskSnapshot { task: string; cwd: string; step?: number; + stepId?: string; status: TaskStatus; exitCode: number | null; output: string; @@ -132,11 +137,22 @@ export interface ManagerOptions { } export const TERMINAL_JOB_STATUSES: ReadonlySet = new Set(["succeeded", "failed", "cancelled", "interrupted"]); +export const TERMINAL_TASK_STATUSES: ReadonlySet = new Set([ + "succeeded", + "failed", + "skipped", + "cancelled", + "interrupted", +]); export function isTerminalJob(status: JobStatus): boolean { return TERMINAL_JOB_STATUSES.has(status); } +export function isTerminalTask(status: TaskStatus): boolean { + return TERMINAL_TASK_STATUSES.has(status); +} + export function emptyUsage(): UsageStats { return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 }; } diff --git a/src/workflow.ts b/src/workflow.ts new file mode 100644 index 0000000..dff985a --- /dev/null +++ b/src/workflow.ts @@ -0,0 +1,187 @@ +/** + * Workflow run preparation, validation, and release-time templating. + * + * The plan module (`workflows.ts`) owns file parsing and structural validation. + * This module owns the run-specific rules that need the manager's vocabulary: + * declared arguments, step-output references, run budgets, and the expanded + * plan returned at start. Nothing here spawns a child or mutates a job. + */ + +import { truncateUtf8Head } from "./output.ts"; +import type { JobSnapshot, PreparedInvocation, PreparedTask } from "./types.ts"; +import { WorkflowValidationError, type WorkflowPlan } from "./workflows.ts"; + +/** The design ceiling for one run, independent of the global worker pool. */ +export const WORKFLOW_MAX_CONCURRENCY = 4; + +/** Standard task-output budget: one prior output may not crowd out the rest. */ +export const MAX_INTERPOLATED_STEP_OUTPUT_BYTES = 50 * 1024; + +/** Expanded step prompts are bounded to keep the child brief sane. */ +export const MAX_EXPANDED_STEP_PROMPT_BYTES = 100 * 1024; + +export interface ExpandedWorkflowStep { + id: string; + agent: string; + needs: string[]; + task: string; +} + +/** The run's steps as admission units, after item fan-out is resolved. */ +export interface ExpandedWorkflowPlan { + name: string; + description: string; + args: string[]; + steps: ExpandedWorkflowStep[]; +} + +export interface PreparedWorkflowStep { + id: string; + needs: string[]; + template: string; + prepared: PreparedTask; +} + +export interface WorkflowRunSpec { + plan: WorkflowPlan; + args: Record; + steps: PreparedWorkflowStep[]; + expandedPlan: ExpandedWorkflowPlan; +} + +export interface PreparedWorkflowInvocation extends PreparedInvocation { + mode: "workflow"; + workflow: WorkflowRunSpec; +} + +export interface WorkflowStartResult { + id: string; + job: JobSnapshot; + plan: ExpandedWorkflowPlan; +} + +export interface WorkflowTemplateContext { + args: Readonly>; + outputs: ReadonlyMap; +} + +const PLACEHOLDER = /\{steps\.([A-Za-z_][A-Za-z0-9_-]*)\.output\}|\{args\.([A-Za-z_][A-Za-z0-9_-]*)\}/g; +const STEP_OUTPUT_REFERENCE = /\{steps\.([A-Za-z_][A-Za-z0-9_-]*)\.output\}/g; + +function fail(plan: WorkflowPlan, message: string, stepId?: string): never { + throw new WorkflowValidationError(`Workflow "${plan.name}" (${plan.filePath}): ${message}`, { + filePath: plan.filePath, + stepId, + }); +} + +/** The per-run reservation inside the shared worker pool (ADR 0002). */ +export function workflowRunConcurrency(maxWorkers: number): number { + return Math.min(maxWorkers - 1, WORKFLOW_MAX_CONCURRENCY); +} + +/** The expanded plan is one admission unit per step until each-steps land. */ +export function expandWorkflowPlan(plan: WorkflowPlan): ExpandedWorkflowPlan { + return { + name: plan.name, + description: plan.description, + args: [...plan.args], + steps: plan.steps.map((step) => ({ + id: step.id, + agent: step.agent, + needs: [...step.needs], + task: step.task, + })), + }; +} + +/** Validate run arguments against the plan's declaration (all declared args are required). */ +export function validateWorkflowArgs(plan: WorkflowPlan, args: Readonly>): Record { + const declared = new Set(plan.args); + const unknown = Object.keys(args).filter((name) => !declared.has(name)); + + if (unknown.length > 0) { + const names = unknown.map((name) => `"${name}"`).join(", "); + fail( + plan, + `unknown argument${unknown.length === 1 ? "" : "s"} ${names}. Declared args: ${plan.args.length > 0 ? plan.args.join(", ") : "none"}.`, + ); + } + + const missing = plan.args.filter((name) => !Object.hasOwn(args, name)); + if (missing.length > 0) { + fail( + plan, + `missing required argument${missing.length === 1 ? "" : "s"} ${missing.map((name) => `"${name}"`).join(", ")}. Provide ${missing.length === 1 ? "it" : "them"} when starting the workflow.`, + ); + } + + return Object.fromEntries(plan.args.map((name) => [name, args[name]])); +} + +/** + * Validate the parts of the plan only a run can know: each-steps are not + * implemented yet, and every step-output reference must be a declared need so + * the value exists when the step is released. + */ +export function validateWorkflowRunShape(plan: WorkflowPlan): void { + const byId = new Map(plan.steps.map((step) => [step.id, step])); + + for (const [index, step] of plan.steps.entries()) { + if (step.each !== undefined) { + fail( + plan, + `steps[${index}] ("${step.id}") declares each: {steps.${step.each}.output}; each-steps are not supported yet (line fan-out lands in ticket #8).`, + step.id, + ); + } + + for (const match of step.task.matchAll(STEP_OUTPUT_REFERENCE)) { + const source = match[1]; + if (!byId.has(source)) { + fail( + plan, + `steps[${index}] ("${step.id}").task references unknown step "${source}". Available steps: ${plan.steps.map((candidate) => `"${candidate.id}"`).join(", ")}.`, + step.id, + ); + } + if (!step.needs.includes(source)) { + fail( + plan, + `steps[${index}] ("${step.id}").task references {steps.${source}.output} but "${source}" is not in its needs (${step.needs.length > 0 ? step.needs.map((need) => `"${need}"`).join(", ") : "none"}). Add "${source}" to needs.`, + step.id, + ); + } + } + } +} + +function appendMarker(text: string, marker: string): string { + return `${text}\n\n${marker}`; +} + +/** + * Expand one step brief at release time. + * + * Substitutions are single-pass, so a value that happens to contain another + * placeholder is inserted literally. Each prior output is bounded to the + * standard task-output budget, then the whole brief to the expanded-prompt + * budget; both truncations carry a visible marker. + */ +export function interpolateWorkflowTask(template: string, context: WorkflowTemplateContext): string { + const expanded = template.replace(PLACEHOLDER, (_match, stepId: string | undefined, argName: string | undefined) => { + if (stepId !== undefined) { + const output = context.outputs.get(stepId) ?? ""; + const bounded = truncateUtf8Head(output, MAX_INTERPOLATED_STEP_OUTPUT_BYTES); + return bounded.truncated + ? appendMarker(bounded.text, `[Output truncated: ${bounded.bytesOmitted} bytes omitted]`) + : output; + } + return context.args[argName ?? ""] ?? ""; + }); + + const bounded = truncateUtf8Head(expanded, MAX_EXPANDED_STEP_PROMPT_BYTES); + return bounded.truncated + ? appendMarker(bounded.text, `[Prompt truncated: ${bounded.bytesOmitted} bytes omitted]`) + : expanded; +} diff --git a/test/runner.test.ts b/test/runner.test.ts index 7b6227e..bf52dd5 100644 --- a/test/runner.test.ts +++ b/test/runner.test.ts @@ -373,3 +373,26 @@ test( } }, ); + +test("a step model overrides the agent and dispatch model without inheriting thinking", async () => { + let captured: string[] = []; + const runner = makeRunner( + { FAKE_PI_MODE: "success" }, + { + invocation: (args) => { + captured = args; + return { command: process.execPath, args: [fixturePath, ...args] }; + }, + }, + ); + + const agent = makeAgent({ model: "agent-model" }); + const defaults: DispatchDefaults = { model: "dispatch-model", thinkingLevel: "high" }; + const result = await runner.run(makeTask({ agent, model: "step-model", stepId: "scan" }), defaults, runOptions()); + + assert.equal(result.exitCode, 0); + assert.equal(captured[captured.indexOf("--model") + 1], "step-model"); + assert.equal(captured.includes("--thinking"), false); + assert.equal(result.model, "step-model"); + assert.equal(result.stepId, "scan"); +}); diff --git a/test/workflow-run.test.ts b/test/workflow-run.test.ts new file mode 100644 index 0000000..f22e286 --- /dev/null +++ b/test/workflow-run.test.ts @@ -0,0 +1,366 @@ +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 { SubagentManager } from "../src/manager.ts"; +import { prepareWorkflowInvocation, type PrepareContext } from "../src/prepare.ts"; +import { parseWorkflow, WorkflowValidationError, type WorkflowPlan } 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 }); +}); + +function makeWorkspace(agentNames = ["scout"]): { cwd: string; ctx: PrepareContext } { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-workflow-run-")); + tempRoots.push(root); + const agentsDir = path.join(root, ".pi", "agents"); + fs.mkdirSync(agentsDir, { recursive: true }); + for (const name of agentNames) { + fs.writeFileSync( + path.join(agentsDir, `${name}.md`), + `---\nname: ${name}\ndescription: ${name} agent\n---\nYou are ${name}.\n`, + "utf-8", + ); + } + return { + cwd: root, + ctx: { + cwd: root, + hasUI: false, + isProjectTrusted: () => true, + ui: { confirm: async () => true }, + }, + }; +} + +function makePlan(steps: Array>, args: string[] = []): WorkflowPlan { + const content = `---\n${JSON.stringify({ name: "test-workflow", description: "Test workflow", args, steps }, null, 2)}\n---\n\nNotes.\n`; + return parseWorkflow(content, { source: "user", filePath: "/tmp/test-workflow.md" }); +} + +function pending(runner: FakeRunner, stepId: string) { + const call = runner.calls.find((candidate) => candidate.task.stepId === stepId && !candidate.settled); + if (!call) throw new Error(`No pending step ${stepId}; running: ${runner.calls.map((c) => `${c.task.stepId}:${c.settled}`).join(", ")}`); + return call; +} + +function completeStep(runner: FakeRunner, stepId: string, output = "done", overrides: Record = {}): void { + const call = pending(runner, stepId); + runner.complete(call.task.task, output, overrides); +} + +test("run releases steps only when needs succeed, interpolating outputs in plan order", async () => { + const { cwd, ctx } = makeWorkspace(); + const plan = makePlan( + [ + { id: "scan", agent: "scout", task: "scan sources" }, + { id: "audit", agent: "scout", task: "audit {steps.scan.output}", needs: ["scan"] }, + { id: "merge", agent: "scout", task: "merge {steps.audit.output}", needs: ["audit"] }, + { id: "notify", agent: "scout", task: "notify {args.channel}", needs: [] }, + ], + ["channel"], + ); + const runner = new FakeRunner(); + const manager = new SubagentManager(runner); + const prepared = await prepareWorkflowInvocation(plan, { channel: "#ops" }, ctx, { + agentScope: "project", + confirmProjectAgents: false, + }); + + const started = manager.startWorkflow(prepared); + assert.equal(started.id, started.job.id); + assert.deepEqual(started.plan.steps.map((step) => step.id), ["scan", "audit", "merge", "notify"]); + assert.deepEqual(started.plan.steps[1].needs, ["scan"]); + + assert.deepEqual(runner.calls.map((call) => call.task.stepId), ["scan", "notify"]); + assert.equal(runner.calls[1].task.task, "notify #ops"); + + completeStep(runner, "scan", "src/a.ts\nsrc/b.ts"); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(runner.calls.map((call) => call.task.stepId), ["scan", "notify", "audit"]); + assert.equal(pending(runner, "audit").task.task, "audit src/a.ts\nsrc/b.ts"); + + completeStep(runner, "audit", "missing auth"); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(pending(runner, "merge").task.task, "merge missing auth"); + + completeStep(runner, "notify", "sent"); + completeStep(runner, "merge", "ranked"); + + const terminal = await manager.wait(started.id, 1); + assert.equal(terminal.status, "succeeded"); + assert.deepEqual(terminal.results.map((result) => result.stepId), ["scan", "audit", "merge", "notify"]); + assert.deepEqual(terminal.results.map((result) => result.status), ["succeeded", "succeeded", "succeeded", "succeeded"]); + assert.equal(terminal.mode, "workflow"); +}); + +test("a failed step skips dependents transitively while independent branches finish and settle the run", async () => { + const { ctx } = makeWorkspace(); + const plan = makePlan([ + { id: "scan", agent: "scout", task: "scan" }, + { id: "notify", agent: "scout", task: "notify" }, + { id: "audit", agent: "scout", task: "audit {steps.scan.output}", needs: ["scan"] }, + { id: "report", agent: "scout", task: "report {steps.audit.output}", needs: ["audit"] }, + { id: "publish", agent: "scout", task: "publish {steps.notify.output}", needs: ["notify"] }, + ]); + const runner = new FakeRunner(); + const manager = new SubagentManager(runner); + const started = manager.startWorkflow( + await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false }), + ); + + completeStep(runner, "scan", "partial", { exitCode: 1, errorMessage: "scan exploded" }); + await new Promise((resolve) => setImmediate(resolve)); + + const midRun = manager.get(started.id); + assert.deepEqual(midRun.results.map((result) => result.status), ["failed", "running", "skipped", "skipped", "queued"]); + assert.equal(midRun.status, "running"); + assert.equal(runner.calls.some((call) => call.task.stepId === "audit" || call.task.stepId === "report"), false); + + completeStep(runner, "notify", "ready"); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(pending(runner, "publish").task.task, "publish ready"); + completeStep(runner, "publish", "published"); + + const terminal = await manager.wait(started.id, 1); + assert.equal(terminal.status, "failed"); + assert.deepEqual( + terminal.results.map((result) => [result.stepId, result.status]), + [ + ["scan", "failed"], + ["notify", "succeeded"], + ["audit", "skipped"], + ["report", "skipped"], + ["publish", "succeeded"], + ], + ); + assert.equal(terminal.results.every((result) => result.finishedAt !== undefined), true); + assert.match(terminal.results[2].errorMessage ?? "", /Skipped/); +}); + +test("the per-run cap holds under fewer workers and the global FIFO releases the next step", async () => { + const { ctx } = makeWorkspace(); + const plan = makePlan([ + { id: "a", agent: "scout", task: "a" }, + { id: "b", agent: "scout", task: "b" }, + { id: "c", agent: "scout", task: "c" }, + { id: "d", agent: "scout", task: "d" }, + ]); + const runner = new FakeRunner(); + const manager = new SubagentManager(runner, { maxWorkers: 3 }); + const started = manager.startWorkflow( + await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false }), + ); + + assert.equal(runner.calls.length, 2); + completeStep(runner, "a"); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(runner.calls.length, 3); + assert.equal(manager.get(started.id).results.find((result) => result.stepId === "c")?.status, "running"); + + completeStep(runner, "b"); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(runner.calls.length, 4); + completeStep(runner, "c"); + completeStep(runner, "d"); + assert.equal((await manager.wait(started.id, 1)).status, "succeeded"); +}); + +test("a single-worker pool rejects workflow runs instead of reserving zero capacity", async () => { + const { ctx } = makeWorkspace(); + const plan = makePlan([{ id: "only", agent: "scout", task: "only" }]); + const runner = new FakeRunner(); + const manager = new SubagentManager(runner, { maxWorkers: 1 }); + const prepared = await prepareWorkflowInvocation(plan, {}, ctx, { + agentScope: "project", + confirmProjectAgents: false, + }); + + assert.throws(() => manager.startWorkflow(prepared), /at least 2 workers/); + assert.equal(runner.calls.length, 0); +}); + +test("cancel mid-run aborts released steps and cancels queued steps without hanging", async () => { + const { ctx } = makeWorkspace(); + const plan = makePlan([ + { id: "a", agent: "scout", task: "a" }, + { id: "b", agent: "scout", task: "b" }, + { id: "child", agent: "scout", task: "child {steps.a.output}", needs: ["a"] }, + { id: "held", agent: "scout", task: "held" }, + ]); + const runner = new FakeRunner(); + const manager = new SubagentManager(runner, { maxWorkers: 3 }); + const started = manager.startWorkflow( + await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false }), + ); + assert.deepEqual(runner.calls.map((call) => call.task.stepId), ["a", "b"]); + + const cancelling = manager.cancel(started.id); + assert.equal(cancelling.status, "cancelling"); + assert.deepEqual( + cancelling.results.map((result) => [result.stepId, result.status]), + [ + ["a", "running"], + ["b", "running"], + ["child", "cancelled"], + ["held", "cancelled"], + ], + ); + + const terminal = await manager.wait(started.id, 1); + assert.equal(terminal.status, "cancelled"); + assert.deepEqual( + terminal.results.map((result) => [result.stepId, result.status]), + [ + ["a", "cancelled"], + ["b", "cancelled"], + ["child", "cancelled"], + ["held", "cancelled"], + ], + ); + assert.deepEqual(runner.aborted.sort(), ["a", "b"]); + assert.equal(runner.calls.length, 2); + assert.equal(manager.cancel(started.id).status, "cancelled"); +}); + +test("start rejects undeclared, missing, and malformed run inputs before any child spawns", async () => { + const { ctx } = makeWorkspace(); + const runner = new FakeRunner(); + const manager = new SubagentManager(runner); + const argsPlan = makePlan([{ id: "scan", agent: "scout", task: "scan {args.glob}" }], ["glob"]); + + await assert.rejects( + prepareWorkflowInvocation(argsPlan, { glob: "src/**", extra: "no" }, ctx, { + agentScope: "project", + confirmProjectAgents: false, + }), + (error: unknown) => error instanceof WorkflowValidationError && /unknown argument "extra".*Declared args: glob/.test(error.message), + ); + await assert.rejects( + prepareWorkflowInvocation(argsPlan, {}, ctx, { agentScope: "project", confirmProjectAgents: false }), + (error: unknown) => error instanceof WorkflowValidationError && /missing required argument "glob"/.test(error.message), + ); + + const eachPlan = makePlan([ + { id: "scan", agent: "scout", task: "scan" }, + { id: "audit", agent: "scout", task: "audit {item}", needs: ["scan"], each: "{steps.scan.output}" }, + ]); + await assert.rejects( + prepareWorkflowInvocation(eachPlan, {}, ctx, { agentScope: "project", confirmProjectAgents: false }), + (error: unknown) => + error instanceof WorkflowValidationError && + /each-steps are not supported yet/.test(error.message) && + /"audit"/.test(error.message), + ); + + const badReference = makePlan([ + { id: "scan", agent: "scout", task: "scan" }, + { id: "merge", agent: "scout", task: "merge {steps.scan.output}" }, + ]); + await assert.rejects( + prepareWorkflowInvocation(badReference, {}, ctx, { agentScope: "project", confirmProjectAgents: false }), + (error: unknown) => + error instanceof WorkflowValidationError && + /references \{steps\.scan\.output\} but "scan" is not in its needs/.test(error.message), + ); + + const unknownReference = makePlan([{ id: "merge", agent: "scout", task: "merge {steps.ghost.output}" }]); + await assert.rejects( + prepareWorkflowInvocation(unknownReference, {}, ctx, { agentScope: "project", confirmProjectAgents: false }), + (error: unknown) => error instanceof WorkflowValidationError && /references unknown step "ghost"/.test(error.message), + ); + + assert.equal(runner.calls.length, 0); + assert.equal(manager.list().length, 0); +}); + +test("start resolves step-local cwd and model precedence while validating every agent", async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-workflow-cwd-")); + tempRoots.push(root); + const project = path.join(root, "project"); + const nested = path.join(project, "nested"); + fs.mkdirSync(path.join(project, ".pi", "agents"), { recursive: true }); + fs.mkdirSync(nested, { recursive: true }); + fs.writeFileSync( + path.join(project, ".pi", "agents", "scout.md"), + "---\nname: scout\ndescription: scout agent\nmodel: agent-model\n---\nYou are scout.\n", + "utf-8", + ); + const ctx: PrepareContext = { + cwd: root, + hasUI: false, + isProjectTrusted: () => true, + ui: { confirm: async () => true }, + }; + const plan = makePlan([ + { id: "scan", agent: "scout", task: "scan", cwd: "project", model: "step-model" }, + { id: "merge", agent: "scout", task: "merge {steps.scan.output}", needs: ["scan"], cwd: "project/nested" }, + ]); + + const prepared = await prepareWorkflowInvocation(plan, {}, ctx, { + agentScope: "project", + confirmProjectAgents: false, + }); + assert.deepEqual(prepared.tasks.map((task) => task.cwd), [project, nested]); + assert.equal(prepared.tasks[0].model, "step-model"); + assert.equal(prepared.tasks[1].model, undefined); + assert.equal(prepared.tasks[1].agent.model, "agent-model"); +}); + +test("reload interruption marks every unfinished workflow step interrupted and preserves step ids", async () => { + const { ctx } = makeWorkspace(); + const plan = makePlan([ + { id: "a", agent: "scout", task: "a" }, + { id: "b", agent: "scout", task: "b" }, + ]); + const runner = new FakeRunner(); + const manager = new SubagentManager(runner, { maxWorkers: 2 }); + const started = manager.startWorkflow( + await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false }), + ); + assert.deepEqual(manager.get(started.id).results.map((result) => result.status), ["running", "queued"]); + + const restoredRunner = new FakeRunner(); + const restoredManager = new SubagentManager(restoredRunner); + restoredManager.restore([manager.get(started.id)]); + const restored = restoredManager.get(started.id); + assert.equal(restored.status, "interrupted"); + assert.deepEqual( + restored.results.map((result) => [result.stepId, result.status]), + [ + ["a", "interrupted"], + ["b", "interrupted"], + ], + ); + assert.equal(restoredRunner.calls.length, 0); + manager.cancel(started.id); + await manager.wait(started.id, 1); +}); + +test("a fan-in step waits for every need and interpolates all of them", async () => { + const { ctx } = makeWorkspace(); + const plan = makePlan([ + { id: "scan", agent: "scout", task: "scan" }, + { id: "audit", agent: "scout", task: "audit" }, + { id: "merge", agent: "scout", task: "merge {steps.scan.output} + {steps.audit.output}", needs: ["scan", "audit"] }, + ]); + const runner = new FakeRunner(); + const manager = new SubagentManager(runner); + const started = manager.startWorkflow( + await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false }), + ); + + completeStep(runner, "scan", "files"); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(runner.calls.length, 2); + + completeStep(runner, "audit", "findings"); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(pending(runner, "merge").task.task, "merge files + findings"); + completeStep(runner, "merge", "ranked"); + assert.equal((await manager.wait(started.id, 1)).status, "succeeded"); +}); diff --git a/test/workflow-template.test.ts b/test/workflow-template.test.ts new file mode 100644 index 0000000..eaf8787 --- /dev/null +++ b/test/workflow-template.test.ts @@ -0,0 +1,71 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + MAX_EXPANDED_STEP_PROMPT_BYTES, + MAX_INTERPOLATED_STEP_OUTPUT_BYTES, + interpolateWorkflowTask, + workflowRunConcurrency, +} from "../src/workflow.ts"; + +// Independent of the exported constants so a changed budget fails the test. +const OUTPUT_BUDGET = 50 * 1024; +const PROMPT_BUDGET = 100 * 1024; + +function context(args: Record = {}, outputs: Record = {}) { + return { args, outputs: new Map(Object.entries(outputs)) }; +} + +test("step outputs and args interpolate at release time in one pass", () => { + const template = "Audit {args.glob}: {steps.scan.output}\nThen {steps.scan.output}"; + assert.equal( + interpolateWorkflowTask(template, context({ glob: "src/**" }, { scan: "a.ts\nb.ts" })), + "Audit src/**: a.ts\nb.ts\nThen a.ts\nb.ts", + ); + assert.equal(interpolateWorkflowTask("no placeholders", context()), "no placeholders"); + assert.equal(interpolateWorkflowTask("{previous} stays literal", context()), "{previous} stays literal"); +}); + +test("substituted values are never re-expanded and placeholder-like text stays literal", () => { + const output = "keep {args.glob} and {steps.other.output} literal"; + const args = { glob: "{steps.scan.output}", other: "$&" }; + const result = interpolateWorkflowTask("{steps.scan.output}|{args.glob}|{args.other}", context(args, { scan: output })); + assert.equal(result, `${output}|{steps.scan.output}|$&`); + assert.equal(interpolateWorkflowTask("{item}", context()), "{item}"); +}); + +test("a single output is bounded to the standard task-output budget with a marker", () => { + assert.equal(MAX_INTERPOLATED_STEP_OUTPUT_BYTES, OUTPUT_BUDGET); + const original = "😀a".repeat(OUTPUT_BUDGET); + const result = interpolateWorkflowTask("{steps.scan.output}", context({}, { scan: original })); + const [prefix, note] = result.split("\n\n[Output truncated: "); + + assert.ok(Buffer.byteLength(prefix, "utf8") <= OUTPUT_BUDGET); + assert.equal(prefix.includes("\uFFFD"), false); + assert.equal(original.startsWith(prefix), true); + const omitted = Buffer.byteLength(original, "utf8") - Buffer.byteLength(prefix, "utf8"); + assert.equal(note, `${omitted} bytes omitted]`); +}); + +test("the whole expanded brief is bounded to the prompt budget with a visible marker", () => { + assert.equal(MAX_EXPANDED_STEP_PROMPT_BYTES, PROMPT_BUDGET); + const piece = "x".repeat(49 * 1024); + const result = interpolateWorkflowTask( + "{steps.a.output}{steps.b.output}{steps.c.output}", + context({}, { a: piece, b: piece, c: piece }), + ); + const [prefix, note] = result.split("\n\n[Prompt truncated: "); + + assert.ok(Buffer.byteLength(prefix, "utf8") <= PROMPT_BUDGET); + assert.notEqual(note, undefined); + assert.match(note, /^\d+ bytes omitted\]$/); + const omitted = Buffer.byteLength(`${piece}${piece}${piece}`, "utf8") - Buffer.byteLength(prefix, "utf8"); + assert.equal(note, `${omitted} bytes omitted]`); + assert.equal(prefix.includes("\uFFFD"), false); +}); + +test("the per-run reservation is min(maxWorkers - 1, 4)", () => { + assert.equal(workflowRunConcurrency(2), 1); + assert.equal(workflowRunConcurrency(3), 2); + assert.equal(workflowRunConcurrency(5), 4); + assert.equal(workflowRunConcurrency(32), 4); +});