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,97 @@
1
+ # Docstrings
2
+
3
+ Functional documentation is generated from docstrings and checked in CI with
4
+ `resource-engine docs validate --strict`. Use Google style with these functional
5
+ sections (title, colon, indented body):
6
+
7
+ | Section | Where |
8
+ |---|---|
9
+ | `Business area:` | Resources |
10
+ | `Actors:` | Resources, actions |
11
+ | `Preconditions:` | Actions, hooks |
12
+ | `Postconditions:` | Actions (required, RE-D007) |
13
+ | `Business Rules:` | Entities, resources |
14
+ | `Effects:` | Actions, hooks with effects |
15
+ | `Exceptions:` | Anything that raises domain errors |
16
+ | `Examples:` | Anything |
17
+ | `States:` / `Transitions:` | State machines: one `name: description` per state and per transition |
18
+
19
+ The first line is a one-sentence summary. Write in the project's language
20
+ (the reference module uses Catalan).
21
+
22
+ ## What `docs validate` requires
23
+
24
+ | Code | Level | Rule |
25
+ |---|---|---|
26
+ | RE-D001 | error | Every resource has a docstring |
27
+ | RE-D002 | error | Every enabled CRUD operation has an `operation_docs` entry |
28
+ | RE-D003 | error | Every state machine has a docstring |
29
+ | RE-D004 | warning | Every state is described under `States:` |
30
+ | RE-D005 | warning | Every transition is described under `Transitions:` |
31
+ | RE-D006 | error | Every action has a docstring |
32
+ | RE-D007 | warning | Every action has `Postconditions:` |
33
+ | RE-D008 | warning | Every hook has a docstring |
34
+ | RE-D009 | warning | Every document slot has a `description` |
35
+ | RE-D010 | warning | No description is still a `TODO` placeholder (from `scaffold`) |
36
+ | RE-D011 | warning | Every declared domain event has a docstring |
37
+
38
+ `--strict` makes warnings fail too; use it in CI.
39
+
40
+ ## Examples
41
+
42
+ ```python
43
+ class InvoiceResource(Resource):
44
+ """Gestió de factures de l'organització.
45
+
46
+ Permet crear, consultar i modificar factures, així com gestionar-ne el
47
+ procés d'aprovació i cobrament.
48
+
49
+ Business area:
50
+ Facturació
51
+
52
+ Actors:
53
+ - Comptable
54
+ - Responsable
55
+ """
56
+
57
+ operation_docs = {
58
+ "list": "Llista les factures, filtrables per estat i client.",
59
+ "get": "Consulta una factura.",
60
+ }
61
+ ```
62
+
63
+ ```python
64
+ class RecalculateTotals(Action):
65
+ """Aplica un descompte percentual a l'import d'una factura.
66
+
67
+ Preconditions:
68
+ La factura és un esborrany.
69
+
70
+ Postconditions:
71
+ L'import queda reduït pel percentatge indicat, arrodonit a cèntims.
72
+
73
+ Effects:
74
+ Emet l'esdeveniment ``InvoiceTotalsRecalculated``.
75
+ """
76
+ ```
77
+
78
+ ```python
79
+ @dataclass
80
+ class Invoice:
81
+ """Factura emesa a un client.
82
+
83
+ Business Rules:
84
+ - L'import total no pot ser negatiu.
85
+ - Una factura només es pot modificar mentre és un esborrany.
86
+ """
87
+ ```
88
+
89
+ Docstrings describe behaviour; they never replace it. Permissions are enforced
90
+ by policies, transitions by the state machine, rules by the domain code.
91
+
92
+ ## Where the docs go
93
+
94
+ `resource-engine docs generate` writes them as Markdown and `resource-engine
95
+ docs site --out site` as a static website for non-developers (diagrams,
96
+ permission matrix, events, search). Both come from these docstrings: fix the
97
+ text here, never in the generated files.
@@ -0,0 +1,81 @@
1
+ # Error codes
2
+
3
+ Every engine error has a stable `code`, a `message`, a `hint` (what to change)
4
+ and a `doc` link. Read the hint first.
5
+
6
+ ## Raised while declaring (fix the code)
7
+
8
+ | Code | Class | Fix |
9
+ |---|---|---|
10
+ | RE-E001 | `ConfigurationError` | A resource, action, hook or option is declared wrongly; the message names it |
11
+ | RE-E004 | `StateFieldExposed` | Remove the state field from the `create` / `update` schema; change it with transitions |
12
+ | RE-E005 | `VersioningNotSupported` | `concurrency = Versioned(...)` on a repository without compare-and-set (REST, SOAP): drop it |
13
+ | RE-E008 | `IdempotencyNotSupported` | Pass `idempotency_table=` to the unit of work factory (`engine_tables(metadata, idempotency=True)`) |
14
+ | RE-E009 | `HistoryNotAvailable` | `history` needs a state machine, `audit` on the resource and `audit=True` (a `RepositoryAuditSink`) on the manager |
15
+ | RE-E010 | `TemplateNotFound` | No template for that name, locale or fallback |
16
+ | RE-E011 | `TemplateFailed` | A template failed to render (a missing variable) |
17
+ | RE-E012 | `TransactionTooLarge` | One commit holds more writes than the store's transactions take (100 in DynamoDB and Cosmos DB, 500 in Firestore): split the operation |
18
+ | RE-E104 | `ExternalEffectInTransaction` | Move the `@external_effect` hook to `after_commit` or record an event |
19
+
20
+ ## Raised by operations
21
+
22
+ | Code | Class | HTTP | Meaning |
23
+ |---|---|---|---|
24
+ | RE-E002 | `ResourceNotRegistered` | 404 | Unknown resource name |
25
+ | RE-E003 | `OperationNotEnabled` | 405 | The operation is not in `operations` |
26
+ | RE-E007 | `TransactionDoomed` | 500 | An operation failed inside `manager.transaction()` |
27
+ | RE-E101 | `ValidationFailed` | 422 | Input does not match the schema (`details`: Pydantic errors) |
28
+ | RE-E102 | `EntityNotFound` | 404 | No record with that id (or not visible) |
29
+ | RE-E103 | `InvalidQuery`, `QueryNotSupported` | 400 | Filter or order field not in `Listing(filterable=)` / `sortable`, an unknown filter operator or a value of the wrong type, a search on a resource without `searchable` fields; `QueryNotSupported`: the store has no index for it (NoSQL capability flags) or can't apply operators or a search |
30
+ | RE-E105 | `VersionConflict` | 409 | Stale version: reload and retry |
31
+ | RE-E106 | `VersionRequired` | 428 | `Versioned(required=True)`: send `If-Match` / `expected_version` |
32
+ | RE-E107 | `IdempotencyKeyReused` | 422 | The idempotency key was used for a different request |
33
+ | RE-E108 | `ReferenceNotFound` | 422 | A reference points to a missing or unreadable record: use an existing id |
34
+ | RE-E109 | `ReferenceInUse` | 409 | Other records still reference it: change or delete them first |
35
+ | RE-E201 | `TransitionNotAllowed` | 409 | Not possible from the current state (`details.allowed`) |
36
+ | RE-E202 | `UnknownTransition` | 404 | No such transition |
37
+ | RE-E301 | `ActionNotFound` | 404 | No such action |
38
+ | RE-E401 | `PublishFailed` | – | A broker refused messages |
39
+ | RE-E402 | `NoHandler` | – | No consumer handler for the event type |
40
+ | RE-E403 | `OutboxNotSupported` | 500 | `OutboxDelivery` without an outbox table |
41
+ | RE-E404 | `InboxNotSupported` | – | A consumer's unit of work has no inbox table |
42
+ | RE-E405 | `UndecodableMessage` | 422 | Inbound body is not an envelope or CloudEvent |
43
+ | RE-E406 | `MessageRejected` | 422 | Raised by a handler: dead-letter without retries |
44
+ | RE-E501 | `RemoteCallFailed` | 502 | A REST or SOAP service failed |
45
+ | RE-E502 | `EmailRejected` | – | The mail service refused the message for good |
46
+ | RE-E601 | `DocumentSlotNotFound` | 404 | No such document slot |
47
+ | RE-E602 | `ContentTypeNotAllowed` | 415 | The slot does not accept the type |
48
+ | RE-E603 | `DocumentTooLarge` | 413 | Over `max_bytes` |
49
+ | RE-E604 | `UploadNotVerified` | 409 | Presigned upload missing or expired |
50
+ | RE-E605 | `DocumentNotAvailable` | 409 | Document pending, processing, rejected or deleted |
51
+ | RE-E606 | `RequiredDocumentMissing` | 409 | The transition needs a document (`required_for`) |
52
+ | RE-E607 | `StorageFailed` | 502 | The blob store failed |
53
+ | RE-E608 | `BlobNotFound` | 404 | No content under the key |
54
+ | RE-E701 | `AuthenticationFailed` | 401 | Missing or invalid credentials, or nobody signed in where permissions apply |
55
+ | RE-E702 | `PermissionDenied` | 403 | Not allowed (`details.action`, `reason`) |
56
+ | RE-E703 | `InvalidPolicy` | 422 | Invalid policy, role or assignment (`details.problems`) |
57
+ | RE-E704 | `PrivilegeEscalation` | 403 | Granting actions the editor does not hold |
58
+ | RE-E705 | `ConditionNotSupported` | 500 | A row filter cannot be applied (fails closed) |
59
+ | RE-E706 | `FieldNotWritable` | 403 | Input sets fields the caller may not write |
60
+ | RE-E707 | `FieldNotReadable` | 403 | Filter or sort by a field the caller may not read |
61
+ | RE-E708 | `TenantRequired` | 403 | Tenant-scoped resource without a tenant |
62
+ | RE-E709 | `TenantMismatch` | 403 | Another tenant named |
63
+ | RE-E710 | `RateLimited` | 429 | Too many requests: wait `details.retry_after` (Retry-After) |
64
+
65
+ Your own business errors subclass `resource_engine.domain.DomainError`, set a
66
+ `code`, and map to HTTP 422.
67
+
68
+ ## Tool rules
69
+
70
+ | Code | Tool | Fix |
71
+ |---|---|---|
72
+ | RE-C001 | `check` | Remove the infrastructure import from `domain/` |
73
+ | RE-C002 | `check` | Move the external effect after commit (event, consumer, `after_commit` + `@external_effect`) |
74
+ | RE-C003 | `check` | Do it before commit, or start a new operation |
75
+ | RE-C004 | `check` | Grant the operation: a seed policy, a system role, or remove the operation |
76
+ | RE-C005 | `check` | The engine refused a declaration: read the `RE-E` code and hint in the message |
77
+ | RE-C006 | `check` | Add the recorded event class to the resource's `events` |
78
+ | RE-C007 | `check` | Add the missing email template (subject, text or HTML) |
79
+ | RE-C008 | `check` | Move code out of the declaration (a `@hook` function, an `Action`, plain code) and long values to modules next to it |
80
+ | RE-C009 | `check` | Write the other resource through the manager: a process or consumer reacting to an event, or application code in `manager.transaction()` |
81
+ | RE-D001…D011 | `docs validate` | Add the missing docstring or section ([docstrings.md](docstrings.md)) |
@@ -0,0 +1,118 @@
1
+ # Lifecycle
2
+
3
+ Every writing operation (create, update, delete, transition, action, attach,
4
+ detach) runs these steps. The order is a contract, covered by the engine's
5
+ tests.
6
+
7
+ | # | Step | In the transaction | Hook points |
8
+ |---|---|---|---|
9
+ | 1 | Resolve resource and operation | – | |
10
+ | 2 | Tenant scope; permission without the record (RE-E702) | – | |
11
+ | 3 | Validate input with the operation's schema (RE-E101) | no | `before_validate`, `after_validate` |
12
+ | 4 | Open the unit of work | yes | |
13
+ | 5 | Load the entity; permission on the record (404 if hidden); writable fields (RE-E706); version check (RE-E105) | yes | |
14
+ | 6 | Before mutation | yes | `before_create` `before_update` `before_delete` `before_transition[:event]` `before_action[:name]` `before_attach[:slot]` `before_detach[:slot]` |
15
+ | 7 | Mutate: add / apply update / delete / fire the state machine / `Action.execute` / store the document | yes | |
16
+ | 8 | After mutation | yes | `after_create` `after_update` `after_delete` `after_transition[:event]` `after_action[:name]` `after_attach[:slot]` `after_detach[:slot]` |
17
+ | 9 | Build the result, write the audit entry, stage events (outbox), commit | yes | |
18
+ | 10 | After commit | no | `ctx.on_commit` callbacks, `after_commit` hooks, then event delivery |
19
+
20
+ - Any exception in steps 3 to 9 aborts the operation; from step 4 it rolls the
21
+ transaction back and no event is published.
22
+ - Generic hooks run before qualified ones: `before_transition` then
23
+ `before_transition:approve`.
24
+ - On create, the entity gets the initial state before step 6.
25
+ - `after_commit` failures are logged and do not undo the operation.
26
+
27
+ ## Hooks
28
+
29
+ ```python
30
+ from resource_engine import OperationContext, hook
31
+
32
+
33
+ @hook.before("update", "delete")
34
+ def ensure_editable(ctx: OperationContext) -> None:
35
+ """Només es poden modificar o eliminar factures en esborrany."""
36
+ ctx.entity.ensure_editable() # the rule lives in the domain
37
+ ```
38
+
39
+ `fn(ctx)` or `async def fn(ctx)`, marked with where it runs
40
+ (`@hook.before(...)`, `@hook.after(...)`, `@hook.after_commit`; stack them for
41
+ several points). The resource lists the marked functions, or their module:
42
+ `hooks = [hooks]` or `hooks = [hooks.ensure_editable, stamp]`. The mapping
43
+ `hooks = {"before_update": [ensure_editable]}` works too. Unknown points or
44
+ qualifiers fail at once (RE-E001), and an unmarked function listed in `hooks`
45
+ at registration.
46
+
47
+ Choosing the point:
48
+
49
+ | You want to | Use |
50
+ |---|---|
51
+ | Normalise raw input | `before_validate` (`ctx.raw_input` is mutable) |
52
+ | Check a rule that needs the stored entity | `before_update`, `before_delete`, `before_transition[:event]` |
53
+ | Check a rule on the final values | `after_create`, `after_update` (raise to roll back) |
54
+ | Set derived fields | `before_create`, `before_update` (assign on `ctx.entity`) |
55
+ | Record a domain event | any point before commit (`ctx.record_event`) |
56
+ | E-mail, HTTP call, message to another system | an `after_commit` hook marked `@external_effect`, or a consumer of the event |
57
+
58
+ ## What a hook sees (`OperationContext`)
59
+
60
+ | Attribute | Content |
61
+ |---|---|
62
+ | `operation`, `transition`, `action`, `slot` | What is running |
63
+ | `actor` | The caller (`Principal`), or `None` |
64
+ | `raw_input`, `data` | Input before and after validation |
65
+ | `entity_id`, `entity` | Target record (loaded or newly built) |
66
+ | `previous_state`, `new_state` | Around a transition |
67
+ | `services` | `ResourceManager(services={...})`: notifiers, clients… |
68
+ | `correlation_id` | Shared by logs, audit and events of the operation |
69
+ | `repository(name=None)` | Repository in the current transaction (not after commit) |
70
+ | `record_event(event)` | Publish after commit |
71
+ | `on_rollback(fn)`, `on_commit(fn)` | Compensation / clean-up callbacks |
72
+ | `documents` | `attach`, `detach`, `list` documents in this transaction |
73
+
74
+ ## External effects
75
+
76
+ Code before commit must not do anything the rollback cannot undo. Mark
77
+ functions that do with `@external_effect`; the engine refuses them anywhere but
78
+ `after_commit` (RE-E104), and `resource-engine check` finds unmarked ones
79
+ (RE-C002):
80
+
81
+ ```python
82
+ from resource_engine import external_effect
83
+
84
+
85
+ @external_effect
86
+ async def notify_approval(ctx: OperationContext) -> None:
87
+ """Notifica el client que la factura ha estat aprovada.
88
+
89
+ Effects:
90
+ Envia una notificació mitjançant el servei ``notifier``.
91
+ """
92
+ if ctx.transition == "approve":
93
+ await ctx.services["notifier"].send(f"Invoice {ctx.entity_id} approved")
94
+ ```
95
+
96
+ For guaranteed delivery, record an event and use `OutboxDelivery`: the event is
97
+ stored in the same transaction and a consumer does the effect.
98
+
99
+ A *staged* effect, such as a blob stored under a new key, may happen before
100
+ commit if it registers its undo: `ctx.on_rollback(lambda: store.delete([key]))`.
101
+
102
+ ## Retries: idempotency keys
103
+
104
+ Writes take `idempotency_key=` (HTTP: the `Idempotency-Key` header). A retry
105
+ with the same key and request returns the first result without running again;
106
+ the record is stored in the operation's transaction, so a failed write keeps no
107
+ key. Use them for anything a client may retry: payments, actions, creates.
108
+
109
+ ## Several operations in one transaction
110
+
111
+ ```python
112
+ async with manager.transaction():
113
+ await manager.update("invoices", 7, {"amount": "120"})
114
+ await manager.transition("invoices", 7, "submit")
115
+ ```
116
+
117
+ They commit together. A failure inside dooms the block: leaving it raises
118
+ RE-E007 and rolls everything back, even if your code caught the error.
@@ -0,0 +1,111 @@
1
+ # Permissions
2
+
3
+ Two layers decide who may do what:
4
+
5
+ - **System roles** in code (`AuthzConfig(system_roles=[SystemRole.admin(),
6
+ SystemRole.viewer()])`). They grant action patterns and cannot be denied.
7
+ - **Policies** (ABAC) stored as data in `authz_policies` and managed from a front
8
+ end at runtime. Or an external engine (OPA, Cedar, OpenFGA) behind
9
+ `EngineAuthorizer`.
10
+
11
+ Business rules ("only drafts can be edited") stay in the domain. Permissions
12
+ answer whether *this caller* may perform *this action* on *this record*.
13
+ **Never check roles or users in hooks.**
14
+
15
+ With an authorizer configured, the default is **deny**. Without one, everything
16
+ is allowed. Engine jobs act as `system_principal("job-name")`, always allowed.
17
+
18
+ ## Action names
19
+
20
+ | Operation | Action |
21
+ |---|---|
22
+ | CRUD | `invoices:list`, `invoices:get`, `invoices:create`, `invoices:update`, `invoices:delete` |
23
+ | Transition | `invoices:transition:approve` |
24
+ | Action | `invoices:action:recalculate_totals` |
25
+ | Documents | `invoices:attach:<slot>`, `invoices:detach:<slot>`, `invoices:download:<slot>` |
26
+ | Fields | `invoices:read:<field>`, `invoices:write:<field>` |
27
+
28
+ `resource-engine inspect --json` lists them. Patterns: `*` matches one segment,
29
+ a trailing `*` the rest (`invoices:*`, `*:list`).
30
+
31
+ The explorer's actions belong to no resource (`register_explorer(registry)`,
32
+ before the manager): `events:read`, `jobs:read`, `jobs:run` and
33
+ `events:publish:<Event>`. The last is *exact*: never grant it through a
34
+ wildcard, name it (see docs/explorer.md).
35
+
36
+ ## Policies (data)
37
+
38
+ ```json
39
+ {
40
+ "name": "Approvers decide invoices under 10,000",
41
+ "effect": "allow",
42
+ "subjects": {"roles": ["approver"]},
43
+ "actions": ["invoices:transition:approve", "invoices:transition:reject"],
44
+ "condition": {"lt": [{"attr": "resource.amount"}, 10000]}
45
+ }
46
+ ```
47
+
48
+ Conditions: one operator per object, `eq ne lt le gt ge`, `in nin`, `contains`,
49
+ `exists`, `and or not`. Operands are literals or `{"attr": "<ns>.<path>"}` with
50
+ namespaces `subject` (`id`, `roles`, `groups`, `tenant`, `claims.*`…),
51
+ `resource` (read-schema fields), `input` (validated input), `context`
52
+ (`action`, `operation`, `now`).
53
+
54
+ Row-level conditions on `list` become SQL filters. A deny that holds wins over
55
+ any allow; system-role grants win over everything. Policies are validated when
56
+ saved (RE-E703).
57
+
58
+ ## Fields
59
+
60
+ Fields are open by default. Mark sensitive ones on the resource:
61
+
62
+ ```python
63
+ access = Access(restricted_fields=["notes"]) # needs invoices:read:notes / :write:notes
64
+ ```
65
+
66
+ Hidden fields are omitted from responses. Writing one fails with RE-E706,
67
+ filtering or sorting by one with RE-E707.
68
+
69
+ ## Tenants
70
+
71
+ ```python
72
+ access = Access(tenant_field="org") # entity attribute holding the tenant
73
+ ```
74
+
75
+ Every operation is confined to `Principal.tenant` before any policy is
76
+ evaluated. The engine stamps the tenant on create. Don't add tenant checks in
77
+ hooks or tenant filters in queries.
78
+
79
+ ## Every operation needs a gate
80
+
81
+ When you add an operation, transition, action or document slot, also add who
82
+ may use it: a policy in the application's seed (the list named by
83
+ `[tool.resource-engine] policies`), or a system-role grant. `resource-engine
84
+ check` reports operations that only `admin` can perform (RE-C004).
85
+
86
+ ## In tests
87
+
88
+ ```python
89
+ manager = ResourceManager(
90
+ registry, store.unit_of_work, authorizer=PolicyAuthorizer(config, store.unit_of_work)
91
+ )
92
+ user = Principal(subject="ana", issuer="idp", roles=frozenset({"approver"}))
93
+ with pytest.raises(PermissionDenied):
94
+ await manager.transition("invoices", 1, "approve", actor=user)
95
+ ```
96
+
97
+ ## Machine clients
98
+
99
+ Clients that cannot use OAuth client credentials get API keys
100
+ (`registry.register_api_keys()`, `ApiKeyAuthenticator(uow_factory,
101
+ fallback=oidc)` in `bearer_actor`), not a hand-made token table or a shared
102
+ secret in settings. Keys carry roles (at most the creator's), a tenant and an
103
+ expiry, and are revoked with the `revoke` transition. See docs/api-keys.md.
104
+
105
+ ## Rate limits
106
+
107
+ Limits are configuration, not code in hooks or endpoints: a `RateLimiter`
108
+ (`default` per caller, `anonymous` per address, `failed_auth`, `actions` per
109
+ engine action) passed to `ResourceManager(rate_limiter=)` and
110
+ `bearer_actor(..., rate_limiter=)`; `RedisRateLimitStore` with several
111
+ instances. Refusals are RE-E710 (429). See docs/rate-limits.md.