@cratis/pi 8.5.0 → 8.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (217) hide show
  1. package/package/corpus/harnesses/copilot/instructions/glossary.instructions.md +5 -3
  2. package/package/corpus/harnesses/copilot/instructions/react.instructions.md +3 -1
  3. package/package/corpus/harnesses/copilot/instructions/reactors.instructions.md +3 -1
  4. package/package/corpus/harnesses/copilot/instructions/specs.csharp.instructions.md +6 -3
  5. package/package/corpus/harnesses/copilot/instructions/vertical-slices.instructions.md +5 -2
  6. package/package/corpus/rules/glossary.md +5 -3
  7. package/package/corpus/rules/react.md +3 -1
  8. package/package/corpus/rules/reactors.md +3 -1
  9. package/package/corpus/rules/specs.csharp.md +6 -3
  10. package/package/corpus/rules/vertical-slices.md +5 -2
  11. package/package/corpus/skills/cratis-application-growth/SKILL.md +1 -2
  12. package/package/corpus/skills/cratis-application-growth/references/csharp.md +0 -2
  13. package/package/corpus/skills/cratis-application-growth/references/move-and-untangle.md +1 -2
  14. package/package/corpus/skills/cratis-application-growth/references/rename-window.md +1 -3
  15. package/package/corpus/skills/cratis-application-growth/references/service-and-delivery.md +3 -2
  16. package/package/corpus/skills/cratis-application-growth/references/stages.md +2 -2
  17. package/package/corpus/skills/cratis-arc-authorize-request/SKILL.md +2 -2
  18. package/package/corpus/skills/cratis-arc-authorize-request/references/authproxy.md +19 -0
  19. package/package/corpus/skills/cratis-arc-authorize-request/references/csharp-query-security.md +15 -0
  20. package/package/corpus/skills/cratis-arc-authorize-request/references/csharp.md +12 -3
  21. package/package/corpus/skills/cratis-arc-declare-command/SKILL.md +2 -0
  22. package/package/corpus/skills/cratis-arc-declare-command/references/csharp-chronicle.md +46 -7
  23. package/package/corpus/skills/cratis-arc-declare-command/references/csharp-controller.md +3 -1
  24. package/package/corpus/skills/cratis-arc-declare-command/references/csharp-history.md +4 -1
  25. package/package/corpus/skills/cratis-arc-declare-command/references/csharp.md +31 -4
  26. package/package/corpus/skills/cratis-arc-declare-command/references/go.md +1 -1
  27. package/package/corpus/skills/cratis-arc-diagnose-live-query/references/csharp.md +24 -2
  28. package/package/corpus/skills/cratis-arc-expose-mcp-operation/references/csharp.md +49 -0
  29. package/package/corpus/skills/cratis-arc-expose-query/SKILL.md +3 -1
  30. package/package/corpus/skills/cratis-arc-expose-query/references/csharp.md +27 -4
  31. package/package/corpus/skills/cratis-arc-generate-proxies/SKILL.md +1 -0
  32. package/package/corpus/skills/cratis-arc-generate-proxies/references/csharp.md +49 -2
  33. package/package/corpus/skills/cratis-arc-generate-proxies/references/typescript.md +9 -0
  34. package/package/corpus/skills/cratis-arc-host-application/SKILL.md +1 -1
  35. package/package/corpus/skills/cratis-arc-host-application/references/csharp-configuration.md +54 -0
  36. package/package/corpus/skills/cratis-arc-host-application/references/csharp-deployment.md +98 -0
  37. package/package/corpus/skills/cratis-arc-host-application/references/csharp-http.md +9 -1
  38. package/package/corpus/skills/cratis-arc-host-application/references/csharp-identity.md +84 -2
  39. package/package/corpus/skills/cratis-arc-host-application/references/csharp.md +2 -0
  40. package/package/corpus/skills/cratis-arc-invoke-command/references/csharp.md +2 -1
  41. package/package/corpus/skills/cratis-arc-isolate-tenant/SKILL.md +18 -1
  42. package/package/corpus/skills/cratis-arc-page-query/references/csharp.md +2 -0
  43. package/package/corpus/skills/cratis-arc-react-bind-slice/SKILL.md +18 -16
  44. package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript-commands.md +8 -3
  45. package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript-host.md +84 -16
  46. package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript-identity.md +22 -2
  47. package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript-instant-feedback.md +81 -0
  48. package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript-localization.md +80 -0
  49. package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript-navigation.md +103 -0
  50. package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript-queries.md +40 -1
  51. package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript-structure.md +117 -0
  52. package/package/corpus/skills/cratis-arc-react-bind-slice/references/typescript.md +7 -3
  53. package/package/corpus/skills/cratis-arc-react-separate-view-model/SKILL.md +3 -3
  54. package/package/corpus/skills/cratis-arc-react-separate-view-model/references/typescript.md +27 -6
  55. package/package/corpus/skills/cratis-arc-validate-command/references/csharp-rules.md +23 -2
  56. package/package/corpus/skills/cratis-arc-validate-command/references/csharp.md +28 -2
  57. package/package/corpus/skills/cratis-authproxy-configure/SKILL.md +136 -0
  58. package/package/corpus/skills/cratis-authproxy-configure/references/admission.md +125 -0
  59. package/package/corpus/skills/cratis-authproxy-configure/references/aspire.md +154 -0
  60. package/package/corpus/skills/cratis-authproxy-configure/references/operations.md +122 -0
  61. package/package/corpus/skills/cratis-authproxy-configure/references/services-and-routing.md +114 -0
  62. package/package/corpus/skills/cratis-authproxy-configure/references/sessions-and-logout.md +126 -0
  63. package/package/corpus/skills/cratis-authproxy-configure/references/sign-in-providers.md +116 -0
  64. package/package/corpus/skills/cratis-authproxy-configure/references/tenant-resolution.md +135 -0
  65. package/package/corpus/skills/cratis-choreography-run-workflow/SKILL.md +117 -0
  66. package/package/corpus/skills/cratis-choreography-run-workflow/references/csharp-chronicle.md +164 -0
  67. package/package/corpus/skills/cratis-choreography-run-workflow/references/csharp.md +354 -0
  68. package/package/corpus/skills/cratis-chronicle-cli-operations/SKILL.md +2 -2
  69. package/package/corpus/skills/cratis-chronicle-cli-operations/references/project-tooling.md +28 -0
  70. package/package/corpus/skills/cratis-chronicle-connect-application/references/csharp-services.md +13 -2
  71. package/package/corpus/skills/cratis-chronicle-connect-application/references/csharp.md +12 -0
  72. package/package/corpus/skills/cratis-chronicle-connect-application/references/kotlin.md +2 -0
  73. package/package/corpus/skills/cratis-chronicle-connect-application/references/typescript.md +10 -1
  74. package/package/corpus/skills/cratis-chronicle-constrain-append/SKILL.md +8 -1
  75. package/package/corpus/skills/cratis-chronicle-constrain-append/references/csharp.md +35 -3
  76. package/package/corpus/skills/cratis-chronicle-constrain-append/references/go.md +1 -1
  77. package/package/corpus/skills/cratis-chronicle-constrain-append/references/operations.md +70 -0
  78. package/package/corpus/skills/cratis-chronicle-deploy-kernel/SKILL.md +2 -0
  79. package/package/corpus/skills/cratis-chronicle-deploy-kernel/references/configuration.md +27 -0
  80. package/package/corpus/skills/cratis-chronicle-deploy-kernel/references/container-and-kubernetes.md +293 -0
  81. package/package/corpus/skills/cratis-chronicle-deploy-kernel/references/kernel-options.md +13 -6
  82. package/package/corpus/skills/cratis-chronicle-deploy-kernel/references/network-and-tls.md +45 -0
  83. package/package/corpus/skills/cratis-chronicle-deploy-kernel/references/storage.md +91 -1
  84. package/package/corpus/skills/cratis-chronicle-deploy-kernel/references/upgrade-and-recovery.md +9 -0
  85. package/package/corpus/skills/cratis-chronicle-evolve-event/SKILL.md +12 -0
  86. package/package/corpus/skills/cratis-chronicle-inspect-observer/SKILL.md +11 -1
  87. package/package/corpus/skills/cratis-chronicle-inspect-observer/references/csharp.md +1 -1
  88. package/package/corpus/skills/cratis-chronicle-project-view/SKILL.md +1 -1
  89. package/package/corpus/skills/cratis-chronicle-project-view/references/csharp-fluent.md +14 -3
  90. package/package/corpus/skills/cratis-chronicle-project-view/references/csharp-model-bound.md +3 -0
  91. package/package/corpus/skills/cratis-chronicle-project-view/references/csharp-reading.md +3 -2
  92. package/package/corpus/skills/cratis-chronicle-project-view/references/csharp.md +23 -0
  93. package/package/corpus/skills/cratis-chronicle-project-view/references/elixir.md +1 -0
  94. package/package/corpus/skills/cratis-chronicle-project-view/references/go.md +2 -1
  95. package/package/corpus/skills/cratis-chronicle-project-view/references/java.md +2 -0
  96. package/package/corpus/skills/cratis-chronicle-project-view/references/kotlin.md +1 -0
  97. package/package/corpus/skills/cratis-chronicle-project-view/references/typescript.md +1 -1
  98. package/package/corpus/skills/cratis-chronicle-protect-decision/SKILL.md +2 -0
  99. package/package/corpus/skills/cratis-chronicle-protect-decision/references/csharp-scopes.md +40 -3
  100. package/package/corpus/skills/cratis-chronicle-protect-decision/references/csharp.md +20 -2
  101. package/package/corpus/skills/cratis-chronicle-protect-decision/references/elixir.md +7 -0
  102. package/package/corpus/skills/cratis-chronicle-protect-decision/references/go.md +9 -1
  103. package/package/corpus/skills/cratis-chronicle-protect-decision/references/java.md +8 -0
  104. package/package/corpus/skills/cratis-chronicle-protect-decision/references/kotlin.md +9 -0
  105. package/package/corpus/skills/cratis-chronicle-protect-decision/references/typescript.md +7 -0
  106. package/package/corpus/skills/cratis-chronicle-protect-personal-data/references/csharp.md +24 -1
  107. package/package/corpus/skills/cratis-chronicle-publish-contract/SKILL.md +1 -1
  108. package/package/corpus/skills/cratis-chronicle-publish-contract/references/csharp.md +41 -0
  109. package/package/corpus/skills/cratis-chronicle-publish-contract/references/webhook-signature-wire-format.md +82 -0
  110. package/package/corpus/skills/cratis-chronicle-react-to-fact/SKILL.md +17 -0
  111. package/package/corpus/skills/cratis-chronicle-react-to-fact/references/csharp-outputs.md +3 -1
  112. package/package/corpus/skills/cratis-chronicle-react-to-fact/references/csharp.md +35 -2
  113. package/package/corpus/skills/cratis-chronicle-react-to-fact/references/elixir.md +11 -0
  114. package/package/corpus/skills/cratis-chronicle-react-to-fact/references/java.md +1 -0
  115. package/package/corpus/skills/cratis-chronicle-react-to-fact/references/kotlin.md +1 -0
  116. package/package/corpus/skills/cratis-chronicle-record-event/SKILL.md +1 -1
  117. package/package/corpus/skills/cratis-chronicle-record-event/references/csharp-coordination.md +31 -2
  118. package/package/corpus/skills/cratis-chronicle-record-event/references/csharp-history.md +21 -4
  119. package/package/corpus/skills/cratis-chronicle-record-event/references/csharp.md +20 -2
  120. package/package/corpus/skills/cratis-chronicle-record-event/references/go.md +1 -1
  121. package/package/corpus/skills/cratis-chronicle-record-event/references/java.md +1 -1
  122. package/package/corpus/skills/cratis-chronicle-record-event/references/kotlin.md +3 -0
  123. package/package/corpus/skills/cratis-chronicle-reduce-state/SKILL.md +2 -1
  124. package/package/corpus/skills/cratis-chronicle-reduce-state/references/csharp.md +3 -1
  125. package/package/corpus/skills/cratis-chronicle-reduce-state/references/java.md +10 -1
  126. package/package/corpus/skills/cratis-chronicle-reduce-state/references/kotlin.md +10 -1
  127. package/package/corpus/skills/cratis-chronicle-reduce-state/references/typescript.md +27 -5
  128. package/package/corpus/skills/cratis-chronicle-select-client/SKILL.md +18 -0
  129. package/package/corpus/skills/cratis-chronicle-select-client/references/elixir.md +21 -1
  130. package/package/corpus/skills/cratis-chronicle-select-client/references/go.md +13 -0
  131. package/package/corpus/skills/cratis-chronicle-select-client/references/java.md +15 -0
  132. package/package/corpus/skills/cratis-chronicle-select-client/references/kotlin.md +15 -0
  133. package/package/corpus/skills/cratis-chronicle-select-client/references/typescript.md +16 -0
  134. package/package/corpus/skills/cratis-code-review/references/csharp-diagnostics.md +28 -2
  135. package/package/corpus/skills/cratis-code-review/references/csharp.md +1 -1
  136. package/package/corpus/skills/cratis-components-accessibility/SKILL.md +6 -8
  137. package/package/corpus/skills/cratis-components-accessibility/references/typescript.md +32 -14
  138. package/package/corpus/skills/cratis-components-build-canvas/SKILL.md +4 -3
  139. package/package/corpus/skills/cratis-components-build-canvas/references/typescript-props.md +1 -1
  140. package/package/corpus/skills/cratis-components-build-canvas/references/typescript.md +4 -2
  141. package/package/corpus/skills/cratis-components-choose-control/SKILL.md +13 -7
  142. package/package/corpus/skills/cratis-components-choose-control/references/from-primereact.md +116 -0
  143. package/package/corpus/skills/cratis-components-choose-control/references/menu.md +90 -0
  144. package/package/corpus/skills/cratis-components-choose-control/references/typescript-composition.md +48 -0
  145. package/package/corpus/skills/cratis-components-choose-control/references/typescript.md +2 -2
  146. package/package/corpus/skills/cratis-components-compose-toolbar/SKILL.md +2 -1
  147. package/package/corpus/skills/cratis-components-compose-toolbar/references/floating-toolbar.md +146 -0
  148. package/package/corpus/skills/cratis-components-diagnose-screen/SKILL.md +102 -0
  149. package/package/corpus/skills/cratis-components-display-list/SKILL.md +10 -10
  150. package/package/corpus/skills/cratis-components-display-list/references/typescript-custom-panel.md +74 -0
  151. package/package/corpus/skills/cratis-components-display-list/references/typescript-datatables.md +2 -7
  152. package/package/corpus/skills/cratis-components-display-list/references/typescript.md +3 -2
  153. package/package/corpus/skills/cratis-components-submit-form/references/typescript-commandform.md +72 -2
  154. package/package/corpus/skills/cratis-components-submit-form/references/typescript.md +5 -3
  155. package/package/corpus/skills/cratis-components-theme-application/SKILL.md +17 -15
  156. package/package/corpus/skills/cratis-components-theme-application/references/localization.md +166 -0
  157. package/package/corpus/skills/cratis-components-theme-application/references/typescript.md +18 -14
  158. package/package/corpus/skills/cratis-components-theme-application/references/upgrade-from-previous-major.md +141 -0
  159. package/package/corpus/skills/cratis-engineering-csharp-conventions/SKILL.md +2 -0
  160. package/package/corpus/skills/cratis-engineering-csharp-conventions/references/csharp-domain-philosophy.md +31 -3
  161. package/package/corpus/skills/cratis-engineering-csharp-conventions/references/csharp-fundamentals-helpers.md +119 -0
  162. package/package/corpus/skills/cratis-engineering-csharp-conventions/references/csharp.md +4 -0
  163. package/package/corpus/skills/cratis-fundamentals-concept/references/csharp-serialization.md +70 -0
  164. package/package/corpus/skills/cratis-fundamentals-concept/references/csharp.md +8 -0
  165. package/package/corpus/skills/cratis-fundamentals-concept/references/go.md +1 -0
  166. package/package/corpus/skills/cratis-fundamentals-concept/references/typescript-serialization.md +33 -0
  167. package/package/corpus/skills/cratis-fundamentals-name-value/references/csharp.md +2 -1
  168. package/package/corpus/skills/cratis-fundamentals-type-discovery/references/csharp-diagnostics.md +5 -0
  169. package/package/corpus/skills/cratis-fundamentals-type-discovery/references/go-dependency-injection.md +3 -0
  170. package/package/corpus/skills/cratis-modeling-design-event-model/SKILL.md +6 -4
  171. package/package/corpus/skills/cratis-modeling-design-event-model/references/command-inventory.md +7 -1
  172. package/package/corpus/skills/cratis-modeling-design-event-model/references/model-first.md +13 -1
  173. package/package/corpus/skills/cratis-modeling-design-event-model/references/review-one-slice.md +6 -0
  174. package/package/corpus/skills/cratis-multi-service-local-orchestration/SKILL.md +6 -6
  175. package/package/corpus/skills/cratis-multi-service-local-orchestration/references/csharp-aspire.md +116 -28
  176. package/package/corpus/skills/cratis-multi-service-local-orchestration/references/docker-compose.md +2 -2
  177. package/package/corpus/skills/cratis-observability/references/chronicle-kernel-export.md +46 -0
  178. package/package/corpus/skills/cratis-orleans-jobs/SKILL.md +4 -2
  179. package/package/corpus/skills/cratis-platform-build-application/SKILL.md +8 -0
  180. package/package/corpus/skills/cratis-platform-build-application/references/cratis-identity.md +71 -0
  181. package/package/corpus/skills/cratis-platform-build-application/references/studio-repository.md +96 -0
  182. package/package/corpus/skills/cratis-platform-deliver-slice/SKILL.md +14 -8
  183. package/package/corpus/skills/cratis-platform-deliver-slice/references/csharp.md +167 -3
  184. package/package/corpus/skills/cratis-platform-deliver-slice/references/eventual-consistency.md +150 -0
  185. package/package/corpus/skills/cratis-platform-diagnose-slice/SKILL.md +1 -1
  186. package/package/corpus/skills/cratis-platform-start-application/SKILL.md +21 -0
  187. package/package/corpus/skills/cratis-platform-start-application/references/csharp.md +77 -3
  188. package/package/corpus/skills/cratis-platform-upgrade-application/SKILL.md +118 -0
  189. package/package/corpus/skills/cratis-platform-upgrade-application/references/csharp.md +117 -0
  190. package/package/corpus/skills/cratis-platform-upgrade-application/references/java.md +53 -0
  191. package/package/corpus/skills/cratis-platform-upgrade-application/references/kotlin.md +53 -0
  192. package/package/corpus/skills/cratis-platform-upgrade-application/references/typescript.md +71 -0
  193. package/package/corpus/skills/cratis-screenplay-accept-model/references/csharp.md +29 -0
  194. package/package/corpus/skills/cratis-screenplay-accept-model/references/read-the-evidence.md +82 -1
  195. package/package/corpus/skills/cratis-screenplay-declare-slice/SKILL.md +1 -1
  196. package/package/corpus/skills/cratis-screenplay-declare-slice/references/structure-and-imports.md +10 -0
  197. package/package/corpus/skills/cratis-screenplay-onboard-workspace/SKILL.md +5 -4
  198. package/package/corpus/skills/cratis-screenplay-onboard-workspace/references/cli.md +19 -2
  199. package/package/corpus/skills/cratis-screenplay-onboard-workspace/references/smallest-model.md +87 -0
  200. package/package/corpus/skills/cratis-screenplay-onboard-workspace/references/typescript.md +13 -0
  201. package/package/corpus/skills/cratis-screenplay-onboard-workspace/references/workspace-mcp.md +5 -0
  202. package/package/corpus/skills/cratis-specifications-exercise-backend/SKILL.md +2 -0
  203. package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-colocated.md +101 -0
  204. package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-command-results.md +3 -1
  205. package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-decision-reads.md +1 -0
  206. package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-events.md +1 -0
  207. package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-integration.md +4 -2
  208. package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-reactors.md +3 -3
  209. package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp.md +34 -1
  210. package/package/corpus/skills/cratis-specifications-exercise-backend/references/elixir.md +2 -0
  211. package/package/corpus/skills/cratis-specifications-isolate-behavior/SKILL.md +1 -1
  212. package/package/corpus/skills/cratis-specifications-isolate-behavior/references/csharp-running.md +10 -3
  213. package/package/corpus/skills/cratis-specifications-test-application-ui/references/typescript.md +22 -4
  214. package/package/corpus/skills/cratis-specifications-test-typescript-behavior/SKILL.md +2 -1
  215. package/package/corpus/skills/cratis-specifications-test-typescript-behavior/references/typescript.md +40 -0
  216. package/package/profile-catalog.json +15 -0
  217. package/package.json +1 -1
@@ -6,6 +6,7 @@
6
6
  - Which event source receives the events
7
7
  - Refuse without recording
8
8
  - Events for another event source
9
+ - Transaction boundary
9
10
  - Stream routing and completion
10
11
  - Server-allocated identity
11
12
  - Subject and tags
@@ -60,8 +61,8 @@ public record OpenAccount(OwnerName Owner)
60
61
  | `Handle` returns | What Chronicle does |
61
62
  | --- | --- |
62
63
  | An `[EventType]` event | Appended to the command's event source. |
63
- | `IEnumerable<object>` of events | Each appended in order, atomically. |
64
- | `EventForEventSourceId`, or a collection of them | Appended to the ID each value carries. |
64
+ | `IEnumerable<object>` of events | Appended atomically. Order is kept per event source, not across sources ("Events for another event source" below). |
65
+ | `EventForEventSourceId`, or a collection of them | Appended atomically to the ID each value carries, in order per event source. |
65
66
  | `EventsWithConcurrencyScopes` | Ordered cross-source events with exact, labelled concurrency scopes. |
66
67
  | Tuple `(event, value)` | The event is appended; the value becomes the response. |
67
68
  | Tuple containing an `EventSourceId` and an event | The ID selects the event source and becomes the response. |
@@ -70,12 +71,14 @@ public record OpenAccount(OwnerName Owner)
70
71
  | `CompleteStream` | Closes a non-default stream after the events commit. |
71
72
  | `Result<TEvent, ValidationResult>` | The event is appended, or the blocking validation result refuses the command and rolls back the pending events. |
72
73
 
73
- Returned events commit together and roll back together. An immediate event-log append, an explicit early commit and an external service call are outside that boundary.
74
+ Which of these to pick, next to the returns that record nothing, is in "What `Handle` may return" in `references/csharp.md`.
75
+
76
+ Returned events commit together and roll back together. An immediate event-log append, an explicit early commit and an external service call are outside that boundary; see "Transaction boundary" below.
74
77
 
75
78
  ## Which event source receives the events
76
79
 
77
80
  1. `ICanProvideEventSourceId.GetEventSourceId()` wins.
78
- 2. Otherwise the first public property that is an `EventSourceId`, derives from `EventSourceId<T>`, or carries Chronicle's `[Key]` (`Cratis.Chronicle.Keys`). The typed and attributed forms have equal priority and never form a composite: declare exactly one candidate.
81
+ 2. Otherwise the first public property that is an `EventSourceId`, derives from `EventSourceId<T>`, or carries Chronicle's `[Key]` (`Cratis.Chronicle.Keys`). The typed and attributed forms have equal priority and never form a composite: declare exactly one candidate. On a positional record, Chronicle's `[Key]` may sit on the parameter.
79
82
  3. With no candidate Arc generates a new identity, which suits creation only.
80
83
 
81
84
  The default is an identity concept deriving from `EventSourceId<T>`, shared by the command, the events and the read models. A property named `Id` alone selects nothing. Chronicle's `[Key]` selects the event source; `[Key]` from `System.ComponentModel.DataAnnotations` selects only the Arc command key.
@@ -94,10 +97,16 @@ public record TransferFunds(AccountId From, AccountId To, Amount Amount) : ICanP
94
97
 
95
98
  A returned `EventSourceId` addresses the returned events and becomes the response, but it arrives after dependencies were loaded: it never reloads a read model or retargets an aggregate. A returned raw `Guid` is only a response.
96
99
 
100
+ An identity created inside `Handle`, such as `new AccountId(Guid.NewGuid())`, is not a generated value and is not guarded: when the source already holds events, the returned events extend that history. When creation must refuse an occupied source, take the identity as a `[GeneratedValue]` parameter ("Server-allocated identity" below).
101
+
102
+ Queries never use this resolution. A query argument is bound by name, and Chronicle's `[Key]` on it selects nothing: filter by the argument explicitly.
103
+
97
104
  ## Refuse without recording
98
105
 
99
106
  A business rule decided in `Handle` returns `Result<TEvent, ValidationResult>` (`Cratis.Monads`, `Cratis.Arc.Validation`): the event, or a failure. Never return a nullable event or an empty collection, since returning no events does not fail the command, and do not move a decision that needs loaded state into a validator class.
100
107
 
108
+ A single `ValidationResult` is the business refusal; give it error severity when the return also carries an operation, where a result below the command's blocking severity does not refuse (an unauthorized `AuthorizationResult` refuses as unauthorized). An error DTO as the other `Result` alternative is response data: the command succeeds, and events already pending in its transaction commit.
109
+
101
110
  ```csharp
102
111
  [Command]
103
112
  public record WithdrawFunds(AccountId AccountId, Amount Amount)
@@ -123,6 +132,29 @@ public IEnumerable<EventForEventSourceId> Handle() =>
123
132
 
124
133
  `EventForEventSourceId` is in `Cratis.Chronicle.EventSequences`. Use it only when an event belongs to a different source than the command's own.
125
134
 
135
+ - **Order.** The values commit atomically, grouped by event source: returned as `A1, B1, A2`, they can commit as `A1, A2, B1`. When the order across sources matters, return `EventsWithConcurrencyScopes`.
136
+ - **Occurrence time.** Set `Occurred` on the value to record when a fact happened, for an import or a backfill: `new(AccountId, new FundsDeposited(From, Amount)) { Occurred = creditedAt }`. Left unset, the event carries the append time.
137
+
138
+ ## Transaction boundary
139
+
140
+ One top-level command is one transaction: Arc starts it before `Handle` runs, enrolls the returned events, and commits or rolls back on the command's result. This holds for a model-bound command over HTTP, one executed through `ICommandPipeline`, one returned by a reactor and one run in a `CommandScenario`. Keep one transaction within one event store, namespace and event sequence. Return events and let Arc commit; that is the default.
141
+
142
+ | Situation | What happens |
143
+ | --- | --- |
144
+ | A command executed from inside another command's `Handle` | It joins the outer transaction, and its returned events commit only when the outer command does. An aggregate the nested command commits explicitly is different: it can commit the shared transaction at once, and a later failure of the outer command cannot then undo it. Do not commit an aggregate inside a nested command. Its successful result means "enrolled", not "committed". Inspect the nested result and propagate a failure, or the outer command commits despite it. Not when either command's `Handle` can return an operation: the nested command is then rejected with `InvalidCommandOperation` before it runs. |
145
+ | Several commands returned by one reactor | Separate transactions: earlier ones stay committed when a later one fails. Return one command when the events must commit together. |
146
+ | A command executed through `ICommandPipeline` from a controller action | Its own transaction, committed when `Execute` returns. A later failure of the action does not undo it. The action's own transactional appends commit when the action ends. |
147
+ | A POST controller action as the command | It has a transaction (not with `[AspNetResult]`), but no read protection and no `[GeneratedValue]` parameters. |
148
+ | Chronicle's request-level unit-of-work middleware | A different boundary. A command starts its own transaction and never joins it. |
149
+
150
+ Appending by hand inside `Handle`, when returning the event is not possible:
151
+
152
+ - `eventLog.Transactional.Append(...)` stages the event in the command's transaction. Awaiting it reports no append outcome, and it throws when no transaction is active.
153
+ - A plain `eventLog.Append(...)` persists at once and is never rolled back; a failed one also fails the command when the append went to the command's own event log and belongs to that command. A failed append to another event store, namespace or event sequence is not observed, so check its result yourself. Under read protection `On` it is refused with `ImmediateAppendWhileReadsAreProtected`.
154
+ - A read of the event log inside `Handle` sees persisted events only, never the ones still staged.
155
+
156
+ Anti-pattern: starting work in `Handle` that outlives the command (fire-and-forget, an unawaited continuation). Events it stages after the command completed can be discarded. Await the work, or move it to a reactor.
157
+
126
158
  ## Stream routing and completion
127
159
 
128
160
  Source identity, stream selection and concurrency are separate decisions. Add stream metadata only when one source needs separate routes.
@@ -147,7 +179,7 @@ Template parts format strings unchanged, enums by name, `DateOnly` as `yyyy-MM-d
147
179
 
148
180
  To compute the same ID outside the pipeline (a read endpoint, a seed, a spec), call `EventStreamIdTemplate.ResolveFor(command)` (`Cratis.Arc.Chronicle.Commands`) instead of repeating the join. It resolves the attribute or the provider interface exactly as the pipeline does and returns null when neither declares an ID; `EventStreamIdTemplate.Resolve(template, command)` resolves a given template.
149
181
 
150
- `concurrency: true` on `[EventSourceType]`, `[EventStreamType]` or `[EventStreamId]` adds that dimension to the concurrency scope Arc declares, always together with the target event source ID. On a command routed with `[EventSource<TSource>]`, any such flag replaces the definition's declared dimensions for that command. Without any flag, the default optimistic check still narrows by the routing metadata, and flagging only some attributes can widen the check compared with that default. Neither guards a decision that read state; for that use a stream decision (below) or `cratis-chronicle-protect-decision`.
182
+ `concurrency: true` on `[EventSourceType]`, `[EventStreamType]` or `[EventStreamId]` adds that dimension to the concurrency scope Arc declares, always together with the target event source ID. On a command routed with `[EventSource<TSource>]`, any such flag replaces the definition's declared dimensions for that command. Without any flag, the default optimistic check still narrows by the routing metadata, and flagging only some attributes can widen the check compared with that default. Without read protection `On`, Arc captures a flagged scope after `Handle` returns, while it processes the response; the unflagged default is captured at commit for an event written through an event source definition. When a returned event's own routing replaces the command's definition with string routing, Arc captures that event's default scope while it processes the response as well. Under read protection `On`, Arc only stages the declared dimensions with the events, and Chronicle resolves the scope at commit. Neither reflects what the handler read, so neither guards a decision that read state; for that use a stream decision (below) or `cratis-chronicle-protect-decision`.
151
183
 
152
184
  Per-event routing overrides the command for one event: `new EventForEventSourceId(id, fact) { EventStream = "Archive" }` selects another stream on the command's definition; setting `EventSource = typeof(OtherDefinition)` selects another definition and its own stream. Neither changes the route used to load command dependencies.
153
185
 
@@ -178,13 +210,20 @@ The generated identity is guarded: the whole event source has to be empty when r
178
210
 
179
211
  Use `ICanProvideSubject.GetSubject()` on the command for a compliance identity known before handling, or return `(fact, new Subject(customerId.ToString()))` when the decision supplies it. The subject need not own the event source.
180
212
 
181
- - `[EventTag("account", nameof(AccountId))]` tags from an input; `[EventTag("origin", Value = "import")]` adds a constant.
213
+ - A command property typed `Subject`, or one marked `[Subject]` (`Cratis.Chronicle`, converted with `ToString()`), also declares the subject without code. A typed and a marked property have equal priority, so declare exactly one; `ICanProvideSubject` wins over both.
214
+ - A returned `Subject` overrides the command's subject for the returned events only. It arrives after validators, `Provide` and the `Handle` dependencies were resolved, so set the subject on the command when they need it.
215
+ - Aggregate `Apply` does not forward the command's subject, declared or returned. Events applied by an aggregate take their subject from the event's own subject metadata, falling back to the event source ID.
216
+
217
+ - `[EventTag("account", nameof(AccountId))]` tags from an input; `[EventTag("origin", Value = "import")]` adds a constant. Give each attribute a property name or `Value`, never both and never neither (`AmbiguousEventTagValue`). A property that does not exist or is not public and readable fails with `UnknownEventTagProperty`, a null value with `EventTagValueMissing`; an empty string is a valid tag value. A concept contributes the value it wraps.
182
218
  - For computed tags implement `ICanProvideEventTags.GetEventTags()` on the command, e.g. `=> [new NamedTag("channel", Channel)]`. For a convention shared across commands implement `ICanProvideCommandEventTags.GetEventTags(object command)` on a discovered service; return an empty sequence when not applicable. `[EventTag]`, `ICanProvideEventTags`, `ICanProvideCommandEventTags` and `EventTags` live in `Cratis.Arc.Chronicle.Commands`; `NamedTag` lives in `Cratis.Chronicle`.
183
219
  - Arc discovers command tag providers by convention and resolves them from the command's service scope, so they may inject scoped tenant or user services. Keep them transient or scoped; a singleton must not capture request values. They run once per command at the first returned-event append, after authorization and validation, and never for validation-only calls or commands that return no events.
184
220
  - Every command tag source (attributes, `ICanProvideEventTags`, providers, returned `EventTags`) applies only to events the handler returns. Aggregate-root commits and events appended directly to an event log or sequence get none of them; a direct append must pass its own named tags.
185
221
  - Return `(fact, new EventTags(new NamedTag("batch", batchId)))` to tag all returned events after handling. Set `NamedTags = [new NamedTag("leg", "credit")]` on an `EventForEventSourceId` to tag only that event. Arc merges by name/value pair at append, not during preflight.
222
+ - In pipeline extension code, `commandContext.GetEventTags()` reads only the tags the handler returned; `commandContext.ResolveEventTags()` resolves the combined set. A replacement event sequence or unit of work has to support named tags: one that does not fails the tagged append instead of dropping the tags.
186
223
  - For explicit guards, return `new EventsWithConcurrencyScopes(events, [new(label, new ConcurrencyScope(expected, EventSourceId: accountId))])`: use the expected revision for the exact history read, and a meaningful nonempty scope label. A label identifies a guard; it does not select the history.
187
224
 
188
225
  ## What the audit record keeps
189
226
 
190
- Arc copies public command values into each event's causation, separately from the event itself. `[NotAudited]` (`Cratis.Arc.Chronicle.Commands`) on a command, property or parameter and Chronicle's `[PII]` on a top-level command property keep the value out. Exclusion is not recursive: mark the containing property or the whole command when nested data is sensitive. Encrypting the event property does not remove the command value from causation. Never store a password or token as a reversible event value.
227
+ Arc copies public command values into causation, separately from the event itself: `commandType`, `commandTypeFullName`, then every readable public command property under its camel-cased name. This applies to an event the command returns, which also gets `eventSequenceId`, and to any other event appended while the command runs, which does not. An indexer is skipped, and so is a property whose name collides with one of those reserved names. A concept records the value it wraps, numbers and dates are written culture-invariantly, a nested object or collection becomes compact JSON, a null is omitted, and a long value keeps its first 1024 characters followed by `…`.
228
+
229
+ `[NotAudited]` (`Cratis.Arc.Chronicle.Commands`) and Chronicle's `[PII]` keep a value out. Either may sit on the property, on the positional parameter, on the property's type (a shared concept is then excluded from every command that uses it) or on the command. `[NotAudited]` on the command excludes all of its values; `[PII]` on the command covers only the properties that command type declares, so a property inherited from a base type is still recorded unless it, its type or its declaring type is marked. Exclusion is not recursive: a marking on a member of a nested object does not remove it from that JSON, so mark the containing property, its type, or the whole command with `[NotAudited]`, when nested data is sensitive. Encrypting the event property does not remove the command value from causation. Never store a password or token as a reversible event value.
@@ -21,7 +21,9 @@ public class CartsController(ICartService carts) : ControllerBase
21
21
  - A `[HttpPost]` action's return value is wrapped in the same command result envelope a model-bound command produces. The request type is a plain body type, not a `[Command]`.
22
22
  - The generated frontend proxy is named after the action method.
23
23
  - **Validate route.** Arc adds `POST <route>/validate` for the action. It runs MVC binding and filters and skips the action body, so a precondition checked only inside the action or its service is not a pre-flight rule.
24
- - **Validation.** Discovered FluentValidation validators and data annotations run during MVC model binding. `[TreatWarningsAsErrors]` (`Cratis.Arc`) on an action or controller makes warning-level results block; the caller-severity header does not apply to controllers.
24
+ - **Validation.** Discovered FluentValidation validators and data annotations run during MVC model binding. Every failure they add blocks the action and reaches the result as an `Error`, whatever severity the rule declares.
25
+ - **Severity.** Do not build a warning or confirmation flow on a controller. `[TreatWarningsAsErrors]` (`Cratis.Arc`) on an action or controller is not a floor: a caller that sends `X-Ignore-Warnings: true` receives only `Error` results even where the attribute is declared. `X-Allowed-Severity` has no effect on controllers. Use a model-bound command instead (`cratis-arc-validate-command`). For a warning the caller confirms, put the rule in a validator and declare no floor: the caller first requests with allowed severity `Information`, then resends with `Warning` after confirming. Declare `[BlockOnValidationSeverity(ValidationResultSeverity.Warning)]` only when a warning must never be waived; that floor makes confirmation impossible.
26
+ - **State rules.** A validator for a controller body type cannot take a read model as a constructor parameter and cannot call `GetTenant()`, `GetCausedBy()` or `IsSystem()` on the validation context: it runs during model binding, outside the command pipeline. The first fails the request with `ReadModelValidatorRequiresCommandPipeline`; the second throws `OperationSnapshotUnavailable`, so the request fails instead of reporting a finding. When a rule depends on state, tenant or caller, convert the action to a model-bound command.
25
27
  - **Authorization.** Use ASP.NET Core's own `[Authorize]` and `[AllowAnonymous]`; MVC authorization runs before body binding.
26
28
  - **Native response.** `[AspNetResult]` (`Cratis.Arc`) on an action or controller returns the ASP.NET result as written, with no envelope, no validate route and no execution scopes. Use it to keep an existing response contract.
27
29
  - **Binding.** `[FromRequest]` (`Cratis.Arc.ModelBinding`) binds one parameter from several request sources; see below. `[property: ExplicitOffset]` works on body properties. `[ApiController]` automatic problem responses can short-circuit before Arc and keep ASP.NET's shape.
@@ -98,6 +98,8 @@ public record AddItemToOrder(OrderId OrderId, ProductId Product, Quantity Quanti
98
98
  - `Commit()` commits the whole command transaction. Return straight after it; a later failure cannot undo it.
99
99
  - Never call `Commit()` in a command whose `Handle` can return a command operation: it throws `InvalidCommandOperation`. The pipeline commits there after the operation ran, and that deferred commit does not see `Failed` results, so make the refusal in the handler before returning the operation (`cratis-arc-declare-operation`).
100
100
  - The aggregate guards its own history: a concurrent append to it rejects the commit. It does not guard read models or other aggregates the command uses.
101
+ - Without `[EventSource<TSource>]`, an existing aggregate guards only the event types it handles. A new aggregate, or one with no handler methods, guards every event type on its event source ID, so two competing creations cannot both commit.
102
+ - A subject declared on or returned by the command does not reach events the aggregate applies. Those events take their subject from the event's own subject metadata; see "Subject and tags" in `references/csharp-chronicle.md`.
101
103
  - There are no snapshots: every command replays the handled history, so keep it bounded.
102
104
 
103
105
  ## Aggregate root catalog
@@ -113,7 +115,7 @@ public record AddItemToOrder(OrderId OrderId, ProductId Product, Quantity Quanti
113
115
  | `[EventSource<TSource>]`, optionally with a stream name | Binds the aggregate to one event source definition and stream: only that stream's events are replayed and guarded. Without it, every handled event for the event source ID in any stream is replayed. |
114
116
  | `IAggregateRootFactory.Get<T>(id, streamId, eventSourceType)` | Load an aggregate for another identity, or outside a command. Loading two aggregates does not make one decision over both: collect every `Commit()` result. |
115
117
 
116
- A constructor may take registered services. A read model injected there is a dependency, not replayed state, and is not updated by `Apply`.
118
+ A constructor may take registered services. A read model injected there is a dependency, not replayed state, and is not updated by `Apply`. It is resolved from the command's context: loading the aggregate through `IAggregateRootFactory` with another ID does not rekey it.
117
119
 
118
120
  ## Failures
119
121
 
@@ -122,4 +124,5 @@ A constructor may take registered services. A read model injected there is a dep
122
124
  | `StreamDecisionRequiresSpecificRoute` | The read has an unspecified event source ID, every stream type, or the default stream ID | Declare the stream type and stream ID on the command or route. |
123
125
  | `EventRoutingContradictsEventSource` | A stream name the event source definition does not declare, or metadata contradicting it | Use a declared stream. |
124
126
  | `UnableToResolveAggregateRootFromCommandContext` | The command's event source ID is declared but unusable, for example unspecified | Supply a usable identity before the aggregate is resolved. |
127
+ | `AggregateRootContradictsEventSource` | An aggregate with `[EventSource<TSource>]` names a stream the definition does not declare, is loaded through `Get<T>` with another event source type, or carries an `[EventStreamType]` that differs from the declared stream's | Make the declaration, the `Get<T>` arguments and the attribute agree with the event source definition. |
125
128
  | `ReadAndAggregateOnSameSource` (analyzer `ARCCHR0033`) | Under read protection `On`, a protected read model and an aggregate guard the same source | Decide from the aggregate, or mark an advisory read `[Unprotected("reason")]`. A protected read of a different source is allowed beside the aggregate and adds its own guard. |
@@ -43,6 +43,8 @@ public interface ICartService { CartLineId AddItem(CartId cart, Sku sku, Quantit
43
43
  ```
44
44
 
45
45
  - The record's properties are the request body; use concepts (`ConceptAs<T>`) rather than primitives. Arc serializes a concept as its underlying value.
46
+ - `Handle` is a public instance method on the command itself. There is no separate handler class: a public instance `Handle` on a type without `[Command]` that takes a `[Command]` type as a parameter is an analyzer error (static classes and types named `*Extensions`, `*Helper` or `*Helpers` are skipped), and a static or non-public `Handle` on the command does not count.
47
+ - Coming from a request and handler pair, merge them: the request becomes the command record, the handler body becomes `Handle`, constructor dependencies become `Handle` parameters, and pipeline behaviours become command filters. Do not keep a handler class that `Handle` forwards to.
46
48
  - `Handle` may be synchronous or return `Task`, `Task<T>` or `ValueTask<T>`. Follow the collaborator's actual signature: call a synchronous method synchronously, and `await` only what returns a task. Do not invent an asynchronous overload or a `CancellationToken` parameter the collaborator does not declare.
47
49
  - Parameters of `Handle` are resolved from the command's service scope; register the services in the host as usual.
48
50
  - One command type has exactly one handler; a second fails startup with `MultipleCommandHandlersForSameCommandType`.
@@ -60,13 +62,29 @@ To record events instead of calling a service, read [Chronicle commands](csharp-
60
62
 
61
63
  ## What `Handle` may return
62
64
 
65
+ Pick the return type from what the caller and the system need:
66
+
67
+ | The command must | `Handle` returns |
68
+ | --- | --- |
69
+ | Change state through a service; the caller needs nothing back | `void` or `Task` |
70
+ | Give the caller one value | `T`: the identity or a value the decision produced |
71
+ | Record a fact (Chronicle) | The event, or a collection of events |
72
+ | Record a fact and give the caller a value | A tuple `(event, value)` |
73
+ | Either succeed or refuse | `Result<TSuccess, ValidationResult>`, or `ValidationResult` alone when success carries nothing |
74
+ | Refuse as unauthorized from data the decision loaded | `Result<TSuccess, AuthorizationResult>` |
75
+ | Perform a further side effect | A tuple with an `ICommandOperation`, or `CommandOperations` for several |
76
+
77
+ To refuse a command, return a single `ValidationResult` for a business rule, or an `AuthorizationResult` that is not authorized. Give the `ValidationResult` error severity whenever the return also carries an operation: there a result below the command's blocking severity does not refuse. A response value handler can fail the command too: a failed aggregate commit result does, and so can a custom handler. An error DTO, a nullable event, an empty collection of events and a collection of `ValidationResult` do not refuse: the command succeeds.
78
+
63
79
  The pipeline classifies the returned value. Values it consumes on the server never reach the caller.
64
80
 
65
81
  | `Handle` returns | What the pipeline does |
66
82
  | --- | --- |
67
83
  | `void`, `Task` | No response. |
68
84
  | `T`, `Task<T>`, `ValueTask<T>` | A value no handler consumes becomes `CommandResult<T>.Response`. |
69
- | One `ValidationResult` (`Cratis.Arc.Validation`) | Makes the ordinary handler result invalid, even at warning or information severity. A collection is not a supported refusal. |
85
+ | One `ValidationResult` (`Cratis.Arc.Validation`) | On an ordinary return, makes the result invalid, even at warning or information severity. When the return also carries an operation, Arc applies the command's validation severity threshold instead: a result below the blocking severity (a warning, by default) is dropped, the command succeeds and the operation runs. Use error severity for a refusal. |
86
+ | `ValidationResult[]`, `IEnumerable<ValidationResult>` | Not a refusal: no built-in handler consumes a collection, so it becomes the response and the command succeeds. In a tuple it counts as the unconsumed value, and a second one is a declaration fault. When the return also carries an operation, the collection is left out of the response and still does not refuse. Return one `ValidationResult`, or put the rules in a validator. |
87
+ | `AuthorizationResult` (`Cratis.Arc.Authorization`) | Not authorized: the command is refused as unauthorized. Authorized: consumed, and the command succeeds. Use it only when the verdict depends on data the decision loaded; otherwise declare the policy on the command. |
70
88
  | `ICommandOperation` | Executed on the server after `Handle`; never the response (`cratis-arc-declare-operation` skill). |
71
89
  | `CommandOperations` | An explicit ordered batch of operations, possibly empty. |
72
90
  | An event, a collection of events, `EventForEventSourceId` | Appended by the Chronicle integration (see [Chronicle commands](csharp-chronicle.md)). |
@@ -102,11 +120,13 @@ public record EmptyCart(CartId CartId)
102
120
 
103
121
  `ICommandOperation` is in `Cratis.Arc.Commands`; `Execute` takes its services as parameters and follows their signatures (`cratis-arc-declare-operation` skill). Use a response value handler instead only when many commands return the same server-consumed type (see "Consume a returned value on the server").
104
122
 
105
- - A single `ValidationResult` on the ordinary response path refuses the command. An error-named record in a `Result` is plain response data and leaves the command successful.
123
+ - A single `ValidationResult` on the ordinary response path refuses the command; beside an operation only one at a blocking severity does. An error-named record in a `Result` is plain response data and leaves the command successful.
106
124
  - With a compiler supporting native unions, `public readonly union DiscountOutcome(DiscountApplied, ValidationResult);` can be the declared return type. Only the active case is processed; declare nameable closed alternatives so the generator can emit metadata and the typed accessor. This does not enable union request binding or native-union `Provide`.
107
125
  - Return `new CommandOperations([reserveStock, notifyWarehouse])` for two ordered `ICommandOperation` values, not a bare array. With operations present, validation collections are control values rather than response candidates.
108
126
  - Two unconsumed tuple elements produce an exception-bearing result (`MultipleUnhandledTupleValues`), not a two-field response: return one record.
109
127
  - A `null` return supplies no response. Never return `null` or an empty collection to signal a refusal.
128
+ - A result that is not successful never carries a response: Arc clears it. Do not design an error payload as the response type; report the failure as a `ValidationResult`.
129
+ - Do not return the read model the command affects. A returned read-model instance is plain response data: nothing refreshes it or keeps it in step with what queries serve. Return the identity or a value the decision produced, and let the caller query or observe the view.
110
130
  - `ValidationResult.Information(...)`, `.Warning(...)` and `.Error(...)` take a message and optional member names.
111
131
 
112
132
  ## Dependencies and `Provide`
@@ -140,6 +160,8 @@ When nothing can be missing, return the value directly (`public ShippingRate Pro
140
160
  - `CancellationToken` is supplied by Arc in both methods, never from dependency injection: the request-aborted token over HTTP, or the token the in-process caller passed.
141
161
  - `Provide` prepares input; it is not a response and not a place for writes. Keep the write in `Handle`, in a returned operation or in a returned event.
142
162
  - A provided value that no `Handle` parameter consumes is a mistake.
163
+ - Each provided value is consumed once: a parameter takes the first unconsumed value its type is assignable from. Arc binds parameters in declaration order, except that the Chronicle integration binds a parameter another one depends on first (the source of a `[LookUpBy]`, for example). Two parameters of one type therefore bind by binding order and by the order the values were provided. Give each provided value its own record or concept type so order never decides.
164
+ - A `Handle` parameter is filled in this order: a `[GeneratedValue]` capture, the cancellation token, a provided value, then a parameter resolver or the service container. A provided value never fills a `[GeneratedValue]` parameter or the cancellation token. A provided value that matches a caller-keyed read-model parameter (`[LookUpBy<TKeyProvider>]`) is always refused with `InvalidLookUpBy`. When the command declares a sibling lookup, the source parameter of that lookup and every parameter carrying `[LookUpBy]` are acquired by the resolver even when a provided value fits. Without a sibling lookup, a matching provided value fills a parameter with a property-based `[LookUpBy]` and the lookup does not run, so do not provide a value of a type you also look up.
143
165
  - For a value many commands need, register a scoped service and take it as a parameter instead of repeating `Provide`.
144
166
 
145
167
  ## Current state as a parameter
@@ -271,6 +293,8 @@ public record ScheduleDelivery(CartId CartId, [property: ExplicitOffset] DateTim
271
293
  | `Response` | The selected response; available only after `Handle`. |
272
294
  | `ServiceProvider`, `CancellationToken` | The command's scope and token. |
273
295
 
296
+ `context.GetResolvedKey()` returns the command key Arc resolved for state lookup. It is `null` or empty when the command carries no usable key (Chronicle supplies an empty string for an unspecified event source ID), so check with `string.IsNullOrEmpty`. Use it in a filter or execution scope that needs the command's target.
297
+
274
298
  Contribute values with `ICommandContextValuesProvider`; it is discovered automatically.
275
299
 
276
300
  ```csharp
@@ -316,11 +340,12 @@ public class StockAdjustmentHandler(IStock stock) :
316
340
 
317
341
  - Put `[Authorize(Policy = "ManageCarts")]` from `Cratis.Arc.Authorization` on the model-bound command, or `[AllowAnonymous]` for a deliberately public command. Use `cratis-arc-authorize-request` for the policy. Do not substitute availability for authorization.
318
342
  - With typed availability configured (`services.AddArcAvailability()`), `[Available<CartManagement>]` requires a block, `[AvailableFor<Staff>]` an audience, and `[AvailableWhen<WarehouseOpen>]` a condition. Separate attributes must all pass.
319
- - Validation normally blocks errors. `[BlockOnValidationSeverity(ValidationResultSeverity.Warning)]` on the command or the assembly makes warnings block too. `[TreatWarningsAsErrors]` applies to controller actions only and has no effect on a model-bound command. `[AllowCallerValidationSeverity(ValidationResultSeverity.Warning)]` opts the command into caller-selected strictness up to that limit. These govern validation, not a refusal returned by `Handle`.
343
+ - Validation normally blocks errors. `[BlockOnValidationSeverity(ValidationResultSeverity.Warning)]` on the command or the assembly makes warnings block too. `[TreatWarningsAsErrors]` applies to controller actions only and has no effect on a model-bound command. `[AllowCallerValidationSeverity(ValidationResultSeverity.Warning)]` opts the command into caller-selected strictness up to that limit. These govern validation and a `ValidationResult` returned beside an operation, not a `ValidationResult` returned on its own by `Handle`.
320
344
  - For infrastructure-supplied parameters implement a parameter resolver (`Cratis.Arc.DependencyInjection`); it is discovered, so no registration is needed. The first resolver that owns a parameter wins; if none owns it, the container resolves the type. A null for a non-nullable parameter fails as an unresolvable dependency whether a resolver or the container supplied it; a nullable one receives null.
321
345
  - Synchronous lookup: implement `ICanResolveParameterDependency.TryResolve(IServiceProvider services, ParameterInfo parameter, out object? dependency)`; return `true` for parameters you own and `false` for the rest.
322
346
  - Asynchronous lookup: implement `IAsyncParameterDependencyResolver` and `ValueTask<ParameterDependencyResolution> Resolve(IServiceProvider, ParameterInfo)`. Await the lookup and return `ParameterDependencyResolution.Resolved(value)` for every parameter you own (also when the value is null), `NotResolved` otherwise. `Handle()` and `Provide()` binding awaits `Resolve`. The interface extends `ICanResolveParameterDependency`, and consumers that cannot await, such as validator constructors, still call `TryResolve`. Keep the same ownership rule there: return `true` for owned parameters (with a synchronously obtained value, or null) and `false` only for parameters you do not own.
323
347
  - Use `IAvailabilityCommandFilter` for availability, `IAuthorizationCommandFilter` for access, `ICommandFilter` for ordinary pre-execution checks. For example, an access filter's `Task<CommandResult> OnExecution(CommandContext context)` can return `Task.FromResult(allowed ? CommandResult.Success(context.CorrelationId) : CommandResult.Unauthorized(context.CorrelationId))` using its computed verdict. An exception result isn't an authorization denial.
348
+ - Filters run in three groups: availability, then authorization, then the ordinary filters, which include validation. Execution stops at the first blocking result. Over HTTP a failed command answers with the first status that applies: 403 not authorized, 400 not valid (including a malformed body, or a required read model with no record for a usable key), 503 retryable, otherwise 500 (including a required dependency that resolved to nothing for any other reason); an exception response mapping can replace the status.
324
349
  - To bracket execution (ambient state, commit on success, release resources) implement an execution scope (`Cratis.Arc.Commands`); `cratis-arc-invoke-command` covers the lifecycle.
325
350
  - To turn a known exception type escaping any command into a different failure, such as a validation finding, implement `ICommandExceptionMapper` (`Cratis.Arc.Commands`); `cratis-arc-invoke-command` covers the contract. `IExceptionResponseMapper` only sets an HTTP status, an error code and optional headers (such as a retry delay) and cannot produce member findings.
326
351
 
@@ -331,8 +356,10 @@ public class StockAdjustmentHandler(IStock stock) :
331
356
 
332
357
  ## Analyzers
333
358
 
334
- `ARC0005` flags a `Provide` value that `Handle` does not consume. `ARC0006` flags a non-nullable read-model dependency so that "required" is a deliberate choice.
359
+ `ARC0002` warns about a command-shaped type without `[Command]`, `ARC0003` reports a public instance `Handle` that takes a `[Command]` type as a parameter on a type without `[Command]` (static classes and types named `*Extensions`, `*Helper` or `*Helpers` are skipped), and `ARC0004` reports a command without a public instance `Handle`. `ARC0005` flags a `Provide` value that `Handle` does not consume. `ARC0006` flags a non-nullable read-model dependency so that "required" is a deliberate choice. Generated-value diagnostics are in `cratis-fundamentals-name-value`; the full list is in `cratis-code-review`.
335
360
 
336
361
  ## Not supported in this SDK
337
362
 
363
+ - No separate handler class for a model-bound command: the handler is the command's own `Handle`.
364
+ - No multi-command batch API: nothing submits several commands as one atomic unit. Declare one command for the whole decision and return all its events and operations. With Chronicle, a command executed inside another command's `Handle` shares the outer transaction (see [Chronicle commands](csharp-chronicle.md)); that is nesting, not a batch.
338
365
  - No schema-first descriptor alternative to a model-bound command: declare the input and response as CLR types, or retain MVC binding for an existing controller API.
@@ -95,7 +95,7 @@ func (c ShipParcel) Handle(ctx context.Context, parcel Parcel) (string, error) {
95
95
  err := commands.Register[ShipParcel](builder, commands.WithProvide(ShipParcel.Provide, ShipParcel.Handle))
96
96
  ```
97
97
 
98
- `WithProvide` passes one typed payload to `Handle` after authorization and input validation; put several prepared values in one struct. Use `WithPreparation` when `Provide` must return a control: `commands.Provided(value)` continues, `commands.ProvidedWith(value, control)` adds a verdict, and `commands.StopProviding[P](control)` always skips `Handle`. `commands.Prepare` is the `Invocation`-receiving form. Validate-only execution invokes neither stage.
98
+ `WithProvide` passes one typed payload to `Handle` after authorization and input validation; put several prepared values in one struct. Use `WithPreparation` when `Provide` must return a control: `commands.Provided(value)` continues, `commands.ProvidedWith(value, control)` adds a verdict, and `commands.StopProviding[P](control)` always skips `Handle`. Always return one of these three: a zero `commands.Preparation` fails the command with `commands.ErrInvalidPreparation`. `commands.Prepare` is the `Invocation`-receiving form. Validate-only execution invokes neither stage.
99
99
 
100
100
  ## What `Handle` may return
101
101
 
@@ -1,5 +1,12 @@
1
1
  # C#: trace a missing delivery run on one subscription
2
2
 
3
+ ## Contents
4
+
5
+ - [Establish the baseline](#establish-the-baseline)
6
+ - [Find the first missing identity](#find-the-first-missing-identity)
7
+ - [Compare the hub subscription](#compare-the-hub-subscription)
8
+ - [Distinguish idle, overload and access failures](#distinguish-idle-overload-and-access-failures)
9
+
3
10
  Use the application's ASP.NET Core Arc host (`builder.AddCratisArc()`); for sockets put `app.UseWebSockets()` before `app.UseCratisArc()`. Use the generated proxy's route for HTTP probes. For hub controls use the query name the server registered (see below); the proxy's `queryName` is only a starting point, and neither is inferred from the URL. Names below are illustrative. Use a test caller, authorized tenant and non-sensitive data; keep real credentials out of transcripts.
4
11
 
5
12
  ## Establish the baseline
@@ -28,7 +35,7 @@ curl -i -X QUERY "$route" -H 'Content-Type: application/json' \
28
35
  1. Keep direct SSE open after the first ready result. Submit a matching delivery run through the normal command path; check command success and retain its ID. Ensure its sort position falls on the observed page.
29
36
  2. Check the **reader's** resolved tenant database and collection. For example in `mongosh`, use `db.deliveryRuns.findOne({_id: runId})` with the actual BSON identity. If absent, trace persistence or projection catch-up before debugging HTTP.
30
37
  3. If present, start `db.deliveryRuns.watch().next()` on that collection **before** a fresh write. Match `documentKey._id`; change streams require a replica set or sharded cluster. Separately observe the server source for the same arguments. A matching change but no updated source value points to the watcher, the predicate or a one-time materialization instead of `collection.Observe(...)`. A date boundary alone does not cause a database notification.
31
- 4. If the source emits, check caller restrictions and `IGuardObservableQueryEmission.Guard(context)`: `Allow` delivers, `Suppress` skips this candidate, `DenyAndTerminate` ends delivery; a throwing guard fails closed. Distinguish this from a query rejected at opening (arguments, authentication or authorization). Record correlation ID and outcome, not credentials. After an identity/tenant change, establish a fresh subscription.
38
+ 4. If the source emits, check caller restrictions and `IGuardObservableQueryEmission.Guard(context)`: `Allow` delivers, `Suppress` skips this candidate, `DenyAndTerminate` ends delivery as a denial, `Unavailable` ends it as a temporary failure of the check (see the last section). With several guards the caller sees one combined verdict: `DenyAndTerminate` overrides `Unavailable`, which overrides `Suppress`, which overrides `Allow`, so check every registered guard, not only the one you suspect. A throwing guard fails closed as a denial. Distinguish this from a query rejected at opening (arguments, authentication or authorization). Record correlation ID and outcome, not credentials. After an identity/tenant change, establish a fresh subscription.
32
39
  5. Inspect whole SSE `data:` events, not individual chunks. From the skill directory run `node scripts/check-frames.mjs < capture.sse` after stopping capture. It skips not-ready events and requires two successful frames; independently confirm the second contains the test ID. If direct SSE works, follow the actual hub frames before changing the source. For a direct socket comparison, open the same query URL and arguments with `wss:` (or `ws:` for HTTP) using a WebSocket client with the same scope; verify both upgrade and a later result.
33
40
 
34
41
  ## Compare the hub subscription
@@ -39,7 +46,7 @@ Open `/.cratis/queries/ws` by WebSocket. `Connected.payload` is the physical con
39
46
  {"type":"Subscribe","queryId":"trace","revision":1,"payload":{"queryName":"Dispatch.DeliveryRuns.Open","arguments":{"depot":"North"},"page":0,"pageSize":20,"sortBy":"departure","sortDirection":"asc","transferMode":"delta"}}
40
47
  ```
41
48
 
42
- Inspect `QueryResult.payload` on `trace` and revision 1. `Error` or `Unauthorized` is not an empty successful result. When finished send `{"type":"Unsubscribe","queryId":"trace","revision":1}`, using the revision you subscribed with. The server ignores a lower unsubscribe revision and accepts an equal or higher one; a higher one also cancels the older work. A subscribe is ignored when its revision is at or below the latest revision the connection still holds for that query ID. A newer active subscription keeps blocking older controls. After an unsubscribe, the connection keeps that record only for a limited time and number of query IDs; once it is dropped and nothing newer has replaced it, a delayed subscribe with an old revision is accepted again. To change arguments, subscribe again on the same `queryId` with a higher revision; it replaces the older subscription. Discard `QueryResult`, `Error` and `Unauthorized` frames whose revision is not current; `Connected`, `Ping` and `Pong` carry no revision, so keep them. After reconnecting, compare connection as well as query ID and revision.
49
+ Inspect `QueryResult.payload` on `trace` and revision 1. `Error` or `Unauthorized` is not an empty successful result. When finished send `{"type":"Unsubscribe","queryId":"trace","revision":1}`, using the revision you subscribed with. The server ignores a lower unsubscribe revision and accepts an equal or higher one; a higher one also cancels the older work. A subscribe is ignored when its revision is at or below the latest revision the connection still holds for that query ID. A newer active subscription keeps blocking older controls. After an unsubscribe, the connection keeps that record for two minutes, and keeps at most 1,024 such records (the oldest go first); this is an ordering window for delayed controls, not a way to resume a subscription. Once it is dropped and nothing newer has replaced it, a delayed subscribe with an old revision is accepted again. To change arguments, subscribe again on the same `queryId` with a higher revision; it replaces the older subscription. Discard `QueryResult`, `Error`, `Unauthorized` and `Unavailable` frames whose revision is not current; `Connected`, `Ping` and `Pong` carry no revision, so keep them. After reconnecting, compare connection as well as query ID and revision.
43
50
 
44
51
  For SSE hub, keep `GET /.cratis/queries/sse` open. Use the same owner credentials for both controls. Example POST bodies (`application/json`), substituting `Connected.payload` for `issued-id`:
45
52
 
@@ -64,4 +71,19 @@ Check these host settings under `Cratis:Arc` against what actually happened:
64
71
 
65
72
  As a permitted operator, `curl -sS "$origin/.cratis/queries/health"` before and after subscribing/cancelling. `Cratis.Arc.Queries.QueryHealth.ObserveHealth` exposes `connections`, `totalConnections`, `totalSubscriptions` and `querySubscriptions` grouped by query identifier. Match the subscriber, protocol and `lastDataServedAt`; counts alone do not prove the row arrived.
66
73
 
74
+ An `Unavailable` verdict reports a check that temporarily could not complete, not a denial. The transport reports the combined verdict of all guards for that emission: a caller sees the temporary failure only when at least one guard returns `Unavailable` and none returns `DenyAndTerminate` or fails. No data is sent and that delivery ends. How it shows depends on the transport:
75
+
76
+ | Probe | Temporary guard failure | Denial |
77
+ | --- | --- | --- |
78
+ | Plain HTTP read of the observable query | 503 with `Retry-After: 1` and `isRetryable: true` | 403 |
79
+ | Hub connection opened with `supportsUnavailable=true`, subscribe sent with a revision | `Unavailable` frame for that `queryId` and revision | `Unauthorized` frame |
80
+ | Hub without that opt-in, or a subscribe without a revision | `Unauthorized` frame | `Unauthorized` frame |
81
+ | Direct WebSocket or SSE on the query route | final result with `isAuthorized: false`, then the stream ends | the same |
82
+
83
+ - Opt in on the request that opens the connection: add `supportsUnavailable=true` to the `/.cratis/queries/ws` upgrade URL or to `GET /.cratis/queries/sse`. `Connected.supportsUnavailable` is true only on a connection that opted in; a subscribe POST cannot opt in.
84
+ - To tell the two apart for a caller that sees `Unauthorized`, reproduce the failing emission as that caller on an opted-in hub connection with a revisioned subscribe. A subscription keeps the subscription scope it captured when it was established, and a fresh one can capture a different scope from identical arguments, so first recreate the original subscription's scope and the conditions its guards depend on, then trigger the same kind of change. A replay that succeeds under different conditions does not classify the original failure. Do this before changing permissions.
85
+ - A plain HTTP read classifies only a candidate it actually evaluates. Without `waitForFirstResult=true`, a source with no readable current value answers 202 and no guard runs. With it, the read evaluates later emissions until one produces an answer or the first-result deadline passes (408). A model-bound async enumerable answers 400. A successful first result says nothing about a later emission that is rejected, so do not use it to clear a subscription that fails after its baseline.
86
+ - Both are retryable, in different ways. After a hub `Unavailable` frame, back off, then subscribe again on the same `queryId` with a higher revision; sibling subscriptions keep streaming. After this 503, repeat the same HTTP read once the `Retry-After` time has passed. The Arc TypeScript client opts in on hub connections and retries by itself for hub subscriptions and for polling; a one-shot read returns its result and the caller decides whether to repeat it. A bare 503 status proves neither a guard failure nor a retryable one: an application exception mapping can also answer 503. Treat it as this temporary failure only when the body has `isRetryable: true` and the response carries `Retry-After`.
87
+ - A guard that throws a non-fatal exception, or cannot be constructed, counts as a denial on every transport, and the server logs it at Error. An explicit `Unavailable` verdict is not logged as an error. Cancellation is the exception: when the subscription or request token is already cancelled, an `OperationCanceledException` from the guard, or an `ObjectDisposedException` while the guard is being resolved, writes no guard-failure log. Any other non-fatal exception is still logged at Error. A plain HTTP read that reaches its first-result deadline answers 408, not 403. Guards apply to every observable query, so one guard with an unresolvable constructor dependency denies them all.
88
+
67
89
  **Not supported in this SDK:** `QueryOptions` has no per-owner connection quota, maximum inbound frame size or handshake timeout setting. Inspect the ASP.NET Core host and proxy limits instead. There is no plain HTTP snapshot of a model-bound async enumerable (400) and no subject-style bounded first-result wait for any async enumerable; open SSE or a WebSocket and cancel the probe explicitly.
@@ -10,6 +10,7 @@
10
10
  - Scopes
11
11
  - Check the scope boundary
12
12
  - Connect a client
13
+ - Test with MCP Inspector
13
14
  - Receiver options
14
15
  - Curated tools
15
16
  - Tool authorizers
@@ -180,8 +181,55 @@ Visual Studio Code, in `.vscode/mcp.json`:
180
181
  }
181
182
  ```
182
183
 
184
+ Claude Desktop can connect through the `mcp-remote` bridge, which takes the endpoint URL and the header as arguments and reads the token from its environment:
185
+
186
+ ```json
187
+ {
188
+ "mcpServers": {
189
+ "dispatch": {
190
+ "command": "npx",
191
+ "args": [
192
+ "mcp-remote",
193
+ "https://dispatch.example.test:5001/mcp",
194
+ "--header",
195
+ "Authorization: Bearer ${PAT}"
196
+ ],
197
+ "env": { "PAT": "<your token>" }
198
+ }
199
+ }
200
+ }
201
+ ```
202
+
203
+ This file then holds the token: keep it in the user's own Claude Desktop configuration, never in a repository.
204
+
183
205
  A hosted connector, where a service calls the endpoint on a user's behalf, cannot be handed a PAT. It needs OAuth: choose `McpProfile.OAuthOnly` or `Combined` and set the public origin, resource and authorization servers in Receiver options. Arc verifies the grants; your own authorization server issues the tokens.
184
206
 
207
+ ## Test with MCP Inspector
208
+
209
+ MCP Inspector is a visual MCP client. Use it to check tool descriptions, input schemas and scope filtering before connecting an agent; use the scripted calls in Check the scope boundary when the check must be repeatable.
210
+
211
+ 1. Start the application with the `PatOnly` or `Combined` profile and PAT verification installed, then issue a PAT holding only the scopes under test through the application's own issuance flow. `OAuthOnly` refuses every PAT, even a valid one, with 401; test that profile with an OAuth grant instead.
212
+ 2. Start the Inspector with `npx @modelcontextprotocol/inspector`.
213
+ 3. Choose the Streamable HTTP transport, enter the endpoint URL (for example `https://dispatch.example.test:5001/mcp`) and add the header `Authorization` with the value `Bearer <token>`.
214
+ 4. Connect and list the tools. With a token holding only the read scope, confirm that command tools are absent.
215
+ 5. Call the mapped query `list_deliveries` and read `outcome` and `data` in the result, not just whether the call returned. A curated tool returns whatever its source defines, so it need not carry an `outcome`.
216
+
217
+ If the Inspector is refused with 403 `origin_not_allowed`, it sent a browser `Origin` header that the receiver does not allow:
218
+
219
+ - Set the `Cratis.Arc.Mcp` log category to Debug. Event `5101` then logs the refused origin and the reason. Do not assume the Inspector's port.
220
+ - Act on the reason. "Origin is not allowed" means one well-formed origin that is not in the list: add it only if it is the Inspector you started and trust. A malformed origin or multiple `Origin` values is a fault in the request: fix the client or the proxy in front of it rather than adding an entry.
221
+ - The log shows the first value only, without control characters and cut at 200 characters. When it may be cut, read the full `Origin` of the request that reaches the endpoint before adding it, and never allowlist a cut value. The browser developer tools show it only when the browser calls the endpoint directly; when the Inspector's proxy sends or rewrites the header, inspect the request the proxy sends to the endpoint instead.
222
+ - Add that single origin for the test run, and remove it when you finish. Production `AllowedOrigins` stays empty unless a real browser client needs an entry.
223
+
224
+ ```csharp
225
+ mcp.Configure(options => options.AllowedOrigins.Add("<the refused origin>"));
226
+ ```
227
+
228
+ - When the Inspector connects through its own proxy process, the proxy makes the request and may send no `Origin` header. A request without one passes the origin check, so no entry is needed; it must still present a valid credential.
229
+ - The capabilities port is a separate listener. With a local development certificate, make the Inspector's process trust it, or test against an `http` loopback URL.
230
+
231
+ The rules for an origin value are under Receiver options.
232
+
185
233
  ## Receiver options
186
234
 
187
235
  Set these in `mcp.Configure(options => ...)`. All are members of `McpOptions`.
@@ -309,3 +357,4 @@ When startup fails, a request is refused, a tool is missing from a caller's list
309
357
  - Approval-required commands as tools: keep them on their approval path.
310
358
  - Streaming or live queries as tools: expose a finite query.
311
359
  - A PAT issuance endpoint: write an application endpoint that calls `IPersonalAccessTokens.Issue` for a signed-in person.
360
+ - A Screenplay capability manifest (`screenplay-capability-manifest/1`) as the tool allowlist: Arc does not load one, so the catalog comes only from what the host declares: the explicit or attributed operation exposures and the registered curated tool sources. When a handoff includes a manifest, `cratis-screenplay-accept-model` (`references/capability-consumption.md`) covers validating it and matching each entry to a registered operation.
@@ -67,7 +67,7 @@ Choose live delivery only when the view must follow changes. Return the provider
67
67
  - **Direct WebSocket:** upgrade the query route for a dedicated connection when supported and enabled by the host.
68
68
  - **Multiplexing:** share subscriptions at `/.cratis/queries/ws` or `/.cratis/queries/sse`; SSE uses companion subscribe/unsubscribe requests because the stream is one-way.
69
69
  - **Transfer mode:** deliver full snapshots or deltas; added, replaced and removed items require stable identity. A change set between deliveries is not an event log.
70
- - **Emission guard:** recheck access at delivery when admission at subscription time is insufficient. Allow delivers, suppress skips one emission, deny-and-terminate ends access.
70
+ - **Emission guard:** recheck access at delivery when admission at subscription time is insufficient. Allow delivers, suppress skips one emission, deny-and-terminate ends access, unavailable ends the operation when the check itself could not run. Only a caller the transport can tell to retry sees unavailable as a retryable failure; every other caller sees it as unauthorized, so return it for a transient fault and never as a softer denial.
71
71
  - **Subscription lifetime:** bind arguments and caller context at open; scope resources to the subscription and clean up on disconnect, cancellation, failure or completion.
72
72
  - **Connection policy:** configure WebSocket enablement, allowed origins, keep-alive, handshake, connection and shutdown timeouts to match the deployment.
73
73
  - **Load limits:** bound connections and subscriptions globally, per caller and per connection; bound inbound/outbound frames, bytes, queued emissions and retained removals. Do not enlarge buffers to hide a stalled consumer.
@@ -78,3 +78,5 @@ Choose live delivery only when the view must follow changes. Return the provider
78
78
  - **Stored view:** a projection or reducer maintains state; declaring an Arc query does not. Prefer a provider query over that stored view for filtering, sorting and paging.
79
79
  - **Keyed read:** ask Chronicle for the instance when the store should remain hidden or the model is computed on demand. Do not assume a keyed model supports listing every instance.
80
80
  - **Observe versus watch:** observe the model when the caller needs its current value and updates; watch individual changes only when the consumer understands change sets.
81
+ - **Read after write:** a stored view follows the write with no bound on delay. For data that a screen's own commands change, expose an observable query; do not look for a setting that makes the write wait for the view (Arc C# commands have none). See `cratis-platform-deliver-slice`, `references/eventual-consistency.md`, for the choice by who reads next.
82
+ - **One read model per screen:** a query that joins two stored read models can return them at different positions in the event log. When the facts must agree, project one read model that carries everything the screen needs.
@@ -65,6 +65,9 @@ With the host's default route settings this maps `GET /api/parking/permits/listi
65
65
  - The method is `public static` and non-generic. Internal and private methods are never exposed.
66
66
  - The method returns the declaring read model in one of the supported shapes.
67
67
  - The method has no parameter of the read model's own type (nullable or not). Such a method is a fold or helper, never a query.
68
+ - The method name is unique among the read model's queries. The name, not the parameter list, identifies the query, so do not overload.
69
+
70
+ The read-model type itself may be `internal`; its query methods must still be `public`.
68
71
 
69
72
  Every eligible method is a query by convention. When the type also holds query-shaped helpers that must stay private to the server, switch to explicit selection:
70
73
 
@@ -80,7 +83,9 @@ public record ParkingPermit(PermitId Id, ZoneName Zone, DateOnly ValidUntil)
80
83
  }
81
84
  ```
82
85
 
83
- A marked method must be an ordinary method with value parameters (no `ref` or `out`); an invalid marker is an invalid declaration, not a way to expose an unsupported result. Adding `[Query]` to one method without `RequireQueryAttribute = true` does not hide its siblings.
86
+ A marked method must be an ordinary method with value parameters (no `ref` or `out`); an invalid marker is an invalid declaration, not a way to expose an unsupported result. Adding `[Query]` to one method without `RequireQueryAttribute = true` does not hide its siblings. Under explicit selection, two marked methods with the same name are an error: rename one, or remove its marker and keep it as a helper.
87
+
88
+ The nearest `[ReadModel]` supplies the setting: the type's own declaration, shared by all its partial declarations, otherwise the closest base type's. A derived type without its own `[ReadModel]` therefore inherits explicit selection, and one with its own `[ReadModel]` starts again from the default. A nested type does not inherit it from its enclosing type; set it on each type that needs it.
84
89
 
85
90
  ## Common mistakes
86
91
 
@@ -118,6 +123,8 @@ Arc classifies each parameter by its type:
118
123
  - GET reads arguments from the query string, never from route values. QUERY reads them from `arguments` in the body.
119
124
  - Optional: a parameter with a default value, a `Nullable<T>` value type, a concept annotated `T?`, and every reference type that is not a concept (such as `string` or a collection) whatever its nullable annotation. These receive their default or null when absent. Required: a non-nullable value type or concept without a default; when it is absent the query answers 400 with a validation error naming the argument, and the method does not run. Over HTTP an empty value (`?name=` on GET, `""` in QUERY `arguments`) is dropped and counts as omitted. To require text or a format on a string, add validation: DataAnnotations on the parameter (`[Required]`, `[RegularExpression]`), a `QueryValidator` over the query's argument model (see Query filters below), or a concept with a `ConceptValidator`.
120
125
  - A supplied value that cannot convert answers 400 with a validation error naming the argument; the method does not run.
126
+ - DataAnnotations on a query parameter are enforced through metadata that Arc's source generator emits; the generator ships with the Arc package, so declare the query in a project that references it. In an assembly built without the generator they are not enforced. They check the bound value only and do not descend into the properties of an object; use a `QueryValidator` for whole-argument and cross-field rules. `[Display]` sets the argument's name in the message. `[Required]` rejects a null or omitted value, except that a non-nullable value parameter with a declared default (`[Required] int size = 10`) may be omitted: it takes its default and is not validated. The other attributes follow DataAnnotations null semantics, so an omitted nullable argument passes `[Range]`.
127
+ - Each validation entry carries `message`, `members` and `severity`. `members` holds camelCase paths such as `maximumBalance` or `items[0].name`; a failing concept is reported on the argument or member that holds it, never on `.value`.
121
128
  - There is no nested-object binding. Flatten a search-criteria object into scalar parameters.
122
129
  - `page`, `pageSize`, `sortBy`, `sortDirection` and the two first-result wait flags are reserved on GET (case-insensitive). Never give a caller argument one of these names: over GET it never binds, so a required parameter fails as a missing argument (400) and an optional one silently gets its default or null. Give business inputs a distinct name, and read real paging and sorting controls through `IQueryContextManager.Current`; `cratis-arc-page-query` covers paging.
123
130
  - For `string[] zones`, use `?zones=north&zones=south`; GET splits delimited values. Use QUERY `{"arguments":{"zones":["North, Annex"]}}` for a literal comma. For `Dictionary<string,int> limits` send `{"arguments":{"limits":{"north":3}}}`, not `?north=3`.
@@ -182,16 +189,26 @@ MongoDB observation needs change streams: a replica set or sharded cluster. A st
182
189
 
183
190
  A plain GET on an observable route is a snapshot. When the subject exposes no readable `Value` property the snapshot answers 202 with `isReady: false`; add `waitForFirstResult=true` to wait, and `waitForFirstResultTimeout=<seconds>` to bound the wait (default 30 seconds; 408 when it expires). An application-owned `BehaviorSubject<T>` has a current value and answers 200.
184
191
 
192
+ Always add `waitForFirstResult=true` to a plain GET on a MongoDB `Observe()` query. Without it the request answers 202, never an empty collection, and can leave the database watcher that `Observe()` started running, because nothing subscribes to the subject or disposes it. With it Arc subscribes, returns the first result that the emission guards allow and disposes the subscription. A suppressed emission is skipped and the wait continues until an allowed emission, a terminal verdict (403 or 503), the timeout (408), or the source failing or completing before any allowed result (500). This waiting applies to an observable subject; an `IAsyncEnumerable<T>` snapshot runs to completion instead, leaves out suppressed items and answers 200 with the allowed ones, even when that is none.
193
+
194
+ `ObserveSingle` and `ObserveById` emit `null` when no document matches: on the first read, after the document is deleted (including removal through `[RemovedWith<T>]` on a Chronicle read model), or when an update moves it out of the filter. That is neither an error nor the end of the subscription; a later match emits a value again. The client keeps the subscription and treats `null` as absence only in a successful result: loading and a failed result are separate states. Straight after a create-and-open flow, absence means the new item has not arrived yet, so show it as pending until the first value appears.
195
+
185
196
  A plain `Subject<T>` has no readable current value, even after `OnNext`; use `new BehaviorSubject<T>(initial)` only when `initial` is a genuine answer. For joined streams observe each contributing collection, re-evaluate on changes to either, and dispose all source subscriptions when the consumer leaves. Do not keep a request-scoped context in a process-wide subject.
186
197
 
187
198
  For one live query, request its URL with `Accept: text/event-stream` or upgrade to WebSocket. For multiplexing, connect to `/.cratis/queries/ws`, then send `{"type":"Subscribe","queryId":"zone-view","revision":1,"payload":{"queryName":"Parking.Permits.Listing.ParkingPermit.PermitsInZone","arguments":{"zone":"north"},"transferMode":"delta"}}`. Alternatively open GET `/.cratis/queries/sse`; use its Connected ID in a JSON POST to `/.cratis/queries/sse/subscribe` with `connectionId`, `queryId`, `revision`, and the same payload under `request`. POST those three identifiers without `request` to `/.cratis/queries/sse/unsubscribe`. Keep control requests on the same server instance. After reconnect, subscribe afresh; do not replay an old delta against stale state.
188
199
 
200
+ The two SSE control POSTs answer 400 for a missing required value or an invalid revision, 404 for a connection that is unknown or belongs to another caller or another endpoint group (the cases are indistinguishable on purpose) and 200 once processed; subscribe answers 401 when the query is refused while the subscription is being established. A denial at a later emission arrives on the stream, not as a status. 200 means the request was processed, not that data arrived: read the stream for results and errors.
201
+
202
+ A hand-written hub client that can retry opts in to `Unavailable` frames (see Emission guards) by adding `supportsUnavailable=true` to the WebSocket upgrade URL or to the SSE stream GET; the server confirms with `supportsUnavailable: true` in `Connected`. The SSE subscribe POST cannot opt in. The frame is sent only for a subscription whose subscribe carried a `revision`; it carries that revision and no data. Retry that subscription alone with a higher revision and backoff. Arc's own client does this already.
203
+
189
204
  The WebSocket transports use ASP.NET Core's WebSocket middleware: add `app.UseWebSockets()` to the host ahead of the Arc call that maps endpoints. Server-sent events need no extra middleware.
190
205
 
191
206
  ## Chronicle-backed read models
192
207
 
193
208
  `[ReadModel]` makes a type queryable through Arc. It does not make Chronicle maintain it; a projection or reducer does that and writes the instances to the read-model store.
194
209
 
210
+ The stored instances follow the events with no bound on delay, and an Arc C# command has no setting to wait for them. For data a screen's own commands change, return an observable query. `cratis-platform-deliver-slice`, `references/eventual-consistency.md`, covers the other readers.
211
+
195
212
  Default: query the stored collection through the storage provider, exactly as above (`IMongoCollection<T>` with `AsQueryable()`, `FindByIdAsync` or `Observe()`). This gives filtering, sorting, paging and live updates in the database. Arc's Chronicle integration releases protected (encrypted or personal) values on the way out through its built-in read-model interceptor, so the query needs no release code.
196
213
 
197
214
  Use `Cratis.Chronicle.ReadModels.IReadModels` when the read must go through Chronicle instead:
@@ -271,7 +288,7 @@ public class PermitSearchRenderer : IQueryRendererFor<PermitSearch>
271
288
  }
272
289
  ```
273
290
 
274
- `PermitSearch` and its operations are provider-specific here: count the restricted selection, then sort it and page only if paging was requested. Implement `IQueryRendererFor<T>` for one query type only. The query method must still return a discovered shape for the generated endpoint; a custom provider type suits controller queries and `IQueryPipeline` callers.
291
+ `PermitSearch` and its operations are provider-specific here: count the restricted selection, then sort it and page only if paging was requested. Implement `IQueryRendererFor<T>` for one query type only. When a renderer throws inside `IQueryPipeline`, an exception type that implements `IValidationFailure` becomes a validation error and any other exception becomes a failed result. A non-streaming HTTP response reports the validation error as 400; a single-query SSE or WebSocket request receives the validation result on the stream. Do not rely on this conversion for a controller query. The query method must still return a discovered shape for the generated endpoint; a custom provider type suits controller queries and `IQueryPipeline` callers.
275
292
 
276
293
  ## Read-model interceptors
277
294
 
@@ -313,10 +330,13 @@ public class RequireActiveSession(ISessions sessions) : IGuardObservableQueryEmi
313
330
  | Verdict | Effect |
314
331
  | --- | --- |
315
332
  | `Allow` | Deliver the result |
316
- | `Suppress` | Withhold this emission; the subscription stays open. A snapshot answers 202 |
333
+ | `Suppress` | Withhold this emission; the subscription stays open. A subject snapshot without `waitForFirstResult=true` answers 202; with it the snapshot skips the emission and keeps waiting for an allowed one, a terminal verdict, the timeout, or the source ending first (500). An `IAsyncEnumerable<T>` snapshot leaves the item out and answers 200 with the allowed items |
317
334
  | `DenyAndTerminate` | Send nothing, report unauthorized, end the subscription. A snapshot answers 403 |
335
+ | `Unavailable` | The check could not complete right now. Send nothing and end the operation; only the callers named here see a retryable failure. A snapshot answers 503 with `Retry-After: 1` and a retryable result. On the hub, a connection that opted in gets a terminal `Unavailable` for a subscription that carries a revision, and retries that subscription with backoff. Every other path (hub without opt-in or revision, single-query SSE or WebSocket) reports unauthorized |
318
336
 
319
- Several guards: the most restrictive verdict wins (`DenyAndTerminate`, then `Suppress`, then `Allow`); discovery order is not a contract, so keep guards independent. `Suppress` does not move the delta baseline: the next allowed emission is diffed against the last admitted snapshot, so its change set carries the net difference since then. A withheld change that has since been reverted is not sent. When the next allowed emission states its changes (`ObservedCollection<T>` with `Changes` set), its change set holds only the items it names, so a withheld change to another item can be lost; combine `Suppress` with stated changes only where that loss is acceptable.
337
+ Return `DenyAndTerminate` when access is refused. Return `Unavailable` only when the guard's own dependency (a permission or session lookup) is temporarily unreachable and the caller should retry.
338
+
339
+ Several guards: the most restrictive verdict wins (`DenyAndTerminate`, then `Unavailable`, then `Suppress`, then `Allow`). A denial stops evaluation; `Unavailable` does not, so a later guard's denial still wins. Discovery order is not a contract, so keep guards independent. A non-fatal exception thrown while constructing or running a guard counts as `DenyAndTerminate` and is logged as an error; ordinary teardown of an ended subscription is the exception described next. Every registered guard applies to every guarded delivery of every query and runs in turn until one denies; a cancellation because the subscription ended also yields `DenyAndTerminate` but is not logged. Because guards are not scoped to a query, a guard that cannot be constructed denies every emission that reaches the guards, live or snapshot (a snapshot with no readable value answers 202 without running any guard): check that its constructor dependencies are registered. `Suppress` does not move the delta baseline: the next allowed emission is diffed against the last admitted snapshot, so its change set carries the net difference since then. A withheld change that has since been reverted is not sent. When the next allowed emission states its changes (`ObservedCollection<T>` with `Changes` set), its change set holds only the items it names, so a withheld change to another item can be lost; combine `Suppress` with stated changes only where that loss is acceptable.
320
340
 
321
341
  When access depends on mutable state, `StateAwareEmissionGuard<TState>` supplies a fail-closed implementation: override `GetKey(context)`, `Read(key, cancellationToken)` and `Decide(principal, state)`. Missing keys, missing state, read failures and rejection terminate delivery; override `OnDenied` for diagnostics. For a decision tied to the opened subscription, a filter can set `QueryContext.SubscriptionScope`; the guard reads a snapshot via `context.SubscriptionScope`.
322
342
 
@@ -355,6 +375,8 @@ Bind `Cratis:Arc:Query` or set `ArcOptions.Query`:
355
375
 
356
376
  `ArcOptions.QueryHealth` (`Cratis:Arc:QueryHealth`) secures the live health feed at `/.cratis/queries/health` with `RequireAuthentication` and `Roles`. Outside Development the feed requires authentication by default.
357
377
 
378
+ `"AllowedWebSocketOrigins": []` in configuration leaves the option unset, so the check stays off. List at least one origin there, or assign an empty list in code to allow the application's own origin and requests without an `Origin` header, and nothing else. Arc takes the application's own origin from the `Host` header and the connection scheme as ASP.NET Core sees them: behind a reverse proxy that rewrites `Host` or terminates TLS, apply forwarded headers (`UseForwardedHeaders`) or list the public origin, otherwise the browser's own-origin connections get 403. Loopback gets no special treatment, so list a development proxy on another port. When cookie authentication is configured and the option is unset, the host logs a warning at startup; set the option in every application that authenticates browsers with cookies.
379
+
358
380
  Origins must be valid origins or `*`; queue capacity must be positive. Health `Roles` accepts comma-separated alternatives and forces authentication in every environment.
359
381
 
360
382
  `transferMode: "full"` sends full snapshots; `"delta"` sends a snapshot first and then changes; omission retains snapshots alongside subsequent changes. This contract is for subject-backed collections on the hub. Delta delivery is chosen by the subscriber, not the server: the hub compares consecutive collection results by each item's `Id` property and sends added, replaced and removed items. Give list read models a stable `Id`; without one every emission is a full list.
@@ -408,4 +430,5 @@ For example, `var result = await pipeline.Perform(queryName, arguments, Paging.N
408
430
  - No presence-preserving flag on a model-bound parameter. Use a separate explicit criterion when “omitted” differs from “use this default”. No arbitrary nested DTO binding: use scalar arguments or an MVC action for that contract.
409
431
  - No declarative watch/topic list on a query. Compose provider observations or return a subscription-owned subject that emits refreshed data on notifications.
410
432
  - No model-bound attribute to force a transport independently of result type, or built-in counted-page return wrapper for these methods. Return a supported subject for live delivery or `IQueryable<T>` for provider paging.
433
+ - No observable query in an ahead-of-time compiled host unless its element type is registered. Arc's source generator (it ships with the Arc package) does that for each model-bound query returning `ISubject<T>` or `IAsyncEnumerable<T>` in the project it builds, and is the supported way to register. An unregistered element type fails there with `MissingObservableQueryElementType`, naming the type. The registration alone does not make the whole application ahead-of-time compatible.
411
434
  - No per-caller hub quotas or frame-byte limits in `QueryOptions`. Bound emissions there and enforce additional connection and request limits at the host or gateway.
@@ -60,6 +60,7 @@ Use only the controls listed in the project reference. The following choices are
60
60
  - **Metadata check:** compare the server metadata module to current source without writing proxies.
61
61
  - **Proxy check:** compare generated output without writing when checking committed artifacts.
62
62
  - **Validation projection report:** inspect which rules travel to the client separately from drift checking.
63
+ - **Client validation mode:** stop emitting generated client rule validators when validation messages must be worded per request by the server's own validation.
63
64
  - **Watch:** regenerate after relevant source edits during development.
64
65
  - **Watch polling:** tune or disable periodic fallback scans when their cost matters.
65
66
  - **Manifest input:** use the lower-level renderer only when build tooling already supplies a validated client description.