AI Agent Generated a 10,000-Line File? Recover Safely

AI Agent Generated a 10,000-Line File? Recover Safely

Aident AI

A dense knot of luminous strands resolves into five clean modular forms.

AI Agent Generated a 10,000-Line File? Recover Safely

If Codex, Claude Code, or another coding agent has turned one file into a 10,000-line tangle, stop asking it to refactor the whole file at once. Preserve the current state on a recovery branch, establish a testable behavior baseline, map the file's responsibilities without editing it, and extract one seam at a time while keeping the public API stable.

The safest goal is not "make this file clean." It is "make one behavior-preserving extraction that is easy to review and reverse." Repeat that small loop until the oversized file becomes a thin coordinator or until the remaining code is cohesive enough to leave alone.

Prerequisites

You need:

  • a Git repository with a known-good commit before the agent's large change;

  • the repository's existing test, type-check, and lint commands;

  • enough knowledge to identify the file's public entrypoints;

  • a protected place for any patch backup if the working tree contains uncommitted work; and

  • authority to change the repository.

Do not start by deleting the file, reverting the entire branch, or accepting another large automated rewrite. First preserve both the known-good state and the agent-generated state.

1. Stop New Writes and Measure the Damage

Pause the coding agent. From the repository root, inspect the current state:

git status --short
git diff --stat
git diff --numstat
wc -l path/to/large-file.ts
git log --oneline -- path/to/large-file.ts

Replace the path and extension with the actual file. On Windows PowerShell, use (Get-Content path\to\large-file.ts).Count for the line count.

Expected result: you know whether the problem is one large uncommitted diff, a series of commits, or an old file that the agent made worse. git diff --numstat also separates a large intentional move from thousands of newly generated lines.

If the working tree contains secrets, generated credentials, or customer data, remove those from the recovery scope before creating any commit or patch.

2. Preserve a Reversible Checkpoint

Create names that identify the last known-good commit and the recovery work:

git branch backup/before-large-file <known-good-commit>
git switch -c recovery/split-large-file

If the agent's work is uncommitted, review it first, then checkpoint the intended files on the recovery branch:

git add path/to/large-file.ts path/to/related-tests.ts
git commit -m "checkpoint agent-generated state"

Expected result: backup/before-large-file points to the clean baseline, and recovery/split-large-file contains the oversized implementation. Neither state depends on chat history or an undo button.

If the generated state is clearly disposable and no useful behavior needs saving, a targeted git restore --source=<known-good-commit> -- path/to/large-file.ts may be enough. Do not use a destructive repository-wide reset when the exact affected paths are still uncertain.

3. Establish the Behavior Baseline

Run the smallest relevant checks before moving code. For a pnpm TypeScript project, that might look like:

pnpm test -- path/to/related-test
pnpm typecheck
pnpm lint -- path/to/large-file.ts

Use the commands documented by your repository. Record which checks pass, which fail, and whether each failure existed at the known-good commit.

If no useful test covers the file, add a characterization test around an observable public behavior before extracting anything. A characterization test captures what the code does now, including awkward behavior, so a later cleanup cannot silently change it.

Expected result: you have at least one fast check that fails when the behavior you are protecting changes. If the baseline is already red, do not ask the agent to "fix everything while refactoring." Isolate the pre-existing failure first.

4. Map Responsibilities Without Editing

Ask the agent for a read-only inventory. A useful prompt is:

Read path/to/large-file.ts and its direct tests. Do not edit files.
List the public entrypoints, state owners, side effects, external dependencies,
and groups of functions that change together. Propose the smallest first
extraction that preserves the current public API and behavior. Name the exact
tests that should prove the extraction is safe

For JavaScript or TypeScript, confirm the inventory with simple searches:

rg -n '^(export |class |function |const )' path/to/large-file.ts
rg -n '^(import |export .* from )' path/to/large-file.ts
rg -n 'path/to/large-file|LargeFileSymbol' path/to/tests path/to/src

Expected result: the proposed seam has one reason to change, a small dependency boundary, and an existing or newly added test. Good first seams are pure parsing, formatting, validation, or data transformation. Shared mutable state, orchestration, and I/O are usually safer to extract later.

5. Extract One Seam and Preserve the API

Give the agent one bounded change:

Extract only <named responsibility> from path/to/large-file.ts into
path/to/new-module.ts. Preserve every existing public export and runtime
behavior. Do not rename unrelated symbols, reformat unrelated code, add a new
dependency, or change business logic. Reuse the existing shared types instead
of copying them. Run <targeted test> and stop after reporting the diff

The old module should delegate to the new module until callers can migrate deliberately. That keeps the existing import path as the compatibility boundary and avoids changing implementation and consumers in one unreviewable step.

Review the extraction before starting another:

git diff --check
git diff --stat
git diff -- path/to/large-file.ts path/to/new-module.ts path/to/related-test.ts
pnpm test -- path/to/related-test
pnpm typecheck

Expected result: the diff removes one coherent responsibility from the large file, adds no second copy of a shared contract, and leaves the protected behavior green.

Commit that extraction separately on the recovery branch. A small commit is a rollback boundary and a review unit, not ceremony.

6. Repeat the Small Verification Loop

For each remaining responsibility:

  1. Select one seam.

  2. Name the behavior and test that protect it.

  3. Extract without changing behavior.

  4. Run the targeted test, type check, lint, and git diff --check.

  5. Review the diff before committing.

Run the broader test suite after several extractions and before merging. Stop when the remaining file has a coherent purpose. A file does not need to be short to be well designed, and an arbitrary line limit can create empty wrappers or circular dependencies.

7. Prevent the Next God File

Add repository instructions that describe boundaries and verification, not just a maximum line count. For example:

- Keep shared domain types in `src/domain/contracts.ts`; do not duplicate them.
- Change one responsibility per refactor commit.
- Preserve public exports while moving implementations.
- Run `pnpm test -- <target>` and `pnpm typecheck` after each extraction.
- Stop and report when the requested change requires an unrelated rewrite

Put these rules in the repository's AGENTS.md, CLAUDE.md, or equivalent instruction file. Also keep formatter, lint, dependency-cycle, and architecture checks executable so the agent receives deterministic feedback instead of prose alone.

Common Failure Modes

Failure

Why it is risky

Safer response

Ask the agent to rewrite all 10,000 lines

Behavior changes and moves become impossible to separate

Extract one tested responsibility

Revert the whole branch immediately

Useful work and forensic context may disappear

Preserve a branch and restore only proven bad paths

Split by line count

Related state and behavior can land in different modules

Split by responsibility and dependency direction

Change APIs during extraction

Call-site churn hides regressions

Keep a compatibility export or delegate first

Copy types into each new file

Multiple sources of truth drift

Import one shared contract

Add tests after the refactor

Tests may encode the new bug

Capture public behavior before moving code

Let formatting touch the whole file

Reviewers cannot see the semantic change

Format only edited files and inspect the diff

Keep prompting after a red check

The agent compounds an unknown failure

Stop, classify the failure, and restore the last green extraction

Why This Recovery Sequence Works

The checkpoint separates preservation from improvement. Characterization tests turn current behavior into evidence. Read-only mapping keeps the agent from changing code before it understands the dependency boundary. Small extractions reduce the number of simultaneous assumptions, while a stable public API keeps downstream changes out of the same diff.

This applies the useful structure behind Aident's Ollama networking guide: name the exact problem, answer early, give reproducible commands and expected results, distinguish similar failure states, and explain why the order matters. The guide's traffic does not prove this topic will perform the same way.

For related safeguards, see how to verify an AI coding agent's tests actually pass and how to stop Codex from deleting files.

Give Your Agent One Read-Only Review Task

Connect GitHub through Aident Loadout, then ask your agent to inspect the draft pull request containing the oversized file and return the three smallest behavior-preserving extraction seams. Require the response to cite the changed files and relevant tests, and tell it not to edit, approve, or merge anything. Success means you receive one evidence-backed extraction plan before another line changes.

Sources

Refresh this guide when Git recovery commands, coding-agent repository instructions, or the linked verification workflows change.

Home

Home

Home

Integrations

Integrations

Integrations

Vault

Vault

Vault

Audit

Audit

Audit

Arana Grande

Arana Grande

Arana Grande

Free

Free

Free

30-day audit summary

30-day audit summary

30-day audit summary

Daily action-call volume and the latest receipts from the Loadout audit trail.

Daily action-call volume and the latest receipts from the Loadout audit trail.

Daily action-call volume and the latest receipts from the Loadout audit trail.

View Audit

View Audit

View Audit

Loadout usage

Loadout usage

Loadout usage

617 action calls in the last 30 days

617 action calls in the last 30 days

617 action calls in the last 30 days

May 19 - Jun 17

May 19 - Jun 17

May 19 - Jun 17

10 active days

10 active days

10 active days

Less

Less

Less

More

More

More

Recent activity

Recent activity

Recent activity

Latest action-call receipts from connected agents

Latest action-call receipts from connected agents

Latest action-call receipts from connected agents

Apr 23, 09:23 AM

Apr 23, 09:23 AM

Apr 23, 09:23 AM

Shopify

Shopify

Shopify

Creates Or Updates An Asset For A Theme

Creates Or Updates An Asset For A Theme

Creates Or Updates An Asset For A Theme

Success

Success

Success

Apr 23, 09:21 AM

Apr 23, 09:21 AM

Apr 23, 09:21 AM

Shopify

Shopify

Shopify

Update Products Param Product Id

Update Products Param Product Id

Update Products Param Product Id

Success

Success

Success

Apr 23, 08:53 AM

Apr 23, 08:53 AM

Apr 23, 08:53 AM

Shopify

Shopify

Shopify

Update Products Param Product Id

Update Products Param Product Id

Update Products Param Product Id

Failed

Failed

Failed

Apr 22, 22:13 PM

Apr 22, 22:13 PM

Apr 22, 22:13 PM

Shopify

Shopify

Shopify

Create Product Image

Create Product Image

Create Product Image

Success

Success

Success

Apr 22, 22:12 PM

Apr 22, 22:12 PM

Apr 22, 22:12 PM

Shopify

Shopify

Shopify

Create Product Image

Create Product Image

Create Product Image

Success

Success

Success

Connected integration coverage

Connected integration coverage

Connected integration coverage

162

162

162

of 753 accessible connected

of 753 accessible connected

of 753 accessible connected

Callable actions

Callable actions

Callable actions

1,126

1,126

1,126

Vault credentials

Vault credentials

Vault credentials

8

8

8

Explore what's possible

Explore what's possible

Explore what's possible

See all Integrations

See all Integrations

See all Integrations

Google Ads

Google Ads

Google Ads

All available Goolge Ads tools via...

All available Goolge Ads tools via...

All available Goolge Ads tools via...

X (twitter)

X (twitter)

X (twitter)

All available X tools via...

All available X tools via...

All available X tools via...

Github

Github

Github

All available Github tools via...

All available Github tools via...

All available Github tools via...

Notion

Notion

Notion

All available Notion tools via...

All available Notion tools via...

All available Notion tools via...

Slack

Slack

Slack

All available Slack tools via...

All available Slack tools via...

All available Slack tools via...

Firecrawl

Firecrawl

Firecrawl

All available Firecrawl tools via...

All available Firecrawl tools via...

All available Firecrawl tools via...

753 integrations are available for loadouts.

753 integrations are available for loadouts.

753 integrations are available for loadouts.

Plug your entire stack into your AI agents.

Plug your entire stack into your AI agents.

Plug your entire stack into your AI agents.

Skip the integration headache. Plug 750+ tools into Claude Code, Codex, and OpenClaw in one go, and let your agents execute today.

Skip the integration headache. Plug 750+ tools into Claude Code, Codex, and OpenClaw in one go, and let your agents execute today.