@tera-system/core 0.2.8 → 0.2.11

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 (32) hide show
  1. package/MANIFEST.json +7 -7
  2. package/RELEASES.md +37 -0
  3. package/agents/domain-research-agent.md +25 -4
  4. package/assets/architecture/README.md +30 -0
  5. package/assets/structurizr-mcp/README.md +134 -0
  6. package/assets/structurizr-mcp/pyproject.toml +19 -0
  7. package/assets/structurizr-mcp/src/structurizr_mcp/__init__.py +0 -0
  8. package/assets/structurizr-mcp/src/structurizr_mcp/config.py +59 -0
  9. package/assets/structurizr-mcp/src/structurizr_mcp/server.py +101 -0
  10. package/assets/structurizr-mcp/src/structurizr_mcp/tools/__init__.py +0 -0
  11. package/assets/structurizr-mcp/src/structurizr_mcp/tools/api.py +63 -0
  12. package/assets/structurizr-mcp/src/structurizr_mcp/tools/dsl.py +36 -0
  13. package/assets/structurizr-mcp/src/structurizr_mcp/tools/export.py +258 -0
  14. package/assets/structurizr-mcp/src/structurizr_mcp/tools/validate.py +43 -0
  15. package/assets/structurizr-mcp/uv.lock +770 -0
  16. package/assets/tera-workshop/client-templates/financial/MySign.png +0 -0
  17. package/assets/tera-workshop/client-templates/financial/V1.png +0 -0
  18. package/assets/tera-workshop/client-templates/financial/V2.png +0 -0
  19. package/assets/tera-workshop/client-templates/financial/VOUCHER_DESIGN_SPEC.md +12 -12
  20. package/assets/tera-workshop/client-templates/financial/VOUCHER_HEADER_PROMPT.md +79 -0
  21. package/assets/tera-workshop/client-templates/financial/VOUCHER_PAYMENT_TEMPLATE.html +76 -172
  22. package/assets/tera-workshop/client-templates/financial/VOUCHER_RECEIPT_TEMPLATE.html +76 -175
  23. package/core/tera-system/AGENT_PERMISSION_MODEL.md +13 -3
  24. package/core/tera-system/TERA_DISTRIBUTION_POLICY.md +26 -5
  25. package/core/tera-system/TOOLING_AND_MCP_POLICY.md +22 -0
  26. package/core/tera-system/TeraArchitectureMap.md +2 -1
  27. package/core/tera-system/TeraPolicyMap.md +4 -2
  28. package/core/tera-system/TeraSystemMaintenanceChecklist.md +8 -0
  29. package/core/tera-system/runtime/DOMAIN_INTELLIGENCE_PROTOCOL.md +42 -0
  30. package/opencode.tera.example.json +3 -3
  31. package/package.json +1 -1
  32. package/tools/tera-tooling.ps1 +128 -0
@@ -0,0 +1,258 @@
1
+ import json
2
+ import subprocess
3
+ from pathlib import Path
4
+ from structurizr_mcp.config import config
5
+ from structurizr_mcp.tools.dsl import _resolve
6
+
7
+ DOCKER_IMAGE = "structurizr/structurizr"
8
+ PLAYWRIGHT_IMAGE = "mcr.microsoft.com/playwright:v1.44.0-jammy"
9
+ CONTAINER_WORKSPACE = "/usr/local/structurizr"
10
+
11
+ # Formats exported purely from the DSL — no running Structurizr server needed.
12
+ CLI_ONLY_FORMATS = ("mermaid", "plantuml", "json", "static", "websequencediagrams")
13
+ # Formats rendered by the Structurizr web UI via a headless browser — require a running server.
14
+ SERVER_FORMATS = ("svg", "png")
15
+
16
+ SUPPORTED_FORMATS = CLI_ONLY_FORMATS + SERVER_FORMATS
17
+
18
+ _EXTENSION_MAP = {
19
+ "mermaid": ".md",
20
+ "plantuml": ".puml",
21
+ "svg": ".svg",
22
+ "png": ".png",
23
+ "json": ".json",
24
+ "static": ".html",
25
+ "websequencediagrams": ".txt",
26
+ }
27
+
28
+
29
+ def _container_path(local: Path, workspace_dir: Path) -> str:
30
+ """Translate a local absolute path to its equivalent inside the Docker container."""
31
+ return f"{CONTAINER_WORKSPACE}/{local.relative_to(workspace_dir)}"
32
+
33
+
34
+ def _docker_url(url: str) -> str:
35
+ """Replace localhost/127.0.0.1 with host.docker.internal so containers can reach the host."""
36
+ return url.replace("localhost", "host.docker.internal").replace("127.0.0.1", "host.docker.internal")
37
+
38
+
39
+ def _get_view_keys() -> list[str]:
40
+ """Fetch all view keys from the running Structurizr workspace."""
41
+ from structurizr_mcp.tools.api import get_workspace_json
42
+ workspace = get_workspace_json()
43
+ views_section = workspace.get("views", {})
44
+ keys = []
45
+ for view_type in (
46
+ "systemLandscapeViews",
47
+ "systemContextViews",
48
+ "containerViews",
49
+ "componentViews",
50
+ "dynamicViews",
51
+ "deploymentViews",
52
+ "filteredViews",
53
+ "customViews",
54
+ ):
55
+ for view in views_section.get(view_type, []):
56
+ key = view.get("key")
57
+ if key:
58
+ keys.append(key)
59
+ return keys
60
+
61
+
62
+ def _export_svg_via_browser(
63
+ view_keys: list[str],
64
+ out_resolved: Path,
65
+ workspace_dir: Path,
66
+ structurizr_url: str,
67
+ fmt: str = "svg",
68
+ ) -> dict:
69
+ """
70
+ Export diagrams as SVG using a Playwright headless browser pointed at the
71
+ running Structurizr server. Captures diagrams exactly as they appear in the
72
+ Structurizr web UI.
73
+ """
74
+ # Parse port from structurizr_url (default 8080)
75
+ import urllib.parse as _urlparse
76
+ parsed = _urlparse.urlparse(structurizr_url)
77
+ remote_host = parsed.hostname or "localhost"
78
+ remote_port = parsed.port or 8080
79
+ # Convert localhost → host.docker.internal for the proxy target (container → host)
80
+ docker_host = remote_host.replace("localhost", "host.docker.internal").replace("127.0.0.1", "host.docker.internal")
81
+
82
+ container_out = _container_path(out_resolved, workspace_dir)
83
+ ext = ".svg" if fmt == "svg" else ".png"
84
+
85
+ tmp_dir = workspace_dir / ".playwright-tmp"
86
+ tmp_dir.mkdir(exist_ok=True)
87
+ script_path = tmp_dir / "export-diagrams.js"
88
+
89
+ script = f"""
90
+ const {{ chromium }} = require('playwright');
91
+ const net = require('net');
92
+ const fs = require('fs');
93
+ const path = require('path');
94
+
95
+ const views = {json.dumps(view_keys)};
96
+ const outputDir = '{container_out}';
97
+ // Structurizr validates the Host header and rejects 'host.docker.internal'.
98
+ // We create a TCP proxy inside the container: localhost:{remote_port} → {docker_host}:{remote_port}
99
+ // Playwright connects to localhost, so the Host header is 'localhost:{remote_port}' which Structurizr accepts.
100
+ const PROXY_PORT = {remote_port};
101
+ const REMOTE_HOST = '{docker_host}';
102
+ const REMOTE_PORT = {remote_port};
103
+ const baseUrl = 'http://localhost:' + PROXY_PORT;
104
+
105
+ const proxyServer = net.createServer(socket => {{
106
+ const remote = net.connect(REMOTE_PORT, REMOTE_HOST);
107
+ socket.pipe(remote);
108
+ remote.pipe(socket);
109
+ socket.on('error', () => remote.destroy());
110
+ remote.on('error', () => socket.destroy());
111
+ }});
112
+
113
+ (async () => {{
114
+ await new Promise(resolve => proxyServer.listen(PROXY_PORT, '127.0.0.1', resolve));
115
+ console.log('Proxy listening on localhost:' + PROXY_PORT + ' → ' + REMOTE_HOST + ':' + REMOTE_PORT);
116
+
117
+ const browser = await chromium.launch();
118
+ const page = await browser.newPage();
119
+ const errors = [];
120
+
121
+ for (const viewKey of views) {{
122
+ try {{
123
+ const url = baseUrl + '/workspace/1/diagrams#' + encodeURIComponent(viewKey);
124
+ console.log('Exporting: ' + viewKey);
125
+ await page.goto(url, {{ waitUntil: 'networkidle', timeout: 30000 }});
126
+
127
+ // Wait until Structurizr has loaded and the export function is available
128
+ await page.waitForFunction(
129
+ () => typeof structurizr !== 'undefined' &&
130
+ structurizr.diagram &&
131
+ typeof structurizr.diagram.exportCurrentDiagramToSVG === 'function',
132
+ {{ timeout: 30000 }}
133
+ );
134
+ // Extra settle time for layout engine to finish
135
+ await page.waitForTimeout(1500);
136
+
137
+ const svgMarkup = await page.evaluate(
138
+ () => structurizr.diagram.exportCurrentDiagramToSVG({{}}).markup
139
+ );
140
+
141
+ const outFile = path.join(outputDir, 'structurizr-' + viewKey + '{ext}');
142
+ fs.writeFileSync(outFile, svgMarkup);
143
+ console.log('Written: ' + outFile);
144
+ }} catch (err) {{
145
+ errors.push(viewKey + ': ' + err.message);
146
+ console.error('Failed ' + viewKey + ': ' + err.message);
147
+ }}
148
+ }}
149
+
150
+ await browser.close();
151
+ proxyServer.close();
152
+ if (errors.length > 0) {{
153
+ process.stderr.write('Errors: ' + errors.join(', ') + '\\n');
154
+ process.exit(1);
155
+ }}
156
+ }})();
157
+ """
158
+
159
+ # package.json lets npm install playwright and caches node_modules in the workspace
160
+ # dir (which is a Docker volume), so only the first run is slow.
161
+ pkg_json = tmp_dir / "package.json"
162
+ pkg_json.write_text(json.dumps({
163
+ "name": "playwright-export",
164
+ "version": "1.0.0",
165
+ "dependencies": {"playwright": "1.44.0"},
166
+ }))
167
+ script_path.write_text(script)
168
+
169
+ container_tmp = _container_path(tmp_dir, workspace_dir)
170
+ container_script = _container_path(script_path, workspace_dir)
171
+
172
+ try:
173
+ result = subprocess.run(
174
+ [
175
+ "docker", "run", "--rm",
176
+ "--add-host=host.docker.internal:host-gateway",
177
+ "-v", f"{workspace_dir}:{CONTAINER_WORKSPACE}",
178
+ "-e", "PLAYWRIGHT_BROWSERS_PATH=/ms-playwright",
179
+ PLAYWRIGHT_IMAGE,
180
+ "bash", "-c",
181
+ f"cd {container_tmp} && npm install --prefer-offline --silent 2>/dev/null && node {container_script}",
182
+ ],
183
+ capture_output=True,
184
+ text=True,
185
+ )
186
+ output = (result.stdout + result.stderr).strip()
187
+ if result.returncode != 0:
188
+ raise RuntimeError(f"Playwright SVG export failed:\n{output}")
189
+ finally:
190
+ script_path.unlink(missing_ok=True)
191
+ pkg_json.unlink(missing_ok=True)
192
+
193
+ files = [str(p) for p in sorted(out_resolved.glob(f"*{ext}"))]
194
+ return {"files": files, "output": output}
195
+
196
+
197
+ def export_diagrams(path: str, format: str = "mermaid", output_dir: str | None = None, workspace: str | None = None) -> dict:
198
+ """
199
+ Export diagrams from a Structurizr DSL file.
200
+
201
+ CLI formats (mermaid, plantuml, json, static, websequencediagrams) use
202
+ Docker (structurizr/structurizr export) and work without a running server.
203
+
204
+ SVG and PNG use a Playwright headless browser (mcr.microsoft.com/playwright)
205
+ that connects to the running Structurizr server and captures diagrams exactly
206
+ as they appear in the web UI. Both Docker images must be available.
207
+
208
+ Args:
209
+ path: Path to the .dsl file (relative to the selected workspace).
210
+ format: Output format — mermaid (default), plantuml, svg, png,
211
+ json, static, websequencediagrams.
212
+ output_dir: Where to write exported files (relative to the selected workspace).
213
+ Defaults to the same directory as the DSL file.
214
+ workspace: Sub-directory under STRUCTURIZR_WORKSPACE_DIR to target. Defaults to
215
+ STRUCTURIZR_DEFAULT_WORKSPACE, then to the base directory.
216
+
217
+ Returns a dict with 'files' (list of output paths) and 'output' (raw CLI output).
218
+ """
219
+ fmt = format.lower()
220
+ if fmt not in SUPPORTED_FORMATS:
221
+ raise ValueError(f"Unsupported format '{format}'. Choose from: {', '.join(SUPPORTED_FORMATS)}")
222
+
223
+ workspace_dir = config.effective_workspace_dir(workspace)
224
+ resolved = _resolve(path, workspace)
225
+ if not resolved.exists():
226
+ raise FileNotFoundError(f"File not found: {resolved}")
227
+
228
+ if output_dir is None:
229
+ out_resolved = resolved.parent
230
+ else:
231
+ out_resolved = _resolve(output_dir, workspace)
232
+ out_resolved.mkdir(parents=True, exist_ok=True)
233
+
234
+ if fmt in SERVER_FORMATS:
235
+ view_keys = _get_view_keys()
236
+ return _export_svg_via_browser(view_keys, out_resolved, workspace_dir, config.structurizr_url, fmt)
237
+
238
+ # CLI-only formats: use structurizr/structurizr export
239
+ cmd = [
240
+ "docker", "run", "--rm",
241
+ "--add-host=host.docker.internal:host-gateway",
242
+ "-v", f"{workspace_dir}:{CONTAINER_WORKSPACE}",
243
+ DOCKER_IMAGE, "export",
244
+ "-w", _container_path(resolved, workspace_dir),
245
+ "-f", fmt,
246
+ "-o", _container_path(out_resolved, workspace_dir),
247
+ ]
248
+
249
+ result = subprocess.run(cmd, capture_output=True, text=True)
250
+ output = (result.stdout + result.stderr).strip()
251
+
252
+ if result.returncode != 0:
253
+ raise RuntimeError(f"Structurizr export failed:\n{output}")
254
+
255
+ ext = _EXTENSION_MAP.get(fmt, f".{fmt}")
256
+ files = [str(p) for p in sorted(out_resolved.glob(f"*{ext}"))]
257
+
258
+ return {"files": files, "output": output}
@@ -0,0 +1,43 @@
1
+ import subprocess
2
+ from pathlib import Path
3
+ from structurizr_mcp.config import config
4
+ from structurizr_mcp.tools.dsl import _resolve
5
+ from structurizr_mcp.tools.export import DOCKER_IMAGE, CONTAINER_WORKSPACE, _container_path
6
+
7
+
8
+ def validate_workspace(path: str, workspace: str | None = None) -> dict:
9
+ """
10
+ Validate a Structurizr DSL file via Docker (structurizr/structurizr validate).
11
+ Returns a dict with 'valid' (bool), 'errors' (list of str), and 'output' (raw CLI output).
12
+ """
13
+ workspace_dir = config.effective_workspace_dir(workspace)
14
+ resolved = _resolve(path, workspace)
15
+ if not resolved.exists():
16
+ raise FileNotFoundError(f"File not found: {resolved}")
17
+
18
+ result = subprocess.run(
19
+ [
20
+ "docker", "run", "--rm",
21
+ "-v", f"{workspace_dir}:{CONTAINER_WORKSPACE}",
22
+ DOCKER_IMAGE, "validate",
23
+ "-w", _container_path(resolved, workspace_dir),
24
+ ],
25
+ capture_output=True,
26
+ text=True,
27
+ )
28
+
29
+ output = (result.stdout + result.stderr).strip()
30
+ valid = result.returncode == 0
31
+ errors = _parse_errors(result.stderr or result.stdout)
32
+
33
+ return {"valid": valid, "errors": errors, "output": output}
34
+
35
+
36
+ def _parse_errors(text: str) -> list[str]:
37
+ """Extract error lines from CLI output."""
38
+ errors = []
39
+ for line in text.splitlines():
40
+ stripped = line.strip()
41
+ if stripped and any(word in stripped.lower() for word in ("error", "warning", "invalid", "unexpected")):
42
+ errors.append(stripped)
43
+ return errors