Files
pi-subagent/test/workflows.test.ts
T
alex 621f6e2579 Make the workflow supervisor host seam real
Move Execution, InternalTask, and the status predicates into job-state.ts; the supervisor now creates, schedules, and settles shared rows only through its host. Concentrate cancellation and shutdown settlement in one supervisor policy, make restored rows honest (no fabricated AgentConfig), and thread load-time cap limits through WorkflowRunSpec so release enforcement and the review card share one value. Agent discovery is memoized per cwd within a prepare call.
2026-12-01 11:09:26 +00:00

546 lines
20 KiB
TypeScript

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 fc from "fast-check";
import {
MAX_EXPANDED_CHILDREN,
MAX_WORKFLOW_STEPS,
UnknownWorkflowError,
WorkflowValidationError,
discoverWorkflows,
loadWorkflow,
parseWorkflow,
validateWorkflowExpansion,
type WorkflowPlan,
} from "../src/workflow-plan.ts";
const tempRoots: string[] = [];
after(() => {
for (const root of tempRoots) fs.rmSync(root, { recursive: true, force: true });
});
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("a workflow file parses into a plan with every field preserved", () => {
const plan = parseWorkflow(SKETCH, {
source: "project",
filePath: "/repo/.pi/workflows/audit-routes.md",
});
assert.deepEqual(plan, {
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.",
needs: [],
each: undefined,
model: undefined,
cwd: undefined,
},
{
id: "audit",
agent: "reviewer",
task: "Audit {item} for missing authentication checks.",
needs: ["scan"],
each: "scan",
model: "sonnet",
cwd: "src/routes",
},
{
id: "merge",
agent: "merger",
task: "Merge these findings into one ranked list: {steps.audit.output}",
needs: ["audit"],
each: undefined,
model: undefined,
cwd: undefined,
},
],
source: "project",
filePath: "/repo/.pi/workflows/audit-routes.md",
});
});
function workflowFile(frontmatter: unknown): string {
return `---\n${JSON.stringify(frontmatter, null, 2)}\n---\n\nOptional prose notes.\n`;
}
function step(id: string, overrides: Record<string, unknown> = {}): Record<string, unknown> {
return { id, agent: "scout", task: `Task for ${id}.`, ...overrides };
}
function plan(steps: unknown[], overrides: Record<string, unknown> = {}): string {
return workflowFile({ name: "test-workflow", description: "Test workflow", ...overrides, steps });
}
function validationErrorFor(thrower: () => unknown): WorkflowValidationError {
try {
thrower();
} catch (error) {
assert.ok(error instanceof WorkflowValidationError, `expected WorkflowValidationError, got ${String(error)}`);
return error;
}
assert.fail("expected the workflow to fail validation");
}
function validationError(content: string): WorkflowValidationError {
return validationErrorFor(() => parseWorkflow(content, { source: "project", filePath: "/repo/.pi/workflows/test.md" }));
}
test("malformed frontmatter is rejected with a precise error", () => {
assert.match(validationError("no frontmatter here\n").message, /missing YAML frontmatter/);
assert.match(validationError("---\nname: [unterminated\n---\n").message, /malformed YAML frontmatter/);
assert.match(validationError("---\n- one\n- two\n---\n").message, /frontmatter must be a YAML mapping/);
assert.match(validationError(workflowFile({ description: "No name", steps: [step("scan")] })).message, /required frontmatter field "name"/);
assert.match(validationError(workflowFile({ name: "no-description", steps: [step("scan")] })).message, /required frontmatter field "description"/);
assert.match(validationError(workflowFile({ name: "no-steps", description: "d" })).message, /"steps" must be a nonempty list/);
assert.match(validationError(workflowFile({ name: "empty-steps", description: "d", steps: [] })).message, /"steps" must be a nonempty list/);
assert.match(validationError(workflowFile({ name: "args", description: "d", args: "glob", steps: [step("scan")] })).message, /"args" must be a list/);
assert.match(validationError(workflowFile({ name: "dupe-args", description: "d", args: ["glob", "glob"], steps: [step("scan")] })).message, /duplicate argument name "glob"/);
assert.match(validationError(workflowFile({ name: "unknown", description: "d", extra: true, steps: [step("scan")] })).message, /unknown frontmatter field "extra"/);
assert.match(validationError(plan([step("scan", { when: "never" })])).message, /unknown field "when"/);
});
test("duplicate step ids and unknown needs are rejected", () => {
const duplicate = validationError(plan([step("scan"), step("audit"), step("scan")]));
assert.match(duplicate.message, /duplicate step id "scan"/);
assert.equal(duplicate.stepId, "scan");
const unknownNeed = validationError(plan([step("scan", { needs: ["missing"] })]));
assert.match(unknownNeed.message, /needs unknown step "missing"/);
});
test("cyclic needs are rejected with the cycle named", () => {
const error = validationError(
plan([step("a", { needs: ["c"] }), step("b", { needs: ["a"] }), step("c", { needs: ["b"] })]),
);
assert.match(error.message, /cycle/);
assert.match(error.message, /"a" -> "c" -> "b" -> "a"|"a" -> "b" -> "c" -> "a"/);
});
test("undeclared argument references are rejected", () => {
const error = validationError(
plan([step("scan", { task: "List {args.path} under src/." })], { args: ["glob"] }),
);
assert.match(error.message, /undeclared argument "path"/);
assert.match(error.message, /Declared args: glob/);
assert.equal(error.stepId, "scan");
});
test("{item} is rejected in a step without each", () => {
const error = validationError(plan([step("scan", { task: "Audit {item} for auth." })]));
assert.match(error.message, /\{item\} is only valid in a step with `each`/);
assert.equal(error.stepId, "scan");
const each = eachPlan([1]);
assert.equal(each.steps[1].task, "Audit {item}.");
});
test("each requires a step-output reference and a needed source step", () => {
assert.match(validationError(plan([step("scan"), step("audit", { each: "scan" })])).message, /each must be a "\{steps\.<id>\.output\}" reference/);
assert.match(validationError(plan([step("scan"), step("audit", { each: "{steps.missing.output}", needs: ["scan"] })])).message, /each references unknown step "missing"/);
const notNeeded = validationError(plan([step("scan"), step("audit", { each: "{steps.scan.output}", needs: [] })]));
assert.match(notNeeded.message, /each source "scan" is not in its needs/);
assert.equal(notNeeded.stepId, "audit");
});
test("the step cap is enforced before any planning", () => {
const atCap = Array.from({ length: MAX_WORKFLOW_STEPS }, (_, index) => step(`step_${index}`));
assert.equal(parseWorkflow(plan(atCap), { source: "project", filePath: "/repo/.pi/workflows/test.md" }).steps.length, MAX_WORKFLOW_STEPS);
const steps = Array.from({ length: MAX_WORKFLOW_STEPS + 1 }, (_, index) => step(`step_${index}`));
const error = validationError(plan(steps));
assert.match(error.message, new RegExp(`too many steps \\(${MAX_WORKFLOW_STEPS + 1}\\)`));
assert.match(error.message, new RegExp(`Max is ${MAX_WORKFLOW_STEPS}`));
});
function makeTempRoot(): string {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-workflows-"));
tempRoots.push(root);
return root;
}
function writeWorkflow(filePath: string, name: string, description: string): void {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, workflowFile({ name, description, steps: [step("scan")] }), "utf-8");
}
test("project workflows override user workflows of the same name", () => {
const root = makeTempRoot();
const agentDir = path.join(root, "agent");
const project = path.join(root, "project");
const previousAgentDir = process.env.PI_CODING_AGENT_DIR;
process.env.PI_CODING_AGENT_DIR = agentDir;
try {
writeWorkflow(path.join(agentDir, "workflows", "shared.md"), "shared", "user version");
writeWorkflow(path.join(agentDir, "workflows", "user-only.md"), "user-only", "user only");
writeWorkflow(path.join(project, ".pi", "workflows", "shared.md"), "shared", "project version");
writeWorkflow(path.join(project, ".pi", "workflows", "project-only.md"), "project-only", "project only");
const discovery = discoverWorkflows(project, "both");
assert.deepEqual(
discovery.workflows.map((workflow) => [workflow.name, workflow.source, workflow.description]),
[
["shared", "project", "project version"],
["user-only", "user", "user only"],
["project-only", "project", "project only"],
],
);
assert.equal(discovery.projectWorkflowsDir, path.join(project, ".pi", "workflows"));
const shared = loadWorkflow("shared", project);
assert.equal(shared.source, "project");
assert.equal(shared.description, "project version");
assert.equal(loadWorkflow("user-only", project).source, "user");
const nested = path.join(project, "src", "deep");
fs.mkdirSync(nested, { recursive: true });
assert.equal(discoverWorkflows(nested, "project").projectWorkflowsDir, path.join(project, ".pi", "workflows"));
assert.deepEqual(
discoverWorkflows(project, "user").workflows.map((workflow) => workflow.name),
["shared", "user-only"],
);
assert.throws(() => loadWorkflow("missing", project), UnknownWorkflowError);
} finally {
if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
else process.env.PI_CODING_AGENT_DIR = previousAgentDir;
}
});
test("discovery finds workflows whose plain scalars need the YAML fallback", () => {
const root = makeTempRoot();
const agentDir = path.join(root, "agent");
const project = path.join(root, "project");
const previousAgentDir = process.env.PI_CODING_AGENT_DIR;
process.env.PI_CODING_AGENT_DIR = agentDir;
try {
const filePath = path.join(project, ".pi", "workflows", "audit-routes.md");
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, SKETCH, "utf-8");
assert.deepEqual(
discoverWorkflows(project, "project").workflows.map((workflow) => workflow.name),
["audit-routes"],
);
const loaded = loadWorkflow("audit-routes", project, "project");
assert.equal(loaded.steps[1].each, "scan");
assert.equal(loaded.steps[2].task, "Merge these findings into one ranked list: {steps.audit.output}");
} finally {
if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
else process.env.PI_CODING_AGENT_DIR = previousAgentDir;
}
});
function eachPlan(counts: number[]): WorkflowPlan {
const steps = [
step("scan"),
...counts.map((_, index) =>
step(`audit_${index}`, { each: "{steps.scan.output}", needs: ["scan"], task: "Audit {item}." }),
),
];
return parseWorkflow(plan(steps), { source: "project", filePath: "/repo/.pi/workflows/each.md" });
}
function itemCounts(counts: number[]): Map<string, number> {
return new Map(counts.map((count, index) => [`audit_${index}`, count]));
}
function limits(maxItemsPerEach = 32, maxExpandedChildren = MAX_EXPANDED_CHILDREN) {
return { maxItemsPerEach, maxExpandedChildren };
}
test("expanded children caps are validated per each-step and per run", () => {
const p = eachPlan([32]);
assert.equal(validateWorkflowExpansion(p, itemCounts([32]), limits()), 33);
const tooManyItems = validationErrorFor(() => validateWorkflowExpansion(p, itemCounts([33]), limits(32)));
assert.match(tooManyItems.message, /steps\[1\] \("audit_0"\) has 33 items/);
assert.match(tooManyItems.message, /max is 32 per each-step/);
assert.match(
validationErrorFor(() =>
validateWorkflowExpansion(eachPlan(Array(8).fill(32)), itemCounts(Array(8).fill(32)), limits()),
).message,
new RegExp(`expanded children \\(257\\) exceed the run cap of ${MAX_EXPANDED_CHILDREN}`),
);
const accepted = eachPlan([...Array(7).fill(32), 31]);
assert.equal(validateWorkflowExpansion(accepted, itemCounts([...Array(7).fill(32), 31]), limits()), 256);
});
test("the each-item cap uses the injected limits", () => {
const p = eachPlan([5]);
const error = validationErrorFor(() => validateWorkflowExpansion(p, itemCounts([5]), limits(4)));
assert.match(error.message, /has 5 items/);
assert.match(error.message, /max is 4 per each-step/);
});
const identifierArb = fc.stringMatching(/^[A-Za-z_][A-Za-z0-9_-]{0,7}$/);
const safeTextArb = fc.stringMatching(/^[A-Za-z0-9.,:;!?()/_-][A-Za-z0-9 .,:;!?()/_-]{0,39}$/);
const pathArb = fc.stringMatching(/^(?:[A-Za-z0-9_.-]+\/?){1,3}$/);
interface GeneratedStep {
id: string;
agent: string;
task: string;
needs: string[];
each?: string;
model?: string;
cwd?: string;
}
interface GeneratedPlan {
name: string;
description: string;
args: string[];
steps: GeneratedStep[];
}
function generatedStepsArb(): fc.Arbitrary<GeneratedStep[]> {
return fc.integer({ min: 1, max: 8 }).chain((count) => {
let steps: fc.Arbitrary<GeneratedStep[]> = fc.constant([]);
for (let index = 0; index < count; index++) {
steps = steps.chain((prior) => {
const priorIds = prior.map((priorStep) => priorStep.id);
const base = fc.record({
id: fc.constant(`step_${index}`),
agent: identifierArb,
task: safeTextArb,
needs: fc.subarray(priorIds),
model: fc.option(identifierArb, { nil: undefined }),
cwd: fc.option(pathArb, { nil: undefined }),
});
return base.chain((generated) => {
const each =
generated.needs.length > 0
? fc.option(fc.constantFrom(...generated.needs), { nil: undefined })
: fc.constant(undefined);
return each.map((source) => [
...prior,
{ ...generated, each: source === undefined ? undefined : `{steps.${source}.output}` },
]);
});
});
}
return steps;
});
}
const generatedPlanArb: fc.Arbitrary<GeneratedPlan> = fc.record({
name: identifierArb,
description: safeTextArb,
args: fc.array(identifierArb, { maxLength: 4 }).map((args) => [...new Set(args)]),
steps: generatedStepsArb(),
});
test("property: generated valid plans round-trip with every field preserved", () => {
fc.assert(
fc.property(generatedPlanArb, (input) => {
const parsed = parseWorkflow(workflowFile(input), {
source: "user",
filePath: "/tmp/generated-workflow.md",
});
assert.deepEqual(parsed, {
name: input.name,
description: input.description,
args: input.args,
steps: input.steps.map((generated) => ({
id: generated.id,
agent: generated.agent,
task: generated.task,
needs: generated.needs,
each: generated.each === undefined ? undefined : /^\{steps\.(.+)\.output\}$/.exec(generated.each)![1],
model: generated.model,
cwd: generated.cwd,
})),
source: "user",
filePath: "/tmp/generated-workflow.md",
});
}),
{ numRuns: 150 },
);
});
test("property: arbitrary file content yields a valid plan or a WorkflowValidationError", () => {
fc.assert(
fc.property(fc.string({ maxLength: 400 }), (content) => {
let parsed: WorkflowPlan;
try {
parsed = parseWorkflow(content, { source: "user", filePath: "/tmp/arbitrary.md" });
} catch (error) {
assert.ok(error instanceof WorkflowValidationError, `unexpected error type: ${String(error)}`);
return;
}
assert.ok(parsed.steps.length >= 1);
assert.ok(parsed.steps.length <= MAX_WORKFLOW_STEPS);
assert.equal(new Set(parsed.steps.map((parsedStep) => parsedStep.id)).size, parsed.steps.length);
}),
{ numRuns: 300 },
);
});
test("property: non-mapping frontmatter is always rejected as malformed", () => {
const nonMapping = fc.oneof(
fc.string({ minLength: 1 }),
fc.integer(),
fc.boolean(),
fc.array(fc.string({ minLength: 1 }), { minLength: 1 }),
);
fc.assert(
fc.property(nonMapping, (value) => {
const content = `---\n${JSON.stringify(value)}\n---\n`;
const error = validationErrorFor(() => parseWorkflow(content, { source: "user", filePath: "/tmp/frontmatter.md" }));
assert.match(error.message, /frontmatter must be a YAML mapping/);
}),
{ numRuns: 100 },
);
});
test("property: any duplicated step id is rejected by name", () => {
fc.assert(
fc.property(identifierArb, safeTextArb, (id, task) => {
const error = validationError(plan([step(id, { task }), step(id, { task: `${task} again` })]));
assert.ok(error.message.includes(`duplicate step id "${id}"`));
assert.equal(error.stepId, id);
}),
{ numRuns: 100 },
);
});
test("property: any needs cycle is rejected with the whole cycle named", () => {
fc.assert(
fc.property(fc.integer({ min: 2, max: 12 }), (count) => {
const ids = Array.from({ length: count }, (_, index) => `step_${index}`);
const steps = ids.map((id, index) =>
step(id, { needs: [index === 0 ? ids[count - 1] : ids[index - 1]] }),
);
const error = validationError(plan(steps));
assert.match(error.message, /needs form a cycle/);
for (const id of ids) assert.ok(error.message.includes(`"${id}"`), `cycle message omits ${id}`);
}),
{ numRuns: 100 },
);
});
test("property: any undeclared argument reference is rejected by name", () => {
fc.assert(
fc.property(fc.uniqueArray(identifierArb, { maxLength: 5 }), (declared) => {
let undeclared = "undeclared";
let suffix = 0;
while (declared.includes(undeclared)) undeclared = `undeclared_${suffix++}`;
const error = validationError(
plan([step("scan", { task: `Use {args.${undeclared}} here.` })], { args: declared }),
);
assert.ok(error.message.includes(`undeclared argument "${undeclared}"`));
assert.equal(error.stepId, "scan");
}),
{ numRuns: 100 },
);
});
test("property: a value that is not an each reference is rejected as an each source", () => {
const validEach = /^\{steps\.[A-Za-z_][A-Za-z0-9_-]*\.output\}$/;
fc.assert(
fc.property(
fc.string({ maxLength: 40 }).filter((value) => !validEach.test(value.trim())),
(each) => {
const error = validationError(plan([step("scan"), step("audit", { each, needs: ["scan"] })]));
assert.match(error.message, /each must be a "\{steps\.<id>\.output\}" reference/);
},
),
{ numRuns: 100 },
);
});
test("property: an each source that is not in needs is rejected by step and source", () => {
fc.assert(
fc.property(identifierArb.map((id) => (id === "audit" ? "source" : id)), (source) => {
const error = validationError(
plan([step(source), step("audit", { each: `{steps.${source}.output}`, needs: [] })]),
);
assert.ok(error.message.includes(`each source "${source}" is not in its needs`));
assert.equal(error.stepId, "audit");
}),
{ numRuns: 100 },
);
});
test("property: any plan above the step cap is rejected with its count and the limit", () => {
fc.assert(
fc.property(fc.integer({ min: MAX_WORKFLOW_STEPS + 1, max: MAX_WORKFLOW_STEPS + 20 }), (count) => {
const steps = Array.from({ length: count }, (_, index) => step(`step_${index}`));
const error = validationError(plan(steps));
assert.ok(error.message.includes(`too many steps (${count})`));
assert.ok(error.message.includes(`Max is ${MAX_WORKFLOW_STEPS}`));
}),
{ numRuns: 30 },
);
});
test("property: any each-step above the item cap is rejected with its count and limit", () => {
fc.assert(
fc.property(fc.integer({ min: 1, max: 32 }), fc.integer({ min: 1, max: 5 }), (maxItems, extra) => {
const count = maxItems + extra;
const error = validationErrorFor(() =>
validateWorkflowExpansion(eachPlan([count]), itemCounts([count]), {
maxItemsPerEach: maxItems,
maxExpandedChildren: 1000,
}),
);
assert.ok(error.message.includes(`steps[1] ("audit_0") has ${count} items`));
assert.ok(error.message.includes(`max is ${maxItems} per each-step`));
assert.equal(error.stepId, "audit_0");
}),
{ numRuns: 100 },
);
});
test("property: any expansion above the run child cap is rejected with both counts", () => {
fc.assert(
fc.property(fc.array(fc.integer({ min: 1, max: 40 }), { minLength: 1, maxLength: 12 }), (counts) => {
const total = 1 + counts.reduce((sum, count) => sum + count, 0);
const cap = total - 1;
const error = validationErrorFor(() =>
validateWorkflowExpansion(eachPlan(counts), itemCounts(counts), {
maxItemsPerEach: 100,
maxExpandedChildren: cap,
}),
);
assert.ok(error.message.includes(`expanded children (${total}) exceed the run cap of ${cap}`));
}),
{ numRuns: 100 },
);
});