682 lines
29 KiB
TypeScript
682 lines
29 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 { buildWorkflowJournal, WORKFLOW_HASH_PAYLOAD_VERSION, workflowItemInputHash, workflowStepInputHash, type WorkflowJournalRun } from "../src/journal.ts";
|
|
import type { InternalTask } from "../src/job-state.ts";
|
|
import { SubagentManager } from "../src/manager.ts";
|
|
import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "../src/output.ts";
|
|
import {
|
|
extractJobSnapshots,
|
|
extractWorkflowJournals,
|
|
persistedJob,
|
|
persistedWorkflowJournal,
|
|
SUBAGENT_JOB_ENTRY,
|
|
WORKFLOW_RUN_ENTRY,
|
|
} from "../src/persistence.ts";
|
|
import { prepareWorkflowInvocation, type PrepareContext } from "../src/prepare.ts";
|
|
import { parseWorkflow, type WorkflowPlan, type WorkflowSource } from "../src/workflow-plan.ts";
|
|
import { emptyUsage, type JobSnapshot, type TaskSnapshot, type TaskStatus, type WorkflowJournal, type WorkflowJournalItem, type WorkflowJournalStep } from "../src/types.ts";
|
|
import { FakeRunner, waitForSnapshot } 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-journal-"));
|
|
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<Record<string, unknown>>,
|
|
args: string[] = [],
|
|
provenance: { source?: WorkflowSource; filePath?: 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: provenance.source ?? "user",
|
|
filePath: provenance.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<string, unknown> = {}): void {
|
|
const call = pending(runner, stepId);
|
|
runner.complete(call.task.task, output, overrides);
|
|
}
|
|
|
|
function tick(): Promise<void> {
|
|
return new Promise((resolve) => setImmediate(resolve));
|
|
}
|
|
|
|
/** What the session store does to a custom entry between turns. */
|
|
function serialized(entry: unknown): unknown {
|
|
return JSON.parse(JSON.stringify(entry));
|
|
}
|
|
|
|
/** One row of a run's DAG index: the shared record the journal projects. */
|
|
function taskRow(stepId: string, status: TaskStatus, output = "", extra: Partial<TaskSnapshot> = {}): InternalTask {
|
|
return {
|
|
messages: [],
|
|
snapshot: {
|
|
agent: "scout",
|
|
agentSource: "user",
|
|
task: "check",
|
|
cwd: "/tmp",
|
|
stepId,
|
|
status,
|
|
exitCode: status === "succeeded" ? 0 : 1,
|
|
output,
|
|
outputTruncated: false,
|
|
outputBytesOmitted: 0,
|
|
stderr: "",
|
|
stderrTruncated: false,
|
|
usage: emptyUsage(),
|
|
startedAt: 2,
|
|
finishedAt: 3,
|
|
...extra,
|
|
},
|
|
};
|
|
}
|
|
|
|
/** The job record's head as the journal carries it, plus the rows its usage sums. */
|
|
function jobHead(rows: InternalTask[], overrides: Partial<WorkflowJournalRun["execution"]> = {}): WorkflowJournalRun["execution"] {
|
|
return { id: "job_0009", status: "succeeded", tasks: rows, createdAt: 1, startedAt: 2, finishedAt: 3, ...overrides };
|
|
}
|
|
|
|
test("a finished run persists one journal entry with per-step records and usage", async () => {
|
|
const { ctx } = makeWorkspace();
|
|
const plan = makePlan(
|
|
[
|
|
{ id: "scan", agent: "scout", task: "scan {args.target}" },
|
|
{ id: "audit", agent: "scout", task: "audit {steps.scan.output}", needs: ["scan"] },
|
|
],
|
|
["target"],
|
|
);
|
|
const runner = new FakeRunner();
|
|
const journals: WorkflowJournal[] = [];
|
|
const manager = new SubagentManager(runner, { onWorkflowJournal: (journal) => journals.push(journal) });
|
|
const started = manager.startWorkflow(
|
|
await prepareWorkflowInvocation(plan, { target: "src" }, ctx, { agentScope: "project", confirmProjectAgents: false }),
|
|
);
|
|
|
|
completeStep(runner, "scan", "src/a.ts");
|
|
await tick();
|
|
completeStep(runner, "audit", "no findings");
|
|
const terminal = await waitForSnapshot(manager, started.id, 1);
|
|
|
|
assert.equal(terminal.status, "succeeded");
|
|
assert.equal(journals.length, 1);
|
|
const journal = journals[0];
|
|
assert.equal(journal.jobId, started.id);
|
|
assert.equal(journal.status, "succeeded");
|
|
assert.deepEqual(journal.plan, plan);
|
|
assert.deepEqual(journal.args, { target: "src" });
|
|
assert.deepEqual(journal.usage, terminal.usage);
|
|
assert.deepEqual(
|
|
journal.steps.map((step) => [step.id, step.status, step.attempts, step.output]),
|
|
[
|
|
["scan", "succeeded", 1, "src/a.ts"],
|
|
["audit", "succeeded", 1, "no findings"],
|
|
],
|
|
);
|
|
for (const step of journal.steps) {
|
|
assert.match(step.inputHash, /^sha256:[0-9a-f]{64}$/);
|
|
assert.equal(typeof step.startedAt, "number");
|
|
assert.equal(typeof step.finishedAt, "number");
|
|
}
|
|
|
|
const entry = serialized({ type: "custom", customType: WORKFLOW_RUN_ENTRY, data: persistedWorkflowJournal("session-a", journal) });
|
|
assert.deepEqual(extractWorkflowJournals([entry]), [serialized(journal)]);
|
|
});
|
|
|
|
test("an unfinished run journals once as interrupted and restores interrupted after reload", async () => {
|
|
const { ctx } = makeWorkspace();
|
|
const plan = makePlan([
|
|
{ id: "scan", agent: "scout", task: "scan" },
|
|
{ id: "audit", agent: "scout", task: "audit {steps.scan.output}", needs: ["scan"] },
|
|
]);
|
|
const runner = new FakeRunner();
|
|
const journals: WorkflowJournal[] = [];
|
|
const jobs: JobSnapshot[] = [];
|
|
const manager = new SubagentManager(runner, {
|
|
maxWorkers: 2,
|
|
onJobEvent: (event) => {
|
|
// Persistence checkpoints at the terminal transition only (ADR 0004).
|
|
if (event.kind === "finalized") jobs.push(manager.get(event.jobId));
|
|
},
|
|
onWorkflowJournal: (journal) => journals.push(journal),
|
|
});
|
|
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"]);
|
|
|
|
await manager.shutdown();
|
|
|
|
assert.equal(journals.length, 1, "one journal entry per run, not one per state change");
|
|
const journal = journals[0];
|
|
assert.equal(journal.status, "interrupted");
|
|
assert.deepEqual(
|
|
journal.steps.map((step) => [step.id, step.status, step.attempts]),
|
|
[
|
|
["scan", "interrupted", 1],
|
|
["audit", "interrupted", 0],
|
|
],
|
|
);
|
|
|
|
// Reload: the job snapshots restore interrupted (existing job semantics) and
|
|
// the journal record read back from the branch stays intact.
|
|
const entry = serialized({ type: "custom", customType: WORKFLOW_RUN_ENTRY, data: persistedWorkflowJournal("session-a", journal) });
|
|
const jobEntries = jobs.map((job) => serialized({ type: "custom", customType: SUBAGENT_JOB_ENTRY, data: persistedJob("session-a", job) }));
|
|
const replayed: unknown[] = [];
|
|
const reloaded = new SubagentManager(new FakeRunner(), { onWorkflowJournal: (journal) => replayed.push(journal) });
|
|
reloaded.restore(extractJobSnapshots(jobEntries));
|
|
assert.equal(reloaded.get(started.id).status, "interrupted");
|
|
assert.deepEqual(replayed, [], "restoring a run never writes a second journal record");
|
|
assert.deepEqual(extractWorkflowJournals([entry]), [serialized(journal)]);
|
|
});
|
|
|
|
test("oversized step outputs are bounded to the async snapshot budget with the truncation marker", async () => {
|
|
const { ctx } = makeWorkspace();
|
|
const plan = makePlan([{ id: "scan", agent: "scout", task: "scan" }]);
|
|
const prepared = await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false });
|
|
const oversized = "é".repeat(60 * 1024);
|
|
// The same bound an async task snapshot applies to a child's output.
|
|
const snapshotBound = truncateUtf8Head(oversized, MAX_TASK_OUTPUT_BYTES);
|
|
|
|
const scan = taskRow("scan", "succeeded", oversized);
|
|
const journal = buildWorkflowJournal({
|
|
execution: jobHead([scan]),
|
|
spec: prepared.workflow,
|
|
stepTasks: new Map([["scan", scan]]),
|
|
itemTasks: new Map(),
|
|
});
|
|
const record = journal.steps[0];
|
|
const [kept, note] = record.output.split("\n\n[Output truncated: ");
|
|
assert.equal(kept, snapshotBound.text);
|
|
assert.equal(note, `${snapshotBound.bytesOmitted} bytes omitted]`);
|
|
assert.equal(Buffer.byteLength(kept, "utf8"), MAX_TASK_OUTPUT_BYTES);
|
|
assert.equal(record.outputTruncated, true);
|
|
assert.equal(record.outputBytesOmitted, Buffer.byteLength(oversized, "utf8") - MAX_TASK_OUTPUT_BYTES);
|
|
|
|
// A snapshot the manager already bounded keeps its own omission count
|
|
// instead of re-marking the text.
|
|
const boundedRow = taskRow("scan", "succeeded", snapshotBound.text, {
|
|
outputTruncated: true,
|
|
outputBytesOmitted: snapshotBound.bytesOmitted,
|
|
});
|
|
const bounded = buildWorkflowJournal({
|
|
execution: jobHead([boundedRow]),
|
|
spec: prepared.workflow,
|
|
stepTasks: new Map([["scan", boundedRow]]),
|
|
itemTasks: new Map(),
|
|
});
|
|
assert.equal(bounded.steps[0].output.split("[Output truncated: ").length, 2);
|
|
assert.equal(bounded.steps[0].outputBytesOmitted, snapshotBound.bytesOmitted);
|
|
|
|
const entry = serialized({ type: "custom", customType: WORKFLOW_RUN_ENTRY, data: persistedWorkflowJournal("session-a", journal) });
|
|
assert.deepEqual(extractWorkflowJournals([entry]), [serialized(journal)]);
|
|
});
|
|
|
|
test("step input hashes are stable across identical inputs and change with args or briefs", () => {
|
|
const steps = [{ id: "scan", agent: "scout", task: "scan {args.target}" }];
|
|
const first = makePlan(steps, ["target"]);
|
|
const second = makePlan(steps, ["target"]);
|
|
const hashes = (plan: WorkflowPlan, args: Record<string, string>) =>
|
|
plan.steps.map((step) => workflowStepInputHash(plan, step.id, args));
|
|
|
|
assert.deepEqual(hashes(first, { target: "src" }), hashes(second, { target: "src" }));
|
|
assert.notDeepEqual(hashes(first, { target: "src" }), hashes(first, { target: "lib" }));
|
|
assert.notEqual(
|
|
workflowStepInputHash(makePlan([{ id: "scan", agent: "scout", task: "scan {args.target} twice" }], ["target"]), "scan", { target: "src" }),
|
|
workflowStepInputHash(first, "scan", { target: "src" }),
|
|
);
|
|
assert.notEqual(workflowStepInputHash(first, "ghost", { target: "src" }), workflowStepInputHash(first, "scan", { target: "src" }));
|
|
|
|
// Whole steps are hashed: a step field beyond the brief still moves the hash.
|
|
const withCwd = makePlan([{ id: "scan", agent: "scout", task: "scan {args.target}", cwd: "src" }], ["target"]);
|
|
assert.notEqual(workflowStepInputHash(withCwd, "scan", { target: "src" }), workflowStepInputHash(first, "scan", { target: "src" }));
|
|
|
|
// Provenance is not an input: the same plan copied elsewhere hashes alike.
|
|
const elsewhere = makePlan(steps, ["target"], { source: "project", filePath: "/repo/.pi/workflows/test-workflow.md" });
|
|
assert.equal(workflowStepInputHash(elsewhere, "scan", { target: "src" }), workflowStepInputHash(first, "scan", { target: "src" }));
|
|
});
|
|
|
|
test("the input-hash payload carries the replay-contract version", () => {
|
|
// Nothing replays today (ADR 0004 journal-only); the marker only separates
|
|
// hash eras, so moving it is a deliberate migration, never a refactor.
|
|
assert.equal(WORKFLOW_HASH_PAYLOAD_VERSION, 2);
|
|
});
|
|
|
|
test("journals hash the step inputs, not the outputs, so identical runs agree", async () => {
|
|
const { ctx } = makeWorkspace();
|
|
const plan = makePlan([
|
|
{ id: "scan", agent: "scout", task: "scan {args.target}" },
|
|
{ id: "audit", agent: "scout", task: "audit {steps.scan.output}", needs: ["scan"] },
|
|
], ["target"]);
|
|
|
|
async function run(args: Record<string, string>, output: string): Promise<WorkflowJournal> {
|
|
const runner = new FakeRunner();
|
|
const journals: WorkflowJournal[] = [];
|
|
const manager = new SubagentManager(runner, { onWorkflowJournal: (journal) => journals.push(journal) });
|
|
const started = manager.startWorkflow(
|
|
await prepareWorkflowInvocation(plan, args, ctx, { agentScope: "project", confirmProjectAgents: false }),
|
|
);
|
|
completeStep(runner, "scan", `${output} sources`);
|
|
await tick();
|
|
completeStep(runner, "audit", output);
|
|
await waitForSnapshot(manager, started.id, 1);
|
|
assert.equal(journals.length, 1);
|
|
return journals[0];
|
|
}
|
|
|
|
const first = await run({ target: "src" }, "first");
|
|
const second = await run({ target: "src" }, "second, different output");
|
|
const otherArgs = await run({ target: "lib" }, "first");
|
|
|
|
const hashes = (journal: WorkflowJournal) => journal.steps.map((step) => [step.id, step.inputHash]);
|
|
assert.deepEqual(hashes(first), hashes(second));
|
|
assert.notDeepEqual(hashes(first), hashes(otherArgs));
|
|
assert.equal(first.steps.every((step) => step.inputHash.startsWith("sha256:")), true);
|
|
});
|
|
|
|
test("journal extraction ignores foreign and malformed entries and keeps the latest record per run", async () => {
|
|
const { ctx } = makeWorkspace();
|
|
const plan = makePlan([{ id: "scan", agent: "scout", task: "scan" }]);
|
|
const prepared = await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false });
|
|
const scan = taskRow("scan", "failed", "", { errorMessage: "boom" });
|
|
const journal = buildWorkflowJournal({
|
|
execution: jobHead([scan], { id: "job_0010", status: "failed", startedAt: undefined, finishedAt: 2 }),
|
|
spec: prepared.workflow,
|
|
stepTasks: new Map([["scan", scan]]),
|
|
itemTasks: new Map(),
|
|
});
|
|
const entry = serialized({ type: "custom", customType: WORKFLOW_RUN_ENTRY, data: persistedWorkflowJournal("session-a", journal) });
|
|
const later = serialized({
|
|
type: "custom",
|
|
customType: WORKFLOW_RUN_ENTRY,
|
|
data: persistedWorkflowJournal("session-a", { ...journal, status: "interrupted" }),
|
|
});
|
|
const broken = serialized({
|
|
type: "custom",
|
|
customType: WORKFLOW_RUN_ENTRY,
|
|
data: { version: 1, sessionId: "session-a", journal: { jobId: "job_0010", status: "success?" } },
|
|
});
|
|
|
|
assert.deepEqual(extractWorkflowJournals([broken, entry, later]), [serialized({ ...journal, status: "interrupted" })]);
|
|
assert.deepEqual(extractWorkflowJournals([{ type: "custom", customType: "other", data: persistedWorkflowJournal("session-a", journal) }, { type: "message" }]), []);
|
|
// A journal record is not a job snapshot: the two entry types stay separate.
|
|
assert.deepEqual(extractJobSnapshots([entry]), []);
|
|
});
|
|
|
|
test("a failed run journals skipped dependents and retains the independent branches", 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"] },
|
|
]);
|
|
const runner = new FakeRunner();
|
|
const journals: WorkflowJournal[] = [];
|
|
const manager = new SubagentManager(runner, { maxWorkers: 3, onWorkflowJournal: (journal) => journals.push(journal) });
|
|
const started = manager.startWorkflow(
|
|
await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false }),
|
|
);
|
|
|
|
completeStep(runner, "scan", "partial", { exitCode: 1, errorMessage: "scan exploded" });
|
|
await tick();
|
|
completeStep(runner, "notify", "sent");
|
|
assert.equal((await waitForSnapshot(manager, started.id, 1)).status, "failed");
|
|
|
|
assert.equal(journals.length, 1);
|
|
assert.equal(journals[0].status, "failed");
|
|
assert.deepEqual(
|
|
journals[0].steps.map((step) => [step.id, step.status, step.attempts]),
|
|
[
|
|
["scan", "failed", 1],
|
|
["notify", "succeeded", 1],
|
|
["audit", "skipped", 0],
|
|
],
|
|
);
|
|
assert.equal(journals[0].steps[2].output, "");
|
|
});
|
|
|
|
test("a cancelled run journals once, with every unfinished step settled cancelled", async () => {
|
|
const { ctx } = makeWorkspace();
|
|
const plan = makePlan([
|
|
{ id: "scan", agent: "scout", task: "scan" },
|
|
{ id: "audit", agent: "scout", task: "audit {steps.scan.output}", needs: ["scan"] },
|
|
]);
|
|
const runner = new FakeRunner();
|
|
const journals: WorkflowJournal[] = [];
|
|
const manager = new SubagentManager(runner, { onWorkflowJournal: (journal) => journals.push(journal) });
|
|
const started = manager.startWorkflow(
|
|
await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false }),
|
|
);
|
|
|
|
manager.cancel(started.id);
|
|
assert.equal((await waitForSnapshot(manager, started.id, 1)).status, "cancelled");
|
|
assert.equal(journals.length, 1);
|
|
assert.equal(journals[0].status, "cancelled");
|
|
assert.deepEqual(
|
|
journals[0].steps.map((step) => [step.id, step.status, step.attempts]),
|
|
[
|
|
["scan", "cancelled", 1],
|
|
["audit", "cancelled", 0],
|
|
],
|
|
);
|
|
});
|
|
|
|
test("an each-step journals per-item rows alongside its aggregate step record", async () => {
|
|
const { ctx } = makeWorkspace();
|
|
const plan = makePlan([
|
|
{ id: "list", agent: "scout", task: "list" },
|
|
{ id: "check", agent: "scout", task: "check {item}", needs: ["list"], each: "{steps.list.output}" },
|
|
]);
|
|
const prepared = await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false });
|
|
const list = taskRow("list", "succeeded", "src/a.ts\nsrc/b.ts");
|
|
// The coordinator row carries the joined item output and the aggregate
|
|
// status; the item children sit in the index beside it.
|
|
const check = taskRow("check", "succeeded", "aggregate");
|
|
const items = [
|
|
taskRow("check", "succeeded", "ok a", { item: 1, itemValue: "src/a.ts" }),
|
|
taskRow("check", "failed", "boom b", { item: 2, itemValue: "src/b.ts" }),
|
|
];
|
|
|
|
const journal = buildWorkflowJournal({
|
|
execution: jobHead([list, check, ...items], { id: "job_0011" }),
|
|
spec: prepared.workflow,
|
|
stepTasks: new Map([["list", list], ["check", check]]),
|
|
itemTasks: new Map([["check", items]]),
|
|
});
|
|
assert.equal(journal.steps.length, 2, "one journal record per plan step");
|
|
assert.deepEqual(
|
|
journal.steps.map((step) => [step.id, step.status, step.output]),
|
|
[
|
|
["list", "succeeded", "src/a.ts\nsrc/b.ts"],
|
|
["check", "succeeded", "aggregate"],
|
|
],
|
|
);
|
|
assert.equal(journal.steps[1].attempts, 1, "a started step records its attempt count");
|
|
assert.deepEqual(journal.steps[0].items, [], "a step that does not fan out has no item rows");
|
|
assert.deepEqual(
|
|
journal.steps[1].items.map((row) => [row.item, row.input, row.status, row.attempts, row.output]),
|
|
[
|
|
// A failed item keeps its own output here, even though the joined step
|
|
// output leaves it an empty slot.
|
|
[1, "src/a.ts", "succeeded", 1, "ok a"],
|
|
[2, "src/b.ts", "failed", 1, "boom b"],
|
|
],
|
|
);
|
|
for (const row of journal.steps[1].items) {
|
|
assert.match(row.inputHash, /^sha256:[0-9a-f]{64}$/);
|
|
assert.equal(typeof row.startedAt, "number");
|
|
assert.equal(typeof row.finishedAt, "number");
|
|
assert.equal(row.outputTruncated, false);
|
|
assert.equal(row.outputBytesOmitted, 0);
|
|
}
|
|
});
|
|
|
|
test("item rows round-trip through the run entry and malformed rows are rejected", () => {
|
|
const plan = makePlan([
|
|
{ id: "list", agent: "scout", task: "list" },
|
|
{ id: "check", agent: "scout", task: "check {item}", needs: ["list"], each: "{steps.list.output}" },
|
|
]);
|
|
const hash = (seed: string) => `sha256:${seed.repeat(64).slice(0, 64)}`;
|
|
const itemRow = (item: number, input: string): WorkflowJournalItem => ({
|
|
item,
|
|
input,
|
|
inputHash: hash(String(item)),
|
|
status: "succeeded",
|
|
attempts: 1,
|
|
output: `ok ${input}`,
|
|
outputTruncated: false,
|
|
outputBytesOmitted: 0,
|
|
startedAt: 4,
|
|
finishedAt: 5,
|
|
});
|
|
const step = (id: string, overrides: Partial<WorkflowJournalStep> = {}): WorkflowJournalStep => ({
|
|
id,
|
|
inputHash: hash(id),
|
|
status: "succeeded",
|
|
attempts: 1,
|
|
output: "",
|
|
outputTruncated: false,
|
|
outputBytesOmitted: 0,
|
|
startedAt: 2,
|
|
finishedAt: 3,
|
|
items: [],
|
|
...overrides,
|
|
});
|
|
const journal: WorkflowJournal = {
|
|
jobId: "job_0012",
|
|
status: "succeeded",
|
|
plan,
|
|
args: {},
|
|
steps: [step("list"), step("check", { items: [itemRow(1, "src/a.ts"), itemRow(2, "src/b.ts")] })],
|
|
usage: emptyUsage(),
|
|
createdAt: 1,
|
|
startedAt: 2,
|
|
finishedAt: 3,
|
|
};
|
|
const entry = serialized({ type: "custom", customType: WORKFLOW_RUN_ENTRY, data: persistedWorkflowJournal("session-a", journal) });
|
|
|
|
assert.deepEqual(extractWorkflowJournals([entry]), [serialized(journal)]);
|
|
|
|
const withSteps = (steps: WorkflowJournalStep[]) =>
|
|
serialized({ type: "custom", customType: WORKFLOW_RUN_ENTRY, data: persistedWorkflowJournal("session-a", { ...journal, steps }) });
|
|
const { items: _items, ...withoutItems } = step("check");
|
|
assert.deepEqual(extractWorkflowJournals([withSteps([step("list"), withoutItems as WorkflowJournalStep])]), [], "item rows are part of the step record, not optional");
|
|
assert.deepEqual(
|
|
extractWorkflowJournals([withSteps([step("list"), step("check", { items: [{ ...itemRow(1, "src/a.ts"), item: 0 }] })])]),
|
|
[],
|
|
"item indexes are one-based",
|
|
);
|
|
assert.deepEqual(
|
|
extractWorkflowJournals([withSteps([step("list"), step("check", { items: [{ ...itemRow(1, "src/a.ts"), inputHash: 7 } as unknown as WorkflowJournalItem] })])]),
|
|
[],
|
|
"every item row carries an input hash",
|
|
);
|
|
});
|
|
|
|
test("item input hashes are stable across identical inputs and change with the item, args, or brief", () => {
|
|
const steps = [
|
|
{ id: "scan", agent: "scout", task: "scan" },
|
|
{ id: "audit", agent: "scout", task: "audit {item} for {args.target}", needs: ["scan"], each: "{steps.scan.output}" },
|
|
];
|
|
const first = makePlan(steps, ["target"]);
|
|
const second = makePlan(steps, ["target"]);
|
|
const hash = (plan: WorkflowPlan, args: Record<string, string>, item: string) =>
|
|
workflowItemInputHash(plan, "audit", args, item);
|
|
|
|
assert.match(hash(first, { target: "src" }, "src/a.ts"), /^sha256:[0-9a-f]{64}$/);
|
|
assert.equal(hash(first, { target: "src" }, "src/a.ts"), hash(second, { target: "src" }, "src/a.ts"));
|
|
assert.notEqual(hash(first, { target: "src" }, "src/a.ts"), hash(first, { target: "src" }, "src/b.ts"));
|
|
assert.notEqual(hash(first, { target: "src" }, "src/a.ts"), hash(first, { target: "lib" }, "src/a.ts"));
|
|
// The item hash keys the step's inputs plus the item, so it is not its step's hash.
|
|
assert.notEqual(hash(first, { target: "src" }, "src/a.ts"), workflowStepInputHash(first, "audit", { target: "src" }));
|
|
|
|
const reworded = makePlan([
|
|
{ id: "scan", agent: "scout", task: "scan" },
|
|
{ id: "audit", agent: "scout", task: "audit {item} twice for {args.target}", needs: ["scan"], each: "{steps.scan.output}" },
|
|
], ["target"]);
|
|
assert.notEqual(hash(reworded, { target: "src" }, "src/a.ts"), hash(first, { target: "src" }, "src/a.ts"));
|
|
});
|
|
|
|
test("property: item input hashes depend only on the plan, args, and item line", () => {
|
|
const steps = [
|
|
{ id: "scan", agent: "scout", task: "scan" },
|
|
{ id: "audit", agent: "scout", task: "audit {item} for {args.target}", needs: ["scan"], each: "{steps.scan.output}" },
|
|
];
|
|
const plan = makePlan(steps, ["target"]);
|
|
fc.assert(
|
|
fc.property(
|
|
fc.string({ maxLength: 60 }),
|
|
fc.string({ maxLength: 60 }),
|
|
fc.string({ maxLength: 20 }),
|
|
(left, right, target) => {
|
|
const args = { target };
|
|
// Separately parsed plans with the same content agree.
|
|
assert.equal(
|
|
workflowItemInputHash(makePlan(steps, ["target"]), "audit", args, left),
|
|
workflowItemInputHash(plan, "audit", args, left),
|
|
);
|
|
if (left !== right) {
|
|
assert.notEqual(
|
|
workflowItemInputHash(plan, "audit", args, left),
|
|
workflowItemInputHash(plan, "audit", args, right),
|
|
);
|
|
}
|
|
},
|
|
),
|
|
{ numRuns: 100 },
|
|
);
|
|
});
|
|
|
|
test("a run journals each item's source line, status, and timings through the manager", async () => {
|
|
const { ctx } = makeWorkspace();
|
|
const plan = makePlan([
|
|
{ id: "scan", agent: "scout", task: "scan {args.target}" },
|
|
{ id: "audit", agent: "scout", task: "audit {item}", needs: ["scan"], each: "{steps.scan.output}" },
|
|
], ["target"]);
|
|
|
|
async function run(source: string): Promise<{ journal: WorkflowJournal; job: JobSnapshot }> {
|
|
const runner = new FakeRunner();
|
|
const journals: WorkflowJournal[] = [];
|
|
const jobs: JobSnapshot[] = [];
|
|
const manager = new SubagentManager(runner, {
|
|
onJobEvent: (event) => {
|
|
if (event.kind === "finalized") jobs.push(manager.get(event.jobId));
|
|
},
|
|
onWorkflowJournal: (journal) => journals.push(journal),
|
|
});
|
|
const started = manager.startWorkflow(
|
|
await prepareWorkflowInvocation(plan, { target: "src" }, ctx, { agentScope: "project", confirmProjectAgents: false }),
|
|
);
|
|
completeStep(runner, "scan", source);
|
|
await tick();
|
|
runner.complete("audit src/a.ts", "ok a");
|
|
runner.complete("audit src/b.ts", "bad b", { exitCode: 1, errorMessage: "b exploded" });
|
|
assert.equal((await waitForSnapshot(manager, started.id, 1)).status, "failed", "a failed item fails the run");
|
|
assert.equal(journals.length, 1);
|
|
return { journal: journals[0], job: jobs.at(-1)! };
|
|
}
|
|
|
|
const { journal, job } = await run(" src/a.ts\nsrc/b.ts ");
|
|
const audit = journal.steps[1];
|
|
assert.equal(audit.status, "succeeded", "the step itself degrades to a success");
|
|
assert.match(audit.output, /^### src\/a\.ts\n\nok a/);
|
|
assert.deepEqual(
|
|
audit.items.map((row) => [row.item, row.input, row.status, row.attempts, row.output]),
|
|
[
|
|
[1, "src/a.ts", "succeeded", 1, "ok a"],
|
|
[2, "src/b.ts", "failed", 1, "bad b"],
|
|
],
|
|
);
|
|
for (const row of audit.items) {
|
|
assert.equal(typeof row.startedAt, "number");
|
|
assert.equal(typeof row.finishedAt, "number");
|
|
}
|
|
assert.equal(audit.items[0].inputHash === audit.items[1].inputHash, false);
|
|
assert.deepEqual(journal.steps[0].items, []);
|
|
|
|
const entry = serialized({ type: "custom", customType: WORKFLOW_RUN_ENTRY, data: persistedWorkflowJournal("session-a", journal) });
|
|
assert.deepEqual(extractWorkflowJournals([entry]), [serialized(journal)]);
|
|
|
|
// Same items, differently formatted source: the item hashes do not move.
|
|
const reformatted = await run("src/a.ts\r\nsrc/b.ts");
|
|
assert.deepEqual(
|
|
reformatted.journal.steps[1].items.map((row) => [row.input, row.inputHash]),
|
|
audit.items.map((row) => [row.input, row.inputHash]),
|
|
);
|
|
|
|
// The job snapshot carries the same identity, so a reloaded run keeps it.
|
|
const itemRows = (snapshot: JobSnapshot) => snapshot.results.filter((row) => row.stepId === "audit" && row.item !== undefined);
|
|
assert.deepEqual(itemRows(job).map((row) => [row.item, row.itemValue]), [[1, "src/a.ts"], [2, "src/b.ts"]]);
|
|
const jobEntry = serialized({ type: "custom", customType: SUBAGENT_JOB_ENTRY, data: persistedJob("session-a", job) });
|
|
assert.deepEqual(extractJobSnapshots([jobEntry])[0].results.filter((row) => row.stepId === "audit" && row.item !== undefined).map((row) => row.itemValue), ["src/a.ts", "src/b.ts"]);
|
|
const brokenJob = serialized({
|
|
type: "custom",
|
|
customType: SUBAGENT_JOB_ENTRY,
|
|
data: persistedJob("session-a", {
|
|
...job,
|
|
results: job.results.map((row) =>
|
|
row.stepId === "audit" && row.item === 2 ? { ...row, itemValue: 42 as unknown as string } : row,
|
|
),
|
|
}),
|
|
});
|
|
assert.deepEqual(extractJobSnapshots([brokenJob]), [], "an item's source line is a string or absent");
|
|
});
|
|
|
|
test("oversized item outputs are bounded like step outputs and survive the round trip", async () => {
|
|
const { ctx } = makeWorkspace();
|
|
const plan = makePlan([
|
|
{ id: "list", agent: "scout", task: "list" },
|
|
{ id: "check", agent: "scout", task: "check {item}", needs: ["list"], each: "{steps.list.output}" },
|
|
]);
|
|
const prepared = await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false });
|
|
const oversized = "é".repeat(60 * 1024);
|
|
const snapshotBound = truncateUtf8Head(oversized, MAX_TASK_OUTPUT_BYTES);
|
|
const list = taskRow("list", "succeeded", "src/a.ts\nsrc/b.ts");
|
|
const check = taskRow("check", "succeeded", "aggregate");
|
|
const first = taskRow("check", "succeeded", oversized, { item: 1, itemValue: "src/a.ts" });
|
|
const second = taskRow("check", "succeeded", snapshotBound.text, {
|
|
item: 2,
|
|
itemValue: "src/b.ts",
|
|
outputTruncated: true,
|
|
outputBytesOmitted: snapshotBound.bytesOmitted,
|
|
});
|
|
|
|
const journal = buildWorkflowJournal({
|
|
execution: jobHead([list, check, first, second], { id: "job_0013" }),
|
|
spec: prepared.workflow,
|
|
stepTasks: new Map([["list", list], ["check", check]]),
|
|
itemTasks: new Map([["check", [first, second]]]),
|
|
});
|
|
const [boundedFirst, boundedSecond] = journal.steps[1].items;
|
|
const [kept, note] = boundedFirst.output.split("\n\n[Output truncated: ");
|
|
assert.equal(kept, snapshotBound.text);
|
|
assert.equal(note, `${snapshotBound.bytesOmitted} bytes omitted]`);
|
|
assert.equal(Buffer.byteLength(kept, "utf8"), MAX_TASK_OUTPUT_BYTES);
|
|
assert.equal(boundedFirst.outputTruncated, true);
|
|
assert.equal(boundedFirst.outputBytesOmitted, Buffer.byteLength(oversized, "utf8") - MAX_TASK_OUTPUT_BYTES);
|
|
|
|
// An already-bounded item row keeps its own omission count instead of
|
|
// re-marking the text, exactly like a step row.
|
|
assert.equal(boundedSecond.output.split("[Output truncated: ").length, 2);
|
|
assert.equal(boundedSecond.outputBytesOmitted, snapshotBound.bytesOmitted);
|
|
|
|
const entry = serialized({ type: "custom", customType: WORKFLOW_RUN_ENTRY, data: persistedWorkflowJournal("session-a", journal) });
|
|
assert.deepEqual(extractWorkflowJournals([entry]), [serialized(journal)]);
|
|
});
|
|
|