Agent Harness Architecture: From a Minimal Loop to Permission Governance

    This article explains how to build a reliable runtime environment, or agent harness, for models that perform coding tasks. It covers the five core components of a harness, a minimal Python agent loop with command allowlisting and output truncation, task dependency and context management, multi-agent isolation with git worktrees, permission governance and security boundaries, a recommended directory layout, CI checks, common pitfalls, and a suggested implementation order.

    1. Key Takeaways and Scope

    Some observers argue that in the future, a single person will be able to run a large number of businesses whose work is performed by agents. That claim currently lacks sufficient public data to support it; real-world results depend on the industry, task complexity, and team size. This article does not discuss that prediction. It addresses one concrete question: how to build a runtime environment in which a model can complete coding tasks reliably.

    This environment is commonly called an agent harness. Its job is to provide tools, knowledge, context management, and permission boundaries. The model handles reasoning and decisions; the harness enforces the constraints of the execution environment. If you write a large number of rules into the workflow from the start, the model’s decision space shrinks and the system becomes harder to maintain. A better approach is to build a minimal working version first, then add capabilities based on real needs.

    2. The Five Components of a Harness

    This article uses the following formula to describe the core elements of a harness. It is a design model meant to make discussion easier, not an industry standard.

    Harness = Tools + Knowledge + Observation + Action Interfaces + Permissions

    Component Responsibility Typical implementation Notes
    Tools Let the model read and write files, execute commands, and search code Command execution, file I/O, Glob, Grep Every tool needs a timeout and an output-length limit
    Knowledge Provide domain background and project conventions Skill files loaded on demand, project documentation Load only what the current task needs to avoid filling the context
    Observation Return environment feedback to the model Standard output, error output, exit codes, compiler reports Truncate feedback and keep the key lines, or it will flood the context
    Action Interfaces Define the format of model output and validate it before execution Tool definitions with typed parameters, JSON validation On validation failure, return an error so the model can retry; do not execute directly
    Permissions Limit what the model can do Command allowlists, path restrictions, human confirmation Deny by default; grant only the permissions a task explicitly needs

    Observation and Action Interfaces are easy to confuse. The former describes how execution results return to the model; the latter describes how the model’s instructions enter the system. They sit at opposite ends of the loop and should be designed separately.

    3. The Minimal Agent Loop

    The agent loop is a cycle of perception, reasoning, and action. The example below keeps only the core logic and works well as a starting point. It targets Python 3.10 or later and uses only the standard library. The example assumes llm is a function that takes a message list and tool definitions and returns a dictionary containing either text content or a tool call.

    1. import shlex
    2. import subprocess
    3. from pathlib import Path
    4. WORKDIR = Path("./workspace").resolve()
    5. ALLOWED_CMDS = {"ls", "cat", "grep", "python3"} # command allowlist
    6. MAX_STEPS = 20 # prevent infinite loops
    7. MAX_OUTPUT = 4000 # output length limit for observations
    8. def run_shell(cmd: str, timeout: int = 30) -> str:
    9. try:
    10. argv = shlex.split(cmd) # do not use shell=True; avoids injection
    11. except ValueError as e:
    12. return f"Command parsing failed: {e}"
    13. if not argv or argv[0] not in ALLOWED_CMDS:
    14. return "Execution denied: command is not on the allowlist"
    15. try:
    16. r = subprocess.run(argv, capture_output=True, text=True,
    17. timeout=timeout, cwd=WORKDIR)
    18. except subprocess.TimeoutExpired:
    19. return "Execution timed out and was terminated"
    20. return f"exit_code={r.returncode}\n" + (r.stdout + r.stderr)[:MAX_OUTPUT]
    21. TOOLS = {"run_shell": run_shell}
    22. def agent_loop(task: str, llm, tool_schemas) -> str:
    23. messages = [{"role": "user", "content": task}]
    24. for _ in range(MAX_STEPS):
    25. reply = llm(messages, tools=tool_schemas)
    26. messages.append(reply)
    27. call = reply.get("tool_call")
    28. if call is None: # the model stopped calling tools; treat as done
    29. return reply["content"]
    30. name, args = call["name"], call.get("arguments", {})
    31. fn = TOOLS.get(name)
    32. result = fn(**args) if fn else f"Unknown tool: {name}"
    33. messages.append({"role": "tool", "content": result})
    34. raise RuntimeError("Reached the maximum number of steps without completing the task")

    This code includes several important safeguards. Commands are parsed with shlex.split and passed to subprocess as a list, so model output is never concatenated into a shell string and command injection cannot be triggered. Every execution has a timeout. Output is truncated so a single command cannot fill the context. The step limit guarantees that the loop terminates.

    Failure handling follows one principle: error messages should go back to the model so it can adjust its strategy, rather than crashing the program or silently skipping the step.

    4. Task Dependencies and Context Management

    Complex tasks need a task graph. Each subtask records the other tasks it depends on, and it enters the execution queue only after all dependencies are complete. The task graph can be stored as a JSON file, which makes recovery and debugging easier.

    Context grows longer with each step. There are three common approaches. First, compress earlier tool output into a one-line summary. Second, write long-lived facts to a separate memory file that is read at the start of each session. Third, load Skill files on demand, adding the relevant instructions to the context only when a task involves a particular framework.

    5. Multi-Agent and Worktree Isolation

    When multiple agents modify the same codebase at the same time, file conflicts are the most likely problem. One approach is to create a separate git worktree for each subtask, let each one modify its own branch, and merge when the work is done.

    1. git worktree add ../wt-task-1 -b task/1 # create a worktree and branch for subtask 1
    2. git worktree add ../wt-task-2 -b task/2
    3. # after subtasks complete, switch back to the main branch and merge one by one
    4. git merge task/1
    5. git merge task/2 # stop on conflict and hand it to a human
    6. git worktree remove ../wt-task-1

    Messages between sub-agents should go through an asynchronous mailbox. Each message includes the sender, receiver, task ID, type, and payload. The receiver sets a timeout; if it expires, the message is resent once, and if that also fails, the main agent is notified and decides whether to reassign the task or mark it as failed.

    Worktree isolation only resolves conflicts at the file level, not logical conflicts. Two subtasks may have modified the same interface under different assumptions, and merging can still produce errors. Tests must therefore be run after merging.

    6. Permission Governance and Security Boundaries

    Permissions are the part of the harness that needs the most careful design. The following should be treated as default constraints.

    1. Least privilege. Each task gets only the tools and paths it needs. Directories for reading and writing should be listed explicitly.
    2. Command allowlist. Deny all commands by default and allow only the ones explicitly listed.
    3. Human confirmation. Operations such as deleting files, pushing code, deploying services, and changing permissions must be confirmed by a human and cannot be decided by the model alone.
    4. Sandboxed execution. Run untrusted code in a container or virtual machine with network access disabled by default and with memory and CPU limits.
    5. Audit logs. Write one line of JSON for every tool call, including the time, tool name, parameter summary, and result status, so the history can be traced later.
    6. Secret management. Keep API keys and database passwords only in environment variables or a secret management service; never write them into code, prompts, or logs.
    7. Rollback and backups. Create a branch or tag before making changes. Back up data before running database migrations and verify that the backup can be restored.
    1. harness-kit/
    2. ├── core/ agent loop, tool dispatch, permission checks (Python)
    3. ├── docs/ mental-model documentation, in English and Chinese
    4. ├── web/ task graph visualization and debugging panel (frontend)
    5. ├── skills/ Skill files loaded on demand, one subdirectory per skill
    6. ├── examples/ step-by-step examples from minimal loop to full implementation
    7. └── .github/workflows/ continuous integration configuration

    Each directory should have a single responsibility. Core logic should not depend on the frontend, Skill files should not contain executable code, and example code should not reference private modules outside of core.

    8. Continuous Integration Checks

    Continuous integration should run on every push to the main branch and on every pull request, with the following steps.

    1. Type checking, for example mypy on the core directory.
    2. Code style checks, for example ruff.
    3. Unit tests, focusing on the command allowlist, timeout handling, and output truncation.
    4. Building the frontend project to confirm it packages correctly.

    Permission-related code must have corresponding tests. For example, commands outside the allowlist should be rejected, and strings containing semicolons or pipes should not be executed as multiple commands.

    9. Common Mistakes

    • No timeouts, so processes started by the model hang for a long time.
    • Tool output is not truncated, and the context exceeds the window after a few rounds.
    • Model output is concatenated directly into a shell string, causing command injection.
    • Permission scope is too broad, and the model can delete files outside the project.
    • Multiple sub-agents modify the same file, and the conflict is discovered only at merge time.
    • No step limit, so the model gets stuck repeatedly calling the same tool.

    When troubleshooting, start with the audit log to confirm which tools the model actually called and what parameters it passed, then determine whether the problem lies in the prompt, the tool definitions, or the permission configuration.

    10. Suggested Order of Implementation

    Start by implementing the agent loop, two tools, and a command allowlist, and run a small task through the full flow. Then add timeouts, output truncation, and audit logging. When tasks genuinely need parallelism, introduce worktree isolation and the asynchronous mailbox. Finally, add Skill loading and the visualization panel. Following this order, each step can be verified independently, and problems are easier to locate when something goes wrong.