Merge ticket/t6-journal: journal workflow runs as resume-ready entries
Resolve the t4/t6 overlap in index.ts by keeping the trust-gated workflow start path and adding the journal persistence hook and entry renderer. Adapt journal step lookup to the item engine: an each-step's item children share their step's id, so the run journal records one row per plan step from the coordinator's aggregate status and joined output. Per-item journal rows remain a follow-up. Adds a regression test for the seam.
This commit is contained in:
commit
5baa7f4508
7 files changed
+700
-4
No files matched your search
+21
-1
@@ -17,7 +17,7 @@ import { Text } from "@earendil-works/pi-tui";
|
||||
import { readMaxWorkers } from "./config.ts";
|
||||
import { formatJob, formatJobList } from "./job-format.ts";
|
||||
import { SubagentManager } from "./manager.ts";
|
||||
import { extractJobSnapshots, persistedJob, SUBAGENT_JOB_ENTRY } from "./persistence.ts";
|
||||
import { extractJobSnapshots, extractWorkflowJournals, persistedJob, persistedWorkflowJournal, SUBAGENT_JOB_ENTRY, WORKFLOW_RUN_ENTRY } from "./persistence.ts";
|
||||
import { InvalidInvocationError, confirmProjectWorkflowSource, prepareInvocation, prepareWorkflowInvocation, type PrepareContext } from "./prepare.ts";
|
||||
import {
|
||||
formatParallelSummary,
|
||||
@@ -122,6 +122,14 @@ export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) {
|
||||
// Ephemeral sessions and persistence failures do not change job execution.
|
||||
}
|
||||
},
|
||||
onWorkflowJournal: (journal) => {
|
||||
if (!currentContext) return;
|
||||
try {
|
||||
pi.appendEntry(WORKFLOW_RUN_ENTRY, persistedWorkflowJournal(currentContext.sessionManager.getSessionId(), journal));
|
||||
} catch {
|
||||
// The journal is an audit record; losing it never changes a run.
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const approvedProjectWorkflowDirs = new Set<string>();
|
||||
@@ -186,6 +194,18 @@ export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) {
|
||||
);
|
||||
});
|
||||
|
||||
pi.registerEntryRenderer(WORKFLOW_RUN_ENTRY, (entry, _options, theme) => {
|
||||
const journal = extractWorkflowJournals([entry])[0];
|
||||
if (!journal) return undefined;
|
||||
return new Text(
|
||||
theme.fg("muted", "Workflow ") +
|
||||
theme.fg("accent", journal.plan.name) +
|
||||
theme.fg("muted", ` ${journal.jobId} · ${journal.steps.length} steps → ${journal.status}`),
|
||||
0,
|
||||
0,
|
||||
);
|
||||
});
|
||||
|
||||
pi.registerTool({
|
||||
name: "subagent",
|
||||
label: "Subagent (sync)",
|
||||
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
/**
|
||||
* 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).
|
||||
*/
|
||||
|
||||
import { createHash } from "node:crypto";
|
||||
import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "./output.ts";
|
||||
import type { JobSnapshot, JobStatus, TaskSnapshot, TaskStatus, UsageStats } from "./types.ts";
|
||||
import type { WorkflowPlan, WorkflowStep } from "./workflows.ts";
|
||||
import type { WorkflowRunSpec } from "./workflow.ts";
|
||||
|
||||
export interface WorkflowJournalStep {
|
||||
id: string;
|
||||
/** Stable across identical step inputs, so a replay layer can key on it. */
|
||||
inputHash: string;
|
||||
status: TaskStatus;
|
||||
/** Children started for this step; always 0 or 1 while no retry exists. */
|
||||
attempts: number;
|
||||
output: string;
|
||||
outputTruncated: boolean;
|
||||
outputBytesOmitted: number;
|
||||
startedAt?: number;
|
||||
finishedAt?: number;
|
||||
}
|
||||
|
||||
export interface WorkflowJournal {
|
||||
jobId: string;
|
||||
status: JobStatus;
|
||||
plan: WorkflowPlan;
|
||||
args: Record<string, string>;
|
||||
steps: WorkflowJournalStep[];
|
||||
usage: UsageStats;
|
||||
createdAt: number;
|
||||
startedAt?: number;
|
||||
finishedAt?: number;
|
||||
errorMessage?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deterministic JSON: object keys sorted, `undefined` members dropped, so the
|
||||
* same logical value always hashes to the same bytes regardless of construction
|
||||
* order.
|
||||
*/
|
||||
function canonical(value: unknown): string {
|
||||
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
|
||||
if (value !== null && typeof value === "object") {
|
||||
const members = Object.entries(value as Record<string, unknown>)
|
||||
.filter(([, member]) => member !== undefined)
|
||||
.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
|
||||
.map(([key, member]) => `${JSON.stringify(key)}:${canonical(member)}`);
|
||||
return `{${members.join(",")}}`;
|
||||
}
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
function planInputs(plan: WorkflowPlan): unknown {
|
||||
// Provenance (source, filePath) is where the plan came from, not what it asks
|
||||
// for; the same plan copied elsewhere keeps its step hashes.
|
||||
return {
|
||||
name: plan.name,
|
||||
description: plan.description,
|
||||
args: plan.args,
|
||||
steps: plan.steps.map((step: WorkflowStep) => ({
|
||||
id: step.id,
|
||||
agent: step.agent,
|
||||
task: step.task,
|
||||
needs: step.needs,
|
||||
each: step.each,
|
||||
model: step.model,
|
||||
cwd: step.cwd,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Hash the inputs that determine a step's work — the plan text, the step's
|
||||
* brief as written, and the resolved run arguments. Prior-step outputs are
|
||||
* deliberately excluded: they are results, not inputs, so identical inputs keep
|
||||
* identical hashes across runs.
|
||||
*/
|
||||
export function workflowStepInputHash(plan: WorkflowPlan, stepId: string, args: Readonly<Record<string, string>>): string {
|
||||
const payload = canonical({ version: 1, plan: planInputs(plan), step: stepId, args });
|
||||
return `sha256:${createHash("sha256").update(payload, "utf8").digest("hex")}`;
|
||||
}
|
||||
|
||||
function boundedOutput(snapshot: TaskSnapshot): Pick<WorkflowJournalStep, "output" | "outputTruncated" | "outputBytesOmitted"> {
|
||||
const bounded = truncateUtf8Head(snapshot.output, MAX_TASK_OUTPUT_BYTES);
|
||||
const bytesOmitted = snapshot.outputBytesOmitted + bounded.bytesOmitted;
|
||||
const truncated = snapshot.outputTruncated || bounded.truncated;
|
||||
return {
|
||||
output: truncated ? `${bounded.text}\n\n[Output truncated: ${bytesOmitted} bytes omitted]` : bounded.text,
|
||||
outputTruncated: truncated,
|
||||
outputBytesOmitted: bytesOmitted,
|
||||
};
|
||||
}
|
||||
|
||||
function journalStep(stepId: string, plan: WorkflowPlan, args: Record<string, string>, snapshot?: TaskSnapshot): WorkflowJournalStep {
|
||||
const inputHash = workflowStepInputHash(plan, stepId, args);
|
||||
if (!snapshot) {
|
||||
return {
|
||||
id: stepId,
|
||||
inputHash,
|
||||
status: "queued",
|
||||
attempts: 0,
|
||||
output: "",
|
||||
outputTruncated: false,
|
||||
outputBytesOmitted: 0,
|
||||
};
|
||||
}
|
||||
return {
|
||||
id: stepId,
|
||||
inputHash,
|
||||
status: snapshot.status,
|
||||
attempts: snapshot.startedAt === undefined ? 0 : 1,
|
||||
...boundedOutput(snapshot),
|
||||
startedAt: snapshot.startedAt,
|
||||
finishedAt: snapshot.finishedAt,
|
||||
};
|
||||
}
|
||||
|
||||
/** 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. Per-item
|
||||
// journal rows are a separate follow-up.
|
||||
if (current === undefined || (current.item !== undefined && snapshot.item === undefined)) byStep.set(snapshot.stepId, snapshot);
|
||||
}
|
||||
return {
|
||||
jobId: job.id,
|
||||
status: job.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) =>
|
||||
journalStep(step.id, spec.plan, spec.args, byStep.get(step.id) ?? (byStep.size === 0 ? job.results[index] : undefined)),
|
||||
),
|
||||
usage: { ...job.usage },
|
||||
createdAt: job.createdAt,
|
||||
startedAt: job.startedAt,
|
||||
finishedAt: job.finishedAt,
|
||||
errorMessage: job.errorMessage,
|
||||
};
|
||||
}
|
||||
+22
-3
@@ -1,4 +1,5 @@
|
||||
import { truncateUtf8Head } from "./output.ts";
|
||||
import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "./output.ts";
|
||||
import { buildWorkflowJournal, type WorkflowJournal } from "./journal.ts";
|
||||
import {
|
||||
emptyUsage,
|
||||
isTerminalJob,
|
||||
@@ -33,7 +34,6 @@ const DEFAULT_MAX_ACTIVE_JOBS = 64;
|
||||
const DEFAULT_HISTORY_LIMIT = 50;
|
||||
const DEFAULT_WAIT_SECONDS = 30;
|
||||
const MAX_WAIT_SECONDS = 300;
|
||||
const ASYNC_OUTPUT_LIMIT_BYTES = 50 * 1024;
|
||||
|
||||
interface InternalTask {
|
||||
prepared: PreparedTask;
|
||||
@@ -129,6 +129,7 @@ export class SubagentManager {
|
||||
private readonly historyLimit: number;
|
||||
private readonly now: () => number;
|
||||
private readonly onJobChange?: (snapshot: JobSnapshot) => void;
|
||||
private readonly onWorkflowJournal?: (journal: WorkflowJournal) => void;
|
||||
private readonly jobs = new Map<string, Execution>();
|
||||
private readonly activeExecutions = new Set<Execution>();
|
||||
private readonly queue: ScheduledTask[] = [];
|
||||
@@ -144,6 +145,7 @@ export class SubagentManager {
|
||||
this.historyLimit = options.historyLimit ?? DEFAULT_HISTORY_LIMIT;
|
||||
this.now = options.now ?? Date.now;
|
||||
this.onJobChange = options.onJobChange;
|
||||
this.onWorkflowJournal = options.onWorkflowJournal;
|
||||
}
|
||||
|
||||
startAsync(request: PreparedInvocation): JobSnapshot {
|
||||
@@ -335,6 +337,7 @@ export class SubagentManager {
|
||||
this.activeExecutions.delete(execution);
|
||||
this.emit(execution);
|
||||
this.resolveWaiters(execution);
|
||||
this.emitJournal(execution);
|
||||
this.emitSync(execution);
|
||||
}
|
||||
this.pruneHistory();
|
||||
@@ -875,7 +878,7 @@ export class SubagentManager {
|
||||
task.snapshot.status = execution.cancelRequested ? "cancelled" : failed(result) ? "failed" : "succeeded";
|
||||
task.result.status = task.snapshot.status;
|
||||
task.snapshot.exitCode = result.exitCode;
|
||||
const output = truncateUtf8Head(result.output, ASYNC_OUTPUT_LIMIT_BYTES);
|
||||
const output = truncateUtf8Head(result.output, MAX_TASK_OUTPUT_BYTES);
|
||||
task.snapshot.output = output.text;
|
||||
task.snapshot.outputTruncated = output.truncated;
|
||||
task.snapshot.outputBytesOmitted = output.bytesOmitted;
|
||||
@@ -910,6 +913,7 @@ export class SubagentManager {
|
||||
this.emit(execution);
|
||||
this.emitSync(execution);
|
||||
this.resolveWaiters(execution);
|
||||
this.emitJournal(execution);
|
||||
this.pruneHistory();
|
||||
}
|
||||
|
||||
@@ -958,6 +962,21 @@ 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.
|
||||
*/
|
||||
private emitJournal(execution: Execution): void {
|
||||
const spec = execution.workflow;
|
||||
if (!this.onWorkflowJournal || execution.request.mode !== "workflow" || !spec) return;
|
||||
try {
|
||||
this.onWorkflowJournal(buildWorkflowJournal(this.snapshot(execution), spec));
|
||||
} catch {
|
||||
// Persistence failures cannot change run execution.
|
||||
}
|
||||
}
|
||||
|
||||
private pruneHistory(): void {
|
||||
const terminal = Array.from(this.jobs.values())
|
||||
.filter((job) => job.isAsync && isTerminalJob(job.status))
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
/** Async task snapshots and journal records share one bounded-output budget. */
|
||||
export const MAX_TASK_OUTPUT_BYTES = 50 * 1024;
|
||||
|
||||
export interface TruncatedText {
|
||||
text: string;
|
||||
truncated: boolean;
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { WorkflowJournal, WorkflowJournalStep } from "./journal.ts";
|
||||
import type { JobSnapshot } from "./types.ts";
|
||||
|
||||
export const SUBAGENT_JOB_ENTRY = "subagent-job-v1";
|
||||
export const WORKFLOW_RUN_ENTRY = "pi-workflow-run-v1";
|
||||
|
||||
interface PersistedJob {
|
||||
version: 1;
|
||||
@@ -8,10 +10,20 @@ interface PersistedJob {
|
||||
job: JobSnapshot;
|
||||
}
|
||||
|
||||
interface PersistedWorkflowJournal {
|
||||
version: 1;
|
||||
sessionId: string;
|
||||
journal: WorkflowJournal;
|
||||
}
|
||||
|
||||
export function persistedJob(sessionId: string, job: JobSnapshot): PersistedJob {
|
||||
return { version: 1, sessionId, job: structuredClone(job) };
|
||||
}
|
||||
|
||||
export function persistedWorkflowJournal(sessionId: string, journal: WorkflowJournal): PersistedWorkflowJournal {
|
||||
return { version: 1, sessionId, journal: structuredClone(journal) };
|
||||
}
|
||||
|
||||
function record(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object";
|
||||
}
|
||||
@@ -66,3 +78,72 @@ export function extractJobSnapshots(entries: unknown[]): JobSnapshot[] {
|
||||
}
|
||||
return snapshots;
|
||||
}
|
||||
|
||||
function validPlan(value: unknown): boolean {
|
||||
if (!record(value)) return false;
|
||||
return typeof value.name === "string"
|
||||
&& typeof value.description === "string"
|
||||
&& Array.isArray(value.args) && value.args.every((arg) => typeof arg === "string")
|
||||
&& (value.source === "user" || value.source === "project")
|
||||
&& typeof value.filePath === "string"
|
||||
&& Array.isArray(value.steps) && value.steps.every(validPlanStep);
|
||||
}
|
||||
|
||||
function validPlanStep(value: unknown): boolean {
|
||||
if (!record(value)) return false;
|
||||
return typeof value.id === "string"
|
||||
&& typeof value.agent === "string"
|
||||
&& typeof value.task === "string"
|
||||
&& Array.isArray(value.needs) && value.needs.every((need) => typeof need === "string")
|
||||
&& (value.each === undefined || typeof value.each === "string")
|
||||
&& (value.model === undefined || typeof value.model === "string")
|
||||
&& (value.cwd === undefined || typeof value.cwd === "string");
|
||||
}
|
||||
|
||||
function finiteNumber(value: unknown): boolean {
|
||||
return typeof value === "number" && Number.isFinite(value);
|
||||
}
|
||||
|
||||
function validJournalStep(value: unknown): value is WorkflowJournalStep {
|
||||
if (!record(value)) return false;
|
||||
return typeof value.id === "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 validJournal(value: unknown): value is WorkflowJournal {
|
||||
if (!record(value)) return false;
|
||||
return typeof value.jobId === "string"
|
||||
&& typeof value.status === "string" && jobStatuses.has(value.status)
|
||||
&& validPlan(value.plan)
|
||||
&& record(value.args) && Object.values(value.args).every((arg) => typeof arg === "string")
|
||||
&& Array.isArray(value.steps) && value.steps.every(validJournalStep)
|
||||
&& validUsage(value.usage)
|
||||
&& finiteNumber(value.createdAt)
|
||||
&& (value.startedAt === undefined || finiteNumber(value.startedAt))
|
||||
&& (value.finishedAt === undefined || finiteNumber(value.finishedAt))
|
||||
&& (value.errorMessage === undefined || typeof value.errorMessage === "string");
|
||||
}
|
||||
|
||||
/**
|
||||
* One journal record per run.
|
||||
*
|
||||
* A run writes its entry once, when it reaches a terminal state. Duplicates are
|
||||
* only possible if a session was written twice, so the last record for a job id
|
||||
* wins and consumers always see one journal per run.
|
||||
*/
|
||||
export function extractWorkflowJournals(entries: unknown[]): WorkflowJournal[] {
|
||||
const byJob = new Map<string, WorkflowJournal>();
|
||||
for (const entry of entries) {
|
||||
if (!record(entry) || entry.type !== "custom" || entry.customType !== WORKFLOW_RUN_ENTRY || !record(entry.data)) continue;
|
||||
if (entry.data.version !== 1 || !validJournal(entry.data.journal)) continue;
|
||||
byJob.set(entry.data.journal.jobId, structuredClone(entry.data.journal));
|
||||
}
|
||||
return Array.from(byJob.values());
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
|
||||
import type { Message } from "@earendil-works/pi-ai";
|
||||
import type { AgentConfig, AgentScope } from "./agents.ts";
|
||||
import type { WorkflowJournal } from "./journal.ts";
|
||||
|
||||
export type InvocationMode = "single" | "parallel" | "chain" | "workflow";
|
||||
export type JobStatus = "queued" | "running" | "cancelling" | "succeeded" | "failed" | "cancelled" | "interrupted";
|
||||
@@ -138,6 +139,8 @@ export interface ManagerOptions {
|
||||
historyLimit?: number;
|
||||
now?: () => number;
|
||||
onJobChange?: (snapshot: JobSnapshot) => void;
|
||||
/** Called once per workflow run, when it reaches a terminal state. */
|
||||
onWorkflowJournal?: (journal: WorkflowJournal) => void;
|
||||
}
|
||||
|
||||
export const TERMINAL_JOB_STATUSES: ReadonlySet<JobStatus> = new Set(["succeeded", "failed", "cancelled", "interrupted"]);
|
||||
|
||||
@@ -0,0 +1,417 @@
|
||||
import assert from "node:assert/strict";
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
import test, { after } from "node:test";
|
||||
import { buildWorkflowJournal, workflowStepInputHash, type WorkflowJournal } from "../src/journal.ts";
|
||||
import { SubagentManager } from "../src/manager.ts";
|
||||
import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "../src/output.ts";
|
||||
import {
|
||||
extractJobSnapshots,
|
||||
extractWorkflowJournals,
|
||||
persistedJob,
|
||||
persistedWorkflowJournal,
|
||||
SUBAGENT_JOB_ENTRY,
|
||||
WORKFLOW_RUN_ENTRY,
|
||||
} from "../src/persistence.ts";
|
||||
import { prepareWorkflowInvocation, type PrepareContext } from "../src/prepare.ts";
|
||||
import { parseWorkflow, type WorkflowPlan } from "../src/workflows.ts";
|
||||
import { emptyUsage, type JobSnapshot, type TaskSnapshot, type TaskStatus } from "../src/types.ts";
|
||||
import { FakeRunner } from "./helpers.ts";
|
||||
|
||||
const tempRoots: string[] = [];
|
||||
|
||||
after(() => {
|
||||
for (const root of tempRoots) fs.rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function makeWorkspace(agentNames = ["scout"]): { cwd: string; ctx: PrepareContext } {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-journal-"));
|
||||
tempRoots.push(root);
|
||||
const agentsDir = path.join(root, ".pi", "agents");
|
||||
fs.mkdirSync(agentsDir, { recursive: true });
|
||||
for (const name of agentNames) {
|
||||
fs.writeFileSync(
|
||||
path.join(agentsDir, `${name}.md`),
|
||||
`---\nname: ${name}\ndescription: ${name} agent\n---\nYou are ${name}.\n`,
|
||||
"utf-8",
|
||||
);
|
||||
}
|
||||
return {
|
||||
cwd: root,
|
||||
ctx: {
|
||||
cwd: root,
|
||||
hasUI: false,
|
||||
isProjectTrusted: () => true,
|
||||
ui: { confirm: async () => true },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function makePlan(steps: Array<Record<string, unknown>>, args: string[] = []): WorkflowPlan {
|
||||
const content = `---\n${JSON.stringify({ name: "test-workflow", description: "Test workflow", args, steps }, null, 2)}\n---\n\nNotes.\n`;
|
||||
return parseWorkflow(content, { source: "user", filePath: "/tmp/test-workflow.md" });
|
||||
}
|
||||
|
||||
function pending(runner: FakeRunner, stepId: string) {
|
||||
const call = runner.calls.find((candidate) => candidate.task.stepId === stepId && !candidate.settled);
|
||||
if (!call) throw new Error(`No pending step ${stepId}; running: ${runner.calls.map((c) => `${c.task.stepId}:${c.settled}`).join(", ")}`);
|
||||
return call;
|
||||
}
|
||||
|
||||
function completeStep(runner: FakeRunner, stepId: string, output = "done", overrides: Record<string, unknown> = {}): void {
|
||||
const call = pending(runner, stepId);
|
||||
runner.complete(call.task.task, output, overrides);
|
||||
}
|
||||
|
||||
function tick(): Promise<void> {
|
||||
return new Promise((resolve) => setImmediate(resolve));
|
||||
}
|
||||
|
||||
/** What the session store does to a custom entry between turns. */
|
||||
function serialized(entry: unknown): unknown {
|
||||
return JSON.parse(JSON.stringify(entry));
|
||||
}
|
||||
|
||||
test("a finished run persists one journal entry with per-step records and usage", async () => {
|
||||
const { ctx } = makeWorkspace();
|
||||
const plan = makePlan(
|
||||
[
|
||||
{ id: "scan", agent: "scout", task: "scan {args.target}" },
|
||||
{ id: "audit", agent: "scout", task: "audit {steps.scan.output}", needs: ["scan"] },
|
||||
],
|
||||
["target"],
|
||||
);
|
||||
const runner = new FakeRunner();
|
||||
const journals: WorkflowJournal[] = [];
|
||||
const manager = new SubagentManager(runner, { onWorkflowJournal: (journal) => journals.push(journal) });
|
||||
const started = manager.startWorkflow(
|
||||
await prepareWorkflowInvocation(plan, { target: "src" }, ctx, { agentScope: "project", confirmProjectAgents: false }),
|
||||
);
|
||||
|
||||
completeStep(runner, "scan", "src/a.ts");
|
||||
await tick();
|
||||
completeStep(runner, "audit", "no findings");
|
||||
const terminal = await manager.wait(started.id, 1);
|
||||
|
||||
assert.equal(terminal.status, "succeeded");
|
||||
assert.equal(journals.length, 1);
|
||||
const journal = journals[0];
|
||||
assert.equal(journal.jobId, started.id);
|
||||
assert.equal(journal.status, "succeeded");
|
||||
assert.deepEqual(journal.plan, plan);
|
||||
assert.deepEqual(journal.args, { target: "src" });
|
||||
assert.deepEqual(journal.usage, terminal.usage);
|
||||
assert.deepEqual(
|
||||
journal.steps.map((step) => [step.id, step.status, step.attempts, step.output]),
|
||||
[
|
||||
["scan", "succeeded", 1, "src/a.ts"],
|
||||
["audit", "succeeded", 1, "no findings"],
|
||||
],
|
||||
);
|
||||
for (const step of journal.steps) {
|
||||
assert.match(step.inputHash, /^sha256:[0-9a-f]{64}$/);
|
||||
assert.equal(typeof step.startedAt, "number");
|
||||
assert.equal(typeof step.finishedAt, "number");
|
||||
}
|
||||
|
||||
const entry = serialized({ type: "custom", customType: WORKFLOW_RUN_ENTRY, data: persistedWorkflowJournal("session-a", journal) });
|
||||
assert.deepEqual(extractWorkflowJournals([entry]), [serialized(journal)]);
|
||||
});
|
||||
|
||||
test("an unfinished run journals once as interrupted and restores interrupted after reload", async () => {
|
||||
const { ctx } = makeWorkspace();
|
||||
const plan = makePlan([
|
||||
{ id: "scan", agent: "scout", task: "scan" },
|
||||
{ id: "audit", agent: "scout", task: "audit {steps.scan.output}", needs: ["scan"] },
|
||||
]);
|
||||
const runner = new FakeRunner();
|
||||
const journals: WorkflowJournal[] = [];
|
||||
const jobs: JobSnapshot[] = [];
|
||||
const manager = new SubagentManager(runner, {
|
||||
maxWorkers: 2,
|
||||
onJobChange: (job) => jobs.push(job),
|
||||
onWorkflowJournal: (journal) => journals.push(journal),
|
||||
});
|
||||
const started = manager.startWorkflow(
|
||||
await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false }),
|
||||
);
|
||||
assert.deepEqual(manager.get(started.id).results.map((result) => result.status), ["running", "queued"]);
|
||||
|
||||
await manager.shutdown();
|
||||
|
||||
assert.equal(journals.length, 1, "one journal entry per run, not one per state change");
|
||||
const journal = journals[0];
|
||||
assert.equal(journal.status, "interrupted");
|
||||
assert.deepEqual(
|
||||
journal.steps.map((step) => [step.id, step.status, step.attempts]),
|
||||
[
|
||||
["scan", "interrupted", 1],
|
||||
["audit", "interrupted", 0],
|
||||
],
|
||||
);
|
||||
|
||||
// Reload: the job snapshots restore interrupted (existing job semantics) and
|
||||
// the journal record read back from the branch stays intact.
|
||||
const entry = serialized({ type: "custom", customType: WORKFLOW_RUN_ENTRY, data: persistedWorkflowJournal("session-a", journal) });
|
||||
const jobEntries = jobs.map((job) => serialized({ type: "custom", customType: SUBAGENT_JOB_ENTRY, data: persistedJob("session-a", job) }));
|
||||
const replayed: unknown[] = [];
|
||||
const reloaded = new SubagentManager(new FakeRunner(), { onWorkflowJournal: (journal) => replayed.push(journal) });
|
||||
reloaded.restore(extractJobSnapshots(jobEntries));
|
||||
assert.equal(reloaded.get(started.id).status, "interrupted");
|
||||
assert.deepEqual(replayed, [], "restoring a run never writes a second journal record");
|
||||
assert.deepEqual(extractWorkflowJournals([entry]), [serialized(journal)]);
|
||||
});
|
||||
|
||||
test("oversized step outputs are bounded to the async snapshot budget with the truncation marker", async () => {
|
||||
const { ctx } = makeWorkspace();
|
||||
const plan = makePlan([{ id: "scan", agent: "scout", task: "scan" }]);
|
||||
const prepared = await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false });
|
||||
const oversized = "é".repeat(60 * 1024);
|
||||
// The same bound an async task snapshot applies to a child's output.
|
||||
const snapshotBound = truncateUtf8Head(oversized, MAX_TASK_OUTPUT_BYTES);
|
||||
|
||||
const 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 record = journal.steps[0];
|
||||
const [kept, note] = record.output.split("\n\n[Output truncated: ");
|
||||
assert.equal(kept, snapshotBound.text);
|
||||
assert.equal(note, `${snapshotBound.bytesOmitted} bytes omitted]`);
|
||||
assert.equal(Buffer.byteLength(kept, "utf8"), MAX_TASK_OUTPUT_BYTES);
|
||||
assert.equal(record.outputTruncated, true);
|
||||
assert.equal(record.outputBytesOmitted, Buffer.byteLength(oversized, "utf8") - MAX_TASK_OUTPUT_BYTES);
|
||||
|
||||
// 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,
|
||||
);
|
||||
assert.equal(bounded.steps[0].output.split("[Output truncated: ").length, 2);
|
||||
assert.equal(bounded.steps[0].outputBytesOmitted, snapshotBound.bytesOmitted);
|
||||
|
||||
const entry = serialized({ type: "custom", customType: WORKFLOW_RUN_ENTRY, data: persistedWorkflowJournal("session-a", journal) });
|
||||
assert.deepEqual(extractWorkflowJournals([entry]), [serialized(journal)]);
|
||||
});
|
||||
|
||||
test("step input hashes are stable across identical inputs and change with args or briefs", () => {
|
||||
const steps = [{ id: "scan", agent: "scout", task: "scan {args.target}" }];
|
||||
const first = makePlan(steps, ["target"]);
|
||||
const second = makePlan(steps, ["target"]);
|
||||
const hashes = (plan: WorkflowPlan, args: Record<string, string>) =>
|
||||
plan.steps.map((step) => workflowStepInputHash(plan, step.id, args));
|
||||
|
||||
assert.deepEqual(hashes(first, { target: "src" }), hashes(second, { target: "src" }));
|
||||
assert.notDeepEqual(hashes(first, { target: "src" }), hashes(first, { target: "lib" }));
|
||||
assert.notEqual(
|
||||
workflowStepInputHash(makePlan([{ id: "scan", agent: "scout", task: "scan {args.target} twice" }], ["target"]), "scan", { target: "src" }),
|
||||
workflowStepInputHash(first, "scan", { target: "src" }),
|
||||
);
|
||||
assert.notEqual(workflowStepInputHash(first, "ghost", { target: "src" }), workflowStepInputHash(first, "scan", { target: "src" }));
|
||||
});
|
||||
|
||||
test("journals hash the step inputs, not the outputs, so identical runs agree", async () => {
|
||||
const { ctx } = makeWorkspace();
|
||||
const plan = makePlan([
|
||||
{ id: "scan", agent: "scout", task: "scan {args.target}" },
|
||||
{ id: "audit", agent: "scout", task: "audit {steps.scan.output}", needs: ["scan"] },
|
||||
], ["target"]);
|
||||
|
||||
async function run(args: Record<string, string>, output: string): Promise<WorkflowJournal> {
|
||||
const runner = new FakeRunner();
|
||||
const journals: WorkflowJournal[] = [];
|
||||
const manager = new SubagentManager(runner, { onWorkflowJournal: (journal) => journals.push(journal) });
|
||||
const started = manager.startWorkflow(
|
||||
await prepareWorkflowInvocation(plan, args, ctx, { agentScope: "project", confirmProjectAgents: false }),
|
||||
);
|
||||
completeStep(runner, "scan", `${output} sources`);
|
||||
await tick();
|
||||
completeStep(runner, "audit", output);
|
||||
await manager.wait(started.id, 1);
|
||||
assert.equal(journals.length, 1);
|
||||
return journals[0];
|
||||
}
|
||||
|
||||
const first = await run({ target: "src" }, "first");
|
||||
const second = await run({ target: "src" }, "second, different output");
|
||||
const otherArgs = await run({ target: "lib" }, "first");
|
||||
|
||||
const hashes = (journal: WorkflowJournal) => journal.steps.map((step) => [step.id, step.inputHash]);
|
||||
assert.deepEqual(hashes(first), hashes(second));
|
||||
assert.notDeepEqual(hashes(first), hashes(otherArgs));
|
||||
assert.equal(first.steps.every((step) => step.inputHash.startsWith("sha256:")), true);
|
||||
});
|
||||
|
||||
test("journal extraction ignores foreign and malformed entries and keeps the latest record per run", async () => {
|
||||
const { ctx } = makeWorkspace();
|
||||
const plan = makePlan([{ id: "scan", agent: "scout", task: "scan" }]);
|
||||
const prepared = await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false });
|
||||
const 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 entry = serialized({ type: "custom", customType: WORKFLOW_RUN_ENTRY, data: persistedWorkflowJournal("session-a", journal) });
|
||||
const later = serialized({
|
||||
type: "custom",
|
||||
customType: WORKFLOW_RUN_ENTRY,
|
||||
data: persistedWorkflowJournal("session-a", { ...journal, status: "interrupted" }),
|
||||
});
|
||||
const broken = serialized({
|
||||
type: "custom",
|
||||
customType: WORKFLOW_RUN_ENTRY,
|
||||
data: { version: 1, sessionId: "session-a", journal: { jobId: "job_0010", status: "success?" } },
|
||||
});
|
||||
|
||||
assert.deepEqual(extractWorkflowJournals([broken, entry, later]), [serialized({ ...journal, status: "interrupted" })]);
|
||||
assert.deepEqual(extractWorkflowJournals([{ type: "custom", customType: "other", data: persistedWorkflowJournal("session-a", journal) }, { type: "message" }]), []);
|
||||
// A journal record is not a job snapshot: the two entry types stay separate.
|
||||
assert.deepEqual(extractJobSnapshots([entry]), []);
|
||||
});
|
||||
|
||||
test("a failed run journals skipped dependents and retains the independent branches", async () => {
|
||||
const { ctx } = makeWorkspace();
|
||||
const plan = makePlan([
|
||||
{ id: "scan", agent: "scout", task: "scan" },
|
||||
{ id: "notify", agent: "scout", task: "notify" },
|
||||
{ id: "audit", agent: "scout", task: "audit {steps.scan.output}", needs: ["scan"] },
|
||||
]);
|
||||
const runner = new FakeRunner();
|
||||
const journals: WorkflowJournal[] = [];
|
||||
const manager = new SubagentManager(runner, { maxWorkers: 3, onWorkflowJournal: (journal) => journals.push(journal) });
|
||||
const started = manager.startWorkflow(
|
||||
await prepareWorkflowInvocation(plan, {}, ctx, { agentScope: "project", confirmProjectAgents: false }),
|
||||
);
|
||||
|
||||
completeStep(runner, "scan", "partial", { exitCode: 1, errorMessage: "scan exploded" });
|
||||
await tick();
|
||||
completeStep(runner, "notify", "sent");
|
||||
assert.equal((await manager.wait(started.id, 1)).status, "failed");
|
||||
|
||||
assert.equal(journals.length, 1);
|
||||
assert.equal(journals[0].status, "failed");
|
||||
assert.deepEqual(
|
||||
journals[0].steps.map((step) => [step.id, step.status, step.attempts]),
|
||||
[
|
||||
["scan", "failed", 1],
|
||||
["notify", "succeeded", 1],
|
||||
["audit", "skipped", 0],
|
||||
],
|
||||
);
|
||||
assert.equal(journals[0].steps[2].output, "");
|
||||
});
|
||||
|
||||
test("an each-step journals one step record from its coordinator, not one row per item", 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 => ({
|
||||
agent: "scout",
|
||||
agentSource: "user",
|
||||
task: "check",
|
||||
cwd: ctx.cwd,
|
||||
stepId,
|
||||
item,
|
||||
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),
|
||||
snapshot("check", "failed", "boom b", 2),
|
||||
],
|
||||
};
|
||||
|
||||
const journal = buildWorkflowJournal(job, prepared.workflow);
|
||||
assert.equal(journal.steps.length, 2, "one journal record per plan step");
|
||||
assert.deepEqual(
|
||||
journal.steps.map((step) => [step.id, step.status, step.output]),
|
||||
[
|
||||
["list", "succeeded", "src/a.ts\nsrc/b.ts"],
|
||||
["check", "succeeded", "aggregate"],
|
||||
],
|
||||
);
|
||||
assert.equal(journal.steps[1].attempts, 1, "a started step records its attempt count");
|
||||
});
|
||||
Reference in new issue
Block a user