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,685 @@
1
+ """``resource-engine mcp``: the development CLI as MCP tools for coding agents.
2
+
3
+ ```json
4
+ {"mcpServers": {"resource-engine": {"command": "uv", "args": ["run", "resource-engine", "mcp"]}}}
5
+ ```
6
+
7
+ - **Tools:** the project catalogue, ``inspect``, ``check``, ``docs validate``,
8
+ the AsyncAPI document and its compatibility check, ``explain_error`` and the
9
+ scaffold commands.
10
+ - **Fresh runs:** each project tool runs the CLI with ``--json`` in a new
11
+ process in the project directory, so it sees the code as it is now (agents
12
+ edit it between calls), and nothing the application prints can corrupt the
13
+ stdio protocol.
14
+ - **Resources:** the AI skill's guides (``resource-engine://skill/...``) and the
15
+ project catalogue.
16
+
17
+ Needs the ``mcp`` extra: ``pip install 'resource-engine-devtools[mcp]'``.
18
+ See docs/ai.md#mcp-server.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import asyncio
24
+ import json
25
+ import re
26
+ import sys
27
+ from collections.abc import Awaitable, Callable, Mapping
28
+ from dataclasses import dataclass
29
+ from pathlib import Path
30
+ from typing import Any
31
+
32
+ SKILL_DIR = Path(__file__).parent / "ai" / "skill"
33
+ TIMEOUT = 180.0
34
+ MAX_OUTPUT = 200_000
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class DevTool:
39
+ """A development tool the MCP server offers."""
40
+
41
+ name: str
42
+ title: str
43
+ description: str
44
+ input_schema: dict[str, Any]
45
+ run: Callable[[DevServer, dict[str, Any]], Awaitable[dict[str, Any]]]
46
+ read_only: bool = True
47
+
48
+
49
+ def _schema(properties: dict[str, Any], required: list[str] | None = None) -> dict[str, Any]:
50
+ schema: dict[str, Any] = {
51
+ "type": "object",
52
+ "properties": properties,
53
+ "additionalProperties": False,
54
+ }
55
+ if required:
56
+ schema["required"] = required
57
+ return schema
58
+
59
+
60
+ _STRINGS = {"type": "array", "items": {"type": "string"}}
61
+ _DRY = {"type": "boolean", "default": False, "description": "Show what would be written only"}
62
+ _PACKAGE = {"type": "string", "description": "Dotted package of the module (shop.orders)"}
63
+ _ROOT = {
64
+ "type": "string",
65
+ "description": "Directory the package lives in (default: first pyproject path)",
66
+ }
67
+
68
+
69
+ class DevServer:
70
+ """The development MCP server for the project in ``project``."""
71
+
72
+ def __init__(self, project: Path | None = None, *, python: str | None = None) -> None:
73
+ self.project = (project or Path.cwd()).resolve()
74
+ self.python = python or sys.executable
75
+ self.tools = {t.name: t for t in TOOLS}
76
+
77
+ # ------------------------------------------------------------ running
78
+
79
+ async def cli(self, *argv: str) -> dict[str, Any]:
80
+ """Run ``resource-engine <argv>`` in a fresh process; its exit code and
81
+ output (parsed JSON when it is JSON)."""
82
+ process = await asyncio.create_subprocess_exec(
83
+ self.python,
84
+ "-m",
85
+ "resource_engine_devtools.cli",
86
+ *argv,
87
+ cwd=self.project,
88
+ stdout=asyncio.subprocess.PIPE,
89
+ stderr=asyncio.subprocess.PIPE,
90
+ )
91
+ try:
92
+ out, err = await asyncio.wait_for(process.communicate(), TIMEOUT)
93
+ except TimeoutError:
94
+ process.kill()
95
+ await process.wait()
96
+ raise RuntimeError(
97
+ f"resource-engine {' '.join(argv)} took more than {TIMEOUT:.0f} s"
98
+ ) from None
99
+ text = out.decode("utf-8", "replace")[:MAX_OUTPUT]
100
+ try:
101
+ output: Any = json.loads(text)
102
+ except ValueError:
103
+ output = text
104
+ result: dict[str, Any] = {"exit_code": process.returncode, "output": output}
105
+ errors = err.decode("utf-8", "replace").strip()
106
+ if errors:
107
+ result["stderr"] = errors[-4000:]
108
+ return result
109
+
110
+ # ------------------------------------------------------------------ mcp
111
+
112
+ def build(self) -> Any:
113
+ """The MCP server, with the tools and resources registered."""
114
+ import mcp_types as types
115
+ from mcp.server import Server
116
+
117
+ async def list_tools(ctx: Any, params: Any) -> Any:
118
+ return types.ListToolsResult(tools=[self._tool(t) for t in self.tools.values()])
119
+
120
+ async def call_tool(ctx: Any, params: Any) -> Any:
121
+ return await self.call(params.name, params.arguments or {})
122
+
123
+ async def list_resources(ctx: Any, params: Any) -> Any:
124
+ return types.ListResourcesResult(resources=self.resources())
125
+
126
+ async def read_resource(ctx: Any, params: Any) -> Any:
127
+ from mcp.shared.exceptions import MCPError
128
+
129
+ uri = str(params.uri)
130
+ try:
131
+ text, mime = await self.read(uri)
132
+ except ValueError as exc:
133
+ raise MCPError(types.INVALID_PARAMS, str(exc)) from None
134
+ return types.ReadResourceResult(
135
+ contents=[types.TextResourceContents(uri=uri, text=text, mime_type=mime)]
136
+ )
137
+
138
+ return Server(
139
+ "resource-engine-dev",
140
+ instructions=INSTRUCTIONS,
141
+ on_list_tools=list_tools,
142
+ on_call_tool=call_tool,
143
+ on_list_resources=list_resources,
144
+ on_read_resource=read_resource,
145
+ )
146
+
147
+ @staticmethod
148
+ def _tool(tool: DevTool) -> Any:
149
+ import mcp_types as types
150
+
151
+ return types.Tool(
152
+ name=tool.name,
153
+ title=tool.title,
154
+ description=tool.description,
155
+ input_schema=tool.input_schema,
156
+ annotations=types.ToolAnnotations(
157
+ title=tool.title,
158
+ read_only_hint=tool.read_only,
159
+ destructive_hint=False,
160
+ idempotent_hint=tool.read_only,
161
+ open_world_hint=False,
162
+ ),
163
+ )
164
+
165
+ async def call(self, name: str, arguments: Mapping[str, Any]) -> Any:
166
+ """Run the tool ``name`` with ``arguments``; returns its result as MCP content."""
167
+ import mcp_types as types
168
+
169
+ tool = self.tools.get(name)
170
+ if tool is None:
171
+ return _error(f"Unknown tool {name!r}")
172
+ unknown = set(arguments) - set(tool.input_schema["properties"])
173
+ missing = set(tool.input_schema.get("required", ())) - set(arguments)
174
+ if unknown or missing:
175
+ return _error(
176
+ f"Bad arguments for {name}: "
177
+ + "; ".join(
178
+ part
179
+ for part in (
180
+ unknown and f"unknown {sorted(unknown)}",
181
+ missing and f"missing {sorted(missing)}",
182
+ )
183
+ if part
184
+ )
185
+ )
186
+ try:
187
+ result = await tool.run(self, dict(arguments))
188
+ except Exception as exc: # the tool's own failure, shown to the agent
189
+ return _error(f"{type(exc).__name__}: {exc}")
190
+ failed = result.get("exit_code") not in (0, 1, None) or (
191
+ "stderr" in result and not result.get("output")
192
+ )
193
+ text = json.dumps(result, indent=2, ensure_ascii=False, default=str)
194
+ return types.CallToolResult(
195
+ content=[types.TextContent(text=text)], structured_content=result, is_error=failed
196
+ )
197
+
198
+ def resources(self) -> list[Any]:
199
+ """The resources the server offers."""
200
+ import mcp_types as types
201
+
202
+ items = [
203
+ types.Resource(
204
+ uri="resource-engine://project",
205
+ name="project",
206
+ title="Project catalogue",
207
+ description="This project's resources, operations, transitions, actions, "
208
+ "events, references and permissions (generated now).",
209
+ mime_type="text/markdown",
210
+ )
211
+ ]
212
+ for path in sorted(SKILL_DIR.rglob("*.md")):
213
+ relative = path.relative_to(SKILL_DIR).as_posix()
214
+ if relative.startswith("examples/"):
215
+ continue
216
+ first = path.read_text(encoding="utf-8").lstrip().splitlines()[:1]
217
+ items.append(
218
+ types.Resource(
219
+ uri=f"resource-engine://skill/{relative}",
220
+ name=relative,
221
+ title=(first[0].lstrip("# ").strip() if first else relative),
222
+ mime_type="text/markdown",
223
+ )
224
+ )
225
+ return items
226
+
227
+ async def read(self, uri: str) -> tuple[str, str]:
228
+ """The text and MIME type of the resource at ``uri``."""
229
+ if uri == "resource-engine://project":
230
+ result = await self.cli("ai", "context")
231
+ output = result["output"]
232
+ return (output if isinstance(output, str) else json.dumps(output)), "text/markdown"
233
+ prefix = "resource-engine://skill/"
234
+ if uri.startswith(prefix):
235
+ path = (SKILL_DIR / uri[len(prefix) :]).resolve()
236
+ if SKILL_DIR.resolve() in path.parents and path.is_file():
237
+ return path.read_text(encoding="utf-8"), "text/markdown"
238
+ raise ValueError(f"Unknown resource {uri!r}")
239
+
240
+ async def run_stdio(self) -> None:
241
+ """Serve over standard input and output until the client leaves."""
242
+ from mcp.server.stdio import stdio_server
243
+
244
+ server = self.build()
245
+ async with stdio_server() as (read, write):
246
+ await server.run(read, write, server.create_initialization_options())
247
+
248
+
249
+ def _error(message: str) -> Any:
250
+ import mcp_types as types
251
+
252
+ return types.CallToolResult(content=[types.TextContent(text=message)], is_error=True)
253
+
254
+
255
+ # ------------------------------------------------------------------- tools
256
+
257
+
258
+ async def _catalogue(server: DevServer, args: dict[str, Any]) -> dict[str, Any]:
259
+ return await server.cli("ai", "context")
260
+
261
+
262
+ async def _inspect(server: DevServer, args: dict[str, Any]) -> dict[str, Any]:
263
+ return await server.cli(
264
+ "inspect", "--json", *([args["resource"]] if args.get("resource") else [])
265
+ )
266
+
267
+
268
+ async def _check(server: DevServer, args: dict[str, Any]) -> dict[str, Any]:
269
+ return await server.cli("check", "--json", *args.get("paths", []))
270
+
271
+
272
+ async def _docs_validate(server: DevServer, args: dict[str, Any]) -> dict[str, Any]:
273
+ argv = ["docs", "validate", "--json"]
274
+ if args.get("strict", True):
275
+ argv.append("--strict")
276
+ result = await server.cli(*argv)
277
+ output = result.get("output")
278
+ if isinstance(output, dict) and not args.get("verbose"):
279
+ output["findings"] = [f for f in output.get("findings", []) if f.get("level") != "ok"]
280
+ return result
281
+
282
+
283
+ async def _asyncapi(server: DevServer, args: dict[str, Any]) -> dict[str, Any]:
284
+ if args.get("check_against"):
285
+ return await server.cli("docs", "asyncapi", "--json", "--check", args["check_against"])
286
+ return await server.cli("docs", "asyncapi")
287
+
288
+
289
+ async def _explain(server: DevServer, args: dict[str, Any]) -> dict[str, Any]:
290
+ return explain_error(args["code"])
291
+
292
+
293
+ def _scaffold_tail(args: dict[str, Any]) -> list[str]:
294
+ argv = ["--json", "--package", args["package"]]
295
+ if args.get("root"):
296
+ argv += ["--root", args["root"]]
297
+ if args.get("dry_run"):
298
+ argv.append("--dry-run")
299
+ return argv
300
+
301
+
302
+ async def _scaffold_resource(server: DevServer, args: dict[str, Any]) -> dict[str, Any]:
303
+ argv = ["scaffold", "resource", args["name"], *_scaffold_tail(args)]
304
+ for value in args.get("fields", []):
305
+ argv += ["--field", value]
306
+ for key in ("entity", "states", "transitions"):
307
+ if args.get(key):
308
+ argv += [f"--{key}", args[key]]
309
+ if args.get("state_machine"):
310
+ argv.append("--state-machine")
311
+ if args.get("versioned"):
312
+ argv.append("--versioned")
313
+ return await server.cli(*argv)
314
+
315
+
316
+ async def _scaffold_action(server: DevServer, args: dict[str, Any]) -> dict[str, Any]:
317
+ argv = ["scaffold", "action", args["resource"], args["action_class"], *_scaffold_tail(args)]
318
+ for value in args.get("inputs", []):
319
+ argv += ["--input", value]
320
+ if args.get("collection"):
321
+ argv.append("--collection")
322
+ return await server.cli(*argv)
323
+
324
+
325
+ async def _scaffold_state_machine(server: DevServer, args: dict[str, Any]) -> dict[str, Any]:
326
+ argv = ["scaffold", "state-machine", args["entity"], *_scaffold_tail(args)]
327
+ for key in ("states", "transitions"):
328
+ if args.get(key):
329
+ argv += [f"--{key}", args[key]]
330
+ return await server.cli(*argv)
331
+
332
+
333
+ async def _scaffold_consumer(server: DevServer, args: dict[str, Any]) -> dict[str, Any]:
334
+ argv = ["scaffold", "consumer", args["name"], "--asyncapi", args["asyncapi"]]
335
+ argv += _scaffold_tail(args)
336
+ for value in args.get("channels", []):
337
+ argv += ["--channel", value]
338
+ for value in args.get("messages", []):
339
+ argv += ["--message", value]
340
+ if args.get("type_prefix"):
341
+ argv += ["--type-prefix", args["type_prefix"]]
342
+ return await server.cli(*argv)
343
+
344
+
345
+ def _flags(args: dict[str, Any], spec: dict[str, str]) -> list[str]:
346
+ """MCP arguments → CLI options: ``spec`` maps each argument to its option;
347
+ booleans become flags, lists repeat the option."""
348
+ argv: list[str] = []
349
+ for key, option in spec.items():
350
+ value = args.get(key)
351
+ if value is None or value is False:
352
+ continue
353
+ if value is True:
354
+ argv.append(option)
355
+ elif isinstance(value, list):
356
+ for item in value:
357
+ argv += [option, str(item)]
358
+ else:
359
+ argv += [option, str(value)]
360
+ return argv
361
+
362
+
363
+ def _part(command: str, positional: list[str], spec: dict[str, str]): # type: ignore[no-untyped-def]
364
+ async def run(server: DevServer, args: dict[str, Any]) -> dict[str, Any]:
365
+ argv = ["scaffold", command, *(args[p] for p in positional), *_scaffold_tail(args)]
366
+ return await server.cli(*argv, *_flags(args, spec))
367
+
368
+ return run
369
+
370
+
371
+ def _part_tool(
372
+ name: str, title: str, description: str, positional: dict[str, Any], options: dict[str, Any],
373
+ spec: dict[str, str], required: list[str] | None = None,
374
+ ) -> DevTool: # fmt: skip
375
+ command = name.removeprefix("scaffold_")
376
+ return DevTool(
377
+ name,
378
+ title,
379
+ description + " Edits the resource class to declare it; never overwrites a name "
380
+ "that exists. Follow the next_steps it returns.",
381
+ _schema(
382
+ {**positional, "package": _PACKAGE, **options, "root": _ROOT, "dry_run": _DRY},
383
+ [*positional, "package", *(required or [])],
384
+ ),
385
+ _part(command, list(positional), spec),
386
+ read_only=False,
387
+ )
388
+
389
+
390
+ _RESOURCE = {"type": "string", "description": "Resource name (orders)"}
391
+
392
+ TOOLS = [
393
+ DevTool(
394
+ "project_catalogue",
395
+ "Project catalogue",
396
+ "This project's resources with their operations, transitions, actions, events, "
397
+ "references, documents and permissions, as Markdown. Read it before changing a "
398
+ "resource.",
399
+ _schema({}),
400
+ _catalogue,
401
+ ),
402
+ DevTool(
403
+ "inspect",
404
+ "Inspect resources",
405
+ "The resolved definitions of the registered resources (schemas, hooks in "
406
+ "lifecycle order, state machine, actions, permissions), as JSON.",
407
+ _schema({"resource": {"type": "string", "description": "Only this resource"}}),
408
+ _inspect,
409
+ ),
410
+ DevTool(
411
+ "check",
412
+ "Check architecture",
413
+ "resource-engine check: domain imports (RE-C001), effects inside the transaction "
414
+ "(RE-C002), after_commit misuse (RE-C003), operations only admin can perform "
415
+ "(RE-C004), declarations the engine refuses (RE-C005), undeclared events (RE-C006), "
416
+ "missing email templates (RE-C007), behaviour or bulk in a declaration (RE-C008), "
417
+ "hooks writing other resources (RE-C009). "
418
+ "Run it after every change; output.passed tells whether it is clean.",
419
+ _schema({"paths": {**_STRINGS, "description": "Directories to lint (default: .)"}}),
420
+ _check,
421
+ ),
422
+ DevTool(
423
+ "docs_validate",
424
+ "Validate documentation",
425
+ "resource-engine docs validate: missing docstrings and functional sections "
426
+ "(RE-D001..RE-D011). Strict by default, like CI.",
427
+ _schema(
428
+ {
429
+ "strict": {"type": "boolean", "default": True},
430
+ "verbose": {"type": "boolean", "default": False, "description": "Include passes"},
431
+ }
432
+ ),
433
+ _docs_validate,
434
+ ),
435
+ DevTool(
436
+ "asyncapi",
437
+ "AsyncAPI document",
438
+ "The AsyncAPI 3.0 document of the events the app publishes and consumes. With "
439
+ "check_against (the published file), the changes that would break consumers "
440
+ "(exit_code 1 when there are some).",
441
+ _schema({"check_against": {"type": "string", "description": "Published asyncapi.json"}}),
442
+ _asyncapi,
443
+ ),
444
+ DevTool(
445
+ "explain_error",
446
+ "Explain an error code",
447
+ "What an RE-E (runtime), RE-C (check) or RE-D (docs) code means and what to change.",
448
+ _schema({"code": {"type": "string", "pattern": "^RE-[ECD]\\d{3}$"}}, ["code"]),
449
+ _explain,
450
+ ),
451
+ DevTool(
452
+ "scaffold_resource",
453
+ "Scaffold a module",
454
+ "A new module with one resource (domain, schemas, hooks, resource, persistence, "
455
+ "tests), laid out like the reference module. Never overwrites files. Follow the "
456
+ "next_steps it returns.",
457
+ _schema(
458
+ {
459
+ "name": {"type": "string", "description": "Plural snake_case (orders)"},
460
+ "package": _PACKAGE,
461
+ "fields": {
462
+ **_STRINGS,
463
+ "description": "name:type[?] with type in str text int bool Decimal date "
464
+ "datetime; ? for optional",
465
+ },
466
+ "entity": {"type": "string"},
467
+ "state_machine": {"type": "boolean"},
468
+ "states": {"type": "string", "description": "draft,placed,shipped"},
469
+ "transitions": {"type": "string", "description": "place:draft>placed,..."},
470
+ "versioned": {"type": "boolean"},
471
+ "root": _ROOT,
472
+ "dry_run": _DRY,
473
+ },
474
+ ["name", "package"],
475
+ ),
476
+ _scaffold_resource,
477
+ read_only=False,
478
+ ),
479
+ DevTool(
480
+ "scaffold_action",
481
+ "Scaffold an action",
482
+ "An Action class (and its input schema) in an existing module.",
483
+ _schema(
484
+ {
485
+ "resource": {"type": "string"},
486
+ "action_class": {"type": "string", "description": "PascalCase (ApplyDiscount)"},
487
+ "package": _PACKAGE,
488
+ "inputs": {**_STRINGS, "description": "Input fields name:type[?]"},
489
+ "collection": {"type": "boolean", "description": "Not tied to one record"},
490
+ "root": _ROOT,
491
+ "dry_run": _DRY,
492
+ },
493
+ ["resource", "action_class", "package"],
494
+ ),
495
+ _scaffold_action,
496
+ read_only=False,
497
+ ),
498
+ DevTool(
499
+ "scaffold_state_machine",
500
+ "Scaffold a state machine",
501
+ "A python-statemachine class in an existing module.",
502
+ _schema(
503
+ {
504
+ "entity": {"type": "string", "description": "Entity class (Order)"},
505
+ "package": _PACKAGE,
506
+ "states": {"type": "string"},
507
+ "transitions": {"type": "string"},
508
+ "root": _ROOT,
509
+ "dry_run": _DRY,
510
+ },
511
+ ["entity", "package"],
512
+ ),
513
+ _scaffold_state_machine,
514
+ read_only=False,
515
+ ),
516
+ DevTool(
517
+ "scaffold_consumer",
518
+ "Scaffold a consumer",
519
+ "From another service's AsyncAPI document: payload models, an EventRouter with "
520
+ "typed handler stubs, a contract snapshot and contract tests.",
521
+ _schema(
522
+ {
523
+ "name": {"type": "string", "description": "snake_case (payments)"},
524
+ "package": _PACKAGE,
525
+ "asyncapi": {"type": "string", "description": "Path to the provider's document"},
526
+ "channels": _STRINGS,
527
+ "messages": _STRINGS,
528
+ "type_prefix": {"type": "string"},
529
+ "root": _ROOT,
530
+ "dry_run": _DRY,
531
+ },
532
+ ["name", "package", "asyncapi"],
533
+ ),
534
+ _scaffold_consumer,
535
+ read_only=False,
536
+ ),
537
+ _part_tool(
538
+ "scaffold_hook",
539
+ "Scaffold a hook",
540
+ "A hook function in application/hooks.py, registered at the given points.",
541
+ {"resource": _RESOURCE, "function": {"type": "string", "description": "snake_case"}},
542
+ {
543
+ "on": {
544
+ **_STRINGS,
545
+ "description": "Hook points: before_create, after_update, "
546
+ "before_transition:place, after_commit...",
547
+ },
548
+ "effect": {"type": "boolean", "description": "External effect (after_commit only)"},
549
+ },
550
+ {"on": "--on", "effect": "--effect"},
551
+ ["on"],
552
+ ),
553
+ _part_tool(
554
+ "scaffold_event",
555
+ "Scaffold a domain event",
556
+ "A DomainEvent in domain/events.py, declared in the resource's events.",
557
+ {
558
+ "resource": _RESOURCE,
559
+ "event_class": {"type": "string", "description": "PascalCase, past tense"},
560
+ },
561
+ {"fields": {**_STRINGS, "description": "Payload fields name:type[?]"}},
562
+ {"fields": "--field"},
563
+ ),
564
+ _part_tool(
565
+ "scaffold_slot",
566
+ "Scaffold a document slot",
567
+ "A DocumentSlot in the resource's documents.",
568
+ {"resource": _RESOURCE, "slot": {"type": "string", "description": "snake_case"}},
569
+ {
570
+ "content_types": _STRINGS,
571
+ "max_mb": {"type": "integer", "minimum": 1},
572
+ "multiple": {"type": "boolean"},
573
+ "upload": {"type": "string", "enum": ["api", "presigned", "any"]},
574
+ "required_for": {**_STRINGS, "description": "Transitions that need a document"},
575
+ "processing": {"type": "boolean"},
576
+ },
577
+ {
578
+ "content_types": "--content-type",
579
+ "max_mb": "--max-mb",
580
+ "multiple": "--multiple",
581
+ "upload": "--upload",
582
+ "required_for": "--required-for",
583
+ "processing": "--processing",
584
+ },
585
+ ),
586
+ _part_tool(
587
+ "scaffold_reference",
588
+ "Scaffold a reference",
589
+ "A Reference to another resource; adds the id field to the entity, schemas and "
590
+ "table when they lack it.",
591
+ {"resource": _RESOURCE, "field": {"type": "string", "description": "customer_id"}},
592
+ {
593
+ "to": {"type": "string", "description": "The referenced resource"},
594
+ "relation": {"type": "string"},
595
+ "on_delete": {"type": "string", "enum": ["restrict", "set_null", "cascade"]},
596
+ "required": {"type": "boolean"},
597
+ "related_name": {"type": "string"},
598
+ },
599
+ {
600
+ "to": "--to",
601
+ "relation": "--relation",
602
+ "on_delete": "--on-delete",
603
+ "required": "--required",
604
+ "related_name": "--related-name",
605
+ },
606
+ ["to"],
607
+ ),
608
+ _part_tool(
609
+ "scaffold_policy",
610
+ "Scaffold a seed policy",
611
+ "A policy granting a role the resource's operations (or only reads), appended to "
612
+ "<package>/authz.py.",
613
+ {"resource": _RESOURCE},
614
+ {
615
+ "role": {"type": "string"},
616
+ "read_only": {"type": "boolean"},
617
+ "name": {"type": "string"},
618
+ "variable": {"type": "string", "description": "List to append to (SEED_POLICIES)"},
619
+ },
620
+ {"role": "--role", "read_only": "--read-only", "name": "--name", "variable": "--variable"},
621
+ ["role"],
622
+ ),
623
+ ]
624
+
625
+ INSTRUCTIONS = """\
626
+ Development tools for a Resource Engine project. Read the project catalogue
627
+ (project_catalogue, or the resource-engine://project resource) and the skill
628
+ guides (resource-engine://skill/...) before changing resources. After each
629
+ change run check and docs_validate and fix what they report (explain_error
630
+ tells what a code means). Use the scaffold tools for new modules, actions,
631
+ state machines and consumers instead of writing the boilerplate by hand."""
632
+
633
+
634
+ # ------------------------------------------------------------------ errors
635
+
636
+ _ROW = re.compile(r"^\|\s*(?:<a id=\"[^\"]+\"></a>)?(RE-[ECD][\d…]+(?:…[ECD]?\d+)?)\s*\|(.*)$")
637
+
638
+
639
+ def explain_error(code: str) -> dict[str, Any]:
640
+ """The catalogue entry for ``code`` (skill references) and, for runtime
641
+ codes, the engine's error class and its description."""
642
+ code = code.strip().upper()
643
+ found: dict[str, Any] = {"code": code}
644
+ rows = []
645
+ for name in ("errors.md", "docstrings.md"):
646
+ text = (SKILL_DIR / "references" / name).read_text(encoding="utf-8")
647
+ for line in text.splitlines():
648
+ match = _ROW.match(line)
649
+ if match and _covers(match.group(1), code):
650
+ cells = [c.strip() for c in match.group(2).strip().strip("|").split("|")]
651
+ rows.append(" | ".join(c for c in cells if c))
652
+ if rows:
653
+ found["catalogue"] = rows
654
+ if code.startswith("RE-E"):
655
+ from resource_engine import errors
656
+
657
+ for value in vars(errors).values():
658
+ if isinstance(value, type) and getattr(value, "code", None) == code:
659
+ found["error_class"] = f"resource_engine.errors.{value.__name__}"
660
+ if value.__doc__:
661
+ found["description"] = " ".join(value.__doc__.split())
662
+ break
663
+ found["doc"] = f"docs/errors.md#{code.lower()}"
664
+ if len(found) == 2:
665
+ raise ValueError(f"No error {code} in the catalogue")
666
+ return found
667
+
668
+
669
+ def _covers(label: str, code: str) -> bool:
670
+ """``RE-D001…D011`` covers ``RE-D005``."""
671
+ if "…" not in label:
672
+ return label == code
673
+ start, _, end = label.partition("…")
674
+ prefix = start[:4]
675
+ if not code.startswith(prefix):
676
+ return False
677
+ try:
678
+ low = int(start[4:])
679
+ high = int(re.sub(r"\D", "", end))
680
+ return low <= int(code[4:]) <= high
681
+ except ValueError:
682
+ return False
683
+
684
+
685
+ __all__ = ["TOOLS", "DevServer", "DevTool", "explain_error"]
File without changes