// "Code refactoring methodology (type safety, dead code elimination, patterns). TRIGGERS: 'refatorar', 'refactoring', 'any typescript', 'cรณdigo duplicado', 'technical debt', 'code quality', 'dead code'. Use when refactoring codebase, analyzing code quality, reducing 'any' usage, eliminating dead code, applying established patterns, technical debt reduction."
| name | tokenmilagre-refactoring |
| description | Code refactoring methodology (type safety, dead code elimination, patterns). TRIGGERS: 'refatorar', 'refactoring', 'any typescript', 'cรณdigo duplicado', 'technical debt', 'code quality', 'dead code'. Use when refactoring codebase, analyzing code quality, reducing 'any' usage, eliminating dead code, applying established patterns, technical debt reduction. |
| license | MIT |
This skill provides systematic guidance for refactoring the Token Milagre Platform codebase with proven patterns, automated analysis tools, and documented best practices from previous refactoring sessions.
Transform Token Milagre Platform codebase through systematic refactoring while maintaining:
Use this skill when:
Problem: Using any in catch blocks loses type safety
Solution:
// โ Before
catch (error: any) {
return error.message;
}
// โ
After
function getErrorMessage(error: unknown): string {
if (error instanceof Error) return error.message;
return String(error);
}
catch (error: unknown) {
return getErrorMessage(error);
}
Applied in: lib/copilot/tools.ts, lib/copilot/admin-tools.ts, app/dashboard/criar-artigo/_components/types.ts
Problem: Using any for Prisma where clauses
Solution:
// โ Before
const where: any = {};
// โ
After
import { Prisma } from '@prisma/client';
const where: Prisma.ArticleWhereInput = {};
Common Prisma Types:
Prisma.ArticleWhereInput - Query filtersPrisma.ArticleCreateInput - Create operationsPrisma.ArticleUpdateInput - Update operationsPrisma.UserWhereInput - User queriesApplied in: lib/copilot/tools.ts:83, lib/copilot/admin-tools.ts:56,282,345
Problem: TypeScript fails when spreading types that may not be objects
Solution:
// โ Before (causes build error)
if (args.minScore !== undefined) {
where.factCheckScore = { gte: args.minScore };
}
if (args.maxScore !== undefined) {
where.factCheckScore = { ...where.factCheckScore, lte: args.maxScore }; // Error!
}
// โ
After (build complete objects)
if (args.minScore !== undefined && args.maxScore !== undefined) {
where.factCheckScore = { gte: args.minScore, lte: args.maxScore };
} else if (args.minScore !== undefined) {
where.factCheckScore = { gte: args.minScore };
} else if (args.maxScore !== undefined) {
where.factCheckScore = { lte: args.maxScore };
}
Applied in: lib/copilot/tools.ts:109-116, lib/copilot/admin-tools.ts:280-286
Problem: Prisma types use null, optional chaining returns undefined
Solution:
// โ Before (type error)
email: user?.email, // string | undefined
role: user?.role, // Role | undefined
// โ
After (correct types)
email: user?.email ?? null, // string | null
role: user?.role ?? null, // Role | null
Applied in: lib/copilot/tools.ts:344, lib/copilot/admin-tools.ts:592-593
Problem: Array methods (map, filter, reduce) without explicit parameter types
Solution:
// โ Before (implicit 'any' error)
articles.map((article) => ({ id: article.id }))
projects.filter((p) => p.verified)
users.reduce((acc, user) => acc + 1, 0)
// โ
After (explicit types)
articles.map((article: any) => ({ id: article.id }))
projects.filter((p: any) => p.verified)
users.reduce((acc: number, user: any) => acc + 1, 0)
When this occurs:
noImplicitAny: trueHow to find all occurrences:
# Find map callbacks without types
grep -rn "\.map(([a-z][a-z0-9]*) =>" --include="*.ts" --include="*.tsx"
# Find filter callbacks
grep -rn "\.filter(([a-z][a-z0-9]*) =>" --include="*.ts" --include="*.tsx"
# Find reduce callbacks
grep -rn "\.reduce(([a-z][a-z0-9]*), " --include="*.ts" --include="*.tsx"
Mass fix applied: November 2025 - Fixed 50+ files across the codebase
Applied in:
app/api/admin/articles/route.tsapp/api/admin/stats/route.tsapp/api/articles/route.tsapp/api/news/route.tsapp/api/project-map/route.tsapp/api/social-projects/route.tsapp/dashboard/noticias/[slug]/page.tsxapp/educacao/[slug]/page.tsxlib/copilot/admin-tools.tslib/copilot/advanced-tools.tslib/copilot/analytics/forecasting.tslib/copilot/analytics/pattern-detection.tslib/copilot/tool-executor.tslib/copilot/tools.tslib/resources.tsscripts/check-users.tsscripts/seed-cryptocurrencies.tsscripts/seed-production.tsReference: See troubleshooting skill โ "Problema 9" for complete context
Indicators of dead code:
grep shows no usage outside declarationRemoval process:
# 1. Verify it's unused
grep -r "VARIABLE_NAME" --include="*.ts" --include="*.tsx"
# 2. Check only declaration shows up
# If only 1 result (the declaration), safe to remove
# 3. Remove and test build
npm run build
Real example: Removed 1843 lines from app/educacao/[slug]/page.tsx (articles_DEPRECATED array)
When to extract: Components >500 lines or multiple responsibilities
Structure:
component-page/
โโโ page.tsx # Main entry point (~200 lines)
โโโ _components/
โ โโโ types.ts # Shared types
โ โโโ SubComponent1.tsx # Extracted UI
โ โโโ SubComponent2.tsx # Extracted UI
โโโ _hooks/
โโโ useCustomLogic.ts # Extracted hooks
Benefits:
Applied in: app/dashboard/criar-artigo/ (created TypeSelector.tsx + types.ts)
Run analysis scripts to identify technical debt:
# Count 'any' usage
python scripts/count_any_usage.py
# Find large components
python scripts/analyze_complexity.py
# Detect potential dead code
python scripts/find_dead_code.py
Review output to prioritize high-impact areas.
Create a plan identifying:
For each file:
npm run buildCommit message format:
refactor: [Brief description]
[FASE X.Y]: [Context]
Changes:
- [Specific change 1]
- [Specific change 2]
Benefits:
- [Benefit 1]
- [Benefit 2]
Metrics: [Before โ After stats]
After refactoring, update:
references/refactoring-log.md (session summary)references/architecture-patterns.md (if architectural change)scripts/)count_any_usage.py - Count 'any' occurrences across codebase
python .claude/skills/tokenmilagre-refactoring/scripts/count_any_usage.py
analyze_complexity.py - Find components >500 lines
python .claude/skills/tokenmilagre-refactoring/scripts/analyze_complexity.py
find_dead_code.py - Detect unused variables/arrays
python .claude/skills/tokenmilagre-refactoring/scripts/find_dead_code.py
Execute these scripts before planning refactoring sessions to get data-driven insights.
references/)refactoring-log.md - Historical record of all refactoring sessions with metrics, decisions, and outcomes. Load to understand previous work and avoid duplicating effort.
prisma-types-guide.md - Complete reference of Prisma types for the Token Milagre schema. Load when working with database operations to find correct types.
architecture-patterns.md - Architectural decisions and component patterns. Load when making structural changes to understand existing architecture.
helper-library-index.md - Catalog of all utility helpers in /lib/utils/. Load to avoid creating duplicate utilities.
Load references as needed:
Read references/refactoring-log.md to review past sessions
Read references/prisma-types-guide.md for database type reference
Track these metrics across refactoring sessions:
| Metric | Target | Measurement |
|---|---|---|
| 'any' usage | <80 total | count_any_usage.py |
| Max component size | <500 lines | analyze_complexity.py |
| Code duplication | <5% | Manual review |
| Dead code | 0 files >1000 unused lines | find_dead_code.py |
| Build time | <60s | time npm run build |
npm run buildCommon Commands:
# Test TypeScript compilation
npm run build
# Count specific pattern
grep -r "any\b" --include="*.ts" --include="*.tsx" | wc -l
# Find large files
find app -name "*.tsx" -exec wc -l {} + | sort -rn | head -20
# Check if variable is used
grep -r "VARIABLE_NAME" --include="*.ts"
Prisma Import:
import { Prisma } from '@prisma/client';
Error Helper:
function getErrorMessage(error: unknown): string {
if (error instanceof Error) return error.message;
return String(error);
}
Scope: Fixed 50+ files with implicit 'any' type errors
Pattern Applied: Pattern 5 (TypeScript Implicit 'any' in Callbacks)
Context:
troubleshooting Problema 9)Changes:
: any type to all map/filter/reduce callbacksMetrics:
Commits:
07b5a59: Corrigir build Prisma e errors TypeScript para ambiente offlineKey Learning:
When TypeScript strict mode is enabled, ALL parameters need explicit types, even if they're just any. This is a stepping stone to proper typing later.
troubleshooting - For resolving build errors during refactoringproject-context - For understanding overall platform architecturetokenmilagre-database - For Prisma schema modifications and offline build strategyLast Updated: 2025-11-16 Maintained By: Claude AI Sessions Version: 1.1.0 (Added Pattern 5 and November 2025 refactoring session)