File size: 22,515 Bytes
2e72013
 
 
 
 
 
5a744b2
 
 
2e72013
 
5a744b2
 
 
 
 
 
 
 
2e72013
 
 
 
5a744b2
 
2e72013
5a744b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e72013
5a744b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e72013
5a744b2
 
 
 
 
 
 
 
 
 
 
2e72013
5a744b2
 
2e72013
 
5a744b2
 
 
 
 
2e72013
 
5a744b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e72013
 
 
 
 
 
5a744b2
2e72013
5a744b2
2e72013
 
 
 
 
 
 
5a744b2
2e72013
 
 
 
 
5a744b2
 
 
 
 
 
 
 
 
 
2e72013
 
 
 
 
5a744b2
2e72013
 
 
5a744b2
 
 
2e72013
5a744b2
2e72013
 
5a744b2
 
 
2e72013
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a744b2
2e72013
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a744b2
2e72013
 
5a744b2
2e72013
5a744b2
 
 
 
 
2e72013
 
 
5a744b2
 
 
 
2e72013
5a744b2
 
2e72013
 
5a744b2
 
2e72013
 
 
 
 
 
 
 
5a744b2
 
 
 
2e72013
 
 
 
 
 
 
 
 
 
 
5a744b2
2e72013
 
5a744b2
 
 
2e72013
5a744b2
 
2e72013
 
5a744b2
2e72013
 
 
 
 
 
 
 
 
 
 
5a744b2
2e72013
 
 
 
 
 
 
 
5a744b2
2e72013
 
 
 
5a744b2
2e72013
 
 
 
 
 
 
 
 
 
 
 
 
5a744b2
2e72013
 
 
 
 
 
 
 
 
 
 
5a744b2
2e72013
 
5a744b2
 
 
 
 
2e72013
5a744b2
2e72013
5a744b2
2e72013
5a744b2
2e72013
 
 
 
5a744b2
 
 
 
 
2e72013
 
5a744b2
2e72013
5a744b2
 
 
2e72013
5a744b2
 
2e72013
5a744b2
 
2e72013
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a744b2
 
2e72013
 
 
 
 
 
 
 
 
 
 
 
5a744b2
2e72013
5a744b2
2e72013
 
 
 
ae3338d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>NoireBox Ask — conformité AI Act & RGPD</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=Source+Serif+4:ital,opsz,wght@0,8..60,400..600;1,8..60,400..600&display=swap" rel="stylesheet">
<style>
  :root {
    --bg: #f6f7f9; --card: #ffffff; --line: #e3e8ef; --line-soft: #edf0f4;
    --ink: #131c2b; --dim: #64748b; --faint: #94a3b8;
    --navy: #12295c; --navy-2: #1a3a80; --user: #12295c;
    --ok: #15803d; --warn: #b45309;
    --t1: #1e6f4f; --t2: #1e40af; --t3: #6d28d9; --t4: #0e7490; --t5: #b45309; --t6: #64748b;
    --sans: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
    --serif: "Source Serif 4", Georgia, "Times New Roman", serif;
    --mono: ui-monospace, SFMono-Regular, Menlo, monospace;
  }
  * { box-sizing: border-box; }
  html, body { height: 100%; }
  body { margin: 0; background: var(--bg); color: var(--ink); display: flex; flex-direction: column;
         font-family: var(--sans); font-size: 14.5px; line-height: 1.65;
         -webkit-font-smoothing: antialiased; }

  .flag { height: 3px; background: linear-gradient(90deg, #000091 0 33%, #fff 33% 66%, #e1000f 66% 100%); }
  header { background: var(--card); border-bottom: 1px solid var(--line); padding: 14px 20px; }
  .head-in { max-width: 840px; margin: 0 auto; display: flex; align-items: center; gap: 14px; }
  .mark { width: 38px; height: 38px; border-radius: 10px; background: linear-gradient(135deg, var(--navy), var(--navy-2));
      color: #fff; display: flex; align-items: center; justify-content: center; flex: none;
      font-weight: 800; font-size: 13px; letter-spacing: .5px; box-shadow: 0 2px 6px rgba(18,41,92,.25); }
  .brand h1 { font-size: 16.5px; margin: 0; font-weight: 700; letter-spacing: -.01em; }
  .brand h1 span { color: var(--navy-2); font-weight: 600; }
  .brand .tagline { font-size: 12px; color: var(--dim); margin-top: 1px; }
  .status { margin-left: auto; display: flex; flex-direction: column; align-items: flex-end; gap: 5px; }
  .voices { display: inline-flex; background: var(--bg); border: 1px solid var(--line); border-radius: 9px; padding: 2px; }
  .voices button { background: transparent; color: var(--dim); border: 0; border-radius: 7px;
      padding: 5px 13px; cursor: pointer; font-size: 12.5px; font-weight: 500; font-family: var(--sans); }
  .voices button.on { background: var(--navy); color: #fff; font-weight: 600; box-shadow: 0 1px 3px rgba(18,41,92,.3); }
  .stats { font-size: 11px; color: var(--faint); display: flex; align-items: center; gap: 5px; }
  .dot { width: 7px; height: 7px; border-radius: 50%; background: var(--faint); display: inline-block; }
  .dot.loading { background: #d97706; animation: pulse 1.2s ease-in-out infinite; }
  .dot.ready { background: var(--ok); }
  @keyframes pulse { 50% { opacity: .35; } }

  #chat { flex: 1; overflow-y: auto; width: 100%; max-width: 840px; margin: 0 auto;
          padding: 24px 16px 14px; scrollbar-width: thin; scrollbar-color: var(--line) transparent; }
  .m { display: flex; margin: 14px 0; gap: 10px; }
  .m.you { justify-content: flex-end; }
  .avatar { width: 26px; height: 26px; border-radius: 8px; flex: none; margin-top: 2px;
      background: linear-gradient(135deg, var(--navy), var(--navy-2)); color: #fff;
      display: flex; align-items: center; justify-content: center; font-size: 9px; font-weight: 800; }
  .m.bot .col { max-width: calc(100% - 40px); }
  .m.you .bubble { background: var(--user); color: #fff; border-radius: 14px 14px 4px 14px;
      padding: 10px 16px; max-width: 72%; font-size: 14.5px; box-shadow: 0 1px 3px rgba(18,41,92,.2); }
  .m.bot .bubble { background: var(--card); border: 1px solid var(--line); border-radius: 4px 14px 14px 14px;
      padding: 16px 20px 14px; box-shadow: 0 1px 3px rgba(19,28,43,.05); }
  .meta-line { display: flex; align-items: center; gap: 6px; font-size: 11px; letter-spacing: .04em;
      color: var(--faint); margin-bottom: 8px; text-transform: uppercase; font-weight: 600; }
  .meta-line.warn { color: var(--warn); }
  .botbody { white-space: normal; }
  .botbody p { margin: 0 0 8px; }
  .botbody table { border-collapse: collapse; margin: 10px 0; font-size: 13px; width: 100%; }
  .botbody th { background: #f1f4f9; font-weight: 600; font-size: 12px; text-transform: uppercase;
      letter-spacing: .03em; color: #3b4a63; }
  .botbody th, .botbody td { border: 1px solid var(--line); padding: 7px 10px; text-align: left; vertical-align: top; }
  .botbody tr:nth-child(even) td { background: #fafbfd; }
  .botbody code { background: #f1f4f9; border: 1px solid var(--line-soft); border-radius: 5px;
      padding: 1px 6px; font-size: 12.5px; color: var(--navy-2); font-family: var(--mono); }
  .botbody a { color: var(--navy-2); text-decoration: underline; text-underline-offset: 2px; }
  .botbody hr { border: 0; border-top: 1px solid var(--line); margin: 12px 0; }
  .botbody p.h { font-weight: 700; font-size: 14.5px; margin: 12px 0 6px; color: var(--navy); }
  .botbody blockquote { font-family: var(--serif); font-style: italic; color: #33415c;
      border-left: 3px solid var(--navy-2); margin: 10px 0; padding: 4px 14px; background: #f8f9fc;
      border-radius: 0 8px 8px 0; }
  details.srcs { margin-top: 12px; border-top: 1px solid var(--line-soft); padding-top: 8px; }
  details.srcs summary { cursor: pointer; color: var(--dim); font-size: 12.5px; font-weight: 600;
      list-style: none; display: flex; align-items: center; gap: 6px; user-select: none; }
  details.srcs summary::-webkit-details-marker { display: none; }
  details.srcs summary::before { content: "▸"; color: var(--faint); transition: transform .15s; }
  details.srcs[open] summary::before { transform: rotate(90deg); }
  .req { margin: 7px 0; padding: 8px 12px; background: #f8f9fc; border: 1px solid var(--line-soft);
      border-radius: 9px; font-size: 13px; }
  .req .id { font-family: var(--mono); color: var(--navy-2); font-size: 11.5px; font-weight: 700; }
  .req .ct { float: right; font-size: 10.5px; color: var(--faint); text-transform: uppercase; letter-spacing: .04em; }
  .art { margin: 10px 0; font-size: 13.5px; }
  .art .ref { font-weight: 700; }
  .art .head { color: var(--dim); }
  .art .quote { font-family: var(--serif); color: #33415c; font-style: italic; display: block;
      margin-top: 4px; padding: 6px 14px; border-left: 3px solid var(--navy-2); background: #f8f9fc;
      border-radius: 0 8px 8px 0; font-size: 13px; line-height: 1.6; }
  .src { border-left: 3px solid var(--t6); padding: 7px 12px; margin: 8px 0;
      background: #f8f9fc; border-radius: 0 9px 9px 0; font-size: 12.5px; }
  .src .meta { font-size: 11px; margin-bottom: 2px; display: flex; align-items: center; gap: 7px; }
  .tierbadge { display: inline-block; border-radius: 999px; padding: 1.5px 9px; font-size: 10px;
      font-weight: 700; letter-spacing: .05em; text-transform: uppercase; color: #fff; }
  .src .sname { color: var(--faint); }
  .src .title { color: var(--ink); font-weight: 600; font-size: 13px; }
  .src .snip { color: var(--dim); margin-top: 2px; }
  .typing { color: var(--dim); }
  .typing::after { content: "▍"; animation: blink 1s steps(1) infinite; color: var(--navy-2); }
  @keyframes blink { 50% { opacity: 0; } }

  .chips { display: flex; flex-wrap: wrap; gap: 7px; max-width: 840px; margin: 0 auto; padding: 0 16px 10px; }
  .chips button { background: var(--card); color: var(--dim); border: 1px solid var(--line);
      border-radius: 999px; padding: 5px 14px; font-size: 12.5px; cursor: pointer; font-family: var(--sans);
      transition: all .15s; }
  .chips button:hover:not(:disabled) { border-color: var(--navy-2); color: var(--navy-2); background: #f4f7ff; }
  .chips button:disabled { opacity: .5; cursor: wait; }

  .askwrap { background: var(--card); border-top: 1px solid var(--line); padding: 12px 16px 14px; }
  .askbox { max-width: 840px; margin: 0 auto; display: flex; gap: 10px; align-items: flex-end;
      background: var(--card); border: 1px solid var(--line); border-radius: 14px; padding: 8px 8px 8px 16px;
      box-shadow: 0 2px 10px rgba(19,28,43,.06); transition: border-color .15s, box-shadow .15s; }
  .askbox:focus-within { border-color: var(--navy-2); box-shadow: 0 2px 14px rgba(26,58,128,.14); }
  input[type=text] { flex: 1; background: transparent; border: 0; color: var(--ink);
      font-size: 15px; outline: none; font-family: var(--sans); padding: 8px 0; }
  input[type=text]::placeholder { color: var(--faint); }
  input[type=text]:disabled { opacity: .55; }
  button.go { background: var(--navy); color: #fff; border: 0; border-radius: 10px;
      width: 40px; height: 40px; cursor: pointer; display: flex; align-items: center; justify-content: center; flex: none;
      transition: background .15s; }
  button.go:hover:not(:disabled) { background: var(--navy-2); }
  button.go:disabled { opacity: .45; cursor: wait; }
  .foot { max-width: 840px; margin: 0 auto; font-size: 11px; color: var(--faint); padding: 7px 4px 0; }
  .foot a { color: var(--navy-2); }
  #loaderr { color: #b91c1c; font-size: 13px; max-width: 840px; margin: 8px auto; padding: 0 16px; display: none; }
  #loaderr button { margin-left: 8px; border: 1px solid var(--line); background: var(--card);
      border-radius: 7px; padding: 3px 10px; cursor: pointer; font-family: var(--sans); }
  @media (max-width: 640px) {
    .status { display: none; }
    .m.you .bubble { max-width: 88%; }
    .m.bot .col { max-width: calc(100% - 36px); }
  }
</style>
</head>
<body>
  <div class="flag"></div>
  <header>
    <div class="head-in">
      <div class="mark">NB</div>
      <div class="brand">
        <h1>NoireBox <span>Ask</span></h1>
        <div class="tagline">AI Act européen &amp; RGPD — réponses rédigées à partir du texte officiel uniquement</div>
      </div>
      <div class="status">
        <div class="voices">
          <button id="v-nontech" class="on" disabled>Chef de projet</button>
          <button id="v-tech" disabled>Dev / auditeur</button>
        </div>
        <div class="stats"><span class="dot loading" id="dot"></span><span id="stats">chargement des textes…</span></div>
      </div>
    </div>
  </header>

  <div id="chat">
    <div class="m bot">
      <div class="avatar">NB</div>
      <div class="col"><div class="bubble">
        <div class="meta-line">assistant conformité — sources officielles</div>
        <div class="botbody">
          <p>Bonjour. Interrogez l'AI Act européen ou le RGPD : journalisation, évaluation d'impact, droits des personnes, chatbots, modèles à usage général, preuves de conformité…</p>
          <p>Chaque réponse est d'abord <b>cherchée dans un corpus versionné</b> (EUR-Lex consolidé, CNIL, Conseil d'État, CNCDH, Code GPAI), puis rédigée à partir des seuls passages retrouvés. Sources et exigences vérifiables sont jointes à chaque réponse.</p>
        </div>
      </div></div>
    </div>
  </div>

  <div class="chips" id="chips"></div>
  <div id="loaderr"></div>

  <div class="askwrap">
    <div class="askbox">
      <input type="text" id="q" placeholder="Votre question — ex. : quelles obligations de journalisation pour un système à haut risque ?"
             autocomplete="off" disabled>
      <button class="go" id="go" disabled aria-label="Envoyer">
        <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
      </button>
    </div>
    <div class="foot">
      La <b>recherche</b> s'exécute dans votre navigateur (aucune donnée personnelle collectée). La
      <b>rédaction</b> est assurée par un modèle ouvert qui ne reçoit que les passages du corpus —
      en cas d'indisponibilité, bascule en <b>mode preuve</b> (résumé déterministe sourcé).
      Corpus &amp; preuves : <a href="https://github.com/slabbdev" target="_blank" rel="noopener">LOI.EXE / NoireBox</a>.
    </div>
  </div>

<script type="module">
import { Normask } from "./engine.js";
import { streamAnswer } from "./llm.js";

const TIERS = {
  "droit-fr":       ["--t1", "Droit FR"],
  "code-officiel":  ["--t2", "Code officiel"],
  "doctrine-fr":    ["--t3", "Doctrine"],
  "communication-ue":["--t4", "Comm. UE"],
  "communauté":     ["--t5", "Communauté"],
  "recherche":      ["--t5", "Recherche"],
  "produit":        ["--t6", "NoireBox"]
};
const CHIPS = [
  "Quelles sont les obligations de journalisation pour un système à haut risque ?",
  "Comment prouver que mon chatbot informe les gens qu'ils parlent à une IA ?",
  "Dois-je faire une évaluation d'impact pour mon système de tri de CV ?",
  "Qu'est-ce que le droit à l'effacement ?",
];
let voice = "nontech", engine = null, busy = false;
const history = [];

const $ = (id) => document.getElementById(id);
const chat = $("chat"), q = $("q"), go = $("go"), stats = $("stats"), dot = $("dot");

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

// téléchargement avec timeout + retries — le champ devient utilisable dès l'étage 1
async function fetchJSONL(name, tries = 3) {
  for (let i = 0; i < tries; i++) {
    const ctrl = new AbortController();
    const timer = setTimeout(() => ctrl.abort(), 20000);
    try {
      const r = await fetch(`data/${name}`, { signal: ctrl.signal });
      clearTimeout(timer);
      if (r.ok) {
        return (await r.text()).split("\n").filter((l) => l.trim()).map((l) => JSON.parse(l));
      }
    } catch { /* timeout ou réseau : on retente */ }
    clearTimeout(timer);
    if (i < tries - 1) await sleep(1200 * (i + 1));
  }
  throw new Error(`${name} : téléchargement impossible`);
}

const esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;");
function inline(s) {
  return esc(s)
    .replace(/\*\*(.+?)\*\*/g, "<b>$1</b>")
    .replace(/`([^`]+)`/g, "<code>$1</code>")
    .replace(/\[([^\]]+)\]\((https?:[^)\s]+)\)/g,
      '<a href="$2" target="_blank" rel="noopener">$1</a>');
}
function rich(s) {
  return s.split("\n").map((line) => {
    if (/^\s*\|.+\|\s*$/.test(line)) return line;      // tables : traitées en bloc
    if (/^\s*(---+|___+)\s*$/.test(line)) return "<hr>";
    const h = line.match(/^\s*#{1,6}\s+(.*)$/);
    if (h) return `<p class="h">${inline(h[1])}</p>`;
    return inline(line);
  }).join("\n")
  .replace(/(^|\n)((?:&gt;|>)[^\n]*(?:\n|$))+/g, (bq) => {
    const inner = bq.trim().split("\n").map((l) => l.replace(/^\s*&gt;\s*|^\s*>\s*/, "")).join("\n");
    return `\n<blockquote>${inner}</blockquote>\n`;
  })
  .replace(/((?:^\s*\|.*\|\s*$\n?)+)/gm, (block) => {
    const rows = block.trim().split("\n").filter((r) => !/^\|[\s:|-]+\|?$/.test(r));
    if (rows.length < 2) return inline(block);
    const cells = (r) => r.trim().replace(/^\||\|$/g, "").split("|").map((c) => c.trim());
    const head = cells(rows[0]);
    const body = rows.slice(1).map(cells);
    return "<table><thead><tr>" + head.map((c) => `<th>${inline(c)}</th>`).join("")
      + "</tr></thead><tbody>" + body.map((r) => "<tr>" + r.map((c) => `<td>${inline(c)}</td>`).join("") + "</tr>").join("")
      + "</tbody></table>";
  })
  .replace(/(^|\n)\s*- /g, "$1• ")
  .replace(/\*\*(.+?)\*\*/g, "<b>$1</b>")
  .replace(/`([^`]+)`/g, "<code>$1</code>");
}

function scrollDown() { chat.scrollTop = chat.scrollHeight; }

function addYou(text) {
  const d = document.createElement("div");
  d.className = "m you";
  d.innerHTML = `<div class="bubble">${esc(text)}</div>`;
  chat.appendChild(d); scrollDown();
}

function addBotShell() {
  const d = document.createElement("div");
  d.className = "m bot";
  d.innerHTML = `<div class="avatar">NB</div><div class="col"><div class="bubble">
                 <div class="meta-line"><span class="typing">recherche dans le corpus</span></div>
                 <div class="botbody"></div></div></div>`;
  chat.appendChild(d); scrollDown();
  return { bubble: d.querySelector(".bubble"), meta: d.querySelector(".meta-line"),
           body: d.querySelector(".botbody") };
}

function attachGrounding(g, warn) {
  let h = "";
  if (g.requirements.length)
    h += `<details class="srcs"><summary>Exigences vérifiables (${g.requirements.length})</summary>`
      + g.requirements.map((r) =>
          `<div class="req"><span class="ct">${r.check_type}${r.machine ? " · machine" : ""}</span>`
          + `<span class="id">${esc(r.req_id)}</span> — ${esc(r.obligation)} `
          + `<span class="sub">(${esc(r.acte)} art. ${esc(r.ref)})</span></div>`).join("")
      + `</details>`;
  if (g.articles.length)
    h += `<details class="srcs"><summary>Texte officiel (${g.articles.map((a) => a.acte + " art. " + a.article).join(", ")})</summary>`
      + g.articles.map((x) =>
          `<div class="art"><span class="ref">${esc(x.acte)} art. ${esc(x.article)}</span>${x.heading ? ` <span class="head">— ${esc(x.heading)}</span>` : ""}`
          + (x.text ? `<span class="quote">« ${esc(x.text.slice(0, 600))}… »</span>` : "") + `</div>`).join("")
      + `</details>`;
  if (g.passages.length)
    h += `<details class="srcs"><summary>Sources (${g.passages.length})</summary>`
      + g.passages.map((s) => {
          const [col, label] = TIERS[s.tier] || TIERS["communauté"];
          return `<div class="src" style="border-left-color:var(${col})">
                    <div class="meta"><span class="tierbadge" style="background:var(${col})">${esc(label)}</span>
                    <span class="sname">${esc(s.source)}</span></div>
                    <div class="title">${esc(s.title)}</div>
                    <div class="snip">${esc(s.text.slice(0, 220))}…</div></div>`;
        }).join("")
      + `</details>`;
  return h;
}

function deterministicText(g) {
  const parts = [];
  if (g.requirements.length) {
    parts.push("Ce qu'on vous demande concrètement :");
    for (const r of g.requirements.slice(0, 3))
      parts.push(`- ${r.obligation} (${r.acte} art. ${r.ref}).`);
    parts.push("\nCela doit se **prouver**, pas se promettre : chaque point correspond à un test exécutable.");
  } else if (g.passages.length) {
    parts.push("Voici ce que disent les sources, de la plus officielle à la plus pratique :");
  }
  if (g.articles.length && g.articles[0].text)
    parts.push(`\n> Le texte légal (${g.articles[0].acte} art. ${g.articles[0].article}) : « ${g.articles[0].text.slice(0, 220)}… »`);
  if (g.passages.length)
    for (const s of g.passages.slice(0, 3)) parts.push(`- ${s.tier_label} : ${s.title}`);
  return parts.join("\n") || "Aucun passage pertinent trouvé — reformulez avec un article ou un mot-clé.";
}

async function send(text) {
  text = (text || q.value).trim();
  if (!text || busy || !engine) return;
  busy = true; q.value = "";
  q.disabled = true; go.disabled = true;
  addYou(text);
  const ui = addBotShell();

  const g = engine.grounding(text);
  ui.meta.innerHTML = `<span class="typing">${g.passages.length + g.requirements.length} passages retrouvés — rédaction</span>`;

  let full = "", timer = null;
  const renderNow = () => { ui.body.innerHTML = rich(full); scrollDown(); };
  const renderSoon = () => { if (!timer) timer = setTimeout(() => { timer = null; renderNow(); }, 90); };

  let ok = false, err = null;
  try {
    full = await streamAnswer({
      grounding: g, question: text, voice, history,
      onDelta: (frag) => { full += frag; renderSoon(); },   // markdown rendu au fil de l'eau
    });
    ok = !!full.trim();
    if (ok) history.push({ role: "user", content: text }, { role: "assistant", content: full });
  } catch (e) {
    err = e;
    if (timer) clearTimeout(timer);
    if (full.trim()) {
      full += "\n\n---\n\n⚠️ **Rédaction interrompue** : " + e.message;
      ok = true;   // on garde le partiel, rendu
    }
  }

  if (!ok) {
    ui.meta.classList.add("warn");
    ui.meta.textContent = "rédaction ia indisponible — mode preuve (sources ci-dessous)";
    ui.body.innerHTML = rich(deterministicText(g));
  } else {
    renderNow();
    ui.meta.textContent = `réponse rédigée à partir de ${g.passages.length + g.requirements.length} passages du corpus`;
  }
  ui.bubble.insertAdjacentHTML("beforeend", attachGrounding(g, !ok));
  scrollDown();
  busy = false; q.disabled = false; go.disabled = false; q.focus();
}

CHIPS.forEach((c) => {
  const b = document.createElement("button");
  b.textContent = c.length > 52 ? c.slice(0, 50) + "…" : c;
  b.title = c;
  b.onclick = () => send(c);
  b.disabled = true;
  $("chips").appendChild(b);
});
$("v-tech").onclick = () => setVoice("tech");
$("v-nontech").onclick = () => setVoice("nontech");
function setVoice(v) {
  voice = v;
  $("v-tech").classList.toggle("on", v === "tech");
  $("v-nontech").classList.toggle("on", v !== "tech");
}
go.onclick = () => send();
q.addEventListener("keydown", (e) => { if (e.key === "Enter") send(); });

function enableAll() {
  for (const el of [q, go, $("v-tech"), $("v-nontech"), ...$("chips").children]) el.disabled = false;
  q.focus();
}

(async () => {
  // étage 1 : articles officiels + exigences (léger, ~700 Ko) → chat utilisable
  try {
    const [provisions, reqs] = await Promise.all([
      fetchJSONL("provisions_fr.jsonl"), fetchJSONL("requirements.jsonl")]);
    engine = new Normask({ kb: [], provisions, reqs });
    dot.className = "dot ready";
    stats.innerHTML = `prêt · ${provisions.length} articles officiels · ${reqs.length} exigences vérifiables · contexte en cours…`;
    enableAll();
  } catch (e) {
    const err = $("loaderr");
    err.style.display = "block";
    err.innerHTML = "Impossible de charger les textes : " + esc(e.message)
      + ' <button onclick="location.reload()">Réessayer</button>';
    return;
  }
  // étage 2 : gros corpus de contexte (4,6 Mo) en arrière-plan
  try {
    const kbDocs = await fetchJSONL("kb.jsonl");
    engine.attachKb(kbDocs);
    stats.innerHTML = `corpus complet · ${kbDocs.length} passages de contexte · ${engine.provisions.length} articles · ${engine.reqs.length} exigences`;
  } catch (e) {
    stats.textContent = "contexte doctrinal indisponible — réponses sur articles et exigences";
  }
})();
</script>
</body>
</html>