Skip to content

feat: implement hierarchical AST extraction with prefaces and fallback support - #57

Open
IbukunChife wants to merge 4 commits into
virgiliojr94:masterfrom
IbukunChife:improvement/hierarchical-ast
Open

feat: implement hierarchical AST extraction with prefaces and fallback support#57
IbukunChife wants to merge 4 commits into
virgiliojr94:masterfrom
IbukunChife:improvement/hierarchical-ast

Conversation

@IbukunChife

Copy link
Copy Markdown

What & why

Este Pull Request implementa a extração de uma Árvore de Granularidade do Documento (Hierarchical AST) em detect_structure. O objetivo é combater a "tributação de contexto" desnecessária em agentes de IA, permitindo que as ferramentas localizem dinamicamente e cortem apenas fatias (slices) exatas de capítulos ou subseções do documento para o contexto de prompts.

As responsabilidades e regras de design foram desenhadas de forma extremamente robusta:

  • Resolução de Aninhamento Recursivo: Cabeçalhos estruturais (Markdown ATX/Setext/RST) e explícitos ("Chapter N") são organizados de forma hierárquica baseados em profundidade, associando filhos de nível maior a pais de nível menor por meio de um algoritmo baseado em pilha ($O(N)$).
  • Cobertura de 100% de Caracteres:
    • Tratamento de Prefácios: Criamos um nó virtual "Prefácio / Introdução" se houver conteúdo não-vazio no texto antes do primeiro cabeçalho oficial do capítulo 1.
    • Suporte a Documentos sem Cabeçalhos (Plano de Contingência): Se um documento ou livro for plano e não possuir subseções nem cabeçalhos clássicos detectados, criamos automaticamente um único nó virtual "Documento Completo" mapeando do caractere 0 a len(text), garantindo que a AST nunca retorne vazia.
    • Limites de Caracteres: Cada nó da AST possui "start_char" e "end_char" precisos delimitando a respectiva seção.

Evidence

  • Testes Unitários: Criados 4 novos testes unitários em tests/test_chapter_detector.py cobrindo cenários recursivos complexos, livros planos normais de múltiplos capítulos, documentos sem cabeçalhos e textos com prefácios iniciais.
  • Sucesso dos Testes: Suite de 124 testes unitários (pytest) passando com 100% de sucesso.
  • Linter: ruff check executado com sucesso e retornando perfeitamente limpo (All checks passed!).

Checklist

  • One focused change
  • Tests added/updated for behavior changes
  • ruff check . clean
  • pytest -q green
  • python3 tools/validate_skill.py SKILL.md passes (não modificado)
  • CHANGELOG.md updated under ## [Unreleased]
  • No raw book text shipped; no net SKILL.md bloat without justification

@virgiliojr94

Copy link
Copy Markdown
Owner

Ibukun — thanks for pushing on this. Two things blocking a merge as-is:

  1. Add chapter offsets, CJK token estimate, OCR, fidelity check, and self-bootstrap #70 (jsconiers) already ships chapter offsets in metadata.json and wires them into SKILL.md Step 7 as a flat chapters[] list. The offsets goal here is covered by that PR with a much smaller diff.
  2. The nested ast tree in this PR has no consumer — SKILL.md doesn't slice from it and there's no discovery_tax measurement showing hierarchy improves generation. Per the "measure, don't assert" rule, I can't merge speculative infra.

The path I'd suggest: open the architecture issue we discussed with a discovery_tax A/B — flat offsets vs nested AST — on 2-3 real books. If hierarchy wins, land the AST with the SKILL.md consumer in the same PR. Otherwise let's close it in favor of #70.

One more note: the virtual nodes hardcode Portuguese strings ("Prefácio / Introdução", "Documento Completo"). Since the tool runs across languages, those would need to be language-neutral or localized before merge.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants