Metadata-Version: 2.5
Name: microharness
Version: 0.2.0
Summary: A minimal, zero-dependency, and pluggable AI agent microframework in Python
Project-URL: Homepage, https://github.com/Kagandi/microharness
Project-URL: Documentation, https://kagandi.github.io/microharness/
Project-URL: Repository, https://github.com/Kagandi/microharness
Project-URL: Issues, https://github.com/Kagandi/microharness/issues
Author: Dima Kagan
License: MIT
License-File: LICENSE
Keywords: agent,ai,coding-agent,harness,llm,microframework,swe-bench,zero-dependency
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
Requires-Python: >=3.11
Description-Content-Type: text/markdown

# microharness

[![PyPI version](https://img.shields.io/pypi/v/microharness.svg)](https://pypi.org/project/microharness/)
[![Docs](https://img.shields.io/badge/docs-github.io-blue.svg)](https://kagandi.github.io/microharness/)
[![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
[![Dependencies: 0](https://img.shields.io/badge/dependencies-0-success.svg)](#)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)

A minimalist, zero-dependency, and fully pluggable AI agent microframework in Python.

Built with **zero external runtime dependencies** (standard library only) to teach the core architectural boundaries of agentic systems. Compatible with modern packaging tools like [`uv`](https://github.com/astral-sh/uv) and standard `pip`.

**Documentation:** [https://kagandi.github.io/microharness/](https://kagandi.github.io/microharness/)

---

## Installation

Install directly from PyPI:

```bash
# Using pip:
pip install microharness

# Or with uv:
uv add microharness

# Or run as a standalone CLI tool without installing into your current environment:
uvx microharness "Inspect the files in this directory"
```

---

## The Core Mental Model: Harness vs. Loop

| Component | Responsibility | Location in `microharness` |
| :--- | :--- | :--- |
| **Agent Loop** *(The Engine)* | Pure Thought $\to$ Action $\to$ Observation cycle. Agnostic to benchmarks, sandboxes, and models. | [`core/loop.py`](core/loop.py) (~40 LOC) |
| **Harness** *(The Chassis)* | The outer environment: workspace directory, sandboxing, budgets, memory compaction, telemetry/tracing, and grading. | [`core/harness.py`](core/harness.py) |
| **Interactive Router** | One command table (`/model`, `/resume`, `/compact`, `/skill`, ...) shared by the CLI session and the TUI, so the two frontends cannot drift. | [`core/interactive.py`](core/interactive.py) |

---

## Configuration, Steering, Skills, Commands & Tool Plugins

`microharness` supports cascading configuration at two distinct scopes:
1. **Global User Baseline** (`~/.microharness/` or `--global-dir`)
2. **Project-Local Scope** (`.microharness/` in current workspace root)

### 1. Configuration Files (`config.json`)
Configure your baseline model, endpoint, API key, and limits globally or override them per project:
* **Global Baseline**: `~/.microharness/config.json`
* **Project Override**: `.microharness/config.json`

```json
{
  "default_model": "smart",
  "max_context_tokens": 64000,
  "trigger_ratio": 0.80,
  "max_tool_tokens": 8000,
  "sandbox": false,
  "models": {
    "fast": {
      "model": "gemini-2.5-flash",
      "provider": "google-ai-studio",
      "description": "Fast flash model"
    },
    "smart": {
      "model": "anthropic/claude-5.5-sonnet",
      "provider": "openrouter",
      "description": "Frontier reasoning model"
    },
    "local": {
      "model": "local-model",
      "provider": "lmstudio",
      "endpoint": "http://localhost:1234/v1",
      "description": "Local offline LLM"
    }
  }
}
```

Per-model context caps: a `models` entry may declare `max_context_tokens`, and a provider profile in `providers.json` may declare `context_tokens` (entry > profile > global `max_context_tokens`/`max_tokens`/`context_tokens`); switching models applies the cap live.

Legacy `max_context_chars`/`max_tool_chars` keys are removed; old char budgets converted as `chars//4` (e.g. 4000 chars behaved as 1000 tokens).
To preserve prior behavior, set `max_tool_tokens`/`max_context_tokens` explicitly (e.g. `"max_tool_tokens": 1000` replaces a former 4000-char tool limit).

#### Precedence Hierarchy:
1. **CLI Flags** (`--model`, `--endpoint`, `--api-key`, `--preset`, `--sandbox`, `-d`) — *Highest priority*
2. **Environment Variables / Local `.env`** (`MODEL_ENDPOINT`, `MODEL_NAME`, `MODEL_API_KEY`, or provider keys like `OPENROUTER_API_KEY`, `GEMINI_API_KEY`, `AI_GATEWAY_API_KEY`)
3. **Global Credential Store** (`~/.microharness/auth.json`) — *Per-provider API keys via `microharness auth login` or `/login`*
4. **Project Config** (`.microharness/config.json`) — *Project overrides (skipped when preset sets `isolated: true` or `inherit_project: false`)*
5. **Agent Preset** (`~/.microharness/presets/<name>/` or `.microharness/presets/<name>/`) — *Optional bundled persona (`agent.md` + `config.json`)*
6. **Global Config** (`~/.microharness/config.json`) — *Machine baseline*
7. **Hardcoded Fallbacks** (`MockModel`, default prompts) — *Lowest priority*

#### Provider Credentials (`~/.microharness/auth.json` & `microharness auth`)
Store API keys once per provider in `~/.microharness/auth.json` instead of duplicating secrets in `config.json`:

```bash
# Store or update a provider API key interactively (masked prompt, written with 0600 permissions):
uv run microharness auth login openrouter

# Or pick from an interactive numbered list of known providers:
uv run microharness auth login

# Inspect configured providers and effective credential sources (secrets are masked):
uv run microharness auth list

# Remove a stored provider credential from auth.json:
uv run microharness auth logout openrouter
```

Pass `--global-dir <dir>` (or `-d <project-dir>`) to any `microharness auth` subcommand to target a custom configuration directory. Credentials are stored per canonical provider name (for example `openrouter`, `google-ai-studio`, `vercel`, `openai`, `anthropic`) and resolve in this order: explicit CLI/model-spec key $\to$ provider environment variables (`env_keys`) $\to$ `~/.microharness/auth.json` $\to$ `providers.json` `api_key` (literal or `env:VAR`) $\to$ fallback environment variables $\to$ top-level `config.json` `"api_key"`.

#### Amazon Bedrock
`bedrock` is a built-in provider that targets Bedrock's official OpenAI-compatible endpoint.
On a machine with active AWS SSO (`aws sso login`) it works with zero config:

```bash
uv run microharness --model "bedrock/us.openai.gpt-5.6-sol" "Refactor auth.py"
```

Credentials resolve from the standard chain (environment, `~/.aws/credentials`, SSO
cache), and requests are SigV4-signed with the standard library; the harness never
shells out to the AWS CLI. The region resolves from `config.json` `"region"`, then
`AWS_REGION`, then `AWS_DEFAULT_REGION`, then the `~/.aws/config` profile region
(profile from `config.json` `"aws_profile"` or `AWS_PROFILE`, default `default`).
Without credentials or region the spec falls back to `MockModel` with a hint
(`aws sso login`). A `BEDROCK_API_KEY` bearer token still overrides SSO when set.
Only models whose Bedrock model card lists Chat Completions are served on this
endpoint (Claude/Nova IDs return `model_not_found`); the registry default is
`us.openai.gpt-5.6-sol`.

Auth schemes are pluggable: built-ins are `none`, `bearer`, `header`, and `sigv4`
(see `core/auth.py`), and extra single-file plugins can be installed as
`~/.microharness/auth/<scheme>.py` (global dir only, never project-local).

The shim exposes no prompt-cache or reasoning parameters, so the Bedrock profile runs with `cache_strategy: "openai_breakpoint"` and `reasoning_format: "none"`: with `cache_ttl` on, the first system text part carries an explicit `prompt_cache_breakpoint` (sub-1024-token prefixes are a server-side no-op); a stale user `providers.json` keeps `"none"` and simply skips breakpoints.

### 2. Cascading Instructions (`AGENTS.md`)
You can provide personal agent preferences globally, while projects can specialize or override them:
* **Global Baseline**: `~/.microharness/AGENTS.md` (e.g., your personal coding habits, formatting preferences).
* **Project Conventions**: `.microharness/AGENTS.md` or `./AGENTS.md` in the repo root (e.g., repo-specific test commands, architecture rules).

The harness loads both in cascading order (Global baseline first, Project local second) into the system prompt.

### 3. Progressive Skills Disclosure (`.microharness/skills/` & Shadowing) — Agent-Facing
Define reusable task workflows for the **agent** in `.microharness/skills/<skill_name>/SKILL.md`:
* **Global Skills** (`~/.microharness/skills/`): Available across all projects on your machine.
* **Project Skills** (`.microharness/skills/`): Project-specific tools and workflows (namespaced cleanly without polluting the project root).
* **Skill Shadowing**: If a project defines a skill with the same name as a global skill, the project version cleanly overrides it.
* **Progressive Disclosure**: Full skill files are never dumped into the prompt. Instead, the harness injects a 1-line index with scope badges (`[global]` or `[project]`).
* **Lazy Loading & Security**: The agent reads full instructions on demand via `read_file`. Global skills are authorized for reading, while all file writes remain strictly sandboxed to the project directory.

### 4. Custom Slash Commands (`.microharness/commands/*.md`) — User-Facing
Define reusable prompt templates and macros for the **user** in `.microharness/commands/<name>.md`:
```markdown
# Review code changes
Review the git diff or specified files: $ARGUMENTS.
Check for:
1. Correctness and edge-case logic bugs
2. Unit test coverage
3. Adherence to conventions in AGENTS.md
```
* **Skills vs. Commands**: Skills teach the **agent** how to perform complex workflows; Commands give the **user** prompt shortcuts.
* **Invocation**: Type `/review src/auth.py` in interactive chat or pass `microharness "/review src/auth.py"`.
* **Argument Substitution**: `$ARGUMENTS` or `{args}` is substituted with your trailing arguments.
* **Dynamic Help & Shadowing**: `/help` lists all discovered custom commands with their descriptions and scopes (`[project]` or `[global]`). Project commands shadow global ones.

### 5. Subagents (`.microharness/agents/*.md`, Presets & Parallel Delegation)
Delegate isolated subtasks to child agents with a clean `Memory` (zero parent context bias) and scoped tools:
* **Built-in Presets**: `explore` (read-only `read_file`, `grep`, `glob`, `git_read`), `reviewer` (unbiased read-only code review), and `worker` (full file + bash tools, excluding recursive `subagent` calls).
* **Custom Agent Files**: Place Markdown definitions with optional YAML frontmatter in `~/.microharness/agents/*.md` (`[global]`) or `.microharness/agents/*.md` (`[project]`, shadowing global and built-in presets):
  ```markdown
  ---
  name: security-reviewer
  description: Audits diffs and auth logic for security flaws
  tools: [read_file, bash]
  model: fast
  effort: high
  max_steps: 10
  ---
  You are a focused security reviewer starting with a clean context...
  ```
  Supports comma-separated or YAML `tools` lists (with `read`/`write`/`edit` aliases), `effort` (`reasoning_effort` / `thinking` aliases), and optional `max_steps` (`max_turns` alias).
* **Parallel Fan-Out**: Emitting multiple `subagent` calls in one turn or passing `tasks: [{agent, task, ...}, ...]` runs child loops concurrently and returns aggregated findings.
* **TUI & Interactive Discovery**: Use `/agent` (or `/agents`, `/subagent`) to list, inspect, or delegate to subagents, with floating Tab autocomplete and live child-step action lines in the TUI.

### 6. Custom Tool Plugins (`.microharness/tools/*.py`) — Zero-Commit Extensibility
Add new capabilities to the agent dynamically without modifying harness core code or making git commits:
* **Global Tools** (`~/.microharness/tools/*.py`): Available across all projects on your machine (always trusted and loaded automatically).
* **Project Tools** (`.microharness/tools/*.py`): Scoped to the current repository. Requires explicit opt-in via `--trust-project-tools` (or `"trust_project_tools": true` in `~/.microharness/config.json`) to prevent untrusted code execution from cloned repositories.
* **Tool Shadowing & Overrides**: A project tool with the same `name` overrides the global version. If a custom plugin shares a name with a built-in tool (e.g. `bash`), it will override it and emit a warning to ensure full visibility.

#### Authoring Conventions
A tool plugin file can follow any of these patterns:

##### Option A: Standalone Tool Class (Simplest)
Any class conforming to the `Tool` protocol (`name`, `description`, `parameters`, `execute`):
```python
# ~/.microharness/tools/web_fetch.py or .microharness/tools/calculator.py
class CalculatorTool:
    name = "calculate"
    description = "Evaluates basic math expressions safely"
    parameters = {
        "type": "object",
        "properties": {
            "expression": {"type": "string", "description": "The math expression (e.g. '24 * 7')"}
        },
        "required": ["expression"],
    }

    def execute(self, expression: str) -> tuple[int, str]:
        try:
            return 0, str(eval(expression, {"__builtins__": {}}, {}))
        except Exception as exc:
            return 1, f"Error: {exc}"
```

##### Option B: Environment-Aware Factory (`get_tools`)
Use `get_tools(env)` if your tool needs access to the harness execution environment (e.g. `env.workspace_dir`):
```python
# .microharness/tools/db_tool.py
class DatabaseTool:
    name = "query_db"
    description = "Queries a project SQLite database"
    parameters = {
        "type": "object",
        "properties": {"query": {"type": "string"}},
        "required": ["query"],
    }

    def __init__(self, env=None):
        self.workspace = env.workspace_dir if env else "."

    def execute(self, query: str) -> tuple[int, str]:
        # Query local database in self.workspace
        return 0, "Query results..."


def get_tools(env=None):
    return [DatabaseTool(env)]
```

##### Option C: Module-Level `tools` List
Export an explicit list of pre-instantiated tool instances:
```python
# .microharness/tools/helpers.py
tools = [ToolOne(), ToolTwo()]
```

### 7. Bundled MCP Support (`plugins/mcp.py` & `ToolProvider`)
`microharness` ships a zero-dependency, lazy-loaded Model Context Protocol (MCP) plugin (`plugins/mcp.py`) implementing `core.protocols.ToolProvider`:

```jsonc
{
  "mcp_mode": "progressive", // "progressive" (default), "direct", or "code_mode"
  "mcp_servers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "env:GITHUB_TOKEN" },
      "description": "GitHub issues, PRs, and repositories"
    },
    "remote-docs": {
      "url": "https://docs.example.com/mcp",
      "headers": { "Authorization": "Bearer env:DOCS_TOKEN" }
    }
  }
}
```

* **Progressive & Code Mode by Design**: `"progressive"` injects only a 1-line-per-server index and exposes `mcp_search` + `mcp_call`. `--mcp-mode code_mode` exposes Python `code_mode` backed by an authenticated loopback bridge and defers `mcp_call` so the model can batch/filter `tools.call(...)` and `mcp.search(...)`/`mcp.call(...)` calls in one script without JS/Wasm dependencies. Pass `--mcp-mode direct` (or `"mode": "direct"` per server) to register `mcp__<server>__<tool>` directly.
* **Optional & Swappable**: Never imported unless `mcp_servers` is configured. Disable with `--no-mcp` / `enable_mcp=False`, or pass custom `ToolProvider` instances via `Harness(tool_providers=[...])`.
* **Trust & Permissions**: Non-global MCP servers (e.g. `.microharness/config.json` or path presets) require `--trust-project-tools` (or `"trust_project_tools": true` in `~/.microharness/config.json`), remote HTTP/SSE servers respect `--no-network-tools`, and mutating tools (`readOnlyHint != true`) obey `ask` / `read-only` permission modes.

See [docs/mcp.md](docs/mcp.md) for all server options, transports (`stdio`, Streamable HTTP, `/sse`), secret references (`env:VAR`), and Code Mode details.

### 8. Agent Config Presets (`presets/<name>/`) — Portable Agent Bundles
Bundle a full runnable agent configuration into a single directory (`~/.microharness/presets/<name>/` or `.microharness/presets/<name>/`):
* **`agent.md`** (or `AGENT.md`): YAML frontmatter (`name`, `description`, `model`, `reasoning_effort`, `tools` allow-list, `isolated`, `include_builtin_subagents`, etc.) plus the base system prompt body.
* **Optional Subdirectories**: `config.json`, `subagents/`, `tools/`, `skills/`, and `commands/` scoped to that preset (with per-subagent `model` / `effort` overrides for heterogeneous multi-model teams).
* **Invocation**: Pass `--preset <name-or-path>` (alias `--agent`), inspect with `--list-presets` (`--list-agents`), or run `/preset` in interactive sessions. Presets outside `<global_dir>/presets/` still require `--trust-project-tools` before running `tools/*.py` plugins or command hooks.

See [docs/presets.md](docs/presets.md) for the full manifest reference and multi-model examples.

---

## Working on Existing Projects

By default, the agent runs directly in your **current working directory** (like Claude Code or Aider). It sees all your existing files, respects git, and resumes right where you left off:

```bash
# Operates directly on the current directory:
uv run microharness "Inspect the files in this directory and explain the architecture"

# Or point to any other project directory with -d:
uv run microharness -d /path/to/my-project "Fix the bug in auth.py"
```

If you ever want an isolated disposable scratchpad (e.g. for testing without touching real files), pass `--sandbox`:
```bash
uv run microharness --sandbox "Experiment with writing a new scraper"
```

### Docker Sandboxing (via OrbStack or Docker Desktop)
For 100% containerized process, operating system, and filesystem isolation (e.g. running untrusted code, heavy test suites, or SWE benchmarks), pass `--docker`:
```bash
# Run educational demo inside an isolated Linux Docker container
uv run microharness --demo calculator --docker

# Run the Mini-SWE benchmark suite inside Docker
uv run microharness --benchmark mini-swe --docker

# Specify a custom Docker image (default: python:3.11)
uv run microharness --docker --docker-image python:3.11 "Run pytest and fix bugs"
```
* **Instant Hybrid I/O**: The workspace directory is mounted at `/workspace`. File reading, writing, and editing occur on the host filesystem with zero container latency, while all bash commands execute inside the isolated Docker Linux container via `docker exec`.
* **Zero Runtime Dependencies**: Operates entirely via Python's standard library `subprocess` without third-party Docker SDKs. Works out of the box with **OrbStack** or standard Docker Desktop.
* **Automatic Teardown**: Containers are automatically stopped and removed upon task completion with zero orphaned background containers.

If you prefer a one-and-done batch run (e.g. for CI), pass `--batch`:
```bash
uv run microharness "Run pytest and fix any failures" --batch
```

---

## Continuous Interactive Chat & Meta-Commands

When you chat with the agent, the harness maintains persistent memory and renders a clean **context budget status line** before every turn:

```text
─── Context: 1.4k / 8k (17.8%) ───
You:
```

### Slash Commands (No Model Call)
You can inspect or control the harness runtime directly:

* **`/model [name|number]`**: Inspect available models or switch active model dynamically on the fly (e.g. `/model fast` or `/model 2`). In TUI mode, Tab autocompletes configured model names. A name is matched against the `models` aliases in `config.json`, their underlying model ids, and the provider registry (`openai` or `openai/gpt-4o` both work). An unrecognized name is **rejected with the list of valid models** rather than silently constructing a client for a model that does not exist. The `--model` startup flag applies the same recognition rules but only warns on stderr, so it remains usable for endpoints whose provider is not in the registry.
* **`/login [provider|number] [key]`**: List providers and their effective credential sources without exposing secrets, or store/update an API key for a provider in `~/.microharness/auth.json` (prompts with masked input when the key is omitted; Tab autocompletes providers in TUI mode).
* **`/logout [provider|number]`**: List providers with keys stored in `~/.microharness/auth.json`, or remove stored credentials for a provider.
* **`/resume [id|number]`**: List previous sessions in `~/.microharness/runs/` (with workspace affinity) or resume conversation history from an earlier session in-place. Discovery reads only the newest sessions first and falls back to a full scan when your repository has no recent session, so an older session for the same repo stays reachable.
* **`/agent [name|number] [task]`**: List built-in and discovered subagents (`.microharness/agents/*.md`), inspect an agent's tools/model/effort/max_steps, or delegate a task directly (with Tab autocomplete in the TUI).
* **`/preset`**: Display the active agent preset (if any) and list discovered presets.
* **`/cache [5m|1h|off]`**: Inspect or switch prompt caching duration on the fly (`5m` standard ephemeral, `1h` extended beta, or `off`).
* **`/status`**: Displays detailed memory metrics (system, user, assistant, and tool counts + budget percentage) and prompt cache hit rates.
* **`/compact`**: Manually triggers memory compaction to prune older tool observations and reclaim context space.
* **`/new`**: Starts a fresh conversation context while keeping all your project files intact.
* **`/help`**: Lists available commands.
* **`/exit`**: Finalizes and exports the session trace.

### Cancelling a Running Turn

The two cancel keys are **not** equivalent, and the status bar says so while a turn runs:

* **`Ctrl+C`** aborts the active step immediately, including a request that is already in flight. The incomplete tool turn is dropped and the session stays usable.
* **`Esc`** is a cooperative cancel. It takes effect at the next step boundary and while the model waits between retries (for example during a throttle backoff). The moment it is seen the UI prints `Cancelling… aborting the pending model request` and abandons the wait.

`Esc` cannot abort a request that is currently waiting on the provider, because the HTTP timeout covers time-to-first-byte and shortening it would break slow models. Use `Ctrl+C` for that. See SPEC.md §5.2 for the planned work to unify the two.

---

## Quickstart with `uv`

### 1. Install & Sync Environment
```bash
uv sync
```

### 2. Run the Test Suite
```bash
uv run pytest
```
*(930+ unit and integration tests run in ~15s. Static checks run via `uv run ruff check .`, `uv run ruff format --check .`, and `uv run ty check`.)*

### 3. Interactive and TUI Sessions
```bash
# Launch interactive mode (full-screen TUI):
uv run microharness

# Resume previous interactive session:
uv run microharness --resume

# Resume a specific session by ID:
uv run microharness --resume run-2026-10-03-xxxx
```

### 4. Run Mini-SWE for Rapid Sanity Testing
Run the lightweight 5-task sanity test suite before launching heavy benchmarks:
```bash
# Run the entire Mini-SWE sanity benchmark suite:
uv run microharness --benchmark mini-swe

# Filter to a specific challenge (e.g. rate_limiter or query_builder):
uv run microharness --benchmark mini-swe --task rate_limiter

# Built-in demo tasks:
uv run microharness --demo calculator
uv run microharness --demo greeting
```

---

## Mini-SWE Benchmark Suite (Sanity & Smoke Testing)

`microharness` includes **Mini-SWE**, a fast, lightweight, pure-Python benchmark designed primarily for **rapid sanity testing, local iteration, and CI smoke testing**:

* **Sanity Testing Focus**: Validates the agent's tool-calling loop, multi-turn file editing, memory compaction, and test assertion grading in seconds—without burning model quota or waiting on multi-hour containerized benchmarks.
* **Pure Python & Zero Docker**: Operates entirely with Python's standard library. No multi-gigabyte container downloads, instant startup.
* **Anti-Cheating Evaluator (`PristineTestEvaluator`)**: Evaluators restore pristine test files prior to running verification. An agent cannot bypass tests by deleting or rewriting assertions in the test suite.
* **5 Realistic Engineering Challenges**:
  1. `rate_limiter`: Token Bucket rate limiter losing fractional refills under rapid polling.
  2. `circular_serializer`: Circular JSON serializer cycle detection & ISO-8601 formatting.
  3. `auth_middleware`: HTTP auth middleware case-insensitive headers & whitespace tolerance.
  4. `lru_ttl_cache`: LRU cache with TTL updating existing keys & refreshing MRU order.
  5. `query_builder`: SQL query builder AST precedence grouping & single-quote escaping.
* **Automated Scorecard & JSON Telemetry**: Generates a formatted summary table in the terminal and exports comprehensive JSON results to `~/.microharness/runs/benchmark_report.json`.

---

## DeepSWE-mini Benchmark Suite (Harbor Format & Docker)

`microharness` natively supports **DeepSWE-mini** (curated from [Datacurve-AI DeepSWE](https://github.com/datacurve-ai/deep-swe) and [`LocalLLaMA/deepswe-mini`](https://huggingface.co/datasets/LocalLLaMA/deepswe-mini)):

* **16 Curated Real-World Repositories**: Across Python, Go, and TypeScript (e.g. `aiomonitor`, `bandit`, `ipython`, `narwhals`, `textual`, `prometheus`, `valibot`, `dasel`).
* **Harbor Standard Compliance**: Automatically parses `task.toml` metadata (via Python 3.11's standard library `tomllib`), pulls task ECR container images, mounts behavioral verifiers, and grades via `tests/grader.py`.
* **Zero Dependency Container Sandboxing**: Spawns isolated Docker containers via **OrbStack** or Docker Desktop, syncs repo code at NVMe speed, and automatically captures `model.patch` diffs.

```bash
# Clone tasks once (only ~3.5MB repository metadata):
git clone --depth 1 https://github.com/datacurve-ai/deep-swe datasets/deep-swe

# Run the entire 16-task DeepSWE-mini benchmark suite in Docker:
uv run main.py --benchmark deepswe-mini --docker

# Run a specific task with custom step & timeout budgets:
uv run main.py --benchmark deepswe-mini --task aiomonitor --max-steps 500 --timeout 7200 --docker

# Run with official Datacurve Pier framework using microharness adapter:
uvx --from datacurve-pier pier run -p datasets/deep-swe/tasks/aiomonitor-task-snapshots-diff \
  --agent-import-path benchmarks.pier_agent:MicroharnessAgent --env docker
```

### Experiment Tracking (`microharness experiments`)
Benchmark runs automatically upsert run summaries (`~/.microharness/experiments.csv`) and per-task outcomes (`~/.microharness/experiments_tasks.csv`), recording `harness_version`, `git_commit`, active `preset`, `subagents`, scores, and token/cache telemetry:
```bash
# List recent benchmark runs
uv run microharness experiments list --limit 20

# Backfill historical *_report.json and standalone trace.json runs into CSV
uv run microharness experiments backfill
```

---

## True Pluggability (Zero Code Modifications)

Because components follow minimal Python `Protocols`, you can plug in any Model, Tool, or Evaluator from the outside without touching a single line of harness code:

```python
from microharness import Harness

# In-place coding agent on your repo with global and project steering:
harness = Harness(
    model=my_custom_model,  # Or HttpChatModel(endpoint, model, key)
    workspace_dir=".",  # Works directly on your project
    global_dir="~/.microharness",  # Global config, instructions & skills
    tools=[bash_tool, my_tool],  # Custom tools (dynamically documented in system prompt)
)
harness.run_tui("Help me refactor the database layer")
```

---

## Key Educational Paradigms Demonstrated

1. **In-Place Project Operation vs. Sandboxing (`core/environment.py`)**
   - By default, operates directly on existing project files with zero root directory pollution.
   - Optional `--sandbox` creates an isolated scratchpad in `~/.microharness/runs/` (or `--runs-dir`).
   - Prevents path traversal outside project boundaries while permitting read access to authorized global directories (`allowed_read_dirs`).
   - Executes bash with timeouts and combined stdout/stderr.

2. **Cascading Configuration & Steering (`core/harness.py`)**
   - Loads global defaults from `~/.microharness/config.json`.
   - Injects global user instructions (`~/.microharness/AGENTS.md`) and project instructions (`./AGENTS.md`) in cascading order.
   - Discovers `skills/` and `commands/` globally and locally; project definitions cleanly shadow global ones.
   - Indexes skills lazily with scope badges to conserve context tokens.

3. **Targeted File Editing vs. Full Rewrites (`core/tools.py`)**
   - Built-in `edit_file(path, old_str, new_str)` enforces exact, unique string replacement.
   - Prevents token wastage and LLM hallucination bugs common when rewriting large files with `write_file`.

4. **Dynamic Tool Introspection (`core/tools.py`)**
   - `ToolRegistry.to_system_prompt_snippet()` automatically reflects registered tools in the system prompt. Custom tools require zero prompt tweaking.

5. **Large Log Handling & Spillover (`core/tools.py`)**
   - Massive command outputs are head + tail truncated.
   - The full, raw output is spilled to `~/.microharness/runs/<run_id>/logs/` so it never pollutes the user's project root.

6. **Proactive 80% Context Compaction & Memory Optimization (`core/memory.py`)**
   - Proactively prunes older tool observations at an 80% high-water mark (`trigger_ratio = 0.80`), keeping 20% reserved for output tokens and model reasoning.
   - **Enriched Tombstones with Log Pointers**: Collapsed tool outputs embed the exact spilled log file path (`Full log: <path>. Use read_file to inspect if needed.`), giving the agent a deterministic bridge to inspect full outputs.
   - **Historical Reasoning Pruning**: Automatically prunes transient `<think>...</think>` and `<thinking>...</thinking>` reasoning streams from older assistant turns to reclaim thousands of tokens for reasoning models (DeepSeek-R1, Claude Thinking, o1/o3).
   - **Session Files Modified Ledger**: Injects and maintains an active session ledger (`[Session Files Modified: file1.py, file2.py]`) across compactions at the safe prefix.
   - Preserves system prompt, initial task, and recent working turns.

7. **Git Patch Export (`patch.diff`) & Modern CLI Tracing (`core/tracer.py`)**
   - Automatic git diff extraction: generates `patch.diff` for coding tasks in git repositories.
   - **Modern Developer CLI Output**: Eliminates academic ReAct tags (`Thought:` / `Action:` / `Observation:`) in favor of natural assistant speech, `$ <command>` execution, `● Read/Write/Edit <path>`, real-time duration headers, and clean output gutters.
   - Persists machine-readable `trace.json` and human-readable `trace.md` in `~/.microharness/runs/<run_id>/` for every run.

8. **Automated Evaluation (`core/evaluator.py`)**
   - Evaluators test whether the agent actually succeeded (e.g. running test commands, asserting file contents, or Docker-based SWE-bench graders).

---

## Project Structure

```
microharness/
├── pyproject.toml      # Modern PEP 621 packaging for uv & hatchling
├── uv.lock             # Deterministic lockfile generated by uv
├── SPEC.md             # Detailed specification & design rationale
├── mkdocs.yml          # MkDocs Material site configuration for GitHub Pages
├── README.md           # Quickstart and overview
├── docs/               # Documentation site (served via GitHub Pages)
│   ├── index.md        # Documentation home & mental model
│   ├── getting-started.md
│   ├── configuration.md
│   ├── interactive-tui.md
│   ├── subagents.md
│   ├── presets.md      # Agent config presets reference
│   ├── mcp.md          # MCP servers, transports & Python Code Mode guide
│   ├── architecture.md
│   ├── pluggability.md
│   └── benchmarks.md
├── AGENTS.md           # Project conventions for agents
├── .microharness/      # Clean project-level configuration namespace
│   ├── skills/         # Progressive disclosure skills
│   │   └── run-tests/
│   │       └── SKILL.md
│   └── commands/       # Custom slash commands (user prompt shortcuts)
│       └── review.md
├── .env.example        # Environment variable template
├── main.py             # Runnable demonstration & CLI entrypoint
├── microharness/       # Top-level package exports & entrypoints (__main__.py)
├── benchmarks/         # SWE benchmark suites & runners
│   ├── mini_swe.py     # 5 real-world pure-Python SWE tasks & PristineTestEvaluator
│   ├── harbor.py       # Harbor / DeepSWE-mini benchmark loader & Docker verifier adapter
│   ├── experiments.py  # Central CSV experiment tracking & historical backfill
│   ├── pier_agent.py   # Datacurve Pier framework agent adapter (MicroharnessAgent)
│   └── runner.py       # Benchmark orchestrator, scorecard table & incremental JSON report export
├── plugins/
│   └── mcp.py          # Zero-dependency stdlib MCP client (stdio, Streamable HTTP & SSE)
├── core/
│   ├── types.py        # Clean dataclasses (Message, ToolCall, Task, Trajectory, RunResult)
│   ├── prompts.py      # System prompt templates & prompt assembly
│   ├── environment.py  # Workspace & bash runner (supports in-place and sandbox)
│   ├── tools.py        # Pluggable tool protocol & built-ins (bash, read_file, write_file)
│   ├── code_mode.py    # Python Code Mode & authenticated loopback tool bridge
│   ├── memory.py       # Context manager & 80% high-water mark compaction
│   ├── protocols.py    # Model protocol, capability protocols (cache, deadline, cancel) & cancellation
│   ├── usage.py        # Token normalization, per-model telemetry & run-level totals
│   ├── providers.py    # Provider registry, model-spec resolution & client construction
│   ├── auth_store.py   # Per-provider global credential store (~/.microharness/auth.json)
│   ├── model.py        # Generic HttpChatModel & MockModel clients
│   ├── config.py       # Cascading configuration, JSONC reading & setting resolution
│   ├── presets.py      # Named agent preset bundles (agent.md + subagents/tools/skills)
│   ├── skills.py       # Progressive-disclosure skills (discovery, summaries, activation)
│   ├── subagents.py    # Subagent presets, .md discovery & isolated child delegation tool
│   ├── commands.py     # Custom slash commands & slash-input resolution
│   ├── discovery.py    # Hierarchical resource discovery & @file-tagging
│   ├── interactive.py  # Interactive command router shared by the CLI session & the TUI
│   ├── session.py      # Step driver, session index, resumption & trace reconstruction
│   ├── loop.py         # Native tool-calling loop (~40 lines)
│   ├── evaluator.py    # Automated graders (CommandTestEvaluator, FileContentEvaluator)
│   ├── tracer.py       # Telemetry collector, modern CLI renderer & trace exporter
│   ├── tui.py          # Full-screen curses TUI (markdown rendering, autocomplete)
│   ├── tui_session.py  # TUI turn driver: step rendering & cooperative cancellation
│   └── harness.py      # Harness orchestrator wiring the chassis together
└── tests/
    ├── test_auth_store.py  # Global auth.json storage, permissions & masking tests
    ├── test_benchmarks.py  # Mini-SWE baseline failure, anti-cheating & reference tests
    ├── test_code_mode.py   # Python Code Mode bridge, auth & Docker/read-only boundary tests
    ├── test_mcp.py         # MCP stdio/HTTP/SSE transports, search ranking & security tests
    ├── test_harbor.py      # Harbor task parsing, Docker image validation & evaluator tests
    ├── test_environment.py # Path sandboxing & bash timeout tests
    ├── test_tools.py       # Tools, truncation & disk spillover tests
    ├── test_memory.py      # Conversation history, stats & 80% compaction tests
    ├── test_model.py       # Endpoint normalization, serialization & mock model tests
    ├── test_evaluator.py   # Grader assertions tests
    ├── test_config.py      # Config cascade, JSONC parsing & tool-trust boundary tests
    ├── test_protocols.py   # Capability protocol detection tests
    ├── test_usage.py       # Token normalization & telemetry accounting tests
    ├── test_providers.py   # Provider registry, model specs & available-model tests
    ├── test_skills.py      # Skill discovery, summaries & activation tests
    ├── test_presets.py     # Agent preset discovery, isolation, trust & CLI tests
    ├── test_experiments.py # Central CSV experiment tracking & backfill tests
    ├── test_subagents.py   # Subagent parsing, isolation, overrides, parallel & TUI tests
    ├── test_commands.py    # Slash-command discovery, expansion & resolution tests
    ├── test_prompts.py     # Prompt assembly & AGENTS.md cascading tests
    ├── test_session.py     # Step driver retries, deadlines & session resumption tests
    ├── test_interactive.py # Command router & rendering tests
    ├── test_tui_session.py # TUI turn rendering & cancellation tests
    └── test_harness.py     # End-to-end lifecycle, global config, commands & guardrails tests
```
