Files
pi-subagent/test/observation.test.ts
T

264 lines
10 KiB
TypeScript

/**
* Observation seam properties: a run persists a constant number of entries no
* matter how many children it fans out, and a run interrupted at crash time
* restores from its start entry as interrupted with no task rows (ADR 0004).
*/
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 { formatWorkflowRunSummary } from "../src/journal.ts";
import { SubagentManager } from "../src/manager.ts";
import {
extractJobSnapshots,
extractWorkflowJournals,
persistedJob,
persistedWorkflowJournal,
SUBAGENT_JOB_ENTRY,
WORKFLOW_RUN_ENTRY,
} from "../src/persistence.ts";
import type { PersistedJob } from "../src/schemas.ts";
import { prepareWorkflowInvocation, type PrepareContext } from "../src/prepare.ts";
import { MAX_EXPANDED_CHILDREN, parseWorkflow, type WorkflowPlan } from "../src/workflow-plan.ts";
import type { ManagerOptions, TaskRunner } from "../src/types.ts";
import { FakeRunner, isRunWait } from "./helpers.ts";
const tempRoots: string[] = [];
after(() => {
for (const root of tempRoots) fs.rmSync(root, { recursive: true, force: true });
});
function makeWorkspace(): { cwd: string; ctx: PrepareContext } {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-observation-"));
tempRoots.push(root);
const agentsDir = path.join(root, ".pi", "agents");
fs.mkdirSync(agentsDir, { recursive: true });
fs.writeFileSync(path.join(agentsDir, "scout.md"), "---\nname: scout\ndescription: scout agent\n---\nYou are scout.\n");
return {
cwd: root,
ctx: {
cwd: root,
hasUI: false,
isProjectTrusted: () => true,
ui: { confirm: async () => true },
},
};
}
function makePlan(steps: Array<Record<string, unknown>>): WorkflowPlan {
const content = `---\n${JSON.stringify({ name: "scale", description: "Scale", args: [], steps }, null, 2)}\n---\n\nNotes.\n`;
return parseWorkflow(content, { source: "user", filePath: "/tmp/scale.md" });
}
function tick(): Promise<void> {
return new Promise((resolve) => setImmediate(resolve));
}
function pendingStep(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}`);
return call;
}
function completeStep(runner: FakeRunner, stepId: string, output = "done"): void {
runner.complete(pendingStep(runner, stepId).task.task, output);
}
/**
* A manager wired exactly like the extension: persistence records the start
* entry and the terminal checkpoint, never a per-transition snapshot.
*/
function recordingManager(runner: TaskRunner, options: ManagerOptions = {}) {
const entries: Array<{ type: "custom"; customType: string; data: unknown }> = [];
const manager = new SubagentManager(runner, {
...options,
onJobEvent: (event) => {
if (event.kind === "changed") return;
entries.push({
type: "custom",
customType: SUBAGENT_JOB_ENTRY,
data: persistedJob("test-session", manager.get(event.jobId)),
});
},
onWorkflowJournal: (journal) => {
entries.push({
type: "custom",
customType: WORKFLOW_RUN_ENTRY,
data: persistedWorkflowJournal("test-session", journal),
});
},
});
return { manager, entries };
}
test("property: a 256-child run persists a constant number of entries and O(N) bytes", async () => {
const { ctx } = makeWorkspace();
const plan = makePlan([
{ id: "source", agent: "scout", task: "emit lines" },
{ id: "work", agent: "scout", task: "work {item}", needs: ["source"], each: "{steps.source.output}" },
]);
const prepared = await prepareWorkflowInvocation(plan, {}, ctx, {
agentScope: "project",
confirmProjectAgents: false,
limits: { maxItemsPerEach: 255, maxExpandedChildren: MAX_EXPANDED_CHILDREN },
});
await fc.assert(
fc.asyncProperty(
fc.array(fc.string({ maxLength: 24 }), { minLength: 255, maxLength: 255 }),
async (generated) => {
// One source step plus 255 item children is exactly the run's 256-child ceiling.
const lines = generated.map((line, index) => `${index}-${line.trim() || "item"}`);
const runner = new FakeRunner();
const { manager, entries } = recordingManager(runner, { maxWorkers: 8 });
const started = manager.startWorkflow(prepared);
runner.complete("emit lines", lines.join("\n"));
await tick();
let settled = 0;
for (let wave = 0; settled < lines.length; wave++) {
assert.ok(wave < lines.length, "every item child must be driven to completion");
const pending = runner.calls.filter((call) => call.task.stepId === "work" && !call.settled);
for (const call of pending) {
runner.complete(call.task.task, "done");
settled++;
}
await tick();
}
assert.equal((await manager.wait(started.id, 5)).status, "succeeded");
// Start entry + terminal checkpoint + one journal: constant in children.
assert.deepEqual(
entries.map((entry) => entry.customType),
[SUBAGENT_JOB_ENTRY, SUBAGENT_JOB_ENTRY, WORKFLOW_RUN_ENTRY],
);
const bytes = Buffer.byteLength(JSON.stringify(entries), "utf8");
// Two bounded records per child plus the run header stay far under this;
// re-persisting a 256-row snapshot per transition would exceed it by orders of magnitude.
assert.ok(bytes <= 256 * 16 * 1024, `aggregate persisted bytes ${bytes} exceeded the linear budget`);
},
),
{ numRuns: 3 },
);
});
test("a run in flight at crash time restores as interrupted with zero task rows", async () => {
const { ctx } = makeWorkspace();
const plan = makePlan([
{ id: "source", agent: "scout", task: "scan" },
{ id: "work", agent: "scout", task: "work {item}", needs: ["source"], each: "{steps.source.output}" },
]);
const prepared = await prepareWorkflowInvocation(plan, {}, ctx, {
agentScope: "project",
confirmProjectAgents: false,
});
const { manager, entries } = recordingManager(new FakeRunner());
const started = manager.startWorkflow(prepared);
// The crash leaves only the start entry: no task rows, no checkpoint.
assert.equal(entries.length, 1);
const start = entries[0].data as PersistedJob;
assert.equal(start.job.status, "queued");
assert.equal(start.job.results.length, 0);
const crashed = structuredClone(entries);
await manager.shutdown();
const restored = new SubagentManager(new FakeRunner());
restored.restore(extractJobSnapshots(crashed));
const job = restored.get(started.id);
assert.equal(job.status, "interrupted");
assert.equal(job.mode, "workflow");
assert.deepEqual(job.results, []);
});
test("wait on a reloaded terminal run returns the consolidated answer its journal carried", 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 { manager, entries } = recordingManager(runner, { maxWorkers: 4 });
const started = manager.startWorkflow(
await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false }),
);
completeStep(runner, "scan", "src/a.ts");
await tick();
completeStep(runner, "audit", "no findings");
const before = await manager.wait(started.id, 5);
assert.ok(isRunWait(before));
assert.deepEqual(before.steps.map((step) => step.line), ["scan succeeded", "audit succeeded"]);
assert.deepEqual(before.answer, { stepId: "audit", output: "no findings" });
// The terminal checkpoint and the journal were written at the same
// transition; reload reads both and keeps the same bounded answer.
const persisted = entries.map((entry) => JSON.parse(JSON.stringify(entry)) as unknown);
await manager.shutdown();
const reloaded = new SubagentManager(new FakeRunner());
reloaded.restore(extractJobSnapshots(persisted), extractWorkflowJournals(persisted));
const after = await reloaded.wait(started.id, 1);
assert.ok(isRunWait(after));
assert.equal(formatWorkflowRunSummary(after), formatWorkflowRunSummary(before));
assert.deepEqual(after.steps.map((step) => step.line), before.steps.map((step) => step.line));
assert.deepEqual(after.answer, before.answer);
});
test("wait on a crash-restored run returns status and error with no step lines", 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 { manager, entries } = recordingManager(new FakeRunner());
const started = manager.startWorkflow(
await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false }),
);
// The crash leaves only the start entry: no task rows, no journal (ADR 0004).
const crashed = structuredClone(entries);
await manager.shutdown();
const restored = new SubagentManager(new FakeRunner());
restored.restore(extractJobSnapshots(crashed));
const answer = await restored.wait(started.id, 1);
assert.ok(isRunWait(answer));
assert.equal(answer.status, "interrupted");
assert.deepEqual(answer.steps, []);
assert.equal(answer.answer, undefined);
assert.match(answer.error ?? "", /Interrupted by session restart/);
assert.equal(formatWorkflowRunSummary(answer).includes("Steps:"), false);
});
test("a run whose supervisor loop throws finalizes failed, journals nothing, and wait degrades to status and error", async () => {
const { ctx } = makeWorkspace();
const plan = makePlan([{ id: "scan", agent: "scout", task: "scan" }]);
const prepared = await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false });
// A need the DAG index cannot satisfy bypasses plan validation and makes the
// step unreleasable, so the supervisor's stall guard fires before settling.
prepared.workflow.steps[0].needs = ["ghost"];
const runner = new FakeRunner();
const journals: unknown[] = [];
const manager = new SubagentManager(runner, { onWorkflowJournal: (journal) => journals.push(journal) });
const started = manager.startWorkflow(prepared);
const answer = await manager.wait(started.id, 1);
assert.ok(isRunWait(answer));
assert.equal(answer.status, "failed");
assert.deepEqual(answer.steps, []);
assert.match(answer.error ?? "", /stalled with no releasable steps/);
assert.deepEqual(journals, []);
assert.equal(runner.calls.length, 0);
const job = manager.get(started.id);
assert.equal(job.status, "failed");
assert.deepEqual(job.results.map((row) => row.status), ["queued"]);
});