Architecture & Internals¶
This page covers the internal subsystems inside core/ that form the harness chassis around AgentLoop.
1. The Agent Loop (core/loop.py)¶
AgentLoop implements a minimal (~40 LOC of core logic) Thought → Action → Observation cycle:
- Build messages from
Memory(applying proactive compaction when needed). - Call
Model.generate(messages, tool_schemas). - Execute returned
ToolCallitems throughToolRegistry.dispatch(...)(in parallel forparallel_safe=Truetools, sequentially otherwise). - Append tool outputs to
Memoryand continue until the model returns a final response with no tool calls (or callsfinishwhenrequire_finish_tool=True).
AgentLoop knows nothing about Docker, benchmarks, configuration cascades, or UI frontends.
2. Environments, Sandboxing & Permissions (core/environment.py)¶
microharness isolates execution through the Environment abstraction:
- In-Place Workspace (default): Operates directly on
workspace_dirwhile preventing path traversal outside the repository (except authorized read-only global directories such as~/.microharness/skills/). - Disposable Sandbox (
--sandbox): Copies the project into an isolated run directory under~/.microharness/runs/<run_id>/while still discovering project.microharness/settings cleanly. - Docker Container (
--docker): Hybrid I/O mounts the workspace at/workspace—file reads/writes/edits occur directly on the host with zero latency whilebashruns inside an isolated Linux container (docker exec) with optional--docker-network,--docker-memory,--docker-cpus, and--docker-pids-limitbounds, plus automatic container teardown. - Permission Guardrails (
GuardedEnvironment): auto(default): Executes workspace tools automatically.ask: Prompts before mutating tools (bash,write_file,edit_file,code_mode, non-read-only MCP tools).read-only(aliasro): Blocks all file-modifying tools,bash, andcode_mode.
3. Built-in Tools, Editing & Log Spillover (core/tools.py, core/editing.py)¶
| Tool | parallel_safe |
modifies_files |
Purpose |
|---|---|---|---|
bash |
false |
true |
Execute shell commands with combined stdout/stderr and configurable timeout |
read_file |
true |
false |
Read file contents with optional line ranges |
write_file |
false |
true |
Create or overwrite files |
edit_file |
false |
true |
Atomic multi-hunk edits: [{old_str, new_str}, ...] replacement with all-or-nothing rollback |
grep |
true |
false |
Fast regex/text search (enabled by default in explore/reviewer or via --inspection-tools) |
glob |
true |
false |
Pattern file matching with {a,b} brace expansion |
git_read |
true |
false |
Read-only git inspection (status, diff, log, show) |
finish |
false |
false |
Explicit completion signal when require_finish_tool=True |
Massive Output Truncation & Spillover¶
When a tool output exceeds max_tool_tokens (default 8000 in core/defaults.json):
ToolRegistrykeeps the head + tail within budget (1/3head +2/3tail).- The complete raw output is spilled to
~/.microharness/runs/<run_id>/logs/so the project workspace stays clean. - The model receives the exact spilled log path so it can inspect specific line ranges with
read_fileon demand.
Tool Schema Minimalism (edit_file, --no-tool-docs, --inspection-tools)¶
Tool schemas directly shape model behavior and prompt cost:
- Focused
edit_file(path, edits)schema: Retaining legacy optionalold_str/new_strfields causedhy4-flashto emit0/116multi-hunk calls onkoota; requiringedits=[...]flipped adoption to50%(26/52calls), cuttingedit_filecalls by55.2%and total steps by35.9%. - Lean main-agent loop: Keeping
grep,glob, andgit_readopt-in onbash-capable main agents (--inspection-tools) while omitting redundant prose tool manuals (--no-tool-docs) reducedMini-SWEprompt tokens by59.6%(227,974 -> 92,155).
4. KV-Cache-Friendly Memory Compaction (core/memory.py)¶
Memory tracks estimated and provider-reported prompt_tokens against the active model's context window:
- Immutable Prefix Until 80% (
trigger_ratio = 0.80): Earlier turns are never mutated before the compaction threshold. Keeping the prefix byte-identical preserves provider KV prefix caching across turns (routinely yielding 80%+ cached prompt tokens). - Proactive Compaction: At 80% utilization,
Memorypreserves the system prompt, initial task, and recent working turns (keep_recent_turns = 4), collapses older tool outputs into enriched tombstones referencing their spilled log files, strips transient<think>...</think>/<thinking>...</thinking>blocks from older assistant turns, and maintains a[Session Files Modified: ...]ledger. - Deterministic Tombstoning vs. LLM Summarization: Compaction collapses old observations deterministically in
<1msfor$0rather than calling an LLM summarizer—avoiding round-trip latency and preventing summarized paraphrases from hallucinating file paths, flags, or error offsets when raw logs remain on disk. - Multimodal Image Budget & Compaction Safety: Multimodal
Messageparts (image_urldata URIs / HTTP URLs) are estimated usingimage_token_estimate(1024tokens per image incore/defaults.json) rather than raw base64 string length, and both compaction tombstones andTracerexports (trace.json,trajectory.jsonl,trace.md) redact base64 payloads down to concise[image: <mime>, <size>]metadata.
5. Prompt Caching Economics (5m vs 1h vs off)¶
Prompt cache strategies are configured declaratively per provider in core/providers.json (anthropic_block, gateway_auto, openai_breakpoint, implicit, none):
5m(default): Standard ephemeral cache TTL—ideal for interactive sessions and fast agent loops.1h: Extended cache TTL—useful when human think-time or long benchmark pauses exceed 5 minutes.off: Disables explicit cache breakpoints.
Switch live during a session with /cache [5m|1h|off] or at startup via --cache-ttl.
- Break-Even Math (
5mvs.1h): An extended1hcache write costs a0.75xupfront premium over5m(2.00x - 1.25xbase input rate), while a cached keep-alive ping (max_tokens=1) costs0.10x. Dividing0.75 / 0.10 = 7.5 pingsmeans periodic5mheartbeats stay cheaper than switching to1hfor up to7–8intervals (~34–35minutes of continuous pauses). - Gateway Replicas & Subagent Wait Latency: Even with a 100% byte-identical prompt prefix, multi-replica API gateways can drop cache hits across replicas compared to direct single-replica endpoints (
64.9%vs.86.0%–99.0%). Likewise, synchronous subagent or command waits longer than 5 minutes will evict the parent's5mKV cache before the next parent step.
6. Lifecycle Hooks (core/hooks.py)¶
HookRegistry fires structured events across every turn and step:
pre_turn → pre_step → pre_tool → post_tool → post_step → post_turn
Two built-in hooks are registered automatically (disable via disabled_hooks or include_default_hooks=False):
python_syntax_diagnostics: Runsast.parseafter.pyedits (write_file/edit_file) and feeds syntax errors immediately back to the agent.doom_loop_detection: Detects repeated identical tool-call cycles (doom_loop_threshold = 3) and nudges or stops runaway loops (DOOM_LOOP).
Command hooks and Python hook objects can also be configured in config.json (project command hooks require --trust-project-tools).
7. Checkpoints (/undo) & Tracing (core/checkpoints.py, core/tracer.py)¶
- Pre-Turn Checkpoints: Before each interactive turn,
CheckpointManagercaptures lightweight workspace state (via isolatedgit write-treewith a temporaryGIT_INDEX_FILEin git repos, or scoped file backups outside git). Running/undoreverts workspace edits and memory to the pre-turn checkpoint without touchingHEADor git branches. - Session Tracing: Every run writes machine-readable
trace.json, human-readabletrace.md, andpatch.diff(in git repos) inside~/.microharness/runs/<run_id>/.