SkilVaultSign inStart free

Catalogue / evidence-preserving-chunking

evidence-preserving-chunking

Older skill: source not recordedSignedBuilds and benchmarks document segmentation for retrieval-augmented systems with exact source provenance: character and model-token windows, recursive, structural, semantic, clustered, hierarchical and hybrid splitters, contextual retrieval, late chunking, frozen-dataset evaluation with ranking metr…
---
name: evidence-preserving-chunking
description: >-
  Builds and benchmarks document segmentation for retrieval-augmented systems
  with exact source provenance: character and model-token windows, recursive,
  structural, semantic, clustered, hierarchical and hybrid splitters,
  contextual retrieval, late chunking, frozen-dataset evaluation with ranking
  metrics, bounded caching, streaming, and HTML/SVG reporting, all as compact
  inline Python modules. Use when the user says "chunk documents for RAG",
  "split PDFs or Markdown for embeddings", "compare chunking strategies",
  "tune chunk size or overlap", or "evaluate retrieval quality". Not for
  prompt engineering, model fine-tuning, or operating a live production index.
---

Evidence-Preserving Chunking Lab

Segmentation is an experiment, not a guess: chunks keep exact source offsets, claims are recomputable numbers, risky side effects are named first. Extract each block to its named file in one directory; imports resolve.

Ground rules and inputs

Record per document: ID and revision, language, format, extraction step, character count, tokenizer identity, confidentiality, question types.

  • Keep the file digest beside the extracted-text digest; offsets refer to

canonical text, never PDF bytes. Preserve negations, units, deadlines, table headers, warnings and relational context.

  • Freeze gold source spans before comparing strategies; split corpus and

questions into train / calibration / held-out by document.

  • Characters are not tokens: size from the real tokenizer and retrieval

budget, and evaluate overlap separately from coverage.

  • An oversized sentence, code node or table gets an explicit policy — larger

budget, flagged split, or reported failure. Never silently discard.

Ask before: writing files, installing packages or models, sending corpus text to a provider, creating or deleting index data, clearing caches. Show exact paths and data volume; wait for a yes.

Choose a strategy

| Level | Method | Fits | Guardrail | |---|---|---|---| | 1 | Fixed character windows | unstructured prose | 10–20% overlap; tune per query type | | 2 | Recursive separators | paragraph/sentence structure | hierarchy ends in a hard size cap | | 3 | Structure-aware | Markdown, code, tables, PDF/DOCX | headings, fences, functions and rows stay whole | | 4 | Semantic boundaries | thematic drift in long prose | threshold + sentence buffer + hard size cap together | | 5 | Contextual / late chunking | high-precision retrieval | provider calls need an approved scope; pooling needs a long-context encoder |

Advanced variants: adaptive overlap, cluster boundaries (k-means, agglomerative, DBSCAN), local dips, hierarchy, hybrid dedup, agentic selection, mixed-content routing, span merging, multi-threshold levels.

| Corpus shape | Method | Check afterwards | |---|---|---| | Plain prose | windows, recursive | punctuation, abbreviations, coverage | | Headed manual | Markdown sections | fenced code, heading paths | | Python source | AST top-level units | imports, decorators, nested defs kept once | | CSV | row groups with embedded headers | multiline quotes, header context | | HTML | canonical blocks | scripts dropped, alt text kept, links unfetched | | PDF / DOCX | bounded local extraction | page provenance, missing OCR flagged | | Topic drift | embedding or topic boundaries | held-out boundaries, size cap respected | | Distant related sections | hierarchy + hybrid | parent expansion, duplicates, source order | | Confidential text | local models, scoped caches | nothing sent out, no raw text in metrics |

Core: span-exact chunking (spans.py)

Contracts: chunk IDs derive from document, revision, span, method; validate rejects any chunk whose text or ID mismatches its span and reports coverage as a character union, so overlaps show up as duplication instead of inflating coverage. units splits oversized units only under an explicit flag; window strides must keep forward progress; counted_windows budget-checks but does not promise maximal chunks (BPE counts are not monotonic); semantic cuts always respect the hard size cap.

"""Span-exact chunking core. No network, no downloads, no writes."""
import ast, dataclasses, hashlib, math, re
from collections.abc import Callable

def need(ok, msg='invalid input'):
    if not ok: raise ValueError(msg)

@dataclasses.dataclass(frozen=True)
class Document:
    id: str; text: str; revision: str = '1'
    def __post_init__(self):
        need(self.id and self.revision and isinstance(self.text, str) and len(self.text) <= 5_000_000)
        self.text.encode('utf-8', errors='strict')

@dataclasses.dataclass(frozen=True)
class Chunk:
    id: str; document: str; revision: str
    start: int; end: int; text: str
    method: str; metadata: dict = dataclasses.field(default_factory=dict)

def make(doc, start, end, method, **meta):
    need(type(start) is int and type(end) is int and 0 <= start < end <= len(doc.text))
    seed = '\0'.join([doc.id, doc.revision, str(start), str(end), method,
                      hashlib.sha256(doc.text.encode()).hexdigest()])
    return Chunk(hashlib.sha256(seed.encode()).hexdigest()[:24], doc.id, doc.revision,
                 start, end, doc.text[start:end], method, meta)

def check_size(size, overlap=0):
    need(type(size) is int and 1 <= size <= 100_000 and 0 <= overlap < size)

def windows(doc, size=800, overlap=80, step=None):
    check_size(size, overlap)
    stride = size - overlap if step is None else step
    need(1 <= stride <= size)
    out, start = [], 0
    while start < len(doc.text):
        end = min(start + size, len(doc.text))
        out.append(make(doc, start, end, 'character-window', unit='characters'))
        if end == len(doc.text): break
        start += stride
    return out

def counted_windows(doc, count: Callable[[str], int], limit=512, overlap_chars=0):
    check_size(limit); need(overlap_chars >= 0)
    out, start = [], 0
    while start < len(doc.text):
        lo, hi, best = start + 1, len(doc.text), None
        while lo <= hi:
            mid = (lo + hi) // 2
            if count(doc.text[start:mid]) <= limit: best, lo = mid, mid + 1
            else: hi = mid - 1
        need(best is not None, 'single character over token budget')
        out.append(make(doc, start, best, 'counted-window', unit='model-tokens',
                        count=count(doc.text[start:best]), limit=limit))
        if best == len(doc.text): break
        nxt = best - overlap_chars
        need(nxt > start)
        start = nxt
    return out

def recursive(doc, size=800, separators=('\n\n', '\n', ' ', '')):
    check_size(size); out = []
    def split(start, end, level):
        if end - start <= size:
            out.append(make(doc, start, end, 'recursive', level=level)); return
        if level >= len(separators) or separators[level] == '':
            for pos in range(start, end, size):
                out.append(make(doc, pos, min(pos + size, end), 'recursive', fallback=True))
            return
        cuts, cursor = [], start
        while True:
            found = doc.text.find(separators[level], cursor, end)
            if found < 0: break
            cursor = found + len(separators[level]); cuts.append(cursor)
        if not cuts: split(start, end, level + 1); return
        begin = start
        for cut in cuts + [end]:
            if cut > begin: split(begin, cut, level + 1)
            begin = cut
    if doc.text: split(0, len(doc.text), 0)
    merged = []
    for c in out:
        if merged and c.end - merged[-1].start <= size:
            old = merged.pop(); merged.append(make(doc, old.start, c.end, 'recursive', merged=True))
        else: merged.append(c)
    return merged

def sentence_spans(text):
    cuts = [0] + [m.end() for m in re.finditer(r'(?<=[.!?])\s+', text)] + [len(text)]
    return [(a, b) for a, b in zip(cuts, cuts[1:]) if a < b]

def paragraph_spans(text):
    cuts = [0] + [m.end() for m in re.finditer(r'(?:\r?\n)[ \t]*(?:\r?\n)+', text)] + [len(text)]
    return [(a, b) for a, b in zip(cuts, cuts[1:]) if a < b]

def units(doc, spans, max_units=4, overlap_units=0, size=1000, method='units'):
    check_size(max_units, overlap_units); check_size(size)
    prev = 0
    for a, b in spans:
        need(a == prev and a < b <= len(doc.text)); prev = b
    need(prev == len(doc.text))
    out, i = [], 0
    while i < len(spans):
        j = i
        while j < len(spans) and j - i < max_units and spans[j][1] - spans[i][0] <= size: j += 1
        if j == i:
            a, b = spans[i]
            for pos in range(a, b, size):
                out.append(make(doc, pos, min(pos + size, b), method, oversized_unit=True))
            i += 1; continue
        out.append(make(doc, spans[i][0], spans[j - 1][1], method, first_unit=i, after_unit=j))
        if j == len(spans): break
        i = max(i + 1, j - overlap_units)
    return out

def markdown_sections(doc):
    offsets, titles, pos, fence = [0], {0: ('Preamble', 0)}, 0, None
    for line in doc.text.splitlines(keepends=True):
        m = re.match(r'^\s{0,3}(`{3,}|~{3,})', line)
        if m:
            ch = m.group(1)[0]
            if fence is None: fence = (ch, len(m.group(1)))
            elif ch == fence[0] and len(m.group(1)) >= fence[1]: fence = None
        if fence is None:
            h = re.match(r'^ {0,3}(#{1,6})\s+(.+?)(?:\s+#+)?\s*$', line.rstrip('\r\n'))
            if h:
                if pos not in offsets: offsets.append(pos)
                titles[pos] = (h.group(2), len(h.group(1)))
        pos += len(line)
    offsets.append(len(doc.text)); out, stack = [], []
    for a, b in zip(offsets, offsets[1:]):
        if a == b: continue
        title, level = titles.get(a, ('Preamble', 0))
        while stack and stack[-1][1] >= level: stack.pop()
        if level: stack.append((title, level))
        out.append(make(doc, a, b, 'markdown-section', title=title, heading_level=level,
                        heading_path=[t for t, _ in stack]))
    return out

def python_structure(doc, size=2000):
    check_size(size); tree = ast.parse(doc.text)
    pos = [0]
    for line in doc.text.splitlines(keepends=True): pos.append(pos[-1] + len(line))
    cuts = {0, len(doc.text)}
    for node in tree.body:
        first = min([node.lineno] + [d.lineno for d in getattr(node, 'decorator_list', [])]) - 1
        cuts |= {pos[first], pos[node.end_lineno]}
    out = []
    for a, b in zip(sorted(cuts), sorted(cuts)[1:]):
        if a == b: continue
        if b - a <= size:
            out.append(make(doc, a, b, 'python-top-level', syntax_preserved=True))
        else:
            for p in range(a, b, size):
                out.append(make(doc, p, min(p + size, b), 'python-top-level',
                                syntax_preserved=False, oversized_unit=True))
    return out

def union_length(spans):
    total, end = 0, -1
    for a, b in sorted(spans):
        need(0 <= a <= b)
        if b > end: total += b - max(a, end); end = b
    return total

def validate(doc, chunks):
    for c in chunks:
        need(c.document == doc.id and c.revision == doc.revision
             and 0 <= c.start < c.end <= len(doc.text)
             and c.text == doc.text[c.start:c.end]
             and c.id == make(doc, c.start, c.end, c.method).id, 'chunk lost source provenance')
    covered = union_length((c.start, c.end) for c in chunks)
    return {'coverage': covered / len(doc.text) if doc.text else 1.0,
            'source_characters': len(doc.text), 'covered_characters': covered,
            'duplicated_characters': sum(c.end - c.start for c in chunks) - covered,
            'chunks': len(chunks)}

def cosine(a, b):
    need(a and len(a) == len(b) and all(map(math.isfinite, [*a, *b])))
    denom = math.sqrt(sum(v * v for v in a)) * math.sqrt(sum(v * v for v in b))
    need(denom)
    return max(-1.0, min(1.0, sum(x * y for x, y in zip(a, b)) / denom))

Preview shortened. The full SKILL.md is in the pack.