refactor-optimize
Skill1 starsChanged 9 months agoMITView on GitHub
Refactor and optimize Glotti (gemili) source code according to architecture standards (DI, Services, Validation).
In this repository4 other files it gives its agents.
- adjust-personaSkill
- project-contextSkill
- refactoringSkill
- update-docsSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
25 rules. About 0 are common, 11 are distinctive, and 14 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈11
Distinctive · estimate
This author's own choices. Worth a look.
14
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 14
Before modifying any code, the AI MUST analyze the target file(s) using this framework:
- Very specific: line 27
When a server file mixes many concerns (e.g., ws-handler.ts was ~320 LOC with 9 responsibilities), apply this extraction order:
- Distinctive: line 59
When refactoring API routes, apply these patterns:
- Very specific: line 61
Dependency Injection: Do not import store directly.
- Very specific: line 65
Validation: Use zod schemas for all req.query, req.params, and req.body.
- Very specific: line 66
CRITICAL: All string validations MUST include .trim() before .min(1) and MUST have a .max(N) limit to prevent memory exhaustion DoS attacks.
- Very specific: line 67
CRITICAL: All object schemas MUST end with .strict() to reject unexpected fields.
- Distinctive: line 74
When optimizing React components:
- Very specific: line 76
Memoization: Use useMemo for expensive calculations (derived metrics) and useCallback for event handlers passed to children.
- Very specific: line 82
Deduplication: If logic appears in 2+ places (e.g., share key generation), move it to utils/ or shared/.
- Very specific: line 90
Check for Existing Plan: Check if a refactoring log exists at specs/[source_file_name]_refactoring.md (e.g., …
- Distinctive: line 92
Read the file to understand the context and current status.
- Distinctive: line 93
Condition A (Ongoing): If unchecked items remain, resume refactoring from the next pending item.
- Distinctive: line 94
Condition B (New Changes): If all items are checked but the file has been modified since or new issues are found:
- Distinctive: line 97
Add new checklist items for the new findings.
- Distinctive: line 99
Read the code and analyze it against the Analysis Framework (Section 1).
- Distinctive: line 101
Document findings, violations, and a step-by-step refactoring plan with a checklist.
- Very specific: line 103
Backup (If New): If starting fresh, copy the original file to a -legacy.ts variant (e.g., ws-handler-legacy.ts) to allow safe rollback.
- Distinctive: line 107
Follow the extraction order in Section 2A (constants -> pure functions -> state -> etc.).
- Very specific: line 111
After completing a step, immediately update specs/[source_file_name]_refactoring.md.
- Distinctive: line 113
Add notes about any deviations or new discoveries.
- Very specific: line 115
Verify Iteratively: After each extraction, verify npx tsc --noEmit passes to ensure incremental correctness.
- Very specific: line 117
Final Verification: Run npx tsc --noEmit for a clean build.
- Very specific: line 119
Document: Update relevant specs/*.md files to reflect the new file structure and patterns.
- Very specific: line 123
Session Store: Always interface with SessionStore abstractly.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Code Refactoring & Optimization Skill
This skill guides the AI to refactor and optimize code within the Glotti (gemili) project, ensuring improvements align with established architecture, patterns, and quality standards.
1. Analysis Framework
Before modifying any code, the AI MUST analyze the target file(s) using this framework:
- Responsibility Check: Does this file/function do too much? (e.g., mixing data fetching, business logic, and UI rendering). Files with 9+ responsibilities or 14+ mutable closure variables are "god objects" — split them.
- Dependency Check: Are there circular dependencies or cross-boundary imports? Are there duplicate instantiations (e.g., two
createStore()calls in different files)? - Security Check: Are inputs validated (Zod)? Do string validations explicitly use
.trim()and.max(limit)to prevent DoS attacks via huge payloads or whitespace bypasses? Are objects.strict()to prevent prototype pollution or JSON bloat? Are outputs sanitized? Are debug hooks guarded byconfig.isDev? - Performance Check: Are expensive operations cached? Are unrelated computations blocking the event loop? Watch for O(n²) patterns (e.g., recomputing metrics from full transcript history on every update).
- Type Safety: Are there
anytypes or loose casts (as string) that can be strict? Replace looseletclosure variables with a typed state object. - Regex Check: Are regex patterns in
RegExpconstructors or string form double-escaped? e.g.,[^\\w\\s]in a regex literal is wrong — use[^\w\s].
2. Standard Refactoring Patterns for Glotti
A. Server-Side "God File" Decomposition (server/*.ts)
When a server file mixes many concerns (e.g., ws-handler.ts was ~320 LOC with 9 responsibilities), apply this extraction order:
- Constants first: Extract magic numbers and static arrays to a
constants.tsfile. This is zero-risk. - Pure functions next: Extract stateless logic (e.g.,
extractMetrics()) to its own module. These are easiest to test. - Stateful classes: Extract logic that manages internal state into classes (e.g.,
TranscriptBuffer,ToneAnalyzer). Pass dependencies via constructor. - Typed state object: Replace loose closure
letvariables with a typedinterface+ factory function (e.g.,SessionState+createSessionState()). This makes state explicit and debuggable. - Protocol/serialization layer: Extract message parsing and serialization into a
protocol.ts. Keep it stateless — passwsand payload as params. - Bridge/connection module: Extract external API connections (e.g., Gemini Live) into a bridge module with a factory function (e.g.,
connectGemini()returns{ session, close() }). - Feature-specific modules: Extract mode-specific logic (e.g.,
feedback-context.ts) into standalone async functions. - Slim orchestrator: The original file becomes a thin orchestrator (~100-120 LOC) that wires modules together and handles lifecycle.
Reference implementation: server/session/ directory (extracted from ws-handler.ts). See specs/voice_agent_websockets.md for full documentation.
B. Server-Side Dependency Injection
Glotti uses module-level DI with setDependencies() — not constructor injection on the orchestrator:
// In the orchestrator (ws-handler.ts):
export interface SessionDependencies { genai: GoogleGenAI; store: SessionStore; }
const deps: SessionDependencies = createDependencies();
export function setDependencies(overrides: Partial<SessionDependencies>): void { ... }
// In main.ts (wiring):
import { setDependencies } from './ws-handler.js';
setDependencies({ store });For extracted modules, prefer function-parameter DI (pure functions receive all inputs) or constructor DI (classes receive dependencies in constructor). The factory createSessionState() composes internal dependencies (creates TranscriptBuffer, ToneAnalyzer instances).
C. Server-Side Route Refactoring (server/api/*.ts)
When refactoring API routes, apply these patterns:
- Dependency Injection: Do not import
storedirectly. Create a factory function:export function createRouter(store: SessionStore): Router { ... } - Validation: Use
zodschemas for allreq.query,req.params, andreq.body.- CRITICAL: All string validations MUST include
.trim()before.min(1)and MUST have a.max(N)limit to prevent memory exhaustion DoS attacks. - CRITICAL: All object schemas MUST end with
.strict()to reject unexpected fields.
- CRITICAL: All string validations MUST include
- Service Extraction: Move complex logic (e.g., image generation, PDF rendering) to
server/services/. - Middleware: Extract auth and guard logic to
server/middleware/. - Error Handling: Catch all errors and return standardized JSON:
{ error: string }.
D. Client-Side Component Optimization (client/src/**/*.tsx)
When optimizing React components:
- Memoization: Use
useMemofor expensive calculations (derived metrics) anduseCallbackfor event handlers passed to children. - Splitting: Break large components (>200 lines) into smaller, single-purpose sub-components.
- Hooks: Extract logic into custom hooks (
useSessionLogic,useAudioAnalysis) to keep views clean.
E. Shared Utilities
- Deduplication: If logic appears in 2+ places (e.g., share key generation), move it to
utils/orshared/. - Environment Agnostic: Utilities that run in both environments (client/server) must not import Node-specific (
fs,crypto) or Browser-specific (window,navigator) APIs without polyfills or checks.
3. Execution Workflow
To apply this skill:
- Initialize Workflow:
- Check for Existing Plan: Check if a refactoring log exists at
specs/[source_file_name]_refactoring.md(e.g.,specs/ws_handler_refactoring.md). - If Plan Exists (Incremental Mode):
- Read the file to understand the context and current status.
- Condition A (Ongoing): If unchecked items remain, resume refactoring from the next pending item.
- Condition B (New Changes): If all items are checked but the file has been modified since or new issues are found:
- Re-analyze the current file against the Analysis Framework (Section 1).
- Append a new section (e.g.,
## [Date] Additional Refactoring) to the existing log. - Add new checklist items for the new findings.
- If No Plan Exists (Start New):
- Read the code and analyze it against the Analysis Framework (Section 1).
- Create
specs/[source_file_name]_refactoring.md. - Document findings, violations, and a step-by-step refactoring plan with a checklist.
- Check for Existing Plan: Check if a refactoring log exists at
- Backup (If New): If starting fresh, copy the original file to a
-legacy.tsvariant (e.g.,ws-handler-legacy.ts) to allow safe rollback. - Refactor (Iterative):
- Execute the next step(s) from the plan.
- Follow the extraction order in Section 2A (constants -> pure functions -> state -> etc.).
- Apply changes incrementally.
- Update Log:
- After completing a step, immediately update
specs/[source_file_name]_refactoring.md. - Mark completed items with
[x]. - Add notes about any deviations or new discoveries.
- After completing a step, immediately update
- Verify Iteratively: After each extraction, verify
npx tsc --noEmitpasses to ensure incremental correctness. - Final Verification: Run
npx tsc --noEmitfor a clean build. All imports must use.jsextensions (ESNext modules). - Document: Update relevant
specs/*.mdfiles to reflect the new file structure and patterns.
4. Specific Considerations for Glotti
- Session Store: Always interface with
SessionStoreabstractly; never assumeFileStoreorFirestoreimplementation details in business logic. The store is a shared singleton created inmain.tsand injected viasetDependencies(). Never callcreateStore()from multiple files. - Gemini Streaming: Audio handling is real-time; avoid blocking the event loop in
ws-handler. Fire-and-forget patterns (e.g.,ToneAnalyzer.tryAnalyze()returningPromise | null) are acceptable for background LLM calls — but always guard against acting on results after session closure. - OG Images: Rendering is expensive; always use the LRU cache strategy defined in
server/services/og-renderer.ts. - TypeScript Config: ES2022 target, ESNext modules, bundler moduleResolution. All server imports use
.jsextensions. Thetsconfig.jsonincludecoversserver/**/*.ts, so new subdirectories (likeserver/session/) are automatically included. - Module Organization: Group related session modules under
server/session/. Each module should have a single concern and clear exports (see Section 2A for the pattern).
5. Common Bugs to Watch For
These bugs were found during prior refactoring and should be checked in future audits:
| Bug Pattern | Example | Fix |
| Regex double-escaping | [^\\w\\s] in regex literal | Use [^\w\s] — string escaping adds extra backslash |
| Duplicate singletons | Two files both calling createStore() | Single instantiation in main.ts, inject elsewhere |
| Debug code in production | globalThis.WebSocket.prototype.send monkey-patch | Remove entirely or guard with if (config.isDev) |
| Stale closure state | Checking sessionClosed boolean after async gap | Use typed state object with status field, check before acting |
| Unguarded WebSocket sends | Sending to closed WebSocket throws | Always check ws.readyState === WebSocket.OPEN via isWsOpen() helper |
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
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.

