Exploit database

GH-786074ac4c791dc9be6cc1a41bc35b4e

royaleybovich/cve-2026-3854-lab

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-3854

2 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars.

Repository files2

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

services/portal/static/app.js

JavaScript · 44,319 bytes
(() => {
  'use strict';

  const POLL_INTERVAL = 2500;
/* SPDX-FileCopyrightText: 2026 Royal Leybovich */
/* SPDX-License-Identifier: GPL-3.0-or-later */

const THEME_KEY = 'flagship-theme';
  const THEME_CHOICES = ['system', 'light', 'dark'];
  const root = document.documentElement;
  const systemTheme = window.matchMedia('(prefers-color-scheme: dark)');
  let currentThemePreference = 'system';

  function storedTheme() {
    try {
      const choice = window.localStorage.getItem(THEME_KEY);
      return THEME_CHOICES.includes(choice) ? choice : 'system';
    } catch {
      return 'system';
    }
  }

  function resolvedTheme(choice) {
    return choice === 'system' ? (systemTheme.matches ? 'dark' : 'light') : choice;
  }

  function applyTheme(choice, persist = false) {
    const preference = THEME_CHOICES.includes(choice) ? choice : 'system';
    const resolved = resolvedTheme(preference);
    currentThemePreference = preference;
    root.dataset.theme = resolved;
    root.dataset.themePreference = preference;
    root.style.colorScheme = resolved;
    const themeColor = document.querySelector('[data-theme-color]');
    if (themeColor) themeColor.content = resolved === 'dark' ? '#0b1117' : '#f4f7f9';
    if (persist) {
      try {
        window.localStorage.setItem(THEME_KEY, preference);
      } catch {
        // A private browsing policy may make localStorage unavailable. The
        // selected theme still applies for the lifetime of this page.
      }
    }
    updateThemeToggle(preference);
    return resolved;
  }

  function updateThemeToggle(preference) {
    const toggle = document.querySelector('[data-theme-toggle]');
    if (!toggle) return;
    const next = THEME_CHOICES[(THEME_CHOICES.indexOf(preference) + 1) % THEME_CHOICES.length];
    const names = {system: 'System', light: 'Light', dark: 'Dark'};
    toggle.dataset.themePreference = preference;
    toggle.setAttribute('aria-label', `${names[preference]} theme. Switch to ${names[next].toLowerCase()} theme`);
    toggle.setAttribute('title', `Theme: ${names[preference]}`);
    toggle.setAttribute('aria-pressed', String(resolvedTheme(preference) === 'dark'));
    const label = toggle.querySelector('[data-theme-label]');
    if (label) label.textContent = names[preference];
  }

  // The inline head script can call this before app.js loads on subsequent
  // pages, avoiding a flash of the wrong theme.
  window.applyFlagshipTheme = applyTheme;
  currentThemePreference = storedTheme();
  applyTheme(currentThemePreference);

  const pollers = new Set();

  function createPoller(task, {onPause, onResume} = {}) {
    let timer = null;
    let running = false;
    let rerun = false;

    const schedule = () => {
      window.clearTimeout(timer);
      timer = null;
      if (!document.hidden) timer = window.setTimeout(run, POLL_INTERVAL);
    };

    const run = async () => {
      if (document.hidden) return;
      if (running) {
        rerun = true;
        return;
      }
      running = true;
      try {
        await task();
      } finally {
        running = false;
        if (rerun && !document.hidden) {
          rerun = false;
          void run();
        } else {
          schedule();
        }
      }
    };

    const poller = {
      pause() {
        window.clearTimeout(timer);
        timer = null;
        onPause?.();
      },
      resume() {
        onResume?.();
        void run();
      },
      run,
    };
    pollers.add(poller);
    if (!document.hidden) void run();
    return poller;
  }

  document.addEventListener('visibilitychange', () => {
    pollers.forEach((poller) => document.hidden ? poller.pause() : poller.resume());
  });

  async function getJSON(url, options = {}) {
    const response = await window.fetch(url, {cache: 'no-store', ...options});
    if (!response.ok) throw new Error(`Request failed with HTTP ${response.status}`);
    if (response.status === 204) return null;
    return response.json();
  }

  function redactProof(value) {
    return String(value ?? '').replace(/FLAG\{[^}\r\n]+\}/g, 'Proof received');
  }

  function escapeMarkup(value) {
    return String(value ?? '').replace(/[&<>'"]/g, (character) => ({
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      "'": '&#39;',
      '"': '&quot;',
    })[character]);
  }

  function escapeHTML(value) {
    return escapeMarkup(redactProof(value));
  }

  function syntaxRules(language) {
    if (language === 'go') {
      return [
        ['comment', /\/\*[\s\S]*?\*\/|\/\/[^\n]*/y],
        ['string', /"(?:\\.|[^"\\])*"|`[^`]*`|'(?:\\.|[^'\\])*'/y],
        ['keyword', /\b(?:break|case|chan|const|continue|default|defer|else|fallthrough|for|func|go|goto|if|import|interface|map|package|range|return|select|struct|switch|type|var)\b/y],
        ['type', /\b(?:any|bool|byte|complex64|complex128|error|float32|float64|int|int8|int16|int32|int64|rune|string|uint|uint8|uint16|uint32|uint64|uintptr)\b/y],
        ['literal', /\b(?:true|false|iota|nil)\b/y],
        ['number', /\b(?:0x[\da-fA-F]+|\d+(?:\.\d+)?)\b/y],
        ['function', /\b[A-Za-z_]\w*(?=\s*\()/y],
        ['operator', /:=|==|!=|<=|>=|&&|\|\||\+\+|--|[=+\-*\/%<>!&|]/y],
      ];
    }
    if (['bash', 'shell', 'sh'].includes(language)) {
      return [
        ['comment', /#[^\n]*/y],
        ['string', /'(?:[^']*)'|"(?:\\.|[^"\\])*"/y],
        ['variable', /\$\{[^}]+\}|\$\([^)]+\)|\$[A-Za-z_][A-Za-z0-9_]*/y],
        ['flag', /--[A-Za-z0-9][A-Za-z0-9-]*(?:=[^\s]+)?|-[A-Za-z]\b/y],
        ['keyword', /\b(?:case|do|done|elif|else|esac|fi|for|function|if|in|then|until|while)\b/y],
        ['command', /\b(?:bash|cd|curl|date|docker|git|jq|mkdir|nano|printf|pwd|touch)\b/y],
        ['variable', /\b[A-Z_][A-Z0-9_]*(?==)/y],
        ['number', /\b\d+\b/y],
        ['operator', /&&|\|\||[|;=]/y],
      ];
    }
    return [];
  }

  function highlightedMarkup(source, language) {
    const rules = syntaxRules(language);
    if (!rules.length) return escapeMarkup(source);
    let result = '';
    let index = 0;
    while (index < source.length) {
      let matched = false;
      for (const [token, pattern] of rules) {
        pattern.lastIndex = index;
        const match = pattern.exec(source);
        if (!match) continue;
        result += `<span class="syntax-${token}">${escapeMarkup(match[0])}</span>`;
        index += match[0].length;
        matched = true;
        break;
      }
      if (!matched) {
        result += escapeMarkup(source[index]);
        index += 1;
      }
    }
    return result;
  }

  function initializeSyntaxHighlighting(scope = document) {
    scope.querySelectorAll('code[data-language]:not([data-highlighted])').forEach((code) => {
      const language = String(code.dataset.language || 'text').toLowerCase();
      code.innerHTML = highlightedMarkup(code.textContent || '', language);
      code.dataset.highlighted = 'true';
    });
  }

  function slug(value) {
    return String(value ?? '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '') || 'unknown';
  }

  function displayValue(value) {
    if (value === null || value === undefined || value === '') return '—';
    if (typeof value === 'object') return JSON.stringify(value, null, 2);
    return String(value);
  }

  function firstDefined(...values) {
    return values.find((value) => value !== undefined && value !== null);
  }

  function objectEntries(value) {
    return value && typeof value === 'object' && !Array.isArray(value) ? Object.entries(value) : [];
  }

  function arrayValue(value) {
    if (value === undefined || value === null) return [];
    return Array.isArray(value) ? value : [value];
  }

  function formatTime(value) {
    if (!value) return 'Time unavailable';
    const parsed = new Date(value);
    if (Number.isNaN(parsed.getTime())) return String(value);
    return parsed.toLocaleString([], {dateStyle: 'medium', timeStyle: 'medium'});
  }

  function statusMarkup(kind, status, label) {
    return `<span class="push-status ${escapeHTML(kind)} ${escapeHTML(slug(status))}"><span aria-hidden="true"></span>${escapeHTML(label || status || 'Unknown')}</span>`;
  }

  function definitionMarkup(label, value, code = false) {
    const rendered = escapeHTML(displayValue(value));
    return `<div><dt>${escapeHTML(label)}</dt><dd>${code ? `<code>${rendered}</code>` : rendered}</dd></div>`;
  }

  function fieldRows(fields, ownership) {
    const entries = objectEntries(fields);
    if (!entries.length) return '<p class="push-empty">No fields recorded.</p>';
    return `<dl class="push-field-list">${entries.map(([name, value]) => `<div><dt><code>${escapeHTML(name)}</code>${ownership ? `<span>${escapeHTML(ownership)}</span>` : ''}</dt><dd><code>${escapeHTML(displayValue(value))}</code></dd></div>`).join('')}</dl>`;
  }

  function directiveMarkup(directive) {
    if (typeof directive !== 'object' || directive === null) return `<li><code>${escapeHTML(directive)}</code></li>`;
    const name = firstDefined(directive.name, directive.directive, 'Unknown directive');
    const value = firstDefined(directive.value, directive.argument);
    const result = firstDefined(directive.result, directive.status, 'recognized');
    return `<li><span><code>${escapeHTML(name)}</code>${value !== undefined ? `<code>${escapeHTML(displayValue(value))}</code>` : ''}</span><strong class="directive-result ${escapeHTML(slug(result))}">${escapeHTML(result)}</strong></li>`;
  }

  function resultMarkup(result) {
    if (typeof result !== 'object' || result === null) return `<li>${escapeHTML(result)}</li>`;
    const label = firstDefined(result.label, result.message, result.result, result.name, 'Result');
    const value = firstDefined(result.value, result.detail);
    const state = firstDefined(result.state, result.status, result.code);
    return `<li${state ? ` class="${escapeHTML(slug(state))}"` : ''}><strong>${escapeHTML(label)}</strong>${value !== undefined ? `<span>${escapeHTML(displayValue(value))}</span>` : ''}</li>`;
  }

  function serializerMarkup(serializer) {
    if (!serializer || typeof serializer !== 'object') return '';
    const trusted = firstDefined(serializer.trusted_fields, serializer.server_fields, serializer.configuration, {});
    const controlled = firstDefined(serializer.push_option_fields, serializer.user_fields, serializer.option_fields, {});
    const serialized = firstDefined(serializer.serialized_value, serializer.value, serializer.state);
    return `<details class="push-detail serializer-detail" data-detail-key="serializer" open>
      <summary><span>Serialized State</span><small>How ForgeDock combined the values</small></summary>
      <div class="push-detail-body">
        <div class="field-groups">
          <section><h4>Server-generated configuration</h4>${fieldRows(trusted, 'Server generated')}</section>
          <section><h4>User-controlled options</h4>${fieldRows(controlled, 'User controlled')}</section>
        </div>
        ${serialized !== undefined ? `<div class="serialized-value"><span>Exact serialized value</span><pre><code>${escapeHTML(displayValue(serialized))}</code></pre></div>` : ''}
        ${serializer.delimiter !== undefined ? `<p class="delimiter-note">Field delimiter <code>${escapeHTML(serializer.delimiter)}</code></p>` : ''}
      </div>
    </details>`;
  }

  function normalizedDuplicate(duplicate, valuesSeen, winningValues) {
    if (typeof duplicate === 'object' && duplicate !== null) {
      const key = firstDefined(duplicate.key, duplicate.name, duplicate.field, 'unknown');
      const history = arrayValue(firstDefined(duplicate.values, duplicate.values_seen, valuesSeen[key], []));
      return {
        key,
        original: firstDefined(duplicate.original, duplicate.original_value, history[0]),
        injected: firstDefined(duplicate.injected, duplicate.injected_value, history.length > 1 ? history.slice(1) : []),
        winner: firstDefined(duplicate.winner, duplicate.winning, duplicate.winning_value, winningValues[key], history.at(-1)),
      };
    }
    const history = arrayValue(valuesSeen[duplicate]);
    return {
      key: duplicate,
      original: history[0],
      injected: history.slice(1),
      winner: firstDefined(winningValues[duplicate], history.at(-1)),
    };
  }

  function parserMarkup(parser) {
    if (!parser || typeof parser !== 'object') return '';
    const winners = firstDefined(parser.winning_values, parser.parsed_fields, parser.fields, {});
    const valuesSeen = firstDefined(parser.values_seen, parser.history, {});
    const duplicates = arrayValue(firstDefined(parser.duplicates, parser.duplicate_keys, []))
      .map((duplicate) => normalizedDuplicate(duplicate, valuesSeen, winners));
    return `<details class="push-detail parser-detail" data-detail-key="parser" open>
      <summary><span>Parsed Fields</span><small>Duplicate history and operational winners</small></summary>
      <div class="push-detail-body">
        <section><h4>Winning values</h4>${fieldRows(winners)}</section>
        <section><h4>Duplicate keys</h4>${duplicates.length ? `<div class="duplicate-list">${duplicates.map((duplicate) => `<article>
          <h5><code>${escapeHTML(duplicate.key)}</code></h5>
          <dl>${definitionMarkup('Original value', duplicate.original, true)}${definitionMarkup('Injected value', duplicate.injected, true)}${definitionMarkup('Winning value', duplicate.winner, true)}</dl>
        </article>`).join('')}</div>` : '<p class="push-empty">No duplicate keys were parsed.</p>'}</section>
      </div>
    </details>`;
  }

  function gateMarkup(name, gate) {
    const structured = gate && typeof gate === 'object' && !Array.isArray(gate) ? gate : {value: gate};
    const passed = firstDefined(structured.passed, structured.open, structured.satisfied);
    const status = firstDefined(structured.status, passed === true ? 'passed' : passed === false ? 'blocked' : 'observed');
    const label = firstDefined(structured.label, String(name).replaceAll('_', ' '));
    const value = firstDefined(structured.value, structured.effective_value, structured.detail);
    return `<li class="${escapeHTML(slug(status))}"><span aria-hidden="true">${passed === true ? '✓' : passed === false ? '○' : '·'}</span><div><strong>${escapeHTML(label)}</strong>${value !== undefined ? `<code>${escapeHTML(displayValue(value))}</code>` : ''}</div><small>${escapeHTML(status)}</small></li>`;
  }

  function executionMarkup(execution) {
    if (!execution || typeof execution !== 'object') return '';
    const gatesValue = firstDefined(execution.gates, execution.execution_gates, {});
    const gates = Array.isArray(gatesValue)
      ? gatesValue.map((gate, index) => gateMarkup(firstDefined(gate?.name, gate?.key, `gate_${index + 1}`), gate))
      : objectEntries(gatesValue).map(([name, gate]) => gateMarkup(name, gate));
    const hookRoot = firstDefined(execution.hook_root, execution.root);
    const manifest = firstDefined(execution.hook_manifest, execution.manifest);
    const resolvedPath = firstDefined(execution.resolved_path, execution.path);
    const result = firstDefined(execution.result, execution.visible_result, execution.outcome);
    return `<details class="push-detail execution-detail" data-detail-key="execution" open>
      <summary><span>Execution Decision</span><small>Each condition must be satisfied</small></summary>
      <div class="push-detail-body">
        ${gates.length ? `<ol class="execution-gates">${gates.join('')}</ol>` : '<p class="push-empty">No execution gates were evaluated.</p>'}
        <dl class="execution-values">
          ${hookRoot !== undefined ? definitionMarkup('Hook root', hookRoot, true) : ''}
          ${manifest !== undefined ? definitionMarkup('Hook manifest', manifest, true) : ''}
          ${resolvedPath !== undefined ? definitionMarkup('Resolved path', resolvedPath, true) : ''}
          ${result !== undefined ? definitionMarkup('Result', result) : ''}
        </dl>
      </div>
    </details>`;
  }

  function attemptMarkup(attempt, level, openByDefault = false) {
    const identifier = firstDefined(attempt.id, attempt.trace_id, 'unknown');
    const number = firstDefined(attempt.number, attempt.attempt_number, '—');
    const occurredAt = firstDefined(attempt.occurred_at, attempt.created_at, attempt.time);
    const repositoryValue = firstDefined(attempt.repository?.full_name, attempt.repository, attempt.repo, 'Repository unavailable');
    const commitValue = firstDefined(attempt.commit?.short_oid, attempt.commit?.oid, attempt.commit, attempt.short_commit, 'Commit unavailable');
    const git = attempt.git || {};
    const gitStatus = firstDefined(git.status, attempt.git_status, 'accepted');
    const gitLabel = firstDefined(git.label, attempt.git_label, gitStatus === 'rejected' ? 'Push rejected' : 'Push accepted');
    const processing = attempt.processing || {};
    const processingStatus = firstDefined(processing.state, processing.status, attempt.processing_status, attempt.status, 'processing');
    const processingLabel = firstDefined(processing.label, processing.summary, attempt.processing_label, 'ForgeDock processing');
    const pushOptions = attempt.push_options || {};
    const rawOptions = arrayValue(firstDefined(pushOptions.raw, pushOptions.raw_push_options, attempt.raw_push_options, []));
    const directives = arrayValue(firstDefined(pushOptions.recognized_directives, pushOptions.recognized, attempt.recognized_directives, []));
    const results = arrayValue(firstDefined(attempt.visible_results, attempt.visible_result, []));
    const serializer = firstDefined(attempt.serializer, attempt.serialized_state);
    const parser = firstDefined(attempt.parser, attempt.parsed_state);
    const execution = firstDefined(attempt.execution, attempt.execution_state);
    const confirmation = firstDefined(attempt.confirmation, attempt.success_confirmation);

    return `<article class="push-card" data-attempt-id="${escapeHTML(identifier)}">
      <details data-detail-key="attempt"${openByDefault ? ' open' : ''}>
        <summary class="push-card-summary">
          <span class="attempt-number">Attempt ${escapeHTML(number)}</span>
          <span class="attempt-time">${escapeHTML(formatTime(occurredAt))}</span>
          <span class="push-statuses">${statusMarkup('git-status', gitStatus, gitLabel)}${statusMarkup('processing-status', processingStatus, processingLabel)}</span>
        </summary>
        <div class="push-card-body">
          ${confirmation ? `<div class="payload-success-banner" role="status"><span aria-hidden="true">✓</span><div><strong>${escapeHTML(confirmation.title || 'Payload worked')}</strong><p>${escapeHTML(confirmation.detail || 'ForgeDock reached the expected learning milestone.')}</p></div></div>` : ''}
          <dl class="push-card-meta">${definitionMarkup('Repository', repositoryValue, true)}${definitionMarkup('Commit', commitValue, true)}</dl>
          <section class="push-options"><h4>Push options</h4>${rawOptions.length ? `<ul>${rawOptions.map((option) => `<li><code>${escapeHTML(displayValue(option))}</code></li>`).join('')}</ul>` : '<p class="push-empty">No push options were provided.</p>'}</section>
          <section class="recognized-directives"><h4>Recognized product directives</h4>${directives.length ? `<ul>${directives.map(directiveMarkup).join('')}</ul>` : '<p class="push-empty">No product directives were recognized.</p>'}</section>
          ${results.length ? `<section class="visible-results"><h4>Visible result</h4><ul>${results.map(resultMarkup).join('')}</ul></section>` : ''}
          ${level >= 2 ? serializerMarkup(serializer) : ''}
          ${level >= 3 ? parserMarkup(parser) : ''}
          ${level >= 4 ? executionMarkup(execution) : ''}
        </div>
      </details>
    </article>`;
  }

  function cardInteractionState(card) {
    const details = [...card.querySelectorAll('details')];
    const controls = [...card.querySelectorAll('input, textarea, select, button, a, summary')];
    const activeIndex = card.contains(document.activeElement) ? controls.indexOf(document.activeElement) : -1;
    return {
      opened: new Set(details.filter((detail) => detail.open).map((detail, index) => detail.dataset.detailKey || String(index))),
      values: controls.map((control) => ('value' in control ? control.value : undefined)),
      activeIndex,
    };
  }

  function restoreCardInteraction(card, state) {
    const details = [...card.querySelectorAll('details')];
    details.forEach((detail, index) => {
      detail.open = state.opened.has(detail.dataset.detailKey || String(index));
    });
    const controls = [...card.querySelectorAll('input, textarea, select, button, a, summary')];
    controls.forEach((control, index) => {
      if (state.values[index] !== undefined && 'value' in control) control.value = state.values[index];
    });
    if (state.activeIndex >= 0) controls[state.activeIndex]?.focus({preventScroll: true});
  }

  function initializeCopyButtons() {
    document.querySelectorAll('[data-copy]').forEach((button) => button.addEventListener('click', async () => {
      try {
        await navigator.clipboard.writeText(button.dataset.copy || '');
        const label = button.textContent;
        button.textContent = 'Copied';
        button.classList.add('copied');
        window.setTimeout(() => {
          button.textContent = label;
          button.classList.remove('copied');
        }, 1800);
      } catch {
        button.textContent = 'Select and copy';
      }
    }));
  }

  function initializeLegacyInteractions() {
    document.querySelectorAll('[data-tab]').forEach((tab) => tab.addEventListener('click', () => {
      const container = tab.closest('article') || document;
      container.querySelectorAll('[data-tab]').forEach((candidate) => candidate.setAttribute('aria-selected', String(candidate === tab)));
      container.querySelectorAll('.tab-panel').forEach((panel) => {
        const active = panel.id === tab.dataset.tab;
        panel.classList.toggle('active', active);
        panel.hidden = !active;
      });
    }));
    document.querySelectorAll('[data-prediction]').forEach((card) => card.querySelectorAll('[data-prediction-choice]').forEach((button) => button.addEventListener('click', () => {
      const correct = button.dataset.predictionChoice === card.dataset.answer;
      card.querySelectorAll('button').forEach((choice) => choice.classList.remove('correct', 'learning'));
      button.classList.add(correct ? 'correct' : 'learning');
      const feedback = card.querySelector('.prediction-feedback');
      if (feedback) feedback.textContent = `${correct ? 'That is correct. ' : 'Good prediction to test. '}${card.dataset.explanation || ''}`;
    })));
  }

  function initializeKnowledgeChecks() {
    document.querySelectorAll('[data-knowledge-check]').forEach((check) => {
      const feedback = check.querySelector('[data-knowledge-feedback]');
      const inputs = [...check.querySelectorAll('input[type="radio"], input[type="checkbox"]')];
      const correct = String(check.dataset.correct || '').split(',').filter(Boolean).sort();

      const clearEvaluation = () => {
        check.classList.remove('is-correct', 'is-incorrect');
        check.querySelectorAll('.knowledge-option').forEach((option) => option.classList.remove('is-answer', 'is-wrong'));
      };

      inputs.forEach((input) => input.addEventListener('change', clearEvaluation));
      check.addEventListener('submit', (event) => {
        event.preventDefault();
        clearEvaluation();
        const selected = inputs.filter((input) => input.checked).map((input) => input.value).sort();
        if (!selected.length) {
          if (feedback) feedback.textContent = 'Choose at least one answer first.';
          inputs[0]?.focus();
          return;
        }
        const matches = selected.length === correct.length && selected.every((value, index) => value === correct[index]);
        check.classList.add(matches ? 'is-correct' : 'is-incorrect');
        inputs.forEach((input) => {
          const option = input.closest('.knowledge-option');
          option?.classList.toggle('is-answer', correct.includes(input.value));
          option?.classList.toggle('is-wrong', input.checked && !correct.includes(input.value));
        });
        if (feedback) {
          feedback.textContent = `${matches ? 'Correct. ' : 'Not quite. Correct answer: '}${check.dataset.answer || ''}`;
          feedback.focus?.({preventScroll: true});
        }
      });
    });
  }

  function initializeResearchDialogs() {
    const dialogs = new Map(
      [...document.querySelectorAll('[data-challenge-dialog]')]
        .map((dialog) => [String(dialog.dataset.challengeDialog), dialog]),
    );

    const openDialog = (id, trigger) => {
      const dialog = dialogs.get(String(id));
      if (!dialog || dialog.open) return;
      if (trigger) dialog.dataset.returnFocus = trigger.dataset.openChallenge || '';
      dialog.showModal();
    };

    const closeDialog = (dialog) => {
      if (!dialog?.open) return;
      dialog.close();
      const triggerId = dialog.dataset.returnFocus;
      if (triggerId) document.querySelector(`[data-open-challenge="${window.CSS?.escape ? window.CSS.escape(triggerId) : triggerId}"]`)?.focus();
    };

    document.querySelectorAll('[data-open-challenge]').forEach((button) => {
      button.addEventListener('click', () => openDialog(button.dataset.openChallenge, button));
    });
    dialogs.forEach((dialog) => {
      dialog.querySelectorAll('[data-close-challenge]').forEach((button) => button.addEventListener('click', () => closeDialog(dialog)));
      dialog.querySelectorAll('[data-switch-challenge]').forEach((button) => button.addEventListener('click', () => {
        const next = button.dataset.switchChallenge;
        dialog.close();
        openDialog(next, document.querySelector(`[data-open-challenge="${next}"]`));
      }));
      dialog.addEventListener('click', (event) => {
        const bounds = dialog.getBoundingClientRect();
        const outside = event.clientX < bounds.left || event.clientX > bounds.right || event.clientY < bounds.top || event.clientY > bounds.bottom;
        if (outside) closeDialog(dialog);
      });
    });
    const automatic = document.querySelector('[data-challenge-dialog][data-auto-open]');
    if (automatic) window.requestAnimationFrame(() => openDialog(automatic.dataset.challengeDialog));
  }

  function initializeTheme() {
    const toggle = document.querySelector('[data-theme-toggle]');
    updateThemeToggle(currentThemePreference);
    toggle?.addEventListener('click', () => {
      const current = currentThemePreference;
      const next = THEME_CHOICES[(THEME_CHOICES.indexOf(current) + 1) % THEME_CHOICES.length];
      applyTheme(next, true);
    });
    const systemChanged = () => {
      if (currentThemePreference === 'system') applyTheme('system');
    };
    if (systemTheme.addEventListener) systemTheme.addEventListener('change', systemChanged);
    else systemTheme.addListener(systemChanged);
  }

  function initializeReadiness() {
    const readiness = document.querySelector('[data-readiness]');
    if (!readiness) return;
    const poll = async () => {
      try {
        const data = await getJSON('/api/readiness');
        arrayValue(data.services).forEach((service) => {
          const row = [...readiness.querySelectorAll('[data-service-name]')].find((candidate) => candidate.dataset.serviceName === String(service.name));
          if (!row) return;
          const dot = row.querySelector('.status-dot');
          const label = row.querySelector('.status-label');
          const detail = row.querySelector('small');
          if (dot) dot.className = `status-dot ${slug(service.state)}`;
          if (label) {
            label.className = `status-label ${slug(service.state)}`;
            label.textContent = service.label;
          }
          if (detail) detail.textContent = service.detail;
        });
        const baseline = document.querySelector('[data-baseline-state]');
        const unlock = document.querySelector('[data-lesson-unlock]');
        if (data.baseline && baseline && baseline.dataset.ready !== 'true') {
          baseline.dataset.ready = 'true';
          baseline.innerHTML = '<div class="alert success"><strong>✓ Push accepted</strong><span>Baseline observed. Lesson 1 is ready.</span></div>';
          if (unlock) unlock.innerHTML = '<a class="button primary full" href="/guided/level/1">Begin Lesson 1</a>';
        }
      } catch {
        // Existing service rows retain their last-known state during a brief
        // readiness outage instead of flickering between states.
      }
    };
    const poller = createPoller(poll);
    readiness.querySelector('[data-check-readiness]')?.addEventListener('click', () => void poller.run());
  }

  function initializeRepository() {
    const repositoryState = document.querySelector('[data-repository-state]');
    const createRepository = document.querySelector('[data-create-repository]');
    if (!repositoryState && !createRepository) return;

    const showRepository = (data) => {
      if (!repositoryState) return;
      repositoryState.className = data.ready ? 'alert success' : 'inline-note';
      repositoryState.innerHTML = data.ready
        ? '<strong>✓ Repository ready</strong><span>The provided clone commands now match devuser/learn-lab.</span>'
        : 'Repository not created yet. Choose Create devuser/learn-lab before cloning.';
      if (createRepository) {
        createRepository.disabled = Boolean(data.ready);
        createRepository.textContent = data.ready ? 'Repository ready' : 'Create devuser/learn-lab';
      }
    };

    const checkRepository = async () => {
      try {
        showRepository(await getJSON('/api/learn-repository'));
      } catch {
        if (repositoryState) repositoryState.textContent = 'Could not verify ForgeDock. Try Check now.';
      }
    };
    const poller = createPoller(checkRepository);

    createRepository?.addEventListener('click', async () => {
      createRepository.disabled = true;
      createRepository.textContent = 'Creating…';
      try {
        showRepository(await getJSON('/api/learn-repository', {method: 'POST'}));
      } catch {
        createRepository.disabled = false;
        createRepository.textContent = 'Try creation again';
        if (repositoryState) {
          repositoryState.className = 'alert error';
          repositoryState.textContent = 'ForgeDock could not create the repository. Confirm the local account is available.';
        }
      } finally {
        void poller.run();
      }
    });
  }

  function initializeLearning() {
    const workspace = document.querySelector('[data-learning-workspace]');
    if (!workspace) return;
    const level = Number(workspace.dataset.level || 1);
    const attemptList = workspace.querySelector('[data-attempt-list]') || document.querySelector('[data-attempt-list]');
    const attemptCount = workspace.querySelector('[data-attempt-count]') || document.querySelector('[data-attempt-count]');
    const pollStatus = workspace.querySelector('[data-poll-status]') || document.querySelector('[data-poll-status]');
    const progressList = document.querySelector('[data-progress-list]');
    const requirementsList = workspace.querySelector('[data-requirements-list]') || document.querySelector('[data-requirements-list]');
    const completionState = workspace.querySelector('.completion-state');
    const continueControl = workspace.querySelector('[data-continue]') || document.querySelector('[data-continue]');
    if (!attemptList) return;

    pollStatus?.setAttribute('aria-live', 'polite');
    pollStatus?.setAttribute('role', 'status');
    const attempts = new Map();
    const cards = new Map();
    let cursor = workspace.dataset.cursor || '';
    let firstAttemptResponse = true;
    let completionRequest = false;
    let completionRetryAfter = 0;

    const setPollStatus = (message, state = 'live') => {
      if (!pollStatus) return;
      pollStatus.textContent = message;
      pollStatus.dataset.state = state;
    };

    const sortAttempts = (left, right) => {
      const leftNumber = Number(firstDefined(left.number, left.attempt_number));
      const rightNumber = Number(firstDefined(right.number, right.attempt_number));
      if (Number.isFinite(leftNumber) && Number.isFinite(rightNumber) && leftNumber !== rightNumber) return rightNumber - leftNumber;
      const leftTime = Date.parse(firstDefined(left.occurred_at, left.created_at, left.time, 0));
      const rightTime = Date.parse(firstDefined(right.occurred_at, right.created_at, right.time, 0));
      return (Number.isNaN(rightTime) ? 0 : rightTime) - (Number.isNaN(leftTime) ? 0 : leftTime);
    };

    const renderAttempts = (payload) => {
      if (!payload || (payload.unchanged && !firstAttemptResponse)) return;
      const incoming = arrayValue(payload.attempts);
      const knownIdentifiers = new Set(attempts.keys());
      const incomingIdentifiers = new Set(incoming.map((attempt) => String(firstDefined(attempt.id, attempt.trace_id, ''))).filter(Boolean));
      const newIdentifiers = new Set([...incomingIdentifiers].filter((identifier) => !knownIdentifiers.has(identifier)));
      const scrollPosition = {x: window.scrollX, y: window.scrollY};
      let changed = false;

      [...attempts.keys()].forEach((identifier) => {
        if (incomingIdentifiers.has(identifier)) return;
        cards.get(identifier)?.remove();
        cards.delete(identifier);
        attempts.delete(identifier);
        changed = true;
      });

      incoming.forEach((attempt) => {
        const identifier = String(firstDefined(attempt.id, attempt.trace_id, ''));
        if (!identifier) return;
        const fingerprint = JSON.stringify(attempt);
        const oldAttempt = attempts.get(identifier);
        attempts.set(identifier, attempt);
        if (oldAttempt && JSON.stringify(oldAttempt) === fingerprint) return;

        const oldCard = cards.get(identifier);
        const interaction = oldCard ? cardInteractionState(oldCard) : null;
        const template = document.createElement('template');
        template.innerHTML = attemptMarkup(attempt, level, !oldCard && attempts.size === 1).trim();
        const newCard = template.content.firstElementChild;
        newCard.dataset.fingerprint = fingerprint;
        if (interaction) restoreCardInteraction(newCard, interaction);
        initializeSyntaxHighlighting(newCard);
        if (oldCard) oldCard.replaceWith(newCard);
        cards.set(identifier, newCard);
        changed = true;
      });

      const ordered = [...attempts.values()].sort(sortAttempts);
      ordered.forEach((attempt) => {
        const identifier = String(firstDefined(attempt.id, attempt.trace_id, ''));
        const card = cards.get(identifier);
        if (card) attemptList.append(card);
      });

      if (ordered.length && (firstAttemptResponse || newIdentifiers.size > 0)) {
        const newestIdentifier = String(firstDefined(ordered[0].id, ordered[0].trace_id, ''));
        cards.forEach((card, identifier) => {
          const topLevel = card.querySelector(':scope > details[data-detail-key="attempt"]');
          if (topLevel) topLevel.open = identifier === newestIdentifier;
        });
      }

      attemptList.querySelectorAll('[data-attempt-state], .push-empty-state').forEach((state) => state.remove());
      if (!attempts.size) {
        const empty = document.createElement('p');
        empty.className = 'push-empty-state';
        empty.dataset.attemptState = 'empty';
        empty.textContent = 'Waiting for your first push. Run the experiment above and this area will update automatically.';
        attemptList.append(empty);
      }
      if (attemptCount) {
        const total = Number(firstDefined(payload.total, attempts.size));
        attemptCount.textContent = total > attempts.size
          ? `${attempts.size} recent of ${total}`
          : `${total} ${total === 1 ? 'attempt' : 'attempts'}`;
      }
      attemptList.setAttribute('aria-busy', 'false');
      if (payload.cursor !== undefined && payload.cursor !== null) cursor = String(payload.cursor);
      firstAttemptResponse = false;
      if (changed) window.requestAnimationFrame(() => window.scrollTo(scrollPosition.x, scrollPosition.y));
    };

    const lessonStatus = (progress, id) => arrayValue(progress?.lessons).find((lesson) => Number(lesson.id) === Number(id));
    const completedIds = (progress) => new Set(arrayValue(progress?.completed).map((item) => Number(typeof item === 'object' ? item.id : item)));

    const requirementsMet = (progress) => {
      const lesson = lessonStatus(progress, level) || {};
      const state = progress?.state || {};
      const levelState = firstDefined(state[level], state[String(level)], state[`lesson_${level}`], {});
      const status = String(firstDefined(lesson.status, levelState.status, '')).toLowerCase();
      return lesson.requirements_met === true
        || lesson.ready === true
        || levelState.requirements_met === true
        || levelState.ready === true
        || ['ready', 'requirements_met', 'observed'].includes(status);
    };

    const renderProgress = (progress) => {
      if (!progress) return;
      const completed = completedIds(progress);
      const milestoneState = progress.state || {};
      arrayValue(progress.lessons).forEach((lesson) => {
        const item = progressList ? [...progressList.querySelectorAll('[data-lesson-id]')].find((candidate) => Number(candidate.dataset.lessonId) === Number(lesson.id)) : null;
        if (!item) return;
        const status = completed.has(Number(lesson.id)) ? 'completed' : firstDefined(lesson.status, Number(lesson.id) === level ? 'current' : 'not-started');
        item.dataset.status = slug(status);
        item.classList.toggle('completed', status === 'completed');
        item.classList.toggle('current', Number(lesson.id) === level && status !== 'completed');
        item.classList.toggle('not-started', status === 'not-started' || status === 'not_started');
        const link = item.matches('a') ? item : item.querySelector('a');
        if (link) {
          if (Number(lesson.id) === level) link.setAttribute('aria-current', 'page');
          else link.removeAttribute('aria-current');
        }
        const marker = item.querySelector('[data-lesson-marker]');
        if (marker) marker.textContent = status === 'completed' ? '✓' : Number(lesson.id) === level ? '●' : '○';
        const label = item.querySelector('[data-lesson-status]');
        if (label) label.textContent = String(status).replaceAll('_', ' ');
      });

      requirementsList?.querySelectorAll('[data-requirement]').forEach((item) => {
        const observed = milestoneState[item.dataset.requirement] === true;
        item.dataset.status = observed ? 'complete' : 'waiting';
        item.classList.toggle('complete', observed);
        item.classList.toggle('waiting', !observed);
        const marker = item.querySelector('[data-requirement-marker]') || item.querySelector('span');
        const label = item.querySelector('[data-requirement-status]') || item.querySelector('strong');
        if (marker) marker.textContent = observed ? '✓' : '○';
        if (label) label.textContent = observed ? 'Observed' : 'Waiting';
        item.setAttribute('aria-label', `${String(item.dataset.requirement).replaceAll('_', ' ')}: ${observed ? 'observed' : 'waiting'}`);
      });

      const lessonComplete = completed.has(level) || ['completed', 'complete'].includes(String(lessonStatus(progress, level)?.status).toLowerCase());
      if (completionState) {
        completionState.classList.toggle('waiting', !lessonComplete);
        completionState.classList.toggle('complete', lessonComplete);
        const heading = completionState.querySelector('strong');
        const detail = completionState.querySelector('span');
        if (heading) heading.textContent = lessonComplete ? '✓ Lesson complete' : 'Experiment in progress';
        if (detail) detail.textContent = lessonComplete ? 'Real behavior verified.' : 'The page will unlock Continue automatically.';
      }
      if (continueControl) {
        continueControl.hidden = !lessonComplete;
        continueControl.toggleAttribute('aria-disabled', !lessonComplete);
        if (continueControl.matches('a')) {
          if (lessonComplete && progress.next_url) continueControl.href = progress.next_url;
          else if (!lessonComplete) continueControl.removeAttribute('href');
        }
      }
      if (lessonComplete) setPollStatus('Lesson complete. You can continue when ready.', 'complete');
    };

    const completeLesson = async (progress) => {
      const completed = completedIds(progress);
      if (completed.has(level) || !requirementsMet(progress) || completionRequest || Date.now() < completionRetryAfter) return null;
      completionRequest = true;
      setPollStatus('Experiment observed. Marking the lesson complete…', 'working');
      try {
        const updated = await getJSON(`/api/learning/lessons/${level}/complete`, {method: 'POST'});
        if (updated) renderProgress(updated);
        return updated;
      } catch {
        completionRetryAfter = Date.now() + 5000;
        setPollStatus('The experiment was observed, but completion could not be saved yet. Retrying…', 'error');
        return null;
      } finally {
        completionRequest = false;
      }
    };

    const pollLearning = async () => {
      setPollStatus('Checking for new pushes…', 'working');
      if (firstAttemptResponse) attemptList.setAttribute('aria-busy', 'true');
      const query = new URLSearchParams({lesson: String(level)});
      if (cursor) query.set('after', cursor);
      const [attemptResult, progressResult] = await Promise.allSettled([
        getJSON(`/api/learning/attempts?${query}`),
        getJSON(`/api/learning/progress?active=${level}`),
      ]);
      if (document.hidden) return;

      let failed = false;
      if (attemptResult.status === 'fulfilled') renderAttempts(attemptResult.value);
      else failed = true;
      if (progressResult.status === 'fulfilled') {
        renderProgress(progressResult.value);
        const updatedProgress = await completeLesson(progressResult.value);
        if (updatedProgress) progressResult.value = updatedProgress;
      } else {
        failed = true;
      }
      if (failed) {
        attemptList.setAttribute('aria-busy', 'false');
        setPollStatus('Live updates are temporarily unavailable. Retrying…', 'error');
        if (firstAttemptResponse && !attemptList.querySelector('[data-attempt-state]')) {
          const error = document.createElement('p');
          error.className = 'push-empty-state error';
          error.dataset.attemptState = 'error';
          error.textContent = 'Could not load push attempts. This panel will retry automatically.';
          attemptList.append(error);
        }
      } else if (!completedIds(progressResult.value).has(level)) {
        setPollStatus('Live · waiting for your next push', 'live');
      }
    };

    if (!attemptList.children.length) {
      const loading = document.createElement('p');
      loading.className = 'push-empty-state';
      loading.dataset.attemptState = 'loading';
      loading.textContent = 'Loading push attempts…';
      attemptList.append(loading);
    }

    createPoller(pollLearning, {
      onPause: () => setPollStatus('Updates paused while this tab is hidden.', 'paused'),
      onResume: () => setPollStatus('Checking for new pushes…', 'working'),
    });
  }

  document.addEventListener('DOMContentLoaded', () => {
    initializeTheme();
    initializeSyntaxHighlighting();
    initializeCopyButtons();
    initializeLegacyInteractions();
    initializeKnowledgeChecks();
    initializeResearchDialogs();
    initializeReadiness();
    initializeRepository();
    initializeLearning();
    const dialog = document.querySelector('#reset-dialog');
    document.querySelectorAll('[data-open-reset]').forEach((button) => button.addEventListener('click', () => dialog?.showModal()));
  });
})();