@cratis/pi 7.192.0 → 7.193.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.
@@ -104,6 +104,11 @@ Read the **cratis-arc-elixir** and **cratis-chronicle-client-elixir** skills bef
104
104
  - **Third parties are integrations behind a behaviour**, with an in-memory stand-in for specs; only
105
105
  reactors write to them.
106
106
 
107
+ Specs follow [specs.elixir.md](./specs.elixir.instructions.md): scripts in `for_*`/`when_*` folders beside the code, no
108
+ `_test` suffix, `should` assertions. Build read models with a projection, not a reducer, unless a projection
109
+ cannot express the transition, and enforce uniqueness with a Chronicle constraint, not a read before the append
110
+ (see the **cratis-arc-elixir** and **cratis-chronicle-client-elixir** skills).
111
+
107
112
  Every `.ex` and `.exs` source file starts with:
108
113
 
109
114
  ```elixir
@@ -0,0 +1,138 @@
1
+ ---
2
+ applyTo: "**/for_*/**/*.exs, **/when_*/**/*.exs"
3
+ paths:
4
+ - "**/for_*/**/*.exs"
5
+ - "**/when_*/**/*.exs"
6
+ ---
7
+ <!-- cratis-ai: generated Copilot instructions. Do not edit; rules/ is the source. -->
8
+
9
+ <!-- Copyright (c) Cratis. All rights reserved. -->
10
+ <!-- Licensed under the MIT license. See LICENSE file in the project root for full license information. -->
11
+
12
+ # How to Write Elixir Specs
13
+
14
+ Extends the base [specs.md](./specs.instructions.md) with Elixir conventions. The philosophy is the same: a spec
15
+ describes a **behavior** in the language of the domain, the folder tree reads as a sentence, and one
16
+ scenario lives in one file. ExUnit is the runner; nothing else is needed.
17
+
18
+ ## Specs are scripts beside the code, never in a release
19
+
20
+ A spec is an `.exs` file (a script). `mix compile` and `mix release` only ever build `.ex` files, so a spec
21
+ beside the code it specifies is **never part of a release**, the same outcome the C# build gets by removing
22
+ `when_*` files from Release builds and the TypeScript build gets by not importing them. Do not rename specs
23
+ to `.ex`. Shared helpers that must be compiled (a `Case` module) live in `test/support/*.ex`, which only the
24
+ `:test` environment adds to `elixirc_paths`.
25
+
26
+ **No `_test` suffix.** ExUnit's default pattern is `*_test.exs`, but the folder already says it is a spec
27
+ (`for_*`/`when_*`), exactly as in C# and TypeScript. Point `mix test` at the folders instead:
28
+
29
+ ```elixir
30
+ # mix.exs: project/0
31
+ elixirc_paths: elixirc_paths(Mix.env()),
32
+ test_paths: ["lib"],
33
+ # A spec is any script in a `for_*` folder; `given/` holds shared contexts, which specs load themselves.
34
+ test_load_filters: [&(String.contains?(&1, "/for_") and not String.contains?(&1, "/given/"))],
35
+
36
+ defp elixirc_paths(:test), do: ["lib", "test/support"]
37
+ defp elixirc_paths(_env), do: ["lib"]
38
+ ```
39
+
40
+ `test_load_filters` **replaces** the default `test_pattern`; do not set both. `test_helper.exs` (`ExUnit.start()`)
41
+ stays beside the specs, in the first of `test_paths`. Let `mix format` cover the scripts
42
+ (`inputs: ["{config,lib,test}/**/*.{ex,exs}"]`).
43
+
44
+ ## Folder and file structure
45
+
46
+ ```
47
+ <feature or slice>/
48
+ └── for_<unit>/ ← "For the unit..."
49
+ ├── given/
50
+ │ └── a_<context>.exs ← shared context, loaded by the specs that need it (not a spec)
51
+ ├── when_<behavior>/ ← "...when doing this..." (a folder when there are several outcomes)
52
+ │ ├── and_<condition>.exs ← one scenario per file
53
+ │ ├── with_<data>.exs
54
+ │ └── without_<requirement>.exs
55
+ └── when_<simple_behavior>.exs ← a single file for a single scenario
56
+ ```
57
+
58
+ The unit is the module, command, read model, component or function under specification:
59
+ `for_rotate_secret`, `for_data_table`, `for_patterns`. Use the prepositions and the rules of
60
+ [specs.md](./specs.instructions.md) (`and_`, `with_`, `without_`, `having_`, `given_`), including: **never put `when` in a
61
+ file or non-`when_` folder name** (`and_ory_fails.exs`, not `when_ory_fails.exs`, under `when_adding/`).
62
+
63
+ Folder names are `snake_case`. A spec's **module name mirrors its path** below the application's namespace,
64
+ `PascalCase`, so it can never clash with the module it specifies and is never named `...Test`:
65
+
66
+ ```elixir
67
+ # lib/access/credentials/adding_credentials/for_add_credential/when_adding/with_selected_vessels.exs
68
+ defmodule Prism.Access.Credentials.AddingCredentials.ForAddCredential.WhenAdding.WithSelectedVessels do
69
+ use ExUnit.Case, async: true
70
+ ```
71
+
72
+ ## One scenario, several `should` assertions
73
+
74
+ The `setup` establishes the context and performs the behavior once per assertion (ExUnit runs `setup` for each
75
+ `test`); each `test` states one expectation and starts with **`should`**, so the file reads as a sentence:
76
+
77
+ ```elixir
78
+ defmodule Prism.Access.ApiCredentials.ForState.WhenDerivingTheStatus do
79
+ use ExUnit.Case, async: true
80
+
81
+ alias Prism.Access.ApiCredentials.State
82
+
83
+ test "should be active by default" do
84
+ assert State.status(%State{id: "c", exists?: true}, ~U[2026-03-01 12:00:00Z]) == :active
85
+ end
86
+ end
87
+ ```
88
+
89
+ - `test "should refuse a duplicate label"`, not `test "a duplicate label is refused"` and not
90
+ `test "refuses..."`. Name the expected result, not the call.
91
+ - A file with several unrelated scenarios is several files. Split `describe` blocks into
92
+ `when_<behavior>/<preposition>_<condition>.exs` files; do not use `describe` to group scenarios.
93
+ - Assert on the **contract**: the result, the events appended, what a collaborator was asked to do. Do not
94
+ assert on internals, and do not spec logging or trivial delegation.
95
+ - `doctest Module` belongs in its own spec (`when_building/with_the_documented_examples.exs`).
96
+
97
+ ## Shared context: `given/`
98
+
99
+ Contexts that several specs share (a table of people, a started kernel) go in `for_<unit>/given/<name>.exs`
100
+ as a module, and a spec loads it by relative path. The filter above keeps `given/` out of the specs ExUnit
101
+ runs, so it is loaded once, by the spec that needs it:
102
+
103
+ ```elixir
104
+ Code.require_file("../given/people.exs", __DIR__)
105
+
106
+ defmodule Prism.Access.Components.DataTable.ForDataTable.WhenFiltering.WithASingleFilter do
107
+ use ExUnit.Case, async: true
108
+
109
+ alias Prism.Access.Components.DataTable.ForDataTable.Given.People
110
+ import People, only: [names: 1, table: 1]
111
+ ...
112
+ ```
113
+
114
+ A context that needs a compiled module (a `Case` with `setup`, an in-memory stand-in) is a `test/support/*.ex`
115
+ module that the spec `use`s, like `Prism.Access.Case` in a Cratis application: it starts the in-memory
116
+ Chronicle kernel and gives `exec/3`, `facts/2` and the stand-ins.
117
+
118
+ ## What to specify, by kind
119
+
120
+ | Kind | Run it through | Assert |
121
+ |---|---|---|
122
+ | Command | the real pipeline (`Cratis.Arc.Test.execute/3`, in-memory Chronicle) | result, events appended (types and data), what the integration was asked |
123
+ | Reactor / automation | the real reactor against the in-memory kernel | the command it ran, the event that records the outcome |
124
+ | Read model, projection | the events folded (`State`, projection function) | the document, never `Process.sleep` |
125
+ | Pure function | a direct call | return values; one file per rule |
126
+ | LiveView / component | `Phoenix.LiveViewTest` (`render_component/2`, `live/2`) | the markup that matters: structure, state classes, the events wired, not every attribute |
127
+
128
+ The in-memory Chronicle kernel does not run read-model queries; specs that need them use the development kernel
129
+ and say so in the file.
130
+
131
+ ## Pitfalls
132
+
133
+ - A spec outside a `for_*` folder is **silently not run**. After adding the filter, check the count: `mix test`
134
+ must report at least what it did before.
135
+ - Do not name a spec `*_test.exs` while the filter is on: it is picked up only when it sits in a `for_*` folder.
136
+ - `Code.require_file` paths are relative to the spec (`__DIR__`), so moving a spec means fixing the path.
137
+ - Specs are scripts: aliases and imports go inside the module; the first line outside it is only for
138
+ `Code.require_file`.
@@ -150,4 +150,5 @@ This file is the shared base. For the concrete patterns:
150
150
  - [specs.csharp.md](./specs.csharp.instructions.md) — C#: the universal `Cratis.Specifications` base + NSubstitute (both profiles; this is what framework/library specs use).
151
151
  - [specs.scenarios.csharp.md](./specs.scenarios.csharp.instructions.md) — C# **application** profile: the in-process scenario family (`CommandScenario`, `EventScenario`, `ReadModelScenario`, `ReactorScenario`) + out-of-process Chronicle integration.
152
152
  - [specs.typescript.md](./specs.typescript.instructions.md) — TypeScript framework-package specs (`given()` helper).
153
+ - [specs.elixir.md](./specs.elixir.instructions.md) — Elixir: `.exs` scripts in `for_*`/`when_*` folders with no `_test` suffix (never in a release), `should` assertions, `given/` contexts.
153
154
  - [frontend-testing.md](./frontend-testing.instructions.md) — application frontend specs (view models, React components).
@@ -92,7 +92,7 @@ The command carries input from the caller. `Handle()` is defined directly on the
92
92
  | Command-input / cross-field / pre-handler rule (incl. injected read-model/service/identity checks) | `CommandValidator<TCommand>` with `RuleFor(...)` |
93
93
  | 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 |
94
94
  | 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 |
95
- | Uniqueness | Chronicle `[Unique]` / `IConstraint` (race-safe) — not a read-model pre-check |
95
+ | Uniqueness (a value used once, a fact once per stream) | Chronicle `[Unique]` / `IConstraint` (race-safe) — **never** a read-model pre-check or a state read in `Provide()`/`Handle()`, which races and says nothing the kernel enforces. Elixir: `unique/2`, `unique_event_type/1` or a standalone `Constraint` module |
96
96
  | Genuinely exceptional failure (bug, missing infra) | `throw` a domain exception |
97
97
 
98
98
  **Do not throw for normal business rejection.** A thrown exception (from `Provide()` or `Handle()`) surfaces as an exception/HTTP 500, *not* a validation result. Recoverable, user-facing rejections are validation: `ValidationResult.Error(...)` via a validator or `Result<,>`. (For step-by-step business-rule placement, invoke the **cratis-arc-command-validation** skill.)
@@ -296,6 +296,10 @@ public record Author(AuthorId Id, AuthorName Name)
296
296
  }
297
297
  ```
298
298
 
299
+ **[convention] Projections over reducers.** A read model is built by a **projection** by default (model-bound attributes, then fluent `IProjectionFor<T>`; in Elixir the `Cratis.Chronicle.Projections` DSL). Reach for a **reducer** only when a projection cannot express the transition (branching on prior state, calculations, guards) and say why in the read model's doc. A projection is declarative, so the kernel can replay, optimize and diagram it; a reducer is code you own and run.
300
+
301
+ **[convention] A read model owns its artifacts.** The read model, its projection (or, by exception, reducer) and its queries live together, in the slice folder of the read model and in one file named for it, not in files named for their technical function (`Queries`, `Reducer`, `Projection`). In Elixir that is one file with the read model's module containing its projection/reducer and its queries as nested modules, the way a command and its events share a file.
302
+
299
303
  **[convention] No default values on `[ReadModel]` constructor parameters** — omit `= null`, `= default`, `= default!`, `= 0`, `= false`, `= ""`, `= []`. Chronicle writes the projected value on the first event, so a sentinel default is never correct and hides missing projection wiring. The only permitted defaults are enum variants that represent an explicit initial state and `[SetValue<T>]`-driven `bool` flags. Use `T?` for data genuinely absent before the relevant event fires.
300
304
 
301
305
  **[convention] Read-model boundaries & naming.** Read models are shaped for consumers and command policies, not CRUD-style aggregate DTOs. Split one when it starts mixing unrelated lifecycles — the test is coupling (state that changes for different reasons), not size. The event log is already the canonical history/audit trail, so name a model `AuditLog`/`ActivityLog` only when it genuinely is an audit surface; for curated UI projections prefer names like `Timeline`, `WorkSurface`, `Summary`, `Detail`, or `Policy`. (This is "specialization over reuse" applied to read models.)
@@ -103,6 +103,11 @@ Read the **cratis-arc-elixir** and **cratis-chronicle-client-elixir** skills bef
103
103
  - **Third parties are integrations behind a behaviour**, with an in-memory stand-in for specs; only
104
104
  reactors write to them.
105
105
 
106
+ Specs follow [specs.elixir.md](./specs.elixir.md): scripts in `for_*`/`when_*` folders beside the code, no
107
+ `_test` suffix, `should` assertions. Build read models with a projection, not a reducer, unless a projection
108
+ cannot express the transition, and enforce uniqueness with a Chronicle constraint, not a read before the append
109
+ (see the **cratis-arc-elixir** and **cratis-chronicle-client-elixir** skills).
110
+
106
111
  Every `.ex` and `.exs` source file starts with:
107
112
 
108
113
  ```elixir
@@ -134,7 +134,7 @@ Verify claims with build, spec, lint or observed-behavior signals, not confidenc
134
134
  | Go | `go.md`; framework: `go-engineering.md`; product APIs: `cratis-chronicle-client-go`, `cratis-arc-go` and `cratis-fundamentals-concept-go` |
135
135
  | React + Arc + Cratis Components + MVVM + dialogs | `react.md`, `components.md`, `dialogs.md` |
136
136
  | Frontend engineering quality & testing | `frontend-quality.md`, `frontend-testing.md`, `storybook.md` |
137
- | Spec patterns — universal `Specification` base (both profiles) | `specs.md`, `specs.csharp.md`, `specs.typescript.md` |
137
+ | Spec patterns — universal `Specification` base (both profiles) | `specs.md`, `specs.csharp.md`, `specs.typescript.md`, `specs.elixir.md` |
138
138
  | Build and spec-run speed: parallel-safe specs, no per-spec startup, cheap analyzers | `fast-feedback.md` |
139
139
  | Spec patterns — the four `*Scenario` helpers (application only) | `specs.scenarios.csharp.md` |
140
140
  | Strongly-typed values (`ConceptAs<T>`, `EventSourceId<T>`); shared term definitions (event, projection, reducer, reactor, observer, DCB, …) | `concepts.md`; `glossary.md` |
@@ -0,0 +1,137 @@
1
+ ---
2
+ applyTo: "**/for_*/**/*.exs, **/when_*/**/*.exs"
3
+ paths:
4
+ - "**/for_*/**/*.exs"
5
+ - "**/when_*/**/*.exs"
6
+ ---
7
+
8
+ <!-- Copyright (c) Cratis. All rights reserved. -->
9
+ <!-- Licensed under the MIT license. See LICENSE file in the project root for full license information. -->
10
+
11
+ # How to Write Elixir Specs
12
+
13
+ Extends the base [specs.md](./specs.md) with Elixir conventions. The philosophy is the same: a spec
14
+ describes a **behavior** in the language of the domain, the folder tree reads as a sentence, and one
15
+ scenario lives in one file. ExUnit is the runner; nothing else is needed.
16
+
17
+ ## Specs are scripts beside the code, never in a release
18
+
19
+ A spec is an `.exs` file (a script). `mix compile` and `mix release` only ever build `.ex` files, so a spec
20
+ beside the code it specifies is **never part of a release**, the same outcome the C# build gets by removing
21
+ `when_*` files from Release builds and the TypeScript build gets by not importing them. Do not rename specs
22
+ to `.ex`. Shared helpers that must be compiled (a `Case` module) live in `test/support/*.ex`, which only the
23
+ `:test` environment adds to `elixirc_paths`.
24
+
25
+ **No `_test` suffix.** ExUnit's default pattern is `*_test.exs`, but the folder already says it is a spec
26
+ (`for_*`/`when_*`), exactly as in C# and TypeScript. Point `mix test` at the folders instead:
27
+
28
+ ```elixir
29
+ # mix.exs: project/0
30
+ elixirc_paths: elixirc_paths(Mix.env()),
31
+ test_paths: ["lib"],
32
+ # A spec is any script in a `for_*` folder; `given/` holds shared contexts, which specs load themselves.
33
+ test_load_filters: [&(String.contains?(&1, "/for_") and not String.contains?(&1, "/given/"))],
34
+
35
+ defp elixirc_paths(:test), do: ["lib", "test/support"]
36
+ defp elixirc_paths(_env), do: ["lib"]
37
+ ```
38
+
39
+ `test_load_filters` **replaces** the default `test_pattern`; do not set both. `test_helper.exs` (`ExUnit.start()`)
40
+ stays beside the specs, in the first of `test_paths`. Let `mix format` cover the scripts
41
+ (`inputs: ["{config,lib,test}/**/*.{ex,exs}"]`).
42
+
43
+ ## Folder and file structure
44
+
45
+ ```
46
+ <feature or slice>/
47
+ └── for_<unit>/ ← "For the unit..."
48
+ ├── given/
49
+ │ └── a_<context>.exs ← shared context, loaded by the specs that need it (not a spec)
50
+ ├── when_<behavior>/ ← "...when doing this..." (a folder when there are several outcomes)
51
+ │ ├── and_<condition>.exs ← one scenario per file
52
+ │ ├── with_<data>.exs
53
+ │ └── without_<requirement>.exs
54
+ └── when_<simple_behavior>.exs ← a single file for a single scenario
55
+ ```
56
+
57
+ The unit is the module, command, read model, component or function under specification:
58
+ `for_rotate_secret`, `for_data_table`, `for_patterns`. Use the prepositions and the rules of
59
+ [specs.md](./specs.md) (`and_`, `with_`, `without_`, `having_`, `given_`), including: **never put `when` in a
60
+ file or non-`when_` folder name** (`and_ory_fails.exs`, not `when_ory_fails.exs`, under `when_adding/`).
61
+
62
+ Folder names are `snake_case`. A spec's **module name mirrors its path** below the application's namespace,
63
+ `PascalCase`, so it can never clash with the module it specifies and is never named `...Test`:
64
+
65
+ ```elixir
66
+ # lib/access/credentials/adding_credentials/for_add_credential/when_adding/with_selected_vessels.exs
67
+ defmodule Prism.Access.Credentials.AddingCredentials.ForAddCredential.WhenAdding.WithSelectedVessels do
68
+ use ExUnit.Case, async: true
69
+ ```
70
+
71
+ ## One scenario, several `should` assertions
72
+
73
+ The `setup` establishes the context and performs the behavior once per assertion (ExUnit runs `setup` for each
74
+ `test`); each `test` states one expectation and starts with **`should`**, so the file reads as a sentence:
75
+
76
+ ```elixir
77
+ defmodule Prism.Access.ApiCredentials.ForState.WhenDerivingTheStatus do
78
+ use ExUnit.Case, async: true
79
+
80
+ alias Prism.Access.ApiCredentials.State
81
+
82
+ test "should be active by default" do
83
+ assert State.status(%State{id: "c", exists?: true}, ~U[2026-03-01 12:00:00Z]) == :active
84
+ end
85
+ end
86
+ ```
87
+
88
+ - `test "should refuse a duplicate label"`, not `test "a duplicate label is refused"` and not
89
+ `test "refuses..."`. Name the expected result, not the call.
90
+ - A file with several unrelated scenarios is several files. Split `describe` blocks into
91
+ `when_<behavior>/<preposition>_<condition>.exs` files; do not use `describe` to group scenarios.
92
+ - Assert on the **contract**: the result, the events appended, what a collaborator was asked to do. Do not
93
+ assert on internals, and do not spec logging or trivial delegation.
94
+ - `doctest Module` belongs in its own spec (`when_building/with_the_documented_examples.exs`).
95
+
96
+ ## Shared context: `given/`
97
+
98
+ Contexts that several specs share (a table of people, a started kernel) go in `for_<unit>/given/<name>.exs`
99
+ as a module, and a spec loads it by relative path. The filter above keeps `given/` out of the specs ExUnit
100
+ runs, so it is loaded once, by the spec that needs it:
101
+
102
+ ```elixir
103
+ Code.require_file("../given/people.exs", __DIR__)
104
+
105
+ defmodule Prism.Access.Components.DataTable.ForDataTable.WhenFiltering.WithASingleFilter do
106
+ use ExUnit.Case, async: true
107
+
108
+ alias Prism.Access.Components.DataTable.ForDataTable.Given.People
109
+ import People, only: [names: 1, table: 1]
110
+ ...
111
+ ```
112
+
113
+ A context that needs a compiled module (a `Case` with `setup`, an in-memory stand-in) is a `test/support/*.ex`
114
+ module that the spec `use`s, like `Prism.Access.Case` in a Cratis application: it starts the in-memory
115
+ Chronicle kernel and gives `exec/3`, `facts/2` and the stand-ins.
116
+
117
+ ## What to specify, by kind
118
+
119
+ | Kind | Run it through | Assert |
120
+ |---|---|---|
121
+ | Command | the real pipeline (`Cratis.Arc.Test.execute/3`, in-memory Chronicle) | result, events appended (types and data), what the integration was asked |
122
+ | Reactor / automation | the real reactor against the in-memory kernel | the command it ran, the event that records the outcome |
123
+ | Read model, projection | the events folded (`State`, projection function) | the document, never `Process.sleep` |
124
+ | Pure function | a direct call | return values; one file per rule |
125
+ | LiveView / component | `Phoenix.LiveViewTest` (`render_component/2`, `live/2`) | the markup that matters: structure, state classes, the events wired, not every attribute |
126
+
127
+ The in-memory Chronicle kernel does not run read-model queries; specs that need them use the development kernel
128
+ and say so in the file.
129
+
130
+ ## Pitfalls
131
+
132
+ - A spec outside a `for_*` folder is **silently not run**. After adding the filter, check the count: `mix test`
133
+ must report at least what it did before.
134
+ - Do not name a spec `*_test.exs` while the filter is on: it is picked up only when it sits in a `for_*` folder.
135
+ - `Code.require_file` paths are relative to the spec (`__DIR__`), so moving a spec means fixing the path.
136
+ - Specs are scripts: aliases and imports go inside the module; the first line outside it is only for
137
+ `Code.require_file`.
@@ -149,4 +149,5 @@ This file is the shared base. For the concrete patterns:
149
149
  - [specs.csharp.md](./specs.csharp.md) — C#: the universal `Cratis.Specifications` base + NSubstitute (both profiles; this is what framework/library specs use).
150
150
  - [specs.scenarios.csharp.md](./specs.scenarios.csharp.md) — C# **application** profile: the in-process scenario family (`CommandScenario`, `EventScenario`, `ReadModelScenario`, `ReactorScenario`) + out-of-process Chronicle integration.
151
151
  - [specs.typescript.md](./specs.typescript.md) — TypeScript framework-package specs (`given()` helper).
152
+ - [specs.elixir.md](./specs.elixir.md) — Elixir: `.exs` scripts in `for_*`/`when_*` folders with no `_test` suffix (never in a release), `should` assertions, `given/` contexts.
152
153
  - [frontend-testing.md](./frontend-testing.md) — application frontend specs (view models, React components).
@@ -91,7 +91,7 @@ The command carries input from the caller. `Handle()` is defined directly on the
91
91
  | Command-input / cross-field / pre-handler rule (incl. injected read-model/service/identity checks) | `CommandValidator<TCommand>` with `RuleFor(...)` |
92
92
  | 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 |
93
93
  | 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 |
94
- | Uniqueness | Chronicle `[Unique]` / `IConstraint` (race-safe) — not a read-model pre-check |
94
+ | Uniqueness (a value used once, a fact once per stream) | Chronicle `[Unique]` / `IConstraint` (race-safe) — **never** a read-model pre-check or a state read in `Provide()`/`Handle()`, which races and says nothing the kernel enforces. Elixir: `unique/2`, `unique_event_type/1` or a standalone `Constraint` module |
95
95
  | Genuinely exceptional failure (bug, missing infra) | `throw` a domain exception |
96
96
 
97
97
  **Do not throw for normal business rejection.** A thrown exception (from `Provide()` or `Handle()`) surfaces as an exception/HTTP 500, *not* a validation result. Recoverable, user-facing rejections are validation: `ValidationResult.Error(...)` via a validator or `Result<,>`. (For step-by-step business-rule placement, invoke the **cratis-arc-command-validation** skill.)
@@ -295,6 +295,10 @@ public record Author(AuthorId Id, AuthorName Name)
295
295
  }
296
296
  ```
297
297
 
298
+ **[convention] Projections over reducers.** A read model is built by a **projection** by default (model-bound attributes, then fluent `IProjectionFor<T>`; in Elixir the `Cratis.Chronicle.Projections` DSL). Reach for a **reducer** only when a projection cannot express the transition (branching on prior state, calculations, guards) and say why in the read model's doc. A projection is declarative, so the kernel can replay, optimize and diagram it; a reducer is code you own and run.
299
+
300
+ **[convention] A read model owns its artifacts.** The read model, its projection (or, by exception, reducer) and its queries live together, in the slice folder of the read model and in one file named for it, not in files named for their technical function (`Queries`, `Reducer`, `Projection`). In Elixir that is one file with the read model's module containing its projection/reducer and its queries as nested modules, the way a command and its events share a file.
301
+
298
302
  **[convention] No default values on `[ReadModel]` constructor parameters** — omit `= null`, `= default`, `= default!`, `= 0`, `= false`, `= ""`, `= []`. Chronicle writes the projected value on the first event, so a sentinel default is never correct and hides missing projection wiring. The only permitted defaults are enum variants that represent an explicit initial state and `[SetValue<T>]`-driven `bool` flags. Use `T?` for data genuinely absent before the relevant event fires.
299
303
 
300
304
  **[convention] Read-model boundaries & naming.** Read models are shaped for consumers and command policies, not CRUD-style aggregate DTOs. Split one when it starts mixing unrelated lifecycles — the test is coupling (state that changes for different reasons), not size. The event log is already the canonical history/audit trail, so name a model `AuditLog`/`ActivityLog` only when it genuinely is an audit surface; for curated UI projections prefer names like `Timeline`, `WorkSurface`, `Summary`, `Detail`, or `Policy`. (This is "specialization over reuse" applied to read models.)
@@ -24,6 +24,26 @@ once and is what Chronicle records.
24
24
 
25
25
  Each callback runs only if the previous steps passed.
26
26
 
27
+ ## Where each decision lives
28
+
29
+ A command's `handle/2` decides what to append from what `provide/2` loaded. Pick the mechanism by what the
30
+ decision is:
31
+
32
+ | Decision | Use |
33
+ | --- | --- |
34
+ | Shape or range of an input | `field` options (`required:`, `max_length:`), then a validator |
35
+ | State of the stream a rule needs (does it exist, is it suspended) | `provide/2` loading the folded state; `handle/2` refuses with a validation result |
36
+ | **Uniqueness**: a value used once, or a fact (an event type) once per stream | **A Chronicle constraint**, declared on the event type (`unique/2`, `unique_event_type/1`) or in a standalone `Cratis.Chronicle.Events.Constraint` module. The kernel checks it at append time, so it holds under concurrency. |
37
+ | A rule over many streams or a count (a tenant limit) | A read model or the integration, and accept that it can race; say so in the command's doc |
38
+ | An exceptional failure (a bug, missing infrastructure) | raise |
39
+
40
+ **Do not check uniqueness by reading first.** A `provide/2` that loads the stream or a read model to see "is
41
+ this taken" (`{:ok, %{exists?: true}} -> refuse(...)`) is a race: two commands both see it free, and both
42
+ append. Declare the constraint and let the append refuse. Arc turns the violation into a validation result with
43
+ reason `constraintViolation` (the constraint name in `reasonDetail`), so a client already handles it; give the
44
+ constraint a `:message` so the refusal reads well. Release a held value with `remove_constraint/1,2` on the event
45
+ that frees it. Read the Chronicle skill's `references/constraints.md` for the options.
46
+
27
47
  ## When Chronicle refuses
28
48
 
29
49
  A constraint or concurrency rejection never raises. It is a validation result with reason
@@ -3,6 +3,13 @@
3
3
 
4
4
  # Proxies and vertical slices
5
5
 
6
+ ## Contents
7
+
8
+ - Vertical slices
9
+ - Group slices into sub-features, and keep an integration beside what it serves
10
+ - A read model owns its artifacts
11
+ - Name things by their ids
12
+
6
13
  Proxy generation is opt-in. Add the compiler and every `mix compile` regenerates the
7
14
  TypeScript for commands and queries:
8
15
 
@@ -46,6 +53,28 @@ The folder is the namespace: `Prism.Access.ApiCredentials.Secrets.RotatingSecret
46
53
  sub-feature as a feature of its own, so the grouping is what readers and tools see. Keep
47
54
  `segments_to_skip` equal to the segments above the module.
48
55
 
56
+ ### A read model owns its artifacts
57
+
58
+ A view slice has one file, named for its read model, holding everything the read model needs:
59
+
60
+ ```text
61
+ viewing/listing/
62
+ credential_listing.ex the read model, its projection (or reducer) and its queries
63
+ page.ex, page.html.heex the page that shows it
64
+ for_credential_listing/ its specs
65
+ ```
66
+
67
+ Inside, the read model's module nests what it needs (`Credential`, then its projection, then its `Queries`),
68
+ the way a command shares a file with its events. Do **not** make files or folders named for a technical function
69
+ (`queries.ex`, `reducer.ex`, `projection.ex`, `read_models/`): the folder is the slice and the file is the read
70
+ model, so a reader finds the whole view in one place and the event model draws one box.
71
+
72
+ **Prefer a projection over a reducer.** Build the read model with the `Cratis.Chronicle.Projections` DSL
73
+ (`from/2`, `join/2`, `children/2,3`, counters). Use a reducer (`Cratis.Chronicle.Reducers.Reducer`) only when a
74
+ projection cannot express the transition (branching on prior state, calculations, guards over the previous
75
+ document) and say why in the read model's `@moduledoc`. A reducer is code you own and run; a projection is
76
+ declarative and the kernel can replay and diagram it.
77
+
49
78
  ### Name things by their ids
50
79
 
51
80
  A command is `use Cratis.Arc.Command, id: "rotate-secret"`, an event type has an `id:`, a reactor has an
@@ -252,6 +252,16 @@ A standalone projection is `use Cratis.Chronicle.Projections.Projection, model:
252
252
  `reduce(event, model_or_nil, context) :: struct()`. **Reducers run in your
253
253
  process**, so the reduction is Elixir code you own.
254
254
 
255
+ **Prefer a projection over a reducer.** Write a reducer only when a projection cannot express the transition
256
+ (branching on prior state, calculations, guards), and say why in its `@moduledoc`. Keep the read model, its
257
+ projection or reducer and its queries together in one file named for the read model; do not name files for
258
+ their technical function (`reducer.ex`, `queries.ex`).
259
+
260
+ **Uniqueness is a constraint, not a read.** To say "this value is used once" or "this event happens once per
261
+ stream", declare `unique/2` or `unique_event_type/1` (or a standalone constraint module) and let the append
262
+ refuse; do not load the stream or a read model first to look. A read-then-append check races. See
263
+ [references/constraints.md](references/constraints.md).
264
+
255
265
  #### Variants — mutually exclusive read models for one entity's lifecycle
256
266
 
257
267
  Requires `cratis_chronicle` `3.4.0` or later. `variant_of/2` requires `:key`; a variant with no `enters_on` raises `Cratis.Chronicle.Projections.VariantMustDeclareEntersOnEvent` at registration.
@@ -107,8 +107,11 @@ For application code, work down this ladder:
107
107
  2. **Fluent `IProjectionFor<T>`** when the definition needs structure or an
108
108
  attribute-free contract. Counters, joins, children and composite keys remain
109
109
  projection features; fluent lambdas are not arbitrary per-event code.
110
- 3. **Reducer code** when branching on prior state, calculations or guards read
111
- better as state transitions. A reducer is a normal choice, not a last resort.
110
+ 3. **Reducer code** only when a projection cannot express the transition:
111
+ branching on prior state, calculations or guards that mappings, counters,
112
+ joins and children cannot say. **Prefer a projection over a reducer**; a
113
+ reducer needs a reason you can name, and it is the exception, not an equal
114
+ choice.
112
115
  For new .NET code default to a **self-reducing model**: public static
113
116
  `Reduce(TEvent @event, TSelf? current[, EventContext context])` on the model,
114
117
  returning `TSelf`/`TSelf?` or `Task` of it. No marker or model activation.
@@ -7,10 +7,10 @@ license: MIT
7
7
  # Chronicle reducers
8
8
 
9
9
  A reducer builds a read model as "current state plus event produces next state",
10
- with real C# control flow. Start with model-bound attributes, use fluent
11
- `IProjectionFor<T>` when mappings need structure, and choose a reducer when
12
- branching on prior state, calculations or guards read better as code. A reducer
13
- is a normal choice, not a last resort. For the application-code ladder and PDL's
10
+ with real C# control flow. **We prefer projections over reducers.** Start with
11
+ model-bound attributes, use fluent `IProjectionFor<T>` when mappings need
12
+ structure, and choose a reducer only when a projection cannot express the
13
+ transition (branching on prior state, calculations or guards). For the application-code ladder and PDL's
14
14
  outside-code role, read [choosing a style](../cratis-chronicle-read-model/SKILL.md#step-3--choose-a-projection-or-a-reducer).
15
15
 
16
16
  Requires Chronicle 19.58.0 for self-reducing read models.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cratis/pi",
3
- "version": "7.192.0",
3
+ "version": "7.193.0",
4
4
  "description": "Configuration-aware Cratis AI integration for Pi",
5
5
  "type": "module",
6
6
  "files": [