Refactoring a Website with AI Coding Agents: Cost, Limits, and a Two-Phase Practice

    Handing an entire website refactor to an AI coding agent with a single prompt sounds appealing, but long-running autonomous tasks can hit usage limits at the worst possible moment—often right before the finish line. This article walks through a real refactoring session that was interrupted at the 85-minute mark after costing $52.55, analyzes why it failed, and proposes a two-phase workflow that separates design exploration from implementation. It also covers choosing the right reasoning tier, capturing visual and performance baselines, setting up branches and checkpoints, writing structured prompt templates, designing resumable execution, six concrete cost-optimization levers, and a post-refactor quality checklist. The goal is to let AI run fast while keeping humans able to see clearly, stop in time, and pick up where things left off.

    1. The Problem: Can a Single Sentence Refactor an Entire Website?

    For indie developers and small teams, a company website is often the most labor-intensive “front-of-house” project:

    • Defining the information architecture and refining the visual language;
    • Iteratively adjusting responsive breakpoints;
    • Balancing accessibility against first-paint load performance.

    None of this is technically hard, but it is deeply tedious. So handing a coding agent a single sentence—“Here’s the codebase. Match the quality of award-winning design sites, refactor the whole site, and don’t ask me anything along the way”—is an attractive idea.

    But a website refactor is a classic “long task”: it combines design exploration, global code changes, visual verification, and multiple rounds of rework. The coding agents that have emerged recently—with multi-step planning, autonomous file read/write, command execution, and the ability to spawn sub-agents for parallel subtasks—are genuinely capable of this kind of work.

    The problem is that once exploration and implementation are handed to the same continuous run, both duration and cost become uncontrollable. When you hit the usage cap within a rolling time window, the task gets force-stopped at an arbitrary stage—and the interruption point often lands exactly on the finishing touches. At that moment, a large amount of completed code is not yet in a deliverable state, while the marginal cost of continuing is high.

    2. Field Report: A Session That Hit the Usage Limit

    2.1 Setup

    • Environment: The OS’s built-in terminal, launching the command-line coding agent in the project directory.
    • Reasoning tier: The default is a medium tier. Because a full-site refactor demands heavy reasoning and self-checking, I switched to the highest tier before starting.
    • Goal: Raise the site from prototype-grade styling to a production-level standard, benchmarked against common award-winning design sites—clear visual hierarchy, a memorable hero section, carefully tuned motion timing, and thorough mobile adaptation.

    2.2 Execution

    After a single instruction, the agent behaved in a typical “long task” mode:

    1. Spawned sub-agents that produced 3 homepage design directions in parallel;
    2. Autonomously chose one “visual-first” direction (carrying content through imagery);
    3. Reworked the code at scale around that direction—modifying 20 files and adding about 4,320 lines of code in total (including helper scripts it wrote itself).

    2.3 The interruption

    At the 85-minute mark, the flow entered the finishing and polishing stage and immediately hit the hourly rolling usage cap, producing a “you have stopped operating” style interruption. The final bill was $52.55.

    2.4 The real cause of the interruption

    Judged by results, the final stage produced very limited value, yet it had already consumed a sizable share of the time budget. The interruption looked like a usage cap on the surface, but the deeper cause was a task-design problem:

    1. Ever-expanding context: Across many rounds of reading and writing files and running commands, the agent’s context kept growing, and it had to carry the existing context forward for each new reasoning step—so the input cost of every step grew.
    2. Exploration and implementation were bound together: Generating and selecting among the 3 design directions happened in the same execution flow as the per-file implementation. Whichever direction was finally chosen, the exploration cost of the other two was already sunk.
    3. No resumable checkpoints: At the finishing stage there was no independently deliverable intermediate version. Once interrupted, the next executor had to first “understand” every change that had already happened before continuing.

    3. Core Idea: Split the Long Task into Two Phases

    The cost of a long task can be approximated as:

    1. Total cost ≈ Σ(input context length per step × input unit price + generated length per step × output unit price) + overhead for tool calls and model inference

    As context grows with task progress, completing the same step gets more expensive the later it happens. The key to controlling long-task cost is not compressing a single step, but making the context converge early and making retry costs as small as possible. On this basis, a website refactor can be split into two phases.

    3.1 Phase 1: Direction Selection

    • Goal: Answer only “which direction to pick”.
    • Boundaries: Produce only lightweight prototypes sufficient to judge quality—e.g., static hero mockups, skeleton code for key sections, and a color-scheme rationale. No real data, no full responsive implementation.
    • Scale control: Generally 2–3 candidate directions is enough; limit each direction to 1–2 core pages and explicitly forbid large-scale expansion.
    • Exit condition: A written comparison conclusion, including the choice, the reasoning, and a next-step list.

    3.2 Phase 2: Targeted Implementation

    • Goal: On the single chosen direction, complete implementation and verification item by item according to the plan.
    • Input: The Phase 1 conclusion file—not the original request.
    • Method: Checklist-driven, committed item by item; verify and commit as each item is done.
    • Priority: First ensure it “runs, looks right, and can ship”, then polish the details.

    3.3 Why this split works

    • Context converges: Phase 2 no longer carries the comparison of multiple directions—only the decision rationale and design spec for the chosen direction—which sharply lowers the input cost of every step.
    • Retry cost is bounded: If the direction is wrong, you only redo the lightweight prototype; if you discover a direction problem only after large-scale coding, rework costs multiply.
    • Decision-making stays with humans: Direction choice is an aesthetic and branding judgment, best left to people. AI supplies candidates efficiently, compares them, and implements; humans make the call.
    • Breakpoints are recoverable: Each phase has clear outputs and commit records, so no single interruption forces a full restart.

    4. Preparation: Five Things That Decide Success

    4.1 Choose the right reasoning tier

    Many coding agents support switching reasoning tiers or model tiers. The general rule:

    • High reasoning tier: suited to architecture decisions, tricky debugging, and global refactor planning;
    • Default or lower tier: sufficient for well-defined work such as formatting, mechanical replacement, and copy polishing;
    • If the tool offers a fast mode: it usually trades a higher unit price for faster generation, which is good for quickly drafting during exploration but not suitable as the main tier for long tasks.

    Selection principle: spend the high-reasoning budget on “judgment”, not on “typing”.

    4.2 Start local services and capture baselines

    Whether or not you use AI, get the project running locally first. In the project root run:

    1. npm run dev

    After it starts, capture three kinds of baselines in the browser:

    1. Visual baseline: Screenshot and archive the homepage hero, the second screen, and core inner pages at both desktop wide and mobile narrow viewports. In my run, the old homepage hero used a dark fantasy background image with a declarative headline, and the second screen was a four-step process-card flow: “research → planning & quoting → design & development → launch”.
    2. Metrics baseline: Record first-paint load time, page size, number of resource requests, and the count of issues flagged by automated accessibility checks.
    3. Behavior baseline: Record whether key paths such as navigation and form submission work.

    After refactoring, compare against these baselines to objectively answer “did it actually get better?”

    4.3 Define the scope of changes

    Use the device toolbar in developer tools to switch to a mobile viewport, then check nav collapse, card layout, font sizes, and touch targets. List the issues that must be prioritized for fixing, as the acceptance criteria for Phase 2.

    4.4 Set up branches and checkpoints

    • Tag or create a baseline branch before refactoring;
    • Commit each phase and each runnable version independently;
    • For multi-file batch changes, keep commits small and clear so they are easy to roll back and review.

    4.5 Estimate usage and leave a buffer

    • Small-scale dry run: First measure the usage burn rate with a small task (e.g., reworking a single page section), then estimate the time and cost the full round needs.
    • Budget by task duration: Hourly rolling usage windows control granularity by task duration, not cumulative spend. Plan long tasks around “how many hours it is expected to run”, leaving room for waiting on human review and verification.
    • Reserve a margin: A single long task should not fill the entire window; reserve 30% or more of the budget for rework.
    • Set alerts: Turn on usage notifications or budget alerts, and try to “schedule” interruptions between tasks rather than in the middle of a task.

    5. Prompt Design: Structured Templates Over “One Sentence”

    The advantage of a one-sentence prompt is brevity; the drawback is missing specs—the model has to guess the scope and standards and tends to keep expanding. Use a five-part template: “role & boundaries + goal & benchmark + scope & no-go zones + delivery & acceptance + execution constraints”.

    5.1 Phase 1: Direction Selection

    1. [Role & Boundaries]
    2. You are a senior front-end design and engineering lead. The current project is the official website's front-end codebase; keep the tech stack unchanged.
    3. You have read/write and command-execution access to this repo. Forbidden: installing new dependencies, modifying build config, accessing paid external services.
    4. [Goal]
    5. Give the homepage a visual upgrade to the level of a mature product website, not a prototype look.
    6. [Scope]
    7. - Candidate directions: 2, differing in hero visual language and information hierarchy;
    8. - Each direction only builds the hero + the second-screen "core process" section; placeholders for images and copy are allowed;
    9. - No real data, no changes to backend or business logic;
    10. - Mobile must work: responsive breakpoints, touch targets no smaller than 44×44 px.
    11. [Deliverables & Acceptance]
    12. 1. A separate branch per direction, runnable locally and screenshot-able;
    13. 2. A comparison note that lists and compares across four dimensions—visual memorability, information clarity, implementation complexity, performance risk—and gives a recommendation;
    14. 3. Do not modify files outside the components directory.
    15. [Execution Constraints]
    16. - Before starting, write an execution plan into PLAN.md at the repo root;
    17. - Commit after each verifiable step, with a message describing what was done and how to verify;
    18. - Do not ask me questions mid-task; for ambiguities you cannot resolve yourself, proceed with the most conservative option and record assumptions and open items in PLAN.md.

    5.2 Phase 2: Targeted Implementation

    1. [Input]
    2. - Design decision: governed by DESIGN_DECISION.md (Phase 1 output); do not re-explore other directions;
    3. - Acceptance checklist: governed by CHECKLIST.md; complete and tick items one by one.
    4. [Execution Order]
    5. 1. Extract global design tokens (colors, font sizes, spacing, radii, shadows) into a unified config;
    6. 2. Layout skeleton and component structure;
    7. 3. Responsive breakpoint adaptation;
    8. 4. Motion and interaction details;
    9. 5. Performance and accessibility fixes (image lazy-loading and size declarations, semantic tags, contrast, keyboard reachability).
    10. [Completion Criteria]
    11. - All items in CHECKLIST.md ticked;
    12. - Local build and preview error-free;
    13. - Desktop and mobile screenshots versus baseline show no obvious misalignment or overflow;
    14. - If interrupted at any stage, the repo's latest commit runs independently.
    15. [Record]
    16. Maintain PROGRESS.md: done items, in-progress items, known issues, and next step. Update after each commit.

    5.3 Key constraints in the template

    • Benchmarks must be measurable: “Match award-winning sites” is a direction, not a standard. Translate it into verifiable specifics—hero copy hierarchy, card spacing, image crop ratios, interaction feedback timing.
    • Permission whitelist: Specify the writable directories (e.g., components, styles) and the forbidden actions (installing dependencies, changing environment variables, committing secrets).
    • Maintain a progress file: Keep progress in the repo, not only in the model’s context. This is the precondition for resuming after an interruption.
    • Unify expression preferences: If communicating in Chinese, explicitly require “documents, comments, and commit messages in Chinese”; otherwise the agent often defaults to English output.

    6. Breakpoint and Resume Design for Long Tasks

    6.1 Three elements of recoverability

    1. Progress file: Record done, in-progress, known issues, and next step; update it after every step.
    2. Fine-grained commits: Each commit maps to a verifiable small goal, so at any moment you can find “the last runnable version”.
    3. Re-entrant execution flow: Cleanup and finishing scripts should be safe to run repeatedly without side effects—e.g., repeated generation should not produce duplicate assets or duplicate data.

    6.2 Multi-sub-agent collaboration

    • Clear division of labor: e.g., one handles the homepage hero, one handles inner-page templates, one handles mobile style checks.
    • Agree on interfaces first: Define design tokens and component naming conventions before parallel development to avoid large-scale merge conflicts later.
    • Aggregation belongs to the main agent: The main agent compares, selects, and does consistency review, and produces a written conclusion.
    • Finish “can ship” first: layout, responsive behavior, basic accessibility, and a passing build.
    • Then “looks good”: motion, micro-interactions, image style, and detail alignment.
    • Exception: if the content is inherently visual (e.g., a photography portfolio or illustration community), motion and visual quality are core functionality and should be handled earlier.

    In my test, it was exactly the “looks good” finishing stage that got interrupted, while the “can ship” foundation was basically in place. Had I progressed by priority, the actual loss from the interruption would have been much smaller.

    6.4 How to resume after an interruption

    1. Check the repo status and PROGRESS.md to confirm which step is done;
    2. Start from the last runnable commit and fill only the missing items, rather than re-issuing the full request;
    3. If usage is near the window cap, stop proactively at a phase boundary and organize the remaining work into the input for the next task.

    7. Six Levers for Cost Optimization

    1. Trim the context: Mount only task-relevant directories and files; avoid pulling the whole codebase, lockfiles, and large static assets into context; keep a concise project note in the repo (tech stack, directory conventions, build and test commands) to reduce repeated explanation.
    2. Use models in tiers: Use the high reasoning tier for architecture decisions and hard problems; use the default or faster mode for formatting, copy, and mechanical replacement; where possible, use rule scripts, linters, or traditional template engines for deterministic work.
    3. Constrain output: Ask for only the necessary code diffs and brief notes; forbid explaining every change file by file, to avoid large generative output driving up cost.
    4. Control parallelism: 2–3 candidate directions is usually enough; more directions bring sharply diminishing marginal returns while cost grows roughly linearly.
    5. Reuse rather than rewrite: Prefer reworking the existing component system and reuse mature design tokens and component libraries instead of having the model “reinvent the wheel”.
    6. Rule-ify visual assets: Programmatically generatable visual elements—icons, gradients, background textures—should be produced uniformly by scripts or a design-token system, rather than having the model generate images one by one or inline large encoded blobs.

    8. Quality Acceptance: A Checklist After AI Refactoring

    AI finishing the code does not mean quality is up to standard. Verify item by item:

    Dimension Key checks
    Visual consistency Do colors, font sizes, spacing, radii, and shadows all come from unified design tokens, or are there scattered hard-coded values?
    Responsive At narrow, standard, and wide widths, check nav, grid, and cards for overflow, overlap, or unbalanced whitespace
    Accessibility Does body-to-background contrast meet standards? Do images have alt text? Do interactions support keyboard use?
    Performance Do hero images declare dimensions, use modern formats, and lazy-load? Are fonts loaded on demand? How does hero size compare to the baseline?
    Functional regression Do key paths—navigation jumps, form validation, contact entry points—work?
    Engineering health Do build and type checks pass? Any leftover debug code, dead references, or redundant dependencies?
    SEO & sharing Are page titles, descriptions, and social share-card info complete?
    Content accuracy Is the copy accurate? Are prices, contact details, and legal terms correct?

    9. Conclusion

    Coding agents are now capable enough to handle comprehensive engineering like a website refactor, but “hosting an entire long task with a single sentence” is neither the most economical nor the most reliable approach. A more robust way is:

    • Use a two-phase split to separate exploration from implementation;
    • Use structured prompts to translate aesthetic goals into verifiable standards;
    • Use branches, progress files, and small commits to stay recoverable at any time;
    • Use tiered models, trimmed context, and clear priorities to keep cost within budget.

    My test’s 85 minutes, $52.55, and one interrupted finishing stage are the real cost of missing these elements. In exchange, they yielded a reusable long-task methodology: let AI run fast, while letting humans see clearly, stop in time, and pick up where it left off.