Emit job events, checkpoint at terminal, and bound the run wait
This commit is contained in:
1 parent
bf70be5729
commit
df929590e8
17 files changed
+501
-166
No files matched your search
+20
-6
@@ -17,6 +17,7 @@ import { Text } from "@earendil-works/pi-tui";
|
|||||||
import { readEnvironmentConfig } from "./config.ts";
|
import { readEnvironmentConfig } from "./config.ts";
|
||||||
import { SubagentDashboard } from "./dashboard.ts";
|
import { SubagentDashboard } from "./dashboard.ts";
|
||||||
import { formatJob, formatJobList } from "./job-format.ts";
|
import { formatJob, formatJobList } from "./job-format.ts";
|
||||||
|
import { formatWorkflowRunSummary } from "./journal.ts";
|
||||||
import { SubagentManager } from "./manager.ts";
|
import { SubagentManager } from "./manager.ts";
|
||||||
import { extractJobSnapshots, extractWorkflowJournals, persistedJob, persistedWorkflowJournal, SUBAGENT_JOB_ENTRY, WORKFLOW_RUN_ENTRY } from "./persistence.ts";
|
import { extractJobSnapshots, extractWorkflowJournals, persistedJob, persistedWorkflowJournal, SUBAGENT_JOB_ENTRY, WORKFLOW_RUN_ENTRY } from "./persistence.ts";
|
||||||
import { InvalidInvocationError, prepareInvocation, prepareWorkflowInvocation, type PrepareContext } from "./prepare.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 => {
|
const updateStatus = (ctx: ExtensionContext | undefined = currentContext): void => {
|
||||||
if (!ctx) return;
|
if (!ctx) return;
|
||||||
const active = manager.list(true).length;
|
const active = manager.activeJobCount();
|
||||||
ctx.ui.setStatus("subagents", active > 0 ? `subagents: ${active} active` : undefined);
|
ctx.ui.setStatus("subagents", active > 0 ? `subagents: ${active} active` : undefined);
|
||||||
};
|
};
|
||||||
|
|
||||||
const manager = new SubagentManager(taskRunner ?? new ProcessRunner(), {
|
const manager = new SubagentManager(taskRunner ?? new ProcessRunner(), {
|
||||||
maxWorkers: workerConfig.value,
|
maxWorkers: workerConfig.value,
|
||||||
onJobChange: (job) => {
|
onJobEvent: (event) => {
|
||||||
updateStatus();
|
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;
|
if (!currentContext) return;
|
||||||
try {
|
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 {
|
} catch {
|
||||||
// Ephemeral sessions and persistence failures do not change job execution.
|
// Ephemeral sessions and persistence failures do not change job execution.
|
||||||
}
|
}
|
||||||
@@ -354,6 +362,7 @@ export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) {
|
|||||||
description: [
|
description: [
|
||||||
"Inspect and control async subagent jobs.",
|
"Inspect and control async subagent jobs.",
|
||||||
"Actions: list {activeOnly?}; get {jobId}; wait {jobId, timeoutSeconds? (default 30, max 300)}; cancel {jobId}.",
|
"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.",
|
"Waiting or timing out never cancels a job. Failed/cancelled/interrupted job snapshots are normal retrieval results, not management-tool errors.",
|
||||||
].join(" "),
|
].join(" "),
|
||||||
parameters: SubagentJobsParams,
|
parameters: SubagentJobsParams,
|
||||||
@@ -366,8 +375,13 @@ export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) {
|
|||||||
}
|
}
|
||||||
case "get":
|
case "get":
|
||||||
return jobResult(manager.get(params.jobId));
|
return jobResult(manager.get(params.jobId));
|
||||||
case "wait":
|
case "wait": {
|
||||||
return jobResult(await manager.wait(params.jobId, params.timeoutSeconds, signal));
|
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":
|
case "cancel":
|
||||||
return jobResult(manager.cancel(params.jobId));
|
return jobResult(manager.cancel(params.jobId));
|
||||||
default:
|
default:
|
||||||
|
|||||||
@@ -30,6 +30,12 @@ export interface InternalTask {
|
|||||||
*/
|
*/
|
||||||
prepared?: PreparedTask;
|
prepared?: PreparedTask;
|
||||||
snapshot: TaskSnapshot;
|
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;
|
controller?: AbortController;
|
||||||
result?: RunResult;
|
result?: RunResult;
|
||||||
}
|
}
|
||||||
@@ -106,6 +112,7 @@ export function initialTask(prepared: PreparedTask): InternalTask {
|
|||||||
prepared,
|
prepared,
|
||||||
result: { ...emptyRunResult(prepared), status: "queued" },
|
result: { ...emptyRunResult(prepared), status: "queued" },
|
||||||
snapshot: emptyTaskSnapshot(prepared),
|
snapshot: emptyTaskSnapshot(prepared),
|
||||||
|
messages: [],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+100
-3
@@ -7,14 +7,19 @@
|
|||||||
* one row per fanned-out item alongside its step's record, plus the run's usage.
|
* one row per fanned-out item alongside its step's record, plus the run's usage.
|
||||||
* It is a projection of the run's DAG index, taken at that transition: plan and
|
* 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
|
* 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
|
* flat job record. The same record also projects onto the bounded consolidated
|
||||||
* future replay layer needs no migration (ADR 0004).
|
* 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 { 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 { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "./output.ts";
|
||||||
import type {
|
import type {
|
||||||
|
JobStatus,
|
||||||
|
TaskStatus,
|
||||||
WorkflowJournal,
|
WorkflowJournal,
|
||||||
WorkflowJournalItem,
|
WorkflowJournalItem,
|
||||||
WorkflowJournalStep,
|
WorkflowJournalStep,
|
||||||
@@ -189,3 +194,95 @@ export function buildWorkflowJournal(run: WorkflowJournalRun): WorkflowJournal {
|
|||||||
errorMessage: execution.errorMessage,
|
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");
|
||||||
|
}
|
||||||
+116
-31
@@ -11,8 +11,12 @@ import {
|
|||||||
type Execution,
|
type Execution,
|
||||||
type InternalTask,
|
type InternalTask,
|
||||||
} from "./job-state.ts";
|
} from "./job-state.ts";
|
||||||
|
import { summarizeWorkflowRun, type WorkflowRunSummary } from "./journal.ts";
|
||||||
import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "./output.ts";
|
import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "./output.ts";
|
||||||
import {
|
import {
|
||||||
|
type JobActivityEvent,
|
||||||
|
type JobEvent,
|
||||||
|
type JobEventKind,
|
||||||
type JobSnapshot,
|
type JobSnapshot,
|
||||||
type JobStatus,
|
type JobStatus,
|
||||||
type ManagerOptions,
|
type ManagerOptions,
|
||||||
@@ -40,14 +44,28 @@ interface ScheduledTask {
|
|||||||
resolve: (result: RunResult) => void;
|
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 {
|
interface Waiter {
|
||||||
resolve: (snapshot: JobSnapshot) => void;
|
resolve: (result: WaitResult) => void;
|
||||||
reject: (error: Error) => void;
|
reject: (error: Error) => void;
|
||||||
timer: NodeJS.Timeout;
|
timer: NodeJS.Timeout;
|
||||||
}
|
}
|
||||||
|
|
||||||
function cloneSnapshot(snapshot: JobSnapshot): JobSnapshot {
|
/** A task row as the snapshot sees it: identity, current fields, bounded activity. */
|
||||||
return structuredClone(snapshot);
|
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 {
|
export class SubagentManager {
|
||||||
@@ -56,8 +74,8 @@ export class SubagentManager {
|
|||||||
private readonly maxActiveJobs: number;
|
private readonly maxActiveJobs: number;
|
||||||
private readonly historyLimit: number;
|
private readonly historyLimit: number;
|
||||||
private readonly now: () => number;
|
private readonly now: () => number;
|
||||||
private readonly onJobChange?: (snapshot: JobSnapshot) => void;
|
private readonly onJobEvent?: (event: JobEvent) => void;
|
||||||
private readonly onJobActivity?: (snapshot: JobSnapshot) => void;
|
private readonly onJobActivity?: (event: JobActivityEvent) => void;
|
||||||
private readonly onWorkflowJournal?: (journal: WorkflowJournal) => void;
|
private readonly onWorkflowJournal?: (journal: WorkflowJournal) => void;
|
||||||
/** DAG supervision for workflow runs; the pool and lifecycle stay here. */
|
/** DAG supervision for workflow runs; the pool and lifecycle stay here. */
|
||||||
private readonly workflows: WorkflowSupervisor;
|
private readonly workflows: WorkflowSupervisor;
|
||||||
@@ -65,6 +83,10 @@ export class SubagentManager {
|
|||||||
private readonly activeExecutions = new Set<Execution>();
|
private readonly activeExecutions = new Set<Execution>();
|
||||||
private readonly queue: ScheduledTask[] = [];
|
private readonly queue: ScheduledTask[] = [];
|
||||||
private readonly waiters = new Map<string, Set<Waiter>>();
|
private readonly waiters = new Map<string, Set<Waiter>>();
|
||||||
|
/** A snapshot is rebuilt on the first read after a change, never on the change itself. */
|
||||||
|
private readonly snapshots = new WeakMap<Execution, JobSnapshot>();
|
||||||
|
/** The bounded run answer, built once at the terminal transition from its journal. */
|
||||||
|
private readonly runSummaries = new WeakMap<Execution, WorkflowRunSummary>();
|
||||||
private liveWorkers = 0;
|
private liveWorkers = 0;
|
||||||
private nextJobId = 1;
|
private nextJobId = 1;
|
||||||
private accepting = true;
|
private accepting = true;
|
||||||
@@ -75,7 +97,7 @@ export class SubagentManager {
|
|||||||
this.maxActiveJobs = options.maxActiveJobs ?? DEFAULT_MAX_ACTIVE_JOBS;
|
this.maxActiveJobs = options.maxActiveJobs ?? DEFAULT_MAX_ACTIVE_JOBS;
|
||||||
this.historyLimit = options.historyLimit ?? DEFAULT_HISTORY_LIMIT;
|
this.historyLimit = options.historyLimit ?? DEFAULT_HISTORY_LIMIT;
|
||||||
this.now = options.now ?? Date.now;
|
this.now = options.now ?? Date.now;
|
||||||
this.onJobChange = options.onJobChange;
|
this.onJobEvent = options.onJobEvent;
|
||||||
this.onJobActivity = options.onJobActivity;
|
this.onJobActivity = options.onJobActivity;
|
||||||
this.onWorkflowJournal = options.onWorkflowJournal;
|
this.onWorkflowJournal = options.onWorkflowJournal;
|
||||||
this.workflows = new WorkflowSupervisor(
|
this.workflows = new WorkflowSupervisor(
|
||||||
@@ -97,6 +119,7 @@ export class SubagentManager {
|
|||||||
const task = initialTask(prepared);
|
const task = initialTask(prepared);
|
||||||
execution.tasks.push(task);
|
execution.tasks.push(task);
|
||||||
execution.plannedTaskCount += 1;
|
execution.plannedTaskCount += 1;
|
||||||
|
this.snapshots.delete(execution);
|
||||||
return task;
|
return task;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -150,6 +173,44 @@ export class SubagentManager {
|
|||||||
return this.snapshot(this.requireJob(jobId));
|
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[] {
|
list(activeOnly = false): JobSnapshot[] {
|
||||||
return Array.from(this.jobs.values())
|
return Array.from(this.jobs.values())
|
||||||
.filter((job) => job.isAsync && (!activeOnly || !isTerminalJob(job.status)))
|
.filter((job) => job.isAsync && (!activeOnly || !isTerminalJob(job.status)))
|
||||||
@@ -157,15 +218,15 @@ export class SubagentManager {
|
|||||||
.map((job) => this.snapshot(job));
|
.map((job) => this.snapshot(job));
|
||||||
}
|
}
|
||||||
|
|
||||||
async wait(jobId: string, timeoutSeconds = DEFAULT_WAIT_SECONDS, signal?: AbortSignal): Promise<JobSnapshot> {
|
async wait(jobId: string, timeoutSeconds = DEFAULT_WAIT_SECONDS, signal?: AbortSignal): Promise<WaitResult> {
|
||||||
const execution = this.requireJob(jobId);
|
const execution = this.requireJob(jobId);
|
||||||
if (!Number.isFinite(timeoutSeconds) || timeoutSeconds <= 0 || timeoutSeconds > MAX_WAIT_SECONDS) {
|
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`);
|
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");
|
if (signal?.aborted) throw new Error("Wait aborted");
|
||||||
|
|
||||||
return new Promise<JobSnapshot>((resolve, reject) => {
|
return new Promise<WaitResult>((resolve, reject) => {
|
||||||
const waiters = this.waiters.get(jobId) ?? new Set<Waiter>();
|
const waiters = this.waiters.get(jobId) ?? new Set<Waiter>();
|
||||||
this.waiters.set(jobId, waiters);
|
this.waiters.set(jobId, waiters);
|
||||||
const waiter: Waiter = {
|
const waiter: Waiter = {
|
||||||
@@ -173,7 +234,7 @@ export class SubagentManager {
|
|||||||
reject,
|
reject,
|
||||||
timer: setTimeout(() => {
|
timer: setTimeout(() => {
|
||||||
waiters.delete(waiter);
|
waiters.delete(waiter);
|
||||||
waiter.resolve({ ...this.snapshot(execution), timedOut: true });
|
waiter.resolve(this.waitResult(execution, true));
|
||||||
}, timeoutSeconds * 1000),
|
}, timeoutSeconds * 1000),
|
||||||
};
|
};
|
||||||
const onAbort = () => {
|
const onAbort = () => {
|
||||||
@@ -182,10 +243,10 @@ export class SubagentManager {
|
|||||||
reject(new Error("Wait aborted"));
|
reject(new Error("Wait aborted"));
|
||||||
};
|
};
|
||||||
if (signal) signal.addEventListener("abort", onAbort, { once: true });
|
if (signal) signal.addEventListener("abort", onAbort, { once: true });
|
||||||
waiter.resolve = (snapshot) => {
|
waiter.resolve = (result) => {
|
||||||
clearTimeout(waiter.timer);
|
clearTimeout(waiter.timer);
|
||||||
if (signal) signal.removeEventListener("abort", onAbort);
|
if (signal) signal.removeEventListener("abort", onAbort);
|
||||||
resolve(snapshot);
|
resolve(result);
|
||||||
};
|
};
|
||||||
waiter.reject = (error) => {
|
waiter.reject = (error) => {
|
||||||
clearTimeout(waiter.timer);
|
clearTimeout(waiter.timer);
|
||||||
@@ -204,7 +265,7 @@ export class SubagentManager {
|
|||||||
const tasks: InternalTask[] = saved.results.map((result) => {
|
const tasks: InternalTask[] = saved.results.map((result) => {
|
||||||
// A persisted snapshot is the record: there is no AgentConfig to
|
// A persisted snapshot is the record: there is no AgentConfig to
|
||||||
// reconstruct, and restored rows are terminal so none is launched.
|
// 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")) {
|
if (interrupted && (task.snapshot.status === "queued" || task.snapshot.status === "running")) {
|
||||||
task.snapshot.status = "interrupted";
|
task.snapshot.status = "interrupted";
|
||||||
task.snapshot.finishedAt = this.now();
|
task.snapshot.finishedAt = this.now();
|
||||||
@@ -274,9 +335,9 @@ export class SubagentManager {
|
|||||||
}
|
}
|
||||||
for (const task of execution.tasks) task.controller?.abort();
|
for (const task of execution.tasks) task.controller?.abort();
|
||||||
this.activeExecutions.delete(execution);
|
this.activeExecutions.delete(execution);
|
||||||
this.emit(execution);
|
this.emit(execution, "finalized");
|
||||||
this.resolveWaiters(execution);
|
|
||||||
this.emitJournal(execution);
|
this.emitJournal(execution);
|
||||||
|
this.resolveWaiters(execution);
|
||||||
this.emitSync(execution);
|
this.emitSync(execution);
|
||||||
}
|
}
|
||||||
this.pruneHistory();
|
this.pruneHistory();
|
||||||
@@ -367,7 +428,10 @@ export class SubagentManager {
|
|||||||
this.activeExecutions.add(execution);
|
this.activeExecutions.add(execution);
|
||||||
if (isAsync) {
|
if (isAsync) {
|
||||||
this.jobs.set(id, execution);
|
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;
|
return execution;
|
||||||
}
|
}
|
||||||
@@ -458,11 +522,13 @@ export class SubagentManager {
|
|||||||
if (!prepared) throw new Error("Task has no prepared brief");
|
if (!prepared) throw new Error("Task has no prepared brief");
|
||||||
const result = await this.runner.run(prepared, execution.request.dispatchDefaults, {
|
const result = await this.runner.run(prepared, execution.request.dispatchDefaults, {
|
||||||
signal: controller.signal,
|
signal: controller.signal,
|
||||||
onUpdate: (partial) => {
|
onUpdate: ({ result: partial, message }) => {
|
||||||
partial.status = "running";
|
partial.status = "running";
|
||||||
if (execution.isAsync) {
|
if (execution.isAsync) {
|
||||||
|
if (message) task.messages.push(message);
|
||||||
this.updateSnapshotFromResult(task, partial);
|
this.updateSnapshotFromResult(task, partial);
|
||||||
this.emitActivity(execution);
|
this.snapshots.delete(execution);
|
||||||
|
if (message) this.emitActivity(execution, message);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
task.result = partial;
|
task.result = partial;
|
||||||
@@ -503,7 +569,6 @@ export class SubagentManager {
|
|||||||
task.snapshot.stopReason = result.stopReason;
|
task.snapshot.stopReason = result.stopReason;
|
||||||
task.snapshot.errorMessage = result.errorMessage;
|
task.snapshot.errorMessage = result.errorMessage;
|
||||||
task.snapshot.terminationSignal = result.terminationSignal;
|
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 {
|
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.result.status = task.snapshot.status;
|
||||||
task.snapshot.exitCode = result.exitCode;
|
task.snapshot.exitCode = result.exitCode;
|
||||||
this.updateSnapshotFromResult(task, result);
|
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();
|
task.snapshot.finishedAt = this.now();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -538,10 +612,12 @@ export class SubagentManager {
|
|||||||
execution.status = execution.cancelRequested && status !== "interrupted" ? "cancelled" : status;
|
execution.status = execution.cancelRequested && status !== "interrupted" ? "cancelled" : status;
|
||||||
execution.finishedAt = this.now();
|
execution.finishedAt = this.now();
|
||||||
this.activeExecutions.delete(execution);
|
this.activeExecutions.delete(execution);
|
||||||
this.emit(execution);
|
this.emit(execution, "finalized");
|
||||||
this.emitSync(execution);
|
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.emitJournal(execution);
|
||||||
|
this.resolveWaiters(execution);
|
||||||
this.pruneHistory();
|
this.pruneHistory();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -549,7 +625,7 @@ export class SubagentManager {
|
|||||||
const waiters = this.waiters.get(execution.id);
|
const waiters = this.waiters.get(execution.id);
|
||||||
if (!waiters) return;
|
if (!waiters) return;
|
||||||
this.waiters.delete(execution.id);
|
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 {
|
private requireJob(jobId: string): Execution {
|
||||||
@@ -559,36 +635,41 @@ export class SubagentManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private snapshot(execution: Execution): JobSnapshot {
|
private snapshot(execution: Execution): JobSnapshot {
|
||||||
return cloneSnapshot({
|
const cached = this.snapshots.get(execution);
|
||||||
|
if (cached) return cached;
|
||||||
|
const snapshot: JobSnapshot = {
|
||||||
id: execution.id,
|
id: execution.id,
|
||||||
mode: execution.request.mode,
|
mode: execution.request.mode,
|
||||||
agentScope: execution.request.agentScope,
|
agentScope: execution.request.agentScope,
|
||||||
projectAgentsDir: execution.request.projectAgentsDir,
|
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,
|
status: execution.status,
|
||||||
plannedTaskCount: execution.plannedTaskCount,
|
plannedTaskCount: execution.plannedTaskCount,
|
||||||
results: execution.tasks.map((task) => task.snapshot),
|
results: execution.tasks.map((task) => taskSnapshotView(task, this.now())),
|
||||||
usage: jobUsage(execution.tasks),
|
usage: jobUsage(execution.tasks),
|
||||||
createdAt: execution.createdAt,
|
createdAt: execution.createdAt,
|
||||||
startedAt: execution.startedAt,
|
startedAt: execution.startedAt,
|
||||||
finishedAt: execution.finishedAt,
|
finishedAt: execution.finishedAt,
|
||||||
errorMessage: execution.errorMessage,
|
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;
|
if (!execution.isAsync) return;
|
||||||
try {
|
try {
|
||||||
this.onJobActivity?.(this.snapshot(execution));
|
this.onJobActivity?.({ jobId: execution.id, message });
|
||||||
} catch {
|
} catch {
|
||||||
// Transient UI observers cannot interrupt scheduling.
|
// Transient UI observers cannot interrupt scheduling.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private emit(execution: Execution): void {
|
private emit(execution: Execution, kind: JobEventKind = "changed"): void {
|
||||||
if (!execution.isAsync) return;
|
if (!execution.isAsync) return;
|
||||||
|
this.snapshots.delete(execution);
|
||||||
try {
|
try {
|
||||||
this.onJobChange?.(this.snapshot(execution));
|
this.onJobEvent?.({ jobId: execution.id, kind });
|
||||||
} catch {
|
} catch {
|
||||||
// Persistence/UI observers cannot interrupt scheduling.
|
// Persistence/UI observers cannot interrupt scheduling.
|
||||||
}
|
}
|
||||||
@@ -603,9 +684,13 @@ export class SubagentManager {
|
|||||||
* missing one.
|
* missing one.
|
||||||
*/
|
*/
|
||||||
private emitJournal(execution: Execution): void {
|
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);
|
const journal = this.workflows.journal(execution);
|
||||||
if (!journal) return;
|
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 {
|
try {
|
||||||
this.onWorkflowJournal(journal);
|
this.onWorkflowJournal(journal);
|
||||||
} catch {
|
} catch {
|
||||||
|
|||||||
+13
-8
@@ -299,17 +299,22 @@ export class ProcessRunner implements TaskRunner {
|
|||||||
let abortRequested = false;
|
let abortRequested = false;
|
||||||
let killTimer: NodeJS.Timeout | undefined;
|
let killTimer: NodeJS.Timeout | undefined;
|
||||||
|
|
||||||
const notify = (): void => {
|
const notify = (message: Message): void => {
|
||||||
if (!options.onUpdate) return;
|
if (!options.onUpdate) return;
|
||||||
try {
|
try {
|
||||||
const tail = stderrTail.read();
|
const tail = stderrTail.read();
|
||||||
options.onUpdate({
|
options.onUpdate({
|
||||||
...result,
|
result: {
|
||||||
messages: [...result.messages],
|
...result,
|
||||||
usage: { ...result.usage },
|
// The live transcript is shared by reference; the appended
|
||||||
output: finalAssistantText(result.messages),
|
// message is also carried as the delta, so an observer never
|
||||||
stderr: tail.text,
|
// has to copy or scan the whole array.
|
||||||
stderrTruncated: tail.truncated,
|
usage: { ...result.usage },
|
||||||
|
output: finalAssistantText(result.messages),
|
||||||
|
stderr: tail.text,
|
||||||
|
stderrTruncated: tail.truncated,
|
||||||
|
},
|
||||||
|
message,
|
||||||
});
|
});
|
||||||
} catch {
|
} catch {
|
||||||
// An observer must not break the child run.
|
// 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.stopReason) result.stopReason = message.stopReason;
|
||||||
if (message.errorMessage) result.errorMessage = message.errorMessage;
|
if (message.errorMessage) result.errorMessage = message.errorMessage;
|
||||||
}
|
}
|
||||||
notify();
|
notify(message);
|
||||||
};
|
};
|
||||||
|
|
||||||
const onStdout = (chunk: Buffer): void => {
|
const onStdout = (chunk: Buffer): void => {
|
||||||
|
|||||||
+34
-4
@@ -71,9 +71,21 @@ export interface RunResult {
|
|||||||
status?: TaskStatus;
|
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 {
|
export interface RunOptions {
|
||||||
signal: AbortSignal;
|
signal: AbortSignal;
|
||||||
onUpdate?: (result: RunResult) => void;
|
onUpdate?: (update: RunUpdate) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface TaskRunner {
|
export interface TaskRunner {
|
||||||
@@ -111,14 +123,32 @@ export interface SyncRunOptions {
|
|||||||
onUpdate?: (outcome: SyncOutcome) => void;
|
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 {
|
export interface ManagerOptions {
|
||||||
maxWorkers?: number;
|
maxWorkers?: number;
|
||||||
maxActiveJobs?: number;
|
maxActiveJobs?: number;
|
||||||
historyLimit?: number;
|
historyLimit?: number;
|
||||||
now?: () => number;
|
now?: () => number;
|
||||||
onJobChange?: (snapshot: JobSnapshot) => void;
|
onJobEvent?: (event: JobEvent) => void;
|
||||||
/** Transient progress for open views. Unlike onJobChange, this is not persisted per message. */
|
/** Transient progress for open views; one event per appended message, never persisted. */
|
||||||
onJobActivity?: (snapshot: JobSnapshot) => void;
|
onJobActivity?: (event: JobActivityEvent) => void;
|
||||||
/** Called once per workflow run, when it reaches a terminal state. */
|
/** Called once per workflow run, when it reaches a terminal state. */
|
||||||
onWorkflowJournal?: (journal: WorkflowJournal) => void;
|
onWorkflowJournal?: (journal: WorkflowJournal) => void;
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -45,7 +45,7 @@ export function buildUltraGuidance(guideline: UltraGuideline, maxItemsPerEach: n
|
|||||||
"",
|
"",
|
||||||
`Size guideline: ${formatUltraGuideline(guideline)}. Hard caps: ${formatUltraCaps(maxItemsPerEach)}.`,
|
`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");
|
].join("\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+15
-34
@@ -9,8 +9,8 @@
|
|||||||
* child's output or reads a task snapshot again.
|
* child's output or reads a task snapshot again.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "./output.ts";
|
import { formatWorkflowRunSummary, summarizeWorkflowRun } from "./journal.ts";
|
||||||
import type { JobStatus, WorkflowJournal, WorkflowJournalStep } from "./types.ts";
|
import type { JobStatus, WorkflowJournal } from "./types.ts";
|
||||||
|
|
||||||
export const ULTRA_DONE_MESSAGE_TYPE = "pi-subagent-ultra-done";
|
export const ULTRA_DONE_MESSAGE_TYPE = "pi-subagent-ultra-done";
|
||||||
|
|
||||||
@@ -36,50 +36,31 @@ export interface UltraNotice {
|
|||||||
details: UltraNoticeDetails;
|
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
|
* The notice for one terminal run, or undefined when notices are off or the
|
||||||
* run came from a workflow file.
|
* run came from a workflow file.
|
||||||
*
|
*
|
||||||
* A run with no succeeded step reports its status and error only: there is no
|
* The payload is the run's consolidated summary — the same bounded bytes
|
||||||
* partial output to present as the consolidated answer. Runs started through
|
* `subagent_jobs wait` returns for that journal. A run with no succeeded step
|
||||||
* `subagent_async` or a workflow file are not inline-sourced and stay
|
* reports its status and error only: there is no partial output to present as
|
||||||
* pull-based.
|
* 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 {
|
export function buildUltraNotice(journal: WorkflowJournal, options: UltraNotifyOptions): UltraNotice | undefined {
|
||||||
if (!options.ultraEnabled || !options.notifyEnabled) return undefined;
|
if (!options.ultraEnabled || !options.notifyEnabled) return undefined;
|
||||||
if (journal.plan.source !== "inline") return undefined;
|
if (journal.plan.source !== "inline") return undefined;
|
||||||
|
|
||||||
const step = lastSucceededStep(journal.steps);
|
const summary = summarizeWorkflowRun(journal);
|
||||||
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 details: UltraNoticeDetails = {
|
const details: UltraNoticeDetails = {
|
||||||
jobId: journal.jobId,
|
jobId: journal.jobId,
|
||||||
status: journal.status,
|
status: journal.status,
|
||||||
planName: journal.plan.name,
|
planName: journal.plan.name,
|
||||||
};
|
};
|
||||||
if (step) details.stepId = step.id;
|
if (summary.answer) details.stepId = summary.answer.stepId;
|
||||||
return { customType: ULTRA_DONE_MESSAGE_TYPE, content: lines.join("\n"), display: true, details };
|
return {
|
||||||
|
customType: ULTRA_DONE_MESSAGE_TYPE,
|
||||||
|
content: formatWorkflowRunSummary(summary),
|
||||||
|
display: true,
|
||||||
|
details,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
+13
-9
@@ -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}`));
|
assert.match(component.render(120).join("\n"), new RegExp(`> ${jobId}`));
|
||||||
const rendersBeforeProgress = h.getCustomRenders();
|
const rendersBeforeProgress = h.getCustomRenders();
|
||||||
const pending = h.runner.calls[0];
|
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?.({
|
pending.options.onUpdate?.({
|
||||||
...makeResult(pending.task, "live output"),
|
result: {
|
||||||
status: "running",
|
...makeResult(pending.task, "live output"),
|
||||||
exitCode: null,
|
status: "running",
|
||||||
messages: [{
|
exitCode: null,
|
||||||
role: "assistant",
|
messages: [message],
|
||||||
content: [{ type: "toolCall", id: "call-1", name: "bash", arguments: { command: "npm test" } }],
|
},
|
||||||
timestamp: 100,
|
message,
|
||||||
}] as unknown as Message[],
|
|
||||||
});
|
});
|
||||||
assert.ok(h.getCustomRenders() > rendersBeforeProgress);
|
assert.ok(h.getCustomRenders() > rendersBeforeProgress);
|
||||||
assert.match(component.render(120).join("\n"), /\$ npm test/);
|
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,
|
undefined,
|
||||||
h.ctx,
|
h.ctx,
|
||||||
);
|
);
|
||||||
assert.equal((waited.details as any).job.status, "succeeded");
|
assert.equal((waited.details as any).run.status, "succeeded");
|
||||||
} finally {
|
} finally {
|
||||||
await h.events.get("session_shutdown")?.({ type: "session_shutdown" }, h.ctx);
|
await h.events.get("session_shutdown")?.({ type: "session_shutdown" }, h.ctx);
|
||||||
await fs.promises.rm(h.cwd, { recursive: true, force: true });
|
await fs.promises.rm(h.cwd, { recursive: true, force: true });
|
||||||
|
|||||||
+19
-1
@@ -1,5 +1,7 @@
|
|||||||
import type { AgentConfig } from "../src/agents.ts";
|
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 = {
|
export const agent: AgentConfig = {
|
||||||
name: "scout",
|
name: "scout",
|
||||||
@@ -83,3 +85,19 @@ export class FakeRunner implements TaskRunner {
|
|||||||
pending.resolve({ ...result(pending.task, output), ...overrides });
|
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<JobSnapshot> {
|
||||||
|
const result = await manager.wait(jobId, timeoutSeconds);
|
||||||
|
if (!isRunWait(result)) return result;
|
||||||
|
const snapshot = manager.get(jobId);
|
||||||
|
return result.timedOut ? { ...snapshot, timedOut: true } : snapshot;
|
||||||
|
}
|
||||||
+43
-32
@@ -2,8 +2,8 @@ import assert from "node:assert/strict";
|
|||||||
import test from "node:test";
|
import test from "node:test";
|
||||||
import type { Message } from "@earendil-works/pi-ai";
|
import type { Message } from "@earendil-works/pi-ai";
|
||||||
import { SubagentManager } from "../src/manager.ts";
|
import { SubagentManager } from "../src/manager.ts";
|
||||||
import type { JobSnapshot } from "../src/types.ts";
|
import type { JobActivityEvent, JobEvent, JobSnapshot } from "../src/types.ts";
|
||||||
import { FakeRunner, invocation, result as makeResult } from "./helpers.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 () => {
|
test("async single returns an ID before completion and later exposes its result", async () => {
|
||||||
const runner = new FakeRunner();
|
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);
|
assert.equal(runner.calls.length, 1);
|
||||||
|
|
||||||
runner.complete("task 1", "finished");
|
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.status, "succeeded");
|
||||||
assert.equal(terminal.results.length, 1);
|
assert.equal(terminal.results.length, 1);
|
||||||
assert.equal(terminal.results[0].output, "finished");
|
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 () => {
|
test("async progress exposes bounded activity without persisting every message", async () => {
|
||||||
const persisted: JobSnapshot[] = [];
|
const persisted: JobSnapshot[] = [];
|
||||||
const progress: JobSnapshot[] = [];
|
const events: JobEvent[] = [];
|
||||||
|
const progress: JobActivityEvent[] = [];
|
||||||
const runner = new FakeRunner();
|
const runner = new FakeRunner();
|
||||||
const manager = new SubagentManager(runner, {
|
const manager = new SubagentManager(runner, {
|
||||||
onJobChange: (job) => persisted.push(job),
|
onJobEvent: (event) => {
|
||||||
onJobActivity: (job) => progress.push(job),
|
events.push(event);
|
||||||
|
if (event.kind !== "changed") persisted.push(manager.get(event.jobId));
|
||||||
|
},
|
||||||
|
onJobActivity: (event) => progress.push(event),
|
||||||
});
|
});
|
||||||
const job = manager.startAsync(invocation());
|
const job = manager.startAsync(invocation());
|
||||||
const persistedBeforeProgress = persisted.length;
|
const persistedBeforeProgress = persisted.length;
|
||||||
const pending = runner.calls[0];
|
const pending = runner.calls[0];
|
||||||
const messages = [{
|
const message = {
|
||||||
role: "assistant",
|
role: "assistant",
|
||||||
content: [{ type: "toolCall", id: "call-1", name: "bash", arguments: { command: "npm test" } }],
|
content: [{ type: "toolCall", id: "call-1", name: "bash", arguments: { command: "npm test" } }],
|
||||||
timestamp: 100,
|
timestamp: 100,
|
||||||
}] as unknown as Message[];
|
} as unknown as Message;
|
||||||
|
|
||||||
pending.options.onUpdate?.({
|
pending.options.onUpdate?.({
|
||||||
...makeResult(pending.task, "working"),
|
result: {
|
||||||
status: "running",
|
...makeResult(pending.task, "working"),
|
||||||
exitCode: null,
|
status: "running",
|
||||||
messages,
|
exitCode: null,
|
||||||
|
messages: [message],
|
||||||
|
},
|
||||||
|
message,
|
||||||
});
|
});
|
||||||
|
|
||||||
const current = manager.get(job.id);
|
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 },
|
{ kind: "toolCall", summary: "$ npm test", timestamp: 100 },
|
||||||
]);
|
]);
|
||||||
assert.equal(progress.length, 1);
|
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");
|
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.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");
|
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);
|
assert.equal(runner.calls.length, 2);
|
||||||
|
|
||||||
runner.complete("task 2", "good");
|
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.equal(terminal.status, "failed");
|
||||||
assert.deepEqual(terminal.results.map((result) => result.status), ["failed", "succeeded"]);
|
assert.deepEqual(terminal.results.map((result) => result.status), ["failed", "succeeded"]);
|
||||||
assert.equal(terminal.results[0].errorMessage, "boom");
|
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");
|
assert.equal(runner.calls[1].task.task, "review first output");
|
||||||
|
|
||||||
runner.complete("review first output", "second 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.equal(terminal.status, "succeeded");
|
||||||
assert.deepEqual(terminal.results.map((result) => result.step), [1, 2]);
|
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(cancelling.results.map((result) => result.status), ["running", "cancelled"]);
|
||||||
assert.deepEqual(runner.aborted, ["task 1"]);
|
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.equal(terminal.status, "cancelled");
|
||||||
assert.deepEqual(terminal.results.map((result) => result.status), ["cancelled", "cancelled"]);
|
assert.deepEqual(terminal.results.map((result) => result.status), ["cancelled", "cancelled"]);
|
||||||
assert.equal(runner.calls.length, 1);
|
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));
|
await new Promise((resolve) => setImmediate(resolve));
|
||||||
assert.equal(runner.calls.length, 17);
|
assert.equal(runner.calls.length, 17);
|
||||||
runner.complete("task 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 () => {
|
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");
|
runner.complete("task 1", "async done");
|
||||||
await new Promise((resolve) => setImmediate(resolve));
|
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);
|
assert.equal(runner.calls.length, 2);
|
||||||
|
|
||||||
runner.complete("task 1", "sync done");
|
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 manager = new SubagentManager(runner);
|
||||||
const job = manager.startAsync(invocation());
|
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.status, "running");
|
||||||
assert.equal(timedOut.timedOut, true);
|
assert.equal(timedOut.timedOut, true);
|
||||||
assert.equal(manager.get(job.id).status, "running");
|
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);
|
assert.equal(runner.aborted.length, 0);
|
||||||
|
|
||||||
runner.complete("task 1");
|
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 () => {
|
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());
|
const next = manager.startAsync(invocation());
|
||||||
assert.equal(next.status, "running");
|
assert.equal(next.status, "running");
|
||||||
runner.complete("task 1");
|
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 () => {
|
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);
|
const output = "🙂ab".repeat(20000);
|
||||||
|
|
||||||
runner.complete("task 1", output);
|
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];
|
const snapshot = terminal.results[0];
|
||||||
assert.equal(snapshot.outputTruncated, true);
|
assert.equal(snapshot.outputTruncated, true);
|
||||||
assert.ok(Buffer.byteLength(snapshot.output, "utf8") <= 50 * 1024);
|
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/);
|
assert.throws(() => manager.startAsync(invocation()), /Too many active async jobs/);
|
||||||
|
|
||||||
runner.complete("task 1", "first");
|
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());
|
const second = manager.startAsync(invocation());
|
||||||
assert.equal(manager.get(first.id).status, "succeeded");
|
assert.equal(manager.get(first.id).status, "succeeded");
|
||||||
runner.complete("task 1", "second");
|
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.throws(() => manager.get(first.id), /Unknown or evicted/);
|
||||||
assert.equal(manager.get(second.id).results[0].output, "second");
|
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 manager = new SubagentManager(runner);
|
||||||
const job = manager.startAsync(invocation("chain"));
|
const job = manager.startAsync(invocation("chain"));
|
||||||
runner.complete("task 1", "bad", { exitCode: 1, errorMessage: "failed step" });
|
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.status, "failed");
|
||||||
assert.equal(terminal.results.length, 1);
|
assert.equal(terminal.results.length, 1);
|
||||||
assert.equal(runner.calls.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());
|
const job = manager.startAsync(invocation());
|
||||||
manager.cancel(job.id);
|
manager.cancel(job.id);
|
||||||
runner.complete("task 1", "too late", { exitCode: 0, stopReason: "stop" });
|
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.status, "cancelled");
|
||||||
assert.equal(terminal.results[0].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"));
|
const job = manager.startAsync(invocation("chain"));
|
||||||
manager.cancel(job.id);
|
manager.cancel(job.id);
|
||||||
runner.complete("task 1", "late success", { exitCode: 0, stopReason: "stop" });
|
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(terminal.status, "cancelled");
|
||||||
assert.equal(runner.calls.length, 1);
|
assert.equal(runner.calls.length, 1);
|
||||||
assert.equal(terminal.results.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 manager = new SubagentManager(runner);
|
||||||
const finished = manager.startAsync(invocation());
|
const finished = manager.startAsync(invocation());
|
||||||
runner.complete("task 1", "old branch");
|
runner.complete("task 1", "old branch");
|
||||||
await manager.wait(finished.id, 1);
|
await waitForSnapshot(manager, finished.id, 1);
|
||||||
const active = manager.startAsync(invocation());
|
const active = manager.startAsync(invocation());
|
||||||
|
|
||||||
manager.replaceHistory([]);
|
manager.replaceHistory([]);
|
||||||
assert.throws(() => manager.get(finished.id), /Unknown or evicted/);
|
assert.throws(() => manager.get(finished.id), /Unknown or evicted/);
|
||||||
assert.equal(manager.get(active.id).status, "running");
|
assert.equal(manager.get(active.id).status, "running");
|
||||||
runner.complete("task 1", "active");
|
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 () => {
|
test("observer failures cannot strand jobs or workers", async () => {
|
||||||
const runner = new FakeRunner();
|
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());
|
const job = manager.startAsync(invocation());
|
||||||
runner.complete("task 1");
|
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"); } });
|
const sync = manager.runSync(invocation(), { onUpdate: () => { throw new Error("observer"); } });
|
||||||
await new Promise((resolve) => setImmediate(resolve));
|
await new Promise((resolve) => setImmediate(resolve));
|
||||||
|
|||||||
+7
-4
@@ -6,7 +6,7 @@ import test from "node:test";
|
|||||||
import { fileURLToPath } from "node:url";
|
import { fileURLToPath } from "node:url";
|
||||||
import type { AgentConfig } from "../src/agents.ts";
|
import type { AgentConfig } from "../src/agents.ts";
|
||||||
import { ProcessRunner, type ProcessRunnerOptions } from "../src/runner.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 fixturePath = fileURLToPath(new URL("./fixtures/fake-pi.mjs", import.meta.url));
|
||||||
const stderrLimit = 64 * 1024;
|
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) => {
|
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 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.exitCode, 0);
|
||||||
assert.equal(result.terminationSignal, undefined);
|
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.ok(updates.length > 0);
|
||||||
assert.equal(
|
assert.equal(
|
||||||
updates.some((partial) => partial.messages.some((message) => message.role === "toolResult")),
|
updates.some((update) => update.message?.role === "toolResult"),
|
||||||
true,
|
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}`);
|
t.diagnostic(`onUpdate calls: ${updates.length}`);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -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\)/,
|
/Size guideline: medium \(aim for fewer than 10 children\)/,
|
||||||
/Hard caps: ≤ 64 steps, ≤ 32 items per each-step, ≤ 256 children per run/,
|
/Hard caps: ≤ 64 steps, ≤ 32 items per each-step, ≤ 256 children per run/,
|
||||||
/wait for it with `subagent_jobs/,
|
/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);
|
assert.match(guidance, expected);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -128,7 +128,8 @@ async function waitFor(h: Awaited<ReturnType<typeof harness>>, jobId: string) {
|
|||||||
undefined,
|
undefined,
|
||||||
h.ctx,
|
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<void>): Promise<void> {
|
async function withEnv(name: string, value: string, run: () => Promise<void>): Promise<void> {
|
||||||
@@ -206,7 +207,7 @@ test("an inline run sends one notice at terminal state with the consolidated ans
|
|||||||
planName: "notice-plan",
|
planName: "notice-plan",
|
||||||
stepId: "merge",
|
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, /Last succeeded step: merge\./);
|
||||||
assert.match(message.content, /the consolidated answer/);
|
assert.match(message.content, /the consolidated answer/);
|
||||||
assert.doesNotMatch(message.content, /src\/a\.ts/);
|
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 () => {
|
test("file-sourced workflow runs never notify", async () => {
|
||||||
const h = await harness();
|
const h = await harness();
|
||||||
try {
|
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(failedJob.status, "failed");
|
||||||
|
|
||||||
assert.equal(h.messages.length, 1);
|
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.match(h.messages[0].message.content, /No step succeeded\./);
|
||||||
assert.doesNotMatch(h.messages[0].message.content, /partial findings/);
|
assert.doesNotMatch(h.messages[0].message.content, /partial findings/);
|
||||||
assert.equal(h.messages[0].message.details?.stepId, undefined);
|
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(cancelledJob.status, "cancelled");
|
||||||
|
|
||||||
assert.equal(h.messages.length, 2);
|
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.match(h.messages[1].message.content, /No step succeeded\./);
|
||||||
assert.equal(h.messages[1].message.details?.stepId, undefined);
|
assert.equal(h.messages[1].message.details?.stepId, undefined);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -334,7 +408,7 @@ test("buildUltraNotice carries the last succeeded step in journal order and the
|
|||||||
);
|
);
|
||||||
assert.ok(noticed);
|
assert.ok(noticed);
|
||||||
assert.equal(noticed.details.stepId, "audit");
|
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.match(noticed.content, /audit output/);
|
||||||
assert.doesNotMatch(noticed.content, /partial merge/);
|
assert.doesNotMatch(noticed.content, /partial merge/);
|
||||||
assert.doesNotMatch(noticed.content, /scan output/);
|
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",
|
role: "custom",
|
||||||
customType: ULTRA_DONE_MESSAGE_TYPE,
|
customType: ULTRA_DONE_MESSAGE_TYPE,
|
||||||
content: "Ultra run job_0042 succeeded — plan \"audit\".",
|
content: "Run job_0042 succeeded — plan \"audit\".",
|
||||||
display: true,
|
display: true,
|
||||||
details: { jobId: "job_0042", status: "succeeded", planName: "audit" },
|
details: { jobId: "job_0042", status: "succeeded", planName: "audit" },
|
||||||
timestamp: 0,
|
timestamp: 0,
|
||||||
|
|||||||
+2
-2
@@ -471,7 +471,7 @@ test("an inline-sourced run journals source inline and round-trips through the j
|
|||||||
undefined,
|
undefined,
|
||||||
h.ctx,
|
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);
|
const journals = extractWorkflowJournals(h.entries);
|
||||||
assert.equal(journals.length, 1);
|
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, /`ultra` tool/);
|
||||||
assert.match(guidance, /Size guideline: medium \(aim for fewer than 10 children\)/);
|
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, /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();
|
const second = promptEvent();
|
||||||
await h.events.get("before_agent_start")!(second, h.ctx);
|
await h.events.get("before_agent_start")!(second, h.ctx);
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ import {
|
|||||||
import { prepareWorkflowInvocation, type PrepareContext } from "../src/prepare.ts";
|
import { prepareWorkflowInvocation, type PrepareContext } from "../src/prepare.ts";
|
||||||
import { parseWorkflow, type WorkflowPlan, type WorkflowSource } from "../src/workflow-plan.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 { 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[] = [];
|
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. */
|
/** One row of a run's DAG index: the shared record the journal projects. */
|
||||||
function taskRow(stepId: string, status: TaskStatus, output = "", extra: Partial<TaskSnapshot> = {}): InternalTask {
|
function taskRow(stepId: string, status: TaskStatus, output = "", extra: Partial<TaskSnapshot> = {}): InternalTask {
|
||||||
return {
|
return {
|
||||||
|
messages: [],
|
||||||
snapshot: {
|
snapshot: {
|
||||||
agent: "scout",
|
agent: "scout",
|
||||||
agentSource: "user",
|
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");
|
completeStep(runner, "scan", "src/a.ts");
|
||||||
await tick();
|
await tick();
|
||||||
completeStep(runner, "audit", "no findings");
|
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(terminal.status, "succeeded");
|
||||||
assert.equal(journals.length, 1);
|
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 jobs: JobSnapshot[] = [];
|
||||||
const manager = new SubagentManager(runner, {
|
const manager = new SubagentManager(runner, {
|
||||||
maxWorkers: 2,
|
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),
|
onWorkflowJournal: (journal) => journals.push(journal),
|
||||||
});
|
});
|
||||||
const started = manager.startWorkflow(
|
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`);
|
completeStep(runner, "scan", `${output} sources`);
|
||||||
await tick();
|
await tick();
|
||||||
completeStep(runner, "audit", output);
|
completeStep(runner, "audit", output);
|
||||||
await manager.wait(started.id, 1);
|
await waitForSnapshot(manager, started.id, 1);
|
||||||
assert.equal(journals.length, 1);
|
assert.equal(journals.length, 1);
|
||||||
return journals[0];
|
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" });
|
completeStep(runner, "scan", "partial", { exitCode: 1, errorMessage: "scan exploded" });
|
||||||
await tick();
|
await tick();
|
||||||
completeStep(runner, "notify", "sent");
|
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.length, 1);
|
||||||
assert.equal(journals[0].status, "failed");
|
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);
|
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.length, 1);
|
||||||
assert.equal(journals[0].status, "cancelled");
|
assert.equal(journals[0].status, "cancelled");
|
||||||
assert.deepEqual(
|
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 journals: WorkflowJournal[] = [];
|
||||||
const jobs: JobSnapshot[] = [];
|
const jobs: JobSnapshot[] = [];
|
||||||
const manager = new SubagentManager(runner, {
|
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),
|
onWorkflowJournal: (journal) => journals.push(journal),
|
||||||
});
|
});
|
||||||
const started = manager.startWorkflow(
|
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();
|
await tick();
|
||||||
runner.complete("audit src/a.ts", "ok a");
|
runner.complete("audit src/a.ts", "ok a");
|
||||||
runner.complete("audit src/b.ts", "bad b", { exitCode: 1, errorMessage: "b exploded" });
|
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);
|
assert.equal(journals.length, 1);
|
||||||
return { journal: journals[0], job: jobs.at(-1)! };
|
return { journal: journals[0], job: jobs.at(-1)! };
|
||||||
}
|
}
|
||||||
|
|||||||
+16
-16
@@ -6,7 +6,7 @@ import test, { after } from "node:test";
|
|||||||
import { SubagentManager } from "../src/manager.ts";
|
import { SubagentManager } from "../src/manager.ts";
|
||||||
import { prepareWorkflowInvocation, type PrepareContext } from "../src/prepare.ts";
|
import { prepareWorkflowInvocation, type PrepareContext } from "../src/prepare.ts";
|
||||||
import { parseWorkflow, WorkflowValidationError, type WorkflowPlan } from "../src/workflow-plan.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[] = [];
|
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, "notify", "sent");
|
||||||
completeStep(runner, "merge", "ranked");
|
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.equal(terminal.status, "succeeded");
|
||||||
assert.deepEqual(terminal.results.map((result) => result.stepId), ["scan", "audit", "merge", "notify"]);
|
assert.deepEqual(terminal.results.map((result) => result.stepId), ["scan", "audit", "merge", "notify"]);
|
||||||
assert.deepEqual(terminal.results.map((result) => result.status), ["succeeded", "succeeded", "succeeded", "succeeded"]);
|
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");
|
assert.equal(pending(runner, "publish").task.task, "publish ready");
|
||||||
completeStep(runner, "publish", "published");
|
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.equal(terminal.status, "failed");
|
||||||
assert.deepEqual(
|
assert.deepEqual(
|
||||||
terminal.results.map((result) => [result.stepId, result.status]),
|
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);
|
assert.equal(runner.calls.length, 4);
|
||||||
completeStep(runner, "c");
|
completeStep(runner, "c");
|
||||||
completeStep(runner, "d");
|
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 () => {
|
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.equal(terminal.status, "cancelled");
|
||||||
assert.deepEqual(
|
assert.deepEqual(
|
||||||
terminal.results.map((result) => [result.stepId, result.status]),
|
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);
|
assert.equal(restoredRunner.calls.length, 0);
|
||||||
manager.cancel(started.id);
|
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 () => {
|
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));
|
await new Promise((resolve) => setImmediate(resolve));
|
||||||
assert.equal(pending(runner, "merge").task.task, "merge files + findings");
|
assert.equal(pending(runner, "merge").task.task, "merge files + findings");
|
||||||
completeStep(runner, "merge", "ranked");
|
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<void> {
|
async function settleScheduler(): Promise<void> {
|
||||||
@@ -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/);
|
assert.match(pending(runner, "merge").task.task, /### a\.ts\n\nok a/);
|
||||||
|
|
||||||
completeStep(runner, "merge", "ranked");
|
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.equal(terminal.status, "succeeded");
|
||||||
assert.deepEqual(terminal.results.filter((result) => result.stepId === "audit").map((result) => result.status), [
|
assert.deepEqual(terminal.results.filter((result) => result.stepId === "audit").map((result) => result.status), [
|
||||||
"succeeded",
|
"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");
|
const report = pending(runner, "report");
|
||||||
assert.match(report.task.task, /### b\.ts/);
|
assert.match(report.task.task, /### b\.ts/);
|
||||||
runner.complete(report.task.task, "reported");
|
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.status, "failed");
|
||||||
assert.equal(terminal.results.find((result) => result.stepId === "report")?.status, "succeeded");
|
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");
|
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.match(audit.errorMessage ?? "", /All 2 items failed/);
|
||||||
assert.equal(runner.calls.some((call) => call.task.stepId === "report"), false);
|
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.equal(terminal.status, "failed");
|
||||||
assert.deepEqual(
|
assert.deepEqual(
|
||||||
terminal.results.map((result) => [result.stepId, result.item ?? null, result.status]),
|
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.match(audit.errorMessage ?? "", /source produced no items/i);
|
||||||
assert.equal(runner.calls.some((call) => call.task.stepId === "audit"), false);
|
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.status, "failed");
|
||||||
assert.equal(terminal.results.find((result) => result.stepId === "report")?.status, "skipped");
|
assert.equal(terminal.results.find((result) => result.stepId === "report")?.status, "skipped");
|
||||||
assert.equal(terminal.results.every((result) => result.finishedAt !== undefined), true);
|
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.equal(stepRow(manager, started.id, "audit").status, "running");
|
||||||
assert.deepEqual(itemRows(manager, started.id, "audit").map((row) => row.status), ["succeeded", "running", "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);
|
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.status, "running");
|
||||||
assert.equal(timedOut.timedOut, true);
|
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");
|
runner.complete("audit c.ts", "good c");
|
||||||
await settleScheduler();
|
await settleScheduler();
|
||||||
completeStep(runner, "report", "reported");
|
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.status, "succeeded");
|
||||||
assert.equal(terminal.results.every((result) => ["succeeded", "failed", "skipped", "cancelled", "interrupted"].includes(result.status)), true);
|
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);
|
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"]);
|
assert.deepEqual(itemRows(manager, started.id, "audit").map((row) => row.status), ["running", "running", "queued", "queued"]);
|
||||||
|
|
||||||
manager.cancel(started.id);
|
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.status, "cancelled");
|
||||||
assert.equal(terminal.results.find((result) => result.stepId === "scan")?.status, "succeeded");
|
assert.equal(terminal.results.find((result) => result.stepId === "scan")?.status, "succeeded");
|
||||||
assert.equal(
|
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 ?? "", /has 33 items/);
|
||||||
assert.match(audit.errorMessage ?? "", /max is 32 per each-step/);
|
assert.match(audit.errorMessage ?? "", /max is 32 per each-step/);
|
||||||
assert.equal(runner.calls.some((call) => call.task.stepId === "audit"), false);
|
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 () => {
|
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(runner.calls.some((call) => call.task.stepId === "audit_7"), false);
|
||||||
assert.equal(manager.get(started.id).status, "running");
|
assert.equal(manager.get(started.id).status, "running");
|
||||||
manager.cancel(started.id);
|
manager.cancel(started.id);
|
||||||
assert.equal((await manager.wait(started.id, 1)).status, "cancelled");
|
assert.equal((await waitForSnapshot(manager, started.id, 1)).status, "cancelled");
|
||||||
});
|
});
|
||||||
Reference in new issue
Block a user