@calmo/task-runner 3.8.4 → 4.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 (124) hide show
  1. package/.agent/workflows/openspec-apply.md +20 -0
  2. package/.agent/workflows/openspec-archive.md +24 -0
  3. package/.agent/workflows/openspec-proposal.md +25 -0
  4. package/.github/workflows/codeql.yml +1 -1
  5. package/.github/workflows/release-please.yml +46 -0
  6. package/.husky/commit-msg +0 -0
  7. package/.husky/pre-commit +0 -0
  8. package/.jules/nexus.md +5 -0
  9. package/.release-please-manifest.json +3 -0
  10. package/AGENTS.md +1 -4
  11. package/CHANGELOG.md +123 -0
  12. package/CODE_OF_CONDUCT.md +131 -0
  13. package/CONTRIBUTING.md +89 -0
  14. package/README.md +1 -1
  15. package/dist/TaskResult.d.ts +9 -0
  16. package/dist/TaskRunner.js +47 -34
  17. package/dist/TaskRunner.js.map +1 -1
  18. package/dist/TaskStateManager.d.ts +22 -6
  19. package/dist/TaskStateManager.js +101 -45
  20. package/dist/TaskStateManager.js.map +1 -1
  21. package/dist/WorkflowExecutor.js +17 -10
  22. package/dist/WorkflowExecutor.js.map +1 -1
  23. package/dist/strategies/DryRunExecutionStrategy.d.ts +1 -1
  24. package/dist/strategies/DryRunExecutionStrategy.js +2 -4
  25. package/dist/strategies/DryRunExecutionStrategy.js.map +1 -1
  26. package/dist/utils/PriorityQueue.d.ts +13 -0
  27. package/dist/utils/PriorityQueue.js +82 -0
  28. package/dist/utils/PriorityQueue.js.map +1 -0
  29. package/openspec/changes/add-resource-concurrency/proposal.md +18 -0
  30. package/openspec/changes/add-resource-concurrency/specs/task-runner/spec.md +25 -0
  31. package/openspec/changes/add-resource-concurrency/tasks.md +9 -0
  32. package/openspec/changes/archive/2026-01-18-add-concurrency-control/specs/task-runner/spec.md +26 -0
  33. package/openspec/changes/archive/2026-01-18-add-external-task-cancellation/specs/task-runner/spec.md +63 -0
  34. package/openspec/changes/archive/2026-01-18-add-integration-tests/specs/task-runner/spec.md +22 -0
  35. package/openspec/changes/archive/2026-01-18-add-task-retry-policy/specs/task-runner/spec.md +40 -0
  36. package/openspec/changes/archive/2026-01-18-add-workflow-preview/specs/task-runner/spec.md +25 -0
  37. package/openspec/changes/archive/2026-01-18-refactor-core-architecture/specs/task-runner/spec.md +31 -0
  38. package/openspec/changes/archive/2026-01-22-adopt-release-pr/design.md +40 -0
  39. package/openspec/changes/archive/2026-01-22-adopt-release-pr/proposal.md +47 -0
  40. package/openspec/changes/archive/2026-01-22-adopt-release-pr/specs/release-pr/spec.md +34 -0
  41. package/openspec/changes/archive/2026-01-22-adopt-release-pr/tasks.md +14 -0
  42. package/openspec/changes/{feat-task-metrics → archive/2026-01-22-feat-task-metrics}/proposal.md +1 -1
  43. package/openspec/changes/archive/2026-01-22-feat-task-metrics/specs/001-generic-task-runner/spec.md +13 -0
  44. package/openspec/changes/archive/2026-01-22-feat-task-metrics/tasks.md +6 -0
  45. package/openspec/changes/feat-conditional-retries/proposal.md +18 -0
  46. package/openspec/changes/feat-conditional-retries/specs/task-runner/spec.md +23 -0
  47. package/openspec/changes/feat-conditional-retries/tasks.md +37 -0
  48. package/openspec/changes/feat-per-task-timeout/specs/task-runner/spec.md +34 -0
  49. package/openspec/changes/feat-state-persistence/specs/task-runner/spec.md +47 -0
  50. package/openspec/specs/release-pr/spec.md +31 -0
  51. package/openspec/specs/task-runner/spec.md +174 -0
  52. package/package.json +11 -20
  53. package/release-please-config.json +9 -0
  54. package/src/TaskResult.ts +9 -0
  55. package/src/TaskRunner.ts +55 -36
  56. package/src/TaskStateManager.ts +114 -46
  57. package/src/WorkflowExecutor.ts +21 -11
  58. package/src/strategies/DryRunExecutionStrategy.ts +2 -3
  59. package/src/utils/PriorityQueue.ts +101 -0
  60. package/.gemini/commands/speckit.analyze.toml +0 -188
  61. package/.gemini/commands/speckit.checklist.toml +0 -298
  62. package/.gemini/commands/speckit.clarify.toml +0 -185
  63. package/.gemini/commands/speckit.constitution.toml +0 -86
  64. package/.gemini/commands/speckit.implement.toml +0 -139
  65. package/.gemini/commands/speckit.plan.toml +0 -93
  66. package/.gemini/commands/speckit.specify.toml +0 -262
  67. package/.gemini/commands/speckit.tasks.toml +0 -141
  68. package/.gemini/commands/speckit.taskstoissues.toml +0 -34
  69. package/.github/workflows/release.yml +0 -46
  70. package/.releaserc.json +0 -27
  71. package/coverage/base.css +0 -224
  72. package/coverage/block-navigation.js +0 -87
  73. package/coverage/coverage-final.json +0 -15
  74. package/coverage/favicon.png +0 -0
  75. package/coverage/index.html +0 -146
  76. package/coverage/lcov-report/base.css +0 -224
  77. package/coverage/lcov-report/block-navigation.js +0 -87
  78. package/coverage/lcov-report/favicon.png +0 -0
  79. package/coverage/lcov-report/index.html +0 -146
  80. package/coverage/lcov-report/prettify.css +0 -1
  81. package/coverage/lcov-report/prettify.js +0 -2
  82. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  83. package/coverage/lcov-report/sorter.js +0 -210
  84. package/coverage/lcov-report/src/EventBus.ts.html +0 -379
  85. package/coverage/lcov-report/src/ExecutionConstants.ts.html +0 -121
  86. package/coverage/lcov-report/src/TaskGraphValidationError.ts.html +0 -130
  87. package/coverage/lcov-report/src/TaskGraphValidator.ts.html +0 -643
  88. package/coverage/lcov-report/src/TaskRunner.ts.html +0 -706
  89. package/coverage/lcov-report/src/TaskRunnerBuilder.ts.html +0 -337
  90. package/coverage/lcov-report/src/TaskRunnerExecutionConfig.ts.html +0 -154
  91. package/coverage/lcov-report/src/TaskStateManager.ts.html +0 -529
  92. package/coverage/lcov-report/src/WorkflowExecutor.ts.html +0 -712
  93. package/coverage/lcov-report/src/contracts/ErrorTypes.ts.html +0 -103
  94. package/coverage/lcov-report/src/contracts/RunnerEvents.ts.html +0 -217
  95. package/coverage/lcov-report/src/contracts/index.html +0 -131
  96. package/coverage/lcov-report/src/index.html +0 -236
  97. package/coverage/lcov-report/src/strategies/DryRunExecutionStrategy.ts.html +0 -178
  98. package/coverage/lcov-report/src/strategies/RetryingExecutionStrategy.ts.html +0 -373
  99. package/coverage/lcov-report/src/strategies/StandardExecutionStrategy.ts.html +0 -190
  100. package/coverage/lcov-report/src/strategies/index.html +0 -146
  101. package/coverage/lcov.info +0 -671
  102. package/coverage/prettify.css +0 -1
  103. package/coverage/prettify.js +0 -2
  104. package/coverage/sort-arrow-sprite.png +0 -0
  105. package/coverage/sorter.js +0 -210
  106. package/coverage/src/EventBus.ts.html +0 -379
  107. package/coverage/src/ExecutionConstants.ts.html +0 -121
  108. package/coverage/src/TaskGraphValidationError.ts.html +0 -130
  109. package/coverage/src/TaskGraphValidator.ts.html +0 -643
  110. package/coverage/src/TaskRunner.ts.html +0 -706
  111. package/coverage/src/TaskRunnerBuilder.ts.html +0 -337
  112. package/coverage/src/TaskRunnerExecutionConfig.ts.html +0 -154
  113. package/coverage/src/TaskStateManager.ts.html +0 -529
  114. package/coverage/src/WorkflowExecutor.ts.html +0 -712
  115. package/coverage/src/contracts/ErrorTypes.ts.html +0 -103
  116. package/coverage/src/contracts/RunnerEvents.ts.html +0 -217
  117. package/coverage/src/contracts/index.html +0 -131
  118. package/coverage/src/index.html +0 -236
  119. package/coverage/src/strategies/DryRunExecutionStrategy.ts.html +0 -178
  120. package/coverage/src/strategies/RetryingExecutionStrategy.ts.html +0 -373
  121. package/coverage/src/strategies/StandardExecutionStrategy.ts.html +0 -190
  122. package/coverage/src/strategies/index.html +0 -146
  123. package/openspec/changes/feat-task-metrics/tasks.md +0 -6
  124. package/test-report.xml +0 -299
@@ -0,0 +1,174 @@
1
+ # task-runner Specification
2
+
3
+ ## Purpose
4
+
5
+ TBD - created by archiving change add-external-task-cancellation. Update Purpose after archive.
6
+
7
+ ## Requirements
8
+
9
+ ### Requirement: TaskRunner Execution
10
+
11
+ The `TaskRunner` SHALL execute a sequence of `TaskStep`s based on their dependencies, processing inputs and producing outputs.
12
+
13
+ #### Scenario: Successful execution
14
+
15
+ - **WHEN** all `TaskStep`s complete successfully
16
+ - **THEN** the `TaskRunner` returns a successful workflow result.
17
+
18
+ #### Scenario: Execution with AbortSignal
19
+
20
+ - **WHEN** `TaskRunner.execute` is called with an `AbortSignal`
21
+ - **THEN** the `TaskRunner` monitors the `AbortSignal` for cancellation requests.
22
+
23
+ #### Scenario: Execution with Global Timeout
24
+
25
+ - **WHEN** `TaskRunner.execute` is called with a `timeout` option
26
+ - **THEN** the `TaskRunner` monitors the elapsed time for the workflow.
27
+
28
+ ### Requirement: External Workflow Cancellation
29
+
30
+ The `TaskRunner` SHALL allow external cancellation of an ongoing workflow.
31
+
32
+ #### Scenario: Workflow cancelled by AbortSignal
33
+
34
+ - **WHEN** an `AbortSignal` provided to `TaskRunner.execute` is triggered
35
+ - **THEN** the `TaskRunner` immediately attempts to stop execution of current and pending tasks.
36
+
37
+ #### Scenario: Workflow cancelled by Global Timeout
38
+
39
+ - **WHEN** the specified global `timeout` for `TaskRunner.execute` is reached
40
+ - **THEN** the `TaskRunner` immediately attempts to stop execution of current and pending tasks.
41
+
42
+ #### Scenario: Tasks marked as cancelled
43
+
44
+ - **WHEN** a workflow is cancelled (by `AbortSignal` or `timeout`)
45
+ - **THEN** all unexecuted `TaskStep`s SHALL be marked with a 'cancelled' status in the final result.
46
+
47
+ #### Scenario: Pre-aborted workflow
48
+
49
+ - **WHEN** `TaskRunner.execute` is called with an `AbortSignal` that is already aborted
50
+ - **THEN** the `TaskRunner` SHALL return immediately with all tasks marked as cancelled, without executing any steps.
51
+
52
+ #### Scenario: Graceful interruption of current task
53
+
54
+ - **WHEN** a workflow is cancelled and a `TaskStep` is currently executing
55
+ - **THEN** the `TaskStep` SHALL receive the cancellation signal (e.g., via `AbortSignal` context) to allow for graceful interruption.
56
+
57
+ ### Requirement: Cancellation Conflict Resolution
58
+
59
+ The `TaskRunner` SHALL handle scenarios where both `AbortSignal` and global `timeout` are provided.
60
+
61
+ #### Scenario: AbortSignal precedes Timeout
62
+
63
+ - **WHEN** both `AbortSignal` and `timeout` are provided, and `AbortSignal` is triggered first
64
+ - **THEN** the `TaskRunner` SHALL cancel the workflow based on the `AbortSignal`, ignoring the `timeout`.
65
+
66
+ #### Scenario: Timeout precedes AbortSignal
67
+
68
+ - **WHEN** both `AbortSignal` and `timeout` are provided, and `timeout` is reached first
69
+ - **THEN** the `TaskRunner` SHALL cancel the workflow based on the `timeout`, ignoring the `AbortSignal`.
70
+
71
+ ### Requirement: Integration Verification
72
+
73
+ The system's integrity SHALL be verified through comprehensive integration scenarios executed against the real runtime environment without mocks.
74
+
75
+ #### Scenario: Complex Graph Execution
76
+
77
+ - **WHEN** a complex task graph (diamonds, sequences, parallel branches) is executed
78
+ - **THEN** the system SHALL respect all dependency constraints and execution orders.
79
+ - **AND** the final state MUST reflect the cumulative side effects of all successful tasks.
80
+
81
+ #### Scenario: Failure Propagation
82
+
83
+ - **WHEN** a task fails in a complex graph
84
+ - **THEN** ONLY dependent tasks SHALL be skipped
85
+ - **AND** independent branches SHALL continue to execute to completion.
86
+
87
+ #### Scenario: Context Integrity
88
+
89
+ - **WHEN** multiple tasks mutate the shared context
90
+ - **THEN** state changes MUST be propagated correctly to downstream tasks.
91
+
92
+ ### Requirement: Modular Execution Architecture
93
+
94
+ The system SHALL support pluggable execution strategies and decoupled state management.
95
+
96
+ #### Scenario: Pluggable Strategy
97
+
98
+ - **WHEN** configured with a custom execution strategy
99
+ - **THEN** the `TaskRunner` SHALL delegate the execution logic to that strategy.
100
+
101
+ ### Requirement: Dry Run Execution Strategy
102
+
103
+ The system SHALL provide a `DryRunExecutionStrategy` that implements `IExecutionStrategy`.
104
+
105
+ #### Scenario: Simulating execution
106
+
107
+ - **WHEN** `WorkflowExecutor` is configured with `DryRunExecutionStrategy`
108
+ - **AND** `execute` is called
109
+ - **THEN** it SHALL traverse the dependency graph respecting order
110
+ - **AND** it SHALL NOT execute the actual work of the `TaskStep`.
111
+ - **AND** it SHALL return `TaskResult`s with a status indicating successful simulation (e.g., `simulated` or `success`).
112
+
113
+ ### Requirement: Mermaid Visualization
114
+
115
+ The system SHALL provide a utility to generate a Mermaid.js graph from task steps.
116
+
117
+ #### Scenario: Generate Mermaid Graph
118
+
119
+ - **GIVEN** a list of `TaskStep`s with dependencies
120
+ - **WHEN** `generateMermaidGraph` is called
121
+ - **THEN** it SHALL return a valid Mermaid flowchart syntax string.
122
+ - **AND** dependencies SHALL be represented as arrows (`-->`).
123
+ - **AND** independent tasks SHALL appear as nodes.
124
+
125
+ ### Requirement: Task Retry Configuration
126
+
127
+ The `TaskStep` interface SHALL support an optional `retry` property of type `TaskRetryConfig`.
128
+
129
+ #### Scenario: Retry Config Structure
130
+
131
+ - **GIVEN** a `TaskRetryConfig` object
132
+ - **THEN** it SHALL support:
133
+ - `attempts`: Number of retry attempts (default: 0).
134
+ - `delay`: Base delay in milliseconds (default: 0).
135
+ - `backoff`: Backoff strategy ('fixed' | 'exponential') (default: 'fixed').
136
+
137
+ ### Requirement: Retrying Execution Strategy
138
+
139
+ The system SHALL provide a `RetryingExecutionStrategy` that implements `IExecutionStrategy` and wraps another `IExecutionStrategy`.
140
+
141
+ #### Scenario: Successful execution
142
+
143
+ - **WHEN** the inner strategy returns a successful `TaskResult`
144
+ - **THEN** `RetryingExecutionStrategy` SHALL return that result immediately.
145
+
146
+ #### Scenario: Retry on failure
147
+
148
+ - **WHEN** the inner strategy throws or returns a failed `TaskResult`
149
+ - **AND** the task has `retry.attempts > 0`
150
+ - **THEN** it SHALL wait for the configured `delay`.
151
+ - **AND** it SHALL re-execute the task using the inner strategy.
152
+ - **AND** it SHALL decrement the remaining attempts.
153
+
154
+ #### Scenario: Max attempts reached
155
+
156
+ - **WHEN** the task fails and no attempts remain
157
+ - **THEN** it SHALL return the failed result (or throw).
158
+
159
+ #### Scenario: Exponential Backoff
160
+
161
+ - **WHEN** `retry.backoff` is 'exponential'
162
+ - **THEN** the delay SHALL increase for each attempt (e.g., `delay * 2^attempt`).
163
+
164
+ ### Requirement: Task Execution Metrics
165
+
166
+ The system SHALL record timing metrics for each executed task, including start time, end time, and duration.
167
+
168
+ #### Scenario: Successful execution
169
+ - **WHEN** a task completes successfully
170
+ - **THEN** the task result contains the start timestamp, end timestamp, and duration in milliseconds
171
+
172
+ #### Scenario: Failed execution
173
+ - **WHEN** a task fails
174
+ - **THEN** the task result contains the start timestamp, end timestamp, and duration in milliseconds
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@calmo/task-runner",
3
- "version": "3.8.4",
3
+ "version": "4.1.0",
4
4
  "description": "A lightweight, type-safe, and domain-agnostic task orchestration engine. It resolves a Directed Acyclic Graph (DAG) of steps, executes independent tasks in parallel, and manages a shared context across the pipeline.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -15,16 +15,6 @@
15
15
  }
16
16
  },
17
17
  "type": "module",
18
- "scripts": {
19
- "build": "tsc",
20
- "test": "tsc --noEmit -p tsconfig.test.json && vitest run --coverage",
21
- "lint": "eslint .",
22
- "lint:fix": "eslint . --fix",
23
- "all": "pnpm run build && pnpm run test && pnpm run lint",
24
- "format": "prettier --write .",
25
- "prepare": "husky",
26
- "commit": "git add . &&git-cz"
27
- },
28
18
  "config": {
29
19
  "commitizen": {
30
20
  "path": "git-cz"
@@ -44,17 +34,10 @@
44
34
  ],
45
35
  "author": "",
46
36
  "license": "ISC",
47
- "packageManager": "pnpm@10.28.0",
48
37
  "devDependencies": {
49
38
  "@commitlint/cli": "^20.3.1",
50
39
  "@commitlint/config-conventional": "^20.3.1",
51
40
  "@eslint/js": "^9.39.2",
52
- "@semantic-release/changelog": "^6.0.3",
53
- "@semantic-release/commit-analyzer": "^13.0.1",
54
- "@semantic-release/git": "^10.0.1",
55
- "@semantic-release/github": "^12.0.2",
56
- "@semantic-release/npm": "^13.1.3",
57
- "@semantic-release/release-notes-generator": "^14.1.0",
58
41
  "@types/node": "^25.0.9",
59
42
  "@vitest/coverage-v8": "4.0.17",
60
43
  "eslint": "^9.39.2",
@@ -62,9 +45,17 @@
62
45
  "git-cz": "^4.9.0",
63
46
  "husky": "^9.1.7",
64
47
  "prettier": "^3.8.0",
65
- "semantic-release": "^25.0.2",
66
48
  "typescript": "^5.9.3",
67
49
  "typescript-eslint": "^8.53.0",
68
50
  "vitest": "^4.0.17"
51
+ },
52
+ "scripts": {
53
+ "build": "tsc",
54
+ "test": "tsc --noEmit -p tsconfig.test.json && vitest run --coverage",
55
+ "lint": "eslint .",
56
+ "lint:fix": "eslint . --fix",
57
+ "all": "pnpm run build && pnpm run test && pnpm run lint",
58
+ "format": "prettier --write .",
59
+ "commit": "git add . &&git-cz"
69
60
  }
70
- }
61
+ }
@@ -0,0 +1,9 @@
1
+ {
2
+ "packages": {
3
+ ".": {
4
+ "release-type": "node",
5
+ "package-name": "@calmo/task-runner"
6
+ }
7
+ },
8
+ "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json"
9
+ }
package/src/TaskResult.ts CHANGED
@@ -12,4 +12,13 @@ export interface TaskResult {
12
12
  error?: string;
13
13
  /** Optional data produced by the step for later inspection. */
14
14
  data?: unknown;
15
+ /** Optional execution metrics for the task. */
16
+ metrics?: {
17
+ /** Start time in milliseconds (performance.now). */
18
+ startTime: number;
19
+ /** End time in milliseconds (performance.now). */
20
+ endTime: number;
21
+ /** Duration in milliseconds. */
22
+ duration: number;
23
+ };
15
24
  }
package/src/TaskRunner.ts CHANGED
@@ -78,19 +78,59 @@ export class TaskRunner<TContext> {
78
78
  */
79
79
  public static getMermaidGraph<T>(steps: TaskStep<T>[]): string {
80
80
  const graphLines = ["graph TD"];
81
+ const idMap = new Map<string, string>();
82
+ const usedIds = new Set<string>();
83
+ const baseIdCounters = new Map<string, number>();
81
84
 
82
- const sanitize = (name: string) => this.sanitizeMermaidId(name);
85
+ const getUniqueId = (name: string) => {
86
+ if (idMap.has(name)) {
87
+ return idMap.get(name)!;
88
+ }
89
+
90
+ const sanitized = this.sanitizeMermaidId(name);
91
+ let uniqueId = sanitized;
92
+
93
+ // First check if the base sanitized ID is available
94
+ if (!usedIds.has(uniqueId)) {
95
+ usedIds.add(uniqueId);
96
+ idMap.set(name, uniqueId);
97
+ return uniqueId;
98
+ }
99
+
100
+ // If not, use the counter for this base ID
101
+ let counter = baseIdCounters.get(sanitized) || 1;
102
+
103
+ while (usedIds.has(uniqueId)) {
104
+ uniqueId = `${sanitized}_${counter}`;
105
+ counter++;
106
+ }
107
+
108
+ baseIdCounters.set(sanitized, counter);
109
+
110
+ usedIds.add(uniqueId);
111
+ idMap.set(name, uniqueId);
112
+ return uniqueId;
113
+ };
83
114
 
115
+ // Pre-calculate IDs for all steps to ensure stable generation order
116
+ // We sort steps by name to ensure deterministic ID generation regardless of input order if names clash
117
+ // But input order is usually significant in graph definition, so we'll stick to input order.
118
+ // However, we must process all step NAMES first.
84
119
  for (const step of steps) {
85
- graphLines.push(
86
- ` ${sanitize(step.name)}[${JSON.stringify(step.name)}]`
87
- );
120
+ getUniqueId(step.name);
121
+ }
122
+
123
+ for (const step of steps) {
124
+ const stepId = getUniqueId(step.name);
125
+ graphLines.push(` ${stepId}[${JSON.stringify(step.name)}]`);
88
126
  }
89
127
 
90
128
  for (const step of steps) {
91
129
  if (step.dependencies) {
130
+ const stepId = getUniqueId(step.name);
92
131
  for (const dep of step.dependencies) {
93
- graphLines.push(` ${sanitize(dep)} --> ${sanitize(step.name)}`);
132
+ const depId = getUniqueId(dep);
133
+ graphLines.push(` ${depId} --> ${stepId}`);
94
134
  }
95
135
  }
96
136
  }
@@ -171,37 +211,16 @@ export class TaskRunner<TContext> {
171
211
  timeout: number,
172
212
  signal?: AbortSignal
173
213
  ): 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
- }
214
+ // Create a timeout signal that aborts after the specified time
215
+ const timeoutSignal = AbortSignal.timeout(timeout);
197
216
 
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
- }
217
+ // If there's a user-provided signal, combine them.
218
+ // Otherwise, use the timeout signal directly.
219
+ const effectiveSignal = signal
220
+ ? AbortSignal.any([signal, timeoutSignal])
221
+ : timeoutSignal;
222
+
223
+ return executor.execute(steps, effectiveSignal);
224
+ // No explicit clean up needed for AbortSignal.timeout as it is handled by the platform
206
225
  }
207
226
  }
@@ -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,39 @@ 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
+ if (!this.dependencyGraph.has(dep)) {
43
+ this.dependencyGraph.set(dep, []);
44
+ }
45
+ this.dependencyGraph.get(dep)!.push(step);
48
46
  }
49
47
  }
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
48
  }
49
+ }
50
+
51
+ /**
52
+ * Processes the pending steps to identify tasks that can be started.
53
+ * Emits `taskSkipped` for skipped tasks (handled during cascade).
54
+ * @returns An array of tasks that are ready to run.
55
+ */
56
+ processDependencies(): TaskStep<TContext>[] {
57
+ const toRun = [...this.readyQueue];
58
+ this.readyQueue = [];
65
59
 
66
- // Cleanup pending set
67
- for (const step of toRemove) {
60
+ // Remove them from pendingSteps as they are now handed off to the executor
61
+ for (const step of toRun) {
68
62
  this.pendingSteps.delete(step);
69
63
  }
70
64
 
@@ -90,6 +84,39 @@ export class TaskStateManager<TContext> {
90
84
  this.running.delete(step.name);
91
85
  this.results.set(step.name, result);
92
86
  this.eventBus.emit("taskEnd", { step, result });
87
+
88
+ if (result.status === "success") {
89
+ this.handleSuccess(step.name);
90
+ } else {
91
+ this.cascadeFailure(step.name);
92
+ }
93
+ }
94
+
95
+ /**
96
+ * Marks a task as skipped and emits `taskSkipped`.
97
+ * @param step The task that was skipped.
98
+ * @param result The result object (status: skipped).
99
+ */
100
+ markSkipped(step: TaskStep<TContext>, result: TaskResult): void {
101
+ if (this.internalMarkSkipped(step, result)) {
102
+ this.cascadeFailure(step.name);
103
+ }
104
+ }
105
+
106
+ /**
107
+ * Internal method to mark skipped without triggering cascade (to be used inside cascade loop).
108
+ * Returns true if the task was actually marked skipped (was not already finished).
109
+ */
110
+ private internalMarkSkipped(step: TaskStep<TContext>, result: TaskResult): boolean {
111
+ if (this.results.has(step.name)) {
112
+ return false;
113
+ }
114
+
115
+ this.running.delete(step.name);
116
+ this.results.set(step.name, result);
117
+ this.pendingSteps.delete(step);
118
+ this.eventBus.emit("taskSkipped", { step, result });
119
+ return true;
93
120
  }
94
121
 
95
122
  /**
@@ -97,10 +124,10 @@ export class TaskStateManager<TContext> {
97
124
  * @param message The cancellation message.
98
125
  */
99
126
  cancelAllPending(message: string): void {
127
+ this.readyQueue = []; // Clear ready queue
128
+
100
129
  // Iterate over pendingSteps to cancel them
101
130
  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
131
  if (!this.results.has(step.name) && !this.running.has(step.name)) {
105
132
  const result: TaskResult = {
106
133
  status: "cancelled",
@@ -136,13 +163,54 @@ export class TaskStateManager<TContext> {
136
163
  }
137
164
 
138
165
  /**
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).
166
+ * Handles successful completion of a task by updating dependents.
142
167
  */
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 });
168
+ private handleSuccess(stepName: string): void {
169
+ const dependents = this.dependencyGraph.get(stepName);
170
+ if (!dependents) return;
171
+
172
+ for (const dependent of dependents) {
173
+ const currentCount = this.dependencyCounts.get(dependent.name)!;
174
+ const newCount = currentCount - 1;
175
+ this.dependencyCounts.set(dependent.name, newCount);
176
+
177
+ if (newCount === 0) {
178
+ // Task is ready. Ensure it's still pending.
179
+ if (this.pendingSteps.has(dependent)) {
180
+ this.readyQueue.push(dependent);
181
+ }
182
+ }
183
+ }
184
+ }
185
+
186
+ /**
187
+ * Cascades failure/skipping to dependents.
188
+ */
189
+ private cascadeFailure(failedStepName: string): void {
190
+ const queue = [failedStepName];
191
+ // Use a set to track visited nodes in this cascade pass to avoid redundant processing,
192
+ // although checking results.has() in internalMarkSkipped also prevents it.
193
+
194
+ while (queue.length > 0) {
195
+ const currentName = queue.shift()!;
196
+ const dependents = this.dependencyGraph.get(currentName);
197
+
198
+ if (!dependents) continue;
199
+
200
+ // Get the result of the failed/skipped dependency to propagate error info if available
201
+ const currentResult = this.results.get(currentName);
202
+ const depError = currentResult?.error ? `: ${currentResult.error}` : "";
203
+
204
+ for (const dependent of dependents) {
205
+ const result: TaskResult = {
206
+ status: "skipped",
207
+ message: `Skipped because dependency '${currentName}' failed${depError}`,
208
+ };
209
+
210
+ if (this.internalMarkSkipped(dependent, result)) {
211
+ queue.push(dependent.name);
212
+ }
213
+ }
214
+ }
147
215
  }
148
216
  }
@@ -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.
@@ -114,14 +115,11 @@ export class WorkflowExecutor<TContext> {
114
115
 
115
116
  // Add newly ready tasks to the queue
116
117
  for (const task of newlyReady) {
117
- this.readyQueue.push(task);
118
+ this.readyQueue.push(task, task.priority ?? 0);
118
119
  }
119
120
 
120
- // Sort by priority (descending) once after adding new tasks
121
- this.readyQueue.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
122
-
123
121
  // Execute ready tasks while respecting concurrency limit
124
- while (this.readyQueue.length > 0) {
122
+ while (!this.readyQueue.isEmpty()) {
125
123
  if (
126
124
  this.concurrency !== undefined &&
127
125
  executingPromises.size >= this.concurrency
@@ -129,7 +127,7 @@ export class WorkflowExecutor<TContext> {
129
127
  break;
130
128
  }
131
129
 
132
- const step = this.readyQueue.shift()!;
130
+ const step = this.readyQueue.pop()!;
133
131
 
134
132
  const taskPromise = this.executeTaskStep(step, signal)
135
133
  .finally(() => {
@@ -194,16 +192,28 @@ export class WorkflowExecutor<TContext> {
194
192
 
195
193
  this.stateManager.markRunning(step);
196
194
 
195
+ const startTime = performance.now();
196
+ let result: TaskResult;
197
+
197
198
  try {
198
- const result = await this.strategy.execute(step, this.context, signal);
199
- this.stateManager.markCompleted(step, result);
199
+ result = await this.strategy.execute(step, this.context, signal);
200
200
  } catch (error) {
201
- const result: TaskResult = {
201
+ result = {
202
202
  status: "failure",
203
203
  message: ExecutionConstants.EXECUTION_STRATEGY_FAILED,
204
204
  error: error instanceof Error ? error.message : String(error),
205
205
  };
206
- this.stateManager.markCompleted(step, result);
207
206
  }
207
+
208
+ const endTime = performance.now();
209
+
210
+ // Always inject metrics to ensure accuracy
211
+ result.metrics = {
212
+ startTime,
213
+ endTime,
214
+ duration: endTime - startTime,
215
+ };
216
+
217
+ this.stateManager.markCompleted(step, result);
208
218
  }
209
219
  }
@@ -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
  }