# Code Enhancer

> >-

- **Type:** Skill
- **Install:** `agentstack add skill-knuckles-team-universal-skills-code-enhancer`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [Knuckles-Team](https://agentstack.voostack.com/s/knuckles-team)
- **Installs:** 0
- **Category:** [Agent Skills](https://agentstack.voostack.com/c/agent-skills)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [Knuckles-Team](https://github.com/Knuckles-Team)
- **Source:** https://github.com/Knuckles-Team/universal-skills/tree/main/universal_skills/core/code-enhancer

## Install

```sh
agentstack add skill-knuckles-team-universal-skills-code-enhancer
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# Code Enhancer

This skill enables the agent to perform a comprehensive, multi-domain "Code Enhancement Review"
of any codebase. It produces a prettified, graded report with standardized 0–100 scoring across
28 analysis domains, actionable TODOs prioritized by impact and risk, and structured SDD handoff
for implementation.

Supports **language-agnostic** analysis for Python, Go, Node/TypeScript, Rust, and Java projects.
Can run against **multiple projects in parallel** for cross-repository integration analysis.

## Capabilities

1.  **Project Analysis** — Scan for architectural patterns, externalized prompts, and observability integrations.
2.  **Dependency Audit, Update & Migration** — Scan `pyproject.toml` and `requirements.txt`, check for latest versions on PyPI, flag outdated/deprecated/yanked packages, **APPLY version bumps** (lossless rewrite of constraint floors/caps, `--level {patch,minor,major}`, dry-run by default) via `apply_dependency_updates.py` (CE-042), **and surface migration impact** — new features to adopt and deprecated/removed APIs our code must drop — via `analyze_dependency_migration.py` (CE-043), including a pytest-driven `DeprecationWarning` capture mode.
3.  **Codebase Optimization** — Apply industry-proven methodologies: system discovery, structural smell identification, feature classification, duplication analysis, dependency boundary establishment, and incremental optimization patterns.
4.  **Security Analysis** — Conduct defensive security analysis: attack surface discovery, dependency/CVE exposure assessment, CWE-centric codebase analysis, threat modeling, input flow analysis, authentication/authorization review, and operational security hardening.
5.  **Test Coverage Analysis** — Perform pytest use-case coverage analysis: test inventory, use-case mapping, coverage dimension analysis (line, feature, risk), test intent classification, and drift detection between docs and tests.
6.  **Documentation & Governance** — Audit README.md (industry-standard grading), AGENTS.md, and `/docs`: validation techniques, taxonomy establishment, lifecycle management, and automated drift detection.
7.  **Brainstorming** — Provide structured ideation for UI/UX enhancements and architectural upgrades.
8.  **Concept Traceability** — Implement executable documentation with bidirectional traceability using stable concept IDs embedded in code docstrings, docs, and pytest markers (including `@pytest.mark.concept()` decorators), with drift detection, registry cross-reference, and missing-marker detection.
9.  **Linting & Formatting** — Execute language-appropriate linters (ruff/mypy/bandit for Python, go vet for Go, eslint for Node). Parse and categorize findings.
10. **Vulnerability Scanning** — Integrate bandit, pip-audit, and repository-manager validation. Consolidate into unified vulnerability register.
11. **Architecture & Design Patterns** — Evaluate against industry patterns (hexagonal/clean architecture, SOLID principles, event-driven orchestration) and find deepening opportunities to turn shallow modules into deep ones. Conduct conversational architectural reviews based on ADRs and domain glossary.
12. **Actionable Reporting** — Generate consolidated report with specific TODOs, prioritized by impact and risk, with SDD handoff for implementation.
13. **Pre-Commit Compliance** — Run `pre-commit run --all-files`, detect outdated hooks, parse per-hook pass/fail. Smart pytest deduplication (pytest hooks skipped → CE-016 handles them).
14. **Test Execution** — Detect test framework (pytest, go test, npm test, cargo test, maven, gradle), execute tests with 300s timeout, grade based on pass/fail ratio.
15. **Directory Organization** — Measure files-per-directory density, detect crowded/monolithic structures, suggest logical reorganization into subdirectories.
16. **Language Ecosystem Detection** — Auto-detect primary/secondary languages, build system, available linters, and test frameworks. Adapts all downstream analysis.
17. **UI/UX Quality** — Grade web and terminal UIs using Nielsen's 10 Usability Heuristics via static file analysis. WCAG 2.1 AA accessibility checks for web projects.
18. **Multi-Project Orchestration** — Run all analysis domains across multiple projects in parallel with configurable concurrency. Per-project reports + unified cross-project summary.
19. **Cross-Project Integration** — Analyze inter-project dependency graphs, detect version conflicts, circular dependencies, and unused internal dependencies.
20. **README Grading** — Industry best-practice scoring for README.md: title, badges, description, ToC, installation, usage, architecture, contributing, license, code blocks, docs references, broken links, length, env var docs, MCP tool tables, deployment docs.
21. **Changelog Audit** — Validate CHANGELOG.md against Keep a Changelog standard using `keepachangelog` library. Check version drift against pyproject.toml, analyze dependency changelogs for version deltas (new features, breaking changes, deprecations, security fixes).
22. **Pytest Quality Grading** — Grade pytest suites against F.I.R.S.T. rubric: naming quality, structure/organization, fixture/parametrize usage, assertion quality, and AI slop detection (duplicate bodies, over-mocking, generic names).
23. **Environment Variable Scanning** — Scan Python source, Dockerfiles, compose.yml, .env/.env.example for all env var usage. Cross-reference against README documentation to identify undocumented variables.
24. **Agent Skill Quality** — Auto-detect SKILL.md files in any repository and grade them using a rule engine ported from skill-check: frontmatter validation, description quality, body structure, link resolution, and duplicate detection. Contextual — only activates when skills are present.
25. **Engineering Heuristics** — Evaluate codebase against battle-tested principles synthesized from 13 industry-standard software engineering books (Clean Code, Clean Architecture, Refactoring, The Pragmatic Programmer, Release It!, DDIA, DDD, and more). Uses contextual activation — domain modeling rules only fire when DDD patterns are detected; production resilience rules only fire for service/API projects.
26. **Circular Dependency Detection** — Scan `pyproject.toml` dependency graphs across workspace projects for circular or transitive resolution cycles. Detect workspace member conflicts and optional-dependency self-references.
27. **CONCEPT ID Parity** — Verify that every project has a `docs/concepts.md` with a unique prefix, cross-reference CONCEPT IDs in docs against code annotations, detect orphaned or undocumented concepts, and verify no prefix collisions across the ecosystem.
28. **Environment Variable Standardization Audit** — Check `auth.py` files across all agents for non-standard env var naming patterns (e.g., `_VERIFY` vs `_SSL_VERIFY`, `_BASE_URL` vs `_URL`, `_INSTANCE` vs `_URL`). Flag duplicates within the same project and deviations from the ecosystem standard.

29. **Intent & Opportunity Discovery** — Infer the codebase's intent (README/docs/entrypoints) and surface value-add opportunities in three tiers: low-hanging fruit (capabilities built but not exposed/wired), implied-but-missing (partial CRUD lifecycles, stubs), and net-new intent-aligned features. Answers *what could this become?*, not just *what's broken?*
30. **Runtime Profiling** — Measure what a single running instance actually costs: import-time resident memory, startup wall time, and the heaviest transitive imports (via `-X importtime`), profiling the console-script entry module rather than the bare package. Flags heavy dependencies (ML runtimes, browser engines) loaded unconditionally into every process. Budget-scored on RSS and startup. **Opt-in** (executes the target).
31. **Scale Profiling** — Spawn N idle instances concurrently, sample real resident memory, and report per-instance footprint, instances-per-GB density, and a projection across common RAM sizes (1/2/4/8 GB) — answers *how many of these fit on a Raspberry Pi / small node?* **Opt-in** (executes the target; never runs in the default sweep).

## Grading System

All domains are scored 0–100 using standardized criteria:

| Grade | Score | Meaning |
|-------|-------|---------|
| A | 90–100 | Excellent — meets or exceeds industry standards |
| B | 80–89 | Good — minor improvements possible |
| C | 70–79 | Acceptable — notable gaps exist |
| D | 60–69 | Below standard — significant issues |
| F | 0–59 | Failing — critical problems require immediate attention |

Every grade includes a justification with specific file paths and evidence citations.

## Headless & KG-Native Operation (60-repo scale)

For batch/CI use across many repositories, prefer the headless driver over running the 11 agent
steps by hand:

```bash
# 1. Validate the toolchain before a batch (smoke-runs every analyzer on a fixture)
python scripts/selftest.py                       # exits non-zero if any script is broken

# 2. Analyze ONE repo headlessly — language-gated, per-domain timeout + fault isolation,
#    incremental JSON written as each domain completes (CE-031)
python scripts/enhance_repo.py /path/to/repo --out reports/ --kg

# 3. Ingest the run into graph-os via the MCP (best-effort; skips cleanly with no endpoint) (CE-032)
GRAPH_OS_MCP_URL=http://localhost:8000 python scripts/kg_ingest_run.py reports/repo.enhance.json

# 4. Cross-repo + bi-temporal questions the KG answers but a filesystem tool can't (CE-034)
python scripts/kg_query_runs.py list                          # the cross-repo Cypher library
python scripts/kg_query_runs.py query regressions            # via graph-os MCP
python scripts/kg_query_runs.py deltas --current reports/ --prior reports_prev/   # offline diff
```

- **`enhance_repo.py`** is the per-repo unit; `run_multi_project.py` fans it out across repos with
  `-c` concurrency. Domains not applicable to the detected primary language are skipped (a Python
  dependency audit does not run on a Rust repo).
- **KG-native** ingest/query talk to the **graph-os MCP server over HTTP**, never via a direct
  `import agent_utilities.*` (that hard dependency previously broke the KG step). Each run is
  time-stamped so the KG's bi-temporal layer surfaces per-repo score deltas over time.
- Every new script supports `--self-test`; `selftest.py` aggregates them plus a fixture run of every
  analyzer.

### Analysis mechanism: KG-native → engine AST → local fallback (CE-045)

Four analyzers — `trace_concepts.py` (concept traceability), `analyze_tests.py` (test discovery),
`grade_pytest.py` (pytest quality), and `analyze_opportunities.py` (intent/opportunity discovery) —
no longer hand-roll Python's stdlib `ast` (fragile — e.g. `ast.Str` broke on 3.12) to walk a
project's functions/classes/decorators. They go through the shared `kg_native.py` helper, which
tries three mechanisms **in this order** for every symbol/concept lookup:

1. **The ingested code KG (graph-os)** — a read-only Cypher query over the already-ingested
   `:Code` graph (`kg_native.kg_repo_symbols`/`kg_repo_concepts`, `POST /graph/query`) or the
   composed `code_context` answer (`POST /graph/code`, action=`code_context` — definition,
   callers, blast-radius, CONCEPT markers, docs — CONCEPT:AU-KG.retrieval.synthesized-cited-answer).
   Zero re-parsing when the target repo is already ingested (`source_sync`/`kg_ingest_run.py`).
2. **The engine AST** (`epistemic_graph.parser.RustASTParser`) — on-demand tree-sitter parsing via
   the Rust engine's out-of-process socket for a file/repo the KG doesn't hold yet. Multi-language,
   version-independent (the fix for the `ast.Str`-on-3.12 class of breakage).
3. **Local stdlib `ast`** — the final fallback, used only when neither the KG nor the engine socket
   answers (`epistemic_graph` not installed, no `GRAPH_OS_MCP_URL`, or the engine erroring). Keeps
   every script working completely standalone, with zero platform dependencies.

Every `kg_native` helper is **best-effort and never raises** — an unreachable KG or engine degrades
silently to the next tier, and the tier actually used is reported back (`"kg"` / `"engine"` /
`"local"`) so a caller can note it was degraded. Set `GRAPH_OS_MCP_URL` (and optionally
`GRAPH_OS_MCP_TOKEN` for an authenticated deployment) to enable Tier 1; Tier 2 activates
automatically whenever `epistemic_graph` is installed and its engine socket is reachable — no
configuration needed for either. **This degradation is real, not theoretical**: even a live
graph-os deployment may be on a protocol/tool surface that predates the REST contract above (fleet
version drift) — the tiering means that never breaks the skill, it just quietly falls back.

The remaining `ast`-heavy analyzers (`analyze_codebase.py`, `analyze_security.py`,
`analyze_liveness.py`, `evaluate_heuristics.py`, `analyze_architecture.py`,
`analyze_dependency_migration.py`, `analyze_minimalism.py`) stay on a direct local `ast` parse:
their scoring depends on fine-grained control-flow/expression-level structure (cyclomatic
complexity via `If`/`While`/`For`/`BoolOp` counts, broad-`except` and canned-literal-return
detection, import-graph extraction, decorator-argument inspection) that the engine's SYMBOL schema
does not carry (it exposes `name`/`kind_detail`/`line`/`decorators`/call/assert-count-class
properties — not branch counts, docstrings, or full expression trees). Porting those to a coarser
schema would silently change their grades, which the KG-native conversion is explicitly not meant
to do — see `kg_native.py`'s module docstring for the full rationale.

## Steps

### Step 1: detect_language
Language ecosystem detection. Auto-detect primary/secondary languages, build system, available linters, and test frameworks to adapt downstream analysis:
- Requires: primary script `scripts/detect_language.py`

### Step 2: project_analysis [depends_on: detect_language]
Project structure and pattern analysis. Identify if the project is an MCP server, Pydantic-AI agent, library, or web application. Scan for architectural patterns, externalized prompts, and dependencies:
- Requires: primary script `scripts/analyze_project.py` and `scripts/audit_dependencies.py` (write path: `scripts/apply_dependency_updates.py`)

### Step 3: run_linters [depends_on: detect_language]
Language-aware linter orchestration. Execute language-appropriate linters (ruff, mypy, bandit for Python, go vet for Go, eslint for Node) and parse/categorize findings:
- Requires: primary script `scripts/run_linters.py` and `scripts/run_precommit.py`

### Step 4: run_tests [depends_on: detect_language]
Multi-framework test execution and grading. Execute detected test framework with a 300s timeout and grade based on the pass/fail ratio:
- Requires: primary script `scripts/run_tests.py`

### Step 5: deep_code_analysis [depends_on: project_analysis]
Code quality, complexity, and duplication analysis. Measure cyclomatic complexity, function length, nesting depth, duplicate blocks, monolithic files, and module coupling:
- Requires: primary script `scripts/analyze_codebase.py` and `scripts/analyze_directory_density.py`

### Step 6: security_analysis [depends_on: project_analysis]
Security and vulnerability scanning. Discover attack surface, scan for CWE patterns, scan environment variables/credentials, and parse vulnerability reports:
- Requires: primary script `scripts/analyze_security.py` and `scripts/scan_env_vars.py`

### Step 7: documentation_audit [depends_on: project_analysis]
Documentation governance and drift detection. Validate README/AGENTS.md, check for documentation staleness, verify KEEP_A_CHANGELOG standards, and detect drift against code:
- Requires: primary script `scripts/audit_documentation.py` and `scripts/audit_changelog.py`

### Step 8: concept_traceability_audit [depends_on: project_analysis]
Concept traceability with drift detection. Scan for CONCEPT ID markers in code docstrings, docs, and pytest markers, and cross-reference against the canon

…

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [Knuckles-Team](https://github.com/Knuckles-Team)
- **Source:** [Knuckles-Team/universal-skills](https://github.com/Knuckles-Team/universal-skills)
- **License:** MIT

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** yes
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/skill-knuckles-team-universal-skills-code-enhancer
- Seller: https://agentstack.voostack.com/s/knuckles-team
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
