Generates reusable, composable Specification pattern implementations for any ORM/stack (EF Core, Spring Data JPA, Prisma, TypeORM, Drizzle, SQLAlchemy, Django, GORM). Deduplicates repeated Where/Include/filter logic.
Ships in AI for Developers Toolkit. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Turn repeated query criteria into reusable, composable, unit-testable specification objects (or the ORM's native equivalent), applied to the query in one place.
Works on a target: a folder, project/repo, or GitHub URL. First find the duplicated query logic to consolidate - specs must target real repetition.
| Manifest | ORM | Native mechanism | Find duplicated criteria |
|---|---|---|---|
*.csproj | EF Core | Custom Specification<T> + evaluator, or Ardalis.Specification if present | grep -rn "\.Where(|\.Include(|\.OrderBy" --include=*.cs |
pom.xml / build.gradle(.kts) | Spring Data JPA | Specification<T> + JpaSpecificationExecutor (built in) | grep -rn "@Query|findBy|CriteriaBuilder" src |
package.json | Prisma / TypeORM / Drizzle | Typed where-input builders / query-builder functions / SQL expressions | grep -rn "where:|\.andWhere(|\.where(" --include=*.ts |
pyproject.toml / requirements*.txt | SQLAlchemy / Django ORM | Functions returning SQL expressions / Q objects and custom QuerySet methods | grep -rn "\.filter(|\.where(|Q(" --include=*.py |
go.mod | GORM (or sqlc/squirrel) | GORM scopes func(*gorm.DB) *gorm.DB | grep -rn "\.Where(|\.Scopes(" --include=*.go |
ActiveOrdersForCustomer, OverdueInvoices), not a generic "filter by field X" wrapper.and / or / not so rules combine without new classes for every combination.Specification, Django QuerySet, GORM scopes).If Ardalis.Specification is already referenced, use it. Otherwise:
public abstract class Specification<T>
{
public Expression<Func<T, bool>>? Criteria { get; protected set; }
public List<Expression<Func<T, object>>> Includes { get; } = new();
public Expression<Func<T, object>>? OrderBy { get; private set; }
public int? Take { get; private set; }
public int? Skip { get; private set; }
public bool AsNoTracking { get; private set; } = true;
protected void Where(Expression<Func<T, bool>> c) => Criteria = c;
protected void Include(Expression<Func<T, object>> i) => Includes.Add(i);
protected void Order(Expression<Func<T, object>> o) => OrderBy = o;
protected void Page(int skip, int take){ Skip = skip; Take = take; }
protected void Tracked() => AsNoTracking = false;
}
public static class SpecificationEvaluator
{
public static IQueryable<T> Apply<T>(IQueryable<T> q, Specification<T> spec) where T : class
{
if (spec.AsNoTracking) q = q.AsNoTracking();
if (spec.Criteria is not null) q = q.Where(spec.Criteria);
q = spec.Includes.Aggregate(q, (cur, inc) => cur.Include(inc));
if (spec.OrderBy is not null) q = q.OrderBy(spec.OrderBy);
if (spec.Skip is not null) q = q.Skip(spec.Skip.Value);
if (spec.Take is not null) q = q.Take(spec.Take.Value);
return q;
}
}
public class ActiveOrdersForCustomer : Specification<Order>
{
public ActiveOrdersForCustomer(Guid customerId)
{
Where(o => o.CustomerId == customerId && o.Status == OrderStatus.Active);
Include(o => o.Lines);
Order(o => o.CreatedAt);
}
}
var orders = await SpecificationEvaluator
.Apply(db.Orders, new ActiveOrdersForCustomer(id)).ToListAsync(ct);
Unit test: spec.Criteria!.Compile()(order) against in-memory entities. For And/Or composition of expression criteria, combine with a parameter-rebinding ExpressionVisitor (or use the library's support).
public interface OrderRepository extends JpaRepository<Order, UUID>, JpaSpecificationExecutor<Order> {}
public final class OrderSpecs {
private OrderSpecs() {}
public static Specification<Order> forCustomer(UUID customerId) {
return (root, query, cb) -> cb.equal(root.get("customerId"), customerId);
}
public static Specification<Order> active() {
return (root, query, cb) -> cb.equal(root.get("status"), OrderStatus.ACTIVE);
}
}
var page = orders.findAll(
OrderSpecs.forCustomer(id).and(OrderSpecs.active()),
PageRequest.of(0, 20, Sort.by("createdAt")));
Use the JPA static metamodel (Order_.status) instead of strings if the project generates it. Eager loading: add an @EntityGraph on the repository method or fetch in the spec only for non-count queries. Querydsl Predicates are the equivalent if the project uses Querydsl.
Prisma - specs are typed WhereInput builders, composed with AND/OR:
export const activeOrders = (): Prisma.OrderWhereInput => ({ status: "ACTIVE" });
export const forCustomer = (customerId: string): Prisma.OrderWhereInput => ({ customerId });
const orders = await prisma.order.findMany({
where: { AND: [activeOrders(), forCustomer(id)] },
include: { lines: true },
orderBy: { createdAt: "asc" },
});
Drizzle - specs return SQL expressions combined with and() / or(): const activeOrders = () => eq(orders.status, "ACTIVE"), then db.select().from(orders).where(and(activeOrders(), eq(orders.customerId, id))).
TypeORM - specs as functions (qb: SelectQueryBuilder<Order>) => SelectQueryBuilder<Order> applied in sequence, or FindOptionsWhere<Order> objects for simple cases. Keep parameter names unique per spec to avoid collisions.
SQLAlchemy - specs return boolean column expressions:
def active_orders() -> ColumnElement[bool]:
return Order.status == OrderStatus.ACTIVE
def for_customer(customer_id: UUID) -> ColumnElement[bool]:
return Order.customer_id == customer_id
stmt = (select(Order)
.where(and_(active_orders(), for_customer(cid)))
.options(selectinload(Order.lines))
.order_by(Order.created_at))
orders = (await session.scalars(stmt)).all()
Django - the idiomatic spec is a custom QuerySet method (chainable) or a Q object (composable with &, |, ~):
class OrderQuerySet(models.QuerySet):
def active(self): return self.filter(status=OrderStatus.ACTIVE)
def for_customer(self, cid): return self.filter(customer_id=cid)
class Order(models.Model):
objects = OrderQuerySet.as_manager()
Order.objects.active().for_customer(cid).prefetch_related("lines").order_by("created_at")
func Active(db *gorm.DB) *gorm.DB { return db.Where("status = ?", StatusActive) }
func ForCustomer(id string) func(*gorm.DB) *gorm.DB {
return func(db *gorm.DB) *gorm.DB { return db.Where("customer_id = ?", id) }
}
func Paginate(page, size int) func(*gorm.DB) *gorm.DB {
return func(db *gorm.DB) *gorm.DB { return db.Offset((page - 1) * size).Limit(size) }
}
var orders []Order
err := db.WithContext(ctx).Scopes(Active, ForCustomer(id), Paginate(1, 20)).
Preload("Lines").Order("created_at").Find(&orders).Error
With sqlc there is no runtime composition - write one named query per rule; with squirrel, specs are sq.Sqlizer values combined with sq.And{...}.
## Detected
<stack, ORM, mechanism chosen (native vs custom) and why>
## Duplication found
| Criteria | Occurrences (file:line) | Spec name |
## Files
<base spec/evaluator (if needed), the specs, the refactored call sites>
## Tests
<a unit test per spec, plus one DB-backed test>
"Add the specification pattern", "dedupe these repeated EF queries into specs", "make my query criteria reusable and testable", "Spring Data Specifications for the order search", "reusable Prisma filters for orders", "custom QuerySet methods instead of repeated filters", "GORM scopes for these repeated Where clauses". Pairs with orm-query-optimizer.
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
Prisma, TypeORM, Drizzle, SQLAlchemy, Django, PostgreSQL, MySQL, SQLite
45 skills in this plugin
/api-endpoint-scaffolderScaffold HTTP API endpoints in any stack - ASP.NET Core Minimal APIs or controllers, Express, Fastify, NestJS, FastAPI, Django REST Framework, Spring Boot controllers, Go net/http, chi, Gin - one feature per endpoint (REPR style) with request validation, typed responses, route grouping, auth, and OpenAPI metadata. Use this skill whenever the user wants to add an endpoint or route, convert controllers to minimal APIs, structure routes or routers, set up endpoint groups, TypedResults, route handlers, request DTOs/schemas (zod, Pydantic, Bean Validation, binding tags), or asks "how do I add an endpoint / structure my API routes". Always use this skill for endpoint scaffolding; it generates a complete, validated endpoint that matches the project's conventions./architecture-test-generatorGenerate architecture tests / fitness functions that fail the build when architectural rules are violated - layer dependencies, module boundaries, cycles, naming, and visibility conventions - in any stack: NetArchTest or ArchUnitNET (.NET), ArchUnit or Konsist (Java/Kotlin), dependency-cruiser or eslint-plugin-boundaries (TypeScript/JavaScript), import-linter (Python), go-arch-lint or depguard (Go). Use this skill whenever the user wants architecture tests, to enforce layering or the dependency rule, dependency rules as tests, import rules, forbidden imports, no circular dependencies, naming conventions, fitness functions, or asks "how do I stop people breaking the architecture / enforce my layers / keep modules from importing each other". Always use this skill for architecture-test requests; it generates rules matching the project's real structure./async-await-auditorAudit async and concurrent code in any language for correctness and performance bugs - C#/.NET (async/await, Task), JavaScript/TypeScript (Promises, async/await), Python (asyncio), Java/Kotlin (CompletableFuture, virtual threads, coroutines), Go (goroutines, channels, context), Rust (tokio/async). Use this skill whenever the user shares async or concurrent code, or asks about deadlocks, hangs, blocking calls, .Result/.Wait(), async void, ConfigureAwait, floating or unhandled promises, await in a loop vs Promise.all, blocking the event loop, forgotten await, asyncio.gather/TaskGroup, CompletableFuture.join, virtual thread pinning, goroutine leaks, context cancellation, WaitGroup/errgroup, holding a lock across .await, fire-and-forget tasks, cancellation tokens, or "why does my async code hang". Always use this skill for async/concurrency reviews instead of answering from memory; it applies a fixed checklist and rewrites the code./authorization-setupDesign API authorization in any stack - policy-based, role-based, claims/permission-based, and resource-based (ownership) checks. Covers ASP.NET Core policies and AuthorizationHandler, NestJS guards, Express middleware and CASL, FastAPI dependencies/scopes, Django and DRF permission classes, Spring Security (@PreAuthorize, SecurityFilterChain), Go middleware, and Casbin/OPA. Use this skill whenever the user wants authorization policies, role/claim/permission checks, RBAC/ABAC, custom authorization rules, resource-based authorization, IDOR protection, "deny by default", or asks "how do I authorize this / policy vs role / restrict this endpoint to X / stop users seeing other users' data". Always use this skill for authorization requests; it generates policies, handlers, and endpoint wiring./benchmark-setupSet up correct micro-benchmarks in any stack and interpret the results - BenchmarkDotNet (.NET), JMH (Java/Kotlin), pytest-benchmark / pyperf (Python), Vitest bench / tinybench / mitata (JavaScript/TypeScript), Go testing.B + benchstat, Rust criterion. Use this skill whenever the user wants to benchmark code, measure performance, compare two implementations or functions, set up a benchmark harness, or asks "which is faster", "benchmark these two functions", "how do I benchmark this", "is this optimization worth it", or "interpret these benchmark results". Always use this skill for micro-benchmarking requests; it writes correct benchmarks, avoids the classic pitfalls, and explains the numbers./caching-strategy-setupAdd the right caching to an app in any stack - in-process, distributed (Redis/Valkey/Memcached), two-level, or HTTP/output caching - with correct keys, expiration, stampede protection, and invalidation. Covers HybridCache / IMemoryCache / IDistributedCache / output caching in .NET, lru-cache / keyv / cache-manager / ioredis in Node, functools / cachetools / redis-py / Django cache in Python, Spring Cache with Caffeine or Redis in Java/Kotlin, and ristretto / groupcache / singleflight / go-redis in Go. Use this skill whenever the user wants caching, to cache a query/response, Redis caching, @Cacheable, lru_cache, HybridCache, cache-aside, output caching, or asks "how do I cache this / add caching / avoid cache stampede / invalidate this cache". Always use this skill for caching requests; it picks the right layer and wires expiration + invalidation correctly./ai-dev-toolkit:specification-pattern-generatorfrom AI for Developers Toolkit
npx claudepluginhub stefanthecode/ai-for-developers --plugin ai-dev-toolkitOther plugins' skills for the same job