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,424 @@
1
+ """Small, comment-preserving edits of Python source for the scaffold commands:
2
+ add an import, append to a class attribute's list or dict, add a field to a
3
+ class, add an argument to a call.
4
+
5
+ Edits insert lines; they never rewrite what is there except a one-line
6
+ literal or import that has to grow (re-rendered on several lines). The result
7
+ is formatted the way ``ruff format`` leaves the generated modules.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import ast
13
+ import sys
14
+ from collections.abc import Callable
15
+
16
+ INDENT = " "
17
+ MAX_LINE = 100
18
+
19
+
20
+ class EditError(ValueError):
21
+ """The source doesn't have the shape the edit expects."""
22
+
23
+
24
+ def _lines(source: str) -> list[str]:
25
+ return source.splitlines(keepends=True)
26
+
27
+
28
+ def _join(lines: list[str]) -> str:
29
+ text = "".join(lines)
30
+ return text if text.endswith("\n") else text + "\n"
31
+
32
+
33
+ def _segment(source: str, node: ast.AST) -> str:
34
+ text = ast.get_source_segment(source, node)
35
+ if text is None: # pragma: no cover - nodes from this source always have one
36
+ raise EditError("Cannot read the source of a node")
37
+ return text
38
+
39
+
40
+ # ------------------------------------------------------------------ imports
41
+
42
+
43
+ def add_import(source: str, module: str, name: str) -> str:
44
+ """``from module import name``, merged into an existing import of ``module``."""
45
+ tree = ast.parse(source)
46
+ for node in tree.body:
47
+ if isinstance(node, ast.ImportFrom) and node.module == module and node.level == 0:
48
+ names = [a.name if a.asname is None else f"{a.name} as {a.asname}" for a in node.names]
49
+ if name in names:
50
+ return source
51
+ names = sorted({*names, name}, key=_import_order)
52
+ lines = _lines(source)
53
+ rendered = _render_import(module, names)
54
+ lines[node.lineno - 1 : node.end_lineno] = [rendered]
55
+ return _join(lines)
56
+ imports = [n for n in tree.body if isinstance(n, ast.Import | ast.ImportFrom)]
57
+ lines = _lines(source)
58
+ line = f"from {module} import {name}\n"
59
+ if not imports:
60
+ position = _after_docstring(tree)
61
+ lines[position:position] = [line, "\n"] if position == 0 else ["\n", line]
62
+ return _join(lines)
63
+ # sorted among the imports of the same package, else of the same section
64
+ # (__future__, standard library, others), else as a section of its own
65
+ top = module.split(".")[0]
66
+ section = _section(module)
67
+ same = [n for n in imports if _module(n).split(".")[0] == top]
68
+ same = same or [n for n in imports if _section(_module(n)) == section]
69
+ if same:
70
+ later = [n for n in same if _module(n) > module]
71
+ if later:
72
+ anchor = min(later, key=lambda n: n.lineno)
73
+ lines[anchor.lineno - 1 : anchor.lineno - 1] = [line]
74
+ else:
75
+ anchor = max(same, key=lambda n: n.end_lineno or 0)
76
+ lines[anchor.end_lineno : anchor.end_lineno] = [line]
77
+ return _join(lines)
78
+ earlier = [n for n in imports if _section(_module(n)) < section]
79
+ if earlier:
80
+ anchor = max(earlier, key=lambda n: n.end_lineno or 0)
81
+ lines[anchor.end_lineno : anchor.end_lineno] = ["\n", line]
82
+ else:
83
+ anchor = min(imports, key=lambda n: n.lineno)
84
+ lines[anchor.lineno - 1 : anchor.lineno - 1] = [line, "\n"]
85
+ return _join(lines)
86
+
87
+
88
+ def _module(node: ast.Import | ast.ImportFrom) -> str:
89
+ if isinstance(node, ast.ImportFrom):
90
+ return node.module or ""
91
+ return node.names[0].name
92
+
93
+
94
+ def _section(module: str) -> int:
95
+ top = module.split(".")[0]
96
+ if top == "__future__":
97
+ return 0
98
+ return 1 if top in sys.stdlib_module_names else 2
99
+
100
+
101
+ def _import_order(name: str) -> tuple[int, str]:
102
+ # ruff (isort) order: CONSTANTS, Classes, functions
103
+ if name.isupper():
104
+ return (0, name)
105
+ if name[:1].isupper():
106
+ return (1, name)
107
+ return (2, name)
108
+
109
+
110
+ def _render_import(module: str, names: list[str]) -> str:
111
+ line = f"from {module} import {', '.join(names)}\n"
112
+ if len(line) - 1 <= MAX_LINE:
113
+ return line
114
+ return f"from {module} import (\n" + "".join(f"{INDENT}{n},\n" for n in names) + ")\n"
115
+
116
+
117
+ def _after_docstring(tree: ast.Module) -> int:
118
+ first = tree.body[0] if tree.body else None
119
+ if (
120
+ isinstance(first, ast.Expr)
121
+ and isinstance(first.value, ast.Constant)
122
+ and isinstance(first.value.value, str)
123
+ ):
124
+ return first.end_lineno or 0
125
+ return 0
126
+
127
+
128
+ # ------------------------------------------------------------------ classes
129
+
130
+
131
+ def find_class(tree: ast.Module, predicate: Callable[[ast.ClassDef], bool]) -> ast.ClassDef | None:
132
+ """The first top-level class that matches ``predicate``."""
133
+ for node in tree.body:
134
+ if isinstance(node, ast.ClassDef) and predicate(node):
135
+ return node
136
+ return None
137
+
138
+
139
+ def _class(source: str, name: str) -> tuple[ast.Module, ast.ClassDef]:
140
+ tree = ast.parse(source)
141
+ cls = find_class(tree, lambda c: c.name == name)
142
+ if cls is None:
143
+ raise EditError(f"No class {name}")
144
+ return tree, cls
145
+
146
+
147
+ def class_attribute(cls: ast.ClassDef, attr: str) -> ast.Assign | ast.AnnAssign | None:
148
+ """The assignment of a class attribute, if the class body has one."""
149
+ for node in cls.body:
150
+ if isinstance(node, ast.Assign) and any(
151
+ isinstance(t, ast.Name) and t.id == attr for t in node.targets
152
+ ):
153
+ return node
154
+ if (
155
+ isinstance(node, ast.AnnAssign)
156
+ and isinstance(node.target, ast.Name)
157
+ and node.target.id == attr
158
+ ):
159
+ return node
160
+ return None
161
+
162
+
163
+ def attribute_value(source: str, class_name: str, attr: str) -> ast.expr | None:
164
+ """The value assigned to a class attribute, if any."""
165
+ _, cls = _class(source, class_name)
166
+ node = class_attribute(cls, attr)
167
+ return None if node is None else node.value
168
+
169
+
170
+ def _last_attribute(cls: ast.ClassDef) -> ast.stmt:
171
+ attrs = [n for n in cls.body if isinstance(n, ast.Assign | ast.AnnAssign)]
172
+ return attrs[-1] if attrs else cls.body[-1]
173
+
174
+
175
+ def _insert_after(source: str, node: ast.stmt, text: str) -> str:
176
+ lines = _lines(source)
177
+ lines[node.end_lineno : node.end_lineno] = [text]
178
+ return _join(lines)
179
+
180
+
181
+ def add_class_attribute(source: str, class_name: str, attr: str, value: str) -> str:
182
+ """``attr = value`` after the class's last attribute."""
183
+ _, cls = _class(source, class_name)
184
+ if class_attribute(cls, attr) is not None:
185
+ raise EditError(f"{class_name}.{attr} already exists")
186
+ return _insert_after(source, _last_attribute(cls), _indent(f"{attr} = {value}", 1) + "\n")
187
+
188
+
189
+ def _indent(text: str, level: int) -> str:
190
+ pad = INDENT * level
191
+ return "\n".join(pad + line if line else line for line in text.split("\n"))
192
+
193
+
194
+ def _container_insert(source: str, node: ast.List | ast.Dict, item: str, level: int) -> str:
195
+ """Add ``item`` (an element, or ``key: value``) at the end of a literal whose
196
+ statement starts at indentation ``level``."""
197
+ lines = _lines(source)
198
+ elements = node.elts if isinstance(node, ast.List) else node.values
199
+ multiline = node.end_lineno != node.lineno
200
+ if multiline:
201
+ closing = node.end_lineno - 1 # type: ignore[operator]
202
+ if lines[closing].strip()[:1] not in ("]", "}"):
203
+ raise EditError("Unexpected layout: the closing bracket shares a line")
204
+ if elements:
205
+ last = elements[-1]
206
+ row = last.end_lineno - 1 # type: ignore[operator]
207
+ text = lines[row]
208
+ col = last.end_col_offset
209
+ rest = text[col:]
210
+ if not rest.lstrip().startswith(","):
211
+ lines[row] = text[:col] + "," + rest
212
+ lines[closing:closing] = [_indent(item, level + 1) + ",\n"]
213
+ return _join(lines)
214
+ # one line: re-render on several lines
215
+ if isinstance(node, ast.List):
216
+ items = [_segment(source, e) for e in node.elts]
217
+ opening, closing_char = "[", "]"
218
+ else:
219
+ items = [
220
+ f"{_segment(source, k)}: {_segment(source, v)}"
221
+ for k, v in zip(node.keys, node.values, strict=True)
222
+ if k is not None
223
+ ]
224
+ opening, closing_char = "{", "}"
225
+ items.append(item)
226
+ row = node.lineno - 1
227
+ text = lines[row]
228
+ before, after = text[: node.col_offset], text[node.end_col_offset :]
229
+ body = "".join(_indent(i, level + 1) + ",\n" for i in items)
230
+ lines[row] = before + opening + "\n" + body + INDENT * level + closing_char + after
231
+ return _join(lines)
232
+
233
+
234
+ def _literal(opening: str, item: str, closing: str, attr: str) -> str:
235
+ """A new one-item literal: on one line when it fits, else one item per line."""
236
+ one_line = f"{opening}{item}{closing}"
237
+ if "\n" not in item and len(INDENT + attr + " = " + one_line) <= MAX_LINE:
238
+ return one_line
239
+ return f"{opening}\n{_indent(item, 1)},\n{closing}"
240
+
241
+
242
+ def append_to_list(source: str, class_name: str, attr: str, item: str) -> str:
243
+ """Add ``item`` to the list ``attr`` of the class (created when missing)."""
244
+ _, cls = _class(source, class_name)
245
+ node = class_attribute(cls, attr)
246
+ if node is None:
247
+ return add_class_attribute(source, class_name, attr, _literal("[", item, "]", attr))
248
+ if not isinstance(node.value, ast.List):
249
+ raise EditError(f"{class_name}.{attr} is not a list literal")
250
+ return _container_insert(source, node.value, item, 1)
251
+
252
+
253
+ def add_to_dict(source: str, class_name: str, attr: str, key: str, value: str) -> str:
254
+ """Add ``"key": value`` to the dict ``attr`` (created when missing)."""
255
+ _, cls = _class(source, class_name)
256
+ node = class_attribute(cls, attr)
257
+ entry = f'"{key}": {value}'
258
+ if node is None:
259
+ return add_class_attribute(source, class_name, attr, _literal("{", entry, "}", attr))
260
+ if not isinstance(node.value, ast.Dict):
261
+ raise EditError(f"{class_name}.{attr} is not a dict literal")
262
+ if key in dict_keys(node.value):
263
+ raise EditError(f"{class_name}.{attr} already has {key!r}")
264
+ return _container_insert(source, node.value, entry, 1)
265
+
266
+
267
+ def add_to_dict_list(source: str, class_name: str, attr: str, key: str, item: str) -> str:
268
+ """Add ``item`` to the list under ``"key"`` in the dict ``attr`` (hooks)."""
269
+ _, cls = _class(source, class_name)
270
+ node = class_attribute(cls, attr)
271
+ if node is None or not isinstance(node.value, ast.Dict) or key not in dict_keys(node.value):
272
+ return add_to_dict(source, class_name, attr, key, f"[{item}]")
273
+ value = node.value.values[dict_keys(node.value).index(key)]
274
+ if isinstance(value, ast.List):
275
+ if item in [_segment(source, e) for e in value.elts]:
276
+ raise EditError(f"{key} already runs {item}")
277
+ lines = _lines(source)
278
+ if value.end_lineno == value.lineno:
279
+ row = value.lineno - 1
280
+ text = lines[row]
281
+ items = [_segment(source, e) for e in value.elts] + [item]
282
+ grown = text[: value.col_offset] + "[" + ", ".join(items) + "]"
283
+ grown += text[value.end_col_offset :]
284
+ if len(grown.rstrip("\n")) <= MAX_LINE:
285
+ lines[row] = grown
286
+ return _join(lines)
287
+ return _container_insert(source, value, item, 2)
288
+ # a single hook: make it a list
289
+ lines = _lines(source)
290
+ row = value.lineno - 1
291
+ if value.end_lineno != value.lineno:
292
+ raise EditError(f"Unexpected layout for {key}")
293
+ text = lines[row]
294
+ before, after = text[: value.col_offset], text[value.end_col_offset :]
295
+ lines[row] = f"{before}[{_segment(source, value)}, {item}]{after}"
296
+ return _join(lines)
297
+
298
+
299
+ def dict_keys(node: ast.Dict) -> list[str | None]:
300
+ """The keys of a dict literal (``None`` where a key isn't a text constant)."""
301
+ return [
302
+ k.value if isinstance(k, ast.Constant) and isinstance(k.value, str) else None
303
+ for k in node.keys
304
+ ]
305
+
306
+
307
+ def list_call_names(node: ast.expr | None, callee: str) -> list[str]:
308
+ """First string argument of each ``callee(...)`` in a list literal."""
309
+ if not isinstance(node, ast.List):
310
+ return []
311
+ names = []
312
+ for element in node.elts:
313
+ if (
314
+ isinstance(element, ast.Call)
315
+ and isinstance(element.func, ast.Name)
316
+ and element.func.id == callee
317
+ and element.args
318
+ and isinstance(element.args[0], ast.Constant)
319
+ ):
320
+ names.append(str(element.args[0].value))
321
+ return names
322
+
323
+
324
+ # ------------------------------------------------------------------ fields
325
+
326
+
327
+ def class_fields(source: str, class_name: str) -> list[str]:
328
+ """The annotated fields of a class."""
329
+ _, cls = _class(source, class_name)
330
+ return [
331
+ n.target.id
332
+ for n in cls.body
333
+ if isinstance(n, ast.AnnAssign) and isinstance(n.target, ast.Name)
334
+ ]
335
+
336
+
337
+ def add_field(
338
+ source: str, class_name: str, line: str, *, required: bool, before: tuple[str, ...] = ()
339
+ ) -> str:
340
+ """Add an annotated field. A required one goes before the first field with
341
+ a default (dataclass order); an optional one before the first of
342
+ ``before`` (engine fields such as ``status``, ``id``), else last."""
343
+ _, cls = _class(source, class_name)
344
+ fields = [
345
+ n for n in cls.body if isinstance(n, ast.AnnAssign) and isinstance(n.target, ast.Name)
346
+ ]
347
+ anchor = None
348
+ if required:
349
+ anchor = next((f for f in fields if f.value is not None), None)
350
+ else:
351
+ anchor = next((f for f in fields if f.target.id in before), None) # type: ignore[union-attr]
352
+ lines = _lines(source)
353
+ text = _indent(line, 1) + "\n"
354
+ if anchor is not None:
355
+ lines[anchor.lineno - 1 : anchor.lineno - 1] = [text]
356
+ return _join(lines)
357
+ last = fields[-1] if fields else _last_attribute(cls)
358
+ lines[last.end_lineno : last.end_lineno] = [text]
359
+ return _join(lines)
360
+
361
+
362
+ def add_call_argument(source: str, variable: str, argument: str) -> str:
363
+ """Add an argument at the end of the call assigned to a module variable
364
+ (``orders_table = Table(...)``)."""
365
+ tree = ast.parse(source)
366
+ for node in tree.body:
367
+ if (
368
+ isinstance(node, ast.Assign)
369
+ and any(isinstance(t, ast.Name) and t.id == variable for t in node.targets)
370
+ and isinstance(node.value, ast.Call)
371
+ ):
372
+ call = node.value
373
+ lines = _lines(source)
374
+ closing = call.end_lineno - 1 # type: ignore[operator]
375
+ if call.end_lineno == call.lineno or lines[closing].strip()[:1] != ")":
376
+ raise EditError(f"{variable} must be a call laid out on several lines")
377
+ arguments = [*call.args, *(k.value for k in call.keywords)]
378
+ if arguments:
379
+ last = arguments[-1]
380
+ row = last.end_lineno - 1 # type: ignore[operator]
381
+ text = lines[row]
382
+ col = last.end_col_offset
383
+ if not text[col:].lstrip().startswith(","):
384
+ lines[row] = text[:col] + "," + text[col:]
385
+ lines[closing:closing] = [_indent(argument, 1) + ",\n"]
386
+ return _join(lines)
387
+ raise EditError(f"No call assigned to {variable}")
388
+
389
+
390
+ # ------------------------------------------------------------- module level
391
+
392
+
393
+ def module_variable(source: str, name: str) -> ast.Assign | ast.AnnAssign | None:
394
+ """The assignment of a module-level variable, if any."""
395
+ tree = ast.parse(source)
396
+ for node in tree.body:
397
+ if isinstance(node, ast.Assign) and any(
398
+ isinstance(t, ast.Name) and t.id == name for t in node.targets
399
+ ):
400
+ return node
401
+ if (
402
+ isinstance(node, ast.AnnAssign)
403
+ and isinstance(node.target, ast.Name)
404
+ and node.target.id == name
405
+ ):
406
+ return node
407
+ return None
408
+
409
+
410
+ def append_to_module_list(source: str, name: str, item: str) -> str:
411
+ """Add an item to a module-level list literal."""
412
+ node = module_variable(source, name)
413
+ if node is None or not isinstance(node.value, ast.List):
414
+ raise EditError(f"{name} is not a list literal")
415
+ return _container_insert(source, node.value, item, 0)
416
+
417
+
418
+ def defines(source: str, name: str) -> bool:
419
+ """Whether the module defines a top-level class or function ``name``."""
420
+ tree = ast.parse(source)
421
+ return any(
422
+ isinstance(n, ast.ClassDef | ast.FunctionDef | ast.AsyncFunctionDef) and n.name == name
423
+ for n in tree.body
424
+ )
@@ -0,0 +1,59 @@
1
+ """``check`` RE-C007: an ``EmailRequested`` names a template set the
2
+ application's renderer doesn't have.
3
+
4
+ The renderer is ``[tool.resource-engine] templates = "pkg.module:templates"``.
5
+ Each ``EmailRequested(template="...")`` with a literal name (found by
6
+ ``resource_engine_devtools.emails``) needs a subject and a text or html body,
7
+ for its literal ``locale`` or, without one, unlocalised. Requests built with a
8
+ computed name can't be checked here.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import Any
14
+
15
+ from resource_engine import ResourceRegistry
16
+
17
+ from resource_engine_devtools.check import Violation
18
+ from resource_engine_devtools.emails import find_email_requests
19
+
20
+
21
+ def check_templates(
22
+ registry: ResourceRegistry, renderer: Any, *, prefix: str = "email/"
23
+ ) -> list[Violation]:
24
+ """RE-C007: requested emails whose subject or body template is missing."""
25
+ violations: list[Violation] = []
26
+ seen: set[tuple[str, int]] = set()
27
+ for use in find_email_requests(registry):
28
+ if use.template is None or (use.path, use.line) in seen:
29
+ continue
30
+ seen.add((use.path, use.line))
31
+ missing = missing_template(renderer, prefix, use.template, use.locale)
32
+ if missing:
33
+ violations.append(
34
+ Violation(
35
+ code="RE-C007",
36
+ path=use.path,
37
+ line=use.line,
38
+ message=f"{use.resource} {use.point} requests the email {use.template!r}"
39
+ + (f" in {use.locale!r}" if use.locale else "")
40
+ + f", but the templates lack {missing}",
41
+ hint=f"Add {prefix}{use.template}.subject.txt and "
42
+ f"{prefix}{use.template}.txt or .html to the templates folder.",
43
+ )
44
+ )
45
+ return violations
46
+
47
+
48
+ def missing_template(renderer: Any, prefix: str, template: str, locale: str | None) -> str | None:
49
+ """The first missing template of an email (subject, text or HTML body), if any."""
50
+ base = f"{prefix}{template}"
51
+ subject = f"{base}.subject.txt"
52
+ if not renderer.exists(subject, locale=locale):
53
+ return subject
54
+ if not (
55
+ renderer.exists(f"{base}.txt", locale=locale)
56
+ or renderer.exists(f"{base}.html", locale=locale)
57
+ ):
58
+ return f"{base}.txt or {base}.html"
59
+ return None
@@ -0,0 +1,68 @@
1
+ """``resource-engine worker``: run the application's ``JobRunner``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import asyncio
7
+ import contextlib
8
+ import importlib
9
+ import inspect
10
+ import signal
11
+ import sys
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from resource_engine.jobs import JobRunner
16
+ from resource_engine.logs import configure_logging
17
+
18
+ from resource_engine_devtools.loader import add_paths, find_config
19
+
20
+
21
+ def load_runner(spec: str | None, cwd: Path) -> Any:
22
+ """``module:attribute``: a ``JobRunner``, or a callable (sync or async)
23
+ returning one. Defaults to ``[tool.resource-engine] worker``."""
24
+ config = find_config(cwd)
25
+ add_paths(config, cwd)
26
+ spec = spec or config.get("worker")
27
+ if not spec:
28
+ raise SystemExit(
29
+ "No worker given. Pass --runner module:attribute or set "
30
+ '[tool.resource-engine] worker = "pkg.worker:runner" in pyproject.toml'
31
+ )
32
+ module_name, _, attr = str(spec).partition(":")
33
+ return getattr(importlib.import_module(module_name), attr or "runner")
34
+
35
+
36
+ async def _resolve(target: Any) -> JobRunner:
37
+ runner = target
38
+ if not isinstance(runner, JobRunner) and callable(runner):
39
+ runner = runner()
40
+ if inspect.isawaitable(runner):
41
+ runner = await runner
42
+ if not isinstance(runner, JobRunner):
43
+ raise SystemExit(f"The worker target is not a JobRunner: {type(runner).__name__}")
44
+ return runner
45
+
46
+
47
+ async def _run(args: argparse.Namespace) -> int:
48
+ runner = await _resolve(load_runner(args.runner, Path.cwd()))
49
+ if args.once:
50
+ runs = await runner.run_once()
51
+ for run in runs:
52
+ print(f"{run.job}: {run.outcome} ({run.seconds:.2f} s)")
53
+ return 1 if any(r.outcome == "failed" for r in runs) else 0
54
+ stop = asyncio.Event()
55
+ loop = asyncio.get_running_loop()
56
+ for sig in (signal.SIGINT, signal.SIGTERM):
57
+ with contextlib.suppress(NotImplementedError): # Windows
58
+ loop.add_signal_handler(sig, stop.set)
59
+ await runner.run_forever(stop)
60
+ return 0
61
+
62
+
63
+ def cmd_worker(args: argparse.Namespace) -> int:
64
+ """``resource-engine worker``: run the application's jobs, consumers and timers."""
65
+ configure_logging(
66
+ format=getattr(args, "log_format", "text"), level=args.log_level, stream=sys.stderr
67
+ )
68
+ return asyncio.run(_run(args))
@@ -0,0 +1,38 @@
1
+ Metadata-Version: 2.5
2
+ Name: resource-engine-devtools
3
+ Version: 0.1.0
4
+ Summary: Functional documentation, inspection and verification CLI for Resource Engine.
5
+ Project-URL: Homepage, https://github.com/EloiSans/python-resource-engine
6
+ Project-URL: Documentation, https://github.com/EloiSans/python-resource-engine/tree/main/docs
7
+ Project-URL: Source, https://github.com/EloiSans/python-resource-engine/tree/main/packages/resource-engine-devtools
8
+ Project-URL: Issues, https://github.com/EloiSans/python-resource-engine/issues
9
+ Project-URL: Changelog, https://github.com/EloiSans/python-resource-engine/blob/main/packages/resource-engine-devtools/CHANGELOG.md
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Framework :: AsyncIO
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.12
23
+ Requires-Dist: babel>=2.14
24
+ Requires-Dist: docstring-parser>=0.16
25
+ Requires-Dist: markdown-it-py>=3.0
26
+ Requires-Dist: resource-engine<0.2,>=0.1.0
27
+ Provides-Extra: mcp
28
+ Requires-Dist: mcp<3,>=2.3; extra == 'mcp'
29
+ Description-Content-Type: text/markdown
30
+
31
+ # resource-engine-devtools
32
+
33
+ Developer tooling for Resource Engine: the `resource-engine` CLI (`inspect`,
34
+ `check`, `docs generate` / `validate`, `ai context` / `install` / `sync`,
35
+ `scaffold`, `worker`) and the AI skill for coding agents
36
+ ([docs/ai.md](../../docs/ai.md)).
37
+
38
+ Part of [Resource Engine](../../README.md).