Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : src/lib/cost/ai/ai.test.ts9 * Module : lib10 * Repository : https://git.spboucher.ai/vrai-prix11 * Created : 2026-09-0812 * Last Modified : 2026-09-0813 *14 * Author : Simon-Pierre Boucher15 * Position : Professor of Finance16 * Institution : Université du Québec en Outaouais (UQO)17 * Organization : SP Boucher18 * Website : https://spboucher.ai19 * Git : https://git.spboucher.ai20 *21 * Preferred Contact: contact@spboucher.ai22 * Development : dev@spboucher.ai23 * Support : support@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Auteur : Simon-Pierre Boucher — contact@spboucher.ai43// Tests hors réseau de l'analyse multimodale : schéma/réparation, empreinte, fusion, mapping, vecteur, images.44import { describe, expect, it } from "vitest";45import { buildModelSchema, isValid, MAX_MISSING_SECTIONS, missingTopLevelSections, schemaForApi, validateAndRepair, type ModelOutput } from "./schema";46import { sampleOutput } from "./fixture";47import { inputHash } from "./context";48import { applyOverrides, listingFactsFromDetails, mergeFacts, type ListingFacts, type MamhFacts } from "./merge";49import { mapToCostInput } from "./mapping";50import { EMBEDDING_DIMENSION, canonicalText, cosine, technicalVector } from "./vector";51import { readDimensions, selectImages, sizeAgnosticKey, sniffMediaType } from "./images";52import { deriveQuantities } from "../geometry";53import { ASSEMBLY_SEEDS } from "../seed/assemblies";5455const CODES = ASSEMBLY_SEEDS.map((a) => a.code);56const SCHEMA = buildModelSchema(CODES);5758const listingFacts = (over: Partial<ListingFacts> = {}): ListingFacts => ({59 yearBuilt: 1998, areaSqft: 2470, bedrooms: 4, bathrooms: 2, powderRooms: 1, propertyType: "Maison", lotSqft: 7200, buildingType: "detached", stories: null, foundation: null, siding: null, roof: null, roofGeometry: null, windows: null,60 heating: null, hasAirConditioning: null, hasAirExchanger: null, basement: null, garage: null, pool: null, units: null, waterSupply: null, wasteSystem: null, ...over,61});62const mamh: MamhFacts = { yearBuilt: 1997, grossFloorAreaSqft: 2300, stories: 2, buildingType: "detached", units: 1, landValue: 182000, buildingValue: 400000, totalValue: 582000, unitId: "123" };6364describe("schema", () => {65 it("la fixture est strictement valide et le schéma API ne contient plus de bornes", () => {66 expect(isValid(sampleOutput(), SCHEMA)).toBe(true);67 expect(JSON.stringify(schemaForApi(SCHEMA))).not.toMatch(/"minimum"|"maximum"/);68 expect(JSON.stringify(SCHEMA)).toContain('"KIT-SUPERIOR"');69 });70 it("répare de façon déterministe : chaîne numérique, énumération inconnue, champ manquant, clé inconnue, confiance bornée", () => {71 const bad = JSON.parse(JSON.stringify(sampleOutput())) as Record<string, unknown>;72 const prop = bad.property as Record<string, Record<string, unknown>>;73 prop.stories.value = "2";74 prop.building_type.value = "castle";75 delete prop.bedrooms;76 (bad.quality as Record<string, unknown>).confidence = 1.7;77 bad.extra_key = 1;78 const { value, issues } = validateAndRepair(bad, SCHEMA);79 const v = value as ModelOutput;80 expect(v.property.stories.value).toBe(2);81 expect(v.property.building_type.value).toBeNull();82 expect(v.property.bedrooms.value).toBeNull();83 expect(v.quality.confidence).toBe(1);84 expect("extra_key" in (value as object)).toBe(false);85 expect(issues.length).toBeGreaterThanOrEqual(5);86 expect(issues.every((i) => i.repaired)).toBe(true);87 expect(isValid(value, SCHEMA)).toBe(true);88 // idempotence89 expect(JSON.stringify(validateAndRepair(value, SCHEMA).value)).toBe(JSON.stringify(value));90 });9192 it("un appel d'outil placeholder est détecté comme sortie vide (sections de premier niveau absentes)", () => {93 // observé avec Sonnet 5 en tool_choice forcé (2026-09-08) : le réparateur remplirait tout de nulls94 const placeholder = { property_analysis: { placeholder: true } };95 const { issues } = validateAndRepair(placeholder, SCHEMA);96 const missing = missingTopLevelSections(issues);97 expect(missing.length).toBeGreaterThan(MAX_MISSING_SECTIONS);98 expect(missing).toContain("property");99 expect(missing).toContain("exterior");100 // une vraie sortie complète : aucune section manquante101 expect(missingTopLevelSections(validateAndRepair(sampleOutput(), SCHEMA).issues)).toEqual([]);102 // une sortie à laquelle il ne manque qu'une section reste acceptable (réparée)103 const partial = { ...(sampleOutput() as unknown as Record<string, unknown>) };104 delete partial.renovations;105 expect(missingTopLevelSections(validateAndRepair(partial, SCHEMA).issues)).toEqual(["renovations"]);106 });107});108109describe("input hash", () => {110 it("est stable pour la même entrée et change avec les photos", () => {111 const a = inputHash("base", ["h1", "h2"]);112 expect(a).toBe(inputHash("base", ["h2", "h1"]));113 expect(a).not.toBe(inputHash("base", ["h1", "h3"]));114 expect(a).not.toBe(inputHash("base2", ["h1", "h2"]));115 expect(a).toMatch(/^[0-9a-f]{64}$/);116 });117});118119describe("merge", () => {120 it("hiérarchie : MAMH > annonce > IA, avec conflits tracés", () => {121 const ai = sampleOutput();122 const m = mergeFacts(ai, listingFacts({ roof: "metal" }), mamh);123 expect(m.grossFloorAreaSqft.value).toBe(2300);124 expect(m.grossFloorAreaSqft.source).toBe("MAMH");125 expect(m.yearBuilt.value).toBe(1997);126 expect(m.roof.value).toBe("metal"); // annonce > photo127 expect(m.roof.source).toBe("listing");128 expect(m.conflicts.some((c) => c.field === "roof" && c.valueB.includes("asphalt"))).toBe(true);129 expect(m.siding.value.brick).toBeCloseTo(0.6, 5);130 expect(m.siding.value.vinyl).toBeCloseTo(0.4, 5);131 expect(m.heating.value).toBe("heat_pump");132 expect(m.conditions.roof).toBe("average");133 expect(m.effectiveAge?.effective).toBe(17);134 });135 it("sans MAMH ni champ d'annonce, l'IA fournit la valeur (source AI)", () => {136 const m = mergeFacts(sampleOutput(), listingFacts({ yearBuilt: null, areaSqft: null, buildingType: null }), null);137 expect(m.grossFloorAreaSqft.value).toBe(2470);138 expect(m.grossFloorAreaSqft.source).toBe("listing"); // l'IA cite la source « listing »139 expect(m.foundation.source).toBe("AI");140 expect(m.basement.value).toBe("finished");141 });142 it("les overrides remplacent la valeur, gardent l'originale et passent en source user", () => {143 const m = mergeFacts(sampleOutput(), listingFacts(), null);144 const o = applyOverrides(m, [{ fieldPath: "roof", value: "metal" }, { fieldPath: "conditions.roof", value: "new" }]);145 expect(o.roof.value).toBe("metal");146 expect(o.roof.source).toBe("user");147 expect(o.roof.alternatives[0].value).toBe("asphalt_shingle");148 expect(o.conditions.roof).toBe("new");149 expect(m.roof.value).toBe("asphalt_shingle"); // l'original n'est pas muté150 });151 it("normalise les détails français d'une annonce", () => {152 const f = listingFactsFromDetails({ year_built: null, area_sqft: null, bedrooms: 3, bathrooms: 1, powder_rooms: 1, property_type: "Maison", lot_sqft: null }, { "Type de bâtiment": "Détaché (isolé)", "Revêtement": "Brique, Vinyle", "Toiture": "Bardeaux d'asphalte", "Chauffage": "Plinthes électriques", "Fondation": "Béton coulé", "Sous-sol": "6 pieds et plus, Totalement aménagé", "Stationnement (total)": "Allée (2), Garage (1)", "Piscine": "Creusée", "Année de construction": "1998" });153 expect(f.buildingType).toBe("detached");154 expect(f.roof).toBe("asphalt_shingle");155 expect(f.foundation).toBe("poured_concrete");156 expect(f.heating).toBe("electric_baseboard");157 expect(f.basement).toBe("finished");158 expect(f.garage).toEqual({ type: "attached", spaces: 1 });159 expect(f.pool).toBe("inground");160 expect(f.yearBuilt).toBe(1998);161 expect(f.siding?.brick).toBeCloseTo(0.6, 5);162 });163});164165describe("mapping", () => {166 const ctx = { listingUid: "t:1", address: "1 rue Test", municipality: "Gatineau", lat: 45.47, lng: -75.7, unitId: "123", landValue: 182000, roll: { landValue: 182000, buildingValue: 400000, totalValue: 582000, year: 2026 }, assemblyCodes: new Set(CODES) };167 it("façade hybride 60/40 → deux assemblages de revêtement pondérés ; quantités IA fiables retenues, faibles ignorées", () => {168 const ai = sampleOutput();169 const m = mergeFacts(ai, listingFacts(), mamh);170 const r = mapToCostInput(m, ai, ctx);171 expect(r.input.mode).toBe("listing");172 expect(r.input.building.siding).toEqual({ brick: 0.6, vinyl: 0.4 });173 const { lines } = deriveQuantities(r.input.building, r.input.quantityOverrides, "AI");174 const brick = lines.find((l) => l.assemblyCode === "ENV-SIDING-BRICK")!;175 const vinyl = lines.find((l) => l.assemblyCode === "ENV-SIDING-VINYL")!;176 expect(brick.quantity / (brick.quantity + vinyl.quantity)).toBeCloseTo(0.6, 2);177 expect(r.aiQuantities["KIT-SUPERIOR"].quantity).toBe(34);178 expect(lines.find((l) => l.assemblyCode === "KIT-SUPERIOR")!.source).toBe("AI");179 expect("OPN-DOOR-INT-SOLID" in r.aiQuantities).toBe(false); // confiance 0,55 < 0,6180 expect("ROOF-ASPHALT-ARCH" in r.aiQuantities).toBe(false); // géométrie dérivée par le code181 expect(r.input.depreciation.method).toBe("components");182 expect(r.input.depreciation.componentConditions.roof).toBe("average");183 expect(r.input.depreciation.effectiveAge).toBe(17);184 expect(r.input.land.value).toBe(182000);185 expect(r.input.attributeSources.grossFloorAreaSqft).toBe("MAMH");186 expect(r.input.attributeSources.foundation).toBe("AI");187 });188});189190describe("vector", () => {191 it("déterministe, de dimension fixe, similarité 1 avec lui-même et < 1 avec un bâtiment différent", () => {192 const ai = sampleOutput();193 const m = mergeFacts(ai, listingFacts(), mamh);194 const v1 = technicalVector(m);195 const v2 = technicalVector(mergeFacts(sampleOutput(), listingFacts(), mamh));196 expect(v1.length).toBe(EMBEDDING_DIMENSION);197 expect(v1).toEqual(v2);198 expect(cosine(v1, v2)).toBeCloseTo(1, 6);199 const ai2 = sampleOutput();200 ai2.quality.overall_quality = "economy";201 ai2.exterior.siding_shares = { brick_pct: 0, vinyl_pct: 100, fiber_cement_pct: 0, wood_pct: 0, stone_pct: 0, stucco_pct: 0, metal_pct: 0, other_pct: 0 };202 const v3 = technicalVector(mergeFacts(ai2, listingFacts({ buildingType: "row" }), null));203 expect(cosine(v1, v3)).toBeLessThan(0.95);204 expect(canonicalText(m)).toContain("Detached.");205 expect(canonicalText(m)).toContain("brick 60%");206 });207});208209describe("images", () => {210 it("détecte le type et lit les dimensions PNG/JPEG", () => {211 const png = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.from("0000000d49484452", "hex"), Buffer.alloc(8)]);212 png.writeUInt32BE(1024, 16); png.writeUInt32BE(768, 20);213 expect(sniffMediaType(png)).toBe("image/png");214 expect(readDimensions(png, "image/png")).toEqual({ width: 1024, height: 768 });215 const jpg = Buffer.alloc(30, 0);216 jpg[0] = 0xff; jpg[1] = 0xd8; jpg[2] = 0xff; jpg[3] = 0xc0; jpg.writeUInt16BE(17, 4); jpg[6] = 8; jpg.writeUInt16BE(600, 7); jpg.writeUInt16BE(800, 9);217 expect(sniffMediaType(jpg)).toBe("image/jpeg");218 expect(readDimensions(jpg, "image/jpeg")).toEqual({ width: 800, height: 600 });219 expect(sniffMediaType(Buffer.from("hello"))).toBeNull();220 });221 it("regroupe les tailles d'une même photo et présélectionne en gardant les extérieurs", () => {222 expect(sizeAgnosticKey("https://x/pic/abc-lg.jpg?x=1")).toBe(sizeAgnosticKey("https://x/pic/abc-sm.jpg"));223 const imgs = Array.from({ length: 50 }, (_, i) => ({ position: i + 1, roomHint: i < 2 ? "exterior" : "unknown", qualityScore: 1, hash: `h${i}` }));224 const sel = selectImages(imgs, 40);225 expect(sel.length).toBe(40);226 expect(sel.filter((i) => i.roomHint === "exterior").length).toBe(2);227 expect(new Set(sel.map((i) => i.hash)).size).toBe(40);228 });229});230