AI Agent Tool Orchestration with Scripts: Why a Four-Line Script Can Edit the Wrong File

    AI agents can search, edit, and run commands, but scripted tool orchestration moves control flow ahead of execution and can silently collapse an important choice into a hardcoded index. This article walks through a real failure case where three retry policies shared the same default value, explains how a four-line orchestration script works, and covers the three main pitfalls: ambiguous candidates, zero matches versus wrong paths, and overly literal replacements. It closes with decision criteria and a practical checklist for deciding when to fix logic in a script and when to hand the decision back to the model.

    1. A Real Failure: The Right Line, the Wrong File

    Imagine a repository with three retry policies serving the payment flow, message delivery, and background sync jobs. All three happen to share the same default maximum attempt count: 3. A product manager asks for a simple change: raise the payment maximum from 3 to 5, then run the relevant tests.

    Hand this task to an AI coding tool with file search, text editing, and command execution, and the path of least resistance is obvious: search the whole repository for the keyword, get a list of candidate files, pick one, make the edit, and run the tests. The problem is in “pick one.” The first search result is the message delivery module. It also contains a maxAttempts: 3, so the replacement succeeds and the diff is a clean single line with a single number changed. The tests may even pass, because they never cover the payment path. Back in the payment service, the bug is still there.

    This is not the model being “dumb.” Once the choice is fixed in advance, the basis for choosing is compressed into an implicit rule: take the first one. The real question is: when should the candidate set be handed to the model for judgment, and when should a script decide on its own?

    2. Four Lines of Script: Writing “the Next Step” Before Execution Starts

    A recent version of an AI coding tool introduced an experimental execution mode: instead of calling tools one at a time, the model writes a short script and the runtime chains search, edit, and test into a single run. The official example looks roughly like this (illustrative code, function names are pseudocode):

    1. const files = await search(`rg -l "function retryPolicy" src`).text();
    2. const target = files.trim().split("\n")[0];
    3. await edit(target, "maxAttempts: 3", "maxAttempts: 5");
    4. ({ edited: target, tests: await run(`npm test -- retryPolicy`).nothrow() });

    The information in these four lines concentrates at the end of the second line: the [0]. The first line returns a newline-separated list of paths. The second splits on newlines and takes index 0. That path is never sent back to the model; it goes straight into the edit tool. After the edit, the script continues to the tests and finally packages the path and test output back to the model.

    Compared with the normal mode, the difference is not “can it be done” but “who decides, and when”:

    • Normal mode: search results return to the model → the model reasons → it chooses the next tool and parameters. Every step pushes intermediate artifacts into the context and requires a fresh decision sample.
    • Script mode: control flow is fixed before the search runs → intermediate artifacts flow inside the runtime → the model reads the summary only once at the end.

    The payoff is lower context usage and fewer round trips, especially when intermediate artifacts are large (hundreds of file paths, long test logs), because the model does not have to pull that noise into its window. The cost is equally clear: any branch that needs to “see the intermediate result before deciding” is quietly replaced by a hardcoded [0].

    3. Ambiguity, Zero Matches, and Exit Codes: Three Easy Traps

    3.1 Ambiguous Candidates Are Silently Resolved

    The payment incident above is fundamentally an identifiability problem: three policies share the same default value, and plain text matching cannot distinguish which one belongs to which business. The safer approach is to hand the candidates back to the model together with their call sites and let it read downward from “the line of code that initiates the payment,” which usually rules out the other two. If payment and background jobs share the same policy, the next question is whether the limit can be overridden only for this payment request instead of changing the global default.

    As an engineering fallback: let the script collect, not choose.

    1. const hits = (await search(`rg -l "maxAttempts:\\s*3" src`).text())
    2. .trim().split("\n").filter(Boolean);
    3. if (hits.length !== 1) return { needDecision: true, candidates: hits };

    Returning to the model whenever the hit count is not 1 makes ambiguity explicit instead of letting index order make a business decision for you.

    3.2 Zero Matches Look Exactly Like a Wrong Path

    Neither case shows a filename on screen, but the two failures return different exit codes: when there is genuinely no match, the search command returns a “no match” style exit code; when the directory or pattern is wrong, it returns a different error code. If the script only checks whether stdout is empty, it will mistake a configuration error for “this thing does not exist in the code” and conclude that no change is needed.

    So the script must explicitly distinguish three states: exactly one hit, multiple hits, and the command itself failing. Convenient patterns like .nothrow(), which keep the script running despite a non-zero exit code, also erase the failure signal. Whether the tests actually ran and actually passed needs to be parsed separately from the exit code and output, not assumed to be successful.

    3.3 Replacement Semantics Are Too Literal

    edit(target, "maxAttempts: 3", "maxAttempts: 5") is a string-level replacement. If the same fragment appears more than once in a file (for example, a default value and an expected value in a test case), you either change too much or change it in the wrong place. A more robust approach is to add a context anchor or use a structured edit:

    1. await edit(target,
    2. "export const paymentRetry = { maxAttempts: 3 }",
    3. "export const paymentRetry = { maxAttempts: 5 }");

    4. Decision Criteria: When to Fix a Script and When to Return to the Model

    Three questions are enough for a quick decision:

    1. Does the intermediate result require semantic judgment? If yes, return it to the model; purely mechanical pass-through can be fixed in the script.
    2. Can failure be tolerated silently? If not, exit codes and empty results must be handled explicitly.
    3. Is the change reversible and verifiable? It must come with diff review and targeted tests, and the tests must actually cover the changed path; otherwise “tests pass” is just a placebo.

    A middle ground is “script collects + model decides + script executes”: first run a read-only search and summarize the candidates with their call sites, then after the model selects a single target, generate a second script to perform the edit and verification. This keeps the context advantage without giving up semantic review.

    5. Implementation Checklist

    • Add business anchors during search (module name, caller, full config key) to reduce collisions when the same value appears in multiple places.
    • Stop and return candidates when the hit count is not 1; never default to the first item.
    • Distinguish “no match,” “wrong path,” and “insufficient permissions,” and give readable diagnostics for each.
    • Use context anchors or structured rewrites for edits; avoid bare string replacement.
    • Establish a traceable mapping between test selection and the changed file, and verify the exit code.
    • Keep the full diff for human review, and run the experimental execution mode only on a branch or a workspace copy by default.

    The value of scripted tool orchestration is handing the deterministic parts to the runtime and leaving the parts that need judgment to a human or the model. The four lines are worth reading not because they are short, but because they compress a choice that should have been explicit into a single [0] — see that compression point, and you see the full boundary of the risks and benefits of this pattern.