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.
- resource_engine_devtools/__init__.py +6 -0
- resource_engine_devtools/ai/__init__.py +1 -0
- resource_engine_devtools/ai/example.py +66 -0
- resource_engine_devtools/ai/installer.py +424 -0
- resource_engine_devtools/ai/skill/SKILL.md +130 -0
- resource_engine_devtools/ai/skill/examples/README.md +7 -0
- resource_engine_devtools/ai/skill/examples/invoices/__init__.py +0 -0
- resource_engine_devtools/ai/skill/examples/invoices/app.py +245 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/__init__.py +0 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/actions.py +61 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/balances.py +51 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/customers.py +35 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/hooks.py +61 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/processes.py +80 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/resource.py +112 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/schemas.py +164 -0
- resource_engine_devtools/ai/skill/examples/invoices/application/tags.py +77 -0
- resource_engine_devtools/ai/skill/examples/invoices/authz.py +126 -0
- resource_engine_devtools/ai/skill/examples/invoices/bootstrap.py +80 -0
- resource_engine_devtools/ai/skill/examples/invoices/domain/__init__.py +0 -0
- resource_engine_devtools/ai/skill/examples/invoices/domain/entities.py +112 -0
- resource_engine_devtools/ai/skill/examples/invoices/domain/events.py +22 -0
- resource_engine_devtools/ai/skill/examples/invoices/domain/state_machine.py +88 -0
- resource_engine_devtools/ai/skill/examples/invoices/infrastructure/__init__.py +0 -0
- resource_engine_devtools/ai/skill/examples/invoices/infrastructure/persistence.py +121 -0
- resource_engine_devtools/ai/skill/examples/invoices/locale/en/LC_MESSAGES/messages.po +682 -0
- resource_engine_devtools/ai/skill/examples/invoices/locale/es/LC_MESSAGES/messages.po +685 -0
- resource_engine_devtools/ai/skill/examples/invoices/notifications.py +47 -0
- resource_engine_devtools/ai/skill/examples/invoices/templates/email/base.html +7 -0
- resource_engine_devtools/ai/skill/examples/invoices/templates/email/invoice_approved.html +5 -0
- resource_engine_devtools/ai/skill/examples/invoices/templates/email/invoice_approved.subject.txt +1 -0
- resource_engine_devtools/ai/skill/examples/invoices/templates/email/invoice_approved.txt +5 -0
- resource_engine_devtools/ai/skill/examples/invoices/tests/conftest.py +40 -0
- resource_engine_devtools/ai/skill/examples/invoices/tests/test_invoices_engine.py +241 -0
- resource_engine_devtools/ai/skill/examples/invoices/worker.py +53 -0
- resource_engine_devtools/ai/skill/llms.txt +25 -0
- resource_engine_devtools/ai/skill/references/anti-patterns.md +209 -0
- resource_engine_devtools/ai/skill/references/docstrings.md +97 -0
- resource_engine_devtools/ai/skill/references/errors.md +81 -0
- resource_engine_devtools/ai/skill/references/lifecycle.md +118 -0
- resource_engine_devtools/ai/skill/references/permissions.md +111 -0
- resource_engine_devtools/ai/skill/references/resource.md +301 -0
- resource_engine_devtools/ai/skill/references/state-machines.md +126 -0
- resource_engine_devtools/ai/skill/references/testing.md +80 -0
- resource_engine_devtools/ai/templates/agents_block.md +26 -0
- resource_engine_devtools/ai/templates/cursor_rule.mdc +7 -0
- resource_engine_devtools/check.py +67 -0
- resource_engine_devtools/cli.py +1112 -0
- resource_engine_devtools/consumer_scaffold.py +715 -0
- resource_engine_devtools/contracts.py +471 -0
- resource_engine_devtools/db.py +132 -0
- resource_engine_devtools/declarations_check.py +116 -0
- resource_engine_devtools/documentation/__init__.py +10 -0
- resource_engine_devtools/documentation/docstrings.py +72 -0
- resource_engine_devtools/documentation/generators/__init__.py +9 -0
- resource_engine_devtools/documentation/generators/ai_context.py +121 -0
- resource_engine_devtools/documentation/generators/api.py +63 -0
- resource_engine_devtools/documentation/generators/json.py +12 -0
- resource_engine_devtools/documentation/generators/markdown.py +687 -0
- resource_engine_devtools/documentation/generators/mermaid.py +22 -0
- resource_engine_devtools/documentation/generators/site.py +379 -0
- resource_engine_devtools/documentation/generators/site_assets/site.css +62 -0
- resource_engine_devtools/documentation/generators/site_assets/site.js +54 -0
- resource_engine_devtools/documentation/i18n.py +185 -0
- resource_engine_devtools/documentation/introspector.py +563 -0
- resource_engine_devtools/documentation/locale/ca/LC_MESSAGES/docs.po +628 -0
- resource_engine_devtools/documentation/locale/es/LC_MESSAGES/docs.po +627 -0
- resource_engine_devtools/documentation/model.py +311 -0
- resource_engine_devtools/documentation/validator.py +128 -0
- resource_engine_devtools/emails.py +172 -0
- resource_engine_devtools/events_check.py +124 -0
- resource_engine_devtools/gates_check.py +133 -0
- resource_engine_devtools/hooks_check.py +287 -0
- resource_engine_devtools/i18n.py +312 -0
- resource_engine_devtools/loader.py +93 -0
- resource_engine_devtools/logic_check.py +136 -0
- resource_engine_devtools/mcp_server.py +685 -0
- resource_engine_devtools/py.typed +0 -0
- resource_engine_devtools/scaffold.py +805 -0
- resource_engine_devtools/scaffold_parts.py +637 -0
- resource_engine_devtools/source_edit.py +424 -0
- resource_engine_devtools/templates_check.py +59 -0
- resource_engine_devtools/worker.py +68 -0
- resource_engine_devtools-0.1.0.dist-info/METADATA +38 -0
- resource_engine_devtools-0.1.0.dist-info/RECORD +88 -0
- resource_engine_devtools-0.1.0.dist-info/WHEEL +4 -0
- resource_engine_devtools-0.1.0.dist-info/entry_points.txt +2 -0
- resource_engine_devtools-0.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,1112 @@
|
|
|
1
|
+
"""``resource-engine`` command line. Every command accepts ``--json`` for agents and CI."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import TYPE_CHECKING, Any
|
|
10
|
+
|
|
11
|
+
from resource_engine import HookPoint, ResourceRegistry
|
|
12
|
+
|
|
13
|
+
from resource_engine_devtools.check import check_domain_imports
|
|
14
|
+
from resource_engine_devtools.documentation import introspect, validate
|
|
15
|
+
from resource_engine_devtools.documentation.generators import (
|
|
16
|
+
render_ai_context,
|
|
17
|
+
render_json,
|
|
18
|
+
render_markdown,
|
|
19
|
+
)
|
|
20
|
+
from resource_engine_devtools.loader import find_config, load_authz, load_registry
|
|
21
|
+
|
|
22
|
+
if TYPE_CHECKING:
|
|
23
|
+
from resource_engine_devtools.i18n import I18nConfig
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _emit(args: argparse.Namespace, data: Any, text: str) -> None:
|
|
27
|
+
print(json.dumps(data, indent=2, ensure_ascii=False, default=str) if args.json else text)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _registry(args: argparse.Namespace) -> ResourceRegistry:
|
|
31
|
+
return load_registry(args.app, Path.cwd())
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _optional_registry(args: argparse.Namespace) -> ResourceRegistry | None:
|
|
35
|
+
"""The registry when one is configured; hook lints are skipped without it."""
|
|
36
|
+
try:
|
|
37
|
+
return _registry(args)
|
|
38
|
+
except SystemExit:
|
|
39
|
+
if args.app:
|
|
40
|
+
raise
|
|
41
|
+
return None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _describe(registry: ResourceRegistry, name: str | None) -> list[dict[str, Any]]:
|
|
45
|
+
from resource_engine.authz import Catalog
|
|
46
|
+
|
|
47
|
+
out = []
|
|
48
|
+
for d in registry:
|
|
49
|
+
if name and d.name != name:
|
|
50
|
+
continue
|
|
51
|
+
hooks: dict[str, list[str]] = {}
|
|
52
|
+
for point in HookPoint: # contractual order
|
|
53
|
+
for key, fns in d.hooks.items():
|
|
54
|
+
if key.point is point:
|
|
55
|
+
hooks.setdefault(str(key), []).extend(
|
|
56
|
+
f"{fn.__module__}.{fn.__qualname__}" for fn in fns
|
|
57
|
+
)
|
|
58
|
+
out.append(
|
|
59
|
+
{
|
|
60
|
+
"name": d.name,
|
|
61
|
+
"resource": f"{d.resource_cls.__module__}.{d.resource_cls.__qualname__}",
|
|
62
|
+
"model": f"{d.model.__module__}.{d.model.__qualname__}",
|
|
63
|
+
"id": {"field": d.id_field, "type": d.id_type.__name__},
|
|
64
|
+
"operations": list(d.operations),
|
|
65
|
+
"schemas": {role: s.__name__ for role, s in d.schemas.items()},
|
|
66
|
+
"filterable": list(d.filterable),
|
|
67
|
+
"sortable": list(d.sortable),
|
|
68
|
+
"state_machines": [
|
|
69
|
+
{
|
|
70
|
+
"name": m.name,
|
|
71
|
+
"class": m.machine_cls.__qualname__,
|
|
72
|
+
"field": m.state_field,
|
|
73
|
+
"since_field": m.since_field,
|
|
74
|
+
"initial": m.info.initial.id if m.info.initial else None,
|
|
75
|
+
"transitions": [
|
|
76
|
+
{
|
|
77
|
+
"event": t.event,
|
|
78
|
+
"source": t.source,
|
|
79
|
+
"target": t.target,
|
|
80
|
+
"input": getattr(
|
|
81
|
+
d.transition_schemas.get(t.event), "__name__", None
|
|
82
|
+
),
|
|
83
|
+
}
|
|
84
|
+
for t in m.info.transitions
|
|
85
|
+
],
|
|
86
|
+
}
|
|
87
|
+
for m in d.machines.values()
|
|
88
|
+
],
|
|
89
|
+
"actions": [
|
|
90
|
+
{
|
|
91
|
+
"name": a.name,
|
|
92
|
+
"instance": a.instance,
|
|
93
|
+
"input": getattr(a.input_schema, "__name__", None),
|
|
94
|
+
"output": getattr(a.output_schema, "__name__", None),
|
|
95
|
+
}
|
|
96
|
+
for a in d.actions.values()
|
|
97
|
+
],
|
|
98
|
+
"permissions": [
|
|
99
|
+
a.name
|
|
100
|
+
for a in Catalog.from_registry(registry).actions.values()
|
|
101
|
+
if a.resource == d.name and a.kind not in ("read", "write")
|
|
102
|
+
],
|
|
103
|
+
"restricted_fields": list(d.restricted_fields),
|
|
104
|
+
"tenant_field": d.tenant_field,
|
|
105
|
+
"version_field": d.version_field,
|
|
106
|
+
"require_version": d.require_version,
|
|
107
|
+
"audit": {
|
|
108
|
+
"enabled": d.audited,
|
|
109
|
+
"reads": d.audit_reads,
|
|
110
|
+
"exclude": list(d.audit_exclude),
|
|
111
|
+
},
|
|
112
|
+
"documents": [
|
|
113
|
+
{
|
|
114
|
+
"slot": s.name,
|
|
115
|
+
"content_types": list(s.content_types),
|
|
116
|
+
"max_bytes": s.max_bytes,
|
|
117
|
+
"multiple": s.multiple,
|
|
118
|
+
"upload": s.upload,
|
|
119
|
+
"required_for": list(s.required_for),
|
|
120
|
+
"processing": s.processing,
|
|
121
|
+
}
|
|
122
|
+
for s in d.document_slots.values()
|
|
123
|
+
],
|
|
124
|
+
"hooks": hooks,
|
|
125
|
+
}
|
|
126
|
+
)
|
|
127
|
+
if name and not out:
|
|
128
|
+
raise SystemExit(f"Resource {name!r} is not registered")
|
|
129
|
+
return out
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def cmd_inspect(args: argparse.Namespace) -> int:
|
|
133
|
+
"""``resource-engine inspect``: the registered resources, their operations and settings."""
|
|
134
|
+
data = _describe(_registry(args), args.resource)
|
|
135
|
+
lines = []
|
|
136
|
+
for r in data:
|
|
137
|
+
lines.append(f"{r['name']} ({r['resource']})")
|
|
138
|
+
lines.append(f" operations: {', '.join(r['operations']) or '-'}")
|
|
139
|
+
lines.append(f" schemas: {r['schemas']}")
|
|
140
|
+
for sm in r["state_machines"]:
|
|
141
|
+
lines.append(
|
|
142
|
+
f" state: {sm['name']}: {sm['class']} on '{sm['field']}' "
|
|
143
|
+
f"(initial {sm['initial']})"
|
|
144
|
+
)
|
|
145
|
+
for t in sm["transitions"]:
|
|
146
|
+
lines.append(f" {t['source']} --{t['event']}--> {t['target']}")
|
|
147
|
+
for a in r["actions"]:
|
|
148
|
+
lines.append(f" action: {a['name']} (input {a['input']})")
|
|
149
|
+
lines.append(f" permissions: {', '.join(r['permissions'])}")
|
|
150
|
+
if r["tenant_field"]:
|
|
151
|
+
lines.append(f" tenant field: {r['tenant_field']}")
|
|
152
|
+
if r["version_field"]:
|
|
153
|
+
strict = " (required)" if r["require_version"] else ""
|
|
154
|
+
lines.append(f" version field: {r['version_field']}{strict}")
|
|
155
|
+
if r["restricted_fields"]:
|
|
156
|
+
lines.append(f" restricted fields: {', '.join(r['restricted_fields'])}")
|
|
157
|
+
audit = r["audit"]
|
|
158
|
+
if not audit["enabled"] or audit["reads"] or audit["exclude"]:
|
|
159
|
+
parts = ["off"] if not audit["enabled"] else []
|
|
160
|
+
parts += ["reads"] if audit["reads"] else []
|
|
161
|
+
parts += [f"exclude {', '.join(audit['exclude'])}"] if audit["exclude"] else []
|
|
162
|
+
lines.append(f" audit: {'; '.join(parts)}")
|
|
163
|
+
for s in r["documents"]:
|
|
164
|
+
required = f", required for {'/'.join(s['required_for'])}" if s["required_for"] else ""
|
|
165
|
+
lines.append(f" document: {s['slot']} ({', '.join(s['content_types'])}{required})")
|
|
166
|
+
for point, fns in r["hooks"].items():
|
|
167
|
+
lines.append(f" hook {point}: {', '.join(fns)}")
|
|
168
|
+
_emit(args, data, "\n".join(lines))
|
|
169
|
+
return 0
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _asyncapi(args: argparse.Namespace, registry: ResourceRegistry) -> dict[str, Any]:
|
|
173
|
+
"""The AsyncAPI document with ``[tool.resource-engine.asyncapi]`` options."""
|
|
174
|
+
from resource_engine.messaging import asyncapi_document
|
|
175
|
+
|
|
176
|
+
from resource_engine_devtools.loader import load_consumers
|
|
177
|
+
|
|
178
|
+
options = dict(find_config(Path.cwd()).get("asyncapi") or {})
|
|
179
|
+
allowed = {
|
|
180
|
+
"title",
|
|
181
|
+
"version",
|
|
182
|
+
"description",
|
|
183
|
+
"resources",
|
|
184
|
+
"servers",
|
|
185
|
+
"channels",
|
|
186
|
+
"format",
|
|
187
|
+
"source",
|
|
188
|
+
"type_prefix",
|
|
189
|
+
}
|
|
190
|
+
unknown = sorted(set(options) - allowed)
|
|
191
|
+
if unknown:
|
|
192
|
+
raise SystemExit(
|
|
193
|
+
f"Unknown [tool.resource-engine.asyncapi] keys: {', '.join(unknown)} "
|
|
194
|
+
f"(allowed: {', '.join(sorted(allowed))})"
|
|
195
|
+
)
|
|
196
|
+
consumers = load_consumers(getattr(args, "consumer", None), Path.cwd())
|
|
197
|
+
return asyncapi_document(registry, consumers=consumers, **options)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def cmd_docs_asyncapi(args: argparse.Namespace) -> int:
|
|
201
|
+
"""``resource-engine docs asyncapi``: write the AsyncAPI document, or check it is up to date."""
|
|
202
|
+
document = _asyncapi(args, _registry(args))
|
|
203
|
+
text = json.dumps(document, indent=2, ensure_ascii=False) + "\n"
|
|
204
|
+
if args.check:
|
|
205
|
+
from resource_engine_devtools.contracts import breaking_changes
|
|
206
|
+
from resource_engine_devtools.scaffold import ScaffoldError
|
|
207
|
+
|
|
208
|
+
try:
|
|
209
|
+
problems = breaking_changes(Path(args.check), document)
|
|
210
|
+
except ScaffoldError as exc:
|
|
211
|
+
_emit(args, {"error": exc.message}, f"error: {exc.message}")
|
|
212
|
+
return 2
|
|
213
|
+
published = Path(args.check).read_text(encoding="utf-8")
|
|
214
|
+
current = json.loads(published) == document
|
|
215
|
+
report = "\n".join(f"BREAKING {p}" for p in problems) or (
|
|
216
|
+
"Same as the published document."
|
|
217
|
+
if current
|
|
218
|
+
else "Compatible changes only: publish the new document."
|
|
219
|
+
)
|
|
220
|
+
data = {
|
|
221
|
+
"breaking": [p.to_dict() for p in problems],
|
|
222
|
+
"changed": not current,
|
|
223
|
+
}
|
|
224
|
+
_emit(args, data, report)
|
|
225
|
+
return 1 if problems else 0
|
|
226
|
+
if args.out:
|
|
227
|
+
target = Path(args.out)
|
|
228
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
229
|
+
target.write_text(text, encoding="utf-8")
|
|
230
|
+
print(json.dumps({"written": [str(target)]}) if args.json else f"wrote {target}")
|
|
231
|
+
else:
|
|
232
|
+
sys.stdout.write(text)
|
|
233
|
+
return 0
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def cmd_docs_openapi(args: argparse.Namespace) -> int:
|
|
237
|
+
"""``resource-engine docs openapi``: write the application's OpenAPI document."""
|
|
238
|
+
from resource_engine_devtools.loader import add_paths
|
|
239
|
+
|
|
240
|
+
add_paths(find_config(Path.cwd()), Path.cwd())
|
|
241
|
+
document = _api_documents().get("openapi")
|
|
242
|
+
if document is None:
|
|
243
|
+
_emit(
|
|
244
|
+
args,
|
|
245
|
+
{"error": "no app"},
|
|
246
|
+
"error: set [tool.resource-engine] app (a FastAPI app or a factory)",
|
|
247
|
+
)
|
|
248
|
+
return 2
|
|
249
|
+
text = json.dumps(document, indent=2, ensure_ascii=False) + "\n"
|
|
250
|
+
if args.check:
|
|
251
|
+
from resource_engine_devtools.contracts import openapi_breaking_changes
|
|
252
|
+
|
|
253
|
+
problems = openapi_breaking_changes(Path(args.check), document)
|
|
254
|
+
current = json.loads(Path(args.check).read_text(encoding="utf-8")) == document
|
|
255
|
+
report = "\n".join(f"BREAKING {p}" for p in problems) or (
|
|
256
|
+
"Same as the published document."
|
|
257
|
+
if current
|
|
258
|
+
else "Compatible changes only: publish the new document."
|
|
259
|
+
)
|
|
260
|
+
_emit(args, {"breaking": [p.to_dict() for p in problems], "changed": not current}, report)
|
|
261
|
+
return 1 if problems else 0
|
|
262
|
+
if args.out:
|
|
263
|
+
target = Path(args.out)
|
|
264
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
265
|
+
target.write_text(text, encoding="utf-8")
|
|
266
|
+
print(json.dumps({"written": [str(target)]}) if args.json else f"wrote {target}")
|
|
267
|
+
else:
|
|
268
|
+
sys.stdout.write(text)
|
|
269
|
+
return 0
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _templates() -> dict[str, Any]:
|
|
273
|
+
"""The renderer named in ``[tool.resource-engine] templates``, for the docs."""
|
|
274
|
+
config = find_config(Path.cwd())
|
|
275
|
+
if not config.get("templates"):
|
|
276
|
+
return {}
|
|
277
|
+
from resource_engine_devtools.loader import load_object
|
|
278
|
+
|
|
279
|
+
return {
|
|
280
|
+
"templates": load_object(config["templates"]),
|
|
281
|
+
"email_prefix": config.get("email_prefix", "email/"),
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _i18n_config() -> I18nConfig | None:
|
|
286
|
+
from resource_engine_devtools.i18n import load_config
|
|
287
|
+
|
|
288
|
+
config = find_config(Path.cwd())
|
|
289
|
+
return load_config(config, Path(str(config.get("_root", Path.cwd()))))
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _docs_locale(args: argparse.Namespace) -> str | None:
|
|
293
|
+
"""``--locale``, else the application's source language (if configured)."""
|
|
294
|
+
config = _i18n_config()
|
|
295
|
+
return args.locale or (config.source_locale if config else None)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _api_documents() -> dict[str, Any]:
|
|
299
|
+
"""The application's OpenAPI (``[tool.resource-engine] app``: a FastAPI app or
|
|
300
|
+
a factory) and GraphQL SDL (``graphql``: a ``GraphQLSchema`` or a factory),
|
|
301
|
+
when configured. Building the app runs nothing (no lifespan)."""
|
|
302
|
+
from resource_engine_devtools.loader import load_object
|
|
303
|
+
|
|
304
|
+
config = find_config(Path.cwd())
|
|
305
|
+
out: dict[str, Any] = {}
|
|
306
|
+
if config.get("app"):
|
|
307
|
+
app = load_object(str(config["app"]))
|
|
308
|
+
if callable(app) and not hasattr(app, "openapi"):
|
|
309
|
+
app = app()
|
|
310
|
+
out["openapi"] = app.openapi()
|
|
311
|
+
if config.get("graphql"):
|
|
312
|
+
from graphql import GraphQLSchema, print_schema
|
|
313
|
+
|
|
314
|
+
schema = load_object(str(config["graphql"]))
|
|
315
|
+
if not isinstance(schema, GraphQLSchema) and callable(schema):
|
|
316
|
+
schema = schema()
|
|
317
|
+
out["graphql"] = print_schema(schema)
|
|
318
|
+
return out
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def cmd_docs_generate(args: argparse.Namespace) -> int:
|
|
322
|
+
"""``resource-engine docs generate``: the Markdown documentation of the application."""
|
|
323
|
+
from resource_engine_devtools.documentation.generators.api import (
|
|
324
|
+
api_pages,
|
|
325
|
+
documents_section,
|
|
326
|
+
)
|
|
327
|
+
from resource_engine_devtools.documentation.i18n import docs_locale, translate_model
|
|
328
|
+
from resource_engine_devtools.i18n import po_gettext
|
|
329
|
+
|
|
330
|
+
registry = _registry(args)
|
|
331
|
+
model = introspect(registry, load_authz(Path.cwd()), **_templates())
|
|
332
|
+
locale = _docs_locale(args)
|
|
333
|
+
config = _i18n_config()
|
|
334
|
+
if locale and config:
|
|
335
|
+
model = translate_model(model, po_gettext(config, locale))
|
|
336
|
+
out = Path(args.out)
|
|
337
|
+
asyncapi = _asyncapi(args, registry)
|
|
338
|
+
with docs_locale(locale):
|
|
339
|
+
if args.format == "json":
|
|
340
|
+
files = {"documentation.json": render_json(model)}
|
|
341
|
+
else:
|
|
342
|
+
files = render_markdown(model)
|
|
343
|
+
pages, documents = api_pages(asyncapi, **_api_documents())
|
|
344
|
+
section = documents_section(documents)
|
|
345
|
+
if args.format != "json":
|
|
346
|
+
files.update(pages)
|
|
347
|
+
if section and "index.md" in files:
|
|
348
|
+
files["index.md"] += section
|
|
349
|
+
files.update(documents)
|
|
350
|
+
for rel, content in files.items():
|
|
351
|
+
target = out / rel
|
|
352
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
353
|
+
target.write_text(content, encoding="utf-8")
|
|
354
|
+
_emit(
|
|
355
|
+
args,
|
|
356
|
+
{"written": sorted(str(out / f) for f in files)},
|
|
357
|
+
"\n".join(f"wrote {out / f}" for f in sorted(files)),
|
|
358
|
+
)
|
|
359
|
+
return 0
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def cmd_docs_site(args: argparse.Namespace) -> int:
|
|
363
|
+
"""``resource-engine docs site``: the static HTML documentation site."""
|
|
364
|
+
from resource_engine_devtools.documentation.generators.site import render_site
|
|
365
|
+
from resource_engine_devtools.i18n import iter_docs_locales, po_gettext
|
|
366
|
+
|
|
367
|
+
registry = _registry(args)
|
|
368
|
+
model = introspect(registry, load_authz(Path.cwd()), **_templates())
|
|
369
|
+
asyncapi = _asyncapi(args, registry)
|
|
370
|
+
config = _i18n_config()
|
|
371
|
+
locales = list(iter_docs_locales(config, args.locale))
|
|
372
|
+
files = render_site(
|
|
373
|
+
model,
|
|
374
|
+
asyncapi=asyncapi,
|
|
375
|
+
title=args.title,
|
|
376
|
+
mermaid_url=args.mermaid_url,
|
|
377
|
+
locales=locales or None,
|
|
378
|
+
translate=(lambda locale: po_gettext(config, locale)) if config else None,
|
|
379
|
+
**_api_documents(),
|
|
380
|
+
)
|
|
381
|
+
out = Path(args.out)
|
|
382
|
+
for rel, content in files.items():
|
|
383
|
+
target = out / rel
|
|
384
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
385
|
+
target.write_text(content, encoding="utf-8")
|
|
386
|
+
_emit(
|
|
387
|
+
args,
|
|
388
|
+
{"written": sorted(str(out / f) for f in files), "index": str(out / "index.html")},
|
|
389
|
+
f"wrote {len(files)} files to {out}; open {out / 'index.html'}",
|
|
390
|
+
)
|
|
391
|
+
return 0
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def cmd_docs_validate(args: argparse.Namespace) -> int:
|
|
395
|
+
"""``resource-engine docs validate``: report missing documentation (errors fail with
|
|
396
|
+
``--strict``)."""
|
|
397
|
+
findings = validate(introspect(_registry(args), load_authz(Path.cwd())))
|
|
398
|
+
errors = [f for f in findings if f.level == "error"]
|
|
399
|
+
warnings = [f for f in findings if f.level == "warning"]
|
|
400
|
+
failed = bool(errors) or (args.strict and bool(warnings))
|
|
401
|
+
labels = {"ok": "OK ", "warning": "WARN", "error": "ERR "}
|
|
402
|
+
text = (
|
|
403
|
+
"Documentation validation\n\n"
|
|
404
|
+
+ "\n".join(
|
|
405
|
+
f"{labels[f.level]} {f.code} {f.target}: {f.message}"
|
|
406
|
+
for f in findings
|
|
407
|
+
if args.verbose or f.level != "ok"
|
|
408
|
+
)
|
|
409
|
+
+ f"\n\n{len(errors)} errors, {len(warnings)} warnings"
|
|
410
|
+
)
|
|
411
|
+
_emit(args, {"passed": not failed, "findings": [f.to_dict() for f in findings]}, text)
|
|
412
|
+
return 1 if failed else 0
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def cmd_ai_context(args: argparse.Namespace) -> int:
|
|
416
|
+
"""``resource-engine ai context``: the compact description of the application for AI
|
|
417
|
+
assistants."""
|
|
418
|
+
content = render_ai_context(introspect(_registry(args), load_authz(Path.cwd())))
|
|
419
|
+
if not args.out:
|
|
420
|
+
print(content, end="")
|
|
421
|
+
return 0
|
|
422
|
+
target = Path(args.out)
|
|
423
|
+
if args.check:
|
|
424
|
+
current = target.read_text(encoding="utf-8") if target.exists() else None
|
|
425
|
+
up_to_date = current == content
|
|
426
|
+
_emit(
|
|
427
|
+
args,
|
|
428
|
+
{"up_to_date": up_to_date, "path": str(target)},
|
|
429
|
+
f"{target}: up to date"
|
|
430
|
+
if up_to_date
|
|
431
|
+
else f"{target}: OUT OF DATE (run resource-engine ai context --out {target})",
|
|
432
|
+
)
|
|
433
|
+
return 0 if up_to_date else 1
|
|
434
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
435
|
+
target.write_text(content, encoding="utf-8")
|
|
436
|
+
_emit(args, {"written": str(target)}, f"wrote {target}")
|
|
437
|
+
return 0
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _project_context(args: argparse.Namespace) -> str | None:
|
|
441
|
+
registry = _optional_registry(args)
|
|
442
|
+
if registry is None:
|
|
443
|
+
return None
|
|
444
|
+
return render_ai_context(introspect(registry, load_authz(Path.cwd())))
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def cmd_ai_install(args: argparse.Namespace) -> int:
|
|
448
|
+
"""``resource-engine ai install``: install the skill, context and MCP configuration for
|
|
449
|
+
assistants."""
|
|
450
|
+
from resource_engine_devtools.ai import installer
|
|
451
|
+
|
|
452
|
+
targets = installer.parse_targets(args.target)
|
|
453
|
+
root = Path(args.root)
|
|
454
|
+
command = None
|
|
455
|
+
if args.mcp or args.mcp_command:
|
|
456
|
+
command = (
|
|
457
|
+
args.mcp_command.split() if args.mcp_command else installer.default_mcp_command(root)
|
|
458
|
+
)
|
|
459
|
+
result = installer.install(root, targets, _project_context(args), mcp_command=command)
|
|
460
|
+
lines = [f"installed resource-engine skill {result['version']} → {result['skill_path']}"]
|
|
461
|
+
lines += [f" wrote {name}" for name in result["written"]]
|
|
462
|
+
lines += [f" removed {name}" for name in result["removed"]]
|
|
463
|
+
if command and not any(t in installer.MCP_CONFIGS for t in targets):
|
|
464
|
+
lines.append(
|
|
465
|
+
" note: no target with an MCP configuration (claude, cursor, copilot); "
|
|
466
|
+
"the server was not registered"
|
|
467
|
+
)
|
|
468
|
+
_emit(args, result, "\n".join(lines))
|
|
469
|
+
return 0
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
def cmd_ai_sync(args: argparse.Namespace) -> int:
|
|
473
|
+
"""``resource-engine ai sync``: report or refresh installed AI files that drifted."""
|
|
474
|
+
from resource_engine_devtools.ai import installer
|
|
475
|
+
|
|
476
|
+
root = Path(args.root)
|
|
477
|
+
context = _project_context(args)
|
|
478
|
+
lock, findings = installer.check(root, context)
|
|
479
|
+
if args.check or lock is None:
|
|
480
|
+
up_to_date = not findings
|
|
481
|
+
text = (
|
|
482
|
+
"AI skill and project context are up to date."
|
|
483
|
+
if up_to_date
|
|
484
|
+
else (
|
|
485
|
+
installer.summary(findings) + "\nRun: resource-engine ai sync"
|
|
486
|
+
if lock is not None
|
|
487
|
+
else installer.summary(findings)
|
|
488
|
+
)
|
|
489
|
+
)
|
|
490
|
+
_emit(args, {"up_to_date": up_to_date, "findings": [f.to_dict() for f in findings]}, text)
|
|
491
|
+
return 0 if up_to_date else 1
|
|
492
|
+
result = installer.install(root, lock["targets"], context, mcp_command=lock.get("mcp_command"))
|
|
493
|
+
lines = [f"synced resource-engine skill {result['version']} → {result['skill_path']}"]
|
|
494
|
+
lines += [f" wrote {name}" for name in result["written"]] or [" nothing to update"]
|
|
495
|
+
lines += [f" removed {name}" for name in result["removed"]]
|
|
496
|
+
_emit(args, result | {"findings": [f.to_dict() for f in findings]}, "\n".join(lines))
|
|
497
|
+
return 0
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def cmd_db_init(args: argparse.Namespace) -> int:
|
|
501
|
+
"""``resource-engine db init``: create the application's and the engine's tables."""
|
|
502
|
+
from resource_engine_devtools import db
|
|
503
|
+
|
|
504
|
+
config = find_config(Path.cwd())
|
|
505
|
+
metadata = args.metadata or config.get("metadata")
|
|
506
|
+
if not metadata:
|
|
507
|
+
raise SystemExit(
|
|
508
|
+
"No metadata given. Pass --metadata pkg.persistence:metadata or set "
|
|
509
|
+
'[tool.resource-engine] metadata = "pkg.persistence:metadata" in pyproject.toml'
|
|
510
|
+
)
|
|
511
|
+
sys_path = [str(p) for p in config.get("paths", [])] or ["."]
|
|
512
|
+
written = db.init(
|
|
513
|
+
Path.cwd(), str(metadata), directory=args.dir, sys_path=sys_path, force=args.force
|
|
514
|
+
)
|
|
515
|
+
lines = [f"wrote {path}" for path in written]
|
|
516
|
+
lines += [
|
|
517
|
+
"",
|
|
518
|
+
"Next:",
|
|
519
|
+
' alembic revision --autogenerate -m "initial schema"',
|
|
520
|
+
" alembic upgrade head # with DATABASE_URL set",
|
|
521
|
+
" alembic check # in CI: fails when the code has changes without a migration",
|
|
522
|
+
]
|
|
523
|
+
_emit(args, {"written": [str(p) for p in written]}, "\n".join(lines))
|
|
524
|
+
return 0
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
PARTS = ("hook", "event", "slot", "reference", "policy")
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
def _scaffold_part(args: argparse.Namespace, root: Path, fields: list[Any]) -> Any:
|
|
531
|
+
from resource_engine_devtools import scaffold_parts as parts
|
|
532
|
+
|
|
533
|
+
common = {"dry_run": args.dry_run}
|
|
534
|
+
match args.scaffold_command:
|
|
535
|
+
case "hook":
|
|
536
|
+
return parts.hook(
|
|
537
|
+
root, args.package, args.resource, args.function, args.on or [],
|
|
538
|
+
effect=args.effect, **common,
|
|
539
|
+
) # fmt: skip
|
|
540
|
+
case "event":
|
|
541
|
+
return parts.event(
|
|
542
|
+
root, args.package, args.resource, args.event_class, fields, **common
|
|
543
|
+
)
|
|
544
|
+
case "slot":
|
|
545
|
+
return parts.slot(
|
|
546
|
+
root, args.package, args.resource, args.slot,
|
|
547
|
+
content_types=args.content_type, max_mb=args.max_mb, multiple=args.multiple,
|
|
548
|
+
upload=args.upload, required_for=args.required_for, processing=args.processing,
|
|
549
|
+
**common,
|
|
550
|
+
) # fmt: skip
|
|
551
|
+
case "reference":
|
|
552
|
+
return parts.reference(
|
|
553
|
+
root, args.package, args.resource, args.field_name, args.to,
|
|
554
|
+
relation=args.relation, on_delete=args.on_delete, required=args.required,
|
|
555
|
+
related_name=args.related_name, **common,
|
|
556
|
+
) # fmt: skip
|
|
557
|
+
case _:
|
|
558
|
+
return parts.policy(
|
|
559
|
+
root, args.package, args.resource, args.role, read_only=args.read_only,
|
|
560
|
+
name=args.name, variable=args.variable, **common,
|
|
561
|
+
) # fmt: skip
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
def cmd_scaffold(args: argparse.Namespace) -> int:
|
|
565
|
+
"""``resource-engine scaffold``: write a resource, a state machine, an action or another
|
|
566
|
+
part."""
|
|
567
|
+
from resource_engine_devtools import scaffold
|
|
568
|
+
|
|
569
|
+
root = Path(args.root) if args.root else _default_root()
|
|
570
|
+
try:
|
|
571
|
+
fields = scaffold.parse_fields(getattr(args, "field", None))
|
|
572
|
+
if args.scaffold_command == "resource":
|
|
573
|
+
machine = (
|
|
574
|
+
scaffold.parse_machine(args.states, args.transitions)
|
|
575
|
+
if args.state_machine or args.states or args.transitions
|
|
576
|
+
else None
|
|
577
|
+
)
|
|
578
|
+
result = scaffold.resource(
|
|
579
|
+
root,
|
|
580
|
+
args.package,
|
|
581
|
+
args.name,
|
|
582
|
+
fields,
|
|
583
|
+
entity=args.entity,
|
|
584
|
+
machine=machine,
|
|
585
|
+
versioned=args.versioned,
|
|
586
|
+
force=args.force,
|
|
587
|
+
dry_run=args.dry_run,
|
|
588
|
+
)
|
|
589
|
+
elif args.scaffold_command == "consumer":
|
|
590
|
+
from resource_engine_devtools.consumer_scaffold import consumer
|
|
591
|
+
|
|
592
|
+
result = consumer(
|
|
593
|
+
root,
|
|
594
|
+
args.package,
|
|
595
|
+
args.name,
|
|
596
|
+
Path(args.asyncapi),
|
|
597
|
+
channels=args.channel or (),
|
|
598
|
+
messages=args.message or (),
|
|
599
|
+
type_prefix=args.type_prefix or "",
|
|
600
|
+
force=args.force,
|
|
601
|
+
dry_run=args.dry_run,
|
|
602
|
+
)
|
|
603
|
+
elif args.scaffold_command == "action":
|
|
604
|
+
result = scaffold.action(
|
|
605
|
+
root,
|
|
606
|
+
args.package,
|
|
607
|
+
args.resource,
|
|
608
|
+
args.action_class,
|
|
609
|
+
fields,
|
|
610
|
+
collection=args.collection,
|
|
611
|
+
dry_run=args.dry_run,
|
|
612
|
+
)
|
|
613
|
+
elif args.scaffold_command in PARTS:
|
|
614
|
+
result = _scaffold_part(args, root, fields)
|
|
615
|
+
else:
|
|
616
|
+
states, transitions = scaffold.parse_machine(args.states, args.transitions)
|
|
617
|
+
result = scaffold.state_machine(
|
|
618
|
+
root,
|
|
619
|
+
args.package,
|
|
620
|
+
args.entity,
|
|
621
|
+
states,
|
|
622
|
+
transitions,
|
|
623
|
+
force=args.force,
|
|
624
|
+
dry_run=args.dry_run,
|
|
625
|
+
)
|
|
626
|
+
except scaffold.ScaffoldError as exc:
|
|
627
|
+
_emit(args, {"error": exc.message}, f"error: {exc.message}")
|
|
628
|
+
return 2
|
|
629
|
+
verb = "would write" if args.dry_run else "wrote"
|
|
630
|
+
lines = [f"{verb} {path}" for path in result.written]
|
|
631
|
+
lines += [f"kept {path} (exists; --force to replace)" for path in result.skipped]
|
|
632
|
+
lines += ["", "Next:"] + [f" - {step}" for step in result.next_steps]
|
|
633
|
+
_emit(args, result.to_dict() | {"dry_run": args.dry_run}, "\n".join(lines))
|
|
634
|
+
return 0
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
def cmd_mcp(args: argparse.Namespace) -> int:
|
|
638
|
+
"""``resource-engine mcp``: serve the development tools over MCP (stdio)."""
|
|
639
|
+
try:
|
|
640
|
+
import mcp # noqa: F401
|
|
641
|
+
except ImportError:
|
|
642
|
+
raise SystemExit(
|
|
643
|
+
"The development MCP server needs the mcp extra: "
|
|
644
|
+
"pip install 'resource-engine-devtools[mcp]'"
|
|
645
|
+
) from None
|
|
646
|
+
import asyncio
|
|
647
|
+
|
|
648
|
+
from resource_engine_devtools.mcp_server import DevServer
|
|
649
|
+
|
|
650
|
+
asyncio.run(DevServer(Path(args.project) if args.project else None).run_stdio())
|
|
651
|
+
return 0
|
|
652
|
+
|
|
653
|
+
|
|
654
|
+
def _default_root() -> Path:
|
|
655
|
+
config = find_config(Path.cwd())
|
|
656
|
+
paths = config.get("paths") or []
|
|
657
|
+
if paths:
|
|
658
|
+
return Path(str(config["_root"])) / str(paths[0])
|
|
659
|
+
return Path.cwd()
|
|
660
|
+
|
|
661
|
+
|
|
662
|
+
def cmd_check(args: argparse.Namespace) -> int:
|
|
663
|
+
"""``resource-engine check``: the architecture and declaration checks (RE-C001 to RE-C009)."""
|
|
664
|
+
violations = []
|
|
665
|
+
for raw in args.paths or ["."]:
|
|
666
|
+
violations += check_domain_imports(Path(raw))
|
|
667
|
+
from resource_engine.errors import ResourceEngineError
|
|
668
|
+
|
|
669
|
+
from resource_engine_devtools import gates_check
|
|
670
|
+
from resource_engine_devtools.declarations_check import check_declarations
|
|
671
|
+
from resource_engine_devtools.events_check import check_events
|
|
672
|
+
from resource_engine_devtools.hooks_check import check_hooks
|
|
673
|
+
from resource_engine_devtools.logic_check import check_logic
|
|
674
|
+
|
|
675
|
+
try:
|
|
676
|
+
registry = _optional_registry(args)
|
|
677
|
+
except ResourceEngineError as exc: # the engine refused a declaration
|
|
678
|
+
registry = None
|
|
679
|
+
violations.append(gates_check.load_error(exc))
|
|
680
|
+
if registry is not None:
|
|
681
|
+
violations += check_hooks(registry)
|
|
682
|
+
violations += check_events(registry)
|
|
683
|
+
violations += check_declarations(registry)
|
|
684
|
+
violations += check_logic(registry)
|
|
685
|
+
config = find_config(Path.cwd())
|
|
686
|
+
if config.get("templates"):
|
|
687
|
+
from resource_engine_devtools.loader import load_object
|
|
688
|
+
from resource_engine_devtools.templates_check import check_templates
|
|
689
|
+
|
|
690
|
+
violations += check_templates(
|
|
691
|
+
registry,
|
|
692
|
+
load_object(config["templates"]),
|
|
693
|
+
prefix=config.get("email_prefix", "email/"),
|
|
694
|
+
)
|
|
695
|
+
seed = args.policies or config.get("policies")
|
|
696
|
+
if seed:
|
|
697
|
+
violations += gates_check.check_gates(
|
|
698
|
+
registry, load_authz(Path.cwd()), gates_check.load_policies(seed)
|
|
699
|
+
)
|
|
700
|
+
text = (
|
|
701
|
+
"\n".join(f"{v.code} {v.path}:{v.line}: {v.message}\n {v.hint}" for v in violations)
|
|
702
|
+
or "No violations."
|
|
703
|
+
)
|
|
704
|
+
_emit(args, {"passed": not violations, "violations": [v.to_dict() for v in violations]}, text)
|
|
705
|
+
return 1 if violations else 0
|
|
706
|
+
|
|
707
|
+
|
|
708
|
+
def cmd_i18n(args: argparse.Namespace) -> int:
|
|
709
|
+
"""``resource-engine i18n``: extract, update, compile and report the translations."""
|
|
710
|
+
from resource_engine_devtools import i18n
|
|
711
|
+
|
|
712
|
+
config = _i18n_config()
|
|
713
|
+
if config is None:
|
|
714
|
+
_emit(
|
|
715
|
+
args,
|
|
716
|
+
{"error": "no [tool.resource-engine.i18n] section"},
|
|
717
|
+
"error: add [tool.resource-engine.i18n] (directory, source_locale, locales)",
|
|
718
|
+
)
|
|
719
|
+
return 2
|
|
720
|
+
command = args.i18n_command
|
|
721
|
+
if command == "extract":
|
|
722
|
+
project = find_config(Path.cwd())
|
|
723
|
+
root = Path(str(project.get("_root", Path.cwd())))
|
|
724
|
+
paths = [root / str(p) for p in project.get("paths", ["."])]
|
|
725
|
+
model = None
|
|
726
|
+
try:
|
|
727
|
+
registry = _registry(args)
|
|
728
|
+
model = introspect(registry, load_authz(Path.cwd()))
|
|
729
|
+
except SystemExit:
|
|
730
|
+
pass # no registry configured: code and templates only
|
|
731
|
+
catalog = i18n.extract(config, paths, model=model)
|
|
732
|
+
path = i18n.write_template(config, catalog)
|
|
733
|
+
count = len([m for m in catalog if m.id])
|
|
734
|
+
_emit(args, {"template": str(path), "messages": count}, f"wrote {path} ({count} messages)")
|
|
735
|
+
return 0
|
|
736
|
+
if command == "update":
|
|
737
|
+
done = i18n.update(config)
|
|
738
|
+
_emit(args, {"locales": done}, "\n".join(f"{loc}: {what}" for loc, what in done.items()))
|
|
739
|
+
return 0
|
|
740
|
+
if command == "compile":
|
|
741
|
+
written = i18n.compile_catalogues(config)
|
|
742
|
+
_emit(
|
|
743
|
+
args,
|
|
744
|
+
{"written": {k: str(v) for k, v in written.items()}},
|
|
745
|
+
"\n".join(f"wrote {v}" for v in written.values()) or "no catalogues",
|
|
746
|
+
)
|
|
747
|
+
return 0
|
|
748
|
+
if command == "export":
|
|
749
|
+
files = i18n.export(config, Path(args.out))
|
|
750
|
+
_emit(args, {"written": [str(f) for f in files]}, "\n".join(f"wrote {f}" for f in files))
|
|
751
|
+
return 0
|
|
752
|
+
report = i18n.status(config)
|
|
753
|
+
lines = [
|
|
754
|
+
f"{s.locale}: {s.translated}/{s.total} translated, {s.fuzzy} fuzzy, "
|
|
755
|
+
f"{len(s.missing)} missing{'' if s.compiled else ' (not compiled)'}"
|
|
756
|
+
for s in report
|
|
757
|
+
]
|
|
758
|
+
failed = args.strict and any(s.missing or s.fuzzy or not s.compiled for s in report)
|
|
759
|
+
_emit(args, {"passed": not failed, "locales": [s.to_dict() for s in report]}, "\n".join(lines))
|
|
760
|
+
return 1 if failed else 0
|
|
761
|
+
|
|
762
|
+
|
|
763
|
+
def cmd_authz(args: argparse.Namespace) -> int:
|
|
764
|
+
"""Artefacts for external policy engines: a Cedar schema, an OPA bundle."""
|
|
765
|
+
registry = _registry(args)
|
|
766
|
+
if args.authz_command == "cedar-schema":
|
|
767
|
+
try:
|
|
768
|
+
from resource_engine_cedar import cedar_schema, validate
|
|
769
|
+
except ImportError:
|
|
770
|
+
_emit(
|
|
771
|
+
args,
|
|
772
|
+
{"error": "install resource-engine-cedar"},
|
|
773
|
+
"error: needs resource-engine-cedar",
|
|
774
|
+
)
|
|
775
|
+
return 2
|
|
776
|
+
types = dict(item.split("=", 1) for item in args.entity_type or [])
|
|
777
|
+
schema = cedar_schema(registry, entity_types=types)
|
|
778
|
+
text = json.dumps(schema, indent=2, sort_keys=True) + "\n"
|
|
779
|
+
if args.out:
|
|
780
|
+
Path(args.out).write_text(text, encoding="utf-8")
|
|
781
|
+
if args.check:
|
|
782
|
+
problems = validate(Path(args.check), schema)
|
|
783
|
+
_emit(
|
|
784
|
+
args,
|
|
785
|
+
{"passed": not problems, "problems": problems},
|
|
786
|
+
"\n".join(problems) or f"{args.check}: every policy fits the schema",
|
|
787
|
+
)
|
|
788
|
+
return 1 if problems else 0
|
|
789
|
+
if args.out:
|
|
790
|
+
_emit(args, {"written": args.out}, f"wrote {args.out}")
|
|
791
|
+
else:
|
|
792
|
+
sys.stdout.write(text)
|
|
793
|
+
return 0
|
|
794
|
+
try:
|
|
795
|
+
from resource_engine_opa import opa_bundle
|
|
796
|
+
except ImportError:
|
|
797
|
+
_emit(args, {"error": "install resource-engine-opa"}, "error: needs resource-engine-opa")
|
|
798
|
+
return 2
|
|
799
|
+
bundle = opa_bundle(registry, load_authz(Path.cwd()), policies=args.policies)
|
|
800
|
+
Path(args.out).write_bytes(bundle)
|
|
801
|
+
_emit(
|
|
802
|
+
args, {"written": args.out, "bytes": len(bundle)}, f"wrote {args.out} ({len(bundle)} bytes)"
|
|
803
|
+
)
|
|
804
|
+
return 0
|
|
805
|
+
|
|
806
|
+
|
|
807
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
808
|
+
"""The ``resource-engine`` command's argument parser, with every subcommand."""
|
|
809
|
+
common = argparse.ArgumentParser(add_help=False)
|
|
810
|
+
common.add_argument("--json", action="store_true", help="machine-readable output")
|
|
811
|
+
common.add_argument("--app", help="registry as module:attribute (default: pyproject config)")
|
|
812
|
+
|
|
813
|
+
parser = argparse.ArgumentParser(prog="resource-engine", description=__doc__)
|
|
814
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
815
|
+
|
|
816
|
+
p = sub.add_parser("inspect", parents=[common], help="show the resolved resource definitions")
|
|
817
|
+
p.add_argument("resource", nargs="?")
|
|
818
|
+
p.set_defaults(func=cmd_inspect)
|
|
819
|
+
|
|
820
|
+
p = sub.add_parser("check", parents=[common], help="architecture, hook/effect and gate lints")
|
|
821
|
+
p.add_argument("paths", nargs="*")
|
|
822
|
+
p.add_argument(
|
|
823
|
+
"--policies",
|
|
824
|
+
help="seed policies as module:attribute (default: pyproject policies); "
|
|
825
|
+
"enables the operations-without-a-gate rule",
|
|
826
|
+
)
|
|
827
|
+
p.set_defaults(func=cmd_check)
|
|
828
|
+
|
|
829
|
+
docs = sub.add_parser("docs", help="functional documentation").add_subparsers(
|
|
830
|
+
dest="docs_command", required=True
|
|
831
|
+
)
|
|
832
|
+
p = docs.add_parser("generate", parents=[common])
|
|
833
|
+
p.add_argument("--out", default="docs/functional")
|
|
834
|
+
p.add_argument("--format", choices=["markdown", "json"], default="markdown")
|
|
835
|
+
p.add_argument(
|
|
836
|
+
"--locale", help="language of the docs (default: the i18n source_locale, else English)"
|
|
837
|
+
)
|
|
838
|
+
p.set_defaults(func=cmd_docs_generate)
|
|
839
|
+
p = docs.add_parser(
|
|
840
|
+
"asyncapi", parents=[common], help="AsyncAPI 3.0 document of published and consumed events"
|
|
841
|
+
)
|
|
842
|
+
p.add_argument("--out", help="file to write (default: standard output)")
|
|
843
|
+
p.add_argument(
|
|
844
|
+
"--check",
|
|
845
|
+
metavar="PUBLISHED",
|
|
846
|
+
help="compare with the published document; exit 1 on changes that break consumers",
|
|
847
|
+
)
|
|
848
|
+
p.add_argument(
|
|
849
|
+
"--consumer",
|
|
850
|
+
action="append",
|
|
851
|
+
help="EventRouter as module:attribute (repeatable; default: pyproject consumers)",
|
|
852
|
+
)
|
|
853
|
+
p.set_defaults(func=cmd_docs_asyncapi)
|
|
854
|
+
p = docs.add_parser(
|
|
855
|
+
"openapi", parents=[common], help="OpenAPI document of the app ([tool.resource-engine] app)"
|
|
856
|
+
)
|
|
857
|
+
p.add_argument("--out", help="file to write (default: standard output)")
|
|
858
|
+
p.add_argument(
|
|
859
|
+
"--check",
|
|
860
|
+
metavar="PUBLISHED",
|
|
861
|
+
help="compare with the published document; exit 1 on changes that break clients",
|
|
862
|
+
)
|
|
863
|
+
p.set_defaults(func=cmd_docs_openapi)
|
|
864
|
+
from resource_engine_devtools.documentation.generators.site import MERMAID_URL
|
|
865
|
+
|
|
866
|
+
p = docs.add_parser(
|
|
867
|
+
"site", parents=[common], help="the functional documentation as a static HTML site"
|
|
868
|
+
)
|
|
869
|
+
p.add_argument("--out", default="site")
|
|
870
|
+
p.add_argument("--title", help="site title (default: the AsyncAPI title)")
|
|
871
|
+
p.add_argument(
|
|
872
|
+
"--locale",
|
|
873
|
+
action="append",
|
|
874
|
+
help="a language of the site (repeatable; default: every i18n locale). With several, "
|
|
875
|
+
"each gets its own folder and a language switcher",
|
|
876
|
+
)
|
|
877
|
+
p.add_argument(
|
|
878
|
+
"--mermaid-url",
|
|
879
|
+
default=MERMAID_URL,
|
|
880
|
+
help="Mermaid ES module for the diagrams (self-hosted copy; empty: no diagrams)",
|
|
881
|
+
)
|
|
882
|
+
p.add_argument(
|
|
883
|
+
"--consumer",
|
|
884
|
+
action="append",
|
|
885
|
+
help="EventRouter as module:attribute (repeatable; default: pyproject consumers)",
|
|
886
|
+
)
|
|
887
|
+
p.set_defaults(func=cmd_docs_site)
|
|
888
|
+
p = docs.add_parser("validate", parents=[common])
|
|
889
|
+
p.add_argument("--strict", action="store_true", help="fail on warnings too")
|
|
890
|
+
p.add_argument("-v", "--verbose", action="store_true", help="also list passing checks")
|
|
891
|
+
p.set_defaults(func=cmd_docs_validate)
|
|
892
|
+
|
|
893
|
+
ai = sub.add_parser("ai", help="context for AI coding agents").add_subparsers(
|
|
894
|
+
dest="ai_command", required=True
|
|
895
|
+
)
|
|
896
|
+
p = ai.add_parser("context", parents=[common], help="generate the project catalogue")
|
|
897
|
+
p.add_argument("--out")
|
|
898
|
+
p.add_argument("--check", action="store_true", help="fail if --out is out of date")
|
|
899
|
+
p.set_defaults(func=cmd_ai_context)
|
|
900
|
+
p = ai.add_parser("install", parents=[common], help="install the skill and agent instructions")
|
|
901
|
+
p.add_argument(
|
|
902
|
+
"--target",
|
|
903
|
+
help="comma-separated: claude, agents, cursor, copilot (default: claude,agents)",
|
|
904
|
+
)
|
|
905
|
+
p.add_argument("--root", default=".", help="project root (default: current directory)")
|
|
906
|
+
p.add_argument(
|
|
907
|
+
"--mcp",
|
|
908
|
+
action="store_true",
|
|
909
|
+
help="also register the development MCP server (.mcp.json, .cursor/mcp.json, "
|
|
910
|
+
".vscode/mcp.json for the targets)",
|
|
911
|
+
)
|
|
912
|
+
p.add_argument(
|
|
913
|
+
"--mcp-command",
|
|
914
|
+
help='command for the MCP server (default: "uv run resource-engine mcp" with a '
|
|
915
|
+
'uv.lock, else "resource-engine mcp")',
|
|
916
|
+
)
|
|
917
|
+
p.set_defaults(func=cmd_ai_install)
|
|
918
|
+
p = ai.add_parser(
|
|
919
|
+
"sync", parents=[common], help="update the installed skill and project context"
|
|
920
|
+
)
|
|
921
|
+
p.add_argument("--check", action="store_true", help="fail if anything is out of date")
|
|
922
|
+
p.add_argument("--root", default=".", help="project root (default: current directory)")
|
|
923
|
+
p.set_defaults(func=cmd_ai_sync)
|
|
924
|
+
|
|
925
|
+
db = sub.add_parser("db", help="database migrations (Alembic)").add_subparsers(
|
|
926
|
+
dest="db_command", required=True
|
|
927
|
+
)
|
|
928
|
+
p = db.add_parser("init", help="write alembic.ini and migrations/ for your MetaData")
|
|
929
|
+
p.add_argument("--json", action="store_true", help="machine-readable output")
|
|
930
|
+
p.add_argument("--metadata", help="MetaData as module:attribute (default: pyproject metadata)")
|
|
931
|
+
p.add_argument("--dir", default="migrations", help="migrations folder (default: migrations)")
|
|
932
|
+
p.add_argument("--force", action="store_true", help="replace existing files")
|
|
933
|
+
p.set_defaults(func=cmd_db_init)
|
|
934
|
+
|
|
935
|
+
scaffold = sub.add_parser(
|
|
936
|
+
"scaffold", help="generate a module or one of its parts (action, hook, event, slot...)"
|
|
937
|
+
).add_subparsers(dest="scaffold_command", required=True)
|
|
938
|
+
shared = argparse.ArgumentParser(add_help=False)
|
|
939
|
+
shared.add_argument("--json", action="store_true", help="machine-readable output")
|
|
940
|
+
shared.add_argument("--package", required=True, help="dotted package of the module")
|
|
941
|
+
shared.add_argument(
|
|
942
|
+
"--root", help="directory the package lives in (default: first pyproject path, or .)"
|
|
943
|
+
)
|
|
944
|
+
shared.add_argument("--dry-run", action="store_true", help="show what would be written")
|
|
945
|
+
p = scaffold.add_parser("resource", parents=[shared], help="a new module with one resource")
|
|
946
|
+
p.add_argument("name", help="resource name, plural snake_case (orders)")
|
|
947
|
+
p.add_argument("--entity", help="entity class (default: singular PascalCase of the name)")
|
|
948
|
+
p.add_argument(
|
|
949
|
+
"--field",
|
|
950
|
+
action="append",
|
|
951
|
+
help="name:type[?], type in str text int bool Decimal date "
|
|
952
|
+
"datetime; ? makes it optional (repeatable)",
|
|
953
|
+
)
|
|
954
|
+
p.add_argument("--state-machine", action="store_true", help="add a state machine")
|
|
955
|
+
p.add_argument("--states", help="comma-separated states (default: draft,active,closed)")
|
|
956
|
+
p.add_argument("--transitions", help="event:source>target,... (default: one per step)")
|
|
957
|
+
p.add_argument("--versioned", action="store_true", help="optimistic concurrency")
|
|
958
|
+
p.add_argument("--force", action="store_true", help="overwrite existing files")
|
|
959
|
+
p.set_defaults(func=cmd_scaffold)
|
|
960
|
+
p = scaffold.add_parser("action", parents=[shared], help="an action in an existing module")
|
|
961
|
+
p.add_argument("resource", help="resource name (for the permission and the route)")
|
|
962
|
+
p.add_argument("action_class", metavar="ActionClass")
|
|
963
|
+
p.add_argument("--input", action="append", dest="field", help="input field name:type[?]")
|
|
964
|
+
p.add_argument("--collection", action="store_true", help="not tied to one record")
|
|
965
|
+
p.set_defaults(func=cmd_scaffold)
|
|
966
|
+
p = scaffold.add_parser(
|
|
967
|
+
"consumer",
|
|
968
|
+
parents=[shared],
|
|
969
|
+
help="a typed consumer and its contract tests from a provider's AsyncAPI document",
|
|
970
|
+
)
|
|
971
|
+
p.add_argument("name", help="consumer name, snake_case (payments)")
|
|
972
|
+
p.add_argument("--asyncapi", required=True, help="the provider's AsyncAPI file (JSON or YAML)")
|
|
973
|
+
p.add_argument("--channel", action="append", help="only this provider channel (repeatable)")
|
|
974
|
+
p.add_argument("--message", action="append", help="only this event type (repeatable)")
|
|
975
|
+
p.add_argument("--type-prefix", help="CloudEvents type prefix to strip (com.example.)")
|
|
976
|
+
p.add_argument("--force", action="store_true", help="overwrite existing files")
|
|
977
|
+
p.set_defaults(func=cmd_scaffold)
|
|
978
|
+
p = scaffold.add_parser(
|
|
979
|
+
"state-machine", parents=[shared], help="a state machine in an existing module"
|
|
980
|
+
)
|
|
981
|
+
p.add_argument("entity", help="entity class name (Order)")
|
|
982
|
+
p.add_argument("--states", help="comma-separated states (default: draft,active,closed)")
|
|
983
|
+
p.add_argument("--transitions", help="event:source>target,... (default: one per step)")
|
|
984
|
+
p.add_argument("--force", action="store_true", help="overwrite an existing state machine")
|
|
985
|
+
p.set_defaults(func=cmd_scaffold)
|
|
986
|
+
p = scaffold.add_parser(
|
|
987
|
+
"hook", parents=[shared], help="a hook function, registered on the resource"
|
|
988
|
+
)
|
|
989
|
+
p.add_argument("resource", help="resource name (orders)")
|
|
990
|
+
p.add_argument("function", help="hook function name, snake_case (check_credit)")
|
|
991
|
+
p.add_argument(
|
|
992
|
+
"--on",
|
|
993
|
+
action="append",
|
|
994
|
+
help="hook point: before_create, after_update, before_transition:place, after_commit... "
|
|
995
|
+
"(repeatable)",
|
|
996
|
+
)
|
|
997
|
+
p.add_argument("--effect", action="store_true", help="an external effect (after_commit, async)")
|
|
998
|
+
p.set_defaults(func=cmd_scaffold)
|
|
999
|
+
p = scaffold.add_parser(
|
|
1000
|
+
"event", parents=[shared], help="a domain event, declared on the resource"
|
|
1001
|
+
)
|
|
1002
|
+
p.add_argument("resource", help="resource name (orders)")
|
|
1003
|
+
p.add_argument(
|
|
1004
|
+
"event_class", metavar="EventClass", help="PascalCase, past tense (OrderShipped)"
|
|
1005
|
+
)
|
|
1006
|
+
p.add_argument("--field", action="append", help="payload field name:type[?] (repeatable)")
|
|
1007
|
+
p.set_defaults(func=cmd_scaffold)
|
|
1008
|
+
p = scaffold.add_parser("slot", parents=[shared], help="a document slot on the resource")
|
|
1009
|
+
p.add_argument("resource", help="resource name (orders)")
|
|
1010
|
+
p.add_argument("slot", help="slot name, snake_case (delivery_note)")
|
|
1011
|
+
p.add_argument("--content-type", action="append", help="accepted MIME type (repeatable)")
|
|
1012
|
+
p.add_argument("--max-mb", type=int, help="size limit in MiB (default 25)")
|
|
1013
|
+
p.add_argument("--multiple", action="store_true", help="several documents at once")
|
|
1014
|
+
p.add_argument("--upload", choices=["api", "presigned", "any"], help="how bytes arrive")
|
|
1015
|
+
p.add_argument(
|
|
1016
|
+
"--required-for", action="append", help="transition that needs a document (repeatable)"
|
|
1017
|
+
)
|
|
1018
|
+
p.add_argument("--processing", action="store_true", help="run the processing pipeline")
|
|
1019
|
+
p.set_defaults(func=cmd_scaffold)
|
|
1020
|
+
p = scaffold.add_parser("reference", parents=[shared], help="a reference to another resource")
|
|
1021
|
+
p.add_argument("resource", help="resource name (orders)")
|
|
1022
|
+
p.add_argument("field_name", metavar="field", help="the id field (customer_id)")
|
|
1023
|
+
p.add_argument("--to", required=True, help="the referenced resource (customers)")
|
|
1024
|
+
p.add_argument("--relation", help="relation name for expand (default: field without _id)")
|
|
1025
|
+
p.add_argument("--on-delete", default="restrict", choices=["restrict", "set_null", "cascade"])
|
|
1026
|
+
p.add_argument("--required", action="store_true", help="the field can't be empty")
|
|
1027
|
+
p.add_argument("--related-name", help="reverse relation on the referenced resource")
|
|
1028
|
+
p.set_defaults(func=cmd_scaffold)
|
|
1029
|
+
p = scaffold.add_parser(
|
|
1030
|
+
"policy", parents=[shared], help="a seed policy granting a role the resource"
|
|
1031
|
+
)
|
|
1032
|
+
p.add_argument("resource", help="resource name (orders)")
|
|
1033
|
+
p.add_argument("--role", required=True, help="the role the policy grants (clerk)")
|
|
1034
|
+
p.add_argument("--read-only", action="store_true", help="list, get and downloads only")
|
|
1035
|
+
p.add_argument("--name", help="policy name (default: '<Role> manages <resource>')")
|
|
1036
|
+
p.add_argument(
|
|
1037
|
+
"--variable", default="SEED_POLICIES", help="list in <package>/authz.py to append to"
|
|
1038
|
+
)
|
|
1039
|
+
p.set_defaults(func=cmd_scaffold)
|
|
1040
|
+
|
|
1041
|
+
authz = sub.add_parser(
|
|
1042
|
+
"authz", help="artefacts for external policy engines (Cedar, OPA)"
|
|
1043
|
+
).add_subparsers(dest="authz_command", required=True)
|
|
1044
|
+
p = authz.add_parser(
|
|
1045
|
+
"cedar-schema", parents=[common], help="the Cedar schema of the resources and actions"
|
|
1046
|
+
)
|
|
1047
|
+
p.add_argument("--out", help="write it to this file (default: print it)")
|
|
1048
|
+
p.add_argument(
|
|
1049
|
+
"--entity-type",
|
|
1050
|
+
action="append",
|
|
1051
|
+
help="resource=EntityType, as CedarEngine(entity_types=...) (repeatable)",
|
|
1052
|
+
)
|
|
1053
|
+
p.add_argument("--check", help="validate the .cedar policies in this file or directory")
|
|
1054
|
+
p.set_defaults(func=cmd_authz)
|
|
1055
|
+
p = authz.add_parser(
|
|
1056
|
+
"opa-bundle", parents=[common], help="an OPA bundle: the catalogue and your Rego"
|
|
1057
|
+
)
|
|
1058
|
+
p.add_argument("--out", default="bundle.tar.gz")
|
|
1059
|
+
p.add_argument("--policies", help="a .rego file or a directory of them to include")
|
|
1060
|
+
p.set_defaults(func=cmd_authz)
|
|
1061
|
+
|
|
1062
|
+
i18n = sub.add_parser(
|
|
1063
|
+
"i18n", help="translation catalogues ([tool.resource-engine.i18n])"
|
|
1064
|
+
).add_subparsers(dest="i18n_command", required=True)
|
|
1065
|
+
p = i18n.add_parser(
|
|
1066
|
+
"extract", parents=[common], help="messages.pot from code, templates and docs texts"
|
|
1067
|
+
)
|
|
1068
|
+
p.set_defaults(func=cmd_i18n)
|
|
1069
|
+
p = i18n.add_parser("update", parents=[common], help="create or update each locale's .po")
|
|
1070
|
+
p.set_defaults(func=cmd_i18n)
|
|
1071
|
+
p = i18n.add_parser("compile", parents=[common], help=".po → .mo for the runtime")
|
|
1072
|
+
p.set_defaults(func=cmd_i18n)
|
|
1073
|
+
p = i18n.add_parser("status", parents=[common], help="translated, fuzzy, missing per locale")
|
|
1074
|
+
p.add_argument("--strict", action="store_true", help="fail on missing or fuzzy texts")
|
|
1075
|
+
p.set_defaults(func=cmd_i18n)
|
|
1076
|
+
p = i18n.add_parser("export", parents=[common], help="JSON catalogues for front ends")
|
|
1077
|
+
p.add_argument("--out", default="locale-json")
|
|
1078
|
+
p.set_defaults(func=cmd_i18n)
|
|
1079
|
+
|
|
1080
|
+
p = sub.add_parser("mcp", help="serve these commands as MCP tools for coding agents (stdio)")
|
|
1081
|
+
p.add_argument("--project", help="project directory (default: the current one)")
|
|
1082
|
+
p.set_defaults(func=cmd_mcp)
|
|
1083
|
+
|
|
1084
|
+
p = sub.add_parser("worker", help="run the application's background jobs and services")
|
|
1085
|
+
p.add_argument("--runner", help="JobRunner as module:attribute (default: pyproject worker)")
|
|
1086
|
+
p.add_argument("--once", action="store_true", help="run every job once and exit")
|
|
1087
|
+
p.add_argument("--log-level", default="info", choices=["debug", "info", "warning", "error"])
|
|
1088
|
+
p.add_argument(
|
|
1089
|
+
"--log-format",
|
|
1090
|
+
default="text",
|
|
1091
|
+
choices=["text", "json"],
|
|
1092
|
+
help="json: one object per line with the job, consumer and correlation id",
|
|
1093
|
+
)
|
|
1094
|
+
p.set_defaults(func=_worker)
|
|
1095
|
+
return parser
|
|
1096
|
+
|
|
1097
|
+
|
|
1098
|
+
def _worker(args: argparse.Namespace) -> int:
|
|
1099
|
+
from resource_engine_devtools.worker import cmd_worker
|
|
1100
|
+
|
|
1101
|
+
return cmd_worker(args)
|
|
1102
|
+
|
|
1103
|
+
|
|
1104
|
+
def main(argv: list[str] | None = None) -> int:
|
|
1105
|
+
"""Run the ``resource-engine`` command; returns its exit code."""
|
|
1106
|
+
args = build_parser().parse_args(argv)
|
|
1107
|
+
code: int = args.func(args)
|
|
1108
|
+
return code
|
|
1109
|
+
|
|
1110
|
+
|
|
1111
|
+
if __name__ == "__main__":
|
|
1112
|
+
sys.exit(main())
|