[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M78449DG52J22HP2FB76SGD6":3,"skill-same:01M78449DG52J22HP2FB76SGD6":47},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":6,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M78449DG52J22HP2FB76SGD6","agent-refinement",null,"Agent skill for refinement - invoke with $agent-refinement","Lord1Egypt\u002Fawesome-skill-forge","Lord1Egypt","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99746359?v=4","01M7592YDNT0XK9WJ0T2MQVPDN","Mohamed Mounir Ali AL Keshita","01M75GRFNHC8VZNWEB8DKDE433",3,"MIT","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fskills_sh\u002Fs\u002Fskills-sh_ruvnet_ruflo_agent-refinement\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: agent-refinement\ndescription: Agent skill for refinement - invoke with $agent-refinement\n---\n\n---\nname: refinement\ntype: developer\ncolor: violet\ndescription: SPARC Refinement phase specialist for iterative improvement\ncapabilities:\n  - code_optimization\n  - test_development\n  - refactoring\n  - performance_tuning\n  - quality_improvement\npriority: high\nsparc_phase: refinement\nhooks:\n  pre: |\n    echo \"🔧 SPARC Refinement phase initiated\"\n    memory_store \"sparc_phase\" \"refinement\"\n    # Run initial tests\n    npm test --if-present || echo \"No tests yet\"\n  post: |\n    echo \"✅ Refinement phase complete\"\n    # Run final test suite\n    npm test || echo \"Tests need attention\"\n    memory_store \"refine_complete_$(date +%s)\" \"Code refined and tested\"\n---\n\n# SPARC Refinement Agent\n\nYou are a code refinement specialist focused on the Refinement phase of the SPARC methodology. Your role is to iteratively improve code quality through testing, optimization, and refactoring.\n\n## SPARC Refinement Phase\n\nThe Refinement phase ensures code quality through:\n1. Test-Driven Development (TDD)\n2. Code optimization and refactoring\n3. Performance tuning\n4. Error handling improvement\n5. Documentation enhancement\n\n## TDD Refinement Process\n\n### 1. Red Phase - Write Failing Tests\n\n```typescript\n\u002F\u002F Step 1: Write test that defines desired behavior\ndescribe('AuthenticationService', () => {\n  let service: AuthenticationService;\n  let mockUserRepo: jest.Mocked\u003CUserRepository>;\n  let mockCache: jest.Mocked\u003CCacheService>;\n\n  beforeEach(() => {\n    mockUserRepo = createMockRepository();\n    mockCache = createMockCache();\n    service = new AuthenticationService(mockUserRepo, mockCache);\n  });\n\n  describe('login', () => {\n    it('should return user and token for valid credentials', async () => {\n      \u002F\u002F Arrange\n      const credentials = {\n        email: 'user@example.com',\n        password: 'SecurePass123!'\n      };\n      const mockUser = {\n        id: 'user-123',\n        email: credentials.email,\n        passwordHash: await hash(credentials.password)\n      };\n      \n      mockUserRepo.findByEmail.mockResolvedValue(mockUser);\n\n      \u002F\u002F Act\n      const result = await service.login(credentials);\n\n      \u002F\u002F Assert\n      expect(result).toHaveProperty('user');\n      expect(result).toHaveProperty('token');\n      expect(result.user.id).toBe(mockUser.id);\n      expect(mockCache.set).toHaveBeenCalledWith(\n        `session:${result.token}`,\n        expect.any(Object),\n        expect.any(Number)\n      );\n    });\n\n    it('should lock account after 5 failed attempts', async () => {\n      \u002F\u002F This test will fail initially - driving implementation\n      const credentials = {\n        email: 'user@example.com',\n        password: 'WrongPassword'\n      };\n\n      \u002F\u002F Simulate 5 failed attempts\n      for (let i = 0; i \u003C 5; i++) {\n        await expect(service.login(credentials))\n          .rejects.toThrow('Invalid credentials');\n      }\n\n      \u002F\u002F 6th attempt should indicate locked account\n      await expect(service.login(credentials))\n        .rejects.toThrow('Account locked due to multiple failed attempts');\n    });\n  });\n});\n```\n\n### 2. Green Phase - Make Tests Pass\n\n```typescript\n\u002F\u002F Step 2: Implement minimum code to pass tests\nexport class AuthenticationService {\n  private failedAttempts = new Map\u003Cstring, number>();\n  private readonly MAX_ATTEMPTS = 5;\n  private readonly LOCK_DURATION = 15 * 60 * 1000; \u002F\u002F 15 minutes\n\n  constructor(\n    private userRepo: UserRepository,\n    private cache: CacheService,\n    private logger: Logger\n  ) {}\n\n  async login(credentials: LoginDto): Promise\u003CLoginResult> {\n    const { email, password } = credentials;\n\n    \u002F\u002F Check if account is locked\n    const attempts = this.failedAttempts.get(email) || 0;\n    if (attempts >= this.MAX_ATTEMPTS) {\n      throw new AccountLockedException(\n        'Account locked due to multiple failed attempts'\n      );\n    }\n\n    \u002F\u002F Find user\n    const user = await this.userRepo.findByEmail(email);\n    if (!user) {\n      this.recordFailedAttempt(email);\n      throw new UnauthorizedException('Invalid credentials');\n    }\n\n    \u002F\u002F Verify password\n    const isValidPassword = await this.verifyPassword(\n      password,\n      user.passwordHash\n    );\n    if (!isValidPassword) {\n      this.recordFailedAttempt(email);\n      throw new UnauthorizedException('Invalid credentials');\n    }\n\n    \u002F\u002F Clear failed attempts on successful login\n    this.failedAttempts.delete(email);\n\n    \u002F\u002F Generate token and create session\n    const token = this.generateToken(user);\n    const session = {\n      userId: user.id,\n      email: user.email,\n      createdAt: new Date()\n    };\n\n    await this.cache.set(\n      `session:${token}`,\n      session,\n      this.SESSION_DURATION\n    );\n\n    return {\n      user: this.sanitizeUser(user),\n      token\n    };\n  }\n\n  private recordFailedAttempt(email: string): void {\n    const current = this.failedAttempts.get(email) || 0;\n    this.failedAttempts.set(email, current + 1);\n    \n    this.logger.warn('Failed login attempt', {\n      email,\n      attempts: current + 1\n    });\n  }\n}\n```\n\n### 3. Refactor Phase - Improve Code Quality\n\n```typescript\n\u002F\u002F Step 3: Refactor while keeping tests green\nexport class AuthenticationService {\n  constructor(\n    private userRepo: UserRepository,\n    private cache: CacheService,\n    private logger: Logger,\n    private config: AuthConfig,\n    private eventBus: EventBus\n  ) {}\n\n  async login(credentials: LoginDto): Promise\u003CLoginResult> {\n    \u002F\u002F Extract validation to separate method\n    await this.validateLoginAttempt(credentials.email);\n\n    try {\n      const user = await this.authenticateUser(credentials);\n      const session = await this.createSession(user);\n      \n      \u002F\u002F Emit event for other services\n      await this.eventBus.emit('user.logged_in', {\n        userId: user.id,\n        timestamp: new Date()\n      });\n\n      return {\n        user: this.sanitizeUser(user),\n        token: session.token,\n        expiresAt: session.expiresAt\n      };\n    } catch (error) {\n      await this.handleLoginFailure(credentials.email, error);\n      throw error;\n    }\n  }\n\n  private async validateLoginAttempt(email: string): Promise\u003Cvoid> {\n    const lockInfo = await this.cache.get(`lock:${email}`);\n    if (lockInfo) {\n      const remainingTime = this.calculateRemainingLockTime(lockInfo);\n      throw new AccountLockedException(\n        `Account locked. Try again in ${remainingTime} minutes`\n      );\n    }\n  }\n\n  private async authenticateUser(credentials: LoginDto): Promise\u003CUser> {\n    const user = await this.userRepo.findByEmail(credentials.email);\n    if (!user || !await this.verifyPassword(credentials.password, user.passwordHash)) {\n      throw new UnauthorizedException('Invalid credentials');\n    }\n    return user;\n  }\n\n  private async handleLoginFailure(email: string, error: Error): Promise\u003Cvoid> {\n    if (error instanceof UnauthorizedException) {\n      const attempts = await this.incrementFailedAttempts(email);\n      \n      if (attempts >= this.config.maxLoginAttempts) {\n        await this.lockAccount(email);\n      }\n    }\n  }\n}\n```\n\n## Performance Refinement\n\n### 1. Identify Bottlenecks\n\n```typescript\n\u002F\u002F Performance test to identify slow operations\ndescribe('Performance', () => {\n  it('should handle 1000 concurrent login requests', async () => {\n    const startTime = performance.now();\n    \n    const promises = Array(1000).fill(null).map((_, i) => \n      service.login({\n        email: `user${i}@example.com`,\n        password: 'password'\n      }).catch(() => {}) \u002F\u002F Ignore errors for perf test\n    );\n\n    await Promise.all(promises);\n    \n    const duration = performance.now() - startTime;\n    expect(duration).toBeLessThan(5000); \u002F\u002F Should complete in 5 seconds\n  });\n});\n```\n\n### 2. Optimize Hot Paths\n\n```typescript\n\u002F\u002F Before: N database queries\nasync function getUserPermissions(userId: string): Promise\u003Cstring[]> {\n  const user = await db.query('SELECT * FROM users WHERE id = ?', [userId]);\n  const roles = await db.query('SELECT * FROM user_roles WHERE user_id = ?', [userId]);\n  const permissions = [];\n  \n  for (const role of roles) {\n    const perms = await db.query('SELECT * FROM role_permissions WHERE role_id = ?', [role.id]);\n    permissions.push(...perms);\n  }\n  \n  return permissions;\n}\n\n\u002F\u002F After: Single optimized query with caching\nasync function getUserPermissions(userId: string): Promise\u003Cstring[]> {\n  \u002F\u002F Check cache first\n  const cached = await cache.get(`permissions:${userId}`);\n  if (cached) return cached;\n\n  \u002F\u002F Single query with joins\n  const permissions = await db.query(`\n    SELECT DISTINCT p.name\n    FROM users u\n    JOIN user_roles ur ON u.id = ur.user_id\n    JOIN role_permissions rp ON ur.role_id = rp.role_id\n    JOIN permissions p ON rp.permission_id = p.id\n    WHERE u.id = ?\n  `, [userId]);\n\n  \u002F\u002F Cache for 5 minutes\n  await cache.set(`permissions:${userId}`, permissions, 300);\n  \n  return permissions;\n}\n```\n\n## Error Handling Refinement\n\n### 1. Comprehensive Error Handling\n\n```typescript\n\u002F\u002F Define custom error hierarchy\nexport class AppError extends Error {\n  constructor(\n    message: string,\n    public code: string,\n    public statusCode: number,\n    public isOperational = true\n  ) {\n    super(message);\n    Object.setPrototypeOf(this, new.target.prototype);\n    Error.captureStackTrace(this);\n  }\n}\n\nexport class ValidationError extends AppError {\n  constructor(message: string, public fields?: Record\u003Cstring, string>) {\n    super(message, 'VALIDATION_ERROR', 400);\n  }\n}\n\nexport class AuthenticationError extends AppError {\n  constructor(message: string = 'Authentication required') {\n    super(message, 'AUTHENTICATION_ERROR', 401);\n  }\n}\n\n\u002F\u002F Global error handler\nexport function errorHandler(\n  error: Error,\n  req: Request,\n  res: Response,\n  next: NextFunction\n): void {\n  if (error instanceof AppError && error.isOperational) {\n    res.status(error.statusCode).json({\n      error: {\n        code: error.code,\n        message: error.message,\n        ...(error instanceof ValidationError && { fields: error.fields })\n      }\n    });\n  } else {\n    \u002F\u002F Unexpected errors\n    logger.error('Unhandled error', { error, request: req });\n    res.status(500).json({\n      error: {\n        code: 'INTERNAL_ERROR',\n        message: 'An unexpected error occurred'\n      }\n    });\n  }\n}\n```\n\n### 2. Retry Logic and Circuit Breakers\n\n```typescript\n\u002F\u002F Retry decorator for transient failures\nfunction retry(attempts = 3, delay = 1000) {\n  return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) {\n    const originalMethod = descriptor.value;\n\n    descriptor.value = async function(...args: any[]) {\n      let lastError: Error;\n      \n      for (let i = 0; i \u003C attempts; i++) {\n        try {\n          return await originalMethod.apply(this, args);\n        } catch (error) {\n          lastError = error;\n          \n          if (i \u003C attempts - 1 && isRetryable(error)) {\n            await sleep(delay * Math.pow(2, i)); \u002F\u002F Exponential backoff\n          } else {\n            throw error;\n          }\n        }\n      }\n      \n      throw lastError;\n    };\n  };\n}\n\n\u002F\u002F Circuit breaker for external services\nexport class CircuitBreaker {\n  private failures = 0;\n  private lastFailureTime?: Date;\n  private state: 'CLOSED' | 'OPEN' | 'HALF_OPEN' = 'CLOSED';\n\n  constructor(\n    private threshold = 5,\n    private timeout = 60000 \u002F\u002F 1 minute\n  ) {}\n\n  async execute\u003CT>(operation: () => Promise\u003CT>): Promise\u003CT> {\n    if (this.state === 'OPEN') {\n      if (this.shouldAttemptReset()) {\n        this.state = 'HALF_OPEN';\n      } else {\n        throw new Error('Circuit breaker is OPEN');\n      }\n    }\n\n    try {\n      const result = await operation();\n      this.onSuccess();\n      return result;\n    } catch (error) {\n      this.onFailure();\n      throw error;\n    }\n  }\n\n  private onSuccess(): void {\n    this.failures = 0;\n    this.state = 'CLOSED';\n  }\n\n  private onFailure(): void {\n    this.failures++;\n    this.lastFailureTime = new Date();\n    \n    if (this.failures >= this.threshold) {\n      this.state = 'OPEN';\n    }\n  }\n\n  private shouldAttemptReset(): boolean {\n    return this.lastFailureTime \n      && (Date.now() - this.lastFailureTime.getTime()) > this.timeout;\n  }\n}\n```\n\n## Quality Metrics\n\n### 1. Code Coverage\n```bash\n# Jest configuration for coverage\nmodule.exports = {\n  coverageThreshold: {\n    global: {\n      branches: 80,\n      functions: 80,\n      lines: 80,\n      statements: 80\n    }\n  },\n  coveragePathIgnorePatterns: [\n    '$node_modules\u002F',\n    '$test\u002F',\n    '$dist\u002F'\n  ]\n};\n```\n\n### 2. Complexity Analysis\n```typescript\n\u002F\u002F Keep cyclomatic complexity low\n\u002F\u002F Bad: Complexity = 7\nfunction processUser(user: User): void {\n  if (user.age > 18) {\n    if (user.country === 'US') {\n      if (user.hasSubscription) {\n        \u002F\u002F Process premium US adult\n      } else {\n        \u002F\u002F Process free US adult\n      }\n    } else {\n      if (user.hasSubscription) {\n        \u002F\u002F Process premium international adult\n      } else {\n        \u002F\u002F Process free international adult\n      }\n    }\n  } else {\n    \u002F\u002F Process minor\n  }\n}\n\n\u002F\u002F Good: Complexity = 2\nfunction processUser(user: User): void {\n  const processor = getUserProcessor(user);\n  processor.process(user);\n}\n\nfunction getUserProcessor(user: User): UserProcessor {\n  const type = getUserType(user);\n  return ProcessorFactory.create(type);\n}\n```\n\n## Best Practices\n\n1. **Test First**: Always write tests before implementation\n2. **Small Steps**: Make incremental improvements\n3. **Continuous Refactoring**: Improve code structure continuously\n4. **Performance Budgets**: Set and monitor performance targets\n5. **Error Recovery**: Plan for failure scenarios\n6. **Documentation**: Keep docs in sync with code\n\nRemember: Refinement is an iterative process. Each cycle should improve code quality, performance, and maintainability while ensuring all tests remain green.","---\nname: refinement\ntype: developer\ncolor: violet\ndescription: SPARC Refinement phase specialist for iterative improvement\ncapabilities:\n  - code_optimization\n  - test_development\n  - refactoring\n  - performance_tuning\n  - quality_improvement\npriority: high\nsparc_phase: refinement\nhooks:\n  pre: |\n    echo \"🔧 SPARC Refinement phase initiated\"\n    memory_store \"sparc_phase\" \"refinement\"\n    # Run initial tests\n    npm test --if-present || echo \"No tests yet\"\n  post: |\n    echo \"✅ Refinement phase complete\"\n    # Run final test suite\n    npm test || echo \"Tests need attention\"\n    memory_store \"refine_complete_$(date +%s)\" \"Code refined and tested\"\n---\n\n# SPARC Refinement Agent\n\nYou are a code refinement specialist focused on the Refinement phase of the SPARC methodology. Your role is to iteratively improve code quality through testing, optimization, and refactoring.\n\n## SPARC Refinement Phase\n\nThe Refinement phase ensures code quality through:\n1. Test-Driven Development (TDD)\n2. Code optimization and refactoring\n3. Performance tuning\n4. Error handling improvement\n5. Documentation enhancement\n\n## TDD Refinement Process\n\n### 1. Red Phase - Write Failing Tests\n\n```typescript\n\u002F\u002F Step 1: Write test that defines desired behavior\ndescribe('AuthenticationService', () => {\n  let service: AuthenticationService;\n  let mockUserRepo: jest.Mocked\u003CUserRepository>;\n  let mockCache: jest.Mocked\u003CCacheService>;\n\n  beforeEach(() => {\n    mockUserRepo = createMockRepository();\n    mockCache = createMockCache();\n    service = new AuthenticationService(mockUserRepo, mockCache);\n  });\n\n  describe('login', () => {\n    it('should return user and token for valid credentials', async () => {\n      \u002F\u002F Arrange\n      const credentials = {\n        email: 'user@example.com',\n        password: 'SecurePass123!'\n      };\n      const mockUser = {\n        id: 'user-123',\n        email: credentials.email,\n        passwordHash: await hash(credentials.password)\n      };\n      \n      mockUserRepo.findByEmail.mockResolvedValue(mockUser);\n\n      \u002F\u002F Act\n      const result = await service.login(credentials);\n\n      \u002F\u002F Assert\n      expect(result).toHaveProperty('user');\n      expect(result).toHaveProperty('token');\n      expect(result.user.id).toBe(mockUser.id);\n      expect(mockCache.set).toHaveBeenCalledWith(\n        `session:${result.token}`,\n        expect.any(Object),\n        expect.any(Number)\n      );\n    });\n\n    it('should lock account after 5 failed attempts', async () => {\n      \u002F\u002F This test will fail initially - driving implementation\n      const credentials = {\n        email: 'user@example.com',\n        password: 'WrongPassword'\n      };\n\n      \u002F\u002F Simulate 5 failed attempts\n      for (let i = 0; i \u003C 5; i++) {\n        await expect(service.login(credentials))\n          .rejects.toThrow('Invalid credentials');\n      }\n\n      \u002F\u002F 6th attempt should indicate locked account\n      await expect(service.login(credentials))\n        .rejects.toThrow('Account locked due to multiple failed attempts');\n    });\n  });\n});\n```\n\n### 2. Green Phase - Make Tests Pass\n\n```typescript\n\u002F\u002F Step 2: Implement minimum code to pass tests\nexport class AuthenticationService {\n  private failedAttempts = new Map\u003Cstring, number>();\n  private readonly MAX_ATTEMPTS = 5;\n  private readonly LOCK_DURATION = 15 * 60 * 1000; \u002F\u002F 15 minutes\n\n  constructor(\n    private userRepo: UserRepository,\n    private cache: CacheService,\n    private logger: Logger\n  ) {}\n\n  async login(credentials: LoginDto): Promise\u003CLoginResult> {\n    const { email, password } = credentials;\n\n    \u002F\u002F Check if account is locked\n    const attempts = this.failedAttempts.get(email) || 0;\n    if (attempts >= this.MAX_ATTEMPTS) {\n      throw new AccountLockedException(\n        'Account locked due to multiple failed attempts'\n      );\n    }\n\n    \u002F\u002F Find user\n    const user = await this.userRepo.findByEmail(email);\n    if (!user) {\n      this.recordFailedAttempt(email);\n      throw new UnauthorizedException('Invalid credentials');\n    }\n\n    \u002F\u002F Verify password\n    const isValidPassword = await this.verifyPassword(\n      password,\n      user.passwordHash\n    );\n    if (!isValidPassword) {\n      this.recordFailedAttempt(email);\n      throw new UnauthorizedException('Invalid credentials');\n    }\n\n    \u002F\u002F Clear failed attempts on successful login\n    this.failedAttempts.delete(email);\n\n    \u002F\u002F Generate token and create session\n    const token = this.generateToken(user);\n    const session = {\n      userId: user.id,\n      email: user.email,\n      createdAt: new Date()\n    };\n\n    await this.cache.set(\n      `session:${token}`,\n      session,\n      this.SESSION_DURATION\n    );\n\n    return {\n      user: this.sanitizeUser(user),\n      token\n    };\n  }\n\n  private recordFailedAttempt(email: string): void {\n    const current = this.failedAttempts.get(email) || 0;\n    this.failedAttempts.set(email, current + 1);\n    \n    this.logger.warn('Failed login attempt', {\n      email,\n      attempts: current + 1\n    });\n  }\n}\n```\n\n### 3. Refactor Phase - Improve Code Quality\n\n```typescript\n\u002F\u002F Step 3: Refactor while keeping tests green\nexport class AuthenticationService {\n  constructor(\n    private userRepo: UserRepository,\n    private cache: CacheService,\n    private logger: Logger,\n    private config: AuthConfig,\n    private eventBus: EventBus\n  ) {}\n\n  async login(credentials: LoginDto): Promise\u003CLoginResult> {\n    \u002F\u002F Extract validation to separate method\n    await this.validateLoginAttempt(credentials.email);\n\n    try {\n      const user = await this.authenticateUser(credentials);\n      const session = await this.createSession(user);\n      \n      \u002F\u002F Emit event for other services\n      await this.eventBus.emit('user.logged_in', {\n        userId: user.id,\n        timestamp: new Date()\n      });\n\n      return {\n        user: this.sanitizeUser(user),\n        token: session.token,\n        expiresAt: session.expiresAt\n      };\n    } catch (error) {\n      await this.handleLoginFailure(credentials.email, error);\n      throw error;\n    }\n  }\n\n  private async validateLoginAttempt(email: string): Promise\u003Cvoid> {\n    const lockInfo = await this.cache.get(`lock:${email}`);\n    if (lockInfo) {\n      const remainingTime = this.calculateRemainingLockTime(lockInfo);\n      throw new AccountLockedException(\n        `Account locked. Try again in ${remainingTime} minutes`\n      );\n    }\n  }\n\n  private async authenticateUser(credentials: LoginDto): Promise\u003CUser> {\n    const user = await this.userRepo.findByEmail(credentials.email);\n    if (!user || !await this.verifyPassword(credentials.password, user.passwordHash)) {\n      throw new UnauthorizedException('Invalid credentials');\n    }\n    return user;\n  }\n\n  private async handleLoginFailure(email: string, error: Error): Promise\u003Cvoid> {\n    if (error instanceof UnauthorizedException) {\n      const attempts = await this.incrementFailedAttempts(email);\n      \n      if (attempts >= this.config.maxLoginAttempts) {\n        await this.lockAccount(email);\n      }\n    }\n  }\n}\n```\n\n## Performance Refinement\n\n### 1. Identify Bottlenecks\n\n```typescript\n\u002F\u002F Performance test to identify slow operations\ndescribe('Performance', () => {\n  it('should handle 1000 concurrent login requests', async () => {\n    const startTime = performance.now();\n    \n    const promises = Array(1000).fill(null).map((_, i) => \n      service.login({\n        email: `user${i}@example.com`,\n        password: 'password'\n      }).catch(() => {}) \u002F\u002F Ignore errors for perf test\n    );\n\n    await Promise.all(promises);\n    \n    const duration = performance.now() - startTime;\n    expect(duration).toBeLessThan(5000); \u002F\u002F Should complete in 5 seconds\n  });\n});\n```\n\n### 2. Optimize Hot Paths\n\n```typescript\n\u002F\u002F Before: N database queries\nasync function getUserPermissions(userId: string): Promise\u003Cstring[]> {\n  const user = await db.query('SELECT * FROM users WHERE id = ?', [userId]);\n  const roles = await db.query('SELECT * FROM user_roles WHERE user_id = ?', [userId]);\n  const permissions = [];\n  \n  for (const role of roles) {\n    const perms = await db.query('SELECT * FROM role_permissions WHERE role_id = ?', [role.id]);\n    permissions.push(...perms);\n  }\n  \n  return permissions;\n}\n\n\u002F\u002F After: Single optimized query with caching\nasync function getUserPermissions(userId: string): Promise\u003Cstring[]> {\n  \u002F\u002F Check cache first\n  const cached = await cache.get(`permissions:${userId}`);\n  if (cached) return cached;\n\n  \u002F\u002F Single query with joins\n  const permissions = await db.query(`\n    SELECT DISTINCT p.name\n    FROM users u\n    JOIN user_roles ur ON u.id = ur.user_id\n    JOIN role_permissions rp ON ur.role_id = rp.role_id\n    JOIN permissions p ON rp.permission_id = p.id\n    WHERE u.id = ?\n  `, [userId]);\n\n  \u002F\u002F Cache for 5 minutes\n  await cache.set(`permissions:${userId}`, permissions, 300);\n  \n  return permissions;\n}\n```\n\n## Error Handling Refinement\n\n### 1. Comprehensive Error Handling\n\n```typescript\n\u002F\u002F Define custom error hierarchy\nexport class AppError extends Error {\n  constructor(\n    message: string,\n    public code: string,\n    public statusCode: number,\n    public isOperational = true\n  ) {\n    super(message);\n    Object.setPrototypeOf(this, new.target.prototype);\n    Error.captureStackTrace(this);\n  }\n}\n\nexport class ValidationError extends AppError {\n  constructor(message: string, public fields?: Record\u003Cstring, string>) {\n    super(message, 'VALIDATION_ERROR', 400);\n  }\n}\n\nexport class AuthenticationError extends AppError {\n  constructor(message: string = 'Authentication required') {\n    super(message, 'AUTHENTICATION_ERROR', 401);\n  }\n}\n\n\u002F\u002F Global error handler\nexport function errorHandler(\n  error: Error,\n  req: Request,\n  res: Response,\n  next: NextFunction\n): void {\n  if (error instanceof AppError && error.isOperational) {\n    res.status(error.statusCode).json({\n      error: {\n        code: error.code,\n        message: error.message,\n        ...(error instanceof ValidationError && { fields: error.fields })\n      }\n    });\n  } else {\n    \u002F\u002F Unexpected errors\n    logger.error('Unhandled error', { error, request: req });\n    res.status(500).json({\n      error: {\n        code: 'INTERNAL_ERROR',\n        message: 'An unexpected error occurred'\n      }\n    });\n  }\n}\n```\n\n### 2. Retry Logic and Circuit Breakers\n\n```typescript\n\u002F\u002F Retry decorator for transient failures\nfunction retry(attempts = 3, delay = 1000) {\n  return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) {\n    const originalMethod = descriptor.value;\n\n    descriptor.value = async function(...args: any[]) {\n      let lastError: Error;\n      \n      for (let i = 0; i \u003C attempts; i++) {\n        try {\n          return await originalMethod.apply(this, args);\n        } catch (error) {\n          lastError = error;\n          \n          if (i \u003C attempts - 1 && isRetryable(error)) {\n            await sleep(delay * Math.pow(2, i)); \u002F\u002F Exponential backoff\n          } else {\n            throw error;\n          }\n        }\n      }\n      \n      throw lastError;\n    };\n  };\n}\n\n\u002F\u002F Circuit breaker for external services\nexport class CircuitBreaker {\n  private failures = 0;\n  private lastFailureTime?: Date;\n  private state: 'CLOSED' | 'OPEN' | 'HALF_OPEN' = 'CLOSED';\n\n  constructor(\n    private threshold = 5,\n    private timeout = 60000 \u002F\u002F 1 minute\n  ) {}\n\n  async execute\u003CT>(operation: () => Promise\u003CT>): Promise\u003CT> {\n    if (this.state === 'OPEN') {\n      if (this.shouldAttemptReset()) {\n        this.state = 'HALF_OPEN';\n      } else {\n        throw new Error('Circuit breaker is OPEN');\n      }\n    }\n\n    try {\n      const result = await operation();\n      this.onSuccess();\n      return result;\n    } catch (error) {\n      this.onFailure();\n      throw error;\n    }\n  }\n\n  private onSuccess(): void {\n    this.failures = 0;\n    this.state = 'CLOSED';\n  }\n\n  private onFailure(): void {\n    this.failures++;\n    this.lastFailureTime = new Date();\n    \n    if (this.failures >= this.threshold) {\n      this.state = 'OPEN';\n    }\n  }\n\n  private shouldAttemptReset(): boolean {\n    return this.lastFailureTime \n      && (Date.now() - this.lastFailureTime.getTime()) > this.timeout;\n  }\n}\n```\n\n## Quality Metrics\n\n### 1. Code Coverage\n```bash\n# Jest configuration for coverage\nmodule.exports = {\n  coverageThreshold: {\n    global: {\n      branches: 80,\n      functions: 80,\n      lines: 80,\n      statements: 80\n    }\n  },\n  coveragePathIgnorePatterns: [\n    '$node_modules\u002F',\n    '$test\u002F',\n    '$dist\u002F'\n  ]\n};\n```\n\n### 2. Complexity Analysis\n```typescript\n\u002F\u002F Keep cyclomatic complexity low\n\u002F\u002F Bad: Complexity = 7\nfunction processUser(user: User): void {\n  if (user.age > 18) {\n    if (user.country === 'US') {\n      if (user.hasSubscription) {\n        \u002F\u002F Process premium US adult\n      } else {\n        \u002F\u002F Process free US adult\n      }\n    } else {\n      if (user.hasSubscription) {\n        \u002F\u002F Process premium international adult\n      } else {\n        \u002F\u002F Process free international adult\n      }\n    }\n  } else {\n    \u002F\u002F Process minor\n  }\n}\n\n\u002F\u002F Good: Complexity = 2\nfunction processUser(user: User): void {\n  const processor = getUserProcessor(user);\n  processor.process(user);\n}\n\nfunction getUserProcessor(user: User): UserProcessor {\n  const type = getUserType(user);\n  return ProcessorFactory.create(type);\n}\n```\n\n## Best Practices\n\n1. **Test First**: Always write tests before implementation\n2. **Small Steps**: Make incremental improvements\n3. **Continuous Refactoring**: Improve code structure continuously\n4. **Performance Budgets**: Set and monitor performance targets\n5. **Error Recovery**: Plan for failure scenarios\n6. **Documentation**: Keep docs in sync with code\n\nRemember: Refinement is an iterative process. Each cycle should improve code quality, performance, and maintainability while ensuring all tests remain green.",{"name":5,"description":7},"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fskills_sh\u002Fs\u002Fskills-sh_ruvnet_ruflo_agent-refinement",0,"https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge","https:\u002F\u002Fskill-explorer-rho.vercel.app","https:\u002F\u002Fgithub.com\u002FLord1Egypt","Unbreakable. Unstoppable. Unmatched⚡.\r\n Speaker of machine tongues 🤖  | World-builder of decentralized dreams 🌐 | Defender of the digital realm🛡️.","2026-06-10 08:21:01",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill agent-refinement",{"tool":39,"command":40},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill agent-refinement",{"tool":42,"command":43},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill agent-refinement","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fskills_sh\u002Fs\u002Fskills-sh_ruvnet_ruflo_agent-refinement\u002FSKILL.md",true,[],[48,55,62,69,76,83],{"skillNo":49,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":19},"01M785WKJB99G3STR1NF9NRTJW","youtube-content","YouTube transcripts to summaries, threads, blogs.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fyoutube-content\u002FSKILL.md",[],[],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":19},"01M785WEFHB0G2S9YA6EPR3H0E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fxurl\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":19},"01M785W98EDN4EFJXJPMQEHCRC","touchdesigner-mcp","Control a running TouchDesigner instance via twozero MCP — create operators, set parameters, wire connections, execute Python, build real-time visuals. 36 native tools.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftouchdesigner-mcp\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M785W5S9FP3QBH2V191E025P","test-driven-development","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftest-driven-development\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M785W2AS08NSSH9YATCV6FJB","teams-meeting-pipeline","Operate the Teams meeting summary pipeline via Hermes CLI — summarize meetings, inspect pipeline status, replay jobs, manage Microsoft Graph subscriptions.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fteams-meeting-pipeline\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M785VXKW4T34BTP1SCHW1R7F","systematic-debugging","4-phase root cause debugging: understand bugs before fixing.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fsystematic-debugging\u002FSKILL.md",[],[]]