saga-ci 1.0.1 → 1.0.4-pre-release

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/README.md CHANGED
@@ -1,70 +1,78 @@
1
1
  # saga-ci
2
2
 
3
3
  [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
4
- [![Node.js](https://img.shields.io/badge/Node.js-%3E%3D18.0.0-brightgreen.svg)](package.json)
4
+ [![Node.js](https://img.shields.io/badge/Node.js-%3E%3D24.0.0-brightgreen.svg)](package.json)
5
5
 
6
6
  A lightweight, zero-dependency **Saga-pattern CI/CD workflow runner** for Node.js and TypeScript.
7
- Wrap deployment and automation steps in a `do()` / `undo()` command contract, compose nested sequential or parallel execution groups, automatically roll back in reverse order on failure, and stream aligned status tables straight to `$GITHUB_STEP_SUMMARY`.
7
+ Subclass `Command` with explicit `takeSnapshot()`, `shouldDo()`, `do()`, `shouldUndo()`, and `undo()` methods, share scoped `WorkflowContext` across steps, compose nested sequential or parallel execution groups, automatically roll back in reverse order on failure, and stream aligned status tables straight to `$GITHUB_STEP_SUMMARY`.
8
8
 
9
- **Documentation Wiki & Live Simulator:** [https://thisispennyleung.github.io/saga-ci/](https://thisispennyleung.github.io/saga-ci/)
9
+ **Documentation Wiki & Live Simulator:** [https://thisispennyleung.github.io/saga-ci/](https://thisispennyleung.github.io/saga-ci/)
10
+ **Install:** `npm install saga-ci`
10
11
 
11
- ---
12
+ ## Background
12
13
 
13
- ## Installation
14
+ Splitting a deployment pipeline across native GitHub Actions jobs (`needs:`, `strategy.matrix`, `if: failure()`) quickly becomes slow and brittle when you need parallel fan-outs, conditional steps, or reliable rollbacks:
14
15
 
15
- ```bash
16
- npm install saga-ci
17
- ```
18
-
19
- Works with Node.js `>=18.0.0` (compiled ESM `.js` + `.d.ts` type declarations included).
16
+ - **Per-job startup overhead:** Every separate GitHub Actions job pays runner queue wait time, VM boot, `actions/checkout`, and toolchain/dependency setup—turning fine-grained parallel steps into minutes of waiting.
17
+ - **Awkward cross-job rollback:** GitHub Actions has no built-in Saga/compensation model; tracking which steps actually ran, skipping converged work, and unwinding partial failures across jobs requires passing outputs or artifacts and writing fragile `if: failure()` cleanup YAML.
20
18
 
21
- ---
19
+ `saga-ci` moves that orchestration inside a **single GitHub Actions job**. In one Node.js/TypeScript process, you get in-process async parallelism (`maxConcurrency`), snapshot-based state checks (`takeSnapshot` + `shouldDo` + `shouldUndo`), automatic reverse-order `undo()` rollback across sequential and parallel groups, and live Markdown status tables in `$GITHUB_STEP_SUMMARY`—without waiting on extra runners.
22
20
 
23
21
  ## Quick Start
24
22
 
25
23
  ```ts
26
- import { CiWorkFlow } from 'saga-ci';
27
-
28
- const workflow = new CiWorkFlow();
29
-
30
- workflow.register(
31
- {
32
- name: 'Preflight Check',
33
- shouldDo: () => true,
34
- do: async () => console.log('Checking credentials...'),
35
- undo: () => {},
36
- },
37
- false // hasUndo = false -> Undo column shows N/A
38
- );
39
-
40
- workflow.register({
41
- name: 'Provision Database',
42
- shouldDo: () => true,
43
- do: async () => console.log('Database ready'),
44
- undo: async () => console.log('Rolling back database'),
45
- });
24
+ import { CiWorkFlow, Command } from 'saga-ci';
25
+ import type { WorkflowContext } from 'saga-ci';
26
+
27
+ interface DeployData {
28
+ dbReady: boolean;
29
+ }
30
+
31
+ class PreflightCommand extends Command<DeployData, void> {
32
+ public readonly name = 'Preflight Check';
33
+ public takeSnapshot(): void {}
34
+ public shouldDo(): boolean {
35
+ return true;
36
+ }
37
+ public async do(): Promise<void> {
38
+ console.log('Checking credentials...');
39
+ }
40
+ public shouldUndo(): boolean {
41
+ return false;
42
+ }
43
+ public undo(): void {}
44
+ }
45
+
46
+ class ProvisionDbCommand extends Command<DeployData, { dbReady: boolean }> {
47
+ public readonly name = 'Provision Database';
48
+ public takeSnapshot(ctx: WorkflowContext<DeployData>) {
49
+ return { dbReady: ctx.data.dbReady };
50
+ }
51
+ public shouldDo(_ctx: WorkflowContext<DeployData>, snap: { dbReady: boolean }): boolean {
52
+ return !snap.dbReady;
53
+ }
54
+ public async do(ctx: WorkflowContext<DeployData>): Promise<void> {
55
+ ctx.data.dbReady = true;
56
+ console.log('Database ready');
57
+ }
58
+ public shouldUndo(ctx: WorkflowContext<DeployData>, snap: { dbReady: boolean }): boolean {
59
+ return ctx.data.dbReady !== snap.dbReady;
60
+ }
61
+ public async undo(ctx: WorkflowContext<DeployData>, snap: { dbReady: boolean }): Promise<void> {
62
+ ctx.data.dbReady = snap.dbReady;
63
+ console.log('Rolling back database');
64
+ }
65
+ }
66
+
67
+ const workflow = new CiWorkFlow<DeployData>({ data: { dbReady: false } });
68
+ workflow.register(new PreflightCommand());
69
+ workflow.register(new ProvisionDbCommand());
46
70
 
47
71
  workflow.registerParallel(
48
72
  'Deploy Services',
49
73
  [
50
- {
51
- command: {
52
- name: 'Deploy API',
53
- shouldDo: () => true,
54
- do: async () => console.log('API deployed'),
55
- undo: async () => console.log('API reverted'),
56
- },
57
- label: 'api',
58
- },
59
- {
60
- command: {
61
- name: 'Deploy Worker',
62
- shouldDo: () => true,
63
- do: async () => console.log('Worker deployed'),
64
- undo: async () => console.log('Worker reverted'),
65
- },
66
- label: 'worker',
67
- },
74
+ { command: deployApiCommand, label: 'api' },
75
+ { command: deployWorkerCommand, label: 'worker' },
68
76
  ],
69
77
  2 // maxConcurrency
70
78
  );
@@ -72,18 +80,16 @@ workflow.registerParallel(
72
80
  await workflow.run();
73
81
  ```
74
82
 
75
- ---
76
-
77
83
  ## Key Features
78
84
 
79
- - **Reverse-Order Saga Rollback** — Automatically runs `undo()` on completed steps (and failed partial steps inside groups) in reverse order when a failure occurs.
85
+ - **Snapshot-Driven Saga Lifecycle (`Command`)** — Every step explicitly implements `takeSnapshot(context)`, `shouldDo(context, snapshot)`, `do(context, snapshot)`, `shouldUndo(context, snapshot)`, and `undo(context, snapshot)`.
86
+ - **Scoped `WorkflowContext<TData>`** — Gives every command a read-only `context.workflow` view of step statuses (`DoStatus` / `UndoStatus`) alongside a typed shared `context.data` bag.
87
+ - **Reverse-Order Saga Rollback** — Automatically evaluates `shouldUndo()` and runs `undo()` on eligible `SUCCESS` and `FAILED` steps in reverse order when a failure occurs (`UndoStatus.SKIPPED` when `shouldUndo()` returns `false`).
80
88
  - **Sequential & Parallel Groups** — Nest `GroupCommand` chains inside `ParallelGroupCommand` forks with optional `maxConcurrency` limits, module `label` prefixes, and custom `subStep` numbering.
81
89
  - **Conditional Skipping (`shouldDo`)** — Return `false` to skip steps cleanly (`SKIPPED` / `N/A`) and exclude them from rollback.
82
90
  - **Teardown / Audit Mode (`continueOnError`)** — Run all steps forward without rollback and throw a composite error at the end.
83
91
  - **GitHub Actions `$GITHUB_STEP_SUMMARY`** — Automatically writes aligned Markdown status tables and `> [!CAUTION]` failure callouts on every state change.
84
92
 
85
- ---
86
-
87
93
  ## GitHub Step Summary Output
88
94
 
89
95
  When `GITHUB_STEP_SUMMARY` is set in GitHub Actions, `CiWorkFlow` renders:
@@ -100,44 +106,17 @@ When `GITHUB_STEP_SUMMARY` is set in GitHub Actions, `CiWorkFlow` renders:
100
106
  | 2.2 | [billing] Run Migrations | FAILED | REVERTED |
101
107
  ```
102
108
 
103
- ---
104
-
105
- ## Documentation
106
-
107
- Browse the full **Wiki Documentation & Interactive Simulator**:
108
- - [Overview & Concepts](https://thisispennyleung.github.io/saga-ci/#overview)
109
- - [Getting Started](https://thisispennyleung.github.io/saga-ci/#getting-started)
110
- - [Groups & Parallel Forks](https://thisispennyleung.github.io/saga-ci/#groups)
111
- - [Rollback & Error Handling](https://thisispennyleung.github.io/saga-ci/#rollback)
112
- - [API Reference](https://thisispennyleung.github.io/saga-ci/#api)
113
- - [Interactive Simulator](https://thisispennyleung.github.io/saga-ci/#simulator)
114
-
115
- ---
116
-
117
- ## Development
118
-
119
- ```bash
120
- npm run typecheck # Type-check src/ and examples/
121
- npm run build # Compile dist/*.js and dist/*.d.ts
122
- npm test # Run unit tests (31 tests, Node 24+)
123
- npm run example:basic # Run basic release pipeline example
124
- npm run example:rollback # Run parallel fork rollback example
125
- npm run example:continue # Run continueOnError teardown example
126
- ```
127
-
128
- ## Releasing to npm
129
-
130
- Pushing a version tag matching `v*.*.*` triggers [`.github/workflows/publish.yml`](.github/workflows/publish.yml), which checks that the tag matches `package.json`, runs `typecheck`, `build`, and `npm test`, and publishes with `--provenance --access public`.
109
+ ## Real GitHub Actions Demos (Before vs After)
131
110
 
132
- 1. Add your npm Automation/Granular Access Token as the `NPM_TOKEN` repository secret in GitHub.
133
- 2. Push a version tag:
134
-
135
- ```bash
136
- npm version patch && git push origin main --follow-tags
137
- # or for the current version:
138
- git tag v1.0.0 && git push origin v1.0.0
139
- ```
111
+ Compare real GitHub Actions runs executing each wiki scenario across **multi-job YAML (Before)** vs **single-job `saga-ci` (After)**:
140
112
 
141
- ## License
113
+ | Demo | Before (Multi-Job) | After (`saga-ci`) |
114
+ | :--- | :--- | :--- |
115
+ | **1. Happy Path** | [Run #3 (20s, 4 jobs)](https://github.com/ThisIsPennyLeung/saga-ci/actions/runs/47184205577) · [Screenshot](docs/assets/demo-1-happy-before.png) | [Run #2 (16s, 1 job)](https://github.com/ThisIsPennyLeung/saga-ci/actions/runs/47177472557) · [Screenshot](docs/assets/demo-1-happy-after.png) |
116
+ | **2. Rollback** | [Run #3 (47s, 6 jobs)](https://github.com/ThisIsPennyLeung/saga-ci/actions/runs/47184185918) · [Screenshot](docs/assets/demo-2-rollback-before.png) | [Run #2 (14s, 1 job)](https://github.com/ThisIsPennyLeung/saga-ci/actions/runs/47177503002) · [Screenshot](docs/assets/demo-2-rollback-after.png) |
117
+ | **3. Fan-out** | [Run #3 (27s, 6 jobs)](https://github.com/ThisIsPennyLeung/saga-ci/actions/runs/47184170199) · [Screenshot](docs/assets/demo-3-fan-out-before.png) | [Run #2 (18s, 1 job)](https://github.com/ThisIsPennyLeung/saga-ci/actions/runs/47177533461) · [Screenshot](docs/assets/demo-3-fan-out-after.png) |
118
+ | **4. Fan-out Rollback** | [Run #5 (50s, 11 jobs)](https://github.com/ThisIsPennyLeung/saga-ci/actions/runs/47184458849) · [Screenshot](docs/assets/demo-4-fan-out-rollback-before.png) | [Run #3 (20s, 1 job)](https://github.com/ThisIsPennyLeung/saga-ci/actions/runs/47189117791) · [Screenshot](docs/assets/demo-4-fan-out-rollback-after.png) |
119
+ | **5. Continue on Error** | [Run #3 (30s, 4 jobs)](https://github.com/ThisIsPennyLeung/saga-ci/actions/runs/47184151296) · [Screenshot](docs/assets/demo-5-continue-on-error-before.png) | [Run #2 (18s, 1 job)](https://github.com/ThisIsPennyLeung/saga-ci/actions/runs/47177592290) · [Screenshot](docs/assets/demo-5-continue-on-error-after.png) |
120
+ | **6. Rollback Fail** | [Run #3 (37s, 5 jobs)](https://github.com/ThisIsPennyLeung/saga-ci/actions/runs/47184135857) · [Screenshot](docs/assets/demo-6-rollback-fail-before.png) | [Run #2 (15s, 1 job)](https://github.com/ThisIsPennyLeung/saga-ci/actions/runs/47177620197) · [Screenshot](docs/assets/demo-6-rollback-fail-after.png) |
142
121
 
143
- [MIT](LICENSE)
122
+ > **Note:** Each screenshot preview and interactive simulator is also embedded directly on its corresponding [Documentation Wiki example page](https://thisispennyleung.github.io/saga-ci/#example-happy).
@@ -1,41 +1,48 @@
1
- import type { GroupEntry, ICommand, StepStatus, UndoStatus } from './ICommand.ts';
2
- export interface GroupItem {
1
+ import { Command, DoStatus, UndoStatus } from './ICommand.ts';
2
+ import type { GroupEntry, WorkflowContext } from './ICommand.ts';
3
+ export interface GroupItem<TData = unknown> {
3
4
  subStep: string;
4
5
  /** Explicit display step from GroupEntryOptions.subStep; undefined when the number is positional. */
5
6
  displaySubStep?: string;
6
- command: ICommand;
7
- hasUndo: boolean;
7
+ command: Command<TData, any>;
8
8
  label?: string;
9
- doStatus: StepStatus;
9
+ doStatus: DoStatus;
10
10
  undoStatus: UndoStatus;
11
+ snapshot?: unknown;
12
+ hasSnapshot: boolean;
11
13
  error?: Error;
12
14
  }
13
- export type ParallelItem = GroupItem;
14
- export declare class GroupCommand implements ICommand {
15
+ export type ParallelItem<TData = unknown> = GroupItem<TData>;
16
+ export declare class GroupCommand<TData = unknown> extends Command<TData, void> {
15
17
  readonly name: string;
16
- readonly items: GroupItem[];
18
+ readonly items: GroupItem<TData>[];
17
19
  readonly parallel: boolean;
18
20
  readonly maxConcurrency?: number;
19
21
  readonly continueOnError: boolean;
20
22
  onStepChange?: () => void;
21
- constructor(name: string, commands: GroupEntry[], baseStepNumber?: number | string, parallel?: boolean, maxConcurrency?: number, continueOnError?: boolean);
22
- shouldDo(): Promise<boolean>;
23
- do(): Promise<void>;
23
+ constructor(name: string, commands: GroupEntry<TData>[], baseStepNumber?: number | string, parallel?: boolean, maxConcurrency?: number, continueOnError?: boolean);
24
+ takeSnapshot(_context: WorkflowContext<TData>): void;
25
+ shouldDo(_context: WorkflowContext<TData>, _snapshot: void): boolean;
26
+ private toItemView;
27
+ private createFallbackContext;
28
+ private buildItemContext;
29
+ private executeItem;
30
+ do(context?: WorkflowContext<TData>, _snapshot?: void): Promise<void>;
24
31
  /**
25
32
  * Returns true when this group has at least one child (directly or in a nested chain)
26
- * that ran do() and either succeeded or failed, so it may have external effects to compensate.
33
+ * that captured a snapshot and started `do()` (succeeded or failed).
27
34
  */
28
35
  hasCompensableWork(): boolean;
36
+ shouldUndo(_context: WorkflowContext<TData>, _snapshot: void): boolean;
29
37
  /**
30
- * Compensates every child that started do() in this group, in reverse order.
31
- * Failed children are included because their partial effects must be reverted.
32
- * Skipped and never-started children are excluded. Every undo is attempted even if an
33
- * earlier one fails; a single aggregate error is thrown after all attempts.
38
+ * Evaluates `shouldUndo` and compensates eligible children in reverse order.
39
+ * Failed children are included because their partial effects may require restoration.
40
+ * Skipped, pending, shielded, and snapshot-failed children are excluded.
34
41
  */
35
- undo(): Promise<void>;
36
- private static requiresUndo;
42
+ undo(context?: WorkflowContext<TData>, _snapshot?: void): Promise<void>;
43
+ private static isRollbackEligible;
37
44
  }
38
- export declare class ParallelGroupCommand extends GroupCommand {
39
- constructor(name: string, commands: GroupEntry[], baseStepNumber?: number | string, maxConcurrency?: number, continueOnError?: boolean);
45
+ export declare class ParallelGroupCommand<TData = unknown> extends GroupCommand<TData> {
46
+ constructor(name: string, commands: GroupEntry<TData>[], baseStepNumber?: number | string, maxConcurrency?: number, continueOnError?: boolean);
40
47
  }
41
48
  //# sourceMappingURL=GroupCommand.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"GroupCommand.d.ts","sourceRoot":"","sources":["../src/GroupCommand.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAElF,MAAM,WAAW,SAAS;IACxB,OAAO,EAAE,MAAM,CAAC;IAChB,qGAAqG;IACrG,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,OAAO,EAAE,QAAQ,CAAC;IAClB,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,UAAU,CAAC;IACrB,UAAU,EAAE,UAAU,CAAC;IACvB,KAAK,CAAC,EAAE,KAAK,CAAC;CACf;AAED,MAAM,MAAM,YAAY,GAAG,SAAS,CAAC;AAErC,qBAAa,YAAa,YAAW,QAAQ;IAC3C,SAAgB,IAAI,EAAE,MAAM,CAAC;IAC7B,SAAgB,KAAK,EAAE,SAAS,EAAE,CAAM;IACxC,SAAgB,QAAQ,EAAE,OAAO,CAAC;IAClC,SAAgB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxC,SAAgB,eAAe,EAAE,OAAO,CAAC;IAClC,YAAY,CAAC,EAAE,MAAM,IAAI,CAAC;IAEjC,YACE,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,UAAU,EAAE,EACtB,cAAc,GAAE,MAAM,GAAG,MAAW,EACpC,QAAQ,GAAE,OAAe,EACzB,cAAc,CAAC,EAAE,MAAM,EACvB,eAAe,GAA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AAa,oBAAoB,CAAC,KAAK,GAAG,OAAO,CAAE,SAAQ,YAAY,CAAC,KAAK,CAAC;IAC5E,YACE,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,UAAU,CAAC,KAAK,CAAC,EAAE,EAC7B,cAAc,GAAE,MAAM,GAAG,MAAW,EACpC,cAAc,CAAC,EAAE,MAAM,EACvB,eAAe,GAAE,OAAe,EAGjC;CACF"}
@@ -1,4 +1,10 @@
1
- export class GroupCommand {
1
+ import { Command, DoStatus, UndoStatus } from './ICommand.js';
2
+ function assertIsCommand(value, label) {
3
+ if (!(value instanceof Command)) {
4
+ throw new TypeError(`${label} must be an instance of Command`);
5
+ }
6
+ }
7
+ export class GroupCommand extends Command {
2
8
  name;
3
9
  items = [];
4
10
  parallel;
@@ -6,15 +12,16 @@ export class GroupCommand {
6
12
  continueOnError;
7
13
  onStepChange;
8
14
  constructor(name, commands, baseStepNumber = '', parallel = false, maxConcurrency, continueOnError = false) {
15
+ super();
9
16
  this.name = name;
10
17
  this.parallel = parallel;
11
18
  this.maxConcurrency = maxConcurrency;
12
19
  this.continueOnError = continueOnError;
13
20
  commands.forEach((entry, idx) => {
14
- const cmd = 'command' in entry ? entry.command : entry;
15
- const hasUndo = 'hasUndo' in entry ? (entry.hasUndo ?? true) : true;
16
- const label = 'label' in entry ? entry.label : undefined;
17
- const displaySubStep = 'subStep' in entry ? entry.subStep : undefined;
21
+ const cmd = entry instanceof Command ? entry : entry.command;
22
+ assertIsCommand(cmd, `Group entry ${idx + 1} in "${name}"`);
23
+ const label = entry instanceof Command ? undefined : entry.label;
24
+ const displaySubStep = entry instanceof Command ? undefined : entry.subStep;
18
25
  const subStep = baseStepNumber ? `${baseStepNumber}.${idx + 1}` : String(idx + 1);
19
26
  // A nested group (branch chain) reports its own progress through this group,
20
27
  // so the status table refreshes while the nested chain runs.
@@ -25,43 +32,117 @@ export class GroupCommand {
25
32
  subStep,
26
33
  displaySubStep,
27
34
  command: cmd,
28
- hasUndo,
29
35
  label,
30
- doStatus: 'PENDING',
31
- undoStatus: hasUndo ? '-' : 'N/A',
36
+ doStatus: DoStatus.PENDING,
37
+ undoStatus: UndoStatus.NONE,
38
+ hasSnapshot: false,
32
39
  });
33
40
  });
34
41
  }
35
- async shouldDo() {
42
+ takeSnapshot(_context) {
43
+ return undefined;
44
+ }
45
+ shouldDo(_context, _snapshot) {
36
46
  return true;
37
47
  }
38
- async do() {
48
+ toItemView(item) {
49
+ return Object.freeze({
50
+ step: item.displaySubStep ?? item.subStep,
51
+ name: item.label ? `[${item.label}] ${item.command.name}` : item.command.name,
52
+ doStatus: item.doStatus,
53
+ undoStatus: item.undoStatus,
54
+ ...(item.error ? { error: item.error } : {}),
55
+ });
56
+ }
57
+ createFallbackContext(isRollingBack) {
58
+ const self = this;
59
+ const workflowView = {
60
+ get currentStep() {
61
+ return self.items[0]
62
+ ? self.toItemView(self.items[0])
63
+ : Object.freeze({
64
+ step: '',
65
+ name: self.name,
66
+ doStatus: DoStatus.PENDING,
67
+ undoStatus: UndoStatus.NONE,
68
+ });
69
+ },
70
+ get steps() {
71
+ return self.items.map((item) => self.toItemView(item));
72
+ },
73
+ currentPosition: 0,
74
+ continueOnError: self.continueOnError,
75
+ isRollingBack,
76
+ };
77
+ return {
78
+ data: {},
79
+ workflow: workflowView,
80
+ };
81
+ }
82
+ buildItemContext(parentContext, item, isRollingBack) {
83
+ const self = this;
84
+ const parentWorkflow = parentContext.workflow;
85
+ const scopedWorkflow = {
86
+ get currentStep() {
87
+ return self.toItemView(item);
88
+ },
89
+ get steps() {
90
+ return parentWorkflow.steps;
91
+ },
92
+ get currentPosition() {
93
+ return parentWorkflow.currentPosition;
94
+ },
95
+ get continueOnError() {
96
+ return parentWorkflow.continueOnError;
97
+ },
98
+ get isRollingBack() {
99
+ return parentWorkflow.isRollingBack || isRollingBack;
100
+ },
101
+ get failure() {
102
+ return parentWorkflow.failure;
103
+ },
104
+ };
105
+ return {
106
+ get data() {
107
+ return parentContext.data;
108
+ },
109
+ set data(value) {
110
+ parentContext.data = value;
111
+ },
112
+ workflow: scopedWorkflow,
113
+ };
114
+ }
115
+ async executeItem(item, baseContext) {
116
+ item.doStatus = DoStatus.RUNNING;
117
+ this.onStepChange?.();
118
+ const itemContext = this.buildItemContext(baseContext, item, false);
119
+ try {
120
+ item.snapshot = await item.command.takeSnapshot(itemContext);
121
+ item.hasSnapshot = true;
122
+ const shouldExecute = await item.command.shouldDo(itemContext, item.snapshot);
123
+ if (!shouldExecute) {
124
+ item.doStatus = DoStatus.SKIPPED;
125
+ item.undoStatus = UndoStatus.NA;
126
+ return;
127
+ }
128
+ await item.command.do(itemContext, item.snapshot);
129
+ if (item.doStatus === DoStatus.RUNNING) {
130
+ item.doStatus = DoStatus.SUCCESS;
131
+ }
132
+ }
133
+ catch (err) {
134
+ item.doStatus = DoStatus.FAILED;
135
+ item.error = err instanceof Error ? err : new Error(String(err));
136
+ throw item.error;
137
+ }
138
+ finally {
139
+ this.onStepChange?.();
140
+ }
141
+ }
142
+ async do(context, _snapshot) {
143
+ const baseContext = context ?? this.createFallbackContext(false);
39
144
  if (this.parallel) {
40
145
  console.log(`[GroupCommand] Starting parallel execution of ${this.items.length} tasks for "${this.name}"...`);
41
- const executeItem = async (item) => {
42
- item.doStatus = 'RUNNING';
43
- this.onStepChange?.();
44
- try {
45
- const shouldExecute = await item.command.shouldDo();
46
- if (!shouldExecute) {
47
- item.doStatus = 'SKIPPED';
48
- item.undoStatus = 'N/A';
49
- return;
50
- }
51
- await item.command.do();
52
- if (item.doStatus === 'RUNNING') {
53
- item.doStatus = 'SUCCESS';
54
- }
55
- }
56
- catch (err) {
57
- item.doStatus = 'FAILED';
58
- item.error = err instanceof Error ? err : new Error(String(err));
59
- throw item.error;
60
- }
61
- finally {
62
- this.onStepChange?.();
63
- }
64
- };
65
146
  let results;
66
147
  if (this.maxConcurrency && this.maxConcurrency > 0 && this.maxConcurrency < this.items.length) {
67
148
  results = new Array(this.items.length);
@@ -72,7 +153,7 @@ export class GroupCommand {
72
153
  const idx = nextIndex++;
73
154
  const item = this.items[idx];
74
155
  try {
75
- await executeItem(item);
156
+ await this.executeItem(item, baseContext);
76
157
  results[idx] = { status: 'fulfilled', value: undefined };
77
158
  }
78
159
  catch (err) {
@@ -83,7 +164,7 @@ export class GroupCommand {
83
164
  await Promise.all(workers);
84
165
  }
85
166
  else {
86
- results = await Promise.allSettled(this.items.map((item) => executeItem(item)));
167
+ results = await Promise.allSettled(this.items.map((item) => this.executeItem(item, baseContext)));
87
168
  }
88
169
  const failures = results.filter((r) => r.status === 'rejected');
89
170
  if (failures.length > 0) {
@@ -95,33 +176,16 @@ export class GroupCommand {
95
176
  console.log(`[GroupCommand] Starting sequential execution of ${this.items.length} tasks for "${this.name}"...`);
96
177
  const failures = [];
97
178
  for (const item of this.items) {
98
- item.doStatus = 'RUNNING';
99
- this.onStepChange?.();
100
179
  try {
101
- const shouldExecute = await item.command.shouldDo();
102
- if (!shouldExecute) {
103
- item.doStatus = 'SKIPPED';
104
- item.undoStatus = 'N/A';
105
- this.onStepChange?.();
106
- continue;
107
- }
108
- await item.command.do();
109
- if (item.doStatus === 'RUNNING') {
110
- item.doStatus = 'SUCCESS';
111
- }
180
+ await this.executeItem(item, baseContext);
112
181
  }
113
182
  catch (err) {
114
- item.doStatus = 'FAILED';
115
- item.error = err instanceof Error ? err : new Error(String(err));
116
- this.onStepChange?.();
183
+ const caught = err instanceof Error ? err : new Error(String(err));
117
184
  if (this.continueOnError) {
118
- failures.push(item.error);
185
+ failures.push(caught);
119
186
  continue;
120
187
  }
121
- throw item.error;
122
- }
123
- finally {
124
- this.onStepChange?.();
188
+ throw caught;
125
189
  }
126
190
  }
127
191
  if (failures.length > 0) {
@@ -132,42 +196,52 @@ export class GroupCommand {
132
196
  }
133
197
  /**
134
198
  * Returns true when this group has at least one child (directly or in a nested chain)
135
- * that ran do() and either succeeded or failed, so it may have external effects to compensate.
199
+ * that captured a snapshot and started `do()` (succeeded or failed).
136
200
  */
137
201
  hasCompensableWork() {
138
202
  return this.items.some((item) => {
139
203
  if (item.command instanceof GroupCommand) {
140
204
  return item.command.hasCompensableWork();
141
205
  }
142
- return item.doStatus === 'SUCCESS' || item.doStatus === 'FAILED';
206
+ return (item.hasSnapshot &&
207
+ (item.doStatus === DoStatus.SUCCESS || item.doStatus === DoStatus.FAILED));
143
208
  });
144
209
  }
210
+ shouldUndo(_context, _snapshot) {
211
+ return this.hasCompensableWork();
212
+ }
145
213
  /**
146
- * Compensates every child that started do() in this group, in reverse order.
147
- * Failed children are included because their partial effects must be reverted.
148
- * Skipped and never-started children are excluded. Every undo is attempted even if an
149
- * earlier one fails; a single aggregate error is thrown after all attempts.
214
+ * Evaluates `shouldUndo` and compensates eligible children in reverse order.
215
+ * Failed children are included because their partial effects may require restoration.
216
+ * Skipped, pending, shielded, and snapshot-failed children are excluded.
150
217
  */
151
- async undo() {
218
+ async undo(context, _snapshot) {
152
219
  console.log(`[GroupCommand] Initiating reverse-order rollback for group "${this.name}"...`);
220
+ const baseContext = context ?? this.createFallbackContext(true);
153
221
  const rollbackFailures = [];
154
222
  // do() has already settled every branch, so reverse item order is safe for parallel stages too.
155
223
  for (let i = this.items.length - 1; i >= 0; i--) {
156
224
  const item = this.items[i];
157
- if (!GroupCommand.requiresUndo(item)) {
225
+ if (!GroupCommand.isRollbackEligible(item)) {
158
226
  continue;
159
227
  }
160
- item.undoStatus = 'RUNNING';
161
- this.onStepChange?.();
228
+ const itemContext = this.buildItemContext(baseContext, item, true);
162
229
  try {
163
- await item.command.undo();
164
- if (item.undoStatus === 'RUNNING') {
165
- item.undoStatus = 'REVERTED';
230
+ const needsUndo = await item.command.shouldUndo(itemContext, item.snapshot);
231
+ if (!needsUndo) {
232
+ item.undoStatus = UndoStatus.SKIPPED;
233
+ continue;
234
+ }
235
+ item.undoStatus = UndoStatus.RUNNING;
236
+ this.onStepChange?.();
237
+ await item.command.undo(itemContext, item.snapshot);
238
+ if (item.undoStatus === UndoStatus.RUNNING) {
239
+ item.undoStatus = UndoStatus.REVERTED;
166
240
  }
167
241
  }
168
242
  catch (err) {
169
243
  const caught = err instanceof Error ? err : new Error(String(err));
170
- item.undoStatus = 'FAILED';
244
+ item.undoStatus = UndoStatus.FAILED;
171
245
  item.error = caught;
172
246
  rollbackFailures.push(caught);
173
247
  }
@@ -180,14 +254,18 @@ export class GroupCommand {
180
254
  throw new Error(`Group rollback encountered ${rollbackFailures.length} failure(s) in "${this.name}": ${errorMsgs}`);
181
255
  }
182
256
  }
183
- static requiresUndo(item) {
184
- if (!item.hasUndo || item.undoStatus === 'N/A' || item.undoStatus === 'SHIELDED') {
257
+ static isRollbackEligible(item) {
258
+ if (item.doStatus === DoStatus.PENDING ||
259
+ item.doStatus === DoStatus.SKIPPED ||
260
+ item.undoStatus === UndoStatus.NA ||
261
+ item.undoStatus === UndoStatus.SHIELDED) {
185
262
  return false;
186
263
  }
187
264
  if (item.command instanceof GroupCommand) {
188
265
  return item.command.hasCompensableWork();
189
266
  }
190
- return item.doStatus === 'SUCCESS' || item.doStatus === 'FAILED';
267
+ return (item.hasSnapshot &&
268
+ (item.doStatus === DoStatus.SUCCESS || item.doStatus === DoStatus.FAILED));
191
269
  }
192
270
  }
193
271
  export class ParallelGroupCommand extends GroupCommand {