headcleaner
headcleaner
Recorre una carpeta y convierte cada documento a Markdown (con frontmatter), OKF v0.2 (con frontmatter), o ambos, con una TUI animada inspirada en omp.
headcleaner convert ~/Documents/inbox --format both --output ~/Documents/inbox.cleanheadcleaner es una CLI de Python que escanea el directorio que le indiques, identifica cada documento por su extensión, ejecuta el motor de extracción adecuado (OfficeCLI para formatos de Office, pdfplumber para PDF, BeautifulSoup para HTML, etc.) y genera una salida limpia y normalizada: ya sea Markdown y OKF lado a lado, o solo uno de ellos.
Formatos de salida:
--format md(Markdown),--format okf(paquete OKF v0.2),--format both(predeterminado)Cobertura de motores: 7 formatos de serie (XLSX, DOCX, PPTX, PDF, HTML, HTM, TXT); consulta docs/FORMAT_MATRIX.md para la hoja de ruta de 16 formatos en v1.0.
TUI: terminal animada inspirada en omp (paneles con caracteres de caja, paleta neón, separadores powerline)
Linter:
headcleaner lintrevisa el Markdown / OKF convertido para detectar problemas de formato.PST por mensaje: un concepto OKF por correo electrónico (mediante readpst), de modo que la revisión y la aprobación funcionen archivo a archivo.
Backend office_oxide: enlaces de Python en Rust puro para formatos de Office (~100 veces más rápido que OfficeCLI).
Limpieza heurística:
headcleaner convert --cleanejecuta un pipeline de limpieza de 12 etapas inspirado en any2md.Respaldo all2md: gestiona automáticamente 38 formatos adicionales (Jupyter, LaTeX, reST, sourcecode, etc.) cuando all2md está instalado.
headcleaner mcp: ejecuta headcleaner como servidor MCP que expone 14 herramientasokf_*a cualquier host de agentes MCP (Claude Code, Cursor, etc.); instálalo conuv pip install "headcleaner[mcp]".Diagnóstico:
headcleaner doctorcomprueba Python, PATH, OfficeCLI, los permisos de salida y el registro@slug, y luego imprime un veredicto GO/NO-GO.Plugins adaptadores: los paquetes de terceros registran formatos a través del grupo de puntos de entrada
headcleaner_plugin.zsv CSV: el analizador CSV SIMD más rápido del mundo (~10-100 veces la biblioteca estándar) cuando
zsvestá en PATH.Atestación de confianza:
headcleaner attestconstruye una raíz Merkle y una firma ed25519;verifyla comprueba.Exploración local:
headcleaner serve <bundle>expone una interfaz FastAPI para explorar y buscar.Valores predeterminados honestos: los campos de confianza de OKF se rellenan con
unverified/human:pending, nunca se inventan.
Instalación
# 1. The Office engine — single binary, no Office install needed
npm install -g @officecli/officecli
# 2. The CLI itself (Python ≥3.12, uv-managed)
uv tool install headcleaner
# Or for development:
git clone <this repo>
cd headcleaner-cli
uv sync
uv run headcleaner --helpPara otros métodos de instalación (curl | bash, pip, brew, Windows PowerShell), consulta docs/INSTALL.md.
Related MCP server: okf-tools
Inicio rápido
headcleaner ~/Documents/inbox --format both --output ./cleanEsto produce:
clean/
├── manifest.json # run summary: per-file status, engine, sha256
├── REPORT.md # count, average time, and error rate by engine
├── _md/ # plain Markdown (one file per source)
│ ├── notes.docx.md
│ ├── q3.pdf.md
│ └── ...
└── okf/ # OKF v0.2 bundle (one concept per source)
├── index.md # auto-generated directory index
├── notes.md # OKF concept: type=Document
├── q3.pdf.md
└── ...Referencia de la CLI
headcleaner convert <INPUT_DIR> [OPTIONS]
Options:
-f, --format {md,okf,both} Output format(s) [default: both]
-o, --output DIR Output directory [default: ./out]
--ocr Enable Tesseract OCR for scanned PDFs
--officecli-timeout <secs> Timeout per OfficeCLI subprocess call (default: 60)
--include, -i GLOB Include glob (may be repeated)
--exclude, -e GLOB Exclude glob (may be repeated)
--jobs, -j N Parallel worker processes (default: 1 = sequential)
--no-cache Re-convert every file (skip the SHA-256 cache)
--no-continue-on-error Stop on the first failure
--obsidian-compat Add Obsidian-friendly flat fields to OKF frontmatter
--clean Run the 12-stage heuristic cleanup pipeline (any2md-inspired) on each body
--tui / --no-tui Force / disable the animated TUI (default: auto-detect TTY)
--no-okf-index Skip OKF directory index.md generationOtros comandos: headcleaner doctor [--output-dir DIR] Ejecuta diagnósticos de instalación y permisos headcleaner templates Muestra los formatos compatibles headcleaner agents Muestra el estado de instalación de los motores headcleaner watch IN [--webhook-url URL] Re-convierte al cambiar archivos (Ctrl+C para detener) headcleaner lint Revisa el Markdown / OKF convertido para detectar problemas de formato headcleaner lint --fix Repara automáticamente problemas seguros en .fixed/ headcleaner serve Navegador HTTP local para el paquete OKF headcleaner notion-import <EXPORT.zip> Revierte una exportación del espacio de trabajo de Notion headcleaner attest Calcula la raíz Merkle y una firma ed25519 opcional headcleaner verify Verifica una atestación contra el paquete
## Why OKF?
OKF (Open Knowledge Format, v0.2) is just **markdown + YAML frontmatter in a directory hierarchy**. That means:
- Every concept is a single `.md` file you can `cat`, `grep`, edit in any text editor
- Bundles live in git — pull requests, diffs, blame all work
- Obsidian, Notion, MkDocs, Hugo, Jekyll all consume OKF natively
- Required frontmatter key is just `type` — anything beyond that is producer freedom
See [docs/OKF_NOTES.md](docs/OKF_NOTES.md) for the OKF v0.2 specifics this CLI emits.
## Trust stance (honest defaults)
We never auto-claim review. Every emitted OKF concept gets:
- `status: unverified`
- `verified: human:pending`
- `generated: human:<user>@<host>` (OKF §7 actor convention)
- `stale_after: <today + 180d>`
- `sources: [{uri: file://..., sha256: ...}]`
A human can grep `human:pending` later to find concepts needing review. See [docs/OKF_NOTES.md](docs/OKF_NOTES.md) for the full contract.
## Supported formats
See [docs/FORMAT_MATRIX.md](docs/FORMAT_MATRIX.md) for the full engine × library table. At a glance:
| Format | Engine | Library |
|---|---|---|
| `.docx`, `.xlsx`, `.pptx` | OfficeCLI binary | (native DOM) |
| `.pdf` | pdfplumber (text-layer), pytesseract if `--ocr` | pdfplumber / pytesseract |
| `.html`, `.htm` | BeautifulSoup | beautifulsoup4 |
| `.txt` | chardet + read | chardet |
| `.md`, `.markdown` | pass-through + frontmatter inject | stdlib |
| `.csv`, `.tsv` | Sniffer dialect + GFM table (zsv SIMD when installed) | stdlib `csv` (or `zsv` binary) |
| `.json` | pretty-print + fenced block | stdlib `json` |
| `.eml` | headers + text/html body + attachments | stdlib `email` |
| `.epub` | per-chapter HTML → MD | ebooklib (+ bs4 fallback) |
| `.rtf` | control-word stripping | striprtf (+ regex fallback) |
| `.odt`, `.ods`, `.odp` | paragraph/row extraction + GFM tables | odfpy (+ raw-XML fallback) |
| `.msg` | Outlook headers + body + attachments | extract-msg |
| `.pst` | **per-message** (one OKF concept per email) | readpst (libpst) + libpff-python fallback |
| `.docx`, `.xlsx`, `.pptx` | **office_oxide** (primary, ~100x faster), OfficeCLI binary (fallback) | office_oxide 0.1.8 (PyO3) |
| `.ipynb`, `.latex`, `.rst`, sourcecode, `.enex`, `.chm`, etc. (38 formats) | all2md (when installed) | all2md 1.12 |
| `.doc`, `.xls`, `.ppt` | clear error path | needs `libreoffice --convert-to` first |
## Live mode
```bash
headcleaner watch ~/inbox --output ~/out --webhook-url https://hooks.slack.com/...Reejecuta la conversión automáticamente cuando los archivos cambian en ~/inbox. Cada reejecución envía el manifiesto a la URL del webhook (opcional). Pulsa Ctrl+C para detener.
Sincronización con Obsidian
headcleaner convert ~/inbox --format okf \
--output ~/Documents/MyVault/Concepts \
--obsidian-compatAñade campos planos compatibles con Obsidian (source, sha256, generated_by, verified_by, stale_on) al frontmatter de OKF para que el concepto se muestre correctamente en el panel de propiedades de Obsidian. Los campos OKF originales se mantienen intactos para el ciclo de ida y vuelta.
Revisión (aprobación humana)
La conversión automática establece verified: human:pending. La TUI headcleaner review recorre cada concepto pendiente en un paquete y permite que una persona lo cambie a:
aprobado →
verified: human:reviewed,status: verified,reviewed_at,reviewed_by,reviewed_viarechazado →
verified: human:rejected,status: rejected,rejection_reasons[]opcionalomitido → deja el concepto como
pending
headcleaner review ./out/okf
# Textual TUI: a=approve, r=reject, s=skip, n=next, p=prev, q=quitSi Textual no está disponible (p. ej., CI sin interfaz gráfica), un REPL en modo simple se utiliza automáticamente como alternativa.
Distribución
PyPI:
pip install headcleaner(compilado con uv, publicado mediante publicación de confianza OIDC al hacer push de una etiqueta)Homebrew:
brew install headcleaner(fórmula enpackaging/homebrew/)Docker:
docker pull ghcr.io/local/headcleaner(imagen multietapa con tesseract)Windows:
winget install headcleaner,scoop install headcleaner,choco install headcleanerBinario estático:
pip install pyinstaller && pyinstaller packaging/pyinstaller/headcleaner.spec
Lista de verificación completa de publicación en RELEASE.md.
Superficie de la CLI
headcleaner view <bundle> (añade --tui para explorar en la terminal) renderiza un paquete OKF como un único gráfico HTML autocontenido (sin backend, se abre en cualquier navegador). Consulta docs/VIEWER.md para ver todas las opciones.
headcleaner convert IN_DIR [flags] # walk + convert
headcleaner watch IN_DIR [flags] # live mode + webhooks
headcleaner review BUNDLE # human sign-off TUI/REPL
headcleaner attest BUNDLE [--private-key PEM] # Merkle root + optional ed25519 sig
headcleaner verify BUNDLE [--public-key PEM] # verify an attestation
headcleaner serve BUNDLE [--host] [--port] # local HTTP browser for the bundle
headcleaner glob DIR # interactive include REPL (Textual)
headcleaner notion-import EXPORT.zip OUT # reverse a Notion workspace export
headcleaner lint DIR [--fix] # OKF + MD rule checks
headcleaner doctor [--output-dir] # dependency and permission preflight
headcleaner agents [stdout] # emit AGENTS.md
headcleaner templates # list supported formatsDocumentación
Documento | Propósito |
este archivo — instalación, inicio rápido, referencia de la CLI | |
todas las rutas de instalación (curl, pip, brew, PowerShell, uv, Docker) | |
guía de uso detallada con ejemplos prácticos | |
cómo encaja el pipeline y dónde ampliarlo | |
todos los formatos × motores × librerías compatibles | |
contrato OKF v0.2 que emite esta CLI + política de confianza | |
esquema JSON del frontmatter OKF e integración con editores/CI | |
protocolo de puntos de entrada para adaptadores de terceros | |
errores comunes y sus soluciones | |
preguntas frecuentes | |
cómo añadir un nuevo formato / motor / emisor | |
historial de versiones | |
44+ mejoras implementadas + ideas futuras | |
extensión HeadCleaner para VS Code (Concept Explorer + Trust Inspector) |
Solución de problemas
officecli not found — instálalo con npm install -g @officecli/officecli. Ejecuta headcleaner agents para verificarlo.
PDF sin texto extraíble — tu PDF es solo de imágenes. Vuélvelo a ejecutar con --ocr (requiere pytesseract + el binario de Tesseract en PATH).
Archivos ocultos omitidos — intencional. El recorredor descarta los archivos que comienzan con ..
Falta OKF index.md para la raíz — se genera automáticamente cuando el paquete tiene ≥1 concepto. Usa --no-okf-index para excluirlo.
Más — consulta docs/TROUBLESHOOTING.md.
Desarrollo
git clone <this repo>
cd headcleaner-cli
uv sync
uv run pytest # 314 tests, ~14s
uv run headcleaner convert ./tests/fixtures --format both --output ./outArquitectura
src/headcleaner/
├── walk.py # recursive folder walker
├── router.py # extension → engine dispatch
├── normalize.py # CanonicalDoc + OKF/MD frontmatter builders
├── lint.py # post-conversion linter (OKF + Markdown)
├── run.py # pipeline orchestrator
├── cli.py # Click CLI (headcleaner command)
├── tui.py # Textual TUI (omp-style)
├── engines/
│ ├── base.py # Adapter ABC
│ ├── officecli.py
│ ├── pdf.py
│ ├── html.py
│ └── txt.py
└── emit/
├── markdown.py
├── okf.py
├── okf_index.py
└── manifest.pyPara añadir un nuevo formato: coloca un módulo en engines/, registra el adaptador en router.py y añade una fila a docs/FORMAT_MATRIX.md. Consulta docs/CONTRIBUTING.md para la guía completa de extensión.
Licencia
Apache-2.0
Available Tools
19 toolsget_chunkC
Return one cited chunk after root, policy, and index validation.
Inputs: chunk_id (required), bundle. Returns: object
get_diagnosticsB
Return a stable, content-free diagnostics envelope for a local bundle.
Inputs: bundle. Returns: object
get_readinessC
Return a stable, content-free readiness envelope for a local bundle.
Inputs: bundle. Returns: object
list_review_queueC
Return a stable, content-free review-queue envelope for a local bundle.
Inputs: limit, bundle. Returns: object
okf_context_toolC
Assemble legacy graph context and an additive indexed package when available.
Inputs: depth, start, bundle, max_tokens.
okf_diff_toolC
What changed on disk since the bundle was loaded.
Inputs: bundle.
okf_doctor_toolB
Health report for a bundle (score, errors, warnings, per-rule findings).
Inputs: bundle, stale_days.
okf_get_concept_toolA
Read one concept (frontmatter + body). Accepts id, title, or filename stem.
Inputs: target (required), bundle.
okf_impact_toolB
Report outbound / inbound / transitive links for a concept.
Inputs: concept (required), bundle.
okf_list_bundles_toolA
List the OKF bundles this server has loaded.
Inputs: no named parameters. Returns: result
okf_refresh_toolC
Re-ingest a bundle so the in-memory catalog reflects current files.
Inputs: bundle.
okf_registry_addB
Add a bundle under a slug alias. Then reference it as @/... .
Example:
okf_registry_add(slug="docs", bundle_path="C:/Users/me/Documents/okf")
okf_get_concept("@docs/readme")
Inputs: slug (required), bundle_path (required).
okf_registry_listA
List all bundles registered under @slug aliases.
Inputs: no named parameters. Returns: result
okf_registry_removeB
Remove a slug from the registry.
Inputs: slug (required).
okf_registry_resolveA
Resolve @slug/concept to the bundle path + concept id.
Inputs: target (required).
okf_search_toolB
Search one or all loaded bundles.
Set all_bundles=True to search across every bundle currently registered
with the server. Hits from other bundles include a `bundle` field.
Inputs: term (required), limit, bundle, all_bundles. Returns: result
okf_sql_toolA
Read-only SELECT over the in-memory catalog (concepts, links).
Inputs: query (required), bundle. Returns: result
search_chunksC
Return cited, policy-gated chunks from an existing local bundle index.
Inputs: query (required), limit, bundle. Returns: object
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 19 tools
Several tool groups are hard to distinguish: okf_related_tool vs okf_impact_tool both analyze links, search_chunks vs okf_search_tool both search, and okf_doctor_tool/get_diagnostics/get_readiness/list_review_queue all sound like status/health endpoints. The descriptions help only after close reading, but an agent could easily pick the wrong tool.
Naming conventions are mixed: some tools use okf_*_tool, some use bare get_*/list_* verbs, and registry tools use okf_registry_*. There is no consistent verb_noun or prefix/suffix rule across the set.
19 tools is on the heavy side; many are justified by the range of bundle, registry, search, SQL, and graph-analysis capabilities, but the status-envelope and search/link-analysis overlaps add bulk. It is not egregiously overpopulated, but it exceeds the comfortable 3-15 range.
The server covers the main read-side lifecycle: list/load bundles, search/read concepts and chunks, inspect health/diff, manage registry aliases, and run SQL. Missing mutation tools for bundle content and review actions are likely out of scope, forming only minor gaps agents can work around.
Maintenance
Related MCP Connectors
Generate PDF, Word (.docx) and PowerPoint (.pptx) documents from Markdown over MCP.
Document conversion MCP server: PDF to Markdown, image OCR, spreadsheet parsing.
Document-to-Markdown MCP server — convert PDF, Office and HTML into LLM-ready Markdown.
Convert scanned PDFs to Markdown or EPUB, and translate PDF and EPUB books via MCP.
Related MCP Servers
- AlicenseDqualityDmaintenanceEnables reading, writing, editing, and converting Office documents (ODT, DOCX, ODS, XLSX, PDF, etc.) using MCP tools, with no external dependencies.1121 npmMIT
- AlicenseAqualityDmaintenanceEnables local semantic search and management of OKF knowledge bundles via MCP tools, with hybrid BM25 and vector search.104Apache 2.0
- AlicenseNot gradedqualityDmaintenanceProvides tools for AI agents to navigate and query OKF knowledge bundles through overview, read, search, and list operations.545 PyPIApache 2.0
- AlicenseNot gradedqualityBmaintenanceEnables document conversion and processing through MCP, including Office/PDF/Markdown conversions, OCR, and PDF operations like split, rotate, encrypt, and extract.MIT