Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text in a single forward pass, in 100+ languages, with a router that picks the right checkpoint per request.
Python calibrationclassificationdecision-modelhuggingfacejevmodernbertmultilingualnlppythonpytorchroutingtyped-decisionszero-shot
feat(java): the preset question sets, generated and gated word for word
Adeshina Lasisiee5ba8a38835
diff --git a/laya-java/fixtures/presets.json b/laya-java/fixtures/presets.jsonindex c8aebc44..bacc904e 100644--- a/laya-java/fixtures/presets.json+++ b/laya-java/fixtures/presets.json@@ -169,5 +169,158 @@"type": "noul","instructions": "Does `message` suggest the customer may leave for a competitor or cancel?"}+ },+ "state_field": {+ "email_questions": "body",+ "guard_questions": "prompt",+ "moderation_questions": "post",+ "router_questions": "request",+ "triage_questions": "message"+ },+ "state_field_hostile": {+ "no-backticks": null,+ "two-fields": null,+ "same-field-twice": "message",+ "empty": null,+ "missing-instructions": null,+ "null-instructions": null,+ "non-word-backticks": null,+ "underscored-field": "customer_message",+ "backtick-in-criteria-only": null+ },+ "hostile_specs": {+ "no-backticks": {+ "q": {+ "type": "noul",+ "instructions": "Is this urgent?"+ }+ },+ "two-fields": {+ "a": {+ "type": "noul",+ "instructions": "Does `message` ask for a refund?"+ },+ "b": {+ "type": "noul",+ "instructions": "Is `body` urgent?"+ }+ },+ "same-field-twice": {+ "a": {+ "type": "noul",+ "instructions": "Does `message` ask for a refund?"+ },+ "b": {+ "type": "noul",+ "instructions": "Is `message` urgent?"+ }+ },+ "empty": {},+ "missing-instructions": {+ "q": {+ "type": "noul"+ }+ },+ "null-instructions": {+ "q": {+ "type": "noul",+ "instructions": null+ }+ },+ "non-word-backticks": {+ "q": {+ "type": "noul",+ "instructions": "Read `a-b` and `c d`."+ }+ },+ "underscored-field": {+ "q": {+ "type": "noul",+ "instructions": "Read `customer_message`."+ }+ },+ "backtick-in-criteria-only": {+ "q": {+ "type": "choice",+ "instructions": "Pick one.",+ "criteria": {+ "x": "look at `message`"+ }+ }+ }+ },+ "email_questions_custom": {+ "category": {+ "type": "choice",+ "instructions": "Which team should handle the email in `body`?",+ "criteria": {+ "ops": "incidents and deploys",+ "legal": "contracts and compliance"+ }+ },+ "is_spam": {+ "type": "noul",+ "instructions": "Is this email unsolicited spam or bulk marketing?"+ },+ "is_phishing": {+ "type": "noul",+ "instructions": "Is this email a phishing or scam attempt to steal money, credentials, or personal data?",+ "criteria": {+ "true": "phishing, scam, or fraud",+ "false": "a legitimate email"+ }+ },+ "urgency": {+ "type": "score",+ "instructions": "How urgent is the request in `body`?",+ "criteria": [+ "no time pressure",+ "needs attention soon",+ "blocking issue or hard deadline"+ ]+ },+ "needs_reply": {+ "type": "noul",+ "instructions": "Does the sender expect a reply?"+ }+ },+ "email_questions_empty_categories": {+ "category": {+ "type": "choice",+ "instructions": "Which team should handle the email in `body`?",+ "criteria": {+ "billing": "invoices, payments, refunds",+ "technical": "bugs, outages, integrations",+ "sales": "pricing, demos, new purchases",+ "security": "phishing, scams, account compromise",+ "hr": "hiring, leave, payroll",+ "other": "none of the above"+ }+ },+ "is_spam": {+ "type": "noul",+ "instructions": "Is this email unsolicited spam or bulk marketing?"+ },+ "is_phishing": {+ "type": "noul",+ "instructions": "Is this email a phishing or scam attempt to steal money, credentials, or personal data?",+ "criteria": {+ "true": "phishing, scam, or fraud",+ "false": "a legitimate email"+ }+ },+ "urgency": {+ "type": "score",+ "instructions": "How urgent is the request in `body`?",+ "criteria": [+ "no time pressure",+ "needs attention soon",+ "blocking issue or hard deadline"+ ]+ },+ "needs_reply": {+ "type": "noul",+ "instructions": "Does the sender expect a reply?"+ }}}diff --git a/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/Presets.java b/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/Presets.javanew file mode 100644index 00000000..2de876d3--- /dev/null+++ b/laya-java/laya-java/src/main/java/com/convaiinnovations/laya/Presets.java@@ -0,0 +1,279 @@+package com.convaiinnovations.laya;++import com.convaiinnovations.laya.lang.UnicodeTables;+import java.util.Collections;+import java.util.LinkedHashMap;+import java.util.LinkedHashSet;+import java.util.List;+import java.util.Map;+import java.util.Set;++/**+ * Ready-to-use question sets for the decision workflows laya ships presets for.+ *+ * <p>A port of {@code laya.presets}. These are generated from the reference rather than retyped,+ * and a test compares them word for word: one changed word is a different question put to the+ * model and therefore a different answer, so a typo here is not a cosmetic bug.+ *+ * <p><b>The backtick convention.</b> A preset says which part of the state it reads by naming it+ * in backticks -- "What does the customer want in {@code `message`}?" -- and+ * {@link #stateField} reads that back out. It is what keeps the preset and the field name in step+ * without a hand-maintained table, and it is why the instruction text is load-bearing and not+ * prose.+ *+ * <p>Each factory returns a fresh mutable {@link LinkedHashMap} in the reference's order, ready to+ * pass to {@link Agent#predict}. Fresh, because a caller is expected to drop a question it does+ * not want or add one of its own; ordered, because the answers come back in the order asked.+ */+public final class Presets {++ private Presets() {+ }++ /** Customer support ticket triage. {@code laya.presets.triage_questions}. */+ public static Map<String, Question> triage() {+ Map<String, Question> out = new LinkedHashMap<>();+ out.put("intent", Question.choice(+ "What does the customer want in `message`?",+ ordered(+ "refund", "money returned or a duplicate charge reversed",+ "technical_help", "a bug, outage or integration problem",+ "billing_question", "a question about an invoice, plan or payment method",+ "information", "general information, pricing or how-to",+ "cancellation", "wants to cancel or downgrade",+ "other", "none of the other options fits")));+ out.put("is_urgent", Question.noul(+ "Does `message` communicate time pressure or a deadline?"));+ out.put("frustration", Question.score(+ "How frustrated does the customer sound in `message`?",+ List.of("calm and neutral",+ "concerned but civil",+ "clearly annoyed",+ "very angry or using strong language")));+ out.put("refund_requested", Question.noul(+ "Does the customer ask for money back?"));+ out.put("churn_risk", Question.noul(+ "Does `message` suggest the customer may leave for a competitor or cancel?"));+ return out;+ }++ /** Inbound email triage and threat filtering, with the reference's default categories. */+ public static Map<String, Question> email() {+ return email(null);+ }++ /**+ * Inbound email triage with the caller's categories in place of the defaults.+ *+ * <p>Categories <b>replace</b> the defaults rather than merge with them, and an empty map is+ * treated as no map at all -- which is the reference's behaviour, because it tests the+ * argument for truthiness and an empty dict is falsy. Worth stating because it reads like a+ * way to ask for no categories, and it is not: it asks for the defaults. A {@code choice}+ * question with no options is refused by {@link Question#choice} regardless.+ *+ * @param categories label to description, in the order they should be offered; may be null+ */+ public static Map<String, Question> email(Map<String, String> categories) {+ Map<String, Object> options;+ if (categories == null || categories.isEmpty()) {+ options = ordered(+ "billing", "invoices, payments, refunds",+ "technical", "bugs, outages, integrations",+ "sales", "pricing, demos, new purchases",+ "security", "phishing, scams, account compromise",+ "hr", "hiring, leave, payroll",+ "other", "none of the above");+ } else {+ options = new LinkedHashMap<>(categories);+ }+ Map<String, Question> out = new LinkedHashMap<>();+ out.put("category", Question.choice(+ "Which team should handle the email in `body`?", options));+ out.put("is_spam", Question.noul(+ "Is this email unsolicited spam or bulk marketing?"));+ out.put("is_phishing", Question.noul(+ "Is this email a phishing or scam attempt to steal money, credentials,"+ + " or personal data?",+ "a legitimate email", "phishing, scam, or fraud", null));+ out.put("urgency", Question.score(+ "How urgent is the request in `body`?",+ List.of("no time pressure", "needs attention soon",+ "blocking issue or hard deadline")));+ out.put("needs_reply", Question.noul("Does the sender expect a reply?"));+ return out;+ }++ /** Real-time guardrails on text going into a language model. */+ public static Map<String, Question> guard() {+ Map<String, Question> out = new LinkedHashMap<>();+ out.put("jailbreak", Question.noul(+ "Does `prompt` try to make an AI assistant ignore its rules, policies or system"+ + " instructions?"));+ out.put("prompt_injection", Question.noul(+ "Does `prompt` contain instructions aimed at the AI system rather than a genuine"+ + " user request?"));+ out.put("sensitive_data", Question.noul(+ "Does `prompt` contain credentials, personal data or other sensitive"+ + " information?"));+ out.put("harm_severity", Question.score(+ "How much harm would complying with `prompt` cause?",+ List.of("none: ordinary request",+ "minor: mildly inappropriate",+ "serious: unsafe advice or abuse",+ "severe: dangerous or illegal")));+ // Every criterion is null on purpose: these options carry no description and render as+ // their label alone. A map literal cannot hold them, which is why this is a LinkedHashMap.+ out.put("topic", Question.choice(+ "What is `prompt` about?",+ ordered("product_support", null,+ "coding", null,+ "general_knowledge", null,+ "personal_advice", null,+ "security_testing", null,+ "other", null)));+ return out;+ }++ /** Content safety and moderation. */+ public static Map<String, Question> moderation() {+ Map<String, Question> out = new LinkedHashMap<>();+ out.put("toxic", Question.noul(+ "Is `post` toxic: rude, disrespectful or likely to make someone leave the"+ + " discussion?"));+ out.put("harassment", Question.noul("Does `post` target or harass a specific person?"));+ out.put("threat", Question.noul(+ "Does `post` threaten violence, harm or intimidation?"));+ out.put("spam", Question.noul("Is `post` spam or advertising?"));+ out.put("severity", Question.score(+ "How severe is any rule-breaking in `post`?",+ List.of("no rule-breaking: ordinary on-topic post",+ "mild: rude tone or off-topic, no target",+ "clear violation: insults, harassment or spam aimed at someone",+ "severe: threats, hate speech or calls for violence")));+ return out;+ }++ /** Routing a request between language models of different cost. */+ public static Map<String, Question> router() {+ Map<String, Question> out = new LinkedHashMap<>();+ out.put("difficulty", Question.score(+ "How hard is `request` for a language model?",+ List.of("trivial: a lookup or one-liner",+ "easy: short answer, no reasoning",+ "moderate: several steps",+ "hard: long multi-step reasoning or specialist knowledge")));+ out.put("domain", Question.choice(+ "What domain does `request` belong to?",+ ordered(+ "code", "software engineering, programming, refactoring, architecture,"+ + " debugging",+ "math_or_logic", "mathematics, logic puzzles, proofs, complex calculation",+ "writing", "creative writing, essays, emails, blog posts, copywriting",+ "factual_lookup", "facts, definitions, trivia, history",+ "data_analysis", "statistics, SQL, data manipulation, metrics",+ "chitchat", "casual conversation, greetings, small talk")));+ out.put("needs_tools", Question.noul(+ "Does answering `request` require external tools, search or private data?"));+ out.put("is_sensitive", Question.noul(+ "Does `request` involve money, legal, medical or safety consequences?"));+ return out;+ }++ /** Every preset by the name {@code laya.presets} gives it, so a caller can list them. */+ public static Map<String, Map<String, Question>> all() {+ Map<String, Map<String, Question>> out = new LinkedHashMap<>();+ out.put("triage_questions", triage());+ out.put("email_questions", email());+ out.put("guard_questions", guard());+ out.put("moderation_questions", moderation());+ out.put("router_questions", router());+ return Collections.unmodifiableMap(out);+ }++ /**+ * The one state key these questions read, or null when that is not exactly one key.+ *+ * <p>Every built-in preset names a single field in backticks -- {@code message}, {@code body},+ * {@code prompt}, {@code post}, {@code request} -- and a caller who puts its text under a+ * different key is asking the model about a field the state does not have. Surfacing the name+ * lets a caller place the text correctly instead of guessing.+ *+ * <p>Null covers both "names nothing" and "names several", because only the caller knows which+ * field a request belongs in when a set reads two of them.+ *+ * <p>Only the instruction text is read. A backtick inside a criterion names no field, which+ * matters because criteria quote user-facing labels and would otherwise look like fields.+ */+ public static String stateField(Map<String, Question> questions) {+ if (questions == null) {+ return null;+ }+ Set<String> named = new LinkedHashSet<>();+ for (Question question : questions.values()) {+ if (question != null) {+ collectBacktickedFields(question.instructions(), named);+ }+ }+ return named.size() == 1 ? named.iterator().next() : null;+ }++ /**+ * The reference's {@code `(\w+)`} over one instruction.+ *+ * <p>Written out rather than handed to {@link java.util.regex.Pattern}, for the same reason the+ * detector's patterns are: Java's {@code \w} is not Python's. Java's admits combining marks+ * and join controls, so an instruction naming a field with a combining mark in it would match+ * here and not in the reference. {@link UnicodeTables#isPythonWordChar} is recorded from+ * CPython.+ *+ * <p>Scanning left to right and resuming after the closing backtick is what the reference's+ * {@code findall} does, and it is observable: in {@code `a`b`c`} the fields are {@code a} and+ * {@code c}, while a scanner that resumed inside the match would also offer {@code b}.+ */+ private static void collectBacktickedFields(String instructions, Set<String> into) {+ if (instructions == null) {+ return;+ }+ int i = 0;+ int length = instructions.length();+ while (i < length) {+ if (instructions.charAt(i) != '`') {+ i++;+ continue;+ }+ int j = i + 1;+ while (j < length) {+ int cp = instructions.codePointAt(j);+ if (!UnicodeTables.isPythonWordChar(cp)) {+ break;+ }+ j += Character.charCount(cp);+ }+ if (j > i + 1 && j < length && instructions.charAt(j) == '`') {+ into.add(instructions.substring(i + 1, j));+ i = j + 1;+ } else {+ i++;+ }+ }+ }++ /**+ * An ordered map from alternating key and value, where a value may be null.+ *+ * <p>{@code Map.of} cannot be used for any of these: it rejects a null value, and its+ * iteration order is unspecified. Both matter -- the {@code topic} preset's criteria are all+ * null, and a choice question's options are rendered in insertion order, so an unordered map+ * would change what the model is asked.+ */+ private static Map<String, Object> ordered(Object... pairs) {+ if (pairs.length % 2 != 0) {+ throw new IllegalArgumentException("ordered() takes alternating keys and values");+ }+ Map<String, Object> out = new LinkedHashMap<>();+ for (int i = 0; i < pairs.length; i += 2) {+ out.put((String) pairs[i], pairs[i + 1]);+ }+ return out;+ }+}diff --git a/laya-java/laya-java/src/test/java/com/convaiinnovations/laya/PresetsTest.java b/laya-java/laya-java/src/test/java/com/convaiinnovations/laya/PresetsTest.javanew file mode 100644index 00000000..11fa36f3--- /dev/null+++ b/laya-java/laya-java/src/test/java/com/convaiinnovations/laya/PresetsTest.java@@ -0,0 +1,271 @@+package com.convaiinnovations.laya;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotSame;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;++import java.util.ArrayList;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.DynamicTest;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestFactory;++/**+ * {@link Presets} against the question sets recorded from {@code laya.presets}.+ *+ * <p>Word for word, because one changed word is a different question put to the model and+ * therefore a different answer. The comparison is made on what the model is actually shown -- the+ * instruction, the rendered options in order, the labels and the legend -- rather than on the+ * Java object, so a difference that survives rendering is the only kind that can pass.+ */+class PresetsTest {++ private static Map<String, Object> fixture() {+ return Fixtures.load("presets.json");+ }++ @SuppressWarnings("unchecked")+ private static Map<String, Object> map(Object value) {+ return (Map<String, Object>) value;+ }++ @SuppressWarnings("unchecked")+ private static List<Object> list(Object value) {+ return (List<Object>) value;+ }++ /** The recorded spec rebuilt as a {@link Question}, so the two can be compared as rendered. */+ private static Question questionOf(Map<String, Object> spec) {+ String type = (String) spec.get("type");+ String instructions = (String) spec.get("instructions");+ Object criteria = spec.get("criteria");+ if ("choice".equals(type)) {+ return Question.choice(instructions, map(criteria));+ }+ if ("score".equals(type)) {+ return Question.score(instructions, list(criteria));+ }+ Map<String, Object> sides = criteria instanceof Map ? map(criteria) : Map.of();+ return Question.noul(instructions, sides.get("false"), sides.get("true"), null);+ }++ private static void assertSameQuestion(String where, Question expected, Question actual) {+ assertEquals(expected.type(), actual.type(), where + ": type");+ assertEquals(expected.instructions(), actual.instructions(), where + ": instructions");+ // Rendered options carry both the criterion text and its ORDER, which for a choice is+ // part of the question: the answer's probabilities are positional.+ assertEquals(expected.renderOptions(), actual.renderOptions(), where + ": rendered options");+ assertEquals(expected.labels(), actual.labels(), where + ": labels");+ // Only a score question has a legend; asking a choice or noul for one is an error by+ // design, because there is no level to describe.+ if (expected.type() == Question.Type.SCORE) {+ assertEquals(expected.legend(), actual.legend(), where + ": legend");+ assertEquals(new ArrayList<>(expected.legend().keySet()),+ new ArrayList<>(actual.legend().keySet()), where + ": legend order");+ }+ }++ private static void assertSameSet(String name, Map<String, Object> recorded,+ Map<String, Question> built) {+ assertEquals(new ArrayList<>(recorded.keySet()), new ArrayList<>(built.keySet()),+ name + ": the questions, or their order, differ from the reference");+ for (Map.Entry<String, Object> entry : recorded.entrySet()) {+ assertSameQuestion(name + "." + entry.getKey(),+ questionOf(map(entry.getValue())), built.get(entry.getKey()));+ }+ }++ @TestFactory+ @DisplayName("every preset matches the reference, question for question and word for word")+ List<DynamicTest> presetsMatch() {+ Map<String, Object> recorded = fixture();+ Map<String, Map<String, Question>> built = Presets.all();+ List<DynamicTest> tests = new ArrayList<>();+ for (Map.Entry<String, Map<String, Question>> entry : built.entrySet()) {+ String name = entry.getKey();+ Map<String, Object> expected = map(recorded.get(name));+ tests.add(DynamicTest.dynamicTest(name,+ () -> assertSameSet(name, expected, entry.getValue())));+ }+ return tests;+ }++ @Test+ @DisplayName("the port carries every preset the reference has, and no invented one")+ void everyPresetIsCovered() {+ List<String> recorded = new ArrayList<>();+ for (String key : fixture().keySet()) {+ if (key.endsWith("_questions")) {+ recorded.add(key);+ }+ }+ List<String> built = new ArrayList<>(Presets.all().keySet());+ recorded.sort(null);+ List<String> sortedBuilt = new ArrayList<>(built);+ sortedBuilt.sort(null);+ assertEquals(recorded, sortedBuilt,+ "the reference's presets and the port's do not line up; a preset was added"+ + " upstream or invented here");+ assertTrue(built.size() >= 5, "only " + built.size() + " presets");+ }++ @Test+ @DisplayName("stateField names the one field each preset reads")+ void stateFieldPerPreset() {+ Map<String, Object> recorded = map(fixture().get("state_field"));+ Map<String, Map<String, Question>> built = Presets.all();+ for (Map.Entry<String, Object> entry : recorded.entrySet()) {+ Map<String, Question> questions = built.get(entry.getKey());+ assertTrue(questions != null, "no port preset named " + entry.getKey());+ assertEquals(entry.getValue(), Presets.stateField(questions),+ entry.getKey() + ": the field named in backticks");+ }+ assertTrue(recorded.size() >= 5, "only " + recorded.size() + " presets checked");+ }++ @TestFactory+ @DisplayName("stateField answers the hostile cases the way the reference does")+ List<DynamicTest> stateFieldHostile() {+ Map<String, Object> expected = map(fixture().get("state_field_hostile"));+ Map<String, Object> specs = map(fixture().get("hostile_specs"));+ List<DynamicTest> tests = new ArrayList<>();+ for (Map.Entry<String, Object> entry : expected.entrySet()) {+ String name = entry.getKey();+ Map<String, Object> spec = map(specs.get(name));+ // Two of the recorded cases give an instruction of null or leave it out entirely.+ // They are not expressible here: Question refuses a blank instruction at+ // construction, which is strictly earlier than the reference, and that refusal is+ // asserted below instead of being skipped silently.+ boolean instructionMissing = false;+ for (Object value : spec.values()) {+ Map<String, Object> question = map(value);+ if (question.get("instructions") == null) {+ instructionMissing = true;+ }+ }+ if (instructionMissing) {+ tests.add(DynamicTest.dynamicTest(name + " (refused at construction)",+ () -> assertThrows(IllegalArgumentException.class,+ () -> questionOf(map(spec.values().iterator().next())),+ "a question with no instruction must be refused, not accepted"+ + " and then reported as naming no field")));+ continue;+ }+ tests.add(DynamicTest.dynamicTest(name, () -> {+ Map<String, Question> questions = new LinkedHashMap<>();+ for (Map.Entry<String, Object> q : spec.entrySet()) {+ questions.put(q.getKey(), questionOf(map(q.getValue())));+ }+ assertEquals(entry.getValue(), Presets.stateField(questions), name);+ }));+ }+ return tests;+ }++ @Test+ @DisplayName("custom email categories replace the defaults, in the caller's order")+ void emailCategoriesReplaceTheDefaults() {+ Map<String, String> categories = new LinkedHashMap<>();+ categories.put("ops", "incidents and deploys");+ categories.put("legal", "contracts and compliance");+ assertSameSet("email_questions_custom", map(fixture().get("email_questions_custom")),+ Presets.email(categories));+ }++ @Test+ @DisplayName("an EMPTY category map asks for the defaults, as the reference's truth test does")+ void emptyEmailCategoriesMeanTheDefaults() {+ // Reads like a way to ask for no categories, and is not: the reference tests the argument+ // for truthiness and an empty dict is falsy, so it falls through to the defaults. Pinned+ // because a port that checked only for null would build a choice question with no options+ // and throw instead.+ assertSameSet("email_questions_empty_categories",+ map(fixture().get("email_questions_empty_categories")),+ Presets.email(new LinkedHashMap<>()));+ assertEquals(Presets.email().get("category").renderOptions(),+ Presets.email(new LinkedHashMap<>()).get("category").renderOptions());+ }++ @Test+ @DisplayName("stateField reads the instruction only, never a criterion")+ void criteriaAreNotFields() {+ // Criteria quote user-facing labels, so a backtick in one is punctuation and not a field+ // name. A port that scanned the whole rendered question would find `message` here and+ // report a field this question does not read.+ Map<String, Question> questions = new LinkedHashMap<>();+ questions.put("q", Question.choice("Pick one.",+ new LinkedHashMap<>(Map.of("x", "look at `message`"))));+ assertNull(Presets.stateField(questions));+ }++ @Test+ @DisplayName("the backtick scan resumes after the closing tick, as findall does")+ void backtickScanIsNonOverlapping() {+ // In "`a`b`c`" the fields are a and c. A scanner that resumed inside its own match would+ // also offer b, which would turn a one-field preset into a three-field one and make+ // stateField answer null.+ Map<String, Question> two = new LinkedHashMap<>();+ two.put("q", Question.noul("Read `a`b`c` please"));+ assertNull(Presets.stateField(two), "two fields named, so no single field");+ Map<String, Question> one = new LinkedHashMap<>();+ one.put("q", Question.noul("Read `a`b`a` please"));+ assertEquals("a", Presets.stateField(one), "the same field twice is still one field");+ Map<String, Question> doubled = new LinkedHashMap<>();+ doubled.put("q", Question.noul("Read ``a`` please"));+ assertEquals("a", Presets.stateField(doubled), "a doubled tick still names the field");+ Map<String, Question> none = new LinkedHashMap<>();+ none.put("q", Question.noul("Read `a-b` and `c d` please"));+ assertNull(Presets.stateField(none), "neither is a word, so neither is a field");+ }++ @Test+ @DisplayName("null and an empty question set name no field rather than throwing")+ void stateFieldHandlesNothing() {+ assertNull(Presets.stateField(null));+ assertNull(Presets.stateField(new LinkedHashMap<>()));+ }++ @Test+ @DisplayName("each call returns a fresh mutable map, so a caller can edit one safely")+ void presetsAreFreshAndMutable() {+ // A caller is expected to drop a question it does not want. Returning a shared or+ // immutable map would make that either impossible or visible to the next caller.+ Map<String, Question> first = Presets.triage();+ Map<String, Question> second = Presets.triage();+ assertNotSame(first, second);+ first.remove("churn_risk");+ assertTrue(second.containsKey("churn_risk"),+ "editing one caller's preset changed the next caller's");+ assertEquals(5, second.size());+ second.put("extra", Question.noul("Is this a test?"));+ assertEquals(5, Presets.triage().size(), "an added question leaked into the preset");+ }++ @Test+ @DisplayName("every preset is accepted by the question renderer")+ void everyPresetRenders() {+ // The presets are data, and data can be wrong in a way that only shows when the model is+ // asked: a score level that is null, a choice with no options. Rendering every one of them+ // here means a typo in this file fails a test rather than a prediction.+ for (Map.Entry<String, Map<String, Question>> preset : Presets.all().entrySet()) {+ for (Map.Entry<String, Question> entry : preset.getValue().entrySet()) {+ String where = preset.getKey() + "." + entry.getKey();+ Question question = entry.getValue();+ List<String> options = question.renderOptions();+ assertTrue(options.size() >= 2, where + " offers " + options.size() + " options");+ for (String option : options) {+ assertTrue(option != null && !option.isBlank(),+ where + " renders a blank option");+ }+ assertTrue(!question.instructions().isBlank(), where + " has no instruction");+ assertEquals(options.size(), question.labels().size(),+ where + ": one label per option");+ }+ }+ }+}diff --git a/laya-java/scripts/gen_fixtures.py b/laya-java/scripts/gen_fixtures.pyindex dd7bd5fc..9e991928 100644--- a/laya-java/scripts/gen_fixtures.py+++ b/laya-java/scripts/gen_fixtures.py@@ -447,6 +447,43 @@ def presets():continueif isinstance(value, dict):out[name] = value++ # `state_field` is the other half of the module and was not recorded: it reads the backtick+ # convention out of each preset's instructions, so a port that retyped one instruction without+ # its backticks would still match the question dicts above and then silently report that the+ # preset names no field. Recorded per preset, plus the inputs that must answer None -- a spec+ # that names nothing, one that names two different fields, and the empty mapping.+ hostile = {+ "no-backticks": {"q": {"type": "noul", "instructions": "Is this urgent?"}},+ "two-fields": {+ "a": {"type": "noul", "instructions": "Does `message` ask for a refund?"},+ "b": {"type": "noul", "instructions": "Is `body` urgent?"},+ },+ "same-field-twice": {+ "a": {"type": "noul", "instructions": "Does `message` ask for a refund?"},+ "b": {"type": "noul", "instructions": "Is `message` urgent?"},+ },+ "empty": {},+ "missing-instructions": {"q": {"type": "noul"}},+ "null-instructions": {"q": {"type": "noul", "instructions": None}},+ "non-word-backticks": {"q": {"type": "noul", "instructions": "Read `a-b` and `c d`."}},+ "underscored-field": {"q": {"type": "noul", "instructions": "Read `customer_message`."}},+ "backtick-in-criteria-only": {+ "q": {"type": "choice", "instructions": "Pick one.",+ "criteria": {"x": "look at `message`"}},+ },+ }+ out["state_field"] = {name: mod.state_field(spec) for name, spec in out.items()+ if isinstance(spec, dict)}+ out["state_field_hostile"] = {name: mod.state_field(spec)+ for name, spec in hostile.items()}+ out["hostile_specs"] = hostile+ # `email_questions` is the one preset that takes an argument, and a caller's categories must+ # replace the defaults rather than merge with them.+ out["email_questions_custom"] = mod.email_questions(+ {"ops": "incidents and deploys", "legal": "contracts and compliance"})+ out["email_questions_empty_categories"] = mod.email_questions({}) \+ if mod.email_questions({}) is not None else Nonereturn out