Token导航 LogoToken导航TokenDH.com
前端设计操作浏览器github未标认证来源可访问许可证需确认审计通过

code-quality代码质量

Agent Skill

code-quality 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

470

周安装

19

GitHub Stars

1

下载量

147
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:code-quality(代码质量)
来源仓库:https://github.com/alexanderstephenthompson/claude-hub
仓库路径:skills/code-quality
安装命令:
npx skills add https://github.com/alexanderstephenthompson/claude-hub --skill code-quality
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/alexanderstephenthompson/claude-hub --skill code-quality

简介

code-quality 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息。

  • 适合在 Codex、Claude、Cursor、Gemini CLI 中围绕仓库状态、代码变更或协作事项进行整理时使用。
  • 安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。
  • 安装方式:通过 npx skills add 从 GitHub 仓库安装。
  • 当前顶部介绍为空,建议结合原始 README 继续核验具体用法。

SKILL.md

Code Quality Standards

Non-negotiable code quality standards. These are not preferences — they are requirements.

The Problem

AI agents produce code that works but diverges. Each session picks slightly different names, nesting patterns, and error handling approaches — not by design, but by independence. Over time this drift compounds: the codebase accumulates three ways to handle errors, four naming conventions, and scattered magic numbers that almost-but-don't-quite match. These standards collapse that divergence to zero so refactoring stays small and infrequent.

Consumption

  • Builders: Read ## Builder Checklist before writing code. Reference narrative sections when a checklist item is ambiguous.
  • Refactorers: Use ## Enforced Rules as your issue list. Read narrative sections for fix guidance.
  • Both: Narrative sections are the authoritative standard. Checklist and rules table are compressed views of the same content.

Test-Driven Development: 4-Layer Validation Framework

Layer 1 — Unit Tests (does the logic work?)

Test individual functions, calculations, state transformations, and data formatting in isolation. Pure input/output — given this input, do I get this output? Mock everything around the piece being tested. These are fast, cheap, and should be the most numerous. Covers: happy path, the specific case you're building for, and edge cases.

Layer 2 — Integration Tests (do the pieces connect?)

Test how multiple pieces work together. API calls return expected shapes, components render with correct props, database queries return the right data, hooks and state management wire up properly, modules pass data between each other correctly. These catch the "works alone, breaks together" problems.

Layer 3 — Behavioral Tests (does the flow work?)

Test the full user-facing flow end to end using automated tools like Playwright or similar. Simulate real interactions — click this, expect that, navigate here, form submits correctly, data appears where it should. Also test adjacent flows to make sure nothing regressed. These are slower and more brittle, but they catch what the other layers miss.

Layer 4 — Human Verification (does it actually feel right?)

Everything automated tests literally cannot judge: does it look correct visually, does the animation feel smooth, does the UX make intuitive sense, does the data on screen match real-world expectations, does it work on your actual device and screen size. After layers 1-3 pass, generate a specific manual checklist based on what changed — not generic checks. If the work touched a chart component, ask the human to eyeball the chart. If it touched an API integration, ask them to verify real data flows through. If it touched layout, ask them to check it at their actual screen width.

The TDD Principle

In true TDD, layers 1-3 are written before any implementation code. All tests should fail initially — that's the point. The tests define what you're building. Then you write code until they pass. Layer 4 is the final gate after everything else is green.

The cycle for every change:

  1. Red — Write a failing test
  2. Green — Write the minimum code to make it pass
  3. Refactor — Clean up without changing behavior
  4. Repeat at Layer 1 until the unit is complete, then Layer 2, then Layer 3
  5. Layer 4 is the final gate after all automated layers are green

When in doubt: Slow down, write the test, make the smallest possible change.

What Makes a Good Test

Structure every test as Arrange-Act-Assert:

def test_apply_discount_reduces_total():
    # Arrange — set up the scenario
    cart = Cart(items=[Item(price=100)])
    discount = Discount(percent=20)

    # Act — perform the action under test
    cart.apply_discount(discount)

    # Assert — verify the outcome
    assert cart.total == 80

One concept per test. If a test name has "and" in it, split it into two tests.

Name tests to describe behavior, not implementation:

BadGood
test_calculatetest_calculate_total_sums_item_prices
test_errortest_negative_quantity_raises_validation_error
test_user_servicetest_deactivated_user_cannot_place_order

Tests must be:

  • Isolated — No test depends on another test's state or execution order
  • Deterministic — Same input, same result. No randomness, no clock dependency, no network calls.
  • Fast — Unit tests run in milliseconds. If they're slow, they're not unit tests.
  • Readable — A failing test name should tell you what broke without reading the test body

Code Structure

Early Returns Over Nesting

Guard clauses first. Flatten control flow.

Bad — nested, hard to follow:

def process(order):
    if order:
        if order.items:
            if order.is_valid:
                return calculate_total(order)
    return None

Good — flat, clear:

def process(order):
    if not order:
        return None
    if not order.items:
        return None
    if not order.is_valid:
        return None

    return calculate_total(order)

Max nesting depth: 3 levels. If deeper, extract to a function.

Function Size

A function should do one thing. If you need a comment to separate "sections" inside a function, those sections should be separate functions.

Guidelines:

  • If a function exceeds ~30 lines, look for extraction opportunities
  • If a function takes more than 3-4 parameters, it's probably doing too much
  • If you can't name the function clearly, it has too many responsibilities

Single Responsibility

Every function, class, and module should have one reason to change.

Smell: "This function handles validation AND formatting AND saving." Fix: Three functions — validate, format, save.

Import Hygiene

  • No unused imports — delete them, don't comment them out
  • No wildcard importsfrom x import * hides where names come from
  • Group imports — stdlib, then external, then internal, separated by a blank line
# Bad — unordered, wildcard, unused
from utils import *
import os
import requests
from collections import OrderedDict  # unused

# Good — grouped, explicit, no dead weight
import os

import requests

from app.models import User
from app.services import send_welcome_email

Dead Code

If it's not called, it doesn't exist. Delete it — version control remembers.

  • No commented-out code// old version, # was:..., /* removed */ are clutter
  • No unreachable branches — dead else after an unconditional return, unused variables
  • No placeholder comments// TODO: removed or // no longer needed just delete the line

Explicit Over Clever

Readability beats brevity. Separate operations into clear steps.

Bad — clever but hard to debug:

names = [u.name for u in users if u.is_active and u.role in allowed]

Good — clear intent, debuggable:

active_users = filter_active(users)
authorized_users = filter_by_role(active_users, allowed)
names = extract_names(authorized_users)

When a one-liner requires mental parsing, break it apart. Optimize for the reader, not the writer.


Error Handling

Fail Fast

Validate inputs at the boundary. Don't let bad data travel deep into the system.

def create_user(email, name):
    if not email:
        raise ValidationError("Email is required")
    if not is_valid_email(email):
        raise ValidationError("Invalid email format")

    return save_user(email, name)

Specific Errors Over Generic

Catch what you expect. Re-raise what you don't. Never write except Exception — identify the actual failure mode first.

Match the exception type to the operation:

OperationCatchWhy
File open/read/writeOSErrorCovers FileNotFoundError, PermissionError, IsADirectoryError
File read + parse content(OSError, UnicodeDecodeError)File may exist but contain invalid encoding
JSON/YAML parsing(json.JSONDecodeError, ValueError)Malformed content
String → number conversionValueErrorInvalid format
Dict/list access(KeyError, IndexError)Missing key or out-of-range index
Network requests(ConnectionError, TimeoutError)Network-specific failures
Subprocess execution(subprocess.SubprocessError, OSError)Process launch or execution failure
Regex operationsre.errorInvalid pattern

Bad — swallows everything:

try:
    do_risky_thing()
except Exception:
    pass

Good — handles what it understands:

try:
    do_risky_thing()
except NetworkError:
    return retry()
except ValidationError as e:
    return error_response(e.message)
# Unexpected errors propagate up

When broad catch IS acceptable: Only at top-level application boundaries (CLI main(), API request handlers) where the alternative is an unhandled crash. Even then, log the full exception before continuing.

Never Swallow Errors

If you catch an error, you must either:

  1. Handle it — take a meaningful recovery action
  2. Log and re-raise it — make the failure visible
  3. Transform it — wrap in a more specific error for the caller

Empty catch / except blocks are bugs.


Naming Conventions

Names must clearly communicate:

  1. Who is acting — The subject performing the action
  2. What action is occurring — The verb describing the behavior
  3. Direction of data or ownership flow — Where things are going to/from

Directional Clarity

Use prepositions (to, from, into, onto) or named parameters.

Bad — Ambiguous:

shop.buy_item(item_id, buyer)      # Who is buying?
transfer(amount, account)           # Transfer to or from?

Good — Clear:

shop.sell_item_to(item_id, buyer)  # Shop sells TO buyer
shop.sell(item_id, to=buyer)       # Named parameter clarifies
transfer_from(account, amount)      # Direction explicit
account.transfer_to(other, amount)  # Direction in method name

The Read-Aloud Test

If a method call doesn't read naturally when spoken aloud, the name is wrong.

# "shop buy item buyer" — confusing
shop.buy_item(item_id, buyer)

# "shop sell item to buyer" — clear
shop.sell_item_to(item_id, buyer)

Boolean Naming

Always prefix booleans with is, has, should, can, will, or did:

# Bad — ambiguous (is it a noun? a verb? a state?)
active = True
permission = True
refresh = True

# Good — clearly a yes/no question
is_active = True
has_permission = True
should_refresh = True

Naming Patterns

PatternUse WhenExample
verb_noun_to(target)Action flows to targetsend_message_to(user)
verb_noun_from(source)Action flows from sourcereceive_payment_from(customer)
noun.verb_to(target)Object performs action toward targetcart.transfer_to(order)
verb(noun, to=target)Named parameter clarifiesassign(task, to=developer)

Never Abbreviate

Write the full word. Every time. The only acceptable abbreviations are universally understood technical terms: id, url, api, db, io.

No single-character variables. Not even loop counters. i and j hide what you're iterating over:

# Bad — what is i? what is j?
for i in range(len(rows)):
    for j in range(len(columns)):
        grid[i][j] = calculate(i, j)

# Good — names describe the iteration
for row_index in range(len(rows)):
    for column_index in range(len(columns)):
        grid[row_index][column_index] = calculate(row_index, column_index)

Common violations — these appear constantly and must always be expanded:

Write ThisNot This
dependencydep
index / positionidx
sourcesrc
destinationdst
descriptiondesc
thresholdthresh
config / configurationcfg
messagemsg
requestreq
responseres
contextctx
errorerr
valueval
countcnt
buttonbtn
userusr
callbackcb
functionfn
managermgr
servicesvc
repositoryrepo
implementationimpl
passwordpwd
temporarytmp
numbernum

Full list: references/naming-reference.md

Avoid

Don'tInstead
Single-character names (i, x, e)Descriptive name (row_index, coordinate, error)
Generic names (data, list, temp)Specific noun (user_data, order_list)
Negated booleans (is_not_disabled)Positive form (is_enabled)

Constants & Clarity

No Magic Values

Every number and string literal should have a name. Apply the extraction test before writing any literal:

The Extraction Test: If a literal isn't 0, 1, -1, True, False, None, or "" — it needs a named constant.

This includes:

  • Thresholds and limitsMAX_RETRIES = 3, HIGH_COUPLING_THRESHOLD = 10
  • Sizes and measurementsMIN_FONT_SIZE_PX = 12, MASK_VISIBLE_CHARACTERS = 4
  • String patternsDEFAULT_ENCODING = "utf-8", CSV_DELIMITER = ","
  • Configuration valuesTOP_RESULTS_DISPLAY_LIMIT = 20, SCAN_DEPTH = 3

Name the constant by what it means, not what it is. THREE = 3 is pointless. MAX_RETRIES = 3 communicates intent.

Bad:

if retry_count > 3:
    sleep(60)
if len(results) > 20:
    results = results[:20]

Good:

MAX_RETRIES = 3
RETRY_DELAY_SECONDS = 60
TOP_RESULTS_DISPLAY_LIMIT = 20

if retry_count > MAX_RETRIES:
    sleep(RETRY_DELAY_SECONDS)
if len(results) > TOP_RESULTS_DISPLAY_LIMIT:
    results = results[:TOP_RESULTS_DISPLAY_LIMIT]

Place constants at the top of the module, grouped by purpose, before any function definitions.

Boolean Parameters

Boolean arguments hide meaning at the call site.

Bad — what does True mean?

create_user(data, True, False)

Good — named parameters or options:

create_user(data, send_welcome=True, require_verification=False)

If the language doesn't support named parameters, use an options object/struct.

Immutability by Default

Default to immutable. Only use mutable bindings when reassignment is genuinely needed.

  • Use const (JS/TS), final (Java/Dart), readonly (C#), or equivalent
  • let / var only when the value must change (loop counters, accumulators)
  • Don't mutate function arguments — return new values instead
# Bad — mutates the input
def apply_discount(cart):
    cart["total"] *= 0.8
    return cart

# Good — returns a new value
def apply_discount(cart):
    return {**cart, "total": cart["total"] * 0.8}

Documentation

Docstrings

Docstrings are living documentation. Public APIs must be self-explanatory without reading implementation.

Required Elements

Every public function, method, and class must include:

  1. Purpose — What it does (one line)
  2. Parameters — Each parameter with type and meaning
  3. Returns — What is returned and when
  4. Side effects — Any state changes, I/O, or mutations
  5. Errors — What exceptions/errors can occur
  6. Examples — Realistic usage showing common cases

Example Docstring

def sell_item_to(self, item_id: str, buyer: Customer) -> Receipt:
    """Sell an item from shop inventory to a customer.

    Transfers ownership of the item from the shop to the buyer,
    processes payment, and updates inventory.

    Args:
        item_id: Unique identifier of the item to sell.
        buyer: Customer purchasing the item. Must have sufficient balance.

    Returns:
        Receipt containing transaction details and timestamp.

    Raises:
        ItemNotFoundError: If item_id doesn't exist in inventory.
        InsufficientBalanceError: If buyer can't afford the item.
        ItemAlreadySoldError: If item was sold between check and purchase.

    Examples:
        Basic sale:
        >>> shop = Shop(inventory=[item])
        >>> buyer = Customer(balance=100)
        >>> receipt = shop.sell_item_to(item.id, buyer)
        >>> assert receipt.amount == item.price
        >>> assert item.id not in shop.inventory

        Handling insufficient balance:
        >>> poor_buyer = Customer(balance=0)
        >>> shop.sell_item_to(item.id, poor_buyer)
        Raises InsufficientBalanceError
    """

Docstring Rules

  • Examples should mirror actual test scenarios
  • Update docstrings when behavior changes
  • Treat docstrings as first-class code, not decoration

Comments

Before writing any comment, apply the Delete Test: mentally delete the comment. Is anything lost? If the code already communicates the same information through naming and structure, don't write the comment.

Do CommentDon't Comment
Why — intent, business reason, non-obvious contextWhat — the code already says this
Non-obvious gotchas or edge casesObvious operations
Complex algorithm summariesBad code to explain it (fix the code instead)
TODO with ticket/issue referenceTODO without context
Regex pattern documentation (what the pattern matches)Restating a function call (# Send the email)

Bad — restates the code:

# Get the users
users = get_users()
# Filter active users
active_users = filter_active(users)
# Count the results
count = len(active_users)

Good — no comments needed (the code speaks for itself):

users = get_users()
active_users = filter_active(users)
count = len(active_users)

Good — explains why:

# Offset by 1 because CSS cascade position is 1-indexed but array is 0-indexed
cascade_position = file_index + 1

If you need a comment to explain what code does, the code should be clearer. Rename variables, extract functions, simplify logic — then the comment becomes unnecessary.


Builder Checklist

Before writing code governed by this skill, verify your plan against these constraints. This is the same guidance described in detail above, compressed for pre-build verification. Builders read this section before writing code; refactorers use the Enforced Rules table and full narrative instead.

  • Layers 1-3 written BEFORE implementation (tests fail first, then code passes them)
  • Layer 1: Unit tests cover logic, happy path, and edge cases
  • Layer 2: Integration tests verify pieces connect correctly
  • Layer 3: Behavioral tests simulate real user flows end to end
  • Layer 4: Human verification checklist generated from what changed
  • Each test has one concept, Arrange-Act-Assert structure
  • Tests are isolated, deterministic, fast
  • Functions are short, single-responsibility
  • Max 3 levels of nesting, early returns used
  • Errors fail fast at boundaries with specific types
  • Exception types match the operation (no bare except Exception)
  • No empty catch/except blocks
  • Names pass the read-aloud test
  • No single-character variables — use descriptive names
  • No abbreviated names — write the full word (dependency not dep)
  • Directional clarity in method names (to/from)
  • Booleans prefixed with is/has/should/can
  • Every literal passes the extraction test — named constant if not 0/1/True/False/None/""
  • Constants at module top, grouped by purpose
  • Boolean parameters use named args or options
  • Variables are immutable by default (const/final/readonly)
  • No unused or wildcard imports
  • No commented-out code or dead code
  • All public APIs have complete docstrings
  • Comments pass the delete test — only explain why, never what

Enforced Rules

These rules are deterministically checked by check.js (clean-team). When updating these standards, update the corresponding check.js rules to match — and vice versa.

Rule IDSeverityWhat It Checks
no-debuggererrordebugger statements left in code
no-varerrorvar declarations (use const/let)
no-empty-catcherrorEmpty catch blocks with no handling
no-consolewarnconsole.log/warn/error statements
no-double-equalswarn==/!= instead of strict equality (allows == null)

References

  • references/testing-reference.md — Testing pyramid deep-dive, mocking guidelines, anti-patterns
  • references/naming-reference.md — Complete naming conventions, abbreviation rules, domain naming
  • references/error-handling-reference.md — Error hierarchies, retry/fallback patterns, error boundaries

Assets

  • assets/tdd-checklist.md — Step-by-step TDD workflow checklist
  • assets/docstring-templates.md — Copy-paste docstring templates (Python, JS/TS, C#, Rust, Go)
  • assets/code-review-checklist.md — Comprehensive code review checklist

Templates

Domain-specific code quality extensions. Each file scaffolds the same categories (structure, naming, testing, error handling, performance) for a project type:

  • templates/web-development.md — Web-specific quality rules
  • templates/data.md — Data pipeline and analytics quality rules
  • templates/world-building.md — Unity and VRChat quality rules

Scripts

  • scripts/check_naming.py — Validate naming conventions across any codebase
  • scripts/check_complexity.py — Check function length, nesting depth, parameter count

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

37.2%
按下载量换算55

Claude

32.53%
按下载量换算48

Cursor

18.29%
按下载量换算27

Gemini CLI

9.66%
按下载量换算14

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

操作浏览器

该 Skill 可能涉及浏览器控制能力,使用时可能读取或操作网页内容,需要在受控环境中确认权限边界。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills