
Summary
Key points of this document
- Balancing speed, inference volume, and quality with goal contracts, expert delegation, and validation gates.
Overview
Agent Harness Design with a High-Speed Lightweight Model as the Control Tower
Balancing speed, inference volume, and quality with goal contracts, expert delegation, and validation gates.
The quality of an AI agent is determined by both the model's inference capability and the execution platform that runs it. When entrusting coordination to a high-speed lightweight model, it is crucial to design a system that clearly defines goals and completion conditions, delegates specialized judgments, and controls progress based on inspection results. This article organizes this division of responsibilities into concrete contracts, state transitions, and validation gates.
1. What becomes a bottleneck when relying solely on a single model?
In building autonomous AI agents, a design that concentrates all responsibilities (requirements understanding, task decomposition, file traversal, code generation, self-verification, error correction) on a single model with high inference capability faces severe structural limitations as the scale of practical operation expands.
The first bottleneck is"Delays due to waiting for responses and sequential execution"High-capability models, while deep and sophisticated in their thinking, have high latency per turn. If tasks like investigating multiple independent files or routine build/type checks are processed serially within the same session, the total time required accumulates linearly.
The second bottleneck is"History bloat and context consumption"When command outputs and file contents accumulate in the same conversational context, it not only approaches the context length limit but also causes the model's attention to become scattered, leading to a decrease in adherence to initially provided constraints and goal definitions.
The third bottleneck is"Cost inefficiency and premature termination"This leads to a rapid increase in operational costs because expensive inference tokens continue to be consumed even for simple file traversals and routine transformations. Furthermore, models may overconfidently declare task completion without performing checks, or conversely, get caught in trivial corrections and fall into infinite loops.
| Failure Factor | Primary Occurrence | Impact |
|---|---|---|
| Accumulation of response waits | Sequential calls to high-capability models | Critical path lengthens, losing benefits of parallel processing |
| Attention Drift | Bloated conversation history | Forgetting initial constraints, rewriting unrelated existing code |
| Wasted inference costs | Routine syntax parsing and file traversal | Rapid increase in token consumption and API charges |
| Premature Completion (False Positive) | Model's own completion judgment | Mistaking incomplete work as finished |
2. Decisions entrusted to the model and conditions enforced by the harness
To overcome these limitations, the design of the agent harness (execution platform) strictly separates "cognitive judgments entrusted to the model" from "conditions deterministically enforced by the platform." The model is always the 'Proposer,' while the harness holds authority over execution permission, state transitions, and pass/fail judgments.
There is a clear boundary between deterministic workflows that follow fixed code paths and agent configurations where LLMs dynamically decompose and delegate tasks. Workflows are suitable when branching conditions are fully known, while agent configurations are suitable for unknown codebases and flexible interpretation of specifications. The goal is not to treat the complexity of the harness itself as an advantage, but to achieve harmony between model autonomy and safe constraints.
| Responsibility Area | Model (Proposer) Responsibilities | Harness (Execution Platform) Enforcements |
|---|---|---|
| Goal Understanding | Proposed requirement decomposition, dependency presentation | Goal Contract (GoalContract) registration and hash fixing |
| Task Execution | Code design/implementation within contract scope | Blocking writes outside permitted resources, validating authorization tokens |
| Budget/Cost | Proposal for necessary external tool calls | Pre-reservation of maximum billing amount (Worst-Case) and refusal of excess |
| Quality Assurance | Self-inspection results report | Independent execution of type checking, AST parsing, unit tests, and evidence preservation |
| Completion Judgment | Declaration of task completion | Verification of all local processes stopped and all required evidence PASS |
Paths where workers or models can independently relax budget limits or self-approve test results are physically excluded (Fail-Closed).
3. Transforming goals into verifiable contracts
The only way to prevent agent runaway or task omissions is to convert ambiguous natural language instructions into machine-verifiable "Goal Contracts" (GoalContract)." The contract is finalized as immutable data before work begins and will not be changed midway due to the model's own convenience.
A Goal Contract includes not only clear objectives (Objective) but also "Non-Goals" intentionally excluded from the scope of work, "Acceptance Criteria" for pass/fail judgment and their corresponding validator IDs, strict budget limits (Budget), and safe termination conditions.
export type Micros = string; // Decimal string representation of a non-negative integer (1 USD = 1,000,000 micros)
export type GoalContract = Readonly<{
id: string;
version: number;
objective: string;
nonGoals: readonly string[];
criteria: readonly Readonly<{
id: string;
statement: string;
verifierIds: readonly string[];
}>[];
policyId: string;
budgetMode: "StrictBudgetExecution";
limits: Readonly<{
deadlineUtc: string;
currency: "USD";
maxCostMicros: Micros;
maxModelCalls: number;
maxParallelWorkers: number;
maxRepairsPerTask: number;
maxRepairsPerRun: number;
}>;
}>;
export type TaskContract = Readonly<{
id: string;
goalDigest: string;
interfaceDigest: string;
baseRevision: string;
deadlineUtc: string;
dependsOn: readonly string[];
criterionIds: readonly string[];
readResources: readonly string[];
writeResources: readonly string[];
capabilityIds: readonly string[];
outputSchemaId: string;
workerRole: "implementation" | "specialist";
inheritedBudgetId: string;
}>;
export type Evidence = Readonly<{
runId: string;
attemptId: string;
epoch: number;
goalDigest: string;
interfaceDigest: string;
criterionId: string;
verifierId: string;
verifierDigest: string;
sourceRevision: string;
artifactDigest: string;
environmentDigest: string;
runnerId: string;
invocation: string;
startedAt: string;
finishedAt: string;
status: "PASS" | "FAIL" | "ERROR" | "SKIP" | "UNKNOWN";
logDigest: string;
}>;Structured data is normalized JSON according to RFC 8785, declaration files are saved in UTF-8/LF, and identified by SHA-256. Any shell string generated by the model is not executed directly but resolved to protected registered capabilities.
4. Overall Architecture of Thin Orchestrator
In the "Thin Orchestrator" architecture, the role of the fast and lightweight model acting as the command center is narrowed down to the minimum: "planning and delegation" and "result collection and reporting." Heavy file scanning, implementation, and deep debugging are offloaded to separate specialized workers, keeping the orchestrator's context always clean.
Process startup, HTTP external requests, model inference, and inspection execution all pass through the harness's centralized control plane. No unmanaged shell execution methods or raw billing credentials are ever directly granted to workers.
| Element | Responsibilities | Limitations |
|---|---|---|
| Lightweight Orchestrator | Decomposition proposals, delegation candidates, information selection, result organization | Cannot change permissions, budget, or acceptance criteria |
| Execution Control Platform | Proposal validation, state transitions, permissions, exclusive control, completion judgment | Does not guarantee sufficient understanding or decomposition of requirements |
| Budget Ledger / Authorization Gate | Reservation of maximum billing amount, enforcement of shared limits, pre-submission authorization | Does not authorize calls without external limit guarantees |
| Run Supervisor | Serialization of actual startup, interruption, resource tracking, termination confirmation | Does not infer remote process termination from connection disconnection |
| Stop Control Plane | Parallel notifications, deadline fixing, independent ACK collection | Do not confuse notification arrival with termination proof |
| Independent Watchdog | Forced termination due to absolute deadline / lease expiration | Cannot execute when OS or device itself stops |
| Specialized Worker | Investigation, design, and implementation within the contracted scope | Cannot give final approval to their own output |
| Validator / Independent Review | Inspection of fixed conditions and deliverables | Undefined defects and correlated judgment errors remain |
| Evidence Ledger | Preservation of target, environment, results, history | Does not indicate correctness beyond the scope of evidence |
| Reconciliation Process | Termination of external processing, impact, determination of usage/charges | Unconfirmable results remain as undetermined |
5. Fix the Delegation Contract before Starting Work
The biggest cause of failure in delegated multi-agent systems is interface discrepancies between workers. In this architecture, before starting implementation work, shared type definitions, semantic contracts, invariant conditions, and exception rules are completely fixed as TypeScript code.
Here, as a concrete example, we will use "a module that adds pagination functionality to TypeScript list processing." Tasks are divided among Worker A responsible for input validation, Worker B responsible for pagination calculation, and an integration specialist responsible for the public wrapper and integration, and changes to the shared contract are prohibited.
export type Result<T, E> =
| Readonly<{ ok: true; value: T }>
| Readonly<{ ok: false; error: E }>;
export type InputError =
| Readonly<{ code: "INVALID_INPUT"; field: "input" }>
| Readonly<{ code: "INVALID_ITEMS"; field: "items" }>
| Readonly<{ code: "INVALID_PAGE"; field: "page" }>
| Readonly<{ code: "INVALID_PAGE_SIZE"; field: "pageSize" }>;
export type UnexpectedError = Readonly<{
code: "UNEXPECTED";
incidentId: string;
}>;
export type PageError = InputError | UnexpectedError;
declare const validatedPageInput: unique symbol;
export type PageInput<T> = Readonly<{
items: readonly T[];
page: number;
pageSize: number;
[validatedPageInput]: true;
}>;
export type Page<T> = Readonly<{
items: readonly T[];
total: number;
page: number;
pageSize: number;
pageCount: number;
}>;
export declare function validatePageInput(
input: unknown
): Result<PageInput<unknown>, PageError>;
export declare function isPageInput(
input: unknown
): input is PageInput<unknown>;
export declare function paginateValidated<T>(
input: PageInput<T>
): Page<T>;
export declare function paginate(
input: unknown
): Result<Page<unknown>, PageError>;
export declare function paginateTyped<T>(
items: readonly T[],
page: number,
pageSize: number
): Result<Page<T>, PageError>;Page Calculation and Strict Boundary Value Specifications
Page numbers start from 1. Out-of-range pages are not treated as errors; instead, a successful result retaining the requested page number and an empty array are returned.
total = length of the array replicated during validation
pageCount = Math.ceil(total / pageSize)
page > pageCount:
items = new empty array
do not multiply the starting position
Otherwise:
start = (page - 1) * pageSize
end = Math.min(start + pageSize, total)
items = new shallow copy of [start, end)| Input | On success,value |
|---|---|
[], 1, 2 | {items: [], total: 0, page: 1, pageSize: 2, pageCount: 0} |
[], 2, 2 | {items: [], total: 0, page: 2, pageSize: 2, pageCount: 0} |
["a"], 1, 1 | {items: ["a"], total: 1, page: 1, pageSize: 1, pageCount: 1} |
["a","b","c"], 1, 2 | {items: ["a","b"], total: 3, page: 1, pageSize: 2, pageCount: 2} |
Same array,2, 2 | {items: ["c"], total: 3, page: 2, pageSize: 2, pageCount: 2} |
Same array,3, 2 | {items: [], total: 3, page: 3, pageSize: 2, pageCount: 2} |
["a","b","c","d"], 2, 2 | {items: ["c","d"], total: 4, page: 2, pageSize: 2, pageCount: 2} |
["a"], Number.MAX_SAFE_INTEGER, 100 | Success, empty array.total=1,pageCount=1, keeping the requested page number |
| Invalid input | Error code / Target field |
| --- | --- |
null, array, missing/excess keys | INVALID_INPUT / input |
| Not an array, sparse array, or index accessor | INVALID_ITEMS / items |
pageis 0, negative, decimal, string, NaN, infinity, or outside safe integer range | INVALID_PAGE / page |
pageSizeis 0, 101, negative, decimal, string, NaN, or infinity | INVALID_PAGE_SIZE / pageSize |
page=0andpageSize=0 | INVALID_PAGEreturned with priority |
| Exception during reflection processing | UNEXPECTED and incidentId |
6. Implementing Autonomous Continuation as a State Machine (Stop/Budget Guarantee)
Agent execution control is driven not by ad-hoc scripts, but by a strict 'State Machine'. It proceeds along two axes: business outcome (RunOutcome) and execution safety (ExecutionSafety), logically preventing processes that have reached a terminal state from improperly reverting to an executing state.
Stop Decision, Parallel Broadcast, ACK Separation
Serial designs that do not initiate suspension until all nodes' ACKs are received are strictly prohibited. Let the linearization point of the stop event be t0, and fix the common forced termination deadline D = t0 + 5,000ms (5 seconds).
Stop commands are issued to each node in parallel and asynchronously. Closure ACK collection and termination evidence collection are executed in parallel as independent observation tasks. Stopping processes on other nodes will not be blocked by waiting for a specific node's response.
t0 D = t0 + 5 seconds
│ │
├─ Node A: Closed → Interrupted → Terminated ─┤
├─ Node B: Closed → Interrupted───────┼─ SIGKILL to Liveness Management Unit
├─ Node C: Notification Not Delivered────────┤
│ │
└─ ACK collection and termination evidence collection continue independentlyWatchdog Independent of Notification Delay, Liveness Lease
Anticipating network delays in stop notifications themselves, all business processes, before starting, acquire a liveness lease with an absolute expiration date from an independent off-node Watchdog (RunLease) will be installed.
L (Lease validity period) + Maximum clock drift + Watchdog trigger delay ≦ 5,000msEven if a stop notification is not received, the Watchdog detects the absolute expiration of the lease, blocks the startup path, and forcibly terminates the entire cgroup/process (SIGKILL).
Worst-Case Reservation and Strict Budget Execution
Before actual transmission, the theoretical maximum billing amount for the entire lifetime is atomically reserved. Under-reservation based on average costs or stop expectations is prohibited.
B = Contractual budget ceiling
S = Total confirmed billing amount
R = Total reserved amount for unconfirmed operations and unused control slots
M = Maximum billing amount for new calls
Authorization condition: S + R + M ≤ BAdapters for which no upper limit enforcement settings or binding fee agreements can be confirmed on the external service side,StrictBudgetExecution will be immediately rejected (zero transmissions) before invocation.
export type Micros = string;
export type CostBound = Readonly<{
quoteId: string;
adapterId: string;
modelId: string | null;
pricingDigest: string;
payloadDigest: string;
currency: "USD";
authorizeBeforeUtc: string;
dimensions: readonly Readonly<{
id: string;
unit: string;
maxQuantity: number;
rateNumeratorMicros: Micros; // bigint calculation with decimal string, non-negative integer
rateDenominator: string; // bigint calculation with decimal string, positive integer
}>[];
fixedMaxMicros: Micros;
feeMaxMicros: Micros;
roundingAllowanceMicros: Micros;
maxCostMicros: Micros;
externalEnforcementDigest: string;
}>;7. Combine Deterministic Inspection with Independent Review
Quality assurance is achieved not by relying on the LLM's own subjective self-evaluation, but through a dual structure of "deterministic machine inspection gates" and "third-party review by isolated independent sessions."
Code and test scripts generated by workers are executed as 'untrusted code' in a sandbox environment. If the test execution process itself hangs or leaves behind child processes, completion will not be acknowledged even if the inspection result is PASS.
| Quality Gate | Subject of Confirmation and Inspection Method | Behavior upon Failure |
|---|---|---|
| JSON Schema | Conformity of input/output data format, type, and value range constraints | Pre-invocation blocking (Fail-Closed) |
| Relational Integrity | Inconsistencies in Task ID, Dependency DAG, Resource Allocation Range | Reversion to Planning Phase |
| Type/Linter/AST | TypeScript compiler (strict), forbidden syntax, negative diff inspection | Correction loop as immediate compilation error |
| Unit/Acceptance Testing | Boundary values, exception conversion, non-destructive snapshot behavior | Retry within correction budget limit |
| Integration/Browser Validation | Integration integrity of multiple modules, actual SSR/DOM operation | Integration discard and re-validation in new epoch |
| Independent Review | Audit of design validity, omissions, and over-correction by third-party models | Organize findings and issue correction tasks |
| Final Reconciliation | Contract, artifact SHA-256, environment digest, actual completion evidence | If inconsistent, reject completion and transition to Stopping |
8. Prevent Concurrent Work Conflicts and Self-Approval (Disjoint File Ownership)
When multiple workers make code changes in parallel, the most critical obstacle is conflicts due to simultaneous writes to the same file. In this harness, "Disjoint File Ownership" is assigned to each task before work begins, and writes outside the assigned scope are blocked at the file system level.
Ownership is granted with a monotonically increasing fencing token and an expiration date, eliminating delayed writes by older generation workers. The deliverables of each worker are submitted from their individual working environments to the integration manager, and a comprehensive inspection is performed after serial merging.
- Fix shared contracts, then parallelize independent scopes.
- Separate working environments and exclusive write scopes.
- Do not grant duplicate write permissions to the same logical resource.
- Ownership leases should have an expiration and a monotonically increasing fencing number.
- Only the integration manager writes to the integration area.
- Reviewers check fixed deliverables in read-only mode.
- Even if files are separated, semantic consistency is checked after integration.
9. Where to Increase Inference and Conditions for Switching Delegation Targets
Allocating inference resources equally to all tasks is highly inefficient. We implement "appropriate inference allocation" by assigning fast, lightweight models to routine implementations based on clear type contracts, and deploying specialized models with high inference capabilities for architectural design, derivation of complex boundary values, and difficult debugging.
At the same time, if corrections for the same error cause fail twice in a row, or if ambiguity in preconditions is discovered, we choose to escalate to a higher-level model or immediately stop (Fail-Closed) before repeating meaningless retries.
| Situation/Task Nature | Inference Model Selection Policy | Escalation/Control Action |
|---|---|---|
| Clear Type Contracts and Boilerplate Modifications | High-speed lightweight models (e.g., Gemini 3.8 Flash) | Parallel Fan-Out execution in minimum turns |
| Implementation of Multiple Independent Modules | Parallel deployment of lightweight models | Simultaneous activation within shared budget () |
| Overall Design / Tightly Coupled Changes | High-intelligence models (e.g., Codex Sol / GPT 6) | Delegate to specialized models from the decomposition stage for pre-drafting |
| Repeated Failure of the Same Test (2 times) | Switch to specialized debugging model | Generate investigation tasks for insufficient information, or stop |
| Significant Ambiguity in Requirements / Completion Conditions | Stop model inference | Prohibit arbitrary implementation, escalate to human |
| External Billing Limit Guarantee Unknown | Adapter execution denied | Blocked with zero transmissions by StrictBudgetExecution |
10. How to Measure Speed, Inference Volume, and Quality
To verify the true effectiveness of a multi-agent harness, it is necessary to eliminate the qualitative impression that "the model worked well" and quantitatively evaluate it using an engineering and objective set of metrics.
This harness strictly defines 14 metrics, including not only the success rate but also the "miscompletion rate (the proportion of tasks incorrectly reported as complete despite being failures)," "actual time taken to stop," and "undetermined billing amount."
| Metric Name | Definition and Formula | Evaluation Focus |
|---|---|---|
| 1. Success Rate | Number of executions that passed all acceptance criteria in independent evaluation / Total number of executions | Strict pass rate without relaxation or skipping midway |
| 2. Error Rate in Completion Reports | Number of failures reported as complete / Number of completion reports | Detect agent overconfidence / self-approval omissions |
| 3. Miscompletion Rate in All Executions | Number of failures reported as complete / Total number of executions | Overall system reliability (lower is better) |
| 4. Time to Termination | p50/p95 from request reception to termination (Success/Stop/Timeout) | Promptness of stop/timeout processing |
| 5. Time to Success | Time distribution of successful cases | Always evaluate in conjunction with success rate |
| 6. Model Usage | Input, output, cache, inference token usage | Actual consumption per model |
| 7. Cost Per Successful Item | Total cost including failures, retries, and stop verifications / Number of successful executions | True cost efficiency in development and operations |
| 8. Human Intervention Burden | Total time required for human investigation, correction, and recovery | Practical evaluation of labor saving and autonomy |
| 9. Execution Breakdown Time | Time for adjustment, model waiting, tools, inspection, review, and queue | Identification of bottleneck processes |
| 10. Required Stop Time | From stop decision to all forced terminations and termination evidence confirmation | Physically verify compliance with the 5-second limit |
| 11. Classification of Missed Deadlines | Delivery delay, Watchdog failure, OS failure, unconfirmed termination | Engineering isolation of failure points |
| 12. Ratio of Undetermined Operations | Number of external operations in In-Doubt state and reserved commitment amount | Resilience to external service failures |
| 13. Budget Commitment Status | Trends in confirmed amount, unconfirmed reservations, control limits, and available amount | Integrity of budget ledger |
| 14. Post-Stop Consumption Amount | Confirmed charges and unconfirmed reservation amounts after stop decision | Verification of stop leaks |
11. Identify necessary mechanisms through comparative experiments
To prove whether each component of the agent harness (contract fixing, parallel stopping, maximum amount reservation, independent review) truly contributes to quality and speed, we design controlled comparative experiments using the same task set and evaluator.
In the experiment, we prepare five variations from a single model configuration to a full harness configuration, and through ablation (gradual removal of components) experiments, we objectively isolate which safety mechanism prevents which defect.
| Comparative Configuration | Features and Architecture | Expected Benefits | Main Challenges/Overheads |
|---|---|---|---|
| A. Single High-Capability Model | Execute all processes in series in a single session | Contextual continuity, less design deviation | Prolonged execution waiting, distraction due to history bloat |
| B. Lightweight Model Centric | Process all steps with a single high-speed model | High responsiveness, low token unit cost | Task decomposition failure, lax self-verification, incorrect completion |
| C. Lightweight Model + Harness | Control lightweight model with state machine and inspection gates | Prevention of procedural omissions, reliable enforcement of stops/budgets | Infrastructure implementation cost, burden of deterministic test setup |
| D. Lightweight Model + Expert Worker + Harness | Coordination of command tower, expert workers, and independent review | Optimal allocation of inference by difficulty, time reduction through parallelization | Module handover, conflicts during integration |
| E. High-Capability Model + Same Harness | Integrate high-intelligence model into execution control platform | Achieving both extremely high first-pass accuracy and strict safety | Increased execution cost, reduced speed due to over-engineering |
We fully align initial states, requirements specifications, permitted tools, safety constraints, and evaluators, then randomize the execution order to conduct paired comparisons. Timeouts and stops are not excluded from the population, and objective confidence intervals are measured.
12. Conditions under which this configuration is suitable and unsuitable
This architecture is not a silver bullet for all software development tasks. Introducing a harness, fixing contracts, and conducting independent verification come with certain overheads. Appropriate adoption decisions must be made based on system characteristics and requirements.
While it is extremely effective for tasks where acceptance criteria can be strictly defined as code or tests, and for the development of independent modules that greatly benefit from parallelization, it is more rational to choose a simpler configuration for exploratory prototyping or early phases with fluid requirements.
| Conditions strongly recommending adoption | Conditions to avoid or simplify adoption |
|---|---|
| Input/output types, boundary values, and acceptance criteria can be mechanically defined | Correctness criteria depend on human perception or preference, untestable |
| Target files for modification can be divided into multiple independent areas | A single tightly coupled file needs to be incrementally rewritten by everyone |
| Strict control over costs and safety of external service calls is desired | Personal use where upper limit management of token consumption or API costs is not required |
| Operationally essential to issue forced termination within a common 5-second limit and independently collect termination evidence | Local, disposable execution of a single script |
The completion status indicates that mandatory inspections have passed for a fixed contract and environment, the actual processing under management has finished, and external impacts and final charges have been determined. The suspension deadline is enforced by an independent watchdog and execution environment that satisfies the pre-contract. A strict budget cap is maintained by authorizing only calls where the external party guarantees the total billing limit and by pre-reserving that maximum amount. It does not indicate the absence of unknown defects, nor a physical halt where the device or OS itself is not functioning.


