feat(chunker): heading-aware Tier 1 splitter

splitByHeadingsImpl detects the dominant Markdown heading level via the
profiler and splits the document at headings of that level (or shallower).
Each resulting chunk gets a breadcrumb prefix like
'# Chapter 1\n## Section 1.2' so downstream embedding sees the section
context, not just the body. Sections larger than ChunkSize fall back to
the legacy splitter for inner segmentation, with the breadcrumb prepended
to every sub-chunk and ChunkSize reduced by the breadcrumb length so the
final chunk still fits the budget.

- DominantHeadingLevel: prefer the lowest level with ≥3 hits, else the
  deepest level with ≥1 hit (so small docs with H1+H2 still split at H2)
- HeadingHierarchy state is updated for sub-headings within a section so
  later primary sections see the right active stack
- Code-block contents are skipped during heading detection so a `# foo`
  inside ``` doesn't create a fake boundary
- strategy.go uses context.Background() for the fallback log entry
  (GetLogger panics on nil context)

https://claude.ai/code/session_01XADhx6mtu2ZYW3DE9Lun6k
This commit is contained in:
Claude
2026-05-02 09:26:40 +00:00
committed by lyingbug
parent 592d3618dc
commit cf8789f84c
4 changed files with 346 additions and 11 deletions
+11 -9
View File
@@ -49,9 +49,13 @@ func (p *DocProfile) HeadingDensity() float64 {
}
// DominantHeadingLevel returns the heading level (1..6) that should drive
// section splitting. It picks the lowest level (closest to root) that has
// at least 3 occurrences, falling back to the most frequent level. Returns
// 0 when no usable Markdown structure exists.
// section splitting. Preference order:
// 1. The lowest level (closest to root) that has at least 3 occurrences —
// a "real" structural backbone of the document.
// 2. Otherwise the deepest level present at least once — gives finer-grained
// boundaries for small documents that just have an H1 + a few H2s.
//
// Returns 0 when no Markdown headings exist.
func (p *DocProfile) DominantHeadingLevel() int {
if p.MdHeadingTotal == 0 {
return 0
@@ -61,14 +65,12 @@ func (p *DocProfile) DominantHeadingLevel() int {
return level
}
}
// fallback: most frequent level
bestLevel, bestCount := 0, 0
for level := 1; level <= 6; level++ {
if p.MdHeadingCounts[level] > bestCount {
bestLevel, bestCount = level, p.MdHeadingCounts[level]
for level := 6; level >= 1; level-- {
if p.MdHeadingCounts[level] > 0 {
return level
}
}
return bestLevel
return 0
}
// HeuristicMarkerTotal sums the non-Markdown structural markers.