Skip to main content
Glama
README.md
<p align="center">
  <img src="assets/clean-context-banner.jpg" alt="Clean-Context — Multi-Agent Context Control & Handoff" width="100%" />
</p>

# Clean-Context

[![Node.js](https://img.shields.io/badge/Node.js-26+-339933?logo=node.js&logoColor=white)](https://nodejs.org/)
[![MCP](https://img.shields.io/badge/MCP-Stdio%20Server-000000)](https://modelcontextprotocol.io/)
[![Clients](https://img.shields.io/badge/Clients-Antigravity%20%7C%20Claude%20Code%20%7C%20Codex-6366f1)](#instalación-rápida)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)

Sistema unificado multi-agente de **control de contexto**, **herencia (`handoff`)**, **modo Solo / Orquestador** y **gestión de workers con `herdr`** para **Antigravity (`agy`)**, **Claude Code** y **Codex**, construido sobre un único **Servidor MCP Local (Stdio)** en Node.js + TypeScript.

---

## Arquitectura

```text
Antigravity (Plugin)  ──┐
Claude Code           ──┤
Codex (config.toml)   ──┼──▶ MCP Stdio Local (dist/index.js)
OpenCode              ──┘       ├── Telemetría: ~/.clean-context/telemetry/*.json
                                ├── OpenCode:   API local en vivo (~/.local/state/opencode/service.json)
                                ├── Codex:      SQLite (~/.codex/state_5.sqlite)
                                ├── Config:     ~/.clean-context/config.json (+ .agents/clean-context.json)
                                ├── Workers:    herdr CLI + ~/.clean-context/workers.json
                                └── Handoff:    .agents/handoff/handoff-*.md + LATEST.md
```

### Herramientas MCP expuestas
| Herramienta | Propósito |
| :--- | :--- |
| `get_context_status` | Lee el `statusline` de la sesión actual (o SQLite en Codex) y compara `%` usado vs límite por rol (`orchestrator`/`solo` vs `worker`). |
| `get_config` / `update_config` | Lee o actualiza umbrales (`maxContextPercent`), modelos y `handoffDir` de forma global o por proyecto. |
| `herdr_spawn` | Divide un pane en `herdr` e inicia un worker con `worker.model` y `worker.kind`, inyectando `CLEAN_CONTEXT_ROLE=worker`. |
| `herdr_status` | Lista panes, agentes vivos en `herdr` y workers rastreados. |
| `herdr_stop` | Cierra limpiamente un worker por nombre o `paneId`. |
| `herdr_cleanup` | Detecta y cierra terminales huérfanas, colgadas o terminadas (`done`/`unknown`) con soporte `dryRun`. |
| `create_handoff` / `read_handoff` | Genera y lee los `.md` de herencia en `.agents/handoff/` con puntero `LATEST.md`. |

---

## Configuración por defecto (`config.default.json`)

```json
{
  "orchestrator": {
    "maxContextPercent": 50,
    "model": "claude-opus-4-5"
  },
  "worker": {
    "maxContextPercent": 25,
    "kind": "opencode",
    "model": "opencode-go/deepseek-v4.1-flash#max",
    "modelFlag": "-m"
  },
  "handoffDir": ".agents/handoff/",
  "telemetryDir": "~/.clean-context/telemetry/"
}
```

- **Modo Solo:** aplica `orchestrator.maxContextPercent` (50%), higiene de terminales y `create_handoff` al llegar al umbral sin forzar workers.
- **Modo Orquestador:** delega subtareas exclusivamente con `herdr_spawn` usando `worker.model` y vigila que ni el orquestador (50%) ni los workers (25%) superen su límite.

---

## Instalación rápida

Requiere pnpm 10+ (`corepack enable pnpm` si no lo tienes).

```bash
pnpm install
pnpm run build
pnpm run install-global
```

`pnpm run install-global` (`scripts/install.mjs`) realiza backups con timestamp antes de modificar archivos y configura automáticamente:
1. **Antigravity:** instala el plugin en `~/.gemini/config/plugins/clean-context/` (`plugin.json`, `mcp_config.json`, `rules/AGENTS.md`) y conecta `~/.gemini/antigravity-cli/statusline.js`.
2. **Claude Code:** registra `clean-context` en `~/.claude.json`, añade las reglas en `~/.claude/CLAUDE.md` y conecta `~/.claude/statusline.js`.
3. **Codex:** registra `[mcp_servers.clean-context]` en `~/.codex/config.toml` y añade las reglas en `~/.codex/AGENTS.md`.

También puedes usar el plugin o `.mcp.json` directamente por proyecto copiando `plugins/clean-context/`, `AGENTS.md`, `CLAUDE.md` y `.mcp.json`.

### OpenCode (bridge en vivo)

`install-global` no configura OpenCode, porque su MCP vive en `~/.config/opencode/opencode.jsonc` y no hay statusline. Dos pasos manuales:

```jsonc
// ~/.config/opencode/opencode.jsonc
"mcp": {
  "servers": {
    "clean-context": {
      "type": "local",
      "command": ["node", "<repo>/dist/index.js"],
      "protocol": "legacy"
    }
  }
}
```

Y la telemetría: OpenCode no escribe un archivo de statusline, pero `src/opencode.ts` lee su API local en vivo. `get_context_status` descubre el servicio en `~/.local/state/opencode/service.json` (url + password), resuelve la sesión por `cwd` y calcula el mismo número que muestra la TUI:

```text
contexto usado = tokens.input + tokens.cache.read   (último mensaje assistant cerrado)
           %   = usado / model.limit.context * 100
```

Verificado contra la barra de OpenCode: `182.7K (18%)` → `182.7K / 1,000,000`. Si OpenCode no está corriendo o no hay sesión para ese `cwd`, cae a las fuentes por archivo (Antigravity, Codex) como siempre.

---

## Pruebas

```bash
pnpm test
```

Ejecuta la suite end-to-end (`tests/run-tests.mjs`):
- Generación de telemetría desde `statusline.js`
- Conexión MCP stdio real (`@modelcontextprotocol/sdk`)
- Validación de umbrales `orchestrator` vs `worker`
- Creación y lectura de handoff en `.agents/handoff/`
- Consultas y ciclo real `split` + `herdr_stop` contra el servidor `herdr` activo

TDQS

B3.2/5.0

Scored across 9 tools

Disambiguation4/5

Each tool maps to a recognizable action within one of three clear sub-domains (config, Herdr workers, handoffs/status). The only mild overlap is between herdr_status (pane/worker inventory) and get_context_status (statusline telemetry vs. context limit), but the descriptions make the distinction reasonably clear.

Naming Consistency4/5

Most tools follow a predictable verb_noun pattern (get_config, update_config, create_handoff, read_handoff, get_context_status). The Herdr group uses a namespace prefix plus verb (herdr_spawn, herdr_stop, herdr_status, herdr_cleanup), which is a minor but coherent deviation that actually aids grouping.

Tool Count5/5

Nine tools is well within the ideal 3-15 range and each one covers a distinct operation: two config, four worker lifecycle, one status check, two handoff operations. No tool feels redundant or superfluous for the stated purpose.

Completeness4/5

Worker lifecycle (spawn/status/stop/cleanup) and handoff persistence (create/read) are well covered, and config has read/update. Minor gaps exist: no list_handoffs or handoff pruning, and no config reset/delete, but read_handoff accepts a specific file so agents can work around the listing gap.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues