@calmo/task-runner 4.0.4 → 4.2.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 (91) hide show
  1. package/.github/workflows/codeql.yml +1 -1
  2. package/.github/workflows/release-please.yml +2 -2
  3. package/.jules/nexus.md +10 -0
  4. package/.release-please-manifest.json +1 -1
  5. package/AGENTS.md +3 -0
  6. package/CHANGELOG.md +46 -0
  7. package/CODE_OF_CONDUCT.md +131 -0
  8. package/CONTRIBUTING.md +89 -0
  9. package/README.md +34 -0
  10. package/conductor/code_styleguides/general.md +23 -0
  11. package/conductor/code_styleguides/javascript.md +51 -0
  12. package/conductor/code_styleguides/typescript.md +43 -0
  13. package/conductor/product-guidelines.md +14 -0
  14. package/conductor/product.md +16 -0
  15. package/conductor/setup_state.json +1 -0
  16. package/conductor/tech-stack.md +19 -0
  17. package/conductor/workflow.md +334 -0
  18. package/dist/EventBus.js +16 -16
  19. package/dist/EventBus.js.map +1 -1
  20. package/dist/PluginManager.d.ts +22 -0
  21. package/dist/PluginManager.js +39 -0
  22. package/dist/PluginManager.js.map +1 -0
  23. package/dist/TaskGraphValidator.d.ts +1 -1
  24. package/dist/TaskGraphValidator.js +16 -21
  25. package/dist/TaskGraphValidator.js.map +1 -1
  26. package/dist/TaskResult.d.ts +9 -0
  27. package/dist/TaskRunner.d.ts +8 -1
  28. package/dist/TaskRunner.js +64 -41
  29. package/dist/TaskRunner.js.map +1 -1
  30. package/dist/TaskStateManager.d.ts +22 -6
  31. package/dist/TaskStateManager.js +105 -45
  32. package/dist/TaskStateManager.js.map +1 -1
  33. package/dist/WorkflowExecutor.js +36 -20
  34. package/dist/WorkflowExecutor.js.map +1 -1
  35. package/dist/contracts/Plugin.d.ts +30 -0
  36. package/dist/contracts/Plugin.js +2 -0
  37. package/dist/contracts/Plugin.js.map +1 -0
  38. package/dist/strategies/DryRunExecutionStrategy.d.ts +1 -1
  39. package/dist/strategies/DryRunExecutionStrategy.js +2 -4
  40. package/dist/strategies/DryRunExecutionStrategy.js.map +1 -1
  41. package/dist/utils/PriorityQueue.d.ts +13 -0
  42. package/dist/utils/PriorityQueue.js +82 -0
  43. package/dist/utils/PriorityQueue.js.map +1 -0
  44. package/openspec/changes/add-middleware-support/proposal.md +19 -0
  45. package/openspec/changes/add-middleware-support/specs/task-runner/spec.md +34 -0
  46. package/openspec/changes/add-middleware-support/tasks.md +9 -0
  47. package/openspec/changes/add-resource-concurrency/proposal.md +18 -0
  48. package/openspec/changes/add-resource-concurrency/specs/task-runner/spec.md +25 -0
  49. package/openspec/changes/add-resource-concurrency/tasks.md +10 -0
  50. package/openspec/changes/allow-plugin-hooks/design.md +51 -0
  51. package/openspec/changes/allow-plugin-hooks/proposal.md +12 -0
  52. package/openspec/changes/allow-plugin-hooks/specs/post-task/spec.md +21 -0
  53. package/openspec/changes/allow-plugin-hooks/specs/pre-task/spec.md +32 -0
  54. package/openspec/changes/allow-plugin-hooks/tasks.md +7 -0
  55. package/openspec/changes/{feat-task-metrics → archive/2026-01-22-feat-task-metrics}/proposal.md +1 -1
  56. package/openspec/changes/archive/2026-01-22-feat-task-metrics/tasks.md +6 -0
  57. package/openspec/changes/archive/2026-02-15-implement-plugin-system/design.md +45 -0
  58. package/openspec/changes/archive/2026-02-15-implement-plugin-system/proposal.md +13 -0
  59. package/openspec/changes/archive/2026-02-15-implement-plugin-system/specs/plugin-context/spec.md +17 -0
  60. package/openspec/changes/archive/2026-02-15-implement-plugin-system/specs/plugin-loading/spec.md +27 -0
  61. package/openspec/changes/archive/2026-02-15-implement-plugin-system/tasks.md +7 -0
  62. package/openspec/changes/feat-completion-dependencies/proposal.md +58 -0
  63. package/openspec/changes/feat-completion-dependencies/tasks.md +46 -0
  64. package/openspec/changes/feat-conditional-retries/proposal.md +18 -0
  65. package/openspec/changes/feat-conditional-retries/specs/task-runner/spec.md +23 -0
  66. package/openspec/changes/feat-conditional-retries/tasks.md +37 -0
  67. package/openspec/changes/feat-state-persistence/specs/task-runner/spec.md +47 -0
  68. package/openspec/changes/feat-task-loop/proposal.md +22 -0
  69. package/openspec/changes/feat-task-loop/specs/task-runner/spec.md +34 -0
  70. package/openspec/changes/feat-task-loop/tasks.md +8 -0
  71. package/openspec/specs/plugin-context/spec.md +19 -0
  72. package/openspec/specs/plugin-loading/spec.md +29 -0
  73. package/openspec/specs/release-pr/spec.md +31 -0
  74. package/openspec/specs/task-runner/spec.md +12 -0
  75. package/package.json +1 -1
  76. package/src/EventBus.ts +7 -8
  77. package/src/PluginManager.ts +41 -0
  78. package/src/TaskGraphValidator.ts +22 -24
  79. package/src/TaskResult.ts +9 -0
  80. package/src/TaskRunner.ts +78 -46
  81. package/src/TaskStateManager.ts +118 -46
  82. package/src/WorkflowExecutor.ts +45 -22
  83. package/src/contracts/Plugin.ts +32 -0
  84. package/src/strategies/DryRunExecutionStrategy.ts +2 -3
  85. package/src/utils/PriorityQueue.ts +101 -0
  86. package/openspec/changes/feat-task-metrics/tasks.md +0 -6
  87. /package/openspec/changes/{adopt-release-pr → archive/2026-01-22-adopt-release-pr}/design.md +0 -0
  88. /package/openspec/changes/{adopt-release-pr → archive/2026-01-22-adopt-release-pr}/proposal.md +0 -0
  89. /package/openspec/changes/{adopt-release-pr → archive/2026-01-22-adopt-release-pr}/specs/release-pr/spec.md +0 -0
  90. /package/openspec/changes/{adopt-release-pr → archive/2026-01-22-adopt-release-pr}/tasks.md +0 -0
  91. /package/openspec/changes/{feat-task-metrics → archive/2026-01-22-feat-task-metrics}/specs/001-generic-task-runner/spec.md +0 -0
package/src/TaskRunner.ts CHANGED
@@ -14,11 +14,10 @@ import { TaskGraphValidationError } from "./TaskGraphValidationError.js";
14
14
  import { IExecutionStrategy } from "./strategies/IExecutionStrategy.js";
15
15
  import { StandardExecutionStrategy } from "./strategies/StandardExecutionStrategy.js";
16
16
  import { RetryingExecutionStrategy } from "./strategies/RetryingExecutionStrategy.js";
17
+ import { Plugin } from "./contracts/Plugin.js";
18
+ import { PluginManager } from "./PluginManager.js";
17
19
  import { DryRunExecutionStrategy } from "./strategies/DryRunExecutionStrategy.js";
18
20
 
19
- // Re-export types for backward compatibility
20
- export { RunnerEventPayloads, RunnerEventListener, TaskRunnerExecutionConfig };
21
-
22
21
  /**
23
22
  * The main class that orchestrates the execution of a list of tasks
24
23
  * based on their dependencies, with support for parallel execution.
@@ -30,10 +29,14 @@ export class TaskRunner<TContext> {
30
29
  private executionStrategy: IExecutionStrategy<TContext> =
31
30
  new RetryingExecutionStrategy(new StandardExecutionStrategy());
32
31
 
32
+ private pluginManager: PluginManager<TContext>;
33
+
33
34
  /**
34
35
  * @param context The shared context object to be passed to each task.
35
36
  */
36
- constructor(private context: TContext) {}
37
+ constructor(private context: TContext) {
38
+ this.pluginManager = new PluginManager({ events: this.eventBus });
39
+ }
37
40
 
38
41
  /**
39
42
  * Subscribe to an event.
@@ -56,17 +59,25 @@ export class TaskRunner<TContext> {
56
59
  event: K,
57
60
  callback: RunnerEventListener<TContext, K>
58
61
  ): void {
59
- /* v8 ignore next 1 */
60
62
  this.eventBus.off(event, callback);
61
63
  }
62
64
 
65
+ /**
66
+ * Registers a plugin.
67
+ * @param plugin The plugin to register.
68
+ * @returns The TaskRunner instance for chaining.
69
+ */
70
+ public use(plugin: Plugin<TContext>): this {
71
+ this.pluginManager.use(plugin);
72
+ return this;
73
+ }
74
+
63
75
  /**
64
76
  * Sets the execution strategy to be used.
65
77
  * @param strategy The execution strategy.
66
78
  * @returns The TaskRunner instance for chaining.
67
79
  */
68
80
  public setExecutionStrategy(strategy: IExecutionStrategy<TContext>): this {
69
- /* v8 ignore next 2 */
70
81
  this.executionStrategy = strategy;
71
82
  return this;
72
83
  }
@@ -77,25 +88,64 @@ export class TaskRunner<TContext> {
77
88
  * @returns A string containing the Mermaid graph definition.
78
89
  */
79
90
  public static getMermaidGraph<T>(steps: TaskStep<T>[]): string {
80
- const graphLines = ["graph TD"];
91
+ const graphLines = new Set<string>(["graph TD"]);
92
+ const idMap = new Map<string, string>();
93
+ const usedIds = new Set<string>();
94
+ const baseIdCounters = new Map<string, number>();
95
+
96
+ const getUniqueId = (name: string) => {
97
+ const existingId = idMap.get(name);
98
+ if (existingId !== undefined) {
99
+ return existingId;
100
+ }
81
101
 
82
- const sanitize = (name: string) => this.sanitizeMermaidId(name);
102
+ const sanitized = this.sanitizeMermaidId(name);
103
+ let uniqueId = sanitized;
83
104
 
105
+ // First check if the base sanitized ID is available
106
+ if (!usedIds.has(uniqueId)) {
107
+ usedIds.add(uniqueId);
108
+ idMap.set(name, uniqueId);
109
+ return uniqueId;
110
+ }
111
+
112
+ // If not, use the counter for this base ID
113
+ let counter = baseIdCounters.get(sanitized) || 1;
114
+
115
+ while (usedIds.has(uniqueId)) {
116
+ uniqueId = `${sanitized}_${counter}`;
117
+ counter++;
118
+ }
119
+
120
+ baseIdCounters.set(sanitized, counter);
121
+
122
+ usedIds.add(uniqueId);
123
+ idMap.set(name, uniqueId);
124
+ return uniqueId;
125
+ };
126
+
127
+ // We process nodes in input order to ensure deterministic ID generation
128
+ // (getUniqueId is called for each unique step name in order, populating the cache).
129
+ const processedNamesForNodes = new Set<string>();
84
130
  for (const step of steps) {
85
- graphLines.push(
86
- ` ${sanitize(step.name)}[${JSON.stringify(step.name)}]`
87
- );
131
+ if (!processedNamesForNodes.has(step.name)) {
132
+ const stepId = getUniqueId(step.name);
133
+ graphLines.add(` ${stepId}[${JSON.stringify(step.name)}]`);
134
+ processedNamesForNodes.add(step.name);
135
+ }
88
136
  }
89
137
 
90
138
  for (const step of steps) {
91
139
  if (step.dependencies) {
140
+ const stepId = getUniqueId(step.name);
92
141
  for (const dep of step.dependencies) {
93
- graphLines.push(` ${sanitize(dep)} --> ${sanitize(step.name)}`);
142
+ const depId = getUniqueId(dep);
143
+ graphLines.add(` ${depId} --> ${stepId}`);
94
144
  }
95
145
  }
96
146
  }
97
147
 
98
- return [...new Set(graphLines)].join("\n");
148
+ return [...graphLines].join("\n");
99
149
  }
100
150
 
101
151
  /**
@@ -119,6 +169,9 @@ export class TaskRunner<TContext> {
119
169
  steps: TaskStep<TContext>[],
120
170
  config?: TaskRunnerExecutionConfig
121
171
  ): Promise<Map<string, TaskResult>> {
172
+ // Initialize plugins
173
+ await this.pluginManager.initialize();
174
+
122
175
  // Validate the task graph before execution
123
176
  const taskGraph: TaskGraph = {
124
177
  tasks: steps.map((step) => ({
@@ -157,9 +210,9 @@ export class TaskRunner<TContext> {
157
210
  config.timeout,
158
211
  config.signal
159
212
  );
160
- } else {
161
- return executor.execute(steps, config?.signal);
162
213
  }
214
+
215
+ return executor.execute(steps, config?.signal);
163
216
  }
164
217
 
165
218
  /**
@@ -171,37 +224,16 @@ export class TaskRunner<TContext> {
171
224
  timeout: number,
172
225
  signal?: AbortSignal
173
226
  ): Promise<Map<string, TaskResult>> {
174
- const controller = new AbortController();
175
- const timeoutId = setTimeout(() => {
176
- controller.abort(new Error(`Workflow timed out after ${timeout}ms`));
177
- }, timeout);
178
-
179
- let effectiveSignal = controller.signal;
180
- let onAbort: (() => void) | undefined;
181
-
182
- // Handle combination of signals if user provided one
183
- if (signal) {
184
- if (signal.aborted) {
185
- // If already aborted, use it directly (WorkflowExecutor handles early abort)
186
- // We can cancel timeout immediately
187
- clearTimeout(timeoutId);
188
- effectiveSignal = signal;
189
- } else {
190
- // Listen to user signal to abort our controller
191
- onAbort = () => {
192
- controller.abort(signal.reason);
193
- };
194
- signal.addEventListener("abort", onAbort);
195
- }
196
- }
227
+ // Create a timeout signal that aborts after the specified time
228
+ const timeoutSignal = AbortSignal.timeout(timeout);
197
229
 
198
- try {
199
- return await executor.execute(steps, effectiveSignal);
200
- } finally {
201
- clearTimeout(timeoutId);
202
- if (signal && onAbort) {
203
- signal.removeEventListener("abort", onAbort);
204
- }
205
- }
230
+ // If there's a user-provided signal, combine them.
231
+ // Otherwise, use the timeout signal directly.
232
+ const effectiveSignal = signal
233
+ ? AbortSignal.any([signal, timeoutSignal])
234
+ : timeoutSignal;
235
+
236
+ return executor.execute(steps, effectiveSignal);
237
+ // No explicit clean up needed for AbortSignal.timeout as it is handled by the platform
206
238
  }
207
239
  }
@@ -11,6 +11,11 @@ export class TaskStateManager<TContext> {
11
11
  private pendingSteps = new Set<TaskStep<TContext>>();
12
12
  private running = new Set<string>();
13
13
 
14
+ // Optimization structures
15
+ private dependencyGraph = new Map<string, TaskStep<TContext>[]>();
16
+ private dependencyCounts = new Map<string, number>();
17
+ private readyQueue: TaskStep<TContext>[] = [];
18
+
14
19
  constructor(private eventBus: EventBus<TContext>) {}
15
20
 
16
21
  /**
@@ -21,50 +26,41 @@ export class TaskStateManager<TContext> {
21
26
  this.pendingSteps = new Set(steps);
22
27
  this.results.clear();
23
28
  this.running.clear();
24
- }
29
+ this.readyQueue = [];
25
30
 
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>[] = [];
31
+ this.dependencyGraph.clear();
32
+ this.dependencyCounts.clear();
34
33
 
35
- for (const step of this.pendingSteps) {
34
+ for (const step of steps) {
36
35
  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;
36
+ this.dependencyCounts.set(step.name, deps.length);
37
+
38
+ if (deps.length === 0) {
39
+ this.readyQueue.push(step);
40
+ } else {
41
+ for (const dep of deps) {
42
+ let dependents = this.dependencyGraph.get(dep);
43
+ if (dependents === undefined) {
44
+ dependents = [];
45
+ this.dependencyGraph.set(dep, dependents);
46
+ }
47
+ dependents.push(step);
48
48
  }
49
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.markSkipped(step, result);
59
- toRemove.push(step);
60
- } else if (!blocked) {
61
- toRun.push(step);
62
- toRemove.push(step);
63
- }
64
50
  }
51
+ }
52
+
53
+ /**
54
+ * Processes the pending steps to identify tasks that can be started.
55
+ * Emits `taskSkipped` for skipped tasks (handled during cascade).
56
+ * @returns An array of tasks that are ready to run.
57
+ */
58
+ processDependencies(): TaskStep<TContext>[] {
59
+ const toRun = [...this.readyQueue];
60
+ this.readyQueue = [];
65
61
 
66
- // Cleanup pending set
67
- for (const step of toRemove) {
62
+ // Remove them from pendingSteps as they are now handed off to the executor
63
+ for (const step of toRun) {
68
64
  this.pendingSteps.delete(step);
69
65
  }
70
66
 
@@ -90,6 +86,39 @@ export class TaskStateManager<TContext> {
90
86
  this.running.delete(step.name);
91
87
  this.results.set(step.name, result);
92
88
  this.eventBus.emit("taskEnd", { step, result });
89
+
90
+ if (result.status === "success") {
91
+ this.handleSuccess(step.name);
92
+ } else {
93
+ this.cascadeFailure(step.name);
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Marks a task as skipped and emits `taskSkipped`.
99
+ * @param step The task that was skipped.
100
+ * @param result The result object (status: skipped).
101
+ */
102
+ markSkipped(step: TaskStep<TContext>, result: TaskResult): void {
103
+ if (this.internalMarkSkipped(step, result)) {
104
+ this.cascadeFailure(step.name);
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Internal method to mark skipped without triggering cascade (to be used inside cascade loop).
110
+ * Returns true if the task was actually marked skipped (was not already finished).
111
+ */
112
+ private internalMarkSkipped(step: TaskStep<TContext>, result: TaskResult): boolean {
113
+ if (this.results.has(step.name)) {
114
+ return false;
115
+ }
116
+
117
+ this.running.delete(step.name);
118
+ this.results.set(step.name, result);
119
+ this.pendingSteps.delete(step);
120
+ this.eventBus.emit("taskSkipped", { step, result });
121
+ return true;
93
122
  }
94
123
 
95
124
  /**
@@ -97,10 +126,10 @@ export class TaskStateManager<TContext> {
97
126
  * @param message The cancellation message.
98
127
  */
99
128
  cancelAllPending(message: string): void {
129
+ this.readyQueue = []; // Clear ready queue
130
+
100
131
  // Iterate over pendingSteps to cancel them
101
132
  for (const step of this.pendingSteps) {
102
- // Also check running? No, running tasks are handled by AbortSignal in Executor.
103
- // We only cancel what is pending and hasn't started.
104
133
  if (!this.results.has(step.name) && !this.running.has(step.name)) {
105
134
  const result: TaskResult = {
106
135
  status: "cancelled",
@@ -136,13 +165,56 @@ export class TaskStateManager<TContext> {
136
165
  }
137
166
 
138
167
  /**
139
- * Marks a task as skipped and emits `taskSkipped`.
140
- * @param step The task that was skipped.
141
- * @param result The result object (status: skipped).
168
+ * Handles successful completion of a task by updating dependents.
142
169
  */
143
- markSkipped(step: TaskStep<TContext>, result: TaskResult): void {
144
- this.running.delete(step.name);
145
- this.results.set(step.name, result);
146
- this.eventBus.emit("taskSkipped", { step, result });
170
+ private handleSuccess(stepName: string): void {
171
+ const dependents = this.dependencyGraph.get(stepName);
172
+ if (!dependents) return;
173
+
174
+ for (const dependent of dependents) {
175
+ const currentCount = this.dependencyCounts.get(dependent.name)!;
176
+ const newCount = currentCount - 1;
177
+ this.dependencyCounts.set(dependent.name, newCount);
178
+
179
+ if (newCount === 0) {
180
+ // Task is ready. Ensure it's still pending.
181
+ if (this.pendingSteps.has(dependent)) {
182
+ this.readyQueue.push(dependent);
183
+ }
184
+ }
185
+ }
186
+ }
187
+
188
+ /**
189
+ * Cascades failure/skipping to dependents.
190
+ */
191
+ private cascadeFailure(failedStepName: string): void {
192
+ const queue = [failedStepName];
193
+ // Optimization: Use index pointer instead of shift() to avoid O(N) array re-indexing
194
+ let head = 0;
195
+ // Use a set to track visited nodes in this cascade pass to avoid redundant processing,
196
+ // although checking results.has() in internalMarkSkipped also prevents it.
197
+
198
+ while (head < queue.length) {
199
+ const currentName = queue[head++];
200
+ const dependents = this.dependencyGraph.get(currentName);
201
+
202
+ if (!dependents) continue;
203
+
204
+ // Get the result of the failed/skipped dependency to propagate error info if available
205
+ const currentResult = this.results.get(currentName);
206
+ const depError = currentResult?.error ? `: ${currentResult.error}` : "";
207
+
208
+ for (const dependent of dependents) {
209
+ const result: TaskResult = {
210
+ status: "skipped",
211
+ message: `Skipped because dependency '${currentName}' failed${depError}`,
212
+ };
213
+
214
+ if (this.internalMarkSkipped(dependent, result)) {
215
+ queue.push(dependent.name);
216
+ }
217
+ }
218
+ }
147
219
  }
148
220
  }
@@ -4,13 +4,14 @@ import { EventBus } from "./EventBus.js";
4
4
  import { TaskStateManager } from "./TaskStateManager.js";
5
5
  import { IExecutionStrategy } from "./strategies/IExecutionStrategy.js";
6
6
  import { ExecutionConstants } from "./ExecutionConstants.js";
7
+ import { PriorityQueue } from "./utils/PriorityQueue.js";
7
8
 
8
9
  /**
9
10
  * Handles the execution of the workflow steps.
10
11
  * @template TContext The shape of the shared context object.
11
12
  */
12
13
  export class WorkflowExecutor<TContext> {
13
- private readyQueue: TaskStep<TContext>[] = [];
14
+ private readyQueue = new PriorityQueue<TaskStep<TContext>>();
14
15
 
15
16
  /**
16
17
  * @param context The shared context object.
@@ -62,8 +63,22 @@ export class WorkflowExecutor<TContext> {
62
63
  }
63
64
 
64
65
  try {
66
+ // Create a signal mechanism to wait for any task completion
67
+ let signalResolver!: () => void;
68
+ let signalPromise = new Promise<void>((resolve) => {
69
+ signalResolver = resolve;
70
+ });
71
+
72
+ const signalWork = () => {
73
+ signalResolver();
74
+ // Reset the promise for the next wait
75
+ signalPromise = new Promise<void>((resolve) => {
76
+ signalResolver = resolve;
77
+ });
78
+ };
79
+
65
80
  // Initial pass
66
- this.processLoop(executingPromises, signal);
81
+ this.processLoop(executingPromises, signalWork, signal);
67
82
 
68
83
  while (
69
84
  this.stateManager.hasPendingTasks() ||
@@ -77,16 +92,13 @@ export class WorkflowExecutor<TContext> {
77
92
  break;
78
93
  } else {
79
94
  // Wait for the next task to finish
80
- await Promise.race(executingPromises);
95
+ await signalPromise;
81
96
  }
82
97
 
83
98
  if (signal?.aborted) {
84
99
  this.stateManager.cancelAllPending(
85
100
  ExecutionConstants.WORKFLOW_CANCELLED
86
101
  );
87
- } else {
88
- // After a task finishes, check for new work
89
- this.processLoop(executingPromises, signal);
90
102
  }
91
103
  }
92
104
 
@@ -108,20 +120,18 @@ export class WorkflowExecutor<TContext> {
108
120
  */
109
121
  private processLoop(
110
122
  executingPromises: Set<Promise<void>>,
123
+ signalWork: () => void,
111
124
  signal?: AbortSignal
112
125
  ): void {
113
126
  const newlyReady = this.stateManager.processDependencies();
114
127
 
115
128
  // Add newly ready tasks to the queue
116
129
  for (const task of newlyReady) {
117
- this.readyQueue.push(task);
130
+ this.readyQueue.push(task, task.priority ?? 0);
118
131
  }
119
132
 
120
- // Sort by priority (descending) once after adding new tasks
121
- this.readyQueue.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
122
-
123
133
  // Execute ready tasks while respecting concurrency limit
124
- while (this.readyQueue.length > 0) {
134
+ while (!this.readyQueue.isEmpty()) {
125
135
  if (
126
136
  this.concurrency !== undefined &&
127
137
  executingPromises.size >= this.concurrency
@@ -129,14 +139,15 @@ export class WorkflowExecutor<TContext> {
129
139
  break;
130
140
  }
131
141
 
132
- const step = this.readyQueue.shift()!;
142
+ const step = this.readyQueue.pop()!;
133
143
 
134
- const taskPromise = this.executeTaskStep(step, signal)
135
- .finally(() => {
136
- executingPromises.delete(taskPromise);
137
- // When a task finishes, we try to run more
138
- this.processLoop(executingPromises, signal);
139
- });
144
+ const taskPromise = this.executeTaskStep(step, signal).finally(() => {
145
+ executingPromises.delete(taskPromise);
146
+ // When a task finishes, we try to run more
147
+ this.processLoop(executingPromises, signalWork, signal);
148
+ // Signal that a task has completed
149
+ signalWork();
150
+ });
140
151
 
141
152
  executingPromises.add(taskPromise);
142
153
  }
@@ -194,16 +205,28 @@ export class WorkflowExecutor<TContext> {
194
205
 
195
206
  this.stateManager.markRunning(step);
196
207
 
208
+ const startTime = performance.now();
209
+ let result: TaskResult;
210
+
197
211
  try {
198
- const result = await this.strategy.execute(step, this.context, signal);
199
- this.stateManager.markCompleted(step, result);
212
+ result = await this.strategy.execute(step, this.context, signal);
200
213
  } catch (error) {
201
- const result: TaskResult = {
214
+ result = {
202
215
  status: "failure",
203
216
  message: ExecutionConstants.EXECUTION_STRATEGY_FAILED,
204
217
  error: error instanceof Error ? error.message : String(error),
205
218
  };
206
- this.stateManager.markCompleted(step, result);
207
219
  }
220
+
221
+ const endTime = performance.now();
222
+
223
+ // Always inject metrics to ensure accuracy
224
+ result.metrics = {
225
+ startTime,
226
+ endTime,
227
+ duration: endTime - startTime,
228
+ };
229
+
230
+ this.stateManager.markCompleted(step, result);
208
231
  }
209
232
  }
@@ -0,0 +1,32 @@
1
+ import { EventBus } from "../EventBus.js";
2
+
3
+ /**
4
+ * Context provided to a plugin during installation.
5
+ * exposes capabilities to hook into the runner lifecycle and context.
6
+ */
7
+ export interface PluginContext<TContext> {
8
+ /**
9
+ * The event bus instance to subscribe to runner events.
10
+ */
11
+ events: EventBus<TContext>;
12
+ }
13
+
14
+ /**
15
+ * Interface that all plugins must implement.
16
+ */
17
+ export interface Plugin<TContext> {
18
+ /**
19
+ * Unique name of the plugin.
20
+ */
21
+ name: string;
22
+ /**
23
+ * Semantic version of the plugin.
24
+ */
25
+ version: string;
26
+ /**
27
+ * Called when the plugin is installed into the runner.
28
+ * This is where the plugin should subscribe to events or perform setup.
29
+ * @param context The plugin context exposing runner capabilities.
30
+ */
31
+ install(context: PluginContext<TContext>): void | Promise<void>;
32
+ }
@@ -16,8 +16,7 @@ export class DryRunExecutionStrategy<
16
16
  * @returns A promise resolving to a success result.
17
17
  */
18
18
  async execute(
19
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
20
- _step: TaskStep<TContext>,
19
+ step: TaskStep<TContext>,
21
20
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
22
21
  _context: TContext,
23
22
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
@@ -25,7 +24,7 @@ export class DryRunExecutionStrategy<
25
24
  ): Promise<TaskResult> {
26
25
  return Promise.resolve({
27
26
  status: "success",
28
- message: "Dry run: simulated success",
27
+ message: "Dry run: simulated success " + step.name,
29
28
  });
30
29
  }
31
30
  }
@@ -0,0 +1,101 @@
1
+ export class PriorityQueue<T> {
2
+ private heap: { item: T; priority: number; sequenceId: number }[] = [];
3
+ private sequenceCounter = 0;
4
+
5
+ push(item: T, priority: number): void {
6
+ const node = { item, priority, sequenceId: this.sequenceCounter++ };
7
+ this.heap.push(node);
8
+ this.bubbleUp();
9
+ }
10
+
11
+ pop(): T | undefined {
12
+ if (this.heap.length === 0) return undefined;
13
+ if (this.heap.length === 1) return this.heap.pop()!.item;
14
+
15
+ const top = this.heap[0];
16
+ this.heap[0] = this.heap.pop()!;
17
+ this.sinkDown();
18
+ return top.item;
19
+ }
20
+
21
+ peek(): T | undefined {
22
+ return this.heap[0]?.item;
23
+ }
24
+
25
+ size(): number {
26
+ return this.heap.length;
27
+ }
28
+
29
+ isEmpty(): boolean {
30
+ return this.heap.length === 0;
31
+ }
32
+
33
+ clear(): void {
34
+ this.heap = [];
35
+ this.sequenceCounter = 0;
36
+ }
37
+
38
+ private bubbleUp(): void {
39
+ let index = this.heap.length - 1;
40
+ const element = this.heap[index];
41
+
42
+ while (index > 0) {
43
+ const parentIndex = Math.floor((index - 1) / 2);
44
+ const parent = this.heap[parentIndex];
45
+
46
+ if (this.compare(element, parent) <= 0) break;
47
+
48
+ this.heap[index] = parent;
49
+ this.heap[parentIndex] = element;
50
+ index = parentIndex;
51
+ }
52
+ }
53
+
54
+ private sinkDown(): void {
55
+ let index = 0;
56
+ const length = this.heap.length;
57
+ const element = this.heap[0];
58
+
59
+ while (true) {
60
+ const leftChildIndex = 2 * index + 1;
61
+ const rightChildIndex = 2 * index + 2;
62
+ let swapIndex: number | null = null;
63
+
64
+ if (leftChildIndex < length) {
65
+ if (this.compare(this.heap[leftChildIndex], element) > 0) {
66
+ swapIndex = leftChildIndex;
67
+ }
68
+ }
69
+
70
+ if (rightChildIndex < length) {
71
+ const rightChild = this.heap[rightChildIndex];
72
+ const leftChild = this.heap[leftChildIndex];
73
+
74
+ if (
75
+ (swapIndex === null && this.compare(rightChild, element) > 0) ||
76
+ (swapIndex !== null && this.compare(rightChild, leftChild) > 0)
77
+ ) {
78
+ swapIndex = rightChildIndex;
79
+ }
80
+ }
81
+
82
+ if (swapIndex === null) break;
83
+
84
+ this.heap[index] = this.heap[swapIndex];
85
+ this.heap[swapIndex] = element;
86
+ index = swapIndex;
87
+ }
88
+ }
89
+
90
+ // Returns positive if a > b (a should come before b)
91
+ private compare(
92
+ a: { priority: number; sequenceId: number },
93
+ b: { priority: number; sequenceId: number }
94
+ ): number {
95
+ if (a.priority !== b.priority) {
96
+ return a.priority - b.priority;
97
+ }
98
+ // Lower sequenceId means earlier insertion, so it has higher priority
99
+ return b.sequenceId - a.sequenceId;
100
+ }
101
+ }