AI Coding Agents in the Terminal: Engineering Practices for Long-Running Tasks
This article examines the engineering practices behind agentic coding tools that operate directly in the terminal. It covers the shift from code completion to autonomous execution, the core loop of planning-acting-observing, verifiable exit conditions, retrieval quality, permission controls, remote triggering, and budget management for long-running tasks.
From Code Completion to Autonomous Execution
Coding assistance tools have evolved through roughly three stages. The first stage is line-level or function-level code completion, where the tool predicts the next snippet of text and the developer confirms each suggestion. The second stage is conversational assistants, where developers paste code into a chat interface and manually copy results back into the project. The third stage is autonomous execution—often referred to as agentic development environments. These tools run in the terminal or a local workspace, where developers describe a goal in natural language and the tool breaks down the task, reads files, modifies code, executes commands, and adjusts course based on the results.
The key distinction lies in control. Traditional IDEs are human-driven: every action is initiated by a person. Autonomous execution tools, by contrast, continuously run a loop: plan, act, observe, correct—until the termination condition is met. Evaluating such tools therefore requires more than checking whether a single response is correct; the entire loop must reliably converge to an acceptable result.
The Core Execution Loop
A typical execution loop consists of five stages:
- Intent understanding: Convert the natural language request into an executable goal description, enriched with project context such as language version, directory structure, and test entry points.
- Task planning: Break the goal into discrete steps, each with clear inputs and expected outputs. The plan should be visible and editable so developers can correct course before execution begins.
- Tool invocation: Read files, search code, edit content, execute commands, and run tests through controlled interfaces. Every invocation should record its parameters and return values.
- Result observation: Parse command output, error messages, and test reports to determine whether the current step achieved its expected outcome.
- Correction or termination: If the step failed, generate a fix plan and retry. If all acceptance criteria are met, end the task and produce a change summary.
The following pseudocode illustrates the control flow; it does not map to any specific implementation:
function run_task(goal, tools, max_steps):context = load_project_context()plan = make_plan(goal, context)for step in plan:for attempt in 1..max_retry:if context.steps >= max_steps:return report_stopped(step, context)action = decide_action(step, context)if action is high_risk:require_human_approval(action)result = tools.execute(action)context.append(action, result)if check_step_done(step, result):breakelse:return report_failure(step, context)return verify_acceptance(goal, context)
The max_steps variable caps the total number of invocations. Without such a limit, the loop can exhaust resources on failing paths.
Verifiable Exit Conditions: The Key to Long-Running Tasks
Long-running agentic tasks share a common failure mode: the agent reports completion when the goal has not actually been achieved. This usually happens for one of two reasons. First, a check happens to pass incidentally, such as a flaky test succeeding once. Second, the agent modifies the check itself, for instance by relaxing an assertion or inserting a fixed-duration wait to mask a race condition.
Acceptance criteria should therefore be written as executable gates, not natural language descriptions. A reliable gate has three characteristics: results are reproducible, the verdict does not depend on the agent’s own statements, and the gate checks whether the changes take shortcuts.
Consider fixing a flaky test as an example. The gate can require the test to pass multiple consecutive times, forbid changes to assertions, and scan newly added code for fixed-duration waits. The pseudocode below illustrates this:
function accept_flaky_fix(test_cmd, n = 20):for i in 1..n:code = run(test_cmd)if code != 0:return reject("run " + i + " failed")diff = get_change_set()if diff.touches_test_assertions():return reject("test assertions modified")if diff.adds_fixed_delay():return reject("fixed-duration delay added")return accept()
The gate’s verdict should be produced by a program and accompanied by evidence, such as failure logs or diff excerpts. This allows a human reviewer to quickly verify the outcome without re-reading the entire execution trace.
Retrieval Quality Determines the Ceiling of Agent Capability
An agent’s accuracy largely depends on whether it can find the right context within the codebase. Three common retrieval approaches are used, each with trade-offs:
| Dimension | Text Retrieval | Symbol Retrieval | Semantic Retrieval |
|---|---|---|---|
| Precision | High, matches literal content | High, based on definitions and references | Medium, depends on vector similarity |
| Speed | Fast | Medium, requires index building | Depends on index scale |
| Typical Use | Finding function names, error messages | Refactoring, cross-file changes | Finding code by functional description |
| Main Risk | False matches from identical names | Limited language support | Unstable identifier matching |
In practice, the three are usually combined. Text retrieval handles quick location, symbol retrieval confirms structural relationships, and semantic retrieval is useful for exploring unfamiliar code.
Several engineering details also significantly affect effectiveness. First, retrieval should respect the project’s ignore rules so that dependency directories and build artifacts do not drown out results. Second, returned content should be size-limited so it does not consume too much of the model’s context window. Third, the agent should log which files it read, so reviewers can trace what informed its decisions.
Permissions and Security Boundaries
Autonomous tools can modify files and execute commands, so security design should follow the principle of least privilege. Specific controls include:
- Command whitelist: Only reversible operations such as builds, tests, and format checks are allowed by default. Commands that delete files, publish releases, or change permissions require human approval.
- Workspace sandbox: Write access is restricted to a designated workspace directory. Paths outside the workspace are blocked.
- Credential management: Secrets are injected through environment variables or a secret service, never written into config files or logs. Network proxy settings and connection parameters should likewise be read from the environment, not hardcoded in the project.
- Injection defense: Code comments, documentation, or web content may contain instructional text. The agent should treat such content as data, not as operational directives.
- Audit trail: Every tool invocation records a parameter summary, execution result, and approver, enabling post-hoc traceability.
Remote Triggering and Asynchronous Collaboration
Some teams want to trigger tasks from a mobile phone or messaging app and check progress later. This model is convenient, but it requires additional design.
First is identity binding. The messaging channel account must be tied to the team account, and high-risk commands require a second confirmation step to prevent accidental triggers. Second is terminal isolation. The remote end should only send instructions and receive status updates—it should not directly forward a raw command-line session, which would effectively expose the terminal to the messaging channel. Third is progress notification. Alerts should cover plan generation, failed retries, pending approvals, and task completion, not just start and finish messages. Finally, interruption and resumption should be supported. Tasks should support pause and cancel, with context snapshots saved so execution can continue later.
Cost and Budget Control
Agentic loops repeatedly invoke models, and cost grows with the number of steps and context length. The following practices help keep spending in check:
- Set a token or cost cap per task. When the cap is reached, pause and request confirmation before continuing.
- Only place the code fragments relevant to the current step into the context, and periodically compress older
