statci brings software-engineering-grade continuous integration, static methodological verification, probabilistic calibration fuzzing, manuscript-to-code auditing, and adversarial sensitivity testing to statistical R pipelines and Quarto/RMarkdown manuscripts.
1. High-Level Module Map
statci/
├── DESCRIPTION / NAMESPACE / LICENSE
├── ARCHITECTURE.md
├── R/
│ ├── statci-package.R # Package-level docs and shared imports
│ ├── security.R # Centralized HTML/MD escaping, path/symlink, Git ref & GHA validators
│ ├── utils.R # Shared helpers, status algebra, formatting, RNG utils
│ ├── config.R # .statci.yml strict YAML config & statci_audit_project()
│ ├── lint-parser.R # .R / .qmd / .Rmd projection, XML AST construction, AST suppression parser
│ ├── lint-rules.R # Rule S3 constructor, registry, and 20 built-in AST rules
│ ├── lint-engine.R # stat_lint(), stat_lint_text(), stat_lint_dir(), S3 methods
│ ├── lint-diff.R # stat_lint_diff() unified diff parser & incremental PR linter
│ ├── sarif.R # export_statci_sarif() SARIF 2.1.0 JSON generator
│ ├── audit-estimator.R # audit_estimator() parameter recovery, coverage, Type-I, convergence
│ ├── audit-sbc.R # audit_sbc() Simulation-Based Calibration (Talts et al., 2018)
│ ├── audit-power.R # audit_power_curve() empirical power monotonicity & MDE
│ ├── audit-parallel-rng.R # check_parallel_rng() and statci_parallel_apply() L'Ecuyer streams
│ ├── audit-manuscript.R # audit_manuscript() prose/table/LaTeX parser & internal arithmetic
│ ├── audit-sensitivity.R # audit_sensitivity() winsorization, LOO/LOCO, missingness, bootstrap
│ ├── audit-multiverse.R # audit_multiverse() specification-curve grid, variance decomposition & plots
│ ├── report.R # statci_report(), statci_check_gate(), render_statci_report()
│ └── github-action.R # use_statci_github_action() hardened CI workflow generator
├── tests/testthat/ # Comprehensive edition-3 unit & integration tests
└── vignettes/ # Executable end-to-end documentation vignettes
Unified Status Algebra
Every verification subsystem emits structured S3 objects whose overall status belongs to a three-level ordered lattice:
Across components and unified reports (statci_report()), statuses compose monotonically via : any single fail elevates the parent section and overall report to fail; otherwise any warn elevates to warn; otherwise pass. CI quality gates (statci_check_gate()) translate this lattice directly into deterministic pass/error behavior for GitHub Actions.
2. Pillar 1: AST-Based Statistical Linter
2.1 Parsing Strategy for .R, .qmd, and .Rmd
Rather than applying fragile regexes to raw text, statci parses code into full R parse trees via base::parse(keep.source = TRUE), converts the parse table to XML via xmlparsedata::xml_parse_data(), and queries syntactic structure with XPath (xml2::xml_find_all()).
For .qmd and .Rmd documents, extract_r_chunks() identifies fenced R code chunks (```{r ...} / ```{R ...}) and builds a blank-line-preserving document projection:
- Every non-R-chunk line (YAML frontmatter, markdown prose, fence delimiters, non-R chunks) is replaced with an empty line
"". - Code lines inside R chunks stay at their exact 1-based original file line numbers.
- A parallel line-to-chunk map records the chunk label (
{r label}or Quarto#| label: ...) for each code line.
This design solves two classic notebook-linting pitfalls simultaneously: - Zero line-offset drift: xmlparsedata line1/col1 attributes match original .qmd/.Rmd line numbers directly. - Cross-chunk scope awareness: A set.seed(42) in an early setup chunk properly satisfies downstream stochastic calls in later chunks, while a scale(df) in chunk 1 before a train/test split in chunk 2 is caught as cross-chunk data leakage.
If the combined document projection fails to parse (e.g., an intentional syntax error in one chunk), the parser gracefully falls back to per-chunk parsing with exact line offsets so valid chunks are still linted and the invalid chunk yields a parse_error diagnostic.
2.2 Inline Suppressions
Authors can silence intentional exceptions using standard line comments: - # statci-ignore — suppresses all rules on that line. - # statci-ignore: rule_a, rule_b — suppresses specific rule IDs on that line. - # statci-ignore-next-line / # statci-ignore-next-line: rule_a — suppresses the immediately following line.
2.3 Extensible Rule Engine & Built-in Rules
Rules are statci_rule S3 objects stored in a package registry environment (.statci_rule_registry). Users inspect rules via list_stat_rules(), register custom AST rules via register_stat_rule(new_stat_rule(...)), and filter rules per invocation via rules / exclude_rules.
statci ships 20 built-in statistical & methodological lint rules:
| # | Rule ID | Severity | Category | Methodological Hazard Caught |
|---|---|---|---|---|
| 1 | unseeded_randomness |
error | reproducibility | Top-level stochastic calls (rnorm, sample, boot, kmeans, etc.) without prior set.seed(), withr::with_seed(), RNGkind(), or enclosing seed wrapper |
| 2 | unsafe_parallel_rng |
error | parallel_rng |
mclapply/parLapply/foreach %dopar%/future_* without L’Ecuyer-CMRG, clusterSetRNGStream, %dorng%/doRNG, or future.seed
|
| 3 | duplicate_parallel_seed |
error | parallel_rng | Constant set.seed(42) inside loops or parallel workers producing identical duplicate Monte Carlo draws |
| 4 | preprocessing_before_split |
error | data_leakage | Global scale(), prcomp(), preProcess(), mice(), etc. executed on a dataset before train/test splitting |
| 5 | in_sample_prediction_eval |
warning | data_leakage | Evaluating RMSE/MAE/AUC/MSE on training-set predictions rather than held-out test/CV data |
| 6 | uncentered_mlm_interaction |
warning | modeling | Fixed-effect interactions (*, :) in lmer/glmer/lme/glmmTMB/brm using raw predictors with no centering call, naming suffix, or prior centering definition |
| 7 | silent_listwise_mismatch |
warning | modeling | Comparing models with differing predictor sets via anova(), AIC(), BIC(), or lrtest() on an unharmonized dataset without na.omit/complete.cases/drop_na/na.action = na.fail
|
| 8 | silent_factor_drop |
warning | modeling |
as.numeric()/as.integer() applied directly to a factor variable (coercing level indices), or passing a subset()/filter() data frame to modeling/contrast functions without droplevels()/fct_drop()
|
| 9 | silent_na_coercion |
warning | data_integrity | Unchecked as.numeric()/as.integer() coercion of character/parsed strings without anyNA()/is.na() checks |
| 10 | unverified_merge_cardinality |
warning | data_integrity |
dplyr::*_join() or base merge() without relationship = or nrow() guards against silent many-to-many row duplication |
| 11 | missing_drop_false_matrix |
warning | data_integrity | 2D matrix/array subsetting (X[, cols], X[idx, ]) lacking drop = FALSE, silently collapsing 1-row/1-column matrices to atomic vectors |
| 12 | implicit_na_rm_masking |
info | data_integrity | Unconditional na.rm = TRUE in summary statistics without nearby missingness inspection (is.na(), anyNA(), complete.cases()) |
| 13 | equality_on_float |
warning | numerics | Exact == / != on floating-point literals or computed continuous expressions instead of all.equal(), near(), or tolerance checks |
| 14 | unadjusted_multiple_testing |
warning | inference | Hypothesis tests (t.test, cor.test, wilcox.test, lm p-values, etc.) run inside loops/applies without p.adjust() or multiple-testing correction in scope |
| 15 | stepwise_selection_unvalidated |
warning | modeling | In-sample step()/MASS::stepAIC()/regsubsets() without cross-validation or holdout validation |
| 16 | missing_convergence_check |
warning | modeling | Iterative models (lmer, glmer, optim, nlminb, glmmTMB) fitted without programmatic AST checks for convergence or isSingular()
|
| 17 | global_seed_override_in_fn |
warning | reproducibility | Calling bare set.seed() inside reusable functions or \(...) lambdas without restoring .Random.seed via on.exit() or withr::local_seed()/with_seed()
|
| 18 | short_logical_literal |
warning | hygiene | Using mutable T/F symbols as logical literals/arguments instead of reserved TRUE/FALSE (ignoring user-bound numeric variables like T <- 100) |
| 19 | cor_without_use_arg |
info | modeling | Calling cor() or cov() without an explicit use = missing-data policy |
| 20 | absolute_path_in_script |
warning | reproducibility | Hardcoded machine-specific absolute paths (/Users/..., /home/..., C:\..., ~/...) in file I/O or setwd() calls |
2.4 Incremental Git-Diff Pull-Request Linting (stat_lint_diff())
stat_lint_diff() parses unified diffs (diff_text or read-only git diff --unified=0 against strictly validated Git refs via validate_git_ref()), enforces repository root confinement on every modified file path, executes full-file AST linting (so upstream context like set.seed() is preserved), and emits only findings landing on added or modified lines alongside diff_meta$n_suppressed_untouched.
3. Pillar 2: Estimator Calibration & Fuzzing Harness
Deterministic unit tests cannot detect biased custom estimators, anti-conservative standard errors, broken MCMC/posterior samplers, or parallel RNG stream collisions. statci implements finite-sample probabilistic verification accounting explicitly for Monte Carlo standard error (MCSE).
3.1 Parameter Recovery, Coverage, SE Ratio & Type-I Error (audit_estimator())
Given a user dgp function, an estimator function (returning either a named list or a standard R model object lm/glm/lmerMod/htest), and true_params, audit_estimator() runs replications inside a locally scoped RNG state (withr::local_seed()), capturing errors, convergence failures, and singular fits cleanly. Let be the number of converged replications:
-
Bias Check:
-
failif (default ) and ; -
warnif ; -
passotherwise.
-
-
Interval Coverage Calibration (Exact Clopper-Pearson Binomial Bounds): For nominal level and , with . Exact two-sided binomial testing (
stats::binom.test(k, M, p = 1 - alpha)) yields exact p-value and Clopper-Pearson interval :-
failif (default0.01) and ; -
warnif ; -
passotherwise.
-
-
Model SE vs. Empirical SE Ratio: Let with asymptotic MCSE . Using configurable target bounds (default
[0.85, 1.15]):-
failif the 95% MC interval lies completely outside ; -
warnif the point ratio lies outside and ; -
passotherwise.
-
-
Type-I Error Calibration (Null DGP or Null Parameters): Under
null_dgp(or any parameter where ), let and . Usingstats::binom.test(k_0, M_0, p = alpha):-
failif and ( or ); -
warnif ; -
passotherwise.
-
-
Convergence & Singularity Auditing: Tracks error rate, non-convergence rate, and singular-fit rate (
lme4::isSingular()or returnedsingular = TRUE) against configurable thresholds (max_fail_rate,warn_fail_rate,max_singular_rate).
3.2 Simulation-Based Calibration (audit_sbc())
Implements Talts et al. (2018): for , draws , simulates , obtains posterior draws , and computes rank statistic: (with randomized tie-breaking for discrete ties). Under a calibrated posterior sampler, . audit_sbc() bins ranks into equal-probability bins and evaluates uniformity via both Pearson’s test (chisq.test) and a Kolmogorov-Smirnov test on , alongside central 50% and 90% posterior interval coverage.
3.3 Parallel RNG Invariance (check_parallel_rng() & statci_parallel_apply())
A subtle R parallelization trap is that standard parallel::mclapply(..., mc.set.seed = TRUE) or clusterSetRNGStream(cl) assigns one stream per worker, so running with cores = 1 vs cores = 2 vs cores = 4 produces different Monte Carlo realizations!
-
statci_parallel_apply(X, FUN, cores, seed)solves this by pre-generating one independent"L'Ecuyer-CMRG"stream per task viaparallel::nextRNGStream(), assigning.Random.seedinside each task before invokingFUN(X[[i]]). Output is mathematically bit-for-bit identical across any number of cores on macOS, Linux, and Windows (using PSOCK clusters with stricton.exit(stopCluster(cl))hygiene). -
check_parallel_rng()executes a user-supplied parallelrunner(cores, seed)(orfunviastatci_parallel_apply) across core counts (defaultc(1L, 2L), honoring CRAN’s 2-core limit) and verifies exact numerical equivalence (identical()/all.equal(tolerance = 0)), failing immediately on any core-count discrepancy.
4. Pillar 3: Manuscript-to-Code Consistency Auditor (audit_manuscript())
4.1 Document Parsing & Tagging Grammar
audit_manuscript() strips YAML frontmatter and fenced code blocks (preserving exact line numbers) and extracts statistical claims from prose in two modes:
-
Explicitly Tagged Claims (Zero-Ambiguity Binding):
- HTML comment anchor preceding text:
<!-- statci: model=fit1 term=x1 --> - Inline Quarto span:
[b = 0.42, SE = 0.11, p = .003]{.statci model="fit1" term="x1"} - Model-level anchor (for , , AIC, BIC):
<!-- statci: model=fit1 -->
- HTML comment anchor preceding text:
-
Automatic Prose Extraction (Untagged Matching): Recognizes standard APA / statistical typography (including markdown italics
*b*,*p*, LaTeX inline math$b = 0.42$, Unicode minus−, and leading-dot decimals.003):- Point estimates (
b,B,beta,β,est,estimate,OR,coef) - Standard errors (
SE,S.E.) - Confidence intervals (
95% CI [L, U],CI (L, U),95% CI: L to U) - p-values (
p = .003,p < .001,p <= .05,p > .05) - Sample sizes (
N = 250,n = 250) - Test & fit statistics (
t(df) = ...,z = ...,r = ...,R^2 = ...,AIC = ...)
- Point estimates (
4.2 Uniform Model Artifact Extraction
Accepts a named list of R models, a single model, an .rds file, or a directory of .rds files. Supports lm, glm, lmerMod/glmerMod/lmerModLmerTest, htest, and tidy data.frame/tibble tables.
4.3 Rounding-Aware Verification Algebra
For any numeric claim reported with decimal places (e.g., 0.42 has ): - Let be the rounding half-unit. - Sign Flip (fail): while and . - Exact Rounding Match (pass): . - Rounding Discrepancy (warn): (off by 1 unit in the final decimal place, e.g., truncation instead of half-to-even rounding). - Value Mismatch (fail): . - Inequality p-values (p < c / p <= c / p > c): Verified directly as exact boolean inequalities against the model’s unrounded p.value. - Sample size (N): Exact integer equality against nobs(model).
5. Pillar 4: Adversarial Sensitivity & Robustness Battery (audit_sensitivity())
Given data, fit_fn(df), and extract_fn(fit), audit_sensitivity() automatically executes four orthogonal perturbation suites around the baseline fit:
- Outlier Winsorization: Clamps continuous non-binary, non-cluster numeric predictors/outcomes to (default ).
-
Leave-One-Cluster-Out (LOCO) / Leave-One-Out (LOO) Influence: Sequentially omits each cluster (
cluster_col) or observation (capped atmax_loo_units, prioritizing high-leverage rows for linear models when subsampling), reporting maximum shift, most influential unit, jackknife SE, and any single-unit sign reversal. -
Missingness & Imputation Stress Tests: Evaluates observed-data missingness handling (if
NAs already exist) plus controlled MCAR perturbation at configured rates (default 5% and 10%) contrasting complete-case deletion against median/mean imputation. -
Nonparametric Bootstrap Stability: Performs cluster bootstrap (resampling whole clusters when
cluster_colis given) or row bootstrap, reporting bootstrap mean, SE, percentile CI, sign consistency rate, and refit convergence rate.
Each perturbation records baseline estimate, perturbed estimate, absolute shift, relative % change, sign-flip indicator, and pass/warn/fail classification.
5.1 Multiverse Specification-Curve Auditor (audit_multiverse())
audit_multiverse() evaluates a pipeline across the full Cartesian grid of named analytical decisions (guarded by max_specs), sorting converged specifications by point estimate and computing:
- Overall median, interquartile range (
IQR),IQR / |median|spread ratio, sign consistency, and proportion statistically significant (); - One-way per-fork variance decomposition ( and median range across each fork’s choices) identifying the top driver of estimate dispersion (
most_influential_fork); - Publication-ready two-panel
plot()combining the sorted specification curve (point estimates and confidence intervals colored by significance) above a decision-choice indicator matrix.
6. Pillar 5: Unified Audit Report & GitHub Actions Integration
-
statci_report()aggregates lint, estimator calibration, SBC, power-curve, parallel RNG, manuscript, sensitivity, and multiverse objects into a singlestatci_reportS3 object with unified summary metrics and session metadata. -
statci_check_gate()enforces CI exit gates (fail_on = "fail"or"warn"), throwing a structured error in non-interactive CI runs when thresholds are breached. -
render_statci_report()generates:- Self-contained, offline-capable HTML5 audit dashboards (safely escaped with
htmltools), - GitHub-Flavored Markdown reports suitable for
$GITHUB_STEP_SUMMARYand PR reviews, - Machine-readable JSON artifacts (via
jsonlite).
- Self-contained, offline-capable HTML5 audit dashboards (safely escaped with
-
use_statci_github_action()writes a ready-to-run.github/workflows/statci.yamlworkflow installing dependencies, runningstatciaudits, publishing Markdown summaries to GitHub Actions, and uploading HTML reports as workflow artifacts.
