@calmo/task-runner 2.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/.jules/nexus.md +5 -0
  2. package/AGENTS.md +49 -0
  3. package/CHANGELOG.md +33 -0
  4. package/README.md +1 -1
  5. package/coverage/coverage-final.json +9 -4
  6. package/coverage/index.html +24 -9
  7. package/coverage/lcov-report/index.html +24 -9
  8. package/coverage/lcov-report/src/EventBus.ts.html +8 -8
  9. package/coverage/lcov-report/src/TaskGraphValidator.ts.html +53 -53
  10. package/coverage/lcov-report/src/TaskRunner.ts.html +377 -20
  11. package/coverage/lcov-report/src/TaskRunnerBuilder.ts.html +313 -0
  12. package/coverage/lcov-report/src/TaskRunnerExecutionConfig.ts.html +139 -0
  13. package/coverage/lcov-report/src/TaskStateManager.ts.html +511 -0
  14. package/coverage/lcov-report/src/WorkflowExecutor.ts.html +119 -137
  15. package/coverage/lcov-report/src/contracts/RunnerEvents.ts.html +1 -1
  16. package/coverage/lcov-report/src/contracts/index.html +1 -1
  17. package/coverage/lcov-report/src/index.html +56 -11
  18. package/coverage/lcov-report/src/strategies/DryRunExecutionStrategy.ts.html +178 -0
  19. package/coverage/lcov-report/src/strategies/StandardExecutionStrategy.ts.html +190 -0
  20. package/coverage/lcov-report/src/strategies/index.html +131 -0
  21. package/coverage/lcov.info +419 -204
  22. package/coverage/src/EventBus.ts.html +8 -8
  23. package/coverage/src/TaskGraphValidator.ts.html +53 -53
  24. package/coverage/src/TaskRunner.ts.html +377 -20
  25. package/coverage/src/TaskRunnerBuilder.ts.html +313 -0
  26. package/coverage/src/TaskRunnerExecutionConfig.ts.html +139 -0
  27. package/coverage/src/TaskStateManager.ts.html +511 -0
  28. package/coverage/src/WorkflowExecutor.ts.html +119 -137
  29. package/coverage/src/contracts/RunnerEvents.ts.html +1 -1
  30. package/coverage/src/contracts/index.html +1 -1
  31. package/coverage/src/index.html +56 -11
  32. package/coverage/src/strategies/DryRunExecutionStrategy.ts.html +178 -0
  33. package/coverage/src/strategies/StandardExecutionStrategy.ts.html +190 -0
  34. package/coverage/src/strategies/index.html +131 -0
  35. package/dist/TaskRunner.d.ts +24 -2
  36. package/dist/TaskRunner.js +99 -3
  37. package/dist/TaskRunner.js.map +1 -1
  38. package/dist/TaskRunnerBuilder.d.ts +33 -0
  39. package/dist/TaskRunnerBuilder.js +54 -0
  40. package/dist/TaskRunnerBuilder.js.map +1 -0
  41. package/dist/TaskRunnerExecutionConfig.d.ts +18 -0
  42. package/dist/TaskRunnerExecutionConfig.js +2 -0
  43. package/dist/TaskRunnerExecutionConfig.js.map +1 -0
  44. package/dist/TaskStateManager.d.ts +54 -0
  45. package/dist/TaskStateManager.js +130 -0
  46. package/dist/TaskStateManager.js.map +1 -0
  47. package/dist/TaskStatus.d.ts +1 -1
  48. package/dist/TaskStep.d.ts +2 -1
  49. package/dist/WorkflowExecutor.d.ts +11 -17
  50. package/dist/WorkflowExecutor.js +67 -69
  51. package/dist/WorkflowExecutor.js.map +1 -1
  52. package/dist/index.d.ts +4 -0
  53. package/dist/index.js +3 -0
  54. package/dist/index.js.map +1 -1
  55. package/dist/strategies/DryRunExecutionStrategy.d.ts +16 -0
  56. package/dist/strategies/DryRunExecutionStrategy.js +25 -0
  57. package/dist/strategies/DryRunExecutionStrategy.js.map +1 -0
  58. package/dist/strategies/IExecutionStrategy.d.ts +16 -0
  59. package/dist/strategies/IExecutionStrategy.js +2 -0
  60. package/dist/strategies/IExecutionStrategy.js.map +1 -0
  61. package/dist/strategies/StandardExecutionStrategy.d.ts +9 -0
  62. package/dist/strategies/StandardExecutionStrategy.js +25 -0
  63. package/dist/strategies/StandardExecutionStrategy.js.map +1 -0
  64. package/openspec/changes/add-concurrency-control/proposal.md +14 -0
  65. package/openspec/changes/add-concurrency-control/tasks.md +9 -0
  66. package/openspec/changes/add-task-retry-policy/proposal.md +16 -0
  67. package/openspec/changes/add-task-retry-policy/tasks.md +10 -0
  68. package/openspec/changes/add-workflow-preview/proposal.md +13 -0
  69. package/openspec/changes/add-workflow-preview/tasks.md +7 -0
  70. package/openspec/changes/archive/2026-01-18-add-external-task-cancellation/tasks.md +10 -0
  71. package/openspec/changes/archive/2026-01-18-add-integration-tests/proposal.md +18 -0
  72. package/openspec/changes/archive/2026-01-18-add-integration-tests/tasks.md +17 -0
  73. package/openspec/changes/archive/2026-01-18-refactor-core-architecture/proposal.md +14 -0
  74. package/openspec/changes/archive/2026-01-18-refactor-core-architecture/tasks.md +8 -0
  75. package/openspec/changes/feat-per-task-timeout/proposal.md +25 -0
  76. package/openspec/changes/feat-per-task-timeout/tasks.md +27 -0
  77. package/package.json +1 -1
  78. package/src/TaskRunner.ts +123 -4
  79. package/src/TaskRunnerBuilder.ts +76 -0
  80. package/src/TaskRunnerExecutionConfig.ts +18 -0
  81. package/src/TaskStateManager.ts +142 -0
  82. package/src/TaskStatus.ts +1 -1
  83. package/src/TaskStep.ts +2 -1
  84. package/src/WorkflowExecutor.ts +77 -83
  85. package/src/index.ts +4 -0
  86. package/src/strategies/DryRunExecutionStrategy.ts +31 -0
  87. package/src/strategies/IExecutionStrategy.ts +21 -0
  88. package/src/strategies/StandardExecutionStrategy.ts +35 -0
  89. package/test-report.xml +139 -45
  90. package/GEMINI.md +0 -48
  91. package/openspec/changes/add-external-task-cancellation/tasks.md +0 -10
  92. /package/openspec/changes/{add-external-task-cancellation → archive/2026-01-18-add-external-task-cancellation}/proposal.md +0 -0
package/src/TaskRunner.ts CHANGED
@@ -5,9 +5,14 @@ import { TaskGraph } from "./TaskGraph.js";
5
5
  import { RunnerEventPayloads, RunnerEventListener } from "./contracts/RunnerEvents.js";
6
6
  import { EventBus } from "./EventBus.js";
7
7
  import { WorkflowExecutor } from "./WorkflowExecutor.js";
8
+ import { TaskRunnerExecutionConfig } from "./TaskRunnerExecutionConfig.js";
9
+ import { TaskStateManager } from "./TaskStateManager.js";
10
+ import { IExecutionStrategy } from "./strategies/IExecutionStrategy.js";
11
+ import { StandardExecutionStrategy } from "./strategies/StandardExecutionStrategy.js";
12
+ import { DryRunExecutionStrategy } from "./strategies/DryRunExecutionStrategy.js";
8
13
 
9
14
  // Re-export types for backward compatibility
10
- export { RunnerEventPayloads, RunnerEventListener };
15
+ export { RunnerEventPayloads, RunnerEventListener, TaskRunnerExecutionConfig };
11
16
 
12
17
  /**
13
18
  * The main class that orchestrates the execution of a list of tasks
@@ -17,6 +22,7 @@ export { RunnerEventPayloads, RunnerEventListener };
17
22
  export class TaskRunner<TContext> {
18
23
  private eventBus = new EventBus<TContext>();
19
24
  private validator = new TaskGraphValidator();
25
+ private executionStrategy: IExecutionStrategy<TContext> = new StandardExecutionStrategy();
20
26
 
21
27
  /**
22
28
  * @param context The shared context object to be passed to each task.
@@ -44,17 +50,81 @@ export class TaskRunner<TContext> {
44
50
  event: K,
45
51
  callback: RunnerEventListener<TContext, K>
46
52
  ): void {
53
+ /* v8 ignore next 1 */
47
54
  this.eventBus.off(event, callback);
48
55
  }
49
56
 
57
+ /**
58
+ * Sets the execution strategy to be used.
59
+ * @param strategy The execution strategy.
60
+ * @returns The TaskRunner instance for chaining.
61
+ */
62
+ public setExecutionStrategy(strategy: IExecutionStrategy<TContext>): this {
63
+ /* v8 ignore next 2 */
64
+ this.executionStrategy = strategy;
65
+ return this;
66
+ }
67
+
68
+ /**
69
+ * Generates a Mermaid.js graph representation of the task workflow.
70
+ * @param steps The list of tasks to visualize.
71
+ * @returns A string containing the Mermaid graph definition.
72
+ */
73
+ public static getMermaidGraph<T>(steps: TaskStep<T>[]): string {
74
+ const graphLines = ["graph TD"];
75
+
76
+ // Helper to sanitize node names or wrap them if needed
77
+ // For simplicity, we just wrap in quotes and use the name as ID if it's simple
78
+ // or generate an ID if strictly needed. Here we assume names are unique IDs.
79
+ // We will wrap names in quotes for the label, but use the name as the ID.
80
+ // Actually, Mermaid ID cannot have spaces without quotes.
81
+ const safeId = (name: string) => JSON.stringify(name);
82
+ const sanitize = (name: string) => this.sanitizeMermaidId(name);
83
+
84
+
85
+ // Add all nodes first to ensure they exist
86
+ for (const step of steps) {
87
+ // Using the name as both ID and Label for simplicity
88
+ // Format: ID["Label"]
89
+ // safeId returns a quoted string (e.g. "Task Name"), so we use it directly as the label
90
+ graphLines.push(` ${sanitize(step.name)}[${safeId(step.name)}]`);
91
+ }
92
+
93
+ // Add edges
94
+ for (const step of steps) {
95
+ if (step.dependencies) {
96
+ for (const dep of step.dependencies) {
97
+ graphLines.push(
98
+ ` ${sanitize(dep)} --> ${sanitize(step.name)}`
99
+ );
100
+ }
101
+ }
102
+ }
103
+
104
+ return [...new Set(graphLines)].join("\n");
105
+ }
106
+
107
+ /**
108
+ * Sanitizes a string for use as a Mermaid node ID.
109
+ * @param id The string to sanitize.
110
+ * @returns The sanitized string.
111
+ */
112
+ private static sanitizeMermaidId(id: string): string {
113
+ return id.replaceAll(/ /g, "_").replaceAll(/:/g, "_").replaceAll(/"/g, "_");
114
+ }
115
+
50
116
  /**
51
117
  * Executes a list of tasks, respecting their dependencies and running
52
118
  * independent tasks in parallel.
53
119
  * @param steps An array of TaskStep objects to be executed.
120
+ * @param config Optional configuration for execution (timeout, cancellation).
54
121
  * @returns A Promise that resolves to a Map where keys are task names
55
122
  * and values are the corresponding TaskResult objects.
56
123
  */
57
- async execute(steps: TaskStep<TContext>[]): Promise<Map<string, TaskResult>> {
124
+ async execute(
125
+ steps: TaskStep<TContext>[],
126
+ config?: TaskRunnerExecutionConfig
127
+ ): Promise<Map<string, TaskResult>> {
58
128
  // Validate the task graph before execution
59
129
  const taskGraph: TaskGraph = {
60
130
  tasks: steps.map((step) => ({
@@ -68,7 +138,56 @@ export class TaskRunner<TContext> {
68
138
  throw new Error(this.validator.createErrorMessage(validationResult));
69
139
  }
70
140
 
71
- const executor = new WorkflowExecutor(this.context, this.eventBus);
72
- return executor.execute(steps);
141
+ const stateManager = new TaskStateManager(this.eventBus);
142
+
143
+ let strategy = this.executionStrategy;
144
+ if (config?.dryRun) {
145
+ strategy = new DryRunExecutionStrategy<TContext>();
146
+ }
147
+
148
+ const executor = new WorkflowExecutor(
149
+ this.context,
150
+ this.eventBus,
151
+ stateManager,
152
+ strategy
153
+ );
154
+
155
+ // We need to handle the timeout cleanup properly.
156
+ if (config?.timeout !== undefined) {
157
+ const controller = new AbortController();
158
+ const timeoutId = setTimeout(() => {
159
+ controller.abort(new Error(`Workflow timed out after ${config.timeout}ms`));
160
+ }, config.timeout);
161
+
162
+ let effectiveSignal = controller.signal;
163
+ let onAbort: (() => void) | undefined;
164
+
165
+ // Handle combination of signals if user provided one
166
+ if (config.signal) {
167
+ if (config.signal.aborted) {
168
+ // If already aborted, use it directly (WorkflowExecutor handles early abort)
169
+ // We can cancel timeout immediately
170
+ clearTimeout(timeoutId);
171
+ effectiveSignal = config.signal;
172
+ } else {
173
+ // Listen to user signal to abort our controller
174
+ onAbort = () => {
175
+ controller.abort(config.signal?.reason);
176
+ };
177
+ config.signal.addEventListener("abort", onAbort);
178
+ }
179
+ }
180
+
181
+ try {
182
+ return await executor.execute(steps, effectiveSignal);
183
+ } finally {
184
+ clearTimeout(timeoutId);
185
+ if (config.signal && onAbort) {
186
+ config.signal.removeEventListener("abort", onAbort);
187
+ }
188
+ }
189
+ } else {
190
+ return executor.execute(steps, config?.signal);
191
+ }
73
192
  }
74
193
  }
@@ -0,0 +1,76 @@
1
+ import { TaskRunner } from "./TaskRunner.js";
2
+ import { RunnerEventPayloads, RunnerEventListener } from "./contracts/RunnerEvents.js";
3
+ import { IExecutionStrategy } from "./strategies/IExecutionStrategy.js";
4
+
5
+ /**
6
+ * A builder for configuring and creating TaskRunner instances.
7
+ */
8
+ export class TaskRunnerBuilder<TContext> {
9
+ private context: TContext;
10
+ private strategy?: IExecutionStrategy<TContext>;
11
+ private listeners: {
12
+ [K in keyof RunnerEventPayloads<TContext>]?: RunnerEventListener<TContext, K>[];
13
+ } = {};
14
+
15
+ /**
16
+ * @param context The shared context object.
17
+ */
18
+ constructor(context: TContext) {
19
+ this.context = context;
20
+ }
21
+
22
+ /**
23
+ * Sets the execution strategy.
24
+ * @param strategy The execution strategy to use.
25
+ * @returns The builder instance.
26
+ */
27
+ public useStrategy(strategy: IExecutionStrategy<TContext>): this {
28
+ this.strategy = strategy;
29
+ return this;
30
+ }
31
+
32
+ /**
33
+ * Adds an event listener.
34
+ * @param event The event name.
35
+ * @param callback The callback to execute.
36
+ * @returns The builder instance.
37
+ */
38
+ public on<K extends keyof RunnerEventPayloads<TContext>>(
39
+ event: K,
40
+ callback: RunnerEventListener<TContext, K>
41
+ ): this {
42
+ if (!this.listeners[event]) {
43
+ this.listeners[event] = [];
44
+ }
45
+ this.listeners[event]!.push(callback);
46
+ return this;
47
+ }
48
+
49
+ /**
50
+ * Builds the TaskRunner instance.
51
+ * @returns A configured TaskRunner.
52
+ */
53
+ public build(): TaskRunner<TContext> {
54
+ const runner = new TaskRunner(this.context);
55
+
56
+ if (this.strategy) {
57
+ runner.setExecutionStrategy(this.strategy);
58
+ }
59
+
60
+ (Object.keys(this.listeners) as Array<keyof RunnerEventPayloads<TContext>>).forEach((event) => {
61
+ const callbacks = this.listeners[event];
62
+ // callbacks is always defined because we are iterating keys of the object
63
+ callbacks!.forEach((callback) =>
64
+ runner.on(
65
+ event,
66
+ callback as unknown as RunnerEventListener<
67
+ TContext,
68
+ keyof RunnerEventPayloads<TContext>
69
+ >
70
+ )
71
+ );
72
+ });
73
+
74
+ return runner;
75
+ }
76
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Configuration options for TaskRunner execution.
3
+ */
4
+ export interface TaskRunnerExecutionConfig {
5
+ /**
6
+ * An AbortSignal to cancel the workflow externally.
7
+ */
8
+ signal?: AbortSignal;
9
+ /**
10
+ * A timeout in milliseconds for the entire workflow.
11
+ */
12
+ timeout?: number;
13
+ /**
14
+ * If true, the runner will simulate execution without running the actual tasks.
15
+ * Useful for verifying the execution order and graph structure.
16
+ */
17
+ dryRun?: boolean;
18
+ }
@@ -0,0 +1,142 @@
1
+ import { TaskStep } from "./TaskStep.js";
2
+ import { TaskResult } from "./TaskResult.js";
3
+ import { EventBus } from "./EventBus.js";
4
+
5
+ /**
6
+ * Manages the state of the task execution, including results, pending steps, and running tasks.
7
+ * Handles dependency resolution and event emission for state changes.
8
+ */
9
+ export class TaskStateManager<TContext> {
10
+ private results = new Map<string, TaskResult>();
11
+ private pendingSteps = new Set<TaskStep<TContext>>();
12
+ private running = new Set<string>();
13
+
14
+ constructor(private eventBus: EventBus<TContext>) {}
15
+
16
+ /**
17
+ * Initializes the state with the given steps.
18
+ * @param steps The steps to execute.
19
+ */
20
+ initialize(steps: TaskStep<TContext>[]): void {
21
+ this.pendingSteps = new Set(steps);
22
+ this.results.clear();
23
+ this.running.clear();
24
+ }
25
+
26
+ /**
27
+ * Processes the pending steps to identify tasks that can be started or must be skipped.
28
+ * Emits `taskSkipped` for skipped tasks.
29
+ * @returns An array of tasks that are ready to run.
30
+ */
31
+ processDependencies(): TaskStep<TContext>[] {
32
+ const toRemove: TaskStep<TContext>[] = [];
33
+ const toRun: TaskStep<TContext>[] = [];
34
+
35
+ for (const step of this.pendingSteps) {
36
+ const deps = step.dependencies ?? [];
37
+ let blocked = false;
38
+ let failedDep: string | undefined;
39
+
40
+ for (const dep of deps) {
41
+ const depResult = this.results.get(dep);
42
+ if (!depResult) {
43
+ // Dependency not finished yet
44
+ blocked = true;
45
+ } else if (depResult.status !== "success") {
46
+ failedDep = dep;
47
+ break;
48
+ }
49
+ }
50
+
51
+ if (failedDep) {
52
+ const depResult = this.results.get(failedDep);
53
+ const depError = depResult?.error ? `: ${depResult.error}` : "";
54
+ const result: TaskResult = {
55
+ status: "skipped",
56
+ message: `Skipped because dependency '${failedDep}' failed${depError}`,
57
+ };
58
+ this.results.set(step.name, result);
59
+ this.eventBus.emit("taskSkipped", { step, result });
60
+ toRemove.push(step);
61
+ } else if (!blocked) {
62
+ toRun.push(step);
63
+ toRemove.push(step);
64
+ }
65
+ }
66
+
67
+ // Cleanup pending set
68
+ for (const step of toRemove) {
69
+ this.pendingSteps.delete(step);
70
+ }
71
+
72
+ return toRun;
73
+ }
74
+
75
+ /**
76
+ * Marks a task as running and emits `taskStart`.
77
+ * @param step The task that is starting.
78
+ */
79
+ markRunning(step: TaskStep<TContext>): void {
80
+ this.running.add(step.name);
81
+ this.eventBus.emit("taskStart", { step });
82
+ }
83
+
84
+ /**
85
+ * Marks a task as completed (success, failure, or cancelled during execution)
86
+ * and emits `taskEnd`.
87
+ * @param step The task that completed.
88
+ * @param result The result of the task.
89
+ */
90
+ markCompleted(step: TaskStep<TContext>, result: TaskResult): void {
91
+ this.running.delete(step.name);
92
+ this.results.set(step.name, result);
93
+ this.eventBus.emit("taskEnd", { step, result });
94
+ }
95
+
96
+ /**
97
+ * Cancels all pending tasks that haven't started yet.
98
+ * @param message The cancellation message.
99
+ */
100
+ cancelAllPending(message: string): void {
101
+ // Iterate over pendingSteps to cancel them
102
+ for (const step of this.pendingSteps) {
103
+ // Also check running? No, running tasks are handled by AbortSignal in Executor.
104
+ // We only cancel what is pending and hasn't started.
105
+ /* v8 ignore next 1 */
106
+ if (!this.results.has(step.name) && !this.running.has(step.name)) {
107
+ const result: TaskResult = {
108
+ status: "cancelled",
109
+ message,
110
+ };
111
+ this.results.set(step.name, result);
112
+ }
113
+ }
114
+ // Clear pending set as they are now "done" (cancelled)
115
+ // Wait, if we clear pending steps, processDependencies won't pick them up.
116
+ // The loop in Executor relies on results.size or pendingSteps.
117
+ // The previous implementation iterated `steps` (all steps) to cancel.
118
+ // Here we iterate `pendingSteps`.
119
+ this.pendingSteps.clear();
120
+ }
121
+
122
+ /**
123
+ * Returns the current results map.
124
+ */
125
+ getResults(): Map<string, TaskResult> {
126
+ return this.results;
127
+ }
128
+
129
+ /**
130
+ * Checks if there are any tasks currently running.
131
+ */
132
+ hasRunningTasks(): boolean {
133
+ return this.running.size > 0;
134
+ }
135
+
136
+ /**
137
+ * Checks if there are any pending tasks.
138
+ */
139
+ hasPendingTasks(): boolean {
140
+ return this.pendingSteps.size > 0;
141
+ }
142
+ }
package/src/TaskStatus.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  /**
2
2
  * Represents the completion status of a task.
3
3
  */
4
- export type TaskStatus = "success" | "failure" | "skipped";
4
+ export type TaskStatus = "success" | "failure" | "skipped" | "cancelled";
package/src/TaskStep.ts CHANGED
@@ -12,7 +12,8 @@ export interface TaskStep<TContext> {
12
12
  /**
13
13
  * The core logic of the task.
14
14
  * @param context The shared context object, allowing for state to be passed between tasks.
15
+ * @param signal An optional AbortSignal to listen for cancellation.
15
16
  * @returns A Promise that resolves to a TaskResult.
16
17
  */
17
- run(context: TContext): Promise<TaskResult>;
18
+ run(context: TContext, signal?: AbortSignal): Promise<TaskResult>;
18
19
  }
@@ -1,126 +1,120 @@
1
1
  import { TaskStep } from "./TaskStep.js";
2
2
  import { TaskResult } from "./TaskResult.js";
3
3
  import { EventBus } from "./EventBus.js";
4
+ import { TaskStateManager } from "./TaskStateManager.js";
5
+ import { IExecutionStrategy } from "./strategies/IExecutionStrategy.js";
4
6
 
5
7
  /**
6
8
  * Handles the execution of the workflow steps.
7
9
  * @template TContext The shape of the shared context object.
8
10
  */
9
11
  export class WorkflowExecutor<TContext> {
10
- private running = new Set<string>();
11
-
12
12
  /**
13
13
  * @param context The shared context object.
14
14
  * @param eventBus The event bus to emit events.
15
+ * @param stateManager Manages execution state.
16
+ * @param strategy Execution strategy.
15
17
  */
16
18
  constructor(
17
19
  private context: TContext,
18
- private eventBus: EventBus<TContext>
20
+ private eventBus: EventBus<TContext>,
21
+ private stateManager: TaskStateManager<TContext>,
22
+ private strategy: IExecutionStrategy<TContext>
19
23
  ) {}
20
24
 
21
25
  /**
22
26
  * Executes the given steps.
23
27
  * @param steps The list of steps to execute.
28
+ * @param signal Optional AbortSignal for cancellation.
24
29
  * @returns A Promise that resolves to a map of task results.
25
30
  */
26
- async execute(steps: TaskStep<TContext>[]): Promise<Map<string, TaskResult>> {
31
+ async execute(
32
+ steps: TaskStep<TContext>[],
33
+ signal?: AbortSignal
34
+ ): Promise<Map<string, TaskResult>> {
27
35
  this.eventBus.emit("workflowStart", { context: this.context, steps });
36
+ this.stateManager.initialize(steps);
37
+
38
+ // Check if already aborted
39
+ if (signal?.aborted) {
40
+ this.stateManager.cancelAllPending("Workflow cancelled before execution started.");
41
+ const results = this.stateManager.getResults();
42
+ this.eventBus.emit("workflowEnd", { context: this.context, results });
43
+ return results;
44
+ }
28
45
 
29
- const results = new Map<string, TaskResult>();
30
46
  const executingPromises = new Set<Promise<void>>();
31
47
 
32
- // Initial pass
33
- this.processQueue(steps, results, executingPromises);
48
+ const onAbort = () => {
49
+ // Mark all pending tasks as cancelled
50
+ this.stateManager.cancelAllPending("Workflow cancelled.");
51
+ };
34
52
 
35
- while (results.size < steps.length && executingPromises.size > 0) {
36
- // Wait for the next task to finish
37
- await Promise.race(executingPromises);
38
- // After a task finishes, check for new work
39
- this.processQueue(steps, results, executingPromises);
53
+ if (signal) {
54
+ signal.addEventListener("abort", onAbort);
40
55
  }
41
56
 
42
- this.eventBus.emit("workflowEnd", { context: this.context, results });
43
- return results;
44
- }
45
-
46
- /**
47
- * Logic to identify tasks that can be started or must be skipped.
48
- */
49
- private processQueue(
50
- steps: TaskStep<TContext>[],
51
- results: Map<string, TaskResult>,
52
- executingPromises: Set<Promise<void>>
53
- ): void {
54
- this.handleSkippedTasks(steps, results);
55
-
56
- const readySteps = this.getReadySteps(steps, results);
57
-
58
- for (const step of readySteps) {
59
- const taskPromise = this.runStep(step, results).then(() => {
60
- executingPromises.delete(taskPromise);
61
- });
62
- executingPromises.add(taskPromise);
63
- }
64
- }
65
-
66
- /**
67
- * Identifies steps that cannot run because a dependency failed.
68
- */
69
- private handleSkippedTasks(steps: TaskStep<TContext>[], results: Map<string, TaskResult>): void {
70
- const pendingSteps = steps.filter(
71
- (step) => !results.has(step.name) && !this.running.has(step.name)
72
- );
57
+ try {
58
+ // Initial pass
59
+ this.processLoop(executingPromises, signal);
60
+
61
+ while (
62
+ this.stateManager.hasPendingTasks() ||
63
+ this.stateManager.hasRunningTasks()
64
+ ) {
65
+ // Safety check: if no tasks are running and we still have pending tasks,
66
+ // it means we are stuck (e.g. cycle or unhandled dependency).
67
+ // Since valid graphs shouldn't have this, we break to avoid infinite loop.
68
+ if (executingPromises.size === 0) {
69
+ break;
70
+ } else {
71
+ // Wait for the next task to finish
72
+ await Promise.race(executingPromises);
73
+ }
74
+
75
+ if (signal?.aborted) {
76
+ this.stateManager.cancelAllPending("Workflow cancelled.");
77
+ } else {
78
+ // After a task finishes, check for new work
79
+ this.processLoop(executingPromises, signal);
80
+ }
81
+ }
73
82
 
74
- for (const step of pendingSteps) {
75
- const deps = step.dependencies ?? [];
76
- const failedDep = deps.find(
77
- (dep) => results.has(dep) && results.get(dep)?.status !== "success"
78
- );
83
+ // Ensure everything is accounted for (e.g. if loop exited early)
84
+ this.stateManager.cancelAllPending("Workflow cancelled.");
79
85
 
80
- if (failedDep) {
81
- const result: TaskResult = {
82
- status: "skipped",
83
- message: `Skipped due to failed dependency: ${failedDep}`,
84
- };
85
- results.set(step.name, result);
86
- this.eventBus.emit("taskSkipped", { step, result });
86
+ const results = this.stateManager.getResults();
87
+ this.eventBus.emit("workflowEnd", { context: this.context, results });
88
+ return results;
89
+ } finally {
90
+ if (signal) {
91
+ signal.removeEventListener("abort", onAbort);
87
92
  }
88
93
  }
89
94
  }
90
95
 
91
96
  /**
92
- * Returns steps where all dependencies have finished successfully.
97
+ * Logic to identify tasks that can be started and run them.
93
98
  */
94
- private getReadySteps(steps: TaskStep<TContext>[], results: Map<string, TaskResult>): TaskStep<TContext>[] {
95
- return steps.filter((step) => {
96
- if (results.has(step.name) || this.running.has(step.name)) return false;
99
+ private processLoop(
100
+ executingPromises: Set<Promise<void>>,
101
+ signal?: AbortSignal
102
+ ): void {
103
+ const toRun = this.stateManager.processDependencies();
97
104
 
98
- const deps = step.dependencies ?? [];
99
- return deps.every(
100
- (dep) => results.has(dep) && results.get(dep)?.status === "success"
101
- );
102
- });
103
- }
105
+ // Execute ready tasks
106
+ for (const step of toRun) {
107
+ this.stateManager.markRunning(step);
104
108
 
105
- /**
106
- * Handles the lifecycle of a single task execution.
107
- */
108
- private async runStep(step: TaskStep<TContext>, results: Map<string, TaskResult>): Promise<void> {
109
- this.running.add(step.name);
110
- this.eventBus.emit("taskStart", { step });
109
+ const taskPromise = this.strategy.execute(step, this.context, signal)
110
+ .then((result) => {
111
+ this.stateManager.markCompleted(step, result);
112
+ })
113
+ .finally(() => {
114
+ executingPromises.delete(taskPromise);
115
+ });
111
116
 
112
- try {
113
- const result = await step.run(this.context);
114
- results.set(step.name, result);
115
- } catch (e) {
116
- results.set(step.name, {
117
- status: "failure",
118
- error: e instanceof Error ? e.message : String(e),
119
- });
120
- } finally {
121
- this.running.delete(step.name);
122
- const result = results.get(step.name)!;
123
- this.eventBus.emit("taskEnd", { step, result });
117
+ executingPromises.add(taskPromise);
124
118
  }
125
119
  }
126
120
  }
package/src/index.ts CHANGED
@@ -1,4 +1,8 @@
1
1
  export { TaskRunner } from "./TaskRunner.js";
2
+ export { TaskRunnerBuilder } from "./TaskRunnerBuilder.js";
3
+ export { TaskStateManager } from "./TaskStateManager.js";
4
+ export { StandardExecutionStrategy } from "./strategies/StandardExecutionStrategy.js";
5
+ export type { IExecutionStrategy } from "./strategies/IExecutionStrategy.js";
2
6
  export type { TaskStep } from "./TaskStep.js";
3
7
  export type { TaskResult } from "./TaskResult.js";
4
8
  export type { TaskStatus } from "./TaskStatus.js";
@@ -0,0 +1,31 @@
1
+ import { IExecutionStrategy } from "./IExecutionStrategy.js";
2
+ import { TaskStep } from "../TaskStep.js";
3
+ import { TaskResult } from "../TaskResult.js";
4
+
5
+ /**
6
+ * Execution strategy that simulates task execution without running the actual logic.
7
+ */
8
+ export class DryRunExecutionStrategy<TContext>
9
+ implements IExecutionStrategy<TContext>
10
+ {
11
+ /**
12
+ * Simulates execution by returning a success result immediately.
13
+ * @param step The task step (ignored).
14
+ * @param context The shared context (ignored).
15
+ * @param signal Optional abort signal (ignored).
16
+ * @returns A promise resolving to a success result.
17
+ */
18
+ async execute(
19
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
20
+ _step: TaskStep<TContext>,
21
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
22
+ _context: TContext,
23
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
24
+ _signal?: AbortSignal
25
+ ): Promise<TaskResult> {
26
+ return Promise.resolve({
27
+ status: "success",
28
+ message: "Dry run: simulated success",
29
+ });
30
+ }
31
+ }