Project the workflow journal from run state
The journal rebuilt the step/item graph from the flat job record: rows were grouped by stepId, an each-step's coordinator row was picked out of the collision with its item children, and a positional fallback covered rows without step ids. After the seam (#22) the supervisor owns the DAG index, so the record is a projection of that state instead. - WorkflowSupervisor.journal(execution) projects the record from its stepTasks/itemTasks index and the run spec while the run is live. - journal.ts keeps the pure row builders, now over the shared InternalTask record, and builds the record from plan order plus the index; itemsByStep, the byStep collision handling, and the positional fallback are gone. - The manager calls the run's projection at finalize and passes it to onWorkflowJournal; interrupted runs project at shutdown as before. - jobUsage() moves the usage summation into job-state.ts so the snapshot and the journal read one number. Journal tests that hand-built flat snapshots to exercise the reverse-engineering are replaced by run-state-driven ones; a cancelled run's journal is now covered too. Part of #23.
This commit is contained in:
1 parent
a3fc182cb5
commit
8bc08bd08a
5 files changed
+211
-233
No files matched your search
@@ -18,6 +18,7 @@ import {
|
||||
type TaskIdentity,
|
||||
type TaskSnapshot,
|
||||
type TaskStatus,
|
||||
type UsageStats,
|
||||
} from "./types.ts";
|
||||
import type { WorkflowRunSpec } from "./workflow-run.ts";
|
||||
|
||||
@@ -148,6 +149,22 @@ export function isFailedResult(result: ResultStatusFields): boolean {
|
||||
return result.stopReason === "error" || result.stopReason === "aborted" || Boolean(result.terminationSignal);
|
||||
}
|
||||
|
||||
/**
|
||||
* The job's usage: rows summed, except the context, which is the peak rather
|
||||
* than the total. The snapshot and the journal are the same job, so they read
|
||||
* the same number here.
|
||||
*/
|
||||
export function jobUsage(tasks: readonly InternalTask[]): UsageStats {
|
||||
const usage = emptyUsage();
|
||||
for (const task of tasks) {
|
||||
for (const key of ["input", "output", "cacheRead", "cacheWrite", "cost", "turns"] as const) {
|
||||
usage[key] += task.snapshot.usage[key];
|
||||
}
|
||||
usage.contextTokens = Math.max(usage.contextTokens, task.snapshot.usage.contextTokens);
|
||||
}
|
||||
return usage;
|
||||
}
|
||||
|
||||
/** The shared row's current status; the supervisor reads through this seam. */
|
||||
export function taskStatus(task: InternalTask): TaskStatus {
|
||||
return task.snapshot.status;
|
||||
|
||||
+51
-52
@@ -5,15 +5,16 @@
|
||||
* interruption on shutdown). The record carries the plan as loaded, one record
|
||||
* per step — stable input hash, status, attempt count, bounded output, timings —
|
||||
* one row per fanned-out item alongside its step's record, plus the run's usage.
|
||||
* Nothing here replays or resumes a run: the shape exists so a future replay
|
||||
* layer needs no migration (ADR 0004).
|
||||
* It is a projection of the run's DAG index, taken at that transition: plan and
|
||||
* item order come from the index, never from re-deriving the graph out of the
|
||||
* flat job record. Nothing here replays or resumes a run: the shape exists so a
|
||||
* future replay layer needs no migration (ADR 0004).
|
||||
*/
|
||||
|
||||
import { createHash } from "node:crypto";
|
||||
import { jobUsage, type Execution, type InternalTask } from "./job-state.ts";
|
||||
import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "./output.ts";
|
||||
import type {
|
||||
JobSnapshot,
|
||||
TaskSnapshot,
|
||||
WorkflowJournal,
|
||||
WorkflowJournalItem,
|
||||
WorkflowJournalStep,
|
||||
@@ -84,7 +85,8 @@ export function workflowItemInputHash(
|
||||
return `sha256:${createHash("sha256").update(payload, "utf8").digest("hex")}`;
|
||||
}
|
||||
|
||||
function boundedOutput(snapshot: Pick<TaskSnapshot, "output" | "outputTruncated" | "outputBytesOmitted">): Pick<WorkflowJournalStep, "output" | "outputTruncated" | "outputBytesOmitted"> {
|
||||
function boundedOutput(task: InternalTask): Pick<WorkflowJournalStep, "output" | "outputTruncated" | "outputBytesOmitted"> {
|
||||
const { snapshot } = task;
|
||||
const bounded = truncateUtf8Head(snapshot.output, MAX_TASK_OUTPUT_BYTES);
|
||||
const bytesOmitted = snapshot.outputBytesOmitted + bounded.bytesOmitted;
|
||||
const truncated = snapshot.outputTruncated || bounded.truncated;
|
||||
@@ -95,14 +97,15 @@ function boundedOutput(snapshot: Pick<TaskSnapshot, "output" | "outputTruncated"
|
||||
};
|
||||
}
|
||||
|
||||
/** One journal row for a plan step, from its coordinator row. */
|
||||
function journalStep(
|
||||
stepId: string,
|
||||
plan: WorkflowPlan,
|
||||
args: Record<string, string>,
|
||||
snapshot?: TaskSnapshot,
|
||||
task?: InternalTask,
|
||||
): Omit<WorkflowJournalStep, "items"> {
|
||||
const inputHash = workflowStepInputHash(plan, stepId, args);
|
||||
if (!snapshot) {
|
||||
if (!task) {
|
||||
return {
|
||||
id: stepId,
|
||||
inputHash,
|
||||
@@ -113,25 +116,28 @@ function journalStep(
|
||||
outputBytesOmitted: 0,
|
||||
};
|
||||
}
|
||||
const { snapshot } = task;
|
||||
return {
|
||||
id: stepId,
|
||||
inputHash,
|
||||
status: snapshot.status,
|
||||
// Always 0 or 1 while no retry exists; this is where a retry count lands.
|
||||
attempts: snapshot.startedAt === undefined ? 0 : 1,
|
||||
...boundedOutput(snapshot),
|
||||
...boundedOutput(task),
|
||||
startedAt: snapshot.startedAt,
|
||||
finishedAt: snapshot.finishedAt,
|
||||
};
|
||||
}
|
||||
|
||||
/** One journal row for a fanned-out item, from the child's own snapshot. */
|
||||
/** One journal row for a fanned-out item, from the child's own row. */
|
||||
function journalItem(
|
||||
stepId: string,
|
||||
item: number,
|
||||
snapshot: TaskSnapshot,
|
||||
task: InternalTask,
|
||||
plan: WorkflowPlan,
|
||||
args: Record<string, string>,
|
||||
): WorkflowJournalItem {
|
||||
const { snapshot } = task;
|
||||
const input = snapshot.itemValue ?? "";
|
||||
return {
|
||||
item,
|
||||
@@ -139,57 +145,50 @@ function journalItem(
|
||||
inputHash: workflowItemInputHash(plan, stepId, args, input),
|
||||
status: snapshot.status,
|
||||
attempts: snapshot.startedAt === undefined ? 0 : 1,
|
||||
...boundedOutput(snapshot),
|
||||
...boundedOutput(task),
|
||||
startedAt: snapshot.startedAt,
|
||||
finishedAt: snapshot.finishedAt,
|
||||
};
|
||||
}
|
||||
|
||||
/** Item children grouped by step id, each group in item order. */
|
||||
function itemsByStep(job: JobSnapshot): Map<string, Array<{ item: number; snapshot: TaskSnapshot }>> {
|
||||
const grouped = new Map<string, Array<{ item: number; snapshot: TaskSnapshot }>>();
|
||||
for (const snapshot of job.results) {
|
||||
if (snapshot.stepId === undefined || snapshot.item === undefined) continue;
|
||||
const rows = grouped.get(snapshot.stepId) ?? [];
|
||||
rows.push({ item: snapshot.item, snapshot });
|
||||
grouped.set(snapshot.stepId, rows);
|
||||
}
|
||||
for (const rows of grouped.values()) rows.sort((left, right) => left.item - right.item);
|
||||
return grouped;
|
||||
/**
|
||||
* The run state a journal record projects: the job record's head and the run's
|
||||
* DAG index. The manager owns the record (identity, status, usage, timings); the
|
||||
* run module owns the index (plan order, step rows, item rows).
|
||||
*/
|
||||
export interface WorkflowJournalRun {
|
||||
execution: Pick<Execution, "id" | "status" | "tasks" | "createdAt" | "startedAt" | "finishedAt" | "errorMessage">;
|
||||
spec: WorkflowRunSpec;
|
||||
/** The coordinator row per step id; every plan step has one at the terminal transition. */
|
||||
stepTasks: ReadonlyMap<string, InternalTask>;
|
||||
/** Item children per each-step id, in fan-out order. */
|
||||
itemTasks: ReadonlyMap<string, readonly InternalTask[]>;
|
||||
}
|
||||
|
||||
/** Build the run's journal record from the terminal snapshot and its spec. */
|
||||
export function buildWorkflowJournal(job: JobSnapshot, spec: WorkflowRunSpec): WorkflowJournal {
|
||||
const byStep = new Map<string, TaskSnapshot>();
|
||||
for (const snapshot of job.results) {
|
||||
if (snapshot.stepId === undefined) continue;
|
||||
const current = byStep.get(snapshot.stepId);
|
||||
// An each-step's item children share their step's id. Prefer the step's own
|
||||
// row: it carries the aggregate status and the joined item output. The item
|
||||
// children become their own rows alongside it.
|
||||
if (current === undefined || (current.item !== undefined && snapshot.item === undefined)) byStep.set(snapshot.stepId, snapshot);
|
||||
}
|
||||
const items = itemsByStep(job);
|
||||
/**
|
||||
* The run's journal record at its terminal transition.
|
||||
*
|
||||
* Plan order is the audit order, and the item rows come from the run's index in
|
||||
* fan-out order; both are read off the DAG the supervisor holds, so the record
|
||||
* never has to guess which row is a step's own and which is a child's.
|
||||
*/
|
||||
export function buildWorkflowJournal(run: WorkflowJournalRun): WorkflowJournal {
|
||||
const { execution, spec, stepTasks, itemTasks } = run;
|
||||
return {
|
||||
jobId: job.id,
|
||||
status: job.status,
|
||||
jobId: execution.id,
|
||||
status: execution.status,
|
||||
plan: structuredClone(spec.plan),
|
||||
args: { ...spec.args },
|
||||
// Plan order is the audit order; fall back to position only for jobs whose
|
||||
// rows predate step ids, so the record stays complete and bounded.
|
||||
steps: spec.steps.map((step, index) => {
|
||||
const snapshot = byStep.get(step.id) ?? (byStep.size === 0 ? job.results[index] : undefined);
|
||||
return {
|
||||
...journalStep(step.id, spec.plan, spec.args, snapshot),
|
||||
items: (items.get(step.id) ?? []).map(({ item, snapshot: child }) =>
|
||||
journalItem(step.id, item, child, spec.plan, spec.args),
|
||||
),
|
||||
};
|
||||
}),
|
||||
usage: { ...job.usage },
|
||||
createdAt: job.createdAt,
|
||||
startedAt: job.startedAt,
|
||||
finishedAt: job.finishedAt,
|
||||
errorMessage: job.errorMessage,
|
||||
steps: spec.steps.map((step) => ({
|
||||
...journalStep(step.id, spec.plan, spec.args, stepTasks.get(step.id)),
|
||||
items: (itemTasks.get(step.id) ?? []).map((task, index) =>
|
||||
journalItem(step.id, index + 1, task, spec.plan, spec.args),
|
||||
),
|
||||
})),
|
||||
usage: jobUsage(execution.tasks),
|
||||
createdAt: execution.createdAt,
|
||||
startedAt: execution.startedAt,
|
||||
finishedAt: execution.finishedAt,
|
||||
errorMessage: execution.errorMessage,
|
||||
};
|
||||
}
|
||||
+12
-15
@@ -5,15 +5,14 @@ import {
|
||||
isFailedResult,
|
||||
isTerminalJob,
|
||||
isTerminalTask,
|
||||
jobUsage,
|
||||
taskBaseResult,
|
||||
taskIdentityExtras,
|
||||
type Execution,
|
||||
type InternalTask,
|
||||
} from "./job-state.ts";
|
||||
import { buildWorkflowJournal } from "./journal.ts";
|
||||
import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "./output.ts";
|
||||
import {
|
||||
emptyUsage,
|
||||
type JobSnapshot,
|
||||
type JobStatus,
|
||||
type ManagerOptions,
|
||||
@@ -23,7 +22,6 @@ import {
|
||||
type TaskRunner,
|
||||
type TaskSnapshot,
|
||||
type TaskStatus,
|
||||
type UsageStats,
|
||||
type SyncOutcome,
|
||||
type SyncRunOptions,
|
||||
type WorkflowJournal,
|
||||
@@ -561,11 +559,6 @@ export class SubagentManager {
|
||||
}
|
||||
|
||||
private snapshot(execution: Execution): JobSnapshot {
|
||||
const usage: UsageStats = emptyUsage();
|
||||
for (const task of execution.tasks) {
|
||||
for (const key of ["input", "output", "cacheRead", "cacheWrite", "cost", "turns"] as const) usage[key] += task.snapshot.usage[key];
|
||||
usage.contextTokens = Math.max(usage.contextTokens, task.snapshot.usage.contextTokens);
|
||||
}
|
||||
return cloneSnapshot({
|
||||
id: execution.id,
|
||||
mode: execution.request.mode,
|
||||
@@ -575,7 +568,7 @@ export class SubagentManager {
|
||||
status: execution.status,
|
||||
plannedTaskCount: execution.plannedTaskCount,
|
||||
results: execution.tasks.map((task) => task.snapshot),
|
||||
usage,
|
||||
usage: jobUsage(execution.tasks),
|
||||
createdAt: execution.createdAt,
|
||||
startedAt: execution.startedAt,
|
||||
finishedAt: execution.finishedAt,
|
||||
@@ -602,15 +595,19 @@ export class SubagentManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* One journal record per workflow run, at its terminal transition. Runs that
|
||||
* are interrupted by shutdown land here too, so a reloaded session reads an
|
||||
* interrupted record rather than a missing one.
|
||||
* One journal record per workflow run, at its terminal transition. The record
|
||||
* is the run's projection of its DAG index, taken while that state is still
|
||||
* live; a run whose loop failed before settling projects nothing and leaves
|
||||
* its failure on the job record. Runs that are interrupted by shutdown land
|
||||
* here too, so a reloaded session reads an interrupted record rather than a
|
||||
* missing one.
|
||||
*/
|
||||
private emitJournal(execution: Execution): void {
|
||||
const spec = execution.workflow;
|
||||
if (!this.onWorkflowJournal || execution.request.mode !== "workflow" || !spec) return;
|
||||
if (!this.onWorkflowJournal || execution.request.mode !== "workflow") return;
|
||||
const journal = this.workflows.journal(execution);
|
||||
if (!journal) return;
|
||||
try {
|
||||
this.onWorkflowJournal(buildWorkflowJournal(this.snapshot(execution), spec));
|
||||
this.onWorkflowJournal(journal);
|
||||
} catch {
|
||||
// Persistence failures cannot change how a run proceeds.
|
||||
}
|
||||
|
||||
@@ -26,12 +26,14 @@ import {
|
||||
type Execution,
|
||||
type InternalTask,
|
||||
} from "./job-state.ts";
|
||||
import { buildWorkflowJournal } from "./journal.ts";
|
||||
import type {
|
||||
JobStatus,
|
||||
PreparedTask,
|
||||
RunResult,
|
||||
TaskSnapshot,
|
||||
TaskStatus,
|
||||
WorkflowJournal,
|
||||
} from "./types.ts";
|
||||
import {
|
||||
interpolateWorkflowTask,
|
||||
@@ -184,6 +186,16 @@ export class WorkflowSupervisor {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The run's audit record at its terminal transition, projected from its DAG
|
||||
* index and spec. Undefined when the run holds no state to project: a run
|
||||
* whose loop failed before settling leaves only the job record behind.
|
||||
*/
|
||||
journal(execution: Execution): WorkflowJournal | undefined {
|
||||
const state = this.runs.get(execution);
|
||||
return state ? buildWorkflowJournal(state) : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancellation is terminal for every step, including the two kinds the FIFO
|
||||
* never owned: steps held back by the DAG or the run cap, and each-step
|
||||
|
||||
+119
-166
@@ -4,7 +4,8 @@ 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, workflowItemInputHash, workflowStepInputHash } from "../src/journal.ts";
|
||||
import { buildWorkflowJournal, 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 {
|
||||
@@ -74,6 +75,35 @@ 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 {
|
||||
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(
|
||||
@@ -172,38 +202,13 @@ test("oversized step outputs are bounded to the async snapshot budget with the t
|
||||
// The same bound an async task snapshot applies to a child's output.
|
||||
const snapshotBound = truncateUtf8Head(oversized, MAX_TASK_OUTPUT_BYTES);
|
||||
|
||||
const job: JobSnapshot = {
|
||||
id: "job_0009",
|
||||
mode: "workflow",
|
||||
agentScope: "user",
|
||||
projectAgentsDir: null,
|
||||
projectAgentsDirs: [],
|
||||
status: "succeeded",
|
||||
plannedTaskCount: 1,
|
||||
usage: emptyUsage(),
|
||||
createdAt: 1,
|
||||
startedAt: 2,
|
||||
finishedAt: 3,
|
||||
results: [{
|
||||
agent: "scout",
|
||||
agentSource: "user",
|
||||
task: "scan",
|
||||
cwd: ctx.cwd,
|
||||
stepId: "scan",
|
||||
status: "succeeded",
|
||||
exitCode: 0,
|
||||
output: oversized,
|
||||
outputTruncated: false,
|
||||
outputBytesOmitted: 0,
|
||||
stderr: "",
|
||||
stderrTruncated: false,
|
||||
usage: emptyUsage(),
|
||||
startedAt: 2,
|
||||
finishedAt: 3,
|
||||
}],
|
||||
};
|
||||
|
||||
const journal = buildWorkflowJournal(job, prepared.workflow);
|
||||
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);
|
||||
@@ -212,12 +217,18 @@ test("oversized step outputs are bounded to the async snapshot budget with the t
|
||||
assert.equal(record.outputTruncated, true);
|
||||
assert.equal(record.outputBytesOmitted, Buffer.byteLength(oversized, "utf8") - MAX_TASK_OUTPUT_BYTES);
|
||||
|
||||
// An already-bounded snapshot keeps its own omission count instead of
|
||||
// re-marking the text.
|
||||
const bounded = buildWorkflowJournal(
|
||||
{ ...job, results: [{ ...job.results[0], output: snapshotBound.text, outputTruncated: true, outputBytesOmitted: snapshotBound.bytesOmitted }] },
|
||||
prepared.workflow,
|
||||
);
|
||||
// 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);
|
||||
|
||||
@@ -277,37 +288,13 @@ test("journal extraction ignores foreign and malformed entries and keeps the lat
|
||||
const { ctx } = makeWorkspace();
|
||||
const plan = makePlan([{ id: "scan", agent: "scout", task: "scan" }]);
|
||||
const prepared = await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false });
|
||||
const job: JobSnapshot = {
|
||||
id: "job_0010",
|
||||
mode: "workflow",
|
||||
agentScope: "user",
|
||||
projectAgentsDir: null,
|
||||
projectAgentsDirs: [],
|
||||
status: "failed",
|
||||
plannedTaskCount: 1,
|
||||
usage: emptyUsage(),
|
||||
createdAt: 1,
|
||||
finishedAt: 2,
|
||||
results: [{
|
||||
agent: "scout",
|
||||
agentSource: "user",
|
||||
task: "scan",
|
||||
cwd: ctx.cwd,
|
||||
stepId: "scan",
|
||||
status: "failed",
|
||||
exitCode: 1,
|
||||
output: "",
|
||||
outputTruncated: false,
|
||||
outputBytesOmitted: 0,
|
||||
stderr: "",
|
||||
stderrTruncated: false,
|
||||
usage: emptyUsage(),
|
||||
errorMessage: "boom",
|
||||
startedAt: 1,
|
||||
finishedAt: 2,
|
||||
}],
|
||||
};
|
||||
const journal = buildWorkflowJournal(job, prepared.workflow);
|
||||
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",
|
||||
@@ -358,6 +345,32 @@ test("a failed run journals skipped dependents and retains the independent branc
|
||||
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 manager.wait(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([
|
||||
@@ -365,48 +378,21 @@ test("an each-step journals per-item rows alongside its aggregate step record",
|
||||
{ id: "check", agent: "scout", task: "check {item}", needs: ["list"], each: "{steps.list.output}" },
|
||||
]);
|
||||
const prepared = await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false });
|
||||
const snapshot = (stepId: string, status: TaskStatus, output: string, item?: number, itemValue?: string): TaskSnapshot => ({
|
||||
agent: "scout",
|
||||
agentSource: "user",
|
||||
task: "check",
|
||||
cwd: ctx.cwd,
|
||||
stepId,
|
||||
item,
|
||||
itemValue,
|
||||
status,
|
||||
exitCode: status === "succeeded" ? 0 : 1,
|
||||
output,
|
||||
outputTruncated: false,
|
||||
outputBytesOmitted: 0,
|
||||
stderr: "",
|
||||
stderrTruncated: false,
|
||||
usage: emptyUsage(),
|
||||
startedAt: 2,
|
||||
finishedAt: 3,
|
||||
});
|
||||
const job: JobSnapshot = {
|
||||
id: "job_0011",
|
||||
mode: "workflow",
|
||||
agentScope: "user",
|
||||
projectAgentsDir: null,
|
||||
projectAgentsDirs: [],
|
||||
status: "succeeded",
|
||||
plannedTaskCount: 2,
|
||||
usage: emptyUsage(),
|
||||
createdAt: 1,
|
||||
startedAt: 2,
|
||||
finishedAt: 3,
|
||||
results: [
|
||||
snapshot("list", "succeeded", "src/a.ts\nsrc/b.ts"),
|
||||
// The step's own row carries the joined item output and the aggregate
|
||||
// status; item children trail it in `results`.
|
||||
snapshot("check", "succeeded", "aggregate"),
|
||||
snapshot("check", "succeeded", "ok a", 1, "src/a.ts"),
|
||||
snapshot("check", "failed", "boom b", 2, "src/b.ts"),
|
||||
],
|
||||
};
|
||||
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(job, prepared.workflow);
|
||||
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]),
|
||||
@@ -633,69 +619,36 @@ test("oversized item outputs are bounded like step outputs and survive the round
|
||||
const prepared = await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false });
|
||||
const oversized = "é".repeat(60 * 1024);
|
||||
const snapshotBound = truncateUtf8Head(oversized, MAX_TASK_OUTPUT_BYTES);
|
||||
const row = (
|
||||
stepId: string,
|
||||
status: TaskStatus,
|
||||
output: string,
|
||||
extra: Partial<TaskSnapshot> = {},
|
||||
): TaskSnapshot => ({
|
||||
agent: "scout",
|
||||
agentSource: "user",
|
||||
task: "check",
|
||||
cwd: ctx.cwd,
|
||||
stepId,
|
||||
status,
|
||||
exitCode: status === "succeeded" ? 0 : 1,
|
||||
output,
|
||||
outputTruncated: false,
|
||||
outputBytesOmitted: 0,
|
||||
stderr: "",
|
||||
stderrTruncated: false,
|
||||
usage: emptyUsage(),
|
||||
startedAt: 2,
|
||||
finishedAt: 3,
|
||||
...extra,
|
||||
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 job: JobSnapshot = {
|
||||
id: "job_0013",
|
||||
mode: "workflow",
|
||||
agentScope: "user",
|
||||
projectAgentsDir: null,
|
||||
projectAgentsDirs: [],
|
||||
status: "succeeded",
|
||||
plannedTaskCount: 3,
|
||||
usage: emptyUsage(),
|
||||
createdAt: 1,
|
||||
startedAt: 2,
|
||||
finishedAt: 3,
|
||||
results: [
|
||||
row("list", "succeeded", "src/a.ts\nsrc/b.ts"),
|
||||
row("check", "succeeded", "aggregate"),
|
||||
row("check", "succeeded", oversized, { item: 1, itemValue: "src/a.ts" }),
|
||||
row("check", "succeeded", snapshotBound.text, {
|
||||
item: 2,
|
||||
itemValue: "src/b.ts",
|
||||
outputTruncated: true,
|
||||
outputBytesOmitted: snapshotBound.bytesOmitted,
|
||||
}),
|
||||
],
|
||||
};
|
||||
|
||||
const journal = buildWorkflowJournal(job, prepared.workflow);
|
||||
const [first, second] = journal.steps[1].items;
|
||||
const [kept, note] = first.output.split("\n\n[Output truncated: ");
|
||||
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(first.outputTruncated, true);
|
||||
assert.equal(first.outputBytesOmitted, Buffer.byteLength(oversized, "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 snapshot keeps its own omission count instead of
|
||||
// An already-bounded item row keeps its own omission count instead of
|
||||
// re-marking the text, exactly like a step row.
|
||||
assert.equal(second.output.split("[Output truncated: ").length, 2);
|
||||
assert.equal(second.outputBytesOmitted, snapshotBound.bytesOmitted);
|
||||
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)]);
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user