@fmatar/archlens-skill 0.0.1-Alpha-07
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.
- package/LICENSE +190 -0
- package/README.md +161 -0
- package/bin/index.js +379 -0
- package/package.json +48 -0
- package/skills/archlens-install-policy/SKILL.md +84 -0
- package/skills/archlens-install-policy/scripts/init_policy.py +325 -0
- package/src/analyzer.js +289 -0
- package/src/installer.js +200 -0
- package/src/ui.js +149 -0
- package/src/updater.js +172 -0
- package/src/upgrader.js +122 -0
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Archlens Policy & Companion Initialization Script
|
|
4
|
+
Zero-dependency CLI tool to inspect any project codebase and scaffold:
|
|
5
|
+
1. .archlens/policy.json (Clean Architecture concentric tiers)
|
|
6
|
+
2. .archlens/workbench.config.json (Visual workbench service settings)
|
|
7
|
+
3. CLAUDE.md & AGENTS.md companion guidelines (Mailbox IPC protocol)
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
import sys
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def detect_project_language(root: Path) -> str:
|
|
19
|
+
if (root / "pom.xml").exists() or (root / "build.gradle").exists() or (root / "build.gradle.kts").exists():
|
|
20
|
+
if list(root.glob("**/src/main/kotlin")):
|
|
21
|
+
return "kotlin"
|
|
22
|
+
return "java"
|
|
23
|
+
if (root / "package.json").exists() or (root / "tsconfig.json").exists():
|
|
24
|
+
return "typescript"
|
|
25
|
+
if (root / "pyproject.toml").exists() or (root / "setup.py").exists() or (root / "requirements.txt").exists():
|
|
26
|
+
return "python"
|
|
27
|
+
if (root / "Cargo.toml").exists():
|
|
28
|
+
return "rust"
|
|
29
|
+
if (root / "go.mod").exists():
|
|
30
|
+
return "go"
|
|
31
|
+
if (root / "project.clj").exists() or (root / "deps.edn").exists():
|
|
32
|
+
return "clojure"
|
|
33
|
+
return "java"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def detect_source_root(root: Path, lang: str) -> str:
|
|
37
|
+
candidates = []
|
|
38
|
+
if lang in ("java", "kotlin"):
|
|
39
|
+
candidates = ["src/main/java", "src/main/kotlin", "backend/src/main/java", "core/src/main/java", "src"]
|
|
40
|
+
elif lang == "typescript":
|
|
41
|
+
candidates = ["src", "lib", "app", "frontend/src"]
|
|
42
|
+
elif lang == "python":
|
|
43
|
+
candidates = ["src", "app", "lib", "."]
|
|
44
|
+
elif lang == "rust":
|
|
45
|
+
candidates = ["src"]
|
|
46
|
+
elif lang == "go":
|
|
47
|
+
candidates = ["pkg", "internal", "cmd", "."]
|
|
48
|
+
elif lang == "clojure":
|
|
49
|
+
candidates = ["src", "src/clj"]
|
|
50
|
+
|
|
51
|
+
for candidate in candidates:
|
|
52
|
+
candidate_path = root / candidate
|
|
53
|
+
if candidate_path.exists() and candidate_path.is_dir():
|
|
54
|
+
return candidate
|
|
55
|
+
|
|
56
|
+
return "src"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def find_common_package_prefix(source_dir: Path) -> str:
|
|
60
|
+
if not source_dir.exists():
|
|
61
|
+
return ""
|
|
62
|
+
|
|
63
|
+
java_files = list(source_dir.glob("**/*.java"))
|
|
64
|
+
if not java_files:
|
|
65
|
+
kt_files = list(source_dir.glob("**/*.kt"))
|
|
66
|
+
if kt_files:
|
|
67
|
+
java_files = kt_files
|
|
68
|
+
|
|
69
|
+
packages = []
|
|
70
|
+
for jf in java_files[:100]:
|
|
71
|
+
try:
|
|
72
|
+
content = jf.read_text(encoding="utf-8", errors="ignore")
|
|
73
|
+
match = re.search(r"^\s*package\s+([a-zA-Z0-9_.]+)\s*;", content, re.MULTILINE)
|
|
74
|
+
if match:
|
|
75
|
+
packages.append(match.group(1))
|
|
76
|
+
except Exception:
|
|
77
|
+
continue
|
|
78
|
+
|
|
79
|
+
if not packages:
|
|
80
|
+
return ""
|
|
81
|
+
|
|
82
|
+
split_pkgs = [p.split(".") for p in packages]
|
|
83
|
+
common = []
|
|
84
|
+
for parts in zip(*split_pkgs):
|
|
85
|
+
if len(set(parts)) == 1:
|
|
86
|
+
common.append(parts[0])
|
|
87
|
+
else:
|
|
88
|
+
break
|
|
89
|
+
|
|
90
|
+
known_layer_terms = {
|
|
91
|
+
"domain", "model", "models", "entity", "entities", "core",
|
|
92
|
+
"application", "app", "usecase", "usecases", "service", "services", "port", "ports",
|
|
93
|
+
"adapter", "adapters", "controller", "controllers", "gateway", "gateways",
|
|
94
|
+
"presenter", "presenters", "repository", "repositories", "resource", "resources", "api", "dto",
|
|
95
|
+
"infrastructure", "infra", "persistence", "db", "database", "config", "configuration", "web", "server"
|
|
96
|
+
}
|
|
97
|
+
while common and common[-1].lower() in known_layer_terms:
|
|
98
|
+
common.pop()
|
|
99
|
+
|
|
100
|
+
return ".".join(common)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def discover_subpackages(source_dir: Path, prefix: str) -> list[str]:
|
|
104
|
+
if not source_dir.exists():
|
|
105
|
+
return []
|
|
106
|
+
|
|
107
|
+
prefix_parts = prefix.split(".") if prefix else []
|
|
108
|
+
search_root = source_dir
|
|
109
|
+
for part in prefix_parts:
|
|
110
|
+
candidate = search_root / part
|
|
111
|
+
if candidate.exists() and candidate.is_dir():
|
|
112
|
+
search_root = candidate
|
|
113
|
+
else:
|
|
114
|
+
break
|
|
115
|
+
|
|
116
|
+
subpackages = []
|
|
117
|
+
for item in sorted(search_root.iterdir()):
|
|
118
|
+
if item.is_dir() and not item.name.startswith("."):
|
|
119
|
+
subpackages.append(item.name)
|
|
120
|
+
|
|
121
|
+
return subpackages
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def classify_layers(subpackages: list[str]) -> tuple[list[str], list[list[str]]]:
|
|
125
|
+
domain_keywords = {"domain", "model", "models", "entity", "entities", "core"}
|
|
126
|
+
app_keywords = {"application", "app", "usecase", "usecases", "service", "services", "port", "ports", "interactor"}
|
|
127
|
+
adapter_keywords = {"adapter", "adapters", "controller", "controllers", "gateway", "gateways", "presenter", "presenters", "repository", "repositories", "resource", "resources", "api", "dto", "endpoint", "endpoints"}
|
|
128
|
+
infra_keywords = {"infrastructure", "infra", "persistence", "db", "database", "config", "configuration", "web", "server", "driver", "client"}
|
|
129
|
+
|
|
130
|
+
level0 = []
|
|
131
|
+
level1 = []
|
|
132
|
+
level2 = []
|
|
133
|
+
level3 = []
|
|
134
|
+
|
|
135
|
+
for pkg in subpackages:
|
|
136
|
+
lower = pkg.lower()
|
|
137
|
+
if any(k in lower for k in domain_keywords):
|
|
138
|
+
level0.append(pkg)
|
|
139
|
+
elif any(k in lower for k in app_keywords):
|
|
140
|
+
level1.append(pkg)
|
|
141
|
+
elif any(k in lower for k in adapter_keywords):
|
|
142
|
+
level2.append(pkg)
|
|
143
|
+
elif any(k in lower for k in infra_keywords):
|
|
144
|
+
level3.append(pkg)
|
|
145
|
+
else:
|
|
146
|
+
level1.append(pkg)
|
|
147
|
+
|
|
148
|
+
if not level0:
|
|
149
|
+
level0 = ["domain"]
|
|
150
|
+
if not level1:
|
|
151
|
+
level1 = ["application"]
|
|
152
|
+
if not level2:
|
|
153
|
+
level2 = ["adapters"]
|
|
154
|
+
|
|
155
|
+
levels = [level0, level1, level2]
|
|
156
|
+
if level3:
|
|
157
|
+
levels.append(level3)
|
|
158
|
+
|
|
159
|
+
order = []
|
|
160
|
+
for group in levels:
|
|
161
|
+
for p in group:
|
|
162
|
+
if p not in order:
|
|
163
|
+
order.append(p)
|
|
164
|
+
|
|
165
|
+
return order, levels
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def generate_policy(root: Path, title: str | None = None, prefix: str | None = None) -> dict:
|
|
169
|
+
lang = detect_project_language(root)
|
|
170
|
+
src_root = detect_source_root(root, lang)
|
|
171
|
+
full_src = root / src_root
|
|
172
|
+
|
|
173
|
+
detected_prefix = prefix or find_common_package_prefix(full_src)
|
|
174
|
+
project_title = title or root.name.replace("-", " ").replace("_", " ").title()
|
|
175
|
+
|
|
176
|
+
subpackages = discover_subpackages(full_src, detected_prefix)
|
|
177
|
+
order, levels = classify_layers(subpackages)
|
|
178
|
+
|
|
179
|
+
foreign_map = {
|
|
180
|
+
"java": ["java.", "jakarta.", "org.springframework.", "io.quarkus."],
|
|
181
|
+
"kotlin": ["kotlin.", "kotlinx."],
|
|
182
|
+
"typescript": ["node:", "@types/"],
|
|
183
|
+
"python": ["sys", "os", "pathlib"],
|
|
184
|
+
"go": ["fmt", "os", "net/http"],
|
|
185
|
+
"rust": ["std::", "core::"],
|
|
186
|
+
"clojure": ["clojure."]
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
return {
|
|
190
|
+
"title": project_title,
|
|
191
|
+
"src": src_root,
|
|
192
|
+
"prefix": detected_prefix,
|
|
193
|
+
"hierarchical": True,
|
|
194
|
+
"order": order,
|
|
195
|
+
"levels": levels,
|
|
196
|
+
"foreign": foreign_map.get(lang, ["java.", "jakarta."]),
|
|
197
|
+
"omit": ["target", "build", ".git", "node_modules", ".gradle", ".idea", ".vscode"],
|
|
198
|
+
"lang": lang
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def write_workbench_config(config_dir: Path, server_url: str = "http://localhost:8088") -> None:
|
|
203
|
+
config_file = config_dir / "workbench.config.json"
|
|
204
|
+
data = {
|
|
205
|
+
"serverUrl": server_url,
|
|
206
|
+
"protocolVersion": "1.0",
|
|
207
|
+
"description": "Visual Workbench communication endpoint and mailbox IPC configuration"
|
|
208
|
+
}
|
|
209
|
+
config_file.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def update_companion_markdown(file_path: Path, server_url: str = "http://localhost:8088") -> None:
|
|
213
|
+
companion_block = f"""
|
|
214
|
+
## Archlens Clean Architecture Workbench Companion Protocol
|
|
215
|
+
|
|
216
|
+
This project is governed by the **Archlens Dynamic Clean Architecture Workbench**.
|
|
217
|
+
- **Workbench UI & API**: `{server_url}`
|
|
218
|
+
- **Architectural Policy**: `.archlens/policy.json`
|
|
219
|
+
- **Mailbox IPC**:
|
|
220
|
+
- Inbound queue: `.archlens/to-agent.json`
|
|
221
|
+
- Outbound response: `.archlens/to-viewer.json`
|
|
222
|
+
|
|
223
|
+
### Handling Mailbox Commands:
|
|
224
|
+
1. **REGEN**: Re-index AST, evaluate package dependency rules, and acknowledge.
|
|
225
|
+
2. **APPLY_PROPOSAL**: Reorganize packages to conform to concentric rings (Adapters -> Application -> Domain Core). Where an inner layer relies on an outer layer, apply the **Dependency Inversion Principle** by creating an interface port in the inner layer and implementing it in the outer layer.
|
|
226
|
+
3. **REFRESH_CRAP**: Execute test suite and report code coverage metrics.
|
|
227
|
+
"""
|
|
228
|
+
if not file_path.exists():
|
|
229
|
+
file_path.write_text(f"# Assistant Guidelines\n{companion_block}\n", encoding="utf-8")
|
|
230
|
+
return
|
|
231
|
+
|
|
232
|
+
content = file_path.read_text(encoding="utf-8")
|
|
233
|
+
modified = False
|
|
234
|
+
if ".uml-viewer" in content:
|
|
235
|
+
content = content.replace(".uml-viewer", ".archlens")
|
|
236
|
+
modified = True
|
|
237
|
+
|
|
238
|
+
if "Archlens Clean Architecture Workbench Companion Protocol" not in content:
|
|
239
|
+
content = content.rstrip() + "\n\n" + companion_block.strip() + "\n"
|
|
240
|
+
modified = True
|
|
241
|
+
|
|
242
|
+
if modified:
|
|
243
|
+
file_path.write_text(content, encoding="utf-8")
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def upgrade_project(root: Path, server_url: str = "http://localhost:8088") -> int:
|
|
247
|
+
legacy_dir = root / ".uml-viewer"
|
|
248
|
+
primary_dir = root / ".archlens"
|
|
249
|
+
|
|
250
|
+
if not legacy_dir.exists() and not primary_dir.exists():
|
|
251
|
+
print(f"Error: No configuration found in {root}. Run without --upgrade to initialize.", file=sys.stderr)
|
|
252
|
+
return 1
|
|
253
|
+
|
|
254
|
+
if legacy_dir.exists():
|
|
255
|
+
if not primary_dir.exists():
|
|
256
|
+
legacy_dir.rename(primary_dir)
|
|
257
|
+
print(f"Migrated legacy directory: {legacy_dir.name} -> {primary_dir.name}")
|
|
258
|
+
else:
|
|
259
|
+
for item in legacy_dir.iterdir():
|
|
260
|
+
target = primary_dir / item.name
|
|
261
|
+
if not target.exists():
|
|
262
|
+
item.rename(target)
|
|
263
|
+
import shutil
|
|
264
|
+
shutil.rmtree(legacy_dir, ignore_errors=True)
|
|
265
|
+
print(f"Merged legacy files into: {primary_dir.name}")
|
|
266
|
+
|
|
267
|
+
update_companion_markdown(root / "CLAUDE.md", server_url)
|
|
268
|
+
update_companion_markdown(root / "AGENTS.md", server_url)
|
|
269
|
+
print("Updated companion files (CLAUDE.md, AGENTS.md)")
|
|
270
|
+
return 0
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def main() -> int:
|
|
274
|
+
parser = argparse.ArgumentParser(
|
|
275
|
+
description="Initialize or upgrade Archlens architectural policy (.archlens/policy.json) and agent guidelines."
|
|
276
|
+
)
|
|
277
|
+
parser.add_argument("--path", "-p", default=".", help="Target project root directory (default: current directory)")
|
|
278
|
+
parser.add_argument("--title", "-t", default=None, help="Custom project title")
|
|
279
|
+
parser.add_argument("--prefix", default=None, help="Custom common package prefix")
|
|
280
|
+
parser.add_argument("--server-url", default="http://localhost:8088", help="Archlens workbench server URL")
|
|
281
|
+
parser.add_argument("--upgrade", "-u", action="store_true", help="Upgrade legacy .uml-viewer configuration to .archlens")
|
|
282
|
+
parser.add_argument("--force", "-f", action="store_true", help="Overwrite existing configuration files")
|
|
283
|
+
|
|
284
|
+
args = parser.parse_args()
|
|
285
|
+
target_root = Path(args.path).resolve()
|
|
286
|
+
|
|
287
|
+
if not target_root.exists():
|
|
288
|
+
print(f"Error: Target directory does not exist: {target_root}", file=sys.stderr)
|
|
289
|
+
return 1
|
|
290
|
+
|
|
291
|
+
if args.upgrade:
|
|
292
|
+
return upgrade_project(target_root, server_url=args.server_url)
|
|
293
|
+
|
|
294
|
+
archlens_dir = target_root / ".archlens"
|
|
295
|
+
legacy_dir = target_root / ".uml-viewer"
|
|
296
|
+
|
|
297
|
+
if not archlens_dir.exists() and legacy_dir.exists() and not args.force:
|
|
298
|
+
print(f"Notice: Found legacy {legacy_dir.name} configuration. Run with --upgrade to migrate to .archlens.")
|
|
299
|
+
target_config_dir = legacy_dir
|
|
300
|
+
else:
|
|
301
|
+
archlens_dir.mkdir(parents=True, exist_ok=True)
|
|
302
|
+
target_config_dir = archlens_dir
|
|
303
|
+
|
|
304
|
+
policy_file = target_config_dir / "policy.json"
|
|
305
|
+
if policy_file.exists() and not args.force:
|
|
306
|
+
print(f"Notice: Policy file already exists at {policy_file}. Use --force to regenerate.")
|
|
307
|
+
else:
|
|
308
|
+
policy = generate_policy(target_root, title=args.title, prefix=args.prefix)
|
|
309
|
+
policy_file.write_text(json.dumps(policy, indent=2) + "\n", encoding="utf-8")
|
|
310
|
+
print(f"Created architectural policy: {policy_file}")
|
|
311
|
+
|
|
312
|
+
write_workbench_config(target_config_dir, server_url=args.server_url)
|
|
313
|
+
print(f"Created workbench config: {target_config_dir / 'workbench.config.json'}")
|
|
314
|
+
|
|
315
|
+
update_companion_markdown(target_root / "CLAUDE.md", server_url=args.server_url)
|
|
316
|
+
update_companion_markdown(target_root / "AGENTS.md", server_url=args.server_url)
|
|
317
|
+
print("Configured companion guidelines in CLAUDE.md and AGENTS.md")
|
|
318
|
+
|
|
319
|
+
print(f"\nArchlens configuration complete for: {target_root.name}")
|
|
320
|
+
print(f"Run Archlens or visit {args.server_url}?projectRoot={target_root} to inspect architecture.")
|
|
321
|
+
return 0
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
if __name__ == "__main__":
|
|
325
|
+
sys.exit(main())
|
package/src/analyzer.js
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Archlens Codebase Analyzer
|
|
3
|
+
* Inspects any project repository to detect language, source roots, package prefixes,
|
|
4
|
+
* and classifies architectural packages into concentric Clean Architecture layers.
|
|
5
|
+
* Zero external dependencies.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import * as fs from 'node:fs';
|
|
9
|
+
import * as path from 'node:path';
|
|
10
|
+
|
|
11
|
+
export function detectProjectLanguage(projectRoot) {
|
|
12
|
+
const root = path.resolve(projectRoot);
|
|
13
|
+
|
|
14
|
+
const exists = (rel) => fs.existsSync(path.join(root, rel));
|
|
15
|
+
|
|
16
|
+
if (exists('pom.xml') || exists('build.gradle') || exists('build.gradle.kts')) {
|
|
17
|
+
if (findMatchingFiles(root, (f) => f.endsWith('.kt'), 5).length > 0) {
|
|
18
|
+
return 'kotlin';
|
|
19
|
+
}
|
|
20
|
+
return 'java';
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
if (exists('package.json') || exists('tsconfig.json')) {
|
|
24
|
+
return 'typescript';
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
if (exists('pyproject.toml') || exists('setup.py') || exists('requirements.txt')) {
|
|
28
|
+
return 'python';
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
if (exists('Cargo.toml')) {
|
|
32
|
+
return 'rust';
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
if (exists('go.mod')) {
|
|
36
|
+
return 'go';
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
if (exists('project.clj') || exists('deps.edn')) {
|
|
40
|
+
return 'clojure';
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
if (exists('CMakeLists.txt') || exists('Makefile')) {
|
|
44
|
+
return 'cpp';
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
return 'java';
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function detectSourceRoot(projectRoot, lang) {
|
|
51
|
+
const root = path.resolve(projectRoot);
|
|
52
|
+
|
|
53
|
+
const candidateMap = {
|
|
54
|
+
java: ['src/main/java', 'backend/src/main/java', 'core/src/main/java', 'src'],
|
|
55
|
+
kotlin: ['src/main/kotlin', 'src/main/java', 'backend/src/main/kotlin', 'src'],
|
|
56
|
+
typescript: ['src', 'frontend/src', 'lib', 'app', '.'],
|
|
57
|
+
python: ['src', 'app', 'lib', '.'],
|
|
58
|
+
rust: ['src'],
|
|
59
|
+
go: ['pkg', 'internal', 'cmd', '.'],
|
|
60
|
+
clojure: ['src', 'src/clj'],
|
|
61
|
+
cpp: ['src', 'include', '.']
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const candidates = candidateMap[lang] || ['src', '.'];
|
|
65
|
+
|
|
66
|
+
for (const cand of candidates) {
|
|
67
|
+
const p = path.join(root, cand);
|
|
68
|
+
if (fs.existsSync(p) && fs.statSync(p).isDirectory()) {
|
|
69
|
+
return cand;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return 'src';
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function findCommonPackagePrefix(sourceDir) {
|
|
77
|
+
const resolved = path.resolve(sourceDir);
|
|
78
|
+
if (!fs.existsSync(resolved)) {
|
|
79
|
+
return '';
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const javaFiles = findMatchingFiles(resolved, (f) => f.endsWith('.java') || f.endsWith('.kt'), 100);
|
|
83
|
+
if (javaFiles.length === 0) {
|
|
84
|
+
return '';
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const packages = [];
|
|
88
|
+
const packageRegex = /^\s*package\s+([a-zA-Z0-9_.]+)\s*;/m;
|
|
89
|
+
|
|
90
|
+
for (const file of javaFiles) {
|
|
91
|
+
try {
|
|
92
|
+
const content = fs.readFileSync(file, 'utf8');
|
|
93
|
+
const match = content.match(packageRegex);
|
|
94
|
+
if (match && match[1]) {
|
|
95
|
+
packages.push(match[1].trim());
|
|
96
|
+
}
|
|
97
|
+
} catch {
|
|
98
|
+
// Continue inspecting next file
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
if (packages.length === 0) {
|
|
103
|
+
return '';
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const splitPackages = packages.map((p) => p.split('.'));
|
|
107
|
+
const common = [];
|
|
108
|
+
const minLength = Math.min(...splitPackages.map((p) => p.length));
|
|
109
|
+
|
|
110
|
+
for (let i = 0; i < minLength; i++) {
|
|
111
|
+
const candidate = splitPackages[0][i];
|
|
112
|
+
const allMatch = splitPackages.every((p) => p[i] === candidate);
|
|
113
|
+
if (allMatch) {
|
|
114
|
+
common.push(candidate);
|
|
115
|
+
} else {
|
|
116
|
+
break;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const architecturalKeywords = new Set([
|
|
121
|
+
'domain', 'model', 'models', 'entity', 'entities', 'core',
|
|
122
|
+
'application', 'app', 'usecase', 'usecases', 'service', 'services', 'port', 'ports',
|
|
123
|
+
'adapter', 'adapters', 'controller', 'controllers', 'gateway', 'gateways',
|
|
124
|
+
'presenter', 'presenters', 'repository', 'repositories', 'resource', 'resources', 'api', 'dto',
|
|
125
|
+
'infrastructure', 'infra', 'persistence', 'db', 'database', 'config', 'configuration', 'web', 'server'
|
|
126
|
+
]);
|
|
127
|
+
|
|
128
|
+
while (common.length > 0 && architecturalKeywords.has(common[common.length - 1].toLowerCase())) {
|
|
129
|
+
common.pop();
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
return common.join('.');
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function discoverSubpackages(sourceDir, prefix) {
|
|
136
|
+
const resolved = path.resolve(sourceDir);
|
|
137
|
+
if (!fs.existsSync(resolved)) {
|
|
138
|
+
return [];
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
let searchPath = resolved;
|
|
142
|
+
if (prefix) {
|
|
143
|
+
const prefixSegments = prefix.split('.');
|
|
144
|
+
for (const seg of prefixSegments) {
|
|
145
|
+
const cand = path.join(searchPath, seg);
|
|
146
|
+
if (fs.existsSync(cand) && fs.statSync(cand).isDirectory()) {
|
|
147
|
+
searchPath = cand;
|
|
148
|
+
} else {
|
|
149
|
+
break;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if (!fs.existsSync(searchPath)) {
|
|
155
|
+
return [];
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const entries = fs.readdirSync(searchPath, { withFileTypes: true });
|
|
159
|
+
return entries
|
|
160
|
+
.filter((e) => e.isDirectory() && !e.name.startsWith('.'))
|
|
161
|
+
.map((e) => e.name)
|
|
162
|
+
.sort();
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export function classifyLayers(subpackages) {
|
|
166
|
+
const domainKeywords = ['domain', 'model', 'models', 'entity', 'entities', 'core', 'types', 'kernel'];
|
|
167
|
+
const appKeywords = ['application', 'app', 'usecase', 'usecases', 'service', 'services', 'port', 'ports', 'interactor'];
|
|
168
|
+
const adapterKeywords = [
|
|
169
|
+
'adapter', 'adapters', 'controller', 'controllers', 'gateway', 'gateways',
|
|
170
|
+
'presenter', 'presenters', 'repository', 'repositories', 'resource', 'resources',
|
|
171
|
+
'api', 'dto', 'endpoint', 'endpoints'
|
|
172
|
+
];
|
|
173
|
+
const infraKeywords = [
|
|
174
|
+
'infrastructure', 'infra', 'persistence', 'db', 'database', 'config',
|
|
175
|
+
'configuration', 'web', 'server', 'driver', 'client'
|
|
176
|
+
];
|
|
177
|
+
|
|
178
|
+
const level0 = [];
|
|
179
|
+
const level1 = [];
|
|
180
|
+
const level2 = [];
|
|
181
|
+
const level3 = [];
|
|
182
|
+
|
|
183
|
+
for (const pkg of subpackages) {
|
|
184
|
+
const lower = pkg.toLowerCase();
|
|
185
|
+
if (domainKeywords.some((k) => lower.includes(k))) {
|
|
186
|
+
level0.push(pkg);
|
|
187
|
+
} else if (appKeywords.some((k) => lower.includes(k))) {
|
|
188
|
+
level1.push(pkg);
|
|
189
|
+
} else if (adapterKeywords.some((k) => lower.includes(k))) {
|
|
190
|
+
level2.push(pkg);
|
|
191
|
+
} else if (infraKeywords.some((k) => lower.includes(k))) {
|
|
192
|
+
level3.push(pkg);
|
|
193
|
+
} else {
|
|
194
|
+
level1.push(pkg);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
if (level0.length === 0) level0.push('domain');
|
|
199
|
+
if (level1.length === 0) level1.push('application');
|
|
200
|
+
if (level2.length === 0) level2.push('adapters');
|
|
201
|
+
|
|
202
|
+
const levels = [level0, level1, level2];
|
|
203
|
+
if (level3.length > 0) {
|
|
204
|
+
levels.push(level3);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const order = [];
|
|
208
|
+
for (const group of levels) {
|
|
209
|
+
for (const p of group) {
|
|
210
|
+
if (!order.includes(p)) {
|
|
211
|
+
order.push(p);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
return { order, levels };
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
export function generatePolicy(projectRoot, options = {}) {
|
|
220
|
+
const root = path.resolve(projectRoot);
|
|
221
|
+
const lang = options.lang || detectProjectLanguage(root);
|
|
222
|
+
const srcRoot = options.src || detectSourceRoot(root, lang);
|
|
223
|
+
const fullSrc = path.join(root, srcRoot);
|
|
224
|
+
|
|
225
|
+
const prefix = options.prefix !== undefined ? options.prefix : findCommonPackagePrefix(fullSrc);
|
|
226
|
+
const title = options.title || formatProjectTitle(path.basename(root));
|
|
227
|
+
|
|
228
|
+
const subpackages = discoverSubpackages(fullSrc, prefix);
|
|
229
|
+
const { order, levels } = classifyLayers(subpackages);
|
|
230
|
+
|
|
231
|
+
const foreignMap = {
|
|
232
|
+
java: ['java.', 'jakarta.', 'org.springframework.', 'io.quarkus.'],
|
|
233
|
+
kotlin: ['kotlin.', 'kotlinx.'],
|
|
234
|
+
typescript: ['node:', '@types/'],
|
|
235
|
+
python: ['sys', 'os', 'pathlib'],
|
|
236
|
+
rust: ['std::', 'core::'],
|
|
237
|
+
go: ['fmt', 'os', 'net/http'],
|
|
238
|
+
clojure: ['clojure.']
|
|
239
|
+
};
|
|
240
|
+
|
|
241
|
+
return {
|
|
242
|
+
title,
|
|
243
|
+
src: srcRoot,
|
|
244
|
+
prefix,
|
|
245
|
+
hierarchical: true,
|
|
246
|
+
order,
|
|
247
|
+
levels,
|
|
248
|
+
foreign: foreignMap[lang] || ['java.', 'jakarta.'],
|
|
249
|
+
omit: ['target', 'build', '.git', 'node_modules', '.gradle', '.idea', '.vscode'],
|
|
250
|
+
lang
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
export function formatProjectTitle(dirname) {
|
|
255
|
+
return dirname
|
|
256
|
+
.replace(/[-_]+/g, ' ')
|
|
257
|
+
.trim()
|
|
258
|
+
.split(' ')
|
|
259
|
+
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
|
|
260
|
+
.join(' ');
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function findMatchingFiles(dir, predicate, limit = 50, collected = []) {
|
|
264
|
+
if (!fs.existsSync(dir) || collected.length >= limit) {
|
|
265
|
+
return collected;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
const skipDirs = new Set(['.git', 'node_modules', 'target', 'build', '.gradle', '.idea', '.vscode']);
|
|
269
|
+
|
|
270
|
+
try {
|
|
271
|
+
const entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
272
|
+
for (const entry of entries) {
|
|
273
|
+
if (collected.length >= limit) break;
|
|
274
|
+
const fullPath = path.join(dir, entry.name);
|
|
275
|
+
|
|
276
|
+
if (entry.isDirectory()) {
|
|
277
|
+
if (!skipDirs.has(entry.name)) {
|
|
278
|
+
findMatchingFiles(fullPath, predicate, limit, collected);
|
|
279
|
+
}
|
|
280
|
+
} else if (entry.isFile() && predicate(entry.name)) {
|
|
281
|
+
collected.push(fullPath);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
} catch {
|
|
285
|
+
// Gracefully handle unreadable directories
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
return collected;
|
|
289
|
+
}
|