@cratis/pi 7.175.0 → 7.176.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (24) hide show
  1. package/package/corpus/agents/spec-writer.md +3 -3
  2. package/package/corpus/harnesses/copilot/instructions/specs.csharp.instructions.md +1 -1
  3. package/package/corpus/harnesses/copilot/instructions/specs.scenarios.csharp.instructions.md +5 -5
  4. package/package/corpus/harnesses/pi/agents/spec-writer.md +3 -3
  5. package/package/corpus/rules/specs.csharp.md +1 -1
  6. package/package/corpus/rules/specs.scenarios.csharp.md +5 -5
  7. package/package/corpus/skills/cratis-application-slice-specifications/SKILL.md +16 -13
  8. package/package/corpus/skills/cratis-application-slice-specifications/references/query-and-decision-scenarios.md +73 -26
  9. package/package/corpus/skills/cratis-arc-authentication-authorization-and-identity/SKILL.md +2 -3
  10. package/package/corpus/skills/cratis-arc-authentication-authorization-and-identity/references/authorization.md +2 -1
  11. package/package/corpus/skills/cratis-arc-authentication-authorization-and-identity/references/command-identity.md +194 -0
  12. package/package/corpus/skills/cratis-arc-authentication-authorization-and-identity/references/product-sources.md +26 -0
  13. package/package/corpus/skills/cratis-arc-command/references/decisions-and-routing.md +24 -18
  14. package/package/corpus/skills/cratis-arc-command/references/read-model-injection.md +29 -13
  15. package/package/corpus/skills/cratis-arc-command-operation/SKILL.md +1 -0
  16. package/package/corpus/skills/cratis-arc-command-validation/SKILL.md +10 -5
  17. package/package/corpus/skills/cratis-chronicle-client-dotnet/SKILL.md +1 -0
  18. package/package/corpus/skills/cratis-chronicle-compliance/SKILL.md +1 -0
  19. package/package/corpus/skills/cratis-chronicle-decision-reads/SKILL.md +11 -6
  20. package/package/corpus/skills/cratis-chronicle-decision-reads/references/choosing-how-a-rule-holds.md +24 -18
  21. package/package/corpus/skills/cratis-code-review/SKILL.md +5 -1
  22. package/package/corpus/skills/cratis-specifications-csharp/SKILL.md +12 -11
  23. package/package/corpus/skills/cratis-specifications-csharp/references/running-specs.md +62 -4
  24. package/package.json +1 -1
@@ -46,7 +46,7 @@ Select from these canonical rules in `.cratis/ai/rules/` only after applying the
46
46
 
47
47
  ## C# specs — start with the plain call
48
48
 
49
- Specify pure `Handle()`, validator, reducer and reactor decisions with plain calls and supplied read-model state. Follow `.cratis/ai/rules/specs.scenarios.csharp.md`: add exactly the scenarios its per-artifact decision table obligates (pipeline and authorization, constraints, projection and reducer dispatch, reactor dispatch and routing), not a platform guard matrix. Prove a rule that must hold under concurrent writers, such as the last seat, from supplied read-model state, never with a race scenario. Keep the single cheap assembly-level admission spec for the application's own decision-model shapes. Prefer in-process helpers over out-of-process Chronicle hosts for the applicable behaviors:
49
+ Specify pure `Handle()`, validator, reducer and reactor decisions with plain calls and supplied read-model state. Follow `.cratis/ai/rules/specs.scenarios.csharp.md`: add exactly the scenarios its per-artifact decision table obligates (pipeline and authorization, constraints, projection and reducer dispatch, reactor dispatch and routing), not a platform guard matrix. Prove ordinary concurrent-writer decisions, such as the last seat, from supplied read-model state, not a replay of the platform matrix. Keep one assembly-level admission check for discoverable application shapes; explicit body reads need their own admission check or focused scenario. Typed scenarios select decision reads automatically; `UseDecisionReads()` is obsolete. For an unusual application-owned explicit guard policy, use only a focused regression a plain call cannot prove. See [decision guidance](../skills/cratis-application-slice-specifications/references/query-and-decision-scenarios.md) for the example, limits and advanced hook boundary; never weaken production guards for speed. Prefer in-process helpers over out-of-process Chronicle hosts for the applicable behaviors:
50
50
 
51
51
  | Tool | Use for |
52
52
  |---|---|
@@ -97,7 +97,7 @@ public class and_all_information_is_valid : Specification
97
97
  0. **Every contract specification first** — one spec each, named after it, using the contract's example values. Then add the code-derived cases below that the contract lacks and report them as proposals for the contract (the `.play` model when one covers the slice, otherwise the agreed outline); never present them as contract coverage. A `.play` specification maps to a plain-call spec for a pure decision, with a scenario added only for the pipeline composition it proves (never a simulated race); never edit, skip or delete a spec derived from the contract to make code pass — change the code or return an edit request.
98
98
  1. **Happy path** — succeeds, correct event(s) appended.
99
99
  2. **Each validation failure** — call the validator directly with supplied state; pipeline validation specs assert **both** `ShouldNotBeSuccessful()` and `ShouldHaveValidationErrors()`. Do not assert on message strings by default; assert exact text only when that wording is the specified behavior, and name that behavior in the fact. Violate **only** the rule the spec is named after (build the command valid in every other respect), or a neighbouring rule makes it pass.
100
- 3. **Business-rule violations** — call `Handle()` or the validator directly with the required model state and assert each rejection. Arc/Chronicle specs alone prove platform concurrency, conflict refusal and isolation. The application's only decision-read spec obligation is the single cheap shape-admission spec in `specs.scenarios.csharp.md`; do not repeat guard scenarios per decision.
100
+ 3. **Business-rule violations** — call the validator directly with the required model state and assert each rejection; `Provide()` acquires data and only short-circuits (`ValidationResult`/`AuthorizationResult`) when acquisition yields nothing usable, not for ordinary validation rules. Arc/Chronicle specs own platform concurrency, conflict refusal and isolation. Keep the assembly-level shape-admission check and any explicit-body-read checks above; do not repeat guard scenarios per decision.
101
101
  4. **Constraint violations** — `ShouldHaveConstraintViolationFor(name)` via `EventScenario`.
102
102
  5. **Authorization** — `ShouldNotBeAuthorized()` (an unauthorized result has no validation errors).
103
103
  6. **Repeat execution**, when a reactor invokes the command — the same command twice for the same source; specify whether the second is rejected, a no-op, or appends again.
@@ -163,4 +163,4 @@ Before handing back:
163
163
  - `Status: done | partial | blocked` (meanings in **cratis-application-slice-conformance**).
164
164
  - Specification map: contract specification → spec class; code-derived extras listed separately as proposals.
165
165
  - The contract used (`.play` slice path or agreed outline).
166
- - Spec results (pending or unexecuted specs named honestly), and any open question or model edit request.
166
+ - Spec results (pending or unexecuted specs named honestly), naming the assembly-level admission check, any explicit-body-read checks or focused policy regression, and any open question, harness gap or model edit request.
@@ -18,7 +18,7 @@ Extends the base [specs.md](./specs.instructions.md) (folder structure, naming,
18
18
 
19
19
  ## Frameworks
20
20
 
21
- - [xUnit v3](https://xunit.net/docs/getting-started/v3/migration) is the house default for new and migrated spec projects: reference `Cratis.Specifications.XUnit.v3` **5.0** with `xunit.v3.mtp-off`, `Microsoft.NET.Test.Sdk` and `xunit.runner.visualstudio`, and set `<OutputType>Exe</OutputType>` in the project. The package supplies the `Specification` base, convention lifecycle and `ShouldXxx` assertions; the namespace remains `Cratis.Specifications`. Its `Cratis.Specifications` dependency supplies `Catch` and `SpecificationMethods`.
21
+ - [xUnit v3](https://xunit.net/docs/getting-started/v3/migration) is the house default for new and migrated spec projects **run as the built executable** ([loop](../../../skills/cratis-specifications-csharp/references/running-specs.md#local-loop)); through `dotnet test` it can be slower (reported measurement). Reference `Cratis.Specifications.XUnit.v3` **5.0** with `xunit.v3.mtp-off`, `Microsoft.NET.Test.Sdk` and `xunit.runner.visualstudio`, and set `<OutputType>Exe</OutputType>` in the project. The package supplies the `Specification` base, convention lifecycle and `ShouldXxx` assertions; the namespace remains `Cratis.Specifications`. Its `Cratis.Specifications` dependency supplies `Catch` and `SpecificationMethods`.
22
22
  - 5.0 targets `net10.0` only. A spec project that must stay on net8.0/net9.0 stays on 4.x, and net48 on 3.x. A project that stays on xUnit v2 uses `Cratis.Specifications.XUnit`, with the same base and conventions.
23
23
  - `.NUnit`/`.NUnit5`, `.TUnit` and the experimental `.Runner` are alternatives for repositories already built on them.
24
24
  - [NSubstitute](https://nsubstitute.github.io/) for mocking collaborators.
@@ -15,15 +15,15 @@ Specs are **mandatory for every slice type**, including reactors.
15
15
 
16
16
  ## Start with the plain call; add a scenario where it adds proof
17
17
 
18
- Call pure `Handle()`, validators, reducers and reactor decisions directly with their inputs, including read-model state. Add a scenario only for the wiring the decision table below obligates (pipeline and authorization, constraints, projection and reducer dispatch, reactor dispatch and routing). Do not repeat every decision through the pipeline; name the extra behavior each scenario proves.
18
+ Call pure `Handle()`, validators, reducers and reactor decisions directly with their inputs, including read-model state. Add a scenario for the wiring the decision table below obligates (pipeline and authorization, constraints, projection and reducer dispatch, reactor dispatch and routing). Do not repeat every decision through the pipeline; name the extra behavior each scenario proves.
19
19
 
20
- **Decision table — apply it per artifact, without judgment.** A plain call proves the decision; a scenario is a coverage obligation for the wiring only the framework proves. These are obligations, not quotas: add a scenario for each behavior listed, and none beyond it.
20
+ **Decision table — apply it per artifact, without judgment.** A plain call proves the decision; a scenario is a coverage obligation for the wiring only the framework proves. These are obligations, not quotas: add a scenario for each behavior listed; only the explicit-policy exceptions below add guard scenarios.
21
21
 
22
22
  | Artifact | Plain call (`Specification`) | Scenario obligation |
23
23
  |---|---|---|
24
- | Command with a pure `Handle(…)` | every outcome and rejection branch, with read-model state supplied | the pipeline path once (`CommandScenario`: discovery, DI, event source, appended events), plus a **negative proof for each wiring that can refuse before `Handle`**: authorization denies (`ShouldNotBeAuthorized`), validation rejects, `Provide()` short-circuits |
24
+ | Command with a pure `Handle(…)` | every outcome and rejection branch, with read-model state supplied | the pipeline path once (`CommandScenario`: discovery, DI, event source, appended events), plus a **negative proof for each wiring that can refuse before `Handle`**: authorization denies (`ShouldNotBeAuthorized`), validation rejects, `Provide()` short-circuits when acquisition yields nothing usable |
25
25
  | `Handle` that needs `IEventStore`, `IReadModels` or services | none: do not substitute the store | keep the scenario; when touched, take the read model as a `Handle` parameter and use the row above |
26
- | `CommandValidator`, `ConceptValidator`, `Provide()` logic | each rule, built with its state | the command's pipeline scenarios prove the wiring |
26
+ | `CommandValidator`, `ConceptValidator`; `Provide()` acquisition/derived values | each validator rule, provided value and acquisition-failure result, built with its state | the command's pipeline scenarios prove the wiring |
27
27
  | Constraint (`[Unique]`, `IConstraint`) | none | an `EventScenario` per constraint: the violation and the nearest non-violation |
28
28
  | Projection or read model | none | `ReadModelScenario` against the real engine, covering **each event, key, join, children and removal the projection declares**: one class per read model with one shared event sequence by default; add a class only for a sequence that cannot share it (a removal, another key) |
29
29
  | Reducer | each transition: `Model.Reduce(event, current[, context])` | a `ReadModelScenario` for dispatch, filters and stream routing |
@@ -54,7 +54,7 @@ public class and_the_caller_is_not_a_maintainer : Specification
54
54
 
55
55
  An unauthenticated scenario against an `[Authorize]`/`[Roles]` command is denied before `Handle`; pair it with the happy-path scenario that registers an allowed identity in `_scenario.Services`.
56
56
 
57
- **Application specs supply state, not decision-read infrastructure.** Call `Handle()` or the validator directly with supplied read-model state. Never call `UseDecisionReads`, configure protection modes, seed events solely for infrastructure, or re-prove the platform's concurrency, conflict-refusal or isolation matrix; Arc/Chronicle specs own it. The application's **only decision-read spec obligation** is one cheap assembly-level shape-admission spec: `DecisionReadAdmissions.ShouldAdmitDecisionReadsIn(assembly)` (`Cratis.Arc.Chronicle.Testing.Commands`). It checks the application's own models/projections without executing commands or running Chronicle, not the platform guards. Never simulate competing appends either (`AppendConcurrently` or any hand-built interleaving): concurrency is a framework concern a developer should not think about in tests, and Arc and Chronicle specs prove it. A rule that must hold under races is expressed in production by taking the read model as a `Handle` parameter under `[ReadProtection(On)]`; the spec gives that read model's state and asserts the outcome. Report harness state gaps upstream; never weaken production guards for speed. `AppendConcurrently` is an advanced framework-verification API: use only for an explicit need. Direction, no release claim: Arc will obsolete `UseDecisionReads`.
57
+ **Application decisions (judgment-shaped).** Supply read-model state to plain `Handle()`/validator calls; validators own refusals; `Provide()` only short-circuits (`ValidationResult`/`AuthorizationResult`) when acquisition yields nothing usable, not for ordinary validation rules. Keep one assembly-level `DecisionReadAdmissions.ShouldAdmitDecisionReadsIn(assembly)` check of discoverable application shapes, not per-decision guard scenarios. Ordinary application specs do not re-prove Arc/Chronicle's platform matrix. For an unusual application-owned explicit guard policy — hand-built `EventsWithConcurrencyScopes` or deliberately unguarded `[Unprotected]` reads — use a focused regression only when a plain call cannot prove it; see [decision specifications](../../../skills/cratis-application-slice-specifications/references/query-and-decision-scenarios.md) for admission limits and the advanced hook's boundary. Never weaken production guards for speed; report harness gaps upstream.
58
58
 
59
59
  **Share setup and budget cost (judgment-shaped).** Keep shared lifecycle on; use `[PerFactSpecificationLifecycle]` only on a class whose facts genuinely mutate shared state and cannot move that mutation into `Because`. Plain decision specs should take roughly milliseconds; measure scenario facts and justify seconds by the extra behavior they prove. Compare TRX durations and suite wall time with unchanged concurrency; see [running-specs.md](../../../skills/cratis-specifications-csharp/references/running-specs.md). Do not multiply scenario startup by splitting assertions into classes or opting the project out of shared lifecycle.
60
60
 
@@ -41,7 +41,7 @@ Select from these canonical rules in `.cratis/ai/rules/` only after applying the
41
41
 
42
42
  ## C# specs — start with the plain call
43
43
 
44
- Specify pure `Handle()`, validator, reducer and reactor decisions with plain calls and supplied read-model state. Follow `.cratis/ai/rules/specs.scenarios.csharp.md`: add exactly the scenarios its per-artifact decision table obligates (pipeline and authorization, constraints, projection and reducer dispatch, reactor dispatch and routing), not a platform guard matrix. Prove a rule that must hold under concurrent writers, such as the last seat, from supplied read-model state, never with a race scenario. Keep the single cheap assembly-level admission spec for the application's own decision-model shapes. Prefer in-process helpers over out-of-process Chronicle hosts for the applicable behaviors:
44
+ Specify pure `Handle()`, validator, reducer and reactor decisions with plain calls and supplied read-model state. Follow `.cratis/ai/rules/specs.scenarios.csharp.md`: add exactly the scenarios its per-artifact decision table obligates (pipeline and authorization, constraints, projection and reducer dispatch, reactor dispatch and routing), not a platform guard matrix. Prove ordinary concurrent-writer decisions, such as the last seat, from supplied read-model state, not a replay of the platform matrix. Keep one assembly-level admission check for discoverable application shapes; explicit body reads need their own admission check or focused scenario. Typed scenarios select decision reads automatically; `UseDecisionReads()` is obsolete. For an unusual application-owned explicit guard policy, use only a focused regression a plain call cannot prove. See [decision guidance](../skills/cratis-application-slice-specifications/references/query-and-decision-scenarios.md) for the example, limits and advanced hook boundary; never weaken production guards for speed. Prefer in-process helpers over out-of-process Chronicle hosts for the applicable behaviors:
45
45
 
46
46
  | Tool | Use for |
47
47
  |---|---|
@@ -92,7 +92,7 @@ public class and_all_information_is_valid : Specification
92
92
  0. **Every contract specification first** — one spec each, named after it, using the contract's example values. Then add the code-derived cases below that the contract lacks and report them as proposals for the contract (the `.play` model when one covers the slice, otherwise the agreed outline); never present them as contract coverage. A `.play` specification maps to a plain-call spec for a pure decision, with a scenario added only for the pipeline composition it proves (never a simulated race); never edit, skip or delete a spec derived from the contract to make code pass — change the code or return an edit request.
93
93
  1. **Happy path** — succeeds, correct event(s) appended.
94
94
  2. **Each validation failure** — call the validator directly with supplied state; pipeline validation specs assert **both** `ShouldNotBeSuccessful()` and `ShouldHaveValidationErrors()`. Do not assert on message strings by default; assert exact text only when that wording is the specified behavior, and name that behavior in the fact. Violate **only** the rule the spec is named after (build the command valid in every other respect), or a neighbouring rule makes it pass.
95
- 3. **Business-rule violations** — call `Handle()` or the validator directly with the required model state and assert each rejection. Arc/Chronicle specs alone prove platform concurrency, conflict refusal and isolation. The application's only decision-read spec obligation is the single cheap shape-admission spec in `specs.scenarios.csharp.md`; do not repeat guard scenarios per decision.
95
+ 3. **Business-rule violations** — call the validator directly with the required model state and assert each rejection; `Provide()` acquires data and only short-circuits (`ValidationResult`/`AuthorizationResult`) when acquisition yields nothing usable, not for ordinary validation rules. Arc/Chronicle specs own platform concurrency, conflict refusal and isolation. Keep the assembly-level shape-admission check and any explicit-body-read checks above; do not repeat guard scenarios per decision.
96
96
  4. **Constraint violations** — `ShouldHaveConstraintViolationFor(name)` via `EventScenario`.
97
97
  5. **Authorization** — `ShouldNotBeAuthorized()` (an unauthorized result has no validation errors).
98
98
  6. **Repeat execution**, when a reactor invokes the command — the same command twice for the same source; specify whether the second is rejected, a no-op, or appends again.
@@ -158,4 +158,4 @@ Before handing back:
158
158
  - `Status: done | partial | blocked` (meanings in **cratis-application-slice-conformance**).
159
159
  - Specification map: contract specification → spec class; code-derived extras listed separately as proposals.
160
160
  - The contract used (`.play` slice path or agreed outline).
161
- - Spec results (pending or unexecuted specs named honestly), and any open question or model edit request.
161
+ - Spec results (pending or unexecuted specs named honestly), naming the assembly-level admission check, any explicit-body-read checks or focused policy regression, and any open question, harness gap or model edit request.
@@ -17,7 +17,7 @@ Extends the base [specs.md](./specs.md) (folder structure, naming, philosophy) w
17
17
 
18
18
  ## Frameworks
19
19
 
20
- - [xUnit v3](https://xunit.net/docs/getting-started/v3/migration) is the house default for new and migrated spec projects: reference `Cratis.Specifications.XUnit.v3` **5.0** with `xunit.v3.mtp-off`, `Microsoft.NET.Test.Sdk` and `xunit.runner.visualstudio`, and set `<OutputType>Exe</OutputType>` in the project. The package supplies the `Specification` base, convention lifecycle and `ShouldXxx` assertions; the namespace remains `Cratis.Specifications`. Its `Cratis.Specifications` dependency supplies `Catch` and `SpecificationMethods`.
20
+ - [xUnit v3](https://xunit.net/docs/getting-started/v3/migration) is the house default for new and migrated spec projects **run as the built executable** ([loop](../skills/cratis-specifications-csharp/references/running-specs.md#local-loop)); through `dotnet test` it can be slower (reported measurement). Reference `Cratis.Specifications.XUnit.v3` **5.0** with `xunit.v3.mtp-off`, `Microsoft.NET.Test.Sdk` and `xunit.runner.visualstudio`, and set `<OutputType>Exe</OutputType>` in the project. The package supplies the `Specification` base, convention lifecycle and `ShouldXxx` assertions; the namespace remains `Cratis.Specifications`. Its `Cratis.Specifications` dependency supplies `Catch` and `SpecificationMethods`.
21
21
  - 5.0 targets `net10.0` only. A spec project that must stay on net8.0/net9.0 stays on 4.x, and net48 on 3.x. A project that stays on xUnit v2 uses `Cratis.Specifications.XUnit`, with the same base and conventions.
22
22
  - `.NUnit`/`.NUnit5`, `.TUnit` and the experimental `.Runner` are alternatives for repositories already built on them.
23
23
  - [NSubstitute](https://nsubstitute.github.io/) for mocking collaborators.
@@ -14,15 +14,15 @@ Specs are **mandatory for every slice type**, including reactors.
14
14
 
15
15
  ## Start with the plain call; add a scenario where it adds proof
16
16
 
17
- Call pure `Handle()`, validators, reducers and reactor decisions directly with their inputs, including read-model state. Add a scenario only for the wiring the decision table below obligates (pipeline and authorization, constraints, projection and reducer dispatch, reactor dispatch and routing). Do not repeat every decision through the pipeline; name the extra behavior each scenario proves.
17
+ Call pure `Handle()`, validators, reducers and reactor decisions directly with their inputs, including read-model state. Add a scenario for the wiring the decision table below obligates (pipeline and authorization, constraints, projection and reducer dispatch, reactor dispatch and routing). Do not repeat every decision through the pipeline; name the extra behavior each scenario proves.
18
18
 
19
- **Decision table — apply it per artifact, without judgment.** A plain call proves the decision; a scenario is a coverage obligation for the wiring only the framework proves. These are obligations, not quotas: add a scenario for each behavior listed, and none beyond it.
19
+ **Decision table — apply it per artifact, without judgment.** A plain call proves the decision; a scenario is a coverage obligation for the wiring only the framework proves. These are obligations, not quotas: add a scenario for each behavior listed; only the explicit-policy exceptions below add guard scenarios.
20
20
 
21
21
  | Artifact | Plain call (`Specification`) | Scenario obligation |
22
22
  |---|---|---|
23
- | Command with a pure `Handle(…)` | every outcome and rejection branch, with read-model state supplied | the pipeline path once (`CommandScenario`: discovery, DI, event source, appended events), plus a **negative proof for each wiring that can refuse before `Handle`**: authorization denies (`ShouldNotBeAuthorized`), validation rejects, `Provide()` short-circuits |
23
+ | Command with a pure `Handle(…)` | every outcome and rejection branch, with read-model state supplied | the pipeline path once (`CommandScenario`: discovery, DI, event source, appended events), plus a **negative proof for each wiring that can refuse before `Handle`**: authorization denies (`ShouldNotBeAuthorized`), validation rejects, `Provide()` short-circuits when acquisition yields nothing usable |
24
24
  | `Handle` that needs `IEventStore`, `IReadModels` or services | none: do not substitute the store | keep the scenario; when touched, take the read model as a `Handle` parameter and use the row above |
25
- | `CommandValidator`, `ConceptValidator`, `Provide()` logic | each rule, built with its state | the command's pipeline scenarios prove the wiring |
25
+ | `CommandValidator`, `ConceptValidator`; `Provide()` acquisition/derived values | each validator rule, provided value and acquisition-failure result, built with its state | the command's pipeline scenarios prove the wiring |
26
26
  | Constraint (`[Unique]`, `IConstraint`) | none | an `EventScenario` per constraint: the violation and the nearest non-violation |
27
27
  | Projection or read model | none | `ReadModelScenario` against the real engine, covering **each event, key, join, children and removal the projection declares**: one class per read model with one shared event sequence by default; add a class only for a sequence that cannot share it (a removal, another key) |
28
28
  | Reducer | each transition: `Model.Reduce(event, current[, context])` | a `ReadModelScenario` for dispatch, filters and stream routing |
@@ -53,7 +53,7 @@ public class and_the_caller_is_not_a_maintainer : Specification
53
53
 
54
54
  An unauthenticated scenario against an `[Authorize]`/`[Roles]` command is denied before `Handle`; pair it with the happy-path scenario that registers an allowed identity in `_scenario.Services`.
55
55
 
56
- **Application specs supply state, not decision-read infrastructure.** Call `Handle()` or the validator directly with supplied read-model state. Never call `UseDecisionReads`, configure protection modes, seed events solely for infrastructure, or re-prove the platform's concurrency, conflict-refusal or isolation matrix; Arc/Chronicle specs own it. The application's **only decision-read spec obligation** is one cheap assembly-level shape-admission spec: `DecisionReadAdmissions.ShouldAdmitDecisionReadsIn(assembly)` (`Cratis.Arc.Chronicle.Testing.Commands`). It checks the application's own models/projections without executing commands or running Chronicle, not the platform guards. Never simulate competing appends either (`AppendConcurrently` or any hand-built interleaving): concurrency is a framework concern a developer should not think about in tests, and Arc and Chronicle specs prove it. A rule that must hold under races is expressed in production by taking the read model as a `Handle` parameter under `[ReadProtection(On)]`; the spec gives that read model's state and asserts the outcome. Report harness state gaps upstream; never weaken production guards for speed. `AppendConcurrently` is an advanced framework-verification API: use only for an explicit need. Direction, no release claim: Arc will obsolete `UseDecisionReads`.
56
+ **Application decisions (judgment-shaped).** Supply read-model state to plain `Handle()`/validator calls; validators own refusals; `Provide()` only short-circuits (`ValidationResult`/`AuthorizationResult`) when acquisition yields nothing usable, not for ordinary validation rules. Keep one assembly-level `DecisionReadAdmissions.ShouldAdmitDecisionReadsIn(assembly)` check of discoverable application shapes, not per-decision guard scenarios. Ordinary application specs do not re-prove Arc/Chronicle's platform matrix. For an unusual application-owned explicit guard policy — hand-built `EventsWithConcurrencyScopes` or deliberately unguarded `[Unprotected]` reads — use a focused regression only when a plain call cannot prove it; see [decision specifications](../skills/cratis-application-slice-specifications/references/query-and-decision-scenarios.md) for admission limits and the advanced hook's boundary. Never weaken production guards for speed; report harness gaps upstream.
57
57
 
58
58
  **Share setup and budget cost (judgment-shaped).** Keep shared lifecycle on; use `[PerFactSpecificationLifecycle]` only on a class whose facts genuinely mutate shared state and cannot move that mutation into `Because`. Plain decision specs should take roughly milliseconds; measure scenario facts and justify seconds by the extra behavior they prove. Compare TRX durations and suite wall time with unchanged concurrency; see [running-specs.md](../skills/cratis-specifications-csharp/references/running-specs.md). Do not multiply scenario startup by splitting assertions into classes or opting the project out of shared lifecycle.
59
59
 
@@ -141,12 +141,14 @@ One specification class for **each** of:
141
141
 
142
142
  1. **The happy path** — a plain call returns the expected event, plus one
143
143
  `CommandScenario` happy path for the pipeline, and a negative scenario for
144
- each authorization policy and `Provide()` short-circuit.
144
+ each authorization policy, validator refusal and `Provide()` acquisition-failure short-circuit.
145
145
  2. **Each validation failure** — instantiate `CommandValidator` or
146
146
  `ConceptValidator` with the required state and validate directly; the
147
147
  command's pipeline scenario proves the wiring.
148
- 3. **Each business-rule rejection** — one `and_` class per condition in
149
- `Handle()` that inspects a read model.
148
+ 3. **Each business-rule rejection** — one `and_` class per validator rule using
149
+ supplied read-model state; `Provide()` only short-circuits
150
+ (`ValidationResult`/`AuthorizationResult`) when acquisition yields nothing usable,
151
+ not for ordinary validation rules.
150
152
  4. **Each constraint violation** — one class per constraint, written with
151
153
  `EventScenario`, because a constraint is enforced at the append and not by
152
154
  the command.
@@ -211,16 +213,17 @@ do not replay a projection merely to feed a pure command decision.
211
213
 
212
214
  Both builder methods return `void`; there is nothing to await.
213
215
 
214
- Read protection is invisible to application spec authors. Never configure modes,
215
- call `UseDecisionReads`, simulate competing appends (`AppendConcurrently`), seed
216
- events solely for infrastructure, or re-prove the platform concurrency/guard
217
- matrix: give state, assert the outcome. Keep one cheap assembly-level
218
- `DecisionReadAdmissions.ShouldAdmitDecisionReadsIn(assembly)` spec for the
219
- application's own model/projection shapes: its only decision-read spec obligation.
220
- If the harness cannot accept required state, report the upstream gap; never weaken
221
- production guards for test speed. Read
222
- [query and decision scenarios](references/query-and-decision-scenarios.md) for
223
- query pipelines.
216
+ Ordinary application specs give state and assert the decision; they do not
217
+ re-prove Arc/Chronicle's platform concurrency/guard matrix or select protection
218
+ modes for test speed. Typed scenarios select decision reads automatically;
219
+ `UseDecisionReads()` is obsolete. Keep one assembly-level
220
+ `DecisionReadAdmissions.ShouldAdmitDecisionReadsIn(assembly)` check for discovered
221
+ application shapes. Explicit body reads need their own admission check or focused
222
+ scenario. An unusual application-owned explicit guard policy may need a focused
223
+ regression a plain call cannot prove. Read
224
+ [query and decision scenarios](references/query-and-decision-scenarios.md) for the
225
+ admission example, limitations and advanced hook boundary. Report harness gaps;
226
+ never weaken production guards for test speed.
224
227
 
225
228
  Validator and `Provide()` dependencies are registered in `_scenario.Services`;
226
229
  the concrete validator itself is discovered automatically.
@@ -69,36 +69,80 @@ cover those pipeline hooks.
69
69
 
70
70
  ## Decision specifications
71
71
 
72
- Start with a direct decision call supplied with read-model state. Follow the
73
- [scenario rule](../../../rules/specs.scenarios.csharp.md): application authors do
74
- not select read-protection modes, call `UseDecisionReads`, seed events only to
75
- satisfy infrastructure, or prove the platform concurrency, conflict-refusal or
76
- isolation matrix. Arc/Chronicle specs own it. The application's only decision-read
77
- spec obligation is one cheap assembly-level check of its own model/projection
78
- shapes, not one scenario per decision:
72
+ Start with a direct `Handle()` or validator call supplied with read-model state;
73
+ validators own refusals. `Provide()` acquires data and only short-circuits
74
+ (`ValidationResult`/`AuthorizationResult`) when acquisition yields nothing usable,
75
+ not for ordinary validation rules. Follow the
76
+ [scenario rule](../../../rules/specs.scenarios.csharp.md): ordinary application
77
+ specs prove business decisions, not Arc/Chronicle's concurrency, conflict-refusal
78
+ or isolation matrix. Add pipeline scenarios only for the wiring they prove.
79
+ For that wiring, an admitted flat model pinned with `.ReadModel(instance)` can
80
+ serve a plain `Handle` parameter under `On`; pins are not advisory-only. Use routed
81
+ events for per-stream models and advanced `DecisionRead<T>` parameters, or when
82
+ mapping/history is the proof. `Given` needs `Cratis.Arc.Chronicle.Testing`.
83
+
84
+ ### One assembly-level admission check
85
+
86
+ Keep one cheap admission spec over the application's command assemblies, not one
87
+ scenario per decision. This excerpt assumes `RegisterAuthor` is an application
88
+ command; include each command assembly in a multi-assembly application:
79
89
 
80
90
  ```csharp
81
- DecisionReadAdmissions.ShouldAdmitDecisionReadsIn(assembly);
91
+ using Cratis.Arc.Chronicle.Testing.Commands;
92
+
93
+ public class when_checking_decision_read_admission
94
+ {
95
+ [Fact]
96
+ public void should_admit_every_declared_protected_read() =>
97
+ DecisionReadAdmissions.ShouldAdmitDecisionReadsIn(typeof(RegisterAuthor).Assembly);
98
+ }
82
99
  ```
83
100
 
84
- This API is in `Cratis.Arc.Chronicle.Testing.Commands`; it discovers declared reads
85
- and checks admission without executing commands or running Chronicle. Keep the
86
- spec's discovered projections representative of production; spec-only competing
87
- definitions can make a model ambiguous. Explicit `IDecisionReads.Get` calls inside
88
- method bodies are not statically discovered. If the harness cannot accept
89
- required state for a business decision, report the upstream gap; never weaken
90
- production guards or invent guard doubles.
91
-
92
- Do not add a scenario to prove a race. A rule such as "two callers reserving the last
93
- seat yield one reservation" is specified from state: supply a read model with no seats
94
- left and assert the rejection, then supply one seat and assert the reservation.
95
- Simulating competing appends is a framework concern a developer should not think
96
- about in tests; Arc and Chronicle prove it. `AppendConcurrently` stays a public but
97
- advanced framework-verification API (hidden from IntelliSense), outside application
98
- testing guidance; use it only for a specific, explicit need. Production expresses
99
- the guarantee with the read model as a `Handle` parameter under
100
- `[ReadProtection(On)]`. Direction, not a release claim: Arc will obsolete
101
- `UseDecisionReads`; do not adopt it.
101
+ The helper checks discovered declarations without executing commands or running
102
+ Chronicle. It inspects protected `Handle`/`Provide` decision-read parameters and,
103
+ under declared `On`, plain Chronicle-backed models and discoverable validator
104
+ constructor parameters, excluding advisory reads. Stream parameters use stream
105
+ admission; inherited methods are included and abstract commands are skipped in
106
+ assembly scans. It honors command/assembly declarations and ignores the runtime
107
+ cap. Keep discovered projections representative of production: a spec-local
108
+ projection for a production model can make admission ambiguous.
109
+
110
+ Explicit `IDecisionReads.Get<T>(key)` calls inside method bodies are not statically
111
+ visible. Give those models their own `Admit<T>()` check or a focused command
112
+ scenario. Do not treat the assembly check as coverage of those calls.
113
+
114
+ ### Business decisions, not the platform race matrix
115
+
116
+ Do not add a scenario to prove a race already guaranteed by Arc/Chronicle. For
117
+ "two callers reserving the last seat yield one reservation", supply no-seat state
118
+ to the validator and assert rejection, then supply one-seat state and assert the
119
+ allowed decision. Direct calls do not prove the guard itself.
120
+
121
+ Typed `CommandScenario<TCommand>` selects decision reads from the command's
122
+ declarations. Do not call `UseDecisionReads()`; it is obsolete. For an untyped
123
+ `CommandScenario<object>` whose declarations cannot be selected at construction,
124
+ `EnableDecisionReads()` must run before seeding or the first `Execute`/`Validate`.
125
+ Do not change production protection for spec speed. If required state cannot be
126
+ supplied, report the harness gap rather than inventing guard doubles.
127
+
128
+ ### Focused explicit-policy regression
129
+
130
+ An unusual application-owned explicit guard policy can justify a focused
131
+ regression that a plain call cannot prove. Examples are a revision captured during
132
+ a read and returned in `EventsWithConcurrencyScopes`, application-owned `[Unprotected]`
133
+ behavior on a command, model or parameter, or a deliberately non-atomic batch contract.
134
+ Test that chosen contract, not the platform's generic conflict/isolation matrix.
135
+ `EventsWithConcurrencyScopes` carries ordered events and supplied scopes into the
136
+ same command transaction, so the policy regression must exercise that boundary.
137
+
138
+ `AppendConcurrently` is an advanced framework-verification hook, hidden from normal
139
+ editor completion, not a routine application-spec template. Use it only for a
140
+ specific, explicit need: it works with or without decision mode and adds no guard
141
+ to an unguarded command. Queue it before the first execution; it appends competing
142
+ facts after response processing and before the owner's commit. Its route overload
143
+ preserves routing; nested commands do not drain the outer queue. It refuses custom
144
+ execution scopes whose ordering it cannot guarantee. Do not call `UseDecisionReads()`
145
+ to make the hook work, or hand-build a race matrix around it.
102
146
  `ShouldHaveCompletedStream(ClosedStreamScope)` may assert that a decision completed a
103
147
  stream at the exact source and route (`Cratis.Arc.Chronicle.Testing.Commands`).
104
148
  Use event history only when it is part of the domain example.
@@ -113,4 +157,7 @@ Provider boundaries remain separate: state fixtures are not a MongoDB substitute
113
157
  - [Query scenarios](https://github.com/Cratis/Arc/blob/main/Documentation/backend/csharp/testing/query-scenario.md)
114
158
  - [Stream decisions and routed specs](https://github.com/Cratis/Arc/blob/main/Documentation/backend/csharp/chronicle/commands/stream-decisions.md)
115
159
  - [Decision-mode extension](https://github.com/Cratis/Arc/blob/main/Source/DotNET/Chronicle.Testing/Commands/CommandScenarioChronicleExtensions.cs)
160
+ - [Admission helper](https://github.com/Cratis/Arc/blob/main/Source/DotNET/Chronicle.Testing/Commands/DecisionReadAdmissions.cs)
161
+ - [Explicit revision scopes](https://github.com/Cratis/Arc/blob/main/Documentation/backend/csharp/chronicle/commands/concurrency.md)
162
+ - [Advisory read declarations](https://github.com/Cratis/Arc/blob/main/Source/DotNET/Chronicle/ReadModels/UnprotectedAttribute.cs)
116
163
  - [Application-shape admission assertion](https://github.com/Cratis/Arc/blob/main/Source/DotNET/Chronicle.Testing/Commands/DecisionReadAdmissions.cs)
@@ -13,7 +13,7 @@ told about them. Each has its own extension point.
13
13
 
14
14
  ## Verified product sources
15
15
 
16
- Read [references/product-sources.md](references/product-sources.md) when you need the owning package for an identity type.
16
+ Read [product sources](references/product-sources.md) for packages; [command identity](references/command-identity.md) for actor injection, caller-keyed reads and Chronicle attribution.
17
17
 
18
18
  Authorization capabilities arrived over time: named policies, schemes, fallback baselines, guest policies and Microsoft-attribute enforcement all need a recent Arc. [authorization](references/authorization.md) lists the requirements; check them if you run an older version.
19
19
 
@@ -297,6 +297,5 @@ To run locally with an identity, supply the forwarded headers yourself — see
297
297
 
298
298
  - Rejecting a command's input or state: `cratis-arc-command-validation` scope
299
299
  (validators are not the place for state-dependent permission rules).
300
- - Chronicle tenant namespaces and per-tenant event stores: the Chronicle
301
- multi-tenancy guidance.
300
+ - Tenant namespaces and per-tenant event stores: Chronicle multi-tenancy.
302
301
  - Building the React page that consumes identity: the Arc React guidance.
@@ -375,7 +375,8 @@ being in-process does not prove permission.
375
375
  of transport. During HTTP it is the request principal; outside HTTP it can be the
376
376
  principal established by a server-side scope. Read claims from it, not from the
377
377
  identity cookie, and not through `IHttpContextAccessor` in code that must also run
378
- on hub emissions.
378
+ on hub emissions. For application actor injection, caller-keyed reads and
379
+ Chronicle attribution, read [command identity](command-identity.md).
379
380
 
380
381
  Command authorization reads the principal from the current request. A reactor,
381
382
  hosted service, or one command orchestrating another has no request, so any
@@ -0,0 +1,194 @@
1
+ # Command identity and Chronicle attribution
2
+
3
+ ## Contents
4
+
5
+ - Choose the contract
6
+ - Supply an application actor
7
+ - Select a caller-keyed read model
8
+ - Attribute events without copying personal data
9
+
10
+ ## Choose the contract
11
+
12
+ | Need | Contract |
13
+ | --- | --- |
14
+ | Identify the caller at the server boundary | `ICurrentPrincipalAccessor.Current` in `Cratis.Arc.Authorization` |
15
+ | Supply an application-owned actor value to `Provide()` or `Handle()` | `IAsyncParameterDependencyResolver` in `Cratis.Arc.DependencyInjection` |
16
+ | Select a Chronicle read model using the caller | `[LookUpBy<CallerSubject>]`, `CallerClaim` or `IReadModelKeyProvider` in `Cratis.Arc.Commands` |
17
+ | Decide whether the caller may perform the action | Named authorization policies and `[Authorize]`; `Provide()` may short-circuit only when acquisition yields nothing usable |
18
+ | Attribute an append | Chronicle's `IIdentityProvider.GetCurrent()` supplies `CausedBy`; observers read `EventContext.CausedBy` |
19
+
20
+ An actor value and a lookup key are neither proof of permission nor a substitute
21
+ for authorization. Derive them from the server-selected authenticated principal,
22
+ not a command's `UserId`, a readable identity cookie, or untrusted headers.
23
+ Configure the trusted authentication boundary first; see
24
+ [forwarded identity](../SKILL.md#read-this-first-what-is-and-is-not-trusted).
25
+ Anonymous callers get no privileged fallback. Never manufacture a System actor
26
+ to make an unresolved caller pass.
27
+
28
+ ## Supply an application actor
29
+
30
+ Prefer a small, immutable application type over passing `ClaimsPrincipal` into
31
+ business decisions. The following is a complete resolver illustration, not a
32
+ host: it requires Arc's principal accessor and the service registration below.
33
+ `CurrentActor` and `ActorSubject` are application-owned types, not Arc APIs. This
34
+ application requires one distinct, nonempty exact `sub` claim and refuses the
35
+ System identity. Adapt that policy explicitly for verified workload callers;
36
+ do not silently substitute a system subject. Keep the raw subject inside the
37
+ application boundary; use a non-personal domain key where the domain needs one.
38
+
39
+ ```csharp
40
+ using System;
41
+ using System.Linq;
42
+ using System.Reflection;
43
+ using System.Threading.Tasks;
44
+ using Cratis.Arc.Authorization;
45
+ using Cratis.Arc.DependencyInjection;
46
+ using Cratis.Concepts;
47
+ using Microsoft.Extensions.DependencyInjection;
48
+
49
+ public record ActorSubject(string Value) : ConceptAs<string>(Value);
50
+ public record CurrentActor(ActorSubject Subject);
51
+
52
+ public sealed class CurrentActorResolver : IAsyncParameterDependencyResolver
53
+ {
54
+ public bool TryResolve(IServiceProvider services, ParameterInfo parameter, out object? dependency)
55
+ {
56
+ dependency = null;
57
+ if (parameter.ParameterType != typeof(CurrentActor)) return false;
58
+ dependency = ActorFor(services.GetRequiredService<ICurrentPrincipalAccessor>());
59
+ return true;
60
+ }
61
+
62
+ public ValueTask<ParameterDependencyResolution> Resolve(IServiceProvider services, ParameterInfo parameter) =>
63
+ ValueTask.FromResult(TryResolve(services, parameter, out var dependency)
64
+ ? ParameterDependencyResolution.Resolved(dependency)
65
+ : ParameterDependencyResolution.NotResolved);
66
+
67
+ static CurrentActor? ActorFor(ICurrentPrincipalAccessor principals)
68
+ {
69
+ if (principals.Current is not { Identity: { IsAuthenticated: true } } principal ||
70
+ principal.Identity.AuthenticationType == "System") return null;
71
+
72
+ var subjects = principal.Claims
73
+ .Where(claim => claim.Type == "sub" && !string.IsNullOrEmpty(claim.Value))
74
+ .Select(claim => claim.Value)
75
+ .Distinct(StringComparer.Ordinal)
76
+ .Take(2)
77
+ .ToArray();
78
+ return subjects is [var subject] && subject != "[System]"
79
+ ? new CurrentActor(new ActorSubject(subject))
80
+ : null;
81
+ }
82
+ }
83
+ ```
84
+
85
+ Register through the public resolver interface in the host's service setup:
86
+
87
+ ```csharp
88
+ services.AddScoped<ICanResolveParameterDependency, CurrentActorResolver>();
89
+ ```
90
+
91
+ `IAsyncParameterDependencyResolver` extends `ICanResolveParameterDependency`, so
92
+ both members matter. Awaiting command parameter binding calls `Resolve`; a
93
+ synchronous consumer calls `TryResolve`. Return
94
+ `ParameterDependencyResolution.NotResolved` (or `false`) for types you do not
95
+ own. `ParameterDependencyResolution.Resolved(null)` means the resolver owns the
96
+ parameter but has no value; it does not mean “try the next resolver”. The example
97
+ has no I/O. If acquisition needs I/O, await it in `Resolve`; do not block on a
98
+ Task in `TryResolve` or hide acquisition in `Handle()`.
99
+
100
+ Chronicle's registered chain consults Chronicle first, then application resolvers
101
+ from the current service scope. Do not replace its
102
+ `IInstancesOf<ICanResolveParameterDependency>` composition to install your actor
103
+ resolver, or claim a Chronicle read-model type as your application actor.
104
+
105
+ Require a named policy such as `[Authorize(Policy = "CanEnableFeature")]` on the
106
+ command and register that policy in the host. The policy owns the `CanEnable`
107
+ permission check, before validation or acquisition. A validator under read
108
+ protection `On` is an alternative for state-dependent preconditions, not caller
109
+ admission; see [validators are not an authorization boundary](../SKILL.md#validators-are-not-an-authorization-boundary).
110
+
111
+ These are **method excerpts** inside that command, not a complete slice.
112
+ `FeatureEnabled` is an application event with no identity fields:
113
+
114
+ ```csharp
115
+ public AuthorizationResult Provide(CurrentActor? actor) =>
116
+ actor is null
117
+ ? AuthorizationResult.Failure("Actor unavailable.")
118
+ : AuthorizationResult.Success;
119
+
120
+ public FeatureEnabled Handle(CurrentActor actor) => new();
121
+ ```
122
+
123
+ The failed authorization result stops handler execution only because acquisition
124
+ yielded no usable actor, not because `Provide()` owns permission checks. A
125
+ non-nullable actor parameter alone is not a permission check. Do not use
126
+ `Provide()` to echo a client-supplied actor: ordinary returned values can satisfy
127
+ assignable `Handle()` parameters before resolver fallback. Keep acquisition in
128
+ `Provide()` or parameter binding and pass decision inputs explicitly; keep the
129
+ handler's decision free of hidden principal/service I/O. See
130
+ [authorization](authorization.md) and
131
+ [command decisions](../../cratis-arc-command/references/decisions-and-routing.md).
132
+
133
+ ## Select a caller-keyed read model
134
+
135
+ Do not build a general actor resolver merely to select an existing Chronicle
136
+ read model. Arc already supports a generic lookup provider on a read-model
137
+ `Handle()` parameter. In a method excerpt where `CallerPreferences` is a
138
+ registered read model keyed by the caller's exact subject:
139
+
140
+ ```csharp
141
+ public FeatureEnabled Handle([LookUpBy<CallerSubject>] CallerPreferences preferences) => new();
142
+ ```
143
+
144
+ `CallerSubject` reads exact `sub`, without claim-type mapping. For another exact
145
+ claim, define a public parameterless provider such as:
146
+
147
+ ```csharp
148
+ public sealed class CallerAccount() : CallerClaim("account_id");
149
+ ```
150
+
151
+ Use `[LookUpBy<CallerAccount>]` on the read-model parameter. `CallerClaim` refuses
152
+ unauthenticated and System callers. `CommandCaller.Single` accepts one distinct
153
+ nonempty value using ordinal comparisons: repeated equal claims are one value;
154
+ different values are ambiguous.
155
+
156
+ For a derived key, implement `IReadModelKeyProvider.Resolve(ReadModelKeyContext)`.
157
+ Its `Caller` is the immutable selected `CommandCaller`, captured before command
158
+ context providers run; actor-chain claims are excluded. Its `ReadModelType` is
159
+ the target model. Return `ReadModelKeyLookup.Found(key)`, `.Missing` or
160
+ `.Ambiguous`. Providers require a public parameterless constructor and must be
161
+ stateless, thread-safe, synchronous, I/O-free and service-free. Do not consult
162
+ ambient identity, inject services, or decode an unvalidated token in a provider.
163
+
164
+ Missing/ambiguous results, provider failures, and a missing or changed captured
165
+ caller fail closed through `ReadModelKeyResolutionDenied`, mapped to an
166
+ unauthorized command result without caller/provider exception data. This is key
167
+ resolution, not proof that the selected model exists or that the action is
168
+ permitted. Do not combine generic and property lookup forms, replace a
169
+ caller-keyed model with a `Provide()` value, or use a caller provider to redirect
170
+ a per-stream model away from the command's own stream. See
171
+ [read-model injection](../../cratis-arc-command/references/read-model-injection.md)
172
+ for command-property lookup, absence and read protection.
173
+
174
+ ## Attribute events without copying personal data
175
+
176
+ Chronicle append preparation calls `IIdentityProvider.GetCurrent()` and sends the
177
+ identity as `CausedBy`. `EventContext.CausedBy` exposes that attribution to
178
+ observers. `Identity.OnBehalfOf` links an identity chain. This is audit metadata,
179
+ not authentication, permission, or an event's compliance subject. Do not put
180
+ subjects, names, emails, usernames, roles, claims or actor objects in event payloads
181
+ merely to record who acted. Keep events about business facts.
182
+
183
+ Chronicle's ASP.NET provider maps exact `sub`, `name` and `preferred_username`,
184
+ with `Identity.Name` fallbacks for the latter two. Arc's identity decorator
185
+ preserves the selected Chronicle identity and also handles authenticated
186
+ server-side principals outside HTTP. When a principal has a `ClaimsIdentity.Actor`,
187
+ Arc records the actor first and the represented user as `Identity.OnBehalfOf`;
188
+ this chain is attribution, never an authorization grant.
189
+
190
+ For standalone Chronicle, configure `IIdentityProvider` at the application
191
+ boundary; `SetCurrentIdentity`/`ClearCurrentIdentity` control attribution, not
192
+ caller permissions. Never forward raw identifiers to external services, logs,
193
+ telemetry, or evaluators. For lawful personal event data and the separate erasure
194
+ subject, use [Chronicle compliance](../../cratis-chronicle-compliance/SKILL.md).
@@ -9,3 +9,29 @@ This reference holds the packages and types Arc identity and authorization guida
9
9
  | `@cratis/arc` | `IdentityProvider`, `IIdentity` |
10
10
  | `@cratis/arc.react` | `IdentityProvider` component, `useIdentity`, `RequireRole` |
11
11
  | Cratis AuthProxy (`cratis/authproxy`) | the trusted ingress described in [AuthProxy](authproxy.md) |
12
+
13
+ ## Command identity and audit evidence
14
+
15
+ Verified against Arc `origin/main` (`d3ecc873b`) and Chronicle `origin/main`
16
+ (`ed97fe729a`). These sources own the contracts in
17
+ [command identity](command-identity.md); check your installed version before using
18
+ caller providers. No minimum release is asserted here.
19
+
20
+ | Source | Contract verified |
21
+ | --- | --- |
22
+ | Arc `Source/DotNET/Arc.Core/Authorization/ICurrentPrincipalAccessor.cs`, `CurrentPrincipalAccessor.cs`, `AuthorizationCommandIdentity.cs` | Selected principal; AsyncLocal, execution-context and HTTP access; immutable exact-claim caller snapshot without actor-chain claims |
23
+ | Arc `Source/DotNET/Arc.Core/DependencyInjection/IAsyncParameterDependencyResolver.cs`, `ICanResolveParameterDependency.cs`, `ParameterDependencyResolution.cs`, `ParameterDependencyResolver.cs` | Async and synchronous resolver members, resolved-null versus not-resolved, awaited binding |
24
+ | Arc `Source/DotNET/Chronicle/ReadModels/ChronicleParameterDependencyResolvers.cs`, `ReadModelServiceCollectionExtensions.cs` | Chronicle-first composition, scoped application resolver discovery through `IInstancesOf<ICanResolveParameterDependency>` |
25
+ | Arc `Source/DotNET/Arc.Core/Commands/CommandProvideInvoker.cs`, `CommandHandlerArgumentResolver.cs`, `ModelBound/ModelBoundCommandHandler.cs` | `Provide()` parameter binding; ordinary provided-value precedence; a supplied matching value for a caller-provider read-model parameter is refused with `InvalidLookUpBy` |
26
+ | Arc `Source/DotNET/Arc.Core/Authorization/AuthorizationResult.cs`; `Source/DotNET/Arc.Core/Commands/CommandPipeline.cs` | Failed `AuthorizationResult` from `Provide()` stops handler execution; key-resolution denial maps to unauthorized without exception details |
27
+ | Arc `Source/DotNET/Arc.Core/Commands/LookUpByAttribute.cs`, `IReadModelKeyProvider.cs`, `ReadModelKeyContext.cs`, `ReadModelKeyLookup.cs`, `CallerClaim.cs`, `CallerSubject.cs`, `ReadModelKeyProviders.cs`, `ReadModelKeyResolutionDenied.cs`, `CommandAttributePolicy.cs`; `Source/DotNET/Arc.Core/Authorization/CommandCaller.cs` | Both lookup forms, parameterless synchronous providers, exact claims, missing/ambiguous denial and caller consistency |
28
+ | Arc `Source/DotNET/Chronicle/ReadModels/CommandReadModelLookup.cs`, `ChronicleParameterDependencyResolver.cs` | Provider lookup precedes read protection; guarded and plain keyed loading |
29
+ | Arc `Source/DotNET/Chronicle.Specs/ReadModels/for_per_stream_models/when_a_key_provider_redirects_the_stream.cs` | A caller provider cannot redirect a per-stream read away from the command stream |
30
+ | Arc `Source/DotNET/Chronicle/Identities/ArcIdentityProvider.cs` | Selected Chronicle identity preservation, non-HTTP principal attribution, actor-first `OnBehalfOf` chain |
31
+ | Chronicle `Source/Clients/DotNET/Identities/IIdentityProvider.cs`, `Identity.cs`, `IdentityConverters.cs`; `Source/Clients/AspNetCore/Identities/IdentityProvider.cs` | Current/explicit identity, exact ASP.NET claim mapping, System identity and actor chain |
32
+ | Chronicle `Source/Clients/DotNET/EventSequences/EventSequence.cs`, `Events/EventContext.cs` | Append preparation obtains `CausedBy` from `GetCurrent()`; event context exposes attribution |
33
+
34
+ `CurrentActor`, `ActorSubject`, `CallerPreferences`, `CallerAccount` and
35
+ `FeatureEnabled` in the example are application-owned, not
36
+ product types. `ConceptAs<string>` follows Chronicle's
37
+ `Source/Clients/DotNET/EventStoreName.cs` and `GlobalUsings.cs`.
@@ -40,11 +40,14 @@ Requires Arc 22.106.0 for read protection. Older Arc has only the per-command
40
40
  `[ProtectedDecision]` path below.
41
41
 
42
42
  - **One entity's state.** Put the rule in a validator with the read model as a
43
- constructor parameter; `Handle()` returns the events. The key is
44
- `[LookUpBy(nameof(Cmd.Prop))]` on the parameter (`Cratis.Arc.Commands`), else the
45
- single command property whose type equals the model's `Id` type, else the
46
- command's event source id. Several matching properties fail with
47
- `AmbiguousReadModelLookup` (500): add `[LookUpBy]`.
43
+ constructor parameter; `Handle()` returns the events. Choose one explicit key
44
+ form: `[LookUpBy(nameof(Cmd.Prop))]` for a command property or
45
+ `[LookUpBy<CallerSubject>]` for a caller-keyed handler model (`Cratis.Arc.Commands`);
46
+ read [command identity](../../cratis-arc-authentication-authorization-and-identity/references/command-identity.md)
47
+ for providers, actor injection and attribution. Without an explicit lookup the
48
+ key is the single command property matching the model's `Id` type, else the
49
+ command's event source id. Several matches fail with
50
+ `AmbiguousReadModelLookup` (500): declare the intended lookup.
48
51
  - **Two entities.** Two read-model parameters, the second with `[LookUpBy]`;
49
52
  `Handle()` returns `IEnumerable<EventForEventSourceId>`, one event per entity,
50
53
  appended atomically. Use a distinct event type per entity.
@@ -187,20 +190,23 @@ source id/type and stream route; reactor tuples/collections cannot mix it with e
187
190
  ## Decision specifications
188
191
 
189
192
  Call `Handle()` and validators directly with read-model state for pure business
190
- decisions. Follow the [scenario rule](../../../rules/specs.scenarios.csharp.md):
191
- read-protection plumbing is invisible to application spec authors. They never
192
- call `UseDecisionReads`, configure modes, simulate competing appends
193
- (`AppendConcurrently`), seed events solely for infrastructure, or re-prove the platform concurrency, conflict-refusal or isolation matrix;
194
- Arc/Chronicle specs own it. The application's only decision-read spec obligation
195
- is one cheap assembly-level shape-admission spec from that rule.
196
- Never weaken production guards for test speed. Report a harness state-setup gap
197
- upstream instead of working around it in application specs.
198
-
199
- Add scenarios for pipeline/authorization wiring or constraints. Never simulate
200
- competing appends: assert the business outcome from supplied state (for example, no
201
- copies left rejects). Read
193
+ decisions; validators own refusals. `Provide()` acquires data and only short-circuits
194
+ (`ValidationResult`/`AuthorizationResult`) when acquisition yields nothing usable,
195
+ not for ordinary validation rules. Follow
196
+ the [scenario rule](../../../rules/specs.scenarios.csharp.md): ordinary application
197
+ specs do not re-prove Arc/Chronicle's platform concurrency, conflict-refusal or
198
+ isolation matrix. Typed scenarios select decision reads automatically;
199
+ `UseDecisionReads()` is obsolete. Keep one assembly-level shape-admission check;
200
+ explicit body reads need their own admission check or focused scenario. Never
201
+ weaken production guards for speed; report harness state-setup gaps upstream.
202
+
203
+ Add scenarios for pipeline/authorization wiring or constraints. Assert the business
204
+ outcome from supplied state (for example, no copies left rejects in the validator).
205
+ An unusual application-owned explicit guard policy may need a focused regression
206
+ a plain call cannot prove, not a generic race matrix. Read
202
207
  [query and decision scenarios](../../cratis-application-slice-specifications/references/query-and-decision-scenarios.md)
203
- for the query and decision setup. Keep shared lifecycle on and measure the added cost.
208
+ for the admission example, limits and advanced hook boundary. Keep shared
209
+ lifecycle on and measure the added cost.
204
210
 
205
211
  ## Sources
206
212
 
@@ -2,6 +2,7 @@
2
2
 
3
3
  ## Contents
4
4
 
5
+ - Choose the key
5
6
  - Nullability is the required/optional switch
6
7
  - `null` is not always what absence looks like
7
8
  - Which provider owns a read model type
@@ -16,28 +17,43 @@ and, for per-command opt-in, `[ProtectedDecision]` with `DecisionRead<T>`.
16
17
 
17
18
  A read model can be injected into a `CommandValidator<T>` constructor, into
18
19
  `Provide()`, or into `Handle()`. Arc resolves it through an
19
- `ICanResolveReadModelForCommand` provider, **by the command's resolved key** —
20
- not by the read-model type, and not by "the property that looks like its key".
20
+ `ICanResolveReadModelForCommand` provider using the selected lookup key. An
21
+ explicit command-property or caller-provider lookup is not limited to protected
22
+ commands. Without one, the default depends on the read-protection mode.
21
23
 
22
- If the instance you need is keyed by anything else, direct injection hands you
23
- the wrong instance or nothing at all. That is a correctness bug, not a compile
24
- error. The three shapes it takes:
24
+ Choose the key explicitly when the default is wrong. Three common cases:
25
25
 
26
26
  1. you need a *referenced other* entity — act on A, check B;
27
27
  2. the command has more than one candidate identity property, so resolution is
28
28
  ambiguous;
29
29
  3. the id is generated inside `Handle()` and does not exist yet.
30
30
 
31
- In all three, under `Off` read by explicit key in `Provide()`; under `On` use a
32
- second parameter with `[LookUpBy]`, or `IDecisionReads.Get` in `Provide()` for a
33
- key computed there:
31
+ Explicit lookup works in every read-protection mode. Choosing a key does not
32
+ make a plain read protected. For a key computed in `Provide()`, use
33
+ `IDecisionReads.Get` when it must guard the append; a direct by-id read under
34
+ `Off` remains unprotected.
34
35
 
35
- ```csharp
36
- var other = await readModels.GetInstanceById<<Other>>((EventSourceId)<OtherId>);
37
- ```
36
+ ## Choose the key
38
37
 
39
- `ReadModelKey` converts implicitly from `EventSourceId`, `Guid` and `string`, so
40
- the cast is all that is needed.
38
+ Use one explicit form on a read-model `Handle()` parameter (`Cratis.Arc.Commands`):
39
+
40
+ - `[LookUpBy(nameof(CommandName.KeyProperty))]` selects a command property.
41
+ - `[LookUpBy<CallerSubject>]`, a `CallerClaim` subclass or another
42
+ `IReadModelKeyProvider` selects a caller-derived key. See
43
+ [command identity](../../cratis-arc-authentication-authorization-and-identity/references/command-identity.md)
44
+ for exact claims, immutable caller capture, denial, actor injection and audit.
45
+
46
+ Do not combine property and provider forms or specify several providers. Without
47
+ an explicit lookup, `On` uses the single command property whose type exactly
48
+ matches the model's `Id` type; several matches raise `AmbiguousReadModelLookup`;
49
+ no match falls back to the command event source id. `Off` and `Measure` retain
50
+ the legacy event-source-id default. A caller provider cannot redirect a
51
+ per-stream model away from the command route.
52
+
53
+ Ordinary `Provide()` values assignable to a `Handle()` parameter are used before
54
+ service/read-model resolution. For a caller-provider read-model parameter, a
55
+ supplied matching value is refused with `InvalidLookUpBy`, not bypassed: do not
56
+ try to replace the identity-keyed model with a provided value.
41
57
 
42
58
  Requires Arc 22.93.0 for ARCCHR0023 (no unique key-type match), ARCCHR0025
43
59
  (keyless command reads a newly generated id and finds no model) and ARCCHR0026
@@ -48,6 +48,7 @@ Arc for TypeScript server API.
48
48
 
49
49
  Do not disguise a write as `Provide()`. Supply identities, clock values, and
50
50
  state before `Handle()`; returning operations does not make hidden I/O pure.
51
+ Actors/audit: [identity](../cratis-arc-authentication-authorization-and-identity/references/command-identity.md).
51
52
 
52
53
  ## Declare the work and its reversal
53
54
 
@@ -272,11 +272,16 @@ Every rule gets a failure specification: instantiate the validator with its
272
272
  read-model state and validate directly, asserting the specific rejection. Add
273
273
  `CommandScenario<TCommand>` only for pipeline/authorization wiring, constraints.
274
274
  Follow the
275
- [scenario rule](../../rules/specs.scenarios.csharp.md): application specs never
276
- configure read-protection modes, call `UseDecisionReads`, simulate competing appends, seed events solely for
277
- infrastructure, or re-prove platform guards. Keep the single cheap assembly-level
278
- application-shape admission spec specified by that rule; it is the application's
279
- only decision-read spec obligation. Report harness gaps upstream; never weaken
275
+ [scenario rule](../../rules/specs.scenarios.csharp.md): ordinary application specs
276
+ supply state, not a replay of the platform guard matrix. Typed scenarios select
277
+ decision reads automatically; `UseDecisionReads()` is obsolete. Keep one
278
+ assembly-level application-shape admission check; explicit body reads need their
279
+ own admission check or focused scenario. An unusual application-owned explicit
280
+ guard policy can justify a focused regression a plain call cannot prove; read the
281
+ [decision guidance](../cratis-application-slice-specifications/references/query-and-decision-scenarios.md)
282
+ for the example, limits and advanced hook boundary. Validators own refusals;
283
+ `Provide()` only short-circuits (`ValidationResult`/`AuthorizationResult`) when
284
+ acquisition yields nothing usable, not for ordinary validation rules. Report harness gaps upstream; never weaken
280
285
  production guards for speed.
281
286
 
282
287
  For a pipeline validation rejection, assert **both** that the command did not
@@ -32,6 +32,7 @@ Read references/occurrences.md when recording durable triggers, implementing
32
32
  occurrence handlers, or choosing startup/shutdown activation and retry semantics.
33
33
  Read references/immediate-append-refusal.md when a unit must prevent immediate
34
34
  appends from escaping its atomic receipt boundary before transport.
35
+ For caller versus `CausedBy` attribution: [command identity](../cratis-arc-authentication-authorization-and-identity/references/command-identity.md).
35
36
 
36
37
  ## Lifecycle
37
38
 
@@ -84,6 +84,7 @@ can fail those appends. Verify a protected-value round trip, not only compilatio
84
84
  Mark only genuinely personal values. Business metadata, identifiers of
85
85
  non-persons, and amounts stay unmarked — every marked value costs an encryption
86
86
  round trip and becomes unreadable the moment the subject is erased.
87
+ Attribution, not payload PII: [identity](../cratis-arc-authentication-authorization-and-identity/references/command-identity.md).
87
88
 
88
89
  ## Decide the subject
89
90
 
@@ -191,13 +191,18 @@ deciding writer is guarded or the rule is a constraint.
191
191
  - Review production enrollment in the intended store, namespace and stream;
192
192
  surface refusal and never replace it with an unprotected read. One owner completes.
193
193
  - Application specs call `Handle()` or the validator directly with supplied state.
194
- Their only decision-read spec obligation is one cheap assembly-level
195
- `DecisionReadAdmissions.ShouldAdmitDecisionReadsIn(assembly)` check of the
196
- application's own model/projection shapes; see the
197
- [scenario rule](../../rules/specs.scenarios.csharp.md).
194
+ Keep one assembly-level `DecisionReadAdmissions.ShouldAdmitDecisionReadsIn(assembly)`
195
+ check of discoverable application shapes; explicit body reads need their own
196
+ admission check or focused scenario. See the
197
+ [scenario rule](../../rules/specs.scenarios.csharp.md) and
198
+ [decision guidance](../cratis-application-slice-specifications/references/query-and-decision-scenarios.md)
199
+ for the example, admission limits and advanced hook boundary.
198
200
  - Arc/Chronicle specs alone prove platform conflict refusal, relevant/irrelevant
199
201
  changes, absence guards, empty checked appends, isolation and commit lifecycle.
200
202
  Their real-client/kernel integration proves the boundary; a default
201
203
  `EventScenario` scope strategy returning `None` is not concurrency evidence.
202
- - Application specs never simulate competing appends or repeat that matrix.
203
- Never weaken production guards for spec speed.
204
+ - Ordinary application specs do not repeat that matrix. An unusual
205
+ application-owned explicit guard policy may need a focused regression a plain
206
+ call cannot prove, not a routine race template. Typed scenarios select decision
207
+ reads automatically; `UseDecisionReads()` is obsolete. Never weaken production
208
+ guards for spec speed.
@@ -131,10 +131,13 @@ Under `On`:
131
131
  Take the model as a parameter, or mark the method `[Unprotected("why")]` (it
132
132
  covers the body, not injected parameters).
133
133
  - Immediate appends (an injected `IEventLog.Append`) are refused. Return the events.
134
- - The key is, in order: `[LookUpBy(nameof(Cmd.Prop))]` on the parameter
135
- (parameter-only attribute, `Cratis.Arc.Commands`); the single command property
136
- whose type equals the model's `Id` type; `AmbiguousReadModelLookup` (HTTP 500) if
137
- several match; the command's event source id.
134
+ - Explicit lookup selects either a command property with
135
+ `[LookUpBy(nameof(Cmd.Prop))]` or a caller-keyed handler model with
136
+ `[LookUpBy<CallerSubject>]` (`Cratis.Arc.Commands`); see
137
+ [command identity](../../cratis-arc-authentication-authorization-and-identity/references/command-identity.md).
138
+ Otherwise use the single command property matching the model's `Id` type;
139
+ several matches raise `AmbiguousReadModelLookup` (HTTP 500); no match falls
140
+ back to the command's event source id.
138
141
  - Admitted: event-source-keyed model-bound or declarative projections with a
139
142
  string or Guid `Id`, and unfiltered reducers without constructor dependencies
140
143
  (except `ILogger<T>`; self-reducing models are exempt). Refused with
@@ -337,20 +340,23 @@ justified opt-out, then remove the property and any per-command
337
340
  ## Specify the business decision
338
341
 
339
342
  Start with a plain `Handle()` or validator call supplied with read-model state.
340
- Follow the [scenario rule](../../../rules/specs.scenarios.csharp.md): read-protection
341
- plumbing is invisible to application spec authors. They never configure modes,
342
- call `UseDecisionReads`, seed events solely for infrastructure or re-prove platform
343
- concurrency, conflict-refusal or isolation guards. Arc/Chronicle specs own that
344
- matrix. The application's only decision-read spec obligation is one cheap
345
- assembly-level `DecisionReadAdmissions.ShouldAdmitDecisionReadsIn(assembly)`
346
- check of its own models/projections, not per-decision scenarios. Production
347
- protection stays unchanged regardless of spec cost.
348
-
349
- Do not simulate competing appends in an application spec, even for a rule such as
350
- two borrowers competing for the last copy. Give the state (no copies left) and assert
351
- the domain outcome (rejected); the guarantee that only one wins is proven by Arc and
352
- Chronicle. If the harness cannot accept required state, report the upstream gap
353
- rather than adding infrastructure setup to application specs.
343
+ Follow the [scenario rule](../../../rules/specs.scenarios.csharp.md): ordinary
344
+ application specs prove the decision, not Arc/Chronicle's platform concurrency,
345
+ conflict-refusal or isolation matrix. Typed scenarios select decision reads
346
+ automatically; `UseDecisionReads()` is obsolete. Keep one assembly-level
347
+ `DecisionReadAdmissions.ShouldAdmitDecisionReadsIn(assembly)` check of discoverable
348
+ application models/projections. Explicit body reads need their own admission check
349
+ or focused scenario; see the
350
+ [decision guidance](../../cratis-application-slice-specifications/references/query-and-decision-scenarios.md)
351
+ for the example, limits and advanced hook boundary. Production protection stays
352
+ unchanged regardless of spec cost.
353
+
354
+ For two borrowers competing for the last copy, give no-copy state to the validator
355
+ and assert rejection; Arc/Chronicle prove the guard. `Provide()` acquires data and
356
+ only short-circuits (`ValidationResult`/`AuthorizationResult`) when acquisition
357
+ yields nothing usable, not for ordinary validation rules. An unusual application-owned explicit guard
358
+ policy may need a focused regression a plain call cannot prove, not a generic
359
+ race matrix. Report harness state gaps upstream rather than inventing guard doubles.
354
360
 
355
361
  ## Costs
356
362
 
@@ -164,7 +164,11 @@ degradations a reviewer can see without measuring:
164
164
  per-artifact decision table of `specs.scenarios.csharp.md` (pipeline and
165
165
  authorization, constraints, projection and reducer dispatch, reactor dispatch
166
166
  and routing) and none beyond it. A rule that must hold under concurrent
167
- writers is proven from supplied read-model state, not a race scenario.
167
+ writers is proven from supplied read-model state, not a race scenario
168
+ re-proving the platform matrix. For an unusual application-owned explicit
169
+ guard policy, accept only a focused regression a plain call cannot prove;
170
+ check the [decision guidance](../cratis-application-slice-specifications/references/query-and-decision-scenarios.md)
171
+ for the assembly-level admission check, body-read limits and advanced hook boundary.
168
172
  - Every State Change command has a happy-path specification.
169
173
  - Every validation rule has a direct-call failure spec. Pipeline validation
170
174
  specs assert **both** `ShouldNotBeSuccessful()` and `ShouldHaveValidationErrors()`.
@@ -90,22 +90,23 @@ before changing runner or package family.
90
90
  The plain `Specification` base is the universal foundation and the dominant mode
91
91
  in library and framework code. In applications, start pure decisions with a
92
92
  plain call, including direct validator calls, and add the scenarios the
93
- per-artifact decision table in `specs.scenarios.csharp.md` obligates. Keep shared lifecycle on; measure scenario cost using
94
- [running-specs.md](references/running-specs.md). Read
93
+ per-artifact decision table in `specs.scenarios.csharp.md` obligates. Keep shared lifecycle on; diagnose runner startup, lifecycle and scenario cost
94
+ before rewriting, using [running-specs.md](references/running-specs.md). Read
95
95
  [application-scenarios.md](references/application-scenarios.md) before using
96
96
  one. Out-of-process integration specifications are an advanced case reserved for
97
97
  boundaries the scenario helpers cannot reach — see
98
98
  [integration-specs.md](references/integration-specs.md).
99
99
 
100
- ⚠️ `EventScenario` wires a strategy that always answers `ConcurrencyScope.None`,
101
- which the validator skips, so an append that lets the strategy choose the scope
102
- never produces a concurrency violation. `ShouldHaveConcurrencyViolations()`
103
- cannot pass for such an append and its negation passes vacuously. Arc/Chronicle
104
- alone prove the platform concurrency, conflict-refusal and isolation matrix,
105
- with real-kernel integration where required. The application's only decision-read
106
- spec obligation is one cheap assembly-level shape-admission check from the
107
- [scenario rule](../../rules/specs.scenarios.csharp.md); business decisions take
108
- supplied state in direct `Handle()`/validator calls.
100
+ ⚠️ An unguarded in-process append using the default no-scope strategy is not
101
+ concurrency evidence: its no-conflict assertion can pass vacuously. This is not
102
+ a claim about every guarded scenario or explicit scope. Arc/Chronicle own the
103
+ platform concurrency/isolation matrix. Ordinary applications supply state in
104
+ plain `Handle()`/validator calls and keep one assembly-level admission check;
105
+ see the [scenario rule](../../rules/specs.scenarios.csharp.md). For an unusual
106
+ application-owned explicit guard policy, use only a focused regression that a
107
+ plain call cannot prove; read the
108
+ [decision guidance](../cratis-application-slice-specifications/references/query-and-decision-scenarios.md)
109
+ for admission limits and the advanced hook's boundary.
109
110
 
110
111
  For a class-based `ReactorScenario<TReactor>` on a recent Chronicle (Requires Chronicle 19.46.0), seed each
111
112
  handler read-model parameter with `Given.ForEventSourceId(id).ReadModel(instance)`
@@ -20,7 +20,8 @@ Check package versions and the actual configuration/TFM; the 4.x migration check
20
20
  below applies only when migrating, not as a prerequisite to running an existing suite.
21
21
 
22
22
  Sources: [Running specifications fast](https://github.com/Cratis/Specifications/blob/main/Documentation/running-fast.md),
23
- [The native runner](https://github.com/Cratis/Specifications/blob/main/Documentation/runner.md) and
23
+ [The native runner](https://github.com/Cratis/Specifications/blob/main/Documentation/runner.md),
24
+ [Phase timings](https://github.com/Cratis/Specifications/blob/main/Documentation/phase-timings.md) and
24
25
  [Upgrading to 5.0](https://github.com/Cratis/Specifications/blob/main/Documentation/upgrading-5.0.md).
25
26
 
26
27
  ## Project shape
@@ -44,9 +45,10 @@ is a worked example, including the CI step that runs the built executable.
44
45
 
45
46
  ## Local loop
46
47
 
47
- An xUnit v3 suite costs about 4.5 times more CPU through `dotnet test` than as the
48
- built executable (indicative, from the upstream benchmark). Restore and build once,
49
- then run the executable:
48
+ In the upstream reported benchmark of 1,500 trivial tests on a loaded Mac, an
49
+ xUnit v3 suite used about 4.5 times more CPU through `dotnet test` than as the
50
+ built executable. This is a measurement, not a universal ratio. Restore and build
51
+ once, then run the executable:
50
52
 
51
53
  ```bash
52
54
  dotnet restore Source/MyProject.Specs
@@ -84,6 +86,62 @@ versions, configuration, filters, concurrency/shards and machine fixed; preserve
84
86
  discovered/passed/failed/skipped counts and investigate any change. Do not count
85
87
  restore/build time as test execution or repeat unchanged runs merely for reassurance.
86
88
 
89
+ ### Diagnose before changing the harness
90
+
91
+ Measure the existing suite before a rewrite. Separate restore/build, runner
92
+ startup/discovery and reporting from specification execution. Phase timings do
93
+ not measure total process startup or discovery; compare launch wall time separately.
94
+ For repeated local runs, use the built executable rather than repeatedly invoking
95
+ `dotnet test`/MSBuild. Keep the evaluated runner and its supported flags.
96
+
97
+ Enable phase diagnostics without changing pass/fail behavior. This example assumes
98
+ the Release/net10.0 executable built above and runs from the repository root:
99
+
100
+ ```bash
101
+ mkdir -p .ai-work/spec-timings
102
+ CRATIS_SPECS_TIMINGS=1 CRATIS_SPECS_TIMINGS_FILE="$PWD/.ai-work/spec-timings/phases.json" \
103
+ ./Source/MyProject.Specs/bin/Release/net10.0/MyProject.Specs
104
+ ```
105
+
106
+ Alternatively, set `<CratisSpecificationsPhaseTimings>true</CratisSpecificationsPhaseTimings>`
107
+ in the project. Slow phases default to a 1,000 ms threshold; set
108
+ `<CratisSpecificationsSlowPhaseThreshold>500</CratisSpecificationsSlowPhaseThreshold>`
109
+ for a 500 ms diagnostic threshold, not a performance budget. The JSON file records
110
+ `Establish`, `Because` and `Destroy` durations; native-runner output also records
111
+ facts. Other frameworks time facts through their own runner output. Timings are
112
+ off by default, additive when enabled, and never change whether a spec passes.
113
+
114
+ | Cost observed | Next check |
115
+ | --- | --- |
116
+ | Restore/build | Keep it outside the execution comparison; restore/build once for the local loop. |
117
+ | Runner startup/discovery | Compare the built executable's launch path, not just fact durations. |
118
+ | Repeated `Establish`/`Because` | Check shared lifecycle eligibility and opt-outs before changing packages. |
119
+ | Scenario setup/action | Identify pipeline, mapping or append-time proof a plain call cannot provide. |
120
+ | Slow fact | Keep assertions read-only; inspect the measured operation rather than adding sleeps. |
121
+ | `Destroy` | Measure disposal/cleanup separately from setup and action. |
122
+
123
+ Specifications 5 shares eligible xUnit v2/v3 lifecycle by default. `Establish` and
124
+ `Because` run once per class; facts only read that shared context. Repeating a
125
+ 200 ms `Because` across five facts costs about 1 s instead of about 200 ms in
126
+ this illustrative calculation, before other costs. Remove accidental opt-outs
127
+ rather than weakening assertions; retain `[PerFactSpecificationLifecycle]` only
128
+ where mutation genuinely cannot move into `Because`.
129
+
130
+ Record a before/after comparison, not a claimed universal timing:
131
+
132
+ | Field | Keep or report |
133
+ | --- | --- |
134
+ | Environment | Machine, package versions, configuration/TFM, launch command, filters and unchanged concurrency/shards. |
135
+ | Coverage | Discovered, passed, failed and skipped counts plus the class/method list; investigate any difference. |
136
+ | Execution | Suite wall time, class totals and phase/fact durations in separate result files. |
137
+ | Change | Name the removed repeated cost or the extra framework proof that justifies scenario cost. |
138
+
139
+ Do not merge unrelated behaviors, remove facts or turn off production guards to
140
+ meet a timing target. One class per declarative read model remains the default:
141
+ share a meaningful event sequence, capture intermediate states and assert them
142
+ with many read-only facts; add a class only for a sequence that cannot share it.
143
+ A slow mandatory scenario is an upstream harness gap, not permission to drop proof.
144
+
87
145
  ## Filters
88
146
 
89
147
  The executable accepts the filters of the xUnit v3 runner flavor the project
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cratis/pi",
3
- "version": "7.175.0",
3
+ "version": "7.176.1",
4
4
  "description": "Configuration-aware Cratis AI integration for Pi",
5
5
  "type": "module",
6
6
  "files": [