Skip to content

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:

  1. Build messages from Memory (applying proactive compaction when needed).
  2. Call Model.generate(messages, tool_schemas).
  3. Execute returned ToolCall items through ToolRegistry.dispatch(...) (in parallel for parallel_safe=True tools, sequentially otherwise).
  4. Append tool outputs to Memory and continue until the model returns a final response with no tool calls (or calls finish when require_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_dir while 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 while bash runs inside an isolated Linux container (docker exec) with optional --docker-network, --docker-memory, --docker-cpus, and --docker-pids-limit bounds, 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 (alias ro): Blocks all file-modifying tools, bash, and code_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):

  1. ToolRegistry keeps the head + tail within budget (1/3 head + 2/3 tail).
  2. The complete raw output is spilled to ~/.microharness/runs/<run_id>/logs/ so the project workspace stays clean.
  3. The model receives the exact spilled log path so it can inspect specific line ranges with read_file on 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 optional old_str/new_str fields caused hy4-flash to emit 0/116 multi-hunk calls on koota; requiring edits=[...] flipped adoption to 50% (26/52 calls), cutting edit_file calls by 55.2% and total steps by 35.9%.
  • Lean main-agent loop: Keeping grep, glob, and git_read opt-in on bash-capable main agents (--inspection-tools) while omitting redundant prose tool manuals (--no-tool-docs) reduced Mini-SWE prompt tokens by 59.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, Memory preserves 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 <1ms for $0 rather 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 Message parts (image_url data URIs / HTTP URLs) are estimated using image_token_estimate (1024 tokens per image in core/defaults.json) rather than raw base64 string length, and both compaction tombstones and Tracer exports (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 (5m vs. 1h): An extended 1h cache write costs a 0.75x upfront premium over 5m (2.00x - 1.25x base input rate), while a cached keep-alive ping (max_tokens=1) costs 0.10x. Dividing 0.75 / 0.10 = 7.5 pings means periodic 5m heartbeats stay cheaper than switching to 1h for up to 7–8 intervals (~34–35 minutes 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's 5m KV 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):

  1. python_syntax_diagnostics: Runs ast.parse after .py edits (write_file / edit_file) and feeds syntax errors immediately back to the agent.
  2. 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, CheckpointManager captures lightweight workspace state (via isolated git write-tree with a temporary GIT_INDEX_FILE in git repos, or scoped file backups outside git). Running /undo reverts workspace edits and memory to the pre-turn checkpoint without touching HEAD or git branches.
  • Session Tracing: Every run writes machine-readable trace.json, human-readable trace.md, and patch.diff (in git repos) inside ~/.microharness/runs/<run_id>/.