@cratis/pi 7.47.0 → 7.48.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 (20) hide show
  1. package/package/corpus/harnesses/copilot/instructions/application-profile.instructions.md +1 -1
  2. package/package/corpus/harnesses/copilot/instructions/vertical-slices.instructions.md +1 -1
  3. package/package/corpus/rules/application-profile.md +1 -1
  4. package/package/corpus/rules/vertical-slices.md +1 -1
  5. package/package/corpus/skills/cratis-arc-command/SKILL.md +7 -6
  6. package/package/corpus/skills/cratis-arc-command/references/decisions-and-routing.md +41 -11
  7. package/package/corpus/skills/cratis-arc-command/references/read-model-injection.md +2 -1
  8. package/package/corpus/skills/cratis-arc-command/references/shop-generation.md +3 -1
  9. package/package/corpus/skills/cratis-arc-command-validation/SKILL.md +18 -4
  10. package/package/corpus/skills/cratis-chronicle-decision-reads/SKILL.md +41 -6
  11. package/package/corpus/skills/cratis-chronicle-decision-reads/references/choosing-how-a-rule-holds.md +213 -0
  12. package/package/corpus/skills/cratis-chronicle-event-constraints/SKILL.md +17 -4
  13. package/package/corpus/skills/cratis-chronicle-event-modeling/SKILL.md +3 -1
  14. package/package/corpus/skills/cratis-chronicle-read-model/SKILL.md +12 -3
  15. package/package/corpus/skills/cratis-chronicle-reducer/SKILL.md +6 -2
  16. package/package/corpus/skills/cratis-fundamentals-concept/references/shop-generation.md +3 -1
  17. package/package/corpus/skills/cratis-screenplay-command-surface/references/generated-values-and-responses.md +2 -1
  18. package/package/corpus/skills/cratis-screenplay-command-surface/references/shop-generation.md +2 -1
  19. package/package/corpus/skills/cratis-screenplay-streams-and-consistency/SKILL.md +2 -1
  20. package/package.json +1 -1
@@ -18,7 +18,7 @@ Pick exactly one type per slice folder — determined by what the slice *does*.
18
18
 
19
19
  | Type | What it does | Contents |
20
20
  | --- | --- | --- |
21
- | **State Change** | Accepts a command, appends events | Command + validator + event(s); optional `[Passive]` read model for command-side decisions |
21
+ | **State Change** | Accepts a command, appends events | Command + validator + event(s); optional `[Passive]` for a current read; a rule that must hold under concurrency needs a decision read or constraint (see the `cratis-chronicle-decision-reads` skill, `references/choosing-how-a-rule-holds.md`) |
22
22
  | **State View** | Projects events into a queryable read model | `[ReadModel]` + model-bound projection + static query method(s) |
23
23
  | **Automation** | Reacts to events, calls external systems / `ICommandPipeline`, or returns follow-up commands/events (including to another stream) | Reactor only |
24
24
  | **Translation** | Takes data from outside our own facts (an external system or another service) and records it as our facts | An adapter at the boundary, often a reactor |
@@ -391,7 +391,7 @@ Redaction is a system-event request that removes payload availability from the e
391
391
 
392
392
  ## Cross-slice patterns **[convention]**
393
393
 
394
- Cross-slice access is **read-only and goes through Chronicle** — inject another slice's read model (validator/`Provide()`/`Handle()`), read by explicit key with `IReadModels.GetInstanceById`, mark a `[Passive]` projection for command-side decisions, or react to its events. **Never** instantiate or DI another slice's command/handler/service.
394
+ Cross-slice access is **read-only and goes through Chronicle** — inject another slice's read model (validator/`Provide()`/`Handle()`), read by explicit key with `IReadModels.GetInstanceById`, mark a `[Passive]` projection for a current read (a rule that must hold under concurrency needs a decision read or constraint, see the `cratis-chronicle-decision-reads` skill's `references/choosing-how-a-rule-holds.md`), or react to its events. **Never** instantiate or DI another slice's command/handler/service.
395
395
 
396
396
  **DCB (Dynamic Consistency Boundary):** the boundary is the event state explicitly
397
397
  enrolled in guarded decisions, not every model a command reads. Use stream
@@ -17,7 +17,7 @@ Pick exactly one type per slice folder — determined by what the slice *does*.
17
17
 
18
18
  | Type | What it does | Contents |
19
19
  | --- | --- | --- |
20
- | **State Change** | Accepts a command, appends events | Command + validator + event(s); optional `[Passive]` read model for command-side decisions |
20
+ | **State Change** | Accepts a command, appends events | Command + validator + event(s); optional `[Passive]` for a current read; a rule that must hold under concurrency needs a decision read or constraint (see the `cratis-chronicle-decision-reads` skill, `references/choosing-how-a-rule-holds.md`) |
21
21
  | **State View** | Projects events into a queryable read model | `[ReadModel]` + model-bound projection + static query method(s) |
22
22
  | **Automation** | Reacts to events, calls external systems / `ICommandPipeline`, or returns follow-up commands/events (including to another stream) | Reactor only |
23
23
  | **Translation** | Takes data from outside our own facts (an external system or another service) and records it as our facts | An adapter at the boundary, often a reactor |
@@ -390,7 +390,7 @@ Redaction is a system-event request that removes payload availability from the e
390
390
 
391
391
  ## Cross-slice patterns **[convention]**
392
392
 
393
- Cross-slice access is **read-only and goes through Chronicle** — inject another slice's read model (validator/`Provide()`/`Handle()`), read by explicit key with `IReadModels.GetInstanceById`, mark a `[Passive]` projection for command-side decisions, or react to its events. **Never** instantiate or DI another slice's command/handler/service.
393
+ Cross-slice access is **read-only and goes through Chronicle** — inject another slice's read model (validator/`Provide()`/`Handle()`), read by explicit key with `IReadModels.GetInstanceById`, mark a `[Passive]` projection for a current read (a rule that must hold under concurrency needs a decision read or constraint, see the `cratis-chronicle-decision-reads` skill's `references/choosing-how-a-rule-holds.md`), or react to its events. **Never** instantiate or DI another slice's command/handler/service.
394
394
 
395
395
  **DCB (Dynamic Consistency Boundary):** the boundary is the event state explicitly
396
396
  enrolled in guarded decisions, not every model a command reads. Use stream
@@ -205,9 +205,8 @@ Chronicle resolves the command's event source id in this order:
205
205
  property on the command;
206
206
  4. otherwise a freshly generated id.
207
207
 
208
- A command with more than one candidate property is ambiguous and `ARCCHR0002`
209
- warns; implement `ICanProvideEventSourceId` to say which value wins. Do not rely
210
- on property order.
208
+ Two or more candidates raise `ARCCHR0002` (`[Key]` does not silence it); Arc
209
+ silently takes the first declared. Implement `ICanProvideEventSourceId`.
211
210
 
212
211
  `[Key]` on a positional record's primary-constructor parameter is recognized
213
212
  and counted once. Child-only/nested read-model types are not standalone
@@ -217,8 +216,9 @@ stream metadata on commands and aggregate roots.
217
216
  Read [decisions and routing](references/decisions-and-routing.md) when a command
218
217
  needs guarded state, stream-id templates, definition-backed routes, event tags or
219
218
  post-commit `CompleteStream`. Plain read-model injection remains advisory;
220
- `Result<,>` alone is not concurrency protection. Explicit routing on a returned
221
- `EventForEventSourceId` wins over command context.
219
+ `Result<,>` and `concurrency: true` are not protection; see
220
+ [choosing how a rule holds](../cratis-chronicle-decision-reads/references/choosing-how-a-rule-holds.md).
221
+ A returned `EventForEventSourceId` route wins over command context.
222
222
 
223
223
  Two attributes are spelled `[Key]`. Chronicle reads `Cratis.Chronicle.Keys.KeyAttribute`.
224
224
  Marking `System.ComponentModel.DataAnnotations.KeyAttribute` in an application
@@ -256,7 +256,8 @@ public record Open<Thing>(<ThingId> Id, <OwnerId> OwnerId)
256
256
  - `Provide` runs after authorization and validation.
257
257
 
258
258
  An Arc read model can also be injected directly into `Provide`, `Handle`, or a
259
- `CommandValidator<T>` — but only by **the command's own resolved key**. Reading a
259
+ `CommandValidator<T>` — but only by **the command's own resolved key**, as a plain
260
+ read that guards nothing. Reading a
260
261
  read model keyed by anything else needs an explicit by-id read, and an absent
261
262
  instance does not always arrive as `null`. Read
262
263
  [read-model injection](references/read-model-injection.md) before relying on a
@@ -1,5 +1,13 @@
1
1
  # Protected decisions and routed streams
2
2
 
3
+ ## Contents
4
+
5
+ - Pick the guarded read
6
+ - Definition-backed routes and templates
7
+ - Tags and completion
8
+ - Decision specifications
9
+ - Sources at v22.75.0
10
+
3
11
  <!-- Copyright (c) Cratis. All rights reserved. -->
4
12
  <!-- Licensed under the MIT license. See LICENSE file in the project root for full license information. -->
5
13
 
@@ -7,8 +15,11 @@ Verified at **Arc v22.75.0**. These features require `Cratis.Arc.Chronicle`.
7
15
 
8
16
  ## Pick the guarded read
9
17
 
10
- Plain injected read models and `IReadModels.GetInstanceById` are advisory. A
11
- `Result<TEvent, ValidationResult>` rejects a request but does not enroll a guard.
18
+ Plain injected read models and `IReadModels.GetInstanceById` are advisory,
19
+ materialized or passive. A `Result<TEvent, ValidationResult>` rejects a request
20
+ but does not enroll a guard. Uniqueness and create-once belong to a Chronicle
21
+ constraint, not to any read. For the routing steps, the matrix and the traps read
22
+ [choosing how a rule holds](../../cratis-chronicle-decision-reads/references/choosing-how-a-rule-holds.md).
12
23
 
13
24
  - For one stream, inject `IStreamReads` into `Provide`, call `ForCommand()`, and
14
25
  return `StreamDecision.Append(...)` from `Handle`. It returns
@@ -19,20 +30,39 @@ Plain injected read models and `IReadModels.GetInstanceById` are advisory. A
19
30
  `Provide`/`Handle` (`Exists`/`Instance`). Command-aware `IDecisionReads.Get<T>`
20
31
  enrolls reads of other keys. Only Chronicle-admitted direct event-source-keyed
21
32
  projections with a known event-type set qualify; reducers, joins, children,
22
- passive and incomplete definitions are refused. Arc certifies parameterless
33
+ open-ended event types and incomplete definitions are refused. Arc certifies parameterless
23
34
  validators it constructs; constructor dependencies and uncertified instances
24
- are refused. Keep all decision state out of validators, including static
25
- members and service locators. `[Unprotected]` on the command opts out; never
35
+ are refused: a protected command's discoverable validator needs exactly one
36
+ public parameterless constructor, otherwise the command fails with HTTP 500.
37
+ The decision model needs an `Id` property, an event-source key and a flat
38
+ projection; self-reducing models are refused like reducers. When the command has
39
+ two or more key candidates, implement `ICanProvideEventSourceId`: `[Key]` does
40
+ not silence `ARCCHR0002`, and Arc silently keys by the first eligible property
41
+ in declaration order. Keep all decision state out of validators, including
42
+ static members and service locators. `[Unprotected]` on the command opts out; never
26
43
  combine it with `[ProtectedDecision]`. A parameter-level marker acknowledges
27
44
  tooling, not a runtime opt-out. `Validate` is advisory, not a commit promise.
28
- - Automatic `concurrency: true` on the routing attributes supplies stream-level
29
- scopes. Exact returned scopes replace automatic capture; remove the flags
30
- when returning `EventsWithConcurrencyScopes` (ARCCHR0016).
45
+ - `concurrency: true` on the routing attributes is **not** a guard for the
46
+ decision: Arc reads the narrowed tail after `Handle`, so it only widens or
47
+ narrows the window the default check covers. Exact returned scopes replace
48
+ automatic capture; remove the flags when returning `EventsWithConcurrencyScopes`
49
+ (ARCCHR0016). The default check also reads the tail after `Handle`, and the first
50
+ append into a scope is unchecked unless `CheckFirstAppendIntoAScope` is set.
31
51
 
32
52
  Do not manually append or commit to bypass the owner-capable unit of work.
33
- Protection does not guard foreign writers, external state, revisions, redactions,
34
- migrations or changes to projection definitions. A successful empty protected
35
- command still validates enrolled reads. In contrast, `StreamDecision.Append([])`
53
+ The guard detects every matching event appended after its boundary, whoever wrote
54
+ it, but it protects only guarded decisions: an unguarded writer deciding on the
55
+ same facts can still append on stale state, so the rule holds only when every
56
+ deciding writer is guarded or the rule is a constraint. Protection does not guard an unguarded writer's own decision (a plain read,
57
+ `[Unprotected]` or a direct append), external state, revisions, redactions,
58
+ migrations, changes to projection definitions or writes that bypass the kernel's
59
+ serialized append path. Protection is per command and
60
+ opt-in; an unmarked command keeps its plain reads, and a conflict is returned as a
61
+ `ConcurrencyViolation` validation result with no automatic retry. A protected command that
62
+ stages no events commits an empty guarded batch: current kernels validate the
63
+ enrolled reads (a scope with an actual boundary or expecting no matching event) and write nothing, while a kernel that rejects an empty batch
64
+ raises `DecisionReadValidateOnlyNotSupported` (HTTP 500), so cover it with an
65
+ integration specification. In contrast, `StreamDecision.Append([])`
36
66
  returns no scopes: use it only for an identical retry, not a rejected request.
37
67
 
38
68
  ## Definition-backed routes and templates
@@ -56,7 +56,8 @@ A command that carries no usable key at all fails inside the resolver with
56
56
  failure rather than a server fault.
57
57
 
58
58
  `ARC0006` warns when a read-model parameter is non-nullable, precisely because a
59
- command-scoped read model can be missing. Make it nullable when absence is part
59
+ command-scoped read model can be missing (it does not fire for model-bound
60
+ projections). Make it nullable when absence is part
60
61
  of the command's valid behavior; keep it non-nullable when absence really is a
61
62
  rejection. When absence is a rejection, check the nullable parameter and return
62
63
  `ValidationResult.Error(...)` through `Result<TEvent, ValidationResult>`; never
@@ -90,7 +90,9 @@ and captured-time semantics, never one exact random suffix.
90
90
  - Randomness is not idempotency, storage freshness or a gapless invoice allocator.
91
91
  Arc#3129 freshness is not delivered by this parameter API; Stage's v15 explicit
92
92
  scopes are a separate realization.
93
- - ApiKey is a credential, never a Chronicle stream ID. `[NotAudited]` protects
93
+ - ApiKey is a credential, never a Chronicle stream ID: event-source IDs are plaintext
94
+ metadata and cannot be encrypted. Identify the key with a separate `ApiKeyId` and keep
95
+ ApiKey a secret value property. `[NotAudited]` protects
94
96
  causation only. Never log captures, return secrets on public endpoints, or
95
97
  append plaintext authentication credentials. Retain a hash; for retained
96
98
  operational secrets use `[Encrypted]` plus `[NotAudited]`.
@@ -63,6 +63,11 @@ another version.
63
63
 
64
64
  ## Step 1 — Choose the mechanism by what the decision *is*
65
65
 
66
+ Which mechanism makes a rule hold under concurrent writers (constraint, protected
67
+ decision, stream decision, aggregate, scope, reactor repair) is routed in
68
+ [choosing how a rule holds](../cratis-chronicle-decision-reads/references/choosing-how-a-rule-holds.md).
69
+ A validator is never that mechanism.
70
+
66
71
  | The rule is… | Put it in |
67
72
  | --- | --- |
68
73
  | A reusable value invariant — length, format, range | `ConceptValidator<T>` on the concept type |
@@ -116,7 +121,11 @@ public class TransferFundsValidator : CommandValidator<TransferFunds>
116
121
  - The validator is discovered by type — no registration.
117
122
  - Constructor dependencies (read models, services) are injected. A read model
118
123
  injected here resolves the same way as one injected into `Handle()`; see
119
- Step 5 for what "the same way" actually means.
124
+ Step 5 for what "the same way" actually means. A validator that reads state is
125
+ **advisory only**: it shows the state at validation time and guards nothing, so
126
+ use it for a friendly early message, never as the rule. A `[ProtectedDecision]`
127
+ command refuses a discoverable validator unless it has exactly one public
128
+ parameterless constructor (otherwise HTTP 500), so keep state rules out of it.
120
129
  - **Omit the validator entirely when there are no rules.** An empty subclass is
121
130
  noise the reader has to check.
122
131
  - Single-property intrinsic rules belong on `ConceptValidator<T>` instead, so
@@ -162,13 +171,18 @@ append. Choose the first boundary that fits at Arc v22.75.0:
162
171
  2. Projected state: mark the command `[ProtectedDecision]` and take
163
172
  `DecisionRead<T>` (`.Exists`/`.Instance`) or command-aware `IDecisionReads`.
164
173
  Only Chronicle-admitted, direct event-source-keyed projections with known
165
- event types qualify; reducers, joins, children and passive shapes are refused.
174
+ event types qualify; reducers (including self-reducing models), joins, children and open-ended event
175
+ types are refused. The model needs an `Id` property.
166
176
  Only parameterless validators constructed/certified by Arc run. Constructor
167
177
  dependencies are refused; static/service-locator decision state is still your
168
178
  responsibility. Command-level `[Unprotected]` opts out, not into safety.
169
179
  3. Stream-level automatic scopes: `concurrency: true` on routing attributes
170
- (`EventStreamId`, `EventStreamType`, `EventSourceType`). Exact returned scopes
171
- take precedence; do not combine automatic capture with exact scopes.
180
+ (`EventStreamId`, `EventStreamType`, `EventSourceType`). It is **not** a guard
181
+ for the decision: like the default check it reads the tail after `Handle`.
182
+ Exact returned scopes take precedence; do not combine automatic capture with
183
+ exact scopes. A guard detects every matching event after its boundary, whoever
184
+ wrote it, but it protects only guarded decisions, so every writer that decides
185
+ on the rule needs one, or the rule must be a constraint.
172
186
 
173
187
  `ARCCHR0011/0012` flag unprotected reads and immediate append bypasses. Return
174
188
  events, never append them directly. Read
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: cratis-chronicle-decision-reads
3
- description: Guard a state-dependent Chronicle decision with IDecisionReads, projection admission, ambient unit-of-work enrollment and commit conflict handling. Use when an append must remain valid for the facts read, when choosing whole-source versus stream-scoped reads, or diagnosing DecisionReadRefused and scope conflicts. Do not use for ordinary query reads, append-time uniqueness alone, or defining an Arc command's ProtectedDecision API.
3
+ description: Guard a state-dependent Chronicle decision with IDecisionReads, projection admission, ambient unit-of-work enrollment and commit conflict handling, and choose which mechanism makes a write-side rule hold (constraint, decision read, stream decision, aggregate, explicit scope, reactor repair or a plain read). Use when an append must remain valid for the facts read, when a rule must hold under concurrent writers, when choosing whole-source versus stream-scoped reads, or diagnosing DecisionReadRefused and scope conflicts. Do not use for ordinary query reads, append-time uniqueness alone, or defining an Arc command's ProtectedDecision API.
4
4
  license: MIT
5
5
  ---
6
6
 
@@ -15,6 +15,12 @@ carries a guard to commit. The append is rejected when a later event inside that
15
15
  guard could change the decision. This is the Chronicle side of a dynamic
16
16
  consistency boundary (DCB), not authorization or a replacement for unique constraints.
17
17
 
18
+ Read [choosing how a rule holds](references/choosing-how-a-rule-holds.md) first
19
+ when the question is which mechanism to use, or before writing code that reads
20
+ state and then appends. It carries the routing steps, the matrix with what not to
21
+ use, and the traps. A plain read, a validator read, `Result<,>` and
22
+ `concurrency: true` are never the guard.
23
+
18
24
  ## Verified product sources
19
25
 
20
26
  | Product | Version | Sources |
@@ -34,9 +40,11 @@ compatibility checking to force a read through.
34
40
  their unit-of-work ownership in a handler. The Chronicle `DecisionRead<T>`
35
41
  below is not a license to invent an Arc wrapper shape.
36
42
  - For a unique value claimed atomically or a closed stream, use
37
- **cratis-chronicle-event-constraints**.
43
+ **cratis-chronicle-event-constraints**. A decision read guards one key's
44
+ history, not a value across keys: it is the wrong tool for uniqueness.
38
45
  - For read-model declarations, use **cratis-chronicle-read-model** and
39
- **cratis-chronicle-projection**. Ordinary `IReadModels` reads do not enroll guards.
46
+ **cratis-chronicle-projection**. Ordinary `IReadModels` reads do not enroll
47
+ guards, materialized or passive.
40
48
  - In model-first scope, settle the rule and its refusal/concurrency specifications
41
49
  in the accepted model using **cratis-screenplay-event-modeling** before gap-fill.
42
50
  Never broaden a projection or bypass model protection just to make admission pass.
@@ -46,7 +54,10 @@ compatibility checking to force a read through.
46
54
  `IDecisionReads` is in `Cratis.Chronicle.ReadModels`; obtain the reader with
47
55
  `eventStore.GetDecisionReads()` (`ReadModels/DecisionReadExtensions.cs`).
48
56
  `Admit<T>()` / `AdmitForStream<T>()` check shape **without I/O**, returning
49
- `DecisionReadAdmission(IsAdmitted, Reason)`. A successful shape check is not
57
+ `DecisionReadAdmission(IsAdmitted, Reason)`. The model needs an `Id` property
58
+ (string, or a Guid in lowercase hyphenated form) and an event-source-keyed flat
59
+ projection. Reducers, including self-reducing models (19.58.0), are refused with
60
+ `Reducer`; a missing `Id` or an unconvertible key refuses with `KeyConversion`. A successful shape check is not
50
61
  runtime read success: definitions, key conversion and fold completion are also
51
62
  checked while reading.
52
63
 
@@ -82,8 +93,12 @@ Enroll the read **before** staging its decision's events through
82
93
  `EventLog.Transactional` and let the owning unit of work commit. Inspect
83
94
  `IsSuccess`, append errors/constraint violations/concurrency violations and
84
95
  `GetDecisionConflicts()`; the latter reports decision conflicts without exposing
85
- sequence numbers. A checked empty append validates its scope without writing
86
- an event. Do not mistake "no event" for "no consistency check".
96
+ sequence numbers. On a kernel whose append validators accept an empty batch
97
+ (Chronicle v19.59.1 does when a scope carries an actual boundary or expects no matching event), a checked empty
98
+ append validates its scope and writes nothing; a kernel that rejects it surfaces
99
+ `DecisionReadValidateOnlyNotSupported`, which fails closed. Do not mistake "no
100
+ event" for "no consistency check", and assert validate-only in an integration
101
+ specification before relying on it.
87
102
 
88
103
  Do not attach a separate explicit concurrency scope to a source already guarded
89
104
  by a decision read: `DecisionReadConflictsWithConcurrencyScope` rejects that
@@ -97,6 +112,26 @@ business rule; never resend stale events as if a retry fixed the decision. A
97
112
  DCB guard protects event facts, not external side effects. Durable follow-up
98
113
  belongs in a reactor/outbox; use **cratis-chronicle-reactor**.
99
114
 
115
+ ## When not to use a decision read
116
+
117
+ A guard detects every matching event after its boundary, whoever wrote it, but it
118
+ protects only the decision that carries it. A writer that decides on the same facts
119
+ without a guard can still append on stale state, so the rule holds only when every
120
+ deciding writer is guarded or the rule is a constraint.
121
+
122
+ - Uniqueness or create-once: a constraint. Two keys that must each be unique are
123
+ not a read problem.
124
+ - A UX hint or a display: a plain read. A decision read costs about four calls per
125
+ attempt and refolds the key's whole history every time.
126
+ - A hot key with a long history: shorten the history, or accept an advisory read
127
+ and repair with a reactor.
128
+ - External state, revise/redact, other sequences: no guard covers them.
129
+ - The unit commits in the ASP.NET Core middleware: it commits after the response
130
+ and reports no concurrency violation. Call
131
+ `IUnitOfWorkCompletionFeature.CommitAsync()` before responding.
132
+ - Protection is opt-in in Arc (`[ProtectedDecision]`), so an unmarked command with
133
+ a read model is still unguarded.
134
+
100
135
  ## Verify
101
136
 
102
137
  - The model is admitted and the read is protected and enrolled in the intended
@@ -0,0 +1,213 @@
1
+ # Choosing how a write-side rule holds
2
+
3
+ ## Contents
4
+
5
+ - Route first
6
+ - The matrix
7
+ - A plain read guards nothing
8
+ - Constraints
9
+ - Decision reads and protected decisions
10
+ - Arc traps
11
+ - Chronicle-only traps
12
+ - Costs and why protection is opt-in
13
+ - Checklist for generated code
14
+
15
+ <!-- Copyright (c) Cratis. All rights reserved. -->
16
+ <!-- Licensed under the MIT license. See LICENSE file in the project root for full license information. -->
17
+
18
+ Shared by the Chronicle, Arc and Screenplay consistency skills. It answers one
19
+ question: **which mechanism makes this rule hold while other writers append at the
20
+ same time**, and which look correct but do not. Read it before writing a command,
21
+ validator, endpoint or handler that reads state and then appends.
22
+
23
+ Verified against Chronicle source at v19.59.1 (decision-read refusals of
24
+ self-reducing models since 19.58.0) and Arc main `0986d097a`. Published guides, which
25
+ this agrees with:
26
+ [Chronicle: choosing how a rule holds](/chronicle/dynamic-consistency-boundary/choosing/),
27
+ [decision reads](/chronicle/read-models/decision-reads/),
28
+ [Arc: choosing how a command's rule holds](/arc/backend/csharp/chronicle/consistency/).
29
+
30
+ ## Route first
31
+
32
+ Take the first step that matches the rule.
33
+
34
+ 1. **A value must be unique, or something may exist once** (email, ISBN, one
35
+ registration per source): a constraint. Not a read, not a validator.
36
+ 2. **The rule uses data outside Chronicle events**: record the external fact as an
37
+ event first, then decide on it; otherwise accept the risk and repair. No decision
38
+ read covers external state.
39
+ 3. **A rare violation is acceptable** (overbooking you can compensate): append
40
+ normally and repair with a reactor that returns a correcting event.
41
+ 4. **Someone edited what someone else changed** (the user saw revision N): an explicit
42
+ concurrency scope built from the revision the user supplied.
43
+ 5. **A rule over one key's history** (cannot ship before payment, stock or count
44
+ on one key): a decision read of a flat, event-source-keyed projection.
45
+ 6. **A rule over one stream inside a source**: a stream-scoped decision read
46
+ (Chronicle) or `IStreamReads`/`StreamDecision` (Arc).
47
+ 7. **A rule across two keys** (course capacity and a student's course limit): one
48
+ decision read per key, one event per event source, one atomic `AppendMany`; or
49
+ put every fact the rule needs on one event source and use one read.
50
+ 8. **Rich behaviour over one lifecycle** (many rules, one key): a richer flat
51
+ projection read as one decision read, or in Arc an aggregate root.
52
+ 9. **Only a UX hint** (disable a button, show seats left): a plain read.
53
+ 10. **Only input shape** (range, format, required): a validator. No guard needed.
54
+
55
+ ## The matrix
56
+
57
+ | Rule shape | Use | Never use | Too much |
58
+ | --- | --- | --- | --- |
59
+ | Unique value | `[Unique]` property or `IConstraint` | read model check then append | decision read or scope (they guard one key's history) |
60
+ | Create once | `[Unique]` on the event type | "does it exist" read then append | decision read |
61
+ | One key's history, stock, count | decision read; Arc `[ProtectedDecision]` + `DecisionRead<T>` | plain read model, validator read, `concurrency: true` | aggregate for one counter |
62
+ | Two keys | two decision reads + one event per source in one `AppendMany` | two separate appends, a guard on one side only | none |
63
+ | One stream | stream-scoped decision read; Arc `IStreamReads` | whole-source read when one stream matters | none |
64
+ | Edit conflict | explicit scope from the user's revision | last writer wins by accident | constraint |
65
+ | Rich behaviour | richer projection read once; Arc aggregate | rules spread over validators and plain reads | aggregate for one rule |
66
+ | Rare violation acceptable | append, repair with a reactor | presenting a plain read as a guarantee | decision read |
67
+ | UX hint | plain read | treating the hint as enforcement | decision read (several calls and a full fold) |
68
+ | Hot key, long history | shorten histories (split by period or stream); constraint for uniqueness | ignoring cost: each decision read refolds the key | none |
69
+
70
+ Not a guard: a plain read, a `CommandValidator` that reads, `Result<,>`, returning
71
+ `ValidationResult.Error`, `concurrency: true`, the default optimistic append, a
72
+ reactor, or an `ExpectedRevision` you never pass into a scope.
73
+
74
+ ## A plain read guards nothing
75
+
76
+ Whatever the backing, a plain read captures no position and enrolls no guard.
77
+
78
+ | Backing | Freshness | Guard |
79
+ | --- | --- | --- |
80
+ | Materialized projection or reducer (default) | may lag the log | none |
81
+ | `[Passive]` projection | fresh at read time | none |
82
+ | `[Passive]` reducer | fresh at read time | none |
83
+ | Self-reducing model (19.58.0) | as its `[Passive]` setting | none |
84
+
85
+ Passive is fresher, not safer. Capturing the tail yourself before a materialized
86
+ read does not fix it: the read may be older than the position you captured, and
87
+ the events in between are neither seen nor guarded. Do not rebuild a decision read
88
+ by hand. Every Arc read-model injection (`Handle`, `Provide`, validator
89
+ constructor) and every `IReadModels.GetInstanceById` is a plain read, on a
90
+ protected command too.
91
+
92
+ ## Constraints
93
+
94
+ A constraint binds every writer, whichever client or service appends, per namespace
95
+ and per event sequence. It cannot count, sum or test a predicate; it expresses
96
+ uniqueness (with release on a removal event), create-once and closed streams.
97
+
98
+ - The claim is settled after the durable append (decision 0005, accepted, not yet
99
+ implemented in every store). A failed index update is logged and a later duplicate
100
+ may pass until a reindex. SQL and InMemory stores do not yet settle claims
101
+ (#3744 and the decision's gap list). A constraint is the right mechanism, not an
102
+ unconditional proof.
103
+ - Tenants in different namespaces can claim the same value.
104
+ - `[RemoveConstraint]` releases attribute constraints (`[Unique]` on a property
105
+ or on the event type); on a fluent `IConstraint` it compiles and does nothing,
106
+ so use `.RemovedWith<T>()` there.
107
+ - It is not re-run when the kernel retries a duplicate sequence number.
108
+ - For a friendly message use `.WithMessage`; Arc maps a violation to HTTP 400.
109
+
110
+ ## Decision reads and protected decisions
111
+
112
+ A decision read folds an admitted projection in a fresh session after capturing
113
+ the log boundary, and the append is rejected if an event of the model's types
114
+ for that key arrived after the boundary, **whoever wrote it** (the kernel checks the
115
+ stored tail filtered by key, types and route). See the skill's
116
+ [admission and ownership](admission-and-ownership.md) for the refusal list.
117
+
118
+ - **Admission.** A flat projection keyed by event source, with a finite event-type
119
+ set and an `Id` property (string, or Guid in lowercase hyphenated form). Reducers,
120
+ self-reducing models, joins, children, `FromEvery`, event-property routing and
121
+ other sequences are refused. A model without `Id`, or keyed by a concept that does
122
+ not convert, refuses with `KeyConversion`; in Arc that surfaces as HTTP 500.
123
+ - **Absent models are guarded.** A concurrent creation conflicts. Do not fabricate a
124
+ default instance for an absent model.
125
+ - **Cross-key.** A read on key X guards X even when the command appends only to Y.
126
+ Per-key reads cover only keys in the read set: when new keys can join the set
127
+ ("a member holds at most three loans" with each loan on its own source), write the
128
+ facts on a key that is read, usually the member's.
129
+ - **Every deciding writer must be guarded.** The guard detects every matching
130
+ event appended after its boundary, but it protects only the decision that carries
131
+ it. If the guarded write lands first, a writer that decides on the same facts
132
+ without a guard (a plain read, an `[Unprotected]` command, a direct append) can
133
+ still append on stale state and break the rule. The rule holds only when every
134
+ writer that decides on it is guarded, or when it is a constraint, which checks
135
+ every append.
136
+ - **Conflict.** No automatic retry. Reread and decide again, or resubmit. Revise/redact,
137
+ other sequences, external state, projection definition changes and writes that
138
+ bypass the kernel's serialized append path (duplicate grain activations, direct
139
+ storage writes) are outside the guard.
140
+ - **Empty protected commit.** A unit that enrolled a decision read and staged no
141
+ events appends an empty batch with the guard scopes. At Chronicle v19.59.1 the kernel
142
+ validators (`AppendManyValidator`, `AppendManyForEventSourcesValidator`) accept an
143
+ empty batch when a scope carries an actual boundary or expects no matching event, and the integration
144
+ spec `for_ReadModels/when_reading_for_a_decision` shows `AppendMany([], guardedBy:)`
145
+ succeeds when nothing changed and reports a concurrency violation when the model
146
+ changed. A kernel that rejects an empty batch ("At least one event is required.")
147
+ surfaces as `DecisionReadValidateOnlyNotSupported`, which fails closed. Read from
148
+ source, not run end to end: treat validate-only as supported on a current kernel
149
+ and assert it with an integration specification before relying on it.
150
+ - **Arc opt-in.** Protection is per command: `[ProtectedDecision]` marks a command
151
+ that takes `DecisionRead<T>` or command-aware `IDecisionReads`; unmarked commands
152
+ keep legacy behaviour, `[Unprotected]` opts out. There is no app-wide option, because
153
+ making it default would refuse validators with dependencies, refused shapes and
154
+ commands appending through an injected `IEventLog`.
155
+ The key is the command's event source id; for other keys use
156
+ `IDecisionReads.Get<T>((ReadModelKey)id)`.
157
+
158
+ ## Arc traps
159
+
160
+ | Trap | What happens | Fix |
161
+ | --- | --- | --- |
162
+ | Read model injected into `Handle`, `Provide` or a validator, then events returned | plain read; two requests both win | decision read, constraint or stream decision |
163
+ | `CommandValidator` that reads state | advisory; also refused on a protected command | validator for shape rules only |
164
+ | Protected command with a discoverable validator that has constructor dependencies or several public constructors | HTTP 500, nothing runs | parameterless validator (exactly one public parameterless constructor); move state rules into the decision |
165
+ | `concurrency: true` on `EventStreamId`, `EventStreamType` or `EventSourceType` | reads the narrowed tail after `Handle`; changes granularity, not the decision. A command that also reads `IReadModels` still triggers `ARCCHR0011` | decision read, explicit scope or stream decision |
166
+ | Default (no attributes) | Arc reads the tail when the unit of work commits, after `Handle` | only protects the window between that read and the write |
167
+ | First append into a scope | unchecked unless `ChronicleOptions.ConcurrencyOptions.CheckFirstAppendIntoAScope` is set | constraint, or an aggregate (new aggregates expect no first event) |
168
+ | Two or more key candidates (`EventSourceId`-typed, `[Key]`-marked or implicitly convertible) | `ARCCHR0002` warns, and `[Key]` does not silence it. At runtime Arc silently takes the first eligible property in declaration order (`EventSourceId`-typed or `[Key]`-marked, no priority for derived types; an unmarked `ConceptAs<Guid>` is not eligible). With one candidate Arc keys by it silently; with none each call gets a new id | implement `ICanProvideEventSourceId` |
169
+ | No id property | a random event source id per call; nothing can conflict | give the command a key |
170
+ | `[Unprotected]` command taking `DecisionRead<T>` | resolves to an unguarded read | use `[ProtectedDecision]` |
171
+ | Injected `IEventLog.Append` in `Handle` | immediate write that survives a conflict rollback | return events |
172
+ | Aggregate `Commit()` whose result is ignored, or `Failed()` without `Commit()` | staged events still commit | return `await aggregate.Commit()` |
173
+ | Aggregate with an enrolled decision read | `Commit()` throws `ProtectedUnitOfWorkRequiresOwner` | choose one mechanism per command |
174
+ | Aggregate for a rule across aggregates | each aggregate guards only itself | cross-key decision reads |
175
+ | Tests without `UseDecisionReads()` and a competing `AppendConcurrently` | the race is never exercised | `CommandScenario` with decision reads |
176
+
177
+ ## Chronicle-only traps
178
+
179
+ - Decision read, then plain `IEventLog.Append`: the immediate append bypasses the
180
+ guard. Stage with `Transactional.Append`, or pass `guardedBy:` to `AppendMany`.
181
+ - `Get<T>` needs an ambient unit of work. `GetDetached<T>` enrolls nothing until you
182
+ pass it to `AppendMany(..., guardedBy:)` or `AddDecisionRead`.
183
+ - The ASP.NET Core middleware commits **after** the response. Call
184
+ `IUnitOfWorkCompletionFeature.CommitAsync()` before responding and check
185
+ `IsSuccess` and `GetDecisionConflicts()`; the middleware reports no concurrency
186
+ violations, so a late commit failure never reaches the caller.
187
+ - Ignoring the `AppendResult` loses a violation silently: violations are results.
188
+ - An explicit scope and a decision read on the same source in one unit throw
189
+ `DecisionReadConflictsWithConcurrencyScope`; pick one.
190
+ - A manual scope built without a sequence number is skipped by the kernel; check
191
+ `ConcurrencyCheckPerformed`. Capture the tail before reading the facts.
192
+ - Arc has a static class also named `ConcurrencyScopeBuilder`; in an Arc project
193
+ qualify Chronicle's builder.
194
+
195
+ ## Costs and why protection is opt-in
196
+
197
+ A decision read makes about four calls per attempt (up to three attempts), folds the
198
+ key's whole history of the model's types on every read, shares a per-model-type
199
+ projection grain across keys and tenants, and is not retried on conflict. Use it
200
+ where histories are short and write contention per key is low; shorten histories
201
+ before reaching for it on a hot key. A constraint costs one index lookup inside the
202
+ append. Decision reads are .NET only.
203
+
204
+ ## Checklist for generated code
205
+
206
+ - Name the mechanism and say why the rule shape needs it. A plain read, validator,
207
+ `Result<,>` or `concurrency: true` is never presented as the guard.
208
+ - Uniqueness is a constraint. A state rule has a decision read, scope or stream
209
+ decision enrolled **before** the events are staged.
210
+ - The decision-read model is admitted (flat projection, `Id`, event-source keyed).
211
+ - Cross-key rules append one event per source atomically.
212
+ - A specification interleaves a competing append and asserts the conflict.
213
+ - What stays unguarded (an unguarded writer's own decision, external state, revisions) is stated.
@@ -13,6 +13,16 @@ already be stale by the time the append lands; a constraint cannot be.
13
13
 
14
14
  Constraints are discovered automatically. There is no registration call.
15
15
 
16
+ A constraint binds **every** writer, whichever client or service appends, so it is
17
+ the mechanism for uniqueness and create-once. It cannot count, sum or test a
18
+ predicate: capacity and stock rules need a decision read, a stream decision or an
19
+ aggregate. Read [choosing how a rule holds](../cratis-chronicle-decision-reads/references/choosing-how-a-rule-holds.md)
20
+ when it is unclear which one a rule needs. Limits: the claim is settled after the
21
+ durable append (decision 0005), so a failed index update can let a later duplicate
22
+ through until a reindex; constraints apply per event store namespace and event
23
+ sequence, so tenants in different namespaces can claim the same value; and a
24
+ constraint is not re-run when the kernel retries a duplicate sequence number.
25
+
16
26
  ## Verified product sources
17
27
 
18
28
  | Package | Version | Purpose |
@@ -32,9 +42,10 @@ memory.
32
42
 
33
43
  - The rule rejects **command input** — a range, a format, a cross-field
34
44
  condition: use `cratis-arc-command-validation`.
35
- - The rule is state-dependent and needs concurrency protection: use enrolled
36
- stream/projection decision reads with `cratis-arc-command-validation`.
37
- Plain injected models and `Result<,>` alone remain advisory.
45
+ - The rule is state-dependent (a count, a capacity, a status) and needs
46
+ concurrency protection: use enrolled stream/projection decision reads with
47
+ `cratis-arc-command-validation` and `cratis-chronicle-decision-reads`. Plain
48
+ injected models, validators and `Result<,>` alone remain advisory.
38
49
  - You are creating or changing a read model that the rule reads: use
39
50
  `cratis-chronicle-read-model`.
40
51
  - You are writing the specification and want the `EventScenario` mechanics in
@@ -261,7 +272,9 @@ removing a manual closure. Closing does not erase history or prevent replay.
261
272
  - **The constraint never fires.** You used class-level `[Unique]` for a value
262
273
  that has to be unique across event sources, or property-level `[Unique]` for
263
274
  a "one per event source" rule. Re-read Step 1 — the kind is the switch.
264
- - **`[RemoveConstraint]` releases nothing.** The string does not match the
275
+ - **`[RemoveConstraint]` releases nothing.** It releases attribute constraints
276
+ (`[Unique]` on a property or on the event type); on a fluent `IConstraint` it
277
+ compiles and does nothing, so use `.RemovedWith<T>()` there. Otherwise the string does not match the
265
278
  `[Unique]` name. When `[Unique]` had no explicit name the real name is the
266
279
  member or type name, which is easy to get wrong; name it explicitly.
267
280
  - **`PropertyDoesNotExistOnEventType` at startup.** A non-member-access lambda
@@ -132,7 +132,9 @@ If a field can only be filled by reaching into another behavior's read model to
132
132
  *learn a fact the events should have carried*, you have found a missing event or
133
133
  a wrong stream boundary. Fix the model. A read-only cross-slice read through
134
134
  Chronicle is allowed where the rule needs it (an injected read model read by
135
- explicit key, or a `[Passive]` projection for a command-side decision); see
135
+ explicit key, or a `[Passive]` projection for a current read; a rule that must hold under
136
+ concurrency needs a decision read or constraint, see
137
+ [choosing how a rule holds](../cratis-chronicle-decision-reads/references/choosing-how-a-rule-holds.md)); see
136
138
  Cross-slice patterns in `rules/vertical-slices.md`. Make such a read deliberate
137
139
  and name it in the brief, with the consistency it needs: a rule that must hold
138
140
  under concurrency needs enrolled guarded reads, not plain injection or a stale
@@ -173,12 +173,19 @@ Neighbouring members include `GetInstances<T>`, `GetSnapshotsById<T>`,
173
173
  surface on `IReadModels`** — filtered reads go through the sink, which is what
174
174
  the Arc query methods above do.
175
175
 
176
- ### `[Passive]` when the read is a command-side decision
176
+ ### `[Passive]` when the read must be current
177
177
 
178
178
  `Cratis.Chronicle.ReadModels.PassiveAttribute` on the read-model type makes it
179
179
  passive: no sink, nothing materialized, and the instance is computed on demand
180
- from the events at the moment it is read. Reach for it when a decision needs the
181
- model **strongly consistent** rather than eventually consistent.
180
+ from the events at the moment it is read. Reach for it when a read must be
181
+ current rather than eventually consistent.
182
+
183
+ **Passive is fresher, not safer.** A materialized read may lag the log; a passive
184
+ read is current when read. Neither captures a position or enrolls a guard, so
185
+ neither makes a rule hold when two requests race. To guard a decision use a decision
186
+ read over a flat, event-source-keyed projection with an `Id` property (reducers and
187
+ self-reducing models are refused), a constraint for uniqueness, or an aggregate;
188
+ see [choosing how a rule holds](../cratis-chronicle-decision-reads/references/choosing-how-a-rule-holds.md).
182
189
 
183
190
  **`IMongoCollection<T>` reads only the sink.** It cannot compute passive state:
184
191
  a fresh passive model has no maintained collection, and a formerly active one
@@ -232,6 +239,8 @@ spans streams.
232
239
  - Query methods are `static` and declare `ISubject<...>` rather than a concrete
233
240
  subject type.
234
241
  - A direct `GetInstanceById` result is checked for absence before use.
242
+ - A plain read, materialized or passive, is never presented as the guard of a
243
+ write-side rule.
235
244
  - Passive access goes through Chronicle, not a sink collection; consistency,
236
245
  access frequency, and non-materialization requirements justify the choice.
237
246
  - Summary payloads and embedded children are bounded; growing histories have
@@ -134,8 +134,12 @@ public sealed class ReducerAttribute(string id = "", string? eventSequence = def
134
134
  `Cratis.Chronicle.ReadModels.PassiveAttribute` (`[Passive]`) goes on the **read
135
135
  model type** and makes it passive as a whole: no sink, nothing materialized, and
136
136
  the instance is computed on demand when it is read. Reach for it when a
137
- command-side decision needs the model strongly consistent at the moment it is
138
- read.
137
+ command-side read needs the model current at the moment it is read. Passive is
138
+ fresher, not safer: a passive reducer read captures no position and guards nothing,
139
+ and a reducer (or a self-reducing model, since Chronicle 19.58.0) is refused by
140
+ decision reads. For a rule that must hold under concurrent writers use a flat
141
+ projection with a decision read; see
142
+ [choosing how a rule holds](../cratis-chronicle-decision-reads/references/choosing-how-a-rule-holds.md).
139
143
 
140
144
  ## Filtering which events reach the reducer
141
145
 
@@ -88,7 +88,9 @@ before the Unix epoch. A fixed context fixes the timestamp, not random suffixes.
88
88
  - Client-minted customer/order IDs stay inputs. Do not replace them on retry.
89
89
  - Random values supply neither idempotency nor gapless invoice allocation.
90
90
  - An ID is not an authentication token or authorization policy.
91
- - ApiKey is a **secret**, not an event-source ID. `[NotAudited]` withholds command
91
+ - ApiKey is a **secret**, not an event-source ID: event-source IDs are plaintext metadata
92
+ and cannot be encrypted. Use a separate `ApiKeyId` as the identity and keep ApiKey a
93
+ secret value property. `[NotAudited]` withholds command
92
94
  causation values; it does not protect logs, responses or storage. Deliver a
93
95
  credential only over an authorized secure channel and retain its hash, not
94
96
  plaintext. For a retained operational integration secret instead, use
@@ -161,7 +161,8 @@ and [generation strategies](../../cratis-screenplay-toolchain/references/generat
161
161
  Stage emits strategy-specific `IGeneratable<T>.New()` factories over Fundamentals
162
162
  7.24.0 (via the Arc scaffold pin in Stage's `references/rendered-application.md`). v15 generated destinations use explicit
163
163
  `EventsWithConcurrencyScopes` with `BeforeFirst` whole-source scopes; Chronicle
164
- checks atomically at append. Generated rejection specs assert
164
+ checks atomically at append: a batch's scopes are checked once against the state before
165
+ the batch, all or nothing, and a storage retry that renumbers the append checks them again. Generated rejection specs assert
165
166
  `ValidationResultReason.ConcurrencyViolation`, not Arc's message text. This is
166
167
  Stage's explicit realization, not a claim that Arc #3129 is delivered.
167
168
  Time-based factories use wall clock, not command-receipt timestamps.
@@ -19,7 +19,8 @@ recovery describes that strategy shape, not equivalent clock/tenant semantics.
19
19
  Context-member/rule recovery stays in code (Screenplay#616 phase 3).
20
20
 
21
21
  The shop's ApiKey remains a **secret**. In .NET its factory is `Bytes(32)` and its
22
- concept is `[NotAudited]`; executable secret generation is **not released in
22
+ concept is `[NotAudited]`. It is never an identifier (event-source IDs are plaintext
23
+ metadata); a separate `ApiKeyId` identifies the key. Executable secret generation is **not released in
23
24
  Screenplay** (phase 4). The declaration below preserves classification without
24
25
  adding `generate bytes 32` or a generated command property. No API-key issuance
25
26
  behavior is claimed; retain it as an explicit gap/owning implementation contract.
@@ -109,7 +109,8 @@ option, mark it `ASSUMED` in the slice or module `documentation` and in the sess
109
109
  - Forbidden: a caller-supplied copy of state in `require`, a boolean attestation input
110
110
  (`confirmsX == true`) standing in for a rule, and rules hidden in `handler` or
111
111
  implementation-hint prose. An unguarded materialized read is unsafe for a protected
112
- decision; that is not "read models never drive decisions".
112
+ decision; that is not "read models never drive decisions". See
113
+ `../cratis-chronicle-decision-reads/references/choosing-how-a-rule-holds.md`.
113
114
  3. **Play the races and retries.** For each enforced or recorded rule write the concurrent case
114
115
  (two commands at once), the retry case (same request again after a lost reply) and the
115
116
  duplicate case (same intent, new id). State the outcome and which construct produces it.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cratis/pi",
3
- "version": "7.47.0",
3
+ "version": "7.48.0",
4
4
  "description": "Configuration-aware Cratis AI integration for Pi",
5
5
  "type": "module",
6
6
  "files": [