@oxface/modular-monolith-patterns 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,100 @@
1
+ # Modular monolith patterns
2
+
3
+ Apply these documents to a consuming application's repository. They describe a preferred
4
+ structure and implementation process, not a generated template or required Gloaming runtime.
5
+ The documents can be read in place or copied as one folder; implementation instructions
6
+ use sibling documents and public library contracts.
7
+
8
+ ## Install the skill
9
+
10
+ The npm distribution is `@oxface/modular-monolith-patterns`; its first public version is
11
+ 0.1.0. Select a published version, then run from the consuming repository:
12
+
13
+ ```sh
14
+ npx --yes @oxface/modular-monolith-patterns@VERSION install --dry-run
15
+ npx --yes @oxface/modular-monolith-patterns@VERSION install
16
+ ```
17
+
18
+ Installation creates `.agents/skills/modular-monolith-patterns/` with `SKILL.md` and all
19
+ supporting documents. `--target PATH` selects another explicit skill directory. `--update`
20
+ replaces an unchanged managed installation after review; edited, unmanaged or additional files
21
+ are preserved through a conflict. Symlink destinations/ancestors are rejected. Dry runs create
22
+ no destination folders. The installer changes no project manifests, agent instructions or
23
+ Git index. Reload the consuming agent's skill discovery when needed.
24
+
25
+ The bundle is built from these source documents, with repository links pinned to its source
26
+ revision. Installation performs no network fetch; npm obtains the package first. Node24 is
27
+ the supported runtime, and the packed-package installation proofs currently run on Linux.
28
+ See [release delivery](https://github.com/oxface/gloaming/blob/b5d9b70171b579565eec21a94f76a774a90347d7/docs/releases.md) for
29
+ publication and [local checks](#develop-the-distribution) for validating package candidates.
30
+
31
+ A request can be as small as:
32
+
33
+ > Explore the documentation in /modular-monolith-patterns and apply it to this repository.
34
+ > Start with modules X (AggregateA, AggregateB) and Y (AggregateE with event sourcing).
35
+
36
+ ## Start here
37
+
38
+ 1. Inspect the target repository's instructions, solution, tooling, existing architecture and
39
+ working changes. Establish the application name, requested modules/aggregate roots, persistence
40
+ choice per aggregate and the first behavior to prove. Preserve unrelated work.
41
+ 2. Read [structure](structure.md). Adapt an existing application toward the boundaries; keep
42
+ working public behavior and current project conventions unless the request changes them.
43
+ 3. For initialization or missing host infrastructure, follow [bootstrap](bootstrap.md).
44
+ For a selected .NET/React/Vite browser application, also follow the
45
+ [stack profile](dotnet-react-vite.md); API and worker applications use the general steps.
46
+ For requested modules/aggregates, follow [modules](modules.md) and the relevant persistence
47
+ branch. Follow [messaging](messaging.md) when durable handoff or command receipts are selected. For Kafka transport adoption, use the
48
+ [native Kafka recipe](kafka.md).
49
+ 4. Resolve [library integration](gloaming.md) against the package versions actually being used.
50
+ Essential contracts remain with each library. Implement one runnable path through the selected
51
+ modules, native persistence and host.
52
+ 5. Complete [verification](verification.md). Record the resulting module map, infrastructure and
53
+ transaction ownership in the target application's architecture documentation.
54
+
55
+ For a first protected state-stored module, follow the [first-module walkthrough](first-module.md).
56
+ It connects package selection, HTTP context, native persistence, audit and the first acceptance
57
+ checks using existing executable examples.
58
+
59
+ The target repository's instructions and explicit user decisions take precedence over these
60
+ defaults. Ask for missing decisions that change business meaning or require credentials; continue
61
+ independent setup while those answers are pending. State ordinary technical assumptions clearly.
62
+
63
+ ## Interpret the request
64
+
65
+ The example selects two modules, not three projects for three aggregates:
66
+
67
+ | Module | Aggregate roots | Persistence |
68
+ | ------ | ---------------------- | -------------------------------------------------- |
69
+ | X | AggregateA, AggregateB | Native state-stored EF by default |
70
+ | Y | AggregateE | Event-sourced aggregate with required inline state |
71
+
72
+ Each module owns a context, schema, migrations and named connection. Aggregate boundaries stay
73
+ inside their module; another module calls its Contracts. A module can mix persistence styles
74
+ when explicitly required. API style is an application choice; match the existing style, using
75
+ minimal APIs for a new HTTP host unless requested otherwise.
76
+
77
+ When only aggregate names are supplied, establish the named boundaries and a minimal labelled
78
+ create/load example. Keep business invariants and additional process stages tied to actual
79
+ requirements. A timer, saga, broker or cross-module write is not implied by having two modules.
80
+
81
+ ## Completion
82
+
83
+ The requested modules are registered and reachable through real application operations.
84
+ Chosen persistence and migrations work; required identity/tenant context is established; tests
85
+ prove accepted/rejected work, isolation and rollback. The report names commands actually run,
86
+ remaining configuration and unsupported behavior. An empty project graph alone is not completion.
87
+ The browser stack profile adds tooling, generated-client and isolated browser acceptance checks;
88
+ these documents remain implementation guidance, not an installable template.
89
+
90
+ ## Develop the distribution
91
+
92
+ ```sh
93
+ npm ci --prefix modular-monolith-patterns --ignore-scripts
94
+ npm --prefix modular-monolith-patterns run check
95
+ ```
96
+
97
+ Run from the Gloaming checkout. The checks compile the installer, build the reference bundle,
98
+ pack an actual tarball, and install/test that tarball in separate temporary consumer repositories.
99
+ The package contains no runtime npm dependencies or install lifecycle hooks. Local bundles
100
+ record dirty-source status; hosted release preparation requires clean committed tag inputs.
@@ -0,0 +1,29 @@
1
+ ---
2
+ name: modular-monolith-patterns
3
+ description: Initialize or adapt a .NET modular monolith, add business modules and aggregates, or wire durable handoff using consumer-owned Contracts, persistence and native hosts.
4
+ ---
5
+
6
+ Use these application patterns for the requested module map and behavior. The target
7
+ repository's instructions and explicit user choices take precedence over the defaults.
8
+
9
+ Start with [the application workflow](README.md#start-here) and
10
+ [module ownership](structure.md). Inspect the existing solution and working changes before
11
+ choosing projects or dependencies. Establish the requested business boundaries and persistence
12
+ choice per aggregate; additional process stages require application requirements.
13
+
14
+ Read only the branches needed for the requested change:
15
+
16
+ - Host initialization: [bootstrap](bootstrap.md), plus the
17
+ [.NET/React/Vite profile](dotnet-react-vite.md) when that browser stack is selected.
18
+ - Module or aggregate work: [modules](modules.md). For a first protected state-stored
19
+ operation, use [the first-module walkthrough](first-module.md).
20
+ - Durable cross-module work: [messaging](messaging.md). Select the
21
+ [Kafka recipe](kafka.md), [entity-work exclusion](entity-work.md) or
22
+ [PostgreSQL wakeups](postgres-wakeups.md) when their protocols are needed.
23
+ - Gloaming adoption: [library integration](gloaming.md), checked against the package
24
+ versions actually consumed. Application structure and business policy remain consumer-owned.
25
+
26
+ Complete [verification](verification.md) for the selected path. Deliver an executable
27
+ consumer operation, relevant failure proofs and an application architecture record identifying
28
+ module, schema, credential and transaction ownership. Report executed checks, remaining
29
+ configuration and supported limits; project scaffolding alone does not establish working behavior.
@@ -0,0 +1,117 @@
1
+ # Initialize or adapt an application
2
+
3
+ Read [structure](structure.md) first. Use native .NET/Aspire tools and the target repository's
4
+ existing package/tool manifests. This task establishes runnable composition and the first
5
+ requested behavior; it does not copy Gloaming sources into the application.
6
+
7
+ ## 1. Establish tooling and package consumption
8
+
9
+ Choose a solution/application name and compatible .NET target, then pin the SDK and central
10
+ package versions. Match existing nullable, analyzer and test-runner conventions. Add ordinary
11
+ build/test commands, formatting and CI appropriate to the selected projects.
12
+ Supply pinned tool manifests, editor configuration, generated-file policies and root commands
13
+ together. The initial handwritten scaffold must pass its own formatting and analyzer checks.
14
+ Hooks check reviewed staged content without formatting or re-staging the index. The
15
+ [browser stack profile](dotnet-react-vite.md) supplies the selected frontend/tooling defaults.
16
+
17
+ Consume selected Gloaming packages through ordinary PackageReferences.
18
+ [Library integration](gloaming.md) describes hosted package selection and capability integration.
19
+ Inspect package framework/API compatibility before copying a snippet from another version.
20
+ Account for the [distribution boundary](gloaming.md#distribution-boundary): pin published
21
+ versions, retain locks and verify clean consumer restore and application acceptance.
22
+
23
+ Done: restore/build uses the intended SDK and selected package versions, without source
24
+ ProjectReferences back into the Gloaming checkout.
25
+
26
+ ## 2. Compose native hosts
27
+
28
+ Create or adapt:
29
+
30
+ - Server: native ASP.NET Core entry point, endpoints, authentication/authorization, module
31
+ registration and selected operational health/telemetry.
32
+ - Migrator: finite executable that applies the requested module migrations/provisioning,
33
+ reports failure and exits. It uses setup credentials and does not serve application traffic.
34
+ - Worker: native host for explicitly selected background roles. Add work only for an actual
35
+ requirement; name its roles and establish a fresh operation scope for each turn.
36
+ - AppHost: local resource graph and references for the application, database, optional identity
37
+ provider, migrator and selected workers.
38
+ - ServiceDefaults: consumer-owned shared native telemetry/health setup when useful to these hosts.
39
+
40
+ Prefer C# SDK-style AppHost projects under `orchestration/local`, included in the main solution
41
+ for project-aware editing and solution restore/build. Keep existing working orchestration when
42
+ adapting another stack. Use explicit runnable project references; mark shared orchestration
43
+ library references with `IsAspireProjectResource="false"`. Create sibling E2E or publishing hosts
44
+ when their behavior is needed, sharing application wiring while keeping lifecycle/data ownership
45
+ separate. Preserve secret identities, volume names and public endpoints during host conversions.
46
+
47
+ Use separate named connection options per module and per restricted role. Runtime startup
48
+ registers services; it does not silently migrate, seed or grant database privileges.
49
+ Development example data is a separately selected finite operation.
50
+ The finite Migrator invokes explicit module setup entry points; each module owns its migrations
51
+ and schema-specific grants. Hosts own infrastructure provisioning. Readiness probes use actual
52
+ runtime connections/credentials; migration completion and tests separately prove schema setup.
53
+
54
+ Done: each selected executable builds and has one clear role. Startup failures are visible.
55
+ Database-dependent hosts wait for required resources and successful migration completion in
56
+ local orchestration.
57
+
58
+ ## 3. Wire identity and tenant admission
59
+
60
+ Use native ASP.NET Core authentication, including cookie/OIDC when a browser login is requested.
61
+ Authority, client IDs, redirect/logout URIs, trust and secrets are application configuration.
62
+ Store secrets through the target's chosen secret mechanism.
63
+
64
+ Map authenticated identity explicitly into application identity/actor context.
65
+ Choose tenantless or selected-tenant execution deliberately. Tenant membership/admission and
66
+ resource permissions belong to the application; a tenant key is not permission.
67
+ Treat the route/header tenant as a candidate until admission succeeds. Gloaming tenant keys
68
+ are opaque; GUID requirements, slug lookup and membership rules are application policy.
69
+
70
+ When first login creates an application user, key external identity by the validated issuer
71
+ and subject, with a native unique constraint. Concurrent registration must recover the same
72
+ account from fresh state after a conflicting transaction. When registration is audited, stage
73
+ that audit in the same transaction so only the accepted registration's audit remains.
74
+ Establish request account state once and guard reads until establishment is complete. Keep this
75
+ pre-admission registry separate from tenant-owned business persistence.
76
+
77
+ Read the selected [HTTP/context contracts](gloaming.md) for ordering. Authentication and effective
78
+ policy evaluation precede actor completion; tenant admission is completed before protected
79
+ module work. The module owns late resource checks. Configure native authorization and
80
+ antiforgery for the chosen HTTP interaction.
81
+ Module operations check current authority for direct Contracts callers as well as HTTP callers.
82
+ Membership suspension can revoke one organization's access while preserving the signed-in
83
+ global account and other memberships; use the application's actual revocation policy.
84
+
85
+ For browser cookies, configure persistent native Data Protection and prove a restart preserves
86
+ the session. Replicas of one application/environment share the intended keyring and discriminator;
87
+ independently trusted hosts/environments have separate rings. The
88
+ [browser security recipe](dotnet-react-vite.md#browser-authentication-and-serving) covers local
89
+ storage, OIDC logout and proxy composition; production storage/access/key protection stay explicit.
90
+
91
+ If the actual issuer or account/membership model is undecided, expose the configuration seam
92
+ and record the missing decision. Protected business operations require a real admitted context;
93
+ a placeholder identity must not silently authorize production work.
94
+
95
+ Done: tests prove authorized/unauthorized paths and context establishment. When an actual local
96
+ OIDC provider is configured, prove login/callback, one protected operation and logout with that
97
+ provider through the chosen frontend origin.
98
+
99
+ ## 4. Add the requested modules
100
+
101
+ Follow [modules](modules.md). Register every module explicitly in Server and the appropriate
102
+ Worker/Migrator. The host supplies native options; a module does not discover other modules,
103
+ choose global transport or configure the application's authentication provider.
104
+
105
+ The [first-module walkthrough](first-module.md) connects these steps for one protected
106
+ state-stored operation with transactional audit.
107
+
108
+ Wire the first real endpoint/operation for each requested module. Keep sample aggregate behavior
109
+ minimal when the request supplies only names.
110
+
111
+ Done: the first requested create/load path reaches native module persistence through Contracts.
112
+
113
+ ## 5. Complete application verification
114
+
115
+ Follow [verification](verification.md). Exercise migration failure/startup ordering, native
116
+ rollback and required tenant isolation. Use real infrastructure for guarantees that depend on it.
117
+ Document exact local setup and selected production integration obligations.
@@ -0,0 +1,25 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "name": "@oxface/modular-monolith-patterns",
4
+ "version": "0.1.1",
5
+ "source": {
6
+ "revision": "b5d9b70171b579565eec21a94f76a774a90347d7",
7
+ "clean": true
8
+ },
9
+ "files": {
10
+ "CHANGELOG.md": "11f187c37a118d54646d99fdb5a4ae0212b1ad91d0c55d46d68a60d2feb6e0c0",
11
+ "README.md": "688a582fb6f693d47cdad2794ed314eb055ac1ee6a08cdd3a0d10163c2c477c7",
12
+ "SKILL.md": "3dc823d09c59c8afc56c9f4ab2317190eb10eb77854148061f59ed2405c57d33",
13
+ "bootstrap.md": "a4bc7c84a6733a2dcedb327bd9e1211f43e1fcd12c7ae6033e671b67a9260f32",
14
+ "dotnet-react-vite.md": "f531528182d94cae29a303226dc885c66879e03850e69dfa66c77de424ddccdb",
15
+ "entity-work.md": "5f958ee599332ec2ef2d6c106af62aba5aff5fba328e03d18e01176a9114dcf6",
16
+ "first-module.md": "f22a19b1cb209585e0259858413056d551beb230e3d9e3b5d4c7397affe48081",
17
+ "gloaming.md": "621ab875185e521a4dc1ec58279e2f7a17c85d34975548764643693aaf6491e7",
18
+ "kafka.md": "8591713c8afe71a9ca85d88d73b0ad493d1b194e62e7246eb10281ba40286200",
19
+ "messaging.md": "71727591216b5a15f29e1f9ad7222dc81605388c3c7cb6ef6e5ac4cff37c017b",
20
+ "modules.md": "58ba732c27bb02a33d32982ff68e6651859c1458f0dac91b5955e202c6ccf5f7",
21
+ "postgres-wakeups.md": "f6948aba83f3550901d556cd96c53629b9b8959130dd0a1d5d5cab69226c41a5",
22
+ "structure.md": "e300cfb574d0fce8fbf598033a76f42e79d294103dfc3487308cd3d84d2669d2",
23
+ "verification.md": "d8b6d6853583e635d3ad012f41a5360731591247db1f4872f38cef71264f0269"
24
+ }
25
+ }
@@ -0,0 +1,244 @@
1
+ # .NET, React and Vite bootstrap profile
2
+
3
+ Apply this profile when the application selects native ASP.NET Core cookie/OIDC authentication,
4
+ PostgreSQL, a React/Vite frontend and Aspire orchestration. Follow [bootstrap](bootstrap.md)
5
+ and the [first-module walkthrough](first-module.md) for backend ownership. Existing repository
6
+ instructions and explicit owner choices take precedence. These are consumer implementation
7
+ defaults; Gloaming supplies no frontend package, generated template or required runtime.
8
+
9
+ ## Pinned workspace and tooling
10
+
11
+ Use `apps/<portal>` for application source and private pnpm workspace packages under `packages/`.
12
+ Pin Node, pnpm, the .NET SDK, central NuGet versions and local .NET tools. Commit workspace,
13
+ orchestration npm and NuGet dependency locks. Include the AppHosts in locked solution restore.
14
+
15
+ Supply working editor configuration, manifests, root commands and matching CI checks together:
16
+
17
+ | Concern | Starting behavior |
18
+ | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
19
+ | Formatting | Prettier for frontend/configuration; CSharpier for handwritten C#/project XML. Declare generated API types, EF migrations, lock files and build output policies explicitly. |
20
+ | C# spacing | Enable IDE2003 through `.editorconfig` and Roslyn style verification. CSharpier preserves logical groups but does not infer them. Agent guidance asks for semantic grouping and keeps `else`, `catch` and `finally` attached. |
21
+ | Type-aware lint | Pin Oxlint and `oxlint-tsgolint`; enable `typescript/no-deprecated` and fail warnings. Cover application and shared workspace source. Use the installed React declarations' supported event types. |
22
+ | Git hooks | Lefthook runs checks against staged blobs and conventional commit validation. Hooks preserve the user's index and working tree. |
23
+ | Install scripts | Use the policy supported by the pinned pnpm version. For pnpm 12, configure explicit `allowBuilds` entries for required packages; verify them during clean installation. |
24
+
25
+ Keep this commitlint configuration, including its disabled capitalization check:
26
+
27
+ ```js
28
+ export default {
29
+ extends: ["@commitlint/config-conventional"],
30
+ rules: {
31
+ // Capitalization does not change the meaning of a conventional commit.
32
+ "subject-case": [0],
33
+ },
34
+ };
35
+ ```
36
+
37
+ Accept a capitalized Dependabot subject such as `chore(deps): Bump dependency`; reject malformed
38
+ messages through the same configuration in hooks and CI. Pin tool versions in manifests rather
39
+ than copying a dated dependency list from this guide. See [type-aware lint setup](https://oxc.rs/docs/guide/usage/linter/type-aware.html)
40
+ and [pnpm build settings](https://pnpm.io/settings#allowbuilds).
41
+
42
+ A staged-content helper exports the complete index into scratch storage, uses staged tool
43
+ configuration, and redirects workspace dependency symlinks to exported package source. External
44
+ dependencies may reuse installed packages matching the staged manifests/locks; require an install
45
+ when they differ. Checking working-tree files by staged filename does not check the commit.
46
+ CSharpier accepts explicitly named files even when normally ignored, so apply the staged ignore
47
+ policy before passing its file list. Retain isolated Git fixtures for both staged/unstaged
48
+ directions, including a workspace dependency and generated migrations.
49
+
50
+ Use `eng/` for enduring verification/codegen helpers, preferably TypeScript for new durable
51
+ scripts. Document their runtime and invocation. Inventory temporary package bridges separately
52
+ with a removal condition; remove superseded one-off helpers. Keep workspace source visible to
53
+ Git/formatters/lint while excluding every nested `node_modules`, build output and generated cache.
54
+
55
+ Done: a frozen clean install and the scaffold's own formatting, type-aware lint and hook fixtures
56
+ pass without changing source or the index.
57
+
58
+ ## Solution-owned orchestration
59
+
60
+ Create `orchestration/local/<Application>.Local.AppHost.csproj` using `Aspire.AppHost.Sdk`,
61
+ with a C# entrypoint, `Aspire.Hosting.AppHost` and explicit runnable project references. Include
62
+ it in the main `.slnx`. Pin the SDK/package versions and use standard
63
+ `Properties/launchSettings.json` for dashboard/telemetry ports and environment settings.
64
+ The [Aspire SDK](https://aspire.dev/get-started/aspire-sdk/) describes typed `Projects.*`
65
+ metadata and CLI-bundle configuration.
66
+
67
+ When an isolated browser suite exists, add a sibling E2E AppHost and a shared orchestration
68
+ class library. Reference the latter with `IsAspireProjectResource="false"`; runnable backend
69
+ references remain in each AppHost. Keep entrypoints thin. Share explicit infrastructure,
70
+ backend/portal and identity wiring; use named local/E2E profiles for ports, database names and
71
+ persistence. Additional portals get application-specific resource names and wiring. Keep a
72
+ future publishing AppHost absent until its deployment behavior is implemented.
73
+
74
+ Use an independent npm-locked Aspire CLI under `orchestration/local`, even though application
75
+ packages use pnpm. Document `npm ci --prefix orchestration/local` separately. Install workspace
76
+ dependencies once, then use `.WithPnpm(install: false)` for Vite resources. A root
77
+ `aspire.config.json` selects the default local project; commands/tests for other hosts always
78
+ pass their exact project path. Shared editor launch entries select hosts while project launch
79
+ profiles retain runtime settings. Reconcile editor-extension and command-line tool versions.
80
+
81
+ With Aspire CLI 13.6.4, the observed central `Aspire.Hosting.AppHost` version form is `13.6.4`:
82
+ `[13.6.4]` builds but fails CLI startup version parsing. Keep the dependency lock and verify
83
+ actual CLI startup for the selected toolchain; this is not a general change to NuGet pinning.
84
+
85
+ Persist local PostgreSQL, identity-provider data, key storage and generated secret parameters.
86
+ Keep issuer/callback endpoints stable and explicitly migrate persisted identity configuration;
87
+ realm import does not itself reconcile an existing realm. Preserve volume names and UserSecrets
88
+ IDs during host/project moves. Allocate application-specific names for a new scaffold rather
89
+ than copying a consumer's migration-specific volume names. Include pgAdmin locally, discovered
90
+ through the dashboard; disposable E2E stacks omit it.
91
+
92
+ Done: solution restore/build covers orchestration, the pinned CLI starts the selected host,
93
+ the finite Migrator gates backend readiness, and a restart preserves data and identity.
94
+
95
+ ## Browser authentication and serving
96
+
97
+ Let Vite serve the SPA in development. Proxy `/api`, `/auth`, `/signin-oidc`,
98
+ `/signout-callback-oidc` and `/signout-oidc` to the backend HTTPS endpoint. Preserve the public
99
+ frontend Host (`changeOrigin: false`) so native OIDC constructs the intended callbacks. A local
100
+ development-certificate exception belongs only to that development proxy. The backend serves
101
+ API/auth endpoints; remove SPA static-file middleware and `MapFallbackToFile("index.html")`
102
+ for this topology. Production serving, ingress and forwarded-header trust require their own
103
+ configuration and checks.
104
+
105
+ Keep browser API calls same-origin with native secure, HttpOnly cookies. Return API 401/403
106
+ responses without browser-login redirects; navigate to login deliberately. Protect mutations
107
+ and the logout POST with native antiforgery. Put generic HTTP filters in host HTTP infrastructure
108
+ and use native local-return URL validation. Application modules keep business authorization.
109
+
110
+ Use authorization-code OIDC with PKCE. When the selected provider needs an ID token for
111
+ RP-initiated logout, retain only that token in the encrypted authentication ticket. Inside
112
+ the native `AddOpenIdConnect` options, compose this with any existing validated-token event:
113
+
114
+ ```csharp
115
+ options.ResponseType = "code";
116
+ options.UsePkce = true;
117
+ options.SaveTokens = false;
118
+ options.Events.OnTokenValidated = context =>
119
+ {
120
+ var idToken = context.TokenEndpointResponse?.IdToken ?? context.ProtocolMessage.IdToken;
121
+ if (!string.IsNullOrEmpty(idToken))
122
+ {
123
+ context.Properties!.StoreTokens([
124
+ new AuthenticationToken { Name = "id_token", Value = idToken },
125
+ ]);
126
+ }
127
+
128
+ return Task.CompletedTask;
129
+ };
130
+ ```
131
+
132
+ Map logout to both schemes, using the same `"oidc"` name supplied to `AddOpenIdConnect`:
133
+
134
+ ```csharp
135
+ app.MapPost("/auth/logout", async (HttpContext context, IAntiforgery antiforgery) =>
136
+ {
137
+ await antiforgery.ValidateRequestAsync(context);
138
+
139
+ return Results.SignOut(
140
+ new AuthenticationProperties { RedirectUri = "/" },
141
+ [CookieAuthenticationDefaults.AuthenticationScheme, "oidc"]);
142
+ })
143
+ .RequireAuthorization()
144
+ .AllowTenantless()
145
+ .ExcludeFromDescription();
146
+ ```
147
+
148
+ These excerpts use `Microsoft.AspNetCore.Authentication`, its `.Cookies` namespace,
149
+ `Microsoft.AspNetCore.Antiforgery` and `Gloaming.Tenancy.AspNetCore`, with native authentication
150
+ and antiforgery already registered. The browser submits the native antiforgery form token or
151
+ configured header. Configure the provider's callback/logout registrations and map validation
152
+ failures to the application's 400 problem response. Access and refresh tokens remain unstored;
153
+ keeping identity claims alone does not supply the provider's logout token hint. Follow the
154
+ [native OIDC composition guide](https://learn.microsoft.com/en-us/aspnet/core/security/authentication/configure-oidc-web-authentication).
155
+
156
+ Persist native Data Protection keys in Azurite locally and provision its container before the
157
+ backend starts. Replicas of one application/environment share the intended keyring/application
158
+ discriminator; independently trusted hosts and environments have separate rings. Configure
159
+ production storage access and key wrapping separately. Ephemeral keys are an explicit isolated
160
+ test or schema-generation choice. Schema generation must not relax normal runtime configuration.
161
+
162
+ Done: an actual browser completes login/callback, a protected operation and provider logout
163
+ through the frontend origin; local restart preserves the signed-in cookie.
164
+
165
+ ## Generated HTTP contracts
166
+
167
+ Use native .NET OpenAPI generation with `Microsoft.AspNetCore.OpenApi` and build-time
168
+ `Microsoft.Extensions.ApiDescription.Server`. Give JSON operations stable names, explicit
169
+ route parameters, success types and problem responses. A tenant parameter consumed only by
170
+ middleware must still appear in endpoint/OpenAPI metadata. Exclude browser redirect endpoints
171
+ from the JSON client contract.
172
+
173
+ Build-time schema generation executes the entrypoint with a mock server. Follow the native
174
+ [entry-assembly detection guidance](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/openapi/aspnetcore-openapi?view=aspnetcore-10.0#customize-runtime-behavior-during-build-time-document-generation)
175
+ for `GetDocument.Insider` to bypass infrastructure startup/runtime secrets only during that
176
+ generation. Keep endpoint/service descriptions available. Normal startup still requires its
177
+ real database, identity and key configuration.
178
+
179
+ Generate reviewed frontend types with `openapi-typescript` and consume them through
180
+ `openapi-fetch`. Keep application-owned TanStack Query caching and mutation boundaries. Define
181
+ root `generate:api` and non-writing `generate:api:check` commands; CI builds the backend schema,
182
+ checks generated-client drift, then type-checks and builds the frontend. Handwritten API
183
+ wrappers may compose generated types; DTO copies are not an additional contract source.
184
+
185
+ Done: generation succeeds without live PostgreSQL, cloud services or runtime secrets, and the
186
+ generated client compiles with every selected route parameter and response shape.
187
+
188
+ ## Frontend ownership and state
189
+
190
+ Keep `main.tsx` to composition, with individual views and focused session/data hooks. A private
191
+ workspace app-shell package owns presentation slots/styles; application routing, account state
192
+ and business behavior stay in the portal. A separate private UI source package owns shared
193
+ controls and Tailwind theme tokens. Use shadcn's Base UI registry, pinned generation tooling
194
+ and matching application/package `components.json` aliases following its
195
+ [monorepo guide](https://ui.shadcn.com/docs/monorepo). Include shared component source in
196
+ Tailwind scanning and consume the controls in real views. Keep generator provenance/licenses.
197
+
198
+ Enable stable React Compiler transforms in development and production for the installed React
199
+ major, including linked workspace source. For `@vitejs/plugin-react` 6+, use
200
+ `reactCompilerPreset` through `@rolldown/plugin-babel`; follow the
201
+ [version-matched installation guide](https://react.dev/learn/react-compiler/installation).
202
+ Inspect representative optimizable application, shell and shared-control output; a successful
203
+ Vite build alone does not establish that the compiler transformed linked source.
204
+
205
+ Include account identity and tenant/resource identity in scoped query keys. Reset view and
206
+ form state when the resource changes; version alone is insufficient because different resources
207
+ can have equal versions. Include identity plus version when resetting an editor to refreshed
208
+ server state, preserving the application's intended unsaved-edit behavior. Mutation invalidation
209
+ stays application-owned. Treat 403 membership revocation and 409 stale writes explicitly.
210
+
211
+ Done: cached navigation between two resources with equal versions displays the correct data
212
+ and form values. Switching accounts cannot display another account's cached data; a suspended
213
+ membership loses protected access while any remaining account/organization access follows policy.
214
+
215
+ ## Clean-consumer acceptance
216
+
217
+ Provide these root commands with the behavior above. Run against a clean checkout and record
218
+ the exact toolchain, Gloaming revision/version/archive source and outcomes:
219
+
220
+ 1. Prepare the selected package source as described in [library integration](gloaming.md).
221
+ Run `pnpm install --frozen-lockfile`, `npm ci --prefix orchestration/local` and
222
+ `dotnet tool restore`, then locked solution restore from an initially empty NuGet package cache.
223
+ 2. Run `pnpm format:check` and `pnpm lint`, plus the retained staged-content fixtures. Check
224
+ both the capitalized conventional-commit example and an invalid message through commitlint.
225
+ 3. Build the backend/native OpenAPI, run `pnpm generate:api:check`, then `pnpm check:web`,
226
+ `pnpm check:e2e` and `pnpm build:web`. Include workspace UI/shell in type/lint checks.
227
+ Verify development and production compiler output for representative shared source.
228
+ 4. Run native PostgreSQL integration/architecture checks through the finite Migrator and
229
+ restricted runtime role. Include admission/direct Contracts rejection, registration races,
230
+ stale writes, audit rollback and forbidden schema/audit SQL from [verification](verification.md).
231
+ 5. Install Playwright Test's browser and Linux system dependencies where required. Run
232
+ `pnpm test:e2e` against a sibling E2E AppHost with its own disposable PostgreSQL, identity
233
+ realm, key storage, secret parameters and ports. Cover actual OIDC/logout, CSRF, generated
234
+ client operations, account changes, equal-version resource navigation and membership revocation.
235
+ 6. Hold an exclusive E2E run lock from startup through teardown, refuse occupied ports and
236
+ target the exact E2E AppHost. Retain ownership/recovery information after failed stop;
237
+ verify the developer stack/data survive. Separately prove developer restart persistence.
238
+
239
+ Use Playwright Test for browser journeys and xUnit with Microsoft Testing Platform for new
240
+ .NET integration/architecture checks, preserving an existing application's selected runner.
241
+ Retain failure traces/screenshots and cleanup instructions.
242
+ Automate ongoing acceptance checks in consumer CI; label one-off or historical execution and
243
+ remote CI/deployment gaps in the handoff. A local browser result does not establish production
244
+ ingress, customer federation or another Gloaming capability's support.
@@ -0,0 +1,93 @@
1
+ # Serializing work for one entity
2
+
3
+ Different deliveries can target the same consumer entity. Choose an explicit complete entity key
4
+ when cooperating workers must exclude each other across those deliveries. Native PostgreSQL
5
+ transaction advisory locks are sufficient for this selected composition; no additional Gloaming
6
+ library interface or reusable mechanism is introduced.
7
+
8
+ Use the owning module's fresh native ReadCommitted transaction. Acquire the lock **before** reading the business
9
+ state used for the decision. Hold it through the selected state/outbox save and native commit.
10
+ Rollback, connection loss and process death release a transaction lock. Committing releases it
11
+ even while the process/connection remains alive. Do not substitute a session advisory lock on a
12
+ pooled connection, release early or move the business decision to another transaction.
13
+ See PostgreSQL's [advisory-lock lifetime](https://www.postgresql.org/docs/18/explicit-locking.html#ADVISORY-LOCKS)
14
+ and [native advisory functions](https://www.postgresql.org/docs/18/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS).
15
+ Rolling back to a savepoint created **before** acquisition releases that lock even while the
16
+ outer transaction remains open. Discard the old decision; reacquire and reread in a supported
17
+ fresh decision before doing more protected work. A savepoint is not evidence of continued exclusion.
18
+
19
+ ## Native composition
20
+
21
+ All cooperating deployed writers agree on the same versioned key protocol and namespace. This
22
+ example uses UTF-8 byte lengths to frame opaque module, technical scope and complete entity keys.
23
+ Native ID values must be canonically encoded by their consumer; an entity with tenant/partition
24
+ components includes all of them. Module and scope are not inferred from optional message metadata.
25
+ Key comparison is ordinal and case-sensitive. A delimiter-joined ambiguous string, `GetHashCode`
26
+ or a delivery ID is not the same protocol.
27
+
28
+ ```csharp
29
+ string[] fields = ["consumer.entity-work.v1", moduleKey, scopeKey, entityKey];
30
+ foreach (string field in fields)
31
+ ArgumentException.ThrowIfNullOrWhiteSpace(field);
32
+
33
+ string framed = string.Concat(fields.Select(field =>
34
+ FormattableString.Invariant($"{Encoding.UTF8.GetByteCount(field)}:{field}")));
35
+ long lockKey = BinaryPrimitives.ReadInt64BigEndian(
36
+ SHA256.HashData(Encoding.UTF8.GetBytes(framed)));
37
+
38
+ await using var command = new NpgsqlCommand(
39
+ "SELECT pg_advisory_xact_lock(@key)", connection, transaction);
40
+ command.Parameters.AddWithValue("key", lockKey);
41
+ await command.ExecuteNonQueryAsync(token);
42
+
43
+ // Now load and decide using this transaction. Save selected effects/outbox, then commit.
44
+ ```
45
+
46
+ Imports are `System.Buffers.Binary`, `System.Security.Cryptography`, `System.Text` and `Npgsql`.
47
+ The application owns `connection`, `transaction`, key admission, bounded execution and cleanup.
48
+ EF consumers may use the current Npgsql connection/transaction from their owning context; don't
49
+ open a separate connection for the lock. Database names are naturally separate PostgreSQL lock
50
+ namespaces. The prefix separates this protocol from logical command receipts and other advisory
51
+ lock conventions. A 64-bit hash collision adds unnecessary contention; it does not admit two
52
+ equal complete keys simultaneously. Advisory locking remains cooperative: raw SQL or other
53
+ writers that omit it can still change rows. Keep native concurrency predicates/constraints.
54
+
55
+ ## Guarantees and limits
56
+
57
+ This supplies mutual exclusion among cooperating transactions for the same complete key. It
58
+ does **not** supply FIFO, ordering by delivery or commit/start time, fairness, deduplication,
59
+ retry policy, admission or exactly-once effects. A waiter may be cancelled or selected in a
60
+ different order. Consumers control queue order and retry/backoff if their business needs them.
61
+ Use logical command/inbox receipts separately for retained duplicate/content evidence. Recheck
62
+ current business state and permissions after acquisition; the lock grants no authority.
63
+
64
+ Use one complete entity per transaction where possible. If a decision locks several entities,
65
+ every writer must use the same total acquisition order; otherwise native deadlock detection may
66
+ abort one transaction. Keep work bounded, propagate cancellation and dispose failed transactions.
67
+ Retry only a fresh authorized decision according to consumer policy. A lost commit response may
68
+ already mean success; inspect retained business/receipt evidence, not the existence of a lock.
69
+ No generic lock table, automatic worker serialization or cleanup scheduler is installed.
70
+
71
+ Ordinary module credentials need only their selected business-table/schema permissions and
72
+ EXECUTE on the native advisory-lock function. The usual PostgreSQL public function grant suffices
73
+ in the proof; deployments that revoke it must deliberately grant required execution. No migration,
74
+ retention, superuser or BYPASSRLS authority is needed. Business tables/migrations and reader/writer
75
+ deployment remain application-owned. Changing key encoding/namespaces during mixed deployment
76
+ requires a coordinated writer rollout; old and new lock keys would not exclude each other.
77
+
78
+ ## Executable evidence
79
+
80
+ The [native-only worker fixture](https://github.com/oxface/gloaming/blob/b5d9b70171b579565eec21a94f76a774a90347d7/src/Gloaming.Messaging/tests/Fixtures/EntityWork/README.md)
81
+ references Npgsql without Gloaming packages. Two real worker processes prove same-key exclusion
82
+ with an observed ungranted native advisory lock; different module/scope/entity keys proceed while
83
+ the first transaction stays open. Other cases cover commit while the process stays alive,
84
+ rollback, killed process recovery, cancellation of an actually blocked acquire, fresh recovery
85
+ and restricted ordinary runtime grants with denied retention deletion. Literal full-key hash
86
+ vectors retain the native composition protocol. These tests establish this PostgreSQL/Linux
87
+ composition, not arbitrary providers or host topologies.
88
+
89
+ From the Gloaming repository root, run the owning provider suite:
90
+
91
+ ```bash
92
+ dotnet test --project src/Gloaming.Messaging/tests/OutboxPostgresTests/OutboxPostgresTests.csproj
93
+ ```