Agent Collaboration Under Attention Constraints: A Test-Driven Development Playbook

    This article explains how to coordinate multiple AI agents in software development when their attention is constrained by limited input capacity, competing task information, and drift over long execution chains. It presents a closed-loop workflow that connects requirements and acceptance criteria, planning, review, layered rule loading, context management, test-driven implementation, deterministic checks, and integration evaluation. You will learn how to build traceable process data, define acceptance before implementation, turn review comments into explicit decisions, organize project rules through progressive disclosure, manage working context without deleting facts, converge collaboration around test evidence, enforce safety baselines with deterministic hooks, optimize for total task cost, and troubleshoot common failure modes. The goal is not more agents generating code in parallel, but giving every step clear boundaries, reliable evidence, and a recoverable path.

    1. Understanding Agent Collaboration Through Attention Constraints

    When agents take part in software development, the common problem is not a lack of code-generation ability. It is the inability to keep attention on the constraint that matters most at the current moment: requirements change while the old plan stays in context; multiple agents edit a shared module and their interface assumptions diverge; tests are already failing while the executor keeps adding features; long discussion histories crowd out the input space, diluting the information that actually drives decisions.

    Here, “attention constraints” is an engineering-level description. It mainly refers to limited model input capacity, competition among task-relevant information, and the tendency of long execution chains to drift from the goal. It does not mean developers can directly control the model’s internal attention weights. What you can actually control is the input content, the order of information, task boundaries, feedback frequency, and external execution permissions.

    So the optimization goal should not be merely to make agents “read more and write faster.” It should be to establish a closed loop:

    Requirements and acceptance criteria → task planning → review and correction → layered rule loading → context organization → test-driven implementation → deterministic validation → integration evaluation.

    These stages are not a one-time pipeline. A test failure may require replanning, an interface change may require reloading rules, and an integration conflict may require adjusting collaboration boundaries.

    2. Building a Traceable Foundation From Process Data

    Without process data, a team can only judge whether agents are efficient by intuition. It is worth building a minimal traceable record around each task, linking requirements, decisions, changes, and validation.

    Data category Suggested content to record Main purpose
    Task information Task ID, goal, scope, acceptance criteria Prevent execution drift
    Planning information Subtasks, dependencies, risks, edit boundaries Support coordinated scheduling
    Decision information Points of dispute, revision comments, confirmed conclusions Reduce repeated discussion
    Change information Modified files, interface changes, impact scope Support review and rollback
    Validation information Test results, failure reasons, execution environment Judge result credibility
    Resource information Call counts, input/output volume, elapsed time Analyze cost and bottlenecks

    Process data should follow the principle of minimal necessity. Logs should not indiscriminately store complete business data, secrets, or sensitive user information; when analysis genuinely requires it, data should be desensitized first and access should be restricted.

    You should also distinguish between “the agent claims it is done” and “the execution system confirms it is done.” For example, “tests pass” must correspond to a real test run record, not merely a generated text summary. When execution capability is missing, it should be explicitly marked as “pending validation,” and speculation must not be treated as a result.

    3. Planning Phase: Define Acceptance First, Then Assign Implementation

    The primary work of planning is to turn a vague requirement into verifiable behavior, not to immediately list the files that need changing.

    Take the “task status statistics” example from process data. The requirement might simply be “add task completion statistics.” This description still leaves many things undetermined:

    • Which statuses count as completed?
    • Do cancelled tasks enter the denominator of the statistics?
    • With empty data, should it return zero, a null value, or an error?
    • How should unknown statuses be handled?
    • Is the result affected by a time range?

    If these questions are left to the coding phase, the agent will easily fill in the business semantics on its own. A more reasonable approach is to form an acceptance table first, then decide the implementation route.

    Planning should include at least four elements:

    1. Target behavior: What observable result the system should present.
    2. Task boundary: Which modules may be modified, and what is out of scope for this requirement.
    3. Dependencies: Which interfaces or rules must be confirmed first.
    4. Validation method: Which tests or checks prove the target is implemented.

    For multi-agent collaboration, prefer dividing tasks along relatively independent modules or work products, such as rule analysis, implementation, test supplementation, and review. Separating roles helps reduce blind spots, but it does not guarantee that judgments are independent, so objective validation is still needed.

    For shared files, designate a single writer responsible for them, with other participants collaborating through change suggestions. For tasks with dependencies, settle the interface contract first and then implement in parallel, so that different executors do not each derive different data formats.

    4. The Comment Loop: Turning Review Feedback Into Explicit Decisions

    After planning, set up a short-cycle review and correction process. Here, comments are not only source-code comments but also structured feedback on the plan, interfaces, and test approach.

    Effective feedback should contain three parts:

    • Problem location: Which item of the plan or constraint has an issue.
    • Problem rationale: Why it creates risk.
    • Suggested action: What exactly needs to be added, changed, or confirmed.

    For example, “the approach is not thorough enough” cannot guide execution, whereas “the return value for an empty task set is undefined; first decide whether the completion rate is zero or statistically meaningless, and add tests accordingly” directly drives a decision.

    The review loop should also have an exit condition. Confirmed comments enter the decision record, unconfirmed issues remain as blockers, and suggestions beyond the current scope move to follow-up tasks. Do not let the agent handle confirmed requirements, exploratory suggestions, and historical arguments in the same execution round, or goal drift is likely.

    The comment loop is not better with more iterations. For low-risk, easily reversible local changes, a brief review is fine; for permission, data-consistency, and cross-module interface changes, raise the review intensity.

    5. Layered Instructions: Reducing Rule Noise With Progressive Disclosure

    Project rules are best organized in layers rather than crammed into one huge instruction file.

    Project-level rules keep only content that is long-term stable and broadly applicable, such as security boundaries, testing requirements, no-edit zones, and completion standards.

    Module-level rules describe local constraints, such as the status semantics of a data-processing module, the consistency requirements of a persistence module, and the compatibility principles of an interface module.

    Task-level material holds the current requirement, acceptance criteria, open questions, and related files.

    Progressive disclosure means first providing the minimum information needed to complete the current task, then adding detail according to the modules the task touches. It is not about hiding important constraints: security, permission, and irreversible-operation rules must take effect before the relevant action happens.

    Note that rule files themselves are only information carriers. Whether the execution system loads them automatically, when it loads them, and how it handles conflicts must be implemented explicitly by the actual workflow; you cannot assume that a document with any given name will be automatically recognized by the agent.

    When rules conflict, establish a priority and escalation mechanism. For example, task instructions must not bypass security limits; if a business requirement conflicts with a module constraint, pause the relevant change and request confirmation rather than picking one interpretation on your own.

    6. Context Management: Clearing Working Memory, Not Deleting Facts

    The goal of context management is to let the next decision quickly find the currently valid information. It does not mean deleting project documentation or clearing audit records.

    It helps to divide information into three categories:

    • Currently required information: Acceptance criteria, interface contracts, the failure being handled.
    • Retrievable on demand: Full design documents, historical test records, other modules’ material.
    • Invalidated information: Rejected implementation routes, already-resolved errors, outdated assumptions.

    After each verifiable stage, you can generate a short status summary:

    1. Task: Add task completion-rate statistics
    2. Confirmed: Cancelled tasks are excluded from the denominator
    3. Done: Status-classification logic and its tests
    4. Current issue: The handling rule for unknown statuses is not yet confirmed
    5. Validation status: Local tests executed; full regression pending
    6. Next step: Confirm the invalid-input strategy, then finish interface integration

    The summary should keep source clues so executors can trace back to the real code, requirements, and test records. Otherwise, omissions during compression can gradually turn into new false facts.

    Error logs should also be curated selectively: keep the failure location, key assertions, the necessary call chain, and reproduction conditions, without repeatedly feeding in large amounts of irrelevant success logs. If an error may be environment-related, keep the relevant environment differences too, and do not delete diagnostic evidence just to shorten the context.

    7. Test-Driven Development: Converging Collaboration Around Evidence

    The core of test-driven development is a short feedback loop: first describe the expected behavior, observe the test fail because the target behavior is missing, then implement the minimal change that satisfies the requirement, and finally refactor under the protection of tests.

    1. First verify the tests actually express the requirement

    In the task-statistics example, you can first define the following illustrative tests:

    1. Test: All valid tasks are completed
    2. Input: Two completed tasks
    3. Expected: Completion rate is one hundred percent
    4. Test: A cancelled task is present
    5. Input: One completed task, one cancelled task
    6. Expected: The cancelled task is excluded per the confirmed rule
    7. Test: No valid tasks exist
    8. Input: Empty set
    9. Expected: Follow the previously defined empty-data semantics

    The above is only an illustration of test structure and does not correspond to any specific language or test tool.

    The first failure must relate to the missing target functionality. If the failure comes from a missing dependency, an undiscovered test, or a misconfigured run, fix the validation environment first instead of jumping straight into implementation.

    2. Use a minimal implementation for clear feedback

    Agents tend to casually add caching, abstraction layers, and extra parameters. The test-driven flow requires completing the necessary behavior first, reducing the number of variables introduced at once.

    Only consider refactoring after tests pass, and rerun the relevant tests afterward. If you need to change a test assertion, explain whether the requirement changed, the original test was wrong, or the implementation exposed a new boundary condition. Do not silently loosen assertions just to get a passing result.

    3. Share the test contract across multiple agents

    The test owner and the implementation owner should share the acceptance criteria. For high-risk logic, add an independent review to check whether the tests only cover paths that are easy for the implementer to satisfy.

    Passing tests does not mean absolute correctness. Beyond local tests, add interface integration, boundary inputs, exception recovery, and necessary end-to-end validation according to the impact scope.

    8. Hook-Based Guardrails: Handing Critical Baselines to Deterministic Rules

    Natural-language instructions are good at explaining goals but not suited to carrying safety defenses alone. For limits that must be obeyed, use deterministic mechanisms such as execution-entry checks, change checks, and pre-commit validation.

    Rules well suited to machine enforcement include:

    • Blocking reads or writes of sensitive credentials;
    • Restricting the edit scope and protecting critical configuration;
    • Requiring extra confirmation for high-risk operations such as deletion and large-scale rewrites;
    • Checking whether new changes come with the necessary tests;
    • Verifying before delivery that the required checks actually passed.

    These mechanisms should be implemented by the execution system, not left to the model remembering rules. The check scripts themselves can also be wrong, so they need tests, permission isolation, and audit records.

    When network access, production-data writes, or external publishing are involved, follow the principle of least privilege and provide preview, confirmation, and rollback mechanisms wherever possible. Deterministic guardrails can shrink the risk surface, but they cannot replace runtime-environment isolation, nor can they guarantee detection of every business-logic defect.

    9. Cost Optimization: Compare Total Task Cost, Not Per-Call Price

    Cost optimization should be measured per deliverable result. A single call may be cheap, but if it causes more rework, repeated context input, and manual review, the total cost can still be higher.

    A possible accounting approach:

    Total task cost = model-call cost + validation-execution cost + rework cost + manual-review cost.

    Model-call cost should be recorded based on actual usage and the applicable billing method, not by applying an unconfirmed fixed rule.

    Model selection should combine task difficulty and risk: clearly structured organizing work can use a lower-resource option; cross-module reasoning, complex fault localization, and high-risk changes need stronger analytical ability and stricter validation. Whether switching is worthwhile should be evaluated with representative tasks, not judged only by output length.

    Parallel collaboration also has costs. When tasks are independent, parallelism may shorten waiting time; with heavy shared context and frequent edits to the same module, coordination and conflict handling may cancel out the gains. Improve task division first, then increase the degree of parallelism.

    10. Common Failures and Troubleshooting Order

    1. The agent repeatedly forgets constraints

    First check whether the constraints are too long, mutually contradictory, or not loaded at the relevant stage. Trim high-frequency rules into clear items and add execution checks for critical baselines, rather than continuously appending repeated reminders.

    2. Tests pass, but the delivered behavior is still wrong

    Check whether the tests cover the real acceptance criteria, whether cross-module impact is missed, and whether overly simplified data is used. Also confirm the test run targets the actual delivered version, not old code or a local substitute implementation.

    3. Multiple agents overwrite each other’s changes

    Check file ownership, interface contracts, and integration order. You can narrow the edit scope of parallel tasks, use isolated working copies, and review changes together at the integration stage. For shared modules that change frequently, temporarily switching to serial edits is often safer.

    4. Judgment is distorted after context compression

    Check whether the summary omits open questions, writes speculation as conclusions, or preserves validation status. On recovery, trace back to the original requirements, code, and execution logs rather than continuing to reason from an incorrect summary.

    5. Guardrail checks cause persistent blocking

    Distinguish false positives from real violations. A false positive needs the rule fixed and rule tests added; a real violation needs the execution approach changed. When an exception is truly needed, use controlled approval and keep the rationale, and never let the executor simply switch off the guardrail.

    11. Continuous Improvement With Feedback Data

    After the process is in place, keep observing metrics such as the first-pass acceptance rate, rollback rate, number of repeated failures, number of integration conflicts, volume of repeated context input, and total cost per task. Metrics must have a consistent definition and be interpreted together with task size and risk.

    For example, the first-pass acceptance rate can be calculated as “number of tasks that meet the agreed acceptance criteria without rework / number of accepted tasks.” But if tasks are split too finely, the metric may improve while overall delivery does not, so it should be combined with the delivery time and defect analysis of complete requirements.

    A generally effective optimization order is: first clarify acceptance criteria, then reduce context noise, then establish tests and execution guardrails, and finally adjust model selection and the degree of parallelism. The value of agent collaboration lies not in having more executors generate code simultaneously, but in giving every step clear boundaries, reliable evidence, and a recoverable path.