File size: 23,668 Bytes
c77a5a3
 
 
 
 
 
 
 
 
 
46cddde
 
 
 
 
c77a5a3
 
 
46cddde
 
c77a5a3
 
 
 
46cddde
c77a5a3
 
 
 
 
 
46cddde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c77a5a3
 
46cddde
 
 
 
c77a5a3
 
 
46cddde
 
 
 
 
 
 
c77a5a3
 
46cddde
 
 
 
 
 
c77a5a3
 
 
46cddde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c77a5a3
 
 
46cddde
8d1d5bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c77a5a3
 
46cddde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d1d5bb
 
 
 
 
 
46cddde
 
 
 
 
 
8d1d5bb
 
 
 
 
 
 
 
 
 
46cddde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c77a5a3
46cddde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
acdeb61
 
 
 
 
 
 
46cddde
 
acdeb61
46cddde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
acdeb61
46cddde
 
acdeb61
46cddde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c77a5a3
 
8d1d5bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c77a5a3
 
8d1d5bb
46cddde
8d1d5bb
 
 
46cddde
c77a5a3
 
46cddde
c77a5a3
 
 
46cddde
c77a5a3
 
 
 
 
 
 
 
 
 
 
46cddde
c77a5a3
 
 
 
 
 
 
 
46cddde
c77a5a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46cddde
c77a5a3
46cddde
 
 
 
 
c77a5a3
46cddde
 
 
8d1d5bb
c77a5a3
46cddde
c77a5a3
8d1d5bb
c77a5a3
 
 
46cddde
 
 
c77a5a3
 
46cddde
c77a5a3
 
 
 
8d1d5bb
 
 
 
 
c77a5a3
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
const PYODIDE_VERSION = "0.29.5";
const PYODIDE_INDEX = `https://cdn.jsdelivr.net/pyodide/v${PYODIDE_VERSION}/full/`;
const ASC_WHEEL = "./vendor/agent_security_contract-0.2.1-py3-none-any.whl";
const ASC_COMMIT = "768853bde5a56fcc6c9b486f52848761db1b0ef1";

const state = {
  status: "loading",
  loadMs: null,
  pyodide: null,
  engine: null,
  info: null,
  currentId: "path_traversal_relative",
  lastEnvelope: "",
  originalEnvelope: "",
  filter: "all",
};

const demo = {
  get status() { return state.status; },
  get loadMs() { return state.loadMs; },
  ready: null,
  evaluateScenario: null,
  evaluateTrace: null,
  runCorpus: null,
  tamperAndVerify: null,
};

window.__ASC_DEMO__ = demo;

const $ = (id) => document.getElementById(id);

function formatError(error) {
  if (error == null) return String(error);
  if (typeof error === "string") return error;
  const parts = [error.name, error.message, error.errno, error.code, error.path]
    .filter((value) => value != null && value !== "")
    .map(String);
  if (parts.length) return parts.join(": ");
  try { return JSON.stringify(error); } catch (_exc) { return String(error); }
}

function parsePyJson(value) {
  const text = typeof value === "string" ? value : value.toString();
  if (value && typeof value.destroy === "function") value.destroy();
  return JSON.parse(text);
}

function setProgress(percent, text, stateName = "loading") {
  state.status = stateName;
  document.body.dataset.ascStatus = stateName;
  const status = $("status");
  status.dataset.state = stateName === "ready" ? "ready" : stateName === "error" ? "error" : "loading";
  $("progress-bar").style.width = `${Math.max(4, Math.min(100, percent))}%`;
  $("status-text").textContent = text;
}

function setBusy(busy) {
  ["evaluate", "recompute", "preset", "trace", "policy", "copy-envelope", "download-envelope", "tamper", "run-all"].forEach((id) => {
    const el = $(id);
    if (el) el.disabled = busy;
  });
  document.querySelectorAll(".scen, .filter").forEach((el) => {
    el.disabled = busy;
  });
}

function argsPreview(args) {
  try {
    const text = JSON.stringify(args);
    return text.length > 140 ? `${text.slice(0, 137)}…` : text;
  } catch (_exc) {
    return "";
  }
}

function renderTimeline(calls) {
  const root = $("timeline");
  if (!calls || !calls.length) {
    root.innerHTML = "<p class=\"details\">No parsed tool calls in this trace.</p>";
    return;
  }
  root.innerHTML = "";
  for (const call of calls) {
    const step = document.createElement("article");
    step.className = "step";
    step.dataset.blocked = call.blocked ? "true" : "false";
    step.innerHTML = `
      <div class="step-id">${escapeHtml(call.call_id)}${call.approved ? " · approved" : ""}</div>
      <div class="step-tool">${escapeHtml(call.tool)}</div>
      <div class="step-args">${escapeHtml(argsPreview(call.args))}</div>
      ${call.blocked ? "<div class=\"step-flag\">Blocked call</div>" : ""}
    `;
    root.appendChild(step);
  }
}

function escapeHtml(value) {
  return String(value == null ? "" : value)
    .split("&").join("&amp;")
    .split("<").join("&lt;")
    .split(">").join("&gt;")
    .split('"').join("&quot;");
}

function openExternalLinks() {
  const links = document.querySelectorAll("a[href]");
  for (let i = 0; i < links.length; i += 1) {
    const href = links[i].getAttribute("href") || "";
    if (href.indexOf("http://") !== 0 && href.indexOf("https://") !== 0) continue;
    links[i].setAttribute("target", "_blank");
    links[i].setAttribute("rel", "noopener noreferrer");
  }
}

function canRunLiveRuntime() {
  try {
    // Pyodide 0.29.x asm.js uses class static blocks, private fields, and ??=
    // Static blocks need Safari 16.4 / iOS 16.4 or later (Pyodide's stated minimum).
    new Function("class F { static {} }");
    new Function("class F { #x = 1; }");
    new Function("var a = {}; a.b ??= 1;");
  } catch (err) {
    return false;
  }
  if (typeof WebAssembly === "undefined") return false;
  if (typeof WebAssembly.instantiate !== "function") return false;
  return true;
}

function forceFallback() {
  try {
    if (window.__FORCE_FALLBACK__) return true;
    const params = new URLSearchParams(window.location.search);
    return params.get("fallback") === "1";
  } catch (err) {
    return false;
  }
}

const FALLBACK_MESSAGE = "The live in-browser runtime needs a newer browser (Safari 16.4 or later, or a current desktop browser). This page is showing precomputed results from the official corpus. Open the page on desktop to run the engine yourself.";

function fallbackMessage(error) {
  if (!error) return FALLBACK_MESSAGE;
  return "The live in-browser runtime could not start in this browser. This page is showing precomputed results from the official corpus. Open the page on a current desktop browser to run the engine yourself.";
}

function chip(text, className) {
  const span = document.createElement("span");
  span.className = `chip ${className || ""}`.trim();
  span.textContent = text;
  return span;
}

function applyDecision(out, preset) {
  state.lastEnvelope = out.envelope_text;
  state.originalEnvelope = out.envelope_text;
  $("restore-envelope").hidden = true;
  $("tamper-result").hidden = true;
  $("copy-status").hidden = true;

  const card = $("verdict-card");
  card.dataset.verdict = out.verdict || "";
  $("verdict-word").textContent = out.verdict || "—";

  const meta = $("verdict-meta");
  meta.innerHTML = "";
  if (out.acs_disposition) meta.appendChild(chip(`ACS ${out.acs_disposition}`, "acs"));
  if (preset && preset.expected) meta.appendChild(chip(`Corpus expected ${preset.expected}`, "expected"));
  if (out.blocked_call_id) meta.appendChild(chip(`Blocked call ${out.blocked_call_id}`, "blocked"));
  if (out.scenario_id) meta.appendChild(chip(out.scenario_id, ""));
  meta.appendChild(chip(
    out.integrity === "passed" ? "Integrity check passed" : "Integrity check failed",
    out.integrity === "passed" ? "integrity-ok" : "integrity-bad",
  ));

  $("reason").textContent = out.reason ? `Reason: ${out.reason}` : "";
  $("details").textContent = out.details && Object.keys(out.details).length
    ? `Details: ${JSON.stringify(out.details)}`
    : "";

  const envMeta = $("envelope-meta");
  envMeta.innerHTML = "";
  envMeta.appendChild(chip(
    out.integrity === "passed" ? "Integrity check passed" : "Integrity check failed",
    out.integrity === "passed" ? "integrity-ok" : "integrity-bad",
  ));
  envMeta.appendChild(chip("Hash-checked, not signed", ""));
  $("envelope").textContent = out.envelope_text || "";
  renderTimeline(out.calls || []);
}

function currentPreset() {
  const presets = (state.info && state.info.presets) || [];
  return presets.find((item) => item.id === state.currentId) || { id: state.currentId };
}

function evaluateCurrent() {
  const out = demo.evaluateTrace
    ? demo.evaluateTrace(state.currentId, $("trace").value, $("policy").value)
    : (state.precomputed && state.precomputed.results && state.precomputed.results[state.currentId]);
  if (!out) {
    throw new Error("No precomputed result for " + state.currentId);
  }
  applyDecision(out, currentPreset());
  markSelectedCard(state.currentId);
  return out;
}

function loadAndShow(scenarioId) {
  let loaded;
  if (state.engine) {
    loaded = parsePyJson(state.engine.load_preset(scenarioId));
  } else {
    const pack = state.precomputed || {};
    loaded = (pack.presets && pack.presets[scenarioId]) || null;
    if (!loaded) {
      throw new Error("Unknown scenario: " + scenarioId);
    }
  }
  state.currentId = loaded.id;
  $("preset").value = loaded.id;
  $("trace").value = loaded.trace;
  $("policy").value = loaded.policy;
  $("note").textContent = loaded.note;
  return loaded;
}

function selectScenario(scenarioId, shouldEvaluate = true) {
  const loaded = loadAndShow(scenarioId);
  if (shouldEvaluate) evaluateCurrent();
  markSelectedCard(scenarioId);
  return loaded;
}

function markSelectedCard(scenarioId) {
  document.querySelectorAll(".scen").forEach((card) => {
    card.setAttribute("aria-pressed", card.dataset.id === scenarioId ? "true" : "false");
  });
}

function visiblePresets() {
  const presets = state.info.presets;
  const filter = state.filter;
  return presets.filter((item) => {
    if (filter === "all") return true;
    if (filter === "attack") return item.group === "attack";
    if (filter === "benign") return item.group === "benign";
    return item.tag === filter;
  });
}

function renderGallery() {
  const attacks = $("gallery-attacks");
  const benign = $("gallery-benign");
  attacks.innerHTML = "";
  benign.innerHTML = "";
  const items = visiblePresets();
  const attackItems = items.filter((item) => item.group === "attack");
  const benignItems = items.filter((item) => item.group === "benign");
  $("attack-heading").textContent = `Attacks (${attackItems.length})`;
  $("benign-heading").textContent = `Benign controls (${benignItems.length})`;
  $("attack-heading").hidden = attackItems.length === 0;
  $("benign-heading").hidden = benignItems.length === 0;
  for (const item of attackItems) attacks.appendChild(scenarioCard(item));
  for (const item of benignItems) benign.appendChild(scenarioCard(item));
  markSelectedCard(state.currentId);
}

function scenarioCard(item) {
  const button = document.createElement("button");
  button.type = "button";
  button.className = "scen";
  button.dataset.id = item.id;
  button.setAttribute("aria-pressed", "false");
  button.innerHTML = `
    <div class="scen-title">${escapeHtml(item.title)}</div>
    <div class="scen-id">${escapeHtml(item.id)}</div>
    <div class="scen-desc">${escapeHtml(item.description)}</div>
    <div class="verdict-meta">
      <span class="chip">${escapeHtml(item.expected)}</span>
      <span class="chip">${escapeHtml(item.tag)}</span>
      ${item.severity && item.severity !== "benign" ? `<span class="chip">${escapeHtml(item.severity)}</span>` : ""}
    </div>
  `;
  button.addEventListener("click", () => {
    selectScenario(item.id, true);
    $("verdict-card").scrollIntoView({ block: "start", behavior: "smooth" });
  });
  return button;
}

function renderFilters() {
  const root = $("filters");
  root.innerHTML = "";
  const attackCount = state.info.attack_count;
  const benignCount = state.info.benign_count;
  const options = [
    { id: "all", label: `All ${state.info.scenario_count}` },
    { id: "attack", label: `Attacks ${attackCount}` },
    { id: "benign", label: `Benign ${benignCount}` },
    ...state.info.tags.map((tag) => ({ id: tag, label: tag })),
  ];
  for (const option of options) {
    const button = document.createElement("button");
    button.type = "button";
    button.className = "filter";
    button.dataset.filter = option.id;
    button.textContent = option.label;
    button.setAttribute("aria-pressed", option.id === state.filter ? "true" : "false");
    button.addEventListener("click", () => {
      state.filter = option.id;
      renderFilters();
      renderGallery();
    });
    root.appendChild(button);
  }
}

function fillPresetSelect() {
  const preset = $("preset");
  preset.innerHTML = "";
  const custom = document.createElement("option");
  custom.value = "custom";
  custom.textContent = "Custom trace (edit JSON below)";
  preset.appendChild(custom);
  for (const item of state.info.presets) {
    const option = document.createElement("option");
    option.value = item.id;
    option.textContent = item.label;
    preset.appendChild(option);
  }
}

async function runAllWithProgress() {
  const ids = state.info.presets.map((item) => item.id);
  const wrap = $("corpus-progress-wrap");
  const bar = $("corpus-bar");
  const label = $("corpus-progress");
  const matrix = $("corpus-matrix");
  const summary = $("corpus-summary");
  wrap.hidden = false;
  matrix.hidden = false;
  $("corpus-legend").hidden = false;
  matrix.innerHTML = "";
  const cells = {};
  for (const id of ids) {
    const cell = document.createElement("button");
    cell.type = "button";
    cell.className = "cell";
    cell.dataset.id = id;
    cell.title = id;
    cell.setAttribute("aria-label", id);
    cell.addEventListener("click", () => {
      selectScenario(id, true);
      $("verdict-card").scrollIntoView({ block: "start", behavior: "smooth" });
    });
    matrix.appendChild(cell);
    cells[id] = cell;
  }

  const setProgress = (done, total) => {
    const pct = total === 0 ? 0 : (done / total) * 100;
    bar.classList.toggle("is-complete", done >= total && total > 0);
    bar.style.width = `${pct}%`;
    label.textContent = `${done} / ${total}`;
  };

  const results = [];
  $("run-all").disabled = true;
  setProgress(0, ids.length);
  for (let index = 0; index < ids.length; index += 1) {
    const id = ids[index];
    const out = demo.evaluateScenario(id);
    const expected = state.info.presets.find((item) => item.id === id).expected;
    const match = out.verdict === expected && out.integrity === "passed";
    const row = {
      id,
      expected,
      actual: out.verdict,
      match,
      reason: out.reason,
      integrity: out.integrity,
    };
    results.push(row);
    cells[id].dataset.state = match ? `match-${out.verdict}` : "mismatch";
    cells[id].title = `${id}: expected ${expected}, got ${out.verdict}, integrity ${out.integrity}`;
    setProgress(index + 1, ids.length);
    await new Promise((resolve) => setTimeout(resolve, 0));
  }
  setProgress(ids.length, ids.length);

  const failed = results.filter((row) => !row.match);
  const counts = { ALLOW: 0, BLOCK: 0, REQUIRE_APPROVAL: 0 };
  for (const row of results) counts[row.actual] = (counts[row.actual] || 0) + 1;
  summary.textContent = failed.length === 0
    ? `${results.length}/${results.length} expected verdicts. Integrity passed on every envelope. Verdicts produced on this official corpus: ${counts.ALLOW} ALLOW, ${counts.BLOCK} BLOCK, ${counts.REQUIRE_APPROVAL} REQUIRE_APPROVAL. These counts describe this corpus only.`
    : `${results.length - failed.length}/${results.length} matched. ${failed.length} mismatch or integrity failure. Verdicts produced: ${counts.ALLOW} ALLOW, ${counts.BLOCK} BLOCK, ${counts.REQUIRE_APPROVAL} REQUIRE_APPROVAL.`;
  $("run-all").disabled = false;
  return {
    total: results.length,
    passed: results.length - failed.length,
    failed: failed.length,
    failures: failed,
    results,
    counts,
  };
}

function applyTheme(theme) {
  const root = document.documentElement;
  if (theme === "light" || theme === "dark") {
    root.dataset.theme = theme;
  } else {
    delete root.dataset.theme;
    theme = window.matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark";
  }
  const next = theme === "dark" ? "light" : "dark";
  $("theme-toggle").textContent = `Switch to ${next} theme`;
  $("theme-toggle").setAttribute("aria-pressed", theme === "dark" ? "true" : "false");
}

function initTheme() {
  const saved = localStorage.getItem("asc-theme");
  applyTheme(saved === "light" || saved === "dark" ? saved : "");
  $("theme-toggle").addEventListener("click", () => {
    const current = document.documentElement.dataset.theme
      || (window.matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark");
    const next = current === "dark" ? "light" : "dark";
    localStorage.setItem("asc-theme", next);
    applyTheme(next);
  });
}

async function fetchText(url) {
  const response = await fetch(url);
  if (!response.ok) throw new Error(`Failed to fetch ${url}: ${response.status}`);
  return response.text();
}

async function fetchBytes(url) {
  const response = await fetch(url);
  if (!response.ok) throw new Error(`Failed to fetch ${url}: ${response.status}`);
  return new Uint8Array(await response.arrayBuffer());
}

async function startFallback(message) {
  const started = performance.now();
  setProgress(30, "Loading precomputed official corpus results…", "loading");
  const raw = await fetchText("./data/precomputed.json");
  const pack = JSON.parse(raw);
  state.precomputed = pack;
  state.engine = null;
  state.info = pack.info;
  demo.evaluateTrace = null;
  demo.evaluateScenario = function (scenarioId) {
    return pack.results[scenarioId];
  };
  demo.runCorpus = function () { return pack.corpus_run; };
  demo.tamperAndVerify = null;
  demo.runAll = runAllWithProgress;
  fillPresetSelect();
  renderFilters();
  renderGallery();
  bindCommonUi(false);
  selectScenario(state.info.default_preset, true);
  setBusy(false);
  $("evaluate").disabled = true;
  $("recompute").disabled = true;
  $("tamper").disabled = true;
  $("run-all").disabled = false;
  $("preset").disabled = false;
  $("trace").disabled = false;
  $("policy").disabled = false;
  $("copy-envelope").disabled = false;
  $("download-envelope").disabled = false;
  const note = $("note");
  if (note && pack.presets[state.info.default_preset]) {
    note.textContent = pack.presets[state.info.default_preset].note + " Custom evaluation needs the live runtime.";
  }
  state.loadMs = Math.round(performance.now() - started);
  document.body.dataset.loadMs = String(state.loadMs);
  document.body.dataset.ascMode = "fallback";
  setProgress(100, message, "fallback");
  return { loadMs: state.loadMs, version: state.info.version, scenarioCount: state.info.scenario_count, mode: "fallback" };
}

let uiBound = false;
function bindCommonUi(live) {
  if (uiBound) return;
  uiBound = true;
  $("preset").addEventListener("change", function () { selectScenario($("preset").value, false); });
  $("evaluate").addEventListener("click", function () { evaluateCurrent(); });
  $("recompute").addEventListener("click", function () {
    if (!state.engine) return;
    const out = parsePyJson(state.engine.recompute_digest($("policy").value));
    $("policy").value = out.policy;
    $("digest-message").hidden = false;
    $("digest-message").textContent = out.message;
  });
  $("copy-envelope").addEventListener("click", async function () {
    const status = $("copy-status");
    try {
      await navigator.clipboard.writeText(state.lastEnvelope || $("envelope").textContent);
      status.hidden = false;
      status.textContent = "Envelope JSON copied.";
    } catch (error) {
      status.hidden = false;
      status.textContent = "Copy failed: " + formatError(error);
    }
  });
  $("download-envelope").addEventListener("click", function () {
    const blob = new Blob([state.lastEnvelope || $("envelope").textContent], { type: "application/json" });
    const link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    link.download = "asc-envelope-" + (state.currentId || "custom") + ".json";
    link.click();
    URL.revokeObjectURL(link.href);
  });
  $("tamper").addEventListener("click", function () {
    if (!demo.tamperAndVerify) return;
    const result = demo.tamperAndVerify(state.originalEnvelope || state.lastEnvelope, "reason");
    $("tamper-result").hidden = false;
    $("restore-envelope").hidden = false;
    if (result.detected) {
      $("tamper-result").textContent = "The library rejected the edited envelope. verify_envelope: " + result.error;
      $("envelope").textContent = result.envelope_text;
      state.lastEnvelope = result.envelope_text;
      const envMeta = $("envelope-meta");
      envMeta.innerHTML = "";
      envMeta.appendChild(chip("Integrity check failed", "integrity-bad"));
      envMeta.appendChild(chip("Field tampered: reason", ""));
    } else {
      $("tamper-result").textContent = "The verifier did not reject this edit. The tamper control was not shown as a successful detection.";
    }
  });
  $("restore-envelope").addEventListener("click", function () {
    $("envelope").textContent = state.originalEnvelope;
    state.lastEnvelope = state.originalEnvelope;
    $("tamper-result").hidden = true;
    $("restore-envelope").hidden = true;
    const envMeta = $("envelope-meta");
    envMeta.innerHTML = "";
    envMeta.appendChild(chip("Integrity check passed", "integrity-ok"));
    envMeta.appendChild(chip("Hash-checked, not signed", ""));
  });
  $("run-all").addEventListener("click", function () {
    runAllWithProgress();
  });
}

async function boot() {
  const started = performance.now();
  openExternalLinks();
  initTheme();
  if (forceFallback() || !canRunLiveRuntime()) {
    return startFallback(FALLBACK_MESSAGE);
  }
  setProgress(8, "Loading Pyodide 0.29.5…");

  const { loadPyodide } = await import(`${PYODIDE_INDEX}pyodide.mjs`);
  setProgress(28, "Starting the in-browser Python runtime…");
  const pyodide = await loadPyodide({ indexURL: PYODIDE_INDEX });
  state.pyodide = pyodide;

  setProgress(48, "Loading PyYAML and the bundled ASC v0.2.1 wheel…");
  await pyodide.loadPackage(["pyyaml"]);

  const [wheel, engineSrc, policyYaml, corpusJson] = await Promise.all([
    fetchBytes(ASC_WHEEL),
    fetchText("./engine.py"),
    fetchText("./data/demo-agent.policy.yaml"),
    fetchText("./data/corpus.json"),
  ]);

  const mkdir = (path) => {
    const info = pyodide.FS.analyzePath(path);
    if (!info.exists) pyodide.FS.mkdir(path);
  };
  mkdir("/asc-pkg");
  mkdir("/asc-data");
  pyodide.FS.writeFile("/tmp/agent_security_contract-0.2.1-py3-none-any.whl", wheel);
  pyodide.FS.writeFile("/asc-pkg/engine.py", engineSrc);
  pyodide.FS.writeFile("/asc-data/policy.yaml", policyYaml);
  pyodide.FS.writeFile("/asc-data/corpus.json", corpusJson);

  setProgress(76, "Importing the Agent Security Contract library…");
  pyodide.runPython(`
import os, sys, zipfile, pathlib
os.environ["ASC_COMMIT_SHA"] = "${ASC_COMMIT}"
dest = pathlib.Path("/asc-pkg")
with zipfile.ZipFile("/tmp/agent_security_contract-0.2.1-py3-none-any.whl") as z:
    z.extractall(dest)
if "/asc-pkg" not in sys.path:
    sys.path.insert(0, "/asc-pkg")
import asc
if asc.__version__ != "0.2.1":
    raise RuntimeError(f"unexpected ASC version: {asc.__version__}")
import engine
policy = pathlib.Path("/asc-data/policy.yaml").read_text(encoding="utf-8")
corpus = pathlib.Path("/asc-data/corpus.json").read_text(encoding="utf-8")
INIT_INFO = engine.init(policy, corpus)
`);

  const engine = pyodide.pyimport("engine");
  state.engine = engine;
  state.info = parsePyJson(pyodide.globals.get("INIT_INFO"));

  demo.evaluateTrace = (scenarioId, traceText, policyText) => parsePyJson(engine.evaluate_trace(scenarioId, traceText, policyText));
  demo.evaluateScenario = (scenarioId) => parsePyJson(engine.evaluate_scenario(scenarioId));
  demo.runCorpus = () => parsePyJson(engine.run_corpus());
  demo.tamperAndVerify = (envelopeText, field = "reason") => parsePyJson(engine.tamper_and_verify(envelopeText, field));
  demo.runAll = runAllWithProgress;

  fillPresetSelect();
  renderFilters();
  renderGallery();
  bindCommonUi(true);

  selectScenario(state.info.default_preset, true);
  setBusy(false);
  document.body.dataset.ascMode = "live";

  state.loadMs = Math.round(performance.now() - started);
  document.body.dataset.loadMs = String(state.loadMs);
  setProgress(
    100,
    `Ready in ${(state.loadMs / 1000).toFixed(1)}s. Pyodide ${PYODIDE_VERSION} (Python 3.13.2), ASC v${state.info.version}. Evaluation stays in this browser.`,
    "ready",
  );
  return { loadMs: state.loadMs, version: state.info.version, scenarioCount: state.info.scenario_count };
}

demo.ready = boot().catch((error) => {
  console.error(error);
  return startFallback(fallbackMessage(error)).catch((fallbackError) => {
    console.error(fallbackError);
    setProgress(100, "Failed to start the in-browser runtime, and precomputed results could not be loaded. Open this page on a current desktop browser.", "error");
    throw error;
  });
});