architecture-refactor
Analyze and refactor backend code to follow entity/service separation patterns. Use when asked to "refactor X to entity pattern", "analyze architecture for X", "extract business rules for X", "separate concerns for X", "create entity for X", or "clean up X service". Triggers on domain concepts like deals, leads, applications, locations, franchisees, etc.
What this skill does
# Architecture Refactor
Analyze backend code for a domain concept and refactor to follow the entity/service separation pattern.
## Architecture Overview
```
Controller (HTTP only)
↓
Service (orchestration, enforcement, side effects)
↓
Entity (business rules as predicates, data access)
↓
Database
```
### Layer Responsibilities
| Layer | Does | Does Not |
| -------------- | ----------------------------------------------------------------------------------------------- | ------------------------------------------------- |
| **Controller** | Parse request, auth, permissions, call service, format response | Business logic, call entities, transactions |
| **Service** | Orchestrate entities, enforce rules (throw), business logic, transactions, trigger side effects | Define rules, write SQL, know HTTP |
| **Entity** | Define rules (canX → boolean), CRUD, queries, data transformation | Throw on rules, call other entities, side effects |
### Key Principle: Rules vs Enforcement
```
ENTITY (defines rules):
canConvert(deal) → { allowed: false, reason: 'Already converted' }
SERVICE (enforces rules):
const { allowed, reason } = dealEntity.canConvert(deal);
if (!allowed) throw new ValidationError(reason); ← SERVICE THROWS
```
## Workflow
### Step 1: Identify Target Files
When user asks to refactor a concept (e.g., "deals"), locate:
```bash
# Find relevant files
find . -name "*deal*" -type f | grep -E "\.(ts|js)$"
```
Look for:
- `{concept}Service.ts` (e.g., `dealsService.ts`)
- `{concept}Controller.ts` (e.g., `dealsController.ts`)
- `{concept}Entity.ts` if it exists
- Related types in `@fsai/sdk` or local `.types.ts` files
Report what you found:
```
📁 Found files for "deals":
• api/deals/dealsService.ts (523 lines)
• api/deals/dealsController.ts (412 lines)
• contact/deal/dealEntity.ts (89 lines) - partial implementation
• Types: @fsai/sdk Deal, DealOverview, DealSummary
```
### Step 2: Analyze Current State
Scan the service file and categorize code:
**🔴 SCATTERED BUSINESS RULES** (should be entity predicates)
```typescript
// These patterns should become entity predicates:
if (deal.convertedAt) throw new ValidationError('...') → canConvert()
if (!deal.applicationId) throw new ValidationError('...') → canConvert()
if (deal.status === 'won') ... → canDelete(), isWon()
if (!deal.applicationId && deal.franchiseeOrgId) ... → isEntityDeal()
```
**🟡 DATA ACCESS** (should move to entity)
```typescript
// Direct database calls should move to entity:
await database.query.deals.findFirst(...) → entity.getById()
await database.insert(drizzleSchema.deals).values(...) → entity.create()
await database.update(drizzleSchema.deals).set(...) → entity.update()
```
**🟠 SIDE EFFECTS** (should be extracted to notification/event classes)
```typescript
// These should be separate:
await notificationsService.franchisees.sendBatch(...) → dealNotifications.onConverted()
await portalEventsService.fireEvent(...) → dealEvents.emitConverted()
logger.info('Business event...') → dealEvents.emit*()
```
**🟢 ORCHESTRATION** (correct location - stays in service)
```typescript
// This is correct for service:
await database.transaction(async () => { ... })
const result = await entityA.create(); await entityB.update();
if (featureFlag) { ... } else { ... }
```
Report findings:
```
🔍 Analysis of dealsService.ts:
BUSINESS RULES (scattered - move to entity):
• Line 340: if (deal.convertedAt) throw → canConvert()
• Line 336: if (!deal.applicationId) throw → canConvert()
• Line 89: implicit - deals require applicationId → document as rule
DATA ACCESS (move to entity):
• getDealOverview() - 80 lines of joins
• createDeal() - insert with displayId generation
• updateDeal() - direct update
SIDE EFFECTS (extract):
• Line 412: notification batch → dealNotifications.onConverted()
• Line 380: invitation service → keep in service but after transaction
ORCHESTRATION (correct - keep in service):
• convertDealToFranchisee() - coordinates multiple entities
• Transaction at line 350
```
### Step 3: Propose Entity Interface
Based on analysis, propose the entity structure:
```typescript
// Proposed: dealEntity.ts
class DealEntity {
// ═══════════ Business Rules (Predicates) ═══════════
// Return boolean or { allowed, reason } - NEVER throw
isEntityDeal(deal): boolean;
isApplicationDeal(deal): boolean;
canConvert(deal): { allowed: boolean; reason?: string };
canHaveProposedLocations(deal): boolean;
canHaveAdditionalApplications(deal): boolean;
canDelete(deal): { allowed: boolean; reason?: string };
// ═══════════ Data Access ═══════════
getById(dealId): Promise<Deal | null>;
getOverview(dealId): Promise<DealOverview | null>;
getByApplication(applicationId): Promise<string | null>;
getByBrand(brandId): Promise<DealSummary[]>;
create(params): Promise<string>;
update(dealId, updates): Promise<void>;
markConverted(dealId, franchiseeOrgId): Promise<void>;
delete(dealId): Promise<void>;
}
```
**Ask user to confirm before proceeding with implementation.**
### Step 4: Implement Entity
Create or update the entity file following this pattern:
```typescript
import { eq, and, desc } from "drizzle-orm";
import { drizzleSchema } from "@fsai/supabase";
import { database } from "../../db/db.js";
import type { Deal, DealOverview } from "@fsai/sdk";
class DealEntity {
// ═══════════════════════════════════════════════════════════════
// BUSINESS RULES (Predicates)
// - Return boolean or { allowed, reason }
// - NEVER throw
// - No side effects
// - Testable in isolation
// ═══════════════════════════════════════════════════════════════
isEntityDeal(
deal: Pick<DealOverview, "applicationId" | "franchiseeOrgId">
): boolean {
return !deal.applicationId && Boolean(deal.franchiseeOrgId);
}
isApplicationDeal(deal: Pick<DealOverview, "applicationId">): boolean {
return Boolean(deal.applicationId);
}
canConvert(
deal: Pick<
DealOverview,
"applicationId" | "convertedAt" | "franchiseeOrgId"
>
): { allowed: boolean; reason?: string } {
if (deal.convertedAt) {
return { allowed: false, reason: "Deal has already been converted" };
}
if (this.isEntityDeal(deal)) {
return {
allowed: false,
reason: "Entity-based deals cannot be converted",
};
}
if (!deal.applicationId) {
return { allowed: false, reason: "Deal has no application to convert" };
}
return { allowed: true };
}
canHaveProposedLocations(
deal: Pick<DealOverview, "applicationId" | "franchiseeOrgId">
): boolean {
return this.isApplicationDeal(deal);
}
canDelete(deal: Pick<DealOverview, "convertedAt" | "status">): {
allowed: boolean;
reason?: string;
} {
if (deal.convertedAt) {
return { allowed: false, reason: "Cannot delete converted deals" };
}
return { allowed: true };
}
// ═══════════════════════════════════════════════════════════════
// DATA ACCESS
// - Encapsulate all database operations
// - Handle joins and transformations
// - Return null for not found (don't throw usually)
// ═══════════════════════════════════════════════════════════════
async getById(dealId: string): Promise<Deal | null> {
const data = await database.query.deals.findFirst({
where: eq(drizzleSchema.deals.id, dealId),
});
return data ?? null;
}
async getOverview(dealId: string): Promise<DealOverview | null> {
// Complex query with joins, transformed to domain shape
const data = await database.query.deals.findFirst({
where: eq(drizzleSchema.deals.id, dealId),
with: {
dealsAgreementsFees: { with: { agreementFee: truRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.