diff --git a/bench/batch_bench.cpp b/bench/batch_bench.cpp index 49a79b3..508504c 100644 --- a/bench/batch_bench.cpp +++ b/bench/batch_bench.cpp @@ -41,9 +41,9 @@ int main() { auto emb = rag::plugin::make_embedder(nlohmann::json{{"type", "hash"}, {"dim", 384}}); c.set_embedder(std::move(*emb)); for (std::size_t i = 0; i < docs; ++i) - c.add_document("d" + std::to_string(i), - "retrieval document " + std::to_string(i) + - " about vectors graphs indexes ranking and search"); + (void)c.add_document("d" + std::to_string(i), + "retrieval document " + std::to_string(i) + + " about vectors graphs indexes ranking and search"); (void)c.build(); std::vector qs; diff --git a/bench/bench.cpp b/bench/bench.cpp index 15650ae..e774c5e 100644 --- a/bench/bench.cpp +++ b/bench/bench.cpp @@ -40,7 +40,7 @@ int main(int argc, char** argv) { auto t0 = Clock::now(); for (std::size_t i = 0; i < n; ++i) - engine.add("doc" + std::to_string(i), synth_doc(rng, 60)); + (void)engine.add("doc" + std::to_string(i), synth_doc(rng, 60)); auto t1 = Clock::now(); auto b = engine.build(); auto t2 = Clock::now(); diff --git a/bench/code_retrieval_bench.cpp b/bench/code_retrieval_bench.cpp index c236efc..43afeaa 100644 --- a/bench/code_retrieval_bench.cpp +++ b/bench/code_retrieval_bench.cpp @@ -26,8 +26,9 @@ // chunks. That isolates chunking, which is the claim. // // Usage: -// ragcpp_code_retrieval_bench \ +// ragcpp_code_retrieval_bench // --model=model.onnx --tokenizer=tokenizer.json [--limit=N] +// (one command; shown on two lines) // // Requires -DRAGCPP_WITH_ONNX=ON (otherwise there is no embedder and nothing to // measure). diff --git a/examples/advanced.cpp b/examples/advanced.cpp index 51b5d43..49af475 100644 --- a/examples/advanced.cpp +++ b/examples/advanced.cpp @@ -9,6 +9,7 @@ #include #include +#include "must.hpp" int main() { rag::Engine engine; @@ -28,8 +29,8 @@ int main() { "Risotto: toast arborio rice, then add warm stock gradually while " "stirring until creamy; finish with butter and parmesan.", }; - for (int i = 0; i < 7; ++i) engine.add("d" + std::to_string(i), docs[i]); - engine.build(); + for (int i = 0; i < 7; ++i) must(engine.add("d" + std::to_string(i), docs[i]), "add"); + must(engine.build(), "build"); const char* Q = "how does approximate nearest neighbour vector search work"; std::printf("Query: %s\n\n", Q); diff --git a/examples/full_pipeline.cpp b/examples/full_pipeline.cpp index 6b439e0..26c25be 100644 --- a/examples/full_pipeline.cpp +++ b/examples/full_pipeline.cpp @@ -6,6 +6,7 @@ #include #include +#include "must.hpp" int main() { using namespace rag; @@ -16,22 +17,22 @@ int main() { Engine engine(cfg); engine.with_embedder(dense::AnyEmbedder{dense::HashEmbedder{256}}); - engine.add("ann.md", + must(engine.add("ann.md", "# Approximate Nearest Neighbours\n\nHNSW builds a layered proximity graph " "for logarithmic-time vector search. Binary quantization speeds the walk.", - {{"section","index"}}); - engine.add("bm25.md", + {{"section","index"}}), "add"); + must(engine.add("bm25.md", "# Lexical Retrieval\n\nBM25 scores documents by term frequency and inverse " "document frequency, catching exact keyword matches embeddings miss.", - {{"section","lexical"}}); - engine.add("fusion.md", + {{"section","lexical"}}), "add"); + must(engine.add("fusion.md", "# Fusion\n\nReciprocal rank fusion combines lexical and dense rankings " "without score normalization, the most robust hybrid retrieval method.", - {{"section","fusion"}}); - engine.add("risotto.md", + {{"section","fusion"}}), "add"); + must(engine.add("risotto.md", "# Risotto\n\nToast arborio rice, then add warm stock one ladle at a time.", - {{"section","cooking"}}); - engine.build(); + {{"section","cooking"}}), "add"); + must(engine.build(), "build"); // A local cross-encoder stand-in: reward passages sharing query terms. rerank::ScoreFnReranker ce([](std::string_view q, std::string_view p) { diff --git a/examples/graphrag.cpp b/examples/graphrag.cpp index 6189239..ed56436 100644 --- a/examples/graphrag.cpp +++ b/examples/graphrag.cpp @@ -9,6 +9,7 @@ #include #include +#include "must.hpp" int main() { rag::Engine engine; @@ -16,22 +17,22 @@ int main() { // A small corpus where documents LINK to one another (markdown) and cluster // by topic. No embedder → similarity edges fall back to lexical Jaccard and // retrieval degrades gracefully to BM25. Attach an embedder for dense edges. - engine.add("intro.md", + must(engine.add("intro.md", "Retrieval-augmented generation grounds a language model on external " - "documents. See [dense](dense.md) and [graph](graph.md) for the engine internals."); - engine.add("dense.md", + "documents. See [dense](dense.md) and [graph](graph.md) for the engine internals."), "add"); + must(engine.add("dense.md", "The dense retriever embeds passages and ranks them by cosine similarity " - "over an HNSW index. It pairs with [lexical](lexical.md) BM25 scoring."); - engine.add("lexical.md", + "over an HNSW index. It pairs with [lexical](lexical.md) BM25 scoring."), "add"); + must(engine.add("lexical.md", "BM25 is the Okapi lexical ranker: term frequency saturation plus inverse " - "document frequency. It fuses with dense results via reciprocal rank fusion."); - engine.add("graph.md", + "document frequency. It fuses with dense results via reciprocal rank fusion."), "add"); + must(engine.add("graph.md", "GraphRAG builds a document graph — link edges and similarity edges — then " - "detects communities and summarizes each cluster for corpus-level questions."); - engine.add("cooking.md", + "detects communities and summarizes each cluster for corpus-level questions."), "add"); + must(engine.add("cooking.md", "Risotto: toast arborio rice, then ladle warm stock gradually while stirring " - "until creamy. Finish with butter and parmesan off the heat."); - engine.build(); + "until creamy. Finish with butter and parmesan off the heat."), "add"); + must(engine.build(), "build"); // ── Document graph ───────────────────────────────────────────────────────── auto g = engine.graph(); diff --git a/examples/must.hpp b/examples/must.hpp new file mode 100644 index 0000000..3b68cd4 --- /dev/null +++ b/examples/must.hpp @@ -0,0 +1,13 @@ +#pragma once +// examples/must.hpp - one helper every example uses: an example must not +// swallow a failure, so it reports it and stops. + +#include +#include + +inline void must(const auto& result, const char* what) { + if (!result) { + std::fprintf(stderr, "%s failed: %s\n", what, result.error().message.c_str()); + std::exit(1); + } +} diff --git a/examples/plugin_backend/host_demo.cpp b/examples/plugin_backend/host_demo.cpp index 6a112f7..89f4097 100644 --- a/examples/plugin_backend/host_demo.cpp +++ b/examples/plugin_backend/host_demo.cpp @@ -8,6 +8,7 @@ #include #include +#include "../must.hpp" int main(int argc, char** argv) { // Path to the compiled plugin (defaults to the CMake output location). @@ -45,9 +46,9 @@ int main(int argc, char** argv) { return 1; } - engine.add("d1", "The Eiffel Tower is in Paris."); - engine.add("d2", "Photosynthesis happens in plant leaves."); - engine.build(); + must(engine.add("d1", "The Eiffel Tower is in Paris."), "add"); + must(engine.add("d2", "Photosynthesis happens in plant leaves."), "add"); + must(engine.build(), "build"); auto hits = engine.search("landmark in Paris", 2); if (hits) { diff --git a/examples/plugin_backend/local_embedder_plugin.cpp b/examples/plugin_backend/local_embedder_plugin.cpp index 8cd1cd4..b40c4b1 100644 --- a/examples/plugin_backend/local_embedder_plugin.cpp +++ b/examples/plugin_backend/local_embedder_plugin.cpp @@ -14,8 +14,7 @@ // of the host and no host knowledge that this type exists. // // Build (standalone, MUST match the host toolchain and rag headers/ABI): -// g++-15 -std=c++23 -fPIC -shared -I/include \ -// local_embedder_plugin.cpp -o liblocal_ngram.so +// g++-15 -std=c++23 -fPIC -shared -I/include local_embedder_plugin.cpp -o liblocal_ngram.so // Or via this repo's CMake (target: local_ngram_plugin). #include diff --git a/examples/plugin_backend/local_host_demo.cpp b/examples/plugin_backend/local_host_demo.cpp index 8ceaebf..1bae6b3 100644 --- a/examples/plugin_backend/local_host_demo.cpp +++ b/examples/plugin_backend/local_host_demo.cpp @@ -15,6 +15,7 @@ #include #include +#include "../must.hpp" namespace { void print_names(const rag::plugin::Registries& regs) { @@ -71,10 +72,10 @@ int main(int argc, char** argv) { } std::printf("\nWired embedder from config (onnx || retry(local_ngram)).\n"); - engine.add("d1", "The Eiffel Tower is a landmark in Paris."); - engine.add("d2", "Photosynthesis converts light into chemical energy in leaves."); - engine.add("d3", "HNSW is a graph index for approximate nearest neighbours."); - engine.build(); + must(engine.add("d1", "The Eiffel Tower is a landmark in Paris."), "add"); + must(engine.add("d2", "Photosynthesis converts light into chemical energy in leaves."), "add"); + must(engine.add("d3", "HNSW is a graph index for approximate nearest neighbours."), "add"); + must(engine.build(), "build"); // Character n-grams give sub-word recall: "landmarks near Paris" matches d1 // even though the exact phrase never appears. diff --git a/examples/plugin_backend/my_embedder_plugin.cpp b/examples/plugin_backend/my_embedder_plugin.cpp index 0f8a0e4..76d76aa 100644 --- a/examples/plugin_backend/my_embedder_plugin.cpp +++ b/examples/plugin_backend/my_embedder_plugin.cpp @@ -6,8 +6,7 @@ // no recompile of the host application. // // Build (standalone, matching the host toolchain): -// g++-15 -std=c++23 -fPIC -shared -I/include \ -// my_embedder_plugin.cpp -o libreverse_hash.so +// g++-15 -std=c++23 -fPIC -shared -I/include my_embedder_plugin.cpp -o libreverse_hash.so // Or via this repo's CMake (see CMakeLists.txt here). #include diff --git a/examples/polyglot/python_backend.cpp b/examples/polyglot/python_backend.cpp index 8663bcf..d15cde2 100644 --- a/examples/polyglot/python_backend.cpp +++ b/examples/polyglot/python_backend.cpp @@ -15,6 +15,7 @@ #include #include +#include "../must.hpp" int main(int argc, char** argv) { std::string server = argc > 1 ? argv[1] : "examples/polyglot/ragcpp_server.py"; @@ -38,9 +39,9 @@ int main(int argc, char** argv) { return 1; } - engine.add("a", "The Eiffel Tower is in Paris."); - engine.add("b", "Plants perform photosynthesis in their leaves."); - engine.build(); + must(engine.add("a", "The Eiffel Tower is in Paris."), "add"); + must(engine.add("b", "Plants perform photosynthesis in their leaves."), "add"); + must(engine.build(), "build"); if (auto hits = engine.search("landmark in the French capital", 2)) { std::printf("[embedder-via-python] top = %s (%zu hits)\n", hits->empty() ? "(none)" : (*hits)[0].uri.c_str(), hits->size()); diff --git a/examples/quickstart.cpp b/examples/quickstart.cpp index 6ff3fb6..d44f821 100644 --- a/examples/quickstart.cpp +++ b/examples/quickstart.cpp @@ -2,19 +2,20 @@ #include #include +#include "must.hpp" int main() { rag::Engine engine; engine.with_embedder(rag::dense::AnyEmbedder{rag::dense::HashEmbedder{256}}); - engine.add("intro.md", + must(engine.add("intro.md", "# rag-cpp\n\nrag-cpp is a type-theoretic retrieval engine. It fuses BM25 " - "lexical scoring with dense vector search using reciprocal rank fusion."); - engine.add("hnsw.md", + "lexical scoring with dense vector search using reciprocal rank fusion."), "add"); + must(engine.add("hnsw.md", "# ANN\n\nThe HNSW index gives logarithmic-time nearest-neighbour search " - "over embeddings, with binary quantization and Matryoshka truncation."); - engine.add("unrelated.md", - "# Cooking\n\nTo make a good risotto, toast the rice before adding stock."); + "over embeddings, with binary quantization and Matryoshka truncation."), "add"); + must(engine.add("unrelated.md", + "# Cooking\n\nTo make a good risotto, toast the rice before adding stock."), "add"); if (auto b = engine.build(); !b) { std::printf("build failed: %s\n", b.error().message.c_str()); diff --git a/examples/rcp_server.cpp b/examples/rcp_server.cpp index 187bc91..dc59c01 100644 --- a/examples/rcp_server.cpp +++ b/examples/rcp_server.cpp @@ -29,6 +29,7 @@ #include #include #include +#include "must.hpp" namespace { @@ -38,19 +39,19 @@ rag::Engine build_demo_engine() { rag::Engine engine; engine.with_embedder(rag::dense::AnyEmbedder{rag::dense::HashEmbedder{256}}); - engine.add("doc://eiffel", "The Eiffel Tower is a wrought-iron lattice tower on " - "the Champ de Mars in Paris, France, completed in 1889.", - {{"lang", "en"}, {"topic", "landmarks"}}); - engine.add("doc://photosynthesis", "Photosynthesis is the process by which plants " - "convert light energy into chemical energy stored in glucose.", - {{"lang", "en"}, {"topic", "biology"}}); - engine.add("doc://hnsw", "HNSW is a graph index for approximate nearest-neighbour " - "search, giving logarithmic query time over high-dimensional vectors.", - {{"lang", "en"}, {"topic", "retrieval"}}); - engine.add("doc://rrf", "Reciprocal rank fusion merges ranked lists from lexical " - "and dense retrievers into one robust hybrid ranking.", - {{"lang", "en"}, {"topic", "retrieval"}}); - engine.build(); + must(engine.add("doc://eiffel", "The Eiffel Tower is a wrought-iron lattice tower on " + "the Champ de Mars in Paris, France, completed in 1889.", + {{"lang", "en"}, {"topic", "landmarks"}}), "add"); + must(engine.add("doc://photosynthesis", "Photosynthesis is the process by which plants " + "convert light energy into chemical energy stored in glucose.", + {{"lang", "en"}, {"topic", "biology"}}), "add"); + must(engine.add("doc://hnsw", "HNSW is a graph index for approximate nearest-neighbour " + "search, giving logarithmic query time over high-dimensional vectors.", + {{"lang", "en"}, {"topic", "retrieval"}}), "add"); + must(engine.add("doc://rrf", "Reciprocal rank fusion merges ranked lists from lexical " + "and dense retrievers into one robust hybrid ranking.", + {{"lang", "en"}, {"topic", "retrieval"}}), "add"); + must(engine.build(), "build"); return engine; } diff --git a/include/rag/rcp/convert.hpp b/include/rag/rcp/convert.hpp index 34a86a2..27ec8dc 100644 --- a/include/rag/rcp/convert.hpp +++ b/include/rag/rcp/convert.hpp @@ -242,7 +242,7 @@ compile_filter(const Json& raw, const Json& advertised_fields) { catch (...) { return false; } }; auto cmp = [&](auto pred) -> bool { - double a, b; + double a; if (num(mv, a) && val.is_number()) return pred(a, val.get()); return pred(std::string_view(mv), std::string_view(as_str(val))); }; diff --git a/include/rag/text/contextual.hpp b/include/rag/text/contextual.hpp index f0be3ae..719ec51 100644 --- a/include/rag/text/contextual.hpp +++ b/include/rag/text/contextual.hpp @@ -35,8 +35,10 @@ using Contextualizer = void contextualize(std::vector& chunks, std::string_view document, const Contextualizer& ctx = {}); -// The deterministic default: document title (first non-empty line) + the -// document sentence with the highest term overlap with the chunk. +// The deterministic default: the document's title + the document sentence with +// the highest term overlap with the chunk. The title is front matter's +// `title:` when present, else the first non-empty line after any front +// matter. Neither is repeated when the chunk already contains it. [[nodiscard]] std::string extractive_context(std::string_view document, std::string_view chunk); diff --git a/src/text/contextual.cpp b/src/text/contextual.cpp index 8687021..26943e2 100644 --- a/src/text/contextual.cpp +++ b/src/text/contextual.cpp @@ -32,14 +32,125 @@ std::vector doc_sentences(std::string_view s) { return out; } -std::string_view first_line(std::string_view s) { - auto nl = s.find('\n'); - auto line = nl == std::string_view::npos ? s : s.substr(0, nl); - // strip markdown heading marks +// A leading front-matter block, YAML ("---" fences) or TOML ("+++"): its +// body, its fence, and the document after it. Absent: empty body and fence, +// the whole document (minus a UTF-8 BOM) as the rest. +struct FrontMatter { + std::string_view body; + std::string_view fence; + std::string_view rest; +}; +FrontMatter split_front_matter(std::string_view s) { + if (s.starts_with("\xEF\xBB\xBF")) s.remove_prefix(3); + auto line_end = [&](std::size_t at) { + auto nl = s.find('\n', at); + return nl == std::string_view::npos ? s.size() : nl; + }; + auto bare = [](std::string_view l) { + while (!l.empty() && (l.back() == '\r' || l.back() == ' ')) l.remove_suffix(1); + return l; + }; + const auto open = bare(s.substr(0, line_end(0))); + if (open != "---" && open != "+++") return {{}, {}, s}; + std::size_t at = line_end(0) + 1; + while (at < s.size()) { + const std::size_t e = line_end(at); + if (bare(s.substr(at, e - at)) == open) + return {s.substr(line_end(0) + 1, at - line_end(0) - 1), open, + e < s.size() ? s.substr(e + 1) : std::string_view{}}; + at = e + 1; + } + return {{}, {}, s}; // unclosed: not front matter +} + +std::string_view trim(std::string_view v) { + while (!v.empty() && std::isspace((unsigned char)v.front())) v.remove_prefix(1); + while (!v.empty() && std::isspace((unsigned char)v.back())) v.remove_suffix(1); + return v; +} + +// The title value of a front-matter block, unquoted: YAML `title: x` (a +// folded or literal block `title: >` takes its first indented line) or TOML +// `title = "x"`. Empty when absent. +std::string_view fm_title(const FrontMatter& fm) { + std::string_view body = fm.body; + const char sep = fm.fence == "+++" ? '=' : ':'; + bool block = false; + while (!body.empty()) { + auto nl = body.find('\n'); + auto line = body.substr(0, nl); + body = nl == std::string_view::npos ? std::string_view{} : body.substr(nl + 1); + if (block) { + if (line.empty() || !std::isspace((unsigned char)line.front())) return {}; + return trim(line); + } + if (!line.starts_with("title")) continue; + auto after = trim(line.substr(5)); + if (after.empty() || after.front() != sep) continue; + auto v = trim(after.substr(1)); + if (sep == ':' && !v.empty() && (v.front() == '>' || v.front() == '|')) { + block = true; + continue; + } + if (v.size() >= 2 && (v.front() == '"' || v.front() == '\'') && v.back() == v.front()) + v = v.substr(1, v.size() - 2); + return v; + } + return {}; +} + +// A line as a title would read in it: trimmed, without ATX heading marks or a +// front-matter `title` key. +std::string_view title_form(std::string_view line) { + line = trim(line); while (!line.empty() && (line.front() == '#' || line.front() == ' ')) line.remove_prefix(1); + if (line.starts_with("title")) { + auto after = trim(line.substr(5)); + if (!after.empty() && (after.front() == ':' || after.front() == '=')) { + line = trim(after.substr(1)); + if (line.size() >= 2 && (line.front() == '"' || line.front() == '\'') + && line.back() == line.front()) + line = line.substr(1, line.size() - 2); + } + } return line; } +// Whether some line of `chunk` is the title itself, so prepending it repeats +// the chunk. A title merely mentioned mid-sentence is not held. +bool holds_title(std::string_view chunk, std::string_view title) { + if (title.empty()) return true; + while (!chunk.empty()) { + auto nl = chunk.find('\n'); + if (title_form(chunk.substr(0, nl)) == title) return true; + chunk = nl == std::string_view::npos ? std::string_view{} : chunk.substr(nl + 1); + } + return false; +} + +// A setext underline ("=====" or "-----"): heading markup, not a sentence. +bool is_underline(std::string_view s) { + s = trim(s); + return !s.empty() && (s.find_first_not_of('=') == std::string_view::npos + || s.find_first_not_of('-') == std::string_view::npos); +} + +// The document's title: front matter's title when it has one, else the +// first non-empty line after any front matter, without heading marks. +std::string_view doc_title(std::string_view document) { + const auto fm = split_front_matter(document); + if (auto t = fm_title(fm); !t.empty()) return t; + std::string_view s = fm.rest; + while (!s.empty()) { + auto nl = s.find('\n'); + auto line = trim(s.substr(0, nl)); + s = nl == std::string_view::npos ? std::string_view{} : s.substr(nl + 1); + while (!line.empty() && (line.front() == '#' || line.front() == ' ')) line.remove_prefix(1); + if (!line.empty()) return line; + } + return {}; +} + } // namespace namespace { @@ -60,8 +171,9 @@ struct PreparedDoc { PreparedDoc prepare(const Tokenizer& tok, std::string_view document) { PreparedDoc p; - p.title = std::string(first_line(document)); - p.sentences = doc_sentences(document); + p.title = std::string(doc_title(document)); + // Front matter is metadata (keys and values), not prose to quote. + p.sentences = doc_sentences(split_front_matter(document).rest); p.sent_tokens.reserve(p.sentences.size()); for (auto s : p.sentences) p.sent_tokens.push_back(tok.tokenize(s)); return p; @@ -77,11 +189,16 @@ std::string situate(const Tokenizer& tok, const PreparedDoc& p, std::string_view // Skip a sentence the chunk already contains: repeating the chunk back // to itself situates nothing. if (chunk.find(p.sentences[i]) != std::string_view::npos) continue; + // Nor the title again as its heading ("# Title"), nor a setext underline. + if (title_form(p.sentences[i]) == p.title || is_underline(p.sentences[i])) continue; std::size_t ov = 0; for (const auto& t : p.sent_tokens[i]) if (cset.count(t)) ++ov; if (ov > best_overlap) { best_overlap = ov; best = p.sentences[i]; } } - std::string out = p.title; + // Same rule for the title: a chunk with a line that IS the title (its + // heading, its front-matter key, or the whole of a one-line document) + // gains nothing from it but a repeat. + std::string out = holds_title(chunk, p.title) ? std::string{} : p.title; if (!best.empty()) { if (!out.empty()) out += " — "; out += std::string(best); } return out; } diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index af4ef5e..2670a59 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -20,4 +20,11 @@ if(TARGET ragcpp::rcp) add_executable(ragcpp_rcp_tests test_rcp.cpp) target_link_libraries(ragcpp_rcp_tests PRIVATE ragcpp::rcp) add_test(NAME ragcpp_rcp_tests COMMAND ragcpp_rcp_tests) + # Same fixture idiom as ragcpp_tests: setup discards Results, the + # assertions check what is retrieved afterwards. + if(MSVC) + target_compile_options(ragcpp_rcp_tests PRIVATE /wd4834) + else() + target_compile_options(ragcpp_rcp_tests PRIVATE -Wno-unused-result) + endif() endif() diff --git a/tests/test_main.cpp b/tests/test_main.cpp index 2de12f8..ed9d92f 100644 --- a/tests/test_main.cpp +++ b/tests/test_main.cpp @@ -3078,6 +3078,69 @@ TEST(contextualize_adds_situating_context) { CHECK(chunks[0].context.find("Acme") != std::string::npos); } +// Front matter is metadata: its fence is not a title, its `title:` is. +TEST(extractive_context_reads_the_title_from_front_matter) { + const std::string doc = + "---\ntitle: Harbour Pilot Manual\ndescription: Boarding rules.\n---\n\n" + "# Harbour Pilot Manual\n\nThe pilot boards at the outer buoy.\n\n" + "Boarding is refused when the swell exceeds 2.5 metres.\n"; + const auto ctx = rag::text::extractive_context( + doc, "Boarding is refused when the swell exceeds 2.5 metres."); + CHECK(ctx.starts_with("Harbour Pilot Manual")); + CHECK(ctx.find("# Harbour") == std::string::npos); // the heading is not quoted back + CHECK(ctx.find("---") == std::string::npos); + CHECK(ctx.find("description:") == std::string::npos); + + // No `title:` key: the first non-empty line after the front matter. + const std::string untitled = "---\nnav_order: 3\n---\n\n# Lighthouse\n\nThe lamp is lit at dusk.\n"; + CHECK(rag::text::extractive_context(untitled, "The lamp is lit at dusk.") + .starts_with("Lighthouse")); + + const auto title_of = [](const std::string& d) { + return rag::text::extractive_context(d, "An unrelated later line."); + }; + // Quoted, with a colon inside the value. + CHECK(title_of("---\ntitle: \"Pilots: Boarding\"\n---\nBody text here.\n") + .starts_with("Pilots: Boarding")); + // A folded block title takes its first line. + CHECK(title_of("---\ntitle: >\n Long Harbour Title\n---\nBody text here.\n") + .starts_with("Long Harbour Title")); + // TOML front matter (Hugo). + CHECK(title_of("+++\ntitle = \"Tide Notes\"\n+++\nBody text here.\n") + .starts_with("Tide Notes")); + // A UTF-8 byte-order mark before the fence. + CHECK(title_of("\xEF\xBB\xBF---\ntitle: Crane Rules\n---\nBody text here.\n") + .starts_with("Crane Rules")); + // An unclosed fence is not front matter: the first line is the title. + CHECK(title_of("---\nnot closed\nBody text here.\n").starts_with("---")); +} + +// A chunk that already holds the title or the best sentence gets neither +// again: the whole of a one-line document, or a document's first chunk. +TEST(extractive_context_does_not_repeat_what_the_chunk_holds) { + const std::string line = "The quay crane lifts at most 40 tonnes in calm wind."; + CHECK(rag::text::extractive_context(line, line).empty()); + + const std::string doc = "# Tide Table Notes\n\nHigh water at the inner basin is 40 minutes late.\n"; + CHECK(rag::text::extractive_context(doc, doc).empty()); + + // A later chunk still gets the title it lacks. + const std::string two = "# Tide Table Notes\n\nHigh water is late.\n\nNeap tides raise the basin by 2.9 metres.\n"; + CHECK(rag::text::extractive_context(two, "Neap tides raise the basin by 2.9 metres.") + .starts_with("Tide Table Notes")); + + // A chunk that only mentions the title mid-sentence still gets it. + const std::string usage = "# Usage\n\nRun it once.\n\nSee Usage above for the flags.\n"; + CHECK(rag::text::extractive_context(usage, "See Usage above for the flags.") + .starts_with("Usage")); + + // Setext headings: the title is the text line, the underline is never quoted. + const std::string setext = "Harbour Rules\n=============\n\nShips moor at berth 4.\n\nTugs wait at the buoy.\n"; + const auto sctx = rag::text::extractive_context(setext, "Tugs wait at the buoy."); + CHECK(sctx.starts_with("Harbour Rules")); + CHECK(sctx.find("===") == std::string::npos); +} + // ── Cascade ──────────────────────────────────────────────── TEST(cascade_narrows_through_stages) {