clean-code
The clean-code skill enforces single responsibility, focused function design, meaningful naming, manageable complexity, and self-documenting code patterns during implementation work. Apply this skill when generating new code, refactoring existing code, or when users explicitly request code quality improvements, simplification, or cleanup guidance.
git clone --depth 1 https://github.com/techygarg/lattice /tmp/clean-code && cp -r /tmp/clean-code/skills/atoms/clean-code ~/.claude/skills/clean-codeSKILL.md
# Clean Code ## Config Resolution Skill support project custom. Order: 1. Look `.lattice/config.yaml` in repo root 2. If found, check `paths.clean_code` for custom doc path 3. If custom path exist, read doc and check YAML frontmatter for `mode`: - **`mode: override`** (or no mode): Custom doc full precedence. Use instead embedded default. Must be comprehensive -- sole reference. - **`mode: overlay`**: Read embedded `./references/defaults.md` first, then apply custom doc sections on top. Custom sections replace matching sections in default (matched by heading). New sections appended after default. 4. If no config/path/file, read `./references/defaults.md` 5. **Language adaptation**: If `paths.language_idioms` exist in config, read that document and adapt defaults using these sections: - **"Error Handling"** → adapt §8 (Error Handling) patterns to language idioms. Language idioms take precedence over pseudocode defaults. - **"Type System & Object Model"** → adapt §1 (Single Responsibility) cohesion guidance to language constructs (e.g., struct vs class). - **"Naming Conventions"** → adapt §4 (Meaningful Naming) patterns to language conventions. - **"Parameter & Function Design"** → adapt §2 (Small, Focused Functions) and §5 (Parameter Design) to language capabilities. - **"Dependency Management"** → adapt §9 (Test-Friendly Code) DI patterns to language idioms. Default ship with skill. Opinionated best practice. Work out of box. Override only when team have different standard. ## Self-Validation Checklist STOP after generate each component. Verify ALL before proceed. If check clearly fail, fix before present. If judgment call with multiple valid approach (see Ambiguity Signals), flag it — present options and reasoning. 1. **SINGLE RESPONSIBILITY**: Describe each function without "and"? If not → extract separate function. 2. **SIZE**: Each function under size threshold per loaded doc (~20 lines default)? If not → extract sub-operation into named function. 3. **COMPLEXITY**: Cyclomatic complexity under threshold per loaded doc (~10 default)? If not → flatten with guard clause, extract branch. 4. **ABSTRACTION LEVEL**: Each function operate at one level? If high-level mixed with low-level → extract detail. 5. **NAMING**: Function/variable name reveal intent without context? If not → rename self-documenting. 6. **PARAMETERS**: Parameter count under threshold per loaded doc (4 default)? If not → group into object. 7. **PRIMITIVE OBSESSION**: String/number/boolean clearer as named type? If so → introduce parameter object or typed wrapper. 8. **ERROR HANDLING**: Every fail-able operation have explicit handling with actionable message? Handled at right level? **Project-specific checks:** If loaded doc (from Config Resolution) contains a Validation Checklist section (§10), apply those checks as additional project-specific validation after the checklist above. ## Active Anti-Pattern Scan After checklist, scan for these. If find, fix before present. - [ ] **God Function**: Function exceed ~30 lines doing multiple thing; description need "and" → extract focused function - [ ] **Deep Nesting**: Three+ level indentation → flatten with early return/guard clause - [ ] **Cryptic Naming**: Variable like `d`, `tmp2`, `processData` → rename reveal intent - [ ] **Long Parameter Lists**: Five+ parameter → group into object or split function - [ ] **Premature Abstraction**: Utility extracted from only two similar block → inline until Rule of Three with same reason to change - [ ] **Swallowed Errors**: Empty catch, generic "something went wrong," silently return null → handle explicitly - [ ] **Comments as Deodorant**: Comment explain convoluted code instead refactor → rename self-documenting; keep only "why" comment, remove "what" - [ ] **Hidden Side Effects**: Function named `getX` also write cache/send notification → rename or separate - [ ] **Dead Code**: Commented-out block, unused import, unreachable branch → delete (version control preserve) - [ ] **Untestable Logic**: Side effect tangled with business logic; unit test need mock I/O → push side effect to boundary, extract pure function, inject dependency ## Ambiguity Signals Multiple valid outcome. Present option rather than silently choose. See `./references/defaults.md` for resolution guidance on each signal below. - **Single Responsibility**: Two tightly-coupled sequential operation may be one responsibility (pipeline), not two. "And" test catch true violation AND false positive. - **Function Size**: Near-threshold (20-30 lines) with one clear purpose -- extract may create five unclear smaller function. Present tradeoff. - **DRY vs Premature Abstraction**: Two identical block may serve different purpose and diverge. Until third instance with same reason to change, genuinely ambiguous. - **Error Handling Strategy**: Exception vs Result type vs error code depend on language idiom and team convention, not universal. ## Core Principle Clean code about **craft writing individual unit** -- function, class, module. Distinct from architecture (govern where code live) and domain modeling (govern business rule). Apply during code generation, not post-generation review. See `./references/defaults.md` for SRP pipeline nuance, size vs clarity thresholds, magic number extraction rules, boolean parameter patterns, DRY vs wrong abstraction heuristics, and error message guidelines.
Audit and fix all Lattice documentation, README, docs/, GitHub issue templates, and CLAUDE.md to ensure they are fully aligned with the current skill inventory. Documentation drift is the most common source of user confusion in Lattice — a skill exists in the codebase but not in the docs, or a renamed skill leaves a stale reference in the bug report template. If you've made any change to skills/ and haven't run this, run it now. Use when the user says 'align docs', 'audit docs', 'update documentation', 'skill align', 'check docs are in sync', 'audit skill inventory', 'ensure docs are aligned', 'are the docs up to date', or 'what needs updating'. Standalone — does not call other skills.
Create a new Lattice skill — atom, molecule, or refiner — following all framework conventions. Writing skill files manually almost always produces convention violations: wrong section order, missing confirmation gates, defaults.md without the right structure. This skill knows all of that and guides you through it. Use whenever adding any new atom, molecule, or refiner to Lattice, or when the user says 'create a new skill', 'add an atom', 'add a molecule', 'add a refiner', 'build X for Lattice', 'new lattice skill', or 'skill forge'. Does not validate, align docs, or deploy — those are separate skills you run after.
Deep behavioral audit of a Lattice skill — proposes 3 review personas relevant to the skill, runs independent scenario analysis from each persona's perspective, then merges only the high-confidence, practical findings into a severity-ordered gap report with proposed fixes. Structural validation (conventions, cross-references) is skill-validate's job — this skill finds gaps that would realistically surface when someone actually uses the skill: missing scenario handling, ambiguous instructions, silent failure cases, and behavioral inconsistencies. Filters out theoretical edge cases, low-likelihood speculation, and findings owned by other skills. Use after writing or significantly changing any skill, or when the user says 'review this skill', 'deep review', 'does this skill work', 'find gaps in this skill', 'stress test this skill', 'review from different angles', or 'skill review'. Standalone — does not call other skills.
Validate any Lattice SKILL.md against all tier conventions — atoms, molecules, and refiners. Catches structural errors, broken cross-references, and convention violations before they reach the repo. If you just wrote or modified a Lattice skill file and haven't run this yet, run it now — manual review consistently misses the same categories of errors this skill is specifically designed to catch. Use when the user says 'validate this skill', 'check this skill', 'does this follow conventions', 'review this skill file', 'check my SKILL.md', or 'skill validate'. Reports PASS/FAIL with specific file-and-section findings and actionable fixes. Standalone — does not call other skills.
Architectural thinking partner for an existing repository — scans the codebase, conducts a structured interview, agrees on current architectural state and recommended direction, and produces a shareable insights document. Scoped to one repository, module, or folder. Does not execute transformation — it orients. Use when the user says 'assess my codebase architecture', 'what direction should my codebase go', 'architecture compass', 'understand my architecture', 'audit architecture drift', 'architectural assessment', or 'help me understand what is wrong with my codebase'.
Facilitate a structured conversation to define architecture principles for a repository. Supports multiple architecture styles: clean architecture (default), hexagonal / ports & adapters, modular monolith, or custom. Produces a formal architecture document that the corresponding atom will use. Use when setting up a new project, defining architecture standards, or when the user says 'setup architecture', 'define layers', 'architecture principles', 'help me define my architecture', 'hexagonal architecture', 'modular monolith', 'ports and adapters', or 'define my architecture style'.
Enforce architectural rules when generating or modifying code. Defaults to clean architecture; supports any architecture style via the architecture-refiner. Validates layer responsibilities, dependency direction, and structural constraints using the loaded architecture rules. Use when generating code, reviewing architecture, creating new files, or when the user mentions 'architecture', 'layers', 'structure', 'dependency rules', 'hexagonal architecture', 'ports and adapters', 'modular monolith', or 'onion architecture'. Also use when reviewing generated code for structural compliance.
Investigate, reproduce, and safely fix a bug with regression protection. Composes context, diagnosis, architecture, code quality, and testing guardrails into a reproduce-first repair workflow. Use when the user says 'fix this bug', 'debug this', 'investigate this failure', 'patch this regression', 'repair this issue', or 'why is this broken'.