Split a policy section on its strongest boundaries into chunks under a token limit, then pack reranked chunks into a token budget, best first, without duplicates or weak evidence.
MegaMart Assist answers from its policy pages. Two pieces of Day 3 decide what the model actually reads:
Tokens here are whitespace-separated words: count_tokens is given, so the tests are exact.
split_section(doc_id, title, text, max_tokens) returns a list of Chunks:
max_tokens, it's one chunk.SEPARATORS ("\n\n", then "\n", then " ") that occurs in the text. Drop empty pieces (after strip()). Walk the pieces in order, joining consecutive pieces with that separator while the result fits; start a new chunk when the next piece won't fit.max_tokens is split recursively with the next separator, and its chunks take their place in order.id = f"{doc_id}:{n}" numbered from 0 in order, doc_id, title, the chunk's text (stripped), tokens = count_tokens(text), content_hash = hash_text(text) and score = 0.0.assemble(chunks, budget, min_score=0.35) returns None or (context, ids):
score, highest first (ties: id alphabetical).min_score: weak evidence doesn't get in, however much room is left.content_hash was already picked (the same text from another doc).budget, and keep going: a smaller one may still fit.None (the caller abstains or hands off). Otherwise context = "\n".join(render(c) for c in picked) and ids in the same order.In JavaScript and TypeScript the functions are splitSection(docId, title, text, maxTokens) and assemble(chunks, budget, minScore = 0.35), which returns null or the array [context, ids]. The given code has the same helpers: SEPARATORS, countTokens, hashText (the same hashes as Python's), render, words(n, start = 0, word = "w") and new Chunk(id, docId, title, text, tokens, contentHash, score = 0), whose fields are docId and contentHash. strip() is trim().
Write your code, then run 3 example tests and 9 hidden tests. Each run is limited to 8 seconds: an infinite loop gets stopped and the runtime restarts, your code stays.