---
name: kotlin-kmp-refactor-safety
description: Refactor discipline for existing codebases. Enforces scope control, migration safety, compatibility, observability, and tests to keep refactors reviewable and low-risk.
license: Apache-2.0
metadata:
  version: "1.0.0"
title: kotlin-kmp-refactor-safety
canonical_url: https://skilld.dev/gh/cpinan/corta-spam/kotlin-kmp-refactor-safety
last_updated: 2026-10-29T10:16:35.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> If the user asked to install this Skill, run `npx skilld install cpinan/corta-spam/kotlin-kmp-refactor-safety`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/kotlin-kmp-refactor-safety`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/cpinan/corta-spam/kotlin-kmp-refactor-safety) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/kotlin-kmp-refactor-safety`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/kotlin-kmp-refactor-safety --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/kotlin-kmp-refactor-safety --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# KMP Refactor Safety Skill

Use this skill when the task is primarily a refactor, migration, reliability hardening, or architectural cleanup of existing code (not a greenfield feature).
This skill is about **change discipline** and **reviewability**, not system architecture itself. Pair it with your architecture/style/testing skills as needed.

## Primary objective

Deliver refactors that are:
- minimal in surface area
- safe to review and merge
- free of parallel/competing implementations
- regression-resistant (tests + observability)

## Non-negotiables

### 1) Scope control (no opportunistic rewrites)
- Touch only files required to achieve the goal.
- Do not reformat, rename, or “clean up” unrelated code.
- Avoid broad mechanical changes unless explicitly requested.
- Keep diffs small and intention-revealing.

### 2) No parallel implementations
- Do not introduce a new pattern while leaving the old pattern active.
- End state must be one of:
  - old path removed, OR
  - old path gated behind a **feature flag** with a clear removal plan (explicit TODO + tracking issue).
- Avoid duplicate sources of truth. If ownership must move, move it once and rewire callers deterministically.

### 3) Preserve public contracts unless required
- Keep public APIs stable (interfaces, model shapes, routing/public endpoints, configuration surface).
- If a contract must change:
  - update all call sites in the same change-set
  - document the breaking change in PR notes/release notes
  - add targeted tests proving compatibility and intent

### 4) Refactor in safe phases
Prefer this order:
1. **Foundation**: introduce the new core abstraction (e.g., manager/store/service) and wire it without changing behavior.
2. **Adoption**: migrate existing call sites incrementally to the new abstraction.
3. **Lock-in**: remove the old path or gate it behind a flag (default off) and make the new path the default.
4. **Cleanup**: delete dead code, consolidate configuration, reduce complexity.

Never ship an ambiguous half-state where both old and new paths may run without a flag and clear routing.

### 5) Observability (redacted)
For flows prone to edge cases (auth, payments, retries, background/foreground, webhooks, state restoration):
- add logs/metrics around transitions and decisions
- never log secrets (tokens, passwords, codes, personal data)
- log only:
  - booleans/branch decisions
  - status codes and operation names
  - hashed or truncated IDs if needed (e.g., last 4 chars)
- ensure logs can be disabled or are appropriate for production environments

### 6) Tests are part of the refactor
Minimum expectations:
- unit tests for pure logic/state transitions/mappers
- regression tests for the bug or failure mode motivating the refactor
- coverage for:
  - success path
  - failure path
  - concurrency/race behavior when applicable (mutex, retry, idempotency)
- avoid brittle tests; prefer deterministic inputs/outputs and stable assertions

### 7) Idempotency and re-entrancy for callbacks
For events that can repeat (callbacks, deep links, webhooks, background resume):
- handle duplicates safely
- validate inputs before side effects
- operations should be safe to retry without corrupting state

### 8) Backwards compatibility and migration safety
- Use versioning or feature flags for behavior changes that might break existing users.
- Provide migration steps (data migrations, config updates) in a single place.
- If data shape changes:
  - define transitional support window
  - ensure rollback strategy (or non-destructive migrations)

### 9) Performance and resource safety
- Avoid adding disk/network reads on hot paths (e.g., per-request storage reads).
- Prefer caching with explicit invalidation when correctness requires it.
- Ensure retries are bounded (max 1 retry unless specified) and do not create loops.

### 10) PR hygiene (reviewable output)
- Prefer small, coherent commits with clear messages.
- Avoid reordering code blocks unless necessary.
- Include PR notes:
  - What changed
  - Why
  - How to test
  - Flags/migration steps
  - Rollback plan (if relevant)

## Quick refactor checklist
- [ ] Single source of truth after refactor
- [ ] No stale in-memory state alongside persisted state (unless intentionally synchronized)
- [ ] No competing interceptors/validators/plugins that overwrite each other
- [ ] Duplicate events/callbacks are handled idempotently
- [ ] Failure modes are explicit and do not cause silent data loss/logouts
- [ ] Tests cover the motivating regression and key edge cases
- [ ] Clear migration/flag/rollback notes included
