---
name: simplify
effort: medium
description: Review changed code for reuse, quality, and efficiency, then fix any issues found. Use when completing a coding task, after implementation, or when the user says /simplify. Covers deduplication (exact/near/inline), code quality patterns, and performance.
---

# Simplify: Code Review, Deduplication, and Cleanup

## Project Context

**Reads from `baldart.config.yml`:** `paths.references_dir`, `paths.components_primitives`, `paths.components_root`, `paths.design_system`, `features.has_toolchain` + `toolchain.commands.{lint,typecheck,test}` (the Step 5 verify gates run those verbatim when the flag is on — see Step 5).
**Gated by features:** `features.has_design_system` (Design System check section is BLOCKING when `true`).
**Overlay:** loads `.baldart/overlays/simplify.md` if present — project-specific utility module paths, hook conventions.
**On missing/empty keys:** ask the user; do not assume defaults. See `framework/agents/project-context.md` § 3.

## Effort

**Baseline:** `effort: medium` (frontmatter). **Inline override:** pass
`effort=<low|medium|high|xhigh|max>` anywhere in the invocation to scale
reasoning depth for this run — detect it once at kickoff and strip the token
before consuming user input. Level→behavior mapping, parsing contract, and
precedence caveats: `framework/agents/effort-protocol.md`.


---

You are a ruthless deduplication and cleanup agent. You do not suggest. You find issues and you eliminate them.

## Step 1: Identify What Changed

Run `git diff HEAD` and `git status` to get the full picture of what was added or modified. Parse the diff to extract:

- New functions, components, hooks, constants, types, and utilities
- New inline logic patterns (string manipulation, fetch calls, validation, type guards, env checks, path handling)
- New API route handlers and middleware

If the diff is empty (everything is committed), run `git diff HEAD~5..HEAD` to cover recent session commits.

If there are no git changes at all, review the most recently modified files that the user mentioned or that you edited earlier in this conversation.

## Step 2: Launch Three Review Agents in Parallel

Use the Agent tool to launch all three agents concurrently in a single message. Pass each agent the full diff so it has the complete context.

### Agent 1: Duplication & Reuse Review

For each new piece of code in the diff:

1. **Start with `${paths.references_dir}/component-registry.md`** — the authoritative inventory of all UI primitives, shared components, hooks, and utility modules. Scan the relevant tables before grepping. Then search for existing utilities and helpers that could replace newly written code in the project's utility roots (e.g. `${paths.components_root}/shared/`, `${paths.components_primitives}/`, and `src/lib/`, `src/hooks/` if they exist), and files adjacent to the changed ones.
2. **For each new component**, Grep the codebase for components with similar names, similar prop signatures, or similar JSX structure. Check for copy-pasted layout components (`layout.tsx` files with near-identical structure).
3. **For each new function/hook**, search for functions with similar signatures or logic patterns elsewhere. Check for duplicated page-level patterns (similar data fetching, similar error boundaries, similar loading states).
   When `features.has_lsp_layer: true`, run LSP `find-references` on each new exported
   symbol before grepping — it tells you exactly which callsites would need to migrate
   if you replaced the new code with an existing utility (textual grep over identifier
   names overcounts because of collisions). See `framework/agents/code-search-protocol.md`.
   Also use LSP `find-references` on candidate "existing" utilities to confirm they're
   really in use and not abandoned dead code before recommending them as the canonical version.
   When `features.has_code_graph: true`, `graphify affected "<symbol>"` gives the same
   reverse-impact set from the graph (and `graphify-out/GRAPH_REPORT.md` surfaces
   duplicated god-node clusters) — see `framework/agents/code-graph-protocol.md`.
4. **Flag components that wrap the same underlying element** with minor style/prop differences.

Classify each finding as:

- **Exact duplicate** — same logic exists elsewhere. Use the existing one. Delete the new one.
- **Near duplicate** — similar logic with minor differences. Extract a shared version with parameters.
- **Inline reimplementation** — hand-rolled logic that an existing utility already handles. Replace with the utility call.

### Agent 2: Code Quality Review

Review the same changes for hacky patterns:

1. **Redundant state**: state that duplicates existing state, cached values that could be derived, observers/effects that could be direct calls
2. **Parameter sprawl**: adding new parameters to a function instead of generalizing or restructuring existing ones
3. **Copy-paste with slight variation**: near-duplicate code blocks that should be unified with a shared abstraction
4. **Leaky abstractions**: exposing internal details that should be encapsulated, or breaking existing abstraction boundaries
5. **Stringly-typed code**: using raw strings where constants, enums (string unions), or branded types already exist in the codebase
6. **Unnecessary JSX nesting**: wrapper Boxes/elements that add no layout value — check if inner component props (flexShrink, alignItems, etc.) already provide the needed behavior
7. **Unnecessary comments**: comments explaining WHAT the code does (well-named identifiers already do that), narrating the change, or referencing the task/caller — delete; keep only non-obvious WHY (hidden constraints, subtle invariants, workarounds)

#### Agent 2 — Design System SSOT Compliance sub-checklist (MANDATORY for UI refactors)

This is part of Agent 2's single task (NOT a separate fourth parallel agent — the three agents in
Step 2 are Agents 1, 2, 3). When the diff includes files under `${paths.components_root}/`,
`${paths.components_root}/**/*.tsx`, or any `.css`/`.module.css`, the simplify pass MUST NOT introduce
hardcoded design values while refactoring. Agent 2 runs this as part of its quality review:

1. Read `${paths.design_system}/INDEX.md` (component index + Canonical Authority Matrix + Quick
   rules MUST) before rewriting any component.
2. For each component in the diff, confirm against `${paths.design_system}/components/<Name>.md`
   that variants/states/props remain honored after the refactor.
3. Replace hardcoded hex / shadow / border values with canonical tokens from the DS SSOT.
   These are Quality issues to fix inline, not advisory.
4. Themed surfaces must preserve the token-pair contract documented in the
   project's design-system patterns (e.g. `${paths.design_system}/patterns/<theme>.md`).
   Never introduce hardcoded text colors on themed backgrounds.
5. Motion-related simplifications must honor `${paths.design_system}/patterns/animations.md`,
   including reduced-motion fallbacks.

### Agent 3: Efficiency Review

Review the same changes for efficiency:

1. **Unnecessary work**: redundant computations, repeated file reads, duplicate network/API calls, N+1 patterns
2. **Missed concurrency**: independent operations run sequentially when they could run in parallel
3. **Hot-path bloat**: new blocking work added to startup or per-request/per-render hot paths
4. **Recurring no-op updates**: state/store updates inside polling loops, intervals, or event handlers that fire unconditionally — add a change-detection guard so downstream consumers aren't notified when nothing changed. Also: if a wrapper function takes an updater/reducer callback, verify it honors same-reference returns (or whatever the "no change" signal is) — otherwise callers' early-return no-ops are silently defeated
5. **Unnecessary existence checks**: pre-checking file/resource existence before operating (TOCTOU anti-pattern) — operate directly and handle the error
6. **Memory**: unbounded data structures, missing cleanup, event listener leaks
7. **Overly broad operations**: reading entire files when only a portion is needed, loading all items when filtering for one

## Step 3: Aggregate Findings

Collect results from all three agents. For each finding, categorize as:

1. **Exact duplicate** — same logic exists elsewhere. Use the existing one. Delete the new one.
2. **Near duplicate** — similar logic with minor differences. Extract a shared version with parameters.
3. **Inline reimplementation** — hand-rolled logic that an existing utility already handles. Replace with the utility call.
4. **Quality issue** — hacky pattern from Agent 2. Fix directly.
5. **Efficiency issue** — performance problem from Agent 3. Fix directly.

If no issues are found, say so and stop. Do not invent problems.

## Step 4: Fix Issues

For each finding, apply the fix directly:

- **Exact duplicates**: Delete the new code, import the existing version, update all references.
- **Near duplicates**: Extract a shared function/component/hook to the project's shared directory resolved from `baldart.config.yml` (see "When extracting shared code" below). Update all call sites to use the shared version.
- **Inline reimplementations**: Replace inline code with calls to the existing utility. Add imports.
- **Quality issues**: Apply the fix inline (remove redundant state, simplify JSX nesting, replace string literals with constants, etc.).
- **Efficiency issues**: Apply the fix inline (parallelize independent calls, add change-detection guards, batch reads, etc.).

When extracting shared code, write to the SAME `${paths.*}` keys the review phase (Step 2) reads from `baldart.config.yml` — never hardcode a fallback that bypasses config. A consumer whose utilities live under `packages/shared/utils/` must get the extracted file there, not in a baked-in `src/lib/`:
- Place shared components under `${paths.components_root}/shared/` (or `${paths.components_primitives}/` for a primitive).
- Place utilities and hooks under the project's utility/hook roots as declared in the project overlay (`.baldart/overlays/simplify.md` lists `paths.lib_dir` / `paths.hooks_dir` or the project's equivalents).
- If the relevant key is missing or empty, ASK the user where the shared code should live — do not assume `src/lib/` / `src/hooks/` / `src/components/shared/`. See `framework/agents/project-context.md` § 3.
- Do not create new directories if equivalent ones already exist.

## Step 5: Verify

These static checks run AFTER Step 4 has mutated code — a pre-fix pass would not cover the post-fix
code, so re-running them here is mandatory whenever Step 4 changed anything.

> **Toolchain:** when `features.has_toolchain: true` in `baldart.config.yml`, run the command from
> `toolchain.commands.{lint,typecheck,test}` **verbatim** instead of the default shown below — per
> `framework/agents/toolchain-protocol.md`. Per gate: a non-empty config command wins; empty/absent
> (or the flag off) falls back to the default. A configured command that exits non-zero is a real
> FAIL (do not fall back to the default).

Run the linter (use the project's lint command):

```
npm run lint
```

Run the type checker as its own blocking step ONLY when `stack.language` includes `typescript`
(skip otherwise — `tsc` is meaningless on a non-TS project):

```
npx tsc --noEmit
```

Run the project's test suite (if tests exist):

```
npm test
```

If tests, lint, or (where applicable) tsc fail, fix the issues. The codebase must be in a passing state when you're done.

When done, briefly summarize what was fixed (or confirm the code was already clean).
