agentleFS
G1JoshiG1Joshi/Agent-Skills/skills/architecture/clean-architecture/SKILL.md

clean-architecture

Skill15 starsChanged 43 days agoMITView on GitHub

Expert Clean Architecture assistance covering Onion/Hexagonal layered boundaries, dependency inversion, use case interactors, entities, and repository interfaces. Use when designing maintainable software architectures, decoupling business logic from frameworks, or structuring testable domain models.

28 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use convention-learner, opentelemetry and 9 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • codewithmukeshSkill

    convention-learner

    Detects and enforces project-specific coding conventions by analyzing existing codebase patterns. Learns naming conventions, folder structure, test organization, and coding style from the existing code. Load when: "conventions", "coding standards", "project patterns", "enforce style", "detect patterns", "learn conventions", "code consistency".

    Also in 3 projects that use this

  • codewithmukeshSkill

    opentelemetry

    OpenTelemetry observability for .NET 10 applications. Covers traces, metrics, and logs using the OpenTelemetry SDK with OTLP export. Includes custom ActivitySource, IMeterFactory metrics, resource configuration, and Aspire Dashboard integration. Load this skill when setting up distributed tracing, custom metrics, OTLP export, or when the user mentions "OpenTelemetry", "OTLP", "traces", "spans", "Activity", "ActivitySource", "metrics", "IMeterFactory", "Meter", "Counter", "Histogram", "Gauge", "telemetry", "observability", "distributed tracing", "OTEL", or "Aspire Dashboard".

    Also in 3 projects that use this

  • MovGP0Skill

    modern-csharp

    Modern C# style guidance for Bendex and MicroSea code changes, including primary constructors, expression-bodied members, var usage, target-typed new, lambdas, and pattern matching.

    Also in 3 projects that use this

  • MicrosoftSkill

    resilience

    Apply resilience patterns (retry, backoff, circuit breaking) when writing or reviewing code that makes outbound HTTP/REST calls, database operations, or any I/O that can experience transient failures. Use this skill when: (1) writing new code that calls external services or APIs, (2) reviewing code that uses fetch, HTTP clients, or service-to-service calls, (3) adding queue consumers or workers that interact with remote systems, (4) debugging intermittent failures in production.

    Also in 3 projects that use this

  • hongyuancSkill

    vertical-slice

    Build and evaluate a production-quality vertical slice before advancing from Pre-Production to Production.

    Also in 3 projects that use this

  • wpankSkill

    caching

    Caching strategies, invalidation, eviction policies, HTTP caching, distributed caching, and anti-patterns. Use when designing cache layers, choosing eviction policies, debugging stale data, or optimizing read-heavy workloads.

    Also in 3 projects that use this

The file

We split this skill into the rules it gives an agent

4 rules. 0 are common, 3 are distinctive, and 1 is very specific to this project.

  • 0

    Common

    Most of the 26 edited versions we read keep these.

  • 3

    Distinctive

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Keep Domain Entities Free of Framework Imports: Never import @Entity, drizzle-orm, or HTTP request classes in the domain layer.

    line 166
  2. Distinctive:

    Test Use Cases with In-Memory Mocks: Execute thousands of unit tests in milliseconds using plain in-memory array/map repository stubs.

    line 168
  3. Distinctive:

    Use DTOs across Boundaries: Map between HTTP JSON payloads and domain entities using validation schemas (Zod/Valibot).

    line 169
  4. Distinctive:

    Create anemic domain models: Do not use entities as dumb data bags with getters/setters.

    line 174

“Common” is measured: kept by at least 6 in 10 of the 26 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Clean Architecture

Clean Architecture, popularized by Robert C. Martin (Uncle Bob), separates software into layers to ensure independence from frameworks, databases, and UIs. The core principle is the Dependency Rule: source code dependencies can only point inwards.

When to Use

  • Long-Lived Enterprise Applications: Building systems designed to evolve over 5-10+ years without being held hostage by framework obsolescence.
  • Framework & Database Decoupling: Structuring codebases where swapping ORMs (Prisma -> Drizzle) or delivery mechanisms (REST -> gRPC) requires zero domain changes.
  • Comprehensive Unit Testing: Enabling fast, isolated unit tests for core business use cases without requiring running databases or network stubs.
  • Complex Business Rule Isolation: Separating intricate domain invariants from presentation controllers and database migration scripts.

Quick Start

// 1. Entity (Enterprise Logic) - Inner Layer
class User {
  constructor(
    public id: string,
    public name: string,
  ) {
    if (name.length < 2) throw new Error("Name too short");
  }
}

// 2. Use Case (Application Logic)
class CreateUserUseCase {
  constructor(private userRepository: UserRepository) {} // Depends on interface

  async execute(name: string): Promise<User> {
    const user = new User(crypto.randomUUID(), name);
    await this.userRepository.save(user);
    return user;
  }
}

// 3. Interface Adapter (Repository Interface)
interface UserRepository {
  save(user: User): Promise<void>;
}

// 4. Frameworks & Drivers (Implementation) - Outer Layer
class SqlUserRepository implements UserRepository {
  async save(user: User): Promise<void> {
    await db.query("INSERT INTO users ...", [user.id, user.name]);
  }
}

Core Concepts

Dependency Inversion Principle (The Dependency Rule)

Source code dependencies must point inward only. Inner circles (Entities, Use Cases) know nothing about outer circles (Web, DB, CLI):

       [ Frameworks & Drivers (DB, Web, Devices) ]
                         ↓
             [ Interface Adapters (Controllers, Gateways) ]
                               ↓
                 [ Application Business Rules (Use Cases) ]
                                     ↓
                     [ Enterprise Business Rules (Entities) ]

Domain Entities (Pure Business Objects)

Encapsulates core business data and invariants without external annotations or framework decorators:

// domain/entities/subscription.entity.ts
export class Subscription {
  constructor(
    public readonly id: string,
    public readonly customerId: string,
    private _status: "ACTIVE" | "PAST_DUE" | "CANCELED",
    private _validUntil: Date,
  ) {}

  public renew(durationDays: number): void {
    if (this._status === "CANCELED") {
      throw new Error("Cannot renew a canceled subscription");
    }
    this._validUntil = new Date(
      this._validUntil.getTime() + durationDays * 86400000,
    );
    this._status = "ACTIVE";
  }

  get isValid(): boolean {
    return this._status === "ACTIVE" && this._validUntil > new Date();
  }
}

Use Case Interactors & Boundary Ports

Coordinates the flow of data to and from entities, defining input/output boundary interfaces:

// application/use-cases/renew-subscription.use-case.ts
export interface SubscriptionRepositoryPort {
  findById(id: string): Promise<Subscription | null>;
  save(sub: Subscription): Promise<void>;
}

export class RenewSubscriptionUseCase {
  constructor(private readonly repo: SubscriptionRepositoryPort) {}

  async execute(subscriptionId: string, days: number): Promise<void> {
    const sub = await this.repo.findById(subscriptionId);
    if (!sub) throw new Error("Subscription not found");
    sub.renew(days);
    await this.repo.save(sub);
  }
}

Common Patterns

Inverted Repository Dependency (Domain -> Infrastructure)

Problem: Business logic becomes tightly coupled to SQL ORM models and database drivers.
Solution: Declare repository interfaces inside domain layer; implement them in infrastructure layer.

// 1. Domain Layer (core/ports/user-repository.port.ts) - Zero external dependencies
export interface UserRepositoryPort {
  findById(id: string): Promise<UserEntity | null>;
  save(user: UserEntity): Promise<void>;
}

// 2. Application Layer (use-cases/create-user.use-case.ts)
export class CreateUserUseCase {
  constructor(private readonly userRepo: UserRepositoryPort) {}
  async execute(dto: CreateUserDto): Promise<UserEntity> {
    const user = new UserEntity(dto.email, dto.name);
    await this.userRepo.save(user);
    return user;
  }
}

// 3. Infrastructure Layer (adapters/drizzle-user.repository.ts)
export class DrizzleUserRepository implements UserRepositoryPort {
  async save(user: UserEntity): Promise<void> {
    await db.insert(usersTable).values({ id: user.id, email: user.email });
  }
  async findById(id: string): Promise<UserEntity | null> {
    const [row] = await db
      .select()
      .from(usersTable)
      .where(eq(usersTable.id, id));
    return row ? new UserEntity(row.email, row.name, row.id) : null;
  }
}

Best Practices

Do:

  • Keep Domain Entities Free of Framework Imports: Never import @Entity, drizzle-orm, or HTTP request classes in the domain layer.
  • Define Ports as Interfaces in the Domain: Let the domain dictate its persistence requirements; implement adapters in the infrastructure layer.
  • Test Use Cases with In-Memory Mocks: Execute thousands of unit tests in milliseconds using plain in-memory array/map repository stubs.
  • Use DTOs across Boundaries: Map between HTTP JSON payloads and domain entities using validation schemas (Zod/Valibot).

Don't:

  • Return database ORM entities to API controllers: Prevent database schema changes from leaking into external API contracts.
  • Create anemic domain models: Do not use entities as dumb data bags with getters/setters; encapsulate operations and invariants inside methods.
  • Over-engineer simple CRUD apps: Clean Architecture carries cognitive and boilerplate overhead; avoid using it for trivial prototypes.

Troubleshooting

ErrorCauseSolution
Circular DependencyViolating the dependency rule.Use Dependency Inversion (Interfaces) to break the cycle.
Boilerplate OverloadCreating strict layers for simple CRUD.Consider "Vertical Slice Architecture" or Modular Monolith for simpler domains.

References

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.