caelum0x 174222bcaa feat: Builder-Track named-user tools, bio + evidence-intelligence platform, Apache-2.0
Builds PaperTrail from the base skeleton into a full evidence-verification platform
for the "Built with Claude: Life Sciences" hackathon (Builder Track).

New named-user features (Build Beyond the Bench):
- Lab Notebook Companion — rough bench notes -> structured, searchable, grounded
  experiment records (lib/labNotebook, /console/lab-notebook, migration 0059)
- Clinical Trial Matcher — de-identified patient notes -> ranked eligible
  ClinicalTrials.gov trials with per-criterion inclusion/exclusion reasoning
  (lib/trialMatcher, /console/trial-matcher, migrations 0060)

Platform:
- Deterministic verification moat (biostats recompute, exact-span grounding)
- 11 biomedical evidence engines (FAERS, GWAS, Open Targets, ChEMBL, ClinVar,
  PharmGKB, PubTator, DDI, repurposing, biomarker, unified verifier)
- Evidence Intelligence (KG, dossier, provenance/export, RWE) + enterprise
  governance (RBAC, /api/v1 gateway, metering, audit chain, retention)
- 17 OSS projects assimilated into native TypeScript on our stack (backend/engines
  retained + credited in NOTICE)
- Multi-format upload (PDF/DOCX/XLSX/CSV/MD/TXT), logo, marketing site
- Next.js 16 upgrade, benchmark harness (honest smoke-test caveat)

Licensing: Apache-2.0 (LICENSE + NOTICE).
2026-07-10 16:23:13 +03:00

1301 lines
92 KiB
HTML

{% extends "base.html" %}
{% block head_extra %}
<style>
.guidebook-layout {
display: grid;
grid-template-columns: 240px 1fr;
gap: 24px;
align-items: start;
}
.guidebook-toc {
position: sticky;
top: 80px;
max-height: calc(100vh - 100px);
overflow-y: auto;
padding: 18px;
background: var(--surface);
border: 1px solid var(--line);
border-radius: var(--radius-lg);
}
.guidebook-toc h3 {
margin: 0 0 12px;
font-size: 0.95rem;
color: var(--ink);
}
.guidebook-toc ol {
list-style: none;
padding: 0;
margin: 0;
display: grid;
gap: 2px;
}
.guidebook-toc a {
display: block;
padding: 5px 10px;
border-radius: var(--radius-sm);
font-size: 0.85rem;
font-weight: 600;
color: var(--ink-muted);
text-decoration: none;
}
.guidebook-toc a:hover {
background: rgba(15, 118, 110, 0.08);
color: var(--ink);
}
.guidebook-body {
display: grid;
gap: 24px;
}
.guidebook-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
}
.guidebook-toolbar-copy {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
.guidebook-copy-status {
color: var(--ink-muted);
font-size: 0.9rem;
font-weight: 700;
}
.guidebook-section h2 {
margin: 0 0 4px;
}
.guidebook-section h3 {
margin: 20px 0 8px;
font-size: 1.05rem;
color: var(--ink);
}
.guidebook-section h4 {
margin: 14px 0 6px;
font-size: 0.95rem;
color: var(--ink);
}
.guidebook-section p,
.guidebook-section li {
margin: 0 0 8px;
line-height: 1.7;
color: var(--ink);
}
.guidebook-section ul {
padding-left: 20px;
margin: 0 0 12px;
}
.guidebook-section .gb-tip {
margin: 12px 0;
padding: 12px 16px;
background: var(--info-bg, #eff6ff);
border: 1px solid var(--info-border, #bfdbfe);
border-radius: var(--radius-md);
font-size: 0.92rem;
}
.guidebook-section .gb-tip strong {
color: var(--brand);
}
.guidebook-section dl {
display: grid;
grid-template-columns: auto 1fr;
gap: 6px 16px;
margin: 0 0 12px;
}
.guidebook-section dt {
font-weight: 700;
color: var(--ink);
}
.guidebook-section dd {
margin: 0;
color: var(--ink);
line-height: 1.6;
}
@media (max-width: 980px) {
.guidebook-layout {
grid-template-columns: 1fr;
}
.guidebook-toc {
position: static;
max-height: none;
}
}
</style>
{% endblock %}
{% block content %}
<div class="guidebook-layout">
<!-- ===== TABLE OF CONTENTS ===== -->
<aside class="guidebook-toc">
<h3>Contents</h3>
<ol>
<li><a href="#overview">What Is Valsci?</a></li>
<li><a href="#getting-started">Getting Started</a></li>
<li><a href="#concepts">Key Concepts</a></li>
<li><a href="#navigation">Navigation &amp; Layout</a></li>
<li><a href="#home">Home Page</a></li>
<li><a href="#data">Data</a></li>
<li><a href="#claims-browser">Claims Browser</a></li>
<li><a href="#claim-detail">Claim Detail</a></li>
<li><a href="#results">Claim Report</a></li>
<li><a href="#batch-results">Batch Results</a></li>
<li><a href="#progress">Progress</a></li>
<li><a href="#arena-builder">Arena Builder</a></li>
<li><a href="#arenas-library">Arenas Library</a></li>
<li><a href="#arena-workspace">Arena Workspace</a></li>
<li><a href="#providers">Providers</a></li>
<li><a href="#settings">Settings</a></li>
<li><a href="#migration">Migration</a></li>
<li><a href="#trace-view">Trace View</a></li>
<li><a href="#login">Login</a></li>
</ol>
</aside>
<!-- ===== MAIN CONTENT ===== -->
<div class="guidebook-body">
<div class="panel guidebook-toolbar">
<div>
<h2 class="panel-title">Guidebook</h2>
<p class="panel-subtitle">Use the table of contents to jump around, or copy the full guide as Markdown.</p>
</div>
<div class="guidebook-toolbar-copy">
<button type="button" class="secondary-button small-button" id="copyGuidebookMarkdownBtn">Copy as Markdown</button>
<span class="guidebook-copy-status" id="copyGuidebookStatus" aria-live="polite"></span>
</div>
</div>
<!-- ============================================================ -->
<!-- SECTION: What Is Valsci? -->
<!-- ============================================================ -->
<section class="panel guidebook-section" id="overview">
<h2 class="panel-title">What Is Valsci?</h2>
<p class="panel-subtitle">Automated scientific claim verification powered by LLMs and academic literature.</p>
<div class="panel-divider"></div>
<p>Valsci is a tool that evaluates scientific claims against published research. You give it a claim like "Creatine supplementation improves short-term memory" and it:</p>
<ul>
<li><strong>Generates search queries</strong> from the claim using an LLM.</li>
<li><strong>Retrieves academic papers</strong> from Semantic Scholar matching those queries.</li>
<li><strong>Analyzes each paper's relevance</strong> to the claim, extracting key excerpts and evidence.</li>
<li><strong>Scores paper reliability</strong> using bibliometric data (author H-index, citation counts, journal quality).</li>
<li><strong>Produces a final report</strong> with a verdict rating from "Contradicted" to "Highly Supported," backed by cited evidence.</li>
</ul>
<p>Every step is grounded in real published papers&mdash;not LLM imagination. The system records a detailed trace of every decision so you can audit exactly how it reached its conclusion.</p>
<h3>Two Ways to Evaluate</h3>
<p>Valsci offers two evaluation modes, each suited to different needs:</p>
<ul>
<li><strong>Quick Runs</strong> (Home page) &mdash; Submit one or more claims and evaluate them with a single provider and model. Fast and straightforward. Best when you trust a particular model or just want a quick answer.</li>
<li><strong>Arenas</strong> (Arena Builder) &mdash; Submit the same claims to multiple models simultaneously and compare their results side-by-side. Best when you want to understand how different LLMs assess the same evidence, or when you need high confidence in the verdict.</li>
</ul>
<h3>How Costs Work</h3>
<p>Every claim evaluation consumes LLM tokens (the units that language models charge for). The cost depends on:</p>
<ul>
<li><strong>The model</strong> &mdash; Different models have different per-token prices. These are configured per model on the Providers page (Input Cost and Output Cost per million tokens).</li>
<li><strong>The number of queries and papers</strong> &mdash; More search queries and more results per query mean more papers to analyze, which means more tokens.</li>
<li><strong>Bibliometric scoring</strong> &mdash; When enabled, adds an extra scoring stage per paper.</li>
</ul>
<p>Every submission starts with a preflight cost estimate that you review and approve before anything queues. The actual cost may differ slightly because token counts are estimates until the LLM responds. All costs are tracked per run and visible in reports, batch results, and arena workspaces.</p>
<div class="gb-tip">
<strong>Tip:</strong> If you're exploring locally, start with the curated mini corpus on the Data page. It keeps the production Semantic Scholar lookup path intact while using a small focused dataset.
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION: Getting Started -->
<!-- ============================================================ -->
<section class="panel guidebook-section" id="getting-started">
<h2 class="panel-title">Getting Started</h2>
<p class="panel-subtitle">Your first claim evaluation in five steps.</p>
<div class="panel-divider"></div>
<h3>Step 1: Configure a Provider</h3>
<p>Go to the <strong>Providers</strong> page. You need at least one enabled provider with a valid API key and at least one enabled model. If you're using OpenAI, enter your API key, ensure a model like <code>gpt-4o</code> is listed and enabled, and save. See the <a href="#providers">Providers</a> section for full details.</p>
<h3>Step 2: Submit a Claim</h3>
<p>Go to the <strong>Home</strong> page. Select your provider and model from the dropdowns. Type a scientific claim (e.g., "Vitamin D supplementation reduces the severity of COVID-19") into the Claims textarea. Click <strong>Stage Claims</strong>.</p>
<h3>Step 3: Review and Queue</h3>
<p>Click <strong>Review &amp; Queue Run</strong>. Valsci estimates the projected token usage and dollar cost, then opens a confirmation modal — approve the spend there and the run queues. You land on the live Progress page automatically.</p>
<h3>Step 4: Monitor Progress</h3>
<p>You'll be redirected to the <strong>Progress</strong> page, which shows a real-time progress bar as your claim moves through the pipeline stages. When complete, you'll be sent to <strong>Batch Results</strong>.</p>
<h3>Step 5: Read the Report</h3>
<p>Click <strong>View Report</strong> on your claim in Batch Results. You'll see the overall verdict, supporting evidence with paper excerpts, non-relevant papers, and full cost/timing breakdowns. From here you can download the report, view the execution trace, or re-run the claim with different settings.</p>
<div class="gb-tip">
<strong>Tip:</strong> Once you're comfortable with single-model runs, try creating an <a href="#arena-builder">Arena</a> to compare how different models evaluate the same claims. It's the best way to build confidence in your results.
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION: Key Concepts -->
<!-- ============================================================ -->
<section class="panel guidebook-section" id="concepts">
<h2 class="panel-title">Key Concepts</h2>
<p class="panel-subtitle">Core terminology used throughout Valsci.</p>
<div class="panel-divider"></div>
<dl>
<dt>Claim</dt>
<dd>A scientific assertion you want to verify, such as "Creatine supplementation improves short-term memory." Valsci evaluates claims by searching for published research and analyzing the evidence.</dd>
<dt>Run</dt>
<dd>A single evaluation of one claim by one provider and model combination. A claim can have many runs, each potentially using different models or settings, letting you compare how different LLMs assess the same claim.</dd>
<dt>Batch</dt>
<dd>A group of claims submitted together in one operation. Every submission from the Home page creates a batch, even if it contains only one claim.</dd>
<dt>Arena</dt>
<dd>A structured comparison where the same set of claims is evaluated by multiple provider/model candidates. Arenas progress through stages, letting you review intermediate results and decide which candidates advance.</dd>
<dt>Candidate</dt>
<dd>A specific provider + model combination participating in an arena. Each selected model becomes a named candidate with a consistent identity across all claims in the arena.</dd>
<dt>Provider</dt>
<dd>A connection to an LLM API service, such as OpenAI, Azure OpenAI, Ollama, or a local llama.cpp server. Each provider stores its credentials, base URL, and a list of available models.</dd>
<dt>Stage</dt>
<dd>One step in the claim evaluation pipeline. The four stages are:
<ul>
<li><strong>Query Generation</strong> &mdash; The LLM reads your claim and generates multiple targeted search queries designed to find relevant academic papers. For example, the claim "Creatine improves memory" might produce queries like "creatine supplementation cognitive function randomized trial" and "creatine monohydrate working memory neuroimaging."</li>
<li><strong>Paper Analysis</strong> &mdash; Each query is sent to Semantic Scholar. Retrieved papers are then individually analyzed by the LLM, which reads the title, abstract, and metadata to determine relevance to the claim and extract supporting or contradicting excerpts.</li>
<li><strong>Venue Scoring</strong> &mdash; When bibliometrics are enabled, each paper receives a reliability score based on the authors' H-indices, the paper's citation count, and the journal's impact. Higher-quality sources carry more weight in the final verdict.</li>
<li><strong>Final Report</strong> &mdash; The LLM synthesizes all analyzed papers, their excerpts, and their reliability scores into a narrative report with an overall claim rating.</li>
</ul>
</dd>
<dt>Semantic Scholar</dt>
<dd>The academic paper database that Valsci searches to find evidence for claims. It returns published papers, their authors, citation counts, and other metadata.</dd>
<dt>Bibliometrics</dt>
<dd>Quantitative measures of paper and author quality, including author H-index, citation count, and journal impact. When enabled, these scores weight evidence so that higher-quality sources carry more influence in the final verdict.</dd>
<dt>Trace</dt>
<dd>A detailed, step-by-step log of every LLM call, API request, and processing decision made during a run. Useful for debugging, auditing prompt behavior, and understanding token usage.</dd>
<dt>Claim Rating</dt>
<dd>The final verdict for a claim, expressed on an ordinal scale:
<ul>
<li><strong>0 &mdash; No Evidence</strong>: No relevant papers were found. The claim can't be assessed.</li>
<li><strong>1 &mdash; Contradicted</strong>: The available evidence directly contradicts the claim.</li>
<li><strong>2 &mdash; Likely False</strong>: The weight of evidence leans against the claim, though some ambiguity exists.</li>
<li><strong>3 &mdash; Mixed Evidence</strong>: Papers both support and contradict the claim; no clear consensus.</li>
<li><strong>4 &mdash; Likely True</strong>: The weight of evidence supports the claim, with minor caveats.</li>
<li><strong>5 &mdash; Highly Supported</strong>: Strong, consistent evidence from multiple high-quality sources supports the claim.</li>
</ul>
</dd>
<dt>Prompt Provenance</dt>
<dd>Valsci tracks exactly which prompt templates were used for each stage of every run, including file names and SHA-256 hashes. This ensures reproducibility: you can verify that two runs used identical prompts, or identify when a prompt change affected results.</dd>
<dt>Issues</dt>
<dd>Warnings or errors that occurred during processing, such as LLM timeouts, parsing failures, or context window overflows. Issues don't necessarily mean the evaluation failed&mdash;the system has retry and recovery logic&mdash;but they flag areas worth reviewing in the trace.</dd>
</dl>
</section>
<!-- ============================================================ -->
<!-- SECTION: Navigation & Layout -->
<!-- ============================================================ -->
<section class="panel guidebook-section" id="navigation">
<h2 class="panel-title">Navigation &amp; Layout</h2>
<p class="panel-subtitle">How to get around the application.</p>
<div class="panel-divider"></div>
<h3>Top Navigation Bar</h3>
<p>The sticky bar at the top of every page contains:</p>
<ul>
<li><strong>VS / Valsci</strong> (brand lockup, far left) &mdash; Click to return to the Home page from anywhere.</li>
<li><strong>Home</strong> &mdash; The claim submission page (quick runs).</li>
<li><strong>Claims</strong> &mdash; The Claims Browser, where you search and browse all evaluated claims.</li>
<li><strong>Arenas</strong> &mdash; The Arenas Library, listing all multi-model comparisons.</li>
<li><strong>Providers</strong> &mdash; Provider configuration: API keys, models, and connection settings.</li>
<li><strong>Migration</strong> &mdash; Legacy batch import tool (only relevant if upgrading from an older Valsci version).</li>
<li><strong>Guidebook</strong> &mdash; This page.</li>
</ul>
<h3>Status Indicators</h3>
<ul>
<li><strong>Logout button</strong> (top right) &mdash; Appears when password protection is enabled. Ends your session and redirects to the login page.</li>
</ul>
<h3>Page Structure</h3>
<p>Most pages follow a consistent layout:</p>
<ul>
<li><strong>Breadcrumbs</strong> &mdash; Appear on sub-pages (like Claim Detail) showing the navigation path. Click any breadcrumb to go back to that level.</li>
<li><strong>Page header</strong> &mdash; Title, optional subtitle, and optional action buttons (e.g., "Refresh" or "New Arena").</li>
<li><strong>Panels</strong> &mdash; Content is organized in bordered panel cards. Some pages use a two-column dashboard grid layout (e.g., Home, Providers, Claim Detail).</li>
<li><strong>Status cards</strong> &mdash; Colored alert banners (blue for info, yellow for warnings, red for errors, green for success) appear contextually to communicate system state.</li>
<li><strong>Modals</strong> &mdash; Cost confirmation dialogs and import modals overlay the page. They always require explicit approval (a checkbox) before proceeding with cost-incurring operations.</li>
</ul>
</section>
<!-- ============================================================ -->
<!-- SECTION: Home Page -->
<!-- ============================================================ -->
<section class="panel guidebook-section" id="home">
<h2 class="panel-title">Home Page</h2>
<p class="panel-subtitle">Submit claims for evaluation using a single provider and model.</p>
<div class="panel-divider"></div>
<h3>Migration Alert</h3>
<p>If legacy batch folders exist from an older version of Valsci, a yellow warning banner appears at the top of the page. It shows how many legacy batches need attention and offers two actions:</p>
<ul>
<li><strong>Review Migration</strong> &mdash; Opens the Migration page so you can inspect each legacy batch before importing.</li>
<li><strong>Migrate &amp; Archive</strong> &mdash; Immediately imports all pending legacy batches into the canonical claim store and moves their old folders into the migration archive.</li>
</ul>
<h3>Run Claims Panel</h3>
<p>The main panel on the left side of the page is where you configure and submit claims.</p>
<h4>Provider &amp; Model</h4>
<p>The <strong>Provider</strong> dropdown lists all enabled providers configured on the Providers page. Selecting a provider populates the <strong>Model</strong> dropdown with that provider's enabled models. These determine which LLM service and model will evaluate your claims.</p>
<h4>Existing Claim Handling</h4>
<p>The <strong>Existing Claim Handling</strong> dropdown controls what happens when you submit a claim that has already been evaluated:</p>
<ul>
<li><strong>Create New Run</strong> &mdash; Always creates a fresh evaluation, even if the same claim text already exists. Useful for comparing results across different models or settings.</li>
<li><strong>Open Existing Claim</strong> &mdash; If the claim already exists, navigates directly to the existing claim detail page instead of running it again.</li>
</ul>
<h4>Batch Tags</h4>
<p>An optional comma-separated list of tags to label this batch. Tags help you organize and identify batches later in the Claims Browser.</p>
<h4>Claims Input</h4>
<p>Enter claims in the <strong>Claims</strong> textarea, one claim per line. Alternatively, click <strong>Upload Claims</strong> to load claims from a <code>.txt</code> file (one claim per line).</p>
<h4>Stage Claims / Clear</h4>
<ul>
<li><strong>Stage Claims</strong> &mdash; Parses the textarea or uploaded file and moves the claims into the staging area below. Claims are not submitted yet; staging lets you review and edit before committing.</li>
<li><strong>Clear</strong> &mdash; Removes all claims from both the textarea and the staging area.</li>
</ul>
<h4>Staged Claims</h4>
<p>A list of claims ready to be submitted. You can review them here before proceeding. Staging is a safety step: it lets you verify claim text, remove duplicates, or catch paste errors before incurring any cost.</p>
<h4>Advanced Run Settings</h4>
<p>Click to expand the advanced settings panel:</p>
<ul>
<li><strong>Queries</strong> &mdash; The number of search queries the LLM will generate from each claim (default: 5). More queries cast a wider net but increase cost.</li>
<li><strong>Results / Query</strong> &mdash; How many papers to retrieve per search query (default: 5). Higher values find more papers but increase processing time.</li>
<li><strong>Use bibliometric scoring</strong> &mdash; When checked, papers are weighted by author H-index, citation count, and venue impact. Uncheck to treat all papers equally.</li>
</ul>
<h4>Cost Estimation &amp; Submission</h4>
<ul>
<li><strong>Review &amp; Queue Run</strong> &mdash; A single two-step button. It first runs a preflight estimate of token usage and dollar cost (shown in the preflight panel below), then opens a confirmation modal. You must check the "I approve this estimated spend" checkbox before confirming. Once confirmed, claims are submitted for processing and you are redirected to the Progress page. If you change any settings after the estimate, the next click re-estimates first.</li>
</ul>
<h3>Sidebar Panels</h3>
<h4>Quick Links</h4>
<p>Two shortcut buttons:</p>
<ul>
<li><strong>New Arena</strong> &mdash; Opens the Arena Builder to create a multi-model comparison.</li>
<li><strong>View Arenas</strong> &mdash; Opens the Arenas Library.</li>
</ul>
<h4>Recent Arenas</h4>
<p>Shows the most recently created arenas. Click <strong>Open Library</strong> to see all arenas.</p>
<h4>Recent Claims</h4>
<p>Shows the most recently evaluated claims. Click <strong>Open Claims</strong> to open the full Claims Browser.</p>
<div class="gb-tip">
<strong>Tip:</strong> For best results, write claims as specific, testable scientific assertions rather than vague questions. "Omega-3 fatty acid supplementation reduces triglyceride levels in adults with hypertriglyceridemia" will produce much better results than "Is fish oil good for you?"
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION: Data -->
<!-- ============================================================ -->
<section class="panel guidebook-section" id="data">
<h2 class="panel-title">Data</h2>
<p class="panel-subtitle">Inspect, download, index, and verify local Semantic Scholar data.</p>
<div class="panel-divider"></div>
<p>Navigate here using the <strong>Data</strong> link in the top navigation bar. The Data page is where you prepare Valsci for real Semantic Scholar retrieval. It shows which releases are present locally, which datasets are indexed, whether the API key is configured, and what downloader or indexer job is currently running.</p>
<h3>When to Use the Data Page</h3>
<ul>
<li><strong>First real-data setup</strong> &mdash; Build the curated Mendelian mini corpus or download full Semantic Scholar datasets before running claims.</li>
<li><strong>Pipeline rehearsal</strong> &mdash; Confirm that the mini release, full-text datasets, abstracts, TLDRs, authors, papers, and binary indices are all available before testing with local models such as Ollama.</li>
<li><strong>Maintenance</strong> &mdash; Rebuild indices after changing local dataset files, verify files after an interrupted download, or inspect which release Valsci will use.</li>
<li><strong>Readiness checks</strong> &mdash; Confirm that a Semantic Scholar API key, local release, and binary indices are available before running claims against real local data.</li>
</ul>
<h3>Semantic Scholar Readiness</h3>
<p>Valsci always uses the real Semantic Scholar retrieval path. The Data page shows whether the pieces needed for that path are present.</p>
<ul>
<li><strong>Semantic Scholar API key</strong> &mdash; Live search and dataset downloads need <code>SEMANTIC_SCHOLAR_API_KEY</code> in <code>app/config/env_vars.json</code>.</li>
<li><strong>Local release</strong> &mdash; Paper content lookup uses the latest local release unless a run selects another release.</li>
<li><strong>Binary indices</strong> &mdash; Dataset rows are found through corpus-ID and author-ID indices. Missing indices should be rebuilt before a rehearsal run.</li>
</ul>
<p>The app can start without the API key so the Data page remains available for setup and inspection, but live search and downloads will fail until the key is configured.</p>
<h3>Local Data State Panel</h3>
<p>The top-left panel summarizes the machine's Semantic Scholar setup:</p>
<ul>
<li><strong>Latest Release</strong> &mdash; The newest locally detected release ID, such as <code>2026-05-26-mini-mendelian-v1</code>.</li>
<li><strong>Local Releases</strong> &mdash; Count of release folders and indexed releases detected under the local Semantic Scholar dataset directory.</li>
<li><strong>Selected Size</strong> &mdash; Disk usage for the release currently selected in the Releases panel.</li>
<li><strong>S2 API Key</strong> &mdash; Shows whether <code>SEMANTIC_SCHOLAR_API_KEY</code> is configured. Downloads and live search require it.</li>
<li><strong>Status card</strong> &mdash; Warns when no release is present, the API key is missing, or setup work is still needed.</li>
<li><strong>Fetch missing papers &amp; author data from the web</strong> &mdash; A toggle. When on, if a paper or author a claim needs isn't in your local corpus, Valsci pulls it from the live Semantic Scholar API (paper abstract/TLDR, and author h-index/citation counts for bibliometrics), using your API key and respecting rate limits. This is most useful with a small <em>mini</em> corpus, where live search routinely returns papers outside the bundled set. It takes effect for processing within a few seconds &mdash; no restart needed.</li>
<li><strong>Refresh</strong> &mdash; Re-scans local files, indices, manifest state, and data jobs.</li>
</ul>
<h3>Releases Panel</h3>
<p>The Releases panel lets you inspect one local Semantic Scholar release at a time.</p>
<ul>
<li><strong>Release selector</strong> &mdash; Choose among locally detected releases. Mini releases are labeled as mini.</li>
<li><strong>New Release</strong> &mdash; Opens a wizard for creating either the bundled Mendelian mini release or a selected full Semantic Scholar release.</li>
<li><strong>Type</strong> &mdash; Shows whether the selected release is a curated mini release or a full release.</li>
<li><strong>Size</strong> &mdash; Total size of dataset JSON files under that release.</li>
<li><strong>Topic</strong> &mdash; For manifest-backed mini releases, shows the topic label such as <code>mendelian_disease_v1</code>.</li>
<li><strong>Index</strong> &mdash; Summarizes whether the selected release has the binary indices needed for local lookup.</li>
<li><strong>Records written pills</strong> &mdash; Mini releases show counts for compact extracted datasets such as papers, authors, abstracts, TLDRs, and S2ORC v2 records.</li>
<li><strong>Manifest coverage card</strong> &mdash; Only appears for the bundled mini release. It compares local compact rows against the current tracked manifest. Full Semantic Scholar releases do not use a manifest; their readiness is based on downloaded dataset files and indices.</li>
<li><strong>Release Maintenance</strong> &mdash; Lets you verify the selected release or index/reindex selected datasets.</li>
</ul>
<h3>Dataset Coverage Panel</h3>
<p>This table is the fastest way to see whether the selected release can support production-style evidence lookup.</p>
<ul>
<li><strong>Dataset</strong> &mdash; The Semantic Scholar dataset name and label. Valsci expects papers, authors, abstracts, TLDRs, and S2ORC v2.</li>
<li><strong>Local Files</strong> &mdash; Shows whether JSON files exist for that dataset and how many local shard files were found.</li>
<li><strong>Size</strong> &mdash; Total disk footprint for that dataset in the selected release.</li>
<li><strong>Index</strong> &mdash; Shows binary index state by ID type, such as corpus ID or author ID. Missing index badges mean lookup will be slower or unavailable for that dataset.</li>
<li><strong>Role</strong> &mdash; Describes how the dataset is used. S2ORC v2 provides local full text, abstracts and TLDRs provide fallback text, papers provide metadata, and authors provide bibliometrics.</li>
</ul>
<h3>New Release Wizard</h3>
<p>The New Release wizard starts downloader and indexing jobs. Output appears in Current Job, and completed jobs appear in Recent Data Jobs.</p>
<ul>
<li><strong>Curated Mini</strong> &mdash; Runs the manifest-backed Mendelian mini builder. It reads the bundled ID manifest at <code>semantic_scholar/manifests/mendelian_v1.json</code>, streams Semantic Scholar dataset shards for the fixed corpus and author IDs, writes compact dataset-shaped JSONL files into the ignored runtime datasets directory, and builds binary indices.</li>
<li><strong>Download Full Dataset Selection</strong> &mdash; Downloads selected full Semantic Scholar datasets for the requested release. This can consume a large amount of disk space, especially when S2ORC v2 is selected.</li>
</ul>
<h4>Mini Manifest</h4>
<p>When <strong>Curated Mini</strong> is selected, the <strong>Mini Manifest</strong> input points to the tracked Mendelian ID manifest, normally <code>semantic_scholar/manifests/mendelian_v1.json</code>. Runtime release output and any source-row cache still go under <code>semantic_scholar/datasets</code>, which is ignored local data.</p>
<p>Full releases do not have or need a manifest. For a full release, Valsci downloads the selected Semantic Scholar datasets for the requested release ID and verifies them against the Semantic Scholar Datasets API file list.</p>
<h4>Release</h4>
<p>For full downloads, the <strong>Release</strong> input selects the Semantic Scholar release to download. Leaving it as <code>latest</code> uses the downloader's current latest-release behavior. Mini builds take their mini release ID from the manifest.</p>
<h4>Datasets</h4>
<p>The dataset picker controls which Semantic Scholar datasets a full release download touches. Selected-release verification and indexing use the dataset picker inside Release Maintenance.</p>
<h3>Current Job Panel</h3>
<ul>
<li><strong>Status badge</strong> &mdash; Shows idle, queued, running, success, failed, cancelled, or interrupted.</li>
<li><strong>Command</strong> &mdash; Displays the exact Python downloader command the app launched.</li>
<li><strong>Log stream</strong> &mdash; Shows downloader output while the job runs. It scrolls as new lines arrive.</li>
<li><strong>Cancel Job</strong> &mdash; Requests cancellation for queued or running jobs.</li>
</ul>
<h3>Recent Data Jobs Panel</h3>
<p>Recent jobs show their operation, status, creation time, and command. Use this history to confirm what was run after a long download or to inspect a failed command.</p>
<h3>Recommended First Real-Data Workflow</h3>
<ul>
<li>Open <strong>Data</strong> and confirm <strong>S2 API Key</strong> is configured.</li>
<li>Click <strong>New Release</strong>, choose <strong>Curated Mini</strong>, and confirm the Mendelian mini manifest path.</li>
<li>Start the job and watch <strong>Current Job</strong> until it succeeds.</li>
<li>Select the new mini release in <strong>Releases</strong>.</li>
<li>Check <strong>Dataset Coverage</strong> for papers, authors, abstracts, TLDRs, S2ORC v2, and indices.</li>
<li>Run a small claim batch using the same local Ollama model you plan to use in production rehearsal.</li>
</ul>
<h3>Troubleshooting</h3>
<ul>
<li><strong>Semantic Scholar API key is missing</strong> &mdash; Set <code>SEMANTIC_SCHOLAR_API_KEY</code> in <code>app/config/env_vars.json</code> before live search or downloads.</li>
<li><strong>Mini release needs rebuild</strong> &mdash; The tracked manifest changed after the selected mini release was built. Use <strong>New Release</strong> &rarr; <strong>Curated Mini</strong>, or run <code>python -m semantic_scholar.utils.downloader --mini</code>.</li>
<li><strong>Mini manifest missing</strong> &mdash; Restore the tracked mini package at <code>semantic_scholar/manifests/mendelian_v1.json</code>, or pass a custom manifest path.</li>
<li><strong>Indices missing</strong> &mdash; Use <strong>Index</strong> or <strong>Reindex</strong> in Release Maintenance for the affected release and datasets.</li>
<li><strong>Full download feels too large</strong> &mdash; Use the curated mini corpus for desktop rehearsal. Full S2ORC datasets are large and can exceed practical local disk limits.</li>
<li><strong>Live search misses curated papers</strong> &mdash; Adjust the curated claims or manifest selection, then rebuild the mini corpus. The mini data is deterministic, but live search ranking can still change.</li>
</ul>
</section>
<!-- ============================================================ -->
<!-- SECTION: Claims Browser -->
<!-- ============================================================ -->
<section class="panel guidebook-section" id="claims-browser">
<h2 class="panel-title">Claims Browser</h2>
<p class="panel-subtitle">Search and browse all evaluated claims across every batch.</p>
<div class="panel-divider"></div>
<p>Navigate here using the <strong>Claims</strong> link in the top navigation bar.</p>
<h3>Search</h3>
<p>Type a keyword, phrase, or claim key into the search box.</p>
<ul>
<li><strong>Search</strong> &mdash; Executes the search and filters results. You can also press Enter.</li>
<li><strong>Clear</strong> &mdash; Resets the search and shows all claims.</li>
</ul>
<h3>Claims Count</h3>
<p>A summary strip shows the total number of claims matching the current search.</p>
<h3>Claim List</h3>
<p>Each result card shows the claim text, its status, and key metadata. Click <strong>Open Claim</strong> on any card to navigate to the Claim Detail page for that claim.</p>
<div class="gb-tip">
<strong>Tip:</strong> The Claims Browser searches across all batches and arenas. If you ran the same claim through multiple models or configurations, they'll all appear under the same claim key, making it easy to compare results.
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION: Claim Detail -->
<!-- ============================================================ -->
<section class="panel guidebook-section" id="claim-detail">
<h2 class="panel-title">Claim Detail</h2>
<p class="panel-subtitle">View detailed results for a single claim and manage reruns.</p>
<div class="panel-divider"></div>
<p>You reach this page by clicking a claim from the Claims Browser, Batch Results, or Arena Workspace.</p>
<h3>Focused Run</h3>
<p>The hero section at the top displays the currently focused run's key information: claim text, rating, status, provider, model, cost, and timestamps. If a specific run was selected (e.g., from an arena), that run is shown. Otherwise, the most recent run is displayed.</p>
<ul>
<li><strong>Open Report</strong> / <strong>Open Arena Stage</strong> &mdash; Navigate to the full Claim Report page for this run.</li>
<li><strong>Open Trace</strong> &mdash; Open the Trace View to see every step of this run's processing.</li>
</ul>
<h3>Runtime and Health</h3>
<p>This panel summarizes execution state and warning signals: current stage, elapsed time, token usage, and counters for issues, retries, truncation, context warnings, and inaccessible papers. When the issue count is non-zero it becomes a link to the <strong>Issues &amp; Warnings</strong> panel below.</p>
<h3>Issues &amp; Warnings</h3>
<p>If anything was logged while the run processed, this panel lists each record &mdash; severity, stage, message, timestamp, and details &mdash; with a <strong>Download (.jsonl)</strong> button for the raw log. It opens with a banner that interprets the records against the run's final outcome, so you can tell recovery from real failure at a glance:</p>
<ul>
<li><strong>Severity tells you what happened next.</strong> A <span class="badge warning-badge">WARN</span> is a transient failure that was <em>automatically retried</em> (e.g. "failed on attempt 1 of 3 &mdash; retrying"). An <span class="badge error-badge">ERROR</span> is terminal &mdash; the step gave up after exhausting retries.</li>
<li><strong>The banner ties it to the verdict.</strong> "This run completed despite the errors below" (the run still produced a verdict) versus "This run did not complete" (no verdict &mdash; the errors explain why). A run can log errors and still succeed, because most failures are retried.</li>
</ul>
<h3>Stage Output</h3>
<p>If the focused run has intermediate stage data (e.g., from an arena that stopped after a middle stage), it is displayed in this collapsible section.</p>
<h3>Alternative Runs</h3>
<p>A list of all other runs for this claim. Each card shows the provider, model, status, rating, and cost. Actions:</p>
<ul>
<li><strong>Focus Run</strong> &mdash; Switches the hero section to display this run's details.</li>
<li><strong>Compare checkbox</strong> &mdash; Select multiple runs to include them in the Comparison Matrix below.</li>
<li><strong>Detail</strong> &mdash; Opens the run in a new context.</li>
</ul>
<h3>Rerun This Claim</h3>
<p>A form to queue a new evaluation of the same claim (or a modified version). The controls mirror the Home Page's run configuration: provider, model, duplicate strategy, batch tags, and advanced settings (queries, results per query, bibliometrics).</p>
<ul>
<li><strong>Review &amp; Queue Rerun</strong> &mdash; Estimates the cost of re-evaluating this claim, then asks you to approve the spend in a confirmation modal before queueing.</li>
</ul>
<h3>Comparison Matrix</h3>
<p>A side-by-side table comparing all runs selected via the compare checkboxes. Shows each run's rating, evidence count, cost, and other key metrics in columns for easy visual comparison.</p>
<div class="gb-tip">
<strong>Tip:</strong> The Comparison Matrix is one of Valsci's most powerful features. If two models give the same claim different ratings, compare their evidence side-by-side to understand why. Did one find papers the other missed? Did they interpret the same excerpts differently? This helps you calibrate which models you trust for specific domains.
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION: Claim Report -->
<!-- ============================================================ -->
<section class="panel guidebook-section" id="results">
<h2 class="panel-title">Claim Report</h2>
<p class="panel-subtitle">The full evaluation report for a single claim run.</p>
<div class="panel-divider"></div>
<p>You reach this page by clicking "View Report" from Batch Results or "Open Report" from Claim Detail.</p>
<h3>Report Content</h3>
<p>The report displays:</p>
<ul>
<li><strong>Claim text</strong> and <strong>overall rating</strong> with a color-coded badge (red for contradicted, green for highly supported, gray for no evidence or mixed).</li>
<li><strong>Explanation</strong> &mdash; A markdown-formatted narrative summarizing the evidence and reasoning behind the rating.</li>
<li><strong>Final Reasoning</strong> &mdash; If available, a collapsible section with the LLM's detailed reasoning. Click <strong>Show Final Reasoning</strong> / <strong>Hide Final Reasoning</strong> to toggle.</li>
</ul>
<h3>Papers Sections</h3>
<ul>
<li><strong>Relevant Papers</strong> &mdash; Papers that the LLM found relevant to the claim. Each entry shows:
<ul>
<li><em>Title</em> &mdash; The paper's title as retrieved from Semantic Scholar.</li>
<li><em>Authors</em> &mdash; Author names with their H-index (a measure of research impact; higher is more influential).</li>
<li><em>Relevance</em> &mdash; The LLM's explanation of why this paper is relevant to the claim.</li>
<li><em>Bibliometric Impact</em> &mdash; A composite reliability score (when bibliometrics are enabled) combining author, citation, and venue quality.</li>
<li><em>Excerpts</em> &mdash; Key passages from the paper that support or contradict the claim.</li>
<li><em>Explanations</em> &mdash; The LLM's interpretation of how each excerpt relates to the claim.</li>
<li><em>Citations</em> &mdash; Formatted citation entries for the paper.</li>
<li><em>Content Type</em> &mdash; The type of paper (e.g., research article, review, meta-analysis).</li>
<li><em>Read Paper</em> &mdash; A link to the original paper on Semantic Scholar.</li>
</ul>
</li>
<li><strong>Other Reviewed Papers</strong> &mdash; Papers that were retrieved but determined not relevant, with an explanation of why.</li>
<li><strong>Inaccessible Papers</strong> &mdash; Papers that could not be retrieved or analyzed, with the reason.</li>
</ul>
<h3>Additional Information</h3>
<ul>
<li><strong>Search Queries</strong> &mdash; The actual search queries generated by the LLM and sent to Semantic Scholar.</li>
<li><strong>Processing Time Breakdown</strong> &mdash; How long each phase took (search, paper processing, report generation, total).</li>
<li><strong>LLM Usage</strong> &mdash; Token counts (input, output, total) and estimated cost.</li>
<li><strong>Usage By Stage</strong> &mdash; A table breaking down token usage and cost per pipeline stage.</li>
<li><strong>Prompt Provenance</strong> &mdash; Expandable section showing which prompt files were used, their SHA-256 hashes, and modification dates. Useful for reproducibility.</li>
<li><strong>Debug &amp; Trace</strong> &mdash; Summary of LLM calls, models used, retries, and a link to the full Trace Viewer.</li>
</ul>
<h3>Action Buttons</h3>
<ul>
<li><strong>Download Report</strong> &mdash; Download the report as a Markdown file.</li>
<li><strong>View Full Trace</strong> &mdash; Open the Trace View page for this run.</li>
<li><strong>Download Trace</strong> &mdash; Download the raw trace file (JSONL, gzipped).</li>
<li><strong>Download Issues</strong> &mdash; Download the issues log (JSONL, gzipped).</li>
<li><strong>Download Citations</strong> &mdash; Download citation data as a JSON file.</li>
<li><strong>Delete Claim</strong> &mdash; Permanently delete this claim and all its data. Requires confirmation.</li>
</ul>
<div class="gb-tip">
<strong>Tip:</strong> The Prompt Provenance section is valuable for reproducibility. If you modify prompt templates and re-run a claim, the SHA-256 hashes let you verify exactly which prompt version produced which result. This is especially useful in team settings or when iterating on prompt engineering.
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION: Batch Results -->
<!-- ============================================================ -->
<section class="panel guidebook-section" id="batch-results">
<h2 class="panel-title">Batch Results</h2>
<p class="panel-subtitle">View all claims in a batch with their ratings and status.</p>
<div class="panel-divider"></div>
<p>You reach this page after a batch finishes processing, or by navigating from the Progress page.</p>
<h3>Status Banner</h3>
<p>Shows the batch status (processing or completed), the number of completed claims, and counts of saved vs. queued claims.</p>
<h3>Action Bar</h3>
<ul>
<li><strong>Delete Batch</strong> &mdash; Permanently delete the entire batch and all its claims. Requires confirmation.</li>
<li><strong>Download CSV</strong> &mdash; Export the results table as a CSV file.</li>
<li><strong>Bulk Download Reports</strong> &mdash; Download all claim reports as a ZIP of Markdown files. Only available after the batch is complete.</li>
<li><strong>Show all tagged runs</strong> &mdash; Toggle to show every run (including reruns) instead of just the primary run per claim.</li>
<li><strong>Filter results</strong> &mdash; Type to filter the table by claim text.</li>
</ul>
<h3>Results Table</h3>
<p>An interactive table with sortable and filterable columns:</p>
<ul>
<li><strong>Claim</strong> &mdash; The claim text.</li>
<li><strong>Status</strong> &mdash; Processing status (completed, processing, error).</li>
<li><strong>Location</strong> &mdash; Where the claim data is stored (saved_jobs or queued_jobs).</li>
<li><strong>Rating</strong> &mdash; The numerical claim rating (0-5).</li>
<li><strong>Supporting / Non-Relevant</strong> &mdash; Count of relevant and non-relevant papers found.</li>
<li><strong>Price</strong> &mdash; Estimated cost for that claim's evaluation.</li>
<li><strong>Report</strong> &mdash; Links to either <strong>View Report</strong> (if completed) or <strong>View Progress</strong> (if still processing), plus a <strong>Claim</strong> link to the Claim Detail page.</li>
</ul>
<h3>Total Batch Price</h3>
<p>The sum of all claim costs in the batch, displayed below the table.</p>
<div class="gb-tip">
<strong>Tip:</strong> Use column header filters to quickly find claims by status (e.g., type "error" in the Status filter to find failed evaluations). Click any column header to sort&mdash;sorting by Rating helps you quickly find the most and least supported claims.
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION: Progress -->
<!-- ============================================================ -->
<section class="panel guidebook-section" id="progress">
<h2 class="panel-title">Progress</h2>
<p class="panel-subtitle">Real-time processing status for a batch or individual claim.</p>
<div class="panel-divider"></div>
<p>You are sent here automatically after submitting claims. The page refreshes every five seconds (a countdown in the header shows when the next refresh lands) and displays:</p>
<ul>
<li><strong>Animated progress bar</strong> &mdash; Fills as claims complete; an animated stripe pattern indicates the batch is actively being worked.</li>
<li><strong>Pipeline stages</strong> &mdash; Counts of claims at each step (Queued &rarr; Searching literature &rarr; Analyzing evidence &rarr; Done), with a separate chip for errors.</li>
<li><strong>Current claim</strong> &mdash; Which claim is currently being evaluated, plus elapsed time on the page.</li>
<li><strong>Processor health</strong> &mdash; If the background processor daemon is not running, a banner warns you that claims will stay queued and explains how to start it. The processor reports a heartbeat every few seconds while alive.</li>
</ul>
<p>Once all claims are complete, the page automatically redirects to the results (the claim report for a single claim, or Batch Results for a batch). If the batch settles with failed claims, a warning summarizes how many failed so you can inspect or retry them.</p>
<div class="gb-tip">
<strong>Tip:</strong> Processing time depends on the number of claims, the number of queries per claim, and the speed of your chosen LLM provider. A single claim with default settings (5 queries, 5 results each) typically takes 30 seconds to a few minutes. Local models (Ollama/llama.cpp) may be slower depending on your hardware.
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION: Arena Builder -->
<!-- ============================================================ -->
<section class="panel guidebook-section" id="arena-builder">
<h2 class="panel-title">Arena Builder</h2>
<p class="panel-subtitle">Create a multi-model comparison arena.</p>
<div class="panel-divider"></div>
<p>Navigate here using <strong>New Arena</strong> from the Home page or the <strong>Arenas</strong> nav link followed by clicking "New Arena."</p>
<h3>When to Use an Arena</h3>
<p>Arenas are best when you need to:</p>
<ul>
<li><strong>Compare models</strong> &mdash; See how GPT-4o, Claude, Llama, etc. evaluate the same evidence differently.</li>
<li><strong>Benchmark cost vs. quality</strong> &mdash; A cheaper model might produce results nearly as good as a premium one for your domain.</li>
<li><strong>Build confidence</strong> &mdash; If three independent models all rate a claim "Highly Supported," that's stronger evidence than one model's opinion.</li>
<li><strong>Control variables</strong> &mdash; Use "Reuse retrieval" mode to give all models the same papers, isolating the analysis quality from retrieval differences.</li>
</ul>
<h3>Stepper</h3>
<p>A four-step visual guide at the top of the page: <strong>Step 1</strong> Choose provider, <strong>Step 2</strong> Choose models, <strong>Step 3</strong> Add claims, <strong>Step 4</strong> Review and launch.</p>
<h3>Default Arena Flow</h3>
<h4>Arena Title</h4>
<p>An optional name for the arena. If left blank, the arena is identified by its auto-generated ID.</p>
<h4>Provider Blocks</h4>
<p>Each provider block lets you select a provider and then check the models you want to include as candidates. By default, one provider block is shown. To compare models across different providers, use the Advanced Arena Settings to add more blocks.</p>
<ul>
<li><strong>Provider dropdown</strong> &mdash; Choose which provider to use for this block.</li>
<li><strong>Model search</strong> &mdash; Filter the model list by typing.</li>
<li><strong>Model checkboxes</strong> &mdash; Check each model you want to include. Each checked model becomes a candidate.</li>
<li><strong>Remove</strong> &mdash; Remove this provider block (only shown when multiple blocks exist).</li>
</ul>
<h4>Claims</h4>
<p>Same input pattern as the Home page:</p>
<ul>
<li><strong>Claims textarea</strong> &mdash; Enter one claim per line.</li>
<li><strong>Upload Claims</strong> &mdash; Load from a <code>.txt</code> file.</li>
<li><strong>Batch Tags</strong> &mdash; Optional labels for the arena's claims.</li>
<li><strong>Stage Claims</strong> / <strong>Clear</strong> &mdash; Move claims to the staging area or clear everything.</li>
</ul>
<h3>Candidates Panel</h3>
<p>Shows a live preview of the candidates that will participate in the arena, based on your model selections. Each candidate is a named combination of provider and model, and each card states plainly what it will run:</p>
<ul>
<li><strong>One model</strong> (default) &mdash; The candidate runs the same model for all four pipeline stages. The card reads "Runs <em>model</em> for all four stages."</li>
<li><strong>Per-stage models</strong> &mdash; Click <strong>Use a different model per stage</strong> on a card to expand an inline editor with one dropdown per stage (Query Generation, Paper Analysis, Venue Scoring, Final Report). Any stage you change is tagged "changed," the card switches to a per-stage breakdown listing exactly what runs where, and a <strong>Reset all stages</strong> button returns it to a single model. You can also rename the candidate here.</li>
</ul>
<h3>Review and Launch</h3>
<ul>
<li><strong>Review &amp; Launch Arena</strong> &mdash; Estimates the cost for all candidates across all claims, then opens a confirmation modal with the breakdown. Check the "I approve this arena spend" checkbox and click <strong>Launch Arena</strong> to start the comparison. You will be redirected to the Arena Workspace.</li>
</ul>
<h3>Advanced Arena Settings</h3>
<p>Click to expand. These settings give you fine-grained control:</p>
<ul>
<li><strong>Execution Mode</strong>:
<ul>
<li><em>Default mode</em> &mdash; Each candidate runs the full pipeline independently (same model for all stages).</li>
<li><em>Reuse retrieval</em> &mdash; Candidate A runs the paper retrieval stage and all other candidates reuse those papers. Useful for comparing analysis quality while controlling for retrieval differences.</li>
</ul>
</li>
<li><strong>Stop After</strong> &mdash; Choose which stage the arena should stop at: Query Generation, Review Evidence, Review Scores, or Final Reports (default). Stopping early lets you inspect intermediate outputs before committing to the full pipeline.</li>
<li><strong>Duplicate Strategy</strong> &mdash; Same as the Home page: Create New Runs or Open Existing Claim.</li>
<li><strong>Queries</strong> / <strong>Results per Query</strong> &mdash; Same as the Home page advanced settings.</li>
<li><strong>Use bibliometric scoring</strong> &mdash; Enable or disable bibliometric weighting.</li>
</ul>
<h4>Advanced Provider Setup</h4>
<p><strong>Add Provider Block</strong> &mdash; Adds a second (or third, etc.) provider block so you can compare models across different API providers in the same arena.</p>
<p>Candidate labels and per-stage model overrides are edited directly on each candidate card under <strong>Candidates</strong> (see above) &mdash; there is no separate editor.</p>
</section>
<!-- ============================================================ -->
<!-- SECTION: Arenas Library -->
<!-- ============================================================ -->
<section class="panel guidebook-section" id="arenas-library">
<h2 class="panel-title">Arenas Library</h2>
<p class="panel-subtitle">Browse and filter all arenas.</p>
<div class="panel-divider"></div>
<p>Navigate here using the <strong>Arenas</strong> link in the top navigation bar.</p>
<h3>Filters</h3>
<ul>
<li><strong>Search arenas</strong> &mdash; Filter by arena title or arena ID.</li>
<li><strong>Status</strong> dropdown &mdash; Filter by arena status:
<ul>
<li><em>All statuses</em> &mdash; Show everything.</li>
<li><em>In Progress</em> &mdash; Arenas that are currently processing.</li>
<li><em>Ready for Review</em> &mdash; Arenas that have completed a stage and are waiting for you to review results and decide which candidates advance.</li>
<li><em>Needs Attention</em> &mdash; Arenas where every run has settled but at least one failed. Open the workspace to review the failures and retry them.</li>
<li><em>Completed</em> &mdash; Arenas that have finished all stages.</li>
</ul>
</li>
</ul>
<h3>Arena Cards</h3>
<p>Each card shows the arena title (or ID), status, number of claims and candidates, and last-updated date. Click <strong>Open Workspace</strong> to navigate to the Arena Workspace for that arena.</p>
</section>
<!-- ============================================================ -->
<!-- SECTION: Arena Workspace -->
<!-- ============================================================ -->
<section class="panel guidebook-section" id="arena-workspace">
<h2 class="panel-title">Arena Workspace</h2>
<p class="panel-subtitle">Monitor, review, and advance a running or completed arena.</p>
<div class="panel-divider"></div>
<p>You reach this page after launching an arena or by clicking "Open Workspace" from the Arenas Library.</p>
<h3>Header</h3>
<ul>
<li><strong>Arena title</strong> and a <strong>summary strip</strong> showing: status, current stage, number of claims, number of models, failed runs (if any), expected cost, and actual cost so far.</li>
<li><strong>Export CSV / Export JSON</strong> &mdash; Download the full model comparison (verdicts, costs, tokens, timings, your picks, summaries, and reasoning) for analysis or sharing.</li>
<li><strong>Refresh state badge</strong> &mdash; Shows whether the workspace is synced or stale.</li>
<li><strong>Last updated</strong> &mdash; Timestamp of the last data refresh.</li>
<li><strong>Refresh Now</strong> &mdash; Manually re-fetch the latest arena data from the server.</li>
</ul>
<h3>Stage Stepper</h3>
<p>A visual progress indicator. For full-pipeline arenas it shows Setup &rarr; Running &rarr; Compare Results. For staged arenas it also shows each pipeline review stage and the winner-selection/continue steps.</p>
<h3>Workspace Tabs</h3>
<p>Three tabs organize the workspace content:</p>
<h4>Overview Tab</h4>
<p>Two tables answer "which model should I use?":</p>
<ul>
<li><strong>Model Scorecard</strong> &mdash; Output quality per model: mean verdict (1&ndash;5), verdict mix, No Evidence count, majority agreement (how often the model matched the consensus verdict), your picks, failed runs, claims with evidence, retrieval overlap with other models, tokens, actual cost, and total time. The best value in key columns is highlighted.</li>
<li><strong>Pipeline Operations</strong> &mdash; Runtime and reliability: status, stage, per-stage timings, issues, retries, and expected cost.</li>
</ul>
<h4>Claims Tab</h4>
<p>This is the comparison bench. It opens with a <strong>Verdict Matrix</strong>: one row per claim, one column per model, each cell a color-coded verdict chip (a ★ marks your pick). The last column flags agreement ("Agree", "Disagree by N pts", or "Split: evidence vs. none"), and the footer shows each model's mean verdict. Click a claim to jump to its side-by-side comparison. Use the toolbar to sort claims (original order, most disagreement, lowest average verdict) and to expand or collapse all outputs.</p>
<p>Below the matrix, claims are grouped by claim text. For each claim:</p>
<ul>
<li>A progress indicator shows how many candidate runs are complete and flags failed runs.</li>
<li>A comparison table lists each model's status, verdict, cost, tokens, issues, and stage-specific metrics, with a <strong>Detail</strong> link to the Claim Detail page and a <strong>Retry</strong> button for failed runs.</li>
<li><strong>Compare Outputs</strong> &mdash; Expands a side-by-side grid with each model's verdict, summary, final reasoning, evidence (papers are marked "Unique to A" or "Also found by B, C"), and search queries aligned in columns so you can read them against each other.</li>
<li><strong>Best</strong> radio buttons (final stage) &mdash; Record which model produced the best output for this claim. Picks are saved to the arena, starred in the matrix, and tallied in the scorecard's "Your Picks" column.</li>
<li><strong>Advance</strong> radio buttons and a <strong>Skip claim</strong> checkbox (staged arenas only) &mdash; Choose which run advances to the next stage. A failed candidate does not block the others: you can still advance a surviving run or retry the failure.</li>
</ul>
<h4>History Tab</h4>
<p>A timeline of all arena activity: when each stage started and finished, which candidates ran, refresh events, and continuation decisions (who advanced, who was skipped).</p>
<h3>Continue Arena Panel</h3>
<p>Visible when the arena has completed a stage and can advance to the next one. Arenas are designed to be iterative: you review results at each stage and decide what moves forward.</p>
<ul>
<li><strong>Estimate Next Stage</strong> &mdash; Calculate the cost of advancing selected claims and candidates to the next pipeline stage.</li>
<li><strong>Continue Arena</strong> &mdash; Opens a confirmation modal showing which claims will advance, the cost delta, and requires you to check "I approve this continuation cost" before confirming.</li>
</ul>
<div class="gb-tip">
<strong>Tip:</strong> You don't have to advance every claim or every candidate. If a candidate is clearly underperforming after the evidence stage, you can skip it to save cost on the more expensive final report stage. Similarly, skip claims that are ambiguous or off-topic to focus resources on the claims that matter most.
</div>
<h3>Understanding the Arena Lifecycle</h3>
<p>An arena progresses through this cycle:</p>
<ul>
<li><strong>Launch</strong> &mdash; All candidates process all claims through the first stage (or up to the "Stop After" setting).</li>
<li><strong>Review</strong> &mdash; The arena pauses. You examine results in the Overview and Claims tabs, select winners, and skip claims you don't want to continue.</li>
<li><strong>Continue</strong> &mdash; Selected claims and candidates advance to the next stage. The arena processes them and pauses again for review.</li>
<li><strong>Complete</strong> &mdash; When all stages are done (or you choose not to continue further), the arena is marked as completed. All results remain accessible for future reference.</li>
</ul>
</section>
<!-- ============================================================ -->
<!-- SECTION: Providers -->
<!-- ============================================================ -->
<section class="panel guidebook-section" id="providers">
<h2 class="panel-title">Providers</h2>
<p class="panel-subtitle">Configure LLM provider connections and manage models.</p>
<div class="panel-divider"></div>
<p>Navigate here using the <strong>Providers</strong> link in the top navigation bar.</p>
<div class="gb-tip">
<strong>Providers vs. Settings (which wins).</strong> This page is the source of truth for which providers and models runs actually use. The provider env values on the <a href="#settings">Settings</a> page (<code>LLM_PROVIDER</code>, <code>LLM_BASE_URL</code>, <code>LLM_API_KEY</code>, <code>LLM_EVALUATION_MODEL</code>) only <em>seed</em> the "Default Config Provider" here. A model's <strong>context window</strong> and <strong>max output tokens</strong> set here take precedence over the <code>LOCAL_MODEL_CONTEXT_OVERRIDE</code> and <code>MODEL_REGISTRY_OVERRIDES</code> fallbacks in Settings (and for Ollama, the live model's window auto-detected from <code>/api/show</code> wins over both). Per-task output budgets are separate and live in Settings → Model Routing &amp; Token Budgets.</div>
<h3>Understanding Provider Types</h3>
<p>Valsci supports several LLM provider types, each with different trade-offs:</p>
<ul>
<li><strong>OpenAI</strong> &mdash; The most common choice. Connects to OpenAI's API (GPT-4o, GPT-4, etc.). Requires an OpenAI API key. Models are high quality but incur per-token costs.</li>
<li><strong>OpenRouter</strong> &mdash; A unified API gateway that provides access to models from many providers (OpenAI, Anthropic, Meta, Google, etc.) through a single API key. Useful if you want to compare models across providers without managing multiple API keys.</li>
<li><strong>Ollama</strong> &mdash; Run open-source models (Llama, Mistral, Gemma, etc.) locally on your own hardware. Free to run but requires sufficient GPU/CPU resources. Valsci can auto-discover which models are installed on your Ollama instance.</li>
<li><strong>llama.cpp</strong> &mdash; Connect to a local llama.cpp server. Similar to Ollama but uses the llama.cpp HTTP server directly.</li>
<li><strong>Azure OpenAI</strong> &mdash; OpenAI models hosted on Microsoft Azure. Requires an Azure OpenAI resource endpoint and API key. Used by organizations with Azure enterprise agreements.</li>
<li><strong>Azure AI Inference</strong> &mdash; Azure's model inference endpoint for non-OpenAI models hosted on Azure. Requires a separate endpoint URL.</li>
</ul>
<h3>Provider Sidebar</h3>
<p>The left panel lists all available provider types. Each row has:</p>
<ul>
<li><strong>Toggle switch</strong> &mdash; Enable or disable this provider type. Disabled providers don't appear in the Provider dropdowns on other pages.</li>
<li><strong>Click the row</strong> &mdash; Select this provider type for editing in the right panel.</li>
</ul>
<h3>Provider Editor</h3>
<p>The right panel shows the configuration for the selected provider. An <strong>Unsaved changes</strong> badge appears when you have modified settings that haven't been saved yet.</p>
<h4>Connection Settings</h4>
<ul>
<li><strong>Label</strong> &mdash; A display name for this provider (shown in dropdowns across the app).</li>
<li><strong>API Key</strong> &mdash; The authentication key for the provider's API. Stored locally in the provider catalog file.</li>
<li><strong>Base URL</strong> &mdash; Only needed if the provider uses a non-default API endpoint (e.g., a proxy or self-hosted deployment).</li>
</ul>
<p>Additional fields appear depending on the provider type:</p>
<ul>
<li><strong>Local Backend</strong> (Local provider) &mdash; Select between Ollama and llama.cpp backends.</li>
<li><strong>HTTP Referer / Site Name</strong> (OpenRouter) &mdash; Optional headers sent with OpenRouter API requests.</li>
<li><strong>Azure OpenAI Endpoint / API Version</strong> (Azure OpenAI) &mdash; Your Azure resource endpoint and API version.</li>
<li><strong>Azure AI Inference Endpoint</strong> (Azure AI Inference) &mdash; Your Azure AI inference endpoint URL.</li>
</ul>
<h4>Discover Models (Ollama only)</h4>
<p>When an Ollama-type provider is selected, a discovery section appears:</p>
<ul>
<li><strong>Discover From Provider URL</strong> &mdash; Queries the provider's configured base URL to find all available Ollama models.</li>
<li><strong>Probe Alternate URL</strong> &mdash; Queries a different URL (entered in the Alternate URL field) to find models. Useful if Ollama is running on a different port or host.</li>
</ul>
<p>Discovered models appear in an import modal where you can filter, select, and add them to the provider.</p>
<h4>Model Import Modal</h4>
<p>After discovery, this modal shows all found models:</p>
<ul>
<li><strong>Filter</strong> &mdash; Type to search among discovered models.</li>
<li><strong>Select Visible</strong> / <strong>Clear Visible</strong> &mdash; Bulk check or uncheck all models matching the current filter.</li>
<li><strong>Individual checkboxes</strong> &mdash; Select specific models to import.</li>
<li><strong>Add Models</strong> &mdash; Merge the selected models into the provider's model list. Nothing is saved to disk until you click Save Provider.</li>
<li><strong>Cancel</strong> &mdash; Close the modal without importing.</li>
</ul>
<h4>Models Section</h4>
<p>Lists all models configured for this provider. The badge shows the total count. For each model:</p>
<ul>
<li><strong>Model Name</strong> &mdash; The identifier sent to the API (e.g., <code>gpt-4o</code>, <code>llama3:latest</code>).</li>
<li><strong>Label</strong> &mdash; Optional human-friendly name shown in the UI.</li>
<li><strong>Context Window</strong> &mdash; Maximum input token capacity.</li>
<li><strong>Default Max Output</strong> &mdash; Default limit on output tokens per request.</li>
<li><strong>Input Cost / Output Cost</strong> &mdash; Price per million tokens, used for cost estimation.</li>
<li><strong>Supports temperature</strong> &mdash; Whether the model accepts a temperature parameter.</li>
<li><strong>Supports JSON mode</strong> &mdash; Whether the model supports structured JSON output.</li>
<li><strong>Enabled</strong> &mdash; Whether this model appears in model selectors across the app.</li>
<li><strong>Remove</strong> &mdash; Delete this model entry from the provider.</li>
</ul>
<p><strong>Add Model</strong> &mdash; Adds a blank model row for manual configuration.</p>
<h4>Provider Actions</h4>
<ul>
<li><strong>Save Provider</strong> &mdash; Persist all changes (connection settings, models) to the provider catalog file on disk.</li>
<li><strong>Reset</strong> &mdash; Discard unsaved changes and reload the last saved state.</li>
<li><strong>Delete Provider</strong> &mdash; Permanently remove this provider and all its models. Only shown for providers that have been previously saved.</li>
</ul>
<div class="gb-tip">
<strong>Tip:</strong> Set accurate Input Cost and Output Cost values for each model. These are used for cost estimation before every run. If you leave them at zero, cost estimates will show $0.00 even though the actual API call may incur charges from your provider. Check your provider's pricing page for current rates.
</div>
<div class="gb-tip">
<strong>Tip:</strong> For Ollama users, use the <strong>Discover From Provider URL</strong> button after installing new models. It automatically detects all models available on your Ollama instance and lets you import them with one click, saving you from manually entering model names and parameters.
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION: Settings -->
<!-- ============================================================ -->
<section class="panel guidebook-section" id="settings">
<h2 class="panel-title">Settings</h2>
<p class="panel-subtitle">Edit Valsci's configuration (env_vars.json) from the browser.</p>
<div class="panel-divider"></div>
<p>The <strong>Settings</strong> page edits the values in <code>app/config/env_vars.json</code>. Settings are organized into collapsible groups (AI Provider, Model Routing &amp; Token Budgets, Performance &amp; Rate Limits, Literature Data, Diagnostics &amp; Tracing, Email, Security, General, and Storage Paths). Each setting shows a friendly label, its raw key, a description, and badges for whether it is <strong>Configured</strong> (set in your file) or running on a <strong>Default</strong>.</p>
<h3>Finding and editing settings</h3>
<ul>
<li><strong>Search</strong> &mdash; Filter all settings by name or description.</li>
<li><strong>Only configured</strong> &mdash; Show just the settings you have explicitly set.</li>
<li><strong>Save Changes</strong> &mdash; Writes every change back to env_vars.json. A <strong>Unsaved changes</strong> badge appears while you have pending edits.</li>
</ul>
<div class="gb-tip">
<strong>Restart badge.</strong> Saving applies changes to the running web app immediately, but the background <em>processor</em> reads its configuration at startup. Settings marked <span class="badge neutral-badge">Restart</span> only affect claim processing after you restart the processor (e.g. <code>docker compose restart processor</code>).
</div>
<h3>Per-task output token budgets</h3>
<p>Under <strong>Model Routing &amp; Token Budgets</strong>, the <strong>Task Routing &amp; Budgets</strong> setting includes a friendly editor with one field per pipeline stage (Query Generation, Paper Analysis, Venue Scoring, Final Report). Each field sets the maximum number of tokens a model may generate for that stage.</p>
<p>This matters for <strong>reasoning ("thinking") models</strong>: they spend output tokens on hidden chain-of-thought before answering, so a budget that is too small gets used up before any answer is produced, and the run fails with empty output. If you see that error, raise the budget for the named stage (e.g. 16000) here. Leave a field blank to use the built-in default. The full routing object is still editable as raw JSON under <strong>Advanced</strong>.</p>
<h3>Structured-output reliability</h3>
<p>Also under <strong>Model Routing &amp; Token Budgets</strong>, two settings control how strictly Valsci holds models to the JSON shape it expects for the final report and query generation:</p>
<ul>
<li><strong>Strict JSON Schema</strong> (on by default) &mdash; Forces those stages to match an exact JSON schema instead of just "valid JSON," so a model can't invent its own field names. If a provider doesn't support schema mode, Valsci automatically falls back to plain JSON. Recommended on; especially helpful for local models that otherwise drift from the required fields.</li>
<li><strong>JSON Repair Pass</strong> (off by default) &mdash; When a model returns valid JSON with the wrong fields, run a second LLM pass that reshapes its output into the required schema (without changing the content), then re-validate. It costs an extra call only when the first output fails validation. Turn it on if a particular model frequently produces non-conforming output even with strict schema.</li>
</ul>
</section>
<!-- ============================================================ -->
<!-- SECTION: Migration -->
<!-- ============================================================ -->
<section class="panel guidebook-section" id="migration">
<h2 class="panel-title">Migration</h2>
<p class="panel-subtitle">Import or clean up legacy batch folders from older versions of Valsci.</p>
<div class="panel-divider"></div>
<p>Navigate here using the <strong>Migration</strong> link in the top navigation bar, or from the migration alert on the Home page.</p>
<div class="gb-tip">
<strong>Tip:</strong> If you've never used an older version of Valsci, this page will be empty and you can safely ignore it.
</div>
<h3>Header Actions</h3>
<ul>
<li><strong>Refresh</strong> &mdash; Re-scan for legacy batch folders and update the status.</li>
<li><strong>Migrate &amp; Archive Pending</strong> &mdash; Import every pending legacy batch into the canonical claim store, then move those old folders into the migration archive.</li>
</ul>
<h3>Migration Status</h3>
<p>An info card showing the result of the latest migration action, including how many runs were created, how many already existed, how many legacy folders were archived, and whether any pending batches remain.</p>
<h3>Batch Table</h3>
<p>A table listing all detected legacy batches with columns for:</p>
<ul>
<li><strong>Batch</strong> &mdash; The batch ID.</li>
<li><strong>Claims</strong> &mdash; Number of claims in the batch.</li>
<li><strong>Last Modified</strong> &mdash; When the batch was last updated.</li>
<li><strong>Status</strong> &mdash; Whether the legacy folder is pending, partially imported, or already represented by canonical runs.</li>
<li><strong>Roots</strong> &mdash; Which legacy directories contain this batch's data.</li>
<li><strong>Actions</strong>:
<ul>
<li><strong>Review contents</strong> &mdash; Opens the Batch Review Panel below to inspect the claims in this batch.</li>
<li><strong>Import</strong> &mdash; Import this specific pending batch into the canonical claim store and archive the legacy folder.</li>
<li><strong>Archive</strong> &mdash; Move an already imported legacy folder into the migration archive without creating duplicate runs.</li>
</ul>
</li>
</ul>
<h3>Batch Review Panel</h3>
<p>Opens when you click "Review contents" on a batch. Shows each claim in the batch with its text, status, stage, and last update. Actions:</p>
<ul>
<li><strong>Import &amp; Archive</strong> &mdash; Import this reviewed batch and move the old folder into the migration archive.</li>
<li><strong>Archive Legacy Copy</strong> &mdash; Available when the canonical run already exists; moves the old folder into the migration archive.</li>
<li><strong>Delete Legacy Batch</strong> &mdash; Permanently remove the legacy batch folder without importing. Use this to clean up batches you no longer need.</li>
</ul>
</section>
<!-- ============================================================ -->
<!-- SECTION: Trace View -->
<!-- ============================================================ -->
<section class="panel guidebook-section" id="trace-view">
<h2 class="panel-title">Trace View</h2>
<p class="panel-subtitle">Inspect the detailed execution trace for a claim run.</p>
<div class="panel-divider"></div>
<p>You reach this page from the Claim Report ("View Full Trace") or Claim Detail ("Open Trace").</p>
<h3>What Is a Trace?</h3>
<p>A trace is a chronological log of every significant action during a claim's evaluation: each LLM call (with the exact prompts and responses), Semantic Scholar API requests, paper parsing steps, scoring calculations, and error recovery. It provides full transparency into how Valsci arrived at its verdict.</p>
<h3>Trace Records</h3>
<p>Each record in the trace is displayed as a row with:</p>
<ul>
<li><strong>Timestamp</strong> &mdash; When the action occurred.</li>
<li><strong>Stage</strong> &mdash; Which pipeline stage (query generation, paper analysis, venue scoring, or final report).</li>
<li><strong>Type</strong> &mdash; The kind of action (LLM call, API request, processing step, error, etc.).</li>
<li><strong>Details</strong> &mdash; Expandable content showing full request/response data, token counts, model used, and timing.</li>
</ul>
<h3>Navigation</h3>
<ul>
<li><strong>Highlighted records</strong> &mdash; Error-like records (failures, retries, warnings) are visually highlighted so you can quickly spot issues.</li>
<li><strong>Focused record</strong> &mdash; If you arrived via a link from an issue banner (e.g., "View trace section"), the relevant record is scrolled into view and highlighted.</li>
</ul>
<div class="gb-tip">
<strong>Tip:</strong> Traces are most useful for debugging unexpected ratings, understanding why certain papers were included or excluded, and verifying that prompts are working as intended.
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION: Login -->
<!-- ============================================================ -->
<section class="panel guidebook-section" id="login">
<h2 class="panel-title">Login</h2>
<p class="panel-subtitle">Password protection for your Valsci instance.</p>
<div class="panel-divider"></div>
<p>When password protection is enabled in your configuration (<code>REQUIRE_PASSWORD</code> set to <code>true</code>), all pages require authentication. You'll be redirected to the login page if your session has expired or you haven't logged in.</p>
<h3>Login Form</h3>
<p>Enter the access password configured in your environment settings and click <strong>Log In</strong>. If the password is incorrect, an error message will appear.</p>
<h3>Logout</h3>
<p>Click the <strong>Logout</strong> button in the top-right corner of any page. This clears your session and redirects you to the login page.</p>
<div class="gb-tip">
<strong>Tip:</strong> Password protection is optional. If you're running Valsci locally for personal use and don't need authentication, you can disable it by setting <code>REQUIRE_PASSWORD</code> to <code>false</code> in your configuration.
</div>
</section>
</div><!-- .guidebook-body -->
</div><!-- .guidebook-layout -->
{% endblock %}
{% block scripts %}
<script>
(() => {
const button = document.getElementById("copyGuidebookMarkdownBtn");
const status = document.getElementById("copyGuidebookStatus");
if (!button || !status) {
return;
}
function squeeze(value) {
return String(value || "").replace(/\s+/g, " ").trim();
}
function inlineMarkdown(node) {
if (node.nodeType === Node.TEXT_NODE) {
return node.textContent || "";
}
if (node.nodeType !== Node.ELEMENT_NODE) {
return "";
}
const tag = node.tagName.toLowerCase();
if (tag === "br") {
return "\n";
}
if (tag === "code") {
return "`" + squeeze(node.textContent).replace(/`/g, "\\`") + "`";
}
const inner = Array.from(node.childNodes).map(inlineMarkdown).join("");
if (tag === "strong" || tag === "b") {
return "**" + squeeze(inner) + "**";
}
if (tag === "em" || tag === "i") {
return "*" + squeeze(inner) + "*";
}
if (tag === "a") {
const text = squeeze(inner);
const href = node.getAttribute("href") || "";
return href && !href.startsWith("#") ? `[${text}](${href})` : text;
}
return inner;
}
function inlineText(element) {
return squeeze(Array.from(element.childNodes).map(inlineMarkdown).join(""));
}
function appendList(list, lines, depth = 0) {
const ordered = list.tagName.toLowerCase() === "ol";
Array.from(list.children).filter((child) => child.tagName.toLowerCase() === "li").forEach((item, index) => {
const nestedLists = [];
const parts = [];
Array.from(item.childNodes).forEach((child) => {
if (child.nodeType === Node.ELEMENT_NODE && ["ul", "ol"].includes(child.tagName.toLowerCase())) {
nestedLists.push(child);
} else {
parts.push(inlineMarkdown(child));
}
});
const prefix = ordered ? `${index + 1}.` : "-";
lines.push(`${" ".repeat(depth)}${prefix} ${squeeze(parts.join(""))}`);
nestedLists.forEach((nested) => appendList(nested, lines, depth + 1));
});
lines.push("");
}
function appendBlock(element, lines) {
if (element.nodeType !== Node.ELEMENT_NODE) {
return;
}
if (element.classList.contains("panel-divider") || element.classList.contains("guidebook-toolbar")) {
return;
}
const tag = element.tagName.toLowerCase();
if (tag === "h2") {
lines.push(`## ${inlineText(element)}`, "");
return;
}
if (tag === "h3") {
lines.push(`### ${inlineText(element)}`, "");
return;
}
if (tag === "h4") {
lines.push(`#### ${inlineText(element)}`, "");
return;
}
if (tag === "p") {
lines.push(inlineText(element), "");
return;
}
if (tag === "ul" || tag === "ol") {
appendList(element, lines);
return;
}
if (tag === "dl") {
const children = Array.from(element.children);
for (let index = 0; index < children.length; index += 2) {
const term = children[index];
const description = children[index + 1];
if (term && description) {
lines.push(`- **${inlineText(term)}:** ${inlineText(description)}`);
}
}
lines.push("");
return;
}
if (element.classList.contains("gb-tip")) {
lines.push(`> ${inlineText(element)}`, "");
return;
}
Array.from(element.children).forEach((child) => appendBlock(child, lines));
}
function buildMarkdown() {
const lines = ["# Valsci Guidebook", ""];
document.querySelectorAll(".guidebook-section").forEach((section) => {
Array.from(section.children).forEach((child) => appendBlock(child, lines));
});
return lines.join("\n").replace(/\n{3,}/g, "\n\n").trim() + "\n";
}
async function copyText(text) {
if (navigator.clipboard?.writeText) {
try {
await navigator.clipboard.writeText(text);
return;
} catch (error) {
// Fall through to the textarea fallback.
}
}
const textarea = document.createElement("textarea");
textarea.value = text;
textarea.setAttribute("readonly", "");
textarea.style.position = "fixed";
textarea.style.left = "-9999px";
document.body.appendChild(textarea);
textarea.select();
document.execCommand("copy");
textarea.remove();
}
button.addEventListener("click", async () => {
button.disabled = true;
status.textContent = "Copying...";
try {
await copyText(buildMarkdown());
status.textContent = "Copied";
window.setTimeout(() => {
status.textContent = "";
}, 2400);
} catch (error) {
status.textContent = "Copy failed";
} finally {
button.disabled = false;
}
});
})();
</script>
{% endblock %}