From 621f6e2579da755c53d8a29672fccdcbc0daffc2 Mon Sep 17 00:00:00 2001 From: alex Date: Tue, 1 Dec 2026 11:09:26 +0000 Subject: [PATCH] Make the workflow supervisor host seam real Move Execution, InternalTask, and the status predicates into job-state.ts; the supervisor now creates, schedules, and settles shared rows only through its host. Concentrate cancellation and shutdown settlement in one supervisor policy, make restored rows honest (no fabricated AgentConfig), and thread load-time cap limits through WorkflowRunSpec so release enforcement and the review card share one value. Agent discovery is memoized per cwd within a prepare call. --- src/config.ts | 21 +++ src/dashboard.ts | 3 +- src/index.ts | 37 +++-- src/job-state.ts | 217 +++++++++++++++++++++++++++++ src/journal.ts | 55 +------- src/manager.ts | 162 +++++++++------------- src/persistence.ts | 3 +- src/prepare.ts | 37 +++-- src/render.ts | 18 +-- src/runner.ts | 17 +-- src/types.ts | 115 +++++++-------- src/ultra-notify.ts | 3 +- src/ultra.ts | 16 +-- src/workflow-plan.ts | 15 +- src/workflow-run.ts | 4 +- src/workflow-supervisor.ts | 254 +++++++++++++++++++++------------- test/concurrency.test.ts | 3 +- test/render.test.ts | 2 +- test/ultra-notify.test.ts | 2 +- test/workflow-journal.test.ts | 4 +- test/workflows.test.ts | 31 ++--- 21 files changed, 610 insertions(+), 409 deletions(-) create mode 100644 src/job-state.ts diff --git a/src/config.ts b/src/config.ts index cf7a247..38db264 100644 --- a/src/config.ts +++ b/src/config.ts @@ -116,3 +116,24 @@ export function readUltraGuideline(value: string | undefined): { value: UltraGui warning: `Invalid PI_SUBAGENT_ULTRA_GUIDELINE="${value}"; using ${DEFAULT_ULTRA_GUIDELINE}.`, }; } + +/** Every load-time setting, read from the process environment exactly once. */ +export function readEnvironmentConfig(env: NodeJS.ProcessEnv = process.env) { + return { + maxWorkers: readMaxWorkers(env.PI_SUBAGENT_MAX_WORKERS), + workflowItems: readMaxWorkflowItems(env.PI_SUBAGENT_WORKFLOW_MAX_ITEMS), + ultra: readUltraEnabled(env.PI_SUBAGENT_ULTRA), + ultraNotify: readUltraNotify(env.PI_SUBAGENT_ULTRA_NOTIFY), + ultraMode: readUltraMode(env.PI_SUBAGENT_ULTRACODE), + ultraGuideline: readUltraGuideline(env.PI_SUBAGENT_ULTRA_GUIDELINE), + ultraKeyword: readUltraKeyword(env.PI_SUBAGENT_ULTRA_KEYWORD), + }; +} + +/** + * The parent environment a child process inherits when the caller does not + * override it. Kept here so no execution module reads `process.env` itself. + */ +export function inheritedEnvironment(): NodeJS.ProcessEnv { + return process.env; +} diff --git a/src/dashboard.ts b/src/dashboard.ts index a72fa45..6fc191b 100644 --- a/src/dashboard.ts +++ b/src/dashboard.ts @@ -8,7 +8,8 @@ import { wrapTextWithAnsi, } from "@earendil-works/pi-tui"; import { formatUsageStats, type SubagentRenderTheme } from "./render.ts"; -import { isTerminalTask, type JobSnapshot, type JobStatus, type TaskSnapshot, type TaskStatus } from "./types.ts"; +import { isTerminalTask } from "./job-state.ts"; +import type { JobSnapshot, JobStatus, TaskSnapshot, TaskStatus } from "./types.ts"; const JOB_PAGE_SIZE = 4; const TASK_PAGE_SIZE = 4; diff --git a/src/index.ts b/src/index.ts index 43d05ba..41c7f68 100644 --- a/src/index.ts +++ b/src/index.ts @@ -14,24 +14,16 @@ import { getAgentDir, } from "@earendil-works/pi-coding-agent"; import { Text } from "@earendil-works/pi-tui"; -import { - readMaxWorkers, - readMaxWorkflowItems, - readUltraEnabled, - readUltraGuideline, - readUltraKeyword, - readUltraMode, - readUltraNotify, -} from "./config.ts"; +import { readEnvironmentConfig } from "./config.ts"; import { SubagentDashboard } from "./dashboard.ts"; import { formatJob, formatJobList } from "./job-format.ts"; import { SubagentManager } from "./manager.ts"; import { extractJobSnapshots, extractWorkflowJournals, persistedJob, persistedWorkflowJournal, SUBAGENT_JOB_ENTRY, WORKFLOW_RUN_ENTRY } from "./persistence.ts"; import { InvalidInvocationError, prepareInvocation, prepareWorkflowInvocation, type PrepareContext } from "./prepare.ts"; +import { isFailedResult } from "./job-state.ts"; import { formatParallelSummary, getResultOutput, - isFailedResult, isRunningResult, renderSubagentCall, renderSubagentResult, @@ -52,7 +44,7 @@ import { UltraKeywordTrigger } from "./ultra-keyword.ts"; import { formatUltraReviewCard, formatUltraStart, UltraDeclinedError } from "./ultra.ts"; import { buildUltraNotice, ULTRA_DONE_MESSAGE_TYPE, type UltraNoticeDetails } from "./ultra-notify.ts"; import { formatWorkflowStart, parseWorkflowCommand } from "./workflow-command.ts"; -import { loadWorkflow, parseInlineWorkflow } from "./workflow-plan.ts"; +import { loadWorkflow, MAX_EXPANDED_CHILDREN, parseInlineWorkflow } from "./workflow-plan.ts"; import type { WorkflowStartResult } from "./workflow-run.ts"; function textResult(text: string, details?: unknown, isError?: boolean): AgentToolResult { @@ -123,13 +115,18 @@ function jobResult(job: JobSnapshot): AgentToolResult<{ job: JobSnapshot }> { } export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) { - const workerConfig = readMaxWorkers(process.env.PI_SUBAGENT_MAX_WORKERS); - const workflowItemsConfig = readMaxWorkflowItems(process.env.PI_SUBAGENT_WORKFLOW_MAX_ITEMS); - const ultraConfig = readUltraEnabled(process.env.PI_SUBAGENT_ULTRA); - const ultraNotifyConfig = readUltraNotify(process.env.PI_SUBAGENT_ULTRA_NOTIFY); - const ultraModeConfig = readUltraMode(process.env.PI_SUBAGENT_ULTRACODE); - const ultraGuidelineConfig = readUltraGuideline(process.env.PI_SUBAGENT_ULTRA_GUIDELINE); - const ultraKeywordConfig = readUltraKeyword(process.env.PI_SUBAGENT_ULTRA_KEYWORD); + const environment = readEnvironmentConfig(); + const workerConfig = environment.maxWorkers; + const workflowItemsConfig = environment.workflowItems; + const ultraConfig = environment.ultra; + const ultraNotifyConfig = environment.ultraNotify; + const ultraModeConfig = environment.ultraMode; + const ultraGuidelineConfig = environment.ultraGuideline; + const ultraKeywordConfig = environment.ultraKeyword; + const workflowLimits = { + maxItemsPerEach: workflowItemsConfig.value, + maxExpandedChildren: MAX_EXPANDED_CHILDREN, + }; const ultraMode = new UltraMode(ultraModeConfig.value); const ultraKeyword = new UltraKeywordTrigger(); let currentContext: ExtensionContext | undefined; @@ -203,6 +200,7 @@ export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) { const prepareContext: PrepareContext = { ...ctx, cwd: effectiveCwd }; const prepared = await prepareWorkflowInvocation(plan, args, prepareContext, { approvedDirectories: approvedProjectDirs, + limits: workflowLimits, }); return manager.startWorkflow(prepared); } @@ -225,9 +223,10 @@ export default function (pi: ExtensionAPI, taskRunner?: TaskRunner) { const prepareContext: PrepareContext = { ...ctx, cwd: effectiveCwd }; const prepared = await prepareWorkflowInvocation(plan, request.args ?? {}, prepareContext, { approvedDirectories: approvedProjectDirs, + limits: workflowLimits, }); if (prepareContext.hasUI && !ultraMode.on) { - const card = formatUltraReviewCard(prepared, { maxItemsPerEach: workflowItemsConfig.value }); + const card = formatUltraReviewCard(prepared); if (!(await ctx.ui.confirm(card.title, card.message))) throw new UltraDeclinedError(plan.name); } return manager.startWorkflow(prepared); diff --git a/src/job-state.ts b/src/job-state.ts new file mode 100644 index 0000000..82ce6b6 --- /dev/null +++ b/src/job-state.ts @@ -0,0 +1,217 @@ +/** + * Shared job and task state. + * + * `Execution` is the flat job record the manager owns; `InternalTask` is one + * row of that record. A workflow's supervisor holds the same rows by reference + * in its own DAG index and settles them through its host seam. The status + * predicates and the small record mutations both adapters need live here, so + * "terminal", "failed", and "the row is running" mean one thing everywhere. + */ + +import { + emptyUsage, + type JobStatus, + type PreparedInvocation, + type PreparedTask, + type RunResult, + type SyncOutcome, + type TaskIdentity, + type TaskSnapshot, + type TaskStatus, +} from "./types.ts"; +import type { WorkflowRunSpec } from "./workflow-run.ts"; + +export interface InternalTask { + /** + * The resolved brief behind a live row. Absent on restored rows: a + * persisted terminal snapshot cannot reconstruct its AgentConfig, and + * restored rows are never launched again. + */ + prepared?: PreparedTask; + snapshot: TaskSnapshot; + controller?: AbortController; + result?: RunResult; +} + +export interface Execution { + id: string; + request: PreparedInvocation; + status: JobStatus; + plannedTaskCount: number; + tasks: InternalTask[]; + createdAt: number; + startedAt?: number; + finishedAt?: number; + errorMessage?: string; + isAsync: boolean; + cancelRequested: boolean; + workflow?: WorkflowRunSpec; + onUpdate?: (outcome: SyncOutcome) => void; + completion?: Promise; +} + +/** The step/item-identity subset, so adding a field changes one mapping here. */ +export function taskIdentityExtras(source: { + step?: number; + stepId?: string; + item?: number; + itemValue?: string; +}): Pick { + return { step: source.step, stepId: source.stepId, item: source.item, itemValue: source.itemValue }; +} + +/** Build the identity a fresh result or snapshot inherits from its prepared task. */ +export function taskIdentity(prepared: PreparedTask): TaskIdentity { + return { + agent: prepared.agent.name, + agentSource: prepared.agent.source, + task: prepared.task, + cwd: prepared.cwd, + ...taskIdentityExtras(prepared), + }; +} + +/** A result before a child has run: no output, no usage, no exit. */ +export function emptyRunResult(prepared: PreparedTask): RunResult { + return { + ...taskIdentity(prepared), + exitCode: null, + messages: [], + output: "", + stderr: "", + usage: emptyUsage(), + }; +} + +/** A snapshot before a child has run: queued and empty. */ +export function emptyTaskSnapshot(prepared: PreparedTask): TaskSnapshot { + return { + ...taskIdentity(prepared), + status: "queued", + exitCode: null, + output: "", + outputTruncated: false, + outputBytesOmitted: 0, + stderr: "", + stderrTruncated: false, + activity: [], + usage: emptyUsage(), + }; +} + +/** A queued row for a live task that has a resolved brief. */ +export function initialTask(prepared: PreparedTask): InternalTask { + return { + prepared, + result: { ...emptyRunResult(prepared), status: "queued" }, + snapshot: emptyTaskSnapshot(prepared), + }; +} + +const TERMINAL_JOB_STATUSES: ReadonlySet = new Set(["succeeded", "failed", "cancelled", "interrupted"]); +const TERMINAL_TASK_STATUSES: ReadonlySet = new Set([ + "succeeded", + "failed", + "skipped", + "cancelled", + "interrupted", +]); + +export function isTerminalJob(status: JobStatus): boolean { + return TERMINAL_JOB_STATUSES.has(status); +} + +export function isTerminalTask(status: TaskStatus): boolean { + return TERMINAL_TASK_STATUSES.has(status); +} + +export interface ResultStatusFields { + status?: TaskStatus; + exitCode?: number | null; + stopReason?: string; + terminationSignal?: string; +} + +/** + * Running/queued placeholders have a null exit code but are not failures. For + * every other result, null or nonzero exits are failures, as are explicit + * error/aborted stop reasons, termination signals, and failure statuses. + * + * This is the one failure predicate: the manager's completion decision and the + * renderers ask the same question here. + */ +export function isFailedResult(result: ResultStatusFields): boolean { + if (result.status === "queued" || result.status === "running") return false; + if (result.status === "skipped") return false; + if (result.status === "failed" || result.status === "cancelled" || result.status === "interrupted") return true; + if (result.exitCode === null || (result.exitCode !== undefined && result.exitCode !== 0)) return true; + return result.stopReason === "error" || result.stopReason === "aborted" || Boolean(result.terminationSignal); +} + +/** The shared row's current status; the supervisor reads through this seam. */ +export function taskStatus(task: InternalTask): TaskStatus { + return task.snapshot.status; +} + +/** The shared row's current output; the supervisor reads through this seam. */ +export function taskOutput(task: InternalTask): string { + return task.snapshot.output; +} + +/** The source line behind an each-step item child, if this row has one. */ +export function taskItemValue(task: InternalTask): string | undefined { + return task.snapshot.itemValue; +} + +/** Whether a running row owns a child process (and so an abort controller). */ +export function taskHasController(task: InternalTask): boolean { + return task.controller !== undefined; +} + +/** The row's latest result, once it has one. */ +export function taskResult(task: InternalTask): RunResult | undefined { + return task.result; +} + +/** + * A neutral result carrying the row's identity. Live rows build it from their + * prepared brief; restored rows have only their snapshot to inherit from. + */ +export function taskBaseResult(task: InternalTask): RunResult { + if (task.prepared) return emptyRunResult(task.prepared); + const { agent, agentSource, task: text, cwd, step, stepId, item, itemValue } = task.snapshot; + return { + agent, + agentSource, + task: text, + cwd, + step, + stepId, + item, + itemValue, + exitCode: null, + messages: [], + output: "", + stderr: "", + usage: emptyUsage(), + }; +} + +/** A step's release-time brief becomes the row's brief, snapshot, and result text. */ +export function setTaskBrief(task: InternalTask, prepared: PreparedTask): void { + task.prepared = prepared; + task.snapshot.task = prepared.task; + if (task.result) task.result = { ...task.result, task: prepared.task, stepId: prepared.stepId }; +} + +/** An each-step coordinator starts when it fans out, before its first item runs. */ +export function markCoordinatorStarted(task: InternalTask, now: number): void { + task.snapshot.startedAt = now; +} + +/** Mark a coordinator running once it has a live item child. */ +export function markTaskRunning(task: InternalTask, now: number): void { + task.snapshot.status = "running"; + task.snapshot.startedAt = now; + if (task.result) task.result = { ...task.result, status: "running" }; +} diff --git a/src/journal.ts b/src/journal.ts index 5bbcd5c..13b4da8 100644 --- a/src/journal.ts +++ b/src/journal.ts @@ -11,57 +11,16 @@ import { createHash } from "node:crypto"; import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "./output.ts"; -import type { JobSnapshot, JobStatus, TaskSnapshot, TaskStatus, UsageStats } from "./types.ts"; +import type { + JobSnapshot, + TaskSnapshot, + WorkflowJournal, + WorkflowJournalItem, + WorkflowJournalStep, +} from "./types.ts"; import type { WorkflowPlan, WorkflowStep } from "./workflow-plan.ts"; import type { WorkflowRunSpec } from "./workflow-run.ts"; -/** One fanned-out item child of an each-step, as the journal records it. */ -export interface WorkflowJournalItem { - /** One-based item index within the step's fan-out. */ - item: number; - /** The source line this item was fanned out from. */ - input: string; - /** Stable across identical item inputs, so a replay layer can key on it. */ - inputHash: string; - status: TaskStatus; - /** Children started for this item; always 0 or 1 while no retry exists. */ - attempts: number; - output: string; - outputTruncated: boolean; - outputBytesOmitted: number; - startedAt?: number; - finishedAt?: number; -} - -export interface WorkflowJournalStep { - id: string; - /** Stable across identical step inputs, so a replay layer can key on it. */ - inputHash: string; - status: TaskStatus; - /** Children started for this step; always 0 or 1 while no retry exists. */ - attempts: number; - output: string; - outputTruncated: boolean; - outputBytesOmitted: number; - startedAt?: number; - finishedAt?: number; - /** One row per each-step item, in item order; empty for steps that do not fan out. */ - items: WorkflowJournalItem[]; -} - -export interface WorkflowJournal { - jobId: string; - status: JobStatus; - plan: WorkflowPlan; - args: Record; - steps: WorkflowJournalStep[]; - usage: UsageStats; - createdAt: number; - startedAt?: number; - finishedAt?: number; - errorMessage?: string; -} - /** * Deterministic JSON: object keys sorted, `undefined` members dropped, so the * same logical value always hashes to the same bytes regardless of construction diff --git a/src/manager.ts b/src/manager.ts index 1b31d4d..064b503 100644 --- a/src/manager.ts +++ b/src/manager.ts @@ -1,13 +1,19 @@ import { summarizeActivity } from "./activity.ts"; import { DEFAULT_MAX_WORKERS } from "./config.ts"; -import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "./output.ts"; -import { buildWorkflowJournal, type WorkflowJournal } from "./journal.ts"; import { - emptyRunResult, - emptyTaskSnapshot, - emptyUsage, + initialTask, + isFailedResult, isTerminalJob, + isTerminalTask, + taskBaseResult, taskIdentityExtras, + type Execution, + type InternalTask, +} from "./job-state.ts"; +import { buildWorkflowJournal } from "./journal.ts"; +import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "./output.ts"; +import { + emptyUsage, type JobSnapshot, type JobStatus, type ManagerOptions, @@ -20,41 +26,16 @@ import { type UsageStats, type SyncOutcome, type SyncRunOptions, + type WorkflowJournal, } from "./types.ts"; import type { PreparedWorkflowInvocation, WorkflowRunSpec, WorkflowStartResult } from "./workflow-run.ts"; -import { WorkflowSupervisor } from "./workflow-supervisor.ts"; +import { WorkflowSupervisor, type WorkflowTermination } from "./workflow-supervisor.ts"; const DEFAULT_MAX_ACTIVE_JOBS = 64; const DEFAULT_HISTORY_LIMIT = 50; const DEFAULT_WAIT_SECONDS = 30; const MAX_WAIT_SECONDS = 300; -export interface InternalTask { - prepared: PreparedTask; - snapshot: TaskSnapshot; - controller?: AbortController; - result?: RunResult; - /** A workflow step submitted to the FIFO, whether or not a worker picked it up yet. */ - submitted?: boolean; -} - -export interface Execution { - id: string; - request: PreparedInvocation; - status: JobStatus; - plannedTaskCount: number; - tasks: InternalTask[]; - createdAt: number; - startedAt?: number; - finishedAt?: number; - errorMessage?: string; - isAsync: boolean; - cancelRequested: boolean; - workflow?: WorkflowRunSpec; - onUpdate?: (outcome: SyncOutcome) => void; - completion?: Promise; -} - interface ScheduledTask { execution: Execution; task: InternalTask; @@ -71,19 +52,6 @@ function cloneSnapshot(snapshot: JobSnapshot): JobSnapshot { return structuredClone(snapshot); } -function initialTask(prepared: PreparedTask, now: number): InternalTask { - void now; - return { - prepared, - result: { ...emptyRunResult(prepared), status: "queued" }, - snapshot: emptyTaskSnapshot(prepared), - }; -} - -function failed(result: RunResult): boolean { - return result.exitCode !== 0 || result.stopReason === "error" || result.stopReason === "aborted" || Boolean(result.terminationSignal); -} - export class SubagentManager { private readonly runner: TaskRunner; private readonly maxWorkers: number; @@ -115,9 +83,9 @@ export class SubagentManager { this.workflows = new WorkflowSupervisor( { schedule: (execution, task) => this.schedule(execution, task), - createTask: (prepared) => initialTask(prepared, this.now()), + createTask: (execution, prepared) => this.createTask(execution, prepared), settleTask: (task, status, result, snapshot) => this.settleTask(task, status, result, snapshot), - cancelledResult: (task) => this.cancelledResult(task), + cancelledResult: (task, status) => this.cancelledResult(task, status), finalize: (execution, status) => this.finalize(execution, status), emit: (execution) => this.emit(execution), now: () => this.now(), @@ -126,6 +94,14 @@ export class SubagentManager { ); } + /** Create a run row through the host seam and register it in the flat job record. */ + private createTask(execution: Execution, prepared: PreparedTask): InternalTask { + const task = initialTask(prepared); + execution.tasks.push(task); + execution.plannedTaskCount += 1; + return task; + } + startAsync(request: PreparedInvocation): JobSnapshot { return this.snapshot(this.startAsyncExecution(request)); } @@ -227,22 +203,10 @@ export class SubagentManager { const existing = this.jobs.get(saved.id); if (existing && this.activeExecutions.has(existing)) continue; const interrupted = !isTerminalJob(saved.status); - const tasks = saved.results.map((result) => { - const source = result.agentSource === "unknown" ? "user" : result.agentSource; - const prepared: PreparedTask = { - agent: { - name: result.agent, - description: "Restored agent", - systemPrompt: "", - source, - filePath: "", - }, - task: result.task, - cwd: result.cwd, - ...taskIdentityExtras(result), - }; - const task = initialTask(prepared, this.now()); - task.snapshot = structuredClone(result); + const tasks: InternalTask[] = saved.results.map((result) => { + // A persisted snapshot is the record: there is no AgentConfig to + // reconstruct, and restored rows are terminal so none is launched. + const task: InternalTask = { snapshot: structuredClone(result) }; if (interrupted && (task.snapshot.status === "queued" || task.snapshot.status === "running")) { task.snapshot.status = "interrupted"; task.snapshot.finishedAt = this.now(); @@ -253,7 +217,7 @@ export class SubagentManager { id: saved.id, request: { mode: saved.mode, - tasks: tasks.map((task) => task.prepared), + tasks: [], agentScope: saved.agentScope, projectAgentsDir: saved.projectAgentsDir, projectAgentsDirs: saved.projectAgentsDirs, @@ -299,12 +263,18 @@ export class SubagentManager { scheduled.task.result = this.interruptedResult(scheduled.task); scheduled.resolve(scheduled.task.result); } - for (const task of execution.tasks) { - if (task.snapshot.status === "succeeded" || task.snapshot.status === "failed" || task.snapshot.status === "cancelled" || task.snapshot.status === "interrupted") continue; - task.snapshot.status = "interrupted"; - task.snapshot.finishedAt = this.now(); - task.controller?.abort(); + // Workflow rows are settled by the supervisor's one termination + // policy; the manager supplies the pool effects and the job outcome. + if (execution.request.mode === "workflow") { + this.workflows.interrupt(execution); + } else { + for (const task of execution.tasks) { + if (isTerminalTask(task.snapshot.status)) continue; + task.snapshot.status = "interrupted"; + task.snapshot.finishedAt = this.now(); + } } + for (const task of execution.tasks) task.controller?.abort(); this.activeExecutions.delete(execution); this.emit(execution); this.resolveWaiters(execution); @@ -317,12 +287,7 @@ export class SubagentManager { } private interruptedResult(task: InternalTask): RunResult { - return { - ...this.cancelledResult(task), - status: "interrupted", - stopReason: "aborted", - errorMessage: "Interrupted by session shutdown", - }; + return this.cancelledResult(task, "interrupted"); } cancel(jobId: string): JobSnapshot { @@ -372,34 +337,39 @@ export class SubagentManager { return task.result; } - private cancelledResult(task: InternalTask): RunResult { + private cancelledResult(task: InternalTask, status: WorkflowTermination = "cancelled"): RunResult { return { - ...emptyRunResult(task.prepared), - status: "cancelled", + ...taskBaseResult(task), + status, stopReason: "aborted", - errorMessage: "Cancelled by caller", + errorMessage: status === "interrupted" ? "Interrupted by session shutdown" : "Cancelled by caller", }; } private createExecution(request: PreparedInvocation, isAsync: boolean): Execution { const id = `job_${String(this.nextJobId++).padStart(4, "0")}`; + const isWorkflow = request.mode === "workflow"; const execution: Execution = { id, request, status: "queued", - plannedTaskCount: request.tasks.length, - tasks: (request.mode === "chain" ? request.tasks.slice(0, 1) : request.tasks).map((task) => initialTask(task, this.now())), + // A workflow creates every row through the supervisor's host seam, + // starting with the plan's step rows. + plannedTaskCount: isWorkflow ? 0 : request.tasks.length, + tasks: isWorkflow + ? [] + : (request.mode === "chain" ? request.tasks.slice(0, 1) : request.tasks).map((task) => initialTask(task)), createdAt: this.now(), isAsync, cancelRequested: false, }; - if (request.mode === "workflow") { + if (isWorkflow) { execution.workflow = (request as PreparedWorkflowInvocation).workflow; } this.activeExecutions.add(execution); if (isAsync) { this.jobs.set(id, execution); - this.emit(execution); + if (!isWorkflow) this.emit(execution); } return execution; } @@ -407,12 +377,12 @@ export class SubagentManager { private async execute(execution: Execution): Promise { if (execution.request.mode === "single") { const result = await this.schedule(execution, execution.tasks[0]); - this.finalize(execution, failed(result) ? "failed" : "succeeded"); + this.finalize(execution, isFailedResult(result) ? "failed" : "succeeded"); return; } if (execution.request.mode === "parallel") { const results = await Promise.all(execution.tasks.map((task) => this.schedule(execution, task))); - this.finalize(execution, results.some(failed) ? "failed" : "succeeded"); + this.finalize(execution, results.some(isFailedResult) ? "failed" : "succeeded"); return; } if (execution.request.mode === "workflow") { @@ -432,14 +402,14 @@ export class SubagentManager { ...execution.request.tasks[index], task: execution.request.tasks[index].task.replace(/\{previous\}/g, previous), }; - execution.tasks.push(initialTask(prepared, this.now())); + execution.tasks.push(initialTask(prepared)); } const result = await this.schedule(execution, execution.tasks[index]); if (execution.cancelRequested || isTerminalJob(execution.status)) { this.finalize(execution, "cancelled"); return; } - if (failed(result)) { + if (isFailedResult(result)) { this.finalize(execution, "failed"); return; } @@ -486,7 +456,9 @@ export class SubagentManager { this.emit(execution); this.emitSync(execution); try { - const result = await this.runner.run(task.prepared, execution.request.dispatchDefaults, { + const prepared = task.prepared; + if (!prepared) throw new Error("Task has no prepared brief"); + const result = await this.runner.run(prepared, execution.request.dispatchDefaults, { signal: controller.signal, onUpdate: (partial) => { partial.status = "running"; @@ -499,17 +471,19 @@ export class SubagentManager { this.emitSync(execution); }, }); - this.applyResult(execution, task, result); + this.applyResult(execution, task, result, prepared); this.emit(execution); this.emitSync(execution); resolve(result); } catch (error) { const result: RunResult = { - ...emptyRunResult(task.prepared), + ...taskBaseResult(task), exitCode: 1, errorMessage: error instanceof Error ? error.message : String(error), }; - this.applyResult(execution, task, result); + const prepared = task.prepared; + if (prepared) this.applyResult(execution, task, result, prepared); + else this.settleTask(task, "failed", result, { exitCode: 1 }); this.emit(execution); this.emitSync(execution); resolve(result); @@ -534,14 +508,14 @@ export class SubagentManager { if (result.messages.length > 0) task.snapshot.activity = summarizeActivity(result.messages, this.now()); } - private applyResult(execution: Execution, task: InternalTask, result: RunResult): void { + private applyResult(execution: Execution, task: InternalTask, result: RunResult, prepared: PreparedTask): void { const settled = execution.isAsync ? { ...result, messages: [] } : result; - task.result = { ...settled, ...taskIdentityExtras(task.prepared) }; + task.result = { ...settled, ...taskIdentityExtras(prepared) }; if (task.snapshot.status === "interrupted") { task.result.status = "interrupted"; return; } - task.snapshot.status = execution.cancelRequested ? "cancelled" : failed(result) ? "failed" : "succeeded"; + task.snapshot.status = execution.cancelRequested ? "cancelled" : isFailedResult(result) ? "failed" : "succeeded"; task.result.status = task.snapshot.status; task.snapshot.exitCode = result.exitCode; this.updateSnapshotFromResult(task, result); diff --git a/src/persistence.ts b/src/persistence.ts index cd21edf..c1c2501 100644 --- a/src/persistence.ts +++ b/src/persistence.ts @@ -1,5 +1,4 @@ -import type { WorkflowJournal, WorkflowJournalItem, WorkflowJournalStep } from "./journal.ts"; -import type { JobSnapshot } from "./types.ts"; +import type { JobSnapshot, WorkflowJournal, WorkflowJournalItem, WorkflowJournalStep } from "./types.ts"; export const SUBAGENT_JOB_ENTRY = "subagent-job-v1"; export const WORKFLOW_RUN_ENTRY = "pi-workflow-run-v1"; diff --git a/src/prepare.ts b/src/prepare.ts index 17ccbd3..56793d6 100644 --- a/src/prepare.ts +++ b/src/prepare.ts @@ -15,7 +15,8 @@ import * as fs from "node:fs"; import * as path from "node:path"; import type { ThinkingLevel } from "@earendil-works/pi-agent-core"; import type { ExtensionToolContext } from "@earendil-works/pi-coding-agent"; -import { type AgentScope, discoverAgents } from "./agents.ts"; +import { type AgentScope, discoverAgents, type AgentDiscoveryResult } from "./agents.ts"; +import { DEFAULT_MAX_WORKFLOW_ITEMS } from "./config.ts"; import type { SubagentParamsType } from "./schemas.ts"; import type { DispatchDefaults, PreparedInvocation, PreparedTask } from "./types.ts"; import { @@ -25,7 +26,7 @@ import { type PreparedWorkflowInvocation, type PreparedWorkflowStep, } from "./workflow-run.ts"; -import { validateWorkflowExpansion, discoverWorkflows, type WorkflowPlan } from "./workflow-plan.ts"; +import { validateWorkflowExpansion, discoverWorkflows, MAX_EXPANDED_CHILDREN, type WorkflowLimits, type WorkflowPlan } from "./workflow-plan.ts"; const MAX_PARALLEL_TASKS = 8; @@ -301,12 +302,18 @@ function resolvePreparedTask( itemCwd: string | undefined, baseCwd: string, agentScope: AgentScope, + discoveries?: Map, ): { task: PreparedTask; projectAgentsDir: string | null } { const cwd = resolveTaskCwd(baseCwd, itemCwd); - // Discovery is per task: agents are a property of the task's effective - // working directory, not of the caller's cwd. - const discovery = discoverAgents(cwd, agentScope); + // Discovery is per effective cwd: agents are a property of the task's + // working directory, not of the caller's cwd. One prepare call memoizes the + // scan so a 64-step plan does not walk the agent directory 64 times. + let discovery = discoveries?.get(cwd); + if (!discovery) { + discovery = discoverAgents(cwd, agentScope); + discoveries?.set(cwd, discovery); + } const agent = discovery.agents.find((candidate) => candidate.name === agentName); if (!agent) { const available = discovery.agents.map((candidate) => `"${candidate.name}"`).join(", ") || "none"; @@ -387,10 +394,11 @@ export async function prepareInvocation( const tasks: PreparedTask[] = []; const projectAgentsByDir = new Map>(); + const discoveries = new Map(); for (let index = 0; index < request.items.length; index++) { const item = request.items[index]; - const resolved = resolvePreparedTask(item.agent, item.task, item.cwd, ctx.cwd, agentScope); + const resolved = resolvePreparedTask(item.agent, item.task, item.cwd, ctx.cwd, agentScope, discoveries); collectProjectAgent(projectAgentsByDir, resolved.task, resolved.projectAgentsDir); if (request.mode === "chain") resolved.task.step = index + 1; tasks.push(resolved.task); @@ -422,6 +430,8 @@ export interface PrepareWorkflowOptions { confirmProjectWorkflows?: boolean; /** Directories already approved in this session, so each prompts once. */ approvedDirectories?: Set; + /** The run's cap limits, captured from load-time config by the caller. */ + limits?: WorkflowLimits; } /** @@ -437,18 +447,16 @@ export async function prepareWorkflowInvocation( ): Promise { validateWorkflowRunShape(plan); const resolvedArgs = validateWorkflowArgs(plan, args); - // Item counts are only known once the source step's output exists, so the - // static shape starts every each-step at zero. Release re-validates with - // the real counts before any item child spawns. - validateWorkflowExpansion( - plan, - new Map(plan.steps.filter((step) => step.each !== undefined).map((step): [string, number] => [step.id, 0])), - ); + const limits = options.limits ?? { + maxItemsPerEach: DEFAULT_MAX_WORKFLOW_ITEMS, + maxExpandedChildren: MAX_EXPANDED_CHILDREN, + }; const agentScope = options.agentScope ?? "both"; const projectAgentsByDir = new Map>(); + const discoveries = new Map(); const steps: PreparedWorkflowStep[] = plan.steps.map((step) => { - const resolved = resolvePreparedTask(step.agent, step.task, step.cwd, ctx.cwd, agentScope); + const resolved = resolvePreparedTask(step.agent, step.task, step.cwd, ctx.cwd, agentScope, discoveries); const prepared: PreparedTask = { ...resolved.task, stepId: step.id, @@ -494,6 +502,7 @@ export async function prepareWorkflowInvocation( args: resolvedArgs, steps, expandedPlan: expandWorkflowPlan(plan), + limits, }, }; } diff --git a/src/render.ts b/src/render.ts index 59e4728..6e3f424 100644 --- a/src/render.ts +++ b/src/render.ts @@ -12,8 +12,11 @@ import { formatReadLineRange, getMarkdownTheme } from "@earendil-works/pi-coding import { Container, Markdown, Spacer, Text, type Component } from "@earendil-works/pi-tui"; import { truncateUtf8Head } from "./output.ts"; import { summarizeActivity } from "./activity.ts"; +import { isFailedResult, type ResultStatusFields } from "./job-state.ts"; import type { RunResult, SubagentDetails, TaskStatus, UsageStats } from "./types.ts"; +export type { ResultStatusFields } from "./job-state.ts"; + export const PER_TASK_OUTPUT_CAP = 50 * 1024; export const PARALLEL_OUTPUT_CAP_BYTES = PER_TASK_OUTPUT_CAP; @@ -40,13 +43,6 @@ export interface SubagentResultLike { details?: (Partial & { results?: readonly RunResult[] }) | undefined; } -export interface ResultStatusFields { - status?: TaskStatus; - exitCode?: number | null; - stopReason?: string; - terminationSignal?: string; -} - type DisplayItem = { type: "text"; text: string } | { type: "toolCall"; name: string; args: Record }; function resolveAgentScope(value: unknown): "user" | "project" | "both" { @@ -195,14 +191,6 @@ export function isSkippedStatus(status: TaskStatus | undefined): boolean { * every other result, null or nonzero exits are failures, as are explicit * error/aborted stop reasons, termination signals, and failure statuses. */ -export function isFailedResult(result: ResultStatusFields): boolean { - if (isRunningStatus(result.status)) return false; - if (isSkippedStatus(result.status)) return false; - if (isFailedStatus(result.status)) return true; - if (result.exitCode === null || (result.exitCode !== undefined && result.exitCode !== 0)) return true; - return result.stopReason === "error" || result.stopReason === "aborted" || Boolean(result.terminationSignal); -} - export function isRunningResult(result: ResultStatusFields): boolean { return isRunningStatus(result.status); } diff --git a/src/runner.ts b/src/runner.ts index 08f6379..002c9d1 100644 --- a/src/runner.ts +++ b/src/runner.ts @@ -11,13 +11,14 @@ import * as os from "node:os"; import * as path from "node:path"; import { StringDecoder } from "node:string_decoder"; import type { Message } from "@earendil-works/pi-ai"; -import { - emptyRunResult, - type DispatchDefaults, - type PreparedTask, - type RunOptions, - type RunResult, - type TaskRunner, +import { inheritedEnvironment } from "./config.ts"; +import { emptyRunResult } from "./job-state.ts"; +import type { + DispatchDefaults, + PreparedTask, + RunOptions, + RunResult, + TaskRunner, } from "./types.ts"; const DEFAULT_KILL_GRACE_MS = 5000; @@ -228,7 +229,7 @@ export class ProcessRunner implements TaskRunner { this.killGraceMs = Math.max(0, options.killGraceMs ?? DEFAULT_KILL_GRACE_MS); this.stderrLimitBytes = Math.max(0, Math.floor(options.stderrLimitBytes ?? DEFAULT_STDERR_LIMIT_BYTES)); this.platform = options.platform ?? process.platform; - this.env = options.env ?? process.env; + this.env = options.env ?? inheritedEnvironment(); } async run(task: PreparedTask, defaults: DispatchDefaults, options: RunOptions): Promise { diff --git a/src/types.ts b/src/types.ts index 786d927..2cf3279 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,7 +1,7 @@ import type { ThinkingLevel } from "@earendil-works/pi-agent-core"; import type { Message } from "@earendil-works/pi-ai"; import type { AgentConfig, AgentScope } from "./agents.ts"; -import type { WorkflowJournal } from "./journal.ts"; +import type { WorkflowPlan } from "./workflow-plan.ts"; export type InvocationMode = "single" | "parallel" | "chain" | "workflow"; export type JobStatus = "queued" | "running" | "cancelling" | "succeeded" | "failed" | "cancelled" | "interrupted"; @@ -126,55 +126,6 @@ export interface TaskIdentity { itemValue?: string; } -/** The step/item-identity subset, so adding a field changes one mapping here. */ -export function taskIdentityExtras(source: { - step?: number; - stepId?: string; - item?: number; - itemValue?: string; -}): Pick { - return { step: source.step, stepId: source.stepId, item: source.item, itemValue: source.itemValue }; -} - -/** Build the identity a fresh result or snapshot inherits from its prepared task. */ -export function taskIdentity(prepared: PreparedTask): TaskIdentity { - return { - agent: prepared.agent.name, - agentSource: prepared.agent.source, - task: prepared.task, - cwd: prepared.cwd, - ...taskIdentityExtras(prepared), - }; -} - -/** A result before a child has run: no output, no usage, no exit. */ -export function emptyRunResult(prepared: PreparedTask): RunResult { - return { - ...taskIdentity(prepared), - exitCode: null, - messages: [], - output: "", - stderr: "", - usage: emptyUsage(), - }; -} - -/** A snapshot before a child has run: queued and empty. */ -export function emptyTaskSnapshot(prepared: PreparedTask): TaskSnapshot { - return { - ...taskIdentity(prepared), - status: "queued", - exitCode: null, - output: "", - outputTruncated: false, - outputBytesOmitted: 0, - stderr: "", - stderrTruncated: false, - activity: [], - usage: emptyUsage(), - }; -} - export interface JobSnapshot { id: string; mode: InvocationMode; @@ -211,6 +162,53 @@ export interface SyncRunOptions { onUpdate?: (outcome: SyncOutcome) => void; } +/** One fanned-out item child of an each-step, as the journal records it. */ +export interface WorkflowJournalItem { + /** One-based item index within the step's fan-out. */ + item: number; + /** The source line this item was fanned out from. */ + input: string; + /** Stable across identical item inputs, so a replay layer can key on it. */ + inputHash: string; + status: TaskStatus; + /** Children started for this item; always 0 or 1 while no retry exists. */ + attempts: number; + output: string; + outputTruncated: boolean; + outputBytesOmitted: number; + startedAt?: number; + finishedAt?: number; +} + +export interface WorkflowJournalStep { + id: string; + /** Stable across identical step inputs, so a replay layer can key on it. */ + inputHash: string; + status: TaskStatus; + /** Children started for this step; always 0 or 1 while no retry exists. */ + attempts: number; + output: string; + outputTruncated: boolean; + outputBytesOmitted: number; + startedAt?: number; + finishedAt?: number; + /** One row per each-step item, in item order; empty for steps that do not fan out. */ + items: WorkflowJournalItem[]; +} + +export interface WorkflowJournal { + jobId: string; + status: JobStatus; + plan: WorkflowPlan; + args: Record; + steps: WorkflowJournalStep[]; + usage: UsageStats; + createdAt: number; + startedAt?: number; + finishedAt?: number; + errorMessage?: string; +} + export interface ManagerOptions { maxWorkers?: number; maxActiveJobs?: number; @@ -223,23 +221,6 @@ export interface ManagerOptions { onWorkflowJournal?: (journal: WorkflowJournal) => void; } -export const TERMINAL_JOB_STATUSES: ReadonlySet = new Set(["succeeded", "failed", "cancelled", "interrupted"]); -export const TERMINAL_TASK_STATUSES: ReadonlySet = new Set([ - "succeeded", - "failed", - "skipped", - "cancelled", - "interrupted", -]); - -export function isTerminalJob(status: JobStatus): boolean { - return TERMINAL_JOB_STATUSES.has(status); -} - -export function isTerminalTask(status: TaskStatus): boolean { - return TERMINAL_TASK_STATUSES.has(status); -} - export function emptyUsage(): UsageStats { return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 }; } diff --git a/src/ultra-notify.ts b/src/ultra-notify.ts index 8d3b440..76034a1 100644 --- a/src/ultra-notify.ts +++ b/src/ultra-notify.ts @@ -9,9 +9,8 @@ * child's output or reads a task snapshot again. */ -import type { WorkflowJournal, WorkflowJournalStep } from "./journal.ts"; import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "./output.ts"; -import type { JobStatus } from "./types.ts"; +import type { JobStatus, WorkflowJournal, WorkflowJournalStep } from "./types.ts"; export const ULTRA_DONE_MESSAGE_TYPE = "pi-subagent-ultra-done"; diff --git a/src/ultra.ts b/src/ultra.ts index aa23d31..73687d0 100644 --- a/src/ultra.ts +++ b/src/ultra.ts @@ -8,7 +8,7 @@ import type { UltraGuideline } from "./config.ts"; import { formatUltraGuidelineLine } from "./ultra-mode.ts"; -import { MAX_EXPANDED_CHILDREN, MAX_WORKFLOW_STEPS } from "./workflow-plan.ts"; +import { MAX_WORKFLOW_STEPS } from "./workflow-plan.ts"; import type { PreparedWorkflowInvocation, WorkflowStartResult } from "./workflow-run.ts"; /** Thrown when the user declines the review card for an inline plan. */ @@ -27,11 +27,6 @@ export interface UltraReviewCard { message: string; } -export interface UltraReviewOptions { - maxItemsPerEach: number; - maxExpandedChildren?: number; -} - function plural(count: number, singular: string, pluralForm = `${singular}s`): string { return `${count} ${count === 1 ? singular : pluralForm}`; } @@ -43,13 +38,10 @@ function plural(count: number, singular: string, pluralForm = `${singular}s`): s * run — every step, its needs and fan-out source, the child-count estimate * against the caps, and every named agent with its user/project source. */ -export function formatUltraReviewCard( - prepared: PreparedWorkflowInvocation, - options: UltraReviewOptions, -): UltraReviewCard { +export function formatUltraReviewCard(prepared: PreparedWorkflowInvocation): UltraReviewCard { const steps = prepared.workflow.steps; - const maxItemsPerEach = options.maxItemsPerEach; - const maxExpandedChildren = options.maxExpandedChildren ?? MAX_EXPANDED_CHILDREN; + const maxItemsPerEach = prepared.workflow.limits.maxItemsPerEach; + const maxExpandedChildren = prepared.workflow.limits.maxExpandedChildren; const fanOutSteps = steps.filter((step) => step.each !== undefined).length; const fixedSteps = steps.length - fanOutSteps; diff --git a/src/workflow-plan.ts b/src/workflow-plan.ts index ff8c702..cbcb5b0 100644 --- a/src/workflow-plan.ts +++ b/src/workflow-plan.ts @@ -12,7 +12,6 @@ import * as fs from "node:fs"; import * as path from "node:path"; import { CONFIG_DIR_NAME, getAgentDir, parseFrontmatter } from "@earendil-works/pi-coding-agent"; -import { readMaxWorkflowItems } from "./config.ts"; export const MAX_WORKFLOW_STEPS = 64; export const MAX_EXPANDED_CHILDREN = 256; @@ -66,9 +65,10 @@ export interface WorkflowDiscoveryResult { export type WorkflowItemCounts = ReadonlyMap; -export interface WorkflowExpansionOptions { - maxItemsPerEach?: number; - maxExpandedChildren?: number; +/** The run's cap limits, captured once from load-time config and threaded here. */ +export interface WorkflowLimits { + maxItemsPerEach: number; + maxExpandedChildren: number; } /** Thrown when no workflow with the requested name exists in scope. */ @@ -520,11 +520,10 @@ function failPlan(plan: WorkflowPlan, message: string, stepId?: string): never { export function validateWorkflowExpansion( plan: WorkflowPlan, items: WorkflowItemCounts, - options: WorkflowExpansionOptions = {}, + limits: WorkflowLimits, ): number { - const maxItems = - options.maxItemsPerEach ?? readMaxWorkflowItems(process.env.PI_SUBAGENT_WORKFLOW_MAX_ITEMS).value; - const maxChildren = options.maxExpandedChildren ?? MAX_EXPANDED_CHILDREN; + const maxItems = limits.maxItemsPerEach; + const maxChildren = limits.maxExpandedChildren; let children = 0; for (const [index, step] of plan.steps.entries()) { diff --git a/src/workflow-run.ts b/src/workflow-run.ts index ae6bcea..5b9ee52 100644 --- a/src/workflow-run.ts +++ b/src/workflow-run.ts @@ -9,7 +9,7 @@ import { truncateUtf8Head } from "./output.ts"; import type { JobSnapshot, PreparedInvocation, PreparedTask } from "./types.ts"; -import { workflowValidationError, type WorkflowPlan } from "./workflow-plan.ts"; +import { workflowValidationError, type WorkflowLimits, type WorkflowPlan } from "./workflow-plan.ts"; /** The design ceiling for one run, independent of the global worker pool. */ export const WORKFLOW_MAX_CONCURRENCY = 4; @@ -49,6 +49,8 @@ export interface WorkflowRunSpec { args: Record; steps: PreparedWorkflowStep[]; expandedPlan: StartPlan; + /** Captured once at prepare time; enforcement and the review card share it. */ + limits: WorkflowLimits; } export interface PreparedWorkflowInvocation extends PreparedInvocation { diff --git a/src/workflow-supervisor.ts b/src/workflow-supervisor.ts index ccec88f..167e418 100644 --- a/src/workflow-supervisor.ts +++ b/src/workflow-supervisor.ts @@ -3,8 +3,8 @@ * * Owns the DAG rules for one run: which steps are ready, how skips cascade, * how each-step items fan out and aggregate, and when the run settles. The - * manager owns the FIFO pool and the job/task lifecycle; a run reaches them - * only through `WorkflowSupervisorHost`. ADR 0002 stands: a run is a job on the + * manager owns the FIFO pool and the job record; a run reaches them only + * through `WorkflowSupervisorHost`. ADR 0002 stands: a run is a job on the * shared manager, not a parallel subsystem. * * The behavior mirrors spec/SubagentJobs.tla: needs sets, the transitive skip @@ -12,16 +12,26 @@ * step is terminal. */ -import type { Execution, InternalTask } from "./manager.ts"; import { - emptyRunResult, - isTerminalJob, isTerminalTask, - type JobStatus, - type PreparedTask, - type RunResult, - type TaskSnapshot, - type TaskStatus, + markCoordinatorStarted, + markTaskRunning, + setTaskBrief, + taskBaseResult, + taskHasController, + taskItemValue, + taskOutput, + taskResult, + taskStatus, + type Execution, + type InternalTask, +} from "./job-state.ts"; +import type { + JobStatus, + PreparedTask, + RunResult, + TaskSnapshot, + TaskStatus, } from "./types.ts"; import { interpolateWorkflowTask, @@ -32,16 +42,21 @@ import { } from "./workflow-run.ts"; import { validateWorkflowExpansion } from "./workflow-plan.ts"; +/** One way an external signal ends a run. */ +export type WorkflowTermination = "cancelled" | "interrupted"; + /** * The manager capabilities a run needs. Queueing, worker accounting, job - * admission, cancellation, snapshots, waiters, and persistence stay with the - * manager; the supervisor sees only this seam. + * admission, snapshots, waiters, and persistence stay with the manager; the + * supervisor sees only this seam. Apart from the clock, every method is an + * effect: the manager registers the row, starts the work, or commits the + * outcome. */ export interface WorkflowSupervisorHost { + /** Create a queued row, register it in the job record, and count it. */ + createTask(execution: Execution, prepared: PreparedTask): InternalTask; /** Submit one step or item child to the shared FIFO; resolves with its result. */ schedule(execution: Execution, task: InternalTask): Promise; - /** Build a fresh queued task for a step or an each-step item child. */ - createTask(prepared: PreparedTask): InternalTask; /** Move a task to a terminal snapshot and its matching result in one step. */ settleTask( task: InternalTask, @@ -50,7 +65,7 @@ export interface WorkflowSupervisorHost { snapshot?: Partial, ): RunResult; /** The result of a task the pool never ran, for cancellation settlement. */ - cancelledResult(task: InternalTask): RunResult; + cancelledResult(task: InternalTask, status?: WorkflowTermination): RunResult; /** Commit the run's terminal status. */ finalize(execution: Execution, status: JobStatus): void; /** Notify job observers that the run changed. */ @@ -62,18 +77,24 @@ export interface WorkflowSupervisorHost { interface WorkflowRunState { execution: Execution; spec: WorkflowRunSpec; + tasks: InternalTask[]; stepTasks: Map; activeChildren: Map>; itemTasks: Map; pendingItems: Map; itemCounts: Map; + /** Step ids whose one release has happened, whatever its outcome. */ + released: Set; concurrency: number; + termination?: WorkflowTermination; } export class WorkflowSupervisor { private readonly host: WorkflowSupervisorHost; private readonly maxWorkers: number; private readonly concurrency: number; + /** Live runs by their opaque job record, so cancellation can reach their DAG state. */ + private readonly runs = new Map(); constructor(host: WorkflowSupervisorHost, maxWorkers: number) { this.host = host; @@ -94,60 +115,72 @@ export class WorkflowSupervisor { const state: WorkflowRunState = { execution, spec, + tasks: [], stepTasks: new Map(), activeChildren: new Map(), itemTasks: new Map(), pendingItems: new Map(), itemCounts: new Map(), + released: new Set(), concurrency: this.concurrency, }; - for (const task of execution.tasks) { - if (task.prepared.stepId) state.stepTasks.set(task.prepared.stepId, task); - } for (const step of spec.steps) { if (step.each !== undefined) state.itemCounts.set(step.id, 0); } + this.runs.set(execution, state); - while (true) { - for (const [task] of state.activeChildren) { - if (isTerminalTask(task.snapshot.status)) state.activeChildren.delete(task); + try { + // The supervisor creates every run row through the host, so the flat + // job record and this DAG index start from the same plan order. + for (const step of spec.steps) { + const task = this.host.createTask(execution, step.prepared); + state.stepTasks.set(step.id, task); + state.tasks.push(task); } - if (isTerminalJob(execution.status)) return; - if (execution.cancelRequested) { - if (state.activeChildren.size === 0) { - this.host.finalize(execution, "cancelled"); + while (true) { + for (const [task] of state.activeChildren) { + if (isTerminalTask(taskStatus(task))) state.activeChildren.delete(task); + } + + if (state.termination === "interrupted") return; + if (state.termination === "cancelled") { + if (state.activeChildren.size === 0) { + this.host.finalize(execution, "cancelled"); + return; + } + await Promise.race(state.activeChildren.values()); + continue; + } + + let changed = false; + if (this.propagateWorkflowSkips(state)) changed = true; + if (this.settleWorkflowItemSteps(state)) changed = true; + + if (state.tasks.every((task) => isTerminalTask(taskStatus(task)))) { + const outcome = state.tasks.some((task) => taskStatus(task) === "failed") ? "failed" : "succeeded"; + this.host.finalize(execution, outcome); return; } + + if (state.concurrency - state.activeChildren.size > 0) { + if (this.releaseWorkflowSteps(state)) changed = true; + if (this.launchWorkflowItems(state)) changed = true; + } + + if (changed) this.host.emit(execution); + + if (state.activeChildren.size === 0) { + if (changed) continue; + // A validated DAG plus a complete skip cascade always leaves a + // releasable or running step. Failing loudly beats hanging. + throw new Error(`Workflow run "${spec.plan.name}" stalled with no releasable steps.`); + } + await Promise.race(state.activeChildren.values()); - continue; } - - let changed = false; - if (this.propagateWorkflowSkips(state)) changed = true; - if (this.settleWorkflowItemSteps(state)) changed = true; - - if (execution.tasks.every((task) => isTerminalTask(task.snapshot.status))) { - const outcome = execution.tasks.some((task) => task.snapshot.status === "failed") ? "failed" : "succeeded"; - this.host.finalize(execution, outcome); - return; - } - - if (state.concurrency - state.activeChildren.size > 0) { - if (this.releaseWorkflowSteps(state)) changed = true; - if (this.launchWorkflowItems(state)) changed = true; - } - - if (changed) this.host.emit(execution); - - if (state.activeChildren.size === 0) { - if (changed) continue; - // A validated DAG plus a complete skip cascade always leaves a - // releasable or running step. Failing loudly beats hanging. - throw new Error(`Workflow run ${execution.id} stalled with no releasable steps.`); - } - - await Promise.race(state.activeChildren.values()); + } finally { + this.runs.delete(execution); } } @@ -157,13 +190,33 @@ export class WorkflowSupervisor { * coordinator rows (which have no child process of their own). */ cancel(execution: Execution): void { - for (const task of execution.tasks) { - if (task.snapshot.status !== "queued") continue; - this.host.settleTask(task, "cancelled", this.host.cancelledResult(task)); + this.terminate(execution, "cancelled"); + } + + /** + * Shutdown is the same settlement policy with interrupted semantics. The + * manager signals the run, this settles every unfinished row, and the + * manager aborts the child processes and commits the job status. + */ + interrupt(execution: Execution): void { + this.terminate(execution, "interrupted"); + } + + private terminate(execution: Execution, outcome: WorkflowTermination): void { + const state = this.runs.get(execution); + if (!state) return; + if (state.termination !== "interrupted") state.termination = outcome; + + for (const task of state.tasks) { + const status = taskStatus(task); + const settles = status === "queued" + || (status === "running" && (outcome === "interrupted" || !taskHasController(task))); + if (!settles) continue; + this.host.settleTask(task, outcome, this.host.cancelledResult(task, outcome)); } - for (const task of execution.tasks) { - if (task.snapshot.status !== "running" || task.controller) continue; - this.host.settleTask(task, "cancelled", this.host.cancelledResult(task)); + + if (state.termination === "cancelled" && state.activeChildren.size === 0) { + this.host.finalize(execution, "cancelled"); } } @@ -175,13 +228,13 @@ export class WorkflowSupervisor { pass = false; for (const step of spec.steps) { const task = stepTasks.get(step.id); - if (!task || task.snapshot.status !== "queued" || task.submitted) continue; + if (!task || taskStatus(task) !== "queued" || state.released.has(step.id)) continue; const deadNeed = step.needs.some((need) => { const needTask = stepTasks.get(need); return Boolean( needTask && - isTerminalTask(needTask.snapshot.status) && - needTask.snapshot.status !== "succeeded", + isTerminalTask(taskStatus(needTask)) && + taskStatus(needTask) !== "succeeded", ); }); if (!deadNeed) continue; @@ -203,22 +256,28 @@ export class WorkflowSupervisor { for (const step of spec.steps) { if (slots <= 0) break; const task = stepTasks.get(step.id); - if (!task || task.snapshot.status !== "queued" || task.submitted) continue; - const needsSucceeded = step.needs.every( - (need) => stepTasks.get(need)?.snapshot.status === "succeeded", - ); + if (!task || taskStatus(task) !== "queued" || state.released.has(step.id)) continue; + const needsSucceeded = step.needs.every((need) => { + const needTask = stepTasks.get(need); + return needTask !== undefined && taskStatus(needTask) === "succeeded"; + }); if (!needsSucceeded) continue; const outputs = new Map(); - for (const need of step.needs) outputs.set(need, stepTasks.get(need)?.snapshot.output ?? ""); + for (const need of step.needs) { + const needTask = stepTasks.get(need); + outputs.set(need, needTask ? taskOutput(needTask) : ""); + } if (step.each !== undefined) { - const items = splitWorkflowItems(stepTasks.get(step.each)?.snapshot.output ?? ""); + const sourceTask = stepTasks.get(step.each); + const items = splitWorkflowItems(sourceTask ? taskOutput(sourceTask) : ""); const nextCounts = new Map(itemCounts); nextCounts.set(step.id, items.length); try { - validateWorkflowExpansion(spec.plan, nextCounts); + validateWorkflowExpansion(spec.plan, nextCounts, spec.limits); } catch (error) { + state.released.add(step.id); this.failWorkflowStep(task, error instanceof Error ? error.message : String(error)); released = true; continue; @@ -226,6 +285,7 @@ export class WorkflowSupervisor { itemCounts.set(step.id, items.length); if (items.length === 0) { + state.released.add(step.id); this.failWorkflowStep( task, `Each-step "${step.id}": source produced no items from "{steps.${step.each}.output}".`, @@ -236,12 +296,17 @@ export class WorkflowSupervisor { const children = items.map((item, index) => { const brief = interpolateWorkflowTask(step.template, { args: spec.args, outputs, item }); - return this.host.createTask({ ...step.prepared, task: brief, stepId: step.id, item: index + 1, itemValue: item }); + return this.host.createTask(execution, { + ...step.prepared, + task: brief, + stepId: step.id, + item: index + 1, + itemValue: item, + }); }); - task.submitted = true; - task.snapshot.startedAt = this.host.now(); - execution.tasks.push(...children); - execution.plannedTaskCount += children.length; + state.released.add(step.id); + markCoordinatorStarted(task, this.host.now()); + state.tasks.push(...children); state.itemTasks.set(step.id, children); state.pendingItems.set(step.id, [...children]); released = true; @@ -249,10 +314,8 @@ export class WorkflowSupervisor { } const brief = interpolateWorkflowTask(step.template, { args: spec.args, outputs }); - task.prepared = { ...step.prepared, task: brief, stepId: step.id }; - task.snapshot.task = brief; - if (task.result) task.result = { ...task.result, task: brief, stepId: step.id }; - task.submitted = true; + setTaskBrief(task, { ...step.prepared, task: brief, stepId: step.id }); + state.released.add(step.id); state.activeChildren.set(task, this.host.schedule(execution, task).then(() => undefined)); released = true; slots--; @@ -276,15 +339,13 @@ export class WorkflowSupervisor { const child = queue?.shift(); if (!child) continue; pass = true; - if (isTerminalTask(child.snapshot.status)) { + if (isTerminalTask(taskStatus(child))) { launched = true; continue; } const stepTask = stepTasks.get(step.id); - if (stepTask && stepTask.snapshot.status === "queued") { - stepTask.snapshot.status = "running"; - stepTask.snapshot.startedAt = this.host.now(); - if (stepTask.result) stepTask.result = { ...stepTask.result, status: "running" }; + if (stepTask && taskStatus(stepTask) === "queued") { + markTaskRunning(stepTask, this.host.now()); } state.activeChildren.set(child, this.host.schedule(execution, child).then(() => undefined)); launched = true; @@ -304,34 +365,36 @@ export class WorkflowSupervisor { const task = stepTasks.get(step.id); const items = itemTasks.get(step.id); if (!task || !items || items.length === 0) continue; - if (task.snapshot.status !== "queued" && task.snapshot.status !== "running") continue; - if (!items.every((item) => isTerminalTask(item.snapshot.status))) continue; + const status = taskStatus(task); + if (status !== "queued" && status !== "running") continue; + if (!items.every((item) => isTerminalTask(taskStatus(item)))) continue; - const statuses = items.map((item) => item.snapshot.status); - const succeeded = statuses.filter((status) => status === "succeeded").length; + const statuses = items.map((item) => taskStatus(item)); + const succeeded = statuses.filter((itemStatus) => itemStatus === "succeeded").length; const interrupted = statuses.includes("interrupted"); const cancelled = statuses.includes("cancelled"); + const base = taskResult(task) ?? this.host.cancelledResult(task); if (interrupted || cancelled) { - const status = interrupted ? "interrupted" : "cancelled"; + const outcome = interrupted ? "interrupted" : "cancelled"; const message = interrupted ? "Interrupted by session shutdown" : "Cancelled by caller"; - const result = { ...(task.result ?? this.host.cancelledResult(task)), output: "", errorMessage: message }; - this.host.settleTask(task, status, result, { errorMessage: message }); + const result = { ...base, output: "", errorMessage: message }; + this.host.settleTask(task, outcome, result, { errorMessage: message }); } else { const output = joinWorkflowItemOutputs( items.map((item) => ({ - item: item.snapshot.itemValue ?? "", + item: taskItemValue(item) ?? "", // Failed items leave an empty slot; their partial output never leaks in. - output: item.snapshot.status === "succeeded" ? item.snapshot.output : "", + output: taskStatus(item) === "succeeded" ? taskOutput(item) : "", })), ); const snapshot = { output, outputTruncated: false, outputBytesOmitted: 0 }; if (succeeded > 0) { - const result = { ...task.result!, output, errorMessage: undefined, exitCode: 0 }; + const result = { ...base, output, errorMessage: undefined, exitCode: 0 }; this.host.settleTask(task, "succeeded", result, { ...snapshot, errorMessage: undefined }); } else { const message = `All ${items.length} item${items.length === 1 ? "" : "s"} failed`; - const result = { ...task.result!, output, errorMessage: message, exitCode: 1 }; + const result = { ...base, output, errorMessage: message, exitCode: 1 }; this.host.settleTask(task, "failed", result, { ...snapshot, exitCode: 1, errorMessage: message }); } } @@ -343,17 +406,18 @@ export class WorkflowSupervisor { } private failWorkflowStep(task: InternalTask, message: string): void { + const base = taskResult(task) ?? this.host.cancelledResult(task); this.host.settleTask( task, "failed", - { ...task.result!, exitCode: 1, errorMessage: message }, + { ...base, exitCode: 1, errorMessage: message }, { exitCode: 1, errorMessage: message }, ); } private skippedResult(task: InternalTask): RunResult { return { - ...emptyRunResult(task.prepared), + ...taskBaseResult(task), status: "skipped", errorMessage: "Skipped because a required step did not succeed", }; diff --git a/test/concurrency.test.ts b/test/concurrency.test.ts index 9c197ed..5416350 100644 --- a/test/concurrency.test.ts +++ b/test/concurrency.test.ts @@ -2,7 +2,8 @@ import assert from "node:assert/strict"; import test from "node:test"; import fc from "fast-check"; import { SubagentManager } from "../src/manager.ts"; -import { isTerminalJob, type JobSnapshot, type JobStatus } from "../src/types.ts"; +import { isTerminalJob } from "../src/job-state.ts"; +import type { JobSnapshot, JobStatus } from "../src/types.ts"; import { FakeRunner, invocation } from "./helpers.ts"; type Action = diff --git a/test/render.test.ts b/test/render.test.ts index 9913d18..4a9d178 100644 --- a/test/render.test.ts +++ b/test/render.test.ts @@ -1,11 +1,11 @@ import assert from "node:assert/strict"; import test from "node:test"; import type { Message } from "@earendil-works/pi-ai"; +import { isFailedResult } from "../src/job-state.ts"; import type { SubagentDetails, RunResult } from "../src/types.ts"; import { PER_TASK_OUTPUT_CAP, formatParallelSummary, - isFailedResult, isRunningResult, isSuccessfulResult, renderSubagentCall, diff --git a/test/ultra-notify.test.ts b/test/ultra-notify.test.ts index 51bde7b..91859be 100644 --- a/test/ultra-notify.test.ts +++ b/test/ultra-notify.test.ts @@ -6,7 +6,7 @@ import test, { after } from "node:test"; import type { AgentToolResult } from "@earendil-works/pi-agent-core"; import type { ExtensionAPI, ExtensionToolContext } from "@earendil-works/pi-coding-agent"; import registerExtension from "../src/index.ts"; -import type { WorkflowJournal, WorkflowJournalStep } from "../src/journal.ts"; +import type { WorkflowJournal, WorkflowJournalStep } from "../src/types.ts"; import { MAX_TASK_OUTPUT_BYTES } from "../src/output.ts"; import { extractWorkflowJournals } from "../src/persistence.ts"; import { emptyUsage, type JobStatus, type TaskStatus } from "../src/types.ts"; diff --git a/test/workflow-journal.test.ts b/test/workflow-journal.test.ts index 39631ce..f7ea027 100644 --- a/test/workflow-journal.test.ts +++ b/test/workflow-journal.test.ts @@ -4,7 +4,7 @@ import * as os from "node:os"; import * as path from "node:path"; import test, { after } from "node:test"; import fc from "fast-check"; -import { buildWorkflowJournal, workflowItemInputHash, workflowStepInputHash, type WorkflowJournal, type WorkflowJournalItem, type WorkflowJournalStep } from "../src/journal.ts"; +import { buildWorkflowJournal, workflowItemInputHash, workflowStepInputHash } from "../src/journal.ts"; import { SubagentManager } from "../src/manager.ts"; import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "../src/output.ts"; import { @@ -17,7 +17,7 @@ import { } from "../src/persistence.ts"; import { prepareWorkflowInvocation, type PrepareContext } from "../src/prepare.ts"; import { parseWorkflow, type WorkflowPlan } from "../src/workflow-plan.ts"; -import { emptyUsage, type JobSnapshot, type TaskSnapshot, type TaskStatus } 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"; const tempRoots: string[] = []; diff --git a/test/workflows.test.ts b/test/workflows.test.ts index a56da2e..5c6bf72 100644 --- a/test/workflows.test.ts +++ b/test/workflows.test.ts @@ -276,39 +276,34 @@ function itemCounts(counts: number[]): Map { return new Map(counts.map((count, index) => [`audit_${index}`, count])); } +function limits(maxItemsPerEach = 32, maxExpandedChildren = MAX_EXPANDED_CHILDREN) { + return { maxItemsPerEach, maxExpandedChildren }; +} + test("expanded children caps are validated per each-step and per run", () => { const p = eachPlan([32]); - assert.equal(validateWorkflowExpansion(p, itemCounts([32])), 33); + assert.equal(validateWorkflowExpansion(p, itemCounts([32]), limits()), 33); - const tooManyItems = validationErrorFor(() => validateWorkflowExpansion(p, itemCounts([33]), { maxItemsPerEach: 32 })); + const tooManyItems = validationErrorFor(() => validateWorkflowExpansion(p, itemCounts([33]), limits(32))); assert.match(tooManyItems.message, /steps\[1\] \("audit_0"\) has 33 items/); assert.match(tooManyItems.message, /max is 32 per each-step/); assert.match( validationErrorFor(() => - validateWorkflowExpansion(eachPlan(Array(8).fill(32)), itemCounts(Array(8).fill(32))), + validateWorkflowExpansion(eachPlan(Array(8).fill(32)), itemCounts(Array(8).fill(32)), limits()), ).message, new RegExp(`expanded children \\(257\\) exceed the run cap of ${MAX_EXPANDED_CHILDREN}`), ); const accepted = eachPlan([...Array(7).fill(32), 31]); - assert.equal(validateWorkflowExpansion(accepted, itemCounts([...Array(7).fill(32), 31])), 256); + assert.equal(validateWorkflowExpansion(accepted, itemCounts([...Array(7).fill(32), 31]), limits()), 256); }); -test("the each-item cap honours PI_SUBAGENT_WORKFLOW_MAX_ITEMS", () => { - const previous = process.env.PI_SUBAGENT_WORKFLOW_MAX_ITEMS; - process.env.PI_SUBAGENT_WORKFLOW_MAX_ITEMS = "4"; - try { - const p = eachPlan([5]); - assert.equal(validateWorkflowExpansion(p, itemCounts([5]), { maxItemsPerEach: 99 }), 6); - const error = validationErrorFor(() => validateWorkflowExpansion(p, itemCounts([5]))); - assert.match(error.message, /has 5 items/); - assert.match(error.message, /max is 4 per each-step/); - assert.match(error.message, /PI_SUBAGENT_WORKFLOW_MAX_ITEMS/); - } finally { - if (previous === undefined) delete process.env.PI_SUBAGENT_WORKFLOW_MAX_ITEMS; - else process.env.PI_SUBAGENT_WORKFLOW_MAX_ITEMS = previous; - } +test("the each-item cap uses the injected limits", () => { + const p = eachPlan([5]); + const error = validationErrorFor(() => validateWorkflowExpansion(p, itemCounts([5]), limits(4))); + assert.match(error.message, /has 5 items/); + assert.match(error.message, /max is 4 per each-step/); }); const identifierArb = fc.stringMatching(/^[A-Za-z_][A-Za-z0-9_-]{0,7}$/);