agentleFS
AnyOrgNameAnyOrgName/php-skills/skills/audit/refactoring/SKILL.md

refactoring

Skill4 starsChanged 4 months agoMITView on GitHub

Brownfield refactoring audit — scan an existing PHP codebase for god classes, circular dependencies, dead code, copy-paste duplication, and untested hot paths, then emit evidence-backed FINDINGS ranked by ROI so refactors are prioritised, not guessed. Use when пользователь просит провести аудит рефакторинга проекта на PHP — найти god-классы, мёртвый код, циклические зависимости, дублирование и непокрытые тестами горячие пути, и оценить находки. Аудит рефакторинга, а не Laravel или Битрикс; the user wants a refactoring audit of an existing PHP codebase — find god classes, circular dependencies, dead code, copy-paste duplication, or untested hot paths; the user wants to locate copy-paste duplication, dead or unreachable code, or oversized classes and methods across a PHP project; the user asks which refactors matter most, wants technical debt quantified, or needs a prioritised backlog of structural cleanups for a legacy PHP project. Keywords: audit, report, refactoring, refactor, findings, roi, brownfield, g…

58 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use ci-cd, multi-agent-orchestration and 7 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • JohnJBorenSkill

    ci-cd

    CI/CD pipeline design, GitHub Actions, testing automation, and deployment strategies

    Also in 5 projects that use this

  • javalenciacaiSkill

    multi-agent-orchestration

    Design and coordinate multi-agent systems where specialized agents work together to solve complex problems. Covers agent communication, task delegation, workflow orchestration, and result aggregation. Use when building coordinated agent teams, complex workflows, or systems requiring specialized expertise across domains.

    Also in 3 projects that use this

  • harrissohail6Skill

    database-design

    Database schema design and SQL best practices. Use when designing tables, writing queries, or optimizing database performance.

    Also in 5 projects that use this

  • AWSSkill

    planning

    Discovers user intent and generates a structured, step-by-step plan for model customization workflows. This skill must always be activated alongside any other skill when the user's request relates to model customization — including fine-tuning, training, building, customizing, reviewing data, or getting advice on approach, regardless of domain. Do not skip this skill even if the immediate ask is narrow (e.g., reviewing data format or a single workflow step), because planning discovers the full scope of work needed. Also activate when the user wants to resume, continue, or modify an existing plan.

    Also in 6 projects that use this

  • MicrosoftSkill

    api-design

    Guide for designing and documenting RESTful APIs. Use when asked to design an API, create endpoints, or document an API.

    Also in 16 projects that use this

  • OpenAISkill

    observability

    Vercel Observability expert guidance — Drains (logs, traces, speed insights, web analytics), Web Analytics, Speed Insights, runtime logs, custom events, OpenTelemetry integration, and monitoring dashboards. Use when instrumenting, debugging, or optimizing application performance and user experience on Vercel.

    Also in 7 projects that use this

The file

We split this skill into the rules it gives an agent

10 rules. 0 are common, 10 are distinctive, and 0 are very specific to this project.

  • 0

    Common

    Most of the 53 edited versions we read keep these.

  • 10

    Distinctive

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Do not use this skill to design a new feature or a greenfield module.

    line 85
  2. Distinctive:

    Do not run a refactoring audit when the user asks to fix one specific bug or implement one change.

    line 87
  3. Distinctive:

    Verify: Every finding has all required fields populated and a path:line in evidence.

    line 138
  4. Distinctive:

    Verify: The report is ordered by roi_score descending with the score shown on each finding.

    line 141
  5. Distinctive:

    Verify: Each remediation names a next step.

    line 145
  6. Distinctive:

    Run structural tooling — a copy-paste detector (phpcpd), PHPStan or Psalm for dead code and complexity, and a class-size or churn report — …

    line 160
  7. Distinctive:

    Verify: You have a raw list of candidate locations for duplication, dead code, and oversized classes.

    line 162
  8. Distinctive:

    Verify: Every retained candidate has a confirmed path:line and a one-line description of the smell.

    line 166
  9. Distinctive:

    Verify: Each candidate has severity, impact, effort (1-5) and confidence (0.5-1.0) grounded in its evidence.

    line 169
  10. Distinctive:

    When a finding sits on an untested hot path, the remediation must sequence characterization tests first and the structural change second — …

    line 176

“Common” is measured: kept by at least 6 in 10 of the 53 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md
<!-- generated: do not edit — source: knowledge/atoms/audit/refactoring/ --><!-- schema: atomVersion=3 skillVersion=2 graphVersion=1 --><!-- compile: @php-skills/compiler v1.0.0 (deterministic build) -->

Audit — Refactoring Smells

When to use

  • Пользователь просит провести аудит рефакторинга проекта на PHP — найти god-классы, мёртвый код, циклические зависимости, дублирование и непокрытые тестами горячие пути, и оценить находки. Аудит рефакторинга, а не Laravel или Битрикс.
  • The user wants a refactoring audit of an existing PHP codebase — find god classes, circular dependencies, dead code, copy-paste duplication, or untested hot paths.
  • The user wants to locate copy-paste duplication, dead or unreachable code, or oversized classes and methods across a PHP project.
  • The user asks which refactors matter most, wants technical debt quantified, or needs a prioritised backlog of structural cleanups for a legacy PHP project.

When NOT to use

  • Do not use this skill to design a new feature or a greenfield module; it audits existing code for smells and has nothing to scan on a blank slate.
  • Do not run a refactoring audit when the user asks to fix one specific bug or implement one change; make the minimal targeted edit instead of scanning for smells.

Core guidance

  • Emit structured FINDINGS, not prose — Report each smell as a FINDING with id (AUD-REFACTOR-{nnn}), title, evidence (path:line), domain, severity, impact, effort (1-5), confidence (0.5-1.0), roi_score, remediation, and tags — never a free-form paragraph.
  • Never emit a finding without evidence — Every finding MUST carry concrete evidence as path:line pointing at real code you sampled; if you cannot cite a file and line, do not emit the finding.
  • Rank findings by ROI score — Compute roi_score = (impact * severity * confidence) / effort for every finding and sort the report descending, so the highest-leverage, lowest-cost refactors surface first.

Decision Engine

Walk this section before choosing an implementation path.

For the smell you found, is the affected code on a hot path (frequently executed or
business-critical) and is it currently covered by tests?

├── Cold or rarely executed path: → Lower ROI — record the finding with reduced impact so it does not crowd out hot-path work;
if the code is also unreachable, reclassify it as dead code and propose deletion.

├── Hot path but already tested: → High ROI, lower risk — the tests are a safety net. Emit a finding whose remediation is
the concrete refactor (extract class, break cycle, dedupe) with the existing suite as the guard.

└── Hot path and untested: → Highest ROI — this is the danger zone. Emit a high-severity finding whose remediation
is add characterization tests first, then refactor; never refactor untested hot code blind.

Full engine: references/decision-engine.md — Decision Tree, Priority Matrix, Decision Table.

Workflows

Workflow: Emit Report

Progress:
- [ ] Build one finding per confirmed smell with `id` (`AUD-REFACTOR-{nnn}`), `title`,
`evidence`, `domain`, `severity`, `impact`, `effort`, `confidence`, `remediation`, and `tags`
- [ ] Compute `roi_score = (impact * severity * confidence) / effort` for each finding and sort
the report descending so the highest-leverage refactors appear first
- [ ] For each finding, write remediation that names the concrete fix and links to the
implementation or strategy skill that performs it, then hand the ranked report off as
the input to scoped fix tasks
  1. Build one finding per confirmed smell with id (AUD-REFACTOR-{nnn}), title, evidence, domain, severity, impact, effort, confidence, remediation, and tags.
    • Verify: Every finding has all required fields populated and a path:line in evidence.
  2. Compute roi_score = (impact * severity * confidence) / effort for each finding and sort the report descending so the highest-leverage refactors appear first.
    • Verify: The report is ordered by roi_score descending with the score shown on each finding.
  3. For each finding, write remediation that names the concrete fix and links to the implementation or strategy skill that performs it, then hand the ranked report off as the input to scoped fix tasks.
    • Verify: Each remediation names a next step; hot-path items reference test-first strategy skills.

Workflow: Scan Codebase

Progress:
- [ ] Run structural tooling — a copy-paste detector (phpcpd), PHPStan or Psalm for dead code
and complexity, and a class-size or churn report — to enumerate candidate smells
- [ ] Open each candidate file, read the code, and confirm the smell is real — count
responsibilities, trace the dependency cycle, or check callers — recording the exact
path:line for evidence
- [ ] For each confirmed smell, walk the Decision Engine to set severity and impact by hot-path
and test-coverage status, estimate effort, and assign confidence
  1. Run structural tooling — a copy-paste detector (phpcpd), PHPStan or Psalm for dead code and complexity, and a class-size or churn report — to enumerate candidate smells.
    • Verify: You have a raw list of candidate locations for duplication, dead code, and oversized classes.
  2. Open each candidate file, read the code, and confirm the smell is real — count responsibilities, trace the dependency cycle, or check callers — recording the exact path:line for evidence.
    • Verify: Every retained candidate has a confirmed path:line and a one-line description of the smell.
  3. For each confirmed smell, walk the Decision Engine to set severity and impact by hot-path and test-coverage status, estimate effort, and assign confidence.
    • Verify: Each candidate has severity, impact, effort (1-5) and confidence (0.5-1.0) grounded in its evidence.

Best practices

  • In each finding's remediation, point to the implementation skill that performs the fix — e.g
  • Open and read the actual files — do not infer smells from names or directory structure
  • When a finding sits on an untested hot path, the remediation must sequence characterization tests first and the structural change second — never propose refactoring critical untested code without a safety net

Anti-patterns

Anti-patternWhy it failsDo instead
Recommending a full rewriteRewrites discard working behavior, carry unbounded risk, and ignore the ROI ranking the audit exists to produce.Break the work into individual findings, each with local evidence and a bounded remediation,<br>and let the ROI order drive an incremental sequence.
Emitting findings without file evidenceReviewers cannot verify, action, or track a finding that points at nothing concrete.Attach path:line evidence to every finding; if you cannot cite a location, drop the<br>finding or lower its confidence and mark it as needing manual confirmation.
Refactoring code during the auditMixing analysis with edits blurs scope, produces unreviewed changes, and hides which smells were actually present.Keep the audit strictly read-only; emit findings and remediation guidance, and let a<br>separate, scoped task apply the top-ranked fixes under the appropriate strategy skill.

See references/anti-patterns.md.

Debugging

  1. Dynamic calls flagged as dead code — PHP resolves many calls at runtime, so static reachability under-reports what is actually used. Fix: Before deleting, grep for the symbol as a string, check DI config, routes, event maps, and Bitrix agents/handlers; lower confidence on the finding when dynamic use is plausible.
  2. Every finding rated the same severity — When all scores are equal, roi_score no longer discriminates and the backlog is effectively unordered. Fix: Calibrate each axis independently against the evidence — blast radius for impact, defect likelihood for severity, realistic hours for effort — so scores spread and the ranking sorts.
  3. Judging god classes by line count alone — Size is a weak proxy; responsibility count and change frequency are what make a class dangerous. Fix: Score god-class findings on responsibilities, fan-in/fan-out, and churn, not raw lines, and set effort/impact accordingly so stable large classes rank low.

Production checklist

  • Every finding in the report carries concrete path:line evidence pointing at code that was actually read.
  • Findings on untested hot paths remediate with characterization tests before any structural change is proposed.
  • The pass produces findings and remediation guidance only; it does not apply large refactors or edit code as a side effect.
  • Dead-code findings confirm the code is unreachable statically and dynamically before recommending deletion.
  • Each finding's remediation names a concrete next step and, where one exists, the implementation skill that performs it.
  • The report lists findings sorted descending by roi_score with impact, severity, effort, and confidence shown.

Version notes

  • Analyzer capabilities scale with PHP version (PHP >=7.4) — The audit applies to PHP >=7.4 through 8.4, but static-analysis fidelity grows with the version: typed properties, enums, and readonly on 8.x let PHPStan and Psalm resolve dead code and unused symbols far more precisely than on 7.4's looser types.

Security

  • Treat unreferenced code as a possible live risk — When auditing dead code, watch for unreferenced-but-reachable endpoints, admin scripts, or debug routes: seemingly dead files can still be served over HTTP and expose input sinks. Flag such code as a security finding, not just a cleanup, and validate reachability before assuming it is inert.

Testing

  • Activation and decision behavior are verified in eval/scenarios/audit/refactoring.yaml.
  • When a finding sits on an untested hot path, the remediation must sequence characterization tests first and the structural change second — never propose refactoring critical untested code without a safety net.

Additional resources

  • references/anti-patterns.md
  • references/core.md
  • references/decision-engine.md
  • references/examples.md
  • references/pitfalls.md
  • references/recipes.md
  • references/version-differences.md

Knowledge graph

Related: audit/project-analysis
Behavior constraints: ai-rules/strategy-no-untested-refactor

<!-- graph-fragment: graph/fragments/audit/refactoring.yaml -->

Skill contract

Produces: audit.refactor-findings
Requires: repo.php-source
Risk: medium · Confidence: 0.9

<!-- contract-fragment: contracts/fragments/audit/refactoring.yaml -->

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.