@fmatar/archlens-skill 0.0.1-Alpha-07 → 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/README.md CHANGED
@@ -57,6 +57,8 @@ node ./cli/bin/index.js
57
57
  - **Multi-Agent Skill Deployment**: Installs the `archlens-install-policy` skill globally into Claude Code (`~/.claude/skills/`), Gemini CLI / Antigravity (`~/.gemini/config/skills/`), and custom agent workspaces.
58
58
  - **Safe Incremental Updates**: Re-scans codebases for newly introduced packages, updating `order` and `levels` while preserving user custom rules and configurations.
59
59
  - **Seamless Upgrade Migration**: Automatically migrates legacy `.uml-viewer/` folders and companion files to modern `.archlens/` via `archlens-skill upgrade`.
60
+ - **Model Context Protocol (MCP) Client Auto-Configuration**: Detects and configures host AI client manifests (Claude Desktop, Google Antigravity, Claude Code, Cursor, VS Code) in a single command (`--mcp`).
61
+ - **On-Demand Container Orchestration & Stdio Bridge**: Automatically spins up the Archlens container when needed, bridges MCP over stdio (`mcp` command), and provides an instant offline AST fallback if Docker is unavailable.
60
62
  - **Mailbox Protocol Integration**: Injects the Clean Architecture Companion Protocol into `CLAUDE.md` and `AGENTS.md` for seamless asynchronous mailbox refactoring (`to-agent.json`, `to-viewer.json`).
61
63
 
62
64
  ---
@@ -100,16 +102,54 @@ Migrates older `.uml-viewer/` directories and companions to the standard `.archl
100
102
  npx @fmatar/archlens-skill upgrade
101
103
  ```
102
104
 
105
+ #### 6. Export LLM Refactoring Prompt Dossier
106
+ Generates copy-ready architectural diagnostics and concrete Dependency Inversion Principle (DIP) instructions for Claude Code, Gemini, ChatGPT, or Antigravity:
107
+ ```bash
108
+ # Print dossier to stdout
109
+ npx @fmatar/archlens-skill prompt
110
+
111
+ # Or copy directly to system clipboard
112
+ npx @fmatar/archlens-skill prompt --copy
113
+ ```
114
+
115
+ #### 7. Model Context Protocol (MCP) Setup & Stdio Bridge
116
+ Configures detected AI client manifests or launches an interactive stdio bridge:
117
+ ```bash
118
+ # Auto-configure Claude Desktop, Google Antigravity, Claude Code, Cursor, and VS Code
119
+ npx @fmatar/archlens-skill --mcp
120
+
121
+ # Launch MCP stdio transport bridge (spins up Docker container automatically when needed)
122
+ npx @fmatar/archlens-skill mcp
123
+ ```
124
+
125
+ #### 8. Start Workbench Container & Auto-Resurrection
126
+ Starts the Archlens container, mounts the workspace, verifies readiness, and optionally opens your browser. **If the container is killed or stopped, running `start` (or calling an MCP tool) automatically starts it again:**
127
+ ```bash
128
+ # Start container and automatically open workbench in browser:
129
+ npx @fmatar/archlens-skill start --open
130
+
131
+ # Start container in background on default port 8088:
132
+ npx @fmatar/archlens-skill start
133
+
134
+ # Specify a custom port or target workspace directory:
135
+ npx @fmatar/archlens-skill start --path /path/to/project --port 8088 --open
136
+ ```
137
+
103
138
  ---
104
139
 
105
140
  ### Command-Line Options
106
141
 
107
142
  | Flag | Shorthand | Description | Default |
108
143
  |------|-----------|-------------|---------|
144
+ | `start` | | Start Archlens Workbench container (auto-resurrects on demand) | |
145
+ | `--open` | `-o` | Open visual workbench in default browser upon startup | `false` |
146
+ | `--port <PORT>` | | Workbench HTTP port | `8088` |
109
147
  | `--path <DIR>` | `-p` | Target repository directory | `.` (current directory) |
110
148
  | `--title <NAME>` | `-t` | Project title in visual workbench | Formatted folder name |
111
149
  | `--prefix <PKG>` | | Common package prefix (e.g. `com.example.service`) | Auto-detected |
112
150
  | `--server-url <URL>` | | Visual Workbench server endpoint | `http://localhost:8088` |
151
+ | `--mcp` | `-m` | Auto-configure MCP client manifests (Claude, Antigravity, Cursor) | `false` |
152
+ | `--copy` | `-c` | Copy LLM prompt output directly to system clipboard | `false` |
113
153
  | `--global` | `-g` | Install skill into global agent directories | `false` |
114
154
  | `--update` | `-u` | Re-scan code and update existing policy | `false` |
115
155
  | `--upgrade` | | Migrate legacy `.uml-viewer` to `.archlens` | `false` |
package/bin/index.js CHANGED
@@ -11,10 +11,20 @@ import * as fs from 'node:fs';
11
11
  import { fileURLToPath } from 'node:url';
12
12
 
13
13
  import * as ui from '../src/ui.js';
14
- import { detectProjectLanguage, detectSourceRoot, findCommonPackagePrefix } from '../src/analyzer.js';
14
+ import {
15
+ detectProjectLanguage,
16
+ detectSourceRoot,
17
+ findCommonPackagePrefix,
18
+ generateLlmPrompt
19
+ } from '../src/analyzer.js';
15
20
  import { installLocalPolicy, installGlobalSkills } from '../src/installer.js';
16
21
  import { updateLocalPolicy, updateGlobalSkills } from '../src/updater.js';
17
22
  import { upgradeProject } from '../src/upgrader.js';
23
+ import { checkArchitecture, generateSarifReport, generateJsonReport } from '../src/checker.js';
24
+ import { installMcpConfigs } from '../src/mcp-registry.js';
25
+ import { startMcpStdioServer } from '../src/mcp-server.js';
26
+ import { executeStart, DEFAULT_CONTAINER_NAME, DEFAULT_SERVER_URL } from '../src/docker-runner.js';
27
+ import { spawnSync } from 'node:child_process';
18
28
 
19
29
  const __filename = fileURLToPath(import.meta.url);
20
30
  const __dirname = path.dirname(__filename);
@@ -41,18 +51,33 @@ ${ui.colors.bold}USAGE:${ui.colors.reset}
41
51
 
42
52
  ${ui.colors.bold}COMMANDS:${ui.colors.reset}
43
53
  init Initialize Clean Architecture policy in target project (default)
54
+ start Start Archlens Workbench container (auto-resurrects on demand)
55
+ check Audit repository against Clean Architecture policy rules
44
56
  update Update existing policy with newly discovered packages and refresh skills
45
57
  upgrade Upgrade legacy .uml-viewer configuration to .archlens
46
58
  global Install Archlens skills globally for AI coding assistants
59
+ prompt Export Clean Architecture LLM Refactoring Prompt Dossier
60
+ mcp Launch Model Context Protocol (MCP) stdio server for AI assistants
47
61
 
48
62
  ${ui.colors.bold}OPTIONS:${ui.colors.reset}
49
63
  -p, --path <DIR> Target repository path (default: current directory)
50
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)
51
70
  --prefix <PKG> Common package prefix (e.g. com.example.app)
52
71
  --server-url <URL> Archlens visual workbench URL (default: http://localhost:8088)
72
+ --port <PORT> Workbench HTTP port (default: 8088)
73
+ -o, --open Open visual workbench in default browser upon startup
74
+ -m, --mcp Auto-configure MCP server manifests in AI clients (Claude, Antigravity, Cursor)
75
+ -c, --copy Copy LLM prompt output directly to system clipboard
53
76
  -g, --global Install or update skill globally in ~/.claude and ~/.gemini
54
77
  -u, --update Update mode: sync new packages into existing policy
55
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
56
81
  -f, --force Overwrite existing policy files
57
82
  --dry-run Simulate actions without writing files to disk
58
83
  -y, --yes Accept defaults automatically (non-interactive mode)
@@ -60,6 +85,20 @@ ${ui.colors.bold}OPTIONS:${ui.colors.reset}
60
85
  -h, --help Display this help guide
61
86
 
62
87
  ${ui.colors.bold}EXAMPLES:${ui.colors.reset}
88
+ ${ui.colors.dim}# Start Archlens workbench container and open in browser:${ui.colors.reset}
89
+ npx @fmatar/archlens-skill start --open
90
+ ${ui.colors.dim}# Configure MCP manifests across Claude, Antigravity, and Cursor:${ui.colors.reset}
91
+ npx @fmatar/archlens-skill --mcp
92
+
93
+ ${ui.colors.dim}# Launch MCP stdio bridge server for AI coding assistants:${ui.colors.reset}
94
+ npx @fmatar/archlens-skill mcp
95
+
96
+ ${ui.colors.dim}# Export Clean Architecture LLM Refactoring Prompt to stdout:${ui.colors.reset}
97
+ npx @fmatar/archlens-skill prompt
98
+
99
+ ${ui.colors.dim}# Copy prompt directly to system clipboard:${ui.colors.reset}
100
+ npx @fmatar/archlens-skill prompt --copy
101
+
63
102
  ${ui.colors.dim}# Interactive setup wizard:${ui.colors.reset}
64
103
  npx @fmatar/archlens-skill
65
104
 
@@ -84,9 +123,23 @@ function parseArgs(args) {
84
123
  title: null,
85
124
  prefix: null,
86
125
  serverUrl: 'http://localhost:8088',
126
+ port: '8088',
127
+ open: false,
128
+ start: false,
129
+ copy: false,
130
+ prompt: false,
87
131
  global: false,
88
132
  update: false,
89
133
  upgrade: false,
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,
90
143
  force: false,
91
144
  dryRun: false,
92
145
  yes: false,
@@ -103,12 +156,38 @@ function parseArgs(args) {
103
156
  parsed.help = true;
104
157
  } else if (arg === '--version' || arg === '-v') {
105
158
  parsed.version = true;
159
+ } else if (arg === '--open' || arg === '-o') {
160
+ parsed.open = true;
161
+ } else if (arg === '--port') {
162
+ parsed.port = args[++i] || '8088';
163
+ } else if (arg === '--mcp' || arg === '-m') {
164
+ parsed.mcp = true;
106
165
  } else if (arg === '--global' || arg === '-g') {
107
166
  parsed.global = true;
108
167
  } else if (arg === '--update' || arg === '-u') {
109
168
  parsed.update = true;
110
169
  } else if (arg === '--upgrade') {
111
170
  parsed.upgrade = true;
171
+ } else if (arg === '--prompt') {
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];
189
+ } else if (arg === '--copy' || arg === '-c') {
190
+ parsed.copy = true;
112
191
  } else if (arg === '--force' || arg === '-f') {
113
192
  parsed.force = true;
114
193
  } else if (arg === '--dry-run') {
@@ -130,7 +209,7 @@ function parseArgs(args) {
130
209
 
131
210
  if (positional.length > 0) {
132
211
  const cmd = positional[0].toLowerCase();
133
- if (['init', 'update', 'upgrade', 'global', 'help', 'version'].includes(cmd)) {
212
+ if (['init', 'start', 'update', 'upgrade', 'global', 'prompt', 'mcp', 'check', 'help', 'version'].includes(cmd)) {
134
213
  parsed.command = cmd;
135
214
  } else if (!parsed.title && !parsed.path) {
136
215
  parsed.path = positional[0];
@@ -139,9 +218,13 @@ function parseArgs(args) {
139
218
 
140
219
  if (parsed.command === 'help') parsed.help = true;
141
220
  if (parsed.command === 'version') parsed.version = true;
221
+ if (parsed.command === 'start') parsed.start = true;
142
222
  if (parsed.command === 'update') parsed.update = true;
143
223
  if (parsed.command === 'upgrade') parsed.upgrade = true;
144
224
  if (parsed.command === 'global') parsed.global = true;
225
+ if (parsed.command === 'prompt') parsed.prompt = true;
226
+ if (parsed.command === 'check') parsed.check = true;
227
+ if (parsed.command === 'mcp') parsed.mcp = true;
145
228
 
146
229
  return parsed;
147
230
  }
@@ -175,8 +258,13 @@ async function runInteractive(options) {
175
258
  },
176
259
  {
177
260
  value: 'both',
178
- label: `${ui.colors.bold}Full Suite (Local Policy + Global Skills)${ui.colors.reset}`,
179
- description: 'Configures current repository and installs global AI assistant skills'
261
+ label: `${ui.colors.bold}Full Suite (Local Policy + Global Skills + MCP)${ui.colors.reset}`,
262
+ description: 'Configures repository, global AI skills, and Model Context Protocol manifests'
263
+ },
264
+ {
265
+ value: 'mcp',
266
+ label: `${ui.colors.bold}Configure Model Context Protocol (MCP)${ui.colors.reset}`,
267
+ description: 'Register Archlens MCP tools into Claude Desktop, Antigravity, and Cursor'
180
268
  },
181
269
  {
182
270
  value: 'update',
@@ -214,6 +302,10 @@ async function runInteractive(options) {
214
302
  executeGlobalInstall(execOptions);
215
303
  }
216
304
 
305
+ if (selectedAction === 'mcp' || selectedAction === 'both') {
306
+ executeMcpInstall(execOptions);
307
+ }
308
+
217
309
  if (selectedAction === 'update') {
218
310
  executeUpdate(targetRoot, execOptions);
219
311
  }
@@ -225,6 +317,20 @@ async function runInteractive(options) {
225
317
  printCompletionMessage(targetRoot, execOptions.serverUrl);
226
318
  }
227
319
 
320
+ function executeMcpInstall(options) {
321
+ const modeSuffix = options.dryRun ? ' (dry run)' : '';
322
+ ui.step(3, 3, `Configuring Model Context Protocol (MCP) Clients${modeSuffix}`);
323
+ const result = installMcpConfigs(options);
324
+
325
+ if (result.configuredClients.length === 0) {
326
+ ui.warn('No active AI client configurations found (~/.claude, ~/.gemini). Use --force to deploy anyway.');
327
+ } else {
328
+ for (const client of result.configuredClients) {
329
+ ui.success(`Configured MCP for ${client.name} (${client.action}): ${client.path}${modeSuffix}`);
330
+ }
331
+ }
332
+ }
333
+
228
334
  function executeLocalInit(targetRoot, options) {
229
335
  ui.step(1, 2, 'Scaffolding Clean Architecture Policy');
230
336
  const result = installLocalPolicy(targetRoot, options);
@@ -316,8 +422,29 @@ function printCompletionMessage(targetRoot, serverUrl) {
316
422
  console.log(` 3. Or press ${ui.colors.bold}⌘O / Ctrl+O${ui.colors.reset} inside Archlens to select this workspace.\n`);
317
423
  }
318
424
 
425
+ function copyToSystemClipboard(text) {
426
+ try {
427
+ if (process.platform === 'darwin') {
428
+ spawnSync('pbcopy', { input: text, encoding: 'utf8' });
429
+ return true;
430
+ } else if (process.platform === 'win32') {
431
+ spawnSync('clip', { input: text, encoding: 'utf8' });
432
+ return true;
433
+ } else {
434
+ const res = spawnSync('xclip', ['-selection', 'clipboard'], { input: text, encoding: 'utf8' });
435
+ if (res.error) {
436
+ spawnSync('wl-copy', { input: text, encoding: 'utf8' });
437
+ }
438
+ return true;
439
+ }
440
+ } catch {
441
+ return false;
442
+ }
443
+ }
444
+
319
445
  async function main() {
320
446
  const options = parseArgs(process.argv.slice(2));
447
+ const targetRoot = path.resolve(options.path || '.');
321
448
 
322
449
  if (options.help) {
323
450
  printHelp();
@@ -329,15 +456,200 @@ async function main() {
329
456
  process.exit(0);
330
457
  }
331
458
 
459
+ if (options.command === 'prompt' || options.prompt) {
460
+ try {
461
+ const dossier = await generateLlmPrompt(targetRoot, options);
462
+ if (options.copy) {
463
+ const ok = copyToSystemClipboard(dossier);
464
+ if (ok) {
465
+ ui.success('Clean Architecture Refactoring Dossier copied to system clipboard!');
466
+ } else {
467
+ process.stdout.write(dossier);
468
+ }
469
+ } else {
470
+ process.stdout.write(dossier);
471
+ }
472
+ process.exit(0);
473
+ } catch (err) {
474
+ ui.error(err.message || String(err));
475
+ process.exit(1);
476
+ }
477
+ }
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
+
605
+ if (options.command === 'mcp') {
606
+ startMcpStdioServer({
607
+ version: getPackageVersion(),
608
+ ...options
609
+ });
610
+ return;
611
+ }
612
+
613
+ if (options.command === 'start' || options.start) {
614
+ try {
615
+ const port = options.port || '8088';
616
+ const targetUrl = options.serverUrl || (port === '8088' ? DEFAULT_SERVER_URL : `http://localhost:${port}`);
617
+ ui.info(`Checking Archlens Workbench server on ${targetUrl}...`);
618
+ const status = await executeStart(options);
619
+ if (status.status === 'running') {
620
+ if (status.spawned) {
621
+ ui.success(`Archlens container (${DEFAULT_CONTAINER_NAME}) launched successfully!`);
622
+ } else {
623
+ ui.success(`Archlens Workbench server is active (${status.version || 'running'}).`);
624
+ }
625
+ console.log(`\n ${ui.colors.bold}Workbench URL:${ui.colors.reset} ${ui.colors.cyan}${status.serverUrl}${ui.colors.reset}\n`);
626
+ } else if (status.status === 'offline') {
627
+ ui.warn(status.message || 'Archlens server is offline and Docker daemon is unavailable.');
628
+ console.log(`\n ${ui.colors.dim}To run offline architecture analysis:${ui.colors.reset}`);
629
+ console.log(` npx @fmatar/archlens-skill prompt\n`);
630
+ } else {
631
+ ui.error(status.message || 'Failed to start Archlens container.');
632
+ process.exit(1);
633
+ }
634
+ process.exit(0);
635
+ } catch (err) {
636
+ ui.error(err.message || String(err));
637
+ process.exit(1);
638
+ }
639
+ }
640
+
332
641
  const isInteractive = Boolean(
333
642
  process.stdin.isTTY &&
334
643
  process.stdout.isTTY &&
335
644
  !options.yes &&
336
645
  !options.dryRun &&
337
646
  !options.command &&
647
+ !options.start &&
338
648
  !options.global &&
339
649
  !options.update &&
340
- !options.upgrade
650
+ !options.upgrade &&
651
+ !options.prompt &&
652
+ !options.mcp
341
653
  );
342
654
 
343
655
  if (isInteractive) {
@@ -351,8 +663,6 @@ async function main() {
351
663
  }
352
664
 
353
665
  // Non-interactive or flag-driven execution
354
- const targetRoot = path.resolve(options.path || '.');
355
-
356
666
  try {
357
667
  if (options.upgrade) {
358
668
  executeUpgrade(targetRoot, options);
@@ -367,6 +677,10 @@ async function main() {
367
677
  executeLocalInit(targetRoot, options);
368
678
  }
369
679
 
680
+ if (options.mcp) {
681
+ executeMcpInstall(options);
682
+ }
683
+
370
684
  if (!options.dryRun) {
371
685
  printCompletionMessage(targetRoot, options.serverUrl);
372
686
  }
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-07",
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"