@cratis/pi 7.5.1 → 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.
Files changed (24) hide show
  1. package/package/corpus/rules/application-profile.md +2 -0
  2. package/package/corpus/rules/code-quality.csharp.md +1 -1
  3. package/package/corpus/rules/csharp.md +2 -0
  4. package/package/corpus/rules/reactors.md +1 -0
  5. package/package/corpus/rules/specs.scenarios.csharp.md +1 -0
  6. package/package/corpus/rules/vertical-slices.md +6 -1
  7. package/package/corpus/skills/cratis-arc-command/SKILL.md +27 -3
  8. package/package/corpus/skills/cratis-arc-command/references/handler-shapes.md +26 -7
  9. package/package/corpus/skills/cratis-arc-command-execution/SKILL.md +23 -2
  10. package/package/corpus/skills/cratis-arc-command-operation/LICENSE +2 -0
  11. package/package/corpus/skills/cratis-arc-command-operation/SKILL.md +277 -0
  12. package/package/corpus/skills/cratis-arc-command-operation/references/execution-and-recovery.md +229 -0
  13. package/package/corpus/skills/cratis-arc-command-operation/references/testing.md +252 -0
  14. package/package/corpus/skills/cratis-arc-command-operation/verification.json +19 -0
  15. package/package/corpus/skills/cratis-chronicle-reactor/SKILL.md +3 -0
  16. package/package/corpus/skills/cratis-screenplay-captures-and-reactions/SKILL.md +20 -0
  17. package/package/corpus/skills/cratis-screenplay-command-surface/SKILL.md +3 -0
  18. package/package/corpus/skills/cratis-screenplay-event-modeling/SKILL.md +31 -1
  19. package/package/corpus/skills/cratis-screenplay-model-authoring/references/language-reference.md +19 -5
  20. package/package/corpus/skills/cratis-screenplay-read-surface/SKILL.md +7 -0
  21. package/package/corpus/skills/cratis-screenplay-specifications/SKILL.md +61 -9
  22. package/package/corpus/skills/cratis-screenplay-specifications/verification.json +12 -0
  23. package/package/profile-catalog.json +1 -0
  24. package/package.json +1 -1
@@ -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.