resource-engine-devtools 0.1.0__py3-none-any.whl

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 (88) hide show
  1. resource_engine_devtools/__init__.py +6 -0
  2. resource_engine_devtools/ai/__init__.py +1 -0
  3. resource_engine_devtools/ai/example.py +66 -0
  4. resource_engine_devtools/ai/installer.py +424 -0
  5. resource_engine_devtools/ai/skill/SKILL.md +130 -0
  6. resource_engine_devtools/ai/skill/examples/README.md +7 -0
  7. resource_engine_devtools/ai/skill/examples/invoices/__init__.py +0 -0
  8. resource_engine_devtools/ai/skill/examples/invoices/app.py +245 -0
  9. resource_engine_devtools/ai/skill/examples/invoices/application/__init__.py +0 -0
  10. resource_engine_devtools/ai/skill/examples/invoices/application/actions.py +61 -0
  11. resource_engine_devtools/ai/skill/examples/invoices/application/balances.py +51 -0
  12. resource_engine_devtools/ai/skill/examples/invoices/application/customers.py +35 -0
  13. resource_engine_devtools/ai/skill/examples/invoices/application/hooks.py +61 -0
  14. resource_engine_devtools/ai/skill/examples/invoices/application/processes.py +80 -0
  15. resource_engine_devtools/ai/skill/examples/invoices/application/resource.py +112 -0
  16. resource_engine_devtools/ai/skill/examples/invoices/application/schemas.py +164 -0
  17. resource_engine_devtools/ai/skill/examples/invoices/application/tags.py +77 -0
  18. resource_engine_devtools/ai/skill/examples/invoices/authz.py +126 -0
  19. resource_engine_devtools/ai/skill/examples/invoices/bootstrap.py +80 -0
  20. resource_engine_devtools/ai/skill/examples/invoices/domain/__init__.py +0 -0
  21. resource_engine_devtools/ai/skill/examples/invoices/domain/entities.py +112 -0
  22. resource_engine_devtools/ai/skill/examples/invoices/domain/events.py +22 -0
  23. resource_engine_devtools/ai/skill/examples/invoices/domain/state_machine.py +88 -0
  24. resource_engine_devtools/ai/skill/examples/invoices/infrastructure/__init__.py +0 -0
  25. resource_engine_devtools/ai/skill/examples/invoices/infrastructure/persistence.py +121 -0
  26. resource_engine_devtools/ai/skill/examples/invoices/locale/en/LC_MESSAGES/messages.po +682 -0
  27. resource_engine_devtools/ai/skill/examples/invoices/locale/es/LC_MESSAGES/messages.po +685 -0
  28. resource_engine_devtools/ai/skill/examples/invoices/notifications.py +47 -0
  29. resource_engine_devtools/ai/skill/examples/invoices/templates/email/base.html +7 -0
  30. resource_engine_devtools/ai/skill/examples/invoices/templates/email/invoice_approved.html +5 -0
  31. resource_engine_devtools/ai/skill/examples/invoices/templates/email/invoice_approved.subject.txt +1 -0
  32. resource_engine_devtools/ai/skill/examples/invoices/templates/email/invoice_approved.txt +5 -0
  33. resource_engine_devtools/ai/skill/examples/invoices/tests/conftest.py +40 -0
  34. resource_engine_devtools/ai/skill/examples/invoices/tests/test_invoices_engine.py +241 -0
  35. resource_engine_devtools/ai/skill/examples/invoices/worker.py +53 -0
  36. resource_engine_devtools/ai/skill/llms.txt +25 -0
  37. resource_engine_devtools/ai/skill/references/anti-patterns.md +209 -0
  38. resource_engine_devtools/ai/skill/references/docstrings.md +97 -0
  39. resource_engine_devtools/ai/skill/references/errors.md +81 -0
  40. resource_engine_devtools/ai/skill/references/lifecycle.md +118 -0
  41. resource_engine_devtools/ai/skill/references/permissions.md +111 -0
  42. resource_engine_devtools/ai/skill/references/resource.md +301 -0
  43. resource_engine_devtools/ai/skill/references/state-machines.md +126 -0
  44. resource_engine_devtools/ai/skill/references/testing.md +80 -0
  45. resource_engine_devtools/ai/templates/agents_block.md +26 -0
  46. resource_engine_devtools/ai/templates/cursor_rule.mdc +7 -0
  47. resource_engine_devtools/check.py +67 -0
  48. resource_engine_devtools/cli.py +1112 -0
  49. resource_engine_devtools/consumer_scaffold.py +715 -0
  50. resource_engine_devtools/contracts.py +471 -0
  51. resource_engine_devtools/db.py +132 -0
  52. resource_engine_devtools/declarations_check.py +116 -0
  53. resource_engine_devtools/documentation/__init__.py +10 -0
  54. resource_engine_devtools/documentation/docstrings.py +72 -0
  55. resource_engine_devtools/documentation/generators/__init__.py +9 -0
  56. resource_engine_devtools/documentation/generators/ai_context.py +121 -0
  57. resource_engine_devtools/documentation/generators/api.py +63 -0
  58. resource_engine_devtools/documentation/generators/json.py +12 -0
  59. resource_engine_devtools/documentation/generators/markdown.py +687 -0
  60. resource_engine_devtools/documentation/generators/mermaid.py +22 -0
  61. resource_engine_devtools/documentation/generators/site.py +379 -0
  62. resource_engine_devtools/documentation/generators/site_assets/site.css +62 -0
  63. resource_engine_devtools/documentation/generators/site_assets/site.js +54 -0
  64. resource_engine_devtools/documentation/i18n.py +185 -0
  65. resource_engine_devtools/documentation/introspector.py +563 -0
  66. resource_engine_devtools/documentation/locale/ca/LC_MESSAGES/docs.po +628 -0
  67. resource_engine_devtools/documentation/locale/es/LC_MESSAGES/docs.po +627 -0
  68. resource_engine_devtools/documentation/model.py +311 -0
  69. resource_engine_devtools/documentation/validator.py +128 -0
  70. resource_engine_devtools/emails.py +172 -0
  71. resource_engine_devtools/events_check.py +124 -0
  72. resource_engine_devtools/gates_check.py +133 -0
  73. resource_engine_devtools/hooks_check.py +287 -0
  74. resource_engine_devtools/i18n.py +312 -0
  75. resource_engine_devtools/loader.py +93 -0
  76. resource_engine_devtools/logic_check.py +136 -0
  77. resource_engine_devtools/mcp_server.py +685 -0
  78. resource_engine_devtools/py.typed +0 -0
  79. resource_engine_devtools/scaffold.py +805 -0
  80. resource_engine_devtools/scaffold_parts.py +637 -0
  81. resource_engine_devtools/source_edit.py +424 -0
  82. resource_engine_devtools/templates_check.py +59 -0
  83. resource_engine_devtools/worker.py +68 -0
  84. resource_engine_devtools-0.1.0.dist-info/METADATA +38 -0
  85. resource_engine_devtools-0.1.0.dist-info/RECORD +88 -0
  86. resource_engine_devtools-0.1.0.dist-info/WHEEL +4 -0
  87. resource_engine_devtools-0.1.0.dist-info/entry_points.txt +2 -0
  88. resource_engine_devtools-0.1.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,301 @@
1
+ # Declaring a resource
2
+
3
+ A `Resource` subclass is a declaration: class attributes only, validated when
4
+ registered (`ResourceRegistry.register`). Errors at registration are
5
+ `RE-E0xx` with a hint.
6
+
7
+ Keep it short: it says what the resource is. Behaviour lives in plain code
8
+ it lists: hooks marked with `@hook` (in `application/hooks.py`), `Action`
9
+ classes, processes, domain methods. Related settings come grouped
10
+ (`listing`, `access`, `concurrency`, `caching`, `audit`). `check` reports
11
+ methods or lambdas in a declaration, and declarations over 80 lines
12
+ (RE-C008): move long values (slots, timers) to modules next to it.
13
+
14
+ ```python
15
+ from resource_engine import CRUD, Listing, Resource
16
+
17
+ from billing.application import hooks
18
+ from billing.application.actions import RecalculateTotals
19
+ from billing.application.schemas import InvoiceCreate, InvoiceRead, InvoiceUpdate, RejectInvoice
20
+ from billing.domain.entities import Invoice
21
+ from billing.domain.state_machine import InvoiceStateMachine
22
+
23
+
24
+ class InvoiceResource(Resource):
25
+ """Gestió de factures de l'organització.
26
+
27
+ Business area:
28
+ Facturació
29
+ """
30
+
31
+ model = Invoice # plain domain class, not an ORM model
32
+ schemas = {"create": InvoiceCreate, "update": InvoiceUpdate, "read": InvoiceRead}
33
+ operations = CRUD # every CRUD operation, or a subset
34
+ operation_docs = {"list": "Llista les factures.", "get": "Consulta una factura.", ...}
35
+ state_machine = InvoiceStateMachine # optional
36
+ transition_schemas = {"reject": RejectInvoice}
37
+ actions = [RecalculateTotals]
38
+ hooks = [hooks] # the functions marked with @hook in hooks.py
39
+ listing = Listing(filterable=["status", "customer"], sortable=["id", "amount"])
40
+ ```
41
+
42
+ ```python
43
+ # billing/application/hooks.py: where each hook runs is said next to its code
44
+ from resource_engine import OperationContext, external_effect, hook
45
+
46
+
47
+ @hook.before("update", "delete")
48
+ def ensure_editable(ctx: OperationContext) -> None:
49
+ """Només es poden modificar factures en esborrany."""
50
+ ctx.entity.ensure_editable()
51
+
52
+
53
+ @hook.after_commit
54
+ @external_effect
55
+ async def notify(ctx: OperationContext) -> None: ...
56
+ ```
57
+
58
+ `hooks` takes marked functions or the modules holding them (only functions
59
+ defined in that module are collected). Targets are the hook points without
60
+ `before_`/`after_`: `"create"`, `"transition:approve"`, `"action:recalculate"`,
61
+ `"attach:signed_pdf"`. The mapping `{"before_update": [fn]}` still works.
62
+
63
+ ## Attributes
64
+
65
+ | Attribute | Default | Meaning |
66
+ |---|---|---|
67
+ | `name` | `InvoiceResource` → `invoices` | Public name (URLs, actions, registry) |
68
+ | `model` | required | Domain entity class |
69
+ | `id_field`, `id_type` | `"id"`, `int` | Identifier attribute and type |
70
+ | `schemas` | `{}` | Pydantic models: `create`, `update`, `read` |
71
+ | `operations` | `()` | Enabled CRUD subset of `list get create update delete`; `CRUD` for all |
72
+ | `operation_docs` | `{}` | One sentence per enabled CRUD operation (`docs validate` needs it) |
73
+ | `hooks` | `()` | Functions marked `@hook.before/after(...)` / `@hook.after_commit`, or their modules; or `{"<point>[:<qualifier>]": [fn]}`; see [lifecycle.md](lifecycle.md) |
74
+ | `state_machine` | `None` | A machine class (state in `status`) or `Machine(cls, field=, since_field=)`; see [state-machines.md](state-machines.md) |
75
+ | `caching` | `Cached()` | `Cached(ttl=, control=)`: seconds the manager's record cache keeps records read by id (`ResourceManager(cache=)`, writes forget them); `Cache-Control` of GET answers (default `private, no-cache`; ETag and 304 always) |
76
+ | `view` | `None` | A read-only resource computed by a query: `Aggregate("invoices", group_by=[...], values={...})` or `True` (custom; docs/views.md) |
77
+ | `discriminator` | `None` | On a base resource with subtypes: the field naming each record's kind (docs/polymorphism.md) |
78
+ | `extends` | `None` | On a subtype: the base resource class, or `Subtype(Base, identity="...")` for its discriminator value |
79
+ | `machines` | `{}` | Several named machines: `{"delivery": Machine(Cls, field="delivery_status")}` |
80
+ | `transition_schemas` | `{}` | Input schema per transition event |
81
+ | `actions` | `()` | `Action` subclasses |
82
+ | `listing` | `Listing()` | `Listing(filterable=, sortable=, max_page_size=100, searchable=)`: fields accepted by `list` filters (also `field[gte]`, `field[in]`, ...) and `order_by`, the page bound, and the text fields `search` (`?q=`) looks in |
83
+ | `documents` | `()` | `DocumentSlot(...)` declarations |
84
+ | `access` | `Access()` | `Access(tenant_field=, restricted_fields=, wildcards=True)`: confine every operation to the caller's tenant; fields that need an explicit `<resource>:read|write:<field>` grant; `wildcards=False` for sensitive resources |
85
+ | `concurrency` | `None` | `Versioned("version", required=False)`: optimistic concurrency (ETag / If-Match, RE-E105) |
86
+ | `internal` | `Internal()` | CRUD operations only code runs (`["create"]`), or `Internal(operations=, transitions=True)` to keep transitions internal too |
87
+ | `link` | `None` | On a join resource: `("invoice_id", "tag_id")`, or `Link(..., names={"invoice_id": "labels"})` to name the relations |
88
+ | `translatable` | `()` | Fields with one text per language: `["name"]`, or `Translatable("name", default_locale="ca")` |
89
+ | `audit` | `True` | `False` leaves it out of the audit trail; `Audited(reads=True, exclude=[...])` |
90
+
91
+ ## Schemas
92
+
93
+ Separate Pydantic models per role. They are the HTTP contract; the entity is
94
+ not exposed directly.
95
+
96
+ - `create`: what a client may send to create. **Never the state field, the
97
+ id or the version field.**
98
+ - `update`: every field optional; only the fields sent are applied
99
+ (`exclude_unset`). The id, state and version fields are ignored even if
100
+ present.
101
+ - `read`: `model_config = ConfigDict(from_attributes=True)`; it is built from
102
+ the entity. Include the state and version fields here.
103
+
104
+ Override `build_entity(data, ctx)`, `apply_update(entity, data, ctx)` or
105
+ `to_read(entity, ctx)` on the resource when the default mapping
106
+ (`model(**data)`, `setattr` per sent field, `read.model_validate(entity)`) is
107
+ not enough.
108
+
109
+ ## Actions
110
+
111
+ Business operations that are neither CRUD nor a transition:
112
+
113
+ ```python
114
+ from resource_engine import Action, OperationContext
115
+
116
+
117
+ class RecalculateTotals(Action):
118
+ """Aplica un descompte percentual a l'import d'una factura.
119
+
120
+ Preconditions:
121
+ La factura és un esborrany.
122
+
123
+ Postconditions:
124
+ L'import queda reduït pel percentatge indicat.
125
+
126
+ Effects:
127
+ Emet l'esdeveniment ``InvoiceTotalsRecalculated``.
128
+ """
129
+
130
+ input_schema = ApplyDiscount # or None
131
+ # name = "recalculate_totals" # default: snake_case of the class name
132
+ # instance = True # False: collection-level (/actions/x)
133
+ # output_schema = None # default: the resource's read schema
134
+
135
+ async def execute(self, ctx: OperationContext) -> None:
136
+ invoice = ctx.entity # loaded and authorized by the engine
137
+ invoice.ensure_editable() # domain rule
138
+ invoice.apply_discount(ctx.data.percent)
139
+ await ctx.repository().update(invoice) # actions write themselves
140
+ ctx.record_event(InvoiceTotalsRecalculated(invoice_id=invoice.id, ...))
141
+ ```
142
+
143
+ `execute` runs inside the transaction (no external effects there). HTTP:
144
+ `POST /invoices/{id}/actions/recalculate_totals`. Permission action:
145
+ `invoices:action:recalculate_totals`.
146
+
147
+ ## Events
148
+
149
+ Domain events are frozen keyword-only dataclasses in `domain/events.py`:
150
+
151
+ ```python
152
+ from dataclasses import dataclass
153
+
154
+ from resource_engine.domain import DomainEvent
155
+
156
+
157
+ @dataclass(frozen=True, kw_only=True)
158
+ class InvoiceTotalsRecalculated(DomainEvent):
159
+ """L'import d'una factura s'ha recalculat."""
160
+
161
+ invoice_id: int
162
+ new_amount: Decimal
163
+ ```
164
+
165
+ Declare them on the resource (`events = [InvoiceTotalsRecalculated]`) and record
166
+ them with `ctx.record_event(...)` in hooks before commit or in actions; `check`
167
+ reports undeclared ones (RE-C006), and the generated docs and AsyncAPI document
168
+ list the declared ones. They are published only if the transaction commits. The engine also publishes
169
+ `ResourceCreated`, `ResourceUpdated`, `ResourceDeleted`, `TransitionExecuted` and
170
+ `ActionExecuted` on its own. With `OutboxDelivery` they are stored with the
171
+ change and sent by `OutboxRelay`; consumers use `EventRouter` and
172
+ `MessageProcessor(manager=...)` for exactly-once effects. Give consumed events a
173
+ payload model (`router.on("PaymentReceived", payload=PaymentReceived)`): the
174
+ handler gets `(envelope, payment)`, invalid payloads are dead-lettered, and the
175
+ AsyncAPI document shows the schema. For another service's events, start with
176
+ `resource-engine scaffold consumer <name> --package ... --asyncapi <their
177
+ document>`: it writes the models, the router and contract tests; keep the
178
+ generated `test_contract` passing.
179
+
180
+ ## Documents
181
+
182
+ ```python
183
+ from resource_engine import DocumentSlot
184
+
185
+ documents = [
186
+ DocumentSlot(
187
+ "signed_pdf",
188
+ content_types=["application/pdf"],
189
+ required_for=["approve"],
190
+ description="Factura signada pel client; cal per aprovar-la.",
191
+ ),
192
+ DocumentSlot("attachments", multiple=True, description="Justificants."),
193
+ ]
194
+ ```
195
+
196
+ Every slot needs a `description` (RE-D009). Inside an action,
197
+ `await ctx.documents.attach(NewDocument(slot, data, filename, content_type))`.
198
+
199
+ ## Registering and wiring
200
+
201
+ ```python
202
+ registry = ResourceRegistry()
203
+ registry.register(InvoiceResource)
204
+ registry.register_documents() # if any resource has document slots
205
+ registry.register_authz() # built-in policies managed from a front end
206
+ registry.register_audit() # audit trail
207
+
208
+ manager = ResourceManager(
209
+ registry,
210
+ unit_of_work_factory(session_factory, registry),
211
+ authorizer=...,
212
+ audit=True,
213
+ services={"notifier": notifier},
214
+ )
215
+ mount_resources(app, registry, manager, actor_dependency=bearer_actor(authenticator))
216
+ ```
217
+
218
+ `services` are reachable from hooks and actions as `ctx.services["notifier"]`.
219
+ Declare the engine's tables on the same `MetaData` as yours
220
+ (`engine_tables(metadata, outbox=True, audit=True, ...)` with
221
+ `MetaData(naming_convention=NAMING_CONVENTION)`) and create migrations with
222
+ `alembic revision --autogenerate`; never `create_all` in production.
223
+ Map the entity with SQLAlchemy **imperative mapping** in `infrastructure/`
224
+ (`mapper_registry.map_imperatively(Invoice, invoices_table)`), never with
225
+ declarative models in the domain.
226
+
227
+ Generated HTTP API: `GET/POST /invoices`, `GET/PATCH/DELETE /invoices/{id}`,
228
+ `GET /invoices/{id}/transitions`, `POST /invoices/{id}/transitions/{event}`,
229
+ `POST /invoices/{id}/actions/{name}`.
230
+
231
+ References to other resources: `references = {"customer_id":
232
+ Reference("customers", name="customer_record")}` (`on_delete="restrict"` by
233
+ default, or `"set_null"`, `"cascade"`). Writes check the referenced record
234
+ exists and is readable (RE-E108); deleting a referenced record is refused
235
+ (RE-E109); `get`/`list` take `expand=["customer_record"]` (`?expand=` over HTTP)
236
+ and `list` filters on `customer_record.<filterable field>`. Never check
237
+ references in hooks or join by hand. Each reference also gives the target a
238
+ reverse relation (`GET /customers/{id}/invoices`, `manager.list_related`,
239
+ `expand=["invoices:10"]`); name it with `related_name=` or hide it with
240
+ `reverse=False`. Many-to-many: a join resource with two references and
241
+ `link = ("invoice_id", "tag_id")` gives `invoices` a `tags` relation (and
242
+ `tags` an `invoices` one); link by creating join records. `expand` paths nest
243
+ with dots (`invoices.customer_record`). See docs/relationships.md.
244
+
245
+ GraphQL (`resource-engine-graphql`): `mount_graphql(app, registry, manager,
246
+ actor_dependency=...)` serves a schema generated from the same definitions
247
+ (camelCase types, offset pages, mutations per write, transition and action);
248
+ nothing to write by hand. See docs/graphql.md.
249
+
250
+ MCP tools for AI agents (`resource-engine-mcp`): `ResourceMcpServer(registry,
251
+ manager)` turns the same operations into tools (`invoices_list`,
252
+ `invoices_transition_approve`, `invoices_action_recalculate_totals`...) called
253
+ through the manager as the caller; `mcp.mount(app, authenticator=...)` after
254
+ `mount_resources`, or `run_stdio(actor=...)`. Tool descriptions come from
255
+ `operation_docs`, action descriptions and the resource and state machine
256
+ docstrings, so write them for a reader who only sees the tool. See docs/mcp.md.
257
+
258
+ ## Kinds of one record
259
+
260
+ Records that come in kinds sharing most fields (vacation and expense
261
+ requests) are a base resource with subtypes, not one resource with nullable
262
+ columns per kind or unrelated copies:
263
+
264
+ ```python
265
+ class RequestResource(Resource):
266
+ name = "requests"
267
+ model = Request
268
+ schemas = {"read": RequestRead}
269
+ operations = ["list", "get"] # bases only read
270
+ discriminator = "type"
271
+ state_machine = RequestFlow # shared by every kind
272
+
273
+
274
+ class VacationResource(Resource):
275
+ name = "vacation_requests"
276
+ extends = Subtype(RequestResource, identity="vacation")
277
+ model = Vacation # subclass of Request
278
+ schemas = {
279
+ "create": VacationIn,
280
+ "update": VacationIn,
281
+ "read": VacationRead,
282
+ } # read ⊇ RequestRead
283
+ operations = ["list", "get", "create", "update", "delete"]
284
+ ```
285
+
286
+ SQL: `extension_table(...)` per subtype and `map_family(mapper_registry,
287
+ registry, "requests", tables)`. See docs/polymorphism.md.
288
+
289
+ ## Figures computed from other records
290
+
291
+ Totals, counts and balances are a view resource, not a stored field kept up
292
+ to date in hooks and not a custom endpoint: see
293
+ `examples/invoices/application/balances.py`. `map_views(mapper_registry,
294
+ registry)` after mapping the sources; nothing to migrate.
295
+
296
+ ## Caching
297
+
298
+ Don't hand-roll caches in hooks or repositories: set `caching = Cached(ttl=...)` on resources
299
+ read far more than written and pass `cache=InMemoryCache()` (one instance) or
300
+ `RedisCache(redis, secret=...)` to the manager. Permissions still run per
301
+ caller on cached records. HTTP ETag/304 is automatic. See docs/caching.md.
@@ -0,0 +1,126 @@
1
+ # State machines
2
+
3
+ Processes with states use `python-statemachine` 3, in `domain/state_machine.py`.
4
+ The engine stores the state in `status` (or `Machine(cls, field=...)`), sets the
5
+ initial state on create and runs each transition as an operation with its own
6
+ hooks, permission and event.
7
+
8
+ ```python
9
+ from statemachine import State, StateMachine
10
+
11
+
12
+ class InvoiceStateMachine(StateMachine):
13
+ """Procés d'aprovació i cobrament d'una factura.
14
+
15
+ States:
16
+ draft: Esborrany editable per l'emissor.
17
+ pending: Enviada a aprovació; ja no es pot modificar.
18
+ approved: Aprovada i pendent de cobrament.
19
+ rejected: Rebutjada pel responsable.
20
+ paid: Cobrada. Estat final.
21
+
22
+ Transitions:
23
+ submit: Envia l'esborrany a aprovació.
24
+ approve: Aprova una factura pendent.
25
+ reject: Rebutja una factura pendent indicant-ne el motiu.
26
+ reopen: Torna una factura rebutjada a esborrany.
27
+ pay: Registra el cobrament d'una factura aprovada.
28
+ """
29
+
30
+ draft = State("Esborrany", initial=True)
31
+ pending = State("Pendent")
32
+ approved = State("Aprovada")
33
+ rejected = State("Rebutjada")
34
+ paid = State("Cobrada", final=True)
35
+
36
+ submit = draft.to(pending)
37
+ approve = pending.to(approved)
38
+ reject = pending.to(rejected)
39
+ reopen = rejected.to(draft)
40
+ pay = approved.to(paid)
41
+
42
+ def on_reject(self, reason: str) -> None:
43
+ self.model.rejection_reason = reason # transition input arrives as arguments
44
+ ```
45
+
46
+ On the resource:
47
+
48
+ ```python
49
+ state_machine = InvoiceStateMachine
50
+ transition_schemas = {"reject": RejectInvoice} # input of `reject`: {"reason": ...}
51
+ ```
52
+
53
+ ## Rules
54
+
55
+ - **Every state and every transition is documented** in the `States:` and
56
+ `Transitions:` sections (RE-D004, RE-D005).
57
+ - **The state field is not in `create` or `update` schemas** (RE-E004), and
58
+ updates never change it. Put it in the `read` schema.
59
+ - **Callbacks change the entity (`self.model`) only.** No I/O, no events:
60
+ record events in `after_transition[:event]` hooks.
61
+ - **Guards** (`cond=`, `unless=`) are fine for state-based conditions. Rules
62
+ about who may transition belong to permissions
63
+ (`invoices:transition:approve`), not guards.
64
+ - Transitions that need documents use `DocumentSlot(required_for=["approve"])`
65
+ (RE-E606 when missing).
66
+ - `internal = Internal(transitions=True)` keeps them internal (consumers,
67
+ jobs), with no HTTP routes.
68
+
69
+ ## Running them
70
+
71
+ ```python
72
+ await manager.transition("invoices", 7, "reject", {"reason": "Import incorrecte"}, actor=user)
73
+ await manager.allowed_transitions("invoices", 7, actor=user) # what the caller may fire now
74
+ await manager.history("invoices", 7, actor=user) # creation and transitions, from the audit trail
75
+ ```
76
+
77
+ HTTP: `GET /invoices/{id}/transitions`, `POST /invoices/{id}/transitions/reject`,
78
+ `GET /invoices/{id}/history` (needs `audit=True`; don't build your own
79
+ transition log table).
80
+ Not possible from the current state → RE-E201 (`details.allowed`); unknown
81
+ event → RE-E202. The engine publishes `TransitionExecuted` (with `source` and
82
+ `target`) after commit.
83
+
84
+ `resource-engine docs generate` draws each machine as a Mermaid diagram.
85
+
86
+ ## Several machines
87
+
88
+ A record that follows independent processes (approval and delivery) declares
89
+ named machines instead of `state_machine`, each with its own field:
90
+
91
+ ```python
92
+ machines = {
93
+ "approval": Machine(InvoiceStateMachine, field="status", since_field="status_changed_at"),
94
+ "delivery": Machine(InvoiceDelivery, field="delivery_status"),
95
+ }
96
+ ```
97
+
98
+ Transition names must be unique across them (routes and permissions use the
99
+ bare event). A guard can read the other machine's field through `self.model`.
100
+ History entries and `TransitionExecuted` name the `machine`; `history(...,
101
+ machine="delivery")` filters. Don't model a second process as extra states of
102
+ one machine, or as a plain field changed in hooks.
103
+
104
+ ## Deadlines
105
+
106
+ A transition that must happen after some time (expire, escalate, remind) is a
107
+ timer on the resource, not a cron job or a hook:
108
+
109
+ ```python
110
+ # since_field: in the entity and read schema; the engine stamps it
111
+ state_machine = Machine(InvoiceStateMachine, since_field="status_changed_at")
112
+ timers = [Timer("reject", after=timedelta(days=30), data={"reason": "No answer in 30 days"})]
113
+ ```
114
+
115
+ The worker runs `TimerJob(manager)` (`single=True`); each due record goes
116
+ through `manager.transition` as `system:timers`. See docs/timers.md.
117
+
118
+ ## Processes across resources
119
+
120
+ A process that reacts to events over time (wait for a payment, then pay the
121
+ invoice, alarm after 15 days) is a `Process` from `resource_engine.processes`,
122
+ not ad-hoc consumers: its records are the instances (`correlation` field),
123
+ `reacts = [On("PaymentReceived", handler, key="invoice_id", payload=Model)]`,
124
+ handlers call `step.start()`, `step.transition()` and the manager as
125
+ `step.actor`, timeouts are `timers`, compensations are transitions with hooks.
126
+ See `examples/invoices/application/processes.py` and docs/processes.md.
@@ -0,0 +1,80 @@
1
+ # Testing
2
+
3
+ Test through the `ResourceManager` with the in-memory adapters: the same
4
+ lifecycle, permissions and hooks as in production, without a database. Use
5
+ `pytest` with `pytest-asyncio` in auto mode.
6
+
7
+ ```python
8
+ import pytest
9
+ from resource_engine import ResourceManager
10
+ from resource_engine.domain import DomainError
11
+ from resource_engine.errors import TransitionNotAllowed
12
+ from resource_engine.testing import InMemoryBlobStore, InMemoryStore, RecordingEventPublisher
13
+
14
+ from billing.bootstrap import registry
15
+
16
+
17
+ @pytest.fixture
18
+ def store():
19
+ return InMemoryStore.from_registry(registry)
20
+
21
+
22
+ @pytest.fixture
23
+ def publisher():
24
+ return RecordingEventPublisher()
25
+
26
+
27
+ @pytest.fixture
28
+ def manager(store, publisher):
29
+ return ResourceManager(
30
+ registry,
31
+ store.unit_of_work,
32
+ event_publisher=publisher,
33
+ services={"notifier": FakeNotifier()},
34
+ blob_store=InMemoryBlobStore(),
35
+ )
36
+
37
+
38
+ async def test_rule_in_hook_rolls_back(manager, store, publisher):
39
+ with pytest.raises(DomainError):
40
+ await manager.create("invoices", {"customer": "ACME", "amount": "-1"})
41
+ assert store.all("invoices") == [] # nothing saved
42
+ assert publisher.events == [] # nothing published
43
+
44
+
45
+ async def test_transition(manager):
46
+ invoice = await manager.create("invoices", {"customer": "ACME", "amount": "10"})
47
+ await manager.transition("invoices", invoice.id, "submit")
48
+ with pytest.raises(TransitionNotAllowed):
49
+ await manager.transition("invoices", invoice.id, "pay")
50
+ ```
51
+
52
+ ## What to test
53
+
54
+ - Domain rules: plain unit tests of the entity methods, no engine.
55
+ - Each hook's rule through the manager, including the rollback.
56
+ - Each transition: allowed and refused (RE-E201).
57
+ - Each action: its postconditions and the events it records
58
+ (`publisher.names()`).
59
+ - Permissions: with `PolicyAuthorizer(config, store.unit_of_work)` and
60
+ `Principal(subject=..., issuer=..., roles=frozenset({...}))`, both allowed
61
+ and `PermissionDenied`.
62
+ - Over HTTP when routes or status codes matter: build the FastAPI app with
63
+ `mount_resources` and use `httpx.AsyncClient(transport=ASGITransport(app))`.
64
+ - With SQLite (`sqlite+aiosqlite`) when the mapping or SQL filters matter.
65
+
66
+ ## Helpers in `resource_engine.testing`
67
+
68
+ | Helper | Use |
69
+ |---|---|
70
+ | `InMemoryStore` | Units of work, repositories, outbox, inbox (`store.unit_of_work`, `store.all(name)`, `store.outbox_records()`) |
71
+ | `RecordingEventPublisher` | Events published after commit (`events`, `names()`) |
72
+ | `InMemoryBlobStore` | Document contents |
73
+ | `InMemoryQueue` | A broker for consumers (`publish`, `MessageConsumer(queue, processor)`) |
74
+ | `InMemoryLocks` | Leases for `JobRunner` jobs with `single=True` |
75
+ | `RecordingTracer` | Spans (`set_tracer(tracer)`, `tracer.named("invoices create")`) |
76
+ | `ConditionEngine` | A policy engine with rules in the condition language |
77
+ | `contracts.*Contract` | Test suites for your own adapters |
78
+
79
+ Never mock the manager or the lifecycle: if a test needs it, use the real
80
+ manager on the in-memory store.
@@ -0,0 +1,26 @@
1
+ ## Resource Engine
2
+
3
+ This project is built with Resource Engine {version}. Before changing
4
+ resources, operations, transitions, actions, hooks or permissions, read the
5
+ skill at `{skill_path}/SKILL.md` and the project catalogue at
6
+ `{skill_path}/project.md`.
7
+
8
+ Rules:
9
+
10
+ - No external effects (HTTP, e-mail, messages) before commit: record a domain
11
+ event, or use an `after_commit` hook marked `@external_effect`.
12
+ - State changes only through transitions; never put the state field in a
13
+ create or update schema.
14
+ - `domain/` imports nothing from FastAPI, SQLAlchemy, Pydantic or HTTP clients.
15
+ - Business processes are actions or transitions, not hooks; permissions are
16
+ policies or system roles, never checks in hooks.
17
+ - Document every resource, operation, state, transition and action with
18
+ docstrings in the functional convention.
19
+
20
+ Verify before finishing:
21
+
22
+ ```bash
23
+ resource-engine check --json
24
+ resource-engine docs validate --strict
25
+ pytest
26
+ ```
@@ -0,0 +1,7 @@
1
+ ---
2
+ description: Resource Engine conventions for resources, lifecycle hooks, state machines, actions and permissions
3
+ globs: "**/*.py"
4
+ alwaysApply: false
5
+ ---
6
+
7
+ {block}
@@ -0,0 +1,67 @@
1
+ """Architecture lints (``resource-engine check``). Rule codes: RE-C0xx."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ from dataclasses import asdict, dataclass
7
+ from pathlib import Path
8
+
9
+ #: Top-level packages that a ``domain/`` package must never import.
10
+ FORBIDDEN_IN_DOMAIN = (
11
+ "fastapi",
12
+ "starlette",
13
+ "sqlalchemy",
14
+ "pydantic",
15
+ "resource_engine_fastapi",
16
+ "resource_engine_sqlalchemy",
17
+ "httpx",
18
+ "requests",
19
+ )
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class Violation:
24
+ """A problem a check found, at a file and line, with its RE-C code."""
25
+
26
+ code: str
27
+ path: str
28
+ line: int
29
+ message: str
30
+ hint: str
31
+
32
+ def to_dict(self) -> dict[str, object]:
33
+ """The violation as JSON-ready data."""
34
+ return asdict(self)
35
+
36
+
37
+ def _imports(tree: ast.AST) -> list[tuple[str, int]]:
38
+ found: list[tuple[str, int]] = []
39
+ for node in ast.walk(tree):
40
+ if isinstance(node, ast.Import):
41
+ found += [(alias.name, node.lineno) for alias in node.names]
42
+ elif isinstance(node, ast.ImportFrom) and node.module and node.level == 0:
43
+ found.append((node.module, node.lineno))
44
+ return found
45
+
46
+
47
+ def check_domain_imports(root: Path) -> list[Violation]:
48
+ """RE-C001: ``domain/`` modules that import infrastructure packages."""
49
+ violations: list[Violation] = []
50
+ for path in sorted(root.rglob("*.py")):
51
+ if "domain" not in path.relative_to(root).parts[:-1] or ".venv" in path.parts:
52
+ continue
53
+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
54
+ for module, line in _imports(tree):
55
+ top = module.split(".")[0]
56
+ if top in FORBIDDEN_IN_DOMAIN:
57
+ violations.append(
58
+ Violation(
59
+ code="RE-C001",
60
+ path=str(path),
61
+ line=line,
62
+ message=f"domain module imports infrastructure package {module!r}",
63
+ hint="Move this code to application/ or infrastructure/, or depend on a "
64
+ "port defined in the domain/application layer.",
65
+ )
66
+ )
67
+ return violations