@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.
- package/.agent/workflows/openspec-apply.md +20 -0
- package/.agent/workflows/openspec-archive.md +24 -0
- package/.agent/workflows/openspec-proposal.md +25 -0
- package/.github/workflows/codeql.yml +1 -1
- package/.github/workflows/release-please.yml +46 -0
- package/.husky/commit-msg +0 -0
- package/.husky/pre-commit +0 -0
- package/.jules/nexus.md +5 -0
- package/.release-please-manifest.json +3 -0
- package/AGENTS.md +1 -4
- package/CHANGELOG.md +123 -0
- package/CODE_OF_CONDUCT.md +131 -0
- package/CONTRIBUTING.md +89 -0
- package/README.md +1 -1
- package/dist/TaskResult.d.ts +9 -0
- package/dist/TaskRunner.js +47 -34
- package/dist/TaskRunner.js.map +1 -1
- package/dist/TaskStateManager.d.ts +22 -6
- package/dist/TaskStateManager.js +101 -45
- package/dist/TaskStateManager.js.map +1 -1
- package/dist/WorkflowExecutor.js +17 -10
- package/dist/WorkflowExecutor.js.map +1 -1
- package/dist/strategies/DryRunExecutionStrategy.d.ts +1 -1
- package/dist/strategies/DryRunExecutionStrategy.js +2 -4
- package/dist/strategies/DryRunExecutionStrategy.js.map +1 -1
- package/dist/utils/PriorityQueue.d.ts +13 -0
- package/dist/utils/PriorityQueue.js +82 -0
- package/dist/utils/PriorityQueue.js.map +1 -0
- package/openspec/changes/add-resource-concurrency/proposal.md +18 -0
- package/openspec/changes/add-resource-concurrency/specs/task-runner/spec.md +25 -0
- package/openspec/changes/add-resource-concurrency/tasks.md +9 -0
- package/openspec/changes/archive/2026-01-18-add-concurrency-control/specs/task-runner/spec.md +26 -0
- package/openspec/changes/archive/2026-01-18-add-external-task-cancellation/specs/task-runner/spec.md +63 -0
- package/openspec/changes/archive/2026-01-18-add-integration-tests/specs/task-runner/spec.md +22 -0
- package/openspec/changes/archive/2026-01-18-add-task-retry-policy/specs/task-runner/spec.md +40 -0
- package/openspec/changes/archive/2026-01-18-add-workflow-preview/specs/task-runner/spec.md +25 -0
- package/openspec/changes/archive/2026-01-18-refactor-core-architecture/specs/task-runner/spec.md +31 -0
- package/openspec/changes/archive/2026-01-22-adopt-release-pr/design.md +40 -0
- package/openspec/changes/archive/2026-01-22-adopt-release-pr/proposal.md +47 -0
- package/openspec/changes/archive/2026-01-22-adopt-release-pr/specs/release-pr/spec.md +34 -0
- package/openspec/changes/archive/2026-01-22-adopt-release-pr/tasks.md +14 -0
- package/openspec/changes/{feat-task-metrics → archive/2026-01-22-feat-task-metrics}/proposal.md +1 -1
- package/openspec/changes/archive/2026-01-22-feat-task-metrics/specs/001-generic-task-runner/spec.md +13 -0
- package/openspec/changes/archive/2026-01-22-feat-task-metrics/tasks.md +6 -0
- package/openspec/changes/feat-conditional-retries/proposal.md +18 -0
- package/openspec/changes/feat-conditional-retries/specs/task-runner/spec.md +23 -0
- package/openspec/changes/feat-conditional-retries/tasks.md +37 -0
- package/openspec/changes/feat-per-task-timeout/specs/task-runner/spec.md +34 -0
- package/openspec/changes/feat-state-persistence/specs/task-runner/spec.md +47 -0
- package/openspec/specs/release-pr/spec.md +31 -0
- package/openspec/specs/task-runner/spec.md +174 -0
- package/package.json +11 -20
- package/release-please-config.json +9 -0
- package/src/TaskResult.ts +9 -0
- package/src/TaskRunner.ts +55 -36
- package/src/TaskStateManager.ts +114 -46
- package/src/WorkflowExecutor.ts +21 -11
- package/src/strategies/DryRunExecutionStrategy.ts +2 -3
- package/src/utils/PriorityQueue.ts +101 -0
- package/.gemini/commands/speckit.analyze.toml +0 -188
- package/.gemini/commands/speckit.checklist.toml +0 -298
- package/.gemini/commands/speckit.clarify.toml +0 -185
- package/.gemini/commands/speckit.constitution.toml +0 -86
- package/.gemini/commands/speckit.implement.toml +0 -139
- package/.gemini/commands/speckit.plan.toml +0 -93
- package/.gemini/commands/speckit.specify.toml +0 -262
- package/.gemini/commands/speckit.tasks.toml +0 -141
- package/.gemini/commands/speckit.taskstoissues.toml +0 -34
- package/.github/workflows/release.yml +0 -46
- package/.releaserc.json +0 -27
- package/coverage/base.css +0 -224
- package/coverage/block-navigation.js +0 -87
- package/coverage/coverage-final.json +0 -15
- package/coverage/favicon.png +0 -0
- package/coverage/index.html +0 -146
- package/coverage/lcov-report/base.css +0 -224
- package/coverage/lcov-report/block-navigation.js +0 -87
- package/coverage/lcov-report/favicon.png +0 -0
- package/coverage/lcov-report/index.html +0 -146
- package/coverage/lcov-report/prettify.css +0 -1
- package/coverage/lcov-report/prettify.js +0 -2
- package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
- package/coverage/lcov-report/sorter.js +0 -210
- package/coverage/lcov-report/src/EventBus.ts.html +0 -379
- package/coverage/lcov-report/src/ExecutionConstants.ts.html +0 -121
- package/coverage/lcov-report/src/TaskGraphValidationError.ts.html +0 -130
- package/coverage/lcov-report/src/TaskGraphValidator.ts.html +0 -643
- package/coverage/lcov-report/src/TaskRunner.ts.html +0 -706
- package/coverage/lcov-report/src/TaskRunnerBuilder.ts.html +0 -337
- package/coverage/lcov-report/src/TaskRunnerExecutionConfig.ts.html +0 -154
- package/coverage/lcov-report/src/TaskStateManager.ts.html +0 -529
- package/coverage/lcov-report/src/WorkflowExecutor.ts.html +0 -712
- package/coverage/lcov-report/src/contracts/ErrorTypes.ts.html +0 -103
- package/coverage/lcov-report/src/contracts/RunnerEvents.ts.html +0 -217
- package/coverage/lcov-report/src/contracts/index.html +0 -131
- package/coverage/lcov-report/src/index.html +0 -236
- package/coverage/lcov-report/src/strategies/DryRunExecutionStrategy.ts.html +0 -178
- package/coverage/lcov-report/src/strategies/RetryingExecutionStrategy.ts.html +0 -373
- package/coverage/lcov-report/src/strategies/StandardExecutionStrategy.ts.html +0 -190
- package/coverage/lcov-report/src/strategies/index.html +0 -146
- package/coverage/lcov.info +0 -671
- package/coverage/prettify.css +0 -1
- package/coverage/prettify.js +0 -2
- package/coverage/sort-arrow-sprite.png +0 -0
- package/coverage/sorter.js +0 -210
- package/coverage/src/EventBus.ts.html +0 -379
- package/coverage/src/ExecutionConstants.ts.html +0 -121
- package/coverage/src/TaskGraphValidationError.ts.html +0 -130
- package/coverage/src/TaskGraphValidator.ts.html +0 -643
- package/coverage/src/TaskRunner.ts.html +0 -706
- package/coverage/src/TaskRunnerBuilder.ts.html +0 -337
- package/coverage/src/TaskRunnerExecutionConfig.ts.html +0 -154
- package/coverage/src/TaskStateManager.ts.html +0 -529
- package/coverage/src/WorkflowExecutor.ts.html +0 -712
- package/coverage/src/contracts/ErrorTypes.ts.html +0 -103
- package/coverage/src/contracts/RunnerEvents.ts.html +0 -217
- package/coverage/src/contracts/index.html +0 -131
- package/coverage/src/index.html +0 -236
- package/coverage/src/strategies/DryRunExecutionStrategy.ts.html +0 -178
- package/coverage/src/strategies/RetryingExecutionStrategy.ts.html +0 -373
- package/coverage/src/strategies/StandardExecutionStrategy.ts.html +0 -190
- package/coverage/src/strategies/index.html +0 -146
- package/openspec/changes/feat-task-metrics/tasks.md +0 -6
- 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
|
+
"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
|
+
}
|
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
|
|
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
|
-
|
|
86
|
-
|
|
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
|
-
|
|
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
|
-
|
|
175
|
-
const
|
|
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
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
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
|
}
|
package/src/TaskStateManager.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
|
34
|
+
for (const step of steps) {
|
|
36
35
|
const deps = step.dependencies ?? [];
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
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
|
-
//
|
|
67
|
-
for (const step of
|
|
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
|
-
*
|
|
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
|
-
|
|
144
|
-
this.
|
|
145
|
-
|
|
146
|
-
|
|
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
|
}
|
package/src/WorkflowExecutor.ts
CHANGED
|
@@ -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
|
|
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.
|
|
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.
|
|
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
|
-
|
|
199
|
-
this.stateManager.markCompleted(step, result);
|
|
199
|
+
result = await this.strategy.execute(step, this.context, signal);
|
|
200
200
|
} catch (error) {
|
|
201
|
-
|
|
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
|
-
|
|
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
|
}
|