Terminal AI Agent Implementation Guide: Architecture, Instruction Files, and Team Practices

    This article provides an actionable guide for deploying terminal AI agents in software development. It covers architecture design, permission boundaries, streaming output and resumability, tool selection, context instruction files, debugging loops, code review practices, and team workflows for multi-agent collaboration.

    Terminal AI agents are well-suited for tasks like code queries, batch modifications, and building and testing. However, because they can read/write files and execute commands, defining boundaries in the architecture design is the first priority. This guide provides actionable parameters, commands, and checklists structured by architecture, interaction, instruction files, debugging, review, and team workflows.

    Defining Agent Permission Boundaries

    An agent requires at least five components: the model invocation layer, tool layer, session layer, sandbox layer, and audit layer. The model only interacts with the external environment through the tool layer, and all tool calls are inspected by the sandbox layer.

    Confirm the following constraints before going live:

    • The working directory is restricted to the project root. Read/write paths must be normalized before comparison, and symbolic links pointing outside the root directory are rejected.
    • Commands use a whitelist. Initially, only read-only or test commands like git status, git diff, pytest, and make test are allowed.
    • Network access is disabled by default. When dependencies need to be installed, only domains pointing to the team’s internal artifact repository are permitted.
    • The following operations require manual confirmation: deleting files, git push, modifying CI configurations, executing database migrations, and accessing production environments.
    • The agent uses a dedicated account with write permissions only to feature branches and no direct push access to the main branch.

    Implementing Streaming Output and Resumability

    Server-Sent Events (SSE) is recommended for streaming output. It is a unidirectional text stream suitable for pushing model outputs to the terminal in segments. Each message includes an incrementing seq number, and the client records the last received number.

    Session state is saved in the .agent/sessions/<session_id>.json file within the project. Key fields include:

    • session_id: Unique session identifier.
    • step_id: Current step number, incrementing from 1.
    • status: Values can be running, waiting_confirm, done, failed, or unknown.
    • last_seq: The last message number acknowledged by the client.
    • pending_tool_call: Tool calls that have not yet returned results, including tool name, parameter summary, and idempotency key.

    The idempotency key is generated by concatenating session_id and step_id. Before executing a tool, check if the idempotency key already has a recorded result. If it does, return the original result directly without re-executing.

    When writing files, use a “temporary file plus atomic rename” approach. Calculate the SHA-256 of the target content before writing. If the hash of the file on disk matches the target, skip the write operation.

    Interruption recovery follows these rules:

    1. After a disconnection, the client reconnects with last_seq, and the server resends messages starting from the next one.
    2. If no heartbeat is received for over 60 seconds, the session is considered interrupted, and the status is marked as unknown.
    3. Tool calls with an unknown status are not retried automatically. First, perform read-only validation (e.g., comparing file hashes or checking git status) to confirm the actual result before deciding whether to continue or roll back.

    Every tool call is written to .agent/audit.log in JSON Lines format. Each line contains a timestamp, session ID, tool name, parameter hash, exit code, and duration. The log does not record environment variables, tokens, or full source code. Before writing, use regex to replace common secret formats, such as AKIA[0-9A-Z]{16} or ghp_[A-Za-z0-9]{36}, replacing matched content with ***.

    Selecting CLI vs. IDE Plugins

    The terminal form has the advantage of a simple permission model, easy log collection, and the ability to run in SSH and container environments. IDE plugins offer strong context awareness and intuitive interaction. The table below provides a qualitative comparison; specific metrics should be tested in the team’s environment.

    Dimension Terminal CLI IDE Plugin Web Chat
    Use Case Batch modifications, build/test, remote servers Single-file editing, instant completion Solution discussion, code explanation
    Permission Model Process-level, easy to whitelist Editor-dependent, weaker fine-grained control Usually no direct local file access
    Audit Capability Commands and outputs fully logged Requires editor event integration Relies on platform logs
    Offline Capability Depends on model deployment Same as CLI Usually requires internet
    Learning Curve Requires command/permission knowledge Quick to learn Lowest

    If the team requires strict auditing, prioritize the terminal form. If it is mainly for individual coding assistance, an IDE plugin is more appropriate.

    Terminal output verbosity needs active management. It is recommended to collapse tool outputs exceeding 20 lines by default, showing only the command, exit code, and the first three lines of results. Users can expand the full output via shortcuts supported by the tool (refer to the tool’s documentation for specific key bindings). At the end of each session, ask at most one feedback question, and allow this prompt to be disabled in the configuration.

    Writing Context Instruction Files

    Context instruction files inform the agent about the project’s tech stack, directory rules, and common commands. The filename is determined by the tool used; this article uses AGENTS.md as an example. Team-shared files should be placed in the repository root and version-controlled, while personal preferences go into .agent/local.md and are ignored from commits.

    A template for the team-shared file is as follows:

    1. # Project Context
    2. ## Tech Stack
    3. - Language: Python 3.10.x
    4. - Dependency Management: uv 0.4.x, lockfile is uv.lock
    5. - Testing Framework: pytest 8.x
    6. ## Directory Boundaries
    7. - Business Code: src/
    8. - Test Code: tests/, new features must include tests
    9. - Do Not Modify: published migration files in migrations/, vendor/, infra/prod/
    10. ## Common Commands
    11. - Install Dependencies: `uv sync`
    12. - Run Tests: `pytest tests/ -q`
    13. - Static Checks: `ruff check src tests`
    14. ## Commit Guidelines
    15. - Branch Name: feat/<ticket>, fix/<ticket>
    16. - Commit Message: One-line summary under 72 characters, explain motivation in the body
    17. - Agent-generated commits should add a trailer: `Generated-by: agent`
    18. ## Sensitive Files
    19. - Must not read or output: .env, *.pem, secrets/
    20. - Stop operation and notify the owner if a suspected secret is found
    21. ## Conflict Resolution
    22. - Team rules take precedence over personal rules
    23. - Personal preferences must not alter test commands, commit guidelines, or restricted paths

    The personal configuration file .agent/local.md can record editor preferences, local aliases, and personal habits. It must not override test commands and restricted paths defined in the team file.

    An example configuration for .gitignore is as follows:

    1. # Personal context and runtime data, do not commit
    2. .agent/local.md
    3. .agent/sessions/
    4. .agent/audit.log
    5. # Environment variables and secrets
    6. .env
    7. *.pem
    8. secrets/

    When writing and maintaining instruction files, check against this list:

    • Every rule can be verified by a command or file path.
    • Remove all ambiguous terms like “try to” or “appropriately” that cannot be evaluated.
    • Keep the file under 200 lines. Split excess content into docs/agent/ and link to it from the main file.
    • Review quarterly and delete outdated instructions. As model capabilities improve, some verbose step-by-step instructions can be replaced with goal descriptions.

    Validating the Debugging Loop

    The debugging loop consists of six steps: capture exceptions, correlate traces, reproduce, propose a hypothesis, verify the hypothesis, and fix/rollback. Each step must leave a verifiable record.

    Taking a memory leak as an example, here is a hypothetical verification process suitable for a Python service.

    Step 1: Fix a batch of requests. Use the same set of scripts to repeatedly send requests, keeping the quantity and order consistent per round (e.g., 2000 requests per round).

    Step 2: Record memory data. Use tracemalloc to capture allocation snapshots while recording the process resident memory:

    1. import tracemalloc
    2. tracemalloc.start(25)
    3. def run_batch():
    4. # Call the fixed batch of requests here, e.g., using a load testing script
    5. ...
    6. snapshots = []
    7. for _ in range(3):
    8. run_batch()
    9. snapshots.append(tracemalloc.take_snapshot())
    10. # Compare allocation differences between the first and third round, take top 10 growth locations
    11. for stat in snapshots[-1].compare_to(snapshots[0], "lineno")[:10]:
    12. print(stat)

    Process resident memory can be read using the following command (in KB):

    1. ps -o rss= -p <pid>

    Step 3: Determine suspicious conditions. The following two conditions must be met simultaneously to enter the fix phase:

    • After three rounds of requests, the allocation at the same code location increases round over round.
    • Process resident memory increases by more than 10% after three rounds.

    If only one condition is met, record it for observation and do not modify the code directly.

    Step 4: Propose a hypothesis and modify. The hypothesis should point to a specific code location (e.g., an unbounded cache, an unregistered callback). Before modifying, tag the current version, e.g., git tag pre-fix-<date>.

    Step 5: Verify the fix. Re-measure using the same three-round process. If resident memory growth is below 2% after three rounds and allocation hotspots no longer increase round over round, it is considered a pass.

    Step 6: Rollback plan. If the fix introduces anomalies, use git revert <commit> to revert. If the fix is behind a feature flag, simply turn off the flag. Keep snapshot files in .agent/sessions/ for retrospective analysis.

    Reviewing Agent-Generated Code

    Responsibility for agent-generated code lies with the submitter. The submitter must understand every change and be able to explain the design rationale. Reviewers focus on correctness, security, and rollback capability.

    The review checklist for pull requests is as follows:

    • The commit message includes the Generated-by: agent trailer for tracking and tracing.
    • Test results are attached, with test commands and output summaries written in the PR description.
    • If dependencies are modified, explain the purpose, version, and license of the new package.
    • If code or files are deleted, explain the reason and confirm no other modules reference them.
    • If data structures or migrations are involved, provide backward compatibility notes and an executable rollback script.
    • Ensure logs and error messages contain no user data, tokens, or internal addresses.
    • Explain the rollback method (e.g., a single git revert is sufficient, or a specific flag needs to be turned off).

    Boundaries for manual review: Changes involving authentication, authorization, payments, data deletion, and permission configurations must be reviewed by two members. Changes involving production configurations are not allowed to be merged directly by the agent.

    Team Workflows and Multi-Agent Collaboration

    Team rollout proceeds over four weeks, expanding permissions gradually:

    • Week 1: Read-only. The agent can query code and run tests but cannot write files.
    • Week 2: Write access to feature branches; all changes are merged manually.
    • Week 3: Introduce automated review. Review results serve as assistance and do not replace manual approval.
    • Week 4: Evaluate results and decide whether to expand scope. Evaluation metrics include pre-merge rework count, rollback count, and review time.

    For multi-agent collaboration, divide roles by responsibility (e.g., coding role, testing role, review role). Each role has an independent tool list. Roles hand off work via files (e.g., writing a test report to .agent/handoff/test-report.md) rather than sharing the same session. This allows role-by-role troubleshooting if issues arise.

    Evaluating Collaboration Skills in Interviews

    To assess agent collaboration skills during interviews, use the following scoring table, with a maximum score of 100:

    Dimension Assessment Point Score 5-Point Standard Example
    Instruction Building Can write clear, verifiable instructions 20 Instructions include input, output, constraints, and verification methods
    Task Breakdown Can decompose large tasks into checkable steps 20 Each step has clear completion criteria and marked dependencies
    Error Correction Can locate causes based on failure information 20 Reproduce before modifying, re-verify after fixing
    Code Judgment Can identify issues in generated code 25 Can point out boundary conditions, security risks, and test gaps
    Security Awareness Can proactively control permissions and sensitive data 15 Actively rejects unauthorized operations, does not leak secrets