@cratis/pi 7.174.0 → 7.175.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 (21) hide show
  1. package/package/corpus/agents/backend-developer.md +1 -1
  2. package/package/corpus/agents/slice-implementer.md +1 -1
  3. package/package/corpus/harnesses/copilot/instructions/application-profile.instructions.md +2 -2
  4. package/package/corpus/harnesses/copilot/instructions/glossary.instructions.md +1 -1
  5. package/package/corpus/harnesses/copilot/instructions/reactors.instructions.md +7 -3
  6. package/package/corpus/harnesses/copilot/instructions/vertical-slices.instructions.md +11 -7
  7. package/package/corpus/harnesses/pi/agents/backend-developer.md +1 -1
  8. package/package/corpus/harnesses/pi/agents/slice-implementer.md +1 -1
  9. package/package/corpus/rules/application-profile.md +2 -2
  10. package/package/corpus/rules/glossary.md +1 -1
  11. package/package/corpus/rules/reactors.md +7 -3
  12. package/package/corpus/rules/vertical-slices.md +11 -7
  13. package/package/corpus/skills/cratis-arc-authentication-authorization-and-identity/references/authorization.md +1 -1
  14. package/package/corpus/skills/cratis-arc-command/SKILL.md +5 -5
  15. package/package/corpus/skills/cratis-arc-command/references/provide-example.md +32 -8
  16. package/package/corpus/skills/cratis-arc-command-operation/SKILL.md +2 -2
  17. package/package/corpus/skills/cratis-arc-command-validation/SKILL.md +12 -13
  18. package/package/corpus/skills/cratis-arc-command-validation/references/read-model-resolution.md +30 -3
  19. package/package/corpus/skills/cratis-chronicle-reactor/SKILL.md +2 -0
  20. package/package/corpus/skills/cratis-chronicle-reactor/references/durable-side-effects.md +123 -0
  21. package/package.json +1 -1
@@ -77,7 +77,7 @@ Load **cratis-application-slice-conformance** when it is installed; read the ski
77
77
 
78
78
  - Record decorated with `[Command]` from `Cratis.Arc.Commands.ModelBound`, with a public instance **`Handle()`** — never a separate handler class.
79
79
  - Put fetched/computed handler data in **`Provide()`** (runs after validation/authorization); keep `Handle()` focused on event construction.
80
- - **Business rejection is validation, never a throw.** Use `CommandValidator<T>`, `ConceptValidator<T>`, `Provide()` short-circuit, or `Result<TEvent, ValidationResult>` for a concurrency-sensitive in-`Handle()` rule. A thrown exception is HTTP 500, not a validation error.
80
+ - **Business rejection is validation, never a throw.** Use `CommandValidator<T>`, `ConceptValidator<T>`, or `Result<TEvent, ValidationResult>` for a concurrency-sensitive in-`Handle()` rule. A thrown exception is HTTP 500, not a validation error.
81
81
  - Return from `Handle()`: a single event, `IEnumerable<object>` (with `EventForEventSourceId` for cross-stream), tuple `(EventSourceId, event)` / `(response, event)`, `Result<TEvent, ValidationResult>`, or `void`. Never inject `IEventLog` to append the primary event.
82
82
  - Event-source id resolution order: `ICanProvideEventSourceId` → an `EventSourceId`/`EventSourceId<T>`-derived property → a `[Key]` property → else generated.
83
83
 
@@ -92,7 +92,7 @@ Proxies now exist. Build React components from the generated proxies (`react.md`
92
92
  ## Hard rules (the silent-failure ones)
93
93
 
94
94
  - All backend artifacts in one `<Slice>.cs`; namespace mirrors the path; layout per `general.md` (no `Features/` wrapper; `<Module>` optional).
95
- - `Handle()` returns the event/result directly (no `Task.FromResult` without `await`); validation in `CommandValidator<T>`/`ConceptValidator<T>`/`Provide()`; **never throw for normal business rejection** — return `ValidationResult`/`Result<,>`.
95
+ - `Handle()` returns the event/result directly (no `Task.FromResult` without `await`); validation in `CommandValidator<T>`/`ConceptValidator<T>`; **never throw for normal business rejection** — return `ValidationResult`/`Result<,>`.
96
96
  - Start with model-bound attributes, fluent for structured mappings, reducer code for clearer prior-state branches/calculations/guards; **never `.AutoMap()`**. New .NET reducers default to static `Reduce` on the model; separate `IReducerFor<T>` for DI/replay instance behavior/separation; plain-class nomination only when its assembly cannot reference Chronicle. Follow the read-model/reducer skills for Arc query discovery, exact signatures and builder ownership. Preserve admission/ordering guards when converting; do not infer Stage renders the self form or apply it to other SDKs.
97
97
  - Events: plain `[EventType]` for new events (explicit id only to retain a persisted id or resolve a cross-package short-name collision; never change a persisted id), non-nullable, past tense, `<summary>`, never carry the event-source id.
98
98
  - `[OnceOnly]` on non-idempotent reactor side effects; reactors return side-effect events or use `ICommandPipeline` (never `IEventLog`).
@@ -46,11 +46,11 @@ Commands are imperative intents (`Register`, `Create`); the slice folder is the
46
46
  Tagged **[contract]** (framework-enforced) or **[convention]** (house default). Mechanics and examples live in `vertical-slices.md`.
47
47
 
48
48
  1. **[contract] Model-bound — no controllers.** Commands are `[Command]` records with a public instance `Handle()` (Arc analyzers enforce this); queries are `static` methods on `[ReadModel]` records; projections/constraints/authorization use attributes. Arc generates the HTTP surface. For read-model style follow rule 11's ladder; for constraints use `IConstraint` when attributes cannot express the rule.
49
- 2. **[contract] Command validation & data flow.** Put command rejection in `CommandValidator<T>`, global value invariants in `ConceptValidator<T>`, and fetched/computed handler data in **`Provide()`** (runs after validation/authorization; may short-circuit with `ValidationResult.Error` / `Result<TProvided, ValidationResult>`). Keep `Handle()` focused on event construction. For a state-dependent rule that must hold **under concurrency**, use read protection `On` (the default from Arc 23; on Arc 22 set `<CratisReadProtection>On</CratisReadProtection>`): put the rule in a `CommandValidator<T>` with the read model as a constructor parameter and return the events from `Handle()`. Use a constraint for uniqueness, a per-stream read model or `IStreamReads`/`StreamDecision` for one stream, an aggregate for a rich lifecycle; `[ProtectedDecision]` with `DecisionRead<T>` is the older per-command opt-in. Under `Off` (set explicitly, or the Arc 22 behavior) a validator over a plain read is a hint, not a guard. Return a typed rejection via `Result<TEvent, ValidationResult>` where needed; the result alone adds no guard. **Throwing from `Provide()`/`Handle()` is an exception (HTTP 500), not a validation rejection** — throw only for genuinely exceptional conditions, never for normal business rejection.
49
+ 2. **[contract] Command validation & data flow.** Put command rejection in `CommandValidator<T>`, global value invariants in `ConceptValidator<T>`, and fetched/computed handler data in **`Provide()`** (runs after validation/authorization; only acquisition yielding nothing usable short-circuits with `ValidationResult.Error` / `Result<TProvided, ValidationResult>`). Validators own refusals, including read-model existence. Keep `Handle()` focused on event construction. For a state-dependent rule that must hold **under concurrency**, use read protection `On` (the default from Arc 23; on Arc 22 set `<CratisReadProtection>On</CratisReadProtection>`): put the rule in a `CommandValidator<T>` with the read model as a constructor parameter and return the events from `Handle()`. Use a constraint for uniqueness, a per-stream read model or `IStreamReads`/`StreamDecision` for one stream, an aggregate for a rich lifecycle; `[ProtectedDecision]` with `DecisionRead<T>` is the older per-command opt-in. Under `Off` (set explicitly, or the Arc 22 behavior) a validator over a plain read is a hint, not a guard. Return a typed rejection via `Result<TEvent, ValidationResult>` where needed; the result alone adds no guard. **Throwing from `Provide()`/`Handle()` is an exception (HTTP 500), not a validation rejection** — throw only for genuinely exceptional conditions, never for normal business rejection.
50
50
  3. **[contract] Event-source id resolution:** `ICanProvideEventSourceId` first; else the first qualifying property in declaration order — an `EventSourceId`/`EventSourceId<T>`-derived value *or* a `[Key]` property (no priority between them; two candidates is `ARCCHR0002`); else Arc generates one. A value actually used as a Chronicle stream identity derives from `EventSourceId<T>` with the underlying `IComparable` primitive — never `ConceptAs<Guid>` for that stream identity. `NotSet`, `New()`, and primitive→derived-id operators are optional domain/API conveniences, not Chronicle requirements; typed empty/zero values are real specified stream IDs, not `EventSourceId.Unspecified`.
51
51
  4. **[contract] Events never carry the event-source id** — it is implicit in the event context.
52
52
  5. **[contract] `[Key]` / `[Subject]` are distinct.** `[Key]` is for event-source/read-model/projection key resolution; `[Subject]` is compliance identity only. Don't put either on an `EventSourceId<T>` value (it already is both); use them only for non-`EventSourceId<T>` values.
53
- 6. **[contract] Avoid nullable event properties** — Chronicle's analyzer warns on them. Model optional facts as a separate event; resolve nullable command inputs to a non-null sentinel before constructing the event. **Likewise `Handle()` never returns a nullable event or `null` for "nothing to do"** — Arc treats a `null` result as success with nothing appended, so the caller is told a command succeeded that never happened. Missing state or a failed rule is a rejection: return `Result<TEvent, ValidationResult>` with `ValidationResult.Error(...)`, or reject in a validator or `Provide()`. Optional `ICommandOperation` returns are a separate contract and unaffected.
53
+ 6. **[contract] Avoid nullable event properties** — Chronicle's analyzer warns on them. Model optional facts as a separate event; resolve nullable command inputs to a non-null sentinel before constructing the event. **Likewise `Handle()` never returns a nullable event or `null` for "nothing to do"** — Arc treats a `null` result as success with nothing appended, so the caller is told a command succeeded that never happened. Missing state or a failed rule is a rejection: return `Result<TEvent, ValidationResult>` with `ValidationResult.Error(...)`, or reject in a validator, not `Provide()`. Optional `ICommandOperation` returns are a separate contract and unaffected.
54
54
  7. **[convention] New events use plain `[EventType]`** — the type name is the id, public contracts included; "public" never implies a UUID or any explicit id. This is a house convention (decision 152), not a Chronicle contract: Chronicle accepts any string id. An explicit id is allowed only (a) to keep an already-persisted id after a CLR rename, or (b) to resolve a cross-package short-name collision (`MultipleEventTypesWithSameIdFound`). Never change an existing persisted id. Schema changes get a new generation + an `EventTypeMigration<TUpgrade,TPrevious>` (never edit stored-event semantics silently). An enum that only gains a member, or has one renamed, is the exception — Chronicle accepts that in place; a *removed* or *renumbered* member still needs a generation, plus a value map saying what the old values became. Gates: see [guards-and-fuses.md](./guards-and-fuses.instructions.md).
55
55
  8. **[convention] Every `[EventType]` has an XML `<summary>`** — a Cratis C# documentation convention (not a Chronicle rule); events live in the log forever, so record why they exist.
56
56
  9. **[convention] `[ReadModel]` properties carry no default values** except semantically meaningful enum initial states and `[SetValue<T>]`-driven `bool` flags. False defaults hide missing projection wiring.
@@ -50,7 +50,7 @@ One precise line per load-bearing term, so the same word means the same thing ev
50
50
  ## Write side
51
51
 
52
52
  - **Command** — a `[Command]` record expressing an imperative **intent**; its public `Handle()` produces event(s) (or a response).
53
- - **Provide()** — the command method that fetches/computes data after validation/authorization and before `Handle()`; may short-circuit with a `ValidationResult`.
53
+ - **Provide()** — acquires inputs after validation/authorization and before `Handle()`; only short-circuits with a `ValidationResult` when acquisition yields nothing usable. Validators own refusals, including read-model existence.
54
54
  - **Causation chain** — the ordered links saying how an append came about (root process → command → …), each carrying properties. A command records its **name and its property values** there, so an event says what the command was asked to do; the chain lives in the event log and is as permanent as the events.
55
55
  - **Observation command** — a command whose input comes from outside the model's own decisions (webhook, poll, sweep, retry, classifier). It compares with current state and appends nothing when nothing changed; looking is not a fact.
56
56
  - **Signal event** — an event appended only to make a reactor do something (`…Requested`, `…Started`, `…Skipped`). Not a domain fact; use a job, state machine, command operation or `ICommandPipeline`.
@@ -179,18 +179,22 @@ public class RenewalBilling : IReactor
179
179
 
180
180
  - **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.
181
181
  - 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.
182
- - 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).
183
- - 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.
182
+ - A reactor retry can execute the command's operations again; inline operations are not a substitute for reactor durability (see the durable side-effect recipe below) — see **cratis-arc-command-operation** (verified at Arc v22.48.1).
183
+ - Prefer returning the command. A manual `ICommandPipeline.Execute(command)` needs `[OnceOnly]` (`ARCCHR0006`) and its own identity: `[ExecuteCommandsAsSystem]` only wraps **returned** commands in Arc's `CommandSideEffectExecutor`. Without a principal, `[Roles]`/`[Authorize]` denies the manual call. Set it deliberately with `Cratis.Arc.Authorization.ISystemExecution`: `using (systemExecution.AsSystem("<role>")) { var result = await pipeline.Execute(command); }` (`As(ClaimsPrincipal)` for an explicit principal). Roles come only from trusted server-side configuration, never event/request input; do not borrow a request principal. Await inside the scope and inspect `CommandResult` so refusals are not discarded. See **cratis-arc-command-execution**.
184
184
 
185
185
  ## External event stores (outbox / inbox)
186
186
 
187
- Cross-service events route through Chronicle's outbox/inbox rather than a shared log:
187
+ Cross-service events route through Chronicle's outbox/inbox — between event stores, not a job outbox — rather than a shared log:
188
188
 
189
189
  - The producing service appends its **public contract event** to `EventSequenceId.Outbox`.
190
190
  - The consuming observer listens to the implicit inbox sequence for the source store (`inbox-<source-store>`).
191
191
  - Chronicle creates/reuses the outbox→inbox subscription from the observer's `[EventStore]` metadata, or from `[EventStore]` on the event type/assembly. Put `[assembly: EventStore("<source-store>")]` in the contracts project when every event there originates from one service; use observer-level `[EventStore("<source-store>")]` to override.
192
192
  - An observer-level `[EventStore]` **cannot** be combined with `[EventSequence]`, `[EventLog]`, or `Reactor(eventSequence: ...)`.
193
193
 
194
+ ## Durable provider side effects
195
+
196
+ **[convention]** After a command commits: reactor + stable delivery identity + idempotent provider call + returned sent-fact event + a `ReactorScenario` retry spec. Operations are inline/non-durable; Chronicle outbox/inbox is cross-event-store, not a provider job queue. Read **cratis-chronicle-reactor** [references/durable-side-effects.md](../../../skills/cratis-chronicle-reactor/references/durable-side-effects.md) for the recipe and its failure window; never promise exactly-once.
197
+
194
198
  ## Storage lookup failures are not absence
195
199
 
196
200
  At **Chronicle v19.50.1**, a failed next-event lookup leaves the observer's
@@ -88,7 +88,7 @@ The command carries input from the caller. `Handle()` is defined directly on the
88
88
  | --- | --- |
89
89
  | Reusable value invariant (length, format, range) | `ConceptValidator<T>` on the concept type |
90
90
  | Command-input / cross-field / pre-handler rule (incl. injected read-model/service/identity checks) | `CommandValidator<TCommand>` with `RuleFor(...)` |
91
- | Handler needs fetched/computed data before it can build the event | `Provide()` — fetches the data; may validate it and short-circuit |
91
+ | Handler needs fetched/computed data before it can build the event | `Provide()` — acquires inputs; only short-circuits when acquisition yields nothing usable. Validators own refusals |
92
92
  | State-dependent rule that must hold **under concurrency** | Read protection `On`: the read model as a `CommandValidator<T>` constructor (or `Handle()`) parameter; a per-stream read model or `IStreamReads`/`StreamDecision` for one stream; an aggregate for a rich lifecycle. `[ProtectedDecision]` + `DecisionRead<T>` is the older per-command opt-in. Under `Off` (set explicitly, or the Arc 22 behavior) injection is a hint |
93
93
  | Uniqueness | Chronicle `[Unique]` / `IConstraint` (race-safe) — not a read-model pre-check |
94
94
  | Genuinely exceptional failure (bug, missing infra) | `throw` a domain exception |
@@ -135,23 +135,27 @@ Values render camel-cased; concepts unwrap to the value they hold; a value that
135
135
 
136
136
  `Provide()` runs after authorization and validation, before `Handle()`. Its parameters resolve from DI (like `Handle()`'s); the command instance is `this`. Return one value, or a tuple (Arc binds tuple values to `Handle(...)` parameters by type). Each provided value should be consumed by a `Handle` parameter — an unused one raises the **`ARC0005`** analyzer warning. Use a **named record** when the provided values form a real domain/snapshot concept; a **tuple** when they are just separate inputs to event construction. It may be sync or async.
137
137
 
138
+ Validators own refusals, including read-model existence: a `CommandValidator<PlaceOrder>` constructor takes the model, using `[LookUpBy(nameof(PlaceOrder.CustomerId))]` if its key differs from the root id. Non-nullable means it must exist; nullable plus a validator rule gives a custom message (see **cratis-arc-command-validation**).
139
+
140
+ Illustrative excerpt: the application supplies `IExchangeRates.GetFor(CustomerId)` returning `Task<Rate?>`, and `OrderPlaced(Rate rate)`. The customer-existence rule belongs in the validator, not this acquisition:
141
+
138
142
  ```csharp
139
143
  [Command]
140
144
  public record PlaceOrder(OrderId OrderId, CustomerId CustomerId) : ICanProvideEventSourceId
141
145
  {
142
146
  public EventSourceId GetEventSourceId() => OrderId;
143
147
 
144
- public async Task<Result<Customer, ValidationResult>> Provide(IReadModels readModels)
148
+ public async Task<Result<Rate, ValidationResult>> Provide(IExchangeRates rates)
145
149
  {
146
- var customer = await readModels.GetInstanceById<Customer>((EventSourceId)CustomerId);
147
- return customer is null ? ValidationResult.Error("Customer must exist.") : customer;
150
+ var rate = await rates.GetFor(CustomerId);
151
+ return rate is null ? ValidationResult.Error("No rate data available.") : rate;
148
152
  }
149
153
 
150
- public OrderPlaced Handle(Customer customer) => new(customer.Name);
154
+ public OrderPlaced Handle(Rate rate) => new(rate);
151
155
  }
152
156
  ```
153
157
 
154
- 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.
158
+ Use `Provide()` for IO/fetched/computed data a valid command needs (explicit-key read-model lookups, external services, snapshots). Only when acquisition itself yields nothing usable may `ValidationResult` / `AuthorizationResult` / `Result<TProvided, ValidationResult>` short-circuit — here, no external rate data, not an ordinary validation rule. 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. Pick one rejection owner: validators for existence/preconditions; `Result<TEvent, ValidationResult>` in `Handle()` only for a rule depending on the event decision. Do not duplicate the same rejection.
155
159
 
156
160
  **[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**.
157
161
 
@@ -234,7 +238,7 @@ Apply authorization attributes on the `[Command]` record or query method. **[con
234
238
  - **[convention] Plain `[EventType]` for new events, public ones included** — the type name is the id; an explicit id only to retain a persisted id or resolve a cross-package collision, never to change one (application-profile.md item 7, decision 152). Evolve a contract with `generation:` (invoke the **cratis-chronicle-event-type-migration** skill).
235
239
  - **[contract] Past-tense, one-purpose names** (`AuthorRegistered`, not `Updated`/`FormSubmitted`) — Chronicle requires past-tense, single-purpose facts. Self-describing without slice context.
236
240
  - **[contract] Avoid nullable properties** — Chronicle's analyzer warns on nullable event members; model optional facts as a separate event, or resolve a nullable command input to a non-null sentinel before constructing the event.
237
- - **[contract] `Handle()` never returns a nullable event or `null` for "nothing to do"** — Arc treats a `null` result as success with nothing appended, so the caller is told a command succeeded that never happened. Missing state or a failed rule is a rejection: return `Result<TEvent, ValidationResult>` with `ValidationResult.Error(...)`, or reject in a validator or `Provide()`. Optional `ICommandOperation` returns are a separate contract and unaffected.
241
+ - **[contract] `Handle()` never returns a nullable event or `null` for "nothing to do"** — Arc treats a `null` result as success with nothing appended, so the caller is told a command succeeded that never happened. Missing state or a failed rule is a rejection: return `Result<TEvent, ValidationResult>` with `ValidationResult.Error(...)`, or reject in a validator, not `Provide()`. Optional `ICommandOperation` returns are a separate contract and unaffected.
238
242
  - **[contract] Never carry the event-source id** — it's implicit in the event context.
239
243
  - **[convention] No `DateTimeOffset`/`DateTime` properties** that duplicate `EventContext.Occurred` — Chronicle records the wall-clock timestamp of every event there. Read it in projections/reducers via `[SetFromContext<T>]` or fluent `.Set(m => m.X).ToEventContextProperty(c => c.Occurred)`. Use `DateOnly` only for a business date the user explicitly supplies.
240
244
  - **[convention] Every `[EventType]` has an XML `<summary>`** (Cratis C# doc convention) recording why the event exists and what each value means.
@@ -72,7 +72,7 @@ Load **cratis-application-slice-conformance** when it is installed; read the ski
72
72
 
73
73
  - Record decorated with `[Command]` from `Cratis.Arc.Commands.ModelBound`, with a public instance **`Handle()`** — never a separate handler class.
74
74
  - Put fetched/computed handler data in **`Provide()`** (runs after validation/authorization); keep `Handle()` focused on event construction.
75
- - **Business rejection is validation, never a throw.** Use `CommandValidator<T>`, `ConceptValidator<T>`, `Provide()` short-circuit, or `Result<TEvent, ValidationResult>` for a concurrency-sensitive in-`Handle()` rule. A thrown exception is HTTP 500, not a validation error.
75
+ - **Business rejection is validation, never a throw.** Use `CommandValidator<T>`, `ConceptValidator<T>`, or `Result<TEvent, ValidationResult>` for a concurrency-sensitive in-`Handle()` rule. A thrown exception is HTTP 500, not a validation error.
76
76
  - Return from `Handle()`: a single event, `IEnumerable<object>` (with `EventForEventSourceId` for cross-stream), tuple `(EventSourceId, event)` / `(response, event)`, `Result<TEvent, ValidationResult>`, or `void`. Never inject `IEventLog` to append the primary event.
77
77
  - Event-source id resolution order: `ICanProvideEventSourceId` → an `EventSourceId`/`EventSourceId<T>`-derived property → a `[Key]` property → else generated.
78
78
 
@@ -87,7 +87,7 @@ Proxies now exist. Build React components from the generated proxies (`react.md`
87
87
  ## Hard rules (the silent-failure ones)
88
88
 
89
89
  - All backend artifacts in one `<Slice>.cs`; namespace mirrors the path; layout per `general.md` (no `Features/` wrapper; `<Module>` optional).
90
- - `Handle()` returns the event/result directly (no `Task.FromResult` without `await`); validation in `CommandValidator<T>`/`ConceptValidator<T>`/`Provide()`; **never throw for normal business rejection** — return `ValidationResult`/`Result<,>`.
90
+ - `Handle()` returns the event/result directly (no `Task.FromResult` without `await`); validation in `CommandValidator<T>`/`ConceptValidator<T>`; **never throw for normal business rejection** — return `ValidationResult`/`Result<,>`.
91
91
  - Start with model-bound attributes, fluent for structured mappings, reducer code for clearer prior-state branches/calculations/guards; **never `.AutoMap()`**. New .NET reducers default to static `Reduce` on the model; separate `IReducerFor<T>` for DI/replay instance behavior/separation; plain-class nomination only when its assembly cannot reference Chronicle. Follow the read-model/reducer skills for Arc query discovery, exact signatures and builder ownership. Preserve admission/ordering guards when converting; do not infer Stage renders the self form or apply it to other SDKs.
92
92
  - Events: plain `[EventType]` for new events (explicit id only to retain a persisted id or resolve a cross-package short-name collision; never change a persisted id), non-nullable, past tense, `<summary>`, never carry the event-source id.
93
93
  - `[OnceOnly]` on non-idempotent reactor side effects; reactors return side-effect events or use `ICommandPipeline` (never `IEventLog`).
@@ -45,11 +45,11 @@ Commands are imperative intents (`Register`, `Create`); the slice folder is the
45
45
  Tagged **[contract]** (framework-enforced) or **[convention]** (house default). Mechanics and examples live in `vertical-slices.md`.
46
46
 
47
47
  1. **[contract] Model-bound — no controllers.** Commands are `[Command]` records with a public instance `Handle()` (Arc analyzers enforce this); queries are `static` methods on `[ReadModel]` records; projections/constraints/authorization use attributes. Arc generates the HTTP surface. For read-model style follow rule 11's ladder; for constraints use `IConstraint` when attributes cannot express the rule.
48
- 2. **[contract] Command validation & data flow.** Put command rejection in `CommandValidator<T>`, global value invariants in `ConceptValidator<T>`, and fetched/computed handler data in **`Provide()`** (runs after validation/authorization; may short-circuit with `ValidationResult.Error` / `Result<TProvided, ValidationResult>`). Keep `Handle()` focused on event construction. For a state-dependent rule that must hold **under concurrency**, use read protection `On` (the default from Arc 23; on Arc 22 set `<CratisReadProtection>On</CratisReadProtection>`): put the rule in a `CommandValidator<T>` with the read model as a constructor parameter and return the events from `Handle()`. Use a constraint for uniqueness, a per-stream read model or `IStreamReads`/`StreamDecision` for one stream, an aggregate for a rich lifecycle; `[ProtectedDecision]` with `DecisionRead<T>` is the older per-command opt-in. Under `Off` (set explicitly, or the Arc 22 behavior) a validator over a plain read is a hint, not a guard. Return a typed rejection via `Result<TEvent, ValidationResult>` where needed; the result alone adds no guard. **Throwing from `Provide()`/`Handle()` is an exception (HTTP 500), not a validation rejection** — throw only for genuinely exceptional conditions, never for normal business rejection.
48
+ 2. **[contract] Command validation & data flow.** Put command rejection in `CommandValidator<T>`, global value invariants in `ConceptValidator<T>`, and fetched/computed handler data in **`Provide()`** (runs after validation/authorization; only acquisition yielding nothing usable short-circuits with `ValidationResult.Error` / `Result<TProvided, ValidationResult>`). Validators own refusals, including read-model existence. Keep `Handle()` focused on event construction. For a state-dependent rule that must hold **under concurrency**, use read protection `On` (the default from Arc 23; on Arc 22 set `<CratisReadProtection>On</CratisReadProtection>`): put the rule in a `CommandValidator<T>` with the read model as a constructor parameter and return the events from `Handle()`. Use a constraint for uniqueness, a per-stream read model or `IStreamReads`/`StreamDecision` for one stream, an aggregate for a rich lifecycle; `[ProtectedDecision]` with `DecisionRead<T>` is the older per-command opt-in. Under `Off` (set explicitly, or the Arc 22 behavior) a validator over a plain read is a hint, not a guard. Return a typed rejection via `Result<TEvent, ValidationResult>` where needed; the result alone adds no guard. **Throwing from `Provide()`/`Handle()` is an exception (HTTP 500), not a validation rejection** — throw only for genuinely exceptional conditions, never for normal business rejection.
49
49
  3. **[contract] Event-source id resolution:** `ICanProvideEventSourceId` first; else the first qualifying property in declaration order — an `EventSourceId`/`EventSourceId<T>`-derived value *or* a `[Key]` property (no priority between them; two candidates is `ARCCHR0002`); else Arc generates one. A value actually used as a Chronicle stream identity derives from `EventSourceId<T>` with the underlying `IComparable` primitive — never `ConceptAs<Guid>` for that stream identity. `NotSet`, `New()`, and primitive→derived-id operators are optional domain/API conveniences, not Chronicle requirements; typed empty/zero values are real specified stream IDs, not `EventSourceId.Unspecified`.
50
50
  4. **[contract] Events never carry the event-source id** — it is implicit in the event context.
51
51
  5. **[contract] `[Key]` / `[Subject]` are distinct.** `[Key]` is for event-source/read-model/projection key resolution; `[Subject]` is compliance identity only. Don't put either on an `EventSourceId<T>` value (it already is both); use them only for non-`EventSourceId<T>` values.
52
- 6. **[contract] Avoid nullable event properties** — Chronicle's analyzer warns on them. Model optional facts as a separate event; resolve nullable command inputs to a non-null sentinel before constructing the event. **Likewise `Handle()` never returns a nullable event or `null` for "nothing to do"** — Arc treats a `null` result as success with nothing appended, so the caller is told a command succeeded that never happened. Missing state or a failed rule is a rejection: return `Result<TEvent, ValidationResult>` with `ValidationResult.Error(...)`, or reject in a validator or `Provide()`. Optional `ICommandOperation` returns are a separate contract and unaffected.
52
+ 6. **[contract] Avoid nullable event properties** — Chronicle's analyzer warns on them. Model optional facts as a separate event; resolve nullable command inputs to a non-null sentinel before constructing the event. **Likewise `Handle()` never returns a nullable event or `null` for "nothing to do"** — Arc treats a `null` result as success with nothing appended, so the caller is told a command succeeded that never happened. Missing state or a failed rule is a rejection: return `Result<TEvent, ValidationResult>` with `ValidationResult.Error(...)`, or reject in a validator, not `Provide()`. Optional `ICommandOperation` returns are a separate contract and unaffected.
53
53
  7. **[convention] New events use plain `[EventType]`** — the type name is the id, public contracts included; "public" never implies a UUID or any explicit id. This is a house convention (decision 152), not a Chronicle contract: Chronicle accepts any string id. An explicit id is allowed only (a) to keep an already-persisted id after a CLR rename, or (b) to resolve a cross-package short-name collision (`MultipleEventTypesWithSameIdFound`). Never change an existing persisted id. Schema changes get a new generation + an `EventTypeMigration<TUpgrade,TPrevious>` (never edit stored-event semantics silently). An enum that only gains a member, or has one renamed, is the exception — Chronicle accepts that in place; a *removed* or *renumbered* member still needs a generation, plus a value map saying what the old values became. Gates: see [guards-and-fuses.md](./guards-and-fuses.md).
54
54
  8. **[convention] Every `[EventType]` has an XML `<summary>`** — a Cratis C# documentation convention (not a Chronicle rule); events live in the log forever, so record why they exist.
55
55
  9. **[convention] `[ReadModel]` properties carry no default values** except semantically meaningful enum initial states and `[SetValue<T>]`-driven `bool` flags. False defaults hide missing projection wiring.
@@ -49,7 +49,7 @@ One precise line per load-bearing term, so the same word means the same thing ev
49
49
  ## Write side
50
50
 
51
51
  - **Command** — a `[Command]` record expressing an imperative **intent**; its public `Handle()` produces event(s) (or a response).
52
- - **Provide()** — the command method that fetches/computes data after validation/authorization and before `Handle()`; may short-circuit with a `ValidationResult`.
52
+ - **Provide()** — acquires inputs after validation/authorization and before `Handle()`; only short-circuits with a `ValidationResult` when acquisition yields nothing usable. Validators own refusals, including read-model existence.
53
53
  - **Causation chain** — the ordered links saying how an append came about (root process → command → …), each carrying properties. A command records its **name and its property values** there, so an event says what the command was asked to do; the chain lives in the event log and is as permanent as the events.
54
54
  - **Observation command** — a command whose input comes from outside the model's own decisions (webhook, poll, sweep, retry, classifier). It compares with current state and appends nothing when nothing changed; looking is not a fact.
55
55
  - **Signal event** — an event appended only to make a reactor do something (`…Requested`, `…Started`, `…Skipped`). Not a domain fact; use a job, state machine, command operation or `ICommandPipeline`.
@@ -178,18 +178,22 @@ public class RenewalBilling : IReactor
178
178
 
179
179
  - **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.
180
180
  - 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.
181
- - 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).
182
- - 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.
181
+ - A reactor retry can execute the command's operations again; inline operations are not a substitute for reactor durability (see the durable side-effect recipe below) — see **cratis-arc-command-operation** (verified at Arc v22.48.1).
182
+ - Prefer returning the command. A manual `ICommandPipeline.Execute(command)` needs `[OnceOnly]` (`ARCCHR0006`) and its own identity: `[ExecuteCommandsAsSystem]` only wraps **returned** commands in Arc's `CommandSideEffectExecutor`. Without a principal, `[Roles]`/`[Authorize]` denies the manual call. Set it deliberately with `Cratis.Arc.Authorization.ISystemExecution`: `using (systemExecution.AsSystem("<role>")) { var result = await pipeline.Execute(command); }` (`As(ClaimsPrincipal)` for an explicit principal). Roles come only from trusted server-side configuration, never event/request input; do not borrow a request principal. Await inside the scope and inspect `CommandResult` so refusals are not discarded. See **cratis-arc-command-execution**.
183
183
 
184
184
  ## External event stores (outbox / inbox)
185
185
 
186
- Cross-service events route through Chronicle's outbox/inbox rather than a shared log:
186
+ Cross-service events route through Chronicle's outbox/inbox — between event stores, not a job outbox — rather than a shared log:
187
187
 
188
188
  - The producing service appends its **public contract event** to `EventSequenceId.Outbox`.
189
189
  - The consuming observer listens to the implicit inbox sequence for the source store (`inbox-<source-store>`).
190
190
  - Chronicle creates/reuses the outbox→inbox subscription from the observer's `[EventStore]` metadata, or from `[EventStore]` on the event type/assembly. Put `[assembly: EventStore("<source-store>")]` in the contracts project when every event there originates from one service; use observer-level `[EventStore("<source-store>")]` to override.
191
191
  - An observer-level `[EventStore]` **cannot** be combined with `[EventSequence]`, `[EventLog]`, or `Reactor(eventSequence: ...)`.
192
192
 
193
+ ## Durable provider side effects
194
+
195
+ **[convention]** After a command commits: reactor + stable delivery identity + idempotent provider call + returned sent-fact event + a `ReactorScenario` retry spec. Operations are inline/non-durable; Chronicle outbox/inbox is cross-event-store, not a provider job queue. Read **cratis-chronicle-reactor** [references/durable-side-effects.md](../skills/cratis-chronicle-reactor/references/durable-side-effects.md) for the recipe and its failure window; never promise exactly-once.
196
+
193
197
  ## Storage lookup failures are not absence
194
198
 
195
199
  At **Chronicle v19.50.1**, a failed next-event lookup leaves the observer's
@@ -87,7 +87,7 @@ The command carries input from the caller. `Handle()` is defined directly on the
87
87
  | --- | --- |
88
88
  | Reusable value invariant (length, format, range) | `ConceptValidator<T>` on the concept type |
89
89
  | Command-input / cross-field / pre-handler rule (incl. injected read-model/service/identity checks) | `CommandValidator<TCommand>` with `RuleFor(...)` |
90
- | Handler needs fetched/computed data before it can build the event | `Provide()` — fetches the data; may validate it and short-circuit |
90
+ | Handler needs fetched/computed data before it can build the event | `Provide()` — acquires inputs; only short-circuits when acquisition yields nothing usable. Validators own refusals |
91
91
  | State-dependent rule that must hold **under concurrency** | Read protection `On`: the read model as a `CommandValidator<T>` constructor (or `Handle()`) parameter; a per-stream read model or `IStreamReads`/`StreamDecision` for one stream; an aggregate for a rich lifecycle. `[ProtectedDecision]` + `DecisionRead<T>` is the older per-command opt-in. Under `Off` (set explicitly, or the Arc 22 behavior) injection is a hint |
92
92
  | Uniqueness | Chronicle `[Unique]` / `IConstraint` (race-safe) — not a read-model pre-check |
93
93
  | Genuinely exceptional failure (bug, missing infra) | `throw` a domain exception |
@@ -134,23 +134,27 @@ Values render camel-cased; concepts unwrap to the value they hold; a value that
134
134
 
135
135
  `Provide()` runs after authorization and validation, before `Handle()`. Its parameters resolve from DI (like `Handle()`'s); the command instance is `this`. Return one value, or a tuple (Arc binds tuple values to `Handle(...)` parameters by type). Each provided value should be consumed by a `Handle` parameter — an unused one raises the **`ARC0005`** analyzer warning. Use a **named record** when the provided values form a real domain/snapshot concept; a **tuple** when they are just separate inputs to event construction. It may be sync or async.
136
136
 
137
+ Validators own refusals, including read-model existence: a `CommandValidator<PlaceOrder>` constructor takes the model, using `[LookUpBy(nameof(PlaceOrder.CustomerId))]` if its key differs from the root id. Non-nullable means it must exist; nullable plus a validator rule gives a custom message (see **cratis-arc-command-validation**).
138
+
139
+ Illustrative excerpt: the application supplies `IExchangeRates.GetFor(CustomerId)` returning `Task<Rate?>`, and `OrderPlaced(Rate rate)`. The customer-existence rule belongs in the validator, not this acquisition:
140
+
137
141
  ```csharp
138
142
  [Command]
139
143
  public record PlaceOrder(OrderId OrderId, CustomerId CustomerId) : ICanProvideEventSourceId
140
144
  {
141
145
  public EventSourceId GetEventSourceId() => OrderId;
142
146
 
143
- public async Task<Result<Customer, ValidationResult>> Provide(IReadModels readModels)
147
+ public async Task<Result<Rate, ValidationResult>> Provide(IExchangeRates rates)
144
148
  {
145
- var customer = await readModels.GetInstanceById<Customer>((EventSourceId)CustomerId);
146
- return customer is null ? ValidationResult.Error("Customer must exist.") : customer;
149
+ var rate = await rates.GetFor(CustomerId);
150
+ return rate is null ? ValidationResult.Error("No rate data available.") : rate;
147
151
  }
148
152
 
149
- public OrderPlaced Handle(Customer customer) => new(customer.Name);
153
+ public OrderPlaced Handle(Rate rate) => new(rate);
150
154
  }
151
155
  ```
152
156
 
153
- 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.
157
+ Use `Provide()` for IO/fetched/computed data a valid command needs (explicit-key read-model lookups, external services, snapshots). Only when acquisition itself yields nothing usable may `ValidationResult` / `AuthorizationResult` / `Result<TProvided, ValidationResult>` short-circuit — here, no external rate data, not an ordinary validation rule. 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. Pick one rejection owner: validators for existence/preconditions; `Result<TEvent, ValidationResult>` in `Handle()` only for a rule depending on the event decision. Do not duplicate the same rejection.
154
158
 
155
159
  **[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**.
156
160
 
@@ -233,7 +237,7 @@ Apply authorization attributes on the `[Command]` record or query method. **[con
233
237
  - **[convention] Plain `[EventType]` for new events, public ones included** — the type name is the id; an explicit id only to retain a persisted id or resolve a cross-package collision, never to change one (application-profile.md item 7, decision 152). Evolve a contract with `generation:` (invoke the **cratis-chronicle-event-type-migration** skill).
234
238
  - **[contract] Past-tense, one-purpose names** (`AuthorRegistered`, not `Updated`/`FormSubmitted`) — Chronicle requires past-tense, single-purpose facts. Self-describing without slice context.
235
239
  - **[contract] Avoid nullable properties** — Chronicle's analyzer warns on nullable event members; model optional facts as a separate event, or resolve a nullable command input to a non-null sentinel before constructing the event.
236
- - **[contract] `Handle()` never returns a nullable event or `null` for "nothing to do"** — Arc treats a `null` result as success with nothing appended, so the caller is told a command succeeded that never happened. Missing state or a failed rule is a rejection: return `Result<TEvent, ValidationResult>` with `ValidationResult.Error(...)`, or reject in a validator or `Provide()`. Optional `ICommandOperation` returns are a separate contract and unaffected.
240
+ - **[contract] `Handle()` never returns a nullable event or `null` for "nothing to do"** — Arc treats a `null` result as success with nothing appended, so the caller is told a command succeeded that never happened. Missing state or a failed rule is a rejection: return `Result<TEvent, ValidationResult>` with `ValidationResult.Error(...)`, or reject in a validator, not `Provide()`. Optional `ICommandOperation` returns are a separate contract and unaffected.
237
241
  - **[contract] Never carry the event-source id** — it's implicit in the event context.
238
242
  - **[convention] No `DateTimeOffset`/`DateTime` properties** that duplicate `EventContext.Occurred` — Chronicle records the wall-clock timestamp of every event there. Read it in projections/reducers via `[SetFromContext<T>]` or fluent `.Set(m => m.X).ToEventContextProperty(c => c.Occurred)`. Use `DateOnly` only for a business date the user explicitly supplies.
239
243
  - **[convention] Every `[EventType]` has an XML `<summary>`** (Cratis C# doc convention) recording why the event exists and what each value means.
@@ -409,7 +409,7 @@ an `[Unprotected]` command (or a model or method marked `[Unprotected("why")]`)
409
409
  read is advisory, so the rule is **not decision-safe**. A `[ProtectedDecision]`
410
410
  command without `On` runs only certified, parameterless validators and refuses a
411
411
  validator whose constructor takes dependencies; put such a rule in `Provide()` or
412
- `Handle()` using `DecisionRead<T>` or `IDecisionReads`. Hand-registered scoped,
412
+ `Handle()` (older opt-in exception) using `DecisionRead<T>` or `IDecisionReads`. Hand-registered scoped,
413
413
  singleton, factory or instance validators are refused under `On`. Keep
414
414
  static/service-locator state out of validators: a guard covers reads Arc can see.
415
415
  Source: [protected validator boundary](https://github.com/Cratis/Arc/blob/main/Documentation/backend/csharp/chronicle/read-models/injecting-into-commands.md).
@@ -112,7 +112,7 @@ stack for this application work.
112
112
  processes a non-null result, so a `null` is success with nothing appended and the
113
113
  caller is told a command succeeded that never happened. Missing state or a failed
114
114
  rule is a rejection: return `Result<TEvent, ValidationResult>` with
115
- `ValidationResult.Error(...)`, or reject in a validator or `Provide()`. Optional
115
+ `ValidationResult.Error(...)`, or reject in a validator, not `Provide()`. Optional
116
116
  `ICommandOperation` returns are a separate contract and unaffected. `ARCCHR0015` warns on nullable event returns. A nullable
117
117
  read-model parameter (`ARC0006`) is handled by rejecting, never by returning a
118
118
  nullable event.
@@ -191,9 +191,9 @@ to `Handle`'s parameters by type.
191
191
 
192
192
  Read [references/provide-example.md](references/provide-example.md) for a worked `Provide()` example.
193
193
 
194
- - Short-circuit with `ValidationResult.Error(...)`; do not throw for a rejection
195
- the user can act on. A thrown exception surfaces as `HasExceptions` and HTTP
196
- 500, not as a validation failure.
194
+ - Validators own refusals, including read-model existence. Only short-circuit
195
+ with `ValidationResult.Error(...)` when acquisition yields nothing usable.
196
+ A thrown exception surfaces as `HasExceptions` and HTTP 500, not validation.
197
197
  - Every value `Provide` returns must be consumed by a `Handle` parameter.
198
198
  `ARC0005` warns otherwise. `ValidationResult`, `AuthorizationResult` and
199
199
  `CommandResult` are exempt because they short-circuit rather than feed `Handle`.
@@ -278,7 +278,7 @@ Keep `Handle` a pure function of the command, its read-model parameters and
278
278
  provided values: that makes it specifiable by a plain call. Start `Handle()` and
279
279
  validator decisions with direct calls and supplied read-model state. Add the
280
280
  pipeline scenario plus a negative proof per authorization policy, validator
281
- rejection and `Provide()` short-circuit, and a constraint scenario; never
281
+ rejection and acquisition-only `Provide()` short-circuit, and a constraint scenario; never
282
282
  read-protection plumbing or simulated concurrency. Follow the
283
283
  [decision table](../../rules/specs.scenarios.csharp.md).
284
284
 
@@ -1,19 +1,43 @@
1
1
  # Provide example
2
2
 
3
- This reference holds a worked `Provide()` example that rejects with a validation result.
3
+ Validators own ordinary refusals, including read-model existence. For this
4
+ command, a `CommandValidator<OpenAccount>` constructor takes
5
+ `[LookUpBy(nameof(OpenAccount.OwnerId))] Owner owner`: non-nullable means the owner
6
+ must exist, looked up by `OwnerId` rather than the account's root id. For a custom
7
+ message, use a nullable model and a validator rule; see
8
+ [the validator example](../../cratis-arc-command-validation/references/read-model-resolution.md).
9
+ Do not duplicate that check in `Provide()`.
10
+
11
+ This illustrative excerpt assumes application types `AccountId` (an event-source
12
+ id), `OwnerId`, `Owner`, `CreditHistory`, `AccountOpened(CreditHistory history)`, and
13
+ `ICreditHistory.GetFor(OwnerId)` returning `Task<CreditHistory?>`. `Provide()`
14
+ acquires the history needed by `Handle()`; its only error means that the external
15
+ lookup yielded no data, not that an ordinary validation rule failed.
4
16
 
5
17
  ```csharp
18
+ /// <summary>Opens an account using acquired credit history.</summary>
19
+ /// <param name="Id">The account's event-source id.</param>
20
+ /// <param name="OwnerId">The owner to validate and look up.</param>
6
21
  [Command]
7
- public record Open<Thing>(<ThingId> Id, <OwnerId> OwnerId)
22
+ public record OpenAccount(AccountId Id, OwnerId OwnerId)
8
23
  {
9
- public async Task<Result<<Owner>, ValidationResult>> Provide(IReadModels readModels)
24
+ /// <summary>Acquires the credit history used by the decision.</summary>
25
+ /// <param name="histories">The external history lookup.</param>
26
+ /// <returns>History, or an error when the lookup yields no data.</returns>
27
+ public async Task<Result<CreditHistory, ValidationResult>> Provide(ICreditHistory histories)
10
28
  {
11
- var owner = await readModels.GetInstanceById<<Owner>>((EventSourceId)OwnerId);
12
- return owner is null
13
- ? ValidationResult.Error("Owner must exist.")
14
- : owner;
29
+ var history = await histories.GetFor(OwnerId);
30
+ return history is null
31
+ ? ValidationResult.Error("No credit history available.")
32
+ : history;
15
33
  }
16
34
 
17
- public <ThingOpened> Handle(<Owner> owner) => new(owner.Id);
35
+ /// <summary>Builds the account-opened fact from the acquired history.</summary>
36
+ /// <param name="history">The history supplied by Provide.</param>
37
+ /// <returns>The account-opened fact.</returns>
38
+ public AccountOpened Handle(CreditHistory history) => new(history);
18
39
  }
19
40
  ```
41
+
42
+ Only acquisition yielding nothing usable short-circuits here. Keep validation in
43
+ the validator, IO in `Provide()` and the event decision in `Handle()`.
@@ -42,7 +42,7 @@ Arc for TypeScript server API.
42
42
  | Perform immediate external work chosen by the command | `ICommandOperation` |
43
43
  | Reverse attempted work after an eligible failure | Optional `Compensate()` |
44
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** |
45
+ | Reliable work after commit: email, payments, retriable webhooks | A reactor; **not inline operations**. Recipe: **cratis-chronicle-reactor** [references/durable-side-effects.md](../cratis-chronicle-reactor/references/durable-side-effects.md) |
46
46
  | Use an external result to make the decision or response | An explicit service call; operations cannot return receipts |
47
47
  | Extend framework interpretation of a specialized return type | Response value handlers, not application operation orchestration |
48
48
 
@@ -254,7 +254,7 @@ migration. Provider tests must separately prove ownership and idempotency.
254
254
  | Raw `IEnumerable<ICommandOperation>` | Return `CommandOperations` (`ARC0017`) |
255
255
  | Capturing services in the record | Inject them into operation methods |
256
256
  | 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 |
257
- | Using inline operations for email/payment delivery that must survive a crash | Use reactors/outbox/durable workflows |
257
+ | Using inline operations for email/payment delivery that must survive a crash | Recipe: **cratis-chronicle-reactor** [references/durable-side-effects.md](../cratis-chronicle-reactor/references/durable-side-effects.md) |
258
258
  | Assuming `!IsSuccess` means nothing committed | Inspect backend commitment and recovery observations |
259
259
  | Marking a committing scope as a nonparticipant | Report its actual boundary; do not evade the single-participant limit |
260
260
 
@@ -66,7 +66,7 @@ under `Off` (set explicitly, or the Arc 22 behavior) it is a hint, never the mec
66
66
  | --- | --- |
67
67
  | A reusable value invariant — length, format, range | `ConceptValidator<T>` on the concept type |
68
68
  | Command input, cross-field, or a pre-handler check | `CommandValidator<TCommand>` with `RuleFor(...)` |
69
- | A dependency on data the handler must fetch first | `Provide()` — fetch, and short-circuit if unusable |
69
+ | A dependency on data the handler must fetch first | `Provide()` — acquire inputs; only short-circuit if acquisition yields nothing usable |
70
70
  | State-dependent and must hold **under concurrency** | Under `On`, a `CommandValidator<T>` with the read model as a constructor parameter (Step 5); or `IStreamReads`/`StreamDecision`; return events through Arc. `[ProtectedDecision]` + `DecisionRead<T>` is the older per-command opt-in |
71
71
  | Uniqueness | A Chronicle constraint, never a command-side read |
72
72
  | A genuine defect or missing infrastructure | `throw` a domain exception |
@@ -152,17 +152,15 @@ metadata. Do not conflate metadata coverage with validator certification.
152
152
  `Provide()` runs after authorization and validation and before `Handle()`. Its
153
153
  parameters resolve from dependency injection; the command instance is `this`.
154
154
 
155
- ```csharp
156
- public async Task<Result<Customer, ValidationResult>> Provide(IReadModels readModels)
157
- {
158
- var customer = await readModels.GetInstanceById<Customer>((EventSourceId)CustomerId);
159
- return customer is null ? ValidationResult.Error("Customer must exist.") : customer;
160
- }
161
- ```
155
+ Validators own refusals, including read-model existence; `Provide()` only
156
+ short-circuits when acquisition itself yields nothing usable. Read
157
+ [read-model-resolution.md](references/read-model-resolution.md) for the validator-owned
158
+ existence check and [provide-example.md](../cratis-arc-command/references/provide-example.md)
159
+ for an external lookup that yields no data.
162
160
 
163
- - Returning a `ValidationResult`, an `IEnumerable<ValidationResult>`, an
164
- `AuthorizationResult`, or a `CommandResult` short-circuits: `Handle()` is
165
- never invoked.
161
+ - When acquisition yields nothing usable, a returned `ValidationResult`, an
162
+ `IEnumerable<ValidationResult>`, an `AuthorizationResult`, or a `CommandResult`
163
+ short-circuits: `Handle()` is never invoked.
166
164
  - A `Result<TProvided, ValidationResult>` has its inner value unwrapped, so the
167
165
  success arm flows to `Handle()` and the error arm short-circuits.
168
166
  - A returned tuple is flattened and its elements bound to `Handle()` parameters
@@ -170,8 +168,9 @@ public async Task<Result<Customer, ValidationResult>> Provide(IReadModels readMo
170
168
  an unused one is `ARC0005`.
171
169
  - Keep the fetch in `Provide()` and the decision in `Handle()`. Do not write a
172
170
  pass-through `Provide()` that only forwards a read model `Handle()` could take
173
- directly, and do not duplicate one rejection in both the validator and
174
- `Provide()` — pick one owner.
171
+ directly. Pick one rejection owner: validators for existence/preconditions;
172
+ `Result<TEvent, ValidationResult>` in `Handle()` only for a rule depending on the
173
+ event decision. Do not duplicate the same rejection.
175
174
 
176
175
  ## Step 5 — Guard a concurrency-sensitive decision
177
176
 
@@ -17,9 +17,36 @@ protected work it is an advisory read, not a consistency guard.
17
17
 
18
18
  A missing instance resolves to `null`, not a default object. A nullable parameter
19
19
  receives that null; a non-nullable one produces a validation failure (400).
20
- `ARC0006` warns on a non-nullable command-scoped read-model parameter. Reject a
21
- missing nullable model through a validator, `Provide()` or
22
- `Result<TEvent, ValidationResult>`; do not return a nullable event.
20
+ `ARC0006` warns on a non-nullable command-scoped read-model parameter.
21
+
22
+ Validators own missing-model refusals, not `Provide()`. A non-nullable read-model
23
+ constructor parameter on `CommandValidator<TCommand>` means the model must exist;
24
+ missing data is refused as `ReadModelDoesNotExistForCommand`. For a custom message,
25
+ take a nullable model and add a validator rule. This illustrative excerpt assumes
26
+ `PlaceOrder` has an `OrderId` root and a separate `CustomerId`, and `Customer` is a
27
+ read model. Use `Cratis.Arc.Commands` and `FluentValidation`:
28
+
29
+ ```csharp
30
+ /// <summary>Requires an existing customer for an order.</summary>
31
+ public class PlaceOrderValidator : CommandValidator<PlaceOrder>
32
+ {
33
+ /// <summary>Builds the customer-existence rule.</summary>
34
+ /// <param name="customer">The customer resolved by the command's customer id.</param>
35
+ public PlaceOrderValidator(
36
+ [LookUpBy(nameof(PlaceOrder.CustomerId))] Customer? customer)
37
+ {
38
+ RuleFor(_ => customer).NotNull().WithMessage("Customer must exist.");
39
+ }
40
+ }
41
+ ```
42
+
43
+ Use `[LookUpBy(nameof(PlaceOrder.CustomerId))]` because this model is keyed by a
44
+ command property other than the root event-source id. `Provide()` is for acquiring
45
+ inputs the valid command needs, and only short-circuits when acquisition yields
46
+ nothing usable; it does not own this existence rule. Use
47
+ `Result<TEvent, ValidationResult>` in `Handle()` only when a rejection depends on
48
+ the event decision, not as a second copy of the validator rule. Do not throw for
49
+ normal business rejection or return a nullable event.
23
50
 
24
51
  Read **cratis-arc-command** for the full resolution and nullability reference,
25
52
  including passive projections where absence is not null.
@@ -192,6 +192,8 @@ Keep `[OnceOnly]` and idempotency. Expected refusals use `Invoke.Command` branch
192
192
  in **cratis-arc-command-execution**; handling stops remaining invocations.
193
193
  Unhandled refusals and framework failures remain partition failures. Inline operations can run again on reactor retry and do not
194
194
  replace durable delivery; see **cratis-arc-command-operation**.
195
+ For a durable provider effect after a command, read [the recipe](references/durable-side-effects.md): hashed named-effect provider key, idempotent call, sent-fact event, retry spec.
196
+ `[ExecuteCommandsAsSystem]` covers returned commands only; manual pipeline calls need `ISystemExecution` — see [reactors.md](../../rules/reactors.md).
195
197
  Mixed event-and-command returns and their ordering are owned by the Arc skills.
196
198
 
197
199
  ## Failure behavior
@@ -0,0 +1,123 @@
1
+ <!-- Copyright (c) Cratis. All rights reserved. -->
2
+ <!-- Licensed under the MIT license. See LICENSE file in the project root for full license information. -->
3
+
4
+ # Durable provider side effects
5
+
6
+ ## Contents
7
+
8
+ - When it applies
9
+ - Recipe
10
+ - Illustrative handler
11
+ - Retry specification
12
+ - Related guidance
13
+
14
+ ## When it applies
15
+
16
+ Use this pattern for an after-commit email, payment or webhook that must survive
17
+ crashes and retries. A stable delivery identity is not an exactly-once guarantee.
18
+
19
+ Command operations are inline: their journal is in memory, with no durable retry.
20
+ A reactor retry can execute its command's operations again. Chronicle outbox/inbox
21
+ moves public events **between event stores** (`EventSequenceId.Outbox` to the
22
+ consumer's inbox); it is not a per-effect job queue for provider calls.
23
+
24
+ ## Recipe
25
+
26
+ 1. Let the command's `Handle()` return the domain event. That committed fact is
27
+ the durable trigger; do not append a signal/tick event just to wake a reactor.
28
+ 2. Handle the fact in a reactor with an explicit `[Reactor("confirmation-email")]`
29
+ identity. Its id contributes to the persisted delivery key, so renaming the
30
+ class must not silently create a different observer identity.
31
+ 3. Accept `ReactorDelivery delivery` and pass
32
+ `delivery.IdempotencyKeyFor("confirmation-email").Value` as the provider's
33
+ idempotency key. This is a 64-character hash including the effect name and
34
+ epoch; do not send raw `delivery.Id` outside your boundary, and check the
35
+ provider's key-length limit.
36
+ 4. Require receiver-side deduplication on that key, including suitable retention
37
+ and retry rules. For an effect in an application-owned database, write the
38
+ receipt and effect in the same transaction. A separate receipt cannot make a
39
+ remote provider call atomic.
40
+ 5. On success, return a past-tense sent-fact event, such as `ConfirmationSent`.
41
+ Returned events get idempotent append keys derived from the delivery. On a
42
+ kernel supporting idempotent appends, repeating the same key and output does
43
+ not append another copy. Keep output stable; do not generate fresh ids or timestamps.
44
+ 6. Keep `[OnceOnly]` when replay must not repeat the effect. It excludes replay,
45
+ not recovery retries, and does not replace provider-side idempotency.
46
+
47
+ **Failure window:** a crash after the provider accepts the request but before the
48
+ sent-fact is recorded causes another call on recovery. Only the provider's
49
+ idempotency contract makes that remote retry safe. A receipt written before the
50
+ call can instead mark work complete that was never sent. Never promise exactly-once.
51
+
52
+ ## Illustrative handler
53
+
54
+ This excerpt uses `Cratis.Chronicle.Reactors` and `Cratis.Chronicle.Events`.
55
+ The application supplies `IConfirmationProvider.Send(ConfirmationRequest request,
56
+ string idempotencyKey)` returning `Task`, `ConfirmationRequested` with a `Request`
57
+ property, and the event `ConfirmationSent`. Here `ConfirmationRequested` records a
58
+ real user request; it is not a synthetic signal appended solely for this reactor.
59
+
60
+ ```csharp
61
+ /// <summary>Sends a requested confirmation with receiver-side deduplication.</summary>
62
+ /// <param name="provider">The idempotent confirmation provider.</param>
63
+ [Reactor("confirmation-email")]
64
+ public class SendConfirmation(IConfirmationProvider provider) : IReactor
65
+ {
66
+ /// <summary>Sends the confirmation and returns the sent fact.</summary>
67
+ /// <param name="@event">The recorded request.</param>
68
+ /// <param name="context">The source event context.</param>
69
+ /// <param name="delivery">The stable delivery identity.</param>
70
+ /// <returns>The sent fact for the source event.</returns>
71
+ [OnceOnly]
72
+ public async Task<ConfirmationSent> Send(
73
+ ConfirmationRequested @event, EventContext context, ReactorDelivery delivery)
74
+ {
75
+ await provider.Send(@event.Request,
76
+ idempotencyKey: delivery.IdempotencyKeyFor("confirmation-email").Value);
77
+ return new ConfirmationSent();
78
+ }
79
+ }
80
+ ```
81
+
82
+ ## Retry specification
83
+
84
+ Requires Chronicle 19.61.0 for `History` and `Redeliver`. Check the testing package
85
+ version; on older packages call the handler with the same context/delivery or
86
+ specify the receipt collaborator, as described in [specifications.md](specifications.md).
87
+
88
+ Use `ReactorScenario<SendConfirmation>` (`Cratis.Chronicle.Testing.Reactors`) with
89
+ an injected, deduplicating provider fake. The fake records every key, sends only
90
+ for a new key, then throws on the first call **after accepting the send**. On a
91
+ repeated key it returns successfully without sending again. This models the
92
+ failure window between the provider accepting and the handler returning its fact.
93
+
94
+ 1. Record one occurrence without invoking the handler:
95
+ `var occurrence = await scenario.Given.ForEventSource(id).History(@event);`.
96
+ 2. Capture the exception from `await scenario.Redeliver(occurrence);`. Handler
97
+ exceptions surface to the caller. Assert the fake accepted one send, and use
98
+ `scenario.ShouldNotHaveProduced<ConfirmationSent>()` before any successful retry.
99
+ 3. Call `await scenario.Redeliver(occurrence);` again. Assert both provider calls
100
+ carried the same `delivery.IdempotencyKeyFor("confirmation-email").Value`,
101
+ the fake sent once in total, and `scenario.ShouldHaveProduced<ConfirmationSent>()`.
102
+ 4. Redeliver that same occurrence a third time. All keys must still match, with
103
+ one fake-provider send. Do not use `Given.Events` twice: that creates distinct
104
+ occurrences rather than preserving the original `ReactorDelivery` identity.
105
+
106
+ `ReactorScenario` records **every returned event**, including another sent-fact on
107
+ successful redelivery. `ShouldHaveProduced` checks presence, not a count. The
108
+ scenario does not append those events and does **not** prove durable append
109
+ deduplication. Returned-event append keys protect the event-log write only with a
110
+ kernel supporting idempotent appends; they do not stop the handler or provider
111
+ call from running again.
112
+
113
+ The scenario does not execute external effects for the test, prove observer
114
+ registration or prove retry scheduling. The injected fake supplies the provider
115
+ behavior; production startup checks belong to **cratis-application-slice-conformance**.
116
+ Run the reactor's specification project and require the retry assertions to pass.
117
+
118
+ ## Related guidance
119
+
120
+ - Read [cratis-arc-command-operation](../../cratis-arc-command-operation/SKILL.md) for inline work and compensation, not durable delivery.
121
+ - Read [cratis-multi-service-architecture](../../cratis-multi-service-architecture/SKILL.md) for cross-store outbox/inbox routing.
122
+ - Read [specifications.md](specifications.md) for scenario setup and redelivery.
123
+ - Read [reactors.md](../../../rules/reactors.md) for returned commands and deliberate execution identity.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cratis/pi",
3
- "version": "7.174.0",
3
+ "version": "7.175.0",
4
4
  "description": "Configuration-aware Cratis AI integration for Pi",
5
5
  "type": "module",
6
6
  "files": [