@fmatar/archlens-skill 0.1.0-Beta-11 → 1.1.0-dev.59
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/README.md +33 -10
- package/bin/index.js +14 -2
- package/llms.txt +17 -3
- package/package.json +1 -1
- package/skills/archlens/SKILL.md +14 -1
- package/src/analyzer.js +135 -0
- package/src/checker.js +179 -20
- package/src/docker-runner.js +108 -5
- package/src/mcp-registry.js +185 -7
- package/src/mcp-server.js +339 -8
package/README.md
CHANGED
|
@@ -12,7 +12,17 @@ Analyzes any project repository, detects programming languages and package hiera
|
|
|
12
12
|
|
|
13
13
|
## ⚡ Quickstart
|
|
14
14
|
|
|
15
|
-
### Option A:
|
|
15
|
+
### Option A: Zero-Touch Autonomous AI Setup (`--mcp` — Recommended for Antigravity & Claude)
|
|
16
|
+
Equip **Google Antigravity**, **Claude Code**, **Claude Desktop**, **Cursor**, **Windsurf**, and **Gemini CLI** in one command. Once configured, your AI assistant **automatically starts or resurrects Archlens on demand** whenever an architectural MCP tool is invoked—no manual container management required:
|
|
17
|
+
```bash
|
|
18
|
+
# Scaffold .archlens/policy.json, AGENTS.md/CLAUDE.md, and auto-configure all installed AI clients:
|
|
19
|
+
npx @fmatar/archlens-skill --yes --mcp
|
|
20
|
+
|
|
21
|
+
# Or also install global skills into ~/.claude/skills and ~/.gemini/config/skills:
|
|
22
|
+
npx @fmatar/archlens-skill --global --mcp
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
### Option B: Install AI Assistant Skills via Open Skills Standard
|
|
16
26
|
Using the open [Vercel Labs Skills](https://github.com/vercel-labs/skills) standard, you can add Archlens capabilities across 15+ AI coding assistants (Claude Code, Cursor, Antigravity, Copilot, Codex, Windsurf, Zed):
|
|
17
27
|
```bash
|
|
18
28
|
# Add to all detected AI assistants in project or globally:
|
|
@@ -22,7 +32,7 @@ npx skills add fmatar/archlens
|
|
|
22
32
|
npx skills add fmatar/archlens --agent claude-code
|
|
23
33
|
```
|
|
24
34
|
|
|
25
|
-
### Option
|
|
35
|
+
### Option C: Run Interactive Policy Scaffolder via NPX
|
|
26
36
|
|
|
27
37
|
```bash
|
|
28
38
|
# Production Stable (recommended)
|
|
@@ -35,13 +45,13 @@ npx @fmatar/archlens-skill@dev
|
|
|
35
45
|
npx github:fmatar/archlens
|
|
36
46
|
```
|
|
37
47
|
|
|
38
|
-
### Option
|
|
48
|
+
### Option D: Install Globally via NPM
|
|
39
49
|
```bash
|
|
40
50
|
npm install -g @fmatar/archlens-skill
|
|
41
51
|
archlens-skill
|
|
42
52
|
```
|
|
43
53
|
|
|
44
|
-
### Option
|
|
54
|
+
### Option E: Run from Local Repository Clone
|
|
45
55
|
```bash
|
|
46
56
|
# Install globally from the local repository:
|
|
47
57
|
npm install -g ./cli
|
|
@@ -148,20 +158,33 @@ npx @fmatar/archlens-skill start --path /path/to/project --port 8088 --open
|
|
|
148
158
|
|
|
149
159
|
### Command-Line Options
|
|
150
160
|
|
|
151
|
-
| Flag | Shorthand | Description | Default |
|
|
161
|
+
| Flag / Command | Shorthand | Description | Default |
|
|
152
162
|
|------|-----------|-------------|---------|
|
|
153
|
-
| `
|
|
163
|
+
| `check` | `--check` | Run headless Clean Architecture CI quality gate | |
|
|
164
|
+
| `start` | | Start Archlens Workbench (Native Binary / JAR / Docker fallback) | |
|
|
165
|
+
| `prompt` | `--prompt` | Export LLM Refactoring Prompt Dossier | |
|
|
166
|
+
| `mcp` | | Run MCP stdio server bridge (online + offline static fallback) | |
|
|
167
|
+
| `update` | `--update`, `-u` | Re-scan code and update existing `.archlens/policy.json` | `false` |
|
|
168
|
+
| `upgrade` | `--upgrade` | Migrate legacy `.uml-viewer` to `.archlens` | `false` |
|
|
169
|
+
| `global` | `--global`, `-g` | Install skills into global agent directories | `false` |
|
|
170
|
+
| `--max-violations <N>` | | Maximum allowed outward layer violations in `check` | `0` |
|
|
171
|
+
| `--detect-cycles` | | Fail `check` if package dependency cycles (ADP) are detected | `false` |
|
|
172
|
+
| `--screaming-threshold <N>` | | Minimum Screaming Architecture Score (`0.0`–`1.0`) | |
|
|
173
|
+
| `--suggest-features` | | Suggest Screaming Architecture feature slice clusters in `check` | `false` |
|
|
174
|
+
| `--fitness-threshold <N>` | | Minimum Composite Architecture Fitness Index (`0.0`–`1.0`) | |
|
|
175
|
+
| `--format <FMT>` | | Output format for `check` (`text`, `json`, `sarif`) | `text` |
|
|
176
|
+
| `--output <FILE>` | `-O` | Write `check` output report (e.g. SARIF) to file | |
|
|
177
|
+
| `--native` | | Force native JVM runner mode on `start` | `false` |
|
|
178
|
+
| `--docker` | | Force Docker container mode on `start` | `false` |
|
|
179
|
+
| `--jar <PATH>` | | Custom path to `quarkus-run.jar` for native mode | Auto-detected |
|
|
154
180
|
| `--open` | `-o` | Open visual workbench in default browser upon startup | `false` |
|
|
155
181
|
| `--port <PORT>` | | Workbench HTTP port | `8088` |
|
|
156
182
|
| `--path <DIR>` | `-p` | Target repository directory | `.` (current directory) |
|
|
157
183
|
| `--title <NAME>` | `-t` | Project title in visual workbench | Formatted folder name |
|
|
158
184
|
| `--prefix <PKG>` | | Common package prefix (e.g. `com.example.service`) | Auto-detected |
|
|
159
185
|
| `--server-url <URL>` | | Visual Workbench server endpoint | `http://localhost:8088` |
|
|
160
|
-
| `--mcp` | `-m` | Auto-configure MCP client manifests (Claude, Antigravity, Cursor) | `false` |
|
|
186
|
+
| `--mcp` | `-m` | Auto-configure MCP client manifests (Claude, Antigravity, Cursor, Gemini, Grok, Windsurf, VS Code) | `false` |
|
|
161
187
|
| `--copy` | `-c` | Copy LLM prompt output directly to system clipboard | `false` |
|
|
162
|
-
| `--global` | `-g` | Install skill into global agent directories | `false` |
|
|
163
|
-
| `--update` | `-u` | Re-scan code and update existing policy | `false` |
|
|
164
|
-
| `--upgrade` | | Migrate legacy `.uml-viewer` to `.archlens` | `false` |
|
|
165
188
|
| `--force` | `-f` | Overwrite existing configuration files | `false` |
|
|
166
189
|
| `--dry-run` | | Simulate execution without writing files | `false` |
|
|
167
190
|
| `--yes` | `-y` | Accept defaults automatically (non-interactive) | `false` |
|
package/bin/index.js
CHANGED
|
@@ -20,7 +20,12 @@ import {
|
|
|
20
20
|
import { installLocalPolicy, installGlobalSkills } from '../src/installer.js';
|
|
21
21
|
import { updateLocalPolicy, updateGlobalSkills } from '../src/updater.js';
|
|
22
22
|
import { upgradeProject } from '../src/upgrader.js';
|
|
23
|
-
import {
|
|
23
|
+
import {
|
|
24
|
+
checkArchitecture,
|
|
25
|
+
generateSarifReport,
|
|
26
|
+
generateJsonReport,
|
|
27
|
+
generateMermaidReport
|
|
28
|
+
} from '../src/checker.js';
|
|
24
29
|
import { installMcpConfigs } from '../src/mcp-registry.js';
|
|
25
30
|
import { startMcpStdioServer } from '../src/mcp-server.js';
|
|
26
31
|
import { executeStart, DEFAULT_CONTAINER_NAME, DEFAULT_SERVER_URL } from '../src/docker-runner.js';
|
|
@@ -506,6 +511,8 @@ async function main() {
|
|
|
506
511
|
formattedOutput = generateSarifReport(report, { version: getPackageVersion() });
|
|
507
512
|
} else if (options.format === 'json') {
|
|
508
513
|
formattedOutput = generateJsonReport(report);
|
|
514
|
+
} else if (options.format === 'mermaid' || options.format === 'mmd') {
|
|
515
|
+
formattedOutput = generateMermaidReport(report, options);
|
|
509
516
|
}
|
|
510
517
|
|
|
511
518
|
if (options.output) {
|
|
@@ -520,7 +527,12 @@ async function main() {
|
|
|
520
527
|
}
|
|
521
528
|
}
|
|
522
529
|
|
|
523
|
-
if (
|
|
530
|
+
if (
|
|
531
|
+
options.format === 'sarif' ||
|
|
532
|
+
options.format === 'json' ||
|
|
533
|
+
options.format === 'mermaid' ||
|
|
534
|
+
options.format === 'mmd'
|
|
535
|
+
) {
|
|
524
536
|
if (!options.output) {
|
|
525
537
|
process.stdout.write(formattedOutput + '\n');
|
|
526
538
|
}
|
package/llms.txt
CHANGED
|
@@ -63,7 +63,7 @@ Archlens CLI requires zero external dependencies and runs cross-platform via Nod
|
|
|
63
63
|
```bash
|
|
64
64
|
# 1. Audit Codebase Conformance & Detect All Architectural Drifts:
|
|
65
65
|
npx @fmatar/archlens-skill check
|
|
66
|
-
npx @fmatar/archlens-skill check --detect-cycles --screaming-threshold 0.70 --fitness-threshold 0.85
|
|
66
|
+
npx @fmatar/archlens-skill check --detect-cycles --screaming-threshold 0.70 --suggest-features --fitness-threshold 0.85
|
|
67
67
|
npx @fmatar/archlens-skill check --format json
|
|
68
68
|
npx @fmatar/archlens-skill check --format sarif -O arch-drift.sarif
|
|
69
69
|
|
|
@@ -89,18 +89,32 @@ npx @fmatar/archlens-skill mcp # Launch MCP stdio bridge server
|
|
|
89
89
|
|
|
90
90
|
When Archlens is registered as an MCP server, AI assistants can query it using standard MCP primitives:
|
|
91
91
|
|
|
92
|
-
### MCP Tools:
|
|
92
|
+
### MCP Tools (10):
|
|
93
93
|
| Tool Name | Parameters | Purpose |
|
|
94
94
|
| :--- | :--- | :--- |
|
|
95
95
|
| `exportLlmDossier` | `projectRoot` (default: `.`), `proposalId` | Diagnoses outward dependency breaches and outputs a Markdown refactoring prompt with concrete DIP interface port prescriptions. |
|
|
96
96
|
| `inspectArchitecture` | `projectRoot` (default: `.`) | Returns full JSON graph model: concentric rings, dependency edges, cycle paths, and screaming metrics. |
|
|
97
|
+
| `synthesizeDipInversion` | `fromClass` (required), `toClass` (required), `projectRoot` | Synthesizes a complete Dependency Inversion Principle (DIP) interface port (`Java`, `Python`, `TypeScript`, `Go`, `Rust`), adapter/caller diffs, and surgical prompt. |
|
|
98
|
+
| `evaluateFitness` | `projectRoot` (default: `.`) | Evaluates the Composite Architecture Fitness Index (AFI score `0`–`100`, grade `A`–`F`, rule breakdowns). |
|
|
99
|
+
| `getFitnessHistory` | `projectRoot` (default: `.`) | Returns historical fitness snapshots across Git release tags and computes the regression trend (`STABLE`, `IMPROVING`, `DEGRADING`). |
|
|
100
|
+
| `proposeScreamingMigration` | `projectRoot` (default: `.`) | Generates a Screaming Architecture package-by-feature migration plan from technical layers into domain feature slices. |
|
|
101
|
+
| `getPolicy` | `projectRoot` (default: `.`) | Returns the active `.archlens/policy.json` concentric ring definitions and omission rules. |
|
|
102
|
+
| `syncDipAdr` | `fromClass`, `toClass`, `portName`, `portPackage`, `reason`, `projectRoot` | Mints a numbered Markdown ADR in `docs/adr/` documenting a Dependency Inversion Principle refactoring. |
|
|
97
103
|
| `listSnapshots` | `projectRoot` (default: `.`) | Lists historical architecture release snapshots in `.archlens/snapshots/` and Git release tags. |
|
|
98
104
|
| `getSnapshot` | `snapshotId` (required), `projectRoot` | Retrieves the graph model of a specific historical snapshot or Git tag for temporal drift diffing. |
|
|
99
105
|
|
|
100
|
-
### MCP Resources:
|
|
106
|
+
### MCP Resources (3):
|
|
101
107
|
| Resource URI | MIME Type | Description |
|
|
102
108
|
| :--- | :--- | :--- |
|
|
103
109
|
| `archlens://llms.txt` | `text/markdown` | This authoritative reference guide, Clean Architecture rules, CLI recipes, and refactoring protocols. |
|
|
110
|
+
| `archlens://policy` | `application/json` | The active `.archlens/policy.json` concentric Clean Architecture layer policy for the workspace. |
|
|
111
|
+
| `archlens://fitness` | `application/json` | Live Architecture Fitness Index (AFI) evaluation report, grade, and rule breakdown. |
|
|
112
|
+
|
|
113
|
+
### MCP Prompts (2):
|
|
114
|
+
| Prompt Name | Arguments | Description |
|
|
115
|
+
| :--- | :--- | :--- |
|
|
116
|
+
| `architectural-review` | `projectRoot` (optional) | Comprehensive Clean Architecture review prompt combining the LLM Dossier and Fitness evaluation. |
|
|
117
|
+
| `dip-refactoring-guide` | `fromClass` (required), `toClass` (required), `projectRoot` | Step-by-step Dependency Inversion Principle (DIP) refactoring prompt for a specific outward violation. |
|
|
104
118
|
|
|
105
119
|
---
|
|
106
120
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fmatar/archlens-skill",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "1.1.0-dev.59",
|
|
4
4
|
"description": "Cross-platform CLI and installer for Archlens Clean Architecture governance policies and AI assistant skills",
|
|
5
5
|
"main": "src/installer.js",
|
|
6
6
|
"type": "module",
|
package/skills/archlens/SKILL.md
CHANGED
|
@@ -17,7 +17,7 @@ This skill equips agents (Antigravity, Gemini CLI, Claude Code) to:
|
|
|
17
17
|
2. Scaffold and maintain `.archlens/policy.json` architectural layer policies.
|
|
18
18
|
3. Act as the autonomous refactoring companion to the visual workbench via mailbox queues (`.archlens/to-agent.json` and `.archlens/to-viewer.json`).
|
|
19
19
|
4. Export LLM Refactoring Prompt Dossiers prescribing concrete Dependency Inversion Principle (DIP) interface ports.
|
|
20
|
-
5. Invoke Archlens MCP tools (`inspectArchitecture`, `exportLlmDossier`, `listSnapshots`, `getSnapshot`).
|
|
20
|
+
5. Invoke Archlens MCP tools (`inspectArchitecture`, `exportLlmDossier`, `synthesizeDipInversion`, `evaluateFitness`, `getFitnessHistory`, `proposeScreamingMigration`, `getPolicy`, `syncDipAdr`, `listSnapshots`, `getSnapshot`), resources (`archlens://llms.txt`, `archlens://policy`, `archlens://fitness`), and prompts (`architectural-review`, `dip-refactoring-guide`).
|
|
21
21
|
|
|
22
22
|
---
|
|
23
23
|
|
|
@@ -65,6 +65,9 @@ npx @fmatar/archlens-skill --path . --yes
|
|
|
65
65
|
# Launch Workbench container (auto-resurrects on demand if stopped or killed):
|
|
66
66
|
npx @fmatar/archlens-skill start --open
|
|
67
67
|
|
|
68
|
+
# Execute Headless Clean Architecture CI Quality Gate (ADP cycles, Screaming score, Fitness index, SARIF):
|
|
69
|
+
npx @fmatar/archlens-skill check --path . --max-violations 0 --detect-cycles --screaming-threshold 0.70 --suggest-features --fitness-threshold 0.85 --format sarif -O archlens-results.sarif
|
|
70
|
+
|
|
68
71
|
# Export Clean Architecture LLM Refactoring Prompt Dossier:
|
|
69
72
|
npx @fmatar/archlens-skill prompt --path .
|
|
70
73
|
|
|
@@ -144,5 +147,15 @@ When Archlens is registered as an MCP server, use the following tools:
|
|
|
144
147
|
| :--- | :--- | :--- |
|
|
145
148
|
| `inspectArchitecture` | Inspect concentric rings, outward violations, and instability metrics | `projectRoot` (default: `.`) |
|
|
146
149
|
| `exportLlmDossier` | Generate copy-ready LLM refactoring prompt with DIP prescriptions | `projectRoot`, `proposalId` |
|
|
150
|
+
| `synthesizeDipInversion` | Synthesize polyglot DIP interface port, adapter/caller diffs, and surgical prompt | `fromClass`, `toClass`, `projectRoot` |
|
|
151
|
+
| `evaluateFitness` | Compute Composite Architecture Fitness Index (AFI score, grade, rule breakdown) | `projectRoot` |
|
|
152
|
+
| `getFitnessHistory` | Retrieve historical fitness snapshots across Git tags and regression trend | `projectRoot` |
|
|
153
|
+
| `proposeScreamingMigration` | Propose Screaming Architecture package-by-feature migration clusters | `projectRoot` |
|
|
154
|
+
| `getPolicy` | Inspect active `.archlens/policy.json` concentric ring definitions | `projectRoot` |
|
|
155
|
+
| `syncDipAdr` | Mint a numbered Markdown ADR in `docs/adr/` for a DIP refactoring | `fromClass`, `toClass`, `portName`, `portPackage`, `reason`, `projectRoot` |
|
|
147
156
|
| `listSnapshots` | List historical Git release tags and pre-compiled architecture snapshots | `projectRoot` |
|
|
148
157
|
| `getSnapshot` | Retrieve graph model for a historical release or snapshot tag | `snapshotId`, `projectRoot` |
|
|
158
|
+
|
|
159
|
+
### MCP Resources & Prompts
|
|
160
|
+
- **Resources**: `archlens://llms.txt`, `archlens://policy`, `archlens://fitness`
|
|
161
|
+
- **Prompts**: `architectural-review` (`projectRoot`), `dip-refactoring-guide` (`fromClass`, `toClass`, `projectRoot`)
|
package/src/analyzer.js
CHANGED
|
@@ -121,6 +121,123 @@ function findNestedSourceRoots(dir, lang, depth = 0, maxDepth = 5, results = [])
|
|
|
121
121
|
return results;
|
|
122
122
|
}
|
|
123
123
|
|
|
124
|
+
export function discoverWorkspaceModules(projectRoot) {
|
|
125
|
+
const root = path.resolve(projectRoot);
|
|
126
|
+
const discovered = new Set();
|
|
127
|
+
|
|
128
|
+
const expandGlobPattern = (pattern) => {
|
|
129
|
+
let clean = pattern.trim().replace(/^['"]|['"]$/g, '').replace(/\\/g, '/');
|
|
130
|
+
if (!clean || clean.startsWith('!')) return;
|
|
131
|
+
if (clean.startsWith(':')) {
|
|
132
|
+
clean = clean.slice(1).replace(/:/g, '/');
|
|
133
|
+
}
|
|
134
|
+
while (clean.endsWith('/')) {
|
|
135
|
+
clean = clean.slice(0, -1);
|
|
136
|
+
}
|
|
137
|
+
if (!clean) return;
|
|
138
|
+
|
|
139
|
+
if (clean.endsWith('/*') || clean.endsWith('/**')) {
|
|
140
|
+
const parentRel = clean.replace(/\/\*\*?$/, '');
|
|
141
|
+
const parentDir = path.join(root, parentRel);
|
|
142
|
+
if (fs.existsSync(parentDir) && fs.statSync(parentDir).isDirectory()) {
|
|
143
|
+
try {
|
|
144
|
+
for (const entry of fs.readdirSync(parentDir, { withFileTypes: true })) {
|
|
145
|
+
if (entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'node_modules') {
|
|
146
|
+
discovered.add(path.posix.join(parentRel, entry.name));
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
} catch {
|
|
150
|
+
// Ignore unreadable parent
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
} else {
|
|
154
|
+
const candidate = path.join(root, clean);
|
|
155
|
+
if (fs.existsSync(candidate) && fs.statSync(candidate).isDirectory()) {
|
|
156
|
+
discovered.add(clean);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
// 1. Gradle settings.gradle / settings.gradle.kts
|
|
162
|
+
for (const gradleSettings of ['settings.gradle', 'settings.gradle.kts']) {
|
|
163
|
+
const settingsPath = path.join(root, gradleSettings);
|
|
164
|
+
if (fs.existsSync(settingsPath)) {
|
|
165
|
+
try {
|
|
166
|
+
const content = fs.readFileSync(settingsPath, 'utf8');
|
|
167
|
+
const includeRegex = /\binclude\s*\(?([^)\n]+)\)?/g;
|
|
168
|
+
let match;
|
|
169
|
+
while ((match = includeRegex.exec(content)) !== null) {
|
|
170
|
+
const strRegex = /['"]([^'"]+)['"]/g;
|
|
171
|
+
let strMatch;
|
|
172
|
+
while ((strMatch = strRegex.exec(match[1])) !== null) {
|
|
173
|
+
expandGlobPattern(strMatch[1]);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
} catch {
|
|
177
|
+
// Ignore malformed Gradle settings
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// 2. Cargo.toml [workspace] members
|
|
183
|
+
const cargoPath = path.join(root, 'Cargo.toml');
|
|
184
|
+
if (fs.existsSync(cargoPath)) {
|
|
185
|
+
try {
|
|
186
|
+
const content = fs.readFileSync(cargoPath, 'utf8');
|
|
187
|
+
if (/\[workspace\]/.test(content)) {
|
|
188
|
+
const membersMatch = content.match(/\bmembers\s*=\s*\[([\s\S]*?)\]/);
|
|
189
|
+
if (membersMatch) {
|
|
190
|
+
const strRegex = /['"]([^'"]+)['"]/g;
|
|
191
|
+
let strMatch;
|
|
192
|
+
while ((strMatch = strRegex.exec(membersMatch[1])) !== null) {
|
|
193
|
+
expandGlobPattern(strMatch[1]);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
} catch {
|
|
198
|
+
// Ignore malformed Cargo.toml
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// 3. pnpm-workspace.yaml
|
|
203
|
+
const pnpmPath = path.join(root, 'pnpm-workspace.yaml');
|
|
204
|
+
if (fs.existsSync(pnpmPath)) {
|
|
205
|
+
try {
|
|
206
|
+
const content = fs.readFileSync(pnpmPath, 'utf8');
|
|
207
|
+
for (const line of content.split(/\r?\n/)) {
|
|
208
|
+
const itemMatch = line.match(/^\s*-\s*['"]?([^'"#]+)['"]?/);
|
|
209
|
+
if (itemMatch) {
|
|
210
|
+
expandGlobPattern(itemMatch[1]);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
} catch {
|
|
214
|
+
// Ignore malformed pnpm-workspace.yaml
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// 4. package.json workspaces (npm / Yarn / Nx / Turborepo)
|
|
219
|
+
const pkgJsonPath = path.join(root, 'package.json');
|
|
220
|
+
if (fs.existsSync(pkgJsonPath)) {
|
|
221
|
+
try {
|
|
222
|
+
const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf8'));
|
|
223
|
+
const workspaces = Array.isArray(pkg.workspaces)
|
|
224
|
+
? pkg.workspaces
|
|
225
|
+
: Array.isArray(pkg.workspaces?.packages)
|
|
226
|
+
? pkg.workspaces.packages
|
|
227
|
+
: [];
|
|
228
|
+
for (const pattern of workspaces) {
|
|
229
|
+
if (typeof pattern === 'string') {
|
|
230
|
+
expandGlobPattern(pattern);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
} catch {
|
|
234
|
+
// Ignore malformed package.json
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
return Array.from(discovered);
|
|
239
|
+
}
|
|
240
|
+
|
|
124
241
|
export function detectSourceRoot(projectRoot, lang) {
|
|
125
242
|
const root = path.resolve(projectRoot);
|
|
126
243
|
|
|
@@ -145,6 +262,24 @@ export function detectSourceRoot(projectRoot, lang) {
|
|
|
145
262
|
}
|
|
146
263
|
}
|
|
147
264
|
|
|
265
|
+
// Check multi-build workspace manifests (Gradle, Cargo, pnpm, npm/Nx/Turborepo)
|
|
266
|
+
const workspaceMods = discoverWorkspaceModules(root);
|
|
267
|
+
for (const modRel of workspaceMods) {
|
|
268
|
+
if (lang === 'java') {
|
|
269
|
+
const javaSrc = path.posix.join(modRel, 'src/main/java');
|
|
270
|
+
if (fs.existsSync(path.join(root, javaSrc))) return javaSrc;
|
|
271
|
+
} else if (lang === 'kotlin') {
|
|
272
|
+
const ktSrc = path.posix.join(modRel, 'src/main/kotlin');
|
|
273
|
+
if (fs.existsSync(path.join(root, ktSrc))) return ktSrc;
|
|
274
|
+
const javaSrc = path.posix.join(modRel, 'src/main/java');
|
|
275
|
+
if (fs.existsSync(path.join(root, javaSrc))) return javaSrc;
|
|
276
|
+
} else {
|
|
277
|
+
const modSrc = path.posix.join(modRel, 'src');
|
|
278
|
+
if (fs.existsSync(path.join(root, modSrc))) return modSrc;
|
|
279
|
+
if (fs.existsSync(path.join(root, modRel))) return modRel;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
148
283
|
// Multi-module dynamic discovery if standard candidates are not found
|
|
149
284
|
const nested = findNestedSourceRoots(root, lang);
|
|
150
285
|
if (nested.length > 0) {
|
package/src/checker.js
CHANGED
|
@@ -737,6 +737,7 @@ export function extractFileImports(content, filePath, fullSrc) {
|
|
|
737
737
|
function countFileTypeAbstractions(content, filePath) {
|
|
738
738
|
let totalTypes = 0;
|
|
739
739
|
let abstractTypes = 0;
|
|
740
|
+
let recordTypes = 0;
|
|
740
741
|
if (filePath.endsWith('.py')) {
|
|
741
742
|
const classMatches = content.match(/^\s*class\s+[A-Za-z_][A-Za-z0-9_]*(?:\s*\(([^)]*)\))?\s*:/gm) || [];
|
|
742
743
|
const hasAbstractMethod = /@abstractmethod\b/.test(content);
|
|
@@ -747,21 +748,29 @@ function countFileTypeAbstractions(content, filePath) {
|
|
|
747
748
|
}
|
|
748
749
|
}
|
|
749
750
|
} else {
|
|
750
|
-
const
|
|
751
|
-
|
|
751
|
+
const cleaned = content
|
|
752
|
+
.replace(/\/\*[\s\S]*?\*\//g, ' ')
|
|
753
|
+
.replace(/\/\/.*$/gm, ' ')
|
|
754
|
+
.replace(/"""[\s\S]*?"""/g, ' ')
|
|
755
|
+
.replace(/"(?:\\.|[^"\\])*"/g, ' ')
|
|
756
|
+
.replace(/'(?:\\.|[^'\\])*'/g, ' ');
|
|
757
|
+
const ifaceMatches = cleaned.match(/\binterface\s+[A-Za-z_$][A-Za-z0-9_$]*/g) || [];
|
|
758
|
+
const absClassMatches = cleaned.match(/\babstract\s+class\s+[A-Za-z_$][A-Za-z0-9_$]*/g) || [];
|
|
759
|
+
const recordMatches = cleaned.match(/\brecord\s+[A-Za-z_$][A-Za-z0-9_$]*/g) || [];
|
|
752
760
|
const concreteClassMatches =
|
|
753
|
-
|
|
754
|
-
const enumMatches =
|
|
761
|
+
cleaned.replace(/\babstract\s+class\b/g, '').match(/\bclass\s+[A-Za-z_$][A-Za-z0-9_$]*/g) || [];
|
|
762
|
+
const enumMatches = cleaned.match(/\benum\s+[A-Za-z_$][A-Za-z0-9_$]*/g) || [];
|
|
755
763
|
abstractTypes = ifaceMatches.length + absClassMatches.length;
|
|
756
|
-
|
|
764
|
+
recordTypes = recordMatches.length;
|
|
765
|
+
totalTypes = abstractTypes + recordTypes + concreteClassMatches.length + enumMatches.length;
|
|
757
766
|
}
|
|
758
767
|
if (totalTypes === 0) {
|
|
759
768
|
totalTypes = 1;
|
|
760
769
|
}
|
|
761
|
-
return { totalTypes, abstractTypes };
|
|
770
|
+
return { totalTypes, abstractTypes, recordTypes };
|
|
762
771
|
}
|
|
763
772
|
|
|
764
|
-
export function calculateMaxMainSequenceDistance(pkgTypeStats, packageEdges) {
|
|
773
|
+
export function calculateMaxMainSequenceDistance(pkgTypeStats, packageEdges, pkgCouplingCounts = null) {
|
|
765
774
|
let maxDistance = 0.0;
|
|
766
775
|
const allPackages = new Set([
|
|
767
776
|
...Array.from(pkgTypeStats.keys()),
|
|
@@ -769,19 +778,34 @@ export function calculateMaxMainSequenceDistance(pkgTypeStats, packageEdges) {
|
|
|
769
778
|
]);
|
|
770
779
|
|
|
771
780
|
for (const pkg of allPackages) {
|
|
772
|
-
|
|
781
|
+
let ce = 0;
|
|
773
782
|
let ca = 0;
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
783
|
+
if (pkgCouplingCounts && pkgCouplingCounts.has(pkg)) {
|
|
784
|
+
const counts = pkgCouplingCounts.get(pkg);
|
|
785
|
+
ca = counts.ca || 0;
|
|
786
|
+
ce = counts.ce || 0;
|
|
787
|
+
} else {
|
|
788
|
+
ce = packageEdges.has(pkg) ? packageEdges.get(pkg).size : 0;
|
|
789
|
+
for (const [otherPkg, targets] of packageEdges.entries()) {
|
|
790
|
+
if (otherPkg !== pkg && targets.has(pkg)) {
|
|
791
|
+
ca++;
|
|
792
|
+
}
|
|
777
793
|
}
|
|
778
794
|
}
|
|
779
795
|
if (ca + ce === 0) {
|
|
780
796
|
continue;
|
|
781
797
|
}
|
|
782
|
-
const stats = pkgTypeStats.get(pkg) || { totalTypes: 1, abstractTypes: 0 };
|
|
783
|
-
const abstractness = stats.totalTypes > 0 ? stats.abstractTypes / stats.totalTypes : 0.0;
|
|
798
|
+
const stats = pkgTypeStats.get(pkg) || { totalTypes: 1, abstractTypes: 0, recordTypes: 0 };
|
|
784
799
|
const instability = ce / (ca + ce);
|
|
800
|
+
const strictAbstractness = stats.totalTypes > 0 ? stats.abstractTypes / stats.totalTypes : 0.0;
|
|
801
|
+
const immutableAbstractness =
|
|
802
|
+
stats.totalTypes > 0
|
|
803
|
+
? (stats.abstractTypes + (stats.recordTypes || 0)) / stats.totalTypes
|
|
804
|
+
: 0.0;
|
|
805
|
+
const abstractness = Math.min(
|
|
806
|
+
immutableAbstractness,
|
|
807
|
+
Math.max(strictAbstractness, 1.0 - instability)
|
|
808
|
+
);
|
|
785
809
|
const distance = Math.abs(abstractness + instability - 1.0);
|
|
786
810
|
if (distance > maxDistance) {
|
|
787
811
|
maxDistance = distance;
|
|
@@ -812,6 +836,7 @@ export async function checkArchitecture(projectRoot, options = {}) {
|
|
|
812
836
|
levels.forEach((tier, lvl) => {
|
|
813
837
|
tier.forEach((p) => pkgToLevel.set(p.toLowerCase(), lvl));
|
|
814
838
|
});
|
|
839
|
+
const sortedPkgEntries = Array.from(pkgToLevel.entries()).sort((a, b) => b[0].length - a[0].length);
|
|
815
840
|
|
|
816
841
|
const fullSrc = path.join(root, policy.src || 'src');
|
|
817
842
|
const sourceFiles = findMatchingFiles(
|
|
@@ -834,17 +859,19 @@ export async function checkArchitecture(projectRoot, options = {}) {
|
|
|
834
859
|
const violations = [];
|
|
835
860
|
const packageEdges = new Map();
|
|
836
861
|
const pkgTypeStats = new Map();
|
|
862
|
+
const pkgCouplingCounts = new Map();
|
|
837
863
|
|
|
838
864
|
for (const file of sourceFiles) {
|
|
839
865
|
try {
|
|
840
866
|
const content = fs.readFileSync(file, 'utf8');
|
|
841
867
|
const relPath = path.relative(root, file);
|
|
842
868
|
const lowerRel = relPath.toLowerCase();
|
|
869
|
+
const normalizedRel = lowerRel.replace(/[\\/]+/g, '.');
|
|
843
870
|
|
|
844
871
|
let fileLevel = null;
|
|
845
872
|
let filePackage = null;
|
|
846
|
-
for (const [pkg, lvl] of
|
|
847
|
-
if (lowerRel.includes(pkg)) {
|
|
873
|
+
for (const [pkg, lvl] of sortedPkgEntries) {
|
|
874
|
+
if (lowerRel.includes(pkg) || normalizedRel.includes(`.${pkg}.`)) {
|
|
848
875
|
fileLevel = lvl;
|
|
849
876
|
filePackage = pkg;
|
|
850
877
|
break;
|
|
@@ -854,23 +881,37 @@ export async function checkArchitecture(projectRoot, options = {}) {
|
|
|
854
881
|
if (fileLevel === null) continue;
|
|
855
882
|
|
|
856
883
|
const fileTypeCounts = countFileTypeAbstractions(content, file);
|
|
857
|
-
const prevStats = pkgTypeStats.get(filePackage) || {
|
|
884
|
+
const prevStats = pkgTypeStats.get(filePackage) || {
|
|
885
|
+
totalTypes: 0,
|
|
886
|
+
abstractTypes: 0,
|
|
887
|
+
recordTypes: 0
|
|
888
|
+
};
|
|
858
889
|
pkgTypeStats.set(filePackage, {
|
|
859
890
|
totalTypes: prevStats.totalTypes + fileTypeCounts.totalTypes,
|
|
860
|
-
abstractTypes: prevStats.abstractTypes + fileTypeCounts.abstractTypes
|
|
891
|
+
abstractTypes: prevStats.abstractTypes + fileTypeCounts.abstractTypes,
|
|
892
|
+
recordTypes: (prevStats.recordTypes || 0) + (fileTypeCounts.recordTypes || 0)
|
|
861
893
|
});
|
|
862
894
|
|
|
863
895
|
const fileImports = extractFileImports(content, file, fullSrc);
|
|
864
896
|
const seenLinePkgViolations = new Set();
|
|
865
897
|
for (const { imported, line } of fileImports) {
|
|
866
898
|
const lowerImport = imported.toLowerCase();
|
|
867
|
-
|
|
868
|
-
|
|
899
|
+
const normalizedImport = lowerImport.replace(/[\\/]+/g, '.');
|
|
900
|
+
for (const [targetPkg, targetLvl] of sortedPkgEntries) {
|
|
901
|
+
if (lowerImport.includes(targetPkg) || normalizedImport.includes(targetPkg)) {
|
|
869
902
|
if (filePackage && filePackage !== targetPkg) {
|
|
870
903
|
if (!packageEdges.has(filePackage)) {
|
|
871
904
|
packageEdges.set(filePackage, new Set());
|
|
872
905
|
}
|
|
873
906
|
packageEdges.get(filePackage).add(targetPkg);
|
|
907
|
+
|
|
908
|
+
const srcCounts = pkgCouplingCounts.get(filePackage) || { ca: 0, ce: 0 };
|
|
909
|
+
srcCounts.ce += 1;
|
|
910
|
+
pkgCouplingCounts.set(filePackage, srcCounts);
|
|
911
|
+
|
|
912
|
+
const dstCounts = pkgCouplingCounts.get(targetPkg) || { ca: 0, ce: 0 };
|
|
913
|
+
dstCounts.ca += 1;
|
|
914
|
+
pkgCouplingCounts.set(targetPkg, dstCounts);
|
|
874
915
|
}
|
|
875
916
|
if (fileLevel < targetLvl) {
|
|
876
917
|
const dedupKey = `${line}:${targetPkg}`;
|
|
@@ -879,8 +920,10 @@ export async function checkArchitecture(projectRoot, options = {}) {
|
|
|
879
920
|
const baseName = path.basename(file, path.extname(file));
|
|
880
921
|
violations.push({
|
|
881
922
|
fromFile: relPath,
|
|
923
|
+
fromPkg: filePackage || `L${fileLevel}`,
|
|
882
924
|
fromTier: tierNames[fileLevel] || `Level ${fileLevel}`,
|
|
883
925
|
toImport: imported,
|
|
926
|
+
toPkg: targetPkg,
|
|
884
927
|
toTier: tierNames[targetLvl] || `Level ${targetLvl}`,
|
|
885
928
|
portName: `${baseName}Port`,
|
|
886
929
|
line
|
|
@@ -903,7 +946,7 @@ export async function checkArchitecture(projectRoot, options = {}) {
|
|
|
903
946
|
|
|
904
947
|
const cycles = detectPackageCycles(packageEdges);
|
|
905
948
|
const failOnCycles = Boolean(options.detectCycles);
|
|
906
|
-
const maxDistance = calculateMaxMainSequenceDistance(pkgTypeStats, packageEdges);
|
|
949
|
+
const maxDistance = calculateMaxMainSequenceDistance(pkgTypeStats, packageEdges, pkgCouplingCounts);
|
|
907
950
|
|
|
908
951
|
const fitness = calculateArchitectureFitness(
|
|
909
952
|
{
|
|
@@ -936,9 +979,18 @@ export async function checkArchitecture(projectRoot, options = {}) {
|
|
|
936
979
|
? suggestFeatureClusters(allKnownPackages, sourceFiles)
|
|
937
980
|
: null;
|
|
938
981
|
|
|
982
|
+
const serializedEdges = [];
|
|
983
|
+
for (const [fromPkg, targets] of packageEdges.entries()) {
|
|
984
|
+
for (const toPkg of targets) {
|
|
985
|
+
serializedEdges.push({ from: fromPkg, to: toPkg });
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
|
|
939
989
|
return {
|
|
940
990
|
passed,
|
|
941
991
|
projectTitle: policy.title || path.basename(root),
|
|
992
|
+
levels: policy.levels || [],
|
|
993
|
+
edges: serializedEdges,
|
|
942
994
|
sourceFilesCount: sourceFiles.length,
|
|
943
995
|
packagesCount: (policy.order || []).length,
|
|
944
996
|
violationsCount: violations.length,
|
|
@@ -1209,3 +1261,110 @@ export function generateSarifReport(report, options = {}) {
|
|
|
1209
1261
|
export function generateJsonReport(report) {
|
|
1210
1262
|
return JSON.stringify(report, null, 2);
|
|
1211
1263
|
}
|
|
1264
|
+
|
|
1265
|
+
const MERMAID_RING_TITLES = [
|
|
1266
|
+
'Ring L0: Domain Core',
|
|
1267
|
+
'Ring L1: Application',
|
|
1268
|
+
'Ring L2: Adapters',
|
|
1269
|
+
'Ring L3: Infrastructure'
|
|
1270
|
+
];
|
|
1271
|
+
|
|
1272
|
+
function sanitizeMermaidId(raw) {
|
|
1273
|
+
return String(raw || 'node').replace(/[^a-zA-Z0-9_]/g, '_');
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
function escapeMermaidLabel(raw) {
|
|
1277
|
+
return String(raw || '').replace(/"/g, "'").replace(/\n/g, ' ');
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
/**
|
|
1281
|
+
* Generate Mermaid flowchart TB diagram representing Concentric Rings or DIP Refactoring topology.
|
|
1282
|
+
*/
|
|
1283
|
+
export function generateMermaidReport(report, options = {}) {
|
|
1284
|
+
if (!report) {
|
|
1285
|
+
return 'flowchart TB\n Empty["No Architecture Report Available"]\n';
|
|
1286
|
+
}
|
|
1287
|
+
const diagramType = String(options.diagramType || 'COMPONENT_RINGS').toUpperCase();
|
|
1288
|
+
const violations = report.violations || [];
|
|
1289
|
+
|
|
1290
|
+
if (diagramType.includes('DIP')) {
|
|
1291
|
+
const v = violations[0] || {};
|
|
1292
|
+
const srcName = v.fromFile ? path.basename(v.fromFile, path.extname(v.fromFile)) : 'InnerDomainService';
|
|
1293
|
+
const tgtName = v.toImport ? v.toImport.split('.').pop() : 'OuterAdapter';
|
|
1294
|
+
const portName = v.portName || `${tgtName}Port`;
|
|
1295
|
+
return [
|
|
1296
|
+
'flowchart TB',
|
|
1297
|
+
' subgraph Before["❌ Before: Outward Dependency Violation"]',
|
|
1298
|
+
' direction TB',
|
|
1299
|
+
` B_Src["${escapeMermaidLabel(srcName)}"] -->|"❌ Violates Dependency Rule"| B_Tgt["${escapeMermaidLabel(tgtName)}"]`,
|
|
1300
|
+
' end',
|
|
1301
|
+
' subgraph After["✅ After: DIP Port Inversion"]',
|
|
1302
|
+
' direction TB',
|
|
1303
|
+
` A_Src["${escapeMermaidLabel(srcName)}"] -->|"depends on"| A_Port["<<interface>> ${escapeMermaidLabel(portName)}"]`,
|
|
1304
|
+
` A_Tgt["${escapeMermaidLabel(tgtName)}"] -.->|"implements"| A_Port`,
|
|
1305
|
+
' end',
|
|
1306
|
+
' linkStyle 0 stroke:#ef4444,stroke-width:2.5px,color:#fca5a5',
|
|
1307
|
+
' linkStyle 1 stroke:#10b981,stroke-width:2px,color:#6ee7b7',
|
|
1308
|
+
' linkStyle 2 stroke:#10b981,stroke-width:2px,color:#6ee7b7',
|
|
1309
|
+
''
|
|
1310
|
+
].join('\n');
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
const levels = Array.isArray(report.levels) && report.levels.length > 0
|
|
1314
|
+
? report.levels
|
|
1315
|
+
: [['domain'], ['application'], ['adapters'], ['infrastructure']];
|
|
1316
|
+
|
|
1317
|
+
const lines = ['flowchart TB'];
|
|
1318
|
+
levels.forEach((pkgs, lvlIdx) => {
|
|
1319
|
+
if (!Array.isArray(pkgs) || pkgs.length === 0) return;
|
|
1320
|
+
const title = MERMAID_RING_TITLES[lvlIdx] || `Ring L${lvlIdx}`;
|
|
1321
|
+
lines.push(` subgraph Ring_L${lvlIdx}["${title}"]`);
|
|
1322
|
+
for (const pkg of pkgs) {
|
|
1323
|
+
lines.push(` ${sanitizeMermaidId('comp_' + pkg)}["${escapeMermaidLabel(pkg)}"]`);
|
|
1324
|
+
}
|
|
1325
|
+
lines.push(' end');
|
|
1326
|
+
});
|
|
1327
|
+
|
|
1328
|
+
const bundledViolations = new Map();
|
|
1329
|
+
for (const v of violations) {
|
|
1330
|
+
const fromPkg = v.fromPkg || v.fromTier || 'inner';
|
|
1331
|
+
const toPkg = v.toPkg || v.toTier || 'outer';
|
|
1332
|
+
const key = `${fromPkg}->${toPkg}`;
|
|
1333
|
+
bundledViolations.set(key, (bundledViolations.get(key) || 0) + 1);
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
let edgeIdx = 0;
|
|
1337
|
+
const violationEdgeIndices = [];
|
|
1338
|
+
const conformingEdgeIndices = [];
|
|
1339
|
+
const emittedPairs = new Set();
|
|
1340
|
+
|
|
1341
|
+
for (const [key, count] of bundledViolations.entries()) {
|
|
1342
|
+
const [fromPkg, toPkg] = key.split('->');
|
|
1343
|
+
const fromId = sanitizeMermaidId('comp_' + fromPkg);
|
|
1344
|
+
const toId = sanitizeMermaidId('comp_' + toPkg);
|
|
1345
|
+
lines.push(` ${fromId} -->|"❌ VIOLATION (${count})"| ${toId}`);
|
|
1346
|
+
emittedPairs.add(key);
|
|
1347
|
+
violationEdgeIndices.push(edgeIdx++);
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
if (Array.isArray(report.edges)) {
|
|
1351
|
+
for (const edge of report.edges) {
|
|
1352
|
+
const key = `${edge.from}->${edge.to}`;
|
|
1353
|
+
if (emittedPairs.has(key)) continue;
|
|
1354
|
+
emittedPairs.add(key);
|
|
1355
|
+
const fromId = sanitizeMermaidId('comp_' + edge.from);
|
|
1356
|
+
const toId = sanitizeMermaidId('comp_' + edge.to);
|
|
1357
|
+
lines.push(` ${fromId} --> ${toId}`);
|
|
1358
|
+
conformingEdgeIndices.push(edgeIdx++);
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
|
|
1362
|
+
for (const idx of violationEdgeIndices) {
|
|
1363
|
+
lines.push(` linkStyle ${idx} stroke:#ef4444,stroke-width:2.5px,color:#fca5a5`);
|
|
1364
|
+
}
|
|
1365
|
+
for (const idx of conformingEdgeIndices) {
|
|
1366
|
+
lines.push(` linkStyle ${idx} stroke:#64748b,stroke-width:1.5px`);
|
|
1367
|
+
}
|
|
1368
|
+
|
|
1369
|
+
return lines.join('\n') + '\n';
|
|
1370
|
+
}
|