Skip to content
Agentmart
Submit a tool

flatten

Find and fix deeply nested code using extraction (pull logic into functions) and inversion (guard clauses, early returns).

Skill by nitrictech

IndexedMIT★ 1
Write a review

Chalk Labs

Need help deploying flatten?

Chalk Labs sets up agents like this inside real teams: connected to your tools, tested on your data, with a human in the loop where it matters.

Book a call

Install

Works with Claude Code, Claude apps, Codex, Cursor, Gemini CLI, GitHub Copilot, VS Code, OpenCode, Goose, Windsurf. Read the repository before you give any tool access to your data.

npx agentmarket install skill/nitrictech-flatten

Asks which of your tools to add it to (Claude Code, Codex, Cursor, VS Code, Windsurf, Gemini CLI, Claude Desktop) and shows the change first. See https://agentmart.dev/cli.

Get the weekly diff

The weekly diff: one email a week with new agent tools, notable updates and grade changes, plus security alerts for tools you follow. Double opt-in, one-click unsubscribe.

We use your email only for this newsletter. Privacy

About

Find and fix deeply nested code using extraction (pull logic into functions) and inversion (guard clauses, early returns). Targets functions exceeding 3 levels of nesting.

No reviews yet. Installed it? Reviews come from verified installers only. How reviews work

Permissions

What this skill can do and what it asks for, from its SKILL.md. Checked Oct 25, 2026.

Tools
No tools found
Secrets
None asked for
Install scripts
None found

Network hosts it talks to 1

  • codeload.github.com · found in install command

Files it touches

  • ~/.claude/skills/flatten

Tools it pre-approves 5

From allowed-tools in SKILL.md: the agent may use these without asking you each time.

  • Read,
  • Edit,
  • Grep,
  • Glob,
  • Bash

What's inside

Skill name
flatten
Description
Find and fix deeply nested code using extraction (pull logic into functions) and inversion (guard clauses, early returns). Targets functions exceeding 3 levels of nesting.
License
MIT
Allowed tools
Read,, Edit,, Grep,, Glob,, Bash
Instructions
278 lines in SKILL.md · view on GitHub

Before installing

  • Pre-approves any shell command

Files (1)

  • SKILL.md

SKILL.md (first lines)

# Flatten

When invoked, scan the specified file or directory for functions with deep nesting. Any code with a depth greater than 3 levels is excessive. Report findings with file paths and line numbers, then refactor each offending function using **extraction** and **inversion** to reduce nesting.

If the user has not specified a scope (file or directory), ask them which file or directory to focus on before proceeding.

## Core Rules

1. **Never nest more than 3 levels deep.** Count from the function body as level 1. An `if` inside the function body is level 2. A loop inside that `if` is level 3. Anything deeper must be refactored.

2. **Apply inversion first** -- it is the simpler technique. Flip conditions to put the failure or edge case first. Return, throw, or `continue` early. The happy path flows downward at the shallowest nesting depth.

3. **Apply extraction second** -- when inversion alone is not enough. Pull inner blocks (loop bodies, switch cases, deeply nested branches) into their own well-named functions. Each extracted function should have a single clear responsibility.

4. **Stack all validations at the top of a function as guard clauses.** Each guard checks one precondition and exits early if it fails. The core logic below the guards runs only when all preconditions are met.

5. **Extracted functions should be pure when possible** -- take inputs as parameters and return outputs. Avoid modifying external state. This makes the functions easier to understand and test.

6. **Add a doc comment to every extracted function.** The doc comment should be concise and describe *what* the function does and *what* it returns -- not *how* it works internally. Describe the interface, not the implementation. Use the language's standard doc format (JSDoc, pydoc, JavaDoc, `///` in Rust/C#, etc.).

7. **After refactoring, the top-level function should read like a table of contents** -- a sequence of named steps that describe what happens at a high level, with details pushed into sub-functions.

8. **Preserve existing behavior.** Do not change what the code does, only how it is structured. Run existing tests after refactoring to verify correctness.

## Procedure

1. **Find candidates.** Read the files in the user's specified scope. Identify functions where nesting exceeds 3 levels. Report each one with its file path, line number, and current max nesting depth.

2. **Assess each function.** Determine whether inversion, extraction, or both are needed:
   - If the deep nesting is caused by validation checks wrapping the main logic → **inversion** (guard clauses).
   - If the deep nesting is caused by large blocks inside loops or conditionals → **extraction** (pull into sub-functions).
   - If both → apply inversion first to flatten the outer structure, then extract remaining deep blocks.

3. **Refactor.** Apply the transformations. Name extracted functions to describe *what* they do, not *how*. Keep extracted functions in the same file/class as their caller unless they are independently reusable.

4. **Present changes.** Show the user what was changed and why, with a brief explanation for each function.

## Adapt to the User's Language

Apply these techniques using the idioms of whatever language the codebase uses. Guard clauses work in every language. Extraction means functions in procedural code, methods in OOP, or named closures in functional code.

---

## Examples

All examples below are original illustrations of the techniques. Adapt the style to match the user's actual codebase.

### Example A: Guard Clause Inversion (Simple)

A function that validates inputs and processes a payment, nested 4 levels deep:

**Before:**

```python
def process_payment(account, amount, currency):
    if account is not None:
        if amount > 0:
            if currency in SUPPORTED_CURRENCIES:
                rate = get_exchange_rate(currency)
                converted = amount * rate
                account.balance -= converted
                ledger.record(account.id, converted, currency)
                return Receipt(account.id, converted)
            else:
                raise ValueError(f"Unsupported currency: {currency}")
        else:
            raise ValueError("Amount must be positive")
    else:
        raise ValueError("Account is required")
```

The actual work (4 lines) is buried under 3 levels of validation. A reader must hold all three conditions in their head while reading the core logic.

**After:**

```python
def process_payment(account, amount, currency):
    if account is None:
        raise ValueError("Account is required")
    if amount <= 0:
        raise ValueError("Amount must be positive")
    if currency not in SUPPORTED_CURRENCIES:
        raise ValueError(f"Unsupported currency: {currency}")

    rate = get_exchange_rate(currency)
    converted = amount * rate
    account.balance -= converted
    ledger.record(account.id, converted, currency)
    return Receipt(account.id, converted)
```

Three guard clauses at the top declare the function's requirements. The core logic flows at the shallowest level. A reader can mentally discard the guards and focus on the payment logic.

---

### Example B: Loop Body Extraction

A function that processes orders inside a loop, with nested conditions for discounts and tax:

**Before:**

```typescript
function generateInvoice(orders: Order[]): Invoice {
    const lineItems: LineItem[] = [];

    for (const order of orders) {
        if (order.status === "confirmed") {
            let subtotal = 0;
            for (const item of order.items) {
                let price = item.unitPrice * item.quantity;
                if (item.category === "electronics" && item.quantity >= 10) {
                    price *= 0.9; // bulk discount
                } else if (item.category === "perishable") {
                    if (item.daysUntilExpiry < 3) {
                        price *= 0.5; // clearance
                    }
                }
                subtotal += price;
            }

From nitrictech/skills, MIT.

Signals

Stars
1
Forks
0
Open issues
0
Last commit (this folder)
May 5, 2026 (5 months ago)

From GitHub (fetched Oct 24, 2026).

Details

License
MIT
First seen
Oct 24, 2026
Last checked
Oct 24, 2026

More from nitrictech

Done for you

Rather not set it up yourself?

Chalk Labs scopes, builds and runs agents for your team: the task audit, the eval harness, the integrations and the weekly ops report. Fixed scope, priced before we start.

See how we build AI agents →Read the case studies

Chalk Labs is a two-founder AI and growth studio. We build AI agents, CRMs and MVPs for Web3 and AI companies, and have shipped 50+ product and token launches.

launches shipped
50+
launches shipped
media placements
500+
media placements
founders on every account
2
founders on every account

Press we've placed: Forbes · CoinDesk · Decrypt · Cointelegraph · The Block

Rahil Jain, Co-founder, Chalk Labs. Ex-Goldman Sachs engineer. You talk to the person who builds it.

Get flatten running in your business

Tell us what you want to automate. A founder replies within one working day with a plan, not a pitch deck.

Goes to the Chalk Labs founders, not the newsletter. Privacy

Need help deploying flatten?

CallGet help
Cite this page

flatten skill. Agent Mart. https://agentmart.dev/skills/nitrictech-flatten (last updated 2026-10-24)