@fmatar/archlens-skill 0.0.1-Alpha-09 → 0.1.0-Beta-02

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/bin/index.js CHANGED
@@ -20,6 +20,7 @@ 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 { checkArchitecture, generateSarifReport, generateJsonReport } from '../src/checker.js';
23
24
  import { installMcpConfigs } from '../src/mcp-registry.js';
24
25
  import { startMcpStdioServer } from '../src/mcp-server.js';
25
26
  import { executeStart, DEFAULT_CONTAINER_NAME, DEFAULT_SERVER_URL } from '../src/docker-runner.js';
@@ -51,6 +52,7 @@ ${ui.colors.bold}USAGE:${ui.colors.reset}
51
52
  ${ui.colors.bold}COMMANDS:${ui.colors.reset}
52
53
  init Initialize Clean Architecture policy in target project (default)
53
54
  start Start Archlens Workbench container (auto-resurrects on demand)
55
+ check Audit repository against Clean Architecture policy rules
54
56
  update Update existing policy with newly discovered packages and refresh skills
55
57
  upgrade Upgrade legacy .uml-viewer configuration to .archlens
56
58
  global Install Archlens skills globally for AI coding assistants
@@ -60,6 +62,11 @@ ${ui.colors.bold}COMMANDS:${ui.colors.reset}
60
62
  ${ui.colors.bold}OPTIONS:${ui.colors.reset}
61
63
  -p, --path <DIR> Target repository path (default: current directory)
62
64
  -t, --title <NAME> Project title displayed in Archlens workbench
65
+ --max-violations <NUM> Maximum allowable outward dependency violations (default: 0)
66
+ --detect-cycles Enforce Robert C. Martin Acyclic Dependencies Principle (ADP)
67
+ --screaming-threshold <NUM> Enforce minimum Screaming Architecture score (0.0-1.0, Uncle Bob Ch. 21)
68
+ --suggest-features Suggest package-by-feature domain refactoring clusters (Uncle Bob Ch. 21)
69
+ --fitness-threshold <NUM> Enforce minimum Architectural Fitness Index (0.0-1.0, Neal Ford)
63
70
  --prefix <PKG> Common package prefix (e.g. com.example.app)
64
71
  --server-url <URL> Archlens visual workbench URL (default: http://localhost:8088)
65
72
  --port <PORT> Workbench HTTP port (default: 8088)
@@ -69,6 +76,8 @@ ${ui.colors.bold}OPTIONS:${ui.colors.reset}
69
76
  -g, --global Install or update skill globally in ~/.claude and ~/.gemini
70
77
  -u, --update Update mode: sync new packages into existing policy
71
78
  --upgrade Upgrade mode: migrate .uml-viewer to .archlens
79
+ --format <FORMAT> Output format: pretty (default), json, sarif
80
+ -O, --output <PATH> Write audit report to specified file path
72
81
  -f, --force Overwrite existing policy files
73
82
  --dry-run Simulate actions without writing files to disk
74
83
  -y, --yes Accept defaults automatically (non-interactive mode)
@@ -123,6 +132,14 @@ function parseArgs(args) {
123
132
  update: false,
124
133
  upgrade: false,
125
134
  mcp: false,
135
+ check: false,
136
+ maxViolations: 0,
137
+ detectCycles: false,
138
+ screamingThreshold: null,
139
+ suggestFeatures: false,
140
+ fitnessThreshold: null,
141
+ format: 'pretty',
142
+ output: null,
126
143
  force: false,
127
144
  dryRun: false,
128
145
  yes: false,
@@ -153,6 +170,22 @@ function parseArgs(args) {
153
170
  parsed.upgrade = true;
154
171
  } else if (arg === '--prompt') {
155
172
  parsed.prompt = true;
173
+ } else if (arg === '--check') {
174
+ parsed.check = true;
175
+ } else if (arg === '--detect-cycles' || arg === '--cycles' || arg === '--fail-on-cycles') {
176
+ parsed.detectCycles = true;
177
+ } else if (arg === '--screaming-threshold' || arg === '--screaming') {
178
+ parsed.screamingThreshold = Number(args[++i] || 0.6);
179
+ } else if (arg === '--suggest-features' || arg === '--suggest' || arg === '--features') {
180
+ parsed.suggestFeatures = true;
181
+ } else if (arg === '--fitness-threshold' || arg === '--fitness') {
182
+ parsed.fitnessThreshold = Number(args[++i] || 0.8);
183
+ } else if (arg === '--max-violations') {
184
+ parsed.maxViolations = Number(args[++i] || 0);
185
+ } else if (arg === '--format') {
186
+ parsed.format = (args[++i] || 'pretty').toLowerCase();
187
+ } else if (arg === '--output' || arg === '-O') {
188
+ parsed.output = args[++i];
156
189
  } else if (arg === '--copy' || arg === '-c') {
157
190
  parsed.copy = true;
158
191
  } else if (arg === '--force' || arg === '-f') {
@@ -176,7 +209,7 @@ function parseArgs(args) {
176
209
 
177
210
  if (positional.length > 0) {
178
211
  const cmd = positional[0].toLowerCase();
179
- if (['init', 'start', 'update', 'upgrade', 'global', 'prompt', 'mcp', 'help', 'version'].includes(cmd)) {
212
+ if (['init', 'start', 'update', 'upgrade', 'global', 'prompt', 'mcp', 'check', 'help', 'version'].includes(cmd)) {
180
213
  parsed.command = cmd;
181
214
  } else if (!parsed.title && !parsed.path) {
182
215
  parsed.path = positional[0];
@@ -190,6 +223,7 @@ function parseArgs(args) {
190
223
  if (parsed.command === 'upgrade') parsed.upgrade = true;
191
224
  if (parsed.command === 'global') parsed.global = true;
192
225
  if (parsed.command === 'prompt') parsed.prompt = true;
226
+ if (parsed.command === 'check') parsed.check = true;
193
227
  if (parsed.command === 'mcp') parsed.mcp = true;
194
228
 
195
229
  return parsed;
@@ -410,6 +444,7 @@ function copyToSystemClipboard(text) {
410
444
 
411
445
  async function main() {
412
446
  const options = parseArgs(process.argv.slice(2));
447
+ const targetRoot = path.resolve(options.path || '.');
413
448
 
414
449
  if (options.help) {
415
450
  printHelp();
@@ -422,7 +457,6 @@ async function main() {
422
457
  }
423
458
 
424
459
  if (options.command === 'prompt' || options.prompt) {
425
- const targetRoot = path.resolve(options.path || '.');
426
460
  try {
427
461
  const dossier = await generateLlmPrompt(targetRoot, options);
428
462
  if (options.copy) {
@@ -442,6 +476,132 @@ async function main() {
442
476
  }
443
477
  }
444
478
 
479
+ if (options.command === 'check' || options.check) {
480
+ try {
481
+ if (options.format === 'pretty') {
482
+ ui.info(`Auditing Clean Architecture conformance for ${targetRoot}...`);
483
+ }
484
+ const report = await checkArchitecture(targetRoot, options);
485
+ if (report.error) {
486
+ ui.error(report.error);
487
+ process.exit(1);
488
+ }
489
+
490
+ let formattedOutput = null;
491
+ if (options.format === 'sarif') {
492
+ formattedOutput = generateSarifReport(report, { version: getPackageVersion() });
493
+ } else if (options.format === 'json') {
494
+ formattedOutput = generateJsonReport(report);
495
+ }
496
+
497
+ if (options.output) {
498
+ const outPath = path.resolve(options.output);
499
+ const dir = path.dirname(outPath);
500
+ if (!fs.existsSync(dir)) {
501
+ fs.mkdirSync(dir, { recursive: true });
502
+ }
503
+ fs.writeFileSync(outPath, formattedOutput || generateJsonReport(report), 'utf8');
504
+ if (options.format === 'pretty') {
505
+ ui.success(`Architecture report written to ${options.output}`);
506
+ }
507
+ }
508
+
509
+ if (options.format === 'sarif' || options.format === 'json') {
510
+ if (!options.output) {
511
+ process.stdout.write(formattedOutput + '\n');
512
+ }
513
+ process.exit(report.passed ? 0 : 1);
514
+ }
515
+
516
+ console.log(`\n ${ui.colors.bold}Architecture Governance Results (${report.projectTitle}):${ui.colors.reset}`);
517
+ console.log(` - Source Files Analyzed: ${report.sourceFilesCount}`);
518
+ console.log(` - Governed Packages: ${report.packagesCount}`);
519
+ console.log(` - Detected Violations: ${report.violationsCount} (threshold: ${report.maxViolations})`);
520
+ if (report.cyclesCount > 0) {
521
+ console.log(` - Package Cycles (ADP): ${report.cyclesCount} cycle(s) detected`);
522
+ report.cycles.forEach((c, idx) => {
523
+ console.log(` [C${idx + 1}] ${c.formatted}`);
524
+ });
525
+ }
526
+ if (report.screaming) {
527
+ console.log(` - Screaming Score (SAS): ${report.screaming.score.toFixed(2)} [${report.screaming.classification}] (${report.screaming.domainPackageCount} domain / ${report.screaming.totalPackageCount} packages)`);
528
+ if (report.screamingThreshold !== null) {
529
+ console.log(` - Screaming Threshold: ${report.screamingThreshold.toFixed(2)} (required minimum)`);
530
+ }
531
+ }
532
+ if (report.featureClusters && report.featureClusters.clusters.length > 0) {
533
+ console.log(` - Feature Migration: ${report.featureClusters.clusters.length} feature cluster(s) proposed`);
534
+ console.log(` Projected SAS Gain: ${report.featureClusters.currentScore.toFixed(2)} -> ${report.featureClusters.projectedScore.toFixed(2)} [${report.featureClusters.projectedClassification}]`);
535
+ report.featureClusters.clusters.forEach((c) => {
536
+ console.log(` 🪄 [Feature: ${c.featureName}] (${c.classCount} classes) -> ${c.proposedPackageName}`);
537
+ console.log(` Classes: ${c.classNames.join(', ')}`);
538
+ });
539
+ }
540
+ if (report.fitness) {
541
+ console.log(` - Fitness Score (AFI): ${(report.fitness.fitnessScore * 100).toFixed(0)}% [Grade ${report.fitness.grade}] (${report.fitness.passedRuleCount}/${report.fitness.totalRuleCount} rules passed)`);
542
+ if (report.fitnessThreshold !== null && !isNaN(report.fitnessThreshold)) {
543
+ console.log(` - Fitness Threshold: ${(report.fitnessThreshold * 100).toFixed(0)}% (required minimum)`);
544
+ }
545
+ report.fitness.rules.forEach((r) => {
546
+ const status = r.passed ? `${ui.colors.green}PASS${ui.colors.reset}` : `${ui.colors.red}FAIL${ui.colors.reset}`;
547
+ console.log(` [${status}] ${r.name}: actual=${r.actualValue}, threshold=${r.threshold}`);
548
+ });
549
+ }
550
+ console.log();
551
+
552
+ const failOnScreaming =
553
+ report.screamingThreshold !== null &&
554
+ report.screaming &&
555
+ report.screaming.score < report.screamingThreshold;
556
+
557
+ const failOnFitness =
558
+ report.fitnessThreshold !== null &&
559
+ !isNaN(report.fitnessThreshold) &&
560
+ report.fitness &&
561
+ report.fitness.fitnessScore < report.fitnessThreshold;
562
+
563
+ if (report.passed) {
564
+ ui.success(
565
+ `Clean Architecture Gate PASSED (0 violations exceeding threshold${
566
+ options.detectCycles ? ', 0 package cycles' : ''
567
+ }${report.screamingThreshold !== null ? `, screaming score ${report.screaming.score.toFixed(2)} >= ${report.screamingThreshold.toFixed(2)}` : ''}${report.fitnessThreshold !== null && !isNaN(report.fitnessThreshold) ? `, fitness ${(report.fitness.fitnessScore * 100).toFixed(0)}% >= ${(report.fitnessThreshold * 100).toFixed(0)}%` : ''}).`
568
+ );
569
+ process.exit(0);
570
+ } else {
571
+ ui.error(
572
+ `Clean Architecture Gate FAILED (${report.violationsCount} violation(s), ${
573
+ report.cyclesCount || 0
574
+ } cycle(s)${failOnScreaming ? ', screaming score below threshold' : ''}${failOnFitness ? ', fitness below threshold' : ''})!`
575
+ );
576
+ report.violations.forEach((v, idx) => {
577
+ console.log(
578
+ ` [${idx + 1}] ${v.fromFile}:${v.line || 1} (${v.fromTier}) -> ${v.toImport} (${v.toTier})`
579
+ );
580
+ console.log(` Prescribed Port: ${v.portName}`);
581
+ });
582
+ if (report.cycles && report.cycles.length > 0) {
583
+ console.log(`\n Package Dependency Cycles (ADP Violations):`);
584
+ report.cycles.forEach((c, idx) => {
585
+ console.log(` [C${idx + 1}] ${c.formatted}`);
586
+ });
587
+ }
588
+ if (failOnScreaming) {
589
+ console.log(`\n Screaming Architecture Violation:`);
590
+ console.log(` Score ${report.screaming.score.toFixed(2)} is below required threshold ${report.screamingThreshold.toFixed(2)}.`);
591
+ console.log(` Technical packages (${report.screaming.technicalPackages.length}): ${report.screaming.technicalPackages.join(', ')}`);
592
+ }
593
+ if (failOnFitness) {
594
+ console.log(`\n Architectural Fitness Invariant Violation:`);
595
+ console.log(` Fitness Score ${(report.fitness.fitnessScore * 100).toFixed(0)}% [Grade ${report.fitness.grade}] is below required threshold ${(report.fitnessThreshold * 100).toFixed(0)}%.`);
596
+ }
597
+ process.exit(1);
598
+ }
599
+ } catch (err) {
600
+ ui.error(err.message || String(err));
601
+ process.exit(1);
602
+ }
603
+ }
604
+
445
605
  if (options.command === 'mcp') {
446
606
  startMcpStdioServer({
447
607
  version: getPackageVersion(),
@@ -503,8 +663,6 @@ async function main() {
503
663
  }
504
664
 
505
665
  // Non-interactive or flag-driven execution
506
- const targetRoot = path.resolve(options.path || '.');
507
-
508
666
  try {
509
667
  if (options.upgrade) {
510
668
  executeUpgrade(targetRoot, options);
package/llms.txt ADDED
@@ -0,0 +1,131 @@
1
+ # Archlens
2
+
3
+ > Dynamic Clean Architecture Governance Workbench, Automated Fitness Inspector & Autonomous Refactoring Companion.
4
+
5
+ Archlens models software systems as concentric Clean Architecture rings, continuously audits codebase dependency flow, detects architectural drift (layer leaks, package cycles, technical packaging decay, distance from the main sequence), and prescribes concrete Dependency Inversion Principle (DIP) interface ports for automated refactoring.
6
+
7
+ ---
8
+
9
+ ## 🏛️ Clean Architecture Concentric Hierarchy
10
+
11
+ Source code dependencies must point strictly inward toward higher-level policies (Uncle Bob's Dependency Rule):
12
+
13
+ ```
14
+ [Level 3: Infrastructure / Web / DB / CLI / Frameworks]
15
+ │
16
+ ▼
17
+ [Level 2: Adapters / Controllers / Presenters / Gateways / Repositories]
18
+ │
19
+ ▼
20
+ [Level 1: Application / Use Cases / Interaction Orchestrators / Ports]
21
+ │
22
+ ▼
23
+ [Level 0: Domain Core / Entities / Value Objects / Domain Logic]
24
+ ```
25
+
26
+ - **Level 0: Domain Core** (`domain.model`, `domain.entity`, `core.domain`):
27
+ Pure business rules, primitives, entities, and domain logic. Zero outward imports or dependencies on frameworks, databases, network libraries, or UI.
28
+ - **Level 1: Application** (`usecase`, `application`, `core.ports`, `domain.ports`):
29
+ Application workflows, use cases, and business orchestration. Depends only on Level 0 (Domain Core). Declares outbound interface ports.
30
+ - **Level 2: Adapters** (`resource`, `controller`, `presenter`, `gateway`, `repository.impl`):
31
+ Translates external delivery protocols (HTTP, REST, CLI, gRPC) and storage models to application formats. Implements application/domain ports.
32
+ - **Level 3: Infrastructure** (`infrastructure`, `config`, `persistence.entity`, `framework`):
33
+ Framework drivers (Quarkus, Spring, Express), database engines, third-party network clients, and entrypoint bootstrap wiring.
34
+
35
+ ---
36
+
37
+ ## 🔍 Governed Architectural Invariants & Drifts
38
+
39
+ Archlens continuously evaluates five foundational architectural invariants:
40
+
41
+ 1. **Concentric Dependency Rule (Layer Drift)**:
42
+ - **Invariant**: Inner rings must never depend on outer rings ($L_i \nrightarrow L_j$ where $i < j$).
43
+ - **Remediation**: Apply Dependency Inversion Principle (DIP). Declare an interface port in $L_i$ and implement it in $L_j$.
44
+ 2. **Acyclic Dependencies Principle (ADP)**:
45
+ - **Invariant**: The component/package dependency structure must be a Directed Acyclic Graph (DAG) with zero cycles.
46
+ - **Remediation**: Break cycles using interface extraction or merging interdependent feature packages.
47
+ 3. **Screaming Architecture Invariant (SAS)**:
48
+ - **Invariant**: Systems should scream business domain use cases rather than framework technology (Uncle Bob Ch. 21).
49
+ - **Metric**: Screaming Architecture Score (SAS) from 0.0 to 1.0 (Feature vs Technical packaging). Minimum threshold: $\ge 0.70$.
50
+ 4. **Main Sequence Balance Invariant ($A, I, D$)**:
51
+ - **Invariant**: Components must remain in the balanced corridor avoiding the **Zone of Pain** (brittle, highly concrete, widely depended upon) and the **Zone of Uselessness** (abstract with no dependents).
52
+ - **Metric**: Normalized distance from Main Sequence: $D = |A + I - 1| \le 0.35$.
53
+ 5. **Architectural Fitness Index (AFI) & Trend Regression**:
54
+ - **Invariant**: Architecture fitness must remain stable or improve across releases.
55
+ - **Metric**: Composite AFI score (0–100%) and letter grade (A through F) tracking historical drift across Git release tags.
56
+
57
+ ---
58
+
59
+ ## ⚡ Command Line Interface (CLI)
60
+
61
+ Archlens CLI requires zero external dependencies and runs cross-platform via Node.js / NPX:
62
+
63
+ ```bash
64
+ # 1. Audit Codebase Conformance & Detect All Architectural Drifts:
65
+ npx @fmatar/archlens-skill check
66
+ npx @fmatar/archlens-skill check --detect-cycles --screaming-threshold 0.70 --fitness-threshold 0.85
67
+ npx @fmatar/archlens-skill check --format json
68
+ npx @fmatar/archlens-skill check --format sarif -O arch-drift.sarif
69
+
70
+ # 2. Export Actionable LLM Refactoring Prompt Dossier (with DIP Interface Prescriptions):
71
+ npx @fmatar/archlens-skill prompt
72
+ npx @fmatar/archlens-skill prompt --copy
73
+
74
+ # 3. Launch Dynamic Visual Workbench (Auto-resurrects Docker container on demand):
75
+ npx @fmatar/archlens-skill start --open
76
+
77
+ # 4. Initialize or Synchronize Policy:
78
+ npx @fmatar/archlens-skill init --yes
79
+ npx @fmatar/archlens-skill update
80
+
81
+ # 5. Model Context Protocol (MCP) Integration:
82
+ npx @fmatar/archlens-skill --mcp # Auto-configure Claude, Antigravity, Cursor manifests
83
+ npx @fmatar/archlens-skill mcp # Launch MCP stdio bridge server
84
+ ```
85
+
86
+ ---
87
+
88
+ ## 🤖 Model Context Protocol (MCP) Tools & Resources
89
+
90
+ When Archlens is registered as an MCP server, AI assistants can query it using standard MCP primitives:
91
+
92
+ ### MCP Tools:
93
+ | Tool Name | Parameters | Purpose |
94
+ | :--- | :--- | :--- |
95
+ | `exportLlmDossier` | `projectRoot` (default: `.`), `proposalId` | Diagnoses outward dependency breaches and outputs a Markdown refactoring prompt with concrete DIP interface port prescriptions. |
96
+ | `inspectArchitecture` | `projectRoot` (default: `.`) | Returns full JSON graph model: concentric rings, dependency edges, cycle paths, and screaming metrics. |
97
+ | `listSnapshots` | `projectRoot` (default: `.`) | Lists historical architecture release snapshots in `.archlens/snapshots/` and Git release tags. |
98
+ | `getSnapshot` | `snapshotId` (required), `projectRoot` | Retrieves the graph model of a specific historical snapshot or Git tag for temporal drift diffing. |
99
+
100
+ ### MCP Resources:
101
+ | Resource URI | MIME Type | Description |
102
+ | :--- | :--- | :--- |
103
+ | `archlens://llms.txt` | `text/markdown` | This authoritative reference guide, Clean Architecture rules, CLI recipes, and refactoring protocols. |
104
+
105
+ ---
106
+
107
+ ## 🛠️ Step-by-Step Refactoring Protocol for LLMs
108
+
109
+ When Archlens reports an illegal outward dependency breach (e.g. `domain/Order.java` imports `infrastructure/OrderRepository.java`):
110
+
111
+ 1. **Isolate Dependency**: Identify the methods called on the outer dependency by the inner class.
112
+ 2. **Declare Interface Port**:
113
+ - Location: Inside the inner layer (`domain/ports/` or `application/ports/`).
114
+ - Signature: Define an interface (e.g. `OrderRepositoryPort`) declaring only the domain-relevant contracts.
115
+ 3. **Implement Port in Outer Layer**:
116
+ - Make the outer class (e.g. `infrastructure/persistence/OrderRepository.java`) implement `OrderRepositoryPort`.
117
+ 4. **Invert Injection**:
118
+ - Inject `OrderRepositoryPort` into the inner class using constructor injection or framework dependency injection (`@Inject` / `@Autowired`).
119
+ 5. **Verify**:
120
+ - Run `npx @fmatar/archlens-skill check --detect-cycles` to confirm zero violations.
121
+ - Run the project test suite to verify zero functional regressions.
122
+
123
+ ---
124
+
125
+ ## 🔄 Dynamic Workbench Autonomous Companion Protocol
126
+
127
+ When human architects interact with the Archlens visual workbench canvas (`http://localhost:8088`), tasks are dispatched via bidirectional mailbox IPC:
128
+ - **Inbound queue (UI $\rightarrow$ Agent)**: `.archlens/to-agent.json`
129
+ - Operations: `REGEN` (recompile AST), `APPLY_PROPOSAL` (restructure packages), `REFRESH_CRAP`, `OMIT`.
130
+ - **Outbound events (Agent $\rightarrow$ UI)**: `.archlens/to-viewer.json`
131
+ - Write completion events (e.g. `{"op": "REGEN_COMPLETE", "payload": {"status": "SUCCESS"}}`) to trigger hot-reload of the visual canvas via Server-Sent Events (SSE).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fmatar/archlens-skill",
3
- "version": "0.0.1-Alpha-09",
3
+ "version": "0.1.0-Beta-02",
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",
@@ -13,7 +13,8 @@
13
13
  "src",
14
14
  "skills",
15
15
  "README.md",
16
- "LICENSE"
16
+ "LICENSE",
17
+ "llms.txt"
17
18
  ],
18
19
  "engines": {
19
20
  "node": ">=18.0.0"
package/src/checker.js ADDED
@@ -0,0 +1,736 @@
1
+ /**
2
+ * Archlens Architecture Conformance Checker
3
+ * Audits repository against .archlens/policy.json Clean Architecture rules.
4
+ * Enforces zero outward dependency violations and configurable thresholds for CI/CD gates.
5
+ * Generates human-readable, JSON, and SARIF 2.1.0 reports for GitHub Code Scanning.
6
+ * Zero external dependencies.
7
+ */
8
+
9
+ import * as fs from 'node:fs';
10
+ import * as path from 'node:path';
11
+
12
+ function findMatchingFiles(dir, predicate, maxFiles = 500, results = []) {
13
+ if (!fs.existsSync(dir) || results.length >= maxFiles) return results;
14
+
15
+ try {
16
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
17
+ for (const entry of entries) {
18
+ if (results.length >= maxFiles) break;
19
+ const fullPath = path.join(dir, entry.name);
20
+
21
+ if (entry.isDirectory()) {
22
+ if (
23
+ entry.name.startsWith('.') ||
24
+ entry.name === 'node_modules' ||
25
+ entry.name === 'target' ||
26
+ entry.name === 'dist' ||
27
+ entry.name === 'build'
28
+ ) {
29
+ continue;
30
+ }
31
+ findMatchingFiles(fullPath, predicate, maxFiles, results);
32
+ } else if (predicate(entry.name)) {
33
+ results.push(fullPath);
34
+ }
35
+ }
36
+ } catch {
37
+ // Ignore unreadable directories
38
+ }
39
+
40
+ return results;
41
+ }
42
+
43
+ export function loadProjectPolicy(projectRoot) {
44
+ const root = path.resolve(projectRoot);
45
+ const candidates = [
46
+ path.join(root, '.archlens', 'policy.json'),
47
+ path.join(root, '.uml-viewer', 'policy.json'),
48
+ path.join(root, 'policy.json')
49
+ ];
50
+
51
+ for (const candidate of candidates) {
52
+ if (fs.existsSync(candidate)) {
53
+ try {
54
+ return JSON.parse(fs.readFileSync(candidate, 'utf8'));
55
+ } catch (err) {
56
+ throw new Error(`Failed to parse policy at ${candidate}: ${err.message}`);
57
+ }
58
+ }
59
+ }
60
+
61
+ return null;
62
+ }
63
+
64
+ export const TECHNICAL_MARKERS = new Set([
65
+ 'controller',
66
+ 'controllers',
67
+ 'service',
68
+ 'services',
69
+ 'dao',
70
+ 'daos',
71
+ 'repository',
72
+ 'repositories',
73
+ 'dto',
74
+ 'dtos',
75
+ 'model',
76
+ 'models',
77
+ 'entity',
78
+ 'entities',
79
+ 'util',
80
+ 'utils',
81
+ 'helper',
82
+ 'helpers',
83
+ 'common',
84
+ 'infra',
85
+ 'infrastructure',
86
+ 'adapter',
87
+ 'adapters',
88
+ 'resource',
89
+ 'resources',
90
+ 'api',
91
+ 'endpoint',
92
+ 'endpoints',
93
+ 'view',
94
+ 'views',
95
+ 'handler',
96
+ 'handlers'
97
+ ]);
98
+
99
+ export function calculateScreamingMetric(packages) {
100
+ if (!packages || packages.length === 0) {
101
+ return {
102
+ score: 1.0,
103
+ domainPackageCount: 0,
104
+ technicalPackageCount: 0,
105
+ totalPackageCount: 0,
106
+ classification: 'PACKAGE_BY_FEATURE',
107
+ domainPackages: [],
108
+ technicalPackages: []
109
+ };
110
+ }
111
+
112
+ const domainPackages = [];
113
+ const technicalPackages = [];
114
+
115
+ for (const pkg of packages) {
116
+ const lower = pkg.toLowerCase();
117
+ const leaf = lower.includes('.') ? lower.substring(lower.lastIndexOf('.') + 1) : lower;
118
+ if (TECHNICAL_MARKERS.has(leaf) || TECHNICAL_MARKERS.has(lower)) {
119
+ technicalPackages.push(pkg);
120
+ } else {
121
+ let isTech = false;
122
+ for (const segment of lower.split('.')) {
123
+ if (TECHNICAL_MARKERS.has(segment)) {
124
+ isTech = true;
125
+ break;
126
+ }
127
+ }
128
+ if (isTech) {
129
+ technicalPackages.push(pkg);
130
+ } else {
131
+ domainPackages.push(pkg);
132
+ }
133
+ }
134
+ }
135
+
136
+ const total = domainPackages.length + technicalPackages.length;
137
+ const score = total > 0 ? Math.round((domainPackages.length / total) * 100) / 100 : 1.0;
138
+ let classification = 'PACKAGE_BY_LAYER';
139
+ if (score >= 0.75) classification = 'PACKAGE_BY_FEATURE';
140
+ else if (score >= 0.40) classification = 'HYBRID';
141
+
142
+ return {
143
+ score,
144
+ domainPackageCount: domainPackages.length,
145
+ technicalPackageCount: technicalPackages.length,
146
+ totalPackageCount: total,
147
+ classification,
148
+ domainPackages,
149
+ technicalPackages
150
+ };
151
+ }
152
+
153
+ export const TECHNICAL_SUFFIXES = [
154
+ 'Controllers',
155
+ 'Controller',
156
+ 'Resources',
157
+ 'Resource',
158
+ 'Endpoints',
159
+ 'Endpoint',
160
+ 'Services',
161
+ 'ServiceImpl',
162
+ 'Service',
163
+ 'Repositories',
164
+ 'Repository',
165
+ 'Repos',
166
+ 'Repo',
167
+ 'Daos',
168
+ 'Dao',
169
+ 'Dtos',
170
+ 'Dto',
171
+ 'Entities',
172
+ 'Entity',
173
+ 'Models',
174
+ 'Model',
175
+ 'Views',
176
+ 'View',
177
+ 'Handlers',
178
+ 'Handler',
179
+ 'Validators',
180
+ 'Validator',
181
+ 'Adapters',
182
+ 'Adapter',
183
+ 'Helpers',
184
+ 'Helper',
185
+ 'Utils',
186
+ 'Util'
187
+ ];
188
+
189
+ export const TECHNICAL_PREFIXES = [
190
+ 'Default',
191
+ 'Abstract',
192
+ 'Base',
193
+ 'Postgres',
194
+ 'Jpa',
195
+ 'Mongo',
196
+ 'Sql',
197
+ 'Http'
198
+ ];
199
+
200
+ export function extractFeatureToken(className) {
201
+ if (!className || typeof className !== 'string') return null;
202
+ let candidate = className;
203
+ for (const prefix of TECHNICAL_PREFIXES) {
204
+ if (candidate.startsWith(prefix) && candidate.length > prefix.length + 2) {
205
+ candidate = candidate.substring(prefix.length);
206
+ break;
207
+ }
208
+ }
209
+ for (const suffix of TECHNICAL_SUFFIXES) {
210
+ if (candidate.endsWith(suffix) && candidate.length > suffix.length) {
211
+ candidate = candidate.substring(0, candidate.length - suffix.length);
212
+ break;
213
+ }
214
+ }
215
+ candidate = candidate.replace(/[0-9_]+$/, '');
216
+ if (
217
+ TECHNICAL_PREFIXES.includes(candidate) ||
218
+ TECHNICAL_SUFFIXES.includes(candidate) ||
219
+ TECHNICAL_MARKERS.has(candidate.toLowerCase())
220
+ ) {
221
+ return null;
222
+ }
223
+ return candidate.length >= 3 ? candidate : null;
224
+ }
225
+
226
+ export function suggestFeatureClusters(packages, sourceFiles = []) {
227
+ const currentMetric = calculateScreamingMetric(packages);
228
+ const techPkgSet = new Set(currentMetric.technicalPackages.map((p) => p.toLowerCase()));
229
+
230
+ if (techPkgSet.size === 0) {
231
+ return {
232
+ currentScore: currentMetric.score,
233
+ projectedScore: currentMetric.score,
234
+ currentClassification: currentMetric.classification,
235
+ projectedClassification: currentMetric.classification,
236
+ clusters: [],
237
+ stagedClassMoves: {},
238
+ unclusteredClasses: []
239
+ };
240
+ }
241
+
242
+ const technicalClasses = [];
243
+ for (const file of sourceFiles) {
244
+ const ext = path.extname(file);
245
+ const className = path.basename(file, ext);
246
+ const lowerFile = file.toLowerCase();
247
+
248
+ let filePkg = null;
249
+ for (const pkg of currentMetric.technicalPackages) {
250
+ const pkgPath = pkg.toLowerCase().replace(/\./g, path.sep);
251
+ if (lowerFile.includes(pkgPath) || lowerFile.includes(pkg.toLowerCase())) {
252
+ filePkg = pkg;
253
+ break;
254
+ }
255
+ }
256
+
257
+ if (filePkg) {
258
+ technicalClasses.push({
259
+ className,
260
+ packageName: filePkg,
261
+ filePath: file
262
+ });
263
+ }
264
+ }
265
+
266
+ const tokenToClasses = new Map();
267
+ for (const cls of technicalClasses) {
268
+ const token = extractFeatureToken(cls.className);
269
+ if (token) {
270
+ if (!tokenToClasses.has(token)) {
271
+ tokenToClasses.set(token, []);
272
+ }
273
+ tokenToClasses.get(token).push(cls);
274
+ }
275
+ }
276
+
277
+ const clusters = [];
278
+ const stagedClassMoves = {};
279
+ const clusteredClassNames = new Set();
280
+
281
+ for (const [token, classes] of tokenToClasses.entries()) {
282
+ const sourcePkgs = new Set(classes.map((c) => c.packageName));
283
+ if (classes.length >= 2 || sourcePkgs.size >= 2) {
284
+ const featureName = token.charAt(0).toUpperCase() + token.slice(1);
285
+ const firstPkg = Array.from(sourcePkgs)[0];
286
+ const parts = firstPkg.split('.');
287
+ let basePrefix = '';
288
+ if (parts.length > 1) {
289
+ basePrefix = parts.slice(0, -1).join('.') + '.';
290
+ }
291
+ const proposedPackage = `${basePrefix}${token.toLowerCase()}`;
292
+
293
+ clusters.push({
294
+ featureName,
295
+ proposedPackageName: proposedPackage,
296
+ classNames: classes.map((c) => c.className),
297
+ sourcePackages: Array.from(sourcePkgs).sort(),
298
+ classCount: classes.length
299
+ });
300
+
301
+ for (const cls of classes) {
302
+ stagedClassMoves[cls.className] = proposedPackage;
303
+ clusteredClassNames.add(cls.className);
304
+ }
305
+ }
306
+ }
307
+
308
+ clusters.sort((a, b) => a.featureName.localeCompare(b.featureName));
309
+
310
+ const unclustered = technicalClasses
311
+ .filter((c) => !clusteredClassNames.has(c.className))
312
+ .map((c) => c.className)
313
+ .sort();
314
+
315
+ const projectedPackages = new Set();
316
+ for (const pkg of packages) {
317
+ if (!techPkgSet.has(pkg.toLowerCase())) {
318
+ projectedPackages.add(pkg);
319
+ }
320
+ }
321
+ for (const cluster of clusters) {
322
+ projectedPackages.add(cluster.proposedPackageName);
323
+ }
324
+
325
+ const projectedMetric = calculateScreamingMetric(Array.from(projectedPackages));
326
+
327
+ return {
328
+ currentScore: currentMetric.score,
329
+ projectedScore: projectedMetric.score,
330
+ currentClassification: currentMetric.classification,
331
+ projectedClassification: projectedMetric.classification,
332
+ clusters,
333
+ stagedClassMoves,
334
+ unclusteredClasses: unclustered
335
+ };
336
+ }
337
+
338
+ export async function checkArchitecture(projectRoot, options = {}) {
339
+ const root = path.resolve(projectRoot || '.');
340
+ const policy = loadProjectPolicy(root);
341
+
342
+ if (!policy) {
343
+ return {
344
+ passed: false,
345
+ violationsCount: 0,
346
+ violations: [],
347
+ error: `No Archlens policy found in ${root}. Run 'npx @fmatar/archlens-skill init' first.`
348
+ };
349
+ }
350
+
351
+ const maxViolations = options.maxViolations !== undefined ? Number(options.maxViolations) : 0;
352
+ const levels = policy.levels || [];
353
+ const tierNames = ['Domain Core (L0)', 'Application (L1)', 'Adapters (L2)', 'Infrastructure (L3)'];
354
+
355
+ const pkgToLevel = new Map();
356
+ levels.forEach((tier, lvl) => {
357
+ tier.forEach((p) => pkgToLevel.set(p.toLowerCase(), lvl));
358
+ });
359
+
360
+ const fullSrc = path.join(root, policy.src || 'src');
361
+ const sourceFiles = findMatchingFiles(
362
+ fullSrc,
363
+ (f) => f.endsWith('.java') || f.endsWith('.kt') || f.endsWith('.ts') || f.endsWith('.js'),
364
+ 500
365
+ );
366
+
367
+ const violations = [];
368
+ const packageEdges = new Map();
369
+ const importRegex = /import\s+(?:static\s+)?([a-zA-Z0-9_.]+)/;
370
+
371
+ for (const file of sourceFiles) {
372
+ try {
373
+ const content = fs.readFileSync(file, 'utf8');
374
+ const relPath = path.relative(root, file);
375
+ const lowerRel = relPath.toLowerCase();
376
+
377
+ let fileLevel = null;
378
+ let filePackage = null;
379
+ for (const [pkg, lvl] of pkgToLevel.entries()) {
380
+ if (lowerRel.includes(pkg)) {
381
+ fileLevel = lvl;
382
+ filePackage = pkg;
383
+ break;
384
+ }
385
+ }
386
+
387
+ if (fileLevel === null) continue;
388
+
389
+ const lines = content.split('\n');
390
+ for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
391
+ const line = lines[lineIndex];
392
+ const match = importRegex.exec(line);
393
+ if (match) {
394
+ const imported = match[1];
395
+ const lowerImport = imported.toLowerCase();
396
+ for (const [targetPkg, targetLvl] of pkgToLevel.entries()) {
397
+ if (lowerImport.includes(targetPkg)) {
398
+ if (filePackage && filePackage !== targetPkg) {
399
+ if (!packageEdges.has(filePackage)) {
400
+ packageEdges.set(filePackage, new Set());
401
+ }
402
+ packageEdges.get(filePackage).add(targetPkg);
403
+ }
404
+ if (fileLevel < targetLvl) {
405
+ const baseName = path.basename(file, path.extname(file));
406
+ violations.push({
407
+ fromFile: relPath,
408
+ fromTier: tierNames[fileLevel] || `Level ${fileLevel}`,
409
+ toImport: imported,
410
+ toTier: tierNames[targetLvl] || `Level ${targetLvl}`,
411
+ portName: `${baseName}Port`,
412
+ line: lineIndex + 1
413
+ });
414
+ }
415
+ break;
416
+ }
417
+ }
418
+ }
419
+ }
420
+ } catch {
421
+ // Ignore unreadable files
422
+ }
423
+ }
424
+
425
+ const allKnownPackages = Array.from(pkgToLevel.keys());
426
+ const screaming = calculateScreamingMetric(allKnownPackages);
427
+ const screamingThreshold = options.screamingThreshold !== undefined ? Number(options.screamingThreshold) : null;
428
+ const failOnScreaming = screamingThreshold !== null && screaming.score < screamingThreshold;
429
+
430
+ const cycles = detectPackageCycles(packageEdges);
431
+ const failOnCycles = Boolean(options.detectCycles);
432
+
433
+ const fitness = calculateArchitectureFitness(
434
+ {
435
+ violationsCount: violations.length,
436
+ cyclesCount: cycles.length,
437
+ screamingScore: screaming.score,
438
+ maxDistance: 0.12
439
+ },
440
+ policy.fitness || {}
441
+ );
442
+
443
+ const fitnessThreshold =
444
+ options.fitnessThreshold !== undefined && options.fitnessThreshold !== null
445
+ ? parseFloat(options.fitnessThreshold)
446
+ : (typeof policy.fitness?.threshold === 'number'
447
+ ? policy.fitness.threshold
448
+ : null);
449
+ const failOnFitness =
450
+ fitnessThreshold !== null &&
451
+ !isNaN(fitnessThreshold) &&
452
+ fitness.fitnessScore < fitnessThreshold;
453
+
454
+ const passed =
455
+ violations.length <= maxViolations &&
456
+ (!failOnCycles || cycles.length === 0) &&
457
+ !failOnScreaming &&
458
+ !failOnFitness;
459
+
460
+ const featureClusters = options.suggestFeatures
461
+ ? suggestFeatureClusters(allKnownPackages, sourceFiles)
462
+ : null;
463
+
464
+ return {
465
+ passed,
466
+ projectTitle: policy.title || path.basename(root),
467
+ sourceFilesCount: sourceFiles.length,
468
+ packagesCount: (policy.order || []).length,
469
+ violationsCount: violations.length,
470
+ cyclesCount: cycles.length,
471
+ maxViolations,
472
+ screamingThreshold,
473
+ screaming,
474
+ fitnessThreshold,
475
+ fitness,
476
+ violations,
477
+ cycles,
478
+ featureClusters
479
+ };
480
+ }
481
+
482
+ /**
483
+ * Calculate composite Architectural Fitness Index (AFI), grade, and rule compliance.
484
+ */
485
+ export function calculateArchitectureFitness(metrics, thresholds = {}) {
486
+ const maxViolations = thresholds.maxViolations ?? 0;
487
+ const maxCycles = thresholds.maxCycles ?? 0;
488
+ const minScreamingScore = thresholds.minScreamingScore ?? 0.70;
489
+ const maxMainSequenceDistance = thresholds.maxMainSequenceDistance ?? 0.35;
490
+
491
+ const violations = metrics.violationsCount ?? 0;
492
+ const cycles = metrics.cyclesCount ?? 0;
493
+ const screamingScore = metrics.screamingScore ?? 1.0;
494
+ const maxDistance = metrics.maxDistance ?? 0.0;
495
+
496
+ const concentricPassed = violations <= maxViolations;
497
+ const concentricScore = concentricPassed ? 1.0 : Math.max(0.0, 1.0 - violations * 0.25);
498
+
499
+ const adpPassed = cycles <= maxCycles;
500
+ const adpScore = adpPassed ? 1.0 : Math.max(0.0, 1.0 - cycles * 0.35);
501
+
502
+ const screamingPassed = screamingScore >= minScreamingScore;
503
+ const screamingFitnessScore =
504
+ minScreamingScore > 0 ? Math.min(1.0, screamingScore / minScreamingScore) : 1.0;
505
+
506
+ const distancePassed = maxDistance <= maxMainSequenceDistance;
507
+ const distanceScore =
508
+ maxMainSequenceDistance > 0
509
+ ? Math.max(0.0, 1.0 - maxDistance / (2.0 * maxMainSequenceDistance))
510
+ : 1.0;
511
+
512
+ const weightedScore =
513
+ concentricScore * 0.35 +
514
+ adpScore * 0.25 +
515
+ screamingFitnessScore * 0.20 +
516
+ distanceScore * 0.20;
517
+ const fitnessScore = Math.round(weightedScore * 100) / 100;
518
+
519
+ let grade = 'F';
520
+ if (fitnessScore >= 0.90) grade = 'A';
521
+ else if (fitnessScore >= 0.80) grade = 'B';
522
+ else if (fitnessScore >= 0.70) grade = 'C';
523
+ else if (fitnessScore >= 0.60) grade = 'D';
524
+
525
+ const rules = [
526
+ {
527
+ id: 'CONCENTRIC_DEPENDENCY_RULE',
528
+ name: 'Concentric Dependency Rule',
529
+ threshold: maxViolations,
530
+ actualValue: violations,
531
+ passed: concentricPassed
532
+ },
533
+ {
534
+ id: 'ACYCLIC_DEPENDENCIES_RULE',
535
+ name: 'Acyclic Dependencies Principle (ADP)',
536
+ threshold: maxCycles,
537
+ actualValue: cycles,
538
+ passed: adpPassed
539
+ },
540
+ {
541
+ id: 'SCREAMING_ARCHITECTURE_RULE',
542
+ name: 'Screaming Architecture Invariant',
543
+ threshold: minScreamingScore,
544
+ actualValue: screamingScore,
545
+ passed: screamingPassed
546
+ },
547
+ {
548
+ id: 'MAIN_SEQUENCE_DISTANCE_RULE',
549
+ name: 'Main Sequence Balance Invariant',
550
+ threshold: maxMainSequenceDistance,
551
+ actualValue: maxDistance,
552
+ passed: distancePassed
553
+ }
554
+ ];
555
+
556
+ const overallPassed = rules.every((r) => r.passed);
557
+
558
+ return {
559
+ fitnessScore,
560
+ grade,
561
+ overallPassed,
562
+ passedRuleCount: rules.filter((r) => r.passed).length,
563
+ totalRuleCount: rules.length,
564
+ rules
565
+ };
566
+ }
567
+
568
+ /**
569
+ * Detect elementary directed cycles in package dependency graph using DFS
570
+ */
571
+ export function detectPackageCycles(packageEdges) {
572
+ const detectedCycles = [];
573
+ const sortedNodes = Array.from(packageEdges.keys()).sort();
574
+
575
+ function dfs(startNode, currentNode, currentPath, visitedOnPath) {
576
+ const neighbors = packageEdges.get(currentNode);
577
+ if (!neighbors) return;
578
+
579
+ for (const neighbor of Array.from(neighbors).sort()) {
580
+ if (neighbor === startNode && currentPath.length > 1) {
581
+ detectedCycles.push([...currentPath, startNode]);
582
+ } else if (neighbor > startNode && !visitedOnPath.has(neighbor)) {
583
+ visitedOnPath.add(neighbor);
584
+ currentPath.push(neighbor);
585
+ dfs(startNode, neighbor, currentPath, visitedOnPath);
586
+ currentPath.pop();
587
+ visitedOnPath.delete(neighbor);
588
+ }
589
+ }
590
+ }
591
+
592
+ for (const startNode of sortedNodes) {
593
+ const visited = new Set([startNode]);
594
+ dfs(startNode, startNode, [startNode], visited);
595
+ }
596
+
597
+ return detectedCycles.map((c) => ({
598
+ packages: c,
599
+ formatted: c.join(' -> ')
600
+ }));
601
+ }
602
+
603
+ /**
604
+ * Generate standard SARIF 2.1.0 JSON report representing architectural violations
605
+ * for GitHub Code Scanning and PR annotations.
606
+ */
607
+ export function generateSarifReport(report, options = {}) {
608
+ const version = options.version || '0.0.1';
609
+ const violations = report.violations || [];
610
+ const cycles = report.cycles || [];
611
+
612
+ const rules = [
613
+ {
614
+ id: 'ARCH001',
615
+ name: 'CleanArchitectureOutwardDependencyRule',
616
+ shortDescription: {
617
+ text: 'Clean Architecture concentric dependency rule violation'
618
+ },
619
+ fullDescription: {
620
+ text: 'Inner layers (Domain, Application) must not depend outwardly on outer layers (Adapters, Infrastructure). Apply the Dependency Inversion Principle (DIP) to invert the dependency.'
621
+ },
622
+ defaultConfiguration: {
623
+ level: 'error'
624
+ },
625
+ helpUri: 'https://github.com/fmatar/archlens#clean-architecture-rules'
626
+ }
627
+ ];
628
+
629
+ if (cycles.length > 0) {
630
+ rules.push({
631
+ id: 'ARCH002',
632
+ name: 'AcyclicDependenciesPrincipleRule',
633
+ shortDescription: {
634
+ text: 'Package dependency cycle detected (Robert C. Martin ADP violation)'
635
+ },
636
+ fullDescription: {
637
+ text: 'The dependency structure between packages must be a Directed Acyclic Graph (DAG). There must be no cycles in the dependency structure.'
638
+ },
639
+ defaultConfiguration: {
640
+ level: 'error'
641
+ },
642
+ helpUri: 'https://github.com/fmatar/archlens#clean-architecture-rules'
643
+ });
644
+ }
645
+
646
+ const screaming = report.screaming;
647
+ const failOnScreaming =
648
+ report.screamingThreshold !== null &&
649
+ report.screamingThreshold !== undefined &&
650
+ screaming &&
651
+ screaming.score < report.screamingThreshold;
652
+
653
+ if (failOnScreaming) {
654
+ rules.push({
655
+ id: 'ARCH003',
656
+ name: 'ScreamingArchitectureRule',
657
+ shortDescription: {
658
+ text: 'Screaming Architecture score below threshold (Uncle Bob Chapter 21 violation)'
659
+ },
660
+ fullDescription: {
661
+ text: 'The architecture should scream its business intent and domain use cases rather than framework delivery mechanisms or technical layers. Package-by-feature should predominate over package-by-layer.'
662
+ },
663
+ defaultConfiguration: {
664
+ level: 'error'
665
+ },
666
+ helpUri: 'https://github.com/fmatar/archlens#clean-architecture-rules'
667
+ });
668
+ }
669
+
670
+ const sarifResults = violations.map((v) => ({
671
+ ruleId: 'ARCH001',
672
+ level: 'error',
673
+ message: {
674
+ text: `Clean Architecture Violation: Inner tier '${v.fromTier}' (${v.fromFile}) depends outwardly on outer tier '${v.toTier}' via import '${v.toImport}'. Invert with interface '${v.portName}'.`
675
+ },
676
+ locations: [
677
+ {
678
+ physicalLocation: {
679
+ artifactLocation: {
680
+ uri: v.fromFile
681
+ },
682
+ region: {
683
+ startLine: v.line || 1
684
+ }
685
+ }
686
+ }
687
+ ]
688
+ }));
689
+
690
+ for (const c of cycles) {
691
+ sarifResults.push({
692
+ ruleId: 'ARCH002',
693
+ level: 'error',
694
+ message: {
695
+ text: `Package Dependency Cycle (ADP Violation): Cyclic loop detected: ${c.formatted}. Invert dependencies to break the cycle.`
696
+ }
697
+ });
698
+ }
699
+
700
+ if (failOnScreaming) {
701
+ sarifResults.push({
702
+ ruleId: 'ARCH003',
703
+ level: 'error',
704
+ message: {
705
+ text: `Screaming Architecture Violation: Score ${screaming.score.toFixed(2)} is below required threshold ${report.screamingThreshold.toFixed(2)} (${screaming.classification}: ${screaming.technicalPackageCount} technical / ${screaming.totalPackageCount} total packages). Organize packages by domain feature.`
706
+ }
707
+ });
708
+ }
709
+
710
+ const sarif = {
711
+ $schema: 'https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json',
712
+ version: '2.1.0',
713
+ runs: [
714
+ {
715
+ tool: {
716
+ driver: {
717
+ name: 'archlens',
718
+ version,
719
+ informationUri: 'https://github.com/fmatar/archlens',
720
+ rules
721
+ }
722
+ },
723
+ results: sarifResults
724
+ }
725
+ ]
726
+ };
727
+
728
+ return JSON.stringify(sarif, null, 2);
729
+ }
730
+
731
+ /**
732
+ * Generate structured JSON report
733
+ */
734
+ export function generateJsonReport(report) {
735
+ return JSON.stringify(report, null, 2);
736
+ }
@@ -94,26 +94,37 @@ export function getAntigravityInstructions() {
94
94
  return `# Archlens Clean Architecture MCP Server Instructions
95
95
 
96
96
  ## Overview
97
- Archlens provides automated Clean Architecture governance and static structural analysis.
98
- It enforces the Dependency Rule: source code dependencies must point inward toward higher-level policies.
97
+ Archlens provides automated Clean Architecture governance, static structural analysis, and autonomous refactoring protocols.
98
+ It strictly enforces Uncle Bob's Dependency Rule: source code dependencies must point inward toward higher-level policies.
99
99
 
100
100
  ### Concentric Layer Hierarchy:
101
- 1. **Domain Core (L0)**: Pure business entities and primitives. Zero outward imports.
102
- 2. **Application (L1)**: Use cases and business orchestrations. Depends only on Domain Core.
103
- 3. **Adapters (L2)**: Gateways, presenters, and controllers converting between UI/database formats and application models.
104
- 4. **Infrastructure (L3)**: Web frameworks, databases, network libraries, UI rendering, CLI entrypoints.
101
+ 1. **Domain Core (L0)**: Pure business entities, primitives, and domain logic. Zero outward imports.
102
+ 2. **Application (L1)**: Use cases, interaction orchestrators, and interface ports. Depends only on Domain Core.
103
+ 3. **Adapters (L2)**: Gateways, presenters, REST resources, controllers, and repository implementations.
104
+ 4. **Infrastructure (L3)**: Web frameworks, persistence engines, database drivers, third-party libraries, CLI entrypoints.
105
105
 
106
- ## Available Tools:
107
- - \`inspectArchitecture\`: Analyzes codebase rings, computes instability metrics, and reports illegal outward dependency breaches.
108
- - \`exportLlmDossier\`: Returns a structured refactoring dossier with concrete Dependency Inversion Principle (DIP) interface port specifications.
109
- - \`listSnapshots\`: Lists historical Git release tags and pre-compiled snapshot files.
110
- - \`getSnapshot\`: Retrieves architectural graph models for a specific historical release tag.
106
+ ## Governed Invariants & Drifts:
107
+ - **Concentric Dependency Rule**: Zero outward dependencies ($L_i \nrightarrow L_j$ where $i < j$).
108
+ - **Acyclic Dependencies Principle (ADP)**: Component dependencies must form a Directed Acyclic Graph (zero package cycles).
109
+ - **Screaming Architecture Invariant (SAS)**: Packaging must scream business use cases rather than framework technology (score >= 0.70).
110
+ - **Main Sequence Balance Invariant**: Distance from Main Sequence $D = |A + I - 1| \le 0.35$ avoiding Zones of Pain and Uselessness.
111
+ - **Architectural Fitness Index (AFI)**: Composite fitness score (0-100%) and letter grade (A-F) tracking regression trends.
111
112
 
112
- ## Refactoring Guidelines:
113
+ ## Available MCP Tools:
114
+ - \`exportLlmDossier\`: Primary tool to diagnose architectural drift and generate copy-ready LLM refactoring instructions with Dependency Inversion Principle (DIP) interface port prescriptions. Accepts \`{ "projectRoot": "." }\`.
115
+ - \`inspectArchitecture\`: Returns full structural JSON graph model: concentric rings, dependency edges, cycle paths, and screaming metrics.
116
+ - \`listSnapshots\`: Lists historical architecture release snapshots in \`.archlens/snapshots/\` and Git release tags.
117
+ - \`getSnapshot\`: Retrieves architectural graph models for a specific historical release tag or snapshot ID.
118
+
119
+ ## Available MCP Resources:
120
+ - \`archlens://llms.txt\`: Canonical reference guide, architectural rules, CLI commands, and refactoring protocols.
121
+
122
+ ## Refactoring Guidelines (Remediating Architectural Drift):
113
123
  Whenever outward breaches are detected from inner layers (Domain Core or Application) to outer layers (Adapters or Infrastructure):
114
- 1. Create an interface port inside the inner layer declaring required contract operations.
115
- 2. Implement the interface inside the outer layer.
116
- 3. Inject the outer implementation into the inner layer using constructor or dependency injection.
124
+ 1. **Declare Port**: Create an interface port inside the inner layer (\`domain/ports/\` or \`application/ports/\`) declaring required operations.
125
+ 2. **Implement Port**: Implement the interface inside the outer layer (\`infrastructure/\` or \`adapters/\`).
126
+ 3. **Invert Injection**: Inject the outer implementation into the inner layer using constructor or dependency injection.
127
+ 4. **Verify**: Run \`npx @fmatar/archlens-skill check --detect-cycles\` to verify zero violations.
117
128
  `.trim();
118
129
  }
119
130
 
package/src/mcp-server.js CHANGED
@@ -9,10 +9,14 @@
9
9
  import * as readline from 'node:readline';
10
10
  import * as path from 'node:path';
11
11
  import * as fs from 'node:fs';
12
+ import { fileURLToPath } from 'node:url';
12
13
  import { ARCHLENS_TOOL_SCHEMAS } from './mcp-registry.js';
13
14
  import { ensureServerRunning, DEFAULT_SERVER_URL } from './docker-runner.js';
14
15
  import { generateLlmPrompt, generatePolicy } from './analyzer.js';
15
16
 
17
+ const __filename = fileURLToPath(import.meta.url);
18
+ const __dirname = path.dirname(__filename);
19
+
16
20
  export function getMcpToolsList() {
17
21
  return Object.values(ARCHLENS_TOOL_SCHEMAS).map((tool) => ({
18
22
  name: tool.name,
@@ -21,6 +25,53 @@ export function getMcpToolsList() {
21
25
  }));
22
26
  }
23
27
 
28
+ export function getMcpResourcesList() {
29
+ return [
30
+ {
31
+ uri: 'archlens://llms.txt',
32
+ name: 'Archlens Architecture Guide & Best Practices',
33
+ description:
34
+ 'Comprehensive Clean Architecture guide, concentric ring hierarchy, CLI commands, fitness invariants, and refactoring protocols for LLMs.',
35
+ mimeType: 'text/markdown'
36
+ }
37
+ ];
38
+ }
39
+
40
+ export function readMcpResource(uri, options = {}, deps = {}) {
41
+ if (uri === 'archlens://llms.txt') {
42
+ const projectRoot = path.resolve(options.path || '.');
43
+ const localLlmsPath = path.join(projectRoot, 'llms.txt');
44
+ const cliLlmsPath = path.resolve(__dirname, '..', 'llms.txt');
45
+ const rootLlmsPath = path.resolve(__dirname, '..', '..', 'llms.txt');
46
+
47
+ const fileReader = deps.readFileSync || fs.readFileSync;
48
+ const fileExists = deps.existsSync || fs.existsSync;
49
+
50
+ let content = '';
51
+ if (fileExists(localLlmsPath)) {
52
+ content = fileReader(localLlmsPath, 'utf8');
53
+ } else if (fileExists(cliLlmsPath)) {
54
+ content = fileReader(cliLlmsPath, 'utf8');
55
+ } else if (fileExists(rootLlmsPath)) {
56
+ content = fileReader(rootLlmsPath, 'utf8');
57
+ } else {
58
+ content = '# Archlens Clean Architecture Guide\n\nRefer to https://github.com/fmatar/archlens for documentation.';
59
+ }
60
+
61
+ return {
62
+ contents: [
63
+ {
64
+ uri,
65
+ mimeType: 'text/markdown',
66
+ text: content
67
+ }
68
+ ]
69
+ };
70
+ }
71
+
72
+ throw new Error(`Resource not found: ${uri}`);
73
+ }
74
+
24
75
  export async function executeToolCall(toolName, args = {}, options = {}, deps = {}) {
25
76
  const serverUrl = options.serverUrl || process.env.ARCHLENS_SERVER_URL || DEFAULT_SERVER_URL;
26
77
  const projectRoot = path.resolve(args.projectRoot || options.path || '.');
@@ -37,7 +88,10 @@ export async function executeToolCall(toolName, args = {}, options = {}, deps =
37
88
  if (args.proposalId) {
38
89
  query.set('proposalId', args.proposalId);
39
90
  }
40
- const res = await (deps.fetch || fetch)(`${serverUrl}/api/llm-dossier?${query}`);
91
+ let res = await (deps.fetch || fetch)(`${serverUrl}/api/diagram/llm-dossier?${query}`);
92
+ if (!res.ok) {
93
+ res = await (deps.fetch || fetch)(`${serverUrl}/api/llm-dossier?${query}`);
94
+ }
41
95
  if (res.ok) {
42
96
  const text = await res.text();
43
97
  return { content: [{ type: 'text', text }] };
@@ -60,7 +114,10 @@ export async function executeToolCall(toolName, args = {}, options = {}, deps =
60
114
  if (isOnline) {
61
115
  try {
62
116
  const query = new URLSearchParams({ projectRoot });
63
- const res = await (deps.fetch || fetch)(`${serverUrl}/api/diagram?${query}`);
117
+ let res = await (deps.fetch || fetch)(`${serverUrl}/api/graph?${query}`);
118
+ if (!res.ok) {
119
+ res = await (deps.fetch || fetch)(`${serverUrl}/api/diagram?${query}`);
120
+ }
64
121
  if (res.ok) {
65
122
  const json = await res.json();
66
123
  return { content: [{ type: 'text', text: JSON.stringify(json, null, 2) }] };
@@ -175,11 +232,12 @@ export async function handleMcpMessage(request, options = {}, deps = {}) {
175
232
  result: {
176
233
  protocolVersion: '2024-11-05',
177
234
  capabilities: {
178
- tools: {}
235
+ tools: {},
236
+ resources: {}
179
237
  },
180
238
  serverInfo: {
181
239
  name: 'archlens-mcp-server',
182
- version: options.version || '0.0.1-Alpha-09'
240
+ version: options.version || '0.1.0-Beta-02'
183
241
  }
184
242
  }
185
243
  };
@@ -203,6 +261,37 @@ export async function handleMcpMessage(request, options = {}, deps = {}) {
203
261
  };
204
262
  }
205
263
 
264
+ if (method === 'resources/list') {
265
+ return {
266
+ jsonrpc: '2.0',
267
+ id,
268
+ result: {
269
+ resources: getMcpResourcesList()
270
+ }
271
+ };
272
+ }
273
+
274
+ if (method === 'resources/read') {
275
+ const uri = params?.uri;
276
+ try {
277
+ const readResult = readMcpResource(uri, options, deps);
278
+ return {
279
+ jsonrpc: '2.0',
280
+ id,
281
+ result: readResult
282
+ };
283
+ } catch (err) {
284
+ return {
285
+ jsonrpc: '2.0',
286
+ id,
287
+ error: {
288
+ code: -32002,
289
+ message: err.message
290
+ }
291
+ };
292
+ }
293
+ }
294
+
206
295
  if (method === 'tools/call') {
207
296
  const toolName = params?.name;
208
297
  const args = params?.arguments || {};