diff --git a/src/index.ts b/src/index.ts index 41c7f68..e421c32 100644 --- a/src/index.ts +++ b/src/index.ts @@ -17,6 +17,7 @@ import { Text } from "@earendil-works/pi-tui"; import { readEnvironmentConfig } from "./config.ts"; import { SubagentDashboard } from "./dashboard.ts"; import { formatJob, formatJobList } from "./job-format.ts"; +import { formatWorkflowRunSummary } from "./journal.ts"; import { SubagentManager } from "./manager.ts"; import { extractJobSnapshots, extractWorkflowJournals, persistedJob, persistedWorkflowJournal, SUBAGENT_JOB_ENTRY, WORKFLOW_RUN_ENTRY } from "./persistence.ts"; import { InvalidInvocationError, prepareInvocation, prepareWorkflowInvocation, type PrepareContext } from "./prepare.ts"; @@ -143,18 +144,25 @@ export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) { const updateStatus = (ctx: ExtensionContext | undefined = currentContext): void => { if (!ctx) return; - const active = manager.list(true).length; + const active = manager.activeJobCount(); ctx.ui.setStatus("subagents", active > 0 ? `subagents: ${active} active` : undefined); }; const manager = new SubagentManager(taskRunner ?? new ProcessRunner(), { maxWorkers: workerConfig.value, - onJobChange: (job) => { + onJobEvent: (event) => { updateStatus(); - activeDashboard?.refresh(); + if (event.kind === "changed") { + activeDashboard?.refresh(); + return; + } + // Start entry and terminal checkpoint only: no per-transition entries (ADR 0004). if (!currentContext) return; try { - pi.appendEntry(SUBAGENT_JOB_ENTRY, persistedJob(currentContext.sessionManager.getSessionId(), job)); + pi.appendEntry( + SUBAGENT_JOB_ENTRY, + persistedJob(currentContext.sessionManager.getSessionId(), manager.get(event.jobId)), + ); } catch { // Ephemeral sessions and persistence failures do not change job execution. } @@ -354,6 +362,7 @@ export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) { description: [ "Inspect and control async subagent jobs.", "Actions: list {activeOnly?}; get {jobId}; wait {jobId, timeoutSeconds? (default 30, max 300)}; cancel {jobId}.", + "wait on a workflow run returns its bounded summary (status, step lines, last succeeded step's output); get returns the full snapshot.", "Waiting or timing out never cancels a job. Failed/cancelled/interrupted job snapshots are normal retrieval results, not management-tool errors.", ].join(" "), parameters: SubagentJobsParams, @@ -366,8 +375,13 @@ export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) { } case "get": return jobResult(manager.get(params.jobId)); - case "wait": - return jobResult(await manager.wait(params.jobId, params.timeoutSeconds, signal)); + case "wait": { + const result = await manager.wait(params.jobId, params.timeoutSeconds, signal); + if ("planName" in result) { + return { content: [{ type: "text", text: formatWorkflowRunSummary(result) }], details: { run: result } }; + } + return jobResult(result); + } case "cancel": return jobResult(manager.cancel(params.jobId)); default: diff --git a/src/job-state.ts b/src/job-state.ts index a4590d5..fcb50fd 100644 --- a/src/job-state.ts +++ b/src/job-state.ts @@ -30,6 +30,12 @@ export interface InternalTask { */ prepared?: PreparedTask; snapshot: TaskSnapshot; + /** + * The transcript this row's appended messages accumulate in, one entry per + * activity event. Bounded activity is projected from it on read; it is + * never copied per transition. + */ + messages: RunResult["messages"]; controller?: AbortController; result?: RunResult; } @@ -106,6 +112,7 @@ export function initialTask(prepared: PreparedTask): InternalTask { prepared, result: { ...emptyRunResult(prepared), status: "queued" }, snapshot: emptyTaskSnapshot(prepared), + messages: [], }; } diff --git a/src/journal.ts b/src/journal.ts index 685e4e1..ce40b69 100644 --- a/src/journal.ts +++ b/src/journal.ts @@ -7,14 +7,19 @@ * one row per fanned-out item alongside its step's record, plus the run's usage. * It is a projection of the run's DAG index, taken at that transition: plan and * item order come from the index, never from re-deriving the graph out of the - * flat job record. Nothing here replays or resumes a run: the shape exists so a - * future replay layer needs no migration (ADR 0004). + * flat job record. The same record also projects onto the bounded consolidated + * answer (status, one line per step, the last succeeded step's output) that + * both the push notice and `wait` carry (ADR 0006). Nothing here replays or + * resumes a run: the shape exists so a future replay layer needs no migration + * (ADR 0004). */ import { createHash } from "node:crypto"; -import { jobUsage, type Execution, type InternalTask } from "./job-state.ts"; +import { isTerminalJob, jobUsage, type Execution, type InternalTask } from "./job-state.ts"; import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "./output.ts"; import type { + JobStatus, + TaskStatus, WorkflowJournal, WorkflowJournalItem, WorkflowJournalStep, @@ -189,3 +194,95 @@ export function buildWorkflowJournal(run: WorkflowJournalRun): WorkflowJournal { errorMessage: execution.errorMessage, }; } + +/** One step's line in a run summary: identity and status, never its output. */ +export interface WorkflowRunStepSummary { + id: string; + status: TaskStatus; + /** One line, e.g. `audit succeeded (2/3 items)`. */ + line: string; +} + +/** + * The consolidated, bounded answer to a run — the one shape both pull and push + * consume (ADR 0006). `steps` carries one line per step; `answer` is the last + * succeeded step's already-bounded journal output, and only exists for a + * terminal run. A run with no succeeded step carries its status and error + * instead of partial output. + */ +export interface WorkflowRunSummary { + jobId: string; + status: JobStatus; + planName: string; + steps: WorkflowRunStepSummary[]; + answer?: { stepId: string; output: string }; + /** Bounded run error, present when no step succeeded. */ + error?: string; + /** True when the pull timed out; the run itself is unchanged and still active. */ + timedOut?: boolean; +} + +/** The journal fields the bounded summary needs; a full journal satisfies it. */ +export interface WorkflowRunSummarySource { + jobId: string; + status: JobStatus; + plan: { name: string }; + steps: readonly WorkflowJournalStep[]; + errorMessage?: string; +} + +function lastSucceededStep(steps: readonly WorkflowJournalStep[]): WorkflowJournalStep | undefined { + for (let index = steps.length - 1; index >= 0; index--) { + if (steps[index].status === "succeeded") return steps[index]; + } + return undefined; +} + +/** Bound the error with the same budget as step output; the summary carries no unbounded text. */ +function boundedReason(message: string): string { + const bounded = truncateUtf8Head(message, MAX_TASK_OUTPUT_BYTES); + return bounded.truncated ? `${bounded.text}\n\n[Error truncated: ${bounded.bytesOmitted} bytes omitted]` : bounded.text; +} + +function stepSummaryLine(step: WorkflowJournalStep): string { + if (step.items.length === 0) return `${step.id} ${step.status}`; + const succeeded = step.items.filter((item) => item.status === "succeeded").length; + return `${step.id} ${step.status} (${succeeded}/${step.items.length} items)`; +} + +/** + * Project a run's journal record onto the bounded answer: run status, one line + * per step, and the last succeeded step's bounded output. While the run is + * still active, intermediate outputs stay out of the summary. + */ +export function summarizeWorkflowRun(run: WorkflowRunSummarySource): WorkflowRunSummary { + const summary: WorkflowRunSummary = { + jobId: run.jobId, + status: run.status, + planName: run.plan.name, + steps: run.steps.map((step) => ({ id: step.id, status: step.status, line: stepSummaryLine(step) })), + }; + if (!isTerminalJob(run.status)) return summary; + const step = lastSucceededStep(run.steps); + if (step) summary.answer = { stepId: step.id, output: step.output }; + else if (run.errorMessage) summary.error = boundedReason(run.errorMessage); + return summary; +} + +/** + * The exact bytes both delivery paths carry for the same run: the ultra push + * notice and `subagent_jobs wait` format the summary here, nowhere else. + */ +export function formatWorkflowRunSummary(summary: WorkflowRunSummary): string { + const lines = [ + `Run ${summary.jobId} ${summary.status} — plan "${summary.planName}"${summary.timedOut ? " (wait timed out; run is unchanged)" : ""}.`, + ]; + if (summary.steps.length > 0) lines.push(`Steps: ${summary.steps.map((step) => step.line).join(" · ")}`); + if (summary.answer) { + lines.push(`Last succeeded step: ${summary.answer.stepId}.`, summary.answer.output || "(no output)"); + } else if (isTerminalJob(summary.status)) { + lines.push("No step succeeded."); + if (summary.error) lines.push(`Error: ${summary.error}`); + } + return lines.join("\n"); +} diff --git a/src/manager.ts b/src/manager.ts index 9ef2cf1..32a89f3 100644 --- a/src/manager.ts +++ b/src/manager.ts @@ -11,8 +11,12 @@ import { type Execution, type InternalTask, } from "./job-state.ts"; +import { summarizeWorkflowRun, type WorkflowRunSummary } from "./journal.ts"; import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "./output.ts"; import { + type JobActivityEvent, + type JobEvent, + type JobEventKind, type JobSnapshot, type JobStatus, type ManagerOptions, @@ -40,14 +44,28 @@ interface ScheduledTask { resolve: (result: RunResult) => void; } +/** + * What `wait` resolves with: the full snapshot for a single/parallel/chain + * job, and the bounded consolidated summary for a run (ADR 0006). `get` is + * the explicit verbose path for either. + */ +export type WaitResult = JobSnapshot | WorkflowRunSummary; + interface Waiter { - resolve: (snapshot: JobSnapshot) => void; + resolve: (result: WaitResult) => void; reject: (error: Error) => void; timer: NodeJS.Timeout; } -function cloneSnapshot(snapshot: JobSnapshot): JobSnapshot { - return structuredClone(snapshot); +/** A task row as the snapshot sees it: identity, current fields, bounded activity. */ +function taskSnapshotView(task: InternalTask, now: number): TaskSnapshot { + return { + ...task.snapshot, + usage: { ...task.snapshot.usage }, + // Live rows project bounded activity from their accumulated messages on + // read; restored rows keep the activity their snapshot was persisted with. + activity: task.messages.length > 0 ? summarizeActivity(task.messages, now) : task.snapshot.activity, + }; } export class SubagentManager { @@ -56,8 +74,8 @@ export class SubagentManager { private readonly maxActiveJobs: number; private readonly historyLimit: number; private readonly now: () => number; - private readonly onJobChange?: (snapshot: JobSnapshot) => void; - private readonly onJobActivity?: (snapshot: JobSnapshot) => void; + private readonly onJobEvent?: (event: JobEvent) => void; + private readonly onJobActivity?: (event: JobActivityEvent) => void; private readonly onWorkflowJournal?: (journal: WorkflowJournal) => void; /** DAG supervision for workflow runs; the pool and lifecycle stay here. */ private readonly workflows: WorkflowSupervisor; @@ -65,6 +83,10 @@ export class SubagentManager { private readonly activeExecutions = new Set(); private readonly queue: ScheduledTask[] = []; private readonly waiters = new Map>(); + /** A snapshot is rebuilt on the first read after a change, never on the change itself. */ + private readonly snapshots = new WeakMap(); + /** The bounded run answer, built once at the terminal transition from its journal. */ + private readonly runSummaries = new WeakMap(); private liveWorkers = 0; private nextJobId = 1; private accepting = true; @@ -75,7 +97,7 @@ export class SubagentManager { this.maxActiveJobs = options.maxActiveJobs ?? DEFAULT_MAX_ACTIVE_JOBS; this.historyLimit = options.historyLimit ?? DEFAULT_HISTORY_LIMIT; this.now = options.now ?? Date.now; - this.onJobChange = options.onJobChange; + this.onJobEvent = options.onJobEvent; this.onJobActivity = options.onJobActivity; this.onWorkflowJournal = options.onWorkflowJournal; this.workflows = new WorkflowSupervisor( @@ -97,6 +119,7 @@ export class SubagentManager { const task = initialTask(prepared); execution.tasks.push(task); execution.plannedTaskCount += 1; + this.snapshots.delete(execution); return task; } @@ -150,6 +173,44 @@ export class SubagentManager { return this.snapshot(this.requireJob(jobId)); } + /** Active async jobs, for the status line: a recount, never a snapshot projection. */ + activeJobCount(): number { + let active = 0; + for (const job of this.jobs.values()) { + if (job.isAsync && !isTerminalJob(job.status)) active++; + } + return active; + } + + /** + * The wait shape: a run yields the bounded consolidated summary (status, + * one line per step, the last succeeded step's output), a non-run job its + * full snapshot. A run still in flight yields its status and step lines + * only, never an intermediate output. + */ + private waitResult(execution: Execution, timedOut = false): WaitResult { + if (execution.request.mode !== "workflow") { + const snapshot = this.snapshot(execution); + return timedOut ? { ...snapshot, timedOut: true } : snapshot; + } + const summary = this.runSummaries.get(execution) ?? this.liveRunSummary(execution); + return timedOut ? { ...summary, timedOut: true } : summary; + } + + private liveRunSummary(execution: Execution): WorkflowRunSummary { + const journal = this.workflows.journal(execution); + if (journal) return summarizeWorkflowRun(journal); + // A run whose loop failed before settling leaves no journal; the bounded + // answer is its status and error. + return summarizeWorkflowRun({ + jobId: execution.id, + status: execution.status, + plan: execution.workflow?.plan ?? { name: "workflow" }, + steps: [], + errorMessage: execution.errorMessage, + }); + } + list(activeOnly = false): JobSnapshot[] { return Array.from(this.jobs.values()) .filter((job) => job.isAsync && (!activeOnly || !isTerminalJob(job.status))) @@ -157,15 +218,15 @@ export class SubagentManager { .map((job) => this.snapshot(job)); } - async wait(jobId: string, timeoutSeconds = DEFAULT_WAIT_SECONDS, signal?: AbortSignal): Promise { + async wait(jobId: string, timeoutSeconds = DEFAULT_WAIT_SECONDS, signal?: AbortSignal): Promise { const execution = this.requireJob(jobId); if (!Number.isFinite(timeoutSeconds) || timeoutSeconds <= 0 || timeoutSeconds > MAX_WAIT_SECONDS) { throw new Error(`wait timeout must be greater than 0 and at most ${MAX_WAIT_SECONDS} seconds`); } - if (isTerminalJob(execution.status)) return this.snapshot(execution); + if (isTerminalJob(execution.status)) return this.waitResult(execution); if (signal?.aborted) throw new Error("Wait aborted"); - return new Promise((resolve, reject) => { + return new Promise((resolve, reject) => { const waiters = this.waiters.get(jobId) ?? new Set(); this.waiters.set(jobId, waiters); const waiter: Waiter = { @@ -173,7 +234,7 @@ export class SubagentManager { reject, timer: setTimeout(() => { waiters.delete(waiter); - waiter.resolve({ ...this.snapshot(execution), timedOut: true }); + waiter.resolve(this.waitResult(execution, true)); }, timeoutSeconds * 1000), }; const onAbort = () => { @@ -182,10 +243,10 @@ export class SubagentManager { reject(new Error("Wait aborted")); }; if (signal) signal.addEventListener("abort", onAbort, { once: true }); - waiter.resolve = (snapshot) => { + waiter.resolve = (result) => { clearTimeout(waiter.timer); if (signal) signal.removeEventListener("abort", onAbort); - resolve(snapshot); + resolve(result); }; waiter.reject = (error) => { clearTimeout(waiter.timer); @@ -204,7 +265,7 @@ export class SubagentManager { const tasks: InternalTask[] = saved.results.map((result) => { // A persisted snapshot is the record: there is no AgentConfig to // reconstruct, and restored rows are terminal so none is launched. - const task: InternalTask = { snapshot: structuredClone(result) }; + const task: InternalTask = { snapshot: structuredClone(result), messages: [] }; if (interrupted && (task.snapshot.status === "queued" || task.snapshot.status === "running")) { task.snapshot.status = "interrupted"; task.snapshot.finishedAt = this.now(); @@ -274,9 +335,9 @@ export class SubagentManager { } for (const task of execution.tasks) task.controller?.abort(); this.activeExecutions.delete(execution); - this.emit(execution); - this.resolveWaiters(execution); + this.emit(execution, "finalized"); this.emitJournal(execution); + this.resolveWaiters(execution); this.emitSync(execution); } this.pruneHistory(); @@ -367,7 +428,10 @@ export class SubagentManager { this.activeExecutions.add(execution); if (isAsync) { this.jobs.set(id, execution); - if (!isWorkflow) this.emit(execution); + // A workflow's rows are created by its supervisor after this event, so + // the start entry carries no task rows; the checkpoint at the terminal + // transition carries them all (ADR 0004). + this.emit(execution, "started"); } return execution; } @@ -458,11 +522,13 @@ export class SubagentManager { if (!prepared) throw new Error("Task has no prepared brief"); const result = await this.runner.run(prepared, execution.request.dispatchDefaults, { signal: controller.signal, - onUpdate: (partial) => { + onUpdate: ({ result: partial, message }) => { partial.status = "running"; if (execution.isAsync) { + if (message) task.messages.push(message); this.updateSnapshotFromResult(task, partial); - this.emitActivity(execution); + this.snapshots.delete(execution); + if (message) this.emitActivity(execution, message); return; } task.result = partial; @@ -503,7 +569,6 @@ export class SubagentManager { task.snapshot.stopReason = result.stopReason; task.snapshot.errorMessage = result.errorMessage; task.snapshot.terminationSignal = result.terminationSignal; - if (result.messages.length > 0) task.snapshot.activity = summarizeActivity(result.messages, this.now()); } private applyResult(execution: Execution, task: InternalTask, result: RunResult, prepared: PreparedTask): void { @@ -517,6 +582,15 @@ export class SubagentManager { task.result.status = task.snapshot.status; task.snapshot.exitCode = result.exitCode; this.updateSnapshotFromResult(task, result); + // A runner that never streamed a message still reports its transcript at + // completion. The terminal row keeps the bounded activity, not the + // transcript it was projected from; the full messages live only in the + // runner's result. + if (task.messages.length === 0 && result.messages.length > 0) task.messages = result.messages; + if (task.messages.length > 0) { + task.snapshot.activity = summarizeActivity(task.messages, this.now()); + task.messages = []; + } task.snapshot.finishedAt = this.now(); } @@ -538,10 +612,12 @@ export class SubagentManager { execution.status = execution.cancelRequested && status !== "interrupted" ? "cancelled" : status; execution.finishedAt = this.now(); this.activeExecutions.delete(execution); - this.emit(execution); + this.emit(execution, "finalized"); this.emitSync(execution); - this.resolveWaiters(execution); + // The summary is built before waiters resolve, so a wait always sees the + // same consolidated answer the push notice carries. this.emitJournal(execution); + this.resolveWaiters(execution); this.pruneHistory(); } @@ -549,7 +625,7 @@ export class SubagentManager { const waiters = this.waiters.get(execution.id); if (!waiters) return; this.waiters.delete(execution.id); - for (const waiter of waiters) waiter.resolve(this.snapshot(execution)); + for (const waiter of waiters) waiter.resolve(this.waitResult(execution)); } private requireJob(jobId: string): Execution { @@ -559,36 +635,41 @@ export class SubagentManager { } private snapshot(execution: Execution): JobSnapshot { - return cloneSnapshot({ + const cached = this.snapshots.get(execution); + if (cached) return cached; + const snapshot: JobSnapshot = { id: execution.id, mode: execution.request.mode, agentScope: execution.request.agentScope, projectAgentsDir: execution.request.projectAgentsDir, - projectAgentsDirs: execution.request.projectAgentsDirs ?? (execution.request.projectAgentsDir ? [execution.request.projectAgentsDir] : []), + projectAgentsDirs: [...(execution.request.projectAgentsDirs ?? (execution.request.projectAgentsDir ? [execution.request.projectAgentsDir] : []))], status: execution.status, plannedTaskCount: execution.plannedTaskCount, - results: execution.tasks.map((task) => task.snapshot), + results: execution.tasks.map((task) => taskSnapshotView(task, this.now())), usage: jobUsage(execution.tasks), createdAt: execution.createdAt, startedAt: execution.startedAt, finishedAt: execution.finishedAt, errorMessage: execution.errorMessage, - }); + }; + this.snapshots.set(execution, snapshot); + return snapshot; } - private emitActivity(execution: Execution): void { + private emitActivity(execution: Execution, message: JobActivityEvent["message"]): void { if (!execution.isAsync) return; try { - this.onJobActivity?.(this.snapshot(execution)); + this.onJobActivity?.({ jobId: execution.id, message }); } catch { // Transient UI observers cannot interrupt scheduling. } } - private emit(execution: Execution): void { + private emit(execution: Execution, kind: JobEventKind = "changed"): void { if (!execution.isAsync) return; + this.snapshots.delete(execution); try { - this.onJobChange?.(this.snapshot(execution)); + this.onJobEvent?.({ jobId: execution.id, kind }); } catch { // Persistence/UI observers cannot interrupt scheduling. } @@ -603,9 +684,13 @@ export class SubagentManager { * missing one. */ private emitJournal(execution: Execution): void { - if (!this.onWorkflowJournal || execution.request.mode !== "workflow") return; + if (execution.request.mode !== "workflow") return; const journal = this.workflows.journal(execution); if (!journal) return; + // The summary is the run's bounded answer; retaining it is what keeps the + // pull path from ever touching the full journal again. + this.runSummaries.set(execution, summarizeWorkflowRun(journal)); + if (!this.onWorkflowJournal) return; try { this.onWorkflowJournal(journal); } catch { diff --git a/src/runner.ts b/src/runner.ts index 002c9d1..43b50af 100644 --- a/src/runner.ts +++ b/src/runner.ts @@ -299,17 +299,22 @@ export class ProcessRunner implements TaskRunner { let abortRequested = false; let killTimer: NodeJS.Timeout | undefined; - const notify = (): void => { + const notify = (message: Message): void => { if (!options.onUpdate) return; try { const tail = stderrTail.read(); options.onUpdate({ - ...result, - messages: [...result.messages], - usage: { ...result.usage }, - output: finalAssistantText(result.messages), - stderr: tail.text, - stderrTruncated: tail.truncated, + result: { + ...result, + // The live transcript is shared by reference; the appended + // message is also carried as the delta, so an observer never + // has to copy or scan the whole array. + usage: { ...result.usage }, + output: finalAssistantText(result.messages), + stderr: tail.text, + stderrTruncated: tail.truncated, + }, + message, }); } catch { // An observer must not break the child run. @@ -344,7 +349,7 @@ export class ProcessRunner implements TaskRunner { if (message.stopReason) result.stopReason = message.stopReason; if (message.errorMessage) result.errorMessage = message.errorMessage; } - notify(); + notify(message); }; const onStdout = (chunk: Buffer): void => { diff --git a/src/types.ts b/src/types.ts index 3fcaf17..d411dac 100644 --- a/src/types.ts +++ b/src/types.ts @@ -71,9 +71,21 @@ export interface RunResult { status?: TaskStatus; } +/** + * One progress update from a runner: the result accumulated so far and, when + * the update was caused by a message, the message appended since the previous + * update. `result.messages` is the runner's live transcript, shared by + * reference; observers that accumulate activity use the delta and never copy + * the transcript. + */ +export interface RunUpdate { + result: RunResult; + message?: Message; +} + export interface RunOptions { signal: AbortSignal; - onUpdate?: (result: RunResult) => void; + onUpdate?: (update: RunUpdate) => void; } export interface TaskRunner { @@ -111,14 +123,32 @@ export interface SyncRunOptions { onUpdate?: (outcome: SyncOutcome) => void; } +/** The job lifecycle transitions an observer is told about. */ +export type JobEventKind = "started" | "changed" | "finalized"; + +/** + * A job lifecycle event: what changed, never a copy of the job. Persistence + * writes at `started` and `finalized`; views read the snapshot they need. + */ +export interface JobEvent { + jobId: string; + kind: JobEventKind; +} + +/** One message appended to a running child, for transient progress views. */ +export interface JobActivityEvent { + jobId: string; + message: Message; +} + export interface ManagerOptions { maxWorkers?: number; maxActiveJobs?: number; historyLimit?: number; now?: () => number; - onJobChange?: (snapshot: JobSnapshot) => void; - /** Transient progress for open views. Unlike onJobChange, this is not persisted per message. */ - onJobActivity?: (snapshot: JobSnapshot) => void; + onJobEvent?: (event: JobEvent) => void; + /** Transient progress for open views; one event per appended message, never persisted. */ + onJobActivity?: (event: JobActivityEvent) => void; /** Called once per workflow run, when it reaches a terminal state. */ onWorkflowJournal?: (journal: WorkflowJournal) => void; } diff --git a/src/ultra-mode.ts b/src/ultra-mode.ts index b5c70f6..cb0b2af 100644 --- a/src/ultra-mode.ts +++ b/src/ultra-mode.ts @@ -45,7 +45,7 @@ export function buildUltraGuidance(guideline: UltraGuideline, maxItemsPerEach: n "", `Size guideline: ${formatUltraGuideline(guideline)}. Hard caps: ${formatUltraCaps(maxItemsPerEach)}.`, "", - "Start a run, then wait for it with `subagent_jobs { action: \"wait\", jobId }` before continuing. The run's final step output is the consolidated answer; children of an ultra run cannot dispatch further agents.", + "Start a run, then wait for it with `subagent_jobs { action: \"wait\", jobId }` before continuing. The wait returns the run's status, a step summary, and the last succeeded step's bounded output — the consolidated answer; use `get` only when every step's output is needed. Children of an ultra run cannot dispatch further agents.", ].join("\n"); } diff --git a/src/ultra-notify.ts b/src/ultra-notify.ts index 76034a1..088e675 100644 --- a/src/ultra-notify.ts +++ b/src/ultra-notify.ts @@ -9,8 +9,8 @@ * child's output or reads a task snapshot again. */ -import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "./output.ts"; -import type { JobStatus, WorkflowJournal, WorkflowJournalStep } from "./types.ts"; +import { formatWorkflowRunSummary, summarizeWorkflowRun } from "./journal.ts"; +import type { JobStatus, WorkflowJournal } from "./types.ts"; export const ULTRA_DONE_MESSAGE_TYPE = "pi-subagent-ultra-done"; @@ -36,50 +36,31 @@ export interface UltraNotice { details: UltraNoticeDetails; } -/** The last step that succeeded, in journal (plan) order. */ -function lastSucceededStep(steps: readonly WorkflowJournalStep[]): WorkflowJournalStep | undefined { - for (let index = steps.length - 1; index >= 0; index--) { - if (steps[index].status === "succeeded") return steps[index]; - } - return undefined; -} - -/** - * Error messages are normally short, but the notice carries no unbounded - * text by contract, so bound them with the same budget as step outputs. - */ -function boundedReason(message: string): string { - const bounded = truncateUtf8Head(message, MAX_TASK_OUTPUT_BYTES); - return bounded.truncated ? `${bounded.text}\n\n[Error truncated: ${bounded.bytesOmitted} bytes omitted]` : bounded.text; -} - /** * The notice for one terminal run, or undefined when notices are off or the * run came from a workflow file. * - * A run with no succeeded step reports its status and error only: there is no - * partial output to present as the consolidated answer. Runs started through - * `subagent_async` or a workflow file are not inline-sourced and stay - * pull-based. + * The payload is the run's consolidated summary — the same bounded bytes + * `subagent_jobs wait` returns for that journal. A run with no succeeded step + * reports its status and error only: there is no partial output to present as + * the consolidated answer. Runs started through `subagent_async` or a workflow + * file are not inline-sourced and stay pull-based. */ export function buildUltraNotice(journal: WorkflowJournal, options: UltraNotifyOptions): UltraNotice | undefined { if (!options.ultraEnabled || !options.notifyEnabled) return undefined; if (journal.plan.source !== "inline") return undefined; - const step = lastSucceededStep(journal.steps); - const lines = [`Ultra run ${journal.jobId} ${journal.status} — plan "${journal.plan.name}".`]; - if (step) { - lines.push(`Last succeeded step: ${step.id}.`, step.output || "(no output)"); - } else { - lines.push("No step succeeded."); - if (journal.errorMessage) lines.push(`Error: ${boundedReason(journal.errorMessage)}`); - } - + const summary = summarizeWorkflowRun(journal); const details: UltraNoticeDetails = { jobId: journal.jobId, status: journal.status, planName: journal.plan.name, }; - if (step) details.stepId = step.id; - return { customType: ULTRA_DONE_MESSAGE_TYPE, content: lines.join("\n"), display: true, details }; + if (summary.answer) details.stepId = summary.answer.stepId; + return { + customType: ULTRA_DONE_MESSAGE_TYPE, + content: formatWorkflowRunSummary(summary), + display: true, + details, + }; } diff --git a/test/extension.test.ts b/test/extension.test.ts index 8e7e18b..2b16026 100644 --- a/test/extension.test.ts +++ b/test/extension.test.ts @@ -192,15 +192,19 @@ test("subagents opens a selected job in the TUI and keeps text output in RPC", a assert.match(component.render(120).join("\n"), new RegExp(`> ${jobId}`)); const rendersBeforeProgress = h.getCustomRenders(); const pending = h.runner.calls[0]; + const message = { + role: "assistant", + content: [{ type: "toolCall", id: "call-1", name: "bash", arguments: { command: "npm test" } }], + timestamp: 100, + } as unknown as Message; pending.options.onUpdate?.({ - ...makeResult(pending.task, "live output"), - status: "running", - exitCode: null, - messages: [{ - role: "assistant", - content: [{ type: "toolCall", id: "call-1", name: "bash", arguments: { command: "npm test" } }], - timestamp: 100, - }] as unknown as Message[], + result: { + ...makeResult(pending.task, "live output"), + status: "running", + exitCode: null, + messages: [message], + }, + message, }); assert.ok(h.getCustomRenders() > rendersBeforeProgress); assert.match(component.render(120).join("\n"), /\$ npm test/); @@ -346,7 +350,7 @@ test("workflow tool starts a run and returns its id and expanded plan", async () undefined, h.ctx, ); - assert.equal((waited.details as any).job.status, "succeeded"); + assert.equal((waited.details as any).run.status, "succeeded"); } finally { await h.events.get("session_shutdown")?.({ type: "session_shutdown" }, h.ctx); await fs.promises.rm(h.cwd, { recursive: true, force: true }); diff --git a/test/helpers.ts b/test/helpers.ts index 2765f67..3f262d5 100644 --- a/test/helpers.ts +++ b/test/helpers.ts @@ -1,5 +1,7 @@ import type { AgentConfig } from "../src/agents.ts"; -import type { PreparedInvocation, RunResult, TaskRunner, RunOptions } from "../src/types.ts"; +import type { WorkflowRunSummary } from "../src/journal.ts"; +import type { SubagentManager, WaitResult } from "../src/manager.ts"; +import type { JobSnapshot, PreparedInvocation, RunResult, TaskRunner, RunOptions } from "../src/types.ts"; export const agent: AgentConfig = { name: "scout", @@ -83,3 +85,19 @@ export class FakeRunner implements TaskRunner { pending.resolve({ ...result(pending.task, output), ...overrides }); } } + +/** True when a wait resolved with a run's bounded summary instead of a job snapshot. */ +export function isRunWait(result: WaitResult): result is WorkflowRunSummary { + return "planName" in result; +} + +/** + * Wait for a job, then read the full snapshot: for a run, `wait` returns the + * bounded summary, so tests that inspect every row use the explicit `get` path. + */ +export async function waitForSnapshot(manager: SubagentManager, jobId: string, timeoutSeconds = 1): Promise { + const result = await manager.wait(jobId, timeoutSeconds); + if (!isRunWait(result)) return result; + const snapshot = manager.get(jobId); + return result.timedOut ? { ...snapshot, timedOut: true } : snapshot; +} diff --git a/test/manager.test.ts b/test/manager.test.ts index 68234cc..16f7c91 100644 --- a/test/manager.test.ts +++ b/test/manager.test.ts @@ -2,8 +2,8 @@ import assert from "node:assert/strict"; import test from "node:test"; import type { Message } from "@earendil-works/pi-ai"; import { SubagentManager } from "../src/manager.ts"; -import type { JobSnapshot } from "../src/types.ts"; -import { FakeRunner, invocation, result as makeResult } from "./helpers.ts"; +import type { JobActivityEvent, JobEvent, JobSnapshot } from "../src/types.ts"; +import { FakeRunner, invocation, result as makeResult, waitForSnapshot } from "./helpers.ts"; test("async single returns an ID before completion and later exposes its result", async () => { const runner = new FakeRunner(); @@ -15,7 +15,7 @@ test("async single returns an ID before completion and later exposes its result" assert.equal(runner.calls.length, 1); runner.complete("task 1", "finished"); - const terminal = await manager.wait(job.id, 1); + const terminal = await waitForSnapshot(manager, job.id, 1); assert.equal(terminal.status, "succeeded"); assert.equal(terminal.results.length, 1); assert.equal(terminal.results[0].output, "finished"); @@ -24,26 +24,33 @@ test("async single returns an ID before completion and later exposes its result" test("async progress exposes bounded activity without persisting every message", async () => { const persisted: JobSnapshot[] = []; - const progress: JobSnapshot[] = []; + const events: JobEvent[] = []; + const progress: JobActivityEvent[] = []; const runner = new FakeRunner(); const manager = new SubagentManager(runner, { - onJobChange: (job) => persisted.push(job), - onJobActivity: (job) => progress.push(job), + onJobEvent: (event) => { + events.push(event); + if (event.kind !== "changed") persisted.push(manager.get(event.jobId)); + }, + onJobActivity: (event) => progress.push(event), }); const job = manager.startAsync(invocation()); const persistedBeforeProgress = persisted.length; const pending = runner.calls[0]; - const messages = [{ + const message = { role: "assistant", content: [{ type: "toolCall", id: "call-1", name: "bash", arguments: { command: "npm test" } }], timestamp: 100, - }] as unknown as Message[]; + } as unknown as Message; pending.options.onUpdate?.({ - ...makeResult(pending.task, "working"), - status: "running", - exitCode: null, - messages, + result: { + ...makeResult(pending.task, "working"), + status: "running", + exitCode: null, + messages: [message], + }, + message, }); const current = manager.get(job.id); @@ -52,11 +59,15 @@ test("async progress exposes bounded activity without persisting every message", { kind: "toolCall", summary: "$ npm test", timestamp: 100 }, ]); assert.equal(progress.length, 1); - assert.equal(persisted.length, persistedBeforeProgress); + assert.equal(progress[0].jobId, job.id); + assert.equal(progress[0].message, message); + assert.equal(persisted.length, persistedBeforeProgress, "a message delta is not a persistence event"); + assert.deepEqual(events.map((event) => event.kind), ["started", "changed"]); runner.complete("task 1", "finished"); - const terminal = await manager.wait(job.id, 1); + const terminal = await waitForSnapshot(manager, job.id, 1); assert.equal(terminal.results[0].activity?.[0].summary, "$ npm test"); + assert.deepEqual(events.map((event) => event.kind), ["started", "changed", "changed", "finalized"]); assert.equal(persisted.at(-1)?.results[0].activity?.[0].summary, "$ npm test"); }); @@ -73,7 +84,7 @@ test("parallel preserves partial results and does not finish while another task assert.equal(runner.calls.length, 2); runner.complete("task 2", "good"); - const terminal = await manager.wait(job.id, 1); + const terminal = await waitForSnapshot(manager, job.id, 1); assert.equal(terminal.status, "failed"); assert.deepEqual(terminal.results.map((result) => result.status), ["failed", "succeeded"]); assert.equal(terminal.results[0].errorMessage, "boom"); @@ -96,7 +107,7 @@ test("chain substitutes the previous output and starts only the next step", asyn assert.equal(runner.calls[1].task.task, "review first output"); runner.complete("review first output", "second output"); - const terminal = await manager.wait(job.id, 1); + const terminal = await waitForSnapshot(manager, job.id, 1); assert.equal(terminal.status, "succeeded"); assert.deepEqual(terminal.results.map((result) => result.step), [1, 2]); }); @@ -111,7 +122,7 @@ test("cancel drains queued tasks, aborts running tasks, and is idempotent", asyn assert.deepEqual(cancelling.results.map((result) => result.status), ["running", "cancelled"]); assert.deepEqual(runner.aborted, ["task 1"]); - const terminal = await manager.wait(job.id, 1); + const terminal = await waitForSnapshot(manager, job.id, 1); assert.equal(terminal.status, "cancelled"); assert.deepEqual(terminal.results.map((result) => result.status), ["cancelled", "cancelled"]); assert.equal(runner.calls.length, 1); @@ -132,7 +143,7 @@ test("the manager defaults to sixteen shared workers", async () => { await new Promise((resolve) => setImmediate(resolve)); assert.equal(runner.calls.length, 17); runner.complete("task 17"); - assert.equal((await manager.wait(job.id, 1)).status, "succeeded"); + assert.equal((await waitForSnapshot(manager, job.id, 1)).status, "succeeded"); }); test("synchronous and async work share the global worker limit", async () => { @@ -150,7 +161,7 @@ test("synchronous and async work share the global worker limit", async () => { runner.complete("task 1", "async done"); await new Promise((resolve) => setImmediate(resolve)); - assert.equal((await manager.wait(background.id, 1)).status, "succeeded"); + assert.equal((await waitForSnapshot(manager, background.id, 1)).status, "succeeded"); assert.equal(runner.calls.length, 2); runner.complete("task 1", "sync done"); @@ -164,7 +175,7 @@ test("wait timeout and caller abort do not cancel the job", async () => { const manager = new SubagentManager(runner); const job = manager.startAsync(invocation()); - const timedOut = await manager.wait(job.id, 0.01); + const timedOut = await waitForSnapshot(manager, job.id, 0.01); assert.equal(timedOut.status, "running"); assert.equal(timedOut.timedOut, true); assert.equal(manager.get(job.id).status, "running"); @@ -177,7 +188,7 @@ test("wait timeout and caller abort do not cancel the job", async () => { assert.equal(runner.aborted.length, 0); runner.complete("task 1"); - assert.equal((await manager.wait(job.id, 1)).status, "succeeded"); + assert.equal((await waitForSnapshot(manager, job.id, 1)).status, "succeeded"); }); test("shutdown interrupts work, drains the queue, awaits cleanup, and rejects admission", async () => { @@ -220,7 +231,7 @@ test("sync abort kills work, rejects the call, and releases its worker", async ( const next = manager.startAsync(invocation()); assert.equal(next.status, "running"); runner.complete("task 1"); - assert.equal((await manager.wait(next.id, 1)).status, "succeeded"); + assert.equal((await waitForSnapshot(manager, next.id, 1)).status, "succeeded"); }); test("async snapshots cap output without mutating the full runner result", async () => { @@ -230,7 +241,7 @@ test("async snapshots cap output without mutating the full runner result", async const output = "🙂ab".repeat(20000); runner.complete("task 1", output); - const terminal = await manager.wait(job.id, 1); + const terminal = await waitForSnapshot(manager, job.id, 1); const snapshot = terminal.results[0]; assert.equal(snapshot.outputTruncated, true); assert.ok(Buffer.byteLength(snapshot.output, "utf8") <= 50 * 1024); @@ -246,11 +257,11 @@ test("active admission is capped and terminal history evicts oldest jobs only", assert.throws(() => manager.startAsync(invocation()), /Too many active async jobs/); runner.complete("task 1", "first"); - assert.equal((await manager.wait(first.id, 1)).status, "succeeded"); + assert.equal((await waitForSnapshot(manager, first.id, 1)).status, "succeeded"); const second = manager.startAsync(invocation()); assert.equal(manager.get(first.id).status, "succeeded"); runner.complete("task 1", "second"); - assert.equal((await manager.wait(second.id, 1)).status, "succeeded"); + assert.equal((await waitForSnapshot(manager, second.id, 1)).status, "succeeded"); assert.throws(() => manager.get(first.id), /Unknown or evicted/); assert.equal(manager.get(second.id).results[0].output, "second"); }); @@ -277,7 +288,7 @@ test("chain stops on the first failure without manufacturing later results", asy const manager = new SubagentManager(runner); const job = manager.startAsync(invocation("chain")); runner.complete("task 1", "bad", { exitCode: 1, errorMessage: "failed step" }); - const terminal = await manager.wait(job.id, 1); + const terminal = await waitForSnapshot(manager, job.id, 1); assert.equal(terminal.status, "failed"); assert.equal(terminal.results.length, 1); assert.equal(runner.calls.length, 1); @@ -289,7 +300,7 @@ test("cancellation wins over a later successful process exit", async () => { const job = manager.startAsync(invocation()); manager.cancel(job.id); runner.complete("task 1", "too late", { exitCode: 0, stopReason: "stop" }); - const terminal = await manager.wait(job.id, 1); + const terminal = await waitForSnapshot(manager, job.id, 1); assert.equal(terminal.status, "cancelled"); assert.equal(terminal.results[0].status, "cancelled"); }); @@ -300,7 +311,7 @@ test("cancelled chain never starts a successor when the current step reports lat const job = manager.startAsync(invocation("chain")); manager.cancel(job.id); runner.complete("task 1", "late success", { exitCode: 0, stopReason: "stop" }); - const terminal = await manager.wait(job.id, 0.1); + const terminal = await waitForSnapshot(manager, job.id, 0.1); assert.equal(terminal.status, "cancelled"); assert.equal(runner.calls.length, 1); assert.equal(terminal.results.length, 1); @@ -311,22 +322,22 @@ test("branch replacement removes terminal history without replacing active jobs" const manager = new SubagentManager(runner); const finished = manager.startAsync(invocation()); runner.complete("task 1", "old branch"); - await manager.wait(finished.id, 1); + await waitForSnapshot(manager, finished.id, 1); const active = manager.startAsync(invocation()); manager.replaceHistory([]); assert.throws(() => manager.get(finished.id), /Unknown or evicted/); assert.equal(manager.get(active.id).status, "running"); runner.complete("task 1", "active"); - assert.equal((await manager.wait(active.id, 1)).status, "succeeded"); + assert.equal((await waitForSnapshot(manager, active.id, 1)).status, "succeeded"); }); test("observer failures cannot strand jobs or workers", async () => { const runner = new FakeRunner(); - const manager = new SubagentManager(runner, { onJobChange: () => { throw new Error("observer"); } }); + const manager = new SubagentManager(runner, { onJobEvent: () => { throw new Error("observer"); } }); const job = manager.startAsync(invocation()); runner.complete("task 1"); - assert.equal((await manager.wait(job.id, 1)).status, "succeeded"); + assert.equal((await waitForSnapshot(manager, job.id, 1)).status, "succeeded"); const sync = manager.runSync(invocation(), { onUpdate: () => { throw new Error("observer"); } }); await new Promise((resolve) => setImmediate(resolve)); diff --git a/test/runner.test.ts b/test/runner.test.ts index f9ac902..64f490f 100644 --- a/test/runner.test.ts +++ b/test/runner.test.ts @@ -6,7 +6,7 @@ import test from "node:test"; import { fileURLToPath } from "node:url"; import type { AgentConfig } from "../src/agents.ts"; import { ProcessRunner, type ProcessRunnerOptions } from "../src/runner.ts"; -import type { DispatchDefaults, PreparedTask, RunOptions, RunResult } from "../src/types.ts"; +import type { DispatchDefaults, PreparedTask, RunOptions, RunUpdate } from "../src/types.ts"; const fixturePath = fileURLToPath(new URL("./fixtures/fake-pi.mjs", import.meta.url)); const stderrLimit = 64 * 1024; @@ -79,9 +79,9 @@ function processIsAlive(pid: number): boolean { test("collects message_end JSONL, ignores tool_result_end, aggregates usage and returns final output", async (t) => { const runner = makeRunner({ FAKE_PI_MODE: "success" }); - const updates: RunResult[] = []; + const updates: RunUpdate[] = []; - const result = await runner.run(makeTask(), {}, runOptions({ onUpdate: (partial) => updates.push(partial) })); + const result = await runner.run(makeTask(), {}, runOptions({ onUpdate: (update) => updates.push(update) })); assert.equal(result.exitCode, 0); assert.equal(result.terminationSignal, undefined); @@ -114,9 +114,12 @@ test("collects message_end JSONL, ignores tool_result_end, aggregates usage and assert.ok(updates.length > 0); assert.equal( - updates.some((partial) => partial.messages.some((message) => message.role === "toolResult")), + updates.some((update) => update.message?.role === "toolResult"), true, ); + // Every update shares the runner's live transcript instead of copying it; + // the appended message rides along as the delta. + assert.equal(new Set(updates.map((update) => update.result.messages)).size, 1); t.diagnostic(`onUpdate calls: ${updates.length}`); }); diff --git a/test/ultra-mode.test.ts b/test/ultra-mode.test.ts index 23ee057..fdf2ce7 100644 --- a/test/ultra-mode.test.ts +++ b/test/ultra-mode.test.ts @@ -55,7 +55,7 @@ test("the guidance names the heuristics, every pattern mapping, the guideline, c /Size guideline: medium \(aim for fewer than 10 children\)/, /Hard caps: ≤ 64 steps, ≤ 32 items per each-step, ≤ 256 children per run/, /wait for it with `subagent_jobs/, - /final step output is the consolidated answer/, + /last succeeded step's bounded output — the consolidated answer/, ]) { assert.match(guidance, expected); } diff --git a/test/ultra-notify.test.ts b/test/ultra-notify.test.ts index 91859be..c9d8442 100644 --- a/test/ultra-notify.test.ts +++ b/test/ultra-notify.test.ts @@ -128,7 +128,8 @@ async function waitFor(h: Awaited>, jobId: string) { undefined, h.ctx, ); - return (waited.details as any).job; + const details = waited.details as any; + return details.run ?? details.job; } async function withEnv(name: string, value: string, run: () => Promise): Promise { @@ -206,7 +207,7 @@ test("an inline run sends one notice at terminal state with the consolidated ans planName: "notice-plan", stepId: "merge", }); - assert.match(message.content, new RegExp(`Ultra run ${started.id} succeeded`)); + assert.match(message.content, new RegExp(`Run ${started.id} succeeded`)); assert.match(message.content, /Last succeeded step: merge\./); assert.match(message.content, /the consolidated answer/); assert.doesNotMatch(message.content, /src\/a\.ts/); @@ -219,6 +220,79 @@ test("an inline run sends one notice at terminal state with the consolidated ans } }); +test("the push notice and wait carry identical bytes for the same run", async () => { + const h = await harness(); + try { + await startSession(h); + const started = await startUltra(h, [ + { id: "scan", agent: "scout", task: "scan sources" }, + { id: "merge", agent: "scout", task: "merge {steps.scan.output}", needs: ["scan"] }, + ]); + + h.runner.complete("scan sources", "src/a.ts"); + await tick(); + h.runner.complete("merge src/a.ts", "the consolidated answer"); + await tick(); + + const waited = await h.tools.get("subagent_jobs")!.execute( + "wait", + { action: "wait", jobId: started.id, timeoutSeconds: 1 }, + undefined, + undefined, + h.ctx, + ); + const waitText = waited.content[0]?.type === "text" ? waited.content[0].text : ""; + assert.equal(h.messages.length, 1); + assert.equal(waitText, h.messages[0].message.content, "pull and push carry the same bytes"); + assert.equal(Buffer.byteLength(waitText, "utf8"), Buffer.byteLength(h.messages[0].message.content, "utf8")); + assert.match(waitText, /Steps: scan succeeded · merge succeeded/); + assert.match(waitText, /Last succeeded step: merge\./); + assert.match(waitText, /the consolidated answer/); + assert.doesNotMatch(waitText, /src\/a\.ts/, "wait never returns an intermediate step output"); + + const run = (waited.details as any).run; + assert.equal(run.status, "succeeded"); + assert.equal(run.answer.stepId, "merge"); + assert.deepEqual(run.steps.map((step: any) => [step.id, step.status]), [ + ["scan", "succeeded"], + ["merge", "succeeded"], + ]); + } finally { + await fs.promises.rm(h.cwd, { recursive: true, force: true }); + } +}); + +test("a timed-out wait on a run carries status and step lines, never an intermediate output", async () => { + const h = await harness(); + try { + await startSession(h); + const started = await startUltra(h, [ + { id: "scan", agent: "scout", task: "scan sources" }, + { id: "merge", agent: "scout", task: "merge {steps.scan.output}", needs: ["scan"] }, + ]); + + h.runner.complete("scan sources", "intermediate secret"); + await tick(); + const waited = await h.tools.get("subagent_jobs")!.execute( + "wait", + { action: "wait", jobId: started.id, timeoutSeconds: 0.01 }, + undefined, + undefined, + h.ctx, + ); + const text = waited.content[0]?.type === "text" ? waited.content[0].text : ""; + assert.match(text, /(wait timed out; run is unchanged)/); + assert.match(text, /Steps: scan succeeded · merge running/); + assert.doesNotMatch(text, /intermediate secret/); + assert.doesNotMatch(text, /Last succeeded step/); + + h.runner.complete("merge intermediate secret", "final"); + await tick(); + } finally { + await fs.promises.rm(h.cwd, { recursive: true, force: true }); + } +}); + test("file-sourced workflow runs never notify", async () => { const h = await harness(); try { @@ -265,7 +339,7 @@ test("a run with no succeeded step notifies with status only, never partial outp assert.equal(failedJob.status, "failed"); assert.equal(h.messages.length, 1); - assert.match(h.messages[0].message.content, new RegExp(`Ultra run ${failed.id} failed`)); + assert.match(h.messages[0].message.content, new RegExp(`Run ${failed.id} failed`)); assert.match(h.messages[0].message.content, /No step succeeded\./); assert.doesNotMatch(h.messages[0].message.content, /partial findings/); assert.equal(h.messages[0].message.details?.stepId, undefined); @@ -283,7 +357,7 @@ test("a run with no succeeded step notifies with status only, never partial outp assert.equal(cancelledJob.status, "cancelled"); assert.equal(h.messages.length, 2); - assert.match(h.messages[1].message.content, new RegExp(`Ultra run ${cancelled.id} cancelled`)); + assert.match(h.messages[1].message.content, new RegExp(`Run ${cancelled.id} cancelled`)); assert.match(h.messages[1].message.content, /No step succeeded\./); assert.equal(h.messages[1].message.details?.stepId, undefined); } finally { @@ -334,7 +408,7 @@ test("buildUltraNotice carries the last succeeded step in journal order and the ); assert.ok(noticed); assert.equal(noticed.details.stepId, "audit"); - assert.match(noticed.content, /Ultra run job_0001 failed/); + assert.match(noticed.content, /Run job_0001 failed/); assert.match(noticed.content, /audit output/); assert.doesNotMatch(noticed.content, /partial merge/); assert.doesNotMatch(noticed.content, /scan output/); @@ -448,7 +522,7 @@ test("the notice renderer is registered and draws one line with the job id and s { role: "custom", customType: ULTRA_DONE_MESSAGE_TYPE, - content: "Ultra run job_0042 succeeded — plan \"audit\".", + content: "Run job_0042 succeeded — plan \"audit\".", display: true, details: { jobId: "job_0042", status: "succeeded", planName: "audit" }, timestamp: 0, diff --git a/test/ultra.test.ts b/test/ultra.test.ts index 2b56b85..7890906 100644 --- a/test/ultra.test.ts +++ b/test/ultra.test.ts @@ -471,7 +471,7 @@ test("an inline-sourced run journals source inline and round-trips through the j undefined, h.ctx, ); - assert.equal((waited.details as any).job.status, "succeeded"); + assert.equal((waited.details as any).run.status, "succeeded"); const journals = extractWorkflowJournals(h.entries); assert.equal(journals.length, 1); @@ -605,7 +605,7 @@ test("the guidance section is present exactly while the mode is on and stable ac assert.match(guidance, /`ultra` tool/); assert.match(guidance, /Size guideline: medium \(aim for fewer than 10 children\)/); assert.match(guidance, /Hard caps: ≤ 64 steps, ≤ 32 items per each-step, ≤ 256 children per run/); - assert.match(guidance, /final step output is the consolidated answer/); + assert.match(guidance, /last succeeded step's bounded output — the consolidated answer/); const second = promptEvent(); await h.events.get("before_agent_start")!(second, h.ctx); diff --git a/test/workflow-journal.test.ts b/test/workflow-journal.test.ts index f9db872..2529303 100644 --- a/test/workflow-journal.test.ts +++ b/test/workflow-journal.test.ts @@ -19,7 +19,7 @@ import { import { prepareWorkflowInvocation, type PrepareContext } from "../src/prepare.ts"; import { parseWorkflow, type WorkflowPlan, type WorkflowSource } from "../src/workflow-plan.ts"; import { emptyUsage, type JobSnapshot, type TaskSnapshot, type TaskStatus, type WorkflowJournal, type WorkflowJournalItem, type WorkflowJournalStep } from "../src/types.ts"; -import { FakeRunner } from "./helpers.ts"; +import { FakeRunner, waitForSnapshot } from "./helpers.ts"; const tempRoots: string[] = []; @@ -85,6 +85,7 @@ function serialized(entry: unknown): unknown { /** One row of a run's DAG index: the shared record the journal projects. */ function taskRow(stepId: string, status: TaskStatus, output = "", extra: Partial = {}): InternalTask { return { + messages: [], snapshot: { agent: "scout", agentSource: "user", @@ -130,7 +131,7 @@ test("a finished run persists one journal entry with per-step records and usage" completeStep(runner, "scan", "src/a.ts"); await tick(); completeStep(runner, "audit", "no findings"); - const terminal = await manager.wait(started.id, 1); + const terminal = await waitForSnapshot(manager, started.id, 1); assert.equal(terminal.status, "succeeded"); assert.equal(journals.length, 1); @@ -168,7 +169,10 @@ test("an unfinished run journals once as interrupted and restores interrupted af const jobs: JobSnapshot[] = []; const manager = new SubagentManager(runner, { maxWorkers: 2, - onJobChange: (job) => jobs.push(job), + onJobEvent: (event) => { + // Persistence checkpoints at the terminal transition only (ADR 0004). + if (event.kind === "finalized") jobs.push(manager.get(event.jobId)); + }, onWorkflowJournal: (journal) => journals.push(journal), }); const started = manager.startWorkflow( @@ -290,7 +294,7 @@ test("journals hash the step inputs, not the outputs, so identical runs agree", completeStep(runner, "scan", `${output} sources`); await tick(); completeStep(runner, "audit", output); - await manager.wait(started.id, 1); + await waitForSnapshot(manager, started.id, 1); assert.equal(journals.length, 1); return journals[0]; } @@ -351,7 +355,7 @@ test("a failed run journals skipped dependents and retains the independent branc 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((await waitForSnapshot(manager, started.id, 1)).status, "failed"); assert.equal(journals.length, 1); assert.equal(journals[0].status, "failed"); @@ -380,7 +384,7 @@ test("a cancelled run journals once, with every unfinished step settled cancelle ); manager.cancel(started.id); - assert.equal((await manager.wait(started.id, 1)).status, "cancelled"); + assert.equal((await waitForSnapshot(manager, started.id, 1)).status, "cancelled"); assert.equal(journals.length, 1); assert.equal(journals[0].status, "cancelled"); assert.deepEqual( @@ -570,7 +574,9 @@ test("a run journals each item's source line, status, and timings through the ma const journals: WorkflowJournal[] = []; const jobs: JobSnapshot[] = []; const manager = new SubagentManager(runner, { - onJobChange: (job) => jobs.push(job), + onJobEvent: (event) => { + if (event.kind === "finalized") jobs.push(manager.get(event.jobId)); + }, onWorkflowJournal: (journal) => journals.push(journal), }); const started = manager.startWorkflow( @@ -580,7 +586,7 @@ test("a run journals each item's source line, status, and timings through the ma 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((await waitForSnapshot(manager, started.id, 1)).status, "failed", "a failed item fails the run"); assert.equal(journals.length, 1); return { journal: journals[0], job: jobs.at(-1)! }; } diff --git a/test/workflow-run.test.ts b/test/workflow-run.test.ts index 32b2f1b..bcc928b 100644 --- a/test/workflow-run.test.ts +++ b/test/workflow-run.test.ts @@ -6,7 +6,7 @@ import test, { after } from "node:test"; import { SubagentManager } from "../src/manager.ts"; import { prepareWorkflowInvocation, type PrepareContext } from "../src/prepare.ts"; import { parseWorkflow, WorkflowValidationError, type WorkflowPlan } from "../src/workflow-plan.ts"; -import { FakeRunner } from "./helpers.ts"; +import { FakeRunner, waitForSnapshot } from "./helpers.ts"; const tempRoots: string[] = []; @@ -91,7 +91,7 @@ test("run releases steps only when needs succeed, interpolating outputs in plan completeStep(runner, "notify", "sent"); completeStep(runner, "merge", "ranked"); - const terminal = await manager.wait(started.id, 1); + const terminal = await waitForSnapshot(manager, started.id, 1); assert.equal(terminal.status, "succeeded"); assert.deepEqual(terminal.results.map((result) => result.stepId), ["scan", "audit", "merge", "notify"]); assert.deepEqual(terminal.results.map((result) => result.status), ["succeeded", "succeeded", "succeeded", "succeeded"]); @@ -126,7 +126,7 @@ test("a failed step skips dependents transitively while independent branches fin assert.equal(pending(runner, "publish").task.task, "publish ready"); completeStep(runner, "publish", "published"); - const terminal = await manager.wait(started.id, 1); + const terminal = await waitForSnapshot(manager, started.id, 1); assert.equal(terminal.status, "failed"); assert.deepEqual( terminal.results.map((result) => [result.stepId, result.status]), @@ -167,7 +167,7 @@ test("the per-run cap holds under fewer workers and the global FIFO releases the assert.equal(runner.calls.length, 4); completeStep(runner, "c"); completeStep(runner, "d"); - assert.equal((await manager.wait(started.id, 1)).status, "succeeded"); + assert.equal((await waitForSnapshot(manager, started.id, 1)).status, "succeeded"); }); test("a single-worker pool rejects workflow runs instead of reserving zero capacity", async () => { @@ -211,7 +211,7 @@ test("cancel mid-run aborts released steps and cancels queued steps without hang ], ); - const terminal = await manager.wait(started.id, 1); + const terminal = await waitForSnapshot(manager, started.id, 1); assert.equal(terminal.status, "cancelled"); assert.deepEqual( terminal.results.map((result) => [result.stepId, result.status]), @@ -336,7 +336,7 @@ test("reload interruption marks every unfinished workflow step interrupted and p ); assert.equal(restoredRunner.calls.length, 0); manager.cancel(started.id); - await manager.wait(started.id, 1); + await waitForSnapshot(manager, started.id, 1); }); test("a fan-in step waits for every need and interpolates all of them", async () => { @@ -360,7 +360,7 @@ test("a fan-in step waits for every need and interpolates all of them", async () await new Promise((resolve) => setImmediate(resolve)); assert.equal(pending(runner, "merge").task.task, "merge files + findings"); completeStep(runner, "merge", "ranked"); - assert.equal((await manager.wait(started.id, 1)).status, "succeeded"); + assert.equal((await waitForSnapshot(manager, started.id, 1)).status, "succeeded"); }); async function settleScheduler(): Promise { @@ -416,7 +416,7 @@ test("an each-step fans out one child per source line, honours the run cap, and assert.match(pending(runner, "merge").task.task, /### a\.ts\n\nok a/); completeStep(runner, "merge", "ranked"); - const terminal = await manager.wait(started.id, 1); + const terminal = await waitForSnapshot(manager, started.id, 1); assert.equal(terminal.status, "succeeded"); assert.deepEqual(terminal.results.filter((result) => result.stepId === "audit").map((result) => result.status), [ "succeeded", @@ -459,7 +459,7 @@ test("failed items leave empty slots and the step succeeds, but the run still fa const report = pending(runner, "report"); assert.match(report.task.task, /### b\.ts/); runner.complete(report.task.task, "reported"); - const terminal = await manager.wait(started.id, 1); + const terminal = await waitForSnapshot(manager, started.id, 1); assert.equal(terminal.status, "failed"); assert.equal(terminal.results.find((result) => result.stepId === "report")?.status, "succeeded"); assert.equal(terminal.results.find((result) => result.stepId === "audit" && result.item === undefined)?.status, "succeeded"); @@ -489,7 +489,7 @@ test("an each-step with all items failed fails the step and skips its dependents assert.match(audit.errorMessage ?? "", /All 2 items failed/); assert.equal(runner.calls.some((call) => call.task.stepId === "report"), false); - const terminal = await manager.wait(started.id, 1); + const terminal = await waitForSnapshot(manager, started.id, 1); assert.equal(terminal.status, "failed"); assert.deepEqual( terminal.results.map((result) => [result.stepId, result.item ?? null, result.status]), @@ -524,7 +524,7 @@ test("a source with zero items fails the step loudly and spawns no item children assert.match(audit.errorMessage ?? "", /source produced no items/i); assert.equal(runner.calls.some((call) => call.task.stepId === "audit"), false); - const terminal = await manager.wait(started.id, 1); + const terminal = await waitForSnapshot(manager, started.id, 1); assert.equal(terminal.status, "failed"); assert.equal(terminal.results.find((result) => result.stepId === "report")?.status, "skipped"); assert.equal(terminal.results.every((result) => result.finishedAt !== undefined), true); @@ -552,7 +552,7 @@ test("a run does not settle while items are in flight and every row ends termina assert.equal(stepRow(manager, started.id, "audit").status, "running"); assert.deepEqual(itemRows(manager, started.id, "audit").map((row) => row.status), ["succeeded", "running", "running"]); assert.equal(runner.calls.some((call) => call.task.stepId === "report"), false); - const timedOut = await manager.wait(started.id, 0.01); + const timedOut = await waitForSnapshot(manager, started.id, 0.01); assert.equal(timedOut.status, "running"); assert.equal(timedOut.timedOut, true); @@ -560,7 +560,7 @@ test("a run does not settle while items are in flight and every row ends termina runner.complete("audit c.ts", "good c"); await settleScheduler(); completeStep(runner, "report", "reported"); - const terminal = await manager.wait(started.id, 1); + const terminal = await waitForSnapshot(manager, started.id, 1); assert.equal(terminal.status, "succeeded"); assert.equal(terminal.results.every((result) => ["succeeded", "failed", "skipped", "cancelled", "interrupted"].includes(result.status)), true); assert.equal(terminal.results.every((result) => result.finishedAt !== undefined), true); @@ -583,7 +583,7 @@ test("cancel with items in flight and items still pending settles every item row assert.deepEqual(itemRows(manager, started.id, "audit").map((row) => row.status), ["running", "running", "queued", "queued"]); manager.cancel(started.id); - const terminal = await manager.wait(started.id, 1); + const terminal = await waitForSnapshot(manager, started.id, 1); assert.equal(terminal.status, "cancelled"); assert.equal(terminal.results.find((result) => result.stepId === "scan")?.status, "succeeded"); assert.equal( @@ -614,7 +614,7 @@ test("an each-step above the item cap fails at release without spawning its item assert.match(audit.errorMessage ?? "", /has 33 items/); assert.match(audit.errorMessage ?? "", /max is 32 per each-step/); assert.equal(runner.calls.some((call) => call.task.stepId === "audit"), false); - assert.equal((await manager.wait(started.id, 1)).status, "failed"); + assert.equal((await waitForSnapshot(manager, started.id, 1)).status, "failed"); }); test("the run-wide expanded child cap rejects the overflow each-step before its children spawn", async () => { @@ -642,5 +642,5 @@ test("the run-wide expanded child cap rejects the overflow each-step before its assert.equal(runner.calls.some((call) => call.task.stepId === "audit_7"), false); assert.equal(manager.get(started.id).status, "running"); manager.cancel(started.id); - assert.equal((await manager.wait(started.id, 1)).status, "cancelled"); + assert.equal((await waitForSnapshot(manager, started.id, 1)).status, "cancelled"); });