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 TaskIdentity,
|
||||||
type TaskSnapshot,
|
type TaskSnapshot,
|
||||||
type TaskStatus,
|
type TaskStatus,
|
||||||
|
type UsageStats,
|
||||||
} from "./types.ts";
|
} from "./types.ts";
|
||||||
import type { WorkflowRunSpec } from "./workflow-run.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);
|
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. */
|
/** The shared row's current status; the supervisor reads through this seam. */
|
||||||
export function taskStatus(task: InternalTask): TaskStatus {
|
export function taskStatus(task: InternalTask): TaskStatus {
|
||||||
return task.snapshot.status;
|
return task.snapshot.status;
|
||||||
|
|||||||
+51
-52
@@ -5,15 +5,16 @@
|
|||||||
* interruption on shutdown). The record carries the plan as loaded, one record
|
* interruption on shutdown). The record carries the plan as loaded, one record
|
||||||
* per step — stable input hash, status, attempt count, bounded output, timings —
|
* 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.
|
* 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
|
* It is a projection of the run's DAG index, taken at that transition: plan and
|
||||||
* layer needs no migration (ADR 0004).
|
* 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 { createHash } from "node:crypto";
|
||||||
|
import { jobUsage, type Execution, type InternalTask } from "./job-state.ts";
|
||||||
import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "./output.ts";
|
import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "./output.ts";
|
||||||
import type {
|
import type {
|
||||||
JobSnapshot,
|
|
||||||
TaskSnapshot,
|
|
||||||
WorkflowJournal,
|
WorkflowJournal,
|
||||||
WorkflowJournalItem,
|
WorkflowJournalItem,
|
||||||
WorkflowJournalStep,
|
WorkflowJournalStep,
|
||||||
@@ -84,7 +85,8 @@ export function workflowItemInputHash(
|
|||||||
return `sha256:${createHash("sha256").update(payload, "utf8").digest("hex")}`;
|
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 bounded = truncateUtf8Head(snapshot.output, MAX_TASK_OUTPUT_BYTES);
|
||||||
const bytesOmitted = snapshot.outputBytesOmitted + bounded.bytesOmitted;
|
const bytesOmitted = snapshot.outputBytesOmitted + bounded.bytesOmitted;
|
||||||
const truncated = snapshot.outputTruncated || bounded.truncated;
|
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(
|
function journalStep(
|
||||||
stepId: string,
|
stepId: string,
|
||||||
plan: WorkflowPlan,
|
plan: WorkflowPlan,
|
||||||
args: Record<string, string>,
|
args: Record<string, string>,
|
||||||
snapshot?: TaskSnapshot,
|
task?: InternalTask,
|
||||||
): Omit<WorkflowJournalStep, "items"> {
|
): Omit<WorkflowJournalStep, "items"> {
|
||||||
const inputHash = workflowStepInputHash(plan, stepId, args);
|
const inputHash = workflowStepInputHash(plan, stepId, args);
|
||||||
if (!snapshot) {
|
if (!task) {
|
||||||
return {
|
return {
|
||||||
id: stepId,
|
id: stepId,
|
||||||
inputHash,
|
inputHash,
|
||||||
@@ -113,25 +116,28 @@ function journalStep(
|
|||||||
outputBytesOmitted: 0,
|
outputBytesOmitted: 0,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
const { snapshot } = task;
|
||||||
return {
|
return {
|
||||||
id: stepId,
|
id: stepId,
|
||||||
inputHash,
|
inputHash,
|
||||||
status: snapshot.status,
|
status: snapshot.status,
|
||||||
|
// Always 0 or 1 while no retry exists; this is where a retry count lands.
|
||||||
attempts: snapshot.startedAt === undefined ? 0 : 1,
|
attempts: snapshot.startedAt === undefined ? 0 : 1,
|
||||||
...boundedOutput(snapshot),
|
...boundedOutput(task),
|
||||||
startedAt: snapshot.startedAt,
|
startedAt: snapshot.startedAt,
|
||||||
finishedAt: snapshot.finishedAt,
|
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(
|
function journalItem(
|
||||||
stepId: string,
|
stepId: string,
|
||||||
item: number,
|
item: number,
|
||||||
snapshot: TaskSnapshot,
|
task: InternalTask,
|
||||||
plan: WorkflowPlan,
|
plan: WorkflowPlan,
|
||||||
args: Record<string, string>,
|
args: Record<string, string>,
|
||||||
): WorkflowJournalItem {
|
): WorkflowJournalItem {
|
||||||
|
const { snapshot } = task;
|
||||||
const input = snapshot.itemValue ?? "";
|
const input = snapshot.itemValue ?? "";
|
||||||
return {
|
return {
|
||||||
item,
|
item,
|
||||||
@@ -139,57 +145,50 @@ function journalItem(
|
|||||||
inputHash: workflowItemInputHash(plan, stepId, args, input),
|
inputHash: workflowItemInputHash(plan, stepId, args, input),
|
||||||
status: snapshot.status,
|
status: snapshot.status,
|
||||||
attempts: snapshot.startedAt === undefined ? 0 : 1,
|
attempts: snapshot.startedAt === undefined ? 0 : 1,
|
||||||
...boundedOutput(snapshot),
|
...boundedOutput(task),
|
||||||
startedAt: snapshot.startedAt,
|
startedAt: snapshot.startedAt,
|
||||||
finishedAt: snapshot.finishedAt,
|
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 }>> {
|
* The run state a journal record projects: the job record's head and the run's
|
||||||
const grouped = new Map<string, Array<{ item: number; snapshot: TaskSnapshot }>>();
|
* DAG index. The manager owns the record (identity, status, usage, timings); the
|
||||||
for (const snapshot of job.results) {
|
* run module owns the index (plan order, step rows, item rows).
|
||||||
if (snapshot.stepId === undefined || snapshot.item === undefined) continue;
|
*/
|
||||||
const rows = grouped.get(snapshot.stepId) ?? [];
|
export interface WorkflowJournalRun {
|
||||||
rows.push({ item: snapshot.item, snapshot });
|
execution: Pick<Execution, "id" | "status" | "tasks" | "createdAt" | "startedAt" | "finishedAt" | "errorMessage">;
|
||||||
grouped.set(snapshot.stepId, rows);
|
spec: WorkflowRunSpec;
|
||||||
}
|
/** The coordinator row per step id; every plan step has one at the terminal transition. */
|
||||||
for (const rows of grouped.values()) rows.sort((left, right) => left.item - right.item);
|
stepTasks: ReadonlyMap<string, InternalTask>;
|
||||||
return grouped;
|
/** 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 {
|
* The run's journal record at its terminal transition.
|
||||||
const byStep = new Map<string, TaskSnapshot>();
|
*
|
||||||
for (const snapshot of job.results) {
|
* Plan order is the audit order, and the item rows come from the run's index in
|
||||||
if (snapshot.stepId === undefined) continue;
|
* fan-out order; both are read off the DAG the supervisor holds, so the record
|
||||||
const current = byStep.get(snapshot.stepId);
|
* never has to guess which row is a step's own and which is a child's.
|
||||||
// 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
|
export function buildWorkflowJournal(run: WorkflowJournalRun): WorkflowJournal {
|
||||||
// children become their own rows alongside it.
|
const { execution, spec, stepTasks, itemTasks } = run;
|
||||||
if (current === undefined || (current.item !== undefined && snapshot.item === undefined)) byStep.set(snapshot.stepId, snapshot);
|
|
||||||
}
|
|
||||||
const items = itemsByStep(job);
|
|
||||||
return {
|
return {
|
||||||
jobId: job.id,
|
jobId: execution.id,
|
||||||
status: job.status,
|
status: execution.status,
|
||||||
plan: structuredClone(spec.plan),
|
plan: structuredClone(spec.plan),
|
||||||
args: { ...spec.args },
|
args: { ...spec.args },
|
||||||
// Plan order is the audit order; fall back to position only for jobs whose
|
steps: spec.steps.map((step) => ({
|
||||||
// rows predate step ids, so the record stays complete and bounded.
|
...journalStep(step.id, spec.plan, spec.args, stepTasks.get(step.id)),
|
||||||
steps: spec.steps.map((step, index) => {
|
items: (itemTasks.get(step.id) ?? []).map((task, index) =>
|
||||||
const snapshot = byStep.get(step.id) ?? (byStep.size === 0 ? job.results[index] : undefined);
|
journalItem(step.id, index + 1, task, spec.plan, spec.args),
|
||||||
return {
|
),
|
||||||
...journalStep(step.id, spec.plan, spec.args, snapshot),
|
})),
|
||||||
items: (items.get(step.id) ?? []).map(({ item, snapshot: child }) =>
|
usage: jobUsage(execution.tasks),
|
||||||
journalItem(step.id, item, child, spec.plan, spec.args),
|
createdAt: execution.createdAt,
|
||||||
),
|
startedAt: execution.startedAt,
|
||||||
};
|
finishedAt: execution.finishedAt,
|
||||||
}),
|
errorMessage: execution.errorMessage,
|
||||||
usage: { ...job.usage },
|
|
||||||
createdAt: job.createdAt,
|
|
||||||
startedAt: job.startedAt,
|
|
||||||
finishedAt: job.finishedAt,
|
|
||||||
errorMessage: job.errorMessage,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
+12
-15
@@ -5,15 +5,14 @@ import {
|
|||||||
isFailedResult,
|
isFailedResult,
|
||||||
isTerminalJob,
|
isTerminalJob,
|
||||||
isTerminalTask,
|
isTerminalTask,
|
||||||
|
jobUsage,
|
||||||
taskBaseResult,
|
taskBaseResult,
|
||||||
taskIdentityExtras,
|
taskIdentityExtras,
|
||||||
type Execution,
|
type Execution,
|
||||||
type InternalTask,
|
type InternalTask,
|
||||||
} from "./job-state.ts";
|
} from "./job-state.ts";
|
||||||
import { buildWorkflowJournal } from "./journal.ts";
|
|
||||||
import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "./output.ts";
|
import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "./output.ts";
|
||||||
import {
|
import {
|
||||||
emptyUsage,
|
|
||||||
type JobSnapshot,
|
type JobSnapshot,
|
||||||
type JobStatus,
|
type JobStatus,
|
||||||
type ManagerOptions,
|
type ManagerOptions,
|
||||||
@@ -23,7 +22,6 @@ import {
|
|||||||
type TaskRunner,
|
type TaskRunner,
|
||||||
type TaskSnapshot,
|
type TaskSnapshot,
|
||||||
type TaskStatus,
|
type TaskStatus,
|
||||||
type UsageStats,
|
|
||||||
type SyncOutcome,
|
type SyncOutcome,
|
||||||
type SyncRunOptions,
|
type SyncRunOptions,
|
||||||
type WorkflowJournal,
|
type WorkflowJournal,
|
||||||
@@ -561,11 +559,6 @@ export class SubagentManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private snapshot(execution: Execution): JobSnapshot {
|
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({
|
return cloneSnapshot({
|
||||||
id: execution.id,
|
id: execution.id,
|
||||||
mode: execution.request.mode,
|
mode: execution.request.mode,
|
||||||
@@ -575,7 +568,7 @@ export class SubagentManager {
|
|||||||
status: execution.status,
|
status: execution.status,
|
||||||
plannedTaskCount: execution.plannedTaskCount,
|
plannedTaskCount: execution.plannedTaskCount,
|
||||||
results: execution.tasks.map((task) => task.snapshot),
|
results: execution.tasks.map((task) => task.snapshot),
|
||||||
usage,
|
usage: jobUsage(execution.tasks),
|
||||||
createdAt: execution.createdAt,
|
createdAt: execution.createdAt,
|
||||||
startedAt: execution.startedAt,
|
startedAt: execution.startedAt,
|
||||||
finishedAt: execution.finishedAt,
|
finishedAt: execution.finishedAt,
|
||||||
@@ -602,15 +595,19 @@ export class SubagentManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* One journal record per workflow run, at its terminal transition. Runs that
|
* One journal record per workflow run, at its terminal transition. The record
|
||||||
* are interrupted by shutdown land here too, so a reloaded session reads an
|
* is the run's projection of its DAG index, taken while that state is still
|
||||||
* interrupted record rather than a missing one.
|
* 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 {
|
private emitJournal(execution: Execution): void {
|
||||||
const spec = execution.workflow;
|
if (!this.onWorkflowJournal || execution.request.mode !== "workflow") return;
|
||||||
if (!this.onWorkflowJournal || execution.request.mode !== "workflow" || !spec) return;
|
const journal = this.workflows.journal(execution);
|
||||||
|
if (!journal) return;
|
||||||
try {
|
try {
|
||||||
this.onWorkflowJournal(buildWorkflowJournal(this.snapshot(execution), spec));
|
this.onWorkflowJournal(journal);
|
||||||
} catch {
|
} catch {
|
||||||
// Persistence failures cannot change how a run proceeds.
|
// Persistence failures cannot change how a run proceeds.
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,12 +26,14 @@ import {
|
|||||||
type Execution,
|
type Execution,
|
||||||
type InternalTask,
|
type InternalTask,
|
||||||
} from "./job-state.ts";
|
} from "./job-state.ts";
|
||||||
|
import { buildWorkflowJournal } from "./journal.ts";
|
||||||
import type {
|
import type {
|
||||||
JobStatus,
|
JobStatus,
|
||||||
PreparedTask,
|
PreparedTask,
|
||||||
RunResult,
|
RunResult,
|
||||||
TaskSnapshot,
|
TaskSnapshot,
|
||||||
TaskStatus,
|
TaskStatus,
|
||||||
|
WorkflowJournal,
|
||||||
} from "./types.ts";
|
} from "./types.ts";
|
||||||
import {
|
import {
|
||||||
interpolateWorkflowTask,
|
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
|
* 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
|
* 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 * as path from "node:path";
|
||||||
import test, { after } from "node:test";
|
import test, { after } from "node:test";
|
||||||
import fc from "fast-check";
|
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 { SubagentManager } from "../src/manager.ts";
|
||||||
import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "../src/output.ts";
|
import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "../src/output.ts";
|
||||||
import {
|
import {
|
||||||
@@ -74,6 +75,35 @@ function serialized(entry: unknown): unknown {
|
|||||||
return JSON.parse(JSON.stringify(entry));
|
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 () => {
|
test("a finished run persists one journal entry with per-step records and usage", async () => {
|
||||||
const { ctx } = makeWorkspace();
|
const { ctx } = makeWorkspace();
|
||||||
const plan = makePlan(
|
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.
|
// The same bound an async task snapshot applies to a child's output.
|
||||||
const snapshotBound = truncateUtf8Head(oversized, MAX_TASK_OUTPUT_BYTES);
|
const snapshotBound = truncateUtf8Head(oversized, MAX_TASK_OUTPUT_BYTES);
|
||||||
|
|
||||||
const job: JobSnapshot = {
|
const scan = taskRow("scan", "succeeded", oversized);
|
||||||
id: "job_0009",
|
const journal = buildWorkflowJournal({
|
||||||
mode: "workflow",
|
execution: jobHead([scan]),
|
||||||
agentScope: "user",
|
spec: prepared.workflow,
|
||||||
projectAgentsDir: null,
|
stepTasks: new Map([["scan", scan]]),
|
||||||
projectAgentsDirs: [],
|
itemTasks: new Map(),
|
||||||
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 record = journal.steps[0];
|
const record = journal.steps[0];
|
||||||
const [kept, note] = record.output.split("\n\n[Output truncated: ");
|
const [kept, note] = record.output.split("\n\n[Output truncated: ");
|
||||||
assert.equal(kept, snapshotBound.text);
|
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.outputTruncated, true);
|
||||||
assert.equal(record.outputBytesOmitted, Buffer.byteLength(oversized, "utf8") - MAX_TASK_OUTPUT_BYTES);
|
assert.equal(record.outputBytesOmitted, Buffer.byteLength(oversized, "utf8") - MAX_TASK_OUTPUT_BYTES);
|
||||||
|
|
||||||
// An already-bounded snapshot keeps its own omission count instead of
|
// A snapshot the manager already bounded keeps its own omission count
|
||||||
// re-marking the text.
|
// instead of re-marking the text.
|
||||||
const bounded = buildWorkflowJournal(
|
const boundedRow = taskRow("scan", "succeeded", snapshotBound.text, {
|
||||||
{ ...job, results: [{ ...job.results[0], output: snapshotBound.text, outputTruncated: true, outputBytesOmitted: snapshotBound.bytesOmitted }] },
|
outputTruncated: true,
|
||||||
prepared.workflow,
|
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].output.split("[Output truncated: ").length, 2);
|
||||||
assert.equal(bounded.steps[0].outputBytesOmitted, snapshotBound.bytesOmitted);
|
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 { ctx } = makeWorkspace();
|
||||||
const plan = makePlan([{ id: "scan", agent: "scout", task: "scan" }]);
|
const plan = makePlan([{ id: "scan", agent: "scout", task: "scan" }]);
|
||||||
const prepared = await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false });
|
const prepared = await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false });
|
||||||
const job: JobSnapshot = {
|
const scan = taskRow("scan", "failed", "", { errorMessage: "boom" });
|
||||||
id: "job_0010",
|
const journal = buildWorkflowJournal({
|
||||||
mode: "workflow",
|
execution: jobHead([scan], { id: "job_0010", status: "failed", startedAt: undefined, finishedAt: 2 }),
|
||||||
agentScope: "user",
|
spec: prepared.workflow,
|
||||||
projectAgentsDir: null,
|
stepTasks: new Map([["scan", scan]]),
|
||||||
projectAgentsDirs: [],
|
itemTasks: new Map(),
|
||||||
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 entry = serialized({ type: "custom", customType: WORKFLOW_RUN_ENTRY, data: persistedWorkflowJournal("session-a", journal) });
|
const entry = serialized({ type: "custom", customType: WORKFLOW_RUN_ENTRY, data: persistedWorkflowJournal("session-a", journal) });
|
||||||
const later = serialized({
|
const later = serialized({
|
||||||
type: "custom",
|
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, "");
|
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 () => {
|
test("an each-step journals per-item rows alongside its aggregate step record", async () => {
|
||||||
const { ctx } = makeWorkspace();
|
const { ctx } = makeWorkspace();
|
||||||
const plan = makePlan([
|
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}" },
|
{ id: "check", agent: "scout", task: "check {item}", needs: ["list"], each: "{steps.list.output}" },
|
||||||
]);
|
]);
|
||||||
const prepared = await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false });
|
const prepared = await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false });
|
||||||
const snapshot = (stepId: string, status: TaskStatus, output: string, item?: number, itemValue?: string): TaskSnapshot => ({
|
const list = taskRow("list", "succeeded", "src/a.ts\nsrc/b.ts");
|
||||||
agent: "scout",
|
// The coordinator row carries the joined item output and the aggregate
|
||||||
agentSource: "user",
|
// status; the item children sit in the index beside it.
|
||||||
task: "check",
|
const check = taskRow("check", "succeeded", "aggregate");
|
||||||
cwd: ctx.cwd,
|
const items = [
|
||||||
stepId,
|
taskRow("check", "succeeded", "ok a", { item: 1, itemValue: "src/a.ts" }),
|
||||||
item,
|
taskRow("check", "failed", "boom b", { item: 2, itemValue: "src/b.ts" }),
|
||||||
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 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.equal(journal.steps.length, 2, "one journal record per plan step");
|
||||||
assert.deepEqual(
|
assert.deepEqual(
|
||||||
journal.steps.map((step) => [step.id, step.status, step.output]),
|
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 prepared = await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false });
|
||||||
const oversized = "é".repeat(60 * 1024);
|
const oversized = "é".repeat(60 * 1024);
|
||||||
const snapshotBound = truncateUtf8Head(oversized, MAX_TASK_OUTPUT_BYTES);
|
const snapshotBound = truncateUtf8Head(oversized, MAX_TASK_OUTPUT_BYTES);
|
||||||
const row = (
|
const list = taskRow("list", "succeeded", "src/a.ts\nsrc/b.ts");
|
||||||
stepId: string,
|
const check = taskRow("check", "succeeded", "aggregate");
|
||||||
status: TaskStatus,
|
const first = taskRow("check", "succeeded", oversized, { item: 1, itemValue: "src/a.ts" });
|
||||||
output: string,
|
const second = taskRow("check", "succeeded", snapshotBound.text, {
|
||||||
extra: Partial<TaskSnapshot> = {},
|
item: 2,
|
||||||
): TaskSnapshot => ({
|
itemValue: "src/b.ts",
|
||||||
agent: "scout",
|
outputTruncated: true,
|
||||||
agentSource: "user",
|
outputBytesOmitted: snapshotBound.bytesOmitted,
|
||||||
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 job: JobSnapshot = {
|
const journal = buildWorkflowJournal({
|
||||||
id: "job_0013",
|
execution: jobHead([list, check, first, second], { id: "job_0013" }),
|
||||||
mode: "workflow",
|
spec: prepared.workflow,
|
||||||
agentScope: "user",
|
stepTasks: new Map([["list", list], ["check", check]]),
|
||||||
projectAgentsDir: null,
|
itemTasks: new Map([["check", [first, second]]]),
|
||||||
projectAgentsDirs: [],
|
});
|
||||||
status: "succeeded",
|
const [boundedFirst, boundedSecond] = journal.steps[1].items;
|
||||||
plannedTaskCount: 3,
|
const [kept, note] = boundedFirst.output.split("\n\n[Output truncated: ");
|
||||||
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: ");
|
|
||||||
assert.equal(kept, snapshotBound.text);
|
assert.equal(kept, snapshotBound.text);
|
||||||
assert.equal(note, `${snapshotBound.bytesOmitted} bytes omitted]`);
|
assert.equal(note, `${snapshotBound.bytesOmitted} bytes omitted]`);
|
||||||
assert.equal(Buffer.byteLength(kept, "utf8"), MAX_TASK_OUTPUT_BYTES);
|
assert.equal(Buffer.byteLength(kept, "utf8"), MAX_TASK_OUTPUT_BYTES);
|
||||||
assert.equal(first.outputTruncated, true);
|
assert.equal(boundedFirst.outputTruncated, true);
|
||||||
assert.equal(first.outputBytesOmitted, Buffer.byteLength(oversized, "utf8") - MAX_TASK_OUTPUT_BYTES);
|
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.
|
// re-marking the text, exactly like a step row.
|
||||||
assert.equal(second.output.split("[Output truncated: ").length, 2);
|
assert.equal(boundedSecond.output.split("[Output truncated: ").length, 2);
|
||||||
assert.equal(second.outputBytesOmitted, snapshotBound.bytesOmitted);
|
assert.equal(boundedSecond.outputBytesOmitted, snapshotBound.bytesOmitted);
|
||||||
|
|
||||||
const entry = serialized({ type: "custom", customType: WORKFLOW_RUN_ENTRY, data: persistedWorkflowJournal("session-a", journal) });
|
const entry = serialized({ type: "custom", customType: WORKFLOW_RUN_ENTRY, data: persistedWorkflowJournal("session-a", journal) });
|
||||||
assert.deepEqual(extractWorkflowJournals([entry]), [serialized(journal)]);
|
assert.deepEqual(extractWorkflowJournals([entry]), [serialized(journal)]);
|
||||||
});
|
});
|
||||||
|
|
||||||
Reference in new issue
Block a user