Skip to main content
Glama

headcleaner

Обходит папку, преобразует каждый документ в Markdown (с frontmatter), OKF v0.2 (с frontmatter) или в оба — с анимированным TUI в стиле omp.

headcleaner convert ~/Documents/inbox --format both --output ~/Documents/inbox.clean

headcleaner — это Python CLI, который сканирует указанную вами директорию, определяет каждый документ по расширению, запускает подходящий механизм извлечения (OfficeCLI для офисных форматов, pdfplumber для PDF, BeautifulSoup для HTML и т.д.) и выдаёт чистый нормализованный результат — либо Markdown и OKF рядом, либо только один.

  • Форматы вывода: --format md (Markdown), --format okf (набор OKF v0.2), --format both (по умолчанию)

  • Покрытие движками: 7 форматов из коробки (XLSX, DOCX, PPTX, PDF, HTML, HTM, TXT) — см. docs/FORMAT_MATRIX.md с дорожной картой 16 форматов к v1.0

  • TUI: анимированный терминал в стиле omp (панели с псевдографикой, неоновая палитра, разделители powerline)

  • Линтер: headcleaner lint проверяет преобразованные Markdown / OKF на проблемы форматирования

  • PST по сообщениям: один концепт OKF на каждое письмо (через readpst), поэтому проверка и согласование работают файл за файлом

  • Бэкенд office_oxide: чистые Python-привязки на Rust для офисных форматов (~100x быстрее OfficeCLI)

  • Эвристическая очистка: headcleaner convert --clean запускает 12-этапный конвейер очистки, вдохновлённый any2md

  • Запасной вариант all2md: автоматически обрабатывает 38 дополнительных форматов (Jupyter, LaTeX, reST, исходный код и т.д.), если установлен all2md

  • headcleaner mcp: запуск headcleaner в качестве MCP-сервера, предоставляющего 14 инструментов okf_* любому хосту MCP-агентов (Claude Code, Cursor и т.д.) — установка через uv pip install "headcleaner[mcp]"

  • Диагностика: headcleaner doctor проверяет Python, PATH, OfficeCLI, права на вывод и реестр @slug, затем выдаёт вердикт GO/NO-GO

  • Плагины адаптеров: сторонние пакеты регистрируют форматы через группу точек входа headcleaner_plugin

  • zsv CSV: самый быстрый в мире SIMD-парсер CSV (~10-100x быстрее stdlib), когда zsv есть в PATH

  • Аттестация доверия: headcleaner attest строит корень Меркла + подпись ed25519; verify проверяет её

  • Локальный просмотр: headcleaner serve <bundle> предоставляет FastAPI-интерфейс для просмотра и поиска

  • Честные значения по умолчанию: поля доверия OKF заполняются unverified / human:pending, никогда не выдумываются

Установка

# 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 --help

Другие способы установки (curl | bash, pip, brew, Windows PowerShell) см. в docs/INSTALL.md.

Related MCP server: okf-tools

Быстрый старт

headcleaner ~/Documents/inbox --format both --output ./clean

В результате получается:

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
    └── ...

Справочник по 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 generation

Другие команды: headcleaner doctor [--output-dir DIR] Запуск диагностики установки и прав headcleaner templates Список поддерживаемых форматов headcleaner agents Показать статус установки движков headcleaner watch IN [--webhook-url URL] Повторное преобразование при изменении файлов (Ctrl+C для остановки) headcleaner lint Проверка преобразованных Markdown / OKF на проблемы форматирования headcleaner lint --fix Автоисправление безопасных проблем в .fixed/ headcleaner serve Локальный HTTP-браузер для набора OKF headcleaner notion-import <EXPORT.zip> Реверсирование экспорта рабочего пространства Notion headcleaner attest Вычисление корня Меркла + опциональная подпись ed25519 headcleaner verify Проверка аттестации относительно набора

## 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/...

Автоматически перезапускает преобразование при изменении файлов в ~/inbox. Каждый повторный запуск отправляет манифест на URL вебхука (опционально). Нажмите Ctrl+C для остановки.

Синхронизация хранилища Obsidian

headcleaner convert ~/inbox --format okf \
    --output ~/Documents/MyVault/Concepts \
    --obsidian-compat

Добавляет плоские поля, совместимые с Obsidian (source, sha256, generated_by, verified_by, stale_on), в frontmatter OKF, чтобы концепт корректно отображался в панели свойств Obsidian. Исходные поля OKF остаются нетронутыми для обратного преобразования.

Проверка (согласование человеком)

Автоконвертация устанавливает verified: human:pending. TUI headcleaner review проходит по всем ожидающим концептам в наборе и позволяет человеку переключить каждый из них на:

  • approved → verified: human:reviewed, status: verified, reviewed_at, reviewed_by, reviewed_via

  • rejected → verified: human:rejected, status: rejected, опциональный rejection_reasons[]

  • skipped → оставляет концепт как pending

headcleaner review ./out/okf
# Textual TUI: a=approve, r=reject, s=skip, n=next, p=prev, q=quit

Если Textual недоступен (например, headless CI), автоматически используется REPL в простом режиме.

Распространение

  • PyPI: pip install headcleaner (сборка через uv, публикация через OIDC trusted publishing при пуше тега)

  • Homebrew: brew install headcleaner (формула в packaging/homebrew/)

  • Docker: docker pull ghcr.io/local/headcleaner (многоступенчатый образ с tesseract)

  • Windows: winget install headcleaner, scoop install headcleaner, choco install headcleaner

  • Статический бинарник: pip install pyinstaller && pyinstaller packaging/pyinstaller/headcleaner.spec

Полный чек-лист релиза в RELEASE.md.

Поверхность CLI

headcleaner view <bundle> (добавьте --tui для просмотра в терминале) отображает набор OKF как единый автономный HTML-граф (без бэкенда, открывается в любом браузере). Полные опции см. в docs/VIEWER.md.

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 formats

Документация

Документ

Назначение

README.md

этот файл — установка, быстрый старт, справочник по CLI

docs/INSTALL.md

все способы установки (curl, pip, brew, PowerShell, uv, Docker)

docs/USAGE.md

подробное руководство по использованию с примерами

docs/ARCHITECTURE.md

как устроен конвейер и где его расширять

docs/FORMAT_MATRIX.md

все поддерживаемые форматы × движки × библиотеки

docs/OKF_NOTES.md

контракт OKF v0.2, который выдаёт этот CLI + политика доверия

docs/SCHEMA.md

JSON-схема frontmatter OKF и интеграция с редакторами/CI

docs/PLUGINS.md

протокол точек входа для сторонних адаптеров

docs/TROUBLESHOOTING.md

частые ошибки и их исправление

docs/FAQ.md

часто задаваемые вопросы

docs/CONTRIBUTING.md

как добавить новый формат / движок / эмиттер

docs/CHANGELOG.md

история релизов

docs/ENHANCEMENTS.md

44+ реализованных улучшений и будущие идеи

vscode-extension/README.md

расширение HeadCleaner для VS Code (Concept Explorer + Trust Inspector)

Устранение неполадок

officecli not found — установите с помощью npm install -g @officecli/officecli. Выполните headcleaner agents для проверки.

PDF без извлекаемого текста — ваш PDF содержит только изображения. Повторно запустите с --ocr (требуются pytesseract и бинарник Tesseract в PATH).

Скрытые файлы пропускаются — это намеренно. Файлы, начинающиеся с ., отбрасываются обходчиком.

Отсутствует index.md OKF для корня — автоматически создаётся, когда в наборе есть ≥1 концепт. Используйте --no-okf-index, чтобы отказаться.

Подробнее — см. docs/TROUBLESHOOTING.md.

Разработка

git clone <this repo>
cd headcleaner-cli
uv sync
uv run pytest                # 314 tests, ~14s
uv run headcleaner convert ./tests/fixtures --format both --output ./out

Архитектура

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.py

Добавление нового формата: поместите модуль в engines/, зарегистрируйте адаптер в router.py, добавьте строку в docs/FORMAT_MATRIX.md. Полное руководство по расширению см. в docs/CONTRIBUTING.md.

Лицензия

Apache-2.0

Available Tools

19 tools
get_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

    C2.7/5.0

    Scored across 19 tools

    Disambiguation2/5

    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 Consistency2/5

    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.

    Tool Count3/5

    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.

    Completeness4/5

    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

    ActivityStale
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      D
      quality
      D
      maintenance
      Enables reading, writing, editing, and converting Office documents (ODT, DOCX, ODS, XLSX, PDF, etc.) using MCP tools, with no external dependencies.
      11
      21 npm
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables document conversion and processing through MCP, including Office/PDF/Markdown conversions, OCR, and PDF operations like split, rotate, encrypt, and extract.
      MIT