Understanding the Harness Architecture and Execution Loop of AI Coding Tools
This article explains how AI coding tools divide responsibilities between the language model and the surrounding Harness layer. It follows a typical CLI-to-tool execution path, covering routing, session persistence, command security, source-code review, and Python-to-Rust migration. The examples are illustrative rather than taken from any specific product or repository.
Understanding the Harness Architecture and Execution Loop of AI Coding Tools
This article uses a general architecture as an example and does not target any specific product. The directory tree and code samples are illustrative. They explain how responsibilities may be divided and do not represent source code from a real project.
1. Separate the Responsibilities of the Model and the Harness
The behavior of an AI coding tool is determined by two components.
The model interprets requirements, plans steps, and generates code. The surrounding shell, commonly called the Harness, receives input, selects tools, controls the number of iterations, stores state, and returns execution results to the model.
The Harness determines the system’s lower bound. It affects whether data is lost, whether the process can enter an infinite loop, and whether execution can resume after an interruption. The model determines the upper bound, including whether it can understand complex requirements and produce a correct patch.
When reading the source code, examine these two parts separately:
- Code that decides what to do next generally belongs to the model-calling layer.
- Code that reads or writes files, starts processes, or saves sessions belongs to the Harness.
- Harness behavior can usually be validated with tests, making it easier to verify than model output.
A typical dependency map looks like this:
| Capability | Main dependency | Typical failure mode |
|---|---|---|
| Traversing project directories and reading files | Harness | Path traversal or access to unintended files |
| Modifying files | Model plus Harness | Patch does not match the original file or overwrites another change |
| Executing shell commands | Harness | Command injection, long-running processes, or accidental data deletion |
| Parsing test and build logs | Model | Context truncation caused by oversized logs or incorrect error attribution |
| Maintaining context across multiple turns | Harness | Corrupted session files or lost history |
2. Verify the Project’s Origin Before Reading the Source
The origin of an open-source repository directly affects how much confidence you should place in its behavior. Before reviewing the code, verify:
- Whether the repository is an official project or a third-party reimplementation based on public information.
- Which license it uses and whether that license fits your use case.
- Which commit you are reviewing, since behavior may differ significantly between commits.
The following commands provide a quick check:
git clone <repository-url>cd <project-directory>git log --oneline | head -5head -n 5 LICENSE
If the README only says that the project was “inspired by” or “based on” another tool, but provides no commit history or tests, its conclusions should be treated as a description of that repository only. They should not be generalized to other tools.
3. From the CLI Entry Point to Execution
A typical Python project may have a structure like this:
project/├── src/│ ├── main.py # CLI entry point and argument parsing│ ├── router.py # Selects candidate tools based on input│ ├── session.py # Session state and usage tracking│ ├── transcript.py # Records each input and output│ └── tools/ # Implementations of individual tools├── tests/ # Tests for routing, sessions, and tools└── README.md
When reading the code, start with main.py and follow the call chain:
main() → parse arguments → load or create a session → run_prompt() → select a tool through routing → execute the tool → write the record → save the session
The following example is illustrative and shows the responsibility of each step. The line marked as the “actual execution point” is the one that can directly affect files or the system.
MAX_TURNS = 8 # Maximum number of turns to prevent infinite loopsdef main(argv):args = parse_args(argv)session = load_session(args.session_id) if args.session_id else new_session()return run_prompt(args.prompt, session)def run_prompt(prompt, session):if session.turns >= MAX_TURNS:raise RuntimeError("Maximum turn limit reached; stopping execution")candidates = route(prompt, session.tool_registry)if not candidates:return reply_without_tool(prompt, session)tool = candidates[0]result = tool.run(prompt, session.context) # Actual execution pointsession.turns += 1session.transcript.append({"role": "tool", "name": tool.name, "output": result.text})save_session(session)return result.text
When reviewing this code, check three points:
- Is the turn limit checked before execution?
- If a tool fails, is the failure recorded while keeping the session consistent?
- Is the session saved after tool execution?
If these conditions are not met, recovery after an interruption may fail.
4. Routing: Benefits and Limits of Lightweight Matching
Many projects do not call a model for routing. Instead, they use simple keyword matching. An illustrative implementation might look like this:
def route(prompt, registry):tokens = set(tokenize(prompt))scored = []for tool in registry:overlap = len(tokens & set(tool.keywords))if overlap > 0:scored.append((overlap, tool))scored.sort(key=lambda item: -item[0])return [tool for _, tool in scored]
This approach is fast, predictable, and easy to test. Its limitations are also clear. Synonyms, omitted subjects, and mixed-language expressions may fail to match. If two tools receive the same score, the result depends on their registration order, which can make behavior unstable.
When reviewing the router, prepare a fixed set of input examples and record which tool is selected for each one. The set should include:
- Positive examples
- Negative examples
- Ambiguous inputs
Place these examples in tests/ and rerun them whenever the routing rules change.
5. Persisting Sessions and Transcripts
A session commonly contains historical messages, usage counters, tool configuration, and the current turn count. A transcript records the input and output of each step for auditing and troubleshooting.
A common persistence problem occurs when the program exits while a file is only partially written, leaving a corrupted session file. The following approach writes to a temporary file first and then atomically replaces the original:
import jsonimport osimport tempfiledef save_session(session, path):directory = os.path.dirname(path) or "."fd, tmp_path = tempfile.mkstemp(dir=directory)with os.fdopen(fd, "w", encoding="utf-8") as f:json.dump(session.to_dict(), f, ensure_ascii=False)os.replace(tmp_path, path) # Atomic on the same filesystem
Transcripts may contain secrets, tokens, or sensitive fragments of user code. Sensitive data should be redacted before writing, for example by filtering common secret formats with regular expressions. Otherwise, the transcript itself can become a source of data leakage.
Context windows are limited. As a session grows, more content must be sent to the model. Some frameworks generate a summary after the context exceeds a threshold and replace earlier history with that summary. When reviewing this logic, verify that important constraints are preserved, including operations the user explicitly prohibited.
6. Security Boundaries for Command Execution
Shell execution is one of the highest-risk parts of an AI coding tool. Common isolation strategies involve different trade-offs:
| Approach | Isolation strength | Resource overhead | Implementation complexity | Suitable scenario |
|---|---|---|---|---|
| Regular subprocess with an allowlist | Low | Low | Low | Trusted local projects |
| System call filtering | Medium | Low | Medium | Restricting network and file access |
| Containers | Medium to high | Medium | Medium | Shared environments or batch execution |
| Virtual machines | High | High | High | Running untrusted code |
Regardless of the chosen approach, follow these rules:
- Pass arguments as a list instead of concatenating model output into a shell command string.
- Set a timeout to prevent commands from hanging.
- Run with the minimum required privileges and avoid administrator accounts.
- Record every command and its exit code.
import subprocessdef run_command(argv, cwd, timeout=30):return subprocess.run(argv,cwd=cwd,capture_output=True,text=True,timeout=timeout,check=False,)
This pattern prevents some injection issues, but it does not limit what the command itself can do. If commands such as rm or network requests are allowed, an additional isolation layer is still required.
7. Defining the Boundary When Migrating from Python to Rust
Some projects first build a Python skeleton to validate the logic and later rewrite the production runtime in Rust. Not every component needs to be rewritten during the migration.
| Module | Recommendation | Reason |
|---|---|---|
| Routing rules | Keep them in Python until the behavior is stable, then migrate | Rules change frequently, and Python is cheaper to modify |
| Session and transcript formats | Migrate after the format is stable and preserve compatibility | Existing session files must remain readable |
| Command execution | Prioritize migration | It defines a security boundary and is well suited to a memory-safe language |
| Test cases | Keep all of them | They provide a basis for behavioral consistency between versions |
Migration should be triggered by measurable conditions, such as profiling showing that a module is a bottleneck or a requirement to distribute a single executable. “Rust is faster” is not, by itself, sufficient justification.
To verify that the migration succeeded, perform two checks:
- Run both versions with the same input samples and compare their transcript outputs.
- Benchmark both versions with identical inputs, reporting median and 95th-percentile latency along with memory usage.
Performance claims should not be included in documentation without measurements.
8. Capability and Boundary Checklist
After reviewing the source code, document the following boundaries clearly:
- The Harness does not determine the model’s reasoning quality. It can only limit the impact of errors.
- Keyword-based routing can misclassify requests, so test cases are needed to reveal problems over time.
- Context windows are limited. Long-running tasks depend on summaries, and summaries may lose important constraints.
- Turn limits and timeouts determine how long a task can run. The behavior after a limit is reached must be verified separately.
- Without network isolation, commands may send code or data to external systems.
- Session and transcript files may contain sensitive information and require access controls and periodic cleanup.
9. Recommended Source-Reading Order
A practical review sequence is:
- Verify the repository origin, license, and commit version.
- Find the CLI entry point and list all commands and arguments.
- Inspect the routing logic and run the existing tests.
- Check turn limits, timeouts, and error handling.
- Review how sessions are saved and verify whether writes are atomic.
- Inspect command isolation and privilege settings.
- Review test coverage and identify behaviors that are not verified.
Following this sequence helps you determine whether a project’s execution path is reliable and how far it is from being production-ready.
