Skill: Finalize Changes and Commit (Cleanup, Deduplication, Hardcoded Audit)
Type: Execution
Purpose
Finalize current changes for production readiness.
Tasks:
- Remove duplicate logic
- Eliminate unnecessary code
- Audit and resolve hardcoded values
- Verify current branch and dirty working tree match the intended task
- Ensure consistency and build integrity
- Prepare structured commits
- Force an explicit cleanup decision after push, PR creation, or PR merge
When to Use
- Before committing finalized work to a shared branch
- Before submitting a pull request for review
- After completing a refactoring session that touched multiple files
- When preparing a clean commit history from messy working changes
- When continuing work after another session may have used the same repository
When NOT to Use
- Work-in-progress code that is still actively being developed
- Trivial single-line fixes (typo, formatting) that need no audit
- Initial prototyping or exploratory coding phases
- Changes already reviewed and approved through another skill
Inputs Required
Do not run this skill without:
Optional but recommended:
Output Format
- Issues Found
- Branch Context Verdict
- Actions Taken
- Verification Results
- Commit Plan
- Final Commit Messages
- Post-Publish Cleanup Decision
Procedure
Gate -1 – Branch Context Check
Run branch-context-check before validating the working set. If that skill is
not installed, run the check inline: inspect git status --short --branch,
git branch --show-current, git log --oneline --decorate -5, and the
staged/dirty file lists, then classify the branch/worktree against the current
task intent using the same four verdicts below.
Required outcome:
- Current task intent is summarized.
- Current branch, upstream state, recent commits, staged files, and dirty files
are inspected.
- Branch/worktree verdict is one of
match, ambiguous, mismatch, or
blocked.
Proceed to Gate 0 only when:
- Verdict is
match, or
- Verdict is
ambiguous and the user explicitly confirms the branch/worktree
is correct for the current task.
Stop before staging or committing when:
- Verdict is
mismatch or blocked.
- Staged files include changes outside the current task.
- Dirty files from a previous session overlap with current-session files.
In a stopped state, recommend a concrete recovery path: create/switch to a
task-appropriate branch, create a separate worktree from the correct base, or
finish/commit the previous-session work first. Do not move, stash, reset, or
discard changes without explicit user approval.
Gate 0 – Working Set Validation
CRITICAL: The working tree may contain changes from other agent sessions
or manual edits. This gate must isolate only the current session's changes
without disturbing anything else.
Step 0-1: Identify current session scope
- Review the conversation history and edit history of this session.
- Build an explicit list of files that were created, modified, or deleted
by this session.
- If the user provided a scope list (files or modules), use that as the
authoritative source.
Step 0-2: Inspect full working tree state
- Run
git status and git diff --name-only to enumerate all uncommitted
changes in the working tree.
Step 0-3: Classify changes
- In-scope: Files that appear in both the session scope (Step 0-1)
and the working tree (Step 0-2).
- Out-of-scope: Files that appear in the working tree but were NOT
modified by this session. These may belong to other agent sessions,
manual edits, or background tooling.
Step 0-4: Protect out-of-scope changes
- NEVER revert, restore, checkout, stash, or discard out-of-scope changes.
- Out-of-scope files must be left exactly as they are in the working tree.
- The only correct action is to exclude them from staging (
git add).
Step 0-5: Confirm with the user
- Present a summary to the user:
- Files to be committed (in-scope)
- Files left untouched (out-of-scope), if any
- Proceed only after the user confirms the commit target set.
- Validate that new/deleted in-scope files do not break entrypoints.
Gate 1 – Duplicate & Dead Code Detection
SCOPING RULE: Focus analysis on in-scope files only (from
Gate 0). When checking for duplicates, search for similar patterns
in the immediate module/directory first, then expand to adjacent
modules only if duplication signals are found.
- Identify repeated logic blocks
- If repeated ≥ 3 times → extract helper
- Avoid over-abstraction
- Remove:
- Unused variables
- Dead branches
- Debug prints
- Stale TODOs without references
Gate 2 – Hardcoded Value Audit
SCOPE ADJUSTMENT: If all in-scope changes are limited to test
files, documentation, or type definitions, perform a quick scan
(search for numeric literals and string constants in the diff)
instead of a full classification audit. The full audit is required
when production logic files are in scope.
Classify hardcoded values into:
A) Algorithmic constants → Extract to named constant + documentation
B) Operational policies → Move to config/env + default fallback
C) Test-only values → Restrict to test scope
Ensure:
- No hidden policy decisions remain hardcoded
- Retry limits, timeouts, thresholds are explicit
Gate 3 – Consistency & Quality Review
Verify:
- Error handling patterns consistent
- Logging structure aligned with project conventions
- No PII/secrets exposed
- Public interface compatibility preserved
- No accidental performance regression
Gate 4 – Verification Proof
Run relevant project checks:
- Tests
- Lint
- Typecheck
- Build
If failures occur:
- Fix root cause
- Do not silence or bypass checks
Gate 5 – Commit Structuring
Staging rule: Stage only in-scope files confirmed in Gate 0.
Use git add <specific-file> for each file individually.
Never use git add ., git add -A, or git add --all.
Separate commits logically:
- Refactor (no behavior change)
- Functional change
- Tests / documentation
Use Conventional Commits:
- fix(scope):
- feat(scope):
- refactor(scope):
- test(scope):
- docs(scope):
- chore(scope):
Each commit must explain:
- What changed
- Why it changed
- Risk considerations (if any)
- Test proof
Gate 6 – Post-Publish Cleanup Handoff
After any commit, push, PR creation, or PR merge performed as part of this
workflow, run Gate 6 of branch-context-check.
Required behavior:
- If only local commits were created, state whether push/PR is pending and what
branch remains checked out.
- If a branch was pushed and the PR is still open, offer to keep the branch,
switch back to base, or leave cleanup for after merge.
- If a PR was merged, offer or perform approved cleanup: switch to base,
fast-forward pull, delete the local task branch, delete the remote task
branch, prune remote refs, and prune stale worktree metadata.
- If a separate worktree was used, offer or perform approved worktree removal
only after confirming that worktree is clean.
Do not end the workflow after push or merge without reporting the cleanup
decision. Deletion still requires the safety checks from branch-context-check
Gate 6 (inline fallback: delete only when the working tree is clean, the PR is
merged or the user confirms the branch is obsolete, the branch is not the
current checkout, and no other branch or worktree depends on it).
Guardrails
- Do not silence or bypass failing checks.
- Do not combine unrelated changes in a single commit.
- Do not commit until branch/worktree intent has passed
branch-context-check
or the user has explicitly accepted an ambiguous verdict.
- Do not end after commit/push/merge without running the post-publish cleanup
handoff.
- Do not over-abstract when extracting helpers (repeated ≥ 3 times threshold).
- Explicitly state assumptions when classifying hardcoded values.
- If context is insufficient to determine intent, ask for clarification.
- Do not remove code without verifying it is truly unused.
- Respect existing project conventions for commit messages and structure.
- NEVER use
git checkout -- <file>, git restore, git stash, git reset --hard,
or any other command that discards or reverts uncommitted changes to files
outside the current session's scope. Other sessions or agents may own those changes.
- NEVER use
git add ., git add -A, or git add --all. Always stage files
individually with git add <specific-file> to avoid accidentally including
out-of-scope changes.
- Working tree changes from other sessions, agents, or manual edits must be
left completely untouched.
Failure Patterns
Common bad outputs:
- Lumping all changes into a single large commit without logical separation
- Skipping build/lint/test verification before committing
- Ignoring hardcoded values because they "look fine"
- Over-extracting helpers for code repeated only once or twice
- Removing code that appears dead but is used via reflection or dynamic imports
- Producing commit messages that describe "what" but not "why"
- Reverting or discarding uncommitted changes that belong to other sessions or agents
- Using
git add . or git add -A which accidentally stages out-of-scope changes
- Treating "ensure no unintended changes" as "revert unrelated files" instead of "exclude from staging"
- Continuing on a stale branch because the working tree is clean
- Treating a dirty previous-session branch as safe just because current-session
files can be staged individually
- Pushing or merging successfully, then leaving stale local/remote branches or
worktrees without offering cleanup choices
- Deleting branches or worktrees after merge without verifying clean state and
merged/obsolete status
Example 1 (Minimal Context)
Input:
3 files changed: a utility function was refactored, an unused import was found, and a debug console.log was left in.
Output:
- Issues Found: unused import in
utils/parse.ts, debug log in api/handler.ts
- Branch Context Verdict:
match — current branch and dirty files align with
the cleanup task
- Actions Taken: removed unused import, removed debug log
- Verification Results: lint pass, tests pass, build pass
- Commit Plan: single refactor commit (scope is small)
- Final Commit Messages:
refactor(utils): clean up unused import and debug log
- Post-Publish Cleanup Decision: not applicable yet — local commit only; push
or PR cleanup will be decided after publish
Example 2 (Realistic Scenario)
Input:
12 files changed across 3 modules. Includes a retry timeout hardcoded as 3000, duplicated validation logic in 4 handlers, and a new API endpoint.
Output:
- Issues Found: hardcoded retry timeout (3000ms) in
services/retry.ts, duplicated input validation in 4 route handlers, unused helper formatLegacy in utils/format.ts
- Branch Context Verdict:
match — branch name, recent commits, and in-scope
files align with the API work
- Actions Taken: extracted retry timeout to config (
RETRY_TIMEOUT_MS), created shared validateInput() helper, removed formatLegacy
- Verification Results: all tests pass, lint pass, typecheck pass, build pass
- Commit Plan: 3 commits — (a) refactor: extract shared validation, (b) refactor: move retry timeout to config, (c) feat: add new API endpoint
- Final Commit Messages:
refactor(validation): extract shared validateInput helper from route handlers
refactor(retry): move hardcoded timeout to config as RETRY_TIMEOUT_MS
feat(api): add POST /items endpoint with input validation
- Post-Publish Cleanup Decision: after PR merge, offer switch-to-base,
local/remote branch deletion, remote prune, and worktree prune; do not delete
while the PR is still open
Notes
FAST MODE (only if explicitly requested):
- Skip deep hardcoded classification
- Allow single commit only if scope is small
1---2name: finalize-and-commit-23description: Finalize code changes for production readiness by removing duplicate logic, auditing hardcoded values, verifying branch/worktree intent, verifying build integrity, structuring clean commits with Conventional Commits format, and forcing a post-publish branch/worktree cleanup decision.4license: MIT5---67# Skill: Finalize Changes and Commit (Cleanup, Deduplication, Hardcoded Audit)89**Type:** Execution1011## Purpose1213Finalize current changes for production readiness.1415Tasks:1617- Remove duplicate logic18- Eliminate unnecessary code19- Audit and resolve hardcoded values20- Verify current branch and dirty working tree match the intended task21- Ensure consistency and build integrity22- Prepare structured commits23- Force an explicit cleanup decision after push, PR creation, or PR merge2425---2627## When to Use2829- Before committing finalized work to a shared branch30- Before submitting a pull request for review31- After completing a refactoring session that touched multiple files32- When preparing a clean commit history from messy working changes33- When continuing work after another session may have used the same repository3435---3637## When NOT to Use3839- Work-in-progress code that is still actively being developed40- Trivial single-line fixes (typo, formatting) that need no audit41- Initial prototyping or exploratory coding phases42- Changes already reviewed and approved through another skill4344---4546## Inputs Required4748Do not run this skill without:4950- [ ] Working tree with uncommitted or staged changes51- [ ] Access to project build, lint, and test commands52- [ ] Knowledge of project commit conventions (if any)5354Optional but recommended:5556- [ ] Target branch context (e.g., main, release)57- [ ] List of intended change scope (files or modules)58- [ ] Current task intent or expected branch/worktree name5960---6162## Output Format63641. Issues Found652. Branch Context Verdict663. Actions Taken674. Verification Results685. Commit Plan696. Final Commit Messages707. Post-Publish Cleanup Decision7172---7374## Procedure7576### Gate -1 – Branch Context Check7778Run `branch-context-check` before validating the working set. If that skill is79not installed, run the check inline: inspect `git status --short --branch`,80`git branch --show-current`, `git log --oneline --decorate -5`, and the81staged/dirty file lists, then classify the branch/worktree against the current82task intent using the same four verdicts below.8384Required outcome:8586- Current task intent is summarized.87- Current branch, upstream state, recent commits, staged files, and dirty files88 are inspected.89- Branch/worktree verdict is one of `match`, `ambiguous`, `mismatch`, or90 `blocked`.9192Proceed to Gate 0 only when:9394- Verdict is `match`, or95- Verdict is `ambiguous` and the user explicitly confirms the branch/worktree96 is correct for the current task.9798Stop before staging or committing when:99100- Verdict is `mismatch` or `blocked`.101- Staged files include changes outside the current task.102- Dirty files from a previous session overlap with current-session files.103104In a stopped state, recommend a concrete recovery path: create/switch to a105task-appropriate branch, create a separate worktree from the correct base, or106finish/commit the previous-session work first. Do not move, stash, reset, or107discard changes without explicit user approval.108109---110111### Gate 0 – Working Set Validation112113> **CRITICAL:** The working tree may contain changes from other agent sessions114> or manual edits. This gate must isolate *only* the current session's changes115> without disturbing anything else.116117**Step 0-1: Identify current session scope**118119- Review the conversation history and edit history of this session.120- Build an explicit list of files that were created, modified, or deleted121 *by this session*.122- If the user provided a scope list (files or modules), use that as the123 authoritative source.124125**Step 0-2: Inspect full working tree state**126127- Run `git status` and `git diff --name-only` to enumerate all uncommitted128 changes in the working tree.129130**Step 0-3: Classify changes**131132- **In-scope:** Files that appear in both the session scope (Step 0-1)133 and the working tree (Step 0-2).134- **Out-of-scope:** Files that appear in the working tree but were NOT135 modified by this session. These may belong to other agent sessions,136 manual edits, or background tooling.137138**Step 0-4: Protect out-of-scope changes**139140- **NEVER** revert, restore, checkout, stash, or discard out-of-scope changes.141- Out-of-scope files must be left exactly as they are in the working tree.142- The only correct action is to *exclude* them from staging (`git add`).143144**Step 0-5: Confirm with the user**145146- Present a summary to the user:147 - Files to be committed (in-scope)148 - Files left untouched (out-of-scope), if any149- Proceed only after the user confirms the commit target set.150- Validate that new/deleted in-scope files do not break entrypoints.151152---153154### Gate 1 – Duplicate & Dead Code Detection155156> **SCOPING RULE:** Focus analysis on **in-scope files only** (from157> Gate 0). When checking for duplicates, search for similar patterns158> in the immediate module/directory first, then expand to adjacent159> modules only if duplication signals are found.160161- Identify repeated logic blocks162 - If repeated ≥ 3 times → extract helper163 - Avoid over-abstraction164- Remove:165 - Unused variables166 - Dead branches167 - Debug prints168 - Stale TODOs without references169170---171172### Gate 2 – Hardcoded Value Audit173174> **SCOPE ADJUSTMENT:** If all in-scope changes are limited to test175> files, documentation, or type definitions, perform a quick scan176> (search for numeric literals and string constants in the diff)177> instead of a full classification audit. The full audit is required178> when production logic files are in scope.179180Classify hardcoded values into:181182A) Algorithmic constants → Extract to named constant + documentation 183B) Operational policies → Move to config/env + default fallback 184C) Test-only values → Restrict to test scope185186Ensure:187188- No hidden policy decisions remain hardcoded189- Retry limits, timeouts, thresholds are explicit190191---192193### Gate 3 – Consistency & Quality Review194195Verify:196197- Error handling patterns consistent198- Logging structure aligned with project conventions199- No PII/secrets exposed200- Public interface compatibility preserved201- No accidental performance regression202203---204205### Gate 4 – Verification Proof206207Run relevant project checks:208209- Tests210- Lint211- Typecheck212- Build213214If failures occur:215216- Fix root cause217- Do not silence or bypass checks218219---220221### Gate 5 – Commit Structuring222223**Staging rule:** Stage only in-scope files confirmed in Gate 0.224Use `git add <specific-file>` for each file individually.225Never use `git add .`, `git add -A`, or `git add --all`.226227Separate commits logically:2282291. Refactor (no behavior change)2302. Functional change2313. Tests / documentation232233Use Conventional Commits:234235- fix(scope):236- feat(scope):237- refactor(scope):238- test(scope):239- docs(scope):240- chore(scope):241242Each commit must explain:243244- What changed245- Why it changed246- Risk considerations (if any)247- Test proof248249---250251### Gate 6 – Post-Publish Cleanup Handoff252253After any commit, push, PR creation, or PR merge performed as part of this254workflow, run Gate 6 of `branch-context-check`.255256Required behavior:257258- If only local commits were created, state whether push/PR is pending and what259 branch remains checked out.260- If a branch was pushed and the PR is still open, offer to keep the branch,261 switch back to base, or leave cleanup for after merge.262- If a PR was merged, offer or perform approved cleanup: switch to base,263 fast-forward pull, delete the local task branch, delete the remote task264 branch, prune remote refs, and prune stale worktree metadata.265- If a separate worktree was used, offer or perform approved worktree removal266 only after confirming that worktree is clean.267268Do not end the workflow after push or merge without reporting the cleanup269decision. Deletion still requires the safety checks from `branch-context-check`270Gate 6 (inline fallback: delete only when the working tree is clean, the PR is271merged or the user confirms the branch is obsolete, the branch is not the272current checkout, and no other branch or worktree depends on it).273274---275276## Guardrails277278- Do not silence or bypass failing checks.279- Do not combine unrelated changes in a single commit.280- Do not commit until branch/worktree intent has passed `branch-context-check`281 or the user has explicitly accepted an `ambiguous` verdict.282- Do not end after commit/push/merge without running the post-publish cleanup283 handoff.284- Do not over-abstract when extracting helpers (repeated ≥ 3 times threshold).285- Explicitly state assumptions when classifying hardcoded values.286- If context is insufficient to determine intent, ask for clarification.287- Do not remove code without verifying it is truly unused.288- Respect existing project conventions for commit messages and structure.289- **NEVER** use `git checkout -- <file>`, `git restore`, `git stash`, `git reset --hard`,290 or any other command that discards or reverts uncommitted changes to files291 outside the current session's scope. Other sessions or agents may own those changes.292- **NEVER** use `git add .`, `git add -A`, or `git add --all`. Always stage files293 individually with `git add <specific-file>` to avoid accidentally including294 out-of-scope changes.295- Working tree changes from other sessions, agents, or manual edits must be296 left completely untouched.297298---299300## Failure Patterns301302Common bad outputs:303304- Lumping all changes into a single large commit without logical separation305- Skipping build/lint/test verification before committing306- Ignoring hardcoded values because they "look fine"307- Over-extracting helpers for code repeated only once or twice308- Removing code that appears dead but is used via reflection or dynamic imports309- Producing commit messages that describe "what" but not "why"310- Reverting or discarding uncommitted changes that belong to other sessions or agents311- Using `git add .` or `git add -A` which accidentally stages out-of-scope changes312- Treating "ensure no unintended changes" as "revert unrelated files" instead of "exclude from staging"313- Continuing on a stale branch because the working tree is clean314- Treating a dirty previous-session branch as safe just because current-session315 files can be staged individually316- Pushing or merging successfully, then leaving stale local/remote branches or317 worktrees without offering cleanup choices318- Deleting branches or worktrees after merge without verifying clean state and319 merged/obsolete status320321---322323## Example 1 (Minimal Context)324325**Input:**3263273 files changed: a utility function was refactored, an unused import was found, and a debug `console.log` was left in.328329**Output:**3303311. Issues Found: unused import in `utils/parse.ts`, debug log in `api/handler.ts`3322. Branch Context Verdict: `match` — current branch and dirty files align with333 the cleanup task3343. Actions Taken: removed unused import, removed debug log3354. Verification Results: lint pass, tests pass, build pass3365. Commit Plan: single refactor commit (scope is small)3376. Final Commit Messages: `refactor(utils): clean up unused import and debug log`3387. Post-Publish Cleanup Decision: not applicable yet — local commit only; push339 or PR cleanup will be decided after publish340341---342343## Example 2 (Realistic Scenario)344345**Input:**34634712 files changed across 3 modules. Includes a retry timeout hardcoded as `3000`, duplicated validation logic in 4 handlers, and a new API endpoint.348349**Output:**3503511. Issues Found: hardcoded retry timeout (3000ms) in `services/retry.ts`, duplicated input validation in 4 route handlers, unused helper `formatLegacy` in `utils/format.ts`3522. Branch Context Verdict: `match` — branch name, recent commits, and in-scope353 files align with the API work3543. Actions Taken: extracted retry timeout to config (`RETRY_TIMEOUT_MS`), created shared `validateInput()` helper, removed `formatLegacy`3554. Verification Results: all tests pass, lint pass, typecheck pass, build pass3565. Commit Plan: 3 commits — (a) refactor: extract shared validation, (b) refactor: move retry timeout to config, (c) feat: add new API endpoint3576. Final Commit Messages:358 - `refactor(validation): extract shared validateInput helper from route handlers`359 - `refactor(retry): move hardcoded timeout to config as RETRY_TIMEOUT_MS`360 - `feat(api): add POST /items endpoint with input validation`3617. Post-Publish Cleanup Decision: after PR merge, offer switch-to-base,362 local/remote branch deletion, remote prune, and worktree prune; do not delete363 while the PR is still open364365---366367## Notes368369**FAST MODE** (only if explicitly requested):370371- Skip deep hardcoded classification372- Allow single commit only if scope is small