ClinStat AI — User Manual

Clinical Statistical Analysis with AI Interpretation

ClinStat AI Development Team

Version 0.1.0: June 2026

Clinical Statistical Analysis with AI Interpretation

Cross-platform desktop application for clinician researchers (MDs, PhDs, epidemiologists) who need publication-ready statistical output without learning SPSS, SAS, or R.


Repository: https://github.com/windysky/clinstat-ai

This manual reflects the application state at HEAD on the main branch. Current automated-gate counts (TypeScript, vitest, R testthat) are tracked in PROJECT_HANDOFF.md.

This is an evaluation-stage release. On first launch, you must accept the Evaluation License Agreement before using the application. See the First Launch chapter for details.

Table of Contents

  1. Introduction
  2. Architecture Overview
  3. System Requirements
  4. Installation (Testing Release)
  5. First Launch
  6. Main Workspace Tour
  7. Importing Data
  8. Variable Profile and Inspection
  9. Core Statistical Analyses
  10. Advanced (Phase 2) Analyses
  11. Bayesian Analyses
  12. Interactive Power Calculator
  13. AI Interpretation
  14. Guided Analysis Wizard
  15. Report Editor and Export
  16. Licensing and Activation
  17. Settings and Configuration
  18. Data Privacy and Security
  19. Troubleshooting
  20. Keyboard Shortcuts and Reference

1. Introduction

ClinStat AI is a cross-platform desktop application that brings together three technologies clinician researchers rely on, but in a single integrated workspace:

Typical users are clinician researchers running a cohort study, a randomized trial, or a secondary analysis of a registry dataset, who want to go from a cleaned CSV file to a publication-ready statistical output in minutes rather than days. ClinStat AI covers the common clinical tests (t-tests, ANOVA, chi-square, correlation, linear and logistic regression), survival analysis (Kaplan-Meier, Cox proportional hazards), longitudinal methods (GEE, repeated-measures ANOVA, linear mixed models), causal-inference adjustments (propensity score matching, IPTW), Bayesian regression (via rstanarm/Stan), and diagnostic metrics (ROC with DeLong’s test).

The application is designed around three core guarantees:

  1. Data stays on your machine. All statistical computation runs locally in R. The configured AI provider receives only aggregated summaries and variable metadata, never patient-level rows.
  2. Reproducibility first. Every analysis can export the exact R code that produced it, together with R package versions and random seeds, so your methods section writes itself.
  3. Clinical sensibility over raw flexibility. The rules engine detects common mistakes (using a t-test on non-normal paired data, omitting the continuity correction on a 2×2 table with small cell counts) and surfaces them as warnings before you run the analysis.

First-launch note: The Evaluation License Agreement must be accepted before the app becomes usable. See the First Launch chapter for details on the EULA gate, including the scroll-to-bottom requirement and persistent acceptance storage.

This manual covers the current evaluation release (version 0.1.0, June 2026). The app is HIPAA-aware but not HIPAA-certified; see the Licensing chapter for usage restrictions.

2. Architecture Overview

ClinStat AI is a native desktop application, not a web application. You do not open it in a browser or visit a URL. You download an installer, run it once, and then launch the app from your Start menu, Applications folder, or application launcher like any other native program.

Under the hood, ClinStat AI uses Electron, which packages a lightweight Chromium rendering engine together with a Node.js runtime into a single installable bundle. This gives the application:

The statistical engine is a separate R installation on your computer. ClinStat AI detects R automatically on first launch and invokes it for every analysis. When the optional Rserve feature is enabled (by setting the environment variable RSERVE_ENABLED=true), analyses run through a persistent TCP connection to a long-running R session, reducing round-trip latency by 60-80 percent compared to the default per-analysis Rscript spawn. R-bridge registry: The app maintains one cached bridge per R installation, so cancellation (including mid-analysis cancel) and app-quit properly reach in-flight runs.

Data flow for a typical analysis:

  1. You import a CSV, Excel, STATA, SPSS, or SAS dataset. The main process reads the file, validates it, and stores it in a local SQLite database inside your project folder.
  2. You select an analysis from the rules-engine-driven menu. The UI validates your variable choices (type compatibility, sample size adequacy) before the R call is even constructed.
  3. The main process serializes your payload to a temporary JSON file and invokes the appropriate R script (or sends it to the Rserve session).
  4. R produces a structured JSON result plus any figures as PNG files. The UI reads the result and renders tables, figures, assumption checks, and effect sizes.
  5. If AI interpretation is enabled, the main process sends only the aggregated summary (coefficient table, variable metadata) to the configured local LLM (OpenAI-compatible endpoint), never the raw data rows.
  6. You export to Word, Excel, or a publication-ready figure PNG.

Project files are stored as .clinstat folders containing the SQLite dataset, analysis history, figures, and report drafts. Transferring a project between machines means copying one folder.

3. System Requirements

3.1 Supported operating systems

Platform Minimum version Notes
Windows Windows 10 22H2 (64-bit) Also tested on Windows 11 23H2 and later
macOS macOS 12 Monterey (Intel) / macOS 13 Ventura (Apple Silicon) Universal binary; Apple Silicon native
Linux Ubuntu 22.04 LTS or compatible distribution with glibc ≥ 2.31 AppImage; runs on Fedora, Debian, openSUSE

Windows 7, 8, and 8.1 are not supported. macOS 11 Big Sur and earlier are not supported. On Linux, distributions with glibc older than 2.31 (such as RHEL 8 and derivatives) may require LD_LIBRARY_PATH tuning.

3.2 Hardware

Resource Minimum Recommended
CPU 64-bit dual-core at 2 GHz Modern quad-core Intel / AMD / Apple M-series
RAM 4 GB 8 GB or more (larger for datasets over 100k rows)
Disk 500 MB for the app + Chromium runtime 1 GB or more for project files
Display 1280 × 800 1920 × 1080

3.3 Dependencies you must install separately

R: version 4.x (4.2 or later), available from https://cran.r-project.org on all three platforms. On first launch, ClinStat AI will detect R automatically (Windows: registry lookup; macOS: standard /usr/local/bin/Rscript and framework install locations; Linux: PATH lookup). If detection fails, you can point the application at your R install in the Settings panel.

For the advanced analyses, install the following R packages once:

install.packages(c("survival", "nlme", "lme4", "emmeans",
                   "geepack", "car", "MatchIt", "WeightIt",
                   "pROC", "pwr", "metafor", "mice"))

For Bayesian analyses, additionally install rstanarm. It installs as prebuilt binaries on every platform — no C++ toolchain is required. It is a large one-time download (several hundred MB with dependencies).

No other dependency is required. Electron, Node.js, and all JavaScript packages are bundled into the installer. Python is not used.

3.4 Network

ClinStat AI runs fully offline for all statistical computation. A network connection is required only for:

4. Installation (Testing Release)

This is a testing release. Installers are not yet code-signed. Windows SmartScreen and macOS Gatekeeper will therefore flag the installer on first run; this is expected during the testing phase and is not a sign of malware. Production-signed installers will be published once the Extended Validation certificate and Apple Developer ID enrollment are complete.

Clone the repository and install dependencies:

git clone https://github.com/windysky/clinstat-ai.git
cd clinstat-ai
nvm use 20           # or 22, or 24: any Node ≥ 20.17
npm install
npx electron-builder install-app-deps   # rebuilds native modules for Electron

Start the application in development mode (with hot-reload):

npm run dev

The application window opens within a few seconds. The Vite dev server running on localhost:5173 is an internal development convenience; end users of signed installers do not see it.

4.2 Option B: Build a local installer

From the project root, build an installer for your own platform:

# Windows: produces release/ClinStat AI-0.1.0-setup.exe
npm run build:win

# macOS: produces release/ClinStat AI-0.1.0.dmg
npm run build:mac

# Linux: produces release/ClinStat AI-0.1.0.AppImage
npm run build:linux

The installer or AppImage appears in the release/ folder. Because this is a testing release, SmartScreen and Gatekeeper will flag the file:

4.3 WSL2 on Windows

ClinStat AI can be run from Windows Subsystem for Linux 2 with WSLg (Windows 11) or an X server (Windows 10). All development-mode features work. This is a convenient path for testing on Linux without a separate Linux host.

4.4 Verifying the installation

On first launch, the title bar reads ClinStat AI. The footer shows four pieces of status text:

If R is not detected, you can continue to explore the UI but analyses will not run until R is installed and detected.

5. First Launch

5.1 Evaluation License Agreement (EULA) Gate

The first time you launch ClinStat AI, before the main window opens, you must accept the Evaluation License Agreement (see Figure 5.1):

Figure 5.1: ClinStat AI EULA gate: scroll-to-bottom enforced before Accept is enabled.

The Agreement is presented in a scrollable modal containing the full legal text from docs/legal/EVALUATION_LICENSE.md. The key points:

Scroll-to-bottom requirement: You must scroll to the bottom of the Agreement before the I Agree button becomes enabled. Alternatively, check the “I have read the Agreement” checkbox to acknowledge you have read the full text.

Persistent acceptance: Once accepted, the gate does not reappear on subsequent launches unless the EULA_VERSION constant changes (e.g., when the legal text is updated in a future release).

Corrupt store recovery: If the electron-store file becomes corrupted or deleted, the gate reappears on the next launch. Re-accept to restore functionality.

5.2 Data Handling Notice

The first time you launch ClinStat AI, a native dialog appears before the main window opens. The notice reads:

ClinStat AI processes clinical data locally on your machine. No patient-identifiable data is sent to external services. AI features transmit only aggregated summaries.

Click I Understand to proceed. The dialog appears only on first launch; after acknowledgement, it is suppressed via a flag in electron-store and does not reappear.

5.3 Onboarding setup

The onboarding page walks you through three quick steps:

Figure 5.2: Three-step onboarding: R detection, local LLM configuration, license activation.

R Environment

This block confirms that ClinStat AI has located an R installation. If the indicator is green, you are done: no action required. If not, follow the prompt to install R from https://cran.r-project.org and click Re-detect.

AI Provider (Local LLM)

ClinStat AI uses a user-configured local LLM (OpenAI-compatible endpoint) for AI interpretation. You must configure the provider before AI features work:

Recommended model: meta/llama-3.2-3b (fast, ~5-19s for interpretation on typical hardware). Not recommended for interactive use: Reasoning models (models that expose a reasoning_content field). These burn tokens on hidden chain-of-thought and can exceed the 90s timeout. Use them only for single, publication-grade interpretations where longer wait times are acceptable.

Click Test Connection to verify the endpoint is reachable. If you click Skip, ClinStat AI enters standalone mode: all statistical analyses work, but the AI narrative panel is replaced with a placeholder. You can configure the provider later from Settings → AI provider.

License

The current release is evaluation-licensed (see docs/legal/EVALUATION_LICENSE.md). No commercial use, clinical decision-making, or redistribution is permitted. The Start Free option continues with the evaluation tier (full features for non-commercial evaluation). Future commercial licensing will require a separate license key.

Click I Understand once all three steps show a green indicator. You are now at the Welcome screen.

6. Main Workspace Tour

6.1 The Welcome screen

Figure 6.1: Welcome screen with quick-start cards and bundled sample datasets.

The Welcome screen (Figure 6.1) offers three entry points:

Below the three cards, the Source section lists the four bundled clinical datasets:

Clicking any sample dataset card loads it into the current project.

6.2 Top navigation

The application shell has several routes, accessible via the top bar or through navigation:

Primary routes:

Secondary routes:

Every screen shows a footer with live status:

R available | License label | 0 tokens used this session | Saved

7. Importing Data

Figure 7.1: Import flow: format selection and file picker

The import modal. ClinStat AI supports CSV, Excel, SPSS, SAS, and Stata; magic-byte verification rejects misnamed files before they reach the parser.

7.1 Supported formats

Format Extension R package used Notes
CSV .csv base R (readr) Most robust; UTF-8 assumed
Excel 2007+ .xlsx readxl First sheet imported by default
Excel legacy .xls readxl Supported
STATA .dta haven Labels preserved as factor levels
SPSS .sav haven Value labels and variable labels preserved
SAS .sas7bdat haven Labels preserved

If the optional R package haven is not installed, the foreign-format imports will prompt you to install it.

7.2 Magic-byte validation

For the three foreign formats, ClinStat AI performs a magic-byte check before passing the file to R. This prevents a malformed or misnamed file (for example, a .sas7bdat that is actually a CSV with a wrong extension) from causing an unhelpful R-side crash. If the magic-byte check fails, the import is aborted with a structured error code ERR-FOREIGN-MAGIC-MISMATCH and a clear user message.

7.3 The import flow

  1. Click Import Your Data on the Welcome screen, or choose File → Import from the top bar.
  2. Select the file in the native file-picker.
  3. ClinStat AI performs the magic-byte check (for foreign formats) and reads the file.
  4. A preview grid appears showing the first 200 rows, detected column types, and any parsing warnings.
  5. You can rename columns, override detected types, or mark columns as “exclude from analysis” in this preview.
  6. Click Confirm Import. The dataset is copied into the project’s SQLite database and the variable profile is computed.

7.4 Data viewer

Figure 7.2: Data viewer: AG Grid with a loaded dataset

The Data route showing the blood-pressure-trial sample in a virtualized AG-Grid. Column headers show detected types; clicking a header opens the variable’s detail card.

After import, the Data route shows the dataset in a virtualized AG-Grid viewer (fast on up to 100k rows). Each column header shows the detected type (numeric, factor, integer, date). Clicking a column header brings up the variable’s detail card: histogram or bar chart, summary statistics, missingness percentage, unique value count, and any flags (for example, “suspected ID column: will be excluded from analyses unless you explicitly select it”).

Figure 7.3: Data view before any dataset is loaded: subsequent screens show the full grid.

Datasets above 100k rows are still importable, but the viewer switches to paged mode (1000 rows per page) and some interactive flourishes (hover highlights, spark-lines) are disabled to preserve responsiveness.

8. Variable Profile and Inspection

Figure 8.1: Variable profile: per-variable histograms and missingness

The Profile tab: one card per variable with distribution, summary statistics, and missingness: computed in R on import.

Once a dataset is loaded, the Data route also displays the automatic variable profile: a one-card-per-variable summary computed in R on import. Each card includes:

8.1 Variable type overrides

If the automatic type detection disagrees with your intent: for example, a 0/1 coded variable detected as integer when you want it treated as a binary factor: you can override the type from the variable card. The override is project-local and does not modify the source file.

8.2 Missingness analysis

The Data route’s Missingness tab shows an upset-plot-style visualization of missingness patterns: which variables are missing together, what fraction of rows are completely observed, and whether missingness is monotone (typical of dropout) or arbitrary (typical of technical failures).

For datasets with non-trivial missingness, ClinStat AI offers:

8.3 Privacy and ID columns

Columns with high uniqueness (e.g., patient_id, mrn) are automatically excluded from analyses unless explicitly selected. This is a safety measure against accidentally shipping patient identifiers to the AI interpretation layer. You can confirm by inspecting the AI payload preview (available from the AI sidebar) before each interpretation request.

8.4 Data Transform

Figure 8.2: Data Transform panel: recode, derive, and power transforms

The Data Transform panel (from the data viewer): normalizing transforms (Box-Cox / Yeo-Johnson), recode, and derive-new-variable tools.

The Data Transform panel (accessible from the data viewer) provides tools for normalizing and transforming variables. It has three modes:

Transformed variables are added to the dataset and can be used in analyses like any other variable. The transform recipe is stored in the project history for reproducibility.

9. Core Statistical Analyses

The Analysis route is where every statistical test is run.

Figure 9.1: Analysis configuration: selecting a two-group comparison

Configuring a two-group t-test: pick the group + outcome variables and the confidence level before Run.

The left panel lets you select a test; the main panel shows variable selectors, assumption checks, results, and figures; the right panel (collapsible) shows AI interpretation narrative.

Figure 9.2: Completed analysis result: two-group t-test

A completed two-group t-test: the statistics table (t, p, Cohen’s d), the assumption-check summary, and the plain-language interpretation.

Figure 9.3: Analysis view before the first analysis is run.

9.1 Tests included in the core set

Test When to use R function under the hood
Baseline characteristics table Descriptive “Table 1” for a two-group comparison table1-style via base R + gtsummary
Independent-samples t-test Two independent groups, continuous outcome, normality assumption stats::t.test
Paired t-test Paired continuous outcomes (before / after on the same subjects) stats::t.test(paired = TRUE)
One-way ANOVA Three or more independent groups, continuous outcome stats::aov + emmeans for contrasts
Pearson / Spearman correlation Linear association between two continuous variables stats::cor.test
Chi-square / Fisher’s exact Association between two categorical variables stats::chisq.test / stats::fisher.test
Simple linear regression Continuous outcome, one continuous predictor stats::lm + diagnostic plots
Multiple linear regression Continuous outcome, multiple predictors stats::lm with stepwise or user-specified
Logistic regression Binary outcome, one or more predictors stats::glm(family = binomial)

9.2 Direction and level control

Binary outcomes (logistic regression): The caseLevel parameter lets you specify which level of the binary outcome represents the “case” (event of interest). If not specified, the level is chosen automatically (first level alphabetically by default). Explicitly setting caseLevel ensures your odds ratios represent the direction you intend.

Ordered outcomes (ordinal logistic regression): The outcomeLevels parameter defines the order of outcome categories. If not specified, levels are ordered alphabetically by default. For clinical outcomes with a natural order (e.g., “None”, “Mild”, “Moderate”, “Severe”), specify the levels explicitly to ensure correct coefficient signs.

Nominal outcomes (multinomial regression): The referenceLevel parameter sets which category is the reference. Coefficients represent log-odds relative to this reference.

Categorical predictors: All regression routines automatically preserve categorical predictors as dummy variables (factor → k-1 indicators). You do not need to manually create dummies; the routine handles factor columns correctly.

Forest plots: When pooling ratio measures (OR, RR, HR), the measure parameter must be specified. Forest plots pool on the log scale for ratio measures (MD/SMD use raw scale). This ensures correct pooled estimates, confidence intervals, and heterogeneity statistics (I²).

9.3 Known-answer validation

Each core analysis has a corresponding testthat test that runs against R’s built-in datasets with known answers. For example, the t-test test asserts that comparing setosa vs versicolor sepal lengths from iris yields p < 0.001. The linear regression test asserts R² ≈ 0.83 for mpg ~ wt + cyl from mtcars. These regressions run as part of the CI suite and guarantee the R engine produces numbers matching any textbook.

10. Advanced (Phase 2) Analyses

Figure 10.1: Phase-2 analysis: Cox proportional hazards configuration

The Phase-2 panel: survival, longitudinal, causal-inference, and diagnostic methods, dispatched through the same engine as the core analyses.

Phase 2 analyses extend the core set to cover clinical methods that go beyond an introductory statistics course. All are dispatched through the same rules-engine + IPC mechanism as the core analyses, but ship in their own panels for clarity.

10.1 Survival analysis

Kaplan-Meier estimator: non-parametric survival curve. Inputs: time variable, event indicator, optional stratification factor. Outputs: median survival, 95% CI per stratum, log-rank test across strata, survival curve figure. Uses survival::survfit.

Cox proportional-hazards regression: semi-parametric hazard-ratio model. Inputs: time, event, predictor(s). Outputs: hazard ratios with 95% CI, Schoenfeld residual test for the proportional-hazards assumption, forest plot figure. Uses survival::coxph.

10.2 Longitudinal analysis

Linear mixed models: random-intercept and random-slope models for repeated measures. Uses nlme::lme or lme4::lmer (auto-select based on model complexity). Outputs fixed effects, random-effects variance, ICC, and model comparison (LRT).

Repeated-measures ANOVA: classical within-subject ANOVA with Huynh-Feldt sphericity correction. The between-subjects factor is not yet supported in this release; use a linear mixed model instead.

Generalized Estimating Equations: population-average models for non-Gaussian outcomes with within-subject correlation. Uses geepack::geeglm. Families supported: gaussian, binomial, poisson.

10.3 Causal inference

Propensity score matching (PSM): 1:1 nearest-neighbor matching on the propensity score with optional caliper. Uses MatchIt::matchit. Outputs standardized mean differences before and after matching, matched dataset, and treatment effect on the matched cohort.

Inverse probability of treatment weighting (IPTW): treatment effect estimation via weighting rather than matching. Uses WeightIt::weightit. Outputs diagnostic plots, effective sample size, and weighted treatment effect.

10.4 Diagnostic metrics

ANCOVA: one-way ANOVA with one or more continuous covariates. Uses stats::lm with car::Anova for Type II/III sums of squares. The UI surfaces a warning when the sum-of-squares type matters (unbalanced design).

McNemar’s test: paired-binary comparison for 2×2 tables from matched or pre-post designs. Uses stats::mcnemar.test with continuity correction and exact option.

ROC curves with DeLong’s test: compares two ROC curves for a common outcome. Uses pROC::roc.test(method = "delong"). Outputs AUC for each curve, difference with 95% CI, DeLong p-value, overlay figure.

10.5 Multiple-testing correction

When you run a family of tests: for example, pairwise post-hoc contrasts after ANOVA: ClinStat AI exposes a multiple-testing correction panel. Supported methods: Bonferroni, Holm, Benjamini-Hochberg (FDR), Benjamini-Yekutieli (FDR under dependence). The corrected p-values and rejection set are shown alongside the raw values.

11. Bayesian Analyses

Figure 11.1: Bayesian regression: configuration with ETI + HDI output

Bayesian regression result showing both equal-tailed intervals (ETI, from the posterior summary) and true highest-density intervals (HDI, via bayestestR).

Bayesian methods are available via the rstanarm R package. Install it with install.packages("rstanarm") or the app’s first-run package prompt; it installs as prebuilt binaries on every platform, so no C++ toolchain is required on Windows, macOS, or Linux. It is a large one-time download (several hundred MB with dependencies); runs themselves complete in seconds to minutes.

11.1 Supported Bayesian models

BEST test: the Bayesian Estimation Supersedes the t-Test method (Kruschke 2013). Replaces the classical t-test with a full posterior over the mean difference, including a posterior probability that the effect exceeds zero. Default priors are the weakly informative Kruschke defaults.

Bayesian linear regression: continuous outcome, multiple predictors, weakly informative Normal priors on coefficients. Outputs posterior means, 95% highest-density intervals, Rhat and effective sample size per parameter, Bayes R² (Gelman et al.).

Bayesian logistic regression: binary outcome, same priors and diagnostics as the linear case.

Bayesian one-way ANOVA: group means with pairwise posterior contrasts. More honest than a classical post-hoc because you see the full posterior of each contrast rather than a rejected-or-not decision.

11.2 Reproducibility

Every Bayesian run includes the number of chains, iterations, warm-up draws, and the random seed in the export. Runs with the same seed and data will produce identical posterior summaries. Chains default to 4, iterations to 2000, warm-up to 1000: the standard rstanarm defaults carried over from the previous engine. Tests override these to shorter chains for speed.

Default seeds: For reproducibility, multiple imputation (mice) defaults to seed=42. Bayesian analyses use a fixed seed per run (stored in the result object) so the same data + settings produce identical posterior summaries.

Interval reporting: Bayesian routines report both ETI (equal-tailed interval, from the posterior summary) and true HDI (highest density interval, computed via bayestestR). ETI is the default model-summary output; HDI is the narrower interval containing the specified probability mass (typically 95%).

11.3 Reproducibility details

Default seeds: For reproducibility across runs, routines with stochastic components use fixed default seeds: - Multiple imputation (mice): seed=42 - Bayesian analyses: seed stored in the result object (generated per run) - Power calculations: deterministic (no randomness)

R package versions: Each analysis result records the exact versions of all loaded R packages (via sessionInfo()$otherPkgs and R.version.string). When exporting R code, the reproducibility appendix includes this metadata so you can recreate the exact environment.

Dataset hash: The input data frame is hashed (SHA-256) and stored in the result. This allows you to verify that the exported R code is running on the same data that produced the live results.

11.4 When the package is missing

If rstanarm is not installed, the Bayesian panels show a clear message with an install snippet and do not attempt the analysis. The panels remain browsable so you can read the interface and plan your installation.

12. Interactive Power Calculator

The power calculator is a self-contained tool for estimating required sample size or achieved power for the most common clinical designs. It does not require a loaded dataset.

Figure 12.1: Power calculator: two-sample t-test setup.

12.1 Supported designs

Listed in the left sidebar:

12.2 How to use it

  1. Select the design on the left.
  2. Choose Required sample size or Achieved power as the target in the “Solve for” block.
  3. Fill in the remaining parameters: significance level (default α = 0.05), effect size (Cohen’s d, f, or w depending on test), and either the target power or the sample size you have.
  4. The calculator solves for the missing parameter.

All calculations use the pwr R package and a numeric-only payload: no R-identifier injection surface.

12.3 Effect size conventions

The calculator interprets Cohen’s d as a standardized effect (difference divided by pooled SD), assuming an SD of 1. If you have raw units, divide your expected difference by the expected standard deviation first. The tooltip under the Effect size field explains this convention.

13. AI Interpretation

Figure 13.1: AI interpretation panel: plain-language result narrative from the local LLM

The AI Interpretation panel: a completed plain-language interpretation generated by the configured local LLM. The spinner + elapsed counter show while waiting; Cancel aborts.

The AI interpretation layer is powered by a user-configured local LLM (OpenAI-compatible endpoint). The privacy contract is strict: only aggregated summaries leave your machine, never row-level data.

13.1 How it works

For each analysis, the AI sidebar can generate:

The AI sees, for example:

Test: Independent-samples t-test
Variables: followup_bp (numeric) ~ treatment (factor: 2 levels)
n per group: placebo=40, active=40
Mean (SD) per group: placebo=142.3 (11.4), active=128.7 (12.1)
Test statistic: t(78) = 5.18
p-value: 1.42e-06
Effect size: Cohen's d = 1.16 (large)
Assumptions: normality Shapiro p>0.05 both groups; equal variance Brown-Forsythe p=0.72

The AI never sees the 80 individual followup_bp values or any patient identifiers. Only the aggregated summary (coefficients, metadata) is transmitted to your configured endpoint. The payload guard is enforced by unit tests that verify raw-row arrays are never included (defense-in-depth; rejects rows/data/raw/observations arrays exceeding 10 rows).

13.2 Model selection

Recommended: meta/llama-3.2-3b (non-reasoning model, fast interpretation: ~5s first token, ~19s total on the development host; timing varies with your LLM hardware).

Not recommended for interactive use: Reasoning models (models that expose a reasoning_content field). These models burn tokens on hidden chain-of-thought and can exceed the 90s timeout on the Interpret button. Use them only for single, publication-grade interpretations where longer wait times are acceptable.

Precision fallback: Larger models (e.g., 70B parameters) provide more precise citations (exact d + CI) but take longer (~49s first token, ~2.3min total on the development host; timing varies with your LLM hardware).

13.4 Request timeout and cancellation

AI interpretation requests have a 90-second timeout. If the endpoint does not respond within this window, the request is cancelled with error code ERR-AI-NETWORK. You can retry by clicking the Interpret button again.

Cancellation: The Cancel button (available during interpretation) aborts the in-flight request via AbortController. The renderer emits an AI_INTERPRET_CANCEL IPC event, and the main process terminates the request, returning error code ERR-AI-CANCELLED to the UI.

13.5 Configuring an AI provider

ClinStat AI uses a user-configured local LLM (OpenAI-compatible endpoint) for AI interpretation. The privacy contract is strict: only aggregated summaries leave your machine, never row-level data.

Self-hosted local LLM setup

LM Studio: 1. Download LM Studio from https://lmstudio.ai 2. Load a model (e.g., Llama 3.2 3B) 3. Enable the OpenAI-compatible server from the server icon 4. The default URL is http://127.0.0.1:1234/v1 (no API key required)

Ollama: 1. Install Ollama from https://ollama.ai 2. Run ollama serve to start the server 3. Run ollama run llama3.2 to download and load a model 4. The default URL is http://localhost:11434/v1 (no API key required)

vLLM: 1. Install vLLM following the official documentation 2. Start the server with your chosen model 3. Configure the base URL in Settings → AI provider

Bring-your–own-key (BYOK) providers

Any OpenAI-compatible endpoint with an API key is supported: - OpenAI (https://api.openai.com/v1) - Together (https://api.together.xyz/v1) - Groq (https://api.groq.com/openai/v1) - OpenRouter (https://openrouter.ai/api/v1)

Enter the base URL and API key in Settings → AI provider. The key is stored in the OS keychain, never in plaintext. OpenRouter routes to many models (Claude, GPT, Gemini, open models) behind one OpenAI-compatible endpoint.

Future hosted service

A managed LLM endpoint will be available when ClinStat AI launches as a service (free trial + paid tiers); until then, configure one of the above.

Model selection guidance

13.6 Standalone mode

If no AI provider is configured, the AI sidebar shows a placeholder prompting you to configure one in Settings. Every statistical feature works without the AI: ClinStat AI degrades gracefully.

14. Guided Analysis Wizard

Figure 14.1: Guided Analysis Wizard: step 1

The Guided Analysis Wizard: a four-step structured path from research question to analysis plan.

For users who prefer a structured path rather than selecting a test from a menu, ClinStat AI provides a Guided Analysis Wizard (introduced in Wave 3 Batch 2 of the development roadmap). The wizard is a four-step form that produces an analysis plan:

14.1 Steps

The Guided Analysis Wizard is a five-step AI-driven workflow that produces an analysis plan and executes it:

  1. Dataset selection: pick the dataset to analyze from the loaded project. The wizard loads the variable profile for the next step.
  2. Question input: enter your research question in natural language (e.g., “Does the treatment reduce blood pressure compared to placebo?”). The AI interprets your question and proposes an analysis plan.
  3. Analysis plan: the AI proposes a specific test with variable assignments, based on your question and the dataset’s variable profile. You can accept the plan, reject it, or modify the question.
  4. Execution: the wizard runs the selected analysis and shows results in the standard analysis panel. From here you can tweak parameters and re-run.
  5. Interpretation: the final step shows the completed analysis with AI-generated narrative interpretation, plus options to export or ask a new question.

14.2 AI multi-planner

A complementary feature (Wave 3 Batch 2 Part 2) lets the AI propose a sequence of three or more analyses with justifications for a given research question and dataset. Useful when you have a vague idea (“I want to understand treatment effect while adjusting for baseline severity”) and want the AI to lay out a defensible methods section.

14.3 Enhanced report editor

The third wizard component (Wave 3 Batch 2 Part 3) is a structured-block report editor. Blocks are typed: heading, paragraph, table, figure, citation: so export to Word produces publication-ready layout without manual reformatting. Tables and figures inserted from the analysis panel flow into the Word .docx via the additive exportReportDocumentToWord function.

15. Report Editor and Export

Figure 15.1: Export dialog: Word, Excel, figure, and R-code formats

The Export dialog: choose Word, Excel, figure (PNG/PDF/SVG), or the reproducible R-code appendix.

15.1 Excel export

Click Export → Excel to produce a multi-sheet workbook:

The file is produced by the exceljs Node library and does not require Microsoft Excel to be installed.

15.2 Word export

Click Export → Word to produce a .docx containing:

The file is produced by the docx Node library. It opens cleanly in Microsoft Word 2019+, LibreOffice 7.5+, and Google Docs import.

15.3 Figure export

Individual figures can be exported as PNG (raster, 300 DPI default: configurable in Settings) or SVG (vector). Figures are rendered by R and saved to the project’s figures/ subfolder automatically, so even figures you forgot to export explicitly are available there.

15.4 R-code export and reproducibility appendix

Figure 15.2: Reproducible R-code export: the clinstat_() source view

The R-code tab: the exported .R is standalone-runnable: a pure clinstat_<type>(df, params) function plus a thin main() wrapper.

A distinctive feature of ClinStat AI: every analysis can export standalone-runnable R code. The exported .R file contains two components:

  1. clinstat_<type>(df, params): A pure, sourceable function containing the statistical core. This function accepts a data frame and a parameters list, and returns the complete result. You can source this file in an R session and call the function directly with your own data.

  2. main() wrapper: A thin wrapper that calls the pure function with the exact parameters used in the live analysis. Running source('exported.R') executes main() and reproduces the live output.

Reproducibility appendix: Each R result carries a reproducibility field listing: - R version - Package versions (all loaded packages) - Random seed (for routines with stochastic components like mice, Bayesian models) - Dataset hash

This metadata is designed to be pasted as a supplementary file for journal submission, ensuring your methods section is fully reproducible.

15.5 CONSORT and STROBE report templates

For randomized trials (CONSORT 2010) and observational studies (STROBE), ClinStat AI can produce a pre-filled template .docx with the reporting-guideline checklist as a numbered list, cross-linked to the sections of your project that satisfy each item. These templates are not a replacement for your own judgement but a scaffolding that catches forgotten items.

16. Licensing

16.1 Evaluation License

The current release is evaluation-licensed under the terms in docs/legal/EVALUATION_LICENSE.md. Key restrictions:

Future commercialization: A commercial license tier with activation keys is planned but not yet implemented. Commercial licensing will require: - Signed license agreement - Payment of license fee - Permission for CONSORT/STROBE checklist redistribution (currently used for evaluation/academic reference only)

For current evaluation use, no license key is required: simply accept the EULA on first launch.

16.2 Activation flow

Enter your license key (format CLST-XXXX-XXXX-XXXX-XXXX) into the License block on the onboarding page or in Settings → License. Click Activate. The client contacts the license server once to redeem a device seat; the server returns an RS256-signed JWT which is cached locally. Subsequent launches validate the JWT offline; a revalidation request is made every 14 days.

Each license includes up to three device seats (configurable per license). Deactivating a device frees a seat; the deactivation is immediate at the server, but the client cache expires after 24 hours on the deactivated device.

16.3 Hardening

In this release, license responses are signed with Ed25519 (independent of the JWT) and verified against an embedded public key, so a man-in-the-middle cannot tamper with the activation response even if the JWT signing key is compromised. The client falls back gracefully if the Ed25519 public key is not configured at build time: this is a defense-in-depth feature, not a hard block.

Hardware fingerprinting uses OS-native machine IDs: MachineGuid from the Windows registry, IOPlatformUUID from ioreg on macOS, and /etc/machine-id on Linux. Fingerprints are hashed with an app-specific salt so the same machine cannot be correlated across applications.

17. Settings and Configuration

Figure 17.1: Settings panel: General tab

The Settings panel: AI provider, R engine, figures, privacy, and themes.

The Settings panel is reached from the gear icon in the top bar.

17.1 General

Application preferences and defaults are configured here. Additional R package installation and re-detection options are available from this section.

17.2 Appearance

Figure 17.2: Clinical-dark theme

The clinical-dark theme. The full UI palette: including the semantic danger + code-surface tokens: adapts for legibility.

17.3 AI provider

17.4 Privacy & HIPAA

HIPAA compliance and data handling settings are configured here. No warranty is made regarding HIPAA, GDPR, or any other regulatory compliance; see the Evaluation License for details.

17.5 Updates

Application update preferences are configured here. In this evaluation release, automatic update checks are available when the installer is wired to GitHub Releases.

17.6 About

Shows application version information: ClinStat AI version, license (all rights reserved), and build metadata.

18. Data Privacy and Security

Privacy is enforced by construction, not by policy alone. The following guarantees are tested in CI and cannot be disabled by a configuration change:

18.1 Raw-row exclusion from AI payloads

Unit tests (tests/unit/ai/*.test.ts) spy on the outbound AI payload and assert that no row-level array is ever included. The tests run on every CI build and must pass for a release to be cut. The same principle applies to the scaffolded offline ONNX channel.

What leaves your machine: Only aggregated summaries (coefficient tables, variable metadata, test statistics) are transmitted to the configured local LLM endpoint. Raw patient rows never leave the machine.

User-configured endpoint: You control where the payload goes. The default points at a local OpenAI-compatible server (for example http://127.0.0.1:1234/v1 for a self-hosted LM Studio or Ollama instance), but you can configure any OpenAI-compatible endpoint, including bring-your-own-key cloud providers or OpenRouter. The app does not send data to any third party unless you explicitly configure such an endpoint.

18.2 Sandbox configuration

The Electron renderer runs with sandbox: true, contextIsolation: true, nodeIntegration: false, and a strict Content-Security-Policy that allows self only: no inline scripts, no eval. Network connections are restricted to the user-configured AI provider endpoint (via Settings) and the license server. Nodetools are disabled in production builds.

18.3 API key storage

The local LLM API key (if configured) is stored in the operating system’s native keychain (Windows Credential Manager, macOS Keychain, Linux libsecret). If the keychain is unavailable: for example, a Linux distribution without libsecret installed: ClinStat AI refuses to persist the key to plaintext disk and returns a structured error asking the user to install a keyring utility and retry.

18.4 Plugin sandbox

User-installed plugins run in a Node worker_threads sandbox with a capability-gated require: fs:read grants read-only access to a plugin-specific temp directory, fs:write grants write access to the same directory only, net:domain:<domain> grants HTTPS fetch to that host only, analysis:run grants posting an analysis request message back to the host. Without the corresponding capability, require('fs'), require('net'), process.exit, and eval all fail loudly. Red-team tests in CI exercise each blocked path.

18.5 At-rest encryption

When HIPAA mode is enabled (from Settings → Privacy), ClinStat AI applies at-rest encryption via SQLCipher. The database is encrypted with a per-project key. Note: No warranty is made regarding HIPAA, GDPR, or any other regulatory compliance; see the Evaluation License for details. For highly sensitive data, consider using an encrypted disk (BitLocker, FileVault, LUKS) as an additional defense-in-depth measure.

18.6 Network whitelist

The renderer’s CSP connect-src directive restricts outbound connections to: - The user-configured AI provider endpoint (via Settings → AI provider → Base URL) - The license server (https://license.clinstat.ai)

All other outbound HTTPS is blocked at the Chromium layer. You can verify this by opening DevTools (Ctrl+Shift+I in dev builds) and attempting any fetch() to a third-party host.

19. Troubleshooting

19.1 Application does not start

Symptom: the installer finishes, you click the shortcut, and nothing visible happens.

Windows: check Task Manager for a running ClinStat AI.exe. If present but no window, the BrowserWindow may be off-screen (multi-monitor scenario after a display change). Delete %AppData%/ClinStat AI/window-state.json and relaunch.

macOS / Linux: run from a terminal to see stderr output: open -a "ClinStat AI" --stdout --stderr on macOS; ./ClinStat\ AI-0.1.0.AppImage on Linux. Look for TypeError: Store is not a constructor (update to the latest release if you see it) or NODE_MODULE_VERSION errors (native binding ABI mismatch: rebuild with npx electron-builder install-app-deps).

19.2 R not found

The footer shows R not found in red. Install R from https://cran.r-project.org and click Settings → R → Re-detect. On Linux, ensure Rscript is on your PATH. On macOS, the standard /usr/local/bin/Rscript and framework paths are checked; Homebrew’s /opt/homebrew/bin/Rscript is also checked on Apple Silicon.

19.3 Analysis returns ERR-R-PACKAGE

A required R package is missing. The error message names the package. Install with:

install.packages("<package-name>")

From an R console. Relaunch ClinStat AI after install or click Settings → R → Re-detect packages.

19.4 AI interpretation fails

Endpoint unreachable (ERR-AI-NETWORK): Check if the local LLM server is running. Verify the base URL in Settings → AI provider → Test Connection. Common issues: - LM Studio/Ollama/vLLM not started - Incorrect port number (e.g., 1234 vs 11434) - Firewall blocking local connections

Model not found: Verify the model name matches exactly what the endpoint serves. Use Discover Models to populate the list.

Timeout (90s): Large models or reasoning models may exceed the timeout. Try a smaller/faster model (recommended: meta/llama-3.2-3b). You can also retry: some local LLMs have variable first-token latency.

Cancellation (ERR-AI-CANCELLED): If you clicked Cancel during interpretation, this is expected. Click Interpret again to retry.

If the AI provider is not configured, you can continue in standalone mode: every statistical feature works; only the narrative panel is disabled. Configure the provider in Settings → AI provider.

19.5 Tokens used climbing faster than expected

The footer token counter shows cumulative session tokens; there is no per-analysis breakdown in the UI. Large tables (e.g., a 500-level factor variable) produce large payloads. Pre-aggregate rare levels into “Other” from the variable card to reduce the payload.

19.6 License activation fails

Note: Commercial licensing is not yet implemented. The current release is evaluation-licensed; no activation key is required for evaluation use. See docs/legal/EVALUATION_LICENSE.md for usage restrictions.

(For future commercial activation, common error codes will include ERR-LICENSE-INVALID-FORMAT, ERR-LICENSE-REVOKED, ERR-LICENSE-SEAT-EXHAUSTED, and ERR-LICENSE-SIGNATURE-INVALID.)

19.7 App won’t launch / EULA loop

Symptom: The app launches but immediately shows the EULA gate again, even though you accepted it.

Cause: The electron-store file (config.json) is corrupted or was deleted.

Resolution: Re-accept the EULA. The gate re-appears as a safety measure when the acceptance record is missing or invalid. After re-accepting, the acceptance is persisted again.

19.8 Single-instance lock

Symptom: Clicking the app icon when it’s already running does not open a second window. Instead, the existing window is focused.

Cause: ClinStat AI uses a single-instance lock to prevent multiple concurrent instances (which could corrupt project files).

Expected behavior: This is intentional. To run two separate projects, use separate user accounts or open a second instance after fully quitting the first.

20. Keyboard Shortcuts and Reference

20.1 Keyboard shortcuts

Action Windows / Linux macOS
New Project Ctrl + N Cmd + N
Open Project Ctrl + O Cmd + O
Close Project Ctrl + W Cmd + W
Save Ctrl + S Cmd + S
Save As Ctrl + Shift + S Cmd + Shift + S
Preferences Ctrl + , Cmd + ,
Quit Ctrl + Q Cmd + Q
Undo Ctrl + Z Cmd + Z
Redo Ctrl + Y Cmd + Y
Cut / Copy / Paste Ctrl + X / C / V Cmd + X / C / V
Find Variable (coming soon) Ctrl + F Cmd + F
Toggle Full Screen F11 F11
Reload Ctrl + R Cmd + R
Toggle Developer Tools Ctrl + Shift + I Cmd + Option + I
Zoom Reset / In / Out Ctrl + 0 / + / − Cmd + 0 / + / −
Ask a Question (opens Guided) Ctrl + Shift + A Cmd + Shift + A
Show this panel Ctrl + / Cmd + /

20.2 File format reference

Audit logs are stored as JSON-lines files in the app logs directory, hash-chain-sealed for tamper detection.

20.3 Error code reference

Code Meaning
ERR-R-PACKAGE Required R package missing: install with install.packages
ERR-R-TIMEOUT R script ran longer than the configured timeout: increase in Settings
ERR-FOREIGN-MAGIC-MISMATCH Imported file’s magic bytes do not match its extension
ERR-API-KEY-INVALID Local LLM API key failed basic format check
ERR-API-KEY-KEYTAR-UNAVAILABLE OS keychain unavailable: install a keyring utility
ERR-AI-AUTH Local LLM endpoint rejected the API key
ERR-AI-NETWORK Network unreachable for local LLM endpoint (timeout, DNS failure, server not running)
ERR-AI-RATE-LIMIT Local LLM endpoint returned 429 (rate limit)
ERR-AI-CANCELLED AI interpretation request was cancelled by user
ERR-LICENSE-INVALID-FORMAT License key format wrong (future commercial tier)
ERR-LICENSE-REVOKED License deactivated by issuer (future commercial tier)
ERR-LICENSE-SEAT-EXHAUSTED Device seats full (future commercial tier)
ERR-LICENSE-SIGNATURE-INVALID Ed25519 signature check failed (future commercial tier)
ERR-PLUGIN-TIMEOUT Plugin exceeded 30-second timeout
ERR-PLUGIN-CRASHED Plugin threw an uncaught exception
ERR-PLUGIN-CAPABILITY-DENIED Plugin attempted a gated operation without capability
ERR-RSERVE-CONNECTION-REFUSED Rserve enabled but not running on configured host/port
ERR-RSERVE-EVAL-ERROR Rserve returned an evaluation error
ERR-RSERVE-TIMEOUT Rserve eval exceeded timeout
ERR-HWID-UNSUPPORTED OS-native hardware fingerprint unavailable
ERR-SQLCIPHER-NOT-WIRED SQLCipher driver swap not yet shipped

R-stderr redaction: Error messages from R may include absolute file paths. Before reaching the UI, these paths are redacted (replaced with [PATH]) to prevent accidental exposure of system information. The full stderr remains in the main-process log for debugging.

20.4 Further reading


End of manual: version 0.1.0, June 2026.