//! Ported case-for-case from `packages/core/__tests__/engine/chunk.test.ts`,//! plus the Node vectors.//!//! The assertion this whole file exists for is DETERMINISM: the indexer decides//! a row is up to date by comparing every chunk's `content_sha` against what//! the row currently produces, so a chunker that answered differently on the//! same text would re-embed the owner's whole database on every pass — spending//! their provider key to arrive back where it started. Two implementations of//! the chunker now exist, so the vectors below are that claim made testable://! every `len` and every `sha` was PRINTED by running the TypeScript, never//! reasoned out.//!//! `len` is the chunk's UTF-16 length, which is what//! `String.prototype.length` counts; a `sha` pins the text exactly.use serde_json::json;usesuper::*;fn source(name: &str) -> &'staticEmbedSource { embed_source(name).unwrap_or_else(|| panic!("no embed source {name}"))}/// Deterministic prose of roughly `chars` UTF-16 units, in `paragraphs` parts —/// the TypeScript test file's own generator, and pinned as a vector below.////// Every token is numbered, so no 120-unit window of the result appears twice,/// which is what lets the overlap assertions find a carried tail by position/// rather than by luck.fn prose(paragraphs: usize, chars: usize) -> String {const WORDS: [&str; 8] = ["payment", "split", "half", "each", "invoice", "agreed", "later", "again", ];let per = chars.div_ceil(paragraphs);letmut n = 0usize;letmut out: Vec<String> = Vec::new();for _ in0..paragraphs {letmut text = String::new();while text.chars().count() < per { text.push_str(&format!("{}{n} ", WORDS[n % WORDS.len()])); n += 1; } out.push(text.trim().to_string()); } out.join("\n\n")}fn utf16(text: &str) -> usize { text.encode_utf16().count()}/// `(index, UTF-16 length, sha)` for every chunk — the shape every vector below/// is written in.fn shape(chunks: &[EmbedChunk]) -> Vec<(usize, usize, &str)> { chunks .iter() .map(|chunk| (chunk.ix, utf16(&chunk.text), chunk.sha.as_str())) .collect()}fn row(pairs: &[(&str, serde_json::Value)]) -> serde_json::Map<String, serde_json::Value> { pairs .iter() .map(|(key, value)| ((*key).to_string(), value.clone())) .collect()}/// Every code unit of `text` that is a surrogate with no partner. On the/// TypeScript side this is measurable and every list below came back empty; on/// the Rust side a `String` cannot hold one at all, so this asserts the two/// agree rather than that Rust did its job.fn lone_surrogates(text: &str) -> Vec<u16> {let units: Vec<u16> = text.encode_utf16().collect();letmut out = Vec::new();letmut i = 0;while i < units.len() {let unit = units[i];if (0xd800..=0xdbff).contains(&unit) {if units .get(i + 1) .is_some_and(|low| (0xdc00..=0xdfff).contains(low)) { i += 2;continue; } out.push(unit); } elseif (0xdc00..=0xdfff).contains(&unit) { out.push(unit); } i += 1; } out}// ── nothing to embed ─────────────────────────────────────────────────────────#[test]fn empty_text_yields_no_chunks() {for text in ["", " ", "\n\n\t\n"] { assert!( embed_chunks(text, EmbedChunking::Whole).is_empty(),"{text:?}" ); assert!( embed_chunks(text, EmbedChunking::Split).is_empty(),"{text:?}" ); }}#[test]fn text_under_the_short_floor_yields_no_chunks_in_either_mode() {let short = "ok thanks"; // 9 units, under the floor assert!(utf16(short) < EMBED_CHUNK_MIN_CHARS); assert!(embed_chunks(short, EmbedChunking::Whole).is_empty()); assert!(embed_chunks(short, EmbedChunking::Split).is_empty());}#[test]fn text_exactly_at_the_floor_earns_a_chunk() {let text = "a".repeat(EMBED_CHUNK_MIN_CHARS); assert_eq!(embed_chunks(&text, EmbedChunking::Whole).len(), 1);}// ── whole — one row, one chunk ───────────────────────────────────────────────#[test]fn keeps_a_message_intact_hash_and_all() {let text = "we agreed on half each, and he pays the deposit";let chunks = embed_chunks(text, EmbedChunking::Whole); assert_eq!(chunks.len(), 1); assert_eq!( chunks[0],EmbedChunk { ix: 0, text: text.to_string(), sha: embed_chunk_sha(text), } );}/// "One message, one chunk" is a rule about not chopping prose up for the sake/// of it, not a promise to hand a provider unbounded text — an imported archive/// holds messages somebody pasted a document into.#[test]fn still_cuts_a_row_that_runs_past_the_maximum() {let chunks = embed_chunks(&prose(8, EMBED_CHUNK_MAX_CHARS * 3), EmbedChunking::Whole); assert!(chunks.len() > 1);}// ── split — paragraph boundaries ─────────────────────────────────────────────fn long_split() -> (String, Vec<EmbedChunk>) {let long = prose(12, EMBED_CHUNK_MAX_CHARS * 4);let chunks = embed_chunks(&long, EmbedChunking::Split); (long, chunks)}#[test]fn produces_contiguous_zero_based_indices() {let (_, chunks) = long_split(); assert!(chunks.len() > 3); assert_eq!( chunks.iter().map(|chunk| chunk.ix).collect::<Vec<_>>(), (0..chunks.len()).collect::<Vec<_>>() );}#[test]fn keeps_every_chunk_within_the_maximum_plus_its_overlap() {let (_, chunks) = long_split();for chunk in &chunks { assert!(utf16(&chunk.text) <= EMBED_CHUNK_MAX_CHARS + EMBED_CHUNK_OVERLAP_CHARS + 2); }}/// No chunk ends mid-word.#[test]fn cuts_at_paragraph_boundaries() {let (long, chunks) = long_split();let paragraphs: Vec<&str> = long.split("\n\n").collect();for chunk in &chunks {let tail = chunk.text.rsplit("\n\n").next().unwrap_or(""); assert!( paragraphs.iter().any(|paragraph| paragraph.ends_with(tail)),"a chunk ended inside a paragraph: {:?}", &tail[tail.len().saturating_sub(40)..] ); }}#[test]fn holds_the_whole_text_between_the_first_chunk_and_the_last() {let (long, chunks) = long_split(); assert!(long.starts_with(chunks[0].text.split("\n\n").next().expect("a first part"))); assert!(long.ends_with( chunks .last() .expect("a last chunk") .text .rsplit("\n\n") .next() .expect("a last part") ));}#[test]fn prose_that_fits_stays_one_chunk() { assert_eq!(embed_chunks(&prose(3, 400), EmbedChunking::Split).len(), 1);}// ── overlap ──────────────────────────────────────────────────────────────────fn overlapped() -> Vec<EmbedChunk> { embed_chunks(&prose(10, EMBED_CHUNK_MAX_CHARS * 3), EmbedChunking::Split)}/// Nothing precedes it, so its text is its body — and the body is where the/// source text begins.#[test]fn gives_the_first_chunk_no_overlap() { assert!(overlapped()[0].text.starts_with("payment"));}#[test]fn opens_every_later_chunk_with_the_tail_of_the_one_before_it() {let chunks = overlapped();for i in1..chunks.len() {let carried = chunks[i].text.split("\n\n").next().expect("a first part"); assert!(!carried.is_empty()); assert!( chunks[i - 1].text.contains(carried),"chunk {i} does not repeat the tail of chunk {}", i - 1 ); assert!(utf16(carried) <= EMBED_CHUNK_OVERLAP_CHARS + 8); }}#[test]fn never_opens_the_overlap_mid_word() {let chunks = overlapped();for i in1..chunks.len() {let carried = chunks[i].text.split("\n\n").next().expect("a first part");let previous = &chunks[i - 1].text;let at = previous.find(carried).expect("the carried tail"); assert!(at == 0 || previous[..at].ends_with(char::is_whitespace)); }}// ── determinism — the property the indexer's staleness test rests on ─────────#[test]fn the_same_text_produces_the_same_chunks_and_the_same_hashes() {let text = prose(9, EMBED_CHUNK_MAX_CHARS * 2); assert_eq!( embed_chunks(&text, EmbedChunking::Split), embed_chunks(&text, EmbedChunking::Split) );}#[test]fn every_chunks_sha_is_the_sha_of_its_own_text() {for chunk in embed_chunks(&prose(9, EMBED_CHUNK_MAX_CHARS * 2), EmbedChunking::Split) { assert_eq!(chunk.sha, embed_chunk_sha(&chunk.text)); }}#[test]fn rewrapping_the_same_prose_does_not_change_a_single_hash() {let text = prose(6, EMBED_CHUNK_MAX_CHARS * 2);let expected: Vec<String> = embed_chunks(&text, EmbedChunking::Split) .into_iter() .map(|chunk| chunk.sha) .collect();/// A relabelling of the same prose: a name and the rewrite itself.typeRewrite = (&'static str, Box<dynFn(&str) -> String>);let rewrites: [Rewrite; 5] = [ ("CRLF line endings",Box::new(|t: &str| t.replace('\n', "\r\n")), ), ("a bare CR", Box::new(|t: &str| t.replace('\n', "\r"))), ("trailing spaces",Box::new(|t: &str| t.replace('\n', " \n")), ), ("extra blank lines",Box::new(|t: &str| t.replace("\n\n", "\n\n\n\n")), ), ("leading and trailing whitespace",Box::new(|t: &str| format!("\n\n {t} \n\n")), ), ];for (label, rewrite) in rewrites {let shas: Vec<String> = embed_chunks(&rewrite(&text), EmbedChunking::Split) .into_iter() .map(|chunk| chunk.sha) .collect(); assert_eq!(shas, expected, "{label} changed a hash"); }}// ── text with no whitespace to cut at ────────────────────────────────────────#[test]fn hard_splits_a_long_unbroken_run() {let chunks = embed_chunks( &"a".repeat(EMBED_CHUNK_MAX_CHARS * 2 + 50),EmbedChunking::Split, ); assert!(chunks.len() > 1);for chunk in &chunks { assert!(utf16(&chunk.text) <= EMBED_CHUNK_MAX_CHARS + EMBED_CHUNK_OVERLAP_CHARS + 2); }}/// Astral code points are two UTF-16 units each, so a cut at a raw count lands/// inside one roughly half the time. No lone surrogate survives.#[test]fn never_cuts_inside_a_character() {let chunks = embed_chunks( &"\u{1f44d}".repeat(EMBED_CHUNK_MAX_CHARS),EmbedChunking::Split, ); assert!(chunks.len() > 1);for chunk in &chunks { assert!( lone_surrogates(&chunk.text).is_empty(),"lone surrogate in chunk {}", chunk.ix ); assert!(chunk.text.chars().all(|c| c == '\u{1f44d}' || c == '\n')); }}/// NFD, with one leading character so the raw unit count lands ON the combining/// mark rather than tidily between two graphemes.#[test]fn never_strands_a_combining_mark_from_the_letter_it_sits_on() {let chunks = embed_chunks( &format!("x{}", "e\u{301}".repeat(EMBED_CHUNK_MAX_CHARS)),EmbedChunking::Split, ); assert!(chunks.len() > 1);for chunk in &chunks { assert!( !chunk.text.starts_with('\u{301}'),"a chunk opened with a bare accent" ); assert!( !chunk.text.ends_with('e'),"a chunk ended on a letter missing its accent" ); }}// ── a runt tail ──────────────────────────────────────────────────────────────/// A body that packs to a full chunk plus a few characters: the tail is real/// prose, not an acknowledgement, so it belongs with what precedes it.#[test]fn a_runt_tail_joins_the_chunk_before_it() {let text = format!("{}\n\nend", "word ".repeat(240).trim());let chunks = embed_chunks(&text, EmbedChunking::Split); assert_eq!(chunks.len(), 1); assert!(chunks[0].text.ends_with("end"));}// ── embedRowText — where each source's text comes from ───────────────────────#[test]fn joins_the_declared_columns_in_declared_order_as_paragraphs() { assert_eq!( embed_row_text( source("note"), &row(&[ ("title", json!("Deposit")), ("body", json!("we agreed on half each")) ]) ),Ok("Deposit\n\nwe agreed on half each".to_string()) );}#[test]fn skips_a_column_that_is_null_absent_or_blank() {let half = Ok("half each".to_string()); assert_eq!( embed_row_text( source("note"), &row(&[("title", json!(null)), ("body", json!("half each"))]) ), half ); assert_eq!( embed_row_text(source("note"), &row(&[("body", json!("half each"))])), half ); assert_eq!( embed_row_text( source("note"), &row(&[("title", json!(" ")), ("body", json!("half each"))]) ), half );}#[test]fn refuses_rather_than_coercing_a_column_that_is_not_text() {let error = embed_row_text( source("note"), &row(&[("title", json!(7)), ("body", json!("x"))]), ) .expect_err("a number in a text column"); assert_eq!( error.to_string(),"embed source note: column title is number, not text" );}#[test]fn chunks_a_row_straight_from_its_sources_declaration() {let chunks = embed_row_chunks( source("memory"), &row(&[ ("title", json!("Memories are tweet-shaped")), ("body", json!("the sentence IS the entry, there is no body field"), ), ]), ) .expect("two text columns"); assert_eq!(chunks.len(), 1); assert!(chunks[0].text.contains("tweet-shaped"));}#[test]fn reads_every_declared_source_without_refusing() {for declared in &EMBED_SOURCES {let fields: Vec<(&str, serde_json::Value)> = declared .columns .iter() .map(|column| { ( *column, json!(format!("{column} text about the payment split")), ) }) .collect();let chunks = embed_row_chunks(declared, &row(&fields)) .unwrap_or_else(|err| panic!("{}: {err}", declared.source)); assert!(!chunks.is_empty(), "{} produced no chunk", declared.source); }}// ─────────────────────────────────────────────────────────────────────────────// Node vectors — every `len` and `sha` below was PRINTED by running the// TypeScript (`packages/core`, `npx tsx`), never reasoned out.// ─────────────────────────────────────────────────────────────────────────────/// The hash itself, before any chunking: sha256 over the text's UTF-8 bytes,/// first 32 hex. The empty string's value is the well-known sha256 prefix,/// which is what proves the truncation is of the HEX and not of the digest.#[test]fn vector_embed_chunk_sha() { assert_eq!(embed_chunk_sha(""), "e3b0c44298fc1c149afbf4c8996fb924"); assert_eq!( embed_chunk_sha("we agreed on half each, and he pays the deposit"),"c96ec7d2e71840ab12485ceb3bb69c08" ); assert_eq!( embed_chunk_sha("\u{1f44d}\u{1f44d} café naı̈ve"),"96e5aa70aa153822924ab35c70552eb8" ); assert_eq!( embed_chunk_sha("one\n\ntwo\n\nthree"),"18850ac01545fc27d54a0199489e33e2" );}/// The test file's own prose generator, pinned so the vectors below mean/// something: a Rust generator that drifted from the TypeScript one would make/// every length and hash after this point a comparison of two different texts.#[test]fn vector_the_prose_generator_matches_the_typescripts() { assert_eq!( prose(2, 60),"payment0 split1 half2 each3 invoice4\n\nagreed5 later6 again7 payment8" ); assert_eq!( &prose(6, EMBED_CHUNK_MAX_CHARS * 2)[..80],"payment0 split1 half2 each3 invoice4 agreed5 later6 again7 payment8 split9 half1" );}#[test]fn vector_whole_mode() { assert_eq!( shape(&embed_chunks("we agreed on half each, and he pays the deposit",EmbedChunking::Whole )), [(0, 47, "c96ec7d2e71840ab12485ceb3bb69c08")] ); assert_eq!( shape(&embed_chunks( &"a".repeat(EMBED_CHUNK_MIN_CHARS),EmbedChunking::Whole )), [(0, 12, "f24abc34b13fade76e805799f71187da")] ); assert!(embed_chunks("ok thanks", EmbedChunking::Whole).is_empty());// Astral characters and a ZWJ sequence, well under the maximum: 27 UTF-16// units for 23 code points — the difference this module counts in.let astral = "\u{1f44d} deal! \u{1f44d} half each \u{1f9d1}\u{200d}\u{1f4bb}"; assert_eq!(astral.chars().count(), 23); assert_eq!( shape(&embed_chunks(astral, EmbedChunking::Whole)), [(0, 27, "8949e6edfea429af9b43de2972a2f01f")] );// A `whole` row past the maximum goes through the same splitter. assert_eq!( shape(&embed_chunks( &prose(8, EMBED_CHUNK_MAX_CHARS * 3),EmbedChunking::Whole )), [ (0, 901, "b8cf143d7a59de968cc187214cefc950"), (1, 1016, "2599a5d9104455bf6dc732256d4e63a9"), (2, 1021, "2c41d4cb8add9227abe1072be098c5c0"), (3, 1021, "7c152ce71b1fa1930db3af5fa0bc6f33"), ] );}#[test]fn vector_split_over_paragraphed_prose() { assert_eq!( shape(&embed_chunks( &prose(12, EMBED_CHUNK_MAX_CHARS * 4),EmbedChunking::Split )), [ (0, 804, "382af601c0d099eb22a31ddbb1d1028a"), (1, 931, "68fe68fbc0f1f0dff0da2a737072a837"), (2, 922, "ef24efd19652ef17a564dc8944983db8"), (3, 917, "527546cf65fb97a7a83dec2db9dea18d"), (4, 930, "9065b3b24d8e2992ed6fc934e7b05457"), (5, 919, "33cdc95b4883ad5c9b896a9c2fc9e960"), ] ); assert_eq!( shape(&embed_chunks( &prose(10, EMBED_CHUNK_MAX_CHARS * 3),EmbedChunking::Split )), [ (0, 1091, "e7d232874dd300010fa5a4eec3d4ce17"), (1, 1213, "0d78f183492f59fc1537c7db50738c01"), (2, 1211, "4897437061cba6f6b8325a517d82ee74"), (3, 479, "c26e60bd41f7eec82b1ec5bbc5db6cc1"), ] ); assert_eq!( shape(&embed_chunks(&prose(3, 400), EmbedChunking::Split)), [(0, 403, "89ec965344124193421642af61b716f3")] );}/// ONE long paragraph of real words: no paragraph boundary to cut at, so/// `hardSplit` cuts at the last whitespace before the maximum and the overlap/// then pushes each later chunk past it. The last cut leaves a fragment that/// is NOT under the floor, so no runt merge happens here.#[test]fn vector_a_single_long_paragraph_is_cut_at_whitespace() { assert_eq!( shape(&embed_chunks( &prose(1, EMBED_CHUNK_MAX_CHARS * 3),EmbedChunking::Split )), [ (0, 1192, "1dca0ac9fce9dd27ee4f8813680598fa"), (1, 1312, "5085c04759b32cb4c98a1b2bb771a582"), (2, 1321, "e58fb9aee477f9e5e4fc5ac47545b4c0"), ] );}/// The same paragraph with an astral character inside a word. Every "payment"/// becomes "pay👍ment", which is two extra UTF-16 units per occurrence and a/// different cut everywhere — a chunker counting `char`s or bytes would answer/// four different hashes here.#[test]fn vector_a_long_paragraph_with_astral_characters_inside_its_words() {let text = prose(1, EMBED_CHUNK_MAX_CHARS * 3).replace("payment", "pay\u{1f44d}ment");let chunks = embed_chunks(&text, EmbedChunking::Split); assert_eq!( shape(&chunks), [ (0, 1198, "ee20915c2ee3e7cfa27593e265aa6f82"), (1, 1309, "51ebcbe848795542540254f98f52c7c8"), (2, 1309, "dd49f74bb7f609d00fd0d072ed42e7bf"), (3, 231, "c40f544a85f5455edbc65d32d1989395"), ] );for chunk in &chunks { assert!(lone_surrogates(&chunk.text).is_empty()); }}/// The three walls with no whitespace anywhere: the cut is `safeBoundary`'s/// alone. The astral wall cuts cleanly at 1200 (600 whole emoji); the/// combining wall steps back to 1199 to keep `e` and its accent together, which/// leaves a three-unit runt that merges into the chunk before it — 1326, not/// 1324.#[test]fn vector_the_walls_with_nothing_to_cut_at() {for (label, text, expected) in [ ("unbroken ascii","a".repeat(EMBED_CHUNK_MAX_CHARS * 2 + 50), vec![ (0, 1200, "4d21dde662555b99cb697061c3b50411"), (1, 1322, "4d685a9a3fa9d71103d28c6b205210b0"), (2, 172, "6f7624a4340a6d97407369fc8e03141b"), ], ), ("astral","\u{1f44d}".repeat(EMBED_CHUNK_MAX_CHARS), vec![ (0, 1200, "206a4e57150b468d6e706df2116a4fc9"), (1, 1322, "e52355504845193ce15ab0811f0c9569"), ], ), ("combining marks", format!("x{}", "e\u{301}".repeat(EMBED_CHUNK_MAX_CHARS)), vec![ (0, 1199, "ae3f1d9dfaadc3e30a9c97cb35952a69"), (1, 1326, "feeb1281abc7f0d68d1d328af23f8e0f"), ], ), ("cjk","漢字".repeat(EMBED_CHUNK_MAX_CHARS), vec![ (0, 1200, "0dd80b16ace9128b475546e666d71c00"), (1, 1322, "e2047b1d9d98bf904b40e2b20e554d42"), ], ), ("zwj sequences","\u{1f9d1}\u{200d}\u{1f4bb}".repeat(400), vec![ (0, 1200, "026715a9c8affa3475c2bca8eee57c8d"), (1, 922, "5bb198ee72ddc540fedc50db87294677"), ], ), ] {let chunks = embed_chunks(&text, EmbedChunking::Split); assert_eq!(shape(&chunks), expected, "{label}");for chunk in &chunks { assert!( lone_surrogates(&chunk.text).is_empty(),"{label}: lone surrogate in chunk {}", chunk.ix ); } }}#[test]fn vector_the_runt_tail_lands_in_the_chunk_before_it() {let text = format!("{}\n\nend", "word ".repeat(240).trim()); assert_eq!( shape(&embed_chunks(&text, EmbedChunking::Split)), [(0, 1204, "c4cd133f8a7413ed234139dd182404f3")] );}/// The normalisation, end to end: CRLF, a bare CR, trailing spaces, a run of/// blank lines and wrapping whitespace all collapse to the same text — and/// `one\n\ntwo\n\nthree` hashes to the same value the bare string does.#[test]fn vector_the_normalisation() {let crlf = embed_chunks("one\r\n\r\ntwo \r\n\r\n\r\n\r\nthree",EmbedChunking::Split, ); assert_eq!(crlf.len(), 1); assert_eq!(crlf[0].text, "one\n\ntwo\n\nthree"); assert_eq!(crlf[0].sha, "18850ac01545fc27d54a0199489e33e2");// A BARE CR is a line break too, so `one\r\rtwo\rthree` is a paragraph// break then a single newline — 14 units, not 15.let cr = embed_chunks("one\r\rtwo\rthree ", EmbedChunking::Split); assert_eq!(shape(&cr), [(0, 14, "2048e68fb39d28fdd6c1f35b82ef3270")]); assert_eq!(cr[0].text, "one\n\ntwo\nthree");let wrapped = embed_chunks("\n\n the payment split, agreed \n\n",EmbedChunking::Split, ); assert_eq!( shape(&wrapped), [(0, 25, "987363d24dbeb3bcefbfa141d034dcb4")] ); assert_eq!(wrapped[0].text, "the payment split, agreed");}#[test]fn vector_embed_row_text() {let note = source("note");for (fields, expected) in [ ( vec![ ("title", json!("Deposit")), ("body", json!("we agreed on half each")), ],"Deposit\n\nwe agreed on half each", ), ( vec![("title", json!(null)), ("body", json!("half each"))],"half each", ), (vec![("body", json!("half each"))], "half each"), ( vec![("title", json!(" ")), ("body", json!("half each"))],"half each", ),// Each column is trimmed on its own before the join, so padding never// reaches the hash. ( vec![ ("title", json!(" Deposit \n")), ("body", json!("\n half each ")), ],"Deposit\n\nhalf each", ), ( vec![("title", json!("\u{1f44d}")), ("body", json!("half each"))],"👍\n\nhalf each", ), (vec![], ""), ] { assert_eq!(embed_row_text(note, &row(&fields)).as_deref(), Ok(expected)); }// A body that already holds a paragraph break keeps it: the join adds one,// it does not collapse the ones already there. assert_eq!( embed_row_text( source("email"), &row(&[ ("subject", json!("Re: split")), ("body", json!("line one\n\nline two")) ]) ) .as_deref(),Ok("Re: split\n\nline one\n\nline two") ); assert_eq!( embed_row_text(source("message"), &row(&[("body", json!(" ok "))])).as_deref(),Ok("ok") );}/// The refusal names JavaScript's `typeof`, and an ARRAY is `"object"` there —/// which is why the two map to one string rather than to `array`/`object`.#[test]fn vector_the_refusals_typeof() {for (value, found) in [ (json!(7), "number"), (json!(true), "boolean"), (json!(["a"]), "object"), (json!({}), "object"), ] {let error = embed_row_text( source("note"), &row(&[("title", value.clone()), ("body", json!("x"))]), ) .expect_err("not a text column"); assert_eq!( error.to_string(), format!("embed source note: column title is {found}, not text"),"{value}" ); }}#[test]fn vector_a_memory_row_chunks_to_one() {let chunks = embed_row_chunks( source("memory"), &row(&[ ("title", json!("Memories are tweet-shaped")), ("body", json!("the sentence IS the entry, there is no body field"), ), ]), ) .expect("two text columns"); assert_eq!(chunks.len(), 1); assert_eq!( chunks[0].text,"Memories are tweet-shaped\n\nthe sentence IS the entry, there is no body field" ); assert_eq!(chunks[0].sha, "5e03f153bf352822674af5ef88af8e1e");}/// Every declared source, read the way the TypeScript test reads them — the/// declaration itself (table, kind, columns, chunking) plus the text and hash/// each produces from a synthetic row.#[test]fn vector_every_declared_source() {/// `(source, table, kind, columns, chunking, text, sha)` — one declared/// source and what it produces from the synthetic row below.typeSourceVector = ( &'static str, &'static str, &'static str, &'static [&'static str],EmbedChunking, &'static str, &'static str, );let expected: [SourceVector; 8] = [ ("note","cotton_notes","note", &["title", "body"],EmbedChunking::Split,"title text about the payment split\n\nbody text about the payment split","2f7d0ff63b8ddd1282490de493d59e85", ), ("message","cotton_msg_messages","message", &["body"],EmbedChunking::Whole,"body text about the payment split","5b06692bd5dca8e9781c60d8d7550279", ), ("email","cotton_emails","email", &["subject", "body"],EmbedChunking::Split,"subject text about the payment split\n\nbody text about the payment split","ca2c67e0afca78477e093eed409726fa", ), ("document_page","cotton_document_pages","document", &["text"],EmbedChunking::Split,"text text about the payment split","1cc83208ba2cd830d70e267e4c3142a9", ), ("meeting","cotton_meetings","meeting", &["summary_md"],EmbedChunking::Split,"summary_md text about the payment split","432df243515c872c63530c20ef3228e4", ), ("memory","cotton_memories","memory", &["title", "body"],EmbedChunking::Whole,"title text about the payment split\n\nbody text about the payment split","2f7d0ff63b8ddd1282490de493d59e85", ), ("person","cotton_people","person", &["summary"],EmbedChunking::Whole,"summary text about the payment split","0f409cb69668853d4649d467d3911a70", ), ("thought","cotton_inbox_items","thought", &["raw_text"],EmbedChunking::Whole,"raw_text text about the payment split","c642c748a352d4da1b176e7124608181", ), ]; assert_eq!(EMBED_SOURCES.len(), expected.len());for (declared, (source, table, kind, columns, chunking, text, sha)) in EMBED_SOURCES.iter().zip(expected) { assert_eq!(declared.source, source); assert_eq!(declared.table, table, "{source}"); assert_eq!(declared.kind, kind, "{source}"); assert_eq!(declared.columns, columns, "{source}"); assert_eq!(declared.chunking, chunking, "{source}");let fields: Vec<(&str, serde_json::Value)> = declared .columns .iter() .map(|column| { ( *column, json!(format!("{column} text about the payment split")), ) }) .collect();let chunks = embed_row_chunks(declared, &row(&fields)).expect("text columns"); assert_eq!(chunks.len(), 1, "{source}"); assert_eq!(chunks[0].text, text, "{source}"); assert_eq!(chunks[0].sha, sha, "{source}"); } assert!(embed_source("no such source").is_none());}// ── the store's own declaration, and why there is no longer one ─────────────//// `EMBED_SOURCES` and the chunk hash were declared twice: here, and in// `packages/store/src/schema/embeddings.ts`. A test read that file by path and// held the two equal. Step 5i deleted the package, and the Rust store carries// no port of the embeddings schema — so `EMBED_SOURCES` and `embed_chunk_sha`// in `rules/chunk.rs` ARE the declaration now. Repointing the test at this// crate's own list would have left something that looks like a guard and// asserts nothing.//// What genuinely has no home: the embeddings DDL and the head-characters// bound, which lived in that file and are the server's concern// (`cotton-server/src/embed/`). The flip records the gap rather than closing// it — closing it is a schema decision, not a file move.// ── the text comes from the definitions ─────────────────────────────────────/// RULE: a source whose kind ships a built-in definition reads its table and/// columns off that definition, never a hand entry — a hand list of table/// names is what goes stale the day a tool's columns change (lane T11, 22 Oct/// 2026). A hand entry stands only where no shipped definition describes the/// source (its reason beside it in `EMBED_DECLARATIONS`): no definition for/// the kind, or one that reads a different table (a document's pages).#[test]fn a_source_with_a_definition_is_never_hand_listed() {for declared in EMBED_DECLARATIONS.iter() {let definition = crate::definitions::builtin_table_definition(declared.kind);match (declared.text, definition) { (EmbedText::Definition, Some(_)) | (EmbedText::Hand { .. }, None) => {} (EmbedText::Definition, None) => panic!("{}: no built-in definition to read", declared.source), (EmbedText::Hand { table, .. }, Some(definition)) => {let described = definition_text(definition, declared.chunking).ok(); assert!( described.as_ref().is_none_or(|(read, _)| read != table),"{}: its definition describes {table}; read it there", declared.source ); } } }}/// A synthetic imported data-only table: its prose is the long text its/// `search` list indexes, headed by its title for a split source; a long text/// it does not search, and its short text, are not read.#[test]fn an_imported_tables_text_is_its_searched_long_text() {letmut value = serde_json::to_value(crate::definitions::builtin_table_definition("note").expect("note")) .expect("a definition serialises"); value["id"] = json!("lesson"); value["builtin"] = json!(false); value["engine"] = serde_json::Value::Null; value.as_object_mut().unwrap().remove("tables");for key in ["project", "date", "order", "archived"] { value[key] = serde_json::Value::Null; } value["title"] = json!("heading"); value["columns"] = json!([ {"key": "heading", "type": "text"}, {"key": "aside", "type": "longtext"}, {"key": "teaching", "type": "longtext"}, {"key": "room", "type": "text"} ]); value["search"] = json!(["heading", "teaching", "room"]);let definition = crate::definitions::TableDefinition::from_json(&value.to_string()) .expect("a data-only definition"); assert_eq!( definition_text(&definition, EmbedChunking::Split).expect("prose"), ("cotton_lesson".to_string(), vec!["heading".to_string(), "teaching".to_string()]) ); assert_eq!( definition_text(&definition, EmbedChunking::Whole).expect("prose"), ("cotton_lesson".to_string(), vec!["teaching".to_string()]) ); value["search"] = json!(["heading"]);let titled_only = crate::definitions::TableDefinition::from_json(&value.to_string()).expect("definition"); assert!(definition_text(&titled_only, EmbedChunking::Split).is_err());}