Domain libraries · entity catalog

airmid library

Authored subsystem deep-dive for airmid, layered on the code-linked entity catalog — what each system is, why it exists, and how it fits.

authored deep-dive
19entities2layers19deep-dives

On this page

The libs/airmid/ area: nineteen Nx libraries that together form an evidence-based phytotherapy and botanical-intelligence platform — from a shared domain core through cheminformatics, network pharmacology, ML, clinical decision support, regulatory/safety science, conservation, and an external-data integration layer.

What this area is#

Airmid (named for the Irish goddess of herbalism) is a self-contained scientific domain: a knowledge platform for medicinal plants, their phytochemical constituents, and the evidence, safety, interaction, quality, and regulatory context around using them therapeutically. Unlike most Oshun lib areas, these are not thin contract or service wrappers — each library is a substantial domain-specific computation engine, ranging from ~3,800 to ~10,600 lines of non-test TypeScript, with curated reference databases and real published algorithms rather than CRUD.

Every project is tagged scope:airmid. Eighteen carry layer:domain and one, @airmid/database, carries layer:data. The dependency shape is a hub: most libraries build on the shared identifiers, entity models, enums, and pharmacology helpers in @airmid/core (libs/airmid/core/src), which defines the typed primitives (SpeciesId, CompoundId, SMILES, InChIKey), the fifteen domain entity classes in entities.ts (BotanicalSpecies, PhytochemicalCompound, ClinicalTrial, DrugHerbInteraction, …), and cross-cutting concerns (errors.ts, events.ts, validation.ts, taxonomy.ts).

The remaining libraries each own one scientific sub-discipline and are largely peers of one another: cheminformatics (@airmid/phytochem, @airmid/docking), AI/ML (@airmid/ml), systems biology (@airmid/network), evidence synthesis (@airmid/evidence), clinical pharmacology (@airmid/interactions, @airmid/clinical, @airmid/precision), safety/toxicology (@airmid/safety), formulation science (@airmid/formulation), microbiome pharmacology (@airmid/microbiome), analytical QC (@airmid/quality), regulatory affairs (@airmid/regulatory), conservation biology (@airmid/sustainability), ethnobotany (@airmid/ethno), computer vision for plant ID (@airmid/vision), plus the persistence schema (@airmid/database) and the integration/API surface (@airmid/api).

How the libraries relate#

The intended composition is: @airmid/core supplies the shared vocabulary; @airmid/database persists it; the domain libraries each compute one kind of answer (a docking score, an interaction alert, a GRADE rating, a conservation status); and @airmid/api exposes the whole knowledge base over external-database connectors, an ETL pipeline, and an OpenAPI surface. Many libraries deliberately keep their own self-contained reference datasets (for example HERB_DRUG_INTERACTION_DATABASE, HEPATOTOXIC_HERB_DATABASE, PHARMACOPOEIA_MONOGRAPH_DATABASE) so each sub-discipline can be reasoned about in isolation, with @airmid/core providing the identifiers that let them be cross-referenced.

How it fits the wider system#

These are leaf domain libraries: they sit at the bottom of the Airmid dependency graph and are meant to be composed by an Airmid service/BFF and by each other. A consumer assembling, say, a personalized herbal recommendation can layer @airmid/precision (pharmacogenomics) over @airmid/interactions (herb-drug risk), @airmid/safety (toxicology), @airmid/evidence (GRADE strength), and @airmid/clinical (FHIR-shaped decision support), all keyed by the same @airmid/core identifiers. @airmid/api is the outward boundary — its OpenAPI spec, export formats, and webhook tooling are how anything outside the area reads the knowledge base; @airmid/database is the inward boundary that persists it. The honest caveats are localized to that integration seam: the ETL extraction/load steps in @airmid/api and a couple of crypto helpers are documented reference implementations meant to be swapped for live HTTP / Node crypto at deploy time (see the per-entity notes below). Walk the "used by" edges on any node to see its exact consumers.

Entity catalog (19)#

The 19 tracked Nx projects in airmid, each a code-linked entity node — package, type, source path, declared targets, and its internal dependency graph (depends-on / used-by, resolved from the package manifests, §6/§8), read from the project graph. Grouped by architectural layer; walk the dependency links to travel the system. 19 of these carry an authored deep-dive (what / why / how it fits); the rest are generated scaffolds awaiting one.

data (1)#

lib

@airmid/database

#

The persistence layer (libs/airmid/database/src), the one library tagged layer:data. It exposes Zod schema modules barreled through src/schema/index.tsbotanical-species, phytochemicals, plant-compounds, clinical-trials, evidence-records, drug-interactions, adverse-events, traditional-use, pharmacopoeia, regulatory, genomics, targets-pathways, conservation, and audit — plus six numbered, ordered migrations under src/migrations/ (initial setup, core tables, safety tables, genomics/targets, materialized views, soft delete) re-exported as a migrations namespace for a migration runner. It is the structural counterpart to @airmid/core's in-memory entities.

buildtestlint
layer: datascope: airmidowner: @GreyChimp

domain (18)#

lib

@airmid/api

#

The data-integration and outward API layer (libs/airmid/api/src). Real bioinformatics connectors build and parse requests for ~10 external databases — PubMed/NCBI E-utilities, PubChem PUG REST, ChEMBL, UniProt, STRING, KEGG, ClinicalTrials.gov, etc. (buildPubMedSearchURL, parseUniProtResponse, calculateExponentialBackoff with jitter and rate-limit awareness). It also ships an ETL pipeline framework (PIPELINE_DEFINITIONS, TRANSFORMATION_RULES with CAS check-digit and InChIKey validation, unit harmonization), genuine cheminformatics in smiles-canonical.ts (Morgan canonical ranking) and smarts.ts (SMARTS substructure matching), an OpenAPI 3.1 spec with 44 endpoints, rate-limit tiers and RFC 7807 errors, and multi-format export (CSV/XML/RDF-Turtle/SDF) with a FAIR assessment. Honest seams: the ETL extract/load steps (runETLExtraction, runETLLoad), species-name resolution, and the SHA-256/HMAC helpers carry "in production, use …" comments — they are documented reference implementations meant to be wired to live HTTP and Node crypto at deployment, while the URL builders, parsers, transformation rules, and exporters are fully implemented.

buildtestlint
layer: domainscope: airmidowner: @GreyChimp
lib

@airmid/clinical

#

Clinical decision support for herbal medicine (libs/airmid/clinical/src). Built around HL7 FHIR R4 resources (createMedicationStatement, createAllergyIntolerance, parseObservation, CDS Hooks responses) with real terminology maps — LOINC_CODES, SNOMED_HERB_CODES, ICD10_RELEVANT_CONDITIONS. It adds real-time multi-axis interaction alerting with alert-fatigue mitigation (checkInteractionsRealTime, deduplicateAlerts, calculateAlertFatigueScore), a GRADE-rated EVIDENCE_SUMMARY_DATABASE with effect sizes (Cohen's d, NNT/NNH, LHH risk-benefit), patient-education generation targeting a 6th-grade Flesch-Kincaid level (generatePatientSheet, countSyllables), and an audit/compliance layer with tamper-evident hash chains, FDA MedWatch 3500A generation, and EU EudraVigilance ICH E2B(R3) validation.

buildtestlint
layer: domainscope: airmidowner: @GreyChimp
lib

@airmid/core

#

The shared domain foundation (libs/airmid/core/src), tagged layer:domain, that every other Airmid library builds on. It owns the branded identifier types and Zod schemas (SpeciesIdSchema, CompoundPropertiesSchema, CAS_NUMBER_PATTERN), fifteen validating entity classes in entities.ts (e.g. PhytochemicalCompound with a Lipinski drugLikenessScore, ClinicalTrial with an Oxford-level and 0–100 qualityScore), a typed error hierarchy (errors.ts), a domain event taxonomy (events.ts), and real pharmacology helpers in pharmacology.ts (calculateBioavailability, estimateHalfLife, classifyDrugLikeness, calculateTherapeuticIndex, assessCYP450Risk). The implementations are domain-specific (route- and compound-class-aware bioavailability penalties, Lipinski/Veber scoring), not generic scaffolding.

buildtestlint
layer: domainscope: airmidowner: @GreyChimp
lib

@airmid/docking

#

A computer-aided drug design (CADD) toolkit (libs/airmid/docking/src). It implements an AutoDock Vina-style scoring function with named published weights (Trott & Olson 2010 — vinaGauss1/2, vinaRepulsion, vinaHydrophobic, vinaHBond in molecular-docking.ts), fpocket-inspired binding-site detection, Gasteiger charge assignment, PAINS filtering (PAINS_ALERT_DATABASE, Baell & Holloway 2010), Tanimoto similarity and MaxMin diversity selection, inverse-docking target prediction against a 30-target panel, MD specification with MM-PBSA free energy (molecular-dynamics.ts), and OECD-compliant QSAR modeling (qsar-modeling.ts, with Y-randomization and applicability-domain checks). The Math.random() calls here are legitimate stochastic-algorithm components (bootstrap sampling, Fisher-Yates shuffles), annotated as such.

buildtestlint
layer: domainscope: airmidowner: @GreyChimp
lib

@airmid/ethno

#

Ethnobotanical knowledge base of traditional medicine systems (libs/airmid/ethno/src). Encodes structured properties for TCM, Ayurveda, Unani, and Kampo (TCM_DATABASE, AYURVEDA_DATABASE, with TCM nature/flavor/channel and Ayurvedic rasa/vipaka/virya/dosha typing), classical formulas and formulation principles including the TCM Eighteen Incompatibles / Nineteen Antagonisms and Ayurvedic incompatibilities (analyzeFormulation, checkCompatibility), preparation methods with extraction-yield calculation, an indigenous-knowledge protection layer (Nagoya Protocol compliance, ABS legislation, biopiracy case database, cultural-sensitivity guidelines), and a scientific-validation database linking traditional uses to reverse-pharmacology status.

buildtestlint
layer: domainscope: airmidowner: @GreyChimp
lib

@airmid/evidence

#

Evidence synthesis and grading (libs/airmid/evidence/src). Implements clinical trial search/ranking, systematic review and meta-analysis (performMetaAnalysis, generateForestPlotData, assessRiskOfBias over Cochrane RoB2 domains ROB2_DOMAINS), GRADE certainty computation (computeGRADECertainty, generateRecommendation, GRADE_FACTORS), publication-quality scoring with predatory-journal and retraction-risk detection (PREDATORY_JOURNAL_INDICATORS, JOURNAL_QUALITY_TIERS), and an evidence search index with contradictory-evidence detection. It operationalizes the GRADE/Oxford machinery that @airmid/core's EvidenceRecord only models.

buildtestlint
layer: domainscope: airmidowner: @GreyChimp
lib

@airmid/formulation

#

Pharmaceutical formulation science (libs/airmid/formulation/src). Provides drug-combination synergy analysis with multiple named models (calculateCombinationIndex Chou-Talalay, calculateBlissIndependence, calculateLoeweAdditivity, calculateHSA, isobologram/Fa-CI plots), antagonism detection across pharmacokinetic/pharmacodynamic/chemical/physical types (ANTAGONISM_DATABASE), extraction optimization over a solvent and compound-solubility database (predictExtractionYield, Hansen-style solvent selection), stability/shelf-life prediction (Arrhenius and Q10 kinetics, ICH climate zones, predictShelfLife), and bioavailability-enhancement strategies keyed to published data.

buildtestlint
layer: domainscope: airmidowner: @GreyChimp
lib

@airmid/interactions

#

Drug-herb interaction clinical decision support (libs/airmid/interactions/src). Carries a HERB_DRUG_INTERACTION_DATABASE plus pharmacokinetic profiling — CYP450 inhibition/induction with inhibition-magnitude prediction (CYP450_PROFILE_DATABASE, SUBSTRATE_DRUG_DATABASE, predictInhibitionMagnitude, narrow-therapeutic-index and prodrug awareness) and transporter interactions (TRANSPORTER_PROFILE_DATABASE) — and pharmacodynamic risk scoring (PHARMACODYNAMIC_RISK_DATABASE). The top-level checkInteractions / generatePatientCounseling / generateMonitoringPlan / suggestAlternatives compose these into an overall risk verdict with plain-language counseling.

buildtestlint
layer: domainscope: airmidowner: @GreyChimp
lib

@airmid/microbiome

#

Gut-microbiome pharmacology for herbal medicine (libs/airmid/microbiome/src). Holds a PREBIOTIC_DATABASE of herb-microbiome effects, a microbial-metabolite database (SCFAs with the canonical 60:20:20 ratio, secondary bile acids, TMAO, equol, urolithin metabotypes), 17 clinical dysbiosis patterns with herbal corrections (DYSBIOSIS_PATTERN_DATABASE, calculateDysbiosisScore), herb prodrug-activation pathways (predictProdrugActivation, PRODRUG_ACTIVATION_DATABASE — sennoside→rheinanthrone, ginsenoside→Compound K), and clinical integration with alpha-diversity indices (Shannon/Simpson/Chao1), enterotype classification (Arumugam 2011), and stool-biomarker interpretation.

buildtestlint
layer: domainscope: airmidowner: @GreyChimp
lib

@airmid/ml

#

The AI/ML layer for natural-product discovery (libs/airmid/ml/src), the largest domain computation engine at ~9,000 LOC. It contains from-scratch implementations of named architectures: biomedical NER/relation extraction (biomedical-nlp.ts, 200+ herb patterns), Message-Passing Neural Networks (Gilmer 2017) and TransE knowledge-graph embedding in graph-neural-networks.ts, a SMILES Transformer encoder (Vaswani 2017 — selfAttention, positionEncoding, multiHeadAttention), a molecular VAE (Kingma & Welling — vaeEncode, reparameterize, calculateELBO, calculateKLDivergence), explainable-AI methods (Shapley values, integrated gradients, counterfactuals), an ADMET filter battery (admet-filter.ts), and advanced learning (active/federated/few-shot with a Gaussian-mechanism differential-privacy step). The matrix math is hand-written (matmul, softmax, layerNorm); randomness is real algorithmic noise (Box-Muller, negative sampling), annotated random:legitimate.

buildtestlint
layer: domainscope: airmidowner: @GreyChimp
lib

@airmid/network

#

Network pharmacology / systems biology (libs/airmid/network/src). Covers compound-target identification with druggability assessment, PPI network construction over a STRING-derived dataset with graph-theory centralities (calculateDegreeCentrality, calculateBetweennessCentrality, calculateClosenessCentrality, findShortestPath, detectCommunities), pathway enrichment with proper statistics (fishersExactTest, benjaminiHochberg multiple-testing correction), Gene Ontology enrichment with information-content semantic similarity (go-analysis.ts), and multi-layer compound-target-pathway integration for synergy and key-driver prediction (network-integration.ts). These are real graph and statistical algorithms, not placeholders.

buildtestlint
layer: domainscope: airmidowner: @GreyChimp
lib

@airmid/phytochem

#

Computational phytochemistry for natural products (libs/airmid/phytochem/src). Provides a curated 55-entry NATURAL_PRODUCTS_DATABASE, molecular-descriptor estimation (estimateLogP, estimateTPSA, estimateLogS, calculateQED, estimateFsp3), a battery of drug-likeness rules (assessLipinski, assessVeber, assessGhose, assessEgan, assessMuegge, assessLeadLikeness, assessBeyondRuleOfFive), ADMET and toxicity prediction (predictADMET, predictToxicity, estimateLD50, GHS classification), 3D conformer/pharmacophore helpers, and Phase I/II metabolite prediction. One honestly-labelled spot: a metabolite "parent SMILES" placeholder in metabolite-prediction.ts where the real structure isn't reconstructed.

buildtestlint
layer: domainscope: airmidowner: @GreyChimp
lib

@airmid/precision

#

Pharmacogenomics-driven personalized herbal medicine (libs/airmid/precision/src). Implements a CPIC-standard CYP allele database (CYP_ALLELE_DATABASE) with Activity-Score genotype→phenotype classification (classifyCYPPhenotype, classifyCOMT, classifyNAT2, classifyUGT1A1, classifyMTHFR), a 39-entry GENOTYPE_RESPONSE_DATABASE of herb-gene-phenotype interactions, a microbiome-herb interaction database (equol/Compound-K/urolithin metabotypes), biomarker integration with reference ranges (BIOMARKER_REFERENCE_DATABASE, inflammatory/oxidative/hepatic/renal/metabolic panels), and a recommendation engine that fuses genotype, organ function, and microbiome into a dose adjustment plus monitoring plan (generatePersonalizedRecommendation).

buildtestlint
layer: domainscope: airmidowner: @GreyChimp
lib

@airmid/quality

#

Herbal-product quality control and authentication (libs/airmid/quality/src). Implements DNA-barcode species authentication with Needleman-Wunsch alignment (alignSequences, authenticateByBarcode, DNA_BARCODE_REFERENCE_LIBRARY), spectroscopic fingerprinting (FTIR/NIR/Raman/UV-Vis peak detection, baseline correction, similarity matching), chromatographic profiling with system-suitability metrics (calculatePlateCount, calculateHETP, calculateTailingFactor, calculateResolution), pharmacopoeial marker-compound quantification with calibration curves, multi-method adulteration detection (KNOWN_ADULTERATION_PATTERNS), and a full chemometrics suite (SNV/MSC and Savitzky-Golay preprocessing, PCA, PLS-DA, SIMCA with Coomans plots). A single marker-quantification.ts note flags an unimplemented unit-conversion branch.

buildtestlint
layer: domainscope: airmidowner: @GreyChimp
lib

@airmid/regulatory

#

Pharmaceutical regulatory affairs for herbal medicines (libs/airmid/regulatory/src). Covers pharmacopoeia compliance across USP/PhEur/ BP/JP/ChP/IP (PHARMACOPOEIA_MONOGRAPH_DATABASE, comparePharmacopoeias), the EMA/HMPC monograph system distinguishing well-established vs traditional use (EMA_MONOGRAPH_DATABASE, WEU_VS_TU_CRITERIA), the FDA/DSHEA dietary-supplement framework with claim classification and NDI/warning-letter logic (classifyFDAClaim, FDA_WARNING_LETTER_PATTERNS, DSHEA_DISCLAIMER), jurisdiction-by-jurisdiction global status (GLOBAL_REGULATORY_DATABASE, findMostPermissiveJurisdiction), and labeling/claims validation (validateLabel, generateCompliantLabel). The "Would require an approved NDA" strings here are correct regulatory facts in claim-classification output, not code stubs.

buildtestlint
layer: domainscope: airmidowner: @GreyChimp
lib

@airmid/safety

#

Safety and toxicology (libs/airmid/safety/src) — a patient-protection module. Implements adverse-event causality (WHO-UMC assessCausalityWHOUMC, Naranjo ADR scale, PRR/ROR disproportionality signal detection), hepatotoxicity assessment (RUCAM scoring, Hy's Law, R-ratio DILI pattern classification over a 24-entry HEPATOTOXIC_HERB_DATABASE), nephrotoxicity risk with renal-function adjustment, special-population safety databases (pregnancy 40+, pediatric, geriatric), and toxic-contaminant assessment against multi-jurisdiction regulatory limits (TOXIC_COMPOUND_DATABASE, USP/EU/WHO/TGA/HKSAR). These are real pharmacovigilance instruments with named scoring rules.

buildtestlint
layer: domainscope: airmidowner: @GreyChimp
lib

@airmid/sustainability

#

Conservation biology and sustainable harvesting (libs/airmid/sustainability/src). Implements IUCN Red List assessment with quantitative Criterion A–E thresholds (assessConservationStatus, classifyByCriterionA/B/D, MEDICINAL_PLANT_CONSERVATION_DATABASE), CITES and United Plant Savers trade/ at-risk checks, harvest-sustainability assessment with Maximum Sustainable Yield (calculateMSY) and FairWild v2.0 compliance, cultivation profiles with wild-vs-cultivated quality comparison (CULTIVATION_DATABASE), LCA-style environmental-impact scoring (carbon/water/land/biodiversity, transport emission factors), and a substitution engine mapping at-risk species to sustainable alternatives by shared pharmacology (findSubstitutes, SUBSTITUTION_DATABASE).

buildtestlint
layer: domainscope: airmidowner: @GreyChimp
lib

@airmid/vision

#

Computational botany and plant-morphology identification (libs/airmid/vision/src). Real morphometric image analysis rather than a model wrapper: leaf analysis via Elliptic Fourier Descriptors and Hu moments with shape/margin/venation/apex/base classification (computeEllipticFourierDescriptors, computeHuMoments, LEAF_MORPHOLOGY_DATABASE), flower analysis (monocot/dicot, actinomorphic/zygomorphic symmetry, inflorescence, floral formulae), bark texture classification (12 types), multi-organ Bayesian species matching with a dichotomous key and toxic-look-alike warnings (identifyPlant, TOXIC_LOOKALIKE_PAIRS, traverseDichotomousKey), geographic filtering over WWF biomes, and a parametric Köppen-Geiger climate model (getClimateProfile).

buildtestlint
layer: domainscope: airmidowner: @GreyChimp