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,6 @@
1
+ """Developer tools: the resource-engine command, checks, documentation, scaffolding and the AI
2
+ skill."""
3
+
4
+ # The package's interface is the ``resource-engine`` command; its Python API is
5
+ # ``resource_engine_devtools.contracts``.
6
+ __all__: list[str] = []
@@ -0,0 +1 @@
1
+ """The AI assistant integration: the skill, the context file and their installer."""
@@ -0,0 +1,66 @@
1
+ """The reference module shipped inside the skill (``skill/examples/invoices``).
2
+
3
+ It is a copy of the repository's ``examples/invoices``, which runs in the
4
+ framework's tests. ``test_skill_example_is_in_sync`` fails when they drift;
5
+ refresh the copy with ``python -m resource_engine_devtools.ai.example``.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import shutil
11
+ import sys
12
+ from pathlib import Path
13
+
14
+ #: Files of ``examples/invoices`` copied into the skill.
15
+ EXAMPLE_FILES = (
16
+ "__init__.py",
17
+ "bootstrap.py",
18
+ "authz.py",
19
+ "app.py",
20
+ "domain/__init__.py",
21
+ "domain/entities.py",
22
+ "domain/events.py",
23
+ "domain/state_machine.py",
24
+ "application/__init__.py",
25
+ "application/schemas.py",
26
+ "application/customers.py",
27
+ "application/balances.py",
28
+ "application/tags.py",
29
+ "application/processes.py",
30
+ "worker.py",
31
+ "notifications.py",
32
+ "templates/email/base.html",
33
+ "templates/email/invoice_approved.subject.txt",
34
+ "templates/email/invoice_approved.txt",
35
+ "templates/email/invoice_approved.html",
36
+ "locale/en/LC_MESSAGES/messages.po",
37
+ "locale/es/LC_MESSAGES/messages.po",
38
+ "application/resource.py",
39
+ "application/hooks.py",
40
+ "application/actions.py",
41
+ "infrastructure/__init__.py",
42
+ "infrastructure/persistence.py",
43
+ "tests/conftest.py",
44
+ "tests/test_invoices_engine.py",
45
+ )
46
+
47
+ SKILL_DIR = Path(__file__).parent / "skill"
48
+ EXAMPLE_DIR = SKILL_DIR / "examples" / "invoices"
49
+
50
+
51
+ def sync(source: Path, target: Path = EXAMPLE_DIR) -> list[str]:
52
+ """Copy the example files from ``source``; returns the files that changed."""
53
+ changed = []
54
+ for name in EXAMPLE_FILES:
55
+ src, dst = source / name, target / name
56
+ if not dst.exists() or dst.read_bytes() != src.read_bytes():
57
+ dst.parent.mkdir(parents=True, exist_ok=True)
58
+ shutil.copyfile(src, dst)
59
+ changed.append(name)
60
+ return changed
61
+
62
+
63
+ if __name__ == "__main__": # pragma: no cover
64
+ repo = Path(sys.argv[1]) if len(sys.argv) > 1 else Path.cwd()
65
+ for name in sync(repo / "examples" / "invoices"):
66
+ print(f"updated {name}")
@@ -0,0 +1,424 @@
1
+ """``resource-engine ai install`` / ``ai sync``: put the skill and the project
2
+ context where AI coding agents look for them, and keep them current.
3
+
4
+ Targets:
5
+
6
+ - ``claude``: the skill in ``.claude/skills/resource-engine/``;
7
+ - ``agents``: a managed block in ``AGENTS.md``;
8
+ - ``cursor``: ``.cursor/rules/resource-engine.mdc``;
9
+ - ``copilot``: a managed block in ``.github/copilot-instructions.md``.
10
+
11
+ The skill files always go to one place (the Claude skill folder, or
12
+ ``.resource-engine/skill/`` without the ``claude`` target), with the generated
13
+ project catalogue as ``project.md``. Managed blocks sit between
14
+ ``<!-- resource-engine:begin -->`` and ``<!-- resource-engine:end -->``; the rest
15
+ of those files is never touched. ``.resource-engine/ai-lock.json`` records the
16
+ version, the targets and a hash of everything written, so ``ai sync --check``
17
+ can tell what is out of date and what was edited locally.
18
+
19
+ With ``mcp`` (``ai install --mcp``) the development MCP server
20
+ (``resource-engine mcp``) is also registered for the targets' agents:
21
+ ``.mcp.json`` (claude), ``.cursor/mcp.json`` (cursor) and ``.vscode/mcp.json``
22
+ (copilot). Only the ``resource-engine`` entry of those files is managed; other
23
+ servers and keys are kept.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import hashlib
29
+ import json
30
+ from collections.abc import Iterable, Sequence
31
+ from dataclasses import dataclass, field
32
+ from pathlib import Path
33
+ from typing import Any
34
+
35
+ from resource_engine_devtools.ai.example import SKILL_DIR
36
+
37
+ TEMPLATES = Path(__file__).parent / "templates"
38
+ TARGETS = ("claude", "agents", "cursor", "copilot")
39
+ DEFAULT_TARGETS = ("claude", "agents")
40
+ LOCK = Path(".resource-engine/ai-lock.json")
41
+ BEGIN = "<!-- resource-engine:begin -->"
42
+ END = "<!-- resource-engine:end -->"
43
+ CLAUDE_SKILL = Path(".claude/skills/resource-engine")
44
+ SERVER_NAME = "resource-engine"
45
+ #: MCP configuration per target: file, key holding the servers, VS Code style entry.
46
+ MCP_CONFIGS: dict[str, tuple[Path, str, bool]] = {
47
+ "claude": (Path(".mcp.json"), "mcpServers", False),
48
+ "cursor": (Path(".cursor/mcp.json"), "mcpServers", False),
49
+ "copilot": (Path(".vscode/mcp.json"), "servers", True),
50
+ }
51
+ PLAIN_SKILL = Path(".resource-engine/skill")
52
+
53
+
54
+ def version() -> str:
55
+ """The installed devtools version (the skill ships with it)."""
56
+ from importlib.metadata import PackageNotFoundError
57
+ from importlib.metadata import version as dist_version
58
+
59
+ try:
60
+ return dist_version("resource-engine-devtools")
61
+ except PackageNotFoundError: # pragma: no cover - running from a source tree
62
+ from resource_engine import __version__
63
+
64
+ return __version__
65
+
66
+
67
+ @dataclass
68
+ class Plan:
69
+ """What an install writes: whole files and managed blocks, by path."""
70
+
71
+ targets: tuple[str, ...]
72
+ skill_path: Path
73
+ files: dict[Path, str] = field(default_factory=dict)
74
+ blocks: dict[Path, str] = field(default_factory=dict)
75
+ #: MCP configuration file → (key holding the servers, the managed entry).
76
+ servers: dict[Path, tuple[str, dict[str, Any]]] = field(default_factory=dict)
77
+ mcp_command: list[str] | None = None
78
+
79
+
80
+ @dataclass
81
+ class Finding:
82
+ """What syncing found for one installed file: missing, out of date, modified, stale or
83
+ unlocked."""
84
+
85
+ path: str
86
+ state: str # missing | out_of_date | modified | stale | unlocked
87
+ message: str
88
+
89
+ def to_dict(self) -> dict[str, str]:
90
+ """The finding as JSON-ready data."""
91
+ return {"path": self.path, "state": self.state, "message": self.message}
92
+
93
+
94
+ def parse_targets(raw: str | Sequence[str] | None) -> tuple[str, ...]:
95
+ """The assistants to install for, from a comma-separated text or a list (all of them by
96
+ default)."""
97
+ if raw is None:
98
+ return DEFAULT_TARGETS
99
+ items = raw.split(",") if isinstance(raw, str) else list(raw)
100
+ targets = tuple(dict.fromkeys(t.strip().lower() for t in items if t.strip()))
101
+ unknown = [t for t in targets if t not in TARGETS]
102
+ if unknown or not targets:
103
+ raise SystemExit(
104
+ f"Unknown targets: {', '.join(unknown) or '(none)'}. Use: {', '.join(TARGETS)}"
105
+ )
106
+ return targets
107
+
108
+
109
+ def default_mcp_command(root: Path) -> list[str]:
110
+ """``uv run resource-engine mcp`` in uv projects, else ``resource-engine mcp``."""
111
+ if (root / "uv.lock").is_file():
112
+ return ["uv", "run", "resource-engine", "mcp"]
113
+ return ["resource-engine", "mcp"]
114
+
115
+
116
+ def mcp_entry(command: Sequence[str], *, vscode: bool) -> dict[str, Any]:
117
+ """The MCP server entry an assistant's configuration needs (VS Code's adds "type": "stdio")."""
118
+ entry: dict[str, Any] = {"command": command[0], "args": list(command[1:])}
119
+ return {"type": "stdio", **entry} if vscode else entry
120
+
121
+
122
+ def plan(
123
+ targets: Sequence[str], context: str | None, mcp_command: Sequence[str] | None = None
124
+ ) -> Plan:
125
+ """The files to write for targets: the skill, the context file and the MCP configuration."""
126
+ skill_path = CLAUDE_SKILL if "claude" in targets else PLAIN_SKILL
127
+ result = Plan(tuple(targets), skill_path)
128
+ if mcp_command:
129
+ result.mcp_command = list(mcp_command)
130
+ for target in targets:
131
+ if target in MCP_CONFIGS:
132
+ path, key, vscode = MCP_CONFIGS[target]
133
+ result.servers[path] = (key, mcp_entry(mcp_command, vscode=vscode))
134
+ for source in sorted(SKILL_DIR.rglob("*")):
135
+ if source.is_file() and "__pycache__" not in source.parts:
136
+ result.files[skill_path / source.relative_to(SKILL_DIR)] = source.read_text(
137
+ encoding="utf-8"
138
+ )
139
+ result.files[skill_path / "project.md"] = context or _NO_CONTEXT
140
+ block = _render(
141
+ (TEMPLATES / "agents_block.md").read_text(encoding="utf-8"),
142
+ version=version(),
143
+ skill_path=skill_path.as_posix(),
144
+ )
145
+ if "agents" in targets:
146
+ result.blocks[Path("AGENTS.md")] = block
147
+ if "copilot" in targets:
148
+ result.blocks[Path(".github/copilot-instructions.md")] = block
149
+ if "cursor" in targets:
150
+ rule = (TEMPLATES / "cursor_rule.mdc").read_text(encoding="utf-8")
151
+ result.files[Path(".cursor/rules/resource-engine.mdc")] = rule.replace("{block}", block)
152
+ return result
153
+
154
+
155
+ _NO_CONTEXT = """\
156
+ # Project catalogue
157
+
158
+ No registry was found when this file was generated. Set
159
+ `[tool.resource-engine] registry = "pkg.bootstrap:registry"` in pyproject.toml
160
+ and run `resource-engine ai sync`, or run `resource-engine inspect --json`.
161
+ """
162
+
163
+
164
+ def _render(template: str, **values: str) -> str:
165
+ for key, value in values.items():
166
+ template = template.replace("{" + key + "}", value)
167
+ return template
168
+
169
+
170
+ # ---------------------------------------------------------------- writing
171
+
172
+
173
+ def install(
174
+ root: Path,
175
+ targets: Sequence[str],
176
+ context: str | None,
177
+ *,
178
+ mcp_command: Sequence[str] | None = None,
179
+ ) -> dict[str, Any]:
180
+ """Write the plan under ``root``; returns a summary (written, removed, kept).
181
+ ``mcp_command``: register the development MCP server with this command."""
182
+ lock = read_lock(root)
183
+ the_plan = plan(targets, context, mcp_command)
184
+ servers = {p: merge_server(_read(root / p), key, entry, p) for p, (key, entry) in
185
+ the_plan.servers.items()} # fmt: skip
186
+ written: list[str] = []
187
+ for path, content in the_plan.files.items():
188
+ if _write(root / path, content):
189
+ written.append(path.as_posix())
190
+ for path, block in the_plan.blocks.items():
191
+ if _write(root / path, merge_block(_read(root / path), block)):
192
+ written.append(path.as_posix())
193
+ for path, content in servers.items():
194
+ if _write(root / path, content):
195
+ written.append(f"{path.as_posix()} ({SERVER_NAME} server)")
196
+ removed = _remove_stale(root, lock, the_plan)
197
+ hashes = {p.as_posix(): _hash(c) for p, c in the_plan.files.items()}
198
+ hashes |= {f"{p.as_posix()}#block": _hash(b) for p, b in the_plan.blocks.items()}
199
+ hashes |= {f"{p.as_posix()}#mcp": _entry_hash(e) for p, (_, e) in the_plan.servers.items()}
200
+ data: dict[str, Any] = {
201
+ "version": version(),
202
+ "targets": list(the_plan.targets),
203
+ "skill_path": the_plan.skill_path.as_posix(),
204
+ "files": hashes,
205
+ }
206
+ if the_plan.mcp_command:
207
+ data["mcp_command"] = the_plan.mcp_command
208
+ write_lock(root, data)
209
+ return {
210
+ "version": version(),
211
+ "targets": list(the_plan.targets),
212
+ "skill_path": the_plan.skill_path.as_posix(),
213
+ "written": written,
214
+ "removed": removed,
215
+ "mcp_command": the_plan.mcp_command,
216
+ "lock": LOCK.as_posix(),
217
+ }
218
+
219
+
220
+ def _remove_stale(root: Path, lock: dict[str, Any] | None, the_plan: Plan) -> list[str]:
221
+ """Files an earlier install wrote that the new plan no longer has, when the
222
+ user has not edited them since."""
223
+ if not lock:
224
+ return []
225
+ keep = {p.as_posix() for p in the_plan.files}
226
+ keep |= {f"{p.as_posix()}#mcp" for p in the_plan.servers}
227
+ removed = []
228
+ for name, digest in lock.get("files", {}).items():
229
+ if name.endswith("#block") or name in keep:
230
+ continue
231
+ if name.endswith("#mcp"):
232
+ if _remove_server(root, name.removesuffix("#mcp"), digest):
233
+ removed.append(f"{name.removesuffix('#mcp')} ({SERVER_NAME} server)")
234
+ continue
235
+ path = root / name
236
+ if path.is_file() and _hash(path.read_text(encoding="utf-8")) == digest:
237
+ path.unlink()
238
+ removed.append(name)
239
+ _prune(path.parent, root)
240
+ return removed
241
+
242
+
243
+ def _prune(directory: Path, root: Path) -> None:
244
+ while directory != root and directory.is_dir() and not any(directory.iterdir()):
245
+ directory.rmdir()
246
+ directory = directory.parent
247
+
248
+
249
+ def merge_block(current: str | None, block: str) -> str:
250
+ """Replace the managed block in ``current`` (or append it)."""
251
+ managed = f"{BEGIN}\n{block.rstrip()}\n{END}\n"
252
+ if not current:
253
+ return managed
254
+ start, end = current.find(BEGIN), current.find(END)
255
+ if start != -1 and end > start:
256
+ return current[:start] + managed + current[end + len(END) :].lstrip("\n")
257
+ return current.rstrip("\n") + "\n\n" + managed
258
+
259
+
260
+ def _load_config(current: str | None, path: Path) -> dict[str, Any]:
261
+ if not current or not current.strip():
262
+ return {}
263
+ try:
264
+ data = json.loads(current)
265
+ except ValueError:
266
+ raise SystemExit(
267
+ f"{path} is not plain JSON (comments?); add the {SERVER_NAME} server by hand "
268
+ "or remove the comments, then run the command again"
269
+ ) from None
270
+ if not isinstance(data, dict):
271
+ raise SystemExit(f"{path} does not hold a JSON object")
272
+ return data
273
+
274
+
275
+ def merge_server(current: str | None, key: str, entry: dict[str, Any], path: Path) -> str:
276
+ """``current`` (an MCP configuration) with the managed server entry set."""
277
+ data = _load_config(current, path)
278
+ servers = data.get(key)
279
+ if not isinstance(servers, dict):
280
+ servers = {}
281
+ data[key] = {**servers, SERVER_NAME: entry}
282
+ return json.dumps(data, indent=2, ensure_ascii=False) + "\n"
283
+
284
+
285
+ def extract_server(current: str | None, key: str) -> dict[str, Any] | None:
286
+ """The engine's server entry in an MCP configuration file, if it has one."""
287
+ try:
288
+ data = json.loads(current) if current else None
289
+ except ValueError:
290
+ return None
291
+ servers = data.get(key) if isinstance(data, dict) else None
292
+ entry = servers.get(SERVER_NAME) if isinstance(servers, dict) else None
293
+ return entry if isinstance(entry, dict) else None
294
+
295
+
296
+ def _remove_server(root: Path, name: str, digest: str) -> bool:
297
+ """Drop the managed entry of ``name`` (a configuration file relative to
298
+ ``root``) when it is unedited; the file too when nothing else is left."""
299
+ key = next((k for p, k, _ in MCP_CONFIGS.values() if p.as_posix() == name), None)
300
+ path = root / name
301
+ current = _read(path)
302
+ entry = extract_server(current, key) if key else None
303
+ if key is None or entry is None or _entry_hash(entry) != digest:
304
+ return False
305
+ data = json.loads(current or "{}")
306
+ del data[key][SERVER_NAME]
307
+ if not data[key]:
308
+ del data[key]
309
+ if data:
310
+ path.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", "utf-8")
311
+ else:
312
+ path.unlink()
313
+ _prune(path.parent, root)
314
+ return True
315
+
316
+
317
+ def _entry_hash(entry: dict[str, Any]) -> str:
318
+ return _hash(json.dumps(entry, sort_keys=True))
319
+
320
+
321
+ def extract_block(current: str | None) -> str | None:
322
+ """The block the installer manages inside a shared file (between its markers), if any."""
323
+ if not current:
324
+ return None
325
+ start, end = current.find(BEGIN), current.find(END)
326
+ if start == -1 or end < start:
327
+ return None
328
+ return current[start + len(BEGIN) : end].strip("\n") + "\n"
329
+
330
+
331
+ def _write(path: Path, content: str) -> bool:
332
+ if _read(path) == content:
333
+ return False
334
+ path.parent.mkdir(parents=True, exist_ok=True)
335
+ path.write_text(content, encoding="utf-8")
336
+ return True
337
+
338
+
339
+ def _read(path: Path) -> str | None:
340
+ return path.read_text(encoding="utf-8") if path.is_file() else None
341
+
342
+
343
+ def _hash(text: str) -> str:
344
+ return hashlib.sha256(text.encode()).hexdigest()
345
+
346
+
347
+ def read_lock(root: Path) -> dict[str, Any] | None:
348
+ """The installer's lock file (what was written, with hashes), if there is one."""
349
+ path = root / LOCK
350
+ return json.loads(path.read_text(encoding="utf-8")) if path.is_file() else None
351
+
352
+
353
+ def write_lock(root: Path, data: dict[str, Any]) -> None:
354
+ """Write the installer's lock file."""
355
+ _write(root / LOCK, json.dumps(data, indent=2, sort_keys=True) + "\n")
356
+
357
+
358
+ # ---------------------------------------------------------------- checking
359
+
360
+
361
+ def check(root: Path, context: str | None) -> tuple[dict[str, Any] | None, list[Finding]]:
362
+ """Compare what is installed with what an install would write now."""
363
+ lock = read_lock(root)
364
+ if lock is None:
365
+ return None, [Finding(LOCK.as_posix(), "missing", "run resource-engine ai install")]
366
+ findings: list[Finding] = []
367
+ if lock.get("version") != version():
368
+ findings.append(
369
+ Finding(
370
+ LOCK.as_posix(),
371
+ "out_of_date",
372
+ f"installed from resource-engine {lock.get('version')}, the package is {version()}",
373
+ )
374
+ )
375
+ the_plan = plan(lock.get("targets", DEFAULT_TARGETS), context, lock.get("mcp_command"))
376
+ locked = lock.get("files", {})
377
+ expected: dict[str, Any] = {p.as_posix(): c for p, c in the_plan.files.items()}
378
+ expected |= {f"{p.as_posix()}#block": b for p, b in the_plan.blocks.items()}
379
+ expected |= {f"{p.as_posix()}#mcp": e for p, (_, e) in the_plan.servers.items()}
380
+ keys = {f"{p.as_posix()}#mcp": key for p, (key, _) in the_plan.servers.items()}
381
+ for name, content in expected.items():
382
+ if name.endswith("#mcp"):
383
+ current_entry = extract_server(_read(root / name.removesuffix("#mcp")), keys[name])
384
+ if current_entry is None:
385
+ findings.append(Finding(name, "missing", f"no {SERVER_NAME} MCP server entry"))
386
+ elif current_entry != content:
387
+ edited = name in locked and _entry_hash(current_entry) != locked[name]
388
+ findings.append(
389
+ Finding(
390
+ name,
391
+ "modified" if edited else "out_of_date",
392
+ "MCP server entry edited locally; ai sync will overwrite it"
393
+ if edited
394
+ else "MCP server entry differs from the current command",
395
+ )
396
+ )
397
+ continue
398
+ path = root / name.removesuffix("#block")
399
+ current = _read(path)
400
+ if name.endswith("#block"):
401
+ current = extract_block(current)
402
+ if current is None:
403
+ findings.append(Finding(name, "missing", "not installed"))
404
+ elif current != content:
405
+ edited = name in locked and _hash(current) != locked[name]
406
+ findings.append(
407
+ Finding(
408
+ name,
409
+ "modified" if edited else "out_of_date",
410
+ "edited locally; ai sync will overwrite it"
411
+ if edited
412
+ else "differs from the current skill or project",
413
+ )
414
+ )
415
+ for name in sorted(set(locked) - set(expected)):
416
+ if (root / name.removesuffix("#block").removesuffix("#mcp")).exists():
417
+ findings.append(Finding(name, "stale", "no longer part of the skill"))
418
+ return lock, findings
419
+
420
+
421
+ def summary(findings: Iterable[Finding]) -> str:
422
+ """Findings as text, one per line."""
423
+ lines = [f"{f.state:<12} {f.path}: {f.message}" for f in findings]
424
+ return "\n".join(lines)
@@ -0,0 +1,130 @@
1
+ ---
2
+ name: resource-engine
3
+ description: Build and change business backends written with Resource Engine (Python) - declarative resources, CRUD, state machines and transitions, actions, lifecycle hooks, permissions, events and documents. Use it whenever the code imports resource_engine, defines a Resource, Action, StateMachine or hook, or the task is adding or changing a resource, operation, transition, permission or event in such a project.
4
+ ---
5
+
6
+ # Resource Engine
7
+
8
+ Resource Engine runs every operation of a resource through one lifecycle:
9
+ validation, permissions, hooks, persistence in one transaction, audit, events
10
+ after commit. You declare *what* exists; the engine does the plumbing. Your code
11
+ is the domain (entities, rules, state machines) and the business logic (hooks,
12
+ actions).
13
+
14
+ Before writing code, look at the project: `resource-engine inspect --json` shows
15
+ every resource as the engine resolved it (operations, schemas, hooks in their
16
+ real order, transitions, actions, permissions). `resource-engine ai context`
17
+ prints a compact catalogue; the installed copy is `project.md` next to this file.
18
+
19
+ ## Workflow
20
+
21
+ 1. **Find the module.** Each business module has `domain/` (entities, state
22
+ machine, events, `DomainError`s), `application/` (resource, schemas, hooks,
23
+ actions) and `infrastructure/` (SQLAlchemy mapping). The composition root
24
+ registers resources (`bootstrap.py`). Follow `examples/invoices/` in this
25
+ skill: it is the reference module and runs in the framework's tests.
26
+ 2. **Write the domain first.** Plain classes or dataclasses, no framework
27
+ imports. Business rules are methods that raise a `DomainError` subclass.
28
+ 3. **Declare the resource.** See [references/resource.md](references/resource.md).
29
+ For a new module or any part of one, start from the scaffold instead of
30
+ writing the boilerplate. The part commands also declare what they write on
31
+ the resource class:
32
+
33
+ ```bash
34
+ resource-engine scaffold resource orders --package shop.orders --field customer:str --field total:Decimal --state-machine
35
+ resource-engine scaffold action orders ApplyDiscount --package shop.orders --input percent:Decimal
36
+ resource-engine scaffold state-machine Order --package shop.orders --states new,paid --transitions 'pay:new>paid'
37
+ resource-engine scaffold hook orders check_credit --package shop.orders --on before_create
38
+ resource-engine scaffold event orders OrderShipped --package shop.orders --field carrier:str
39
+ resource-engine scaffold slot orders delivery_note --package shop.orders --content-type application/pdf
40
+ resource-engine scaffold reference orders customer_id --package shop.orders --to customers
41
+ resource-engine scaffold policy orders --package shop.orders --role clerk
42
+ ```
43
+
44
+ Then follow the printed next steps and replace every `TODO` docstring
45
+ (`docs validate` reports them as RE-D010).
46
+ 4. **Add behaviour in the right place.** The resource class only declares
47
+ what the resource is; code goes in plain functions and classes it lists
48
+ (`check` RE-C008 reports methods, lambdas and declarations over 80 lines;
49
+ RE-C009 hooks and actions that write other resources' records).
50
+ - A field-level rule or invariant → a domain method, called from a hook.
51
+ - A process with states → a state machine with transitions
52
+ ([references/state-machines.md](references/state-machines.md)).
53
+ - A business operation that is not CRUD or a transition → an `Action`.
54
+ - An email → record `EmailRequested(template=..., to=..., context=...)` in
55
+ a hook or action inside the transaction; the worker sends it after the
56
+ commit (`Mailer.router()`). Templates live in `templates/email/`
57
+ (`<name>.subject.txt`, `.txt`, `.html`, per locale); `check` reports
58
+ missing ones (RE-C007).
59
+ - A text people read (an email line, a message) → write it in the
60
+ project's source language inside `_()` / `{% trans %}`; run
61
+ `resource-engine i18n extract` and `update`, and leave the `.po`
62
+ translations to translators (`docs/i18n.md`). Never translate JSON
63
+ data; errors already carry a translated `title`.
64
+ - Something else to do after the change is saved (call another system)
65
+ → record a domain event and handle it in a consumer, or an `after_commit`
66
+ hook marked `@external_effect`.
67
+ - Who may do it → permissions, not hooks: a policy in the seed or a
68
+ system-role grant for every new operation
69
+ ([references/permissions.md](references/permissions.md)).
70
+ 5. **Document with docstrings** in the functional convention
71
+ ([references/docstrings.md](references/docstrings.md)). Documentation is
72
+ generated from them and checked in CI.
73
+ 6. **Map the entity** in `infrastructure/` with SQLAlchemy imperative mapping
74
+ and register the resource in the composition root.
75
+ 7. **Test** against the in-memory adapters (`resource_engine.testing`), then
76
+ over HTTP or SQLite if the change touches them
77
+ ([references/testing.md](references/testing.md)).
78
+ 8. **Verify**, and fix everything reported:
79
+
80
+ ```bash
81
+ resource-engine check --json # architecture, hook/effect and gate lints
82
+ resource-engine docs validate --strict
83
+ pytest
84
+ resource-engine ai sync --check # skill and project context up to date
85
+ ```
86
+
87
+ With the `resource-engine` MCP server configured (`resource-engine mcp`),
88
+ call its `check`, `docs_validate`, `explain_error` and `scaffold_*` tools
89
+ instead of shell commands.
90
+
91
+ ## Rules that must not be broken
92
+
93
+ - **No external effects before commit.** Hooks before `after_commit` and
94
+ `Action.execute` run inside the transaction: no HTTP calls, e-mails, messages
95
+ or payments there. Record a domain event (`ctx.record_event`) or use an
96
+ `after_commit` hook marked `@external_effect`. (`check`: RE-C002; engine:
97
+ RE-E104.)
98
+ - **State changes only through transitions.** Never put the state field in a
99
+ `create` or `update` schema (RE-E004 at registration), and never assign it
100
+ in a hook or an action: that skips the transition's permission, hooks and
101
+ event.
102
+ - **`domain/` imports nothing from FastAPI, SQLAlchemy, Pydantic or HTTP
103
+ clients** (`check`: RE-C001).
104
+ - **Business processes are actions or transitions, not hooks.** Hooks guard
105
+ and enrich an operation; they do not start new ones.
106
+ - **Permissions live in policies and system roles**, never in `if user...`
107
+ checks inside hooks.
108
+ - **`after_commit` cannot change the operation.** The transaction is over: no
109
+ `ctx.record_event`, `ctx.repository()`, `ctx.uow` or changes to `ctx.entity`
110
+ (`check`: RE-C003).
111
+ - **Document every functional element** (resource, operations, state machine,
112
+ states, transitions, actions) with docstrings in the convention.
113
+
114
+ Common mistakes and their fixes: [references/anti-patterns.md](references/anti-patterns.md).
115
+
116
+ ## References
117
+
118
+ | File | Read it when |
119
+ |---|---|
120
+ | [resource.md](references/resource.md) | Declaring or changing a resource, schemas, operations, actions, documents |
121
+ | [lifecycle.md](references/lifecycle.md) | Choosing a hook point; understanding order, rollback and events |
122
+ | [state-machines.md](references/state-machines.md) | Adding states or transitions |
123
+ | [permissions.md](references/permissions.md) | Who may do what, fields, tenants |
124
+ | [docstrings.md](references/docstrings.md) | Writing docstrings that `docs validate` accepts |
125
+ | [testing.md](references/testing.md) | Writing tests |
126
+ | [errors.md](references/errors.md) | An `RE-*` code shows up |
127
+ | [anti-patterns.md](references/anti-patterns.md) | Before finishing: check your code against it |
128
+
129
+ Engine errors carry a stable code, a hint and a documentation link: read the
130
+ hint, it usually says exactly what to change.
@@ -0,0 +1,7 @@
1
+ # Reference module: invoices
2
+
3
+ A complete, tested module: `domain/` (entity, state machine, events),
4
+ `application/` (resource, schemas, hooks, actions), `infrastructure/`
5
+ (SQLAlchemy imperative mapping), `bootstrap.py` (composition root),
6
+ `authz.py` (example policies) and `tests/`. It is the framework's own example
7
+ and runs in its test suite, so it matches the installed version.