repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/ultra/__tests__/engine.test.ts
RawFile outline
- fakeRunner line 19
- runner line 25
- tick line 40
- spec line 43
- baseDeps line 55
- stepRunner line 56
- memoryJournal line 62
- runWorkflow — phase dispatch line 78
- single phase runs the step exactly once with item=undefined line 79
- fanout over a literal array launches one step per element (order preserved) line 105
- runWorkflow — interpolation line 135
- resolves {item} and {args.NAME} in the prompt before calling the runner line 136
- fanout over a prior phase's flattened findings, filtering by `where real`, retaining the join key line 155
- retains null positionally in a phase's results for dropped steps line 209
- runWorkflow — concurrency line 241
- never exceeds the global concurrency cap, and parallelizes up to it line 242
- honors a per-phase concurrency override below the global cap line 268
- runWorkflow — resume journal line 300
- writes successful step results and reuses matching cached steps line 301
- keeps an aborted journal incomplete so a later run reuses completed slots and runs missing slots line 335
- runWorkflow — drops & dropped-end emission line 390
- a failed step yields null, increments dropped, and emits a board-only dropped end carrying the reason line 391
- an all-null phase does not halt the workflow; later phases still run line 439
- runWorkflow — abort line 469
- aborting mid-phase stops the pool, surfaces partial counts, and emits no end for un-launched agents line 470
- a pre-aborted signal launches no steps and reports every item dropped line 509
- runWorkflow — result shape line 538
- persists every phase's positional results for later inspection line 539
- returns { workflow, phases:[{id,ran,ok,dropped}], phaseResults, result, steered, tokenUsage } line 589
- runWorkflow — progress forwarding & steer line 652
- forwards runner progress events to onProgress, tagged with the phase + engine agentId line 653
- flips steered to true when a forwarded agent's controls.steer is invoked, delegating to the bound control line 688
- leaves steered false when no steer occurs line 721
import { describe, expect, it, vi } from "vitest";
import { type EngineDeps, runWorkflow } from "../engine.ts";
import {
initialReducerState,
reduceProgress,
type UltraProgressEvent,
} from "../progress.ts";
import type { RunStepResult, StepRunner, StepRunnerArgs } from "../runner.ts";
import type { Phase, WorkflowSpec } from "../spec.ts";
// ---------------------------------------------------------------------------
// Test doubles
// ---------------------------------------------------------------------------
/** A fake `StepRunner`: a per-call handler keyed off `StepRunnerArgs`, plus
* call capture and a live-concurrency high-watermark for cap assertions. The
* handler keys on `args` (never call order) because fanout calls land out of
* order under concurrency. */
function fakeRunner(
handler: (args: StepRunnerArgs) => RunStepResult | Promise<RunStepResult>,
): { runner: StepRunner; calls: StepRunnerArgs[]; maxLive: () => number } {
const calls: StepRunnerArgs[] = [];
let live = 0;
let maxLive = 0;
const runner: StepRunner = async (args) => {
calls.push(args);
live++;
if (live > maxLive) maxLive = live;
try {
return await handler(args);
} finally {
live--;
}
};
return { runner, calls, maxLive: () => maxLive };
}
/** Yield so concurrent pool workers actually overlap (real timer; this test
* runs under Node/vitest where timers are available). */
const tick = (ms = 5): Promise<void> => new Promise((r) => setTimeout(r, ms));
/** Build a minimal valid `WorkflowSpec`. */
function spec(p: {
name?: string;
return?: string;
phases: Phase[];
}): WorkflowSpec {
return {
name: p.name ?? "wf",
phases: p.phases,
...(p.return !== undefined ? { return: p.return } : {}),
};
}
const baseDeps = (
over: Partial<EngineDeps> & { stepRunner: StepRunner },
): EngineDeps => ({
concurrency: 4,
...over,
});
function memoryJournal(seed: Record<string, RunStepResult> = {}) {
const entries = new Map(Object.entries(seed));
return {
get: vi.fn((key: string) => entries.get(key)),
set: vi.fn((key: string, result: RunStepResult) =>
entries.set(key, result),
),
complete: vi.fn(),
entries,
};
}
// ---------------------------------------------------------------------------
// single / fanout dispatch
// ---------------------------------------------------------------------------
describe("runWorkflow — phase dispatch", () => {
it("single phase runs the step exactly once with item=undefined", async () => {
const fr = fakeRunner((args) => ({
ok: true,
value: { said: args.step.prompt },
}));
const s = spec({
phases: [{ id: "judge", kind: "single", step: { prompt: "hello" } }],
});
const res = await runWorkflow(
s,
undefined,
baseDeps({ stepRunner: fr.runner }),
);
expect(fr.calls).toHaveLength(1);
expect(fr.calls[0].item).toBeUndefined();
expect(fr.calls[0].phase).toBe("judge");
expect(fr.calls[0].agentId).toBe("judge#0");
expect(res.phases).toEqual([{ id: "judge", ran: 1, ok: 1, dropped: 0 }]);
expect(res.workflow).toBe("wf");
expect(res.steered).toBe(false);
// No `return` ⇒ result defaults to the last phase's values.
expect(res.result).toEqual([{ said: "hello" }]);
});
it("fanout over a literal array launches one step per element (order preserved)", async () => {
const fr = fakeRunner((args) => ({ ok: true, value: args.item }));
const s = spec({
return: "{f.results}",
phases: [
{
id: "f",
kind: "fanout",
over: ["x", "y", "z"],
step: { prompt: "{item}" },
},
],
});
const res = await runWorkflow(
s,
undefined,
baseDeps({ stepRunner: fr.runner }),
);
expect(fr.calls).toHaveLength(3);
expect(res.phases[0]).toEqual({ id: "f", ran: 3, ok: 3, dropped: 0 });
expect(res.result).toEqual(["x", "y", "z"]);
});
});
// ---------------------------------------------------------------------------
// interpolation — engine owns it; runner gets the resolved prompt verbatim
// ---------------------------------------------------------------------------
describe("runWorkflow — interpolation", () => {
it("resolves {item} and {args.NAME} in the prompt before calling the runner", async () => {
const fr = fakeRunner((args) => ({ ok: true, value: args.step.prompt }));
const s = spec({
phases: [
{
id: "p",
kind: "fanout",
over: ["a", "b"],
step: { prompt: "do {item} for {args.who}" },
},
],
});
await runWorkflow(s, { who: "alice" }, baseDeps({ stepRunner: fr.runner }));
const prompts = fr.calls.map((c) => c.step.prompt).sort();
expect(prompts).toEqual(["do a for alice", "do b for alice"]);
});
it("fanout over a prior phase's flattened findings, filtering by `where real`, retaining the join key", async () => {
const fr = fakeRunner((args) => {
if (args.phase === "review") {
const dim = args.item as string;
return {
ok: true,
value: { findings: [{ title: `${dim}-1`, file: `${dim}.ts` }] },
};
}
// verify echoes the finding's `file` (correction #6b) + a `real` flag.
const finding = args.item as { title: string; file: string };
return {
ok: true,
value: {
title: finding.title,
file: finding.file,
real: finding.file === "correctness.ts",
},
};
});
const s = spec({
return: "{verify.results | where real}",
phases: [
{
id: "review",
kind: "fanout",
over: ["correctness", "security"],
step: { prompt: "review {item}" },
},
{
id: "verify",
kind: "fanout",
over: "{review.results[].findings[]}",
step: { prompt: "verify {item}" },
},
],
});
const res = await runWorkflow(
s,
undefined,
baseDeps({ stepRunner: fr.runner }),
);
expect(res.phases[0].id).toBe("review");
expect(res.phases[1].id).toBe("verify");
expect(res.phases[1].ran).toBe(2); // verify fanned out over both findings
// Only the correctness verdict is `real`; it retains its join key.
expect(res.result).toEqual([
{ title: "correctness-1", file: "correctness.ts", real: true },
]);
expect((res.result as { file: string }[])[0].file).toBe("correctness.ts");
});
it("retains null positionally in a phase's results for dropped steps", async () => {
const fr = fakeRunner((args) =>
args.item === 1
? { ok: false, value: null, reason: "x" }
: { ok: true, value: { n: args.item } },
);
const s = spec({
return: "{p.results}",
phases: [
{
id: "p",
kind: "fanout",
over: [0, 1, 2],
step: { prompt: "{item}" },
},
],
});
const res = await runWorkflow(
s,
undefined,
baseDeps({ stepRunner: fr.runner }),
);
expect(res.result).toEqual([{ n: 0 }, null, { n: 2 }]);
});
});
// ---------------------------------------------------------------------------
// concurrency
// ---------------------------------------------------------------------------
describe("runWorkflow — concurrency", () => {
it("never exceeds the global concurrency cap, and parallelizes up to it", async () => {
const fr = fakeRunner(async () => {
await tick();
return { ok: true, value: 1 };
});
const s = spec({
phases: [
{
id: "f",
kind: "fanout",
over: [1, 2, 3, 4, 5, 6],
step: { prompt: "x" },
},
],
});
await runWorkflow(
s,
undefined,
baseDeps({ stepRunner: fr.runner, concurrency: 2 }),
);
expect(fr.maxLive()).toBeLessThanOrEqual(2);
expect(fr.maxLive()).toBe(2); // proves it actually parallelizes (non-vacuity)
});
it("honors a per-phase concurrency override below the global cap", async () => {
const fr = fakeRunner(async () => {
await tick();
return { ok: true, value: 1 };
});
const s = spec({
phases: [
{
id: "f",
kind: "fanout",
over: [1, 2, 3, 4],
concurrency: 1,
step: { prompt: "x" },
},
],
});
await runWorkflow(
s,
undefined,
baseDeps({ stepRunner: fr.runner, concurrency: 5 }),
);
// Serialized by the override; without it, the global cap of 5 would let all 4 overlap.
expect(fr.maxLive()).toBe(1);
});
});
// ---------------------------------------------------------------------------
// resume journal
// ---------------------------------------------------------------------------
describe("runWorkflow — resume journal", () => {
it("writes successful step results and reuses matching cached steps", async () => {
const firstJournal = memoryJournal();
const s = spec({
return: "{p.results}",
phases: [
{ id: "p", kind: "fanout", over: ["a"], step: { prompt: "do {item}" } },
],
});
const first = fakeRunner(() => ({ ok: true, value: "live-a" }));
await runWorkflow(
s,
undefined,
baseDeps({ stepRunner: first.runner, journal: firstJournal }),
);
expect(firstJournal.set).toHaveBeenCalledTimes(1);
const [key, cachedResult] = firstJournal.set.mock.calls[0];
const secondJournal = memoryJournal({ [key]: cachedResult });
const second = fakeRunner(() => {
throw new Error("cached step should not run");
});
const res = await runWorkflow(
s,
undefined,
baseDeps({ stepRunner: second.runner, journal: secondJournal }),
);
expect(second.calls).toHaveLength(0);
expect(res.result).toEqual(["live-a"]);
expect(res.tokenUsage.total).toBe(0);
});
it("keeps an aborted journal incomplete so a later run reuses completed slots and runs missing slots", async () => {
const controller = new AbortController();
const journal = memoryJournal();
const s = spec({
return: "{p.results}",
phases: [
{
id: "p",
kind: "fanout",
over: ["a", "b"],
step: { prompt: "do {item}" },
},
],
});
const first = fakeRunner((args) => {
if (args.item === "a") {
controller.abort();
return { ok: true, value: "cached-a" };
}
return { ok: true, value: "should-not-launch" };
});
await runWorkflow(
s,
undefined,
baseDeps({
stepRunner: first.runner,
concurrency: 1,
signal: controller.signal,
journal,
}),
);
expect(journal.set).toHaveBeenCalledTimes(1);
expect(journal.complete).not.toHaveBeenCalled();
const resumed = fakeRunner((args) => ({
ok: true,
value: `live-${args.item}`,
}));
const res = await runWorkflow(
s,
undefined,
baseDeps({ stepRunner: resumed.runner, concurrency: 1, journal }),
);
expect(res.result).toEqual(["cached-a", "live-b"]);
expect(resumed.calls.map((c) => c.item)).toEqual(["b"]);
expect(journal.complete).toHaveBeenCalledTimes(1);
});
});
// ---------------------------------------------------------------------------
// drops, dropped-end emission, and the launched-vs-unlaunched discriminating pair
// ---------------------------------------------------------------------------
describe("runWorkflow — drops & dropped-end emission", () => {
it("a failed step yields null, increments dropped, and emits a board-only dropped end carrying the reason", async () => {
const REASON = "schema invalid then null"; // deliberately NOT a DROP_STATUSES token
const fr = fakeRunner((args) =>
args.item === "bad"
? { ok: false, value: null, reason: REASON }
: { ok: true, value: args.item },
);
const events: UltraProgressEvent[] = [];
const s = spec({
phases: [
{
id: "f",
kind: "fanout",
over: ["ok1", "bad", "ok2"],
step: { prompt: "{item}" },
},
],
});
const res = await runWorkflow(
s,
undefined,
baseDeps({
stepRunner: fr.runner,
concurrency: 3,
onProgress: (e) => events.push(e),
}),
);
expect(res.phases[0]).toEqual({ id: "f", ran: 3, ok: 2, dropped: 1 });
const end = events.find((e) => e.kind === "end" && e.status === "dropped");
expect(end).toBeDefined();
// The status is a DROP_STATUSES token, NOT the free-form reason — the exact
// bug the runner fixed in its own cycle (free-form reason ⇒ reducer miscount).
expect(end?.status).toBe("dropped");
expect(end?.text).toContain(REASON); // reason recorded — no silent cap
expect(end?.agentId).toBe("f#1"); // the failed item
// Fed through the REAL reducer, the row classifies as dropped (not done).
const state = reduceProgress(
initialReducerState(),
end as UltraProgressEvent,
);
expect(state.rows[0].status).toBe("dropped");
expect(state.dropped).toBe(1);
});
it("an all-null phase does not halt the workflow; later phases still run", async () => {
const fr = fakeRunner((args) =>
args.phase === "a"
? { ok: false, value: null, reason: "all fail" }
: { ok: true, value: `b-saw-${args.phase}` },
);
const s = spec({
return: "{b.results}",
phases: [
{ id: "a", kind: "fanout", over: [1, 2], step: { prompt: "{item}" } },
{ id: "b", kind: "single", step: { prompt: "after a" } },
],
});
const res = await runWorkflow(
s,
undefined,
baseDeps({ stepRunner: fr.runner, concurrency: 2 }),
);
expect(res.phases[0]).toEqual({ id: "a", ran: 2, ok: 0, dropped: 2 }); // flagged via ok:0
expect(res.phases[1]).toEqual({ id: "b", ran: 1, ok: 1, dropped: 0 }); // continued
expect(res.result).toEqual(["b-saw-b"]);
});
});
// ---------------------------------------------------------------------------
// abort
// ---------------------------------------------------------------------------
describe("runWorkflow — abort", () => {
it("aborting mid-phase stops the pool, surfaces partial counts, and emits no end for un-launched agents", async () => {
const controller = new AbortController();
const events: UltraProgressEvent[] = [];
const fr = fakeRunner(async (args) => {
await tick(); // ensure both concurrency-2 items launch before the abort fires
if (args.item === 0) controller.abort();
return { ok: true, value: args.item };
});
const s = spec({
phases: [
{
id: "f",
kind: "fanout",
over: [0, 1, 2, 3, 4, 5],
step: { prompt: "{item}" },
},
],
});
const res = await runWorkflow(
s,
undefined,
baseDeps({
stepRunner: fr.runner,
concurrency: 2,
signal: controller.signal,
onProgress: (e) => events.push(e),
}),
);
expect(res.phases[0].ran).toBe(2); // only the first concurrency-window launched
expect(res.phases[0].ok).toBe(2);
expect(res.phases[0].dropped).toBe(4); // 4 un-launched, counted as dropped
// No phantom end for the never-launched agents.
const endIds = events.filter((e) => e.kind === "end").map((e) => e.agentId);
expect(endIds).not.toContain("f#2");
expect(endIds).not.toContain("f#5");
});
it("a pre-aborted signal launches no steps and reports every item dropped", async () => {
const controller = new AbortController();
controller.abort();
const fr = fakeRunner(() => ({ ok: true, value: 1 }));
const s = spec({
phases: [
{ id: "f", kind: "fanout", over: [1, 2, 3], step: { prompt: "x" } },
],
});
const res = await runWorkflow(
s,
undefined,
baseDeps({
stepRunner: fr.runner,
concurrency: 2,
signal: controller.signal,
}),
);
expect(fr.calls).toHaveLength(0);
expect(res.phases[0]).toEqual({ id: "f", ran: 0, ok: 0, dropped: 3 });
});
});
// ---------------------------------------------------------------------------
// result shape
// ---------------------------------------------------------------------------
describe("runWorkflow — result shape", () => {
it("persists every phase's positional results for later inspection", async () => {
const fr = fakeRunner((args) => {
if (args.phase === "review") {
return args.item === "drop"
? { ok: false, value: null, reason: "bad schema" }
: {
ok: true,
value: { findings: [{ title: String(args.item), file: "a.ts" }] },
};
}
return {
ok: true,
value: { title: "refuted", real: false, file: "a.ts" },
};
});
const s = spec({
name: "review",
return: "{verify.results | where real}",
phases: [
{
id: "review",
kind: "fanout",
over: ["kept", "drop"],
step: { prompt: "review {item}" },
},
{
id: "verify",
kind: "fanout",
over: "{review.results[].findings[]}",
step: { prompt: "verify {item}" },
},
],
});
const res = await runWorkflow(
s,
undefined,
baseDeps({ stepRunner: fr.runner, concurrency: 2 }),
);
expect(res.result).toEqual([]);
expect(res.phaseResults.review).toEqual([
{ ok: true, value: { findings: [{ title: "kept", file: "a.ts" }] } },
{ ok: false, value: null, reason: "bad schema" },
]);
expect(res.phaseResults.verify).toEqual([
{ ok: true, value: { title: "refuted", real: false, file: "a.ts" } },
]);
});
it("returns { workflow, phases:[{id,ran,ok,dropped}], phaseResults, result, steered, tokenUsage }", async () => {
const fr = fakeRunner((args) => ({
ok: true,
value: args.item ?? "v",
usage: {
input: 7,
output: 3,
total: 10,
cacheRead: 2,
cacheWrite: 1,
cost: 0.4,
},
}));
const s = spec({
name: "demo",
return: "{p.results}",
phases: [
{ id: "p", kind: "fanout", over: ["a"], step: { prompt: "{item}" } },
],
});
const res = await runWorkflow(
s,
undefined,
baseDeps({ stepRunner: fr.runner, concurrency: 1 }),
);
expect(Object.keys(res).sort()).toEqual([
"phaseResults",
"phases",
"result",
"steered",
"tokenUsage",
"workflow",
]);
expect(res).toEqual({
workflow: "demo",
phases: [{ id: "p", ran: 1, ok: 1, dropped: 0 }],
phaseResults: { p: [{ ok: true, value: "a" }] },
result: ["a"],
steered: false,
tokenUsage: {
input: 7,
output: 3,
total: 10,
cacheRead: 2,
cacheWrite: 1,
cost: 0.4,
},
});
expect(Object.keys(res.phases[0]).sort()).toEqual([
"dropped",
"id",
"ok",
"ran",
]);
});
});
// ---------------------------------------------------------------------------
// progress forwarding & steer taint
// ---------------------------------------------------------------------------
describe("runWorkflow — progress forwarding & steer", () => {
it("forwards runner progress events to onProgress, tagged with the phase + engine agentId", async () => {
const events: UltraProgressEvent[] = [];
const fr = fakeRunner((args) => {
args.onProgress?.({
agentId: args.agentId,
phase: args.phase,
kind: "action",
toolName: "read",
text: "a.ts",
});
return { ok: true, value: 1 };
});
const s = spec({
phases: [
{ id: "scan", kind: "fanout", over: ["x"], step: { prompt: "{item}" } },
],
});
await runWorkflow(
s,
undefined,
baseDeps({
stepRunner: fr.runner,
concurrency: 1,
onProgress: (e) => events.push(e),
}),
);
const action = events.find((e) => e.kind === "action");
expect(action).toBeDefined();
expect(action?.phase).toBe("scan");
expect(action?.agentId).toBe("scan#0");
expect(action?.toolName).toBe("read");
});
it("flips steered to true when a forwarded agent's controls.steer is invoked, delegating to the bound control", async () => {
const steerSpy = vi.fn();
const fr = fakeRunner((args) => {
args.onProgress?.({
agentId: args.agentId,
phase: args.phase,
kind: "start",
controls: { steer: steerSpy, abort: vi.fn() },
});
return { ok: true, value: 1 };
});
// The overlay reacts to the first controls-bearing event by steering.
let steered = false;
const onProgress = (e: UltraProgressEvent) => {
if (e.controls && !steered) {
steered = true;
e.controls.steer("redirect now");
}
};
const s = spec({
phases: [{ id: "p", kind: "single", step: { prompt: "go" } }],
});
const res = await runWorkflow(
s,
undefined,
baseDeps({ stepRunner: fr.runner, concurrency: 1, onProgress }),
);
expect(steerSpy).toHaveBeenCalledWith("redirect now"); // delegated to the runner-bound control
expect(res.steered).toBe(true);
});
it("leaves steered false when no steer occurs", async () => {
const fr = fakeRunner(() => ({ ok: true, value: 1 }));
const s = spec({
phases: [{ id: "p", kind: "single", step: { prompt: "go" } }],
});
const res = await runWorkflow(
s,
undefined,
baseDeps({ stepRunner: fr.runner, concurrency: 1 }),
);
expect(res.steered).toBe(false);
});
});