diff --git a/src/journal.ts b/src/journal.ts index 4d0cd24..f97d936 100644 --- a/src/journal.ts +++ b/src/journal.ts @@ -2,10 +2,11 @@ * Workflow run journal records. * * One record per run, built when the run reaches a terminal state (including - * interruption on shutdown). The record carries the plan as loaded and one - * record per step — stable input hash, status, attempt count, bounded output, - * timings — 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). + * 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). */ import { createHash } from "node:crypto"; @@ -14,6 +15,24 @@ import type { JobSnapshot, JobStatus, TaskSnapshot, TaskStatus, UsageStats } fro import type { WorkflowPlan, WorkflowStep } from "./workflows.ts"; import type { WorkflowRunSpec } from "./workflow.ts"; +/** One fanned-out item child of an each-step, as the journal records it. */ +export interface WorkflowJournalItem { + /** One-based item index within the step's fan-out. */ + item: number; + /** The source line this item was fanned out from. */ + input: string; + /** Stable across identical item inputs, so a replay layer can key on it. */ + inputHash: string; + status: TaskStatus; + /** Children started for this item; always 0 or 1 while no retry exists. */ + attempts: number; + output: string; + outputTruncated: boolean; + outputBytesOmitted: number; + startedAt?: number; + finishedAt?: number; +} + export interface WorkflowJournalStep { id: string; /** Stable across identical step inputs, so a replay layer can key on it. */ @@ -26,6 +45,8 @@ export interface WorkflowJournalStep { outputBytesOmitted: number; startedAt?: number; finishedAt?: number; + /** One row per each-step item, in item order; empty for steps that do not fan out. */ + items: WorkflowJournalItem[]; } export interface WorkflowJournal { @@ -88,7 +109,23 @@ export function workflowStepInputHash(plan: WorkflowPlan, stepId: string, args: return `sha256:${createHash("sha256").update(payload, "utf8").digest("hex")}`; } -function boundedOutput(snapshot: TaskSnapshot): Pick { +/** + * Hash the inputs that determine one item child's work — the step's inputs plus + * the item line itself. Prior-step outputs are excluded for the same reason as + * step hashes, so identical items keep identical hashes across runs. Two + * identical lines share a hash; the row's `item` index carries the position. + */ +export function workflowItemInputHash( + plan: WorkflowPlan, + stepId: string, + args: Readonly>, + item: string, +): string { + const payload = canonical({ version: 1, plan: planInputs(plan), step: stepId, item, args }); + return `sha256:${createHash("sha256").update(payload, "utf8").digest("hex")}`; +} + +function boundedOutput(snapshot: Pick): Pick { const bounded = truncateUtf8Head(snapshot.output, MAX_TASK_OUTPUT_BYTES); const bytesOmitted = snapshot.outputBytesOmitted + bounded.bytesOmitted; const truncated = snapshot.outputTruncated || bounded.truncated; @@ -99,7 +136,12 @@ function boundedOutput(snapshot: TaskSnapshot): Pick, snapshot?: TaskSnapshot): WorkflowJournalStep { +function journalStep( + stepId: string, + plan: WorkflowPlan, + args: Record, + snapshot?: TaskSnapshot, +): Omit { const inputHash = workflowStepInputHash(plan, stepId, args); if (!snapshot) { return { @@ -123,6 +165,40 @@ function journalStep(stepId: string, plan: WorkflowPlan, args: Record, +): WorkflowJournalItem { + const input = snapshot.itemValue ?? ""; + return { + item, + input, + inputHash: workflowItemInputHash(plan, stepId, args, input), + status: snapshot.status, + attempts: snapshot.startedAt === undefined ? 0 : 1, + ...boundedOutput(snapshot), + startedAt: snapshot.startedAt, + finishedAt: snapshot.finishedAt, + }; +} + +/** Item children grouped by step id, each group in item order. */ +function itemsByStep(job: JobSnapshot): Map> { + const grouped = new Map>(); + 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; +} + /** 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(); @@ -130,10 +206,11 @@ export function buildWorkflowJournal(job: JobSnapshot, spec: WorkflowRunSpec): W 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. Per-item - // journal rows are a separate follow-up. + // 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); return { jobId: job.id, status: job.status, @@ -141,9 +218,15 @@ export function buildWorkflowJournal(job: JobSnapshot, spec: WorkflowRunSpec): W 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) => - journalStep(step.id, spec.plan, spec.args, byStep.get(step.id) ?? (byStep.size === 0 ? job.results[index] : undefined)), - ), + 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, diff --git a/src/manager.ts b/src/manager.ts index fb4c772..51d1acb 100644 --- a/src/manager.ts +++ b/src/manager.ts @@ -35,8 +35,6 @@ export interface InternalTask { result?: RunResult; /** A workflow step submitted to the FIFO, whether or not a worker picked it up yet. */ submitted?: boolean; - /** The source line behind an each-step item child. */ - itemValue?: string; } export interface Execution { diff --git a/src/persistence.ts b/src/persistence.ts index 3bef16b..101bc8d 100644 --- a/src/persistence.ts +++ b/src/persistence.ts @@ -1,4 +1,4 @@ -import type { WorkflowJournal, WorkflowJournalStep } from "./journal.ts"; +import type { WorkflowJournal, WorkflowJournalItem, WorkflowJournalStep } from "./journal.ts"; import type { JobSnapshot } from "./types.ts"; export const SUBAGENT_JOB_ENTRY = "subagent-job-v1"; @@ -45,6 +45,7 @@ function validTask(value: unknown): boolean { && typeof value.cwd === "string" && (value.stepId === undefined || typeof value.stepId === "string") && (value.item === undefined || (typeof value.item === "number" && Number.isInteger(value.item))) + && (value.itemValue === undefined || typeof value.itemValue === "string") && typeof value.status === "string" && taskStatuses.has(value.status) && (typeof value.exitCode === "number" || value.exitCode === null) && typeof value.output === "string" @@ -104,6 +105,20 @@ function finiteNumber(value: unknown): boolean { return typeof value === "number" && Number.isFinite(value); } +function validJournalItem(value: unknown): value is WorkflowJournalItem { + if (!record(value)) return false; + return typeof value.item === "number" && Number.isInteger(value.item) && value.item >= 1 + && typeof value.input === "string" + && typeof value.inputHash === "string" + && typeof value.status === "string" && taskStatuses.has(value.status) + && typeof value.attempts === "number" && Number.isInteger(value.attempts) && value.attempts >= 0 + && typeof value.output === "string" + && typeof value.outputTruncated === "boolean" + && typeof value.outputBytesOmitted === "number" && value.outputBytesOmitted >= 0 + && (value.startedAt === undefined || finiteNumber(value.startedAt)) + && (value.finishedAt === undefined || finiteNumber(value.finishedAt)); +} + function validJournalStep(value: unknown): value is WorkflowJournalStep { if (!record(value)) return false; return typeof value.id === "string" @@ -114,7 +129,8 @@ function validJournalStep(value: unknown): value is WorkflowJournalStep { && typeof value.outputTruncated === "boolean" && typeof value.outputBytesOmitted === "number" && value.outputBytesOmitted >= 0 && (value.startedAt === undefined || finiteNumber(value.startedAt)) - && (value.finishedAt === undefined || finiteNumber(value.finishedAt)); + && (value.finishedAt === undefined || finiteNumber(value.finishedAt)) + && Array.isArray(value.items) && value.items.every(validJournalItem); } function validJournal(value: unknown): value is WorkflowJournal { diff --git a/src/types.ts b/src/types.ts index e20d5e0..cffecd3 100644 --- a/src/types.ts +++ b/src/types.ts @@ -20,6 +20,8 @@ export interface PreparedTask { stepId?: string; /** One-based item index within an each-step fan-out. */ item?: number; + /** The source line behind an each-step item child. */ + itemValue?: string; /** Per-step model override (step -> agent -> parent precedence). */ model?: string; } @@ -51,6 +53,7 @@ export interface RunResult { step?: number; stepId?: string; item?: number; + itemValue?: string; exitCode: number | null; messages: Message[]; output: string; @@ -81,6 +84,8 @@ export interface TaskSnapshot { step?: number; stepId?: string; item?: number; + /** The source line behind an each-step item child. */ + itemValue?: string; status: TaskStatus; exitCode: number | null; output: string; @@ -106,15 +111,17 @@ export interface TaskIdentity { step?: number; stepId?: string; item?: number; + itemValue?: string; } -/** The step-identity subset, so adding a field changes one mapping here. */ +/** The step/item-identity subset, so adding a field changes one mapping here. */ export function taskIdentityExtras(source: { step?: number; stepId?: string; item?: number; -}): Pick { - return { step: source.step, stepId: source.stepId, item: source.item }; + itemValue?: string; +}): Pick { + return { step: source.step, stepId: source.stepId, item: source.item, itemValue: source.itemValue }; } /** Build the identity a fresh result or snapshot inherits from its prepared task. */ diff --git a/src/workflow-supervisor.ts b/src/workflow-supervisor.ts index 91354c8..ebf3b6b 100644 --- a/src/workflow-supervisor.ts +++ b/src/workflow-supervisor.ts @@ -236,9 +236,7 @@ export class WorkflowSupervisor { const children = items.map((item, index) => { const brief = interpolateWorkflowTask(step.template, { args: spec.args, outputs, item }); - const child = this.host.createTask({ ...step.prepared, task: brief, stepId: step.id, item: index + 1 }); - child.itemValue = item; - return child; + return this.host.createTask({ ...step.prepared, task: brief, stepId: step.id, item: index + 1, itemValue: item }); }); task.submitted = true; task.snapshot.startedAt = this.host.now(); @@ -322,7 +320,7 @@ export class WorkflowSupervisor { } else { const output = joinWorkflowItemOutputs( items.map((item) => ({ - item: item.itemValue ?? "", + item: item.snapshot.itemValue ?? "", // Failed items leave an empty slot; their partial output never leaks in. output: item.snapshot.status === "succeeded" ? item.snapshot.output : "", })), diff --git a/test/workflow-journal.test.ts b/test/workflow-journal.test.ts index 657e379..1afe851 100644 --- a/test/workflow-journal.test.ts +++ b/test/workflow-journal.test.ts @@ -3,7 +3,8 @@ 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 { buildWorkflowJournal, workflowStepInputHash, type WorkflowJournal } from "../src/journal.ts"; +import fc from "fast-check"; +import { buildWorkflowJournal, workflowItemInputHash, workflowStepInputHash, type WorkflowJournal, type WorkflowJournalItem, type WorkflowJournalStep } from "../src/journal.ts"; import { SubagentManager } from "../src/manager.ts"; import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "../src/output.ts"; import { @@ -357,20 +358,21 @@ test("a failed run journals skipped dependents and retains the independent branc assert.equal(journals[0].steps[2].output, ""); }); -test("an each-step journals one step record from its coordinator, not one row per item", async () => { +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 snapshot = (stepId: string, status: TaskStatus, output: string, item?: number): TaskSnapshot => ({ + 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, @@ -399,8 +401,8 @@ test("an each-step journals one step record from its coordinator, not one row pe // 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), - snapshot("check", "failed", "boom b", 2), + snapshot("check", "succeeded", "ok a", 1, "src/a.ts"), + snapshot("check", "failed", "boom b", 2, "src/b.ts"), ], }; @@ -414,4 +416,286 @@ test("an each-step journals one step record from its coordinator, not one row pe ], ); 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 => ({ + 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, 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, { + onJobChange: (job) => jobs.push(job), + 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 manager.wait(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 row = ( + stepId: string, + status: TaskStatus, + output: string, + extra: Partial = {}, + ): 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 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: "); + 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); + + // An already-bounded item snapshot 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); + + const entry = serialized({ type: "custom", customType: WORKFLOW_RUN_ENTRY, data: persistedWorkflowJournal("session-a", journal) }); + assert.deepEqual(extractWorkflowJournals([entry]), [serialized(journal)]); });