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,805 @@
1
+ """``resource-engine scaffold``: deterministic boilerplate for a module, an action
2
+ or a state machine, laid out like the reference module (``examples/invoices``).
3
+
4
+ The generated code imports, registers and passes ``check`` and its own tests
5
+ as it is. Every docstring starts with ``TODO:``; ``docs validate`` warns about
6
+ them (RE-D010) until they describe the business. Existing files are never
7
+ overwritten without ``force``.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import itertools
13
+ import keyword
14
+ import re
15
+ from dataclasses import dataclass, field
16
+ from pathlib import Path
17
+ from string import Template
18
+
19
+ #: Field type → (Python annotation, SQLAlchemy column type, import of the annotation).
20
+ TYPES: dict[str, tuple[str, str, str | None]] = {
21
+ "str": ("str", "String(200)", None),
22
+ "text": ("str", "Text", None),
23
+ "int": ("int", "Integer", None),
24
+ "bool": ("bool", "Boolean", None),
25
+ "Decimal": ("Decimal", "Numeric(12, 2, asdecimal=True)", "from decimal import Decimal"),
26
+ "date": ("date", "Date", "from datetime import date"),
27
+ "datetime": ("datetime", "DateTime(timezone=True)", "from datetime import datetime"),
28
+ }
29
+
30
+ #: Values used in generated tests, per type.
31
+ SAMPLES = {
32
+ "str": '"Sample"',
33
+ "text": '"Sample text"',
34
+ "int": "1",
35
+ "bool": "True",
36
+ "Decimal": '"10.00"',
37
+ "date": '"2026-01-31"',
38
+ "datetime": '"2026-01-31T10:00:00+00:00"',
39
+ }
40
+
41
+
42
+ class ScaffoldError(SystemExit):
43
+ """A bad argument or a file that already exists (exit status 2)."""
44
+
45
+ def __init__(self, message: str) -> None:
46
+ super().__init__(message)
47
+ self.code = 2
48
+ self.message = message
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class Field:
53
+ """A field to scaffold: its name, type and whether it is optional."""
54
+
55
+ name: str
56
+ type: str
57
+ optional: bool = False
58
+
59
+ @property
60
+ def annotation(self) -> str:
61
+ """The field's Python type annotation."""
62
+ base = TYPES[self.type][0]
63
+ return f"{base} | None" if self.optional else base
64
+
65
+ @property
66
+ def column(self) -> str:
67
+ """The SQLAlchemy column type of the field."""
68
+ return TYPES[self.type][1]
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class Transition:
73
+ """A transition to scaffold."""
74
+
75
+ event: str
76
+ source: str
77
+ target: str
78
+
79
+
80
+ @dataclass
81
+ class Result:
82
+ """What a scaffold wrote, skipped and what to do next."""
83
+
84
+ written: list[str] = field(default_factory=list)
85
+ skipped: list[str] = field(default_factory=list)
86
+ next_steps: list[str] = field(default_factory=list)
87
+
88
+ def to_dict(self) -> dict[str, list[str]]:
89
+ """The result as JSON-ready data."""
90
+ return {"written": self.written, "skipped": self.skipped, "next_steps": self.next_steps}
91
+
92
+
93
+ # ----------------------------------------------------------------- parsing
94
+
95
+
96
+ def parse_fields(raw: list[str] | None) -> list[Field]:
97
+ """Fields from ``name:type`` arguments (``name:str?`` for optional ones)."""
98
+ fields = []
99
+ for item in raw or []:
100
+ name, _, kind = item.partition(":")
101
+ optional = kind.endswith("?")
102
+ kind = kind.rstrip("?") or "str"
103
+ _identifier(name, "field")
104
+ if kind not in TYPES:
105
+ raise ScaffoldError(
106
+ f"Unknown type {kind!r} for {name!r}; use one of: {', '.join(TYPES)}"
107
+ )
108
+ if name in ("id", "status", "version"):
109
+ raise ScaffoldError(f"{name!r} is generated; don't pass it as a field")
110
+ fields.append(Field(name, kind, optional))
111
+ if len({f.name for f in fields}) != len(fields):
112
+ raise ScaffoldError("Duplicate field names")
113
+ return fields
114
+
115
+
116
+ def parse_machine(
117
+ states: str | None, transitions: str | None
118
+ ) -> tuple[list[str], list[Transition]]:
119
+ """States and transitions from the ``--states`` and ``--transitions`` arguments."""
120
+ names = [s.strip() for s in (states or "draft,active,closed").split(",") if s.strip()]
121
+ for name in names:
122
+ _identifier(name, "state")
123
+ if len(names) < 2:
124
+ raise ScaffoldError("A state machine needs at least two states and one transition")
125
+ raw = transitions or ",".join(f"{_verb(b)}:{a}>{b}" for a, b in itertools.pairwise(names))
126
+ result = []
127
+ for item in raw.split(","):
128
+ match = re.fullmatch(r"\s*(\w+)\s*:\s*(\w+)\s*>\s*(\w+)\s*", item)
129
+ if not match:
130
+ raise ScaffoldError(f"Bad transition {item!r}; use event:source>target")
131
+ event, source, target = match.groups()
132
+ for state in (source, target):
133
+ if state not in names:
134
+ raise ScaffoldError(f"Transition {event!r} uses unknown state {state!r}")
135
+ _identifier(event, "transition")
136
+ result.append(Transition(event, source, target))
137
+ if len(names) < 2 or not result:
138
+ raise ScaffoldError("A state machine needs at least two states and one transition")
139
+ clash = {t.event for t in result} & set(names)
140
+ if clash:
141
+ raise ScaffoldError(f"Names used both as state and transition: {', '.join(sorted(clash))}")
142
+ return names, result
143
+
144
+
145
+ def _verb(state: str) -> str:
146
+ known = {"active": "activate", "closed": "close", "approved": "approve", "done": "finish"}
147
+ return known.get(state, f"to_{state}")
148
+
149
+
150
+ def _identifier(name: str, what: str) -> None:
151
+ if not name.isidentifier() or keyword.iskeyword(name) or not name.islower():
152
+ raise ScaffoldError(f"Invalid {what} name {name!r}: use a lowercase Python identifier")
153
+
154
+
155
+ def pascal(name: str) -> str:
156
+ """``snake_case`` as ``PascalCase``."""
157
+ return "".join(part.capitalize() for part in name.split("_") if part)
158
+
159
+
160
+ def singular(name: str) -> str:
161
+ """An English plural made singular (``invoices`` → ``invoice``)."""
162
+ if name.endswith("ies"):
163
+ return name[:-3] + "y"
164
+ if name.endswith("ses"):
165
+ return name[:-2]
166
+ return name[:-1] if name.endswith("s") and not name.endswith("ss") else name
167
+
168
+
169
+ def package_dir(root: Path, package: str) -> Path:
170
+ """The directory of a dotted package under ``root``."""
171
+ if not re.fullmatch(r"[a-z_][a-z0-9_]*(\.[a-z_][a-z0-9_]*)*", package):
172
+ raise ScaffoldError(f"Invalid package {package!r}: use a dotted lowercase name")
173
+ return root.joinpath(*package.split("."))
174
+
175
+
176
+ # ----------------------------------------------------------------- writing
177
+
178
+
179
+ def _write(path: Path, content: str, result: Result, *, force: bool, dry_run: bool) -> None:
180
+ if path.exists() and not force:
181
+ result.skipped.append(str(path))
182
+ return
183
+ result.written.append(str(path))
184
+ if not dry_run:
185
+ path.parent.mkdir(parents=True, exist_ok=True)
186
+ path.write_text(content, encoding="utf-8")
187
+
188
+
189
+ def _render(template: str, **values: str) -> str:
190
+ text = Template(template).substitute(values)
191
+ return re.sub(r"\n{3,}", "\n\n\n", text).strip("\n") + "\n"
192
+
193
+
194
+ # ---------------------------------------------------------------- resource
195
+
196
+
197
+ def resource(
198
+ root: Path,
199
+ package: str,
200
+ name: str,
201
+ fields: list[Field],
202
+ *,
203
+ entity: str | None = None,
204
+ machine: tuple[list[str], list[Transition]] | None = None,
205
+ versioned: bool = False,
206
+ force: bool = False,
207
+ dry_run: bool = False,
208
+ ) -> Result:
209
+ """Write a resource: its entity, schemas, declaration and a test."""
210
+ _identifier(name, "resource")
211
+ entity = entity or pascal(singular(name))
212
+ if not entity.isidentifier() or not entity[0].isupper():
213
+ raise ScaffoldError(f"Invalid entity class name {entity!r}")
214
+ base = package_dir(root, package)
215
+ if base.exists() and any(base.iterdir()) and not force:
216
+ raise ScaffoldError(f"{base} already exists; pick another package or pass --force")
217
+ result = Result()
218
+ if not fields:
219
+ fields = [Field("name", "str")]
220
+ ctx = _Context(package, name, entity, fields, machine, versioned)
221
+ files = {
222
+ "__init__.py": f'"""{entity} module."""\n',
223
+ "domain/__init__.py": '"""The domain: entities, rules and the state machine."""\n',
224
+ "domain/entities.py": ctx.entities(),
225
+ "application/__init__.py": '"""Schemas, hooks, actions and the resource declaration."""\n',
226
+ "application/schemas.py": ctx.schemas(),
227
+ "application/hooks.py": ctx.hooks(),
228
+ "application/resource.py": ctx.resource(),
229
+ "infrastructure/__init__.py": '"""The infrastructure: how the entities are stored."""\n',
230
+ "infrastructure/persistence.py": ctx.persistence(),
231
+ f"tests/test_{name}.py": ctx.tests(),
232
+ }
233
+ if machine:
234
+ files["domain/state_machine.py"] = state_machine_source(entity, *machine)
235
+ for relative, content in files.items():
236
+ _write(base / relative, content, result, force=force, dry_run=dry_run)
237
+ cls = f"{entity}Resource"
238
+ result.next_steps = [
239
+ f"Register it in your composition root: from {package}.application.resource import {cls}; "
240
+ f"registry.register({cls})",
241
+ f"Map it at start-up: from {package}.infrastructure.persistence import map_entities; "
242
+ "map_entities() (and add its metadata to your migrations)",
243
+ f"Give every operation a gate: a seed policy or a system role for {name}:list, "
244
+ f"{name}:get, {name}:create, {name}:update, {name}:delete"
245
+ + "".join(
246
+ f", {name}:transition:{event}"
247
+ for event in dict.fromkeys(t.event for t in (machine[1] if machine else []))
248
+ )
249
+ + " (resource-engine check reports the rest as RE-C004)",
250
+ "Replace every TODO docstring and the TODO rule in the entity; then run "
251
+ "resource-engine check, resource-engine docs validate --strict and pytest",
252
+ ]
253
+ return result
254
+
255
+
256
+ @dataclass
257
+ class _Context:
258
+ package: str
259
+ name: str
260
+ entity: str
261
+ fields: list[Field]
262
+ machine: tuple[list[str], list[Transition]] | None
263
+ versioned: bool
264
+
265
+ @property
266
+ def imports(self) -> list[str]:
267
+ return sorted(
268
+ {TYPES[f.type][2] for f in self.fields if TYPES[f.type][2]} # type: ignore[misc]
269
+ )
270
+
271
+ def entities(self) -> str:
272
+ required = [f for f in self.fields if not f.optional]
273
+ optional = [f for f in self.fields if f.optional]
274
+ lines = [f" {f.name}: {f.annotation}" for f in required]
275
+ lines += [f" {f.name}: {f.annotation} = None" for f in optional]
276
+ if self.machine:
277
+ lines.append(" status: str | None = None")
278
+ if self.versioned:
279
+ lines.append(" version: int | None = None")
280
+ lines.append(" id: int | None = None")
281
+ return _render(
282
+ '''
283
+ """The $entity entity and its business errors."""
284
+
285
+ from __future__ import annotations
286
+
287
+ from dataclasses import dataclass$imports
288
+
289
+ from resource_engine.domain import DomainError
290
+
291
+
292
+ class ${entity}Error(DomainError):
293
+ """A $label broke a business rule."""
294
+
295
+ code = "$code"
296
+
297
+
298
+ @dataclass
299
+ class $entity:
300
+ """TODO: describe what a $label is.
301
+
302
+ Business Rules:
303
+ - TODO: list the rules a $label must keep.
304
+ """
305
+
306
+ $fields
307
+
308
+ def ensure_valid(self) -> None:
309
+ """TODO: enforce the business rules; raise ${entity}Error when one is broken."""
310
+ ''',
311
+ entity=self.entity,
312
+ code=self.name.upper(),
313
+ label=self.name.removesuffix("s").replace("_", " "),
314
+ imports="".join(f"\n{line}" for line in self.imports),
315
+ fields="\n".join(lines),
316
+ )
317
+
318
+ def schemas(self) -> str:
319
+ create = [
320
+ f" {f.name}: {f.annotation}" + (" = None" if f.optional else "") for f in self.fields
321
+ ]
322
+ update = [f" {f.name}: {TYPES[f.type][0]} | None = None" for f in self.fields]
323
+ read = [f" {f.name}: {f.annotation}" for f in self.fields]
324
+ if self.machine:
325
+ read.append(" status: str")
326
+ if self.versioned:
327
+ read.append(" version: int")
328
+ imports = "\n".join(self.imports)
329
+ return _render(
330
+ '''
331
+ """What the API takes and returns: the create, update and read schemas."""
332
+
333
+ from __future__ import annotations$imports
334
+
335
+ from pydantic import BaseModel, ConfigDict
336
+
337
+
338
+ class ${entity}Create(BaseModel):
339
+ """TODO: data needed to create a $label."""
340
+
341
+ $create
342
+
343
+
344
+ class ${entity}Update(BaseModel):
345
+ """TODO: fields that can be changed."""
346
+
347
+ $update
348
+
349
+
350
+ class ${entity}Read(BaseModel):
351
+ """TODO: what clients see of a $label."""
352
+
353
+ model_config = ConfigDict(from_attributes=True)
354
+
355
+ id: int
356
+ $read
357
+ ''',
358
+ entity=self.entity,
359
+ label=self.name.removesuffix("s").replace("_", " "),
360
+ imports=("\n\n" + imports) if imports else "",
361
+ create="\n".join(create),
362
+ update="\n".join(update),
363
+ read="\n".join(read),
364
+ )
365
+
366
+ def hooks(self) -> str:
367
+ return _render(
368
+ '''
369
+ """Hooks: the rules that run around the resource's operations."""
370
+
371
+ from __future__ import annotations
372
+
373
+ from resource_engine import OperationContext, hook
374
+
375
+
376
+ @hook.before("create")
377
+ @hook.after("update")
378
+ def validate(ctx: OperationContext) -> None:
379
+ """TODO: say which rules are checked before the $label is saved."""
380
+ ctx.entity.ensure_valid()
381
+ ''',
382
+ label=self.name.removesuffix("s").replace("_", " "),
383
+ )
384
+
385
+ def resource(self) -> str:
386
+ machine_import = (
387
+ f"from {self.package}.domain.state_machine import {self.entity}StateMachine\n"
388
+ if self.machine
389
+ else ""
390
+ )
391
+ options = []
392
+ if self.machine:
393
+ options.append(f" state_machine = {self.entity}StateMachine")
394
+ if self.versioned:
395
+ options.append(' concurrency = Versioned("version")')
396
+ return _render(
397
+ '''
398
+ """The resource: what the engine exposes, and how."""
399
+
400
+ from __future__ import annotations
401
+
402
+ from resource_engine import $engine_imports
403
+
404
+ from $package.application import hooks
405
+ from $package.application.schemas import ${entity}Create, ${entity}Read, ${entity}Update
406
+ from $package.domain.entities import $entity
407
+ $machine_import
408
+
409
+ class ${entity}Resource(Resource):
410
+ """TODO: describe what this resource lets users do.
411
+
412
+ Business area:
413
+ TODO
414
+ """
415
+
416
+ name = "$name"
417
+ model = $entity
418
+ schemas = {"create": ${entity}Create, "update": ${entity}Update, "read": ${entity}Read}
419
+ operations = CRUD
420
+ operation_docs = {
421
+ "list": "TODO: describe the list.",
422
+ "get": "TODO: describe what is returned.",
423
+ "create": "TODO: describe the creation.",
424
+ "update": "TODO: describe what can be changed.",
425
+ "delete": "TODO: describe the deletion.",
426
+ }
427
+ hooks = [hooks] # the functions marked with @hook in hooks.py
428
+ listing = Listing(sortable=["id"])
429
+ $options
430
+ ''',
431
+ package=self.package,
432
+ entity=self.entity,
433
+ name=self.name,
434
+ machine_import=machine_import,
435
+ options="\n".join(options),
436
+ engine_imports=", ".join(
437
+ ["CRUD", "Listing", "Resource", *(["Versioned"] if self.versioned else [])]
438
+ ),
439
+ )
440
+
441
+ def persistence(self) -> str:
442
+ columns = [
443
+ f' Column("{f.name}", {f.column}, nullable={f.optional}),' for f in self.fields
444
+ ]
445
+ if self.machine:
446
+ columns.append(' Column("status", String(32), nullable=False),')
447
+ if self.versioned:
448
+ columns.append(' Column("version", Integer, nullable=False, default=1),')
449
+ used = {"Column", "Integer", "MetaData", "Table"}
450
+ for f in self.fields:
451
+ used.add(f.column.split("(")[0])
452
+ if self.machine:
453
+ used.add("String")
454
+ return _render(
455
+ '''
456
+ """SQLAlchemy mapping of the $name module. Only infrastructure imports SQLAlchemy."""
457
+
458
+ from __future__ import annotations
459
+
460
+ from sqlalchemy import $sa_imports
461
+ from sqlalchemy.orm import registry as orm_registry
462
+
463
+ from $package.domain.entities import $entity
464
+
465
+ metadata = MetaData()
466
+ mapper_registry = orm_registry(metadata=metadata)
467
+
468
+ ${name}_table = Table(
469
+ "$name",
470
+ metadata,
471
+ Column("id", Integer, primary_key=True, autoincrement=True),
472
+ $columns
473
+ )
474
+
475
+ _mapped = False
476
+
477
+
478
+ def map_entities() -> None:
479
+ """Idempotently map the domain entities to their tables."""
480
+ global _mapped
481
+ if not _mapped:
482
+ mapper_registry.map_imperatively($entity, ${name}_table)
483
+ _mapped = True
484
+ ''',
485
+ name=self.name,
486
+ package=self.package,
487
+ entity=self.entity,
488
+ sa_imports=", ".join(sorted(used)),
489
+ columns="\n".join(columns),
490
+ )
491
+
492
+ def tests(self) -> str:
493
+ payload = ", ".join(f'"{f.name}": {SAMPLES[f.type]}' for f in self.fields if not f.optional)
494
+ first = self.fields[0]
495
+ changed = {
496
+ "str": '"Changed"',
497
+ "text": '"Changed"',
498
+ "int": "2",
499
+ "bool": "False",
500
+ "Decimal": '"20.00"',
501
+ "date": '"2026-02-28"',
502
+ "datetime": '"2026-02-28T10:00:00+00:00"',
503
+ }[first.type]
504
+ machine_test = ""
505
+ if self.machine:
506
+ states, transitions = self.machine
507
+ t = next(x for x in transitions if x.source == states[0])
508
+ machine_test = f'''
509
+
510
+ async def test_starts_in_{states[0]}_and_{t.event}(manager):
511
+ created = await manager.create("{self.name}", {{{payload}}})
512
+ assert created.status == "{states[0]}"
513
+ moved = await manager.transition("{self.name}", created.id, "{t.event}")
514
+ assert moved.status == "{t.target}"
515
+ '''
516
+ return _render(
517
+ '''
518
+ """Lifecycle tests of the $name module against the in-memory adapters."""
519
+
520
+ from __future__ import annotations
521
+
522
+ import pytest
523
+ from resource_engine import ResourceManager, ResourceRegistry
524
+ from resource_engine.testing import InMemoryStore, RecordingEventPublisher
525
+
526
+ from $package.application.resource import ${entity}Resource
527
+
528
+ pytestmark = pytest.mark.asyncio
529
+
530
+
531
+ @pytest.fixture
532
+ def publisher():
533
+ return RecordingEventPublisher()
534
+
535
+
536
+ @pytest.fixture
537
+ def manager(publisher):
538
+ registry = ResourceRegistry()
539
+ registry.register(${entity}Resource)
540
+ store = InMemoryStore.from_registry(registry)
541
+ return ResourceManager(registry, store.unit_of_work, event_publisher=publisher)
542
+
543
+
544
+ async def test_create_get_update_delete(manager, publisher):
545
+ created = await manager.create("$name", {$payload})
546
+ assert (await manager.get("$name", created.id)).id == created.id
547
+ updated = await manager.update("$name", created.id, {"$first": $changed})
548
+ assert updated.$first != created.$first
549
+ await manager.delete("$name", created.id)
550
+ assert (await manager.list("$name")).total == 0
551
+ assert publisher.names() == ["ResourceCreated", "ResourceUpdated", "ResourceDeleted"]
552
+ $machine_test
553
+ ''',
554
+ name=self.name,
555
+ package=self.package,
556
+ entity=self.entity,
557
+ payload=payload,
558
+ first=first.name,
559
+ changed=changed,
560
+ machine_test=machine_test,
561
+ )
562
+
563
+
564
+ # ----------------------------------------------------------- state machine
565
+
566
+
567
+ def state_machine_source(entity: str, states: list[str], transitions: list[Transition]) -> str:
568
+ """The source of a state machine class."""
569
+ state_lines = []
570
+ for i, state in enumerate(states):
571
+ flags = []
572
+ if i == 0:
573
+ flags.append("initial=True")
574
+ if not any(t.source == state for t in transitions):
575
+ flags.append("final=True")
576
+ state_lines.append(
577
+ f' {state} = State("{pascal(state)}"' + "".join(f", {f}" for f in flags) + ")"
578
+ )
579
+ return _render(
580
+ '''
581
+ """The entity's state machine: its states and the transitions between them."""
582
+
583
+ from __future__ import annotations
584
+
585
+ from statemachine import State, StateMachine
586
+
587
+
588
+ class ${entity}StateMachine(StateMachine):
589
+ """TODO: describe the process.
590
+
591
+ States:
592
+ $state_docs
593
+
594
+ Transitions:
595
+ $transition_docs
596
+ """
597
+
598
+ $states
599
+
600
+ $transitions
601
+ ''',
602
+ entity=entity,
603
+ state_docs="\n".join(f" {s}: TODO" for s in states),
604
+ transition_docs="\n".join(
605
+ f" {e}: TODO" for e in dict.fromkeys(t.event for t in transitions)
606
+ ),
607
+ states="\n".join(state_lines),
608
+ transitions="\n".join(
609
+ f" {event} = "
610
+ + " | ".join(f"{t.source}.to({t.target})" for t in transitions if t.event == event)
611
+ for event in dict.fromkeys(t.event for t in transitions)
612
+ ),
613
+ )
614
+
615
+
616
+ def state_machine(
617
+ root: Path,
618
+ package: str,
619
+ entity: str,
620
+ states: list[str],
621
+ transitions: list[Transition],
622
+ *,
623
+ force: bool = False,
624
+ dry_run: bool = False,
625
+ ) -> Result:
626
+ """Write a state machine and attach it to the entity's resource."""
627
+ base = _existing(root, package)
628
+ result = Result()
629
+ _write(
630
+ base / "domain/state_machine.py",
631
+ state_machine_source(entity, states, transitions),
632
+ result,
633
+ force=force,
634
+ dry_run=dry_run,
635
+ )
636
+ if result.skipped:
637
+ raise ScaffoldError(f"{result.skipped[0]} already exists; pass --force to replace it")
638
+ result.next_steps = [
639
+ f"On the resource: from {package}.domain.state_machine import {entity}StateMachine; "
640
+ f"state_machine = {entity}StateMachine",
641
+ "Add `status: str | None = None` to the entity, `status: str` to the read schema and a "
642
+ "status column to the table; never put it in the create or update schema",
643
+ "Grant the transitions: "
644
+ + ", ".join(
645
+ f"<resource>:transition:{e}" for e in dict.fromkeys(t.event for t in transitions)
646
+ ),
647
+ "Describe every state and transition in the docstring (replace the TODOs)",
648
+ ]
649
+ return result
650
+
651
+
652
+ # ------------------------------------------------------------------ action
653
+
654
+
655
+ def action(
656
+ root: Path,
657
+ package: str,
658
+ resource_name: str,
659
+ class_name: str,
660
+ fields: list[Field],
661
+ *,
662
+ collection: bool = False,
663
+ dry_run: bool = False,
664
+ ) -> Result:
665
+ """Write an action and add it to its resource."""
666
+ if not re.fullmatch(r"[A-Z][A-Za-z0-9]*", class_name):
667
+ raise ScaffoldError(f"Invalid action class name {class_name!r}: use PascalCase")
668
+ base = _existing(root, package)
669
+ actions_path = base / "application/actions.py"
670
+ schemas_path = base / "application/schemas.py"
671
+ current = actions_path.read_text(encoding="utf-8") if actions_path.exists() else ""
672
+ if re.search(rf"^class {class_name}\b", current, re.M):
673
+ raise ScaffoldError(f"{actions_path} already defines {class_name}")
674
+ action_name = re.sub(r"(?<!^)(?=[A-Z])", "_", class_name).lower()
675
+ input_cls = f"{class_name}Input" if fields else None
676
+ result = Result()
677
+ header = (
678
+ '"""The resource\'s actions."""\n\n'
679
+ "from __future__ import annotations\n\n"
680
+ "from resource_engine import Action, OperationContext\n"
681
+ )
682
+ if input_cls:
683
+ header += f"\nfrom {package}.application.schemas import {input_cls}\n"
684
+ body = _render(
685
+ '''
686
+ class $cls(Action):
687
+ """TODO: say what the action does.
688
+
689
+ Preconditions:
690
+ TODO
691
+
692
+ Postconditions:
693
+ TODO
694
+ """
695
+ $options
696
+ async def execute(self, ctx: OperationContext) -> None:
697
+ """TODO: implement; runs inside the transaction (no external effects)."""
698
+ $body
699
+ ''',
700
+ cls=class_name,
701
+ options=(
702
+ "\n"
703
+ + "\n".join(
704
+ ([f" input_schema = {input_cls}"] if input_cls else [])
705
+ + ([" instance = False"] if collection else [])
706
+ )
707
+ + "\n"
708
+ )
709
+ if input_cls or collection
710
+ else "",
711
+ body="raise NotImplementedError"
712
+ if collection
713
+ else (
714
+ "entity = ctx.entity # loaded and authorized\n"
715
+ " await ctx.repository().update(entity)"
716
+ ),
717
+ )
718
+ if current:
719
+ content = current.rstrip("\n") + "\n\n\n" + body
720
+ if "from resource_engine import" not in current:
721
+ content = header + "\n\n" + content
722
+ elif input_cls and f"import {input_cls}" not in current:
723
+ content = content.replace(
724
+ "from resource_engine import Action, OperationContext\n",
725
+ "from resource_engine import Action, OperationContext\n\n"
726
+ f"from {package}.application.schemas import {input_cls}\n",
727
+ 1,
728
+ )
729
+ else:
730
+ content = header + "\n\n" + body
731
+ result.written.append(str(actions_path))
732
+ if not dry_run:
733
+ actions_path.parent.mkdir(parents=True, exist_ok=True)
734
+ actions_path.write_text(content, encoding="utf-8")
735
+ if input_cls:
736
+ schema = _render(
737
+ '''
738
+ class $cls(BaseModel):
739
+ """TODO: input of the action."""
740
+
741
+ $fields
742
+ ''',
743
+ cls=input_cls,
744
+ fields="\n".join(
745
+ f" {f.name}: {f.annotation}" + (" = None" if f.optional else "") for f in fields
746
+ ),
747
+ )
748
+ existing = schemas_path.read_text(encoding="utf-8") if schemas_path.exists() else ""
749
+ if not existing:
750
+ existing = (
751
+ '"""What the API takes and returns: the create, update and read schemas."""\n\n'
752
+ "from __future__ import annotations\n\nfrom pydantic import BaseModel\n"
753
+ )
754
+ extra = [line for f in fields if (line := TYPES[f.type][2]) and line not in existing]
755
+ if extra:
756
+ existing = existing.replace(
757
+ "from __future__ import annotations\n",
758
+ "from __future__ import annotations\n\n" + "\n".join(sorted(set(extra))) + "\n",
759
+ 1,
760
+ )
761
+ result.written.append(str(schemas_path))
762
+ if not dry_run:
763
+ schemas_path.write_text(existing.rstrip("\n") + "\n\n\n" + schema, encoding="utf-8")
764
+ declared = _declare_action(base, package, resource_name, class_name, result, dry_run)
765
+ result.next_steps = [
766
+ *(
767
+ []
768
+ if declared
769
+ else [
770
+ f"On the resource: from {package}.application.actions import {class_name}; "
771
+ f"add {class_name} to `actions`"
772
+ ]
773
+ ),
774
+ f"Grant it: {resource_name}:action:{action_name} in a seed policy or a system role",
775
+ f"HTTP: POST /{resource_name}"
776
+ + ("" if collection else "/{id}")
777
+ + f"/actions/{action_name}",
778
+ "Implement execute and replace the TODO docstring (Postconditions are required)",
779
+ ]
780
+ return result
781
+
782
+
783
+ def _declare_action(
784
+ base: Path, package: str, resource: str, class_name: str, result: Result, dry_run: bool
785
+ ) -> bool:
786
+ """Add the action to the resource's ``actions``; ``False`` when the
787
+ resource class isn't found in the module."""
788
+ from resource_engine_devtools import source_edit as edit
789
+ from resource_engine_devtools.scaffold_parts import _ResourceFile
790
+
791
+ try:
792
+ target = _ResourceFile(base, package, resource)
793
+ except ScaffoldError:
794
+ return False
795
+ target.apply(lambda s: edit.add_import(s, f"{package}.application.actions", class_name))
796
+ target.apply(lambda s: edit.append_to_list(s, target.class_name, "actions", class_name))
797
+ target.write(result, dry_run=dry_run)
798
+ return True
799
+
800
+
801
+ def _existing(root: Path, package: str) -> Path:
802
+ base = package_dir(root, package)
803
+ if not (base / "application").is_dir() and not (base / "domain").is_dir():
804
+ raise ScaffoldError(f"{base} is not a module (no domain/ or application/)")
805
+ return base