TL;DR
If you deliver a user story in a previous sprint and then need to modify it in a new sprint, what do you do?
You don't. All work must be prioritized by the Product Owner on the Product Backlog, and no unplanned stories should be introduced into the current iteration after Sprint Planning is completed.
If you discover work that needs to be done in a future sprint, write up a new user story and submit it to the Product Owner for inclusion in the Product Backlog. If it's truly a show-stopper that blocks progress within the current sprint, raise the issue within the team (e.g. during the daily stand-up) and let the Scrum Master escalate it.
Refactoring vs. New Work and Rework
Refactoring doesn't change the behavior of a feature, it just changes the internal implementation. You might need to refactor existing code to accommodate a new feature, but the old code should fundamentally behave the same way, and all your old tests should still pass.
In addition, such refactorings should be kept to the absolute minimum needed to accommodate the new feature. This is not the time to go back and make improvements or optimizations that extend beyond the scope of the story you're working on.
If you need to change behavior, improve a user interface, or optimize a section of code, that's new work. It must be added to the Product Backlog, prioritized by the Product Owner during Backlog Grooming, and then get added to the Sprint Backlog during Sprint Planning for a future sprint rather than the current one.
There Are Always Exceptions
There are exceptions to every rule. Some examples include:
- New work essential to the current Sprint Goal might be discovered during a sprint, and might justify an Early Termination and a return to Sprint Planning.
- Paying down technical debt when you have no other stories to work on is a good use of one's time.
- Refactoring (or even improving) something in passing while working on a deliverable feature is often okay in practice, but it's a very fine line that often leads to yak shaving and takes resources away from stories the team has committed to for the sprint. Don't do that.
- Stories that aren't on the critical path to the Sprint Goal can be swapped out, modified, or de-scoped with the active cooperation of the Product Owner without triggering an Early Termination. This is an advanced technique that can backfire easily, so don't rely on it.
Scrum and other agile frameworks aren't meant to be a straight-jacket. There is enough flex in the system to accommodate variations and edge cases. However, a team really needs to master the underlying principles before attempting to violate principles like YAGNI or bypass formal scoping controls, or else it risks turning its framework into ScrumBut or its failure-inducing equivalent.