package com.linkerbot.vibemake.service.cad.ai;

import static org.assertj.core.api.Assertions.*;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.linkerbot.vibemake.service.config.CadAiProperties;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import org.junit.jupiter.api.*;

class CadAiKnowledgeTest {
    private static final String BUILD = "5707e4ae25621c4a32c40108";
    private static final String EXPANSION_BUILD = "f3d62ce93f72db42f311a46e";
    private final ObjectMapper json = new ObjectMapper();
    private CadAiProperties properties;
    private CadAiKnowledge knowledge;

    @BeforeEach void setup() throws Exception {
        properties = new CadAiProperties();
        properties.setKnowledgeMode("pilot");
        knowledge = HistoricalCadAiKnowledge.knowledge(json, properties);
    }

    private ObjectNode request(String query) {
        ObjectNode input = json.createObjectNode().put("query", query);
        input.putObject("facts").put("module_mm", 2).put("teeth", 24).put("pressure_angle_deg", 20)
                .put("profile_shift", 0).put("backlash_mm", 0).put("addendum_coefficient", 1)
                .put("clearance_coefficient", 0.25).put("root_transition", "radial-simplified");
        return input;
    }

    @Test void fixedRoutingEvaluationCovers140DeclaredScenarios() throws Exception {
        JsonNode suite = json.readTree(getClass().getResourceAsStream("/cad/ai/knowledge/evals/gear-routing-v3.json"));
        assertThat(suite.path("cases")).hasSize(140);
        Map<String, Integer> counts = new HashMap<>();
        for (JsonNode item : suite.path("cases")) {
            counts.merge(item.path("group").asText(), 1, Integer::sum);
            if (item.has("previous_query")) {
                assertThat(knowledge.lookup(request(item.path("previous_query").asText()), item.path("previous_build").asText(BUILD)).path("status").asText())
                        .as(item.path("id").asText()).isEqualTo(item.path("previous_status").asText());
            }
            ObjectNode input = request(item.path("query").asText());
            if (item.has("facts")) input.set("facts", item.path("facts").deepCopy());
            ObjectNode facts = (ObjectNode) input.path("facts");
            for (JsonNode field : item.path("remove_facts")) facts.remove(field.asText());
            Iterator<Map.Entry<String, JsonNode>> overrides = item.path("fact_overrides").fields();
            while (overrides.hasNext()) { Map.Entry<String, JsonNode> entry = overrides.next(); facts.set(entry.getKey(), entry.getValue()); }
            JsonNode result = knowledge.lookup(input, item.path("build").asText(BUILD));
            String expectedStatus = HistoricalCadAiKnowledge.runtimeStatus(item);
            assertThat(result.path("status").asText()).as(item.path("id").asText()).isEqualTo(expectedStatus);
            if (item.has("type_id")) assertThat(result.path("type_id").asText()).as(item.path("id").asText()).isEqualTo(item.path("type_id").asText());
            assertThat(result.path("documents").size()).as(item.path("id").asText()).isEqualTo("matched".equals(expectedStatus) ? 1 : 0);
            if (item.has("doc_id")) assertThat(result.path("documents").get(0).path("id").asText())
                    .as(item.path("id").asText()).isEqualTo(item.path("doc_id").asText());
            for (JsonNode field : item.path("missing")) assertThat(result.path("missing").toString())
                    .as(item.path("id").asText()).contains(field.asText());
            for (JsonNode field : item.path("conflicts")) assertThat(result.path("conflicts").toString())
                    .as(item.path("id").asText()).contains(field.asText());
        }
        assertThat(counts).containsExactlyInAnyOrderEntriesOf(Map.ofEntries(
                Map.entry("explicit",18), Map.entry("nested",12), Map.entry("ambiguous",10), Map.entry("negation",8),
                Map.entry("multi_turn",12), Map.entry("unavailable",8), Map.entry("nonmodel",4), Map.entry("eligible",13),
                Map.entry("missing",13), Map.entry("scope",13), Map.entry("compatibility",13), Map.entry("mechanism_component",4),
                Map.entry("derived_domain",12)));
    }

    @Test void fixedRoutingV4KeepsHistoricalCasesAndChecksExplicitMechanismMembership() throws Exception {
        JsonNode previous = json.readTree(getClass().getResourceAsStream("/cad/ai/knowledge/evals/gear-routing-v3.json"));
        JsonNode suite = json.readTree(getClass().getResourceAsStream("/cad/ai/knowledge/evals/gear-routing-v4.json"));
        assertThat(suite.path("cases")).hasSize(152);
        for (int index = 0; index < 140; index++) assertThat(suite.path("cases").get(index)).isEqualTo(previous.path("cases").get(index));
        for (JsonNode item : suite.path("cases")) {
            if (!"mechanism_membership".equals(item.path("group").asText())) continue;
            ObjectNode input = json.createObjectNode().put("query", item.path("query").asText());
            input.set("facts", item.path("facts").deepCopy());
            if (item.has("input_type_id")) input.put("type_id", item.path("input_type_id").asText());
            JsonNode result = knowledge.lookup(input, item.path("build").asText());
            assertThat(result.path("status").asText()).as(item.path("id").asText()).isEqualTo(item.path("status").asText());
            assertThat(result.path("documents").size()).as(item.path("id").asText()).isEqualTo("matched".equals(item.path("status").asText()) ? 1 : 0);
            if (item.has("doc_id")) assertThat(result.path("documents").get(0).path("id").asText()).isEqualTo(item.path("doc_id").asText());
        }
    }

    @Test void fixedRoutingV5KeepsHistoricalCasesAndChecksScopedEngagementQualifiers() throws Exception {
        JsonNode previous = json.readTree(getClass().getResourceAsStream("/cad/ai/knowledge/evals/gear-routing-v4.json"));
        JsonNode suite = json.readTree(getClass().getResourceAsStream("/cad/ai/knowledge/evals/gear-routing-v5.json"));
        assertThat(suite.path("cases")).hasSize(180);
        for (int index = 0; index < 152; index++) assertThat(suite.path("cases").get(index)).isEqualTo(previous.path("cases").get(index));
        List<org.junit.jupiter.api.function.Executable> checks = new ArrayList<>();
        for (JsonNode item : suite.path("cases")) {
            if (!"engagement_qualifier".equals(item.path("group").asText())) continue;
            checks.add(() -> {
                ObjectNode input = json.createObjectNode().put("query", item.path("query").asText());
                input.set("facts", item.path("facts").deepCopy());
                if (item.has("input_type_id")) input.put("type_id", item.path("input_type_id").asText());
                ObjectNode original = input.deepCopy();
                JsonNode result = knowledge.lookup(input, item.path("build").asText());
                assertThat(result.path("status").asText()).as(item.path("id").asText()).isEqualTo(item.path("status").asText());
                assertThat(result.path("documents").size()).as(item.path("id").asText()).isEqualTo("matched".equals(item.path("status").asText()) ? 1 : 0);
                if (item.has("type_id")) assertThat(result.path("type_id").asText()).as(item.path("id").asText()).isEqualTo(item.path("type_id").asText());
                if (item.has("doc_id")) assertThat(result.path("documents").get(0).path("id").asText()).isEqualTo(item.path("doc_id").asText());
                assertThat(input).isEqualTo(original);
            });
        }
        assertThat(checks).hasSize(28);
        org.junit.jupiter.api.Assertions.assertAll(checks);
    }

    @Test void fixedRoutingV6KeepsHistoryAndChecksProhibitionScopeAndExplicitRackPinionNames() throws Exception {
        JsonNode previous = json.readTree(getClass().getResourceAsStream("/cad/ai/knowledge/evals/gear-routing-v5.json"));
        JsonNode suite = json.readTree(getClass().getResourceAsStream("/cad/ai/knowledge/evals/gear-routing-v6.json"));
        assertThat(suite.path("cases")).hasSize(222);
        for (int index = 0; index < 180; index++) assertThat(suite.path("cases").get(index)).isEqualTo(previous.path("cases").get(index));
        List<org.junit.jupiter.api.function.Executable> checks = new ArrayList<>();
        for (int index = 180; index < suite.path("cases").size(); index++) {
            JsonNode item = suite.path("cases").get(index);
            checks.add(() -> {
                ObjectNode input = json.createObjectNode().put("query", item.path("query").asText());
                input.set("facts", item.path("facts").deepCopy());
                if (item.has("input_type_id")) input.put("type_id", item.path("input_type_id").asText());
                ObjectNode original = input.deepCopy();
                JsonNode result = knowledge.lookup(input, item.path("build").asText());
                assertThat(result.path("status").asText()).as(item.path("id").asText()).isEqualTo(item.path("status").asText());
                assertThat(result.path("documents").size()).as(item.path("id").asText()).isEqualTo("matched".equals(item.path("status").asText()) ? 1 : 0);
                if (item.has("type_id")) assertThat(result.path("type_id").asText()).as(item.path("id").asText()).isEqualTo(item.path("type_id").asText());
                if (item.has("doc_id")) assertThat(result.path("documents").get(0).path("id").asText()).isEqualTo(item.path("doc_id").asText());
                for (JsonNode field : item.path("missing")) assertThat(result.path("missing").toString()).as(item.path("id").asText()).contains(field.asText());
                assertThat(input).isEqualTo(original);
            });
        }
        assertThat(checks).hasSize(42);
        org.junit.jupiter.api.Assertions.assertAll(checks);
    }

    @Test void fixedRoutingV7PreservesHistoryAndSeparatesReferencesFromCreationTargets() throws Exception {
        JsonNode previous = json.readTree(getClass().getResourceAsStream("/cad/ai/knowledge/evals/gear-routing-v6.json"));
        JsonNode suite = json.readTree(getClass().getResourceAsStream("/cad/ai/knowledge/evals/gear-routing-v7.json"));
        assertThat(suite.path("cases").size()).isGreaterThan(222);
        for (int index = 0; index < 222; index++) assertThat(suite.path("cases").get(index)).isEqualTo(previous.path("cases").get(index));
        List<org.junit.jupiter.api.function.Executable> checks = new ArrayList<>();
        for (int index = 222; index < suite.path("cases").size(); index++) {
            JsonNode item = suite.path("cases").get(index);
            checks.add(() -> {
                ObjectNode input = json.createObjectNode().put("query", item.path("query").asText());
                input.set("facts", item.path("facts").deepCopy());
                if (item.has("input_type_id")) input.put("type_id", item.path("input_type_id").asText());
                ObjectNode original = input.deepCopy();
                JsonNode result = knowledge.lookup(input, EXPANSION_BUILD);
                assertThat(result.path("status").asText()).as(item.path("id").asText()).isEqualTo(item.path("status").asText());
                assertThat(result.path("documents").size()).as(item.path("id").asText()).isEqualTo("matched".equals(item.path("status").asText()) ? 1 : 0);
                if (item.has("type_id")) assertThat(result.path("type_id").asText()).as(item.path("id").asText()).isEqualTo(item.path("type_id").asText());
                if (item.has("doc_id")) assertThat(result.path("documents").get(0).path("id").asText()).isEqualTo(item.path("doc_id").asText());
                assertThat(input).isEqualTo(original);
            });
        }
        org.junit.jupiter.api.Assertions.assertAll(checks);
    }

    @Test void fixedRoutingV8KeepsHistoryAndRequiresQualifiedPinionTypes() throws Exception {
        JsonNode previous = json.readTree(getClass().getResourceAsStream("/cad/ai/knowledge/evals/gear-routing-v7.json"));
        JsonNode suite = json.readTree(getClass().getResourceAsStream("/cad/ai/knowledge/evals/gear-routing-v8.json"));
        assertThat(suite.path("cases")).hasSize(287);
        for (int index = 0; index < 268; index++) assertThat(suite.path("cases").get(index)).isEqualTo(previous.path("cases").get(index));
        List<org.junit.jupiter.api.function.Executable> checks = new ArrayList<>();
        for (int index = 268; index < suite.path("cases").size(); index++) {
            JsonNode item = suite.path("cases").get(index);
            checks.add(() -> {
                ObjectNode input = json.createObjectNode().put("query", item.path("query").asText());
                input.set("facts", item.path("facts").deepCopy());
                JsonNode result = knowledge.lookup(input, EXPANSION_BUILD);
                assertThat(result.path("status").asText()).as(item.path("id").asText()).isEqualTo(item.path("status").asText());
                assertThat(result.path("documents").size()).isZero();
                if (item.has("type_id")) assertThat(result.path("type_id").asText()).as(item.path("id").asText()).isEqualTo(item.path("type_id").asText());
            });
        }
        org.junit.jupiter.api.Assertions.assertAll(checks);
    }

    @Test void wormFactDescriptionsIdentifyTheReferenceObjectWithoutInferringValues() throws Exception {
        JsonNode fields = HistoricalCadAiKnowledge.tools(json).definitions(true).stream().filter(tool -> "knowledge_lookup".equals(tool.name()))
                .findFirst().orElseThrow().parameters().path("properties").path("facts").path("properties");
        assertThat(fields.path("pitch_diameter_mm").path("description").asText()).contains("蜗杆", "参考", "蜗轮", "不是");
        assertThat(fields.path("worm_starts").path("description").asText()).contains("参考", "蜗轮");
    }

    @Test void rackFactDescriptionsSeparateCircularToothCountAndRootBelowBaseThickness() throws Exception {
        JsonNode fields = HistoricalCadAiKnowledge.tools(json).definitions(true).stream().filter(tool -> "knowledge_lookup".equals(tool.name()))
                .findFirst().orElseThrow().parameters().path("properties").path("facts").path("properties");
        assertThat(fields.path("teeth").path("description").asText()).contains("圆齿轮", "rack_teeth");
        assertThat(fields.path("rack_teeth").path("description").asText()).contains("直齿齿条", "斜齿齿条", "完整齿数", "teeth");
        assertThat(fields.path("base_height_mm").path("description").asText()).contains("直齿齿条", "斜齿齿条", "齿根", "底面", "不含齿高");
    }

    @Test void conflictResponseOffersRegisteredConditionsWithoutChangingInput() throws Exception {
        ObjectNode input = json.createObjectNode().put("query", "直齿锥齿轮").put("type_id", "straight-bevel-gear");
        input.set("facts", json.readTree("""
                {"module_mm":2,"teeth":24,"pressure_angle_deg":20,"profile_shift":0,"backlash_mm":0,
                 "addendum_coefficient":1,"clearance_coefficient":0.25,"cone_angle_deg":45,"axial_height_mm":8,
                 "root_transition":"radial-simplified","geometry_representation":"natural-language approximation"}
                """));
        ObjectNode original = input.deepCopy();
        JsonNode result = knowledge.lookup(input, EXPANSION_BUILD);
        assertThat(result.path("status").asText()).isEqualTo("uncovered");
        assertThat(result.path("documents")).isEmpty();
        assertThat(result.path("supported_conditions").path("geometry_representation").path("equals").asText())
                .isEqualTo("homothetic-frontal-involute-bevel-v1");
        assertThat(input).isEqualTo(original);
    }

    @Test void schemaListsPolicyRepresentationIdsAndPressureAngleApplicability() throws Exception {
        CadAiTools tools = HistoricalCadAiKnowledge.tools(json);
        JsonNode schema = tools.definitions(true).stream().filter(tool -> "knowledge_lookup".equals(tool.name())).findFirst().orElseThrow().parameters();
        JsonNode fields = schema.path("properties").path("facts").path("properties");
        JsonNode policy = HistoricalCadAiKnowledge.policy(json);
        Set<String> expected = new TreeSet<>();
        for (JsonNode document : policy.path("documents")) {
            JsonNode value = document.path("conditions").path("geometry_representation").path("equals");
            if (!"retired".equals(document.path("status").asText()) && value.isTextual()) expected.add(value.asText());
        }
        Set<String> actual = new TreeSet<>();
        for (JsonNode value : fields.path("geometry_representation").path("enum")) if (value.isTextual()) actual.add(value.asText());
        assertThat(actual).containsExactlyElementsOf(expected);
        assertThat(fields.path("pressure_angle_deg").path("description").asText()).contains("直齿", "端面", "normal_pressure_angle_deg", "axial_pressure_angle_deg");
        assertThat(fields.path("normal_pressure_angle_deg").path("description").asText()).contains("斜齿圆柱", "斜齿齿条");
        assertThat(fields.path("axial_pressure_angle_deg").path("description").asText()).contains("ZA蜗杆");
        ObjectNode input = request("齿轮副").put("type_id", "gear-pair");
        ((ObjectNode) input.path("facts")).putNull("geometry_representation");
        tools.validateCall("knowledge_lookup", input);
        ((ObjectNode) input.path("facts")).put("geometry_representation", "invented-representation");
        assertThatThrownBy(() -> tools.validateCall("knowledge_lookup", input)).isInstanceOf(com.linkerbot.vibemake.common.BusinessException.class);
        assertThat(CadAiKnowledge.INSTRUCTIONS).doesNotContain("一次查询").contains("补齐", "重查");
    }

    @Test void rootTransitionSchemaUsesPolicyValuesAndIdentifiesInternalCircularRoot() throws Exception {
        JsonNode schema = HistoricalCadAiKnowledge.tools(json).definitions(true).stream().filter(tool -> "knowledge_lookup".equals(tool.name()))
                .findFirst().orElseThrow().parameters().path("properties").path("facts").path("properties");
        JsonNode root = schema.path("root_transition");
        Set<String> values = new TreeSet<>();
        for (JsonNode value : root.path("enum")) if (value.isTextual()) values.add(value.asText());
        assertThat(values).containsExactly("circular-simplified", "radial-simplified", "sharp-simplified");
        assertThat(root.path("description").asText()).contains("内直齿", "圆弧", "径向", "尖角", "internal-spur-gear", "circular-simplified");
        CadAiTools tools = HistoricalCadAiKnowledge.tools(json);
        for (String value : values) {
            ObjectNode input = request("直齿轮");
            ((ObjectNode) input.path("facts")).put("root_transition", value);
            tools.validateCall("knowledge_lookup", input);
        }
        ObjectNode input = request("内直齿轮").put("type_id", "internal-spur-gear");
        ((ObjectNode) input.path("facts")).put("teeth",40).put("outer_radius_mm",50);
        ObjectNode original = input.deepCopy();
        JsonNode result = knowledge.lookup(input, EXPANSION_BUILD);
        assertThat(result.path("status").asText()).isEqualTo("uncovered");
        assertThat(result.path("supported_conditions").path("root_transition").path("equals").asText()).isEqualTo("circular-simplified");
        assertThat(input).isEqualTo(original);
        ((ObjectNode) input.path("facts")).putNull("root_transition");
        tools.validateCall("knowledge_lookup", input);
        assertThat(knowledge.lookup(input, EXPANSION_BUILD).path("status").asText()).isEqualTo("needs_conditions");
    }

    @Test void directlyLoadsOnlyUnchangedRecipeOnceConditionsAndBuildMatch() {
        JsonNode result = knowledge.lookup(request("做一个渐开线直齿轮，不要凸台和键槽"), BUILD);
        assertThat(result.path("status").asText()).isEqualTo("matched");
        assertThat(result.path("documents")).hasSize(1);
        assertThat(result.path("documents").get(0).path("sha256").asText())
                .isEqualTo("70cf10a008e7f4183456579201d1f42fbc04511f4cb573a8afd784e2d730ab2d");
        assertThat(result.path("documents").get(0).path("text").asText()).contains("sketch.equation_curve");
        assertThat(result.toString()).doesNotContain("MCB", "完整分类树");
    }

    @Test void separatesGearTypesAndRequiresTheirOwnConditions() {
        Map<String, String> inputs = Map.ofEntries(
                Map.entry("斜齿轮", "helical-cylindrical-gear"), Map.entry("直齿锥齿轮", "straight-bevel-gear"), Map.entry("圆锥直齿轮", "straight-bevel-gear"), Map.entry("内啮合直齿轮", "internal-spur-gear"),
                Map.entry("螺旋锥齿轮", "spiral-bevel-gear"), Map.entry("内直齿轮", "internal-spur-gear"),
                Map.entry("直齿齿条", "straight-rack"), Map.entry("斜齿齿条", "helical-rack"),
                Map.entry("蜗轮", "worm-wheel"), Map.entry("蜗杆", "worm"),
                Map.entry("齿轮箱外壳", "gearbox-housing"), Map.entry("摆线齿轮", "other-geared-transmission"));
        for (Map.Entry<String, String> input : inputs.entrySet()) {
            JsonNode result = knowledge.lookup(json.createObjectNode().put("query", input.getKey()), EXPANSION_BUILD);
            assertThat(result.path("type_id").asText()).as(input.getKey()).isEqualTo(input.getValue());
            assertThat(result.path("documents")).isEmpty();
            assertThat(result.path("status").asText()).isEqualTo(
                    Set.of("gearbox-housing", "other-geared-transmission").contains(input.getValue()) ? "uncovered" : "needs_conditions");
        }
    }

    @Test void keepsAmbiguityAndMechanismBoundaries() {
        for (String query : List.of("齿轮", "螺旋齿轮", "锥齿轮", "齿条", "平行轴传动", "90度传动")) {
            JsonNode result = knowledge.lookup(request(query), BUILD);
            assertThat(result.path("status").asText()).as(query).isEqualTo("ambiguous");
            assertThat(result.path("documents")).isEmpty();
        }
        for (String query : List.of("蜗轮蜗杆机构", "齿轮齿条机构", "行星齿轮机构", "齿轮副")) {
            JsonNode result = knowledge.lookup(json.createObjectNode().put("query", query), EXPANSION_BUILD);
            assertThat(result.path("documents")).as(query).isEmpty();
            assertThat(result.path("status").asText()).as(query).isEqualTo("needs_conditions");
            assertThat(result.path("missing").toString()).contains("geometry_representation");
        }
    }

    @Test void honorsNegatedAlternativesAndRejectsConflictingExplicitType() {
        assertThat(knowledge.lookup(request("不要蜗杆，用直齿轮"), BUILD).path("status").asText()).isEqualTo("matched");
        assertThat(knowledge.lookup(request("不要直齿轮，改成斜齿轮"), BUILD).path("type_id").asText()).isEqualTo("helical-cylindrical-gear");
        assertThat(knowledge.lookup(request("直齿锥齿轮").put("type_id", "involute-spur-gear"), BUILD).path("status").asText()).isEqualTo("ambiguous");
        assertThat(knowledge.lookup(request("不要齿轮"), BUILD).path("documents")).isEmpty();
        assertThat(knowledge.lookup(request("不要直齿轮，只做外壳").put("type_id", "involute-spur-gear"), BUILD).path("documents")).isEmpty();
        assertThat(knowledge.lookup(request("做一个spur gear和一个未明确的gear"), BUILD).path("status").asText()).isEqualTo("ambiguous");
    }

    @Test void requiresEveryCriticalConditionAndRejectsUnsupportedValuesWithoutChangingThem() {
        ObjectNode complete = request("直齿轮");
        List<String> fields = new ArrayList<>();
        complete.path("facts").fieldNames().forEachRemaining(fields::add);
        for (String field : fields) {
            ObjectNode input = complete.deepCopy();
            ((ObjectNode) input.path("facts")).remove(field);
            JsonNode result = knowledge.lookup(input, BUILD);
            assertThat(result.path("status").asText()).as(field).isEqualTo("needs_conditions");
            assertThat(result.path("missing").toString()).contains(field);
            assertThat(result.path("documents")).isEmpty();
        }
        for (String field : List.of("pressure_angle_deg", "profile_shift", "backlash_mm", "addendum_coefficient", "clearance_coefficient")) {
            ObjectNode input = complete.deepCopy();
            ((ObjectNode) input.path("facts")).put(field, 13);
            JsonNode result = knowledge.lookup(input, BUILD);
            assertThat(result.path("status").asText()).as(field).isEqualTo("uncovered");
            assertThat(result.path("conflicts").toString()).contains(field);
            assertThat(result.path("documents")).isEmpty();
            assertThat(input.path("facts").path(field).asInt()).isEqualTo(13);
        }
        for (double teeth : List.of(17.0, 41.0, 24.5)) {
            ObjectNode input = complete.deepCopy();
            ((ObjectNode) input.path("facts")).put("teeth", teeth);
            assertThat(knowledge.lookup(input, BUILD).path("documents")).isEmpty();
        }
    }

    @Test void respectsModeWithoutCouplingIndependentFrontendAndBackendBuilds() {
        for (String build : Arrays.asList(null, "", "000000000000000000000000", "independent-frontend-release"))
            assertThat(knowledge.lookup(request("直齿轮"), build).path("status").asText()).isEqualTo("matched");
        properties.setKnowledgeMode("enabled");
        assertThat(knowledge.lookup(request("直齿轮"), BUILD).path("status").asText()).isEqualTo("uncovered");
        properties.setKnowledgeMode("off");
        assertThat(knowledge.lookup(request("直齿轮"), BUILD).path("status").asText()).isEqualTo("disabled");
    }

    @Test void historicalBuildEvidenceIsOptionalAndDoesNotControlResourceInitialization() throws Exception {
        List<JsonNode> metadata = Arrays.asList(null, json.nullNode(), json.createArrayNode(),
                json.createArrayNode().add("old-release-label"), json.getNodeFactory().textNode("historical-note"),
                json.createObjectNode().put("diagnostic", "not-an-admission-list"));
        for (JsonNode value : metadata) {
            JsonNode policy = HistoricalCadAiKnowledge.policy(json).deepCopy();
            for (JsonNode item : policy.path("documents")) {
                ObjectNode document = (ObjectNode) item;
                if (value == null) document.remove("compatible_builds");
                else document.set("compatible_builds", value.deepCopy());
            }
            CadAiKnowledge independent = new CadAiKnowledge(json, properties, policy);
            JsonNode result = independent.lookup(request("创建外渐开线直齿轮"), null);
            assertThat(result.path("status").asText()).isEqualTo("matched");
            assertThat(result.path("documents")).isEqualTo(knowledge.lookup(request("创建外渐开线直齿轮"), BUILD).path("documents"));
        }
    }

    @Test void buildValidationRejectsTamperedBodyAndBrokenCatalog() throws Exception {
        assertThatThrownBy(() -> CadAiKnowledge.verifyHash("changed".getBytes(StandardCharsets.UTF_8), "0".repeat(64))).isInstanceOf(IOException.class);
        JsonNode catalog = json.readTree(getClass().getResourceAsStream("/cad/ai/knowledge/generation/catalog.json"));
        ((ObjectNode) catalog.path("types").get(0)).put("parent", "not-registered");
        assertThatThrownBy(() -> CadAiKnowledge.validateCatalog(catalog)).isInstanceOf(IOException.class);
        ((ObjectNode) catalog.path("types").get(0)).put("parent", "gear-transmission");
        assertThatThrownBy(() -> CadAiKnowledge.validateCatalog(catalog)).isInstanceOf(IOException.class);
    }

    @Test void rejectsHostileStringsAndNumericOverflowBeforeRecipeUse() throws Exception {
        CadAiTools tools = HistoricalCadAiKnowledge.tools(json);
        for (ObjectNode invalid : List.of(request(""), request("x".repeat(2001)), request("直齿轮").put("type_id", "x".repeat(81)))) {
            assertThatThrownBy(() -> tools.validateCall("knowledge_lookup", invalid))
                    .isInstanceOf(com.linkerbot.vibemake.common.BusinessException.class);
        }
        ObjectNode input = request("直齿轮");
        ((ObjectNode) input.path("facts")).put("module_mm", Double.MAX_VALUE);
        assertThat(knowledge.lookup(input, BUILD).path("documents")).isEmpty();
        ((ObjectNode) input.path("facts")).put("module_mm", -2);
        assertThat(knowledge.lookup(input, BUILD).path("conflicts").toString()).contains("module_mm");
        ((ObjectNode) input.path("facts")).put("root_transition", "x".repeat(81));
        assertThatThrownBy(() -> tools.validateCall("knowledge_lookup", input))
                .isInstanceOf(com.linkerbot.vibemake.common.BusinessException.class);
    }

    @Test void rejectsMalformedConflictingAndIncompleteEligibilityRules() throws Exception {
        JsonNode policy = HistoricalCadAiKnowledge.policy(json);
        ObjectNode valid = (ObjectNode) policy.path("documents").get(1).path("conditions");
        CadAiKnowledge.validateConditions("involute-spur-gear", valid);
        for (String field : List.of("teeth", "root_transition")) {
            ObjectNode invalid = valid.deepCopy(); invalid.remove(field);
            assertThatThrownBy(() -> CadAiKnowledge.validateConditions("involute-spur-gear", invalid)).isInstanceOf(IOException.class);
        }
        ObjectNode invalid = valid.deepCopy();
        ((ObjectNode) invalid.path("teeth")).put("min", 99);
        assertThatThrownBy(() -> CadAiKnowledge.validateConditions("involute-spur-gear", invalid)).isInstanceOf(IOException.class);
        ObjectNode badType = valid.deepCopy();
        ((ObjectNode) badType.path("profile_shift")).put("equals", "zero");
        assertThatThrownBy(() -> CadAiKnowledge.validateConditions("involute-spur-gear", badType)).isInstanceOf(IOException.class);
        ObjectNode infinite = valid.deepCopy();
        ((ObjectNode) infinite.path("module_mm")).put("min_exclusive", Double.POSITIVE_INFINITY);
        assertThatThrownBy(() -> CadAiKnowledge.validateConditions("involute-spur-gear", infinite)).isInstanceOf(IOException.class);
    }

    @Test void factsAllowMissingFieldsAndNullButNeverInventRequiredRecipeConditions() throws Exception {
        CadAiTools tools = HistoricalCadAiKnowledge.tools(json);
        ObjectNode request = request("外啮合渐开线直齿圆柱齿轮，基圆内齿根段允许径向直线连接到齿根圆，标注简化齿根");
        ObjectNode facts = (ObjectNode) request.path("facts");
        facts.remove("root_transition");
        tools.validateCall("knowledge_lookup", request);
        assertThat(knowledge.lookup(request, BUILD).path("missing").toString()).contains("root_transition");
        facts.putNull("root_transition");
        tools.validateCall("knowledge_lookup", request);
        JsonNode result = knowledge.lookup(request, BUILD);
        assertThat(result.path("status").asText()).isEqualTo("needs_conditions");
        assertThat(result.path("documents")).isEmpty();
        assertThat(result.path("missing").toString()).contains("root_transition");
        assertThat(result.path("reason").asText()).contains("正文未返回", "不能据本结果声称已读取或适用");
        facts.putNull("module_mm");
        tools.validateCall("knowledge_lookup", request);
        assertThat(knowledge.lookup(request, BUILD).path("missing").toString()).contains("module_mm");
        facts.put("module_mm", 2).put("root_transition", "radial-simplified");
        tools.validateCall("knowledge_lookup", request);
        assertThat(knowledge.lookup(request, BUILD).path("status").asText()).isEqualTo("matched");
        request.remove("facts");
        tools.validateCall("knowledge_lookup", request);
        assertThat(knowledge.lookup(request, BUILD).path("documents")).isEmpty();
    }

    @Test void repeatedGeneralNounForSameSpecifiedPartDoesNotRequireAnotherLookup() {
        String actualQuery = "制作外啮合渐开线直齿圆柱齿轮：模数2.5，齿数24，压力角20°，零变位、零侧隙，齿顶高系数1，顶隙系数0.25，齿宽12，中心孔直径16，轴线Z，齿形工作段必须为渐开线，允许误差不超过0.03并明确标注；基圆内齿根段允许径向直线连接到齿根圆；需要等厚圆盘状齿轮，不要轮毂、键槽、减重孔。";
        ObjectNode input = request(actualQuery).put("type_id", "involute-spur-gear");
        ((ObjectNode) input.path("facts")).put("module_mm", 2.5);
        assertThat(knowledge.lookup(input, BUILD).path("status").asText()).isEqualTo("matched");
        input.remove("type_id");
        assertThat(knowledge.lookup(input, BUILD).path("status").asText()).isEqualTo("matched");
        for (String query : List.of("做直齿轮，另一个未明确的gear", "做spur gear and another gear", "做直齿轮和一个未明确的齿轮", "做直齿轮和斜齿轮", "做直齿轮和齿轮")) {
            assertThat(knowledge.lookup(request(query).put("type_id", "involute-spur-gear"), BUILD).path("status").asText())
                    .as(query).isEqualTo("ambiguous");
        }
    }

    @Test void approvedPublicationRequiresBenefitVerdictAndAllEvidenceReferences() throws Exception {
        ObjectNode recipe = json.createObjectNode().put("status", "experimental");
        CadAiKnowledge.validatePublication(recipe);
        recipe.put("status", "approved");
        assertThatThrownBy(() -> CadAiKnowledge.validatePublication(recipe)).isInstanceOf(IOException.class);
        ObjectNode evidence = recipe.putObject("evidence").put("verdict", "benefit_observed")
                .put("engine_replay", "reports/replay").put("ab_comparison", "reports/ab");
        evidence.putArray("parameter_transfer").add("reports/transfer20").add("reports/transfer32");
        CadAiKnowledge.validatePublication(recipe);
        for (String field : List.of("verdict", "engine_replay", "ab_comparison", "parameter_transfer")) {
            ObjectNode invalid = recipe.deepCopy(); ((ObjectNode) invalid.path("evidence")).remove(field);
            assertThatThrownBy(() -> CadAiKnowledge.validatePublication(invalid)).isInstanceOf(IOException.class);
        }
        evidence.put("verdict", "partial_benefit_completion_unstable");
        assertThatThrownBy(() -> CadAiKnowledge.validatePublication(recipe)).isInstanceOf(IOException.class);
    }

    @Test void typeIdEnumComesFromCanonicalCatalogAndRejectsInventedIds() throws Exception {
        CadAiTools tools = HistoricalCadAiKnowledge.tools(json);
        JsonNode definition = tools.definitions(true).stream().filter(tool -> "knowledge_lookup".equals(tool.name())).findFirst().orElseThrow().parameters();
        List<String> enumerated = new ArrayList<>();
        for (JsonNode id : definition.path("properties").path("type_id").path("enum")) enumerated.add(id.asText());
        JsonNode catalog = json.readTree(getClass().getResourceAsStream("/cad/ai/knowledge/generation/catalog.json"));
        assertThat(enumerated).containsExactlyElementsOf(CadAiKnowledge.validateCatalog(catalog).keySet().stream().sorted().toList());
        ObjectNode invented = request("外啮合渐开线直齿圆柱齿轮").put("type_id", "spur_external_involute_gear");
        assertThatThrownBy(() -> tools.validateCall("knowledge_lookup", invented)).isInstanceOf(com.linkerbot.vibemake.common.BusinessException.class);
        JsonNode recovery = knowledge.lookup(invented, BUILD);
        assertThat(recovery.path("status").asText()).isEqualTo("ambiguous");
        assertThat(recovery.path("candidates").toString()).contains("involute-spur-gear");
        assertThat(recovery.path("documents")).isEmpty();
        invented.remove("type_id");
        tools.validateCall("knowledge_lookup", invented);
        assertThat(knowledge.lookup(invented, BUILD).path("status").asText()).isEqualTo("matched");
    }

    @Test void gearFactsComeFromTheCatalogAndOnlyRecipeConditionsAreRequired() throws Exception {
        CadAiTools tools = HistoricalCadAiKnowledge.tools(json);
        ObjectNode helical = json.createObjectNode().put("query", "外啮合右旋斜齿圆柱齿轮").put("type_id", "helical-cylindrical-gear");
        helical.putObject("facts").put("normal_module_mm", 2).put("teeth", 24)
                .put("normal_pressure_angle_deg", 20).put("helix_angle_deg", 20).put("helix_hand", "right");
        tools.validateCall("knowledge_lookup", helical);
        assertThat(knowledge.lookup(helical, EXPANSION_BUILD).path("status").asText()).isEqualTo("needs_conditions");

        ObjectNode spur = request("外渐开线直齿圆柱齿轮");
        ((ObjectNode) spur.path("facts")).remove("root_transition");
        tools.validateCall("knowledge_lookup", spur);
        assertThat(knowledge.lookup(spur, BUILD).path("missing").toString()).contains("root_transition");
        ObjectNode unknown = helical.deepCopy();
        ((ObjectNode) unknown.path("facts")).put("private_unknown_field", 1);
        assertThatThrownBy(() -> tools.validateCall("knowledge_lookup", unknown))
                .isInstanceOf(com.linkerbot.vibemake.common.BusinessException.class);
        ((ObjectNode) helical.path("facts")).put("helix_hand", 42);
        assertThatThrownBy(() -> tools.validateCall("knowledge_lookup", helical))
                .isInstanceOf(com.linkerbot.vibemake.common.BusinessException.class);
    }

    @Test void validatesGearSpecificNumericAndTextConditionsFromCatalogDefinitions() throws Exception {
        ObjectNode conditions = json.createObjectNode();
        conditions.putObject("normal_module_mm").put("min_exclusive", 0);
        conditions.putObject("helix_angle_deg").put("min_exclusive", 0).put("max", 40);
        conditions.putObject("helix_hand").put("equals", "right");
        CadAiKnowledge.validateConditions("helical-cylindrical-gear", conditions);
        ((ObjectNode) conditions.path("helix_hand")).put("equals", 42);
        assertThatThrownBy(() -> CadAiKnowledge.validateConditions("helical-cylindrical-gear", conditions)).isInstanceOf(IOException.class);
    }

    @Test void absoluteAngleConditionsAllowSignedHelicesAndRejectConflictingBounds() throws Exception {
        ObjectNode conditions = json.createObjectNode();
        conditions.putObject("helix_angle_deg").put("abs_min", 5).put("abs_max", 25);
        CadAiKnowledge.validateConditions("helical-cylindrical-gear", conditions);
        ObjectNode facts = json.createObjectNode();
        for (double angle : List.of(-25.0, -20.0, -5.0, 5.0, 20.0, 25.0)) {
            facts.put("helix_angle_deg", angle);
            assertThat(conditionConflicts("helical-cylindrical-gear", conditions, facts)).as("angle=%s", angle).isEmpty();
        }
        for (double angle : List.of(-25.01, -4.99, 0.0, 4.99, 25.01, Double.POSITIVE_INFINITY, Double.NaN)) {
            facts.put("helix_angle_deg", angle);
            assertThat(conditionConflicts("helical-cylindrical-gear", conditions, facts)).as("angle=%s", angle)
                    .containsExactly("helix_angle_deg");
        }
        for (String invalidRule : List.of(
                "{\"abs_min\":-1}", "{\"abs_max\":-1}", "{\"abs_min\":26,\"abs_max\":25}",
                "{\"abs_min\":5,\"abs_max\":25,\"equals\":0}",
                "{\"abs_min\":5,\"abs_max\":25,\"min\":26}",
                "{\"abs_min\":5,\"abs_max\":25,\"max\":-26}")) {
            conditions.set("helix_angle_deg", json.readTree(invalidRule));
            assertThatThrownBy(() -> CadAiKnowledge.validateConditions("helical-cylindrical-gear", conditions))
                    .as(invalidRule).isInstanceOf(IOException.class);
        }
    }

    @Test void internalGearChecksRimAndInvoluteDomainWithoutApplyingExternalRootRule() throws Exception {
        ObjectNode conditions = (ObjectNode) json.readTree("""
                {"module_mm":{"min_exclusive":0},"teeth":{"min":1},
                 "pressure_angle_deg":{"equals":20},"outer_radius_mm":{"min_exclusive":0}}
                """);
        ObjectNode facts = json.createObjectNode().put("module_mm", 2).put("teeth", 40)
                .put("pressure_angle_deg", 20).put("outer_radius_mm", 50);
        assertThat(conditionConflicts("internal-spur-gear", conditions, facts)).isEmpty();
        facts.put("outer_radius_mm", 42.5);
        assertThat(conditionConflicts("internal-spur-gear", conditions, facts))
                .containsExactly("internal_radii_must_satisfy_outer_gt_root_gt_tip_gt_base_gt_zero");
        facts.put("outer_radius_mm", 50).put("teeth", 33);
        assertThat(conditionConflicts("internal-spur-gear", conditions, facts))
                .containsExactly("internal_radii_must_satisfy_outer_gt_root_gt_tip_gt_base_gt_zero");
        facts.put("teeth", 34);
        assertThat(conditionConflicts("internal-spur-gear", conditions, facts)).isEmpty();
        facts.put("module_mm", Double.MAX_VALUE);
        assertThat(conditionConflicts("internal-spur-gear", conditions, facts))
                .containsExactly("internal_radii_must_satisfy_outer_gt_root_gt_tip_gt_base_gt_zero");
    }

    @Test void helicalGearChecksNormalToTransverseRadiiForBothHands() throws Exception {
        ObjectNode conditions = (ObjectNode) json.readTree("""
                {"normal_module_mm":{"min_exclusive":0},"teeth":{"min":1},
                 "normal_pressure_angle_deg":{"equals":20},"helix_angle_deg":{"abs_min":5,"abs_max":25}}
                """);
        ObjectNode facts = json.createObjectNode().put("normal_module_mm", 2).put("teeth", 24)
                .put("normal_pressure_angle_deg", 20).put("helix_angle_deg", 20);
        assertThat(conditionConflicts("helical-cylindrical-gear", conditions, facts)).isEmpty();
        facts.put("helix_angle_deg", -20);
        assertThat(conditionConflicts("helical-cylindrical-gear", conditions, facts)).isEmpty();
        facts.put("teeth", 100);
        assertThat(conditionConflicts("helical-cylindrical-gear", conditions, facts))
                .containsExactly("helical_radii_must_satisfy_zero_lt_root_lt_base_lt_tip");
        facts.put("teeth", 24).put("normal_module_mm", Double.MAX_VALUE);
        assertThat(conditionConflicts("helical-cylindrical-gear", conditions, facts))
                .containsExactly("helical_radii_must_satisfy_zero_lt_root_lt_base_lt_tip");
    }

    @Test void derivedGearChecksRequireDeclaredConditionsAndDoNotReplaceMissingFacts() throws Exception {
        ObjectNode conditions = (ObjectNode) json.readTree("""
                {"module_mm":{"min_exclusive":0},"teeth":{"min":1},
                 "pressure_angle_deg":{"equals":20},"outer_radius_mm":{"min_exclusive":0}}
                """);
        ObjectNode facts = json.createObjectNode().put("module_mm", 2).put("teeth", 40)
                .put("pressure_angle_deg", 20).put("outer_radius_mm", 1);
        assertThat(conditionConflicts("straight-rack", conditions, facts)).isEmpty();
        ObjectNode withoutRim = conditions.deepCopy();
        withoutRim.remove("outer_radius_mm");
        assertThat(conditionConflicts("internal-spur-gear", withoutRim, facts)).isEmpty();
        facts.remove("outer_radius_mm");
        List<String> missing = new ArrayList<>();
        List<String> conflicts = new ArrayList<>();
        CadAiKnowledge.checkConditions("internal-spur-gear", conditions, facts, missing, conflicts);
        assertThat(missing).containsExactly("outer_radius_mm");
        assertThat(conflicts).isEmpty();
        assertThat(facts.has("outer_radius_mm")).isFalse();
    }

    @Test void complexRecipeDomainsRejectInvalidScaleCoreAndThroatBeforeReturningText() throws Exception {
        JsonNode suite = json.readTree(getClass().getResourceAsStream("/cad/ai/knowledge/evals/gear-routing-v2.json"));
        Map<String, ObjectNode> fixtures = new HashMap<>();
        for (JsonNode item : suite.path("cases")) if (item.path("group").asText().equals("eligible"))
            fixtures.put(item.path("type_id").asText(), (ObjectNode) item.path("facts").deepCopy());

        for (String type : List.of("straight-bevel-gear", "spiral-bevel-gear")) {
            ObjectNode facts = fixtures.get(type).deepCopy().put("axial_height_mm", 25);
            assertRejectedDomain(type, facts, "bevel_end_scale_must_be_between_045_and_09");
            assertRejectedDomain(type, fixtures.get(type).deepCopy().put("module_mm", Double.MAX_VALUE),
                    "bevel_end_scale_must_be_between_045_and_09");
        }
        assertRejectedDomain("worm", fixtures.get("worm").deepCopy().put("pitch_diameter_mm", 4),
                "worm_core_length_and_turns_outside_recipe_domain");
        assertRejectedDomain("worm", fixtures.get("worm").deepCopy().put("axial_length_mm", 1),
                "worm_core_length_and_turns_outside_recipe_domain");
        assertRejectedDomain("worm", fixtures.get("worm").deepCopy().put("axial_length_mm", 2000),
                "worm_core_length_and_turns_outside_recipe_domain");
        assertRejectedDomain("worm", fixtures.get("worm").deepCopy().put("axial_module_mm", Double.MAX_VALUE),
                "worm_core_length_and_turns_outside_recipe_domain");
        assertRejectedDomain("worm-wheel", fixtures.get("worm-wheel").deepCopy().put("face_width_mm", 20),
                "worm_wheel_throat_outside_recipe_domain");
        assertRejectedDomain("worm-wheel", fixtures.get("worm-wheel").deepCopy().put("face_width_mm", 10),
                "worm_wheel_throat_outside_recipe_domain");
        assertRejectedDomain("worm-wheel", fixtures.get("worm-wheel").deepCopy().put("module_mm", Double.MAX_VALUE),
                "worm_wheel_throat_outside_recipe_domain");
    }

    @Test void complexDerivedDomainsNeedDeclaredDependenciesAndDoNotOverrideMissingConditions() throws Exception {
        ObjectNode bevel = (ObjectNode) json.readTree("""
                {"module_mm":{"min_exclusive":0},"teeth":{"min":18},"cone_angle_deg":{"equals":45},
                 "axial_height_mm":{"min_exclusive":0},"geometry_representation":{"equals":"homothetic-frontal-involute-bevel-v1"}}
                """);
        ObjectNode worm = (ObjectNode) json.readTree("""
                {"axial_module_mm":{"min_exclusive":0},"pitch_diameter_mm":{"min_exclusive":0},
                 "worm_starts":{"min":1},"axial_length_mm":{"min_exclusive":0}}
                """);
        ObjectNode wheel = (ObjectNode) json.readTree("""
                {"module_mm":{"min_exclusive":0},"teeth":{"min":18},"pressure_angle_deg":{"equals":20},
                 "pitch_diameter_mm":{"min_exclusive":0},"face_width_mm":{"min_exclusive":0},
                 "geometry_representation":{"equals":"illustrative-helical-involute-with-toroidal-throat-v1"}}
                """);
        Map<String, ObjectNode> conditions = Map.of("straight-bevel-gear", bevel, "worm", worm, "worm-wheel", wheel);
        Map<String, ObjectNode> facts = Map.of(
                "straight-bevel-gear", json.createObjectNode().put("module_mm",2).put("teeth",24).put("cone_angle_deg",45)
                        .put("axial_height_mm",25).put("geometry_representation","homothetic-frontal-involute-bevel-v1"),
                "worm", json.createObjectNode().put("axial_module_mm",2).put("pitch_diameter_mm",4).put("worm_starts",1).put("axial_length_mm",30),
                "worm-wheel", json.createObjectNode().put("module_mm",2).put("teeth",32).put("pressure_angle_deg",20)
                        .put("pitch_diameter_mm",20).put("face_width_mm",20).put("geometry_representation","illustrative-helical-involute-with-toroidal-throat-v1"));
        Map<String, String> dependency = Map.of("straight-bevel-gear","axial_height_mm", "worm","axial_length_mm", "worm-wheel","face_width_mm");
        for (String type : conditions.keySet()) {
            ObjectNode incompletePolicy = conditions.get(type).deepCopy();
            incompletePolicy.remove(dependency.get(type));
            assertThat(conditionConflicts(type, incompletePolicy, facts.get(type))).as(type).isEmpty();
            ObjectNode missingFacts = facts.get(type).deepCopy();
            missingFacts.remove(dependency.get(type));
            List<String> missing = new ArrayList<>();
            List<String> conflicts = new ArrayList<>();
            CadAiKnowledge.checkConditions(type, conditions.get(type), missingFacts, missing, conflicts);
            assertThat(missing).as(type).containsExactly(dependency.get(type));
            assertThat(conflicts).as(type).isEmpty();
            assertThat(conditionConflicts("straight-rack", conditions.get(type), facts.get(type))).as(type).isEmpty();
        }
    }

    private void assertRejectedDomain(String type, ObjectNode facts, String conflict) {
        String query = Map.of("straight-bevel-gear", "直齿锥齿轮", "spiral-bevel-gear", "螺旋锥齿轮", "worm", "蜗杆", "worm-wheel", "蜗轮").get(type);
        ObjectNode input = json.createObjectNode().put("query", query).put("type_id", type);
        input.set("facts", facts);
        JsonNode result = knowledge.lookup(input, EXPANSION_BUILD);
        assertThat(result.path("status").asText()).as(type).isEqualTo("uncovered");
        assertThat(result.path("documents")).isEmpty();
        assertThat(result.path("conflicts").toString()).contains(conflict);
    }

    private List<String> conditionConflicts(String type, JsonNode conditions, JsonNode facts) {
        List<String> missing = new ArrayList<>();
        List<String> conflicts = new ArrayList<>();
        CadAiKnowledge.checkConditions(type, conditions, facts, missing, conflicts);
        assertThat(missing).isEmpty();
        return conflicts;
    }

    @Test void rejectsMalformedCanonicalPropertyDefinitions() throws Exception {
        ObjectNode catalog = (ObjectNode) json.readTree(getClass().getResourceAsStream("/cad/ai/knowledge/generation/catalog.json"));
        CadAiKnowledge.validateFactDefinitions(catalog);
        ObjectNode definitions = (ObjectNode) catalog.path("fact_definitions");
        ((ObjectNode) definitions.path("normal_module_mm")).put("type", "array");
        assertThatThrownBy(() -> CadAiKnowledge.validateFactDefinitions(catalog)).isInstanceOf(IOException.class);
        ((ObjectNode) definitions.path("normal_module_mm")).put("type", "number").put("unit", "unknown");
        assertThatThrownBy(() -> CadAiKnowledge.validateFactDefinitions(catalog)).isInstanceOf(IOException.class);
    }

    @Test void schemaAllowsNoPathsAndNeverBatchesLookup() throws Exception {
        CadAiTools tools = HistoricalCadAiKnowledge.tools(json);
        tools.validateCall("knowledge_lookup", request("直齿轮"));
        assertThatThrownBy(() -> tools.validateCall("knowledge_lookup", request("直齿轮").put("file", "/private")))
                .isInstanceOf(com.linkerbot.vibemake.common.BusinessException.class);
        ObjectNode batch = json.createObjectNode();
        batch.putArray("commands").addObject().put("command", "knowledge_lookup").set("params", request("直齿轮"));
        assertThatThrownBy(() -> tools.validateCall("batch", batch)).isInstanceOf(com.linkerbot.vibemake.common.BusinessException.class);
        assertThat(tools.definitions(false)).noneMatch(tool -> "knowledge_lookup".equals(tool.name()));
    }
}
