@cratis/pi 7.5.2 → 7.6.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.
@@ -48,6 +48,8 @@ Tagged **[contract]** (framework-enforced) or **[convention]** (house default).
48
48
  16. **[convention] Use the Cratis dialogs** — `CommandDialog` from `@cratis/components/CommandDialog`, `Dialog` from `@cratis/components/Dialogs`; never a vendor or hand-rolled modal. The default frontend stack is Cratis Components **4.x** (Components-owned markup, `--cratis-*` tokens, `pt`/`data-cratis-part` parts; no PrimeReact dependency) — **not** Tailwind (Tailwind is one supported way to write the token-mapping CSS, not the generic default).
49
49
  17. **[convention] One slice is one unit** — creating/renaming/moving/deleting a slice means doing the same to every artifact (the `.cs`, every `when_*/`, every `.tsx`, the composition import/JSX, the route).
50
50
 
51
+ **[convention]** Return immediate external work chosen by a command as a command operation, not a service write inside `Handle()`; durable after-commit work belongs in reactors. Direct service calls remain supported when the decision needs their result. Audit custom `ICommandExecutionScope`s first — every one must implement `ICommandOperationExecutionScope` or operation-bearing commands are rejected. See **cratis-arc-command-operation** (verified at Arc v22.48.1).
52
+
51
53
  ## Implementation Workflow
52
54
 
53
55
  - **Phase 0 — Model.** Confirm Module/Feature, slice name, slice type, domain rules; for new behavior or unclear event vocabulary run the **cratis-chronicle-event-modeling** skill first.
@@ -68,7 +68,7 @@ The Chronicle + Arc stack has clear layer boundaries. Violating them creates cou
68
68
 
69
69
  **Rules:**
70
70
  - Domain types must not reference EF Core, MongoDB, or HTTP concepts directly.
71
- - Command handlers express intent in domain terms — they delegate persistence and I/O to injected collaborators.
71
+ - Command handlers express intent in domain terms — they delegate persistence and I/O to injected collaborators. For immediate inline work chosen by an Arc command, prefer returned operations over service writes inside `Handle()`; see **cratis-arc-command-operation**. Durable after-commit work remains a reactor/outbox concern.
72
72
  - Projections build read models; they must not trigger commands or produce side effects.
73
73
  - Reactors handle side effects; they must not directly read or write the event log.
74
74
 
@@ -339,6 +339,8 @@ These are the building blocks. Each type has a specific role in the vertical sli
339
339
  | `IConstraint` | Constraint definition — enforced server-side by Chronicle at append time |
340
340
  | `AggregateRoot` | Chronicle aggregate root with `Apply()` and `Commit()` |
341
341
  | `ICommandPipeline` | Programmatic command execution from reactors or other code |
342
+ | `ICommandOperation` | `Cratis.Arc.Commands` marker for returned inline work with `Execute` and optional `Compensate`; see **cratis-arc-command-operation** |
343
+ | `CommandOperations` | Explicit ordered server-only operation batch; use instead of bare operation arrays/enumerables |
342
344
  | `EventContext` | Event metadata: `Occurred`, `SequenceNumber`, `CorrelationId`, `EventSourceId`, etc. |
343
345
  | `ISubject<T>` | Observable query return type — enables real-time push |
344
346
  | `IMongoCollection<T>` | MongoDB collection — use `.Observe()` for reactive queries |
@@ -174,6 +174,7 @@ public class StockKeeping : IReactor
174
174
 
175
175
  - **A reactor runs with no principal.** It is not an HTTP request, so a returned command gated by `[Roles]`/`[Authorize]` is denied. Opt in on the reactor **class** with `[ExecuteCommandsAsSystem("<role>", …)]` (`Cratis.Arc.Chronicle.Reactors`), naming only the roles its returned commands need. The attribute covers **returned** commands only.
176
176
  - Mark the handler `[OnceOnly]` — a replay would otherwise execute the command again. Replay exclusion is not exactly-once: recovery re-delivers, so the command itself must be safe to repeat.
177
+ - A reactor retry can execute the command's operations again; inline operations are not a substitute for reactor/outbox durability — see **cratis-arc-command-operation** (verified at Arc v22.48.1).
177
178
  - The imperative alternative — inject `ICommandPipeline` and call `Execute(command)` — remains supported (see the **cratis-arc-command-execution** skill). It needs `[OnceOnly]` (`ARCCHR0006` warns otherwise), its `CommandResult` must be inspected (a denied or invalid result is otherwise discarded), and it needs its own execution context: `[ExecuteCommandsAsSystem]` does not apply to it.
178
179
 
179
180
  ## External event stores (outbox / inbox)
@@ -57,6 +57,7 @@ public class and_all_information_is_valid : Specification
57
57
  - **Seed prior state through `_scenario.Given` or `_scenario.Services`.** `_scenario.Given.ForEventSource(id).Events(...)` materializes the seeded events into an **in-memory read-model dictionary** the harness answers keyed reads from — it never reaches the event log (see the false-greens list below). To populate the DCB read models the validator/`Provide()`/`Handle()` inject, substitute `IReadModels` and register it (`_scenario.Services.Replace(new ServiceDescriptor(typeof(IReadModels), mock))`, mocking `GetInstanceById(...)`) or register projections with `_scenario.Services.AddReadModels(...)`.
58
58
  - **Validator/`Provide()` dependencies:** register them in `_scenario.Services`; Arc testing discovers the concrete validator automatically. When several specs need different injected validator states, test rejected variants by instantiating the validator directly (per-scenario state can be order-sensitive under parallel xUnit).
59
59
  - **`Provide()`:** drive it through `CommandScenario` end-to-end; when the handler's decision is pure given provided data, also test `Handle(providedValue)` directly.
60
+ - **Command operations:** use **cratis-arc-command-operation** for decision/adapter specs and real `CommandScenario` execution, forward failure, compensation, and Chronicle commit rejection; a direct `Handle()` does not execute operations.
60
61
 
61
62
  #### Validation-failure assertions — non-negotiable
62
63
 
@@ -73,6 +73,8 @@ The command carries input from the caller. `Handle()` is defined directly on the
73
73
 
74
74
  > This application is event-sourced, so the guidance below assumes a command's `Handle()` returns event(s) that Arc+Chronicle appends. Arc itself is a standalone CQRS framework (see [general.md](./general.md)) — a command may legitimately return a response or `void` and do its work through injected services when a slice isn't event-sourced; the return-shape and "never inject `IEventLog`" rules are the event-sourced default, not universal Arc laws.
75
75
 
76
+ **[convention]** Return immediate external work chosen by a command as a command operation rather than performing it inside `Handle()`; durable after-commit work belongs in reactors. Operations also work without Chronicle; direct service calls remain supported when the decision needs their result. Audit custom `ICommandExecutionScope`s first — every one must implement `ICommandOperationExecutionScope` or operation-bearing commands are rejected. See **cratis-arc-command-operation** (verified at Arc v22.48.1).
77
+
76
78
  ### The decision matrix — where each rule lives **[contract]**
77
79
 
78
80
  `Handle()` assumes the command is valid and constructs the event(s). Pick the mechanism by what the decision *is*:
@@ -136,6 +138,8 @@ public record PlaceOrder(OrderId OrderId, CustomerId CustomerId) : ICanProvideEv
136
138
 
137
139
  Use `Provide()` for IO/fetched/computed data a valid command needs (explicit-key read-model lookups, external services, snapshots). It may short-circuit with `ValidationResult` / `AuthorizationResult` / `Result<TProvided, ValidationResult>` when the supplied data is missing or unusable. Keep IO in `Provide()` and the decision in `Handle()`. Do **not** write a pass-through `Provide()` that only wraps a read model `Handle(...)` could take directly, and do **not** duplicate the same rejection in both the validator and `Provide()` — pick one owner.
138
140
 
141
+ **[convention]** `Provide()` acquires decision inputs, not the writes moved out of `Handle()`; declare those as operations and let Arc execute them. Operations cannot return receipts into the decision — see **cratis-arc-command-operation**.
142
+
139
143
  ### `Handle()` return shapes **[contract]**
140
144
 
141
145
  Return the event(s) directly — Arc appends them; never inject `IEventLog` to append the primary event. If there is no `await`, return the value directly (no `Task<T>`/`Task.FromResult`).
@@ -147,9 +151,10 @@ Return the event(s) directly — Arc appends them; never inject `IEventLog` to a
147
151
  | `(TResponse, TEvent)` | a response value plus an event |
148
152
  | `IEnumerable<object>` | multiple events; `EventForEventSourceId(id, @event)` wrappers for cross-stream |
149
153
  | `Result<TEvent, ValidationResult>` | success event or a typed validation error (concurrency-sensitive rule) |
154
+ | `ICommandOperation` / `CommandOperations` | immediate server-side work after event enrollment, never the client response |
150
155
  | `void` | no event |
151
156
 
152
- **How Arc picks the response vs. metadata:** for an `(A, B)` tuple, each element is checked — exactly one element *without* a registered event handler becomes the `CommandResult<...>` response; if all are events, there is no response; **more than one un-handled element throws**. A `Result<TSuccess, TError>` has its inner value unwrapped and processed by these same rules (so `Result<(TId, TEvent), ValidationResult>` is processed as a tuple). A `(TEvent, Subject)` tuple's `Subject` is treated as **append metadata** (not a response) and overrides the resolved compliance subject. A `(TIdConcept, TEvent)` tuple opens a new stream — the id concept is the event source for that event.
157
+ **How Arc picks the response vs. metadata:** for an `(A, B)` tuple, each element is checked — operations are server-consumed, and at most one ordinary element without a response-value handler becomes the `CommandResult<...>` response; if all are server-consumed, there is no response; **more than one un-handled element throws**. A `Result<TSuccess, TError>` has its inner value unwrapped and processed by these same rules (so `Result<(TId, TEvent), ValidationResult>` is processed as a tuple). A `(TEvent, Subject)` tuple's `Subject` is treated as **append metadata** (not a response) and overrides the resolved compliance subject. A `(TIdConcept, TEvent)` tuple opens a new stream — the id concept is the event source for that event.
153
158
 
154
159
  ### Stream metadata & DCB concurrency **[contract]**
155
160
 
@@ -8,7 +8,8 @@ license: MIT
8
8
 
9
9
  A command is a record that carries the user's intent and owns its own handler.
10
10
  Arc discovers it, runs authorization and validation, calls `Handle()`, and turns
11
- whatever `Handle()` returns into appended events, a response, or both.
11
+ whatever `Handle()` returns into events, server-executed operations, a response,
12
+ or a combination.
12
13
 
13
14
  ## Verified product sources
14
15
 
@@ -25,6 +26,8 @@ whatever `Handle()` returns into appended events, a response, or both.
25
26
 
26
27
  Reverify before claiming support for another version. Arc without Chronicle is a
27
28
  supported setup; everything on this page that appends events needs Chronicle.
29
+ Operation guidance below is verified at **Arc v22.48.1**; see
30
+ `cratis-arc-command-operation` for its source and recovery contract.
28
31
 
29
32
  ## Declare the command
30
33
 
@@ -57,6 +60,8 @@ Rules the framework actually enforces:
57
60
  when a `[Command]` type has no public instance `Handle`.
58
61
  - `ARC0002` warns when a type has `Handle` but no `[Command]`; `ARC0007` warns
59
62
  when a command is a `class` rather than a `record`.
63
+ - For returned operations, `ARC0016` checks method shapes, `ARC0017` rejects bare
64
+ operation collections, and `ARC0018` checks generated-invoker accessibility.
60
65
  - Name the command as the action — `OpenDebitAccount`, not
61
66
  `OpenDebitAccountCommand`.
62
67
  - `Handle` parameters are resolved from DI, so ask for services there rather
@@ -72,7 +77,9 @@ Chronicle-backed identities the `EventSourceId<T>` base — see the
72
77
  ## Choose the return shape
73
78
 
74
79
  `Handle()`'s return value is dispatched by its runtime type. The shape decides
75
- what is appended and what the caller gets back.
80
+ what is appended and what the caller gets back. Operations are the exception:
81
+ the *declared* return type must name `ICommandOperation`/`CommandOperations`
82
+ (directly or in a tuple, `Task`, `Result`/`OneOf`) for Arc to execute them.
76
83
 
77
84
  | Return | What Arc does |
78
85
  | --- | --- |
@@ -80,6 +87,8 @@ what is appended and what the caller gets back.
80
87
  | `IEnumerable<object>` of registered events | Appends each to the command's event source id |
81
88
  | `EventForEventSourceId(id, @event)` | Appends that one event to `id` |
82
89
  | A collection mixing events and `EventForEventSourceId` | Appends each to its own target, wrappers to their id and plain events to the command's |
90
+ | `ICommandOperation` (or a concrete operation) | Executes server-side after returned events are enrolled; never the response |
91
+ | `CommandOperations` | Executes an explicit batch sequentially after event enrollment; never the response |
83
92
  | A tuple | Each element is dispatched on its own; the one element nothing can handle becomes the response |
84
93
  | Anything else | Becomes the response payload |
85
94
  | `Result<TEvent, ValidationResult>` | Success appends the event; failure becomes a validation failure |
@@ -88,13 +97,24 @@ what is appended and what the caller gets back.
88
97
  See [handler shapes](references/handler-shapes.md) for the dispatch order, the
89
98
  tuple rule, and the exact failure modes.
90
99
 
100
+ For immediate inline side effects chosen by the command, prefer returning an
101
+ operation rather than calling the service inside `Handle()`. Arc executes the
102
+ work and selects optional compensation from the commit facts. Direct service
103
+ calls remain supported when their result is needed for the decision; durable
104
+ after-commit work belongs in reactors/outboxes/workflows. Use
105
+ `cratis-arc-command-operation` rather than a custom response handler or rollback
106
+ stack for this application work.
107
+
91
108
  Two consequences worth knowing before writing the first command:
92
109
 
93
110
  - **The tuple is how a create command returns its new id.** An
94
111
  `EventSourceId`-derived value in the tuple is not appendable, so it becomes the
95
112
  response — and the response, when it is an event-source id value, is also what
96
113
  the events in that same tuple are appended to. Returning more than one
97
- unhandleable element throws `MultipleUnhandledTupleValues`.
114
+ unhandleable element throws `MultipleUnhandledTupleValues`. When the command
115
+ also returns an operation keyed by that id, have the caller supply the id
116
+ instead of calling `New()` in `Handle()`, so a retried request reuses the same
117
+ ownership key.
98
118
  - **Events never carry their own event source.** Cross-stream writes use
99
119
  `EventForEventSourceId`; they are not expressed by a property on the event.
100
120
 
@@ -265,6 +285,8 @@ Components guidance, not to this skill.
265
285
  - Adding or changing a rule on an existing command: the Arc command validation
266
286
  guidance.
267
287
  - Executing an existing command from backend code: `cratis-arc-command-execution`.
288
+ - Declaring inline work, compensation, or operation specs:
289
+ `cratis-arc-command-operation`.
268
290
  - Append-time uniqueness or concurrency constraints: the Chronicle event
269
291
  constraints guidance.
270
292
  - Choosing the concept or identity type for a value: `cratis-fundamentals-concept`.
@@ -276,6 +298,8 @@ Components guidance, not to this skill.
276
298
  - The return shape matches what the command is supposed to do, and any
277
299
  cross-stream event is wrapped in `EventForEventSourceId`.
278
300
  - At most one tuple element is unhandleable.
301
+ - Inline work follows `cratis-arc-command-operation`: explicit operation return
302
+ shapes, no duplicate direct write, and tested execution/recovery boundaries.
279
303
  - The event source id resolves from exactly one place; `ARCCHR0002` is silent.
280
304
  - `[Key]`, where used, is `Cratis.Chronicle.Keys.KeyAttribute`.
281
305
  - No `IEventLog` is injected into `Handle`.
@@ -1,7 +1,8 @@
1
1
  # Handler shapes and how Arc dispatches them
2
2
 
3
3
  Verified against `Cratis.Arc.Core` and `Cratis.Arc.Chronicle` `22.16.0` with
4
- `Cratis.Chronicle` `18.3.0`.
4
+ `Cratis.Chronicle` `18.3.0`. Operation dispatch additions are verified against
5
+ Arc **v22.48.1**, `CommandPipeline` and `CommandOperationExecution`.
5
6
 
6
7
  ## The pipeline around `Handle`
7
8
 
@@ -14,8 +15,11 @@ One command execution runs in this order:
14
15
  stopping at the first blocking verdict;
15
16
  5. resolve `Handle`'s arguments, which is where `Provide()` runs;
16
17
  6. invoke `Handle`;
17
- 7. dispatch the returned value;
18
- 8. complete the execution scopes in reverse order.
18
+ 7. classify returned values and preflight operation metadata/dependencies;
19
+ 8. dispatch control/other server values (including Chronicle event enrollment),
20
+ then execute declared operations sequentially while the command is successful;
21
+ 9. complete the execution scopes in reverse order, select eligible operation
22
+ recovery from commitment facts, and finalize backend observations.
19
23
 
20
24
  If the final result is not successful, the response is **cleared** before it is
21
25
  serialized. A caller never receives both a failure and a payload.
@@ -27,7 +31,10 @@ leaving the authorization verdict at its permissive default.
27
31
  ## Dispatch
28
32
 
29
33
  The returned value is dispatched on its **runtime** type, not on the method's
30
- declared return type.
34
+ declared return type. The one exception is operation participation: Arc decides
35
+ from the **declared** return type whether a command may carry operations, and
36
+ only then dispatches concrete operations by runtime type. An operation hidden
37
+ behind `object` is rejected, and one inside `IEnumerable<object>` is not executed.
31
38
 
32
39
  - `Task<T>` and `ValueTask<T>` are awaited first, then the inner value is
33
40
  dispatched. (`ARC0010` warns when a synchronous result is wrapped in a `Task`
@@ -39,7 +46,18 @@ declared return type.
39
46
  conversions, so `return new SomethingHappened(...)` and
40
47
  `return ValidationResult.Error("...")` both compile in the same method.
41
48
  - A tuple has every non-null element dispatched independently.
42
- - Anything no handler claims becomes the response payload.
49
+ - `ICommandOperation` and `CommandOperations` are reserved for operation
50
+ processing, not ordinary response handlers or the client response. Null is
51
+ absent; raw operation collections are rejected (`ARC0017`).
52
+ - Other unclaimed values become the response payload. When operations
53
+ participate, control values are reserved for pipeline handling instead.
54
+
55
+ When operation values participate, Arc flattens tuples and active union branches,
56
+ preflights both operation methods' dependencies, and selects at most one ordinary
57
+ response. Control values are processed before other server values regardless of
58
+ tuple order. Returned events enroll before operations execute, and scopes complete
59
+ afterward. Custom response handlers never receive operation values a second time.
60
+ See `cratis-arc-command-operation` for compensation and unsupported nesting.
43
61
 
44
62
  ## What claims an event
45
63
 
@@ -72,8 +90,9 @@ left alone.
72
90
 
73
91
  Within a tuple:
74
92
 
75
- 1. every element is offered to the handlers;
76
- 2. the elements nothing can handle are candidates for the response;
93
+ 1. operations are reserved for their own phase; other elements are classified
94
+ for response/control handling;
95
+ 2. ordinary elements nothing can handle are candidates for the response;
77
96
  3. **more than one unhandleable element throws `MultipleUnhandledTupleValues`** —
78
97
  Arc cannot decide which one is the response;
79
98
  4. the single unhandleable element is set as the response *before* the
@@ -9,7 +9,8 @@ license: MIT
9
9
  `ICommandPipeline` is the same entry point the HTTP boundary uses. Everything
10
10
  downstream of the entry point is identical: authorization filters, validation
11
11
  filters, argument resolution including `Provide()`, `Handle()`, and response
12
- dispatch.
12
+ dispatch. `Execute` also runs returned command operations and completes eligible
13
+ recovery; calling `Handle()` directly only returns their declarations.
13
14
 
14
15
  ## Verified product sources
15
16
 
@@ -20,7 +21,9 @@ dispatch.
20
21
 
21
22
  > Re-verified at the versions above by **symbol and signature**: every type, attribute and member this skill names exists at that tag, and the public surface it describes is unchanged since the previous verification (Chronicle 16.45.x / Arc 22.10.4 — the Chronicle 16→18 client diff is converters, options and doc comments; no type was removed or renamed). Behavior claims were verified at the earlier tag unless a section says otherwise.
22
23
 
23
- Reverify before claiming support for another version.
24
+ Reverify before claiming support for another version. Operation execution,
25
+ nesting restrictions, and backend recovery members below are verified at
26
+ **Arc v22.48.1**; see `cratis-arc-command-operation` for sources and limits.
24
27
 
25
28
  ## When this is the wrong tool
26
29
 
@@ -29,6 +32,14 @@ validation. It is not the way to append an event to another stream from inside a
29
32
  handler — return an `EventForEventSourceId` from `Handle()` instead, and never
30
33
  inject `IEventLog` (`ARCCHR0007`).
31
34
 
35
+ Do not call `ICommandPipeline` for a same-host nested command while an
36
+ operation-capable command runs (from its `Provide()`, `Handle()`, validators,
37
+ `Execute()` or `Compensate()`), nor execute an operation-capable command nested
38
+ inside another command: the flat operation boundary refuses it and the child
39
+ never runs. Ignoring
40
+ the child's failed result still rejects the executing batch; during compensation
41
+ it records a failed compensator. Compose operation declarations instead.
42
+
32
43
  ## Inject and execute
33
44
 
34
45
  > **Reactors have a declarative alternative.** With the Arc Chronicle integration a
@@ -107,6 +118,14 @@ crash.
107
118
  | `IsValid` | Derived: no blocking validation results survived. `ValidationResults` carries them |
108
119
  | `HasExceptions` | Derived: `ExceptionMessages` is non-empty. `ExceptionStackTrace` has the detail |
109
120
  | `CorrelationId` | The pipeline-wide id to correlate logs and traces on |
121
+ | `Recovery` | Backend-only nullable commit/recovery summary when operations participate |
122
+ | `OperationOutcomes` | Backend-only observations of entered operations and their compensation |
123
+
124
+ `Recovery` and `OperationOutcomes` are excluded from HTTP JSON and the TypeScript
125
+ result contract. **A failed result is not proof that nothing committed.** Known
126
+ commit suppresses automatic reversal; unknown/mixed commitment is indeterminate,
127
+ not permission to compensate or retry. Consult `cratis-arc-command-operation`
128
+ before interpreting these observations.
110
129
 
111
130
  A command with no registered handler comes back with an exception message naming
112
131
  the command type rather than throwing.
@@ -154,5 +173,7 @@ mis-marking it to silence the warning.
154
173
 
155
174
  - Defining the command or choosing its `Handle()` return shape:
156
175
  `cratis-arc-command`.
176
+ - Declaring operations or diagnosing their execution/recovery:
177
+ `cratis-arc-command-operation`.
157
178
  - Adding or changing a rule: the Arc command validation guidance.
158
179
  - Designing what a reactor should observe: the Chronicle reactor guidance.
@@ -0,0 +1,2 @@
1
+ Copyright (c) Cratis. All rights reserved.
2
+ Licensed under the MIT license. See LICENSE file in the project root for full license information.
@@ -0,0 +1,277 @@
1
+ ---
2
+ name: cratis-arc-command-operation
3
+ description: Declare immediate inline work as a Cratis Arc ICommandOperation returned by a model-bound command, with optional compensation and commit-aware recovery. Use when moving service writes out of Handle(), choosing operation return shapes, diagnosing recovery, or specifying execution and compensation through CommandScenario. Do not use for durable after-commit delivery, validation-only changes, or framework return-type extensions through response value handlers.
4
+ license: MIT
5
+ ---
6
+
7
+ # Return work from an Arc command
8
+
9
+ A command should be able to decide which seat to reserve without reserving it
10
+ in the decision spec. `Handle()` returns immutable descriptions of the work;
11
+ Arc executes them and, when the commit boundary permits, compensates attempted
12
+ work. You write the business reversal, not a rollback stack.
13
+
14
+ **Command operations are the recommended way to express immediate inline side
15
+ effects in model-bound commands.** Direct service calls remain supported.
16
+ Chronicle is not required.
17
+
18
+ ## Verified product sources
19
+
20
+ | Package / source assembly | Verified version | Purpose |
21
+ | --- | --- | --- |
22
+ | `Cratis.Arc.Core` | `22.48.1` | `Cratis.Arc.Commands`: operation declarations, pipeline, scopes, recovery observations |
23
+ | `Cratis.Arc.Core.CodeAnalysis` / `Cratis.Arc.Core.Generators` | `22.48.1` | ARC0016–ARC0018 and typed invocation; generator ships inside Core, not as a standalone package |
24
+ | `Cratis.Arc.ProxyGenerator` | `22.48.1` | Excludes operations and batches from the client response |
25
+ | `Cratis.Arc.Testing` | `22.48.1` | `Cratis.Arc.Testing.Commands.CommandScenario<TCommand>` and operation assertions |
26
+ | `Cratis.Arc.Chronicle` / `Cratis.Arc.Chronicle.Testing` | `22.48.1` | Deferred event commitment and real in-process constraint-rejection specs |
27
+
28
+ Verified at **Arc v22.48.1**, against the
29
+ [operation docs](https://github.com/Cratis/Arc/blob/v22.48.1/Documentation/backend/csharp/commands/operations/index.md),
30
+ [execution reference](https://github.com/Cratis/Arc/blob/v22.48.1/Documentation/backend/csharp/commands/operations/reference.md),
31
+ `Source/DotNET/Arc.Core/Commands/`, the analyzer/generator, and the testing
32
+ sources. Reverify for other versions. These are C# APIs, not the separate
33
+ Arc for TypeScript server API.
34
+
35
+ ## Choose the boundary
36
+
37
+ | Need | Use |
38
+ | --- | --- |
39
+ | Acquire data for the decision | `Provide()` or explicitly supplied decision inputs |
40
+ | Reject input or a business decision | Validators or a recognized `ValidationResult` alternative |
41
+ | Return information | An ordinary response |
42
+ | Perform immediate external work chosen by the command | `ICommandOperation` |
43
+ | Reverse attempted work after an eligible failure | Optional `Compensate()` |
44
+ | Record durable Chronicle facts | Returned events, enrolled for deferred commitment |
45
+ | Reliable work after commit: email, payments, retriable webhooks | A reactor, outbox, or durable workflow; **not inline operations** |
46
+ | Use an external result to make the decision or response | An explicit service call; operations cannot return receipts |
47
+ | Extend framework interpretation of a specialized return type | Response value handlers, not application operation orchestration |
48
+
49
+ Do not disguise a write as `Provide()`. Supply identities, clock values, and
50
+ state before `Handle()`; returning operations does not make hidden I/O pure.
51
+
52
+ ## Declare the work and its reversal
53
+
54
+ Use an immutable record implementing `ICommandOperation`. Business data belongs
55
+ in properties; services belong in method parameters. This example reuses the
56
+ application-owned `ReservationId`, `SeatId`, and `ISeatReservations` from Arc's
57
+ [reservation example](https://github.com/Cratis/Arc/blob/v22.48.1/Documentation/backend/csharp/commands/operations/implementing.md).
58
+ The provider's `Reserve` and `Cancel` methods return `Task`; they are not Arc APIs.
59
+
60
+ ```csharp
61
+ // Copyright (c) Cratis. All rights reserved.
62
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
63
+
64
+ using System.Threading;
65
+ using System.Threading.Tasks;
66
+ using Cratis.Arc.Commands;
67
+ using Cratis.Arc.Commands.ModelBound;
68
+
69
+ namespace SeatBooking;
70
+
71
+ public sealed record ReserveSeat(ReservationId ReservationId, SeatId SeatId)
72
+ : ICommandOperation
73
+ {
74
+ public Task Execute(ISeatReservations reservations, CancellationToken cancellationToken) =>
75
+ reservations.Reserve(ReservationId, SeatId, cancellationToken);
76
+
77
+ public Task Compensate(ISeatReservations reservations, CancellationToken cancellationToken) =>
78
+ reservations.Cancel(ReservationId, cancellationToken);
79
+ }
80
+
81
+ [Command]
82
+ public record BookSeat(ReservationId ReservationId, SeatId SeatId)
83
+ {
84
+ public (ReservationId Response, ReserveSeat Operation) Handle() =>
85
+ (ReservationId, new ReserveSeat(ReservationId, SeatId));
86
+ }
87
+ ```
88
+
89
+ Register the application provider through the host's normal DI. No separate
90
+ operation-handler or response-value-handler registration is needed.
91
+
92
+ - Exactly one public, non-generic instance `Execute`; at most one optional
93
+ public, non-generic instance `Compensate`.
94
+ - Return only `void`, `Task`, or `ValueTask`. No values, `Task<T>`, or
95
+ `ValueTask<T>`: neither method supplies more pipeline values or a receipt.
96
+ - Method-parameter DI resolves required services from the originating command's
97
+ provider. Each method may request at most one `CancellationToken`.
98
+ - At most one `CommandOperationFailure` parameter, **only on `Compensate()`**.
99
+ - No `async void`, static/generic methods, overloads, optional/`params`/by-ref
100
+ arguments, pointers, or service-locator parameters. Do not capture services.
101
+ - `ARC0016` diagnoses invalid methods; `ARC0017` rejects bare operation
102
+ collections; `ARC0018` requires accessible, non-file-local, non-generic
103
+ public/internal operation types and accessible non-generic containing types.
104
+
105
+ Omit `Compensate()` when there is no meaningful reversal; Arc does not invent
106
+ one. Full contract: [execution and recovery](references/execution-and-recovery.md).
107
+
108
+ ## Return one, none, or many
109
+
110
+ | `Handle()` return | Meaning |
111
+ | --- | --- |
112
+ | Concrete operation / `ICommandOperation` | One server-executed operation |
113
+ | Nullable operation | Null is absent and skipped |
114
+ | `CommandOperations` | Explicit ordered batch; `[]` and `default(CommandOperations)` are empty |
115
+ | Tuple | Operations, other server-handled values, and at most one client response |
116
+ | `Result` / `OneOf` | Only the active branch, including a tuple alternative |
117
+ | `Task<T>` / `ValueTask<T>` | Await first, then classify the supported inner shape |
118
+
119
+ This handler fragment assumes `First`/`Second` reservation IDs and
120
+ `FirstSeat`/`SecondSeat` seat IDs are command inputs:
121
+
122
+ ```csharp
123
+ public CommandOperations Handle() =>
124
+ [
125
+ new ReserveSeat(First, FirstSeat),
126
+ new ReserveSeat(Second, SecondSeat)
127
+ ];
128
+ ```
129
+
130
+ **Never return a raw array or `IEnumerable<ICommandOperation>` as a batch.**
131
+ `CommandOperations` materializes membership once and rejects null elements.
132
+ Ordinary collections are response data, not an implicit operation executor.
133
+ **Keep the signature statically operation-bearing.** Arc decides whether a
134
+ command participates from `Handle()`'s *declared* return type, and unwraps only
135
+ tuples and `Result`/`OneOf` branches. So:
136
+
137
+ - An operation returned as a top-level value of an `object`-typed `Handle()`
138
+ (alone or inside a tuple) is rejected with `InvalidCommandOperation`.
139
+ - **An operation placed inside `IEnumerable<object>` or `object[]` — the usual
140
+ multi-event shape — is silently not executed.** Neither ARC0017 nor the
141
+ runtime sees it; it is treated as ordinary response data. To return events and
142
+ operations together, use a tuple such as
143
+ `(IEnumerable<object> Events, CommandOperations Operations)`.
144
+ - A controller action that returns an operation object does not execute it;
145
+ operations run only through the model-bound command pipeline.
146
+
147
+ Operations never reach the client/proxy; only the ordinary response does.
148
+ **Calling `Handle()` directly does not execute operations.** Use `ICommandPipeline`
149
+ or `CommandScenario` for orchestration; `Validate()` does not run operations.
150
+
151
+ ## Execution and compensation
152
+
153
+ Arc preflights operation metadata and dependencies, processes control values and
154
+ other server values (including returned-event enrollment), then executes
155
+ operations sequentially. A failure stops later operations. Required scopes
156
+ complete before Arc selects recovery from observed commitment facts.
157
+
158
+ If A and B return, C throws inside `Execute()`, and D never starts, eligible
159
+ compensation runs **C, B, A — never D**. The throwing operation is included:
160
+ a lost acknowledgment may hide a successful external write. A dependency
161
+ preflight failure is not an entered invocation.
162
+
163
+ Compensators must be ownership-aware and safe for partially applied or lost-ack
164
+ work. A delete-if-present can race a create still in flight. The provider owns
165
+ idempotency, tenant/owner isolation, conflicting-key rejection, terminal
166
+ cancellation or reconciliation, and protection of earlier finalized successes
167
+ from a later attempt's reversal. Arc cannot supply those guarantees.
168
+
169
+ ## Commit facts decide recovery
170
+
171
+ On command failure with started operations:
172
+
173
+ | `CommandCommitDisposition` | Action |
174
+ | --- | --- |
175
+ | `NoCommit` / `NotCommitted` | Attempt declared compensation in reverse order |
176
+ | `Committed` | Suppress reversal associated with committed business facts |
177
+ | `Unknown` / `Mixed` | Report indeterminate recovery; do not guess or reverse |
178
+
179
+ **A failed result is not proof that nothing committed.** Compensation is new
180
+ business work, not atomic rollback. It is best-effort, in-process, with no durable
181
+ journal and no automatic retries of execution or compensation. Crashes,
182
+ post-pipeline serialization, and result delivery are outside this recovery.
183
+
184
+ With Chronicle, **return events for deferred enrollment**. Operations run before
185
+ automatic transaction completion. A known rejection can permit compensation;
186
+ an uncertain commit cannot. Do not explicitly commit aggregates or immediately
187
+ append events and expect operation recovery to undo them: if the commit
188
+ participant has already committed (or its outcome is unknown or mixed) when
189
+ operations would start, Arc rejects the batch with `InvalidCommandOperation` and
190
+ none of them run. Explicit commits made inside an operation-capable command are
191
+ refused outright.
192
+
193
+ `Execute()` receives the command token. `Compensate()` receives a separate token;
194
+ `CommandOperationOptions.CompensationTimeout` defaults to **30 seconds**, shared
195
+ by the recovery attempt. The budget is cooperative: code ignoring cancellation
196
+ is still awaited, not forcibly terminated.
197
+
198
+ ## Keep the execution boundary supported
199
+
200
+ The supported profile is **flat, sequential, with at most one deferred commit
201
+ participant**. **No same-host nested commands at all** while an operation-capable
202
+ command runs: an `ICommandPipeline` call from its `Provide()`, `Handle()`,
203
+ validators, `Execute()` or `Compensate()` — or any nested call whose child
204
+ command is itself operation-capable — is refused and the child never runs.
205
+ During execution this rejects the batch even if the child result is ignored;
206
+ during compensation it is recorded as a failed compensation. Compose operation
207
+ declarations instead, or move follow-up commands to a reactor.
208
+
209
+ **Every discovered `ICommandExecutionScope` must implement
210
+ `ICommandOperationExecutionScope`.** "Operation-capable" means `Handle()`'s
211
+ declared return type structurally contains `ICommandOperation` or
212
+ `CommandOperations` — directly, nullable, in a tuple, `Task`/`ValueTask`, or
213
+ `Result`/`OneOf`. For such a command Arc rejects execution with
214
+ `InvalidCommandOperation` before any scope begins if any scope is unclassified — even when the handler returns null or
215
+ an empty batch. Audit the application's own unit-of-work or audit scopes before
216
+ adopting operations.
217
+
218
+ Custom scopes opt in through `ICommandOperationExecutionScope`; they must report
219
+ real commit facts, not infer them from `IsSuccess`. A nonparticipant promises not
220
+ to commit business changes; `Begin()` must not commit. Chronicle supplies its
221
+ integration. **EF Core and MongoDB have no built-in operation commit participant.**
222
+ See the [custom-scope checklist](references/execution-and-recovery.md#supported-scopes).
223
+
224
+ ## Observe and test on the backend
225
+
226
+ Backend `CommandResult.Recovery` and `OperationOutcomes` describe recovery and
227
+ entered invocations. Both are excluded from HTTP JSON and the TypeScript result.
228
+ `Completed` recovery means callbacks returned, not that external history was
229
+ erased or a retry is safe. Keep operation types and failure details in trusted
230
+ diagnostics.
231
+
232
+ Test three boundaries with `Cratis.Specifications`:
233
+
234
+ 1. Direct `Handle()`: assert immutable decision data and order, without services.
235
+ 2. Direct `Execute()` / `Compensate()`: assert provider requests with substitutes.
236
+ 3. `CommandScenario`: assert real execution, original failure, skipped operations,
237
+ compensation, and commit observations. Register controlled dependencies first.
238
+
239
+ See [testing](references/testing.md) for failure, Chronicle rejection, and
240
+ migration. Provider tests must separately prove ownership and idempotency.
241
+
242
+ ## Common mistakes
243
+
244
+ | Mistake | Correction |
245
+ | --- | --- |
246
+ | Calling the service in `Handle()` and returning its operation | Remove the direct write; otherwise it runs twice |
247
+ | Calling `Execute()` manually before returning the operation | Let the pipeline invoke it once |
248
+ | Moving the write into `Provide()` | Acquire inputs there; writes remain outside operation recovery |
249
+ | `try/catch` rollback stacks in `Handle()` | Return work and implement its business `Compensate()` |
250
+ | Raw `IEnumerable<ICommandOperation>` | Return `CommandOperations` (`ARC0017`) |
251
+ | Capturing services in the record | Inject them into operation methods |
252
+ | Generating an operation's request/ownership key (or clock values it depends on) inside `Handle()` | Have the caller supply it so a retry reuses the same key |
253
+ | Using inline operations for email/payment delivery that must survive a crash | Use reactors/outbox/durable workflows |
254
+ | Assuming `!IsSuccess` means nothing committed | Inspect backend commitment and recovery observations |
255
+ | Marking a committing scope as a nonparticipant | Report its actual boundary; do not evade the single-participant limit |
256
+
257
+ ## Route near misses
258
+
259
+ - Command definition / `Provide()`: `cratis-arc-command`.
260
+ - Rejection rules: `cratis-arc-command-validation`.
261
+ - Calling an existing command: `cratis-arc-command-execution`.
262
+ - Reliable reactions to committed facts: `cratis-chronicle-reactor`.
263
+ - Specialized framework return-value interpretation: Arc's
264
+ [response value handlers](https://github.com/Cratis/Arc/blob/v22.48.1/Documentation/backend/csharp/commands/response-value-handlers.md).
265
+
266
+ ## Verify
267
+
268
+ - The work belongs inline; no durable delivery requirement was lost.
269
+ - Inputs and caller response are preserved; `Handle()` only declares the work.
270
+ - Method shapes satisfy ARC0016–ARC0018; batches use `CommandOperations`.
271
+ - The provider protects ownership, earlier successes, partial work, and retries.
272
+ - Every registered execution scope implements `ICommandOperationExecutionScope`,
273
+ honors the flat boundary, and reports authoritative commit facts.
274
+ - Decision, adapter, and scenario specs cover success and a specific failure;
275
+ Chronicle specs prove real non-commit, not only a fabricated failed result.
276
+ - Debug and Release builds are clean; the generated proxy contains no operation
277
+ descriptor and the client still compiles against the intended response.
@@ -0,0 +1,229 @@
1
+ # Operation execution and recovery reference
2
+
3
+ Verified at **Arc v22.48.1** against the
4
+ [product reference](https://github.com/Cratis/Arc/blob/v22.48.1/Documentation/backend/csharp/commands/operations/reference.md)
5
+ and `Source/DotNET/Arc.Core/Commands/`. Types below are in
6
+ `Cratis.Arc.Commands`. Start with [the skill](../SKILL.md) to choose the boundary.
7
+
8
+ ## Declaration contract
9
+
10
+ | Surface | Contract |
11
+ | --- | --- |
12
+ | `ICommandOperation` | Marker; immutable business-data record is the convention, not a record-only runtime requirement |
13
+ | `Execute(...)` | Exactly one public, non-generic, non-abstract instance method |
14
+ | `Compensate(...)` | Optional single public, non-generic, non-abstract instance method |
15
+ | Method return | Only `void`, `Task`, `ValueTask`; no receipt or further pipeline values |
16
+ | Services | Required method parameters resolved from the command's provider; no service captures |
17
+ | `CancellationToken` | At most one per method, supplied by Arc |
18
+ | `CommandOperationFailure` | At most one, only on `Compensate` |
19
+ | Accessibility | Non-file-local, non-generic public/internal operation in accessible non-generic containing types |
20
+
21
+ No `async void`, static/generic methods, overloads, optional/`params`/by-ref or
22
+ pointer parameters. Service locators (`IServiceProvider`, `IServiceScopeFactory`,
23
+ `IServiceScope`, including implementing types) are forbidden parameters.
24
+ `ARC0016` checks method conventions, `ARC0017` checks bare operation collections,
25
+ and `ARC0018` checks accessibility for generated invokers. The generator emits
26
+ typed calls; validated reflection fallback covers source-free declarations.
27
+ This is not a claim of whole-host NativeAOT support.
28
+
29
+ ## Returned values
30
+
31
+ | Return shape | Treatment |
32
+ | --- | --- |
33
+ | Concrete operation or `ICommandOperation` | Execute on the server |
34
+ | Nullable operation, including nullable value type | Null is absent; present value remains server-only |
35
+ | `CommandOperations` | Ordered immutable batch membership, materialized once; null elements rejected |
36
+ | `[]` / `default(CommandOperations)` | Empty batch |
37
+ | Nullable batch | Present value is server-only; prefer an empty non-nullable batch |
38
+ | Tuple | Flatten values; at most one ordinary client response |
39
+ | `Result` / `OneOf` | Flatten only the active alternative, including tuple alternatives |
40
+ | `Task<T>` / `ValueTask<T>` | Await the handler, then classify its result |
41
+ | Ordinary array/enumerable | Ordinary response classification, not an operation batch |
42
+
43
+ Bare collections of operations are rejected; use `CommandOperations`.
44
+ Participation is decided from the declared return type, and only tuples and
45
+ `Result`/`OneOf` are unwrapped: a top-level operation under an `object`
46
+ signature is rejected, while an operation inside `IEnumerable<object>`/`object[]`
47
+ is treated as response data and silently not executed. Combine events and
48
+ operations with a tuple, e.g. `(IEnumerable<object>, CommandOperations)`. Operations bypass
49
+ ordinary response handlers and never become client/proxy response types.
50
+
51
+ ## Nine-step ordering
52
+
53
+ 1. Run authorization, validation, `Provide()`, and `Handle()`.
54
+ 2. Classify the return graph; validate operation metadata and preflight both
55
+ execution and compensation dependencies before starting work.
56
+ 3. Process control values before other server values, regardless of tuple order;
57
+ enroll returned Chronicle events before operation execution.
58
+ 4. If still successful and the commit boundary permits entry, execute operations
59
+ sequentially in declaration order.
60
+ 5. Record each invocation immediately before entering `Execute()`, after
61
+ dependency resolution and cancellation checks.
62
+ 6. Stop starting operations after execution failure or cancellation.
63
+ 7. Complete required execution scopes in reverse scope order and obtain
64
+ conservative commitment facts, including when completion failed.
65
+ 8. Run eligible compensators in reverse invocation order; a failed compensator
66
+ does not erase the original failure or prevent remaining eligible callbacks.
67
+ 9. Publish backend observations and clear the result response if unsuccessful.
68
+
69
+ The throwing operation **is started** and eligible for compensation. Never-entered
70
+ operations are not. Dependency preflight is not entry. Direct calls to `Handle`,
71
+ `Execute`, or `Compensate` are ordinary C# calls without this orchestration.
72
+
73
+ ## Commit and recovery
74
+
75
+ Failure plus started work requires a recovery decision; `!IsSuccess` does not
76
+ establish non-commit.
77
+
78
+ | `CommandCommitDisposition` | Meaning | Recovery on failure |
79
+ | --- | --- | --- |
80
+ | `NoCommit` | No coordinated participant | Attempt declared compensation |
81
+ | `NotCommitted` | Coordinated changes known not committed | Attempt declared compensation |
82
+ | `Committed` | Known committed business boundary | `Suppressed` |
83
+ | `Unknown` | Commitment cannot be safely established | `Indeterminate`; no reversal |
84
+ | `Mixed` | Some changes committed, others did not | `Indeterminate`; no blanket reversal |
85
+
86
+ With Chronicle, returned events enroll before operations; automatic transaction
87
+ completion follows them. A known commit rejection permits recovery. An uncertain
88
+ acknowledgment does not. Pending events still undergo real transaction rollback
89
+ on command failure; compensation does not un-append events. Explicit aggregate
90
+ commits are not supported within operation boundaries, and already successful
91
+ immediate appends cannot be undone. Operations cannot start after an observed
92
+ early, unknown, or mixed commit.
93
+
94
+ Recovery is best-effort, in-process **new business work**, not atomic rollback.
95
+ There is no durable journal, automatic retry, or promised crash recovery.
96
+ Serialization/result delivery after the pipeline and arbitrary service writes
97
+ outside returned operations are not covered.
98
+
99
+ ## Backend observations
100
+
101
+ `CommandResult.Recovery` is nullable; processing that never participates can leave
102
+ it absent. `OperationOutcomes` is an immutable list of entered invocations. Both
103
+ carry `[JsonIgnore]`: neither is part of HTTP JSON or the TypeScript result.
104
+
105
+ | `CommandRecoverySummary` member | Meaning |
106
+ | --- | --- |
107
+ | `CommitDisposition` | Observed coordinated commitment, not command success |
108
+ | `Status` | `CommandRecoveryStatus` decision/outcome |
109
+ | `StartedCount` | Entered `Execute` invocations |
110
+ | `CompletedCount` | `Execute` methods that returned successfully |
111
+ | `CompensatedCount` | `Compensate` methods that returned successfully |
112
+ | `FailedCompensationCount` | Compensators that threw |
113
+ | `UncompensatedCount` | Started work requiring recovery without observed completed compensation |
114
+
115
+ | `CommandRecoveryStatus` | Meaning |
116
+ | --- | --- |
117
+ | `NotNeeded` | No started work requires recovery |
118
+ | `Completed` | Every required compensator returned; not proof of atomic reversal |
119
+ | `Incomplete` | Compensation unavailable, failed, or budget exhausted |
120
+ | `Suppressed` | Business changes committed |
121
+ | `Indeterminate` | Commitment unknown or mixed |
122
+
123
+ Each `CommandOperationOutcome` exposes `InvocationIndex`, `OperationType`,
124
+ `ExecutionCompleted`, `Compensation`, and optional `CompensationFailure` message.
125
+ It carries no operation business properties.
126
+
127
+ | `CommandOperationCompensation` | Meaning |
128
+ | --- | --- |
129
+ | `NotNeeded` | Recovery not required |
130
+ | `Completed` | Compensator returned |
131
+ | `Failed` | Compensator threw or attempted unsupported nesting |
132
+ | `NotAvailable` | No compensator declared |
133
+ | `BudgetExpired` | Recovery budget expired before callback entry |
134
+ | `Suppressed` | Commit facts prohibit automatic reversal |
135
+
136
+ Keep these observations and messages in trusted diagnostics, correlated with
137
+ `CommandResult.CorrelationId`. Do not treat `Completed` as permission to retry.
138
+
139
+ ## Optional failure context
140
+
141
+ `CommandOperationFailure` is immutable context for specialized compensators,
142
+ not a mutable command result or an external execution receipt.
143
+
144
+ | Member | Meaning |
145
+ | --- | --- |
146
+ | `InvocationIndex` | Zero-based invocation index |
147
+ | `InvocationCompleted` | Its `Execute()` returned successfully |
148
+ | `IsFailingInvocation` | This invocation threw the original execution failure |
149
+ | `Source` | `CommandOperationFailureSource`: `Planning`, `ResponseHandling`, `Execution`, `Cancellation`, `ScopeCompletion` |
150
+ | `CommitDisposition` | Facts used to select recovery |
151
+ | `ExceptionMessages` | Defensive snapshot of original exception messages; recovery failures are separate |
152
+
153
+ A false `InvocationCompleted` does not prove the provider made no change. Do not
154
+ skip necessary reversal solely because forward execution threw.
155
+
156
+ ## Cancellation and budget
157
+
158
+ `Execute` receives the command token (normally request-aborted over HTTP).
159
+ `Compensate` receives an independent recovery token so disconnection does not
160
+ immediately cancel cleanup. `CommandOperationOptions.CompensationTimeout` is
161
+ shared across the recovery attempt, defaults to 30 seconds, and must be positive
162
+ and at most 4294967294 milliseconds.
163
+
164
+ Host configuration fragment, with `System`, `Cratis.Arc.Commands`, and
165
+ `Microsoft.Extensions.DependencyInjection` imported:
166
+
167
+ ```csharp
168
+ builder.Services.Configure<CommandOperationOptions>(options =>
169
+ options.CompensationTimeout = TimeSpan.FromSeconds(10));
170
+ ```
171
+
172
+ The budget is cooperative. A callback ignoring cancellation is still awaited;
173
+ Arc neither terminates it nor disposes its services underneath it. Not-yet-entered
174
+ callbacks are reported `BudgetExpired` after expiry. No automatic execution or
175
+ compensation retries occur; provider/driver policies can still retry internally.
176
+
177
+ ## Supported scopes
178
+
179
+ Flat, sequential execution; at most one deferred commit participant. No
180
+ parallel/detached participation or durable recovery. Any same-host nested
181
+ `ICommandPipeline` call is refused (the child never runs) when the parent or the
182
+ child is operation-capable — from `Provide`, `Handle`, validators, `Execute` or
183
+ `Compensate`. Explicit commits inside the boundary are refused too. From
184
+ `Execute` a nested call rejects the batch even when its failed result is ignored. From `Compensate` it fails that compensation;
185
+ remaining eligible compensators still run.
186
+
187
+ Custom scopes implement `ICommandOperationExecutionScope`, extending
188
+ `ICommandExecutionScope`. Verify against the actual provider:
189
+
190
+ - `Begin(CommandContext)` does not commit; partial initialization is safe to clean up.
191
+ - `IsCommitParticipant` is stable and names responsibility, not the latest outcome.
192
+ - A nonparticipant truly does not commit business changes.
193
+ - `GetCommitDisposition(CommandContext)` is read **before operations start** as
194
+ well as after completion. While the deferred commit is still pending it must
195
+ report `NotCommitted` (or `NoCommit`); report `Committed`/`Unknown`/`Mixed`
196
+ only when an early or uncertain commit actually happened, otherwise Arc
197
+ refuses to start operations.
198
+ - It reports authoritative facts after `Complete` fails too; unavailable facts
199
+ mean `Unknown`, not `NotCommitted`.
200
+ - Known commit remains committed after a later scope fails. Scope completion
201
+ order is unchanged; never infer disposition from `IsSuccess` or a completed flag.
202
+ - Compensation can use its dependencies after completion; a live DI scope does
203
+ not repair a failed transaction/context. Preserve tenant and ownership context.
204
+ - Cancellation/disposal cannot invalidate resources under running recovery.
205
+
206
+ | Integration | Boundary |
207
+ | --- | --- |
208
+ | Standalone Arc | Registered application services; no automatic database transaction |
209
+ | Chronicle | Compatible deferred event commit with conservative commitment observations |
210
+ | EF Core | No built-in operation commit participant; registration does not call `SaveChanges` or coordinate operation writes |
211
+ | MongoDB | No built-in operation commit participant; sessions and driver resilience remain provider concerns |
212
+
213
+ Independent EF and Chronicle commits do not become atomic by sharing a command.
214
+ Do not label a committing scope nonparticipating to evade validation.
215
+
216
+ ## Troubleshooting
217
+
218
+ | Symptom | Check |
219
+ | --- | --- |
220
+ | `Handle()` returns work but nothing runs | Use `ICommandPipeline` / `CommandScenario`, not a direct decision call |
221
+ | Zero operations entered | Authorization, validation, `Provide`, declaration/DI preflight, early commit, scope compatibility; `Validate` never executes work |
222
+ | `Recovery` absent | HTTP intentionally omits it; backend processing may not have participated |
223
+ | `Incomplete` recovery | Per-operation missing compensator, thrown compensation, or exhausted budget |
224
+ | `Suppressed` recovery | Known commit; a later failure is not permission to reverse it |
225
+ | `Indeterminate` recovery | Reconcile storage/provider facts; Arc scheduled no durable recovery |
226
+ | Cleanup outlives cancellation | Independent cooperative token; check provider cancellation support |
227
+ | Work repeats | Caller/reactor retries or provider resilience; verify ownership-safe idempotency |
228
+ | Ignored child result still rejects batch | Compose declarations instead of nested commands |
229
+ | No cleanup after process loss | Use reactor/outbox/workflow durability rather than an in-memory operation journal |
@@ -0,0 +1,252 @@
1
+ # Specify decisions, adapters, and pipeline composition
2
+
3
+ Verified at **Arc v22.48.1**. These class excerpts follow the product's
4
+ [standalone lesson](https://github.com/Cratis/Arc/blob/v22.48.1/Documentation/backend/csharp/testing/command-operations.md)
5
+ and [Chronicle rejection lesson](https://github.com/Cratis/Arc/blob/v22.48.1/Documentation/backend/csharp/testing/command-operations-with-chronicle.md).
6
+ Use `Cratis.Specifications.XUnit`, NSubstitute, and matching Arc packages in a
7
+ separate spec project. Keep standalone and Chronicle scenarios in separate
8
+ projects: Chronicle's discovered scenario extender changes the test environment.
9
+
10
+ The standalone examples reuse `ReservationId`, `SeatId`, `ISeatReservations`,
11
+ `ReserveSeat`, `BookSeat`, `SeatReservation`, and `BookSeats` from the
12
+ [application declarations](https://github.com/Cratis/Arc/blob/v22.48.1/Documentation/backend/csharp/commands/operations/implementing.md).
13
+ Add these imports to each standalone spec file (and its own namespace):
14
+
15
+ ```csharp
16
+ using System;
17
+ using System.Threading;
18
+ using System.Threading.Tasks;
19
+ using Cratis.Arc.Commands;
20
+ using Cratis.Arc.Testing.Commands;
21
+ using Cratis.Specifications;
22
+ using Microsoft.Extensions.DependencyInjection;
23
+ using NSubstitute;
24
+ using SeatBooking;
25
+ using Xunit;
26
+ ```
27
+
28
+ ## Decision: direct Handle
29
+
30
+ No provider or container is needed. Fixed inputs and record equality prove the
31
+ proposed work, not its execution or authorization.
32
+
33
+ ```csharp
34
+ public class when_deciding_to_book : Specification
35
+ {
36
+ readonly ReservationId _id = new(Guid.Parse("757660b8-55ac-4c1a-89cb-8151c8fd3562"));
37
+ readonly SeatId _seat = new("A-12");
38
+ (ReservationId Response, ReserveSeat Operation) _decision;
39
+
40
+ void Because() => _decision = new BookSeat(_id, _seat).Handle();
41
+
42
+ [Fact] void should_return_the_request_identifier() => _decision.Response.ShouldEqual(_id);
43
+ [Fact] void should_declare_the_reservation() =>
44
+ _decision.Operation.ShouldEqual(new ReserveSeat(_id, _seat));
45
+ }
46
+ ```
47
+
48
+ For batches assert membership and order, including conditional/empty decisions.
49
+ Do not infer that calling `Handle()` performed any external work.
50
+
51
+ ## Adapter: direct Execute and Compensate
52
+
53
+ This tests the provider mapping, not Arc's recovery selection:
54
+
55
+ ```csharp
56
+ public class when_reserving_directly : Specification
57
+ {
58
+ readonly ReservationId _id = new(Guid.Parse("757660b8-55ac-4c1a-89cb-8151c8fd3562"));
59
+ readonly SeatId _seat = new("A-12");
60
+ ISeatReservations _reservations = null!;
61
+
62
+ void Establish()
63
+ {
64
+ _reservations = Substitute.For<ISeatReservations>();
65
+ _reservations.Reserve(_id, _seat, CancellationToken.None).Returns(Task.CompletedTask);
66
+ }
67
+
68
+ Task Because() => new ReserveSeat(_id, _seat).Execute(_reservations, CancellationToken.None);
69
+
70
+ [Fact] Task should_reserve_the_requested_seat() =>
71
+ _reservations.Received(1).Reserve(_id, _seat, CancellationToken.None);
72
+ [Fact] Task should_not_cancel() =>
73
+ _reservations.DidNotReceive().Cancel(Arg.Any<ReservationId>(), Arg.Any<CancellationToken>());
74
+ }
75
+ ```
76
+
77
+ For the reversal's own spec, arrange `Cancel` to return `Task.CompletedTask`,
78
+ call `new ReserveSeat(_id, _seat).Compensate(_reservations, CancellationToken.None)`
79
+ in `Because`, and assert `Received(1).Cancel(_id, CancellationToken.None)` plus no
80
+ `Reserve` call. A direct throwing `Execute` does not automatically compensate.
81
+
82
+ ## Composition: forward failure and reverse compensation
83
+
84
+ Reference `Cratis.Arc.Testing`. `CommandScenario<TCommand>` runs the real pipeline
85
+ and invokers, not a recording stub. Register substitutes through `Services`
86
+ before first execution; do not register a production external client.
87
+
88
+ This case fails the second reservation. Both entered invocations must be
89
+ compensated; the third must never start.
90
+
91
+ ```csharp
92
+ public class ReservationProviderUnavailable() : Exception("Reservation provider unavailable.");
93
+
94
+ public class when_the_second_reservation_fails : Specification
95
+ {
96
+ readonly CommandScenario<BookSeats> _scenario = new();
97
+ readonly ReservationId _first = new(Guid.Parse("757660b8-55ac-4c1a-89cb-8151c8fd3562"));
98
+ readonly ReservationId _second = new(Guid.Parse("b52a8554-fab3-4050-af81-554d105d9b9d"));
99
+ readonly ReservationId _third = new(Guid.Parse("0aeb4b2f-0515-44fe-8e79-7c8f304d2c65"));
100
+ ISeatReservations _reservations = null!;
101
+ CommandResult _result = null!;
102
+
103
+ void Establish()
104
+ {
105
+ _reservations = Substitute.For<ISeatReservations>();
106
+ _reservations.Reserve(Arg.Any<ReservationId>(), Arg.Any<SeatId>(), Arg.Any<CancellationToken>())
107
+ .Returns(Task.CompletedTask);
108
+ _reservations.Reserve(_second, Arg.Any<SeatId>(), Arg.Any<CancellationToken>())
109
+ .Returns(Task.FromException(new ReservationProviderUnavailable()));
110
+ _reservations.Cancel(Arg.Any<ReservationId>(), Arg.Any<CancellationToken>())
111
+ .Returns(Task.CompletedTask);
112
+ _scenario.Services.AddSingleton(_reservations);
113
+ }
114
+
115
+ async Task Because() => _result = await _scenario.Execute(new BookSeats(
116
+ [
117
+ new SeatReservation(_first, new SeatId("A-12")),
118
+ new SeatReservation(_second, new SeatId("A-13")),
119
+ new SeatReservation(_third, new SeatId("A-14"))
120
+ ]));
121
+
122
+ [Fact] void should_preserve_failure() => _result.ShouldNotBeSuccessful();
123
+ [Fact] void should_preserve_the_original_error() =>
124
+ _result.ExceptionMessages.ShouldContain("Reservation provider unavailable.");
125
+ [Fact] void should_record_only_entered_invocations() => _scenario.Operations.Count.ShouldEqual(2);
126
+ [Fact] void should_observe_the_first_execution_completing() =>
127
+ _scenario.Operations[0].ExecutionCompleted.ShouldBeTrue();
128
+ [Fact] void should_observe_the_throwing_execution() =>
129
+ _scenario.Operations[1].ExecutionCompleted.ShouldBeFalse();
130
+ [Fact] Task should_not_start_the_third() =>
131
+ _reservations.DidNotReceive().Reserve(_third, Arg.Any<SeatId>(), Arg.Any<CancellationToken>());
132
+ [Fact] void should_compensate_in_reverse_order() => Received.InOrder(() =>
133
+ {
134
+ _ = _reservations.Cancel(_second, Arg.Any<CancellationToken>());
135
+ _ = _reservations.Cancel(_first, Arg.Any<CancellationToken>());
136
+ });
137
+ [Fact] void should_observe_both_compensations() => _result.Recovery!.CompensatedCount.ShouldEqual(2);
138
+ [Fact] void should_report_callback_completion() =>
139
+ _result.Recovery!.Status.ShouldEqual(CommandRecoveryStatus.Completed);
140
+
141
+ void Destroy() => _scenario.Dispose();
142
+ }
143
+ ```
144
+
145
+ `Operations` snapshots the latest `Execute`'s entered invocations, including the
146
+ throwing one. `ShouldHaveExecutedOperation<T>()` requires at least one matching
147
+ execution to have **completed**; it does not mean every operation of that type
148
+ succeeded. Pair it with exact counts, indices, and provider arguments as needed.
149
+ `ShouldHaveCompensatedOperation<T>()` likewise proves a callback returned, not
150
+ provider durability. A lone unsuccessful-result assertion could pass because
151
+ DI failed before any work began.
152
+
153
+ ## Chronicle: a real commit rejection
154
+
155
+ Reference `Cratis.Arc.Chronicle.Testing` and the `Cratis.Arc` test-host dependency.
156
+ Reuse the `Onboarding` declarations from the linked Chronicle lesson:
157
+ `StartOnboarding(EventSourceId, OrganizationNumber, ReservationKey)` returns
158
+ `OnboardingStarted` plus `ReserveOnboardingCapacity`. The event declares
159
+ `UniqueOrganizationNumber` uniqueness. Import `Onboarding` instead of
160
+ `SeatBooking`, plus `Cratis.Arc.Chronicle.Testing.Commands` and
161
+ `Cratis.Chronicle.Events`; retain the other imports above.
162
+
163
+ ```csharp
164
+ public class when_the_organization_is_already_onboarding : Specification, IAsyncDisposable
165
+ {
166
+ CommandScenario<StartOnboarding> _scenario = null!;
167
+ readonly OrganizationNumber _organization = new("ORG-OPERATIONS");
168
+ readonly ReservationKey _key = new(Guid.Parse("96ce8c18-1e67-4e44-b5e7-4fb2b2cb3b97"));
169
+ EventSourceId _newPartner = null!;
170
+ IOnboardingReservations _reservations = null!;
171
+ CommandResult _result = null!;
172
+
173
+ async Task Establish()
174
+ {
175
+ _scenario = new();
176
+ _newPartner = EventSourceId.New();
177
+ _reservations = Substitute.For<IOnboardingReservations>();
178
+ _reservations.Reserve(_key, Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
179
+ _reservations.Cancel(_key, Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
180
+ _scenario.Services.AddSingleton(_reservations);
181
+ await _scenario.EventScenario.Given.ForEventSource(EventSourceId.New())
182
+ .Events(new OnboardingStarted(_organization));
183
+ }
184
+
185
+ async Task Because() =>
186
+ _result = await _scenario.Execute(new StartOnboarding(_newPartner, _organization, _key));
187
+
188
+ [Fact] void should_report_the_constraint() =>
189
+ _result.ShouldHaveConstraintViolationFor("UniqueOrganizationNumber");
190
+ [Fact] void should_observe_forward_execution() =>
191
+ _scenario.ShouldHaveExecutedOperation<ReserveOnboardingCapacity>();
192
+ [Fact] void should_observe_compensation() =>
193
+ _scenario.ShouldHaveCompensatedOperation<ReserveOnboardingCapacity>();
194
+ [Fact] void should_call_the_provider_in_order() => Received.InOrder(() =>
195
+ {
196
+ _ = _reservations.Reserve(_key, Arg.Any<CancellationToken>());
197
+ _ = _reservations.Cancel(_key, Arg.Any<CancellationToken>());
198
+ });
199
+ [Fact] void should_report_noncommit() =>
200
+ _result.Recovery!.CommitDisposition.ShouldEqual(CommandCommitDisposition.NotCommitted);
201
+ [Fact] void should_report_callback_completion() =>
202
+ _result.Recovery!.Status.ShouldEqual(CommandRecoveryStatus.Completed);
203
+ [Fact] async Task should_not_persist_the_rejected_event() =>
204
+ (await _scenario.EventScenario.EventLog.HasEventsFor(_newPartner)).ShouldBeFalse();
205
+
206
+ async Task Destroy() => await ((IAsyncDisposable)this).DisposeAsync();
207
+ ValueTask IAsyncDisposable.DisposeAsync() => _scenario.DisposeAsync();
208
+ }
209
+ ```
210
+
211
+ Seed the constraint in the **event log** through `EventScenario.Given`, not only
212
+ in a read-model dictionary. This follows the maintained
213
+ [real-rejection spec](https://github.com/Cratis/Arc/blob/v22.48.1/Source/DotNET/Chronicle.Specs/Commands/for_CommandScenario/operations/when_a_real_constraint_rejects_the_commit.cs).
214
+ It proves known non-commit and eligible compensation with the in-process store,
215
+ not uncertain remote acknowledgments or the external provider's durability.
216
+
217
+ ## Extend the failure coverage
218
+
219
+ - Happy path: assert provider arguments, `ShouldHaveExecutedOperation<ReserveSeat>()`,
220
+ `Recovery.Status == CommandRecoveryStatus.NotNeeded`, and the actual response.
221
+ - `Validate(command)`: no `Provide`, `Handle`, scope lifecycle, or operations;
222
+ assert the specific validation rule and `DidNotReceive` provider calls.
223
+ - Execution-path rejection: `Execute` invalid input, assert the specific verdict
224
+ and `ShouldHaveNoOperationInvocations()`.
225
+ - Cancellation: `Execute(command, cancellationToken)`; cancel deterministically
226
+ inside a substitute and prove compensation got a separate uncanceled token.
227
+ - Missing/throwing compensation: `Incomplete`, `NotAvailable`/`Failed`, exact
228
+ `UncompensatedCount`/`FailedCompensationCount`, and remaining callbacks attempted.
229
+
230
+ Arc's [failure recipes](https://github.com/Cratis/Arc/blob/v22.48.1/Documentation/backend/csharp/testing/command-operation-failures.md)
231
+ contain the full cases. Run `dotnet test <Your.Specs.csproj>`; assert behavior,
232
+ not just command success. These corpus excerpts are source-checked, not compiled
233
+ by the corpus text-verification gate. Test provider ownership, repeated finalized
234
+ requests, conflicting keys, and delayed creates at the provider integration boundary.
235
+
236
+ ## Migrate an existing service-backed Handle
237
+
238
+ Follow the [migration recipe](https://github.com/Cratis/Arc/blob/v22.48.1/Documentation/backend/csharp/commands/operations/migrating.md):
239
+
240
+ 1. Separate acquired inputs, decision, and service writes. Preserve the input,
241
+ endpoint, and response; move the write into an operation and return it with
242
+ the existing response. Remove the old call, including any manual `Execute`.
243
+ 2. Keep a direct service interaction if its receipt is needed to construct the
244
+ decision/response. Do not hide the write in `Provide` or redesign persistence
245
+ solely for syntactic purity.
246
+ 3. Keep provider DI; remove an obsolete custom response handler only if its sole
247
+ purpose was this side effect. Keep specialized framework handlers and events.
248
+ 4. Audit custom scopes, early commits, and ownership-safe reversal before enabling
249
+ the new path. Do not add rollback stacks or relabel a committing scope.
250
+ 5. Prove decision data, provider effects, response, validation/authorization,
251
+ failure/compensation, and (with Chronicle) actual commit rejection. Rebuild
252
+ the proxy: it must still expose the original response, not the operation.
@@ -0,0 +1,19 @@
1
+ {
2
+ "skill": "cratis-arc-command-operation",
3
+ "input": "Move a model-bound command's immediate seat reservation into an ICommandOperation, preserve its response, and specify forward failure and compensation without assuming a failed command means nothing committed.",
4
+ "fixtures": [],
5
+ "assertions": [
6
+ { "kind": "skill-contains", "value": "Chronicle is not required." },
7
+ { "kind": "skill-contains", "value": "operations cannot return receipts" },
8
+ { "kind": "skill-contains", "value": "only on `Compensate()`" },
9
+ { "kind": "skill-contains", "value": "Never return a raw array or `IEnumerable<ICommandOperation>` as a batch." },
10
+ { "kind": "skill-contains", "value": "Calling `Handle()` directly does not execute operations." },
11
+ { "kind": "skill-contains", "value": "C, B, A — never D" },
12
+ { "kind": "skill-contains", "value": "A failed result is not proof that nothing committed." },
13
+ { "kind": "skill-contains", "value": "`Unknown` / `Mixed`" },
14
+ { "kind": "skill-contains", "value": "CommandOperationOptions.CompensationTimeout" },
15
+ { "kind": "skill-contains", "value": "EF Core and MongoDB have no built-in operation commit participant." },
16
+ { "kind": "skill-contains", "value": "CommandResult.Recovery" },
17
+ { "kind": "skill-contains", "value": "references/testing.md" }
18
+ ]
19
+ }
@@ -300,6 +300,9 @@ public class <ReactorName> : IReactor
300
300
  A reactor runs with **no principal**; `[ExecuteCommandsAsSystem]` (class-level,
301
301
  `Cratis.Arc.Chronicle.Reactors`) supplies one for the **returned** commands only.
302
302
  A collection return is executed as commands when every element is a command.
303
+ A reactor retry can execute the command's operations again; inline operations
304
+ are not a substitute for reactor/outbox durability (see
305
+ `cratis-arc-command-operation`, verified at Arc v22.48.1).
303
306
 
304
307
  The imperative form — inject `ICommandPipeline` (`Cratis.Arc.Commands`) and call
305
308
  `Execute(command)` — is still supported and is the subject of the
@@ -253,6 +253,7 @@
253
253
  "availableTargets": [
254
254
  "cratis-arc-command",
255
255
  "cratis-arc-command-execution",
256
+ "cratis-arc-command-operation",
256
257
  "cratis-arc-command-validation",
257
258
  "cratis-arc-observable-query-http",
258
259
  "cratis-arc-query-paging"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cratis/pi",
3
- "version": "7.5.2",
3
+ "version": "7.6.0",
4
4
  "description": "Configuration-aware Cratis AI integration for Pi",
5
5
  "type": "module",
6
6
  "files": [