Repository Public
1// Tests unitaires du moteur de règles : évaluation des conditions (pure), échéances de mise en veille, validation du schéma,2// et garde statique — le module ne contient aucun chemin vers une soumission de courrier.3import assert from "node:assert/strict"4import fs from "node:fs"5import { test } from "node:test"6import { appliesTo, matchCondition, matchRule, resolveUntil, RULE_CLOCK_SKEW_MS, zAction, zCondition, type Condition, type RuleFacts } from "./rules"78const facts = (o: Partial<RuleFacts> = {}): RuleFacts => ({9 from: [{ email: "jean.tremblay@banque.example.ca", text: "jean tremblay <jean.tremblay@banque.example.ca>" }], to: [{ email: "moi@stg.spboucher.ai", text: " <moi@stg.spboucher.ai>" }],10 subject: "Votre Facture de novembre", list: "", has_attachment: true, is_newsletter: false, size: 20_000, ...o,11})12const c = (field: Condition["field"], op: Condition["op"], value: Condition["value"]) => ({ field, op, value })1314test("conditions : expéditeur, destinataire, sujet, liste, pièce jointe, infolettre, taille, catégorie", () => {15 const f = facts()16 assert.ok(matchCondition(c("from", "contains", "Tremblay"), f), "contient, sans casse, sur le nom")17 assert.ok(matchCondition(c("from", "contains", "banque.example"), f))18 assert.ok(!matchCondition(c("from", "contains", "desjardins"), f))19 assert.ok(matchCondition(c("from", "equals", "Jean.Tremblay@banque.example.ca"), f))20 assert.ok(!matchCondition(c("from", "equals", "tremblay@banque.example.ca"), f))21 assert.ok(matchCondition(c("from", "matches_domain", "example.ca"), f), "sous-domaine")22 assert.ok(matchCondition(c("from", "matches_domain", "@banque.example.ca"), f))23 assert.ok(!matchCondition(c("from", "matches_domain", "xample.ca"), f), "pas de correspondance partielle de domaine")24 assert.ok(matchCondition(c("to", "equals", "moi@stg.spboucher.ai"), f))25 assert.ok(matchCondition(c("subject", "contains", "facture"), f))26 assert.ok(matchCondition(c("subject", "equals", "votre facture de novembre"), f))27 assert.ok(!matchCondition(c("subject", "equals", "facture"), f))28 assert.ok(matchCondition(c("has_attachment", "is", true), f) && !matchCondition(c("has_attachment", "is", false), f))29 assert.ok(matchCondition(c("is_newsletter", "is", false), f))30 assert.ok(matchCondition(c("size", "gt", 10_000), f) && !matchCondition(c("size", "gt", 20_000), f))31 assert.ok(matchCondition(c("list", "contains", "infolettre"), facts({ list: "Infolettre <infolettre.example.ca>" })))32 assert.ok(matchCondition(c("list", "equals", "infolettre.example.ca"), facts({ list: "Infolettre <infolettre.example.ca>" })))33 // catégorie IA : fausse tant que l'IA n'a rien dit (coupée, erreur) — jamais devinée34 assert.ok(!matchCondition(c("ai_category", "is", "work"), f))35 assert.ok(!matchCondition(c("ai_category", "is", "work"), facts({ ai_category: null })))36 assert.ok(matchCondition(c("ai_category", "is", "work"), facts({ ai_category: "work" })))37})3839test("règle : toutes / au moins une ; sans condition = tout message reçu", () => {40 const f = facts()41 const yes = c("subject", "contains", "facture"), no = c("from", "contains", "desjardins")42 assert.deepEqual(matchRule({ match: "all", conditions: [yes, no] }, f), { matched: false, results: [true, false] })43 assert.deepEqual(matchRule({ match: "any", conditions: [yes, no] }, f), { matched: true, results: [true, false] })44 assert.equal(matchRule({ match: "any", conditions: [no] }, f).matched, false)45 assert.equal(matchRule({ match: "all", conditions: [] }, f).matched, true)46 assert.equal(matchRule({ match: "any", conditions: [] }, f).matched, true)47})4849test("échéances : durées, plus tard, demain 8 h, fin de semaine, semaine prochaine (heure locale, changement d'heure compris)", () => {50 const now = new Date("2026-11-20T15:30:00Z") // vendredi, 10 h 30 à Toronto (UTC−5)51 assert.equal(resolveUntil("3h", now).toISOString(), "2026-11-20T18:30:00.000Z")52 assert.equal(resolveUntil("2d", now).toISOString(), "2026-11-22T15:30:00.000Z")53 assert.equal(resolveUntil("later_today", now).toISOString(), "2026-11-20T18:30:00.000Z")54 assert.equal(resolveUntil("tomorrow", now, "America/Toronto").toISOString(), "2026-11-21T13:00:00.000Z")55 assert.equal(resolveUntil("weekend", now, "America/Toronto").toISOString(), "2026-11-21T13:00:00.000Z")56 assert.equal(resolveUntil("next_week", now, "America/Toronto").toISOString(), "2026-11-23T13:00:00.000Z")57 assert.equal(resolveUntil("tomorrow", now, "UTC").toISOString(), "2026-11-21T08:00:00.000Z")58 // un samedi : « fin de semaine » = samedi suivant ; un lundi : « semaine prochaine » = lundi suivant59 assert.equal(resolveUntil("weekend", new Date("2026-11-21T15:00:00Z"), "America/Toronto").toISOString(), "2026-11-28T13:00:00.000Z")60 assert.equal(resolveUntil("next_week", new Date("2026-11-23T15:00:00Z"), "America/Toronto").toISOString(), "2026-11-30T13:00:00.000Z")61 // tard le soir à Toronto, c'est déjà demain en UTC : « demain » reste le lendemain LOCAL62 assert.equal(resolveUntil("tomorrow", new Date("2026-11-21T03:30:00Z"), "America/Toronto").toISOString(), "2026-11-21T13:00:00.000Z")63 // heure d'été (UTC−4) : 8 h locales = 12 h UTC64 assert.equal(resolveUntil("tomorrow", new Date("2026-07-01T15:00:00Z"), "America/Toronto").toISOString(), "2026-07-02T12:00:00.000Z")65 assert.throws(() => resolveUntil("someday", now))66})6768test("schéma : opérateurs par champ, types de valeur, actions strictes", () => {69 const ok = (v: unknown) => assert.ok(zCondition.safeParse(v).success, JSON.stringify(v))70 const ko = (v: unknown) => assert.ok(!zCondition.safeParse(v).success, JSON.stringify(v))71 ok({ field: "from", op: "matches_domain", value: "example.ca" }); ok({ field: "size", op: "gt", value: 1000 }); ok({ field: "is_newsletter", op: "is", value: true }); ok({ field: "ai_category", op: "is", value: "newsletter" })72 ko({ field: "size", op: "contains", value: "x" }); ko({ field: "size", op: "gt", value: "1000" }); ko({ field: "subject", op: "matches_domain", value: "x" }); ko({ field: "has_attachment", op: "is", value: "true" })73 ko({ field: "ai_category", op: "is", value: "spam" }); ko({ field: "from", op: "contains", value: "" }); ko({ field: "body", op: "contains", value: "x" }); ko({ field: "from", op: "contains", value: "x", extra: 1 })74 const a = (v: unknown) => zAction.safeParse(v).success75 assert.ok(a({ type: "star" }) && a({ type: "snooze", until_rule: "tomorrow" }) && a({ type: "snooze", until_rule: "36h" }) && a({ type: "remind", after_hours: 48 }) && a({ type: "event", name: "invoice.received" }) && a({ type: "notify_app", app: "sp-wallet" }))76 assert.ok(a({ type: "draft_reply", ai_tone: "concise" }) && a({ type: "draft_reply", snippet_id: "3f2b8c1e-9a4d-4e6f-8b7a-1c2d3e4f5a6b" }))77 assert.ok(!a({ type: "draft_reply" }), "ni extrait ni ton")78 assert.ok(!a({ type: "draft_reply", ai_tone: "concise", snippet_id: "3f2b8c1e-9a4d-4e6f-8b7a-1c2d3e4f5a6b" }), "les deux")79 assert.ok(!a({ type: "snooze", until_rule: "0h" }) && !a({ type: "snooze", until_rule: "never" }) && !a({ type: "remind", after_hours: 0 }) && !a({ type: "event", name: "Bad Name" }))80 // aucune action d'envoi n'existe dans le vocabulaire81 for (const type of ["send", "reply", "forward", "redirect", "auto_reply", "submit"]) assert.ok(!a({ type, to: "x@evil.test" }), type)82})8384test("garde statique : rules.ts ne contient aucun chemin vers une soumission de courrier", () => {85 const src = fs.readFileSync(new URL("./rules.ts", import.meta.url), "utf8").split("\n").filter((l) => !l.trim().startsWith("//")).join("\n")86 for (const forbidden of ["EmailSubmission", "submitOutbound", "createOutbound", "/messages/send", "outbound.js", "nodemailer", "smtp"]) assert.ok(!src.includes(forbidden), `rules.ts mentionne ${forbidden}`)87 assert.match(src, /keywords: \{ \$draft: true/)88})8990test("portée dans le temps : une règle ne vaut que pour le courrier reçu après son activation (tolérance d'horloge bornée)", () => {91 const rule = { enabled_at: new Date("2026-11-20T10:00:00Z") }92 assert.ok(appliesTo(rule, "2026-11-20T10:00:00Z"))93 assert.ok(appliesTo(rule, "2026-11-20T10:05:00Z"))94 assert.ok(appliesTo(rule, new Date(rule.enabled_at.getTime() - RULE_CLOCK_SKEW_MS).toISOString()), "écart d'horloge toléré")95 assert.ok(!appliesTo(rule, new Date(rule.enabled_at.getTime() - RULE_CLOCK_SKEW_MS - 1000).toISOString()))96 assert.ok(!appliesTo(rule, "2026-11-19T10:00:00Z"), "message antérieur à la règle")97 assert.ok(!appliesTo(rule, null) && !appliesTo(rule, "pas une date"), "date de réception inconnue : la règle ne s'applique pas")98 assert.ok(appliesTo({ enabled_at: "2026-11-20T10:00:00.000Z" }, "2026-11-20T10:00:01Z"), "date d'activation lue de la base")99})100