architectural-refactor
Execute architectural refactoring from an assessment document with deterministic, chunked operations and aggressive verification at every step. Use when you have an architectural assessment, clean architecture review, refactoring recommendations, or seam-ripper output and need to actually perform the refactoring safely. Also use when asked to "refactor based on this assessment", "execute these architectural recommendations", "fix architectural drift", "refactor in chunks", or any request to systematically restructure a codebase according to a plan. Designed specifically to prevent the kind of agent drift that causes architectural problems in the first place.
What this skill does
# Architectural Refactor
Turn architectural recommendations into reality without breaking anything.
Coding agents are great at local changes but bad at maintaining architectural coherence across long sessions, context compactions, and multi-session work. This skill solves that by externalizing the plan to disk, tracking progress in a manifest, and enforcing verification gates between every chunk. The agent can lose context entirely and pick up exactly where it left off.
## Core Mechanism
The entire approach rests on three files that live on disk (not in context):
1. **`refactor-plan.md`** — The concrete, ordered plan derived from the assessment. Every chunk has explicit entry criteria, steps, and exit criteria.
2. **`refactor-manifest.json`** — Machine-readable progress tracker. What's done, what's next, what failed, verification results.
3. **`refactor-log.md`** — Append-only human-readable log of what happened and why, so any agent (or human) can understand the history.
These files are the source of truth. Not your memory. Not the conversation. The files.
## Phase 1: Ingest the Assessment
Read the assessment document(s) the user provides. These might be markdown files, seam-ripper output, simplicity audit results, or any structured analysis with recommendations.
Extract from the assessment:
- **What needs to change** — the specific problems identified
- **What the target architecture looks like** — the desired end state
- **Any ordering constraints** — dependencies between changes (e.g., "extract module X before you can decouple Y from Z")
If the assessment is vague or missing critical details, stop and ask. A refactoring plan built on ambiguous recommendations will drift — which is exactly what we're trying to prevent.
## Phase 2: Build the Plan
Convert the assessment into a concrete, ordered sequence of **chunks**. Each chunk is a self-contained unit of refactoring that moves the codebase from one valid state to another.
### How to decide chunk boundaries
A chunk should be:
- **Independently verifiable** — after completing it, you can run tests/types/lint and confirm nothing broke
- **Independently committable** — it makes sense as a single commit with a clear message
- **Small enough to hold in your head** — if a chunk requires understanding 15 files simultaneously, break it down further
- **Large enough to be meaningful** — moving a single import is not a chunk; extracting a module is
Good chunks typically look like:
- Extract a set of related functions/types into a new module
- Move a responsibility from module A to module B (and update all references)
- Replace an abstraction with a simpler alternative
- Invert a dependency direction
- Collapse multiple files/abstractions into one
- Remove dead code identified in the assessment
Bad chunks:
- "Refactor the auth system" (too vague — what specifically?)
- "Rename variable on line 42" (too granular — group related renames)
- "Restructure everything" (not independently verifiable)
### Dependency analysis
Before ordering chunks, map which chunks depend on which:
- Does chunk B move code into a module that chunk A creates? → A before B
- Does chunk C remove an abstraction that chunk D's changes assume is gone? → C before D
- Are chunks E and F independent? → Order doesn't matter (but pick one for consistency)
If you find circular dependencies between chunks, the chunk boundaries are wrong. Re-slice until the dependency graph is a DAG (directed acyclic graph — meaning no circular dependencies).
### Write the plan
Create `refactor-plan.md` in the project root (or wherever the user prefers):
```markdown
# Refactoring Plan
**Source:** [link/path to assessment document]
**Created:** [date]
**Target:** [one-sentence description of desired end state]
## Pre-flight Checks
- [ ] All tests pass before starting
- [ ] No uncommitted changes
- [ ] Working branch created
## Chunk 1: [Descriptive Name]
**Why:** [Which assessment finding this addresses]
**Entry criteria:** All tests pass, no prior chunks pending
**Steps:**
1. [Concrete action — e.g., "Create `src/auth/tokens.ts` with the TokenService class"]
2. [Next action — e.g., "Move `generateToken()` and `validateToken()` from `src/core/utils.ts`"]
3. [Continue — e.g., "Update imports in `src/api/middleware.ts` and `src/api/routes/login.ts`"]
4. [e.g., "Remove the now-empty token section from `src/core/utils.ts`"]
**Exit criteria:** All tests pass, types check, lint clean
**Commit message:** `refactor: extract token management into dedicated auth module`
## Chunk 2: [Descriptive Name]
**Depends on:** Chunk 1
**Why:** [...]
**Entry criteria:** Chunk 1 complete and verified
**Steps:**
1. [...]
**Exit criteria:** All tests pass, types check, lint clean
**Commit message:** `refactor: ...`
[...continue for all chunks...]
## Post-flight Checks
- [ ] Full test suite passes
- [ ] No TODO/FIXME markers left from refactoring
- [ ] Assessment findings are resolved
```
The steps within each chunk should be concrete enough that an agent with zero prior context could execute them mechanically. File paths, function names, specific moves — not "restructure as needed."
### Initialize the manifest
Create `refactor-manifest.json`:
```json
{
"plan_file": "refactor-plan.md",
"assessment_source": "[path to assessment]",
"created": "[ISO date]",
"total_chunks": 5,
"current_chunk": 0,
"status": "ready",
"preflight_passed": false,
"chunks": [
{
"id": 1,
"name": "Extract token management",
"status": "pending",
"depends_on": [],
"verification": null,
"commit_sha": null,
"started_at": null,
"completed_at": null
},
{
"id": 2,
"name": "Decouple auth from core",
"status": "pending",
"depends_on": [1],
"verification": null,
"commit_sha": null,
"started_at": null,
"completed_at": null
}
]
}
```
### Get user sign-off
Present the plan to the user before executing anything. They should confirm:
- The chunks make sense and cover the assessment's recommendations
- The ordering is correct
- Nothing critical is missing
- The chunk granularity feels right
If the user wants changes, update the plan and manifest before proceeding.
## Phase 3: Execute
This is the main loop. It's deliberately rigid because rigidity prevents drift.
### Starting a session (or resuming after compaction)
Every time you begin work — whether it's the first time or you're resuming after a context compaction or new session — do this:
1. **Read `refactor-manifest.json`** — find where you are
2. **Read `refactor-plan.md`** — understand the current chunk
3. **Read `refactor-log.md`** — understand what happened recently
4. **Verify the current state** — run the verification suite to confirm the codebase is in a good state
This takes 30 seconds and prevents the #1 cause of agent drift: starting work based on stale or assumed context.
### The chunk execution loop
```
FOR each chunk (in order):
1. READ the chunk from refactor-plan.md
2. CHECK entry criteria
- Dependencies met? (check manifest)
- Tests passing? (run them)
- If not: STOP. Fix or escalate to user.
3. UPDATE manifest: chunk status → "in_progress"
4. LOG: "Starting chunk N: [name]"
5. EXECUTE each step in the chunk sequentially
- Follow the plan literally
- If a step can't be done as written: STOP
→ Log what went wrong
→ Update manifest with the blocker
→ Ask the user how to proceed
→ Do NOT improvise a workaround
6. VERIFY (the gate)
- Run the full test suite
- Run type checking
- Run linter
- If ANY verification fails:
→ Fix the issue (if it's clearly caused by this chunk's changes)
→ Re-verify
→ If you can't fix it in 2 attempts: STOP
→ Revert the chunk (git checkout/restore)
→ Log the failure
→ Update manifest: chunk status → "failed"
→ Ask the user
7Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.