improve-codebase-architecture
БесплатноБез исполняемых скриптовНе проверенSurveys a real repository for structural problems and turns the findings into a staged plan: measures churn, size, import cycles, coupling and co-change…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
Improve Codebase Architecture
Overview
Architecture work fails in two ways: opinions without evidence, and plans too large to ship. This skill replaces both with a procedure: measure the repository, name a handful of candidates with the numbers that support them, let the user choose, design the new boundary, and deliver it as steps that each keep the build green. Two kinds of problem repay the effort most:
- Shallow module: its interface is nearly as large as what it does. Pass-through wrappers, one-function files and layers that only forward mean a reader opens five files to follow one idea and a caller gains nothing.
- Tangled cluster: modules that cannot be understood, tested or changed apart. Import cycles, files in different folders that always change together, and modules that import half the codebase.
The output is an evidence table, three to five candidate cards, and one proposal with a staged plan. Code changes only after the user approves a step.
Instructions
1. Set the scope
Ask what hurts (slow changes, repeat bugs in one area, tests that need heavy mocking, onboarding), which paths are off limits (generated, vendored, about to be deleted), how much change the team can take per week, and where proposals live (a docs folder or the issue tracker). Then read the README, any architecture notes, the CI config and the test command, and run the tests. A red baseline makes every later step unverifiable, so report it and stop if they fail.
2. Measure
Keep measurement output outside the repository: export ARCH=$(mktemp -d).
Hotspots, any language. Commits in the last year multiplied by current length; columns are score, commits, lines, file. Run from the repository root and replace src with the source root.
git log --no-merges --since=12.months --name-only --pretty=format: -- src | grep . | sort | uniq -c | sort -rn > "$ARCH/churn.txt"
while read -r n f; do [ -f "$f" ] && echo "$((n * $(wc -l < "$f"))) $n $(wc -l < "$f") $f"; done < "$ARCH/churn.txt" | sort -rn | head -15
Co-change, any language. Save as $ARCH/cochange.py; it lists file pairs from different folders that keep landing in the same commit.
"""git log --no-merges --since=12.months --name-only --pretty=format:'@%h' -- src | python3 "$ARCH/cochange.py" 5"""
import collections, itertools, sys
min_shared = int(sys.argv[1]) if len(sys.argv) > 1 else 5
commits, files = [], None
for line in sys.stdin:
line = line.strip()
if line.startswith("@"):
files = set()
commits.append(files)
elif line and files is not None:
files.add(line)
changes, together = collections.Counter(), collections.Counter()
for files in commits:
if len(files) > 30: # sweeping commits (renames, formatting) say nothing about coupling
continue
changes.update(files)
together.update(itertools.combinations(sorted(files), 2))
for (a, b), n in together.most_common():
if n >= min_shared and a.rsplit("/", 1)[0] != b.rsplit("/", 1)[0]:
print(f"{n:4} commits {n / min(changes[a], changes[b]):4.0%} of the rarer file {a} <-> {b}")
Dependencies, JavaScript and TypeScript.
npx madge --circular --extensions ts,tsx src # import cycles
npx madge --json --extensions ts,tsx --exclude '\.test\.tsx?$' src > "$ARCH/deps.json"
npm install --prefix "$ARCH" dependency-cruiser typescript@6 # outside the repository, with a TypeScript it can load
"$ARCH/node_modules/.bin/depcruise" src --no-config --do-not-follow node_modules --metrics --output-type metrics # Ca, Ce, instability per folder and module
npx knip --files --exports # files and exports nothing uses
grep -rcE "(vi|jest)\.mock\(" src --include='*.test.ts' | sort -t: -k2 -rn | head # mocks per test file
Save this as $ARCH/shape.cjs and run node "$ARCH/shape.cjs" src for per-file size, exports, importers (fanIn) and imports (fanOut):
const fs = require('fs'), path = require('path')
const root = process.argv[2] || 'src', deps = require(path.join(process.env.ARCH, 'deps.json'))
const fanIn = {}
for (const targets of Object.values(deps)) for (const t of targets) fanIn[t] = (fanIn[t] || 0) + 1
const rows = Object.keys(deps).map((file) => {
const text = fs.readFileSync(path.join(root, file), 'utf8')
const loc = text.split('\n').filter((l) => l.trim() && !l.trim().startsWith('//')).length
return { file, loc, exports: (text.match(/^export\s/gm) || []).length, fanIn: fanIn[file] || 0, fanOut: deps[file].length }
})
const show = (title, list) => { console.log('\n' + title); console.table(list.slice(0, 10)) }
show('Most outgoing imports', [...rows].sort((a, b) => b.fanOut - a.fanOut))
show('One importer and under 40 lines', rows.filter((r) => r.fanIn === 1 && r.loc < 40).sort((a, b) => a.loc - b.loc))
show('Fewer than 8 lines per export', rows.filter((r) => r.exports >= 5 && r.loc / r.exports < 8))
**Depen
Установить improve-codebase-architecture в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл improve-codebase-architecture?
Surveys a real repository for structural problems and turns the findings into a staged plan: measures churn, size, import cycles, coupling and co-change, finds shallow modules (wrappers that hide nothing) and tangled clusters, ranks a few candidates on evidence, designs the new boundary and proposes the change as small reversible steps guarded by a CI rule. Use when someone says "improve the architecture", "where should we refactor", "this codebase is a mess", "find the worst modules", "untangle these dependencies", "too many tiny files", "make this easier to test", or asks for a refactoring roadmap.
Как установить скилл improve-codebase-architecture?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл improve-codebase-architecture запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic