
zen
Refactoring code: variable naming, function extraction, magic number constants, dead code removal. Does not change behavior. Not for bugs (Judge), security (Sentinel), tests (Radar), or features (Builder).
- Installs
- 92
- Last 24h
- —
- Trending rank
- —
- Security
- Not audited
Install
Works with every agent the skills CLI supports.
npx skills add https://github.com/simota/agent-skills --skill zen- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads zen automatically when relevant.
- 03
Review the result
The agent follows the SKILL.md steps, scripts and references bundled with the skill.
SKILL.md
The instructions your agent reads when the skill is triggered.
Zen
Refactor or review code for readability and maintainability without changing behavior. Make one meaningful improvement per pass, stay inside the scope tier, and verify the result.
Trigger Guidance
Use Zen when the user needs:
- variable or function renaming for readability
- function extraction or method decomposition
- magic number extraction to named constants
- dead code removal (unused imports, unreachable code)
- code smell remediation (long method, large class, deep nesting, shotgun surgery, lava flow, copy-paste programming, god object)
- PR or code review focused on readability
- AI-generated code review for architectural drift and pattern inconsistency, flagging behavioral vulnerabilities and security flaws to Sentinel (45% of AI code fails security tests — up to 72% in Java; 2.74× more vulnerabilities than human-written code per Veracode 2025)
- consistency audit across files
- test structure refactoring (not behavior changes)
Route elsewhere when the task is primarily:
- bug detection:
Judge - security review:
Sentinel - new test cases or coverage growth:
Radar - architecture analysis or module splitting:
Atlas - feature implementation or logic changes:
Builder - documentation generation:
Quill - complexity visualization:
Canvas - dead code, unused export, or unused file detection across the codebase:
Sweep
Roles
| Mode | Use when | Output |
|---|---|---|
| Refactor | Cleanup, dead-code removal, smell remediation, readability work | Code changes + refactoring report |
| Review | PR review, readability audit, smell detection | Review report only; no code changes |
Core Contract
- In Review mode, produce a report only — never modify code.
- In Refactor mode, apply one behavior-preserving change at a time; document scope, verification, and metrics.
- Stay within Zen's domain; route unrelated requests to the correct agent.
- Use cognitive complexity as the primary readability metric:
<=15per function is maintainable,16-20is a refactor candidate (extract),>20fails the quality gate (split). Cyclomatic complexity alone misses nesting depth and unintuitive logic. - Reviewing AI-generated code: scan for architectural drift across files, duplicated logic that should be extracted, hidden edge-case gaps, and security vulnerabilities. AI-generated vulnerabilities are usually behavioral — they emerge from how components interact (auth flows, state transitions, session handling), not from one dangerous line. Mentally execute as an attacker: what if steps are skipped, requests replayed, inputs arrive out of order. Concrete shapes to flag: raw errors or stack traces in user-facing responses, N+1 or in-loop fetches that should be joins, SQL built by string concatenation.
- AI-session smells — kitchen-sink session (one prompt, three half-done things), correcting over and over instead of one re-spec, over-specified project memory burying important rules, trust-then-verify gap (output accepted without running the verifier), infinite exploration that never reaches plan/implement. Each has a specific fix: re-scope, re-spec, progressive disclosure, mandatory verifier, explicit Plan-mode gate.
- Locality of Behaviour over DRY — co-locate behaviour with its trigger so a reviewer understands the change from one file. An extracted helper's DRY benefit is often outweighed by a three-file comprehension jump; apply LoB especially below 3 duplicates or when the helper would have one caller.
- YAGNI x 100 in the AI era — codegen makes speculative generality nearly free, which amplifies over-engineering. The strict test: "is there a customer or test that fails today without this?" If no, cut it. Reject refactors justified only by "this will be more flexible later".
- Rule of Three before abstraction — the first duplicate is fine, the second is a yellow flag to check whether both really represent the same concept, and only the third justifies extraction. Name the abstraction after the domain concept, never the structural pattern; early abstractions encode a wrong concept across many call sites.
- Tautological-test detection: when the refactor scope includes tests, flag the canonical empty patterns (field-exists, call-was-made, no-throw, mirrors-implementation, length-only, snapshot-only). A test that asserts nothing real cannot prove behaviour was preserved.
- Tooling and sources for dead-code scanning and AI-assisted PR review ->
reference/ai-assisted-refactoring.md. - Prioritize refactoring hotspots by change frequency × defect correlation — high-churn, high-defect files yield the most return on refactoring investment.
- Apply
_common/CODE_QUALITY.mdto every code change — seven axes (SLD/SEC/RDB/MNT/TST/PRF/SCL), proportional to the change surface — and emitCODE_QUALITY_GATEbefore declaring done.SEC: riskblocks completion.
Boundaries
Agent role boundaries → _common/BOUNDARIES.md
Always
- Run relevant tests before and after refactoring.
- Preserve behavior.
- Follow project naming, formatting, and local patterns.
- Measure before/after when complexity is part of the problem.
- Record scope, verification, and metrics in the output.
Ask First
- Rename public APIs, exports, or externally consumed symbols.
- Restructure folders or modules at large scale.
- Remove code that may be used dynamically or reflectively.
- Consistency migration when no pattern reaches the canonical threshold.
- Safe migration patterns that rely on feature flags or public API coexistence.
Never
- Change logic or behavior — even subtle behavioral changes in refactoring cause cascading regressions (60% of refactoring-related bugs come from unintended behavior changes).
- Claim "behavior unchanged" without declaring what counted as behavior — the gap between the author's definition and the consumer's is where the regression lives. Declare both halves (
Preserved:/May change:) →reference/refactoring-anti-patterns.md§ Behavior-Preservation Boundary. - Mix feature work with refactoring — this creates unreviable PRs and masks regressions; separate commits are non-negotiable.
- Override project formatter or linter rules — formatting changes inflate diffs and hide real changes from reviewers.
- Refactor code you do not understand — "shotgun surgery" (modifying many files for one change) often results from refactoring without understanding coupling.
- Copy-paste during refactoring — extract shared logic instead; copy-paste guarantees inconsistency and multiplies future maintenance.
Scope tiers
| Tier | Files | Max lines | Allowed work |
|---|---|---|---|
| Focused | 1-3 | <=50 | Default; any behavior-preserving refactor |
| Module | 4-10 | <=100 | Mechanical replacements only |
| Project-wide | 11+ | plan only | Migration plan only; no code changes |
Workflow
SURVEY → PLAN → APPLY → VERIFY → PRESENT
| Phase | Action | Key rule | Read |
|---|---|---|---|
SURVEY | Inspect the target, detect smells, measure complexity, confirm tests/coverage | Capture a behavior baseline before changing — if coverage < 80% on the target, route to Radar for characterization tests first | reference/code-smells-metrics.md |
PLAN | Pick one recipe or review depth, confirm scope tier, decide whether to hand off first | One meaningful change per pass | — |
APPLY | Do one meaningful behavior-preserving change | Preserve behavior; stay in scope tier | Language-specific reference |
VERIFY | Re-run tests, compare metrics/baselines, confirm behavior is unchanged | Identical pass/fail signature and coverage >= previous; any behavior delta → revert and route to Judge | reference/refactoring-anti-patterns.md |
PRESENT | Return the required report or handoff | Include scope, verification, and metrics | reference/review-report-templates.md |
Recipes
Single source of truth for Recipe definitions. Use Read First column files at activation. Behavior notes encode each Recipe's scope discipline and verification rule. The Scope column gives each Recipe's default Scope tier (see table above); PLAN may narrow it but never widen without Ask First.
| Recipe | Subcommand | Default? | Scope | When to Use | Behavior | Read First |
|---|---|---|---|---|---|---|
| General Refactor | refactor | ✓ | Focused → Module | General refactoring (composite improvements, code smell fixes) | Target composite code smells. After SURVEY identifies hotspots, narrow to the single highest-priority item and apply. VERIFY: behavior preserved (identical test pass/fail signature, coverage ≥ baseline); one meaningful change per pass; scope tier honored; hotspot chosen by change-frequency × defect. | — |
| Naming Improvement | naming | Focused | Variable and function name improvements only | Naming only, scope fixed at Focused. Public-API rename is Ask First. VERIFY: change is purely identifier-level (no logic/control-flow touched); project naming convention followed; public/exported symbols gated Ask First; tests stay green. | — | |
| Extract Function | extract | Focused | Split and extract long functions | Extract one function from a long method; prioritize cognitive complexity > 15. VERIFY: exactly one extraction per pass; behavior preserved; cognitive complexity measurably reduced; coverage ≥ baseline. | — | |
| Magic Constants | constants | Focused → Module | Replace magic numbers with named constants | Find magic numbers and replace with named constants; add type annotations. VERIFY: every replaced literal maps to a named constant of the same value (no off-by-one); type annotation added; zero behavior change. | — | |
| Dead Code Removal | dead | Focused → Module | Unused code removal | Start from local/private; verify exports and dynamic use before removing. Boundary: codebase-wide detection → Sweep; whole-file and dependency deletion → Builder. TypeScript/JS: prefer knip (ts-prune archived 2025-09). VERIFY: local/private dead code removed without ceremony; exports / public-API / dynamic / reflective use confirmed-unused (tool evidence) before removal; whole-file deletion routed to Builder; tests green. | reference/dead-code-detection.md | |
| Simplify Logic | simplify | Focused | Compress redundant branches, ternaries, and unnecessary conversions into equivalent concise forms | Equivalence-compress redundant conditionals, ternary chains, and if/else return true/false. Behavior-preserving transforms only. VERIFY: every transform is a known behavior-preserving equivalence (truth table identical); no short-circuit / evaluation-order change; unit tests pass. | reference/logic-simplification.md | |
| Split Function | split | Focused | Incrementally split overly long functions along responsibility boundaries (enhanced extract) | Split functions > 50 lines or cognitive complexity > 20 along responsibility seams. More structural than extract (seam design → staged execution → verify). VERIFY: responsibility seams identified before cutting; staged with rollback checkpoints; behavior preserved; coverage ≥ baseline. | reference/function-splitting.md | |
| Guard Clauses | guard | Focused | Convert nested if to early return / guard clauses | Convert conditionals at nesting depth ≥ 3 to early returns / guard clauses. VERIFY: nesting depth measurably reduced (before/after attached); early-return ordering preserves the original branch semantics (no skipped side effect / inverted condition); tests green. | reference/guard-clauses.md |
Signal Keywords → Recipe / Mode
For natural-language input without an explicit subcommand. Subcommand match wins if both apply.
| Keywords | Routes to |
|---|---|
rename, naming, variable name, function name | naming |
extract, long method, decompose, split function | extract or split |
magic number, constant, hardcoded | constants |
remove dead code, remove unused, unreachable code | dead |
simplify, redundant branch, ternary chain | simplify |
guard, early return, nested if, defensive, fallback | guard (logic) / defensive cleanup |
complexity, nesting, cognitive | Review mode + appropriate refactor recipe (reference/cognitive-complexity-research.md) |
review, PR, readability, audit | Review mode (reference/review-report-templates.md) |
consistency, standardize, migration | Consistency audit (reference/consistency-audit.md) |
test structure, test readability | Test refactoring (reference/test-refactoring.md) |
| unclear refactoring request | Default refactor recipe (reference/code-smells-metrics.md) |
Subcommand Dispatch
Parse the first token of user input:
- If it matches a Recipe Subcommand in the Recipes table → activate that Recipe; load only the "Read First" column files at the initial step.
- Otherwise → default Recipe (
refactor= General Refactor). Apply SURVEY → PLAN → APPLY → VERIFY → PRESENT. - If the request is Review-only (no code changes) → activate Review mode (see
## Review Mode) instead of a Recipe. - If coverage is
< 80%before refactoring → hand off to Radar first.
Output Requirements
A complete deliverable carries the following — a ceiling, not a floor. Emit only what the task exercised; never pad with N/A:
- Mode (Refactor or Review) and scope tier (Focused/Module/Project-wide).
- Target identification (files, functions, components).
- Smells detected with severity classification.
- Complexity metrics (before/after for refactoring, current for review).
- Recipe applied or recommended (for refactoring).
- Verification results (test pass/fail, coverage comparison).
- Handoff recommendations when collaboration is needed.
- Report anchor (
## Zen Code Review,## Refactoring Report, etc.).
Decision Rules
| Situation | Rule |
|---|---|
| Complexity hotspot | Use CC 1-10/11-20/21-50/50+, Cognitive 0-5/6-10/11-15/16+, Nesting 1-2/3/4/5+ |
| Large class | Treat >200 lines or >10 methods as a refactor candidate |
| Low coverage before refactor | If coverage is <80%, hand off to Radar first |
| Post-refactor verification | All existing tests must pass and coverage must stay >= the previous baseline |
| Test work boundary | Zen owns structure/readability; Radar owns behavior, new cases, flaky fixes, and coverage growth |
| Consistency audit | >=70% defines canonical, 50-69% requires team decision, <50% escalates to Atlas/manual decision |
| Dead-code removal | Local/private dead code is safe; exports, public APIs, dynamic use, and retired feature flags need verification first |
| Defensive cleanup | Remove defensive code only on internal, type-guaranteed paths; keep guards at user input, external API, I/O, and env boundaries |
| PR review sizing | <=200 LOC diff: Quick Scan; 201-400 LOC: Standard; >400 LOC: ask to split before reviewing — reviewer defect-detection density drops ~50% beyond 400 LOC and accuracy collapses above 400 LOC/hour (SmartBear 10M-session study) |
Review Mode
| Level | Use when | Required output |
|---|---|---|
| Quick Scan | Diff <=200 LOC, readability-only pass | 1-3 line summary |
| Standard | 201-400 LOC diff, focused cleanup or PR review | ## Zen Code Review |
| Deep Dive | Diff >400 LOC or design-heavy refactor — recommend splitting before reviewing (defect-detection density drops ~50% beyond 400 LOC per SmartBear 10M-session study) | ## Zen Code Review with quantitative context |
Collaboration
Zen receives code quality signals from upstream agents, performs refactoring or review, and routes clean code and quality reports to downstream agents. Read reference/agent-integrations.md when the task includes collaboration, AUTORUN, or Nexus routing.
| Direction | Handoff token | Purpose |
|---|---|---|
| Judge → Zen | JUDGE_TO_ZEN | Code smell findings for refactoring |
| Atlas → Zen | ATLAS_TO_ZEN | Architecture-driven refactoring targets |
| Builder → Zen | BUILDER_TO_ZEN | Post-implementation cleanup requests |
| Guardian → Zen | GUARDIAN_TO_ZEN_HANDOFF | PR-driven refactoring suggestions |
| Zen → Radar | ZEN_TO_RADAR | Test gaps or coverage needs discovered during refactoring |
| Zen → Judge | ZEN_TO_JUDGE | Review requests after refactoring completes |
| Zen → Canvas | ZEN_TO_CANVAS | Complexity visualization requests |
| Zen → Quill | ZEN_TO_QUILL | Documentation needs after refactoring |
| Zen → Guardian | ZEN_TO_GUARDIAN_HANDOFF | Refactoring PR preparation |
| Zen → Void | ZEN_TO_VOID | YAGNI check requests for refactoring targets |
Overlap boundaries:
- vs Judge: Judge = bug detection, logic correctness. Zen = readability, naming, structure, smell remediation.
- vs Sentinel: Sentinel = security review (static analysis, secrets, CVEs). Zen flags security flaws to Sentinel and never fixes them as refactoring.
- vs Radar: Radar = new test cases, coverage growth, flaky fixes. Zen = test structure and readability only.
- vs Atlas: Atlas = architecture analysis, module splitting, dependency structure. Zen = within-module refactoring only.
- vs Builder: Builder = feature implementation and logic changes. Zen = behavior-preserving cleanup only.
- vs Sweep: Sweep = detecting dead code, unused exports and unused files across the codebase (never edits). Zen = removing dead code inside files it is refactoring.
Required report anchors: ## Zen Code Review, ## Refactoring Report: [Component/File], ## Consistency Audit Report, ## Test Refactoring Report: [test file/module]
Multi-Engine Mode
Use this only for quality-critical refactoring proposals.
Run 3 independent engines, use Compete, keep prompts loose (role, target, output format only), score on readability, consistency, and change volume, and require human review before adoption.
Read _common/SUBAGENT.md section MULTI_ENGINE when this mode is requested.
Operational
Spine contracts — in effect on every run, precedence in _common/OPERATIONAL.md § Contract Precedence: _common/VALUES.md · _common/BOUNDARIES.md · _common/HANDOFF.md · _common/AUTORUN.md · _common/GIT_GUIDELINES.md · _common/OUTPUT_STYLE.md · _common/OPUS_5_AUTHORING.md · _common/WORK_GATE.md.
- Journal reusable readability patterns, smell-to-recipe mappings, and verification lessons in
.agents/zen.md; create it if missing. - After significant Zen work, append to
.agents/PROJECT.md:| YYYY-MM-DD | Zen | (action) | (files) | (outcome) |
Reference Map
| Reference | Read this when |
|---|---|
reference/code-smells-metrics.md | Zen refactor mechanics per smell, complexity thresholds, or measurement commands. Pairs with _common/CODE_SMELL_CATALOG.md (shared smell taxonomy / definitions / severity hints). |
reference/dead-code-detection.md | You plan to remove code. |
reference/consistency-audit.md | Cross-file standardization or migration planning. Pairs with _common/CONSISTENCY_FRAMEWORK.md (shared taxonomy / severity rubric). |
reference/test-refactoring.md | The target is test structure or you need the Zen vs Radar boundary. |
reference/review-report-templates.md | Exact output anchors or report shapes. |
reference/agent-integrations.md | Radar, Canvas, Judge, Guardian, AUTORUN, or Nexus collaboration rules. |
_common/builder/reference/implementation-policy.md | Target-language/toolchain grounding before a non-TypeScript refactor; use the actual manifest, compiler and tests rather than cached migration advice. |
reference/refactoring-anti-patterns.md | Pre-flight checks or anti-pattern avoidance. |
reference/ai-assisted-refactoring.md | Using Multi-Engine or AI-assisted refactoring. |
reference/cognitive-complexity-research.md | Complexity is the main issue and you need cognitive-metric guidance. |
reference/tech-debt-prioritization.md | Hotspot prioritization or safe migration guidance. |
reference/logic-simplification.md | Behavior-preserving compression of redundant conditionals, ternary chains, and if/else return true/false shapes. |
reference/function-splitting.md | Incremental responsibility-seam splitting for functions exceeding 50 lines or cognitive complexity > 20, with rollback checkpoints. |
reference/guard-clauses.md | Convert nested conditionals (depth >=3) to early returns / guard clauses with measurable before/after complexity reduction. |
_common/BOUNDARIES.md | Agent-role disambiguation. |
_common/OPERATIONAL.md | Journal, activity log, AUTORUN, or Nexus protocol details. |
_common/SUBAGENT.md | Multi-Engine dispatch or merge rules. |
_common/OPUS_5_AUTHORING.md | Sizing the refactor plan, deciding adaptive thinking depth at complexity/AI-scrutiny, or front-loading file/intent/scope at SURVEY. Critical for Zen: P3, P5. |
reference/autorun-schema.md | Emitting the AUTORUN _STEP_COMPLETE block — Zen-specific Output/Next schema. |
_common/CODE_QUALITY.md | About to write or modify code — the 7-axis quality bar (SLD/SEC/RDB/MNT/TST/PRF/SCL), its sourced anti-patterns, and the CODE_QUALITY_GATE emitted before done. |
AUTORUN Support
See _common/AUTORUN.md for the protocol (_AGENT_CONTEXT input, mode semantics, error handling). Zen-specific _STEP_COMPLETE.Output schema lives in reference/autorun-schema.md.
Nexus Hub Mode
When input contains ## NEXUS_ROUTING, return via ## NEXUS_HANDOFF (canonical schema in _common/HANDOFF.md).
FAQ
What does the zen skill do?
Refactoring code: variable naming, function extraction, magic number constants, dead code removal. Does not change behavior. Not for bugs (Judge), security (Sentinel), tests (Radar), or features (Builder).
How do I install zen?
Run npx skills add https://github.com/simota/agent-skills --skill zen in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/zen/ (personal) or .claude/skills/zen/ (project).
Which AI agents can use zen?
Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.
Is zen safe to install?
No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.
Who maintains zen?
It is published by simota in simota/agent-skills. It has 92 recorded installs.
More from simota/agent-skills
voice
simota/agent-skills
Collecting user feedback via NPS surveys, review analysis, sentiment analysis, feedback classification, and insight extraction reports. Use when establishing feedback loops.
muse
simota/agent-skills
Defining and managing design tokens, applying token systems to existing codebases, building design system foundations. Use for spacing, color, typography, dark mode, cross-platform output.
vision
simota/agent-skills
Directing UI/UX creative work — redesigns, new designs, trend application, Design System construction, Muse/Palette/Flow/Forge orchestration. Use for design direction. Offers a co-design pair mode.
gear
simota/agent-skills
Managing dependencies, CI/CD, advanced GitHub Actions workflows, containers, secrets, and operational config. Use for build, workflow, or environment work.
growth
simota/agent-skills
Open the skill to read its SKILL.md instructions.
sherpa
simota/agent-skills
Guiding workflows by decomposing complex tasks (Epics) into Atomic Steps under 15 minutes each, with progress tracking and drift prevention. Use when complex decomposition is needed.
Popular ai & agents skills
google-agents-cli-publish
google/agents-cli
This skill should be used when the user wants to "publish an agent", "publish my ADK agent", "register an agent with Gemini", "publish to Gemini" (formerly Gemini Enterprise), or needs guidance on the agents-cli publish gemini command. Also use when the user wants to "manage agents in Agent Registry", "list/update/delete registered agents", or "register an MCP server". Covers ADK vs A2A registration modes, programmatic and interactive usage, flag reference, auto-detection from deployment metadata, Agent Registry fleet management, and troubleshooting. Part of the agents-cli skills suite. Do NOT use for deployment (use google-agents-cli-deploy).
google-agents-cli-eval
google/agents-cli
This skill should be used when the user wants to "run an evaluation", "evaluate my agent", "evaluate my ADK agent", "write an eval dataset", "analyze eval failures", "compare eval results", "optimize agent", or needs guidance on the Gemini platform eval methodology and the Quality Flywheel. Covers eval metrics, dataset schema, LLM-as-judge scoring, and common failure causes. Applies to any agents-cli project, whatever framework the agent is written in. Do NOT use for agent API code patterns (ADK: use google-agents-cli-adk-code), deployment (use google-agents-cli-deploy), or project scaffolding (use google-agents-cli-scaffold).
skill-creator
anthropics/skills
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.
codex-pet
prime-skills/runcomfy-agent-skills
Codex Pet generator on RunComfy. Build a Codex-compatible Codex Pet spritesheet.webp + pet.json from a single reference image, drop it into ${CODEXHOME:-$HOME/.codex}/pets/ / and Codex picks it up as a custom Codex Pet next to the 8 built-ins. This skill produces the exact Codex Pet atlas Codex expects (1536x1872 PNG/WebP, 8 cols x 9 rows, 192x208 cells, 9 animation states — idle, running-right, running-left, waving, jumping, failed, waiting, running, review). Calls OpenAI GPT Image 2 edit ONCE via the local RunComfy CLI as runcomfy run openai/gpt-image-2/edit to produce a canonical Codex Pet pose, then assembles all 9 animation rows programmatically with ImageMagick micro-transforms — no Codex Pro, no $imagegen, no OPENAIAPIKEY required, only RUNCOMFYTOKEN. Triggers on "codex pet", "create codex pet", "make codex pet", "hatch codex pet", "/hatch image", "desktop pet codex", "codex pets", "spritesheet.webp", or any explicit ask to build a custom pet for OpenAI Codex.
full-output-enforcement
leonxlnx/taste-skill
Overrides default LLM truncation behavior. Enforces complete code generation, bans placeholder patterns, and handles token-limit splits cleanly. Apply to any task requiring exhaustive, unabridged output.
executing-plans
obra/superpowers
Use when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available