Claude opencode Skill

refactor

Execute one behavior-preserving structural transformation and report evidence. Triggers: "refactor this", "simplify without changing behavior".

LLM Mart · 0 points · 10 views 0 listing impressions 0 install-command copies
Virus-scanned Reviewed automatically before listing.

Full trust report

Download boshu2-agentops-skills_refactor-9ac484e.zip · 6 KB
boshu2/agentops 445 41 forks Apache-2.0 Updated 1d ago
Part of boshu2/agentops — 73 skills

Install

skills CLI npx skills add https://github.com/boshu2/agentops/tree/main/skills/refactor
Claude Code claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install boshu2-agentops@llmmart
Git git clone https://github.com/boshu2/agentops.git

The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole boshu2/agentops collection as a plugin from our marketplace. Git is the plain clone.

Skill manifest

Refactor — one structural experiment

Refactor changes structure while preserving observable behavior. It performs one caller-selected transformation and reports the result.

Prompt

Refactor billing-service/internal/retry/backoff.go: extract the exponential backoff calculation out of RetryRequest into its own function, no other behavior change. Record a baseline, run go test ./internal/retry/... before and after, and report the diff summary, commands, results, and anything not checked.

It's working if

  • The report names the preserved behavior and cites go test ./internal/retry/... run both before and after.
  • git diff --stat touches only internal/retry/backoff.go, never an unrelated file.
  • Golden-output hashes get captured and compared byte-for-byte whenever the changed surface produces output, e.g. sha256sum before and after.
  • The report's behavior not checked list is present in the output even when empty, naming any surface the gates skipped.

Procedure

  1. Name the preserved behavior, the focused acceptance surface and the concrete structural problem for its callers. Reuse the caller's domain terms and accepted behavioral examples; preserve their meaning through the change.
  2. Record an honest baseline, including any reproducible ambient failures. For an evaluation comparing executable behavior, pin the starting source and build its baseline before edits; retain that binary and the comparison inputs. Compare the candidate using those inputs and the same toolchain. This adds no executable-comparison ritual to ordinary refactoring.
  3. Apply one bounded transformation: extract, rename, inline, simplify, encapsulate, move, or delete dead code. Judge the result by what callers must understand and where a domain rule must be changed, not by file size alone.
  4. Run the focused check and the smallest package-level regression check justified by the changed surface.
  5. Return the diff summary, commands, results, and behavior not checked.

Do not combine a newly discovered behavior fix with the structural change. A red result is evidence for the caller; this skill does not revert, narrow, retry, commit, validate, or route subsequent work automatically.

Responsibility and interface cost

Before adding an interface or splitting a module, inspect representative callers. Count the concepts they must coordinate: required setup, ordering, states, error handling and repeated domain rules. A useful boundary puts a cohesive rule under one owner and lets callers request an outcome without reproducing that rule. Reject a wrapper that only adds another name or pushes the same coordination into its callers. Existing boundaries are sufficient when no concrete caller problem warrants changing them.

Use the caller's vocabulary for extracted operations and types. A naming ambiguity that changes behavior belongs with the existing domain definition; consult Domain only when that distinction needs work. Renaming a public symbol, persisted field or protocol value is a compatibility change unless the accepted scope provides for it.

When the transformation needs a seam — an extraction boundary, interface, or module split — and more than one candidate seam exists, probe before you cut. Run the probe in disposable isolation (a scratch branch, worktree, or copied tree the caller's policy allows): rough in the seam, see what it forces — signature churn, import cycles, test rewrites — then discard the probe and keep only the knowledge. Stop condition: at most two probes; if the second candidate seam also fights back, report both findings to the caller instead of trying a third. Cutting the first imaginable seam directly into the working tree is the premature seam failure mode: the wrong boundary calcifies because reverting it now costs more than living with it.

Neutrality gates

"Behavior-preserving" is a claim to execute, not assert. Gate the transformation on behavior-identical proof:

  • The focused check and the package-level regression check pass both before and after, with the same set of pre-existing failures — no new red, and no quietly vanished red either (a test that stops running is a behavior change).
  • For output-producing surfaces (generators, serializers, formatters, reports), hash the outputs: capture golden-output hashes over identical inputs before the change and compare byte-for-byte after. A hash mismatch is a behavior diff to surface and explain, never to shrug at; the caller decides whether to keep, narrow, or reverse the change.
  • Observable error messages, exit codes, and public signatures on the changed surface are part of behavior unless the caller excluded them.

A neutrality gate that was skipped or narrowed after the fact is the post-hoc neutrality failure mode — the diff decides what got tested. Name any surface the gates did not cover in the report's behavior-not-checked list.

References

Files (agentops)
  • references
    • behavior-preserving-simplification.md 5.2 KB
      # Behavior-Preserving Simplification
      
      Use this reference when `/refactor` is asked to simplify code, remove AI-writing artifacts, reduce indirection, or make a module easier to maintain without changing behavior.
      
      ## Contract
      
      The external behavior must remain the same. If you discover a bug, file or switch to a bug-fix task instead of hiding the behavior change inside the refactor.
      
      ## Good Targets
      
      - Redundant branches that return the same result.
      - Over-abstracted helpers with one call site.
      - Names that hide domain meaning.
      - Deep nesting that can become guard clauses.
      - Duplicated logic that has the same inputs and outputs.
      - Comments that narrate obvious code instead of explaining constraints.
      - AI-style verbose prose in docs or messages that can be made precise.
      
      ## Required Loop
      
      1. Establish a green baseline.
      2. Identify the exact behavior contract and tests that protect it.
      3. Make one simplification.
      4. Run focused tests immediately.
      5. Keep the change only if behavior is unchanged and readability improves.
      6. Record the simplification in the refactor summary.
      
      ## Red Flags
      
      - The diff changes outputs, error messages, ordering, timing, or persistence.
      - Tests need broad rewrites to pass.
      - The new abstraction has no second use or clear contract.
      - The simplification deletes context that future maintainers need.
      
      ## Summary Addendum
      
      ```markdown
      ## Simplification Checks
      
      | Check | Result |
      |---|---|
      | Behavior unchanged | PASS/FAIL |
      | Focused tests passed | PASS/FAIL |
      | New abstraction justified | yes/no |
      ```
      
      ---
      
      **Source:** Adapted from an external skill corpus / `simplify-and-refactor-code-isomorphically` and `de-slopify`. Pattern-only, no verbatim text.
      
      ## Refactoring Catalog
      
      Use these patterns only after the kernel has established a green baseline, an observable behavior contract, and an atomic transformation plan.
      
      ### Extract Method
      
      Use when a function exceeds roughly 30 lines or contains a cohesive block with clear inputs and outputs.
      
      ```text
      Before: longFunction() { blockA; blockB; blockC }
      After:  longFunction() { doA(); doB(); doC() }
      ```
      
      Safety checks:
      
      - pass shared locals explicitly or return values;
      - preserve error propagation and cleanup order;
      - document side effects and mutation ownership;
      - reject an extraction that merely moves complexity behind an opaque name.
      
      ### Extract Module or Class
      
      Use when a file owns multiple unrelated concerns or a cohesive type has a stable boundary.
      
      Safety checks:
      
      - map imports before moving code and reject circular dependencies;
      - expose package-level state deliberately rather than duplicating it;
      - preserve initialization order, registration, reflection, and serialization names;
      - run callers in every affected package, not only the extracted unit.
      
      ### Rename
      
      Use when a name is misleading, ambiguous, or hides domain meaning.
      
      Safety checks:
      
      - use language tooling where available and search every tracked reference;
      - include strings, configuration, docs, tests, generated surfaces, and scripts;
      - treat exported symbol, CLI, JSON, database, metric, and event names as public API;
      - avoid preference-only churn that does not improve comprehension.
      
      ### Inline
      
      Use when a single-use helper or temporary adds indirection without a contract.
      
      Safety checks:
      
      - preserve evaluation count and order;
      - make sure the inlined expression has no hidden side effect;
      - reject inlining that duplicates behavior or makes the caller harder to test.
      
      ### Simplify Conditional
      
      Use guard clauses, early returns, or table-driven logic when nesting obscures mutually exclusive behavior.
      
      ```text
      if err == nil: succeed and return
      if not retryable or attempts exhausted: fail and return
      retry
      ```
      
      Safety checks:
      
      - preserve branch priority, error identity, logging, and side-effect order;
      - add boundary tests for every moved condition;
      - do not replace explicit domain states with a clever boolean expression.
      
      ### Reduce Parameters
      
      Use an options or request type when more than four parameters travel together and form one concept.
      
      Safety checks:
      
      - update every caller and preserve defaults;
      - distinguish required fields from optional zero values;
      - avoid a generic bag that hides unrelated responsibilities;
      - preserve public API compatibility or make migration explicit.
      
      ### Remove Dead Code
      
      Use static analysis plus repository-wide search. For CLI commands, flags, or cross-language surfaces, run:
      
      ```bash
      scripts/check-removed-symbol-refs.sh -- <removed-command-or-flag>
      ```
      
      Safety checks:
      
      - rule out reflection, string dispatch, interfaces, plugins, build tags, generated callers, and external packages;
      - search source, shell, workflows, docs, skills, Codex skills, and tests;
      - exclude historical release material only when the removal checker documents that policy;
      - keep any remaining hit blocking unless an explicit exclusion is justified in the summary.
      
      ### Complexity Interpretation
      
      | Cyclomatic complexity | Interpretation |
      |---:|---|
      | 1–5 | Simple; usually leave alone |
      | 6–10 | Manageable |
      | 11–20 | Refactor candidate |
      | 21–30 | Urgent |
      | 31+ | Critical; split carefully |
      
      Complexity is a targeting signal, not a success metric by itself. A refactor is better only when the behavior proof remains green and the resulting boundary is easier to understand, test, and change.
      
    • refactor.feature 2.7 KB · in bundle
  • SKILL.md 5.9 KB
    ---
    name: refactor
    description: 'Simplify structure, interfaces or responsibilities while preserving behavior. Use when: a focused refactor is requested; feature changes need their own intent.'
    practices:
    - refactoring
    - legacy-code-seams
    - design-patterns
    hexagonal_role: supporting
    consumes:
    - repo-context
    produces:
    - code-changes
    context_rel: []
    skill_api_version: 1
    user-invocable: true
    context:
      window: fork
      intent:
        mode: task
      sections:
        exclude:
        - HISTORY
    metadata:
      capabilities: [refactor]
      effects: [modify_source_files]
      canonical_status: canonical
      disposition: keep_specialist
      tier: execution
      dependencies: []
    output_contract: code changes with regression evidence
    ---
    # Refactor — one structural experiment
    
    Refactor changes structure while preserving observable behavior. It performs one
    caller-selected transformation and reports the result.
    
    ## Prompt
    
    ```text
    Refactor billing-service/internal/retry/backoff.go: extract the exponential backoff calculation out of RetryRequest into its own function, no other behavior change. Record a baseline, run go test ./internal/retry/... before and after, and report the diff summary, commands, results, and anything not checked.
    ```
    
    ## It's working if
    
    - The report names the preserved behavior and cites `go test ./internal/retry/...` run both before and after.
    - `git diff --stat` touches only `internal/retry/backoff.go`, never an unrelated file.
    - Golden-output hashes get captured and compared byte-for-byte whenever the changed surface produces output, e.g. `sha256sum` before and after.
    - The report's `behavior not checked` list is present in the output even when empty, naming any surface the gates skipped.
    
    ## Procedure
    
    1. Name the preserved behavior, the focused acceptance surface and the concrete
       structural problem for its callers. Reuse the caller's domain terms and
       accepted behavioral examples; preserve their meaning through the change.
    2. Record an honest baseline, including any reproducible ambient failures.
       For an evaluation comparing executable behavior, pin the starting source
       and build its baseline before edits; retain that binary and the comparison
       inputs. Compare the candidate using those inputs and the same toolchain.
       This adds no executable-comparison ritual to ordinary refactoring.
    3. Apply one bounded transformation: extract, rename, inline, simplify,
       encapsulate, move, or delete dead code. Judge the result by what callers must
       understand and where a domain rule must be changed, not by file size alone.
    4. Run the focused check and the smallest package-level regression check justified
       by the changed surface.
    5. Return the diff summary, commands, results, and behavior not checked.
    
    Do not combine a newly discovered behavior fix with the structural change. A red
    result is evidence for the caller; this skill does not revert, narrow, retry,
    commit, validate, or route subsequent work automatically.
    
    ## Responsibility and interface cost
    
    Before adding an interface or splitting a module, inspect representative callers.
    Count the concepts they must coordinate: required setup, ordering, states, error
    handling and repeated domain rules. A useful boundary puts a cohesive rule under
    one owner and lets callers request an outcome without reproducing that rule.
    Reject a wrapper that only adds another name or pushes the same coordination
    into its callers. Existing boundaries are sufficient when no concrete caller
    problem warrants changing them.
    
    Use the caller's vocabulary for extracted operations and types. A naming
    ambiguity that changes behavior belongs with the existing domain definition;
    consult [Domain](../domain/SKILL.md) only when that distinction needs work.
    Renaming a public symbol, persisted field or protocol value is a compatibility
    change unless the accepted scope provides for it.
    
    When the transformation needs a seam — an extraction boundary, interface, or
    module split — and more than one candidate seam exists, probe before you cut.
    Run the probe in disposable isolation (a scratch branch, worktree, or copied
    tree the caller's policy allows): rough in the seam, see what it forces —
    signature churn, import cycles, test rewrites — then discard the probe and
    keep only the knowledge. Stop condition: at most two probes; if the second
    candidate seam also fights back, report both findings to the caller instead of
    trying a third. Cutting the first imaginable seam directly into the working
    tree is the **premature seam** failure mode: the wrong boundary calcifies
    because reverting it now costs more than living with it.
    
    ## Neutrality gates
    
    "Behavior-preserving" is a claim to execute, not assert. Gate the
    transformation on behavior-identical proof:
    
    - The focused check and the package-level regression check pass both before
      and after, with the same set of pre-existing failures — no new red, and no
      quietly vanished red either (a test that stops running is a behavior change).
    - For output-producing surfaces (generators, serializers, formatters, reports),
      hash the outputs: capture golden-output hashes over identical inputs before
      the change and compare byte-for-byte after. A hash mismatch is a behavior
      diff to surface and explain, never to shrug at; the caller decides whether to
      keep, narrow, or reverse the change.
    - Observable error messages, exit codes, and public signatures on the changed
      surface are part of behavior unless the caller excluded them.
    
    A neutrality gate that was skipped or narrowed after the fact is the
    **post-hoc neutrality** failure mode — the diff decides what got tested. Name
    any surface the gates did not cover in the report's behavior-not-checked list.
    
    ## References
    
    - [Behavior-preserving simplification](references/behavior-preserving-simplification.md)
    - [Behavior scenarios](references/refactor.feature)
    - [Upstream capability reference](https://github.com/mattpocock/skills/blob/main/skills/engineering/codebase-design/SKILL.md) — Matt Pocock; original AgentOps adaptation.
    

Comments (0)

Sign in to join the conversation.

No comments yet.

Reviews (0)

No reviews yet.

Related