@cratis/pi 8.13.0 → 8.15.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 (27) hide show
  1. package/package/corpus/skills/cratis-code-review/SKILL.md +1 -1
  2. package/package/corpus/skills/cratis-components-diagnose-screen/SKILL.md +1 -1
  3. package/package/corpus/skills/cratis-components-theme-application/SKILL.md +5 -2
  4. package/package/corpus/skills/cratis-migrate-arc-22-to-23/SKILL.md +59 -0
  5. package/package/corpus/skills/cratis-migrate-arc-22-to-23/references/csharp.md +121 -0
  6. package/package/corpus/skills/cratis-migrate-arc-23-to-24/SKILL.md +60 -0
  7. package/package/corpus/skills/cratis-migrate-arc-23-to-24/references/csharp.md +91 -0
  8. package/package/corpus/skills/cratis-migrate-arc-23-to-24/references/typescript.md +26 -0
  9. package/package/corpus/skills/cratis-migrate-components-3-to-4/SKILL.md +72 -0
  10. package/package/corpus/skills/cratis-migrate-components-3-to-4/references/typescript.md +137 -0
  11. package/package/corpus/skills/cratis-platform-upgrade-application/SKILL.md +2 -2
  12. package/package/corpus/skills/cratis-platform-upgrade-application/references/typescript.md +1 -1
  13. package/package/corpus/skills/cratis-specifications-exercise-backend/SKILL.md +1 -0
  14. package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-command-results.md +34 -1
  15. package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-decision-reads.md +4 -7
  16. package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-query-scenario.md +7 -8
  17. package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp-read-models.md +1 -1
  18. package/package/corpus/skills/cratis-specifications-exercise-backend/references/csharp.md +25 -3
  19. package/package/corpus/skills/cratis-specifications-observe-ui/SKILL.md +20 -0
  20. package/package/corpus/skills/cratis-specifications-observe-ui/references/typescript.md +17 -0
  21. package/package/corpus/skills/cratis-specifications-test-application-ui/SKILL.md +9 -2
  22. package/package/corpus/skills/cratis-specifications-test-application-ui/references/typescript.md +45 -1
  23. package/package/corpus/skills/cratis-specifications-test-typescript-behavior/SKILL.md +21 -0
  24. package/package/corpus/skills/cratis-specifications-test-typescript-behavior/references/typescript.md +58 -3
  25. package/package/profile-catalog.json +78 -0
  26. package/package.json +1 -1
  27. package/package/corpus/skills/cratis-components-theme-application/references/upgrade-from-previous-major.md +0 -141
@@ -0,0 +1,137 @@
1
+ # Components 3 to 4 in TypeScript: codemods and mappings
2
+
3
+ ## Contents
4
+
5
+ - Run a codemod
6
+ - What each codemod does and refuses
7
+ - Dependencies
8
+ - Stylesheets
9
+ - Removed root namespaces
10
+ - Removed subpaths and symbols
11
+ - Provider
12
+ - Parts and selectors
13
+ - Controls that behave differently
14
+ - Avoid
15
+
16
+ ## Run a codemod
17
+
18
+ Prerequisite: the application has `@cratis/components` 3 or 4 installed, and you are following Order in this skill. Paths and names in examples are illustrative.
19
+
20
+ All three commands ship in `@cratis/components.migrator`, which is released with the same version number as `@cratis/components`. Run them from the application directory whose installed Components package is being upgraded. Keep the migrator inside major 4; never use `latest`.
21
+
22
+ ```sh
23
+ TOOLING_RANGE='^4.0.0'
24
+
25
+ # Preview: writes nothing.
26
+ npx --package "@cratis/components.migrator@$TOOLING_RANGE" \
27
+ cratis-components-remove-root-namespace-imports --check src
28
+
29
+ # Apply.
30
+ npx --package "@cratis/components.migrator@$TOOLING_RANGE" \
31
+ cratis-components-remove-root-namespace-imports src
32
+ ```
33
+
34
+ - The other two commands, `cratis-components-button-variant-tone` and `cratis-components-change-handler`, take the same form. With pnpm use `pnpm dlx --package …`, with Yarn 2 or later `yarn dlx --package …`.
35
+ - The path argument (`src` here) only selects the files to scan. The installed `@cratis/components` is resolved from the working directory, so run from the application directory.
36
+ - `--check` exits non-zero when a rewrite is pending or a case needs manual review. That exit does not mean the tool failed.
37
+ - An apply run rewrites the safe cases, reports the rest and exits non-zero while any refused case remains.
38
+ - Before scanning, the migrator checks the installed `@cratis/components`. It accepts Components 3 or Components 4, and otherwise scans and writes nothing.
39
+ - Requires Node.js 20 or later. The codemods bring their own TypeScript, scan `.js`, `.jsx`, `.mjs`, `.cjs`, `.ts`, `.tsx`, `.mts` and `.cts` recursively, skip `node_modules` and `dist`, and are safe to rerun.
40
+ - A codemod does not remove imports it leaves unused. Run the formatter and lint afterwards.
41
+ - Pass `--package <name>` when the application installs Components under another package name.
42
+
43
+ **Coming from Components 2 or older (edge case):** the migrator refuses the installed package. Change the imports by hand, install Components 4, then run the codemods.
44
+
45
+ ## What each codemod does and refuses
46
+
47
+ | Codemod | Rewrites | Leaves for you (reported) |
48
+ | --- | --- | --- |
49
+ | `cratis-components-remove-root-namespace-imports` | `import { X } from '@cratis/components'` to `import * as X from '@cratis/components/<subpath>'`, and `export { X } from '@cratis/components'` to `export * as X from '@cratis/components/<subpath>'`, for every root namespace. Aliases and type-only imports are kept; an import that mixes a setup symbol with a namespace is split. | Whole-package imports (`import * as`, default, `import = require`), dynamic `import()`, `require()`, `export *` re-exports, side-effect imports, unknown symbols, and the `Compatibility` namespace with its pass-through exports. A statement with one refused name is left whole. |
50
+ | `cratis-components-button-variant-tone` | Literal `Button` props: `text` → `variant='ghost'`, `link` → `variant='link'`, `outlined` → `variant='outline'`, `rounded` → `shape='pill'`, and `severity` → `tone` (`secondary`, `contrast` → `neutral`; `info`, `help` → `accent`; `success` → `positive`; `warn` → `caution`; `danger` → `critical`). With several old variant props, `link` wins over `text`, and `text` over `outlined`. `severity='contrast'` also adds `variant='solid'` when no other variant applies. A literal new prop that is already there wins. | Dynamic values, JSX spreads, duplicate props, and a new prop with a non-literal value beside the old prop it replaces. |
51
+ | `cratis-components-change-handler` | A callback that only forwards one event field, on a standalone `Dropdown` `onChange` and on a command form field's `onValueChange`: it now receives the value itself. The field is `event.value` for `Dropdown`, `DropdownField` and `MultiSelectField`, `target.value` for the text, password, text area and color fields, `target.checked` for the checkbox and toggle fields, and `target.valueAsNumber` for the number and slider fields (`currentTarget` likewise). | Callbacks with several statements, several uses of the event, or use of the native event. An `event.value` callback whose parameter is not typed as `DropdownChangeEvent`, because `.value` may belong to the selected value. `onChange` on a command form field. |
52
+
53
+ ```tsx
54
+ // Before
55
+ <Button outlined rounded severity='warn'>Review</Button>
56
+ <Dropdown onChange={(event: DropdownChangeEvent<Role>) => setRole(event.value)} />
57
+
58
+ // After
59
+ <Button variant='outline' shape='pill' tone='caution'>Review</Button>
60
+ <Dropdown onChange={(value) => setRole(value)} />
61
+ ```
62
+
63
+ - The first codemod keeps namespace access (`Canvas.Canvas` still resolves). Converting to named imports is optional cleanup by hand.
64
+ - The Button codemod removes an old prop only when discarding its value cannot change what runs: a bare prop or a literal value. When the value is an expression that would no longer be evaluated, as `text` in `<Button link text={record()} />`, the whole prop group stays unchanged and is reported for manual review.
65
+ - A refused case stays unchanged and is reported. The Button and change-handler codemods also mark it with one `TODO(cratis-codemod)` comment, with three exceptions that are reported only: a Button prop that is not safe to remove (above), an untyped `event.value` callback and `onChange` on a command form field.
66
+ - A command form field's `onValueChange` already receives the value on the latest Components 3 release, and `onChange` is not a prop of a field in either major. Expect no rewrite on fields. If the codemod reports a field `onChange`, move the side effect to the enclosing `CommandForm`'s `onFieldChange(command, fieldName, oldValue, newValue)`.
67
+ - After the change-handler codemod, remove every `DropdownChangeEvent` type import: Components 4 does not export the type.
68
+
69
+ ## Dependencies
70
+
71
+ - Components 4 has no PrimeReact, PrimeIcons or Prime theme dependency. Uninstall those packages only when the application no longer imports them directly; otherwise keep them, with their provider, CSS and license, for the surfaces that still use them.
72
+ - `pixi.js` is an optional peer, `^8.20.0`. Install it when the application imports from the `Canvas` or `PivotViewer` subpath, and keep one resolution of it in the application.
73
+ - Components 4 declares `@cratis/arc` and `@cratis/arc.react` from 20.3.1 up to, not including, 26. `AutoCommandForm` needs 22.16.0 or later, which honors an explicit field name. Raise the two Arc packages together, to the same version.
74
+ - React 19 stays the required React major.
75
+ - Add the recommended config of `@cratis/eslint-plugin-components` (major 4, needs ESLint 9 or later) after `@cratis/eslint-config`. Its `no-root-barrel-import` rule keeps root namespace imports from returning.
76
+
77
+ ## Stylesheets
78
+
79
+ Import `@cratis/components/tokens`, then `@cratis/components/styles`, once in every host entry. Add `@cratis/components/theme` for the Cratis baseline look, or leave it out and assign the `--cratis-*` tokens yourself. The setup, the tokens and the scheme selectors are in `cratis-components-theme-application`.
80
+
81
+ ## Removed root namespaces
82
+
83
+ The package root exports the provider, its configuration, message and icon types, and their helpers. Every component comes from its subpath.
84
+
85
+ | Components 3 root namespace | Subpath |
86
+ | --- | --- |
87
+ | `Canvas`, `Chat`, `CommandDialog`, `CommandForm`, `Common`, `DataPage`, `DataTables`, `Dialogs`, `Display`, `Dropdown`, `Filter`, `Notifications`, `ObjectContentEditor`, `ObjectNavigationalBar`, `PivotViewer`, `SchemaEditor`, `TimeMachine`, `Toolbar` | `@cratis/components/<same name>` |
88
+ | `Types` | `@cratis/components/types` |
89
+ | `CommandStepper` | The codemod maps the namespace to `@cratis/components/CommandDialog`, because the old namespace was that whole module. In new code import the `CommandStepper` component from `@cratis/components/CommandStepper`. |
90
+ | `Compatibility` | None. Replace its contracts with the typed parts of each component, then delete the import. |
91
+
92
+ `@cratis/components/CommandForm/fields` and `@cratis/components/CommandForm` are the same module.
93
+
94
+ ## Removed subpaths and symbols
95
+
96
+ | Removed | Do instead |
97
+ | --- | --- |
98
+ | `@cratis/components/styled`; `styledMode`, `StyledModeOptions`, `CratisPreset`, `primeReactStyles` | Remove the renderer configuration. Import `tokens`, `styles` and optionally `theme`; assign product values to `--cratis-*` tokens directly. |
99
+ | `@cratis/components/compatibility`; the `Compatibility` namespace and its pass-through contract, sentinel and assert helpers | Use each component's typed parts (`DialogParts`, `DataTableParts`, `TablePaginatorParts`, `StepperParts`, `ToolbarParts`) and `data-cratis-part` selectors. |
100
+ | `@cratis/components/primereact-v10-palette` | Map product tokens to `--cratis-*`, or use the baseline theme. |
101
+ | `primeReactCssLayer`, `primeReactCssLayerOrder` | Delete, unless the product still owns direct PrimeReact CSS. Layer order belongs in product CSS. |
102
+ | `cratisDarkModeSelector` | The product's own theme selector, with the matching `--cratis-*` values assigned under it. |
103
+ | `PivotViewerOptimized` | `PivotViewer`. |
104
+ | `CommandStepperContent` | No replacement. Use `CommandStepper` or `StepperCommandDialog`. |
105
+ | Internal helpers of `Canvas` (`getInitials`, `reactionsExcludingUser`, mention and emoji helpers) and `Filter` (`buildFilterValues`, `buildRangeValues`, `RenderedHistogramBucket`) | No replacement. Inline the logic the application needs. |
106
+
107
+ ## Provider
108
+
109
+ - `CratisComponentsProvider` takes locale, messages, icons, routing, dialog header actions and the toast region. Its options are in `cratis-components-theme-application`.
110
+ - Renderer keys in `value` are type errors: `license`, `theme`, `defaults`, `pt`, `ripple`, `unstyled` and z-index settings. Remove them. Configure a PrimeReact provider that is still needed on its own.
111
+ - `value.locales` is still accepted for the old paginator and date labels, and deprecated. Move them to `value.messages`.
112
+
113
+ ## Parts and selectors
114
+
115
+ - `pt` stays, with new keys and plain HTML attributes as values. `ptOptions` and `unstyled` are accepted and do nothing.
116
+ - Check every `pt` key against the component's part type; every part is listed in `cratis-components-theme-application`, `references/parts.md`. Known keys that are no longer parts: `popup` on a dialog, and `theadRow` and `theadCell` on a data table.
117
+ - Replace selectors on PrimeReact markup (`.p-*` classes, `[data-scope]` and `[data-part]` attributes) with `[data-cratis-part='…']` selectors and the state attributes listed there, as `[data-cratis-part='step'][data-active='true']`.
118
+ - `Dropdown` still accepts `inputId` for `id` and `panelClassName` for the class of the `popover` part. Prefer the new names.
119
+
120
+ ## Controls that behave differently
121
+
122
+ | Control | Change | Do |
123
+ | --- | --- | --- |
124
+ | `DatePickerInput` | Still takes and returns `Date \| null`. Formatting follows the locale; `dateFormat` is accepted and ignored. | Set the locale on the provider and remove `dateFormat`. |
125
+ | `DataTableForQuery`, `DataTableForObservableQuery` | Without `serverQuery`, sorting and filtering apply to the loaded page; `clientFiltering` is accepted and does nothing. | Remove `clientFiltering`. Set `serverQuery` to pass filter arguments to the query and apply them before paging. |
126
+ | `RadioButtonField` | `name` is required. | Give every option bound to one property the same `name`. |
127
+ | An icon passed as a PrimeIcons class string | Still rendered as that class on an `<i>` element. `primeicons` is no longer a peer of Components. | Keep `primeicons` installed and its stylesheet imported in the application while class strings are in use, or pass a React icon component. |
128
+
129
+ ## Avoid
130
+
131
+ - Raising the package before the root-import codemod has run and passed on Components 3.
132
+ - Running the Button or change-handler codemod before the raise.
133
+ - Fetching the migrator with `latest`.
134
+ - Treating a non-zero `--check` exit as a tool failure.
135
+ - Deleting a `TODO(cratis-codemod)` without resolving the case it marks.
136
+ - Uninstalling PrimeReact while a direct import of it remains.
137
+ - Recreating a product → PrimeReact → Cratis token chain. Map product values to `--cratis-*` directly.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: cratis-platform-upgrade-application
3
- description: Use when moving an existing Cratis application to newer Cratis packages, tools or images, pinning Cratis package and image versions before a first production deployment, planning or reviewing a Cratis dependency upgrade (which package versions pair, and the order of the steps), or when a build or run breaks after such an update. Not for the PrimeReact codemods and the renderer and CSS migration of a Components major (`cratis-components-theme-application`), upgrading the Chronicle kernel itself (`cratis-chronicle-deploy-kernel`) or scaffolding a new application (`cratis-platform-start-application`).
3
+ description: Use when moving an existing Cratis application to newer Cratis packages, tools or images, pinning Cratis package and image versions before a first production deployment, planning or reviewing a Cratis dependency upgrade (which package versions pair, and the order of the steps), or when a build or run breaks after such an update. Not for the codemods and the renderer and CSS migration of a Components major (the matching Components migration profile), upgrading the Chronicle kernel itself (`cratis-chronicle-deploy-kernel`) or scaffolding a new application (`cratis-platform-start-application`).
4
4
  ---
5
5
 
6
6
  # Move an application to newer Cratis packages, tools and images
@@ -68,7 +68,7 @@ Compile-time and changed-default steps belong to the application. Stored-state,
68
68
  | Chronicle kernel: order, backup, rollout, majors | `cratis-chronicle-deploy-kernel`, `references/upgrade-and-recovery.md` |
69
69
  | Chronicle kernel that holds unique constraint claims | `cratis-chronicle-constrain-append`, `references/operations.md` |
70
70
  | Arc on .NET: defaults that changed | `references/csharp.md` in this skill |
71
- | Components across the major that stopped rendering through PrimeReact | `cratis-components-theme-application`, `references/upgrade-from-previous-major.md` |
71
+ | Components across a major | The matching `cratis/migrate/components-<from>-to-<to>` profile |
72
72
  | Specifications across a major | `cratis-specifications-isolate-behavior`, `references/csharp-running.md` |
73
73
  | AuthProxy | Read both its upgrade notes and the release notes of every version you cross: a change to what an unchanged configuration does can be described in only one of them. Settings are in `cratis-authproxy-configure` |
74
74
 
@@ -56,7 +56,7 @@ A Components major is not a version bump: imports, provider setup, styling selec
56
56
  - The migrator refuses an installed version outside the majors it supports. On the direct path from an older major, no command runs on the old release: make the preparatory import changes by hand, and run every command, the import migration included, only after the new major is installed.
57
57
  - After the bump, update the provider setup and the stylesheet imports and make the source changes the guide lists before expecting the frontend to build. A failing build between the bump and those changes is expected, not a defect.
58
58
 
59
- Order, commands and what changes by hand: `cratis-components-theme-application`, `references/upgrade-from-previous-major.md`.
59
+ Order, commands and what changes by hand: the matching `cratis/migrate/components-<from>-to-<to>` profile.
60
60
 
61
61
  ## Node backend and Chronicle client
62
62
 
@@ -73,6 +73,7 @@ Names in examples across this skill's references are illustrative.
73
73
  4. For an accepted event-writing command, assert the event, source and values. For a response-only command or query, assert the promised response fields or rows instead.
74
74
  5. Await every assertion that returns a task, future or promise; otherwise the runner can finish before a failing assertion completes.
75
75
  6. For delivery against a running kernel, wait on a bounded completion signal for the observer or append under test, not a sleep or polling loop. Without that signal, an append does not prove delivery.
76
+ 7. Before combining two scenarios, seeding one fact in two places, or handing a scenario's read surface to the code under test, read what each scenario does not prove and which members it has in your language reference. A member another scenario has is not implied, and a hand-built substitute for the read surface proves no fold.
76
77
 
77
78
  For a decision or validation rule, the spec should fail if the rule is removed and pass when it is restored. For delivery, require the exact promised observation after the completion signal.
78
79
 
@@ -19,7 +19,16 @@ Applies to `CommandScenario<TCommand>` with `Cratis.Arc.Testing.Commands` and, f
19
19
 
20
20
  Set everything here before the first `Execute` or `Validate`. The caller and pinned generated values cannot change after that call.
21
21
 
22
- - **History.** `_scenario.Given.ForEventSource(id).Events(first, second)` supplies the events the command's read models are built from. For a per-stream model, add `.OnRoute(route)` before `.Events(...)`, resolving the route from `_scenario.EventRoutes`. Routed seeds need decision mode, which a command declaring a per-stream or other protected decision dependency uses automatically; in ordinary mode `.OnRoute(...)` makes `.Events(...)` throw `RoutedEventSeedingRequiresDecisionReads`. In decision mode one shared log holds the seeds, reads and appends, so seed only through `Given`: `_scenario.EventScenario` throws there. In an ordinary scenario these seeds control the read models injected into the command and are separate from the event log: `_scenario.EventScenario.Given` fills only the log, which the handler's event-log reads and constraints see, and events the command appends never reach these seeds. When the command needs both, seed the same facts in both places. Observable queries combine both histories, so facts seeded in both places are processed twice when observed.
22
+ - **History.** `_scenario.Given.ForEventSource(id).Events(first, second)` supplies the events the command decides on. Where they land depends on the scenario's mode, which the scenario selects from the command type when it is constructed:
23
+
24
+ | Mode | The scenario is in it when | `Given...Events(...)` | `_scenario.EventScenario` |
25
+ | --- | --- | --- | --- |
26
+ | Decision | The command's read protection is `On` or `Measure`, or it carries `[ProtectedDecision]`, or a `Handle()`/`Provide()` parameter or a discoverable validator's constructor takes `DecisionRead<T>`, `IDecisionReads`, `IStreamReads`, `StreamDecision`, a per-stream read model or a guarded generated value | Enters the one log that injected read models, event-log reads, constraints and the commit all use | Throws `EventScenarioUnavailableInDecisionMode` |
27
+ | Legacy | Read protection is `Off` for the command and none of those dependencies is declared | Feeds only the read models injected into the command; never enters the event log | `EventScenario.Given` fills only the log, which event-log reads and constraints see; injected read models do not see it |
28
+
29
+ When the Chronicle build props are imported, an unset `CratisReadProtection` defaults the command assembly to `On`. Without a command or assembly declaration, it resolves to `Off`. `[Unprotected]` sets rollout to `Off`; otherwise the command declaration overrides the assembly declaration. An `Off` command still uses the decision store if it declares `[ProtectedDecision]` or a decision dependency. The runtime ceiling can lower enforcement without changing the scenario's store. Do not lower protection to make a spec pass.
30
+
31
+ For a per-stream model, add `.OnRoute(route)` before `.Events(...)`, resolving the route from `_scenario.EventRoutes`; in legacy mode that makes `.Events(...)` throw `RoutedEventSeedingRequiresDecisionReads`. In legacy mode a command that needs a fact both in an injected read model and in the log needs it seeded in both places, and events the command appends never reach the `Given` seeds. An observable query shared with that scenario combines both histories, so a fact seeded in both is folded twice there.
23
32
  - **A fixed read model.** `_scenario.Given.ForEventSource(id).ReadModel(instance)` pins the instance the command receives. A pin wins over seeded events for that model and key. It cannot back a `DecisionRead<T>` parameter (`PinnedReadModelCannotProvideDecisionToken`) or a per-stream model; seed events for those.
24
33
  - **The caller.** `.WithClaims(new Claim(ClaimTypes.Role, "Dispatcher"))` runs the command as an authenticated caller with those claims, `.WithPrincipal(principal)` uses an existing `ClaimsPrincipal`, and `.Unauthenticated()` runs it anonymously. These set the principal authorization reads; they do not exercise login or token validation.
25
34
  - **Server-generated values.** `_scenario.PinGeneratedValue("orderId", id)` fixes a generated parameter so the spec can assert it. When the exact value is irrelevant, call `.AllowGeneration()`. With neither, `Execute` returns a result carrying a `GeneratedValueNotPinned` exception instead of running the command.
@@ -117,6 +126,30 @@ The check does not evaluate tenant-membership verification: when the provider ha
117
126
 
118
127
  The result also exposes `Outcome` (`Authorized`, `Denied`, `Unsupported`), `ReasonCode` (set when unsupported) and a `Message` safe to print. Use it for a matrix of roles and policies across commands; keep one pipeline scenario per command to prove authorization actually gates execution.
119
128
 
129
+ These are the `Unsupported` diagnostics. Inspection can stop before policy evaluation; evaluation itself can also return `Unsupported`. If multiple discovered filters make the check unsupported, the first encountered wins. Most causes lie in the command type or the provider, not in the caller, so one of them can turn every cell of a matrix for that command, or for that whole provider, into Unsupported:
130
+
131
+ | `ReasonCode` | Cause | Scope |
132
+ | --- | --- | --- |
133
+ | `context-invalid` | The supplied context has another command type, no command, another provider, or was already evaluated | This call |
134
+ | `approval-required` | The command carries `[RequiresApproval]`, whether or not an approval flow is registered | Every caller of this command |
135
+ | `host-required` | An HTTP request is active in the provider | Every command |
136
+ | `services-missing` | Arc's authorization services are not registered in the provider | Every command |
137
+ | `runtime-unsupported` | The provider's policy runtime is not Arc's own | Every command |
138
+ | `tenant-membership` | Tenant membership is registered in the provider | Every command |
139
+ | `availability-gate` | An availability gate gates this command | This command |
140
+ | `custom-filter` | The provider discovers any `ICommandFilter` that is not one of Arc's own, whether or not that filter would act on this command | Every command |
141
+ | `principal-unavailable` | The principal override and accessor in the provider do not return the supplied principal | Every command |
142
+ | `host-required` | The declaration names an authentication scheme | This command |
143
+ | `resource-required` | The declaration has a requirement evaluated asynchronously, such as a policy that reads the command, and no command instance or context was passed | This command; pass the instance |
144
+ | `principal-selection` | The runtime selected another authenticated identity than the one supplied | This command |
145
+ | `async-runtime-required` | A requirement needs an asynchronous authorization runtime the provider does not have | This command |
146
+ | `invalid-configuration` | Invalid or ambiguous authorization declarations or policy registrations | This command |
147
+ | `read-model-key-resolution` | Authorization encountered a read-model key-resolution denial; reproduce binding in a command scenario | This command |
148
+
149
+ A matrix therefore has two kinds of expected cell, and both are asserted with the verdict helpers, never by comparing `Outcome` or `Message` strings: `ShouldBeAuthorized()` or `ShouldBeDenied()` where the check can evaluate, and `ShouldBeUnsupported()` plus the `ReasonCode` where it cannot. An Unsupported cell is not a pass or a fail of the rule: add a `CommandScenario` or hosted spec for it. Expecting `Authorized` for a `[RequiresApproval]` command, or a role verdict from a provider that discovers a custom filter, is a wrong expectation.
150
+
151
+ If authorization and validation succeed, both `Execute` and `Validate` refuse a `[RequiresApproval]` command with no registered flow, with `IsAuthorized == false`; the handler does not run. `Validate` runs authorization and the validation filters and then that approval refusal; it never resolves arguments or runs `Provide()` or `Handle()`, so a refusal those raise is proven only with `Execute`.
152
+
120
153
  ## Check wiring across all commands
121
154
 
122
155
  A scenario proves one invocation. `CommandWiring` checks every command's declarations against the application's configured, scoped service provider, so a `Handle()` dependency or a discoverable validator's constructor dependency that is not registered fails one spec instead of surfacing at run time.
@@ -4,10 +4,7 @@ Applies when a command claims uniqueness, or decides from history that another w
4
4
 
5
5
  ## Prove a uniqueness claim
6
6
 
7
- Exercise a real claim, then a conflicting one from a different source. The scenario has two seeding paths, and only one of them reaches the constraint:
8
-
9
- - `_scenario.EventScenario.Given.ForEventSource(id).Events(...)` appends to the scenario's event log. Constraints see these events.
10
- - `_scenario.Given.ForEventSource(id).Events(...)` supplies the state the command's read models are built from.
7
+ Exercise a real claim, then a conflicting one from a different source. This example uses decision mode. Seed the existing claim through `Given` so the constraint sees it in the shared log. For a legacy-mode scenario, seed the constraint's history through `EventScenario.Given` instead.
11
8
 
12
9
  This fragment assumes the application registers a unique-name constraint over `CarrierRegistered.Name` and exposes its registered name as `CarrierConstraintNames.UniqueName`. Seeding an event does not register a constraint.
13
10
 
@@ -19,7 +16,7 @@ public class when_registering_a_carrier_with_a_taken_name : Specification
19
16
  readonly CommandScenario<RegisterCarrier> _scenario = new();
20
17
  CommandResult _result = null!;
21
18
 
22
- Task Establish() => _scenario.EventScenario.Given.ForEventSource(_existing).Events(new CarrierRegistered("Aster"));
19
+ void Establish() => _scenario.Given.ForEventSource(_existing).Events(new CarrierRegistered("Aster"));
23
20
  async Task Because() => _result = await _scenario.Execute(new RegisterCarrier(_carrier, "Aster"));
24
21
  void Destroy() => _scenario.Dispose();
25
22
 
@@ -32,12 +29,12 @@ public class when_registering_a_carrier_with_a_taken_name : Specification
32
29
 
33
30
  ## Prove a guarded decision
34
31
 
35
- A command that declares read protection, `[ProtectedDecision]`, a `DecisionRead<T>` parameter or a per-stream read model is run in decision mode automatically. One shared log then supplies seeded history, the guarded read and the commit.
32
+ A command whose read protection is `On` or `Measure` runs in decision mode automatically, and so does one with `[ProtectedDecision]`, a `DecisionRead<T>` parameter or a per-stream read model. Read protection is `On` unless the project or the command turns it off, so this is the usual mode; the exact rule is the mode table in [csharp-command-results.md](csharp-command-results.md). One shared log then supplies seeded history, the guarded read and the commit.
36
33
 
37
34
  - Seed with `_scenario.Given.ForEventSource(id).Events(...)`. `_scenario.EventScenario` throws in this mode.
38
35
  - Give the command state and assert the outcome. Do not invent sequence numbers or decision tokens, and do not simulate a concurrent writer: the guard itself is the framework's behavior, already covered there.
39
36
  - Let Arc complete a protected command's unit of work: the command returns its events. Calling `Commit()` or `Rollback()` on that unit of work directly fails with `ProtectedUnitOfWorkRequiresOwner`. An aggregate root's own `Commit()` is narrower than it looks. Arc completes it as the owner only when read protection is on and the aggregate belongs to that command's own unit of work, not to a unit inherited from an outer command. Otherwise it is a direct completion, which fails the same way once protected reads have enrolled in the unit. A command executing as an occurrence effect refuses any early commit. Where the aggregate commit applies, read first and return that `Commit()` last; in every other case return the events.
40
- - `EnableDecisionReads()` exists only for an untyped `CommandScenario<object>` that executes protected commands; call it before seeding. A typed scenario needs no switch.
37
+ - For an untyped `CommandScenario<object>`, call `EnableDecisionReads()` before seeding or executing. Typed scenarios select their initial store automatically; the same method can explicitly opt a legacy-mode typed scenario into the shared log.
41
38
  - `AppendConcurrently(source, events)` (or `(source, route, events)`) queues competing events to append after the handler reads and before the commit. It is hidden from editor completion and exists to verify the framework's concurrency handling; use it only when the task explicitly asks to prove a guard against an interleaved writer, then assert `ShouldHaveValidationErrorBecauseOf(ValidationResultReason.ConcurrencyViolation)` and that nothing was appended. Queue it before the first `Execute`.
42
39
 
43
40
  Setup errors in decision mode, all fixed in the spec:
@@ -41,7 +41,7 @@ A successful result without the expected ID does not satisfy the query contract.
41
41
 
42
42
  Both `Perform` and `Observe` take optional `paging` (`Paging`) and `sorting` (`Sorting`) arguments after the query arguments and a `CancellationToken` last; `Observe` also takes a `timeout` for the first emission, and `Next(timeout)` one for the next. A scenario extender (`IQueryScenarioExtender`) can publish helpers through `scenario.Context`; the Chronicle package uses it for `Given`.
43
43
 
44
- Events seeded through `Given.ForEventSource(id).Events(...)` run the application's own projection or reducer, including children and joins, so the query is proven against the model production would hold. After `Observe`, seed further events and await `observation.Next()` to prove the query pushes the changed model.
44
+ Events seeded through `Given.ForEventSource(id).Events(...)` run the application's own projection or reducer, including children and joins, so the query is proven against the model production would hold. A query method that calls `IReadModels.GetInstances<T>()` is the exception: its result fails with a message containing "not available in test scenarios" for seeded events and pinned instances alike, so prove that query against a running kernel. `GetInstanceById` and `Observe<T>()` are served. After `Observe`, seed further events and await `observation.Next()` to prove the query pushes the changed model.
45
45
 
46
46
  ## Observe what a command appends
47
47
 
@@ -63,16 +63,15 @@ foreach (var service in commands.Services) queries.Services.Add(service);
63
63
  foreach (var (key, value) in commands.Context) queries.Context[key] = value;
64
64
  ```
65
65
 
66
- Then seed with `queries.Given.ForEventSource(id).Events(...)`, open `await queries.Observe(...)`, run `await commands.Execute(...)` and assert the result of `await observation.Next()`.
66
+ Then seed once with `queries.Given.ForEventSource(id).Events(...)` and run `await commands.Execute(...)`. `QueryScenario` has no mode switch and follows the command scenario's store, which the command type selects (the mode table is in [csharp-command-results.md](csharp-command-results.md)).
67
67
 
68
- State each prior event exactly once. After sharing, `queries.Given` and `commands.Given` write to the same seed store, and the observation also receives every successful append to the command's log, including events placed there with `commands.EventScenario.Given`. An event stated through two of those is folded twice, so counts and sums double.
68
+ Default: after `Execute`, assert the updated content with `await queries.Perform(...)`. To also observe a query backed by `IReadModels.Observe<T>()`, subscribe before executing and await `Next()` only when the append changes the observed result. With effective `On`, a refold that runs inside the command's protected scope can terminate that observation, so verify delivery through the host instead. Do not lower the command's read protection to make the observation pass. Decision mode can also run with rollout `Off`; it still uses the shared log.
69
69
 
70
- | Mode | What the observation folds | Where a seed lands |
71
- | --- | --- | --- |
72
- | Default | The `Given` seeds plus the command log's successful appends | `Given` seeds feed injected read models and the observation, and never enter the command log |
73
- | Decision | One log shared by seeds, commands and observation | `Given` seeds enter that log; `commands.EventScenario` throws |
70
+ In legacy mode, `Perform` of an observable query after `Execute` also includes the append, but a query that reads one instance with `GetInstanceById` still returns the seeded state without the command's append.
74
71
 
75
- `QueryScenario` has no decision-mode switch: the command scenario selects the mode and the shared query follows it.
72
+ Always assert `IsSuccess` on the result of `Next()` before its data: a failed result has no data, so a cast of `Data` alone hides the reason, which is in `ExceptionMessages`.
73
+
74
+ State each prior event exactly once. After sharing, `queries.Given` and `commands.Given` write to the same seeds: in decision mode both enter the one shared log, and in legacy mode the observation folds those seeds plus every successful append to the command's log, including events placed there with `commands.EventScenario.Given`. An event stated through two of those is folded twice, so counts and sums double. `commands.EventScenario` throws in decision mode.
76
75
 
77
76
  An observed query merges a row pinned with `.ReadModel(instance)` by its identifier: `[Key]`, then `[Subject]`, then a property named `Id`. A pinned instance without a readable identifier, or with a null one, cannot be merged. `scenario.Observe` does not throw for it: the failure arrives as a failed query result carrying the `PinnedReadModelCannotBeObserved` message. Where it arrives depends on when the instance was pinned:
78
77
 
@@ -10,7 +10,7 @@ Names are illustrative; the application's own domain language replaces them.
10
10
  - **Read the result by key.** `scenario.Instance` is the single materialized instance and throws when there are several; use `scenario.InstanceForEventSourceId(id)` or `scenario.Instances` then. `ShouldPartiallyMatchReadModel(id, new { Status = "Held" })` recursively checks only the listed public properties at that key, `ShouldExactlyMatchReadModel(id, expected)` the complete public property set, and `ShouldHaveNoReadModel(id)` absence.
11
11
  - **Several sources feed one model.** `CollectEventsFor(id, events)` accumulates events per source and they are processed together on the next read, which a model with children from other streams needs; `await ProcessEventsFor(id, events)` collects bare events for the next read.
12
12
  - **Start from existing state when that is the premise.** `await scenario.Given.ForEventSource(id).ReadModel(existing)` seeds an instance; later events fold on top of it. `Given.ForKey(...)` seeds a composite key. Seeding the same key twice throws `ReadModelAlreadySeeded`.
13
- - **Reuse real envelopes.** `ProcessAppendedEvents(events)` applies `AppendedEvent` values captured elsewhere with their original context.
13
+ - **Reuse real envelopes.** `ProcessAppendedEvents(events)` applies `AppendedEvent` values captured elsewhere with their original context. Only an envelope carries the original `Occurred`, including its UTC offset: a bare event passed to `Given...Events(...)` or `ProcessEventsFor` gets the time of the spec run. A regression about a value taken from the event context therefore needs the envelopes. `DateTimeOffset` equality compares the instant and ignores the offset, so `ShouldEqual` passes when only the offset changed: assert `actual.EqualsExact(expected)` or the `Offset` as well.
14
14
  - **Do not replace the definition under test.** `WithProjection(builder => ...)` overrides discovery, including a discovered reducer, so the spec then proves the inline recipe instead of the application's. Use it only for a model with no definition of its own. A missing or ambiguous definition is a failure to fix, not a reason to substitute one.
15
15
  - **Catch a silent drop.** `WithStrictEventSubscription()` makes a seeded event the model does not subscribe to throw instead of being ignored.
16
16
 
@@ -75,14 +75,36 @@ Every scenario here runs in process. None of them proves observer delivery, stor
75
75
 
76
76
  | Scenario | It does not prove | Do not combine |
77
77
  | --- | --- | --- |
78
- | `CommandScenario` | That a query or subscription sees what the command appended. That needs a query scenario sharing its services and context: [csharp-query-scenario.md](csharp-query-scenario.md). | Seeds in two places for one fact. In default mode `Given` supplies injected read-model state and `EventScenario.Given` supplies log history. |
79
- | `QueryScenario` | Anything about a command scenario created independently: the two have separate state, so waiting for the next emission times out. | The same event seeded through both `commands.Given` and `queries.Given` once the scenarios are shared: they write to one seed store and the observation folds both copies. Seed each event once. |
78
+ | `CommandScenario` | That a query or subscription sees what the command appended. That needs a query scenario sharing its services and context: [csharp-query-scenario.md](csharp-query-scenario.md). | One fact seeded through both `Given` and `EventScenario.Given`, or `EventScenario` at all in decision mode, where it throws. Decide the mode first: [csharp-command-results.md](csharp-command-results.md). |
79
+ | `QueryScenario` | Anything about a command scenario created independently: the two have separate state, so waiting for the next emission times out. A query whose method calls `IReadModels.GetInstances<T>()`: the result fails with a message containing "not available in test scenarios", whatever was seeded. Prove that query against a running kernel. | The same event seeded through both `commands.Given` and `queries.Given` once the scenarios are shared: they write to one seed store and the observation folds both copies. Seed each event once. |
80
80
  | `EventScenario` | That a projection, reducer or reactor was delivered the event by an observer. `ReadModels` folds the scenario's own log on each read. | Appends through `Defaults.Instance.EventStore` or another store: that is a different log, which this scenario's `ReadModels` never reads. |
81
81
  | `ReadModelScenario` | Collection reads and subscriptions. It collects its input instead of appending it to a log, so its `ReadModels` serves only `GetInstanceById` for seeded instances. | `ReadModels.GetInstances` or `ReadModels.Observe` expecting the scenario's output: `Observe` throws `ReadModelCannotBeObserved` and `GetInstances` needs a running Chronicle. Assert through `Instance`, `Instances` or `InstanceForEventSourceId`. Hand code that enumerates or observes through `IReadModels` the `ReadModels` of an `EventScenario` instead ([csharp-events.md](csharp-events.md)). |
82
82
  | `ReactorScenario` | That anything was sent, appended or executed. The default recorder records what the reactor returned; it does not append events, execute commands or call a registered `IReactorSideEffectHandler`. | An assertion on a gateway or a substitute behind a side-effect handler after a default-recorder run: it was never called. Assert `Produced` or `ShouldHaveProduced<T>`, and prove the effect in a spec of the handler or against a running kernel. |
83
83
 
84
84
  A reactor that returns a custom type still needs an `IReactorSideEffectHandler` claiming that type registered in `scenario.Services`; without one, the scenario throws `InvalidReactorHandlerReturnType`. The registration only makes the return type legal: the recorder keeps the value and the handler does not handle it.
85
85
 
86
+ ### Members each scenario has
87
+
88
+ Use only these. A member a neighbouring scenario has is not implied here: writing it is a compile error, not a setup error.
89
+
90
+ | Scenario | Arrange and act | Read and assert | It has no |
91
+ | --- | --- | --- | --- |
92
+ | `CommandScenario<TCommand>` | `Given`, `WithClaims`, `WithPrincipal`, `Unauthenticated`, `Tenant`, `Clock`, `PinGeneratedValue`, `Services`, `Execute`, `Validate` | The returned `CommandResult`, `LastResult`, `AppendedEvents`, `EventLog`, `ShouldHaveAppendedEvent...`, `ShouldNotHaveAppendedEvents` | `When`, `ReadModels`, `Perform` |
93
+ | `QueryScenario<TReadModel>` | `Given`, `Services`, `Perform`, `Observe` | The returned `QueryResult`; `Initial` and `Next()` on the observation | `When`, `ReadModels`, `EventLog`, `Execute`, `WithClaims`, `WithPrincipal`, `Unauthenticated` |
94
+ | `EventScenario` | `Given`, `When`, `Time` | Append results, `EventLog`, `ReadModels` | `Services`, `Instance`, `Instances` |
95
+ | `ReadModelScenario<TReadModel>` | `Given`, `ProcessEventsFor`, `ProcessAppendedEvents`, `Services`, `Substitutions` | `Instance`, `Instances`, `InstanceForEventSourceId`, `InstanceForKey`, `Should...ReadModel` | `When`, `EventLog`, a working `ReadModels.GetInstances` or `ReadModels.Observe` |
96
+ | `ReactorScenario<TReactor>` | `Given`, `Redeliver`, `Services` | `Produced`, `ProducedEvents`, `PartitionOutcomes`, `ShouldHaveProduced...`, `ShouldHaveDeferred`, `ShouldHaveFailed` | `When`, `EventLog`, `AppendedEvents`, `Instance` |
97
+
98
+ `IReadModels` in process, by where it comes from:
99
+
100
+ | Source of `IReadModels` | `GetInstanceById` | `GetInstances` | `Observe` |
101
+ | --- | --- | --- | --- |
102
+ | `EventScenario.ReadModels` | Folded from the scenario's log | Folded from the scenario's log | Emits the initial collection, then emits changed results after successful append batches |
103
+ | `ReadModelScenario.ReadModels` | Only an instance pinned with `.ReadModel(...)`; `null` for a source that has only events | Throws `GrainNotAvailableInTestScenario` | Throws `ReadModelCannotBeObserved` |
104
+ | Injected into a query run by `QueryScenario` | Folded from the seeds | The query result fails | Emits the folded collection |
105
+
106
+ So the default for code that takes `IReadModels` and enumerates or observes it is an `EventScenario`: append the history with its `Given` and pass its `ReadModels`. Never substitute `IReadModels` by hand to prove such code: a substitute returns what the spec told it and exercises no fold.
107
+
86
108
  ## Default path: refuse an invalid command
87
109
 
88
110
  Seed another registration so earlier history is distinguishable from this command’s work.
@@ -161,7 +183,7 @@ Awaited assertions on the scenario: `ShouldHaveAppendedEvent<TCommand, TEvent>(i
161
183
 
162
184
  ## Seeding before the act
163
185
 
164
- `Given.ForEventSource(id)[.OnRoute(route)].Events(...)` and `.ReadModel(instance)`; `EventRoutes` resolves a route; in an ordinary scenario, `EventScenario.Given` seeds the log that constraints see; routed seeds need decision mode, which commands with decision dependencies use automatically; there `Given` seeds one shared log and `EventScenario` throws. Guarded reads, uniqueness, competing writers (`AppendConcurrently`) and `DecisionReadAdmissions`: [csharp-decision-reads.md](csharp-decision-reads.md).
186
+ `Given.ForEventSource(id)[.OnRoute(route)].Events(...)` and `.ReadModel(instance)`; `EventRoutes` resolves a route; the scenario runs in decision mode unless the command's read protection is `Off` and it declares no decision dependency: `Given` then seeds one shared log, routed seeds work and `EventScenario` throws. In legacy mode `Given` seeds injected read models only and `EventScenario.Given` seeds the log that constraints see. The mode table is in [csharp-command-results.md](csharp-command-results.md). Guarded reads, uniqueness, competing writers (`AppendConcurrently`) and `DecisionReadAdmissions`: [csharp-decision-reads.md](csharp-decision-reads.md).
165
187
 
166
188
  ## Slice
167
189
 
@@ -15,6 +15,26 @@ Use the browser frontend's SDK reference regardless of the backend SDK. This ski
15
15
  - **Native browser check.** Use the existing browser runner for real Tab order, Shift+Tab, or a held key. A play function can test activation after explicitly focusing a trigger, but simulated traversal does not prove native tab order. A browser-mode spec also fits a composition that should not have a story.
16
16
  - **Live application check.** Use the running app for a routed page that depends on real identity, commands, or live queries. Do not turn a connected page into a backend-dependent story. When delivery matters, submit a unique value in a disposable namespace and wait for its result on the same page without reloading. See Live submission in your language reference.
17
17
 
18
+ ## What each observation proves
19
+
20
+ | Observation | Proves | Does not prove |
21
+ | --- | --- | --- |
22
+ | Story run in the browser test run, with fixtures | The composition's interaction for the fixture's data: activation, the named dialog, input, dismissal, focus return, feedback for a fixture refusal | Any backend rule, real command acceptance, live query delivery, native Tab order |
23
+ | Native browser check on the isolated preview | Real Tab and Shift+Tab order, focus containment, held-key repeat | Backend behavior; anything outside the browsers it ran in |
24
+ | Live application check | The submitted value became visible without a reload. To prove live delivery, also verify that the update came from the live query, not optimistic state, polling or a refetch. | Which backend rule decided it, the refusal branches, or delivery in another environment |
25
+ | Accessibility scan | That the scanned content has no detectable violation | Keyboard usability or focus order |
26
+ | Static story build or story typecheck | A build checks bundling; a typecheck checks types | That any play function ran or passed |
27
+
28
+ Do not present one as another:
29
+
30
+ - **A fixture refusal as a rule.** A story that shows "name already in use" proves the feedback, not uniqueness. The rule belongs to `cratis-specifications-exercise-backend`.
31
+ - **A story against a running backend.** It is neither deterministic nor a live check. Stop the backend for stories; use the live check for delivery.
32
+ - **Simulated traversal as native order.** A play function's simulated Tab does not prove the browser's tab order.
33
+ - **Two key presses as a held key.** Only a second keydown while the key is still down carries the repeat flag.
34
+ - **A reload in a live check.** A row visible after reload is evidence about the reloaded page, not live delivery.
35
+ - **A reused value in a live check.** A row left by an earlier run satisfies the wait.
36
+ - **An excluded story as a gate.** A story tagged out of the test run has executed nothing.
37
+
18
38
  ## Default path
19
39
 
20
40
  1. Put the application's relevant providers, router and entry-point styles in the preview. Supply fixed props and data. Before mounting any connected composition, install deterministic identity, query, validation and command fixtures for every path it uses; block unexpected backend traffic. Done when the preview renders correctly with the backend stopped. See Preview in your language reference.
@@ -6,3 +6,20 @@ Use this reference in the React frontend workspace, independent of which SDK hos
6
6
  - [Native keyboard checks and live submission](typescript-browser.md) — use browser-driven keys for actual Tab order or held-key behavior. Use the authenticated application only when the proof needs the live page, such as a command's result appearing without a reload.
7
7
 
8
8
  Not supported by a story: real command acceptance or live query delivery — do those checks against the owning application instead. For Arc server tests, use `cratis-specifications-exercise-backend`; for view-model decisions, use `cratis-specifications-test-application-ui`.
9
+
10
+ ## What ships and what the application owns
11
+
12
+ | Need | Where it comes from |
13
+ | --- | --- |
14
+ | Showcase layout: `StoryContainer`, `StorySection`, `StoryGrid`, `StoryDivider`, `StoryBadge` | `@cratis/arc.react/stories`, with `@cratis/arc.react/stories/styles.css`. These five are the whole story kit. |
15
+ | Refusal and result fixtures | Arc's own result types: `CommandResult` from `@cratis/arc/commands`, `QueryResult` from `@cratis/arc/queries`, `ValidationResult` from `@cratis/arc/validation` |
16
+ | Command, query, identity and transport fixtures; preview decorators; request interception | The application. No Cratis package ships them. |
17
+ | Play-function helpers and assertions | `storybook/test` |
18
+ | Native keys and the live check | The project's browser runner |
19
+
20
+ Do not import these; they do not exist or are for something else:
21
+
22
+ - `@cratis/components/testing`, `@cratis/components/stories` and `@cratis/arc.react/testing`: no such entry points.
23
+ - `@cratis/arc.testing` in a frontend story or browser check: it holds the Arc Node server's command and query scenarios and renders nothing.
24
+ - A Cratis mock backend, fake command proxy or story decorator for Arc: build the fixture as a subclass of the generated proxy or a fixed provider value, as the Storybook reference shows.
25
+
@@ -10,6 +10,7 @@ compatibility: Requires the application's frontend test project and its installe
10
10
 
11
11
  - What it is
12
12
  - When to use it
13
+ - What a spec proves
13
14
  - How it behaves at runtime
14
15
  - Default path
15
16
  - Capability catalog
@@ -29,12 +30,19 @@ An application UI spec proves a decision a screen makes: what it keeps, closes,
29
30
  - **Render the component** only for behavior the view model cannot show. Use static markup for an initial app-owned output contract; mount for provider-driven gating, routing or DOM interactions. Query by accessible role and name; use a browser when the assertion depends on browser behavior.
30
31
  - **Not this skill**: browser evidence for focus, keyboard or portals, or live command-to-row delivery (see `cratis-specifications-observe-ui`); backend decisions; logic with no UI.
31
32
 
33
+ ## What a spec proves
34
+
35
+ A UI spec proves what the screen does with the result the spec supplies. It does not prove that the backend returns that result, that a rule exists, or that the request is well formed. See What each spec proves in your language reference.
36
+
37
+ - The real execute first runs the command's client rules and required-property checks, returning a validation failure without a request; on success it resets change tracking. A stubbed execute does neither.
38
+ - To prove what a form refuses with no backend, call the synchronous client-side validation on a real generated proxy. Asynchronous validate and execute contact the server once local checks pass; never call them unstubbed.
39
+ - A rule only the server can evaluate belongs in a backend spec, not behind a canned refusal.
40
+
32
41
  ## How it behaves at runtime
33
42
 
34
43
  - Generated command proxies post over HTTP. Query proxies fetch over HTTP; observable queries receive pushes (the Arc host defaults to Server-Sent Events; WebSocket and polling are configurable). A spec replaces the proxy's execute, perform or subscribe, so nothing goes over the wire.
35
44
  - Command outcomes and caught request failures resolve as results: branch on flags for refusals, server exceptions, unknown routes and failed fetches. Setup can throw before the request is caught (for example, a missing origin or a throwing headers callback); a collaborator can also throw. Test rejection separately when the screen handles it.
36
45
  - The client takes a result's flags exactly as given and derives none. A hand-built failure must also say it did not succeed, or success callbacks run.
37
- - Before sending, the real execute runs the command's client rules and required-property checks and returns a validation failure without a request. On success it resets change tracking. A stubbed execute does neither.
38
46
  - Validation results carry `members` (field paths). A command form shows a message on a field when a member equals the field's property name or is a dotted path under it, case-sensitive.
39
47
  - An unauthorized result whose reason is `NotAvailable` or `Suspended` is the availability signal; any other unauthorized result is a plain authorization failure. Unauthorized callbacks fire for all three.
40
48
  - Query results carry data, success, authorized, valid, exception and ready flags, validation results, paging and, for observable list queries, an optional change set. Observable queries deliver each result through a subscription callback.
@@ -177,7 +185,6 @@ Done when the affected specs, lint and type check pass and inverting a faked res
177
185
  - Do not use a rejection to simulate a resolved refusal or fetch failure; separate the two paths.
178
186
  - A validation result whose member differs in case or name from the property shows on no field.
179
187
  - A hand-built failure left marked successful runs success callbacks.
180
- - A stubbed execute lets a draft missing required values "succeed".
181
188
  - Forgetting to clear caches or restore prototype stubs makes later spec files order-dependent.
182
189
  - Mounting to test a decision the view model owns makes the spec slow and brittle.
183
190
  - Application specs and Storybook builds do not run story `play` functions. The interactive preview can run them; use a browser story test run as the gate.
@@ -3,6 +3,7 @@
3
3
  ## Contents
4
4
 
5
5
  - Packages and imports
6
+ - What each spec proves
6
7
  - Runner and structure
7
8
  - View-model spec
8
9
  - Command results
@@ -37,6 +38,49 @@ Use this reference for the React frontend regardless of the backend SDK; a React
37
38
  | `Navigation`, `INavigation`, `ILocalStorage` | `@cratis/arc.react.mvvm/browser` |
38
39
  | `MVVM`, `IHandleProps`, `IHandleParams`, `IHandleQueryParams`, `IPropsChanged`, `IViewModelDetached` | `@cratis/arc.react.mvvm` |
39
40
 
41
+ ## What each spec proves
42
+
43
+ Default: a view-model spec with the proxy methods stubbed. Pick another row only for the promise in its second column.
44
+
45
+ | Spec | Proves | Does not prove |
46
+ | --- | --- | --- |
47
+ | View model with `execute`, `perform` or `subscribe` stubbed | What the screen keeps, closes, navigates to, publishes or shows for that result | That the server returns that result, that the rule behind a refusal exists, local validation, the request |
48
+ | `validateClientSide()` on a real generated proxy | Which drafts are refused before any request | Server-only rules, or how the screen displays the failure |
49
+ | Real `execute` against a stubbed `fetch` | Local validation ahead of the request, the request itself, the change-tracking reset | Anything about the server: the envelope is the spec's own text |
50
+ | Static markup | The initial app-owned markup | Effects, state updates and event handling, which never run |
51
+ | Mounted component under the DOM test environment | Provider-driven gating, routing and the DOM events the component handles | Layout, native Tab order, held keys, and live command-to-row delivery |
52
+
53
+ Combinations to avoid:
54
+
55
+ - **A canned refusal as proof of a rule.** A stubbed `execute` or `fetch` that answers "not certified" proves the screen's reaction, not the rule. The rule is proven in a backend spec (`cratis-specifications-exercise-backend`, or `cratis-arc-testing-typescript` for an Arc Node server).
56
+ - **`validate()` or an unstubbed `execute()` in a suite with no backend.** Both send a request for every draft the local checks accept.
57
+ - **The same case at two layers.** Mount only for what the view-model spec cannot show.
58
+ - **A status code as a result.** For command calls and query `perform()`, model unauthorized outcomes with a complete result envelope containing `isAuthorized: false` and `isSuccess: false`, not a bare `401` or `403`. Polling subscriptions are different: they recognize those statuses and can synthesize an unauthorized result. Commands special-case `404`; queries using Auto can retry `405` or `501` with GET. Build the unauthorized result with the envelope helper in Command results.
59
+
60
+ ### Client validation in a UI spec
61
+
62
+ Use a real proxy and the synchronous call; nothing is stubbed and nothing is sent. This proxy carries a mirrored `notEmpty()` rule for `name`:
63
+
64
+ ```ts
65
+ const command = new RegisterInspector();
66
+ command.name = 'Kari Nordmann';
67
+ command.validateClientSide().isValid.should.be.true;
68
+
69
+ command.name = '';
70
+
71
+ const result = command.validateClientSide();
72
+ result.isValid.should.be.false;
73
+ result.validationResults.flatMap(_ => _.members).should.contain('name');
74
+ ```
75
+
76
+ - `validateClientSide()` runs the generated rules, then the required-property check, and returns a `CommandResult` synchronously.
77
+ - `await command.validate()` runs the same local steps and returns without a request only when one of them blocks. For a draft they accept, it POSTs to the command's route with `/validate` appended. It is the wrong call for a spec that must pass with no backend.
78
+ - The required-property check refuses only `null` and `undefined`. A cleared text field holds `''`, which passes it; `''` is refused only when the proxy carries a mirrored rule such as `notEmpty()`. Spec the cleared field and the never-set field as separate cases when both matter.
79
+ - `command.validation.validate(command)` runs the rules alone, without the required-property check. Do not use it in place of `validateClientSide()`.
80
+ - Rules that need the server (`Must`, `MustAsync`, `When`, `Unless`, custom validators, anything that reads state) are not on the proxy. For those, the UI spec stubs `execute` to resolve `CommandResult.validationFailed([...])` and proves only what the screen does next.
81
+
82
+ The result shape, the severity behaviour and the full list of what is mirrored are in `cratis-specifications-test-typescript-behavior`, Generated command client validation.
83
+
40
84
  ## Runner and structure
41
85
 
42
86
  Dev dependencies of the frontend project: `vitest`, `chai`, `chai-as-promised`, `sinon`, `sinon-chai`, typings for the Mocha-style globals (`@types/mocha`), typings for the assertion libraries that do not bundle their own (`@types/chai`, `@types/chai-as-promised`, `@types/sinon`, `@types/sinon-chai`), and a reflect-metadata polyfill (`reflect-metadata` or `@cratis/fundamentals/reflection`). View models carry `tsyringe` decorators, and `tsyringe` throws on import without the polyfill. Mounted specs also need `@testing-library/react`, its peer `@testing-library/dom` (the package manager does not add it for you) and `jsdom`. Use what the app already has.
@@ -298,7 +342,7 @@ export const commandResult = (overrides: Partial<CommandEnvelope>, responseType:
298
342
  - `severity` is a `ValidationResultSeverity`: `Unknown`, `Information`, `Warning` or `Error`.
299
343
  - `members` names the fields. A command form attributes a result to a field when a member equals the property name exactly (case-sensitive) or is a dotted path that starts with it (`startsAt.Value`).
300
344
  - `reason` defaults to `ValidationResultReason.Rule`. The others are `ConcurrencyViolation`, `ConstraintViolation`, `ValidatorFailed`, `DependencyUnavailable`, `MalformedRequest` and `FrameworkFailure`. `ValidationResultReasonDetail.Required` marks a missing required value.
301
- - Warning-confirmation flows: `execute(allowedSeverity?, ignoreWarnings?)`. Without arguments only `Error` blocks on the client. A proxy generated for a command that declares a blocking severity sets `blockOnValidationSeverity`; client results at or above it then block whatever the caller allows. Assert that the re-submit passed `ValidationResultSeverity.Warning` or `ignoreWarnings` `true` (`context.execute.secondCall.args`).
345
+ - Warning-confirmation flows: `execute(allowedSeverity?, ignoreWarnings?)`. Without a declared blocking severity and with default caller options, only `Error` blocks locally. With a declared floor, findings at or above it and `Unknown` block; caller options cannot weaken that floor. `validateClientSide()` lists advisory findings without marking the draft invalid. Assert that the re-submit passed `ValidationResultSeverity.Warning` or `ignoreWarnings` `true` (`context.execute.secondCall.args`).
302
346
 
303
347
  What you give up by stubbing `execute`: the real `execute` first runs the command's client rules and required-property checks. If either fails, it returns a validation failure without sending a request; a missing required property gets the message `<name> is required` with the property as its member. On success it also resets the change-tracking baseline (`hasChanges`). To prove either behaviour, keep the real `execute` and stub `fetch` (see Isolation and reset), or call `validateClientSide()`, which returns the client result synchronously. The other command members you can drive or assert are `validate()`, `clear()`, `setInitialValues(values)`, `setInitialValuesFromCurrentValues()`, `revertChanges()`, `hasChanges` and `onPropertyChanged(callback, thisArg)`.
304
348
 
@@ -9,6 +9,7 @@ description: Use when writing or repairing an isolated TypeScript spec for a cal
9
9
 
10
10
  - What an isolated spec is
11
11
  - Choose the boundary
12
+ - What each spec proves
12
13
  - How a given context behaves
13
14
  - Default path
14
15
  - Capability catalog
@@ -34,6 +35,26 @@ Read `references/<language>.md` for the project's SDK (`.csproj` → csharp, Nod
34
35
 
35
36
  A direct call bypasses Arc's pipeline. Cover the decision's branches directly and prove the wiring at the pipeline layer, not the same rule at both layers. Skip getters, forwarding, and other trivial code with no consequential behavior of its own.
36
37
 
38
+ ## What each spec proves
39
+
40
+ Default: call the behavior directly with explicit inputs. Reach for the other rows only when the promise is the one named in their first column.
41
+
42
+ | Spec | Proves | Does not prove |
43
+ | --- | --- | --- |
44
+ | Direct call of a function, view model or handler | The decision for those inputs | Validation, authorization, binding or encoding around it |
45
+ | `validateClientSide()` on a real generated command proxy | Which drafts the browser refuses before any request | That the server accepts the draft, or any rule that exists only on the server |
46
+ | Real proxy call against a stubbed `fetch` | The request the proxy sends, and how the caller treats the envelope the stub returns | That a server would return that envelope: the rule, status code, authorization and route are the stub's invention |
47
+ | Stubbed proxy method (execute, perform, subscribe) | What the caller does with that result | Local validation, the request and change tracking, which the stub skips |
48
+
49
+ Do not combine them into a false proof:
50
+
51
+ - A canned refusal from a stubbed `fetch` or a stubbed proxy method is not evidence that the rule exists. Prove the rule where it runs.
52
+ - The proxy's asynchronous validate and its execute reach the server for every draft the local rules accept. Neither belongs in a spec that must pass with no backend unless `fetch` is stubbed.
53
+ - A stubbed `fetch` does not feed an observable query's subscription over a socket or event source. Stub the subscription.
54
+ - Do not assert the same rule at two layers. The client mirror gets one case per rule the screen depends on; the server rule is proven once in the pipeline.
55
+
56
+ See Generated command client validation and Proxies against a stubbed fetch in your language reference for the exact calls, what the client reads from a response, and the members that do not exist.
57
+
37
58
  ## How a given context behaves
38
59
 
39
60
  The `given` helper takes a context type and a callback and returns the body of a suite. See Given context lifetime in your language reference when a spec passes alone but fails with its siblings, when a context constructor receives `undefined`, or when choosing between per-test and per-suite setup.