Files
pi-subagent/test/workflow-supervisor.test.ts
T

390 lines
12 KiB
TypeScript

import assert from "node:assert/strict";
import test from "node:test";
import type { AgentConfig } from "../src/agents.ts";
import {
initialTask,
isFailedResult,
isTerminalTask,
taskBaseResult,
type Execution,
type InternalTask,
} from "../src/job-state.ts";
import type { JobStatus, PreparedTask, RunResult, TaskSnapshot, TaskStatus } from "../src/types.ts";
import { MAX_EXPANDED_CHILDREN, type WorkflowLimits, type WorkflowPlan } from "../src/workflow-plan.ts";
import { toStartPlan, type WorkflowRunSpec } from "../src/workflow-run.ts";
import {
WorkflowSupervisor,
type WorkflowSupervisorHost,
type WorkflowTermination,
} from "../src/workflow-supervisor.ts";
/**
* A second adapter for the supervisor seam: it creates and settles real job
* rows but has no manager, FIFO, worker, or agent directory. Each test drives
* the DAG by completing the scheduled rows it can see.
*/
const agent: AgentConfig = {
name: "scout",
description: "fake agent",
systemPrompt: "",
source: "user",
filePath: "/tmp/fake-scout.md",
};
interface FakeStep {
id: string;
task: string;
needs?: string[];
each?: string;
}
function runSpec(steps: FakeStep[], limits: WorkflowLimits = {
maxItemsPerEach: 32,
maxExpandedChildren: MAX_EXPANDED_CHILDREN,
}): WorkflowRunSpec {
const plan: WorkflowPlan = {
name: "fake-run",
description: "A run for the fake host",
args: [],
steps: steps.map((step) => ({
id: step.id,
agent: agent.name,
task: step.task,
needs: step.needs ?? [],
each: step.each,
})),
source: "inline",
filePath: "test:fake-run",
};
return {
plan,
args: {},
steps: plan.steps.map((step) => ({
id: step.id,
needs: [...step.needs],
template: step.task,
each: step.each,
prepared: { agent, task: step.task, cwd: "/tmp", stepId: step.id },
})),
startPlan: toStartPlan(plan),
limits,
};
}
interface Pending {
task: InternalTask;
resolve: (result: RunResult) => void;
}
class FakeHost implements WorkflowSupervisorHost {
readonly execution: Execution = {
id: "run_fake",
request: { mode: "workflow", tasks: [], agentScope: "user", projectAgentsDir: null, dispatchDefaults: {} },
status: "queued",
plannedTaskCount: 0,
tasks: [],
createdAt: 0,
isAsync: true,
cancelRequested: false,
};
readonly tasks: InternalTask[] = [];
readonly scheduled: string[] = [];
readonly settled: Array<{ task: InternalTask; status: TaskStatus }> = [];
plannedTaskCount = 0;
finalStatus?: JobStatus;
emits = 0;
private readonly pending: Pending[] = [];
private clock = 0;
createTask(_execution: Execution, prepared: PreparedTask): InternalTask {
const task = initialTask(prepared);
this.tasks.push(task);
this.plannedTaskCount += 1;
return task;
}
schedule(_execution: Execution, task: InternalTask): Promise<RunResult> {
this.scheduled.push(task.prepared?.stepId ?? "");
task.snapshot.status = "running";
task.snapshot.startedAt = this.now();
task.controller = new AbortController();
return new Promise<RunResult>((resolve) => {
this.pending.push({ task, resolve });
});
}
settleTask(
task: InternalTask,
status: TaskStatus,
result: RunResult,
snapshot: Partial<TaskSnapshot> = {},
): RunResult {
task.snapshot.status = status;
task.snapshot.output = result.output;
task.snapshot.exitCode = result.exitCode;
task.snapshot.errorMessage = result.errorMessage;
Object.assign(task.snapshot, snapshot);
task.snapshot.finishedAt = this.now();
task.result = { ...result, status };
task.controller = undefined;
this.settled.push({ task, status });
return task.result;
}
cancelledResult(task: InternalTask, status: WorkflowTermination = "cancelled"): RunResult {
return {
...taskBaseResult(task),
status,
stopReason: "aborted",
errorMessage: status === "interrupted" ? "Interrupted by session shutdown" : "Cancelled by caller",
};
}
finalize(_execution: Execution, status: JobStatus): void {
this.finalStatus = status;
}
emit(): void {
this.emits += 1;
}
now(): number {
return ++this.clock;
}
complete(stepId: string, output = "done", overrides: Partial<RunResult> = {}): void {
this.resolvePending(
(pending) => pending.task.prepared?.stepId === stepId && pending.task.prepared.item === undefined,
output,
overrides,
);
}
completeItem(stepId: string, item: number, output: string, overrides: Partial<RunResult> = {}): void {
this.resolvePending(
(pending) => pending.task.prepared?.stepId === stepId && pending.task.prepared.item === item,
output,
overrides,
);
}
/** The manager's abort half of cancellation: running children settle cancelled. */
cancelRunning(): void {
for (const pending of this.pending.splice(0)) {
pending.task.controller?.abort();
const result = this.settleTask(pending.task, "cancelled", this.cancelledResult(pending.task));
pending.resolve(result);
}
}
task(stepId: string, item?: number): InternalTask | undefined {
return this.tasks.find(
(candidate) => candidate.prepared?.stepId === stepId && candidate.prepared.item === item,
);
}
private resolvePending(
match: (pending: Pending) => boolean,
output: string,
overrides: Partial<RunResult>,
): void {
const index = this.pending.findIndex(match);
if (index === -1) throw new Error("No matching pending task");
const [pending] = this.pending.splice(index, 1);
const result: RunResult = { ...taskBaseResult(pending.task), output, exitCode: 0, ...overrides };
const status: TaskStatus = isFailedResult(result) ? "failed" : "succeeded";
pending.resolve(this.settleTask(pending.task, status, result));
}
}
function tick(): Promise<void> {
return new Promise((resolve) => setImmediate(resolve));
}
test("the supervisor releases ready steps in plan order and registers every row through the host", async () => {
const host = new FakeHost();
const supervisor = new WorkflowSupervisor(host, 4);
const spec = runSpec([
{ id: "scan", task: "scan" },
{ id: "notify", task: "notify" },
{ id: "merge", task: "merge {steps.scan.output}", needs: ["scan"] },
]);
const run = supervisor.run(host.execution, spec);
await tick();
assert.deepEqual(host.scheduled, ["scan", "notify"]);
assert.equal(host.plannedTaskCount, 3);
assert.equal(host.tasks.length, 3);
host.complete("scan", "files");
await tick();
assert.deepEqual(host.scheduled, ["scan", "notify", "merge"]);
assert.equal(host.task("merge")?.prepared?.task, "merge files");
host.complete("notify");
host.complete("merge");
await run;
assert.equal(host.finalStatus, "succeeded");
assert.equal(host.tasks.every((task) => isTerminalTask(task.snapshot.status)), true);
});
test("a failed step skips its dependents transitively while independent branches finish", async () => {
const host = new FakeHost();
const supervisor = new WorkflowSupervisor(host, 4);
const spec = runSpec([
{ id: "scan", task: "scan" },
{ id: "notify", task: "notify" },
{ id: "audit", task: "audit {steps.scan.output}", needs: ["scan"] },
{ id: "report", task: "report {steps.audit.output}", needs: ["audit"] },
{ id: "publish", task: "publish {steps.notify.output}", needs: ["notify"] },
]);
const run = supervisor.run(host.execution, spec);
await tick();
host.complete("scan", "partial", { exitCode: 1, errorMessage: "scan exploded" });
await tick();
assert.deepEqual(
host.tasks.map((task) => [task.prepared?.stepId, task.snapshot.status]),
[
["scan", "failed"],
["notify", "running"],
["audit", "skipped"],
["report", "skipped"],
["publish", "queued"],
],
);
assert.equal(host.scheduled.includes("audit") || host.scheduled.includes("report"), false);
host.complete("notify", "ready");
await tick();
assert.equal(host.task("publish")?.prepared?.task, "publish ready");
host.complete("publish", "published");
await run;
assert.equal(host.finalStatus, "failed");
assert.equal(host.task("audit")?.snapshot.status, "skipped");
});
test("failed items leave empty slots, the step succeeds, and the run still fails", async () => {
const host = new FakeHost();
const supervisor = new WorkflowSupervisor(host, 4);
const spec = runSpec([
{ id: "scan", task: "scan" },
{ id: "audit", task: "audit {item}", needs: ["scan"], each: "scan" },
{ id: "report", task: "report {steps.audit.output}", needs: ["audit"] },
]);
const run = supervisor.run(host.execution, spec);
await tick();
host.complete("scan", "a.ts\nb.ts\nc.ts");
await tick();
host.completeItem("audit", 1, "good a");
host.completeItem("audit", 2, "bad b", { exitCode: 1, errorMessage: "b exploded" });
host.completeItem("audit", 3, "good c");
await tick();
const audit = host.task("audit");
assert.equal(audit?.snapshot.status, "succeeded");
assert.equal(audit?.snapshot.output, "### a.ts\n\ngood a\n\n### b.ts\n\n\n\n### c.ts\n\ngood c");
assert.equal(audit?.snapshot.output.includes("bad b"), false);
assert.equal(host.task("audit", 2)?.snapshot.status, "failed");
assert.match(host.task("report")?.prepared?.task ?? "", /### b\.ts/);
host.complete("report", "reported");
await run;
assert.equal(host.finalStatus, "failed");
assert.equal(host.task("report")?.snapshot.status, "succeeded");
});
test("a source with zero items fails the step loudly and spawns no item children", async () => {
const host = new FakeHost();
const supervisor = new WorkflowSupervisor(host, 4);
const spec = runSpec([
{ id: "scan", task: "scan" },
{ id: "audit", task: "audit {item}", needs: ["scan"], each: "scan" },
{ id: "report", task: "report {steps.audit.output}", needs: ["audit"] },
]);
const run = supervisor.run(host.execution, spec);
await tick();
host.complete("scan", " \n\t\r\n\n");
await tick();
const audit = host.task("audit");
assert.equal(audit?.snapshot.status, "failed");
assert.match(audit?.snapshot.errorMessage ?? "", /source produced no items/i);
assert.equal(host.tasks.some((task) => task.prepared?.stepId === "audit" && task.prepared.item !== undefined), false);
await run;
assert.equal(host.finalStatus, "failed");
assert.equal(host.task("report")?.snapshot.status, "skipped");
});
test("cancel with items in flight and items pending settles every row cancelled", async () => {
const host = new FakeHost();
const supervisor = new WorkflowSupervisor(host, 3);
const spec = runSpec([
{ id: "scan", task: "scan" },
{ id: "audit", task: "audit {item}", needs: ["scan"], each: "scan" },
]);
const run = supervisor.run(host.execution, spec);
await tick();
host.complete("scan", "a\nb\nc\nd");
await tick();
assert.equal(host.task("audit")?.snapshot.status, "running");
assert.deepEqual(
[1, 2, 3, 4].map((item) => host.task("audit", item)?.snapshot.status),
["running", "running", "queued", "queued"],
);
supervisor.cancel(host.execution);
assert.equal(host.task("audit")?.snapshot.status, "cancelled");
assert.deepEqual(
[1, 2, 3, 4].map((item) => host.task("audit", item)?.snapshot.status),
["running", "running", "cancelled", "cancelled"],
);
host.cancelRunning();
await run;
assert.equal(host.finalStatus, "cancelled");
assert.equal(host.task("scan")?.snapshot.status, "succeeded");
assert.equal(host.tasks.filter((task) => task.prepared?.stepId === "audit").every((task) => task.snapshot.status === "cancelled"), true);
});
test("an unresolvable DAG stalls loudly instead of hanging", async () => {
const host = new FakeHost();
const supervisor = new WorkflowSupervisor(host, 4);
const spec = runSpec([
{ id: "a", task: "a", needs: ["ghost"] },
{ id: "b", task: "b", needs: ["ghost"] },
]);
await assert.rejects(supervisor.run(host.execution, spec), /stalled with no releasable steps/);
assert.equal(host.plannedTaskCount, 2);
assert.equal(host.scheduled.length, 0);
});
test("release-time cap enforcement uses the limits injected into the run spec", async () => {
const host = new FakeHost();
const supervisor = new WorkflowSupervisor(host, 4);
const spec = runSpec(
[
{ id: "scan", task: "scan" },
{ id: "audit", task: "audit {item}", needs: ["scan"], each: "scan" },
],
{ maxItemsPerEach: 2, maxExpandedChildren: MAX_EXPANDED_CHILDREN },
);
const run = supervisor.run(host.execution, spec);
await tick();
host.complete("scan", "a\nb\nc");
await run;
const audit = host.task("audit");
assert.equal(audit?.snapshot.status, "failed");
assert.match(audit?.snapshot.errorMessage ?? "", /has 3 items/);
assert.match(audit?.snapshot.errorMessage ?? "", /max is 2 per each-step/);
assert.equal(host.scheduled.includes("audit"), false);
assert.equal(host.tasks.some((task) => task.prepared?.stepId === "audit" && task.prepared.item !== undefined), false);
assert.equal(host.finalStatus, "failed");
});