Turn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 250,000+ scientists worldwide. 177 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.
Python agent-skillsai-scientistbioinformaticschemoinformaticsclaudeclaude-skillsclaudecodeclinical-researchcomputational-biologydata-analysisdrug-discoverygenomicsmaterials-sciencemetabolomicsproteomicsscientific-computingscientific-visualization
Update README and skill requirements to reflect new skill count and additions
Timothy Kassis51f621c13ed1
diff --git a/README.md b/README.mdindex 7425df03..df7365ce 100644--- a/README.md+++ b/README.md@@ -3,7 +3,7 @@[](LICENSE.md)[](https://arxiv.org/abs/2609.00065)[](pyproject.toml)-[](#-whats-included)+[](#-whats-included)[](#-whats-included)[](https://agentskills.io/)[](https://agent-plugins.org/)@@ -17,7 +17,7 @@> **🔔 Claude Scientific Skills is now Scientific Agent Skills.** Same skills, broader compatibility — now works with any AI agent that supports the open [Agent Skills](https://agentskills.io/) standard, not just Claude.-> **New: [K-Dense BYOK](https://github.com/K-Dense-AI/k-dense-byok)** — A free, open-source AI co-scientist that runs on your desktop, powered by Scientific Agent Skills. Bring your own API keys, pick from 40+ models, and get a full research workspace with web search, file handling, 100+ scientific databases, and access to all 169 skills in this repo. Your data stays on your computer, and you can optionally scale to cloud compute via [Modal](https://modal.com/) for heavy workloads. [Get started here.](https://github.com/K-Dense-AI/k-dense-byok)+> **New: [K-Dense BYOK](https://github.com/K-Dense-AI/k-dense-byok)** — A free, open-source AI co-scientist that runs on your desktop, powered by Scientific Agent Skills. Bring your own API keys, pick from 40+ models, and get a full research workspace with web search, file handling, 100+ scientific databases, and access to all 170 skills in this repo. Your data stays on your computer, and you can optionally scale to cloud compute via [Modal](https://modal.com/) for heavy workloads. [Get started here.](https://github.com/K-Dense-AI/k-dense-byok)> **🎥 Webinar recording — [Getting Started with K-Dense BYOK](https://youtu.be/Du3BIE48DKc?si=9dPpETKSc2PeQbvU)**> A hands-on walkthrough of [K-Dense BYOK](https://github.com/K-Dense-AI/k-dense-byok), our free, open-source AI co-scientist that runs locally on your own machine and is powered by Scientific Agent Skills. We cover how to set it up, bring your own API keys, and run real research workflows with these skills. No prior technical experience needed. **[Watch the recording →](https://youtu.be/Du3BIE48DKc?si=9dPpETKSc2PeQbvU)**@@ -26,7 +26,7 @@> **📄 Paper:** Scientific Agent Skills is described in [*Scientific Agent Skills: A Library of Procedural Knowledge for Research Agents*](https://arxiv.org/abs/2609.00065) (arXiv:2609.00065). If you use these skills in your research, please [cite the paper](#-citation).-A comprehensive collection of **169 ready-to-use scientific and research skills** (covering cancer genomics, individual-level 1000 Genomes queries, genome-wide precomputed variant effects from the AlphaGenome Atlas, hosted regulatory-sequence prediction, live pathogen-variant surveillance, analytical method validation, PK/PD modelling and dose selection, full-text biomedical and regulatory literature retrieval, drug-target binding, bounded biomedical knowledge graph search, custom lab-part fabrication quotes and orders through Fictiv, molecular dynamics, RNA velocity, microbiome foundation models, geospatial science, time series forecasting, scientific ML resource discovery via Hugging Science, 78+ scientific databases, and more) for any AI agent that supports the open [Agent Skills](https://agentskills.io/) standard, created by [K-Dense](https://k-dense.ai). The repository is also a portable [Agent Plugins](https://agent-plugins.org/) package (`plugin.json` + `skills/`), so plugin-capable clients can load the whole collection as one plugin. Works with **Cursor, Claude Code, Codex, Google Antigravity, and more**. Transform your AI agent into a research assistant capable of executing complex multi-step scientific workflows across biology, chemistry, medicine, and beyond.+A comprehensive collection of **170 ready-to-use scientific and research skills** (covering cancer genomics, individual-level 1000 Genomes queries, genome-wide precomputed variant effects from the AlphaGenome Atlas, hosted regulatory-sequence prediction, live pathogen-variant surveillance, analytical method validation, PK/PD modelling and dose selection, full-text biomedical and regulatory literature retrieval, drug-target binding, bounded biomedical knowledge graph search, custom lab-part fabrication quotes and orders through Fictiv, molecular dynamics, RNA velocity, microbiome foundation models, geospatial science, time series forecasting, scientific ML resource discovery via Hugging Science, 78+ scientific databases, and more) for any AI agent that supports the open [Agent Skills](https://agentskills.io/) standard, created by [K-Dense](https://k-dense.ai). The repository is also a portable [Agent Plugins](https://agent-plugins.org/) package (`plugin.json` + `skills/`), so plugin-capable clients can load the whole collection as one plugin. Works with **Cursor, Claude Code, Codex, Google Antigravity, and more**. Transform your AI agent into a research assistant capable of executing complex multi-step scientific workflows across biology, chemistry, medicine, and beyond.> ⭐ **Help make AI for science easier to discover:** If Scientific Agent Skills saves you time, teaches your agent a workflow, or helps your lab move faster, please [star this repository](https://github.com/K-Dense-AI/scientific-agent-skills). A star is a public signal that these open, reusable research skills are worth maintaining: it helps scientists, engineers, and open-source contributors find the project, shows which agent-skill standards are gaining real adoption, and gives us a clear reason to keep expanding the collection for the community.@@ -74,7 +74,7 @@ Recorded walkthroughs of these skills on real research tasks, from the [K-Dense## 📦 What's Included-This repository provides **169 scientific and research skills** organized into the following categories:+This repository provides **170 scientific and research skills** organized into the following categories:- **100+ Scientific & Financial Databases** - A unified database-lookup skill provides deterministic, provenance-rich access to 78 public databases (PubChem, ChEMBL, UniProt, COSMIC, ClinicalTrials.gov, FRED, USPTO, and more), plus dedicated skills for DepMap, Imaging Data Commons, PrimeKG, NCATS ARAX, U.S. Treasury Fiscal Data, Hugging Science, OneKGPd, Genomic Intelligence, and AlphaGenome (Atlas lookups and model scoring). Multi-database packages like BioServices (~40 bioinformatics services), BioPython (39 NCBI sub-databases via Entrez), and gget (20+ genomics databases) add further coverage- **70+ Optimized Python Package Skills** - Explicitly defined, version-aware workflows for RDKit, Scanpy, PyTorch Lightning, scikit-learn, PyTDC, PathML, pydicom, NeuroKit2, PufferLib, QuTiP, GeoPandas, pymatgen, BioPython, Qiskit, Molecular Dynamics (OpenMM/MDAnalysis), and others. The agent can still use *any* Python package; these skills provide stronger, safer guidance for the packages listed@@ -121,7 +121,7 @@ Each skill includes:- **Multi-Step Workflows** - Execute complex pipelines with a single prompt### 🎯 **Comprehensive Coverage**-- **169 Skills** - Extensive coverage across all major scientific domains+- **170 Skills** - Extensive coverage across all major scientific domains- **100+ Databases** - Unified access to 78+ databases via database-lookup, plus dedicated data access skills and multi-database packages like BioServices, BioPython, and gget- **70+ Optimized Python Package Skills** - Current, version-scoped guidance for packages including RDKit, Scanpy, PyTorch Lightning, scikit-learn, PyTDC, pydicom, PufferLib, QuTiP, GeoPandas, pymatgen, Qiskit, Molecular Dynamics (OpenMM/MDAnalysis), scVelo, and TimesFM (the agent can use any Python package; these are the pre-documented paths)@@ -228,7 +228,7 @@ For Hermes versions that support skill taps, add the repository as a tap:hermes skills tap add K-Dense-AI/scientific-agent-skills```-Every `SKILL.md` has YAML frontmatter, but legacy and community skills vary in `metadata` formatting (block or flow style) and optional extension fields. Repository updates must keep `metadata.version` as a quoted numeric string and pass canonical `skills-ref validate ./skills/<skill-name>` checks. Hosts may interpret optional metadata and credential prompts differently, so verify behavior on the target host. Because 169 skills add up to a lot of standing context, consider installing a topical subset rather than the whole collection.+Every `SKILL.md` has YAML frontmatter, but legacy and community skills vary in `metadata` formatting (block or flow style) and optional extension fields. Repository updates must keep `metadata.version` as a quoted numeric string and pass canonical `skills-ref validate ./skills/<skill-name>` checks. Hosts may interpret optional metadata and credential prompts differently, so verify behavior on the target host. Because 170 skills add up to a lot of standing context, consider installing a topical subset rather than the whole collection.> **NemoClaw note:** NemoClaw runs agents inside NVIDIA OpenShell with default-deny outbound networking. Skills are discovered and loaded normally, but any skill that needs the network — package installs via `uv`, or API calls (Exa, Parallel, Benchling, NCBI, Materials Project, …) — only works once the operator pre-approves the relevant domains in the OpenShell TUI.@@ -469,15 +469,16 @@ networks, and search GEO for similar patterns.## 📚 Available Skills-This repository contains **169 scientific and research skills** organized across multiple domains. Each skill provides comprehensive documentation, code examples, and best practices for working with scientific libraries, databases, and tools.+This repository contains **170 scientific and research skills** organized across multiple domains. Each skill provides comprehensive documentation, code examples, and best practices for working with scientific libraries, databases, and tools.### Skill Categories> **Note:** The Python package and integration skills listed below are *explicitly defined* skills — curated with documentation, examples, and best practices for stronger, more reliable performance. They are not a ceiling: the agent can install and use *any* Python package or call *any* API, even without a dedicated skill. The skills listed simply make common workflows faster and more dependable.-#### 🧬 **Bioinformatics & Genomics** (29 skills)+#### 🧬 **Bioinformatics & Genomics** (30 skills)- RNA-seq pipelines: Bulk RNA-seq (end-to-end FASTQ -> counts -> DE -> enrichment orchestrator)- Sequence analysis: BioPython, pysam, scikit-bio, BioServices+- PCR assay design: [Primer Design](skills/primer-design/SKILL.md) (Primer3 candidates, thermodynamics, variant masking, tails, and bounded local or BLAST-assisted specificity screening)- Single-cell analysis: Scanpy, AnnData, scvi-tools, scVelo (RNA velocity), Arboreto, Cellxgene Census- Genomic tools: gget, current geniml/Gtars interval workflows, deepTools, Polars-Bio, Zarr, TileDB-VCF- Flow cytometry: FlowIO (FCS input/output), [FlowKit](skills/flowkit/SKILL.md) (compensation, transforms, hierarchical gating, and FlowJo workspace analysis)@@ -926,7 +927,7 @@ If you also need to cite a specific version of the repository itself (for exampltitle = {Scientific Agent Skills: A Comprehensive Collection of Scientific Tools for AI Agents},year = {2026},url = {https://github.com/K-Dense-AI/scientific-agent-skills},- note = {169 skills covering databases, packages, integrations, and analysis tools}+ note = {170 skills covering databases, packages, integrations, and analysis tools}}```diff --git a/skills/primer-design/SKILL.md b/skills/primer-design/SKILL.mdnew file mode 100644index 00000000..b6f7a931--- /dev/null+++ b/skills/primer-design/SKILL.md@@ -0,0 +1,272 @@+---+name: primer-design+description: Designs and audits PCR and RT-qPCR primers with Primer3, explicit thermodynamic conditions, reference-based off-target amplification searches, and traceable sequence coordinates. Use for designing primer pairs, checking existing primers, exon-junction or isoform-specific assays, variant masking, cloning tails, multiplex compatibility, and interpreting Primer-BLAST results. Includes bounded local in-silico PCR and BLAST screening; distinguishes computational candidates from experimentally validated assays.+license: MIT+compatibility: Requires Python 3.11+ and primer3-py 2.3.1 for design and thermodynamics. Local exhaustive screening uses the standard library; BLAST screening additionally needs blastn and makeblastdb on PATH. Network access is needed only for installation, reference retrieval, or external Primer-BLAST.+metadata:+ version: "1.0"+ skill-author: K-Dense Inc.+ last-reviewed: "2026-09-30"+---++# Primer design and specificity++Produce candidate oligos in 5-prime-to-3-prime orientation, with the exact template,+chemistry, intended products, and search scope behind each conclusion. Calculate+sequence-dependent quantities with the supplied tools. A familiar gene name, good+Primer3 penalty, or a single BLAST alignment cannot establish primer specificity.++## Choose the workflow++| Request | Start here |+| --- | --- |+| New genomic PCR or RT-qPCR pair | Define the assay and reference; design; assess thermodynamics; screen products. |+| Check an existing pair | Prepare pair TSV; assess both full oligos and annealing cores; screen with explicit intended coordinates. |+| Exon junction, transcript isoform, allele discrimination | Read [design-workflows.md](references/design-workflows.md); supply sequence annotation before imposing constraints. |+| Cloning/adaptor-tailed primers | Design annealing cores, append declared 5-prime tails, reassess full oligos, reconstruct the final product. |+| Multiplex panel | Enable `--multiplex` in both thermodynamics and specificity tools to assess oligo interactions and cross-pair products. |+| Degenerate, bisulfite, probe, or modified-base assay | Use the specialized workflow in [design-workflows.md](references/design-workflows.md); the bundled ordinary-DNA model is insufficient. |++The local tooling supports paired primers with unambiguous ACGT cores. Advanced assay+types have substantive design and validation guidance, but are not silently reduced+to ordinary PCR. This skill designs assays; expression normalization, experimental+diagnostic validation, and guide-RNA design are separate tasks.++## Establish the assay contract++Obtain what changes the result; use explicit provisional assumptions for an exploratory+design, and identify them in the report:++- **Purpose and template:** genomic DNA, cDNA, plasmid, or another defined substrate;+ target organism, accession **with version**, assembly/transcript release, strand,+ desired isoforms, and product-size range. Name wanted and unwanted templates.+- **Sequence evidence:** local FASTA plus source/retrieval date and its SHA-256 hash.+ A locus excerpt uses local coordinates; record its mapping to the full reference.+ Include relevant paralogs, pseudogenes, alternate contigs, transcript isoforms,+ vector backbone, and host sequence in the appropriate screen.+- **Reaction conditions:** polymerase/buffer, monovalent salt, total divalent salt,+ total dNTP, and oligo concentrations. Primer3 uses mM for salts/dNTP and nM for DNA.+ Engine defaults are starting assumptions, not a measured formulation.+- **Constraints:** target interval, allowed/excluded binding regions, junctions,+ variant exclusions and their source, fixed primers, tails, or multiplex membership.+ Do not guess exon boundaries or silently substitute another assembly.+- **Definition of an acceptable result:** relevant off-target references, amplicon+ lengths, mismatch search limits, controls, and experimental validation appropriate+ to the assay. There is no universal thermodynamic cutoff that validates all PCRs.++Use [input-contract.md](references/input-contract.md) for file schemas and coordinate+examples. Copy [assay-report-template.md](assets/assay-report-template.md) into the+analysis directory to collect evidence. Reference retrieval may be manual or through+an established sequence API; preserve accession/version and verify the returned+sequence. The supplied scripts use local files and do not submit sequences online.++## Install and verify++Set `SKILL_DIR` to this skill's actual installed directory. Work in a separate analysis+directory so environments, reference databases, and results do not enter the skill.++```bash+uv venv --python 3.13 .venv-primer+uv pip install --python .venv-primer/bin/python -r "$SKILL_DIR/assets/requirements.txt"+.venv-primer/bin/python "$SKILL_DIR/scripts/design_primers.py" --help+```++Use the environment's `Scripts/python.exe` on Windows. The design/thermodynamic+examples target primer3-py **2.3.1**, tested with Python **3.13**. For the optional+BLAST engine, install NCBI BLAST+ from its official distribution and check:++```bash+blastn -version+makeblastdb -version+```++Local integration checks also exercise BLAST+ 2.17.0; other releases require checking+their output and search behavior before claiming equivalent coverage.++Read [sources.md](references/sources.md) when updating dependencies or API assumptions.+The scripts record engine versions and effective settings in their JSON reports.++## 1. Design candidates++For an initial functional demonstration, use the bundled synthetic sequence. It is+nonbiological example input, not an experimentally validated assay:++```bash+.venv-primer/bin/python "$SKILL_DIR/scripts/design_primers.py" \+ --template "$SKILL_DIR/assets/demo-template.fasta" \+ --preset qpcr --config "$SKILL_DIR/assets/qpcr-config.json" \+ --output design.json --pairs-out pairs.tsv --expected-out expected.tsv+```++For actual work, substitute the reviewed target FASTA and constraints. A multi-record+FASTA requires `--record` with its exact ID. The `pcr` preset requests 100–1000 bp;+`qpcr` requests 70–200 bp. Override these starting ranges in the configuration.+The example overrides its range to 90–180 bp and includes a specific target interval.++The tool:++- Passes validated `sequence_args` and `global_args` to Primer3. Unsupported or+ misspelled tags fail rather than silently changing the task.+- Converts ambiguous template positions to `N` and forbids ambiguous primer bases.+ It does not interpret lowercase sequence as a repeat mask; use explicit exclusions.+- Optionally imports `--mask-bed` exclusions in **the supplied template's coordinates**.+ Use BED intervals for variant/repeat masking only after validating the reference+ mapping; it does not infer allele frequencies or convert arbitrary VCFs.+- Verifies returned forward and reverse sequences against the template and checks+ product lengths. Primer3's right-primer position is converted into a half-open+ binding interval; the reverse primer is already in ordering orientation.+- Optionally appends `--forward-tail` and `--reverse-tail` to cores. The design score+ and core Tm do not include those tails; step 2 checks complete oligos.++Inspect `engine_explanations` when no candidates are found. Change a biologically+justified constraint and rerun; do not silently relax all constraints or return an+invented sequence. Preserve previous reports when comparing parameter choices.++`expected.tsv` describes intended products **on the design template**. If screening+another reference, map these coordinates to its exact record IDs and orientation.+A cDNA product cannot be relabeled as a genomic interval across introns.++## 2. Assess thermodynamics++Use the **same chemistry as the design**. The following explicit values match the+bundled design defaults; replace them together when the actual conditions differ:++```bash+.venv-primer/bin/python "$SKILL_DIR/scripts/check_thermodynamics.py" \+ --pairs pairs.tsv --mv-conc 50 --dv-conc 1.5 --dntp-conc 0.6 \+ --dna-conc 50 --temp-c 37 --output thermodynamics.json+```++The report contains core Tm, core and full-oligo hairpins/homodimers, full-oligo+heterodimers, self 3-prime end stability, and both directional inter-oligo 3-prime+end-stability calculations. Delta-G and+delta-H are reported in kcal/mol; delta-S in cal/(mol K). `--temp-c` controls the+temperature for delta-G, **not** a recommended PCR annealing temperature.++If design used different Tm/salt models, also set `--tm-method` and+`--salt-corrections-method` to match; see the mapping in the input contract.++For a panel, add `--multiplex` to examine all unordered oligo combinations, including+forward/forward and reverse/reverse between different pairs. Distinguish a panel to+be combined from alternative candidates that will be tested separately.++Read [thermodynamics.md](references/thermodynamics.md) before interpreting these+values. Full oligos longer than 60 bases are reported as unresolved; they are never+silently truncated. Modified bases and degenerate mixtures require a suitable model.+Thermodynamic predictions support ranking and experimental planning, not a blanket+claim of primer quality.++## 3. Screen amplification products++Read [specificity.md](references/specificity.md) before making a specificity claim.+Search each primer on both strands and pair inward-facing binding sites. A binding+hit alone is not an amplicon; absence of a reported hit is not proof of absence.++### Exhaustive bounded local search++```bash+.venv-primer/bin/python "$SKILL_DIR/scripts/screen_specificity.py" \+ --pairs pairs.tsv --reference "$SKILL_DIR/assets/demo-template.fasta" \+ --expected expected.tsv --engine exhaustive \+ --min-product 40 --max-product 1000 --max-mismatches 2 \+ --three-prime-bases 5 --max-three-prime-mismatches 0 \+ --output specificity.json+```++This enumerates full-length, ungapped binding sites in a **bounded local reference**+and checks F/R, R/F, F/F, and R/R products for each pair. Reference ambiguity is+treated conservatively as unresolved sequence; it cannot establish a clean result.+The mismatch limits are a search model, not a validated polymerase discrimination+rule. Tight 3-prime thresholds can exclude amplifiable mismatched sites; broaden+the search when evaluating that uncertainty.++Use `--circular RECORD_ID` for a circular molecule. Wrapped products use canonical+start coordinates and unwrapped ends greater than the reference length; only+products spanning at most one molecule are considered. Caps on comparisons, hits,+and products prevent unbounded work; hitting a cap makes the result incomplete.++### BLAST-assisted local search++```bash+.venv-primer/bin/python "$SKILL_DIR/scripts/screen_specificity.py" \+ --pairs pairs.tsv --reference "$SKILL_DIR/assets/demo-template.fasta" \+ --expected expected.tsv --engine blast \+ --min-product 40 --max-product 1000 --max-mismatches 2 \+ --three-prime-bases 5 --max-three-prime-mismatches 0 \+ --output specificity-blast.json+```++The script builds a temporary local BLAST database, runs short-query alignment,+rechecks complete primer-length candidate sites, and records commands and versions.+It checks configured hit limits and tool failures. BLAST discovery is heuristic:+successful execution and unsaturated limits do not establish exhaustive coverage.+The reference is loaded in memory; plan memory and search bounds for large genomes.+The small example verifies execution, not human-genome sensitivity or scalability.++For broader public-reference screening, follow the official NCBI Primer-BLAST+workflow in [specificity.md](references/specificity.md), choosing the organism,+database, intended templates, maximum product length, and mismatch policy deliberately.+Submitting a sequence sends it to NCBI; keep local-only work local. Primer-BLAST+is not a documented REST API implemented by these scripts.++### Interpret the result++- `potential_off_target`: inspect every unexpected product, including its orientation,+ length, mismatch positions, and reference identity; redesign or justify its relevance.+- `intended_target_not_found`: resolve mapping, reference, sequence, and search problems+ before drawing specificity conclusions.+- `no_expected_target`: results are a product inventory, without a target-specific+ conclusion. Supply all intended product intervals for the assay.+- `incomplete`: reference uncertainty, resource limits, or failed computation leaves+ the conclusion unresolved. Inspect the reported reason and repeat appropriately.+- `no_off_target_found_within_search_scope`: state the exact reference and search+ model. Check the report's exhaustive/heuristic flags; this is not empirical validation.++For a multiplex reaction, add `--multiplex` to the specificity command as well as+the thermodynamics command. The specificity tool then searches every cross-pair+oligo combination, retaining the original oligo identities and tails. It treats+cross-pair products as unintended; intentionally shared-primer designs require+explicit standalone combinations with reviewed expected products. The+`--max-panel-combinations` cap defaults to 10,000 and is checked before expansion.+Thermodynamic `--multiplex` checks structures; specificity `--multiplex` checks+reference products. Both are necessary for this panel assessment.++## 4. Validate the assay and deliver evidence++Select candidates using assay purpose, coverage, specificity evidence, and chemistry,+not just the lowest Primer3 penalty. Preserve multiple candidates when uncertainty+remains. Follow [design-workflows.md](references/design-workflows.md) for the relevant+experimental checks: expected product identity/size, negative and no-template controls,+genomic contamination controls for RT-qPCR, and efficiency/dynamic-range assessment+when quantification is intended. A single melt peak alone does not prove identity.++Deliver the completed [report template](assets/assay-report-template.md), pair TSV,+design/thermodynamic/specificity JSON, and source manifest. Include:++1. Exact ordering sequences, separated annealing cores and tails, primer lengths,+ intended product coordinates/size, and any relevant transcript/junction mapping.+2. Chemistry and model settings; engine versions; reference accession/release, source,+ retrieval date, and file hashes; explicit exclusions and rationale.+3. Intended and potential unintended products; uncertainty from unknown bases,+ incomplete references, heuristic searches, caps, and unsupported assay chemistry.+4. Experimental evidence actually obtained, outstanding validation, and the reason+ for each recommended candidate. Label untested candidates accurately.++## Validation and limits of this implementation++The repository suite at `tests/primer-design/` exercises actual Primer3 calculations,+orientation and coordinate reconstruction, masking, tails, concentration handling,+off-target product geometry, mismatch/ambiguity behavior, failure states, and local+BLAST integration when its executables are installed. Synthetic fixtures establish+software behavior; they do not validate a biological assay or prove genome-wide recall.++Tools return 0 when their computation completes, 1 for a completed design with no+candidates or incomplete long-oligo thermodynamics, and 2 for invalid input or tool+failure. Read the JSON scientific status even after exit 0: finding an off-target is+a successfully completed calculation. See the input contract for screen-specific exits.++## Citing Scientific Agent Skills++If used in published work, cite the upstream methods in [sources.md](references/sources.md)+and [Scientific Agent Skills](https://arxiv.org/abs/2609.00065). Report the software+versions and assay-specific settings required to reproduce the actual analysis.diff --git a/skills/primer-design/assets/assay-report-template.md b/skills/primer-design/assets/assay-report-template.mdnew file mode 100644index 00000000..85b75984--- /dev/null+++ b/skills/primer-design/assets/assay-report-template.md@@ -0,0 +1,55 @@+# Primer design evidence report++## Assay and intended conclusion++- Purpose, template type, organism, and intended target/isoforms:+- Intended and explicitly excluded products:+- Product-size requirement and reason:+- Current evidence level: computational candidate / experimental results available:++## Reference manifest++| File | Source URL/accession.version | Assembly/transcript release | Retrieval date | SHA-256 | Scope and limitations |+| --- | --- | --- | --- | --- | --- |++Record local-to-reference coordinate mapping, strand, circularity, and annotation source.+Record variant/repeat mask source, release, thresholds, and coordinate transformation.++## Reaction and design assumptions++- Polymerase and buffer formulation:+- Monovalent / total divalent / total dNTP concentrations (mM):+- Primer concentration (nM, model convention):+- Design constraints, engine versions, and report paths:+- Assumptions requiring confirmation:++## Candidate oligos++| Pair | Role | Annealing core 5′→3′ | 5′ tail | Full order sequence 5′→3′ | Core Tm / conditions | Binding interval |+| --- | --- | --- | --- | --- | --- | --- |++State coordinate convention and reference ID. Do not reverse-complement a returned+reverse-primer ordering sequence again. Include intended product sequence/length and,+for tailed assays, the separately reconstructed final product.++## Specificity evidence++| Pair | Intended products recovered | Potential unintended products | Search engine/reference | Search limits/completeness | Decision and reason |+| --- | --- | --- | --- | --- | --- |++Include FF/RR as well as FR products, 3′ mismatch positions, unknown-base regions,+cap saturation, and heuristic limitations. For multiplex, include cross-pair products.++## Thermodynamic evidence++Record core Tm, full-oligo hairpins and dimers, directional 3′ interactions, chemistry,+temperature for delta-G, unsupported calculations, and relevant panel interactions.+Explain assay-specific ranking; do not invent universal pass thresholds.++## Experimental checks and final recommendation++- Product identity/size evidence and relevant controls:+- Quantitative assay efficiency, dynamic range, and precision when applicable:+- Findings supporting each selected candidate:+- Unresolved questions and next validation steps:+- Output files, hashes, and upstream method citations:diff --git a/skills/primer-design/assets/demo-template.fasta b/skills/primer-design/assets/demo-template.fastanew file mode 100644index 00000000..22c3473f--- /dev/null+++ b/skills/primer-design/assets/demo-template.fasta@@ -0,0 +1,9 @@+>synthetic_target reproducible nonbiological demonstration; seed 717+CCCTCAAGAGTAGTCGTTATCACAACGCCACATTGATTTAGAAAGACAAGTCGGATATAGTCAACTTGCT+ATGCTATATAGTATTCACAAGGCATTGCTCCAGAGGCTATCGATTATAGTATAAGTCGCCGAAGAGTACC+TAGTTTGGTGCTAGAAAGGCGCTAAGCTGATGGGGAATCCTTCGCCTCCGTGACGCTAGATGCAACTATA+ATCACAAATAATCCATGCCCGATCATGGCAGGACCCCGAACTCTTGACACAGCCTGGACGCTCTTACGGA+ATATCGTTGAGGAATTAACCGAGCCATGCGGTAAGACATGGAACAAGACGCAGAGACCTCCTTAAATGGC+GACCTCAAAACCGCGAACGTAGTCCTAGGTGTGGTTTTGTATGGATCCAATCGCCGTGAACTGATTAAAA+CAACCTGGCAATCATAATAGGTAATCCGCTCCAACCTTGTCTTGGCACGAGGACTTGTCCCTGCCATGGT+GTTGATTACTdiff --git a/skills/primer-design/assets/qpcr-config.json b/skills/primer-design/assets/qpcr-config.jsonnew file mode 100644index 00000000..3b086acc--- /dev/null+++ b/skills/primer-design/assets/qpcr-config.json@@ -0,0 +1,19 @@+{+ "sequence_args": {+ "SEQUENCE_TARGET": [+ [+ 235,+ 30+ ]+ ]+ },+ "global_args": {+ "PRIMER_PRODUCT_SIZE_RANGE": [+ [+ 90,+ 180+ ]+ ],+ "PRIMER_NUM_RETURN": 3+ }+}diff --git a/skills/primer-design/assets/requirements.txt b/skills/primer-design/assets/requirements.txtnew file mode 100644index 00000000..5c7df705--- /dev/null+++ b/skills/primer-design/assets/requirements.txt@@ -0,0 +1 @@+primer3-py==2.3.1diff --git a/skills/primer-design/references/design-workflows.md b/skills/primer-design/references/design-workflows.mdnew file mode 100644index 00000000..617f9855--- /dev/null+++ b/skills/primer-design/references/design-workflows.md@@ -0,0 +1,177 @@+# Assay-specific design workflows++Documentation checked: 2026-09-30. These are design and review procedures. The+bundled tools automate ordinary DNA-primer design, thermodynamics, and bounded+local-reference screening; they do not implement every specialized assay below.++## Define success before choosing sequences++Write a design brief with:++- Assay purpose: genomic PCR, RT-PCR/RT-qPCR, cloning, genotyping, or another named+ assay; biological material and expected background DNA.+- Intended target set: one locus, one transcript, several named isoforms, or all+ members of an explicitly listed set. A gene symbol alone is insufficient.+- Reference identity: accession **with version**, assembly and annotation release,+ strand, extraction coordinates, FASTA checksum, and reference retrieval date.+- Desired product interval, region that must be contained in the product, regions+ primers must avoid, and any fixed primer or required junction.+- Polymerase/master mix, known reaction chemistry, available empirical validation,+ and constraints imposed by the downstream method.++Keep defaults provisional when chemistry is unknown. Do not translate a missing+reference or ambiguous target into a made-up sequence. Acquire the sequence or+provide the unfinished design specification and the missing inputs.++## Ordinary genomic PCR++1. Extract the target with enough flanking sequence for alternative binding sites.+ Retain its mapping to the full reference; template-local coordinates are not+ chromosome coordinates.+2. Mark low-confidence sequence, repeats, and relevant population/sample variants+ as exclusions when their avoidance is part of the assay specification.+3. Design several candidates with explicit product and primer constraints. Inspect+ rejection reasons if none return; relax one justified constraint at a time and+ record each change.+4. Verify both synthesized primer sequences against the template, their inward+ orientation, and the entire expected product. Include primer-binding sites in+ the product length.+5. Screen against the broader reference and expected background. A successful+ design on a small extracted window establishes no genome-wide specificity.+6. Retain at least one alternative pair at different sites when feasible. Rank+ acceptable candidates by assay priorities, not solely by Primer3 penalty.++Keep intended product size distinct from the maximum unintended-product size+screened. Search for plausible off-target products outside the intended design+range as well. See [specificity.md](specificity.md).++## RT-PCR and RT-qPCR++Choose **transcript-specific**, **gene-level**, or **explicit multi-transcript**+detection before designing. Enumerate intended and excluded transcript accessions;+check that the selected annotation actually contains the junction of interest.++An exon-junction primer can reduce genomic amplification, but its binding site must+be checked against genomic DNA and processed pseudogenes. A pair in different+exons instead relies on intervening genomic structure; short introns can still+produce genomic products. Test the annotated transcript sequence and corresponding+genomic context separately. NCBI Primer-BLAST supports these distinctions when+appropriate reference records are supplied. Its “allow splice variants” option+permits additional variants; it does **not** require coverage of all variants.+[Primer-BLAST guidance](https://www.ncbi.nlm.nih.gov/tools/primer-blast/).++For qPCR, select product dimensions appropriate to the chemistry, sample quality,+and assay purpose; no size or Tm range guarantees an efficient assay. Plan+experimental specificity checks, no-template controls, and a no-RT control where+genomic carryover matters. Estimate efficiency and usable quantitative range with+suitable material. A single melt peak is evidence to review with product identity,+not proof that the desired transcript was amplified. Report sequences, product+identity, chemistry, controls, and measured validation separately from predictions.+[MIQE 2.0](https://academic.oup.com/clinchem/article/71/6/634/8119148).++Primer design does not establish stable reference-gene expression, valid+normalization, or biological replication. Hydrolysis probes additionally require+probe-specific chemistry and modification-aware analysis; a Primer3 internal oligo+alone is not a validated probe assay.++## Variants and allele discrimination++For a general assay, intersect **both complete binding intervals** with variants+from the relevant assembly and population or sample. Inspect near-3′ variants+closely, but retain the position and identity of every overlapping variant.+Variant absence from a database is not evidence that a sample has no variation.++Use an explicit coordinate conversion before creating exclusions. For example, a+1-based SNP at reference position `p` occupies `[p-1, p)` in 0-based half-open+coordinates. If a plus-strand extracted template starts at offset `s`, its local+interval is `[p-1-s, p-s)`. For reverse-complement extraction, additionally transform+through the extracted sequence length. Confirm the reference allele after mapping.+Indels require their complete affected interval and attention to normalization;+do not treat every VCF record as a one-base exclusion.++For intended allele-specific PCR, state which allele each primer should recognize,+retain both allele sequences, and predict binding/product formation on both.+Deliberate 3′ discrimination needs validation with known positive and negative+genotypes. Neither a terminal mismatch nor a numerical mismatch budget proves+allele discrimination; this is a specialized assay, not an automatic “pass” from+the ordinary specificity screen. The need to consider polymorphic binding sites+is discussed in the [Primer-BLAST paper](https://pmc.ncbi.nlm.nih.gov/articles/PMC3412702/).++## Cloning primers and 5′ additions++Store three distinct sequences for each oligo: the **annealing core**, the **5′+tail**, and the **full ordered oligo** (`tail + core`, all 5′→3′). The reverse primer+is already supplied in synthesized orientation; do not reverse-complement its+entire ordered sequence again.++Use the core for initial template binding and reference specificity. Assess the+full oligo for hairpins and primer-primer interactions. Reconstruct the final+double-stranded product explicitly: in forward orientation its ends are the+forward tail and the reverse complement of the reverse tail. Verify every junction,+orientation, coding frame, and required downstream sequence.++For restriction cloning, check recognition-site placement, internal sites, and the+enzyme's current end-cleavage requirements. For overlap assembly, validate overlap+identity and order against the neighboring fragment, not the source template.+Assembly and PCR impose separate constraints; use the chosen reagent's current+instructions. [NEB assembly design guidance](https://www.neb.com/en-sg/tools-and-resources/video-library/primer-design-and-fragment-assembly-using-gibson-assembly?autoplay=1).++Very long tails may exceed the bundled thermodynamic engine's supported lengths.+Report that gap; do not silently truncate the oligo. Circular plasmids also require+an origin-aware product search rather than ordinary linear coordinates.++## Multiplex panels++Validate each pair independently first. Then enumerate interactions across **all**+oligos sharing a tube, including tails and cross-pair forward/reverse combinations.+Assess cross-pair amplification on the reference in addition to dimers. A dimer+matrix alone does not establish multiplex specificity.++Build a conflict table linking interacting oligo IDs, predicted structures, products,+and proposed pool assignments. Reconsider conflicting pairs or split pools, then+recompute the complete panel. Report omitted combinations and any analysis cap.+Validate performance in the final mixture: favorable singleplex results do not+establish multiplex efficiency or balanced yield. Pool assignment can be treated+as a separate optimization problem, as in+[PrimerPooler](https://pubmed.ncbi.nlm.nih.gov/32161789/).++## Degenerate and family-wide primers++Start from a curated multi-sequence alignment and an explicit coverage target.+Identify which variants each concrete oligo can bind. IUPAC codes describe mixtures;+they are not ordinary bases for the bundled thermodynamic/design routines. For+small, bounded mixtures, expand every concrete oligo and analyze all resulting+species and products; record the expansion size and the assumed concentration per+species. If expansion is capped, report incomplete coverage instead of selecting+one arbitrary realization.++For protein-guided family discovery, CODEHOP uses a degenerate core and consensus+clamp; it requires an appropriate alignment and specialized design procedure.+Do not substitute ordinary single-template Primer3 design and claim equivalent+family coverage. [CODEHOP primary description](https://pubmed.ncbi.nlm.nih.gov/12824413/).++## Bisulfite and other specialized chemistries++Distinguish methylation-specific amplification from methylation-independent+bisulfite sequencing. They have different requirements for CpGs in binding sites.+Design on the appropriate converted sequence states and screen the corresponding+converted reference strands; an untreated-reference search cannot establish+specificity after conversion. Conversion reduces sequence complexity and can alter+which strands are complementary. These workflows need dedicated conversion-aware+tools and validation, such as those described in+[MethPrimer](https://pubmed.ncbi.nlm.nih.gov/12424112/) and+[BiSearch](https://pubmed.ncbi.nlm.nih.gov/15653630/).++Modified oligos, LNA/PNA chemistries, nested PCR, long-range PCR, inverse PCR, and+site-directed mutagenesis each add requirements beyond this skill's automatic+ordinary-primer workflow. Retain the relevant chemistry or geometry explicitly,+use its specialist method, and report what the bundled tools could not establish.++## Candidate decision record++Deliver a ranked table with oligo IDs, 5′→3′ sequences, core/tail distinction,+reference coordinates and strand, expected product, chemistry-specific Tm,+structure flags, specificity evidence, and decision rationale. Include discarded+candidates with concrete failure reasons when useful. Label the state precisely:+**designed**, **computationally screened within stated limits**, or **empirically+validated under stated conditions**. These are different evidence levels.diff --git a/skills/primer-design/references/input-contract.md b/skills/primer-design/references/input-contract.mdnew file mode 100644index 00000000..2c24e8a5--- /dev/null+++ b/skills/primer-design/references/input-contract.md@@ -0,0 +1,200 @@+# Files, coordinates, settings, and result contracts++Use local UTF-8 files. All scripts accept `--help` without contacting a service.+Generated JSON is evidence, not a command file. Keep results outside the skill.++## Template and screening FASTA++- The first whitespace-delimited token after `>` is the record ID. IDs must be unique.+- Sequence is case-normalized. Internal whitespace, digits, gaps, RNA U, and non-IUPAC+ symbols are rejected. Empty records and sequence before a header are rejected.+- Design uses one selected record; `--record` is required with multiple records.+- Design replaces ambiguity with N and excludes it from primers. Screen reference+ ambiguity uses possible-base sets and reports unresolved matching sites.+- Preserve full reference ID/version/source in a separate manifest. A user-written+ FASTA label is not verified evidence of an accession or assembly.+- Local files are hashed. Checksums identify the bytes used; they do not independently+ establish database currency, biological correctness, or adequate coverage.++The example FASTA in `../assets/demo-template.fasta` contains 500 deterministic+synthetic bases generated with Python `random.Random(717)`, choosing A/C/G/T uniformly.+It is reproducible demonstration input with no claimed biological function.++## Primer pair TSV++Required columns: `pair_id`, `forward`, `reverse`.+Optional columns: `forward_tail`, `reverse_tail` (empty means no tail).+Columns are tab-separated; unknown/duplicate columns and malformed rows are errors.++```text+pair_id forward reverse forward_tail reverse_tail+assay_1 ACGTCAGTACGATCGTACGA TCGATGCACTGATCGTACGT GGATCC GAATTC+```++These illustrative oligos explain the schema; they are not recommended experimental+primers. Pair IDs use letters, digits, underscores, periods, and hyphens and must be+unique. Cores and tails are unambiguous ACGT DNA, written in ordering orientation+5′→3′. Modified bases and degenerate symbols are rejected, not stripped.++The full ordering sequence is `tail + core`. A reverse primer is already reverse-+complemented relative to its target; do not reverse-complement it again for ordering.+For an exact-match product oriented from the forward primer toward the reverse:++```text+final top strand = forward_tail + template_product + reverse_complement(reverse_tail)+```++For mismatched primers, late-cycle products incorporate primer bases; a reference+product hash does not identify that final synthesized molecule. The screen explicitly+names its hash `reference_product_sha256` and does not reconstruct such products.++## Design configuration JSON++Top-level keys are only `sequence_args` and `global_args`, both objects. Template,+record ID, paired-primer task, 0-based indexing, and unambiguous output are controlled+by the adapter. It rejects unsupported tags, including tags for another Primer3 task.++Example (JSON, not skill frontmatter):++```json+{+ "sequence_args": {+ "SEQUENCE_TARGET": [[235, 30]],+ "SEQUENCE_EXCLUDED_REGION": [[80, 5]]+ },+ "global_args": {+ "PRIMER_PRODUCT_SIZE_RANGE": [[90, 180]],+ "PRIMER_NUM_RETURN": 3,+ "PRIMER_SALT_MONOVALENT": 50.0,+ "PRIMER_SALT_DIVALENT": 1.5,+ "PRIMER_DNTP_CONC": 0.6,+ "PRIMER_DNA_CONC": 50.0+ }+}+```++### Sequence constraints supported by the adapter++| Tag | Value and meaning |+| --- | --- |+| `SEQUENCE_TARGET` | List of `[start,length]` regions the product should encompass; primers flank the target |+| `SEQUENCE_INCLUDED_REGION` | One `[start,length]` design region within the selected template |+| `SEQUENCE_EXCLUDED_REGION` | List of `[start,length]` regions where primer binding is disallowed |+| `SEQUENCE_PRIMER_PAIR_OK_REGION_LIST` | List of `[left_start,left_length,right_start,right_length]`; `[-1,-1]` makes that side unconstrained |+| `SEQUENCE_OVERLAP_JUNCTION_LIST` | Indices of bases immediately left of internal junctions; verify returned overlap against transcript annotation |+| `SEQUENCE_PRIMER` | Fixed forward core in ordering orientation |+| `SEQUENCE_PRIMER_REVCOMP` | Fixed reverse core in ordering orientation |+| `SEQUENCE_QUALITY` | One nonnegative integer score per template base; pair with explicit quality thresholds or weights |++`SEQUENCE_OVERLAP_JUNCTION_LIST` uses the index of the base immediately **before**+the junction with this adapter's `PRIMER_FIRST_BASE_INDEX=0`. A junction between+bases at indices 99 and 100 is supplied as **99**. Use the minimum 5′/3′ overlap controls and verify the returned+binding interval, not just the command's exit status.++### Global controls supported by the adapter++- Candidate count (`PRIMER_NUM_RETURN`, 1–100).+- Primer size: `PRIMER_MIN_SIZE`, `PRIMER_OPT_SIZE`, `PRIMER_MAX_SIZE`; adapter range+ 15–36 nt, ordered minimum ≤ optimum ≤ maximum.+- Tm: `PRIMER_MIN_TM`, `PRIMER_OPT_TM`, `PRIMER_MAX_TM`, `PRIMER_PAIR_MAX_DIFF_TM`.+- GC: `PRIMER_MIN_GC`, `PRIMER_OPT_GC_PERCENT`, `PRIMER_MAX_GC`, `PRIMER_GC_CLAMP`,+ `PRIMER_MAX_END_GC`; `PRIMER_MAX_POLY_X`, `PRIMER_MAX_END_STABILITY`.+- Thermodynamic structure limits: `PRIMER_MAX_SELF_ANY_TH`, `PRIMER_MAX_SELF_END_TH`,+ `PRIMER_MAX_HAIRPIN_TH`, `PRIMER_PAIR_MAX_COMPL_ANY_TH`, `PRIMER_PAIR_MAX_COMPL_END_TH`.+- Chemistry: `PRIMER_SALT_MONOVALENT`, `PRIMER_SALT_DIVALENT`, `PRIMER_DNTP_CONC`,+ `PRIMER_DNA_CONC`. Salt/dNTP units are mM; DNA concentration is nM.+- Core Tm model: `PRIMER_TM_FORMULA` is 0 Breslauer or 1 SantaLucia; salt correction+ `PRIMER_SALT_CORRECTIONS` is 0 Schildkraut, 1 SantaLucia, or 2 Owczarzy. Match these+ to `check_thermodynamics.py --tm-method` and `--salt-corrections-method` respectively.+ Defaults are SantaLucia for both. Structure calculations use libprimer3 defaults.+- `PRIMER_PRODUCT_SIZE_RANGE`: nonempty list of `[minimum,maximum]` inclusive ranges.+ Multiple ranges retain Primer3's preference ordering; no global optimum is implied.+- Junction overlap: `PRIMER_MIN_5_PRIME_OVERLAP_OF_JUNCTION` and+ `PRIMER_MIN_3_PRIME_OVERLAP_OF_JUNCTION`.+- Optional ranking weights: `PRIMER_WT_TM_GT`, `PRIMER_WT_TM_LT`, `PRIMER_WT_SIZE_GT`,+ `PRIMER_WT_SIZE_LT`, `PRIMER_PAIR_WT_DIFF_TM`, `PRIMER_PAIR_WT_PR_PENALTY`.+- Quality controls: `PRIMER_MIN_QUALITY`, `PRIMER_MIN_END_QUALITY`,+ `PRIMER_QUALITY_RANGE_MIN`, `PRIMER_QUALITY_RANGE_MAX`, `PRIMER_WT_SEQ_QUAL`,+ `PRIMER_WT_END_QUAL`; supply `SEQUENCE_QUALITY` and meaningful assay-specific values.+- `PRIMER_MAX_NS_ACCEPTED` must remain zero.++All numeric inputs must be finite. For an unimplemented native tag or another task,+use the official Primer3 interface explicitly and retain the same coordinate,+provenance, and validation discipline. Do not disguise it as tested adapter behavior.++## BED masking++`--mask-bed` reads tab-separated `record_id start end` (extra BED columns are allowed).+Intervals are 0-based, half-open. Every record must occur in the input template FASTA;+every interval must fit its record. Exclusions for the selected record are combined+with configuration exclusions. A BED interval `[start,end)` becomes Primer3's+`[start,end-start]`.++For example, VCF POS 101 on a whole-chromosome template describes a single base at+BED `[100,101)`, **after confirming assembly, contig, and REF**. For an extracted+locus, subtract its genomic offset and transform strand where needed. Indels and+multiallelic loci need deliberate affected-interval definitions, not a universal+POS-only conversion. See [design-workflows.md](design-workflows.md).++## Expected product TSV++Exactly four columns: `pair_id`, `record_id`, `start`, `end`. Multiple rows may specify+multiple acceptable products for one pair. Match actual reference IDs; no record-name+allowlist or fuzzy coordinate matching is performed.++- Linear interval: `0 <= start < end <= record_length`.+- Circular interval: `0 <= start < record_length`, `start < end <= start+record_length`.+ Example: on a 500-base circular record, `[450,550)` describes a 100-base product.+- An expected product matches its exact outer interval and mixed primer roles (F/R+ or R/F). Same-primer products are flagged separately even at the same coordinates.+- Empty/missing expected targets produce an inventory, not a specificity clearance.+- Design export coordinates belong to the design FASTA. Translate them explicitly+ when switching reference; genomic and transcript coordinates are not interchangeable.++## Reports, flags, and exit codes++`design_primers.py` emits pairs, product/core/order sequences, binding/product+intervals, lengths, core Tm, penalties, engine explanations, effective input settings,+and SHA-256/version provenance. Empty results return `no_candidates`, not fake primers.++`check_thermodynamics.py` emits per-oligo core/full structures and per-interaction+directional results. `--multiplex` enumerates all unordered oligo pairs, not just+F/R. A requested panel exceeding `--max-interactions` errors before partial output.+Long full oligos return `unsupported_length`; no full-oligo assessment is implied.++`screen_specificity.py` emits hits and products for each pair, expected/missing+products, status, limitations, settings, reference/pair/expected hashes, and executable+provenance. Binding hit indices are relative to the primer in 5′→3′ orientation;+explicit `*_from_three_prime_1based` fields count back from its 3′ end. Ambiguous bases+carry mismatch lower/upper bounds. A possible base match is not a confirmed match.++All product lengths include binding cores. `length_with_tails` adds the applicable+tails for that product's two primer roles. Product-size search bounds refer to the+reference product before tails. Only nonoverlapping inward-facing sites are modeled.++BLAST is never exhaustive. `complete_within_model=false` and `exhaustive=false`+remain false even when `discovery_completed=true`. Inspect `issues` and per-pair+statuses as well as top-level status. Aggregate status selects the most limiting+state and does not erase other pairs' findings.++For specificity `--multiplex`, the report includes original pairs and generated+cross-pair combinations, with `cross_pair` flags and source oligo identities. The+engine searches unique annealing cores once. With N input pairs, there are+`2*N*(N-1)` cross-pair oligo combinations, checked against `--max-panel-combinations`+before expansion. Same-primer products remain in the original pair inventory.+Every generated cross product is unintended in this mode; no-product cross+combinations receive the scoped no-off-target status. Expected TSV rows may name+only original pairs. Intentional shared-primer panels require explicit standalone+pair definitions and a reviewed set of acceptable products.++| Tool | Exit 0 | Exit 1 | Exit 2 |+| --- | --- | --- | --- |+| Design | Candidates produced | No candidates | Invalid input/engine failure |+| Thermodynamics | Supported calculations completed | Long full oligos remain unassessed | Invalid input/engine failure/cap |+| Specificity | Computation completed; read biological status | Not used | Incomplete search, uncertain matching sites, invalid input, or engine failure |++An observed off-target can accompany a successful exit 0. Missing intended products+also require action even when computation succeeds. Specificity failures write an+`incomplete` report where possible. Invalid design/thermodynamic inputs return an+error without creating a new report; do not reuse a stale output from an earlier run.+Output paths cannot overwrite input files; use distinct filenames for each analysis.diff --git a/skills/primer-design/references/sources.md b/skills/primer-design/references/sources.mdnew file mode 100644index 00000000..b0bf1b12--- /dev/null+++ b/skills/primer-design/references/sources.md@@ -0,0 +1,65 @@+# Sources and maintenance notes++Checked 2026-09-30. Links below are upstream documentation or primary publications.+Their availability does not imply that remote services, specialized assays, or+every API option were exercised by the bundled test suite.++## Executable design and analysis++- [Primer3 manual](https://primer3.org/manual.html): authoritative Boulder-IO design+ tags, coordinates, constraint semantics, and output definitions. Distinguish+ template binding length from products that include overhangs.+- [primer3-py documentation](https://libnano.github.io/primer3-py/): documentation+ currently identifies release 2.3.1 and links the Primer3 2.6.1 manual. Package and+ embedded engine versions are distinct; record both at runtime.+- [Primary Python API](https://libnano.github.io/primer3-py/api/bindings.html):+ `design_primers`, Tm/structure functions, physical parameters, and length limits.+- [Thermodynamic result API](https://libnano.github.io/primer3-py/api/thermoanalysis.html):+ result units, structure flags, and `get_libprimer3_version`.++## Reference specificity++- [NCBI Primer-BLAST](https://www.ncbi.nlm.nih.gov/tools/primer-blast/): current+ assay-design/specificity interface and field-level help.+- [NCBI search tips](https://www.ncbi.nlm.nih.gov/tools/primer-blast/search_tips.html):+ accession-based inputs, target assignment, and search interpretation.+- [Ye et al. (2012), Primer-BLAST](https://pmc.ncbi.nlm.nih.gov/articles/PMC3412702/):+ combined design, alignment, and amplicon-level specificity workflow.+- [BLAST+ nucleotide options](https://www.ncbi.nlm.nih.gov/sites/books/NBK279684/table/appendices.T.blastn_application_options/):+ short-query tasks and search settings. Consult the installed executable's help+ because the Bookshelf table also contains historical release information.++## Thermodynamic foundations++- [SantaLucia (1998)](https://pubmed.ncbi.nlm.nih.gov/9465037/): DNA nearest-neighbor+ parameter framework, DOI `10.1073/pnas.95.4.1460`.+- [Owczarzy et al. (2008)](https://pubmed.ncbi.nlm.nih.gov/18422348/): mixed-ion+ corrections, DOI `10.1021/bi702363u`.+- [Owczarzy et al. (2011)](https://pubmed.ncbi.nlm.nih.gov/21928795/): LNA-specific+ thermodynamics and mismatch behavior, DOI `10.1021/bi200904e`.++## Assay-specific evidence++- [Bustin et al. (2025), MIQE 2.0](https://academic.oup.com/clinchem/article/71/6/634/8119148):+ current qPCR assay reporting and validation guidance,+ DOI `10.1093/clinchem/hvaf043`.+- [NEB overlap-assembly primer guidance](https://www.neb.com/en-sg/tools-and-resources/video-library/primer-design-and-fragment-assembly-using-gibson-assembly?autoplay=1):+ connecting annealing regions to assembly overlaps.+- [Brown et al., PrimerPooler](https://pubmed.ncbi.nlm.nih.gov/32161789/): multiplex+ pool allocation; consult the linked erratum when reproducing published details.+- [Rose et al. (2003), CODEHOP](https://pubmed.ncbi.nlm.nih.gov/12824413/):+ protein-alignment-guided degenerate primers, DOI `10.1093/nar/gkg524`.+- [Li and Dahiya (2002), MethPrimer](https://pubmed.ncbi.nlm.nih.gov/12424112/):+ bisulfite-specific design constraints, DOI `10.1093/bioinformatics/18.11.1427`.+- [Tusnády et al. (2005), BiSearch](https://pubmed.ncbi.nlm.nih.gov/15653630/):+ converted-reference mispriming analysis, DOI `10.1093/nar/gni012`.++## When maintaining this skill++Check upstream parameter names, supported alphabets/lengths, concentrations, output+coordinates, and returned warnings before changing package pins. Re-run the+repository suite and documented examples. Test off-target products and negative+cases, not only whether a program returns primers. Preserve the distinction between+locally tested numerical behavior, external service documentation, and empirical+assay validation. A newer package or web interface does not justify upgrading old+assay claims without rerunning their evidence.diff --git a/skills/primer-design/references/specificity.md b/skills/primer-design/references/specificity.mdnew file mode 100644index 00000000..047aba5b--- /dev/null+++ b/skills/primer-design/references/specificity.md@@ -0,0 +1,165 @@+# Reference specificity and amplicon geometry++Documentation checked: 2026-09-30. Specificity is a claim about named sequences,+search settings, and assay conditions. A favorable thermodynamic score or a clean+search of an incomplete reference does not establish a unique biological product.++## Select the reference universe++Create a manifest before screening. Include reference source, accession/version or+assembly release, annotation release if relevant, date retrieved, checksums, record+IDs, lengths, topology, and which intended/expected background molecules it covers.++| Assay | References to consider |+| --- | --- |+| Genomic locus | Appropriate assembly; alternate/unplaced sequences and relevant haplotypes when required |+| Transcript assay | Intended and excluded isoforms; related genes/pseudogenes; genomic DNA as a separate check |+| Plasmid or cloning | Complete construct, parental vector, inserts, and plausible host background |+| Family-wide detection | Explicit intended sequence collection and near-neighbor negatives |+| Mixed sample | Target plus likely host and other background relevant to interpretation |++Document omitted components. Do not silently reduce a reference to the design+window to make screening faster. Preserve distinct sequence identifiers; duplicated+records and multiple genomic loci are different issues. Several loci with the same+amplicon sequence remain several loci.++## What the bundled local methods establish++`screen_specificity.py` supports two local search strategies. Their guarantees are+different; retain the method and all settings in the report.++- **Exhaustive ungapped search:** evaluate complete primer-length windows on both+ strands under the configured total and 3′ mismatch rules. Completeness is only+ for the supplied reference, implemented geometry, and bounded mismatch model.+ Insertions/deletions, longer permissible products, absent haplotypes, and unknown+ bases cannot be dismissed from biological consideration.+- **BLAST discovery with full-length verification:** use short-query alignment to+ locate candidate binding windows, then verify the full primer sequence at those+ windows. This avoids treating a short favorable local alignment as a complete+ primer match. BLAST remains a heuristic: realignment cannot recover sites that+ discovery never returned.++Inspect the script's current options and emitted limitations for size, hit, and+product caps and for supported topology. A cap reached during screening means the+analysis is incomplete. Missing expected amplification, unsupported input, or+truncated enumeration is not a specificity pass.++The exhaustive method is useful for constructs and bounded references. For large+genomes, use scalable search or Primer-BLAST, retain limitations, and avoid treating+the Python scanner as a whole-genome performance guarantee.++## Binding orientation and coordinates++Store oligos in **synthesized 5′→3′ orientation**. Relative to the supplied reference:++- A primer equal to the plus-strand window has a plus-direction binding hit and+ extends toward increasing reference coordinates.+- A primer equal to the reverse complement of that window has a minus-direction+ hit and extends toward decreasing reference coordinates.++“Forward” and “reverse” are design labels; either oligo can find hits in either+orientation elsewhere. For linear reference intervals, a plus-direction binding+site upstream and a minus-direction site downstream may form an inward-facing+product. The product extends from the upstream primer's outer 5′ boundary to the+downstream primer's outer 5′ boundary and includes both primers.++Enumerate the two-oligo reaction's **F/R, F/F, and R/R** possibilities, not just the+intended F/R orientation. For multiplex reactions, additionally evaluate+cross-assay pairs. Primer-BLAST checks same-primer as well as mixed-primer products;+this avoids overlooking inverted-repeat products.+[Primer-BLAST publication](https://pmc.ncbi.nlm.nih.gov/articles/PMC3412702/).++The bundled specificity CLI's `--multiplex` mode generates all cross-pair oligo+combinations under a declared cap and preserves their source identities. All+cross-pair products are classified as unintended in that mode. Assess intentional+shared-primer designs using explicit standalone combinations and expected intervals.++For circular templates, wrapped products cross coordinate zero. Use an explicitly+supported circular search and a documented maximum product length; preserve+original record length and wrapped coordinates. Doubling a reference without+deduplication and length constraints can create misleading duplicate or+multi-circumference products. Linear screening cannot clear origin-spanning risk.++## Expected versus unintended products++Supply intended **record and coordinate intervals**, not just a record-name+allowlist. A chromosome can contain the intended site and many unintended sites.+If several loci or isoforms are acceptable, list each explicitly with its rationale.++Classify every predicted product against that specification. Report binding+coordinates, primer identities, product length, total mismatches, and mismatch+positions counted from the synthesized primer's 3′ end. Review expected products+that are missing or mismatched separately from additional products.++For a whole-reference reverse-complement transformation, `[start, end)` becomes+`[L-end, L-start)` and the direction flips. This simple identity is useful for+testing coordinate handling. An oligo's last base is its 3′ end on either strand;+using the genomic window's last base unconditionally is wrong.++## Interpreting mismatch settings++A mismatch budget is a screening model, not a polymerase law. Mismatch identity,+position, reaction conditions, and template abundance affect whether amplification+occurs. Review especially plausible competing products even if they lie just+outside a chosen bound. Compare total mismatch counts with the positions near each+primer's 3′ end; do not summarize both as a single identity percentage.++Use a stricter discovery model only when justified by the assay. Raising required+3′ mismatches or decreasing a total-mismatch budget may reduce predicted products+by definition; it does not improve the oligo. Keep settings constant when ranking+candidates, or report the difference clearly.++Ambiguous reference bases represent unknown or multiple possibilities. A sequence+containing `N` should not be treated as strong evidence of an impossible binding+site. Retain ambiguity warnings or resolve the sequence. Indel-containing primer+alignments require an appropriate alignment method beyond a substitution-only+screen.++## NCBI Primer-BLAST review workflow++Use the [official interface](https://www.ncbi.nlm.nih.gov/tools/primer-blast/) to+review candidate primers when public-reference searching is appropriate.++1. Supply a versioned target record where available and both predesigned primers+ in synthesized orientation. Specify the intended organism and suitable database.+2. Set the maximum searched product length based on plausible competing products,+ not merely the desired product range.+3. Review specificity stringency, short-query sensitivity, and result/search caps.+ Save the actual settings rather than assuming current web defaults.+4. Review intended-target assignments and similar sequence matches manually. Do+ not accept an off-target solely because its description shares a gene symbol.+5. Save the complete report, retrieval date, database description, settings, and+ result interpretation. A transient job URL is insufficient provenance.++NCBI distinguishes the cap on database sequences searched from output display+limits. Larger searches may reveal additional products. Exact reference accessions+help distinguish intended targets from redundant records.+[NCBI search tips](https://www.ncbi.nlm.nih.gov/tools/primer-blast/search_tips.html).++Do not invent a supported Primer-BLAST API or substitute the general BLAST URL API+for its pair-specific workflow. Any remote submission sends the submitted sequence+to that service; use a local reference workflow when sequences must stay local.++## Local BLAST review++The BLAST+ `blastn-short` task is optimized for short nucleotide queries; its+documented word size is seven. Query masking, scoring, E-value, subject/result+limits, and database composition affect retrieval. Record them alongside the+executable version and database metadata.+[BLAST+ options](https://www.ncbi.nlm.nih.gov/sites/books/NBK279684/table/appendices.T.blastn_application_options/).++For each discovery hit, retain the query ID, subject ID, orientation, query and+subject alignment endpoints, gaps, and aligned strings or an equivalent trace.+Recover the full-length window in the subject and check its complete alignment,+including the 3′ end. Pair verified hits using reference geometry. A BLAST table of+high-scoring single-primer matches is not an amplicon report.++Separate these statements in the final interpretation:++- No unintended products were **found** by this search.+- The search completed **within its declared model and caps**.+- The supplied references represent the required biological background.+- Wet-lab evidence supports specificity **under tested conditions**.++Only make the statements for which evidence exists. Even all four together apply+to the stated assay and sample universe, not every possible biological sequence.diff --git a/skills/primer-design/references/thermodynamics.md b/skills/primer-design/references/thermodynamics.mdnew file mode 100644index 00000000..b6298f28--- /dev/null+++ b/skills/primer-design/references/thermodynamics.md@@ -0,0 +1,105 @@+# Thermodynamic calculations and interpretation++Documentation checked: 2026-09-30 against primer3-py 2.3.1 documentation.+Use the version recorded by the actual run to describe tested behavior.++## Record the physical assumptions++Nearest-neighbor predictions use sequence context and specified solution+conditions. They do not make an oligo's Tm an invariant property. The unified DNA+parameter framework is described by+[SantaLucia (1998)](https://pubmed.ncbi.nlm.nih.gov/9465037/); mixed monovalent and+magnesium effects require appropriate correction, as studied by+[Owczarzy et al. (2008)](https://pubmed.ncbi.nlm.nih.gov/18422348/).++| Input | primer3-py unit | Reporting requirement |+| --- | --- | --- |+| Monovalent cations (`mv_conc`) | mM | State measured, manufacturer-supplied, or assumed value |+| Divalent cations (`dv_conc`) | mM | Record the supplied magnesium/cation value |+| dNTPs (`dntp_conc`) | mM | State concentration convention; avoid silently mixing total and per-nucleotide amounts |+| Oligo concentration (`dna_conc`) | nM | Use the model's concentration convention consistently |+| Free-energy evaluation (`temp_c`) | °C | Store with every ΔG comparison |+| DMSO, when modeled | percent | Tm correction is not a complete reaction model |+| Formamide, when modeled | mol/L | Do not enter a percentage as molarity |++These parameter units are documented in the+[primer3-py quickstart](https://libnano.github.io/primer3-py/quickstart.html).+For proprietary mixes with undisclosed composition, label chosen values as+assumptions and compare plausible conditions if necessary. Never back-fill exact+chemistry from the name of a kit.++## Calculate several distinct quantities++Use the snake_case APIs: `calc_tm`, `calc_hairpin`, `calc_homodimer`,+`calc_heterodimer`, and `calc_end_stability`. The end-stability calculation is+directional; examine both oligo orders when either primer's 3′ end matters.+Do not reverse-complement an oligo before passing synthesized sequences to the+structure routines. [API definitions](https://libnano.github.io/primer3-py/api/bindings.html).++For each oligo record its annealing-core Tm, GC fraction, and length, then review+hairpin and self-dimer results for the full ordered sequence. For each interacting+pair record heterodimer and both directional 3′-end assessments. Preserve predicted+structure alignments when available so the location of terminal complementarity+can be inspected.++`ThermoResult.dg` and `.dh` use **cal/mol**; `.ds` uses **cal/(mol·K)**; `.tm` uses+°C. Divide energy by 1000 before displaying kcal/mol. Store `structure_found`:+missing structures and zero-valued fields are not interchangeable evidence.+[ThermoResult documentation](https://libnano.github.io/primer3-py/api/thermoanalysis.html).++## Keep screening thresholds in context++- A low difference between primer Tm values supports compatible conditions but says+ nothing about reference specificity or amplification efficiency.+- A predicted favorable dimer ΔG does not by itself show that the polymerase can+ extend that alignment. Inspect 3′ placement as well as thermodynamic stability.+- Compare energies only at matched temperatures, concentrations, and model settings.+ Comparing one program's default ΔG with another's numeric cutoff is unreliable.+- A candidate close to a chosen limit deserves sensitivity analysis, not unwarranted+ numerical precision. Report useful decimals while retaining raw output.++Thresholds are selection criteria chosen for a particular assay. They are not+universal scientific pass/fail constants. Retain the assumptions, threshold+definition, observed value, and reason for any override.++Predicted Tm is not an automatic annealing temperature. Follow the selected+polymerase's current instructions and validate an appropriate condition range.+Even manufacturer protocols differ; for example, NEB's+[Taq guidance](https://www.neb.com/en/protocols/taq-5x-master-mix-pcr-guidelines?pdf=true)+and [Phusion Flash guidance](https://www.neb.com/en/protocols/guidelines-for-pcr-optimization-with-phusion-flash-high-fidelity-pcr-master-mix?pdf=true)+use different temperature recommendations.++## Model and implementation boundaries++The documented `calc_tm` nearest-neighbor path applies up to its configured length+limit, normally 60 bases; longer sequences switch to an approximation. Structure+routines also have length limits. The bundled checker constrains ordinary oligos+instead of silently using unsupported long-tail calculations. Check runtime errors+and emitted limits rather than inferring successful analysis from a partial table.+[primer3-py API](https://libnano.github.io/primer3-py/api/bindings.html).++Do not substitute ambiguity symbols, RNA, inosine, or modified bases into an ACGT+DNA model and call the result validated. Modified chemistries require appropriate+parameters; for example, LNA substitutions affect both stability and+sequence-dependent mismatch discrimination.+[LNA thermodynamics study](https://pubmed.ncbi.nlm.nih.gov/21928795/).++For tailed primers, model the core's initial template interaction separately from+full-oligo structures. For degenerate mixtures, a single “consensus Tm” hides the+different species and effective concentrations. For multiplex panels, include+cross-pair interactions and disclose any capped enumeration.++## Reproducibility and implementation checks++Record Python, primer3-py, and underlying libprimer3 versions, full sequence inputs,+all chemistry/model settings, warnings, and raw results. Test that:++1. Tm changes appropriately when chemistry inputs change; values were not replaced+ by a fixed rule based only on GC count.+2. Displayed energy units match raw values and conversions.+3. Swapping oligos preserves symmetric dimer comparisons while directional end+ results retain their correct orientation.+4. An invalid or unsupported sequence is reported as unassessed, never silently+ shortened, stripped of modifications, or replaced with an arbitrary base.+5. Tails are included in full-oligo interaction analysis and excluded from the+ initial binding-core Tm and ordinary reference search.diff --git a/skills/primer-design/scripts/_common.py b/skills/primer-design/scripts/_common.pynew file mode 100644index 00000000..9e4d28d1--- /dev/null+++ b/skills/primer-design/scripts/_common.py@@ -0,0 +1,134 @@+"""Validated local inputs and provenance shared by primer-design tools."""+from __future__ import annotations++import csv+import hashlib+import json+import math+import os+import re+import tempfile+from pathlib import Path++IUPAC = "ACGTRYSWKMBDHVN"+PAIR_FIELDS = ("pair_id", "forward", "reverse", "forward_tail", "reverse_tail")+++def dna(value: str, label: str, *, ambiguous: bool = False, empty: bool = False) -> str:+ if not isinstance(value, str):+ raise ValueError(f"{label}: sequence must be a string")+ seq = value.strip().upper()+ if (not seq and not empty) or any(c not in (IUPAC if ambiguous else "ACGT") for c in seq):+ raise ValueError(f"{label}: expected {'IUPAC' if ambiguous else 'ACGT'} DNA, 5-prime to 3-prime, without internal whitespace")+ return seq+++def revcomp(seq: str) -> str:+ return seq.translate(str.maketrans(IUPAC, "TGCAYRSWMKVHDBN"))[::-1]+++def read_fasta(path) -> dict[str, str]:+ records, chunks, current = {}, [], None+ with Path(path).open(encoding="utf-8-sig") as handle:+ for number, raw in enumerate(handle, 1):+ line = raw.strip()+ if not line:+ continue+ if line.startswith(">"):+ if current is not None:+ records[current] = dna("".join(chunks), current, ambiguous=True)+ current = line[1:].split()[0] if line[1:].split() else ""+ if not current or current in records:+ raise ValueError(f"FASTA line {number}: empty or duplicate record ID")+ chunks = []+ else:+ if current is None:+ raise ValueError(f"FASTA line {number}: sequence before header")+ chunks.append(line)+ if current is not None:+ records[current] = dna("".join(chunks), current, ambiguous=True)+ if not records:+ raise ValueError("FASTA contains no records")+ return records+++def read_pairs(path) -> list[dict[str, str]]:+ with Path(path).open(newline="", encoding="utf-8-sig") as handle:+ reader = csv.DictReader(handle, delimiter="\t")+ header = reader.fieldnames or []+ if len(set(header)) != len(header) or not {"pair_id", "forward", "reverse"} <= set(header):+ raise ValueError("Pair TSV needs unique columns pair_id, forward, reverse; optional forward_tail, reverse_tail")+ if set(header) - set(PAIR_FIELDS):+ raise ValueError(f"Unknown pair TSV columns: {sorted(set(header) - set(PAIR_FIELDS))}")+ result, seen = [], set()+ for number, row in enumerate(reader, 2):+ if None in row or any(v is None for v in row.values()):+ raise ValueError(f"Pair TSV line {number}: wrong column count")+ pair_id = row["pair_id"].strip()+ if not re.fullmatch(r"[A-Za-z0-9_.-]+", pair_id) or pair_id in seen:+ raise ValueError(f"Pair TSV line {number}: duplicate or invalid pair_id")+ seen.add(pair_id)+ result.append({"pair_id": pair_id, **{+ field: dna(row.get(field, ""), f"{pair_id}.{field}", empty=field.endswith("_tail"))+ for field in PAIR_FIELDS[1:]+ }})+ if not result:+ raise ValueError("Pair TSV contains no primer pairs")+ return result+++def sha256_file(path) -> str:+ digest = hashlib.sha256()+ with Path(path).open("rb") as handle:+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):+ digest.update(chunk)+ return digest.hexdigest()+++def check_output_paths(inputs, outputs):+ sources = {Path(p).resolve() for p in inputs if p is not None}+ destinations = [Path(p).resolve() for p in outputs if p is not None]+ if len(set(destinations)) != len(destinations) or sources.intersection(destinations):+ raise ValueError("Output paths must be distinct from each other and all inputs")+ paths = list(sources) + destinations+ for index, path in enumerate(paths):+ if path.exists():+ for other in paths[index + 1:]:+ if other.exists() and path.samefile(other):+ raise ValueError("Output paths must not be hardlink aliases of inputs or other outputs")+++def write_json(path, data):+ """Replace a complete JSON document atomically, never serialize NaN/Infinity."""+ destination = Path(path)+ serialized = json.dumps(data, indent=2, allow_nan=False) + "\n"+ destination.parent.mkdir(parents=True, exist_ok=True)+ with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=destination.parent, delete=False) as handle:+ temporary = Path(handle.name)+ handle.write(serialized)+ try:+ os.replace(temporary, destination)+ finally:+ temporary.unlink(missing_ok=True)+++def load_primer3():+ try:+ import primer3+ except ImportError as exc:+ raise ValueError("primer3-py is not installed; install primer3-py==2.3.1 in an isolated environment") from exc+ return primer3+++def finite_number(value, name, minimum=0, *, positive=False):+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):+ raise ValueError(f"{name} must be a finite number")+ if value < minimum or (positive and value == minimum):+ raise ValueError(f"{name} must be {'greater than' if positive else 'at least'} {minimum}")+ return value+++def integer(value, name, minimum=0):+ if isinstance(value, bool) or not isinstance(value, int) or value < minimum:+ raise ValueError(f"{name} must be an integer >= {minimum}")+ return valuediff --git a/skills/primer-design/scripts/_specificity.py b/skills/primer-design/scripts/_specificity.pynew file mode 100644index 00000000..aad88673--- /dev/null+++ b/skills/primer-design/scripts/_specificity.py@@ -0,0 +1,395 @@+"""Bounded, ungapped primer binding and inward-facing amplicon enumeration.++Coordinates are zero-based, half-open on the reference's forward strand.+For circular records, start is canonical and end may exceed the record length.+Neither this mismatch model nor BLAST models PCR chemistry or proves specificity.+"""++from __future__ import annotations++import csv+import hashlib+import shutil+import subprocess+import tempfile+from collections import Counter, defaultdict+from itertools import combinations+from pathlib import Path++from _common import revcomp+++IUPAC = {+ "A": "A", "C": "C", "G": "G", "T": "T", "R": "AG", "Y": "CT",+ "S": "GC", "W": "AT", "K": "GT", "M": "AC", "B": "CGT", "D": "AGT",+ "H": "ACT", "V": "ACG", "N": "ACGT",+}+++class SearchIncomplete(ValueError):+ """The requested screen cannot support a completed-search result."""+++def source_oligos(pair):+ """Retain the physical oligo identity behind each local F/R role."""+ return pair.get("source_oligos") or {+ role: {+ "oligo_id": f"{pair['pair_id']}:{role}", "pair_id": pair["pair_id"],+ "primer_role": role, "annealing_sequence": pair[key],+ "tail_5prime": pair.get(key + "_tail", ""),+ }+ for role, key in (("F", "forward"), ("R", "reverse"))+ }+++def expand_panel_pairs(pairs, max_combinations):+ """Add all cross-pair oligo combinations without mutating original pairs."""+ count = 2 * len(pairs) * (len(pairs) - 1)+ if count > max_combinations:+ raise SearchIncomplete(+ f"Multiplex requires {count:,} cross-oligo combinations; cap is {max_combinations:,}. "+ "No panel expansion or truncated screen was accepted."+ )+ prefix = "multiplex-cross-"+ while any(pair["pair_id"].startswith(prefix) for pair in pairs):+ prefix = "_" + prefix+ generated = []+ for first, second in combinations(sorted(pairs, key=lambda pair: pair["pair_id"]), 2):+ for first_role in ("F", "R"):+ for second_role in ("F", "R"):+ first_oligo, second_oligo = source_oligos(first)[first_role], source_oligos(second)[second_role]+ generated.append({+ "pair_id": f"{prefix}{len(generated) + 1:06d}",+ "forward": first_oligo["annealing_sequence"],+ "reverse": second_oligo["annealing_sequence"],+ "forward_tail": first_oligo["tail_5prime"],+ "reverse_tail": second_oligo["tail_5prime"],+ "cross_pair": True, "source_oligos": {"F": first_oligo, "R": second_oligo},+ })+ return list(pairs) + generated+++def read_expected(path, pairs, references, circular):+ """Read exact intended product intervals; reject unverifiable identifiers."""+ result = {pair["pair_id"]: [] for pair in pairs}+ if path is None:+ return result+ with Path(path).open(newline="", encoding="utf-8-sig") as handle:+ reader = csv.DictReader(handle, delimiter="\t")+ required = {"pair_id", "record_id", "start", "end"}+ header = reader.fieldnames or []+ if set(header) != required or len(header) != len(required):+ raise ValueError("Expected-target TSV requires exactly pair_id, record_id, start, end")+ for line, row in enumerate(reader, 2):+ if None in row or any(value is None for value in row.values()):+ raise ValueError(f"Wrong expected-target column count, line {line}")+ pair_id, record_id = row["pair_id"], row["record_id"]+ if pair_id not in result or record_id not in references:+ raise ValueError(f"Unknown pair_id or record_id in expected targets, line {line}")+ try:+ start, end = int(row["start"]), int(row["end"])+ except (ValueError, TypeError) as exc:+ raise ValueError(f"Non-integer expected coordinates, line {line}") from exc+ length = len(references[record_id])+ if not (0 <= start < length and start < end):+ raise ValueError(f"Invalid expected interval, line {line}")+ if end > (start + length if record_id in circular else length):+ raise ValueError(f"Expected interval exceeds molecule, line {line}")+ interval = {"record_id": record_id, "start": start, "end": end}+ if interval in result[pair_id]:+ raise ValueError(f"Duplicate expected interval, line {line}")+ result[pair_id].append(interval)+ return result+++def reference_window(sequence, start, length, circular=False):+ if circular:+ if length > len(sequence):+ return None+ start %= len(sequence)+ end = start + length+ return sequence[start:end] if end <= len(sequence) else sequence[start:] + sequence[:end - len(sequence)]+ if start < 0 or start + length > len(sequence):+ return None+ return sequence[start:start + length]+++def score_window(primer, window, strand, settings):+ """Conservative mismatch lower bounds; ambiguity never certifies a base."""+ oriented = window if strand == "+" else revcomp(window)+ mismatches, ambiguous = [], []+ for index, (base, reference_base) in enumerate(zip(primer, oriented), 1):+ if reference_base not in "ACGT":+ ambiguous.append(index)+ if base not in IUPAC[reference_base]:+ mismatches.append(index)+ boundary = len(primer) - settings["three_prime_bases"]+ terminal = [index for index in mismatches if index > boundary]+ if (len(mismatches) > settings["max_mismatches"] or+ len(terminal) > settings["max_three_prime_mismatches"]):+ return None+ possible = sorted(set(mismatches) | set(ambiguous))+ return {+ "mismatches": len(mismatches),+ "mismatch_positions_1based": mismatches,+ "mismatch_positions_from_five_prime_1based": mismatches,+ "mismatch_positions_from_three_prime_1based": sorted(len(primer) - i + 1 for i in mismatches),+ "three_prime_mismatches": len(terminal),+ "three_prime_mismatch_positions_1based": terminal,+ "three_prime_mismatch_positions_from_three_prime_1based": sorted(len(primer) - i + 1 for i in terminal),+ "mismatches_upper_bound": len(possible),+ "three_prime_mismatches_upper_bound": sum(i > boundary for i in possible),+ "ambiguous_positions_1based": ambiguous,+ "ambiguous_positions_from_five_prime_1based": ambiguous,+ "ambiguous_positions_from_three_prime_1based": sorted(len(primer) - i + 1 for i in ambiguous),+ "unresolved_ambiguity": bool(ambiguous),+ }+++def make_hit(primer, record_id, sequence, start, strand, circular, settings):+ window = reference_window(sequence, start, len(primer), circular)+ if window is None:+ return None+ score = score_window(primer, window, strand, settings)+ if score is None:+ return None+ start = start % len(sequence) if circular else start+ return {+ "record_id": record_id, "start": start, "end": start + len(primer),+ "strand": strand, "wraps_origin": start + len(primer) > len(sequence),+ **score,+ }+++def exhaustive_hits(primers, references, circular, settings):+ """Search every full-length window on both strands within declared bounds."""+ comparisons = sum(+ (len(seq) if record in circular and len(primer) <= len(seq)+ else max(0, len(seq) - len(primer) + 1)) * len(primer) * 2+ for primer in primers for record, seq in references.items()+ )+ if comparisons > settings["max_comparisons"]:+ raise SearchIncomplete(+ f"Exhaustive search requires at most {comparisons:,} base comparisons; "+ f"cap is {settings['max_comparisons']:,}. Increase deliberately or use "+ "the explicitly heuristic BLAST engine. No truncated screen was accepted."+ )+ result = {primer: [] for primer in primers}+ total = 0+ for primer in primers:+ for record, sequence in references.items():+ is_circular = record in circular+ windows = len(sequence) if is_circular else len(sequence) - len(primer) + 1+ if len(primer) > len(sequence):+ continue+ for strand in ("+", "-"):+ for start in range(windows):+ hit = make_hit(primer, record, sequence, start, strand, is_circular, settings)+ if hit is not None:+ total += 1+ if total > settings["max_hits"]:+ raise SearchIncomplete("Binding-hit cap exceeded; screen discarded, not truncated")+ result[primer].append(hit)+ return result, {"base_comparisons_upper_bound": comparisons, "tools": {}}, []+++def run_tool(command, timeout):+ try:+ completed = subprocess.run(+ command, check=True, capture_output=True, text=True, timeout=timeout,+ )+ except subprocess.TimeoutExpired as exc:+ raise SearchIncomplete(f"{Path(command[0]).name} timed out after {timeout}s") from exc+ except subprocess.CalledProcessError as exc:+ raise SearchIncomplete(+ f"{Path(command[0]).name} failed (exit {exc.returncode}): {exc.stderr[-2000:]}"+ ) from exc+ except OSError as exc:+ raise SearchIncomplete(f"Cannot execute {Path(command[0]).name}: {exc}") from exc+ return completed.stdout.strip()+++def blast_hits(primers, references, circular, settings):+ """Use BLAST for candidate discovery, then recheck entire ungapped primers.++ Discovery is heuristic even with unsaturated reporting limits. Both ends of+ clipped HSPs are restored before mismatch counting on the original FASTA.+ Synthetic database IDs prevent pipe/accession conventions from changing IDs.+ """+ if any(len(primer) < 7 for primer in primers):+ raise SearchIncomplete("BLAST's configured 7-base seed requires annealing cores of at least 7 bases")+ program_paths = {}+ for name in ("blastn", "makeblastdb"):+ executable = shutil.which(settings[name])+ if not executable:+ raise SearchIncomplete(f"{name} executable not found: {settings[name]}")+ program_paths[name] = executable+ timeout = settings["blast_timeout"]+ tools = {name: {"executable": path, "version": run_tool([path, "-version"], timeout)}+ for name, path in program_paths.items()}+ primer_map = {f"q{i}": primer for i, primer in enumerate(primers)}+ record_map = {f"r{i}": record for i, record in enumerate(references)}+ hits = {primer: [] for primer in primers}+ seen, target_counts, hsp_counts = set(), defaultdict(set), Counter()+ total_hits, rows, comparisons = 0, 0, 0+ max_length = max(map(len, primers))+ with tempfile.TemporaryDirectory(prefix="primer-specificity-") as temporary:+ temporary = Path(temporary)+ database_fasta, query_fasta = temporary / "reference.fa", temporary / "queries.fa"+ database_path, output = temporary / "reference_db", temporary / "hits.tsv"+ with database_fasta.open("w", encoding="utf-8") as handle:+ for synthetic, record in record_map.items():+ sequence = references[record]+ if record in circular:+ sequence += sequence[:max_length - 1]+ handle.write(f">{synthetic}\n{sequence}\n")+ with query_fasta.open("w", encoding="utf-8") as handle:+ for query, primer in primer_map.items():+ handle.write(f">{query}\n{primer}\n")+ make_command = [program_paths["makeblastdb"], "-in", str(database_fasta), "-dbtype", "nucl",+ "-out", str(database_path), "-parse_seqids"]+ blast_command = [+ program_paths["blastn"], "-task", "blastn-short", "-query", str(query_fasta),+ "-db", str(database_path), "-out", str(output), "-strand", "both", "-ungapped",+ "-dust", "no", "-soft_masking", "false", "-word_size", "7", "-evalue", "1000",+ "-max_target_seqs", str(settings["blast_max_target_seqs"]),+ "-max_hsps", str(settings["blast_max_hsps"]),+ "-outfmt", "6 qseqid sseqid qstart qend sstart send gaps",+ ]+ run_tool(make_command, timeout)+ run_tool(blast_command, timeout)+ with output.open(encoding="utf-8") as handle:+ for line in handle:+ rows += 1+ if rows > settings["max_blast_rows"]:+ raise SearchIncomplete("BLAST output-row cap exceeded; screen discarded")+ fields = line.rstrip("\n").split("\t")+ if len(fields) != 7:+ raise SearchIncomplete("Unexpected BLAST output format")+ query, subject = fields[:2]+ # BLAST may decorate local identifiers when -parse_seqids is used.+ subject = subject.removeprefix("lcl|")+ if query not in primer_map or subject not in record_map:+ raise SearchIncomplete("Unrecognized BLAST query/reference identifier")+ qstart, qend, sstart, send, gaps = map(int, fields[2:])+ primer, record = primer_map[query], record_map[subject]+ if gaps or not 1 <= qstart <= qend <= len(primer):+ raise SearchIncomplete("Unsupported gapped/reversed-query BLAST alignment")+ target_counts[query].add(subject)+ hsp_counts[query, subject] += 1+ strand = "+" if send >= sstart else "-"+ start = sstart - qstart if strand == "+" else sstart + qstart - 1 - len(primer)+ if record in circular:+ start %= len(references[record])+ key = (primer, record, start, strand)+ if key in seen:+ continue+ seen.add(key)+ comparisons += len(primer)+ if comparisons > settings["max_comparisons"]:+ raise SearchIncomplete("BLAST candidate realignment comparison cap exceeded")+ hit = make_hit(primer, record, references[record], start, strand,+ record in circular, settings)+ if hit is not None:+ total_hits += 1+ if total_hits > settings["max_hits"]:+ raise SearchIncomplete("Binding-hit cap exceeded; screen discarded")+ hits[primer].append(hit)+ issues = []+ if any(len(records) >= settings["blast_max_target_seqs"] and+ len(records) < len(references) for records in target_counts.values()):+ issues.append("BLAST max_target_seqs reporting limit reached; targets may be omitted")+ if any(count >= settings["blast_max_hsps"] for count in hsp_counts.values()):+ issues.append("BLAST max_hsps reporting limit reached; binding sites may be omitted")+ provenance = {+ "tools": tools, "commands": [make_command, blast_command],+ "blast_rows": rows, "candidate_intervals": len(seen),+ "realignment_base_comparisons": comparisons,+ }+ return hits, provenance, issues+++def enumerate_products(pair, hits_by_sequence, references, circular, settings, expected):+ cross_pair = pair.get("cross_pair", False)+ sources = source_oligos(pair)+ hits = []+ for role, key in (("F", "forward"), ("R", "reverse")):+ for hit in sorted(hits_by_sequence[pair[key]],+ key=lambda h: (h["record_id"], h["start"], h["strand"])):+ hits.append({+ **hit, "primer_role": role, "hit_id": f"{pair['pair_id']}:h{len(hits) + 1}",+ "source_oligo_id": sources[role]["oligo_id"],+ "source_pair_id": sources[role]["pair_id"],+ "source_primer_role": sources[role]["primer_role"],+ })+ by_record = defaultdict(lambda: {"+": [], "-": []})+ for hit in hits:+ by_record[hit["record_id"]][hit["strand"]].append(hit)+ combinations = sum(len(group["+"]) * len(group["-"]) for group in by_record.values())+ if combinations > settings["max_product_combinations"]:+ raise SearchIncomplete(f"Pair {pair['pair_id']}: product-combination cap exceeded")+ products = []+ intended_coordinates = {(item["record_id"], item["start"], item["end"]) for item in expected}+ found_expected = set()+ for record, strands in by_record.items():+ sequence = references[record]+ for plus in strands["+"]:+ for minus in strands["-"]:+ if cross_pair and plus["primer_role"] == minus["primer_role"]:+ continue # Single-source-oligo products are already enumerated under its original pair.+ minus_start, end = minus["start"], minus["end"]+ if record in circular and minus_start < plus["end"]:+ minus_start += len(sequence)+ end += len(sequence)+ if minus_start < plus["end"]:+ continue # Overlapping primer sites are not accepted as PCR products.+ length = end - plus["start"]+ if record in circular and length > len(sequence):+ continue+ if not settings["min_product"] <= length <= settings["max_product"]:+ continue+ kind = plus["primer_role"] + "/" + minus["primer_role"]+ coordinates = (record, plus["start"], end)+ intended = not cross_pair and coordinates in intended_coordinates and kind in ("F/R", "R/F")+ if intended:+ found_expected.add(coordinates)+ classification = "intended" if intended else ("potential_off_target" if expected or cross_pair else "unclassified")+ tails = {"F": pair.get("forward_tail", ""), "R": pair.get("reverse_tail", "")}+ product_sequence = reference_window(sequence, plus["start"], length, record in circular)+ products.append({+ "product_id": f"{pair['pair_id']}:p{len(products) + 1}",+ "record_id": record, "start": plus["start"], "end": end,+ "length": length, "wraps_origin": end > len(sequence),+ "primer_roles": kind, "left_hit_id": plus["hit_id"], "right_hit_id": minus["hit_id"],+ "left_source_oligo_id": plus["source_oligo_id"], "right_source_oligo_id": minus["source_oligo_id"],+ "source_primer_roles": plus["source_primer_role"] + "/" + minus["source_primer_role"],+ "cross_pair": cross_pair,+ "classification": classification,+ "length_with_tails": length + len(tails[plus["primer_role"]]) + len(tails[minus["primer_role"]]),+ "reference_product_sha256": hashlib.sha256(product_sequence.encode("ascii")).hexdigest(),+ "unresolved_ambiguity": plus["unresolved_ambiguity"] or minus["unresolved_ambiguity"],+ })+ if len(products) > settings["max_products"]:+ raise SearchIncomplete(f"Pair {pair['pair_id']}: product cap exceeded; screen discarded")+ missing = [item for item in expected if (item["record_id"], item["start"], item["end"]) not in found_expected]+ if cross_pair:+ status = "potential_off_target" if products else "no_off_target_found_within_search_scope"+ elif not expected:+ status = "no_expected_target"+ elif missing:+ status = "intended_target_not_found"+ elif any(item["classification"] == "potential_off_target" for item in products):+ status = "potential_off_target"+ else:+ status = "no_off_target_found_within_search_scope"+ unresolved = any(h["unresolved_ambiguity"] for h in hits)+ return {+ "pair_id": pair["pair_id"], "status": status,+ "cross_pair": cross_pair, "source_oligos": sources,+ "hit_count": len(hits), "product_count": len(products), "hits": hits,+ "products": products, "expected": expected, "missing_expected": missing,+ "potential_off_target_count": sum(p["classification"] == "potential_off_target" for p in products),+ "unresolved_ambiguity": unresolved,+ "product_combinations_checked": combinations,+ **({"status_before_incomplete": status, "status": "incomplete"} if unresolved else {}),+ }diff --git a/skills/primer-design/scripts/check_thermodynamics.py b/skills/primer-design/scripts/check_thermodynamics.pynew file mode 100644index 00000000..09d3f1d2--- /dev/null+++ b/skills/primer-design/scripts/check_thermodynamics.py@@ -0,0 +1,133 @@+#!/usr/bin/env python3+"""Assess annealing cores and full tailed oligos using explicit solution chemistry."""+from __future__ import annotations++import argparse+import itertools+import math+import sys+from pathlib import Path++sys.dont_write_bytecode = True+from _common import check_output_paths, finite_number, load_primer3, read_pairs, sha256_file, write_json+++def structure(result):+ values = [result.tm, result.dg, result.dh, result.ds]+ if any(not math.isfinite(v) for v in values):+ raise ValueError("Thermodynamic engine returned nonfinite values")+ return {"structure_found": bool(result.structure_found), "tm_c": result.tm,+ "delta_g_kcal_per_mol": result.dg / 1000,+ "delta_h_kcal_per_mol": result.dh / 1000,+ "delta_s_cal_per_mol_k": result.ds,+ "ascii_structure": result.ascii_structure}+++def assess(args):+ pairs = read_pairs(args.pairs)+ p3 = load_primer3()+ chemistry = {key: finite_number(getattr(args, key), key, positive=(key == "dna_conc"))+ for key in ("mv_conc", "dv_conc", "dntp_conc", "dna_conc")}+ finite_number(args.temp_c, "temp_c", -20)+ if args.temp_c > 100:+ raise ValueError("temp_c must be between -20 and 100 Celsius")+ if args.max_interactions < 1:+ raise ValueError("max_interactions must be positive")+ count = 2 * len(pairs)+ interaction_count = count * (count - 1) // 2 if args.multiplex else len(pairs)+ if interaction_count > args.max_interactions:+ raise ValueError(f"{interaction_count} dimer comparisons exceed --max-interactions; partition deliberately or raise the limit")+ thermo_args = {**chemistry, "temp_c": args.temp_c}+ records, pair_summaries, warnings = [], [], []+ if chemistry["dntp_conc"] >= chemistry["dv_conc"] and chemistry["dv_conc"] > 0:+ warnings.append("Total dNTP is at least divalent concentration; verify the buffer/free-Mg assumptions used by the salt model.")+ for pair in pairs:+ entries = []+ for role in ("forward", "reverse"):+ core, tail = pair[role], pair[f"{role}_tail"]+ full = tail + core+ entry = {"oligo_id": f"{pair['pair_id']}:{role}", "pair_id": pair["pair_id"],+ "role": role, "annealing_core": core, "tail": tail,+ "order_sequence": full, "length": len(full), "core_length": len(core),+ "core_gc_percent": 100 * sum(c in "GC" for c in core) / len(core)}+ if not 2 <= len(core) <= 60:+ raise ValueError(f"{entry['oligo_id']}: core length must be 2..60 for this nearest-neighbor workflow")+ entry["annealing_tm_c"] = p3.calc_tm(core, **chemistry, tm_method=args.tm_method, salt_corrections_method=args.salt_corrections_method)+ if not math.isfinite(entry["annealing_tm_c"]):+ raise ValueError("Thermodynamic engine returned nonfinite core Tm")+ entry["core_hairpin"] = structure(p3.calc_hairpin(core, **thermo_args, output_structure=True))+ entry["core_homodimer"] = structure(p3.calc_homodimer(core, **thermo_args, output_structure=True))+ entry["core_self_three_prime"] = structure(p3.calc_end_stability(core, core, **thermo_args))+ if len(full) <= 60:+ entry["full_oligo_status"] = "computed"+ entry["full_hairpin"] = structure(p3.calc_hairpin(full, **thermo_args, output_structure=True))+ entry["full_homodimer"] = structure(p3.calc_homodimer(full, **thermo_args, output_structure=True))+ entry["full_self_three_prime"] = structure(p3.calc_end_stability(full, full, **thermo_args))+ else:+ entry["full_oligo_status"] = "unsupported_length"+ warnings.append(f"{entry['oligo_id']}: full oligo exceeds 60 nt; full-length secondary structure is unresolved, not truncated.")+ records.append(entry)+ entries.append(entry)+ pair_summaries.append({"pair_id": pair["pair_id"],+ "core_tm_difference_c": abs(entries[0]["annealing_tm_c"] - entries[1]["annealing_tm_c"])})+ comparisons = itertools.combinations(records, 2) if args.multiplex else ((records[i], records[i + 1]) for i in range(0, len(records), 2))+ interactions = []+ for a, b in comparisons:+ interaction = {"oligo_a": a["oligo_id"], "oligo_b": b["oligo_id"],+ "cross_pair": a["pair_id"] != b["pair_id"]}+ if max(a["length"], b["length"]) > 60:+ interaction["status"] = "unsupported_length"+ else:+ seq_a, seq_b = a["order_sequence"], b["order_sequence"]+ interaction.update(status="computed",+ heterodimer=structure(p3.calc_heterodimer(seq_a, seq_b, **thermo_args, output_structure=True)),+ a_three_prime_to_b=structure(p3.calc_end_stability(seq_a, seq_b, **thermo_args)),+ b_three_prime_to_a=structure(p3.calc_end_stability(seq_b, seq_a, **thermo_args)))+ interactions.append(interaction)+ complete = all(r["full_oligo_status"] == "computed" for r in records)+ report = {"schema_version": "1.0", "status": "computed" if complete else "incomplete",+ "provenance": {"pairs_file": str(args.pairs), "pairs_sha256": sha256_file(args.pairs),+ "primer3_py_version": p3.__version__,+ "libprimer3_version": p3.thermoanalysis.get_libprimer3_version(),+ "python_version": sys.version.split()[0]},+ "settings": {**chemistry, "temp_c": args.temp_c, "multiplex": args.multiplex,+ "tm_method": args.tm_method, "salt_corrections_method": args.salt_corrections_method,+ "secondary_structure_model": "libprimer3 thermodynamic alignment defaults",+ "max_interactions": args.max_interactions},+ "units": {"mv_conc": "mM monovalent cations", "dv_conc": "mM total divalent cations",+ "dntp_conc": "mM total dNTPs", "dna_conc": "nM oligonucleotide concentration under Primer3 conventions",+ "temp_c": "Celsius for delta-G; not annealing temperature selection"},+ "oligos": records, "pairs": pair_summaries, "interactions": interactions, "warnings": warnings,+ "limitations": ["Predictions do not establish PCR performance or a universal pass/fail cutoff.",+ "Core Tm excludes untemplated tails; secondary structures use complete ordered oligos.",+ "End-stability calculations are directional and are reported in both orders.",+ "Modified bases, degenerate mixtures, unequal multiplex concentrations, and oligos >60 nt require a suitable external model.",+ "Multiplex dimer checks do not screen cross-pair genomic amplification."]}+ write_json(args.output, report)+ return 0 if complete else 1+++def main(argv=None):+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--pairs", required=True, type=Path)+ parser.add_argument("--output", required=True, type=Path)+ parser.add_argument("--mv-conc", type=float, default=50.0, help="Monovalent cations, mM")+ parser.add_argument("--dv-conc", type=float, default=1.5, help="Total divalent cations, mM")+ parser.add_argument("--dntp-conc", type=float, default=0.6, help="Total dNTPs, mM (sum of all four)")+ parser.add_argument("--dna-conc", type=float, default=50.0, help="Oligonucleotide concentration, nM")+ parser.add_argument("--temp-c", type=float, default=37.0, help="Temperature at which delta-G is calculated")+ parser.add_argument("--tm-method", choices=("breslauer", "santalucia"), default="santalucia")+ parser.add_argument("--salt-corrections-method", choices=("schildkraut", "santalucia", "owczarzy"), default="santalucia")+ parser.add_argument("--multiplex", action="store_true", help="Check all unordered oligo combinations, including between pairs")+ parser.add_argument("--max-interactions", type=int, default=10000)+ args = parser.parse_args(argv)+ try:+ check_output_paths([args.pairs], [args.output])+ return assess(args)+ except (ValueError, OSError, RuntimeError, TypeError, OverflowError) as exc:+ print(f"error: {exc}", file=sys.stderr)+ return 2+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/primer-design/scripts/design_primers.py b/skills/primer-design/scripts/design_primers.pynew file mode 100644index 00000000..314f49de--- /dev/null+++ b/skills/primer-design/scripts/design_primers.py@@ -0,0 +1,262 @@+#!/usr/bin/env python3+"""Design paired PCR primers with Primer3 and export auditable coordinates."""+from __future__ import annotations++import argparse+import csv+import json+import sys+from pathlib import Path++sys.dont_write_bytecode = True+from _common import (PAIR_FIELDS, check_output_paths, dna, finite_number, integer,+ load_primer3, read_fasta, revcomp, sha256_file, write_json)++# A deliberately explicit supported interface prevents misspelled tags being+# silently ignored by Primer3. More advanced Primer3 tasks use its native API.+GLOBAL_KEYS = set("""+PRIMER_NUM_RETURN PRIMER_MIN_SIZE PRIMER_OPT_SIZE PRIMER_MAX_SIZE+PRIMER_MIN_TM PRIMER_OPT_TM PRIMER_MAX_TM PRIMER_PAIR_MAX_DIFF_TM+PRIMER_MIN_GC PRIMER_OPT_GC_PERCENT PRIMER_MAX_GC PRIMER_MAX_POLY_X+PRIMER_GC_CLAMP PRIMER_MAX_END_GC PRIMER_MAX_END_STABILITY+PRIMER_MAX_SELF_ANY_TH PRIMER_MAX_SELF_END_TH PRIMER_MAX_HAIRPIN_TH+PRIMER_PAIR_MAX_COMPL_ANY_TH PRIMER_PAIR_MAX_COMPL_END_TH+PRIMER_SALT_MONOVALENT PRIMER_SALT_DIVALENT PRIMER_DNTP_CONC+PRIMER_DNA_CONC PRIMER_TM_FORMULA PRIMER_SALT_CORRECTIONS+PRIMER_PRODUCT_SIZE_RANGE PRIMER_MIN_5_PRIME_OVERLAP_OF_JUNCTION+PRIMER_MIN_3_PRIME_OVERLAP_OF_JUNCTION PRIMER_MAX_NS_ACCEPTED+PRIMER_WT_TM_GT PRIMER_WT_TM_LT PRIMER_WT_SIZE_GT PRIMER_WT_SIZE_LT+PRIMER_PAIR_WT_DIFF_TM PRIMER_PAIR_WT_PR_PENALTY+PRIMER_MIN_QUALITY PRIMER_MIN_END_QUALITY PRIMER_QUALITY_RANGE_MIN+PRIMER_QUALITY_RANGE_MAX PRIMER_WT_SEQ_QUAL PRIMER_WT_END_QUAL+""".split())+SEQUENCE_KEYS = set("""+SEQUENCE_TARGET SEQUENCE_INCLUDED_REGION SEQUENCE_EXCLUDED_REGION+SEQUENCE_PRIMER_PAIR_OK_REGION_LIST SEQUENCE_OVERLAP_JUNCTION_LIST+SEQUENCE_PRIMER SEQUENCE_PRIMER_REVCOMP SEQUENCE_QUALITY+""".split())+++def region(value, length, name):+ if not isinstance(value, list) or len(value) != 2:+ raise ValueError(f"{name} requires [start, length]")+ start, size = value+ integer(start, name + ' start')+ integer(size, name + ' length', 1)+ if start + size > length:+ raise ValueError(f"{name} lies outside the selected FASTA record")+++def validate_config(config, length):+ if not isinstance(config, dict) or set(config) - {"sequence_args", "global_args"}:+ raise ValueError("Config accepts only sequence_args and global_args mappings")+ sequence, global_args = config.get("sequence_args", {}), config.get("global_args", {})+ if not isinstance(sequence, dict) or not isinstance(global_args, dict):+ raise ValueError("sequence_args and global_args must be JSON objects")+ for values, allowed, label in [(sequence, SEQUENCE_KEYS, "sequence_args"), (global_args, GLOBAL_KEYS, "global_args")]:+ if set(values) - allowed:+ raise ValueError(f"Unsupported {label}: {sorted(set(values) - allowed)}; see input-contract.md")+ for key in ("SEQUENCE_TARGET", "SEQUENCE_EXCLUDED_REGION"):+ if key in sequence:+ if not isinstance(sequence[key], list):+ raise ValueError(f"{key} must be a list of [start, length] intervals")+ for value in sequence[key]:+ region(value, length, key)+ if "SEQUENCE_INCLUDED_REGION" in sequence:+ region(sequence["SEQUENCE_INCLUDED_REGION"], length, "SEQUENCE_INCLUDED_REGION")+ for key in ("SEQUENCE_PRIMER", "SEQUENCE_PRIMER_REVCOMP"):+ if key in sequence:+ sequence[key] = dna(sequence[key], key)+ if not 15 <= len(sequence[key]) <= 36:+ raise ValueError(f"{key}: supported annealing core length is 15..36")+ if "SEQUENCE_OVERLAP_JUNCTION_LIST" in sequence:+ junctions = sequence["SEQUENCE_OVERLAP_JUNCTION_LIST"]+ if not isinstance(junctions, list):+ raise ValueError("SEQUENCE_OVERLAP_JUNCTION_LIST must be a list")+ for value in junctions:+ integer(value, "junction")+ if value >= length - 1:+ raise ValueError("Junction must name the base immediately left of an internal template boundary")+ if "SEQUENCE_QUALITY" in sequence:+ quality = sequence["SEQUENCE_QUALITY"]+ if not isinstance(quality, list) or len(quality) != length:+ raise ValueError("SEQUENCE_QUALITY needs one integer per template base")+ for value in quality:+ integer(value, "quality")+ if "SEQUENCE_PRIMER_PAIR_OK_REGION_LIST" in sequence:+ rows = sequence["SEQUENCE_PRIMER_PAIR_OK_REGION_LIST"]+ if not isinstance(rows, list):+ raise ValueError("SEQUENCE_PRIMER_PAIR_OK_REGION_LIST must be a list")+ for row in rows:+ if not isinstance(row, list) or len(row) != 4:+ raise ValueError("OK region requires [left_start,left_length,right_start,right_length]")+ for value in (row[:2], row[2:]):+ if value != [-1, -1]:+ region(value, length, "OK region")+ for key, value in global_args.items():+ if key == "PRIMER_PRODUCT_SIZE_RANGE":+ if not isinstance(value, list) or not value:+ raise ValueError("Product ranges must be a nonempty list of [minimum,maximum]")+ for limits in value:+ if not isinstance(limits, list) or len(limits) != 2:+ raise ValueError("Product range requires [minimum,maximum]")+ integer(limits[0], "minimum product", 1)+ integer(limits[1], "maximum product", limits[0])+ else:+ finite_number(value, key)+ if global_args.get("PRIMER_MAX_NS_ACCEPTED", 0) != 0:+ raise ValueError("This workflow requires unambiguous primers; PRIMER_MAX_NS_ACCEPTED must be 0")+ return sequence, global_args+++def bed_exclusions(path, records, record_id):+ exclusions = []+ with Path(path).open(encoding="utf-8") as handle:+ for number, raw in enumerate(handle, 1):+ if not raw.strip() or raw.startswith(("#", "track ", "browser ")):+ continue+ parts = raw.rstrip().split("\t")+ if len(parts) < 3 or parts[0] not in records:+ raise ValueError(f"BED line {number}: unknown record or fewer than 3 tab-separated columns")+ start, end = int(parts[1]), int(parts[2])+ region([start, end - start], len(records[parts[0]]), "BED interval")+ if parts[0] == record_id:+ exclusions.append([start, end - start])+ return exclusions+++def design(args):+ records = read_fasta(args.template)+ record_id = args.record or (next(iter(records)) if len(records) == 1 else None)+ if record_id not in records:+ raise ValueError("Choose --record from the FASTA IDs when the template has multiple records")+ original = records[record_id]+ # Primer3's sequence alphabet is narrower than IUPAC. Unknown positions are+ # made explicitly unavailable, never guessed into a concrete nucleotide.+ template = "".join(base if base in "ACGT" else "N" for base in original)+ config = json.loads(Path(args.config).read_text()) if args.config else {}+ sequence_args, overrides = validate_config(config, len(template))+ global_args = {+ "PRIMER_TASK": "generic", "PRIMER_PICK_LEFT_PRIMER": 1,+ "PRIMER_PICK_RIGHT_PRIMER": 1, "PRIMER_PICK_INTERNAL_OLIGO": 0,+ "PRIMER_FIRST_BASE_INDEX": 0, "PRIMER_EXPLAIN_FLAG": 1,+ "PRIMER_THERMODYNAMIC_OLIGO_ALIGNMENT": 1,+ "PRIMER_NUM_RETURN": 5, "PRIMER_MIN_SIZE": 18, "PRIMER_OPT_SIZE": 20,+ "PRIMER_MAX_SIZE": 25, "PRIMER_MIN_TM": 57.0, "PRIMER_OPT_TM": 60.0,+ "PRIMER_MAX_TM": 63.0, "PRIMER_PAIR_MAX_DIFF_TM": 3.0,+ "PRIMER_MIN_GC": 20.0, "PRIMER_MAX_GC": 80.0,+ "PRIMER_MAX_POLY_X": 4, "PRIMER_MAX_NS_ACCEPTED": 0,+ "PRIMER_SALT_MONOVALENT": 50.0, "PRIMER_SALT_DIVALENT": 1.5,+ "PRIMER_DNTP_CONC": 0.6, "PRIMER_DNA_CONC": 50.0,+ "PRIMER_TM_FORMULA": 1, "PRIMER_SALT_CORRECTIONS": 1,+ "PRIMER_PRODUCT_SIZE_RANGE": [[70, 200]] if args.preset == "qpcr" else [[100, 1000]],+ }+ global_args.update(overrides)+ for key in ("PRIMER_NUM_RETURN", "PRIMER_MIN_SIZE", "PRIMER_OPT_SIZE", "PRIMER_MAX_SIZE", "PRIMER_MAX_POLY_X", "PRIMER_GC_CLAMP", "PRIMER_MAX_END_GC", "PRIMER_TM_FORMULA", "PRIMER_SALT_CORRECTIONS", "PRIMER_MIN_5_PRIME_OVERLAP_OF_JUNCTION", "PRIMER_MIN_3_PRIME_OVERLAP_OF_JUNCTION", "PRIMER_MAX_NS_ACCEPTED", "PRIMER_MIN_QUALITY", "PRIMER_MIN_END_QUALITY", "PRIMER_QUALITY_RANGE_MIN", "PRIMER_QUALITY_RANGE_MAX"):+ if key in global_args:+ integer(global_args[key], key)+ if global_args["PRIMER_TM_FORMULA"] not in (0, 1):+ raise ValueError("PRIMER_TM_FORMULA must be 0 (Breslauer) or 1 (SantaLucia)")+ if global_args["PRIMER_SALT_CORRECTIONS"] not in (0, 1, 2):+ raise ValueError("PRIMER_SALT_CORRECTIONS must be 0 (Schildkraut), 1 (SantaLucia), or 2 (Owczarzy)")+ if not 1 <= global_args["PRIMER_NUM_RETURN"] <= 100:+ raise ValueError("PRIMER_NUM_RETURN must be 1..100")+ if not 15 <= global_args["PRIMER_MIN_SIZE"] <= global_args["PRIMER_OPT_SIZE"] <= global_args["PRIMER_MAX_SIZE"] <= 36:+ raise ValueError("Require 15 <= MIN_SIZE <= OPT_SIZE <= MAX_SIZE <= 36")+ if not global_args["PRIMER_MIN_TM"] <= global_args["PRIMER_OPT_TM"] <= global_args["PRIMER_MAX_TM"]:+ raise ValueError("Require MIN_TM <= OPT_TM <= MAX_TM")+ if not 0 <= global_args["PRIMER_MIN_GC"] <= global_args["PRIMER_MAX_GC"] <= 100:+ raise ValueError("Require 0 <= MIN_GC <= MAX_GC <= 100")+ finite_number(global_args["PRIMER_DNA_CONC"], "PRIMER_DNA_CONC", positive=True)+ if args.mask_bed:+ sequence_args.setdefault("SEQUENCE_EXCLUDED_REGION", []).extend(bed_exclusions(args.mask_bed, records, record_id))+ sequence_args.update(SEQUENCE_ID=record_id, SEQUENCE_TEMPLATE=template)+ tails = {name: dna(getattr(args, name), name, empty=True) for name in ("forward_tail", "reverse_tail")}+ p3 = load_primer3()+ result = p3.bindings.design_primers(sequence_args, global_args)+ if result.get("PRIMER_ERROR"):+ raise ValueError(result["PRIMER_ERROR"])+ pairs = []+ for i in range(result.get("PRIMER_PAIR_NUM_RETURNED", 0)):+ left, left_length = result[f"PRIMER_LEFT_{i}"]+ right, right_length = result[f"PRIMER_RIGHT_{i}"]+ forward, reverse = result[f"PRIMER_LEFT_{i}_SEQUENCE"], result[f"PRIMER_RIGHT_{i}_SEQUENCE"]+ if template[left:left + left_length] != forward or revcomp(template[right - right_length + 1:right + 1]) != reverse:+ raise ValueError("Primer3 output failed template/orientation verification")+ product = template[left:right + 1]+ if len(product) != result[f"PRIMER_PAIR_{i}_PRODUCT_SIZE"]:+ raise ValueError("Primer3 output failed product-length verification")+ pairs.append({+ "pair_id": f"pair_{i + 1}", "forward": forward, "reverse": reverse, **tails,+ "forward_order_sequence": tails["forward_tail"] + forward,+ "reverse_order_sequence": tails["reverse_tail"] + reverse,+ "record_id": record_id, "forward_interval": [left, left + left_length],+ "reverse_interval": [right - right_length + 1, right + 1],+ "product_interval": [left, right + 1], "product_size": len(product),+ "tailed_product_size": len(product) + sum(map(len, tails.values())),+ "product_sequence": product,+ "tailed_product_sequence": tails["forward_tail"] + product + revcomp(tails["reverse_tail"]),+ "forward_tm_c": result[f"PRIMER_LEFT_{i}_TM"],+ "reverse_tm_c": result[f"PRIMER_RIGHT_{i}_TM"],+ "penalty": result[f"PRIMER_PAIR_{i}_PENALTY"],+ "specificity_status": "not_screened",+ })+ report = {+ "schema_version": "1.0", "status": "candidates_generated" if pairs else "no_candidates",+ "coordinate_system": "0-based half-open on supplied FASTA record; reverse oligos are 5-prime to 3-prime",+ "provenance": {"template_file": str(args.template), "template_sha256": sha256_file(args.template),+ "record_id": record_id, "template_length": len(template),+ "primer3_py_version": p3.__version__,+ "libprimer3_version": p3.thermoanalysis.get_libprimer3_version(),+ "python_version": sys.version.split()[0],+ "config_sha256": sha256_file(args.config) if args.config else None,+ "mask_bed_sha256": sha256_file(args.mask_bed) if args.mask_bed else None},+ "settings": {"preset": args.preset, "sequence_args": sequence_args, "global_args": global_args, "tails": tails},+ "ambiguous_template_bases_masked": sum(c not in "ACGT" for c in original),+ "pairs": pairs,+ "engine_explanations": {key: value for key, value in result.items() if key.endswith("EXPLAIN") or key in ("PRIMER_WARNING", "PRIMER_ERROR")},+ "limitations": ["Primer3 penalty is a design ranking, not experimental validation or genomic specificity.",+ "Coordinates refer to the supplied template, not a genome unless the FASTA itself is that reference.",+ "Defaults are starting conditions; record the actual polymerase/buffer and validate experimentally.",+ "Tails were appended after design; assess full oligos separately for secondary structures."],+ }+ write_json(args.output, report)+ for path in (args.pairs_out, args.expected_out):+ if path:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ if args.pairs_out:+ with Path(args.pairs_out).open("w", newline="", encoding="utf-8") as handle:+ writer = csv.DictWriter(handle, fieldnames=PAIR_FIELDS, delimiter="\t", extrasaction="ignore")+ writer.writeheader()+ writer.writerows(pairs)+ if args.expected_out:+ with Path(args.expected_out).open("w", newline="", encoding="utf-8") as handle:+ writer = csv.writer(handle, delimiter="\t")+ writer.writerow(["pair_id", "record_id", "start", "end"])+ writer.writerows([p["pair_id"], record_id, *p["product_interval"]] for p in pairs)+ return 0 if pairs else 1+++def main(argv=None):+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--template", required=True, type=Path, help="Local FASTA; no remote retrieval")+ parser.add_argument("--record", help="Exact FASTA ID; required for multi-record input")+ parser.add_argument("--preset", choices=("pcr", "qpcr"), default="pcr")+ parser.add_argument("--config", type=Path, help="JSON sequence_args/global_args overrides")+ parser.add_argument("--mask-bed", type=Path, help="Exclude primer binding in BED intervals in template coordinates")+ parser.add_argument("--forward-tail", default="", help="5-prime tail appended to forward core")+ parser.add_argument("--reverse-tail", default="", help="5-prime tail appended to reverse core")+ parser.add_argument("--output", required=True, type=Path, help="JSON design report")+ parser.add_argument("--pairs-out", type=Path, help="TSV for downstream thermodynamics/screening")+ parser.add_argument("--expected-out", type=Path, help="TSV intended product coordinates on this template")+ args = parser.parse_args(argv)+ try:+ check_output_paths([args.template, args.config, args.mask_bed], [args.output, args.pairs_out, args.expected_out])+ return design(args)+ except (ValueError, OSError, RuntimeError, TypeError, OverflowError) as exc:+ print(f"error: {exc}", file=sys.stderr)+ return 2+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/primer-design/scripts/screen_specificity.py b/skills/primer-design/scripts/screen_specificity.pynew file mode 100644index 00000000..e8f9bad9--- /dev/null+++ b/skills/primer-design/scripts/screen_specificity.py@@ -0,0 +1,180 @@+#!/usr/bin/env python3+"""Screen primers against an explicit local FASTA with reproducible search bounds."""++from __future__ import annotations++import argparse+import platform+import sys+from datetime import datetime, timezone+from pathlib import Path++sys.dont_write_bytecode = True++from _common import check_output_paths, read_fasta, read_pairs, sha256_file, write_json+from _specificity import blast_hits, enumerate_products, exhaustive_hits, expand_panel_pairs, read_expected+++def build_parser():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--pairs", required=True, type=Path, help="TSV: pair_id, forward, reverse; optional forward_tail, reverse_tail")+ parser.add_argument("--reference", required=True, type=Path, help="FASTA with unique record IDs")+ parser.add_argument("--output", required=True, type=Path, help="JSON report; incomplete runs exit 2")+ parser.add_argument("--expected", type=Path, help="TSV: pair_id, record_id, start, end (0-based half-open)")+ parser.add_argument("--engine", choices=("exhaustive", "blast"), default="exhaustive")+ parser.add_argument("--multiplex", action="store_true", help="Also screen every cross-pair oligo combination; all cross-pair products are potential off-targets")+ parser.add_argument("--max-panel-combinations", type=int, default=10_000, help="Cross-pair oligo combination cap, checked before panel expansion")+ parser.add_argument("--circular", action="append", default=[], metavar="RECORD_ID", help="Repeat for circular records; intervals can end beyond record length")+ parser.add_argument("--min-product", type=int, default=40)+ parser.add_argument("--max-product", type=int, default=2000)+ parser.add_argument("--max-mismatches", type=int, default=2)+ parser.add_argument("--three-prime-bases", type=int, default=5)+ parser.add_argument("--max-three-prime-mismatches", type=int, default=0)+ parser.add_argument("--max-comparisons", type=int, default=100_000_000, help="Base comparison cap; exceeding a cap fails closed")+ parser.add_argument("--max-hits", type=int, default=100_000)+ parser.add_argument("--max-products", type=int, default=100_000, help="Per-pair product cap")+ parser.add_argument("--max-product-combinations", type=int, default=1_000_000, help="Per-pair inward-facing candidate comparison cap")+ parser.add_argument("--max-blast-rows", type=int, default=1_000_000)+ parser.add_argument("--blastn", default="blastn", help="Local BLAST+ blastn executable")+ parser.add_argument("--makeblastdb", default="makeblastdb", help="Local BLAST+ makeblastdb executable")+ parser.add_argument("--blast-max-target-seqs", type=int, default=100_000)+ parser.add_argument("--blast-max-hsps", type=int, default=100_000)+ parser.add_argument("--blast-timeout", type=int, default=300, help="Seconds per BLAST+ invocation")+ return parser+++def run(args):+ settings = {key: value for key, value in vars(args).items()+ if key not in {"pairs", "reference", "expected", "output"}}+ report = {+ "schema_version": "1.0", "analysis": "local_primer_specificity", "status": "incomplete",+ "complete_within_model": False, "exhaustive": False,+ "created_utc": datetime.now(timezone.utc).isoformat(),+ "coordinate_convention": "0-based half-open forward-reference; circular end may exceed record length",+ "strand_convention": "+ matches reference sequence and extends right; - matches its reverse complement and extends left",+ "settings": settings, "provenance": {"python": platform.python_version()},+ "limitations": [+ "Potential amplification under a bounded ungapped mismatch model; not experimental specificity.",+ "Only supplied reference records, mismatch thresholds, 3-prime window and product-size range are screened.",+ "Unrepresented variants, contaminants, insertions/deletions, and chemistry are not screened.",+ "Reference ambiguity is conservatively compatible when a primer base is possible; mismatches are lower bounds.",+ "Only annealing cores are searched. Tails affect final length but tail-created later-cycle binding is not searched.",+ "F/F, R/R and both F/R orientations are enumerated; overlapping binding sites are excluded.",+ ],+ "issues": [], "pairs": [],+ }+ report["limitations"].append(+ "Multiplex mode treats all cross-pair products as unintended; predeclared intentional cross-pair "+ "designs should be assessed as explicit standalone pairs. Same-oligo products remain in original-pair results."+ if args.multiplex else "Cross-pair multiplex products are not screened; enable --multiplex for a panel."+ )+ try:+ input_paths = [args.pairs, args.reference] + ([args.expected] if args.expected else [])+ check_output_paths(input_paths, [args.output])+ for key in ("min_product", "max_product", "three_prime_bases", "max_comparisons", "max_hits",+ "max_products", "max_product_combinations", "max_blast_rows", "blast_max_target_seqs",+ "blast_max_hsps", "blast_timeout", "max_panel_combinations"):+ if settings[key] <= 0:+ raise ValueError(f"{key} must be positive")+ if args.min_product > args.max_product:+ raise ValueError("min_product must not exceed max_product")+ if args.max_mismatches < 0 or args.max_three_prime_mismatches < 0:+ raise ValueError("Mismatch thresholds must be nonnegative")+ if args.max_three_prime_mismatches > args.three_prime_bases:+ raise ValueError("3-prime mismatch threshold exceeds its window")+ pairs, references = read_pairs(args.pairs), read_fasta(args.reference)+ circular = set(args.circular)+ if circular - set(references):+ raise ValueError("Unknown circular record IDs: " + ", ".join(sorted(circular - set(references))))+ primers = sorted({pair[key] for pair in pairs for key in ("forward", "reverse")})+ if not primers or not references:+ raise ValueError("Nonempty primer pairs and reference records are required")+ if any(args.three_prime_bases > len(primer) for primer in primers):+ raise ValueError("3-prime window exceeds a primer's annealing-core length")+ if any(set(primer) - set("ACGT") for primer in primers):+ raise ValueError("Only unambiguous ACGT annealing cores are supported")+ report["provenance"].update({+ "implementation_sha256": {+ name: sha256_file(Path(__file__).parent / name)+ for name in ("screen_specificity.py", "_specificity.py", "_common.py")+ },+ "pairs": {"path": str(args.pairs), "sha256": sha256_file(args.pairs)},+ "reference": {"path": str(args.reference), "sha256": sha256_file(args.reference),+ "record_count": len(references), "total_bases": sum(map(len, references.values())),+ "record_lengths": {key: len(value) for key, value in references.items()},+ "ambiguous_base_count": sum(base not in "ACGT" for sequence in references.values() for base in sequence)},+ "expected": {"path": str(args.expected), "sha256": sha256_file(args.expected)} if args.expected else None,+ })+ expected = read_expected(args.expected, pairs, references, circular)+ original_pair_count = len(pairs)+ if args.multiplex:+ pairs = expand_panel_pairs(pairs, args.max_panel_combinations)+ report["provenance"]["panel"] = {+ "enabled": args.multiplex, "original_pair_count": original_pair_count,+ "source_oligo_count": original_pair_count * 2,+ "cross_pair_count": len(pairs) - original_pair_count,+ "unique_annealing_cores_searched": len(primers),+ "generated_pair_ids": [pair["pair_id"] for pair in pairs if pair.get("cross_pair")],+ }+ search = exhaustive_hits if args.engine == "exhaustive" else blast_hits+ if args.engine == "blast":+ report["limitations"].append(+ "BLAST discovery is heuristic, uses exact 7-base seeds and E-value 1000; full-length ungapped "+ "realignment validates only discovered sites. No-hit output never proves absence of binding sites."+ )+ hits, engine_provenance, issues = search(primers, references, circular, settings)+ report["provenance"].update(engine_provenance)+ report["issues"].extend(issues)+ for pair in pairs:+ result = enumerate_products(pair, hits, references, circular, settings, expected.get(pair["pair_id"], []))+ if result["unresolved_ambiguity"]:+ report["issues"].append(+ f"Pair {pair['pair_id']}: ambiguous reference bases at potential binding sites; "+ "binding and 3-prime mismatch counts remain unresolved"+ )+ if issues:+ result.setdefault("status_before_incomplete", result["status"])+ result["status"] = "incomplete"+ report["pairs"].append(result)+ report["complete_within_model"] = args.engine == "exhaustive" and not report["issues"]+ report["exhaustive"] = args.engine == "exhaustive" and not report["issues"]+ report["discovery_completed"] = not issues+ statuses = {pair["status"] for pair in report["pairs"]}+ report["status"] = next(status for status in (+ "incomplete", "intended_target_not_found", "potential_off_target", "no_expected_target",+ "no_off_target_found_within_search_scope",+ ) if status in statuses)+ return report, 2 if report["issues"] else 0+ except (ValueError, OSError, KeyError) as exc:+ report["issues"].append(str(exc))+ report["status"] = "incomplete"+ report["complete_within_model"] = False+ report["exhaustive"] = False+ report["discovery_completed"] = False+ for pair in report["pairs"]:+ pair.setdefault("status_before_incomplete", pair["status"])+ pair["status"] = "incomplete"+ return report, 2+++def main(argv=None):+ args = build_parser().parse_args(argv)+ # Never replace an input with an error report, either.+ inputs = [args.pairs, args.reference] + ([args.expected] if args.expected else [])+ try:+ check_output_paths(inputs, [args.output])+ except (ValueError, OSError) as exc:+ print(f"error: {exc}", file=sys.stderr)+ return 2+ report, exit_code = run(args)+ try:+ write_json(args.output, report)+ except OSError as exc:+ print(f"Cannot write report: {exc}", file=sys.stderr)+ return 2+ print(f"{report['status']}: {args.output}")+ return exit_code+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/primer-design/VALIDATION.md b/tests/primer-design/VALIDATION.mdnew file mode 100644index 00000000..fe78e66b--- /dev/null+++ b/tests/primer-design/VALIDATION.md@@ -0,0 +1,88 @@+# Primer-design validation record++Validated on 2026-09-30 with Python 3.13.3, primer3-py 2.3.1,+libprimer3 release 2.6.1, and NCBI BLAST+ 2.17.0 on macOS. These results+establish software behavior on synthetic inputs, not biological assay performance.++## Executed checks++| Check | Result |+| --- | --- |+| `uv sync` | Passed |+| `uv run skills-ref validate skills/primer-design` | Passed |+| `uv run --with pytest python -m pytest tests/_meta -q` | 11 passed; 4,212 subtests passed |+| `python tests/run_all.py --isolated primer-design` | 86 passed; no skipped tests in this environment |+| Documented design, thermodynamics, exhaustive-screen, and BLAST-screen examples | Executed successfully on the bundled synthetic template |+| `git diff --check` | Passed |+| Repository security scanner, failing at HIGH severity | Passed; 0 CRITICAL, 0 HIGH, 2 LOW findings reviewed below |++The isolated suite includes six integration tests that execute real BLAST+ tools.+Those six skip explicitly when `blastn` or `makeblastdb` is absent; a passing+Python-only run must not be represented as BLAST integration evidence.++Coverage includes actual Primer3 design and numerical thermodynamics; explicit+chemistry and Tm models; quality scores; fixed primers; exon-junction coordinate+semantics; exclusions and BED masking; reverse orientation; tail concatenation+and product reconstruction; unsupported long oligos; both directional 3-prime+interactions; F/R, R/F, F/F and R/R products; circular origin crossing; mismatch+positions and ambiguous reference bases; multiplex cross-pair products and search+deduplication; resource caps; tool failures; and protection against overwriting+input files, including linked paths.++## Agent workflow evaluations++Prompts, grader assertions, and raw synthetic inputs are retained in+[evals.json](evals.json) and [fixtures/](fixtures/). Each case was run once with the+skill and once without it. Grading combined artifact inspection with independent+sequence/coordinate, thermodynamic, product-inventory, and source-hash checks.++| Case | With skill | Without skill | What was verified |+| --- | --- | --- | --- |+| Existing pair with same-primer off-target products | 5/5 assertions | 5/5 assertions | Intended 154-bp product and both unexpected F/F products, numerical thermodynamics, provenance, and redesign recommendation |+| Tailed design with BED exclusions | 6/6 assertions | 6/6 assertions | Three valid flanking pairs, correct strands and masks, exact 48-base tails, core Tm, unresolved 68-nt full-oligo structures, scoped specificity, and reproducibility |++The first case is a workflow smoke test, **not a blinded efficacy comparison**:+the skill-assisted executor read the evaluation definition, which exposed an+expected-output hint about the same-primer products. Fresh executors for the+second case received only the prompt and named input fixtures; expected outputs+and grader assertions were withheld. Future executors must follow that separation.++Both configurations passed both cases. This small evaluation does **not** establish+improved task success, time savings, or token savings from the skill. Overall agent+wall times and token counts were not reliably measured and are not reported. The+baseline's second report additionally quantified isolated-tail self-association;+the skill-assisted report identified the self-complementary tail and correctly+left complete-oligo structure assessment unresolved.++## Security review++The final `scan_pr_skills.py` run returned two LOW findings:++- `LLM_UNAUTHORIZED_TOOL_USE`: informational absence of optional `allowed-tools`.+ The skill is portable across agent hosts, documents its executables and+ dependencies, and invokes local BLAST tools with argument lists rather than a+ shell. The scanner identified no injection vector.+- `LLM_RESOURCE_ABUSE`: the exhaustive scan can consume substantial resources if+ a caller deliberately raises its bounds. Existing comparison, hit, product,+ panel, subprocess-output, and timeout limits stop incomplete work from being+ reported as a complete search. The reference-memory and genome-scale limits+ are documented. The scan recommended no required action.++An earlier critical behavioral finding was verified against the scanner and AST:+its substring detector interpreted an ordinary identifier containing `exec` as+dynamic execution. Renaming that local identifier removed the false positive;+there are no `eval`, `exec`, or shell-based process calls in the skill scripts.++## Remaining validation boundaries++- All sequence fixtures are synthetic; no primers were ordered or experimentally+ validated. No human-genome sensitivity or scalability benchmark was performed.+- BLAST discovery remains heuristic even when its integration tests pass. The+ exhaustive engine is complete only within its stated bounded, ungapped model.+- NCBI Primer-BLAST is documented as an external workflow; no live submission or+ undocumented API integration was tested.+- Specialized probe, degenerate, bisulfite, modified-base, and allele-specific+ workflows have explicit guidance and limits. They are not automated or+ empirically validated by the ordinary-DNA CLI suite.+- Full oligos longer than 60 nt remain explicitly unresolved in the bundled+ thermodynamic workflow; no truncation is used to manufacture a result.diff --git a/tests/primer-design/evals.json b/tests/primer-design/evals.jsonnew file mode 100644index 00000000..bb31d10f--- /dev/null+++ b/tests/primer-design/evals.json@@ -0,0 +1,43 @@+{+ "skill_name": "primer-design",+ "fixture_base": "fixtures",+ "evals": [+ {+ "id": 1,+ "name": "existing-pair-specificity",+ "prompt": "Review the existing research PCR pair in review-pairs.tsv against review-reference.fasta. The intended product is in review-expected.tsv (0-based half-open). Screen products from 40 to 500 bp with up to two mismatches per core, allowing zero mismatches in its terminal five bases. Assess thermodynamics at 50 mM monovalent cations, 1.5 mM total divalent cations, 0.6 mM total dNTP, 50 nM oligos, and 37 C for free energy. Provide the ordering sequences, an auditable product inventory, numerical thermodynamics, reference provenance, and your recommendation about using the pair. Work locally; do not order anything.",+ "files": [+ "review-pairs.tsv",+ "review-reference.fasta",+ "review-expected.tsv"+ ],+ "expected_output": "Report correct intended product and unexpected same-primer product with scoped conclusions, numerical evidence, and provenance.",+ "assertions": [+ "Recovers the intended product at construct_A:[40,194), length 154.",+ "Finds both unexpected F/F products [40,434) and [280,434), with correct roles and lengths.",+ "Calculates thermodynamics under the requested chemistry and preserves correct 5-prime-to-3-prime ordering sequences.",+ "Preserves input hashes and an executable reproduction path.",+ "Recommends redesign and confines specificity claims to the supplied synthetic reference and search model."+ ]+ },+ {+ "id": 2,+ "name": "tailed-design-with-mask",+ "prompt": "Design three candidate pairs on design-template.fasta for research PCR. Products should be 100\u2013200 bp before tails and flank template interval [280,320). Exclude primer binding in design-mask.bed, which is in template coordinates. Add the following 48-base 5-prime tail to BOTH primers: ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGT. Use 50 mM monovalent cations, 1.5 mM total divalent cations, 0.6 mM total dNTP, and 50 nM oligos. Report core Tm, assess full oligo secondary structures where supported at 37 C, and screen this supplied reference for products of 40\u2013500 bp with up to two mismatches and zero mismatches in the terminal five bases. Deliver ordering sequences, intended product coordinates, reproducible artifacts, and clear remaining limitations. Work locally; do not order anything.",+ "files": [+ "design-template.fasta",+ "design-mask.bed"+ ],+ "expected_output": "Three valid flanking pairs with mask/strand/tail correctness, scoped local product screen, and explicit unsupported full-oligo structure assessment.",+ "assertions": [+ "Returns three candidate pairs with 100-200 bp reference products flanking [280,320).",+ "Both binding cores avoid the BED exclusions and match the correct template strands.",+ "Full order sequences concatenate exactly the supplied 48-base tail and correct core, including the reverse primer.",+ "Core Tm agrees with Primer3 under the supplied chemistry.",+ "Identifies full-oligo structure calculations as unsupported or supplies a valid length-appropriate calculation without silently truncating.",+ "Computes a scoped product screen and preserves input/settings/version evidence and a reproduction path."+ ]+ }+ ],+ "evaluation_instructions": "Supply only the prompt and named fixtures to each executor; keep expected_output and assertions with the grader. Never expose the entire evals.json to the executor."+}diff --git a/tests/primer-design/fixtures/design-mask.bed b/tests/primer-design/fixtures/design-mask.bednew file mode 100644index 00000000..0237a292--- /dev/null+++ b/tests/primer-design/fixtures/design-mask.bed@@ -0,0 +1,2 @@+synthetic_cDNA 200 215+synthetic_cDNA 365 380diff --git a/tests/primer-design/fixtures/design-template.fasta b/tests/primer-design/fixtures/design-template.fastanew file mode 100644index 00000000..8cc1d4ff--- /dev/null+++ b/tests/primer-design/fixtures/design-template.fasta@@ -0,0 +1,2 @@+>synthetic_cDNA synthetic design fixture+CTGGAGCCGCCGTGGGTGCAAAGTGGAATGCGGTATGGGTCTACATACTCCTAACTACTTCCGGTTCGGCCTTCCACACATGGAGTGCATGGACTCGACTTGTAGCTGGAACCCGAAGAGTGATCCTCCATTACTACGATCACACCGCATTCGGGCGACAGGTGATCAATCGGCAATACTGTACCCGCTCACCGCTGAGATCATATGTAGAGAGTTCTGTATTAACGATAGACCGATCAGGCCATATTCGGTCGGGGGTTACCCCATTCCGGCGTACGAGCACGCCCCCGCCTATGGGCGAACAAGTCGTTTCGAGAGACCTCGAGGGAACATTAGCTCTACCTGAAATGCACAGTAACTATCCTGATATGCTAGTAGCCTCACCGCAGCCAAGTTATCGGATAGAGCCAAAGGCACATCGCACAGACAGAAATCCATTAGAAATCATACAGTTGGCTATTGACGTAGGCATCTTTTCATTGCCAGTCAGCCAATTCCATAATTCAGCCGGGGAATTAGCCCATAAAAGATTCGCTGTACTCTTCTCGCTTCATGAGGTGCTTTGCACGCTTATTAGGCTGGCACCCATAATTCGTCTCTGTCACCACGCATACGATCTTACTGGCGAGATTTTACCGCGCGCTTTCCTTGCATTGCCGTGCGTCACGACGTTATTGTAGGAAATCGAATGGGCGATATTdiff --git a/tests/primer-design/fixtures/review-expected.tsv b/tests/primer-design/fixtures/review-expected.tsvnew file mode 100644index 00000000..c6193b8b--- /dev/null+++ b/tests/primer-design/fixtures/review-expected.tsv@@ -0,0 +1,2 @@+pair_id record_id start end+assay_A construct_A 40 194diff --git a/tests/primer-design/fixtures/review-pairs.tsv b/tests/primer-design/fixtures/review-pairs.tsvnew file mode 100644index 00000000..5d79cd03--- /dev/null+++ b/tests/primer-design/fixtures/review-pairs.tsv@@ -0,0 +1,2 @@+pair_id forward reverse+assay_A GACTCGATGTCAGACGCTAGTCGA TCGACAGTCGATGCTACGATCAGTdiff --git a/tests/primer-design/fixtures/review-reference.fasta b/tests/primer-design/fixtures/review-reference.fastanew file mode 100644index 00000000..a221e8c8--- /dev/null+++ b/tests/primer-design/fixtures/review-reference.fasta@@ -0,0 +1,2 @@+>construct_A synthetic review fixture+CTTATAGCGAAATTCCCACGCGCTTACGTCTTGGTACTCAGACTCGATGTCAGACGCTAGTCGACCTCGTGATATCGTTAGGGCGTGAGTTGCGTCCTATGAGTCGCCAAGGCCATAGGTCGCGACGCTTCCAGCCCTATTGCGATATGCGTTGCCCTTTCCCGGTATAGACTGATCGTAGCATCGACTGTCGATGTGGTCCAATATAGTGCGGTCATACTCCAGGAACCCTGATTACAGCCGCATCGTGATCAGGGCCTGATTGCTGTCGCCTAAGGCTGACTCGATGTCAGACGCTAGTCGAAATTTGGCCATACGCCCCGTGGGCTTCGCCCGTTGTGTGACGTAACTGTGTGAGCTGGGGTTGGACCTAGGCACGTTCGTGGCCGATGAACCCGAGACTTTAAAGTTCGACTAGCGTCTGACATCGAGTCTTGGCACCGTTAAACGACGTGTTCGGACTTTGTGCCGGAAGTTTTTTCCTCTGCCTAATTGATCCAGTGACGAATTTGGGATGCGTGTTTATAGAGTCACCCCGAGdiff --git a/tests/primer-design/test_design_thermodynamics.py b/tests/primer-design/test_design_thermodynamics.pynew file mode 100644index 00000000..ca1413c9--- /dev/null+++ b/tests/primer-design/test_design_thermodynamics.py@@ -0,0 +1,360 @@+"""Real Primer3 checks for coordinates, constraints, and physical model inputs."""+from __future__ import annotations++import csv+import hashlib+import itertools+import json+import os+import subprocess+import sys+from pathlib import Path++import pytest+import skill_contract++primer3 = pytest.importorskip("primer3")++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "primer-design"+CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+++def run_script(name, *arguments):+ return subprocess.run(+ [sys.executable, str(SKILL_ROOT / "scripts" / name), *map(str, arguments)],+ capture_output=True, text=True, timeout=60,+ env={**os.environ, "PYTHONDONTWRITEBYTECODE": "1"},+ )+++def reverse_complement(sequence):+ return sequence.translate(str.maketrans("ACGT", "TGCA"))[::-1]+++def demo_sequence():+ return "".join(+ line.strip() for line in (SKILL_ROOT / "assets" / "demo-template.fasta").read_text().splitlines()+ if not line.startswith(">")+ )+++def design(tmp_path, config=None, extra=(), template=None, name="design"):+ output = tmp_path / f"{name}.json"+ command = ["--template", template or SKILL_ROOT / "assets" / "demo-template.fasta",+ "--preset", "qpcr", "--output", output]+ if config is not None:+ config_path = tmp_path / f"{name}-config.json"+ config_path.write_text(json.dumps(config))+ command.extend(["--config", config_path])+ result = run_script("design_primers.py", *command, *extra)+ return result, json.loads(output.read_text()) if output.exists() else None+++def write_pairs(tmp_path, rows, name="pairs.tsv"):+ path = tmp_path / name+ with path.open("w", newline="") as handle:+ writer = csv.DictWriter(handle, delimiter="\t", fieldnames=[+ "pair_id", "forward", "reverse", "forward_tail", "reverse_tail",+ ])+ writer.writeheader()+ writer.writerows(rows)+ return path+++def assess(tmp_path, rows, extra=(), name="thermo"):+ pairs = write_pairs(tmp_path, rows, name=f"{name}-pairs.tsv")+ output = tmp_path / f"{name}.json"+ result = run_script("check_thermodynamics.py", "--pairs", pairs, "--output", output, *extra)+ return result, json.loads(output.read_text()) if output.exists() else None+++def ordinary_pair():+ # These deliberately yield different directional end-stability energies.+ return {"pair_id": "alpha", "forward": "GTAAAACGACGGCCAGT", "reverse": "ACTGGCCGTCGTTTAC"}+++def test_shipped_design_obeys_target_geometry_and_export_contract(tmp_path):+ config = json.loads((SKILL_ROOT / "assets" / "qpcr-config.json").read_text())+ pairs_path, expected_path = tmp_path / "pairs.tsv", tmp_path / "expected.tsv"+ result, report = design(tmp_path, config, extra=[+ "--pairs-out", pairs_path, "--expected-out", expected_path,+ "--forward-tail", "GGTCTC", "--reverse-tail", "ATCG",+ ])+ assert result.returncode == 0, result.stderr+ assert report["status"] == "candidates_generated"+ assert len(report["pairs"]) == config["global_args"]["PRIMER_NUM_RETURN"]+ template = demo_sequence()+ for pair in report["pairs"]:+ left, left_end = pair["forward_interval"]+ right_start, right_end = pair["reverse_interval"]+ assert pair["forward"] == template[left:left_end]+ assert pair["reverse"] == reverse_complement(template[right_start:right_end])+ assert left_end <= 235 and right_start >= 265+ assert pair["product_interval"] == [left, right_end]+ assert pair["product_sequence"] == template[left:right_end]+ assert 90 <= pair["product_size"] == right_end - left <= 180+ assert pair["tailed_product_size"] == pair["product_size"] + 10+ assert pair["tailed_product_sequence"] == "GGTCTC" + pair["product_sequence"] + "CGAT"+ assert pair["forward_order_sequence"] == "GGTCTC" + pair["forward"]+ assert pair["reverse_order_sequence"] == "ATCG" + pair["reverse"]+ assert pair["specificity_status"] == "not_screened"+ with pairs_path.open() as handle:+ exported = list(csv.DictReader(handle, delimiter="\t"))+ with expected_path.open() as handle:+ expected = list(csv.DictReader(handle, delimiter="\t"))+ assert len(exported) == len(expected) == len(report["pairs"])+ for row, coordinates, pair in zip(exported, expected, report["pairs"]):+ assert row["pair_id"] == coordinates["pair_id"] == pair["pair_id"]+ assert row["reverse"] == pair["reverse"]+ assert [int(coordinates["start"]), int(coordinates["end"])] == pair["product_interval"]+ source = SKILL_ROOT / "assets" / "demo-template.fasta"+ assert report["provenance"]["template_sha256"] == hashlib.sha256(source.read_bytes()).hexdigest()+ assert report["provenance"]["primer3_py_version"] == primer3.__version__+ assert report["provenance"]["libprimer3_version"] == primer3.thermoanalysis.get_libprimer3_version()+++def test_design_and_checker_agree_under_nondefault_tm_and_salt_models(tmp_path):+ config = json.loads((SKILL_ROOT / "assets" / "qpcr-config.json").read_text())+ config["global_args"].update(PRIMER_TM_FORMULA=0, PRIMER_SALT_CORRECTIONS=2)+ pairs_path = tmp_path / "nondefault-pairs.tsv"+ result, designed = design(tmp_path, config, extra=["--pairs-out", pairs_path])+ assert result.returncode == 0, result.stderr+ output = tmp_path / "nondefault-thermo.json"+ result = run_script("check_thermodynamics.py", "--pairs", pairs_path, "--output", output,+ "--tm-method", "breslauer", "--salt-corrections-method", "owczarzy")+ assert result.returncode == 0, result.stderr+ thermo = json.loads(output.read_text())+ oligos = {entry["oligo_id"]: entry for entry in thermo["oligos"]}+ for pair in designed["pairs"]:+ for role in ("forward", "reverse"):+ assert oligos[f"{pair['pair_id']}:{role}"]["annealing_tm_c"] == pytest.approx(pair[f"{role}_tm_c"])+ assert thermo["settings"]["tm_method"] == "breslauer"+ assert thermo["settings"]["salt_corrections_method"] == "owczarzy"+ assert thermo["provenance"]["libprimer3_version"] == primer3.thermoanalysis.get_libprimer3_version()+++def test_masked_variant_is_excluded_from_both_binding_intervals(tmp_path):+ config = json.loads((SKILL_ROOT / "assets" / "qpcr-config.json").read_text())+ result, original = design(tmp_path, config, name="initial")+ assert result.returncode == 0, result.stderr+ first = original["pairs"][0]+ positions = [first["forward_interval"][1] - 1, first["reverse_interval"][0]]+ mask = tmp_path / "variants.bed"+ mask.write_text("".join(f"synthetic_target\t{p}\t{p + 1}\n" for p in positions))+ result, screened = design(tmp_path, config, extra=["--mask-bed", mask], name="masked")+ assert result.returncode == 0, result.stderr+ for pair in screened["pairs"]:+ for start, end in [pair["forward_interval"], pair["reverse_interval"]]:+ assert all(not start <= position < end for position in positions)+ assert screened["provenance"]["mask_bed_sha256"] == hashlib.sha256(mask.read_bytes()).hexdigest()+++def test_junction_index_names_base_immediately_left_of_boundary(tmp_path):+ sequence = demo_sequence()+ # These exact cores pass default design constraints. Boundary 246 has+ # precisely 8 bases at the forward 5-prime side and 12 at its 3-prime side.+ config = {"sequence_args": {+ "SEQUENCE_PRIMER": sequence[238:258],+ "SEQUENCE_PRIMER_REVCOMP": reverse_complement(sequence[356:376]),+ "SEQUENCE_OVERLAP_JUNCTION_LIST": [245],+ }, "global_args": {+ "PRIMER_MIN_5_PRIME_OVERLAP_OF_JUNCTION": 8,+ "PRIMER_MIN_3_PRIME_OVERLAP_OF_JUNCTION": 12,+ }}+ result, report = design(tmp_path, config, name="junction")+ assert result.returncode == 0, result.stderr+ assert report["pairs"][0]["forward_interval"] == [238, 258]+ config["sequence_args"]["SEQUENCE_OVERLAP_JUNCTION_LIST"] = [246]+ result, report = design(tmp_path, config, name="wrong-junction")+ assert result.returncode == 1+ assert report["status"] == "no_candidates"+++def test_base_quality_excludes_low_confidence_binding_bases(tmp_path):+ result, initial = design(tmp_path, name="initial")+ assert result.returncode == 0+ site = initial["pairs"][0]["forward_interval"][0]+ scores = [50] * len(demo_sequence())+ scores[site] = 5+ result, report = design(tmp_path, {"sequence_args": {"SEQUENCE_QUALITY": scores},+ "global_args": {"PRIMER_MIN_QUALITY": 20}}, name="quality")+ assert result.returncode == 0, result.stderr+ assert all(not start <= site < end for pair in report["pairs"]+ for start, end in (pair["forward_interval"], pair["reverse_interval"]))+++def test_ambiguous_template_site_is_not_guessed_into_a_primer(tmp_path):+ result, original = design(tmp_path, name="initial")+ assert result.returncode == 0, result.stderr+ position = original["pairs"][0]["forward_interval"][0] + 3+ sequence = demo_sequence()+ fasta = tmp_path / "ambiguous.fasta"+ fasta.write_text(f">synthetic_target\n{sequence[:position]}R{sequence[position + 1:]}\n")+ result, report = design(tmp_path, template=fasta, name="ambiguous")+ assert result.returncode == 0, result.stderr+ assert report["ambiguous_template_bases_masked"] == 1+ for pair in report["pairs"]:+ for start, end in [pair["forward_interval"], pair["reverse_interval"]]:+ assert not start <= position < end+ assert set(pair["forward"] + pair["reverse"]) <= set("ACGT")++[email protected]("config", [+ {"global_arg": {}},+ {"sequence_args": []},+ {"global_args": {"PRIMER_MIN_TMM": 57}},+ {"sequence_args": {"SEQUENCE_TARGET": [[490, 30]]}},+ {"sequence_args": {"SEQUENCE_TARGET": [[-1, 10]]}},+ {"sequence_args": {"SEQUENCE_EXCLUDED_REGION": [[10, 0]]}},+ {"sequence_args": {"SEQUENCE_INCLUDED_REGION": [False, 100]}},+ {"sequence_args": {"SEQUENCE_QUALITY": [20]}},+ {"global_args": {"PRIMER_NUM_RETURN": True}},+ {"global_args": {"PRIMER_NUM_RETURN": 0}},+ {"global_args": {"PRIMER_MIN_SIZE": 26}},+ {"global_args": {"PRIMER_MIN_TM": 70}},+ {"global_args": {"PRIMER_DNA_CONC": 0}},+ {"global_args": {"PRIMER_DNA_CONC": float("nan")}},+ {"global_args": {"PRIMER_MAX_NS_ACCEPTED": 1}},+ {"global_args": {"PRIMER_PRODUCT_SIZE_RANGE": [[200, 100]]}},+ {"global_args": {"PRIMER_TM_FORMULA": 42}},+ {"global_args": {"PRIMER_SALT_CORRECTIONS": 42}},+])+def test_invalid_configuration_is_an_error_not_no_candidates(tmp_path, config):+ result, report = design(tmp_path, config)+ assert result.returncode == 2, result.stderr+ assert "error:" in result.stderr and "Traceback" not in result.stderr+ assert report is None+++def test_no_candidates_is_an_explicit_scientific_result(tmp_path):+ fasta = tmp_path / "poly-a.fasta"+ fasta.write_text(">no_suitable_primers\n" + "A" * 500 + "\n")+ result, report = design(tmp_path, template=fasta)+ assert result.returncode == 1, result.stderr+ assert report["status"] == "no_candidates" and report["pairs"] == []+ assert report["engine_explanations"]+ assert "error:" not in result.stderr+++def test_multiple_fasta_records_require_explicit_selection(tmp_path):+ fasta = tmp_path / "multiple.fasta"+ fasta.write_text(">first\n" + demo_sequence() + "\n>second\n" + "A" * 500 + "\n")+ result, report = design(tmp_path, template=fasta)+ assert result.returncode == 2 and report is None+ result, report = design(tmp_path, template=fasta, extra=["--record", "first"], name="selected")+ assert result.returncode == 0, result.stderr+ assert report["provenance"]["record_id"] == "first"+++def assert_structure_matches(observed, expected):+ assert observed["structure_found"] == bool(expected.structure_found)+ assert observed["tm_c"] == pytest.approx(expected.tm)+ assert observed["delta_g_kcal_per_mol"] == pytest.approx(expected.dg / 1000)+ assert observed["delta_h_kcal_per_mol"] == pytest.approx(expected.dh / 1000)+ assert observed["delta_s_cal_per_mol_k"] == pytest.approx(expected.ds)+++def test_thermodynamics_uses_explicit_chemistry_and_both_3prime_directions(tmp_path, ordinary_pair):+ result, report = assess(tmp_path, [ordinary_pair], extra=[+ "--mv-conc", "62", "--dv-conc", "2", "--dntp-conc", "0.8",+ "--dna-conc", "175", "--temp-c", "55",+ ])+ assert result.returncode == 0, result.stderr+ chemistry = {"mv_conc": 62, "dv_conc": 2, "dntp_conc": .8, "dna_conc": 175}+ structures = {**chemistry, "temp_c": 55}+ forward, reverse = ordinary_pair["forward"], ordinary_pair["reverse"]+ for entry in report["oligos"]:+ sequence = entry["annealing_core"]+ assert entry["annealing_tm_c"] == pytest.approx(primer3.calc_tm(sequence, **chemistry))+ assert_structure_matches(entry["full_hairpin"], primer3.calc_hairpin(sequence, **structures))+ assert_structure_matches(entry["full_homodimer"], primer3.calc_homodimer(sequence, **structures))+ interaction, = report["interactions"]+ assert_structure_matches(interaction["heterodimer"], primer3.calc_heterodimer(forward, reverse, **structures))+ assert_structure_matches(interaction["a_three_prime_to_b"], primer3.calc_end_stability(forward, reverse, **structures))+ assert_structure_matches(interaction["b_three_prime_to_a"], primer3.calc_end_stability(reverse, forward, **structures))+ assert interaction["a_three_prime_to_b"]["delta_g_kcal_per_mol"] != pytest.approx(+ interaction["b_three_prime_to_a"]["delta_g_kcal_per_mol"])+ result, changed = assess(tmp_path, [ordinary_pair], extra=["--mv-conc", "5"], name="different-chemistry")+ assert result.returncode == 0, result.stderr+ assert changed["oligos"][0]["annealing_tm_c"] != pytest.approx(report["oligos"][0]["annealing_tm_c"])+++def test_tail_is_excluded_from_tm_but_included_in_structures(tmp_path, ordinary_pair):+ tailed = {**ordinary_pair, "forward_tail": reverse_complement(ordinary_pair["forward"])}+ result, report = assess(tmp_path, [tailed])+ assert result.returncode == 0, result.stderr+ forward = report["oligos"][0]+ full = tailed["forward_tail"] + tailed["forward"]+ assert forward["order_sequence"] == full+ assert forward["annealing_tm_c"] == pytest.approx(primer3.calc_tm(tailed["forward"]))+ assert_structure_matches(forward["full_hairpin"], primer3.calc_hairpin(full))+ assert_structure_matches(forward["full_homodimer"], primer3.calc_homodimer(full))+ assert_structure_matches(forward["full_self_three_prime"], primer3.calc_end_stability(full, full))+ assert_structure_matches(forward["core_self_three_prime"], primer3.calc_end_stability(tailed["forward"], tailed["forward"]))+ assert forward["full_hairpin"]["tm_c"] != pytest.approx(forward["core_hairpin"]["tm_c"])+ assert_structure_matches(report["interactions"][0]["heterodimer"], primer3.calc_heterodimer(full, tailed["reverse"]))+++def test_multiplex_computes_all_distinct_oligo_pairs(tmp_path, ordinary_pair):+ rows = [ordinary_pair, {"pair_id": "beta", "forward": "CCCCCATCCGATCAGGGGG", "reverse": "TCCTACTAGCATGGCGTATA"}]+ result, report = assess(tmp_path, rows, extra=["--multiplex"])+ assert result.returncode == 0, result.stderr+ ids = ["alpha:forward", "alpha:reverse", "beta:forward", "beta:reverse"]+ assert {(row["oligo_a"], row["oligo_b"]) for row in report["interactions"]} == set(itertools.combinations(ids, 2))+ assert sum(row["cross_pair"] for row in report["interactions"]) == 4+ assert all(row["status"] == "computed" for row in report["interactions"])+ result, capped = assess(tmp_path, rows, extra=["--multiplex", "--max-interactions", "5"], name="capped")+ assert result.returncode == 2 and capped is None+ assert "6 dimer comparisons" in result.stderr+++def test_unsupported_full_length_preserves_core_and_marks_report_incomplete(tmp_path, ordinary_pair):+ tailed = {**ordinary_pair, "forward_tail": "A" * 61}+ result, report = assess(tmp_path, [tailed])+ assert result.returncode == 1, result.stderr+ assert report["status"] == "incomplete"+ forward = report["oligos"][0]+ assert forward["order_sequence"] == tailed["forward_tail"] + tailed["forward"]+ assert forward["annealing_tm_c"] == pytest.approx(primer3.calc_tm(ordinary_pair["forward"]))+ assert forward["full_oligo_status"] == "unsupported_length"+ assert "full_hairpin" not in forward and "full_homodimer" not in forward+ assert report["interactions"][0]["status"] == "unsupported_length"+ assert report["warnings"]++[email protected]("change", [+ {"forward": "ACGTNACGT"}, {"reverse": "ACGUACGU"},+ {"forward": "A"}, {"forward_tail": "[FAM]"}, {"pair_id": "duplicate:name"},+])+def test_invalid_oligos_are_rejected_without_partial_reports(tmp_path, ordinary_pair, change):+ result, report = assess(tmp_path, [{**ordinary_pair, **change}])+ assert result.returncode == 2 and report is None+ assert "Traceback" not in result.stderr++[email protected]("extra", [["--dna-conc", "nan"], ["--mv-conc", "-1"], ["--temp-c", "101"]])+def test_invalid_chemistry_is_rejected(tmp_path, ordinary_pair, extra):+ result, report = assess(tmp_path, [ordinary_pair], extra=extra)+ assert result.returncode == 2 and report is None+++def test_output_collisions_preserve_inputs(tmp_path, ordinary_pair):+ pairs = write_pairs(tmp_path, [ordinary_pair])+ original_pairs = pairs.read_bytes()+ result = run_script("check_thermodynamics.py", "--pairs", pairs, "--output", pairs)+ assert result.returncode == 2 and pairs.read_bytes() == original_pairs+ template = tmp_path / "template.fasta"+ template.write_text(">target\n" + demo_sequence() + "\n")+ original_template = template.read_bytes()+ alias = tmp_path / "alias.fasta"+ alias.symlink_to(template)+ result = run_script("design_primers.py", "--template", template, "--output", alias)+ assert result.returncode == 2 and template.read_bytes() == original_template+ output = tmp_path / "result.json"+ result = run_script("design_primers.py", "--template", template, "--output", output, "--pairs-out", output)+ assert result.returncode == 2 and not output.exists()+ hardlink = tmp_path / "hardlink.tsv"+ hardlink.hardlink_to(template)+ result = run_script("design_primers.py", "--template", template, "--output", output, "--pairs-out", hardlink)+ assert result.returncode == 2 and template.read_bytes() == original_templatediff --git a/tests/primer-design/test_specificity.py b/tests/primer-design/test_specificity.pynew file mode 100644index 00000000..18e5fab9--- /dev/null+++ b/tests/primer-design/test_specificity.py@@ -0,0 +1,469 @@+"""Scientific failure cases and genuine offline BLAST integration for primer screens."""++from __future__ import annotations++import json+import random+import shutil+import subprocess+import sys+from pathlib import Path++import pytest++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "primer-design"+sys.path.insert(0, str(SKILL_ROOT / "scripts"))++from _common import revcomp+from _specificity import SearchIncomplete, expand_panel_pairs, run_tool, score_window+from screen_specificity import build_parser, main, run+++F = "ACGTTGCACTGATCGTACGA"+R = "TGCAGATCGACCTAGTCAGC"+SPACER = "".join(random.Random(1729).choices("ACGT", k=80))+TARGET = F + SPACER + revcomp(R)+++def inputs(tmp_path, references=None, expected=True, forward=F, reverse=R, tails=None):+ pairs = tmp_path / "pairs.tsv"+ header = "pair_id\tforward\treverse"+ values = f"p1\t{forward}\t{reverse}"+ if tails:+ header += "\tforward_tail\treverse_tail"+ values += "\t" + "\t".join(tails)+ pairs.write_text(header + "\n" + values + "\n")+ reference = tmp_path / "reference.fa"+ references = references or {"target": TARGET}+ reference.write_text("".join(f">{key}\n{value}\n" for key, value in references.items()))+ args = ["--pairs", str(pairs), "--reference", str(reference), "--output", str(tmp_path / "screen.json"),+ "--max-mismatches", "0"]+ if expected:+ expected_path = tmp_path / "expected.tsv"+ expected_path.write_text("pair_id\trecord_id\tstart\tend\np1\ttarget\t0\t120\n")+ args += ["--expected", str(expected_path)]+ return args+++def execute(arguments):+ return run(build_parser().parse_args(arguments))+++def test_exact_intended_product_and_provenance(tmp_path):+ report, code = execute(inputs(tmp_path))+ assert code == 0+ assert report["complete_within_model"] and report["exhaustive"]+ pair = report["pairs"][0]+ assert pair["status"] == "no_off_target_found_within_search_scope"+ assert pair["hit_count"] == 2+ product, = pair["products"]+ assert (product["start"], product["end"], product["length"]) == (0, 120, 120)+ assert product["primer_roles"] == "F/R"+ assert product["classification"] == "intended"+ assert {h["strand"] for h in pair["hits"]} == {"+", "-"}+ assert len(report["provenance"]["reference"]["sha256"]) == 64+ assert len(report["provenance"]["expected"]["sha256"]) == 64+++def test_unintended_second_amplicon_rejected(tmp_path):+ report, code = execute(inputs(tmp_path, {"target": TARGET, "paralog": TARGET}))+ assert code == 0+ assert report["status"] == "potential_off_target"+ pair = report["pairs"][0]+ assert pair["potential_off_target_count"] == 1+ assert {p["classification"] for p in pair["products"]} == {"intended", "potential_off_target"}++[email protected]("primer,kind", [(F, "F/F"), (R, "R/R")])+def test_same_primer_products_are_reported(tmp_path, primer, kind):+ references = {"target": TARGET, "single_primer": primer + SPACER + revcomp(primer)}+ report, code = execute(inputs(tmp_path, references))+ assert code == 0+ assert report["status"] == "potential_off_target"+ product, = [p for p in report["pairs"][0]["products"] if p["record_id"] == "single_primer"]+ assert product["primer_roles"] == kind+++def test_reverse_orientation_pair(tmp_path):+ report, code = execute(inputs(tmp_path, {"target": R + SPACER + revcomp(F)}))+ assert code == 0+ product, = report["pairs"][0]["products"]+ assert product["primer_roles"] == "R/F"+ assert product["classification"] == "intended"++[email protected]("strand", ["+", "-"])+def test_terminal_mismatch_is_strand_correct(tmp_path, strand):+ f = F[:-1] + "C" if strand == "+" else F+ r = R[:-1] + "A" if strand == "-" else R+ args = inputs(tmp_path, {"target": f + SPACER + revcomp(r)})+ args += ["--max-mismatches", "1"]+ strict, _ = execute(args)+ assert strict["status"] == "intended_target_not_found"+ permissive, _ = execute(args + ["--max-three-prime-mismatches", "1"])+ assert permissive["status"] == "no_off_target_found_within_search_scope"+ hit, = [h for h in permissive["pairs"][0]["hits"] if h["strand"] == strand]+ assert hit["mismatch_positions_1based"] == [20]+ assert hit["mismatch_positions_from_three_prime_1based"] == [1]+ assert hit["three_prime_mismatches"] == 1+++def test_five_prime_mismatch_is_not_a_three_prime_mismatch(tmp_path):+ args = inputs(tmp_path, {"target": "T" + TARGET[1:]})+ report, _ = execute(args + ["--max-mismatches", "1"])+ assert report["status"] == "no_off_target_found_within_search_scope"+ hit, = [h for h in report["pairs"][0]["hits"] if h["strand"] == "+"]+ assert hit["mismatch_positions_1based"] == [1]+ assert hit["three_prime_mismatches"] == 0+++def test_ambiguous_reference_is_conservative_and_unresolved(tmp_path):+ args = inputs(tmp_path, {"target": F[:-1] + "N" + SPACER + revcomp(R)})+ report, code = execute(args)+ assert code == 2+ assert report["status"] == "incomplete"+ assert not report["complete_within_model"]+ pair = report["pairs"][0]+ assert pair["status_before_incomplete"] == "no_off_target_found_within_search_scope"+ assert pair["unresolved_ambiguity"]+ assert pair["products"][0]["unresolved_ambiguity"]+ hit, = [h for h in pair["hits"] if h["strand"] == "+"]+ assert hit["mismatches"] == 0+ assert hit["mismatches_upper_bound"] == 1+ assert hit["three_prime_mismatches_upper_bound"] == 1+ assert hit["ambiguous_positions_from_three_prime_1based"] == [1]+++def test_ambiguous_off_target_retains_evidence_and_marks_incomplete(tmp_path):+ off = F[:-1] + "N" + SPACER + revcomp(R)+ report, code = execute(inputs(tmp_path, {"target": TARGET, "ambiguous_alternative": off}))+ assert code == 2 and report["status"] == "incomplete"+ assert not report["complete_within_model"]+ pair = report["pairs"][0]+ assert pair["status_before_incomplete"] == "potential_off_target"+ assert pair["potential_off_target_count"] == 1+ assert any(p["classification"] == "potential_off_target" and p["unresolved_ambiguity"] for p in pair["products"])+++def test_nonbinding_internal_ambiguity_does_not_suppress_screen(tmp_path):+ sequence = F + SPACER[:40] + "N" + SPACER[41:] + revcomp(R)+ report, code = execute(inputs(tmp_path, {"target": sequence}))+ assert code == 0+ assert report["status"] == "no_off_target_found_within_search_scope"+ assert report["complete_within_model"]+ assert report["provenance"]["reference"]["ambiguous_base_count"] == 1+++def test_incompatible_iupac_base_counts_as_definite_mismatch():+ settings = {"three_prime_bases": 1, "max_mismatches": 0, "max_three_prime_mismatches": 0}+ assert score_window("A", "Y", "+", settings) is None+ assert score_window("A", "R", "+", settings)["unresolved_ambiguity"]+++def test_no_expected_target_never_claims_specificity(tmp_path):+ report, code = execute(inputs(tmp_path, expected=False))+ assert code == 0+ assert report["status"] == "no_expected_target"+ assert report["pairs"][0]["products"][0]["classification"] == "unclassified"+++def test_missing_expected_interval_is_reported_even_with_another_product(tmp_path):+ args = inputs(tmp_path)+ (tmp_path / "expected.tsv").write_text("pair_id\trecord_id\tstart\tend\np1\ttarget\t1\t120\n")+ report, code = execute(args)+ assert code == 0+ assert report["status"] == "intended_target_not_found"+ assert report["pairs"][0]["missing_expected"] == [{"record_id": "target", "start": 1, "end": 120}]+ assert report["pairs"][0]["potential_off_target_count"] == 1+++def test_all_declared_intended_products_must_be_found(tmp_path):+ args = inputs(tmp_path, {"target": TARGET, "isoform": "A" * 120})+ with (tmp_path / "expected.tsv").open("a") as handle:+ handle.write("p1\tisoform\t0\t120\n")+ report, _ = execute(args)+ assert report["status"] == "intended_target_not_found"+ assert len(report["pairs"][0]["missing_expected"]) == 1+++def test_overlapping_sites_do_not_form_product(tmp_path):+ sequence = F + "AGTCAGTCGA"+ reverse = revcomp(sequence[10:])+ args = inputs(tmp_path, {"target": sequence}, expected=False, reverse=reverse)+ report, code = execute(args + ["--min-product", "1"])+ assert code == 0+ assert report["pairs"][0]["product_count"] == 0+ assert report["pairs"][0]["hit_count"] == 2+++def test_circular_product_across_origin(tmp_path):+ sequence = SPACER[:30] + revcomp(R) + SPACER[30:60] + F+ args = inputs(tmp_path, {"target": sequence})+ (tmp_path / "expected.tsv").write_text("pair_id\trecord_id\tstart\tend\np1\ttarget\t80\t150\n")+ report, code = execute(args + ["--circular", "target"])+ assert code == 0+ product, = report["pairs"][0]["products"]+ assert (product["start"], product["end"], product["length"]) == (80, 150, 70)+ assert product["wraps_origin"]+ assert product["classification"] == "intended"+++def test_circular_binding_site_can_cross_origin(tmp_path):+ sequence = TARGET[10:] + TARGET[:10]+ args = inputs(tmp_path, {"target": sequence})+ (tmp_path / "expected.tsv").write_text("pair_id\trecord_id\tstart\tend\np1\ttarget\t110\t230\n")+ report, code = execute(args + ["--circular", "target"])+ assert code == 0+ assert report["pairs"][0]["products"][0]["length"] == 120+ assert any(h["wraps_origin"] for h in report["pairs"][0]["hits"])+++def test_tails_affect_product_length_but_not_binding(tmp_path):+ report, code = execute(inputs(tmp_path, tails=("GCGC", "ATATAT")))+ assert code == 0+ product, = report["pairs"][0]["products"]+ assert (product["length"], product["length_with_tails"]) == (120, 130)++[email protected]("limit", ["--max-comparisons", "--max-hits"])+def test_resource_caps_fail_closed(tmp_path, limit):+ report, code = execute(inputs(tmp_path) + [limit, "1"])+ assert code == 2+ assert report["status"] == "incomplete"+ assert not report["complete_within_model"]+ assert report["issues"]+++def test_product_cap_discards_completed_claim(tmp_path):+ report, code = execute(inputs(tmp_path, {"target": TARGET, "offtarget": TARGET}) + ["--max-products", "1"])+ assert code == 2 and report["status"] == "incomplete"++[email protected]("extra", [+ ["--max-mismatches", "-1"], ["--min-product", "200", "--max-product", "100"],+ ["--three-prime-bases", "21"], ["--circular", "missing"],+])+def test_invalid_settings_fail_closed(tmp_path, extra):+ report, code = execute(inputs(tmp_path) + extra)+ assert code == 2 and report["status"] == "incomplete"+++def test_unknown_expected_reference_fails_closed(tmp_path):+ args = inputs(tmp_path)+ (tmp_path / "expected.tsv").write_text("pair_id\trecord_id\tstart\tend\np1\tmissing\t0\t120\n")+ report, code = execute(args)+ assert code == 2 and report["status"] == "incomplete"+++def test_cli_writes_failure_report(tmp_path):+ code = main(inputs(tmp_path) + ["--max-comparisons", "1"])+ assert code == 2+ report = json.loads((tmp_path / "screen.json").read_text())+ assert report["status"] == "incomplete"+++def test_output_cannot_replace_input(tmp_path):+ args = inputs(tmp_path)+ original = (tmp_path / "pairs.tsv").read_text()+ assert main(args + ["--output", str(tmp_path / "pairs.tsv")]) == 2+ assert (tmp_path / "pairs.tsv").read_text() == original+++def test_tool_failure_and_timeout_fail_closed(monkeypatch):+ def failure(*args, **kwargs):+ raise subprocess.CalledProcessError(3, args[0], stderr="fixture failure")+ monkeypatch.setattr(subprocess, "run", failure)+ with pytest.raises(SearchIncomplete, match="exit 3"):+ run_tool(["fake-blastn", "-version"], 1)+ def timeout(*args, **kwargs):+ raise subprocess.TimeoutExpired(args[0], 1)+ monkeypatch.setattr(subprocess, "run", timeout)+ with pytest.raises(SearchIncomplete, match="timed out"):+ run_tool(["fake-blastn", "-version"], 1)+++HAS_BLAST = bool(shutil.which("blastn") and shutil.which("makeblastdb"))++[email protected](not HAS_BLAST, reason="Requires local NCBI BLAST+ executables")+def test_real_blast_finds_intended_and_second_product(tmp_path):+ report, code = execute(inputs(tmp_path, {"target": TARGET, "paralog": TARGET}) + ["--engine", "blast"])+ assert code == 0, report["issues"]+ assert report["status"] == "potential_off_target"+ assert not report["exhaustive"] and not report["complete_within_model"]+ assert report["discovery_completed"]+ assert report["pairs"][0]["product_count"] == 2+ assert "blastn:" in report["provenance"]["tools"]["blastn"]["version"]++[email protected](not HAS_BLAST, reason="Requires local NCBI BLAST+ executables")+def test_real_blast_rechecks_clipped_three_prime_mismatch(tmp_path):+ off = F[:-1] + "C" + SPACER + revcomp(R)+ args = inputs(tmp_path, {"target": TARGET, "clipped_mismatch": off}) + ["--engine", "blast", "--max-mismatches", "1"]+ strict, code = execute(args)+ assert code == 0, strict["issues"]+ assert strict["pairs"][0]["potential_off_target_count"] == 0+ permissive, code = execute(args + ["--max-three-prime-mismatches", "1"])+ assert code == 0, permissive["issues"]+ assert permissive["pairs"][0]["potential_off_target_count"] == 1++[email protected](not HAS_BLAST, reason="Requires local NCBI BLAST+ executables")+def test_real_blast_rechecks_clipped_reverse_primer(tmp_path):+ off = F + SPACER + revcomp(R[:-1] + "A")+ args = inputs(tmp_path, {"target": TARGET, "clipped_reverse": off}) + ["--engine", "blast", "--max-mismatches", "1"]+ strict, code = execute(args)+ assert code == 0, strict["issues"]+ assert strict["pairs"][0]["potential_off_target_count"] == 0+ permissive, code = execute(args + ["--max-three-prime-mismatches", "1"])+ assert code == 0, permissive["issues"]+ assert permissive["pairs"][0]["potential_off_target_count"] == 1++[email protected](not HAS_BLAST, reason="Requires local NCBI BLAST+ executables")+def test_real_blast_hsp_limit_fails_closed(tmp_path):+ args = inputs(tmp_path, {"target": TARGET + "A" * 30 + TARGET})+ report, code = execute(args + ["--engine", "blast", "--blast-max-hsps", "1"])+ assert code == 2+ assert report["status"] == "incomplete"+ assert any("max_hsps" in issue for issue in report["issues"])++[email protected](not HAS_BLAST, reason="Requires local NCBI BLAST+ executables")+def test_real_blast_target_limit_fails_closed(tmp_path):+ args = inputs(tmp_path, {"target": TARGET, "paralog": TARGET})+ report, code = execute(args + ["--engine", "blast", "--blast-max-target-seqs", "1"])+ assert code == 2+ assert report["status"] == "incomplete"+ assert any("max_target_seqs" in issue for issue in report["issues"])++[email protected](not HAS_BLAST, reason="Requires local NCBI BLAST+ executables")+def test_real_blast_circular_binding_and_product(tmp_path):+ sequence = TARGET[10:] + TARGET[:10]+ args = inputs(tmp_path, {"target": sequence})+ (tmp_path / "expected.tsv").write_text("pair_id\trecord_id\tstart\tend\np1\ttarget\t110\t230\n")+ report, code = execute(args + ["--engine", "blast", "--circular", "target"])+ assert code == 0, report["issues"]+ assert report["pairs"][0]["products"][0]["classification"] == "intended"+++def test_missing_blast_executable_fails_closed(tmp_path):+ report, code = execute(inputs(tmp_path) + ["--engine", "blast", "--blastn", "nonexistent-primer-test-blastn"])+ assert code == 2+ assert report["status"] == "incomplete"+++F2 = "GATCCAGTTCGACGATGTCA"+R2 = "CGTAGCTACCGTATGACGTC"+++def panel_inputs(tmp_path, cross_roles=None):+ references = {"target": TARGET, "target2": F2 + SPACER + revcomp(R2)}+ if cross_roles:+ second = F2 if cross_roles == "F/F" else R2+ references["cross_product"] = F + SPACER + revcomp(second)+ args = inputs(tmp_path, references, tails=("AAA", "CCC"))+ with (tmp_path / "pairs.tsv").open("a") as handle:+ handle.write(f"p2\t{F2}\t{R2}\tGGG\tTTT\n")+ with (tmp_path / "expected.tsv").open("a") as handle:+ handle.write("p2\ttarget2\t0\t120\n")+ return args++[email protected]("cross_roles", ["F/F", "F/R"])+def test_multiplex_detects_cross_product_despite_individually_clean_pairs(tmp_path, cross_roles):+ args = panel_inputs(tmp_path, cross_roles)+ individual, code = execute(args)+ assert code == 0 and individual["status"] == "no_off_target_found_within_search_scope"+ report, code = execute(args + ["--multiplex"])+ assert code == 0 and report["status"] == "potential_off_target"+ originals = [pair for pair in report["pairs"] if not pair["cross_pair"]]+ assert originals == individual["pairs"]+ generated = [pair for pair in report["pairs"] if pair["cross_pair"]]+ assert len(generated) == 4+ cross_pair, = [pair for pair in generated if pair["product_count"]]+ product, = cross_pair["products"]+ assert product["classification"] == "potential_off_target"+ assert product["source_primer_roles"] == cross_roles+ assert product["left_source_oligo_id"] == "p1:F"+ assert product["right_source_oligo_id"] == "p2:" + cross_roles[-1]+ assert product["cross_pair"]+ assert product["length_with_tails"] == 126+ assert cross_pair["source_oligos"]["F"]["tail_5prime"] == "AAA"+ assert cross_pair["source_oligos"]["R"]["tail_5prime"] == ("GGG" if cross_roles == "F/F" else "TTT")+ assert all(pair["status"] != "no_expected_target" for pair in generated)+++def test_multiplex_with_no_cross_products_has_scoped_clear_result(tmp_path):+ report, code = execute(panel_inputs(tmp_path) + ["--multiplex"])+ assert code == 0 and report["status"] == "no_off_target_found_within_search_scope"+ assert len(report["pairs"]) == 6+ assert all(pair["product_count"] == 0 for pair in report["pairs"] if pair["cross_pair"])+ assert report["provenance"]["panel"]["cross_pair_count"] == 4+++def test_multiplex_still_requires_original_expected_targets(tmp_path):+ args = panel_inputs(tmp_path)+ (tmp_path / "expected.tsv").write_text("pair_id\trecord_id\tstart\tend\np1\ttarget\t0\t120\n")+ report, code = execute(args + ["--multiplex"])+ assert code == 0 and report["status"] == "no_expected_target"+ assert next(pair for pair in report["pairs"] if pair["pair_id"] == "p2")["status"] == "no_expected_target"+++def test_expected_manifest_cannot_whitelist_generated_cross_pairs(tmp_path):+ args = panel_inputs(tmp_path, "F/F")+ with (tmp_path / "expected.tsv").open("a") as handle:+ handle.write("multiplex-cross-000001\tcross_product\t0\t120\n")+ report, code = execute(args + ["--multiplex"])+ assert code == 2 and report["status"] == "incomplete"+ assert "Unknown pair_id" in report["issues"][0]+++def test_multiplex_combination_cap_fails_before_search(tmp_path, monkeypatch):+ import screen_specificity+ def unexpected_search(*args, **kwargs):+ raise AssertionError("Binding search must not begin after panel cap exceeded")+ monkeypatch.setattr(screen_specificity, "exhaustive_hits", unexpected_search)+ report, code = execute(panel_inputs(tmp_path) + ["--multiplex", "--max-panel-combinations", "3"])+ assert code == 2 and report["status"] == "incomplete"+ assert "4 cross-oligo combinations" in report["issues"][0]+ assert not report["pairs"]+++def test_multiplex_uses_single_deduplicated_binding_search(tmp_path, monkeypatch):+ import screen_specificity+ original = screen_specificity.exhaustive_hits+ searches = []+ def counting_search(primers, *args, **kwargs):+ searches.append(tuple(primers))+ return original(primers, *args, **kwargs)+ monkeypatch.setattr(screen_specificity, "exhaustive_hits", counting_search)+ report, code = execute(panel_inputs(tmp_path, "F/R") + ["--multiplex"])+ assert code == 0+ assert len(searches) == 1+ assert set(searches[0]) == {F, R, F2, R2}+ assert report["provenance"]["panel"]["unique_annealing_cores_searched"] == 4+++def test_panel_expansion_is_deterministic_collision_safe_and_does_not_mutate():+ originals = [+ {"pair_id": "multiplex-cross-000001", "forward": F, "reverse": R},+ {"pair_id": "p2", "forward": F2, "reverse": R2},+ ]+ before = json.dumps(originals, sort_keys=True)+ first = expand_panel_pairs(originals, 4)+ second = expand_panel_pairs(list(reversed(originals)), 4)+ assert json.dumps(originals, sort_keys=True) == before+ assert first[2:] == second[2:]+ assert len({pair["pair_id"] for pair in first}) == 6+++def test_specificity_output_cannot_replace_hardlinked_input(tmp_path):+ args = inputs(tmp_path)+ original = (tmp_path / "pairs.tsv").read_text()+ alias = tmp_path / "alias.json"+ alias.hardlink_to(tmp_path / "pairs.tsv")+ assert main(args + ["--output", str(alias)]) == 2+ assert (tmp_path / "pairs.tsv").read_text() == original+ assert alias.read_text() == originaldiff --git a/tests/skill-requirements.toml b/tests/skill-requirements.tomlindex 65067eb6..956d9c9e 100644--- a/tests/skill-requirements.toml+++ b/tests/skill-requirements.toml@@ -464,6 +464,11 @@ packages = [][skills.biopython]packages = ["biopython", "matplotlib", "numpy", "reportlab"]+# Primer design and nearest-neighbor thermodynamics; BLAST+ is an optional system tool.+[skills.primer-design]+python = "3.13"+packages = ["primer3-py==2.3.1"]+[skills.pysam]packages = ["pysam"]