Letting an AI Agent Refactor an Official Website: An 85-Minute, $52 Compute Ledger

    This article examines how to use a high-reasoning coding agent to autonomously refactor a product website, using an 85-minute, $52.55 run as a practical case study. It covers reasoning-effort settings, fast-mode tradeoffs, baseline capture, structured task specifications, multi-agent orchestration, observability curves for wall-clock time, change surface, and token cost, and strategies for rolling usage quotas. The goal is to show how to turn agent productivity into verifiable engineering outcomes rather than merely generating code.

    1. Reframing the Problem: From Generating Code to Handing Over a Codebase

    Conversational code generation solves local problems: changing a function, writing a component, or adding a test. Refactoring an entire official website is different. It is a long-horizon agentic task, and the difficulty is not single-step generation quality. The real challenges are four:

    1. Transfer of decision authority: Who decides whether a design direction is “good enough”? If a human does not intervene, the model must replace subjective preference with verifiable criteria.
    2. Context drift: After hours of work and dozens of tool calls, early constraints can become diluted, and the implementation gradually drifts away from the original goal.
    3. Solution divergence: Without a convergence mechanism, an agent may repeatedly overturn its own work, making the change surface grow larger and larger.
    4. Cost and quota breakpoints: Input tokens are replayed in every turn. For long tasks, cost can grow super-linearly with the number of turns. At the same time, many accounts have a rolling “usage within the last N hours” limit, so a long task can be hard-stopped during final validation.

    This article is therefore not asking whether AI can write frontend code. It asks: while handing over control, how do you design constraints, observability, and recovery mechanisms? The practical case is a product website refresh, with the visual target set at the level of award-winning international design sites.

    2. Before Starting: Reasoning Effort, Baseline Capture, and Backward Budgeting

    2.1 Use a High Reasoning Effort for Refactoring Tasks

    Most command-line intelligent coding agents expose reasoning or thinking effort levels, such as low, medium, and high. In practice, this setting controls the amount of intermediate reasoning the model is allowed to spend before giving an answer. A higher setting allows more planning, constraint checking, and self-criticism before the model takes action.

    High effort is reasonable for refactoring tasks because the cost of a mistake is high. One wrong directory-structure change or one replacement of the styling system can contaminate dozens of files, and rollback can be far more expensive than the extra reasoning tokens. By contrast, mechanical tasks such as adding comments, batch formatting, or writing boilerplate tests do not need high effort.

    An illustrative configuration might look like this. Key names vary by tool; this is only meant to express intent:

    1. {
    2. "reasoning_effort": "high",
    3. "fast_mode": false,
    4. "max_wall_clock_minutes": 45,
    5. "budget_usd_soft_cap": 40
    6. }

    2.2 Fast Mode Is a Cost Tradeoff, Not a Free Gain

    Many newer reasoning-oriented models offer a “fast mode”: generation speed increases significantly, but unit price also increases. This tradeoff is worthwhile for short interactive sessions. For long tasks, it requires caution, because the total cost of a long task is roughly unit price multiplied by the total amount of replayed context. If the unit price doubles, the already expensive input-side cost also doubles.

    A practical rule:

    • For short interactive debugging or steps that need immediate human feedback, fast mode can reduce waiting time.
    • For long unattended batch refactoring, use standard mode and spend the budget on reasoning depth rather than throughput.

    If team policy disables fast mode, which is common in organizations with centralized cost control, skip that option. It does not affect task execution.

    2.3 Capture Baselines Before the Agent Starts

    Before the agent takes over, you must freeze “what it looked like before the change.” Otherwise, you cannot later judge whether the result is better or worse.

    • Version-control branch: Create a separate branch for the refactoring work so the main branch remains runnable.
    • Reproducible local development service: Start the project using its scaffold-provided dev command so the agent can verify rendered output itself.
    • Visual baselines: Capture screenshots of the desktop and mobile above-the-fold, second screen, and key inner pages. For mobile, use the developer tools’ simulated viewport and save a separate set.
    • Performance baselines: Record above-the-fold render time, above-the-fold asset weight, and bundle size as hard “must not get worse” constraints.

    For example, the old version of the site had a dark-fantasy-style hero background with one main headline. The second screen was a four-step flow card layout: research → planning and quote → design and build → launch. This information should be provided as context to the agent, because it helps the agent judge what to preserve and what to replace.

    3. Turn “The Codebase Is Yours” into an Acceptance-Ready Task Specification

    In practice, “hand it over to the agent with one sentence” is not enough. Effective delegation is a structured task specification that replaces real-time human decision-making. A template is shown below:

    1. # Goal
    2. Refactor the homepage and navigation of the official website, raise the visual quality to the level of award-winning international design sites, and preserve the existing copy and information architecture.
    3. # Audience and Context
    4. Visitors to the product website. The desktop and mobile above-the-fold screens are the primary battleground.
    5. # Hard Constraints (Non-Negotiable)
    6. - Reuse existing design tokens such as colors, type scale, and spacing. Do not introduce a second design system.
    7. - Preserve existing routes and accessibility semantics. Heading levels must not be skipped.
    8. - Above-the-fold asset weight must not exceed 1.2x the baseline.
    9. - Body text contrast must meet WCAG AA.
    10. # Definition of Done
    11. - The local dev service has no compile errors and no console errors.
    12. - Provide one new desktop above-the-fold screenshot and one new mobile above-the-fold screenshot, compared side by side with the baselines.
    13. - Provide a change note listing which files were changed, why each file was changed, and what remains.
    14. # Decision Boundaries
    15. - You may decide independently: layout, motion, and image treatment.
    16. - You must present a plan before acting: adding dependencies, changing route structure, or deleting existing components.
    17. # Budget
    18. - Exploration phase: no more than 3 directions in parallel, each no longer than 10 minutes.
    19. - Implementation phase: pause and report if the number of changed files exceeds 30.

    The key is to translate subjective goals such as “match award-winning sites” into a verifiable checklist: grid and breakpoints, type scale, maximum motion duration, contrast, and above-the-fold loading budget. Without a checklist, the agent can only evaluate itself against its own preferences. The output may look different, but it is hard to say whether it is actually better.

    4. Multi-Agent Orchestration: Divergent in Parallel, Convergent in Series

    In this practice, the main agent spawned multiple sub-agents in the background for parallel design exploration. It produced three homepage directions. After selecting the image-led visual narrative, it entered the implementation phase. This structure can be generalized into a reusable orchestration pattern:

    Role Responsibility Context Persist to Disk?
    Orchestrator (main agent) Decompose the task, dispatch work, review, aggregate, and execute Global constraints and budget Yes
    Direction-exploration agent Produce structural and design drafts, including tradeoff reasoning Visual and information architecture only No, outputs are placed in a temporary directory
    Audit agent Check accessibility, performance, standards, and dead code Read-only No
    Implementation agent Batch edit files according to the selected plan and add tests Selected plan and relevant files Yes

    The orchestration logic can be expressed in pseudocode:

    1. directions = parallel_spawn("explore_layout", n=3, budget_minutes=10)
    2. chosen = orchestrator.review(directions, rubric=RUBRIC) # Score against a checklist, not gut feeling.
    3. orchestrator.commit(chosen) # Commit a rollback-safe checkpoint.
    4. parallel_spawn("audit", targets=["a11y", "perf", "lint"]) # Read-only audits; no code changes.
    5. orchestrator.apply(chosen, guardrail="pause if files > 30")

    The value of isolation is threefold:

    • Failed attempts from exploration agents do not contaminate the implementation context.
    • Parallelism compresses wall-clock time from “three times serial execution” to “close to single execution.”
    • Rejected directions can be discarded directly and do not enter later reasoning.

    One should still be clear-eyed about output-volume metrics. The task changed 20 files and produced about 4,320 lines of code, including scripts. That sounds large, but lines of code are not equivalent to value. What matters is structural soundness: whether components were split meaninglessly, whether styles bypassed existing tokens, and whether new abstractions were introduced that no one will maintain. In this task, the main changes were completed and then the quota limit was hit during wrap-up. That also shows that “large change volume” often means the context and number of calls are already close to the budget boundary.

    5. Three Observability Curves: Wall-Clock Time, Change Surface, and Token Cost

    When running unattended, the human role changes from operator to dashboard reader. At least three curves should be monitored.

    Wall-Clock Time

    In an 85-minute run, actual token generation usually occupies only part of the time. Tool calls, such as reading files, running builds, taking screenshots, and starting services, along with their waiting time, often account for most of the duration. This means optimizing wall-clock time usually depends on reducing unnecessary tool round trips, not on switching to a faster model.

    Change Surface

    Inspect diffs by layer: configuration layer → layout layer → component layer → content layer. If the configuration layer and layout layer have unexpectedly many changes, the model may be “rebuilding a design system” rather than “refreshing a website.” Intervention is required immediately.

    Cost

    The cost of one round can be written as:

    1. cost_round = in_tokens * p_in + cache_read_tokens * p_cache + out_tokens * p_out
    2. cost_total = Σ cost_round

    The structural fact is that in_tokens grows monotonically with the number of session rounds, because every round replays the previous context and tool results. Therefore, the cost curve of a long task accelerates upward.

    Using illustrative unit prices of input 5 / output 25 / cache read 0.5 USD per million tokens, a sensitivity estimate can be made. Actual unit prices vary by model and effort level, so they should be checked against the current pricing page.

    1. p_in, p_cache, p_out = 5.0, 0.5, 25.0 # USD per 1M tokens (illustrative values)
    2. def estimate(rounds, ctx_growth, out_per_round, cache_hit=0.8):
    3. """ctx_growth: context increment per round (tokens); cache_hit: fraction of cached tokens."""
    4. total, ctx = 0.0, 20_000 # Initial context is about 20k tokens.
    5. for _ in range(rounds):
    6. cached = ctx * cache_hit
    7. fresh = ctx - cached
    8. total += fresh / 1e6 * p_in + cached / 1e6 * p_cache + out_per_round / 1e6 * p_out
    9. ctx += ctx_growth
    10. return total
    11. for r in (30, 60, 100, 150):
    12. print(r, round(estimate(r, ctx_growth=8_000, out_per_round=1_200), 2))

    The approximate output is: 30 rounds about 1.6 USD, 60 rounds about 6 USD, 100 rounds about 17 USD, and 150 rounds about 37 USD. By connecting this estimation model to actual usage logs, you can judge before starting whether the refactoring is worth the price. You can also locate which phase consumes the budget. In this case, it is usually the exploration phase, especially multiple image reads and multiple build-log reviews.

    6. Why Long-Running Tasks Hit a Rolling Time-Window Quota During Wrap-Up

    In the final stage of this task, a message appeared saying that the five-hour usage limit had been reached. The exact wording and window length vary by platform, but the mechanism is the same: usage is calculated over the most recent N hours, not against the account’s total balance. This is especially painful because the task may already be 80% complete, the code may be written, but the final validation and wrap-up commit cannot be obtained.

    Four countermeasures are useful:

    1. Make checkpoints idempotent. Commit once every verifiable milestone is reached, such as finalizing the design, finishing the navigation, or replacing the styling system. This ensures interruption always occurs in a runnable state. Never pile 40 files of changes into one uncommitted session.

    2. Use a resume prompt. Write the state into a repository document so the next session can take over at zero cost:

    1. ## Handoff Notes
    2. Completed: design token unification, desktop above-the-fold layout, navigation component refactor (branch feat/redesign).
    3. Not completed: mobile breakpoint tuning, componentization of the four-step flow cards, accessibility contrast review.
    4. Pending: image compression strategy for the image-led layout (original images are 4.2MB; decide between WebP/AVIF and responsive sizes).
    5. Do not redo completed items. Start from item 1 under "Not completed."
    1. Back-calculate the budget and throttle by phase. Allocate the window quota by phase, for example 25% for exploration, 50% for implementation, and 25% for validation. In the task specification, fix the number of parallel exploration directions and the duration of each direction. This prevents the most expensive exploration phase from expanding without control.

    2. Build observability and alerts. Connect token usage, per-round cost, tool-call failure rate, and build duration to logging and monitoring services. Set threshold notifications, such as “this task has accumulated more than 30 USD,” so cost is discovered before exceeding the limit, not after seeing the bill. In cloud environments, this is usually assembled from general-purpose capabilities such as object storage, CDN, logging services, and monitoring alerts. For example, on Baidu AI Cloud, build artifacts can be published to object storage and distributed through CDN, while logs and metrics can be observed through logging and monitoring services.

    7. Six Cost-Optimization Practices

    • Context hygiene: For large files, full build logs, and base64 images, let sub-agents summarize and return only conclusions. The main context should retain only decision-relevant information. This is the highest-return practice.
    • Tiered effort: Use low effort or rule-based scripts for mechanical checks such as lint, formatting, and snapshot comparison. Use high effort only for architectural decisions.
    • Specification before implementation: Have the agent first output a directory draft and component list. After human confirmation, allow coding. This avoids burning 4,000 lines of code exploring a wrong direction.
    • Hard limits in the specification: Set thresholds for parallel branches, per-phase duration, and number of changed files. Pause and report when limits are exceeded.
    • Reuse existing assets: Prefer existing design tokens and component libraries. “Refresh” does not mean “rewrite.”
    • Automated verification loop: Script type checks, lint, snapshot tests, and accessibility scans so the agent can find and fix problems itself, rather than relying on manual diff review. This saves both time and round-trip tokens.

    8. Post-Project Checklist

    Before starting: reasoning effort is set high; fast-mode policy is confirmed; branch is created; baseline screenshots for desktop and mobile are archived; performance metrics are recorded; budget and hard constraints are written into the specification.

    During execution: commit after every milestone; inspect diffs by layer; enable cost-threshold alerts; control the number of exploration directions; require approval before adding dependencies.

    At wrap-up: compare accessibility and performance against baselines; document change notes and remaining items; write the handoff document into the repository; write actual usage back into the cost-estimation script to calibrate the budget model for next time.

    9. Conclusion

    This test shows that a new generation of high-reasoning coding agents can already complete a full frontend refactoring on a scale of tens of minutes to hours. They can autonomously spawn sub-agents, explore options in parallel, converge based on review results, and apply changes in batches, all without step-by-step human direction.

    The real bottleneck has also shifted. It is no longer whether the agent can write the code. It is whether you can provide clear enough acceptance criteria, dense enough checkpoints, and accurate enough budget and quota accounting.

    85 minutes, 52.55 USD, 20 files, and 4,320 lines of code are process metrics, not success metrics. Whether the refactoring is valid still depends on older standards: whether the structure is more maintainable, whether accessibility meets requirements, whether above-the-fold performance stays within budget, and whether online conversion metrics improve. Only when agent productivity is connected to this existing engineering evaluation system does AI-driven autonomous development truly become practical.