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
Add bounded NCATS ARAX knowledge graph skill
neuroepithelial550b965a693b
diff --git a/README.md b/README.mdindex d3134557..958a1013 100644--- a/README.md+++ b/README.md@@ -2,7 +2,7 @@[](LICENSE.md)[](pyproject.toml)-[](#-whats-included)+[](#-whats-included)[](#-whats-included)[](https://agentskills.io/)[](https://github.com/K-Dense-AI/scientific-agent-skills/actions/workflows/security-scan.yml)@@ -24,11 +24,11 @@> **🔔 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 159 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 161 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)> **Stay up to date:** Follow K-Dense on [X](https://x.com/k_dense_ai), [LinkedIn](https://www.linkedin.com/company/k-dense-inc), and [YouTube](https://www.youtube.com/@K-Dense-Inc) for new skills, release announcements, walkthroughs, research workflow demos, and examples you can use with your own AI agent.-A comprehensive collection of **159 ready-to-use scientific and research skills** (covering cancer genomics, individual-level 1000 Genomes queries, 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, molecular dynamics, RNA velocity, 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). 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 **161 ready-to-use scientific and research skills** (covering cancer genomics, individual-level 1000 Genomes queries, 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, molecular dynamics, RNA velocity, 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). 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.@@ -63,9 +63,9 @@ These skills enable your AI agent to seamlessly work with specialized scientific## 📦 What's Included-This repository provides **159 scientific and research skills** organized into the following categories:+This repository provides **161 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, U.S. Treasury Fiscal Data, Hugging Science, OneKGPd, and Genomic Intelligence. Multi-database packages like BioServices (~40 bioinformatics services), BioPython (39 NCBI sub-databases via Entrez), and gget (20+ genomics databases) add further coverage+- **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, and Genomic Intelligence. 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- **9 Scientific Integration Skills** - Explicitly defined skills for Benchling, DNAnexus, LatchBio, OMERO, Protocols.io, Open Notebook, Ginkgo Cloud Lab, LabArchives, and Opentrons. Again, the agent is not limited to these — any API or platform reachable from Python is fair game; these skills are the optimized, pre-documented paths- **30+ Analysis & Communication Tools** - Literature review, evidence-traceable scientific writing, confidential peer review, document processing, Paperclip (full-text papers, FDA/PMDA/EMA filings, and trial registries with line-pinned citations), Paperzilla, Exa Search, macro-free PPTX posters, slides, schematics, infographics, Mermaid diagrams, and more@@ -110,7 +110,7 @@ Each skill includes:- **Multi-Step Workflows** - Execute complex pipelines with a single prompt### 🎯 **Comprehensive Coverage**-- **159 Skills** - Extensive coverage across all major scientific domains+- **161 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)@@ -196,7 +196,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 159 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 161 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.@@ -435,7 +435,7 @@ networks, and search GEO for similar patterns.## 📚 Available Skills-This repository contains **159 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 **161 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@@ -551,12 +551,13 @@ This repository contains **159 scientific and research skills** organized across- Citations: Citation Management, pyzotero- Illustration: Generate Image (AI image generation with FLUX.2 Pro and Gemini 3.1 Flash Image / Nano Banana 2)-#### 🔬 **Scientific Databases & Data Access** (10 skills → 100+ databases total)+#### 🔬 **Scientific Databases & Data Access** (11 skills → 100+ databases total)> A unified database-lookup skill provides deterministic REST API access to 78 public databases across all domains, with retrieval contracts, pagination/count reconciliation, and endpoint provenance. Dedicated skills cover specialized data platforms. Multi-database packages like BioServices (~40 bioinformatics services), BioPython (39 NCBI sub-databases via Entrez), and gget (20+ genomics databases) add further coverage.- Unified access: Database Lookup (78 databases spanning chemistry, genomics, clinical, pathways, patents, economics, and more — PubChem, ChEMBL, UniProt, PDB, AlphaFold, KEGG, Reactome, STRING, ClinVar, COSMIC, ClinicalTrials.gov, FDA, FRED, USPTO, SEC EDGAR, and dozens more — with auditable filters and provenance)- Cancer genomics: DepMap (cancer cell line dependencies, drug sensitivity, gene effect profiles)- Cancer imaging: Imaging Data Commons (NCI radiology & pathology datasets via idc-index)- Knowledge graph: PrimeKG (precision medicine knowledge graph — genes, drugs, diseases, phenotypes)+- Biomedical knowledge graph search: [NCATS ARAX](skills/ncats-arax/) (bounded, Biolink-constrained one-hop and endpoint-pinned two-hop queries over knowledge graphs with up to five explicitly selected NCATS Translator providers, with provenance preservation)- Fiscal data: U.S. Treasury Fiscal Data (national debt, Treasury statements, auctions, exchange rates)- Scientific ML resource catalog: Hugging Science (curated index of datasets, models, blog posts, and interactive Spaces across 17 scientific domains — astronomy, biology, chemistry, climate, genomics, materials science, medicine, physics, scientific reasoning, and more — with usage patterns for `datasets`, `transformers`, and `gradio_client`)- Individual-level population genomics: OneKGPd (3,202-person high-coverage 1000 Genomes cohort queries)@@ -829,7 +830,7 @@ Recommended practice:title = {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 = {159 skills covering databases, packages, integrations, and analysis tools}+ note = {161 skills covering databases, packages, integrations, and analysis tools}}```diff --git a/skills/ncats-arax/SKILL.md b/skills/ncats-arax/SKILL.mdnew file mode 100644index 00000000..cc2cf7b9--- /dev/null+++ b/skills/ncats-arax/SKILL.md@@ -0,0 +1,178 @@+---+name: ncats-arax+description: Queries the NCATS Translator ARAX production API for bounded, typed, provenance-rich one-hop and endpoint-pinned two-hop biomedical knowledge-graph relationships. Use for Biolink-constrained RTX-KG2 lookup, explicit selected-provider ARAX federation, separate entity normalization, qualifier-aware graph traversal, and inspection of TRAPI edge bindings, publications, and knowledge-source provenance. Do not use for inference, ranking, open-ended pathfinding, clinical guidance, or sensitive queries.+allowed-tools: Read Bash+license: MIT+compatibility: Requires Python 3.10+ and outbound HTTPS access to arax.transltr.io. The client uses only the Python standard library and needs no API key. Queries and caller metadata may be publicly visible; never submit sensitive or patient-specific content.+metadata:+ version: "1.0"+ skill-author: neuroepithelial+---++# NCATS ARAX++Use ARAX as a constrained knowledge-graph lookup service. Submit reviewed CURIEs and explicit+Biolink types, preserve the exact TRAPI exchange, inspect query-edge bindings and provenance, and+treat every returned path as a candidate for subsequent verification.++Read [query-contract.md](references/query-contract.md) before constructing a query. Read+[output-schema.md](references/output-schema.md) when interpreting saved artifacts, warnings,+provenance, or partial results.++## Safety boundary++- Use only public, nonsensitive research questions. ARAX status facilities may expose query and+ caller metadata even when `store=false` is requested.+- Do not submit patient information, confidential research questions, unpublished compound+ programs, or proprietary target hypotheses.+- Do not present a returned path as a validated mechanism or clinical recommendation.+- Report a zero as "not returned under these constraints," never as evidence that no relationship+ exists.+- Describe position as unscored response order, never rank.+- Verify important candidates with literature and authoritative databases separately.++## Workflow++1. Normalize free text separately, then review and report the proposed CURIE and category.+2. Choose a typed one-hop query or an exactly two-hop query with both endpoints pinned.+3. Use default RTX-KG2 lookup unless the user explicitly names two to five providers.+4. Acknowledge that the biomedical query is public and choose a new or empty output directory.+5. Run the client once. Do not silently change provider selection or expansion order after a+ failure or empty result.+6. Inspect `summary.json` for bounded bindings and provenance and `response.json` for the exact+ TRAPI payload.+7. Verify scientifically important paths outside ARAX.++## Preflight++Check the production OpenAPI without making a biomedical query:++```bash+python skills/ncats-arax/scripts/arax_client.py preflight+```++The client verifies that the service identifies itself as ARAX, exposes `/query`, and reports a+supported TRAPI version. A nonproduction endpoint or untested TRAPI series requires an explicit+override; neither override changes the fixed query shapes or operations.++## Normalize an entity++Normalization is review-only and never triggers a graph query:++```bash+python skills/ncats-arax/scripts/arax_client.py normalize "primary myelofibrosis" \+ --expected-category biolink:Disease \+ --max-synonyms 10 \+ --acknowledge-public-query \+ --output-dir outputs/normalize-myelofibrosis+```++Review the canonical identifier, name, category, and synonym preview before using a CURIE. Report+all CURIEs and categories regardless of query outcome. A category warning or zero result is a+reason to curate the identifier, not to chain automatically to `/query`.++## One-hop lookup++Pin at least one endpoint and type both nodes:++```bash+python skills/ncats-arax/scripts/arax_client.py one-hop \+ --subject-id CHEBI:31690 \+ --subject-category biolink:SmallMolecule \+ --predicate biolink:affects \+ --object-id NCBIGene:25 \+ --object-category biolink:Gene \+ --qualifier biolink:object_aspect_qualifier=activity_or_abundance \+ --qualifier biolink:object_direction_qualifier=decreased \+ --acknowledge-public-query \+ --output-dir outputs/imatinib-abl1+```++Lookup mode is the default and fixes expansion to `infores:rtx-kg2`. It defaults to 20 results.+Use `--result-limit N` to request 1-50 results; 50 is the hard cap in either mode.++## Endpoint-pinned two-hop lookup++Use exactly one typed, unpinned intermediate node:++```bash+python skills/ncats-arax/scripts/arax_client.py two-hop \+ --subject-id CHEBI:66901 \+ --subject-category biolink:SmallMolecule \+ --predicate-1 biolink:affects \+ --intermediate-category biolink:Gene \+ --predicate-2 biolink:associated_with \+ --object-id MONDO:0009061 \+ --object-category biolink:Disease \+ --qualifier-1 biolink:object_aspect_qualifier=activity_or_abundance \+ --qualifier-1 biolink:object_direction_qualifier=increased \+ --expand-order right-first \+ --acknowledge-public-query \+ --output-dir outputs/ivacaftor-cystic-fibrosis+```++Right-first expansion is the default. If an empty result merits another attempt, run a new query+explicitly with `--expand-order left-first` and keep the runs separate.++## Selected-provider federation++Federation is explicit and accepts two to five named providers:++```bash+python skills/ncats-arax/scripts/arax_client.py one-hop \+ --subject-id CHEBI:31690 \+ --subject-category biolink:SmallMolecule \+ --predicate biolink:affects \+ --object-id NCBIGene:25 \+ --object-category biolink:Gene \+ --mode federated \+ --kp infores:rtx-kg2 \+ --kp infores:molepro \+ --acknowledge-public-query \+ --output-dir outputs/federated-imatinib-abl1+```++Federation defaults to the hard maximum of 50 results. Provider errors may coexist with useful+results; such a run exits 7 after retaining its artifacts and is marked partial.++## Inspect saved provenance++Rebuild a bounded summary without network access:++```bash+python skills/ncats-arax/scripts/arax_client.py summarize \+ --request outputs/ivacaftor-cystic-fibrosis/request.json \+ --response outputs/ivacaftor-cystic-fibrosis/response.json \+ --format text+```++The inspector accepts only the same constrained request shapes and fixed operations that the live+commands generate. Use `--format json` for the normalized view on standard output.++## Interpret results++- Follow each analysis's query-edge bindings; do not summarize every knowledge-graph edge.+- Preserve the physical edge subject, predicate, object, and qualifier values returned by ARAX.+ Returned predicates or qualifier aspects may be more specific than the query constraint.+- Inspect all source objects, including primary, aggregator, supporting-data, upstream-resource,+ and source-record URL fields.+- Treat `publication_availability: not_returned` as missing metadata, not evidence that no+ publications exist.+- Treat missing auxiliary-graph references and provider failures as explicit warnings.+- Consult the raw response whenever the bounded summary omits detail or the service response is+ partial, unfamiliar, or scientifically surprising.++## Deliberate exclusions++The client has no raw-query, workflow, operation, overlay, ranking, inference, link-prediction,+Pathfinder, ARS, batch, all-provider, three-hop, cache, daemon, SDK, MCP, or+natural-language-to-TRAPI surface. Do not work around those limits with direct HTTP calls under+this skill.++## Official references++- [ARAX documentation](https://ncatstranslator.github.io/TranslatorTechnicalDocumentation/architecture/ara/arax/)+- [ARAX production OpenAPI](https://arax.transltr.io/api/arax/v1.4/openapi.json)+- [ARAXi operation documentation](https://github.com/RTXteam/RTX/blob/master/code/ARAX/Documentation/DSL_Documentation.md)+- [Translator Reasoner API](https://github.com/NCATSTranslator/ReasonerAPI)+- [Biolink Model](https://biolink.github.io/biolink-model/)diff --git a/skills/ncats-arax/references/output-schema.md b/skills/ncats-arax/references/output-schema.mdnew file mode 100644index 00000000..42f90628--- /dev/null+++ b/skills/ncats-arax/references/output-schema.md@@ -0,0 +1,186 @@+# ARAX artifact and output contract++## Contents++- [Artifact sets](#artifact-sets)+- [Exact byte preservation](#exact-byte-preservation)+- [Query summary](#query-summary)+- [Normalization and preflight summaries](#normalization-and-preflight-summaries)+- [Provenance interpretation](#provenance-interpretation)+- [Truncation and completeness](#truncation-and-completeness)+- [Manifest](#manifest)+- [Warnings and exit codes](#warnings-and-exit-codes)++## Artifact sets++Every graph query requires a new or empty output directory and writes:++```text+request.json+response.json+summary.json+manifest.json+```++Normalization writes the exact entity response, a bounded normalization summary, and a manifest.+Preflight writes the exact OpenAPI response, a service summary, and a manifest only when an output+directory is requested. GET commands do not create a fictitious `request.json`; the corresponding+manifest file, byte, and hash fields are null. Offline `summarize` writes nothing.++Reject an existing nonempty directory before network access. Write artifacts through a private+temporary file, flush and `fsync`, set mode `0600` where supported, and atomically replace the final+path. Write the manifest last.++## Exact byte preservation++Serialize a POST body once with sorted keys, compact separators, UTF-8, and `ensure_ascii=False`.+Save and send that same byte string. Request `Accept-Encoding: identity`, save the raw response+before JSON parsing, and hash request and response bytes with SHA-256.++Read at most 26,214,401 response bytes. If the extra byte exists, treat the response as oversized,+save no partial `response.json`, retain the request when applicable, write a terminal manifest, and+exit 6. A bounded HTTP-error body is preserved exactly. A bounded malformed JSON response is also+preserved, but no misleading summary is produced.++## Query summary++`summary.json` is a normalized bounded view; `response.json` remains authoritative.++```json+{+ "schema_version": "1.0",+ "query": {+ "kind": "one-hop|two-hop",+ "mode": "lookup|federated",+ "provider_ids": [],+ "expand_order": "right-first|left-first|null",+ "qnode_ids": {},+ "result_limit": 20+ },+ "service": {+ "base_url": null,+ "arax_version": null,+ "trapi_version": null,+ "biolink_version": null+ },+ "counts": {+ "results_returned": 0,+ "results_summarized": 0,+ "analyses_summarized": 0,+ "bound_edges_summarized": 0,+ "knowledge_graph_nodes": 0,+ "knowledge_graph_edges": 0,+ "server_total_results_count": null+ },+ "truncation_status": "no|possible|confirmed",+ "completeness": "complete|partial|unknown",+ "results": [],+ "warnings": []+}+```++Keep response order. A result contains its one-based unscored `position`, bounded description,+normalized node bindings, and separate analyses. Each analysis contains its resource ID, returned+score, support-graph IDs, and bound-edge objects grouped by query-edge key.++A bound-edge object contains the returned edge ID, physical subject/predicate/object and names,+query-direction match flag, qualifiers, full source objects, role-derived source ID lists,+publication IDs and availability, and support-graph IDs and status.++## Normalization and preflight summaries++A normalization summary records the input, expected category, whether free-text confirmation is+required, service versions, canonical identifier/name/category, category-count mapping, total+synonym count, bounded candidate preview, and warnings.++A preflight summary records service versions plus Boolean checks for ARAX identity, `/query`, and+version compatibility. Neither summary claims graph results.++## Provenance interpretation++Use each analysis's `edge_bindings` to select knowledge-graph edges. Do not include unrelated graph+edges. Preserve multiple analyses separately and retain all entries from each bound edge's+`sources`, including `resource_id`, `resource_role`, `upstream_resource_ids`, and+`source_record_urls`. Derive unique, first-seen resource ID lists for primary, aggregator, and+supporting-data roles without discarding the full objects.++Preserve returned qualifiers as type/value pairs. Preserve physical edge direction and set+`matches_query_direction: false` rather than rewriting a reversed edge.++V1 recognizes `biolink:publications` edge attributes. Accept a string or list of strings and+deduplicate in first-seen order. Missing recognized metadata means:++```text+publication_ids: []+publication_availability: not_returned+```++It never means that no publications exist.++Use `analysis.support_graphs` as the support-graph references. If none are returned, report+`not_returned`; if all appear in `message.auxiliary_graphs`, report `available`; if a referenced ID+is absent, report `missing` and warn.++## Truncation and completeness++- Fewer results than the requested limit: `no`, unless logs or counts show removal.+- Exactly the limit: `possible` and `RESULT_LIMIT_REACHED`.+- More than the limit, an explicit pruning/removal log, or a larger server total: `confirmed`.++Keep only the first requested number of results in the normalized summary while preserving the+entire size-bounded raw response.++Federated KP timeout, provider error, or malformed-provider evidence yields `completeness: partial`,+`result_status: partial`, retained artifacts, and exit 7. Otherwise a valid parsed response is+`complete`; raw malformed responses produce no summary.++## Manifest++The manifest records run UUID, UTC timestamps, command, execution/result status, privacy+acknowledgment, fixed client identity, service versions, request/response method, URL, filenames,+byte counts, hashes, elapsed time, applied limits, attempt counts, artifact names, bounded error,+and warnings. Fields for artifacts that do not exist are null rather than false filenames.++Execution statuses are `success`, `http_error`, and `client_error`. Result statuses are `results`,+`no_results`, `partial`, and `not_available`.++## Warnings and exit codes++Warnings are objects with a stable `code`, bounded sanitized `message`, and a small scalar+`context`. Supported codes:++```text+PUBLIC_QUERY+NORMALIZATION_REQUIRES_CONFIRMATION+NORMALIZATION_CATEGORY_MISMATCH+NO_RESULTS+NO_PUBLICATIONS_RETURNED+NO_PRIMARY_SOURCE_RETURNED+UNSCORED_RESPONSE_ORDER+RESULT_LIMIT_REACHED+INTERNAL_PRUNING_DETECTED+KP_TIMEOUT+KP_ERROR+MALFORMED_KP_RESPONSE+MISSING_AUXILIARY_GRAPH+REVERSED_EDGE_BINDING+UNTESTED_SERVICE_VERSION+NONPRODUCTION_ENDPOINT+```++Exit codes:++| Code | Meaning |+| ---: | --- |+| 0 | Complete success, including a valid zero-result graph response |+| 2 | Invalid CLI input, unsupported saved request, or local validation failure |+| 3 | Service preflight or unsupported-version failure |+| 4 | Normalization returned no usable result |+| 5 | Transport or HTTP failure |+| 6 | Malformed, oversized, or artifact-integrity failure |+| 7 | Partial federated response with retained artifacts |++Text output prints at most the bounded result set and ten publication IDs per edge, labels every+position unscored, includes all source-role IDs, and points to `summary.json` and `response.json`.+Use "ARAX returned" and "not returned under these constraints," never proof, absence, or ranking+language.diff --git a/skills/ncats-arax/references/query-contract.md b/skills/ncats-arax/references/query-contract.mdnew file mode 100644index 00000000..58facedd--- /dev/null+++ b/skills/ncats-arax/references/query-contract.md@@ -0,0 +1,140 @@+# ARAX query contract++## Contents++- [Service boundary](#service-boundary)+- [Supported query shapes](#supported-query-shapes)+- [Validation](#validation)+- [Fixed operations](#fixed-operations)+- [Limits and retries](#limits-and-retries)+- [Version and endpoint policy](#version-and-endpoint-policy)+- [Excluded escape hatches](#excluded-escape-hatches)++## Service boundary++Use `https://arax.transltr.io/api/arax/v1.4` by default. A networked command first retrieves+`/openapi.json`, verifies an ARAX title and `/query`, and records the advertised ARAX and TRAPI+versions. Normalization uses `/entity`; graph lookup uses `/query`.++Every normalization or graph request requires `--acknowledge-public-query`. This is an explicit+acknowledgment that query and caller metadata may be visible through service facilities. The+`store=false` operation reduces intentional response storage but is not a privacy guarantee.++## Supported query shapes++### One hop++Use two qnodes (`n0`, `n1`) and one qedge (`e0`). Require one category on each qnode, one to five+predicates, and at least one pinned endpoint. Each qnode has at most one CURIE. Omit `ids` from an+unpinned qnode.++### Two hops++Use three qnodes (`n0`, `n1`, `n2`) and two qedges (`e0`, `e1`). Pin `n0` and `n2` with exactly one+CURIE each. Type every qnode. Keep `n1` unpinned. Each edge has one to five predicates.++For either shape, an edge may have zero to six qualifiers. Combine them in one+`qualifier_constraints` entry containing one AND-conjoined `qualifier_set`. Omit the whole field+when no qualifier is supplied. Do not repeat a qualifier type on the same edge.++## Validation++CURIEs follow this conservative form:++```text+^[A-Za-z][A-Za-z0-9._-]*:[^\s]+$+```++They must be no more than 200 characters and contain no controls, NUL, tabs, or newlines.++Categories, predicates, and qualifier types follow:++```text+^biolink:[A-Za-z][A-Za-z0-9._-]*$+```++Provider identifiers are interpolated into an ARAXi action and therefore use the stricter form:++```text+^infores:[A-Za-z0-9._-]+$+```++Do not maintain a local Biolink model or provider registry. Shape validation is local; ARAX remains+the semantic authority. Reject duplicate predicates, qualifier types, provider IDs, and repeated+scalar endpoint options.++## Fixed operations++Lookup mode fixes the provider to `infores:rtx-kg2`. Federated mode requires two to five explicit,+distinct provider identifiers and emits them in one list-valued `kp=` argument. Never omit `kp` and+never generate duplicate `kp=` arguments.++One hop expands `e0`. Two-hop right-first expands `e1` and then `e0`; left-first reverses only those+two actions. Append exactly:++```text+scoreless_resultify(ignore_edge_direction=true)+filter_results(action=limit_number_of_results,max_results=<1-50>,prune_kg=true)+return(response=true,store=false)+```++Each expansion fixes:++```text+kp_timeout=30,return_minimal_metadata=false+```++Always send `stream_progress: false` and the constant submitter+`scientific-agent-skills-ncats-arax`. Never put a user name, project name, or query term into the+submitter or User-Agent.++## Limits and retries++| Control | Value |+| --- | ---: |+| OpenAPI/entity HTTP timeout | 30 seconds |+| Lookup query HTTP timeout | 120 seconds |+| Federated query HTTP timeout | 180 seconds |+| ARAX KP timeout | 30 seconds |+| Lookup default result limit | 20 |+| Federated default result limit | 50 |+| Hard result limit | 50 |+| Provider count | 2-5 in federation |+| Predicates per edge | 1-5 |+| Qualifiers per edge | 0-6 |+| Raw response limit | 25 MiB (26,214,400 bytes) |++Retry OpenAPI and entity GET requests once after HTTP 429, 502, 503, 504, or a transport timeout.+Honor `Retry-After` for at most 10 seconds; otherwise wait one second. Never retry POST `/query`.+A failed POST may have been processed and must be rerun only by an explicit user decision.++Use these headers:++```text+Accept: application/json+Accept-Encoding: identity+Content-Type: application/json # POST only+User-Agent: scientific-agent-skills-ncats-arax/1.0+```++## Version and endpoint policy++The tested target is ARAX 1.5.4 with TRAPI 1.5.0. Parse the common response fields for TRAPI 1.5+and 1.6, warning whenever the version is not the tested value. Refuse an unknown or missing TRAPI+series unless `--allow-untested-version` is explicit. Record `biolink_version` from each query+response rather than assuming it.++Accept only HTTPS base URLs without credentials, query strings, or fragments. Reject localhost and+literal private, loopback, link-local, or reserved addresses. A URL other than the production base+requires `--allow-nonproduction-endpoint`, must still identify ARAX through OpenAPI, and receives a+warning. Reject cross-origin and protocol-downgrade redirects. Never fall back automatically to+`arax.ncats.io` or another ARA.++## Excluded escape hatches++Expose no raw JSON submission, query-file, generic node/edge list, workflow, operations, action,+overlay, ranking, inference, creative-query, link-prediction, Pathfinder, ARS, all-provider,+batching, stdin-list, cache, database, daemon, server, SDK, MCP, or third-hop option.++The offline summarizer validates the saved request against this same topology and operation+contract. It refuses unsupported requests rather than becoming a back door for broader ARAX use.diff --git a/skills/ncats-arax/scripts/arax_client.py b/skills/ncats-arax/scripts/arax_client.pynew file mode 100644index 00000000..4f8ea36c--- /dev/null+++ b/skills/ncats-arax/scripts/arax_client.py@@ -0,0 +1,2087 @@+#!/usr/bin/env python3+"""Bounded, provenance-preserving client for the NCATS Translator ARAX API."""++from __future__ import annotations++import argparse+import email.utils+import hashlib+import ipaddress+import json+import os+import re+import socket+import sys+import tempfile+import time+import urllib.error+import urllib.parse+import urllib.request+import uuid+from dataclasses import dataclass+from datetime import datetime, timezone+from pathlib import Path+from typing import Any, Callable, Iterable, Mapping, Sequence+++CLIENT_NAME = "ncats-arax"+CLIENT_VERSION = "1.0"+USER_AGENT = "scientific-agent-skills-ncats-arax/1.0"+SUBMITTER = "scientific-agent-skills-ncats-arax"+PRODUCTION_BASE_URL = "https://arax.transltr.io/api/arax/v1.4"+TESTED_ARAX_VERSION = "1.5.4"+TESTED_TRAPI_VERSION = "1.5.0"+SUPPORTED_TRAPI_SERIES = {"1.5", "1.6"}++GET_TIMEOUT_SECONDS = 30+LOOKUP_TIMEOUT_SECONDS = 120+FEDERATED_TIMEOUT_SECONDS = 180+KP_TIMEOUT_SECONDS = 30+LOOKUP_RESULT_LIMIT = 20+FEDERATED_RESULT_LIMIT = 50+MAX_RESULT_LIMIT = 50+MAX_PROVIDERS = 5+MIN_FEDERATED_PROVIDERS = 2+MAX_PREDICATES = 5+MAX_QUALIFIERS = 6+MAX_IDENTIFIER_LENGTH = 200+MAX_RESPONSE_BYTES = 25 * 1024 * 1024+MAX_WARNING_MESSAGE = 500+MAX_DISPLAY_TEXT = 500+PUBLICATION_PREVIEW = 10++RETRYABLE_GET_STATUS = {429, 502, 503, 504}+CURIE_RE = re.compile(r"^[A-Za-z][A-Za-z0-9._-]*:[^\s]+$")+BIOLINK_RE = re.compile(r"^biolink:[A-Za-z][A-Za-z0-9._-]*$")+PROVIDER_RE = re.compile(r"^infores:[A-Za-z0-9._-]+$")+TRAPI_VERSION_RE = re.compile(r"\bTRAPI\s+(\d+\.\d+(?:\.\d+)?)\b", re.IGNORECASE)+EXPAND_RE = re.compile(+ r"^expand\(edge_key=(e[01]),kp=(.+),kp_timeout=30,"+ r"return_minimal_metadata=false\)$"+)+FILTER_RE = re.compile(+ r"^filter_results\(action=limit_number_of_results,max_results=(\d+),"+ r"prune_kg=true\)$"+)++WARNING_CODES = {+ "PUBLIC_QUERY",+ "NORMALIZATION_REQUIRES_CONFIRMATION",+ "NORMALIZATION_CATEGORY_MISMATCH",+ "NO_RESULTS",+ "NO_PUBLICATIONS_RETURNED",+ "NO_PRIMARY_SOURCE_RETURNED",+ "UNSCORED_RESPONSE_ORDER",+ "RESULT_LIMIT_REACHED",+ "INTERNAL_PRUNING_DETECTED",+ "KP_TIMEOUT",+ "KP_ERROR",+ "MALFORMED_KP_RESPONSE",+ "MISSING_AUXILIARY_GRAPH",+ "REVERSED_EDGE_BINDING",+ "UNTESTED_SERVICE_VERSION",+ "NONPRODUCTION_ENDPOINT",+}+++class AraxClientError(Exception):+ """Base error carrying the documented CLI exit classification."""++ def __init__(+ self,+ message: str,+ *,+ exit_code: int,+ kind: str,+ http_status: int | None = None,+ response_body: bytes | None = None,+ attempts: int = 0,+ ) -> None:+ super().__init__(message)+ self.exit_code = exit_code+ self.kind = kind+ self.http_status = http_status+ self.response_body = response_body+ self.attempts = attempts+++class UsageError(AraxClientError):+ def __init__(self, message: str) -> None:+ super().__init__(message, exit_code=2, kind="invalid_input")+++class PreflightError(AraxClientError):+ def __init__(self, message: str, **kwargs: Any) -> None:+ super().__init__(message, exit_code=3, kind="preflight", **kwargs)+++class NormalizationError(AraxClientError):+ def __init__(self, message: str) -> None:+ super().__init__(message, exit_code=4, kind="normalization_no_result")+++class TransportError(AraxClientError):+ def __init__(self, message: str, **kwargs: Any) -> None:+ super().__init__(message, exit_code=5, kind="transport_or_http", **kwargs)+++class ResponseError(AraxClientError):+ def __init__(self, message: str, **kwargs: Any) -> None:+ super().__init__(message, exit_code=6, kind="invalid_response", **kwargs)+++@dataclass(frozen=True)+class HttpResult:+ status: int+ body: bytes+ headers: dict[str, str]+ elapsed_ms: int+ attempts: int+++@dataclass(frozen=True)+class ServiceInfo:+ base_url: str+ openapi_url: str+ arax_version: str | None+ trapi_version: str | None+ warnings: tuple[dict[str, Any], ...]++ def as_dict(self, *, biolink_version: str | None = None) -> dict[str, Any]:+ return {+ "base_url": self.base_url,+ "openapi_url": self.openapi_url,+ "arax_version": self.arax_version,+ "trapi_version": self.trapi_version,+ "biolink_version": biolink_version,+ }+++@dataclass(frozen=True)+class QueryContract:+ kind: str+ mode: str+ provider_ids: tuple[str, ...]+ expand_order: str | None+ qnode_ids: dict[str, list[str]]+ result_limit: int+ query_edges: dict[str, tuple[str, str]]+++class RejectRepeatedValueAction(argparse.Action):+ """Reject repeated scalar flags instead of silently accepting the last value."""++ def __call__(+ self,+ parser: argparse.ArgumentParser,+ namespace: argparse.Namespace,+ values: Any,+ option_string: str | None = None,+ ) -> None:+ if getattr(namespace, self.dest, None) is not None:+ parser.error(f"{option_string} may be supplied only once")+ setattr(namespace, self.dest, values)+++def _sanitize_text(value: Any, limit: int = MAX_DISPLAY_TEXT) -> str:+ text = str(value)+ text = "".join(" " if ord(char) < 32 or ord(char) == 127 else char for char in text)+ text = " ".join(text.split())+ if len(text) > limit:+ return text[: max(0, limit - 1)] + "…"+ return text+++def make_warning(+ code: str,+ message: str,+ context: Mapping[str, Any] | None = None,+) -> dict[str, Any]:+ if code not in WARNING_CODES:+ raise ValueError(f"unknown warning code: {code}")+ safe_context: dict[str, Any] = {}+ for key, value in (context or {}).items():+ if value is None or isinstance(value, (bool, int, float)):+ safe_context[str(key)] = value+ else:+ safe_context[str(key)] = _sanitize_text(value, 200)+ return {+ "code": code,+ "message": _sanitize_text(message, MAX_WARNING_MESSAGE),+ "context": safe_context,+ }+++def _append_warning(+ warnings: list[dict[str, Any]],+ code: str,+ message: str,+ context: Mapping[str, Any] | None = None,+) -> None:+ warning = make_warning(code, message, context)+ identity = (warning["code"], json.dumps(warning["context"], sort_keys=True), warning["message"])+ existing = {+ (item.get("code"), json.dumps(item.get("context", {}), sort_keys=True), item.get("message"))+ for item in warnings+ }+ if identity not in existing:+ warnings.append(warning)+++def _has_control(value: str) -> bool:+ return any(ord(char) < 32 or ord(char) == 127 for char in value)+++def validate_curie(value: str) -> str:+ if not isinstance(value, str) or not value or len(value) > MAX_IDENTIFIER_LENGTH:+ raise UsageError("CURIE must be a nonempty string of at most 200 characters")+ if _has_control(value) or not CURIE_RE.fullmatch(value):+ raise UsageError(f"invalid CURIE: {_sanitize_text(value, 80)}")+ return value+++def _looks_like_curie(value: str) -> bool:+ try:+ validate_curie(value)+ except UsageError:+ return False+ return True+++def validate_biolink_term(value: str, label: str = "Biolink term") -> str:+ if not isinstance(value, str) or len(value) > MAX_IDENTIFIER_LENGTH:+ raise UsageError(f"{label} must be at most 200 characters")+ if _has_control(value) or not BIOLINK_RE.fullmatch(value):+ raise UsageError(f"invalid {label.lower()}: {_sanitize_text(value, 80)}")+ return value+++def validate_provider_id(value: str) -> str:+ if not isinstance(value, str) or len(value) > MAX_IDENTIFIER_LENGTH:+ raise UsageError("provider identifier must be at most 200 characters")+ if _has_control(value) or not PROVIDER_RE.fullmatch(value):+ raise UsageError(f"invalid provider identifier: {_sanitize_text(value, 80)}")+ if value.lower() == "infores:all":+ raise UsageError("all-provider federation is not supported")+ return value+++def _unique(values: Sequence[str], label: str) -> list[str]:+ if len(set(values)) != len(values):+ raise UsageError(f"duplicate {label} values are not allowed")+ return list(values)+++def validate_predicates(values: Sequence[str]) -> list[str]:+ if not 1 <= len(values) <= MAX_PREDICATES:+ raise UsageError("each query edge requires one to five predicates")+ return _unique([validate_biolink_term(value, "Biolink predicate") for value in values], "predicate")+++def parse_qualifiers(values: Sequence[str]) -> list[tuple[str, str]]:+ if len(values) > MAX_QUALIFIERS:+ raise UsageError("each query edge accepts at most six qualifiers")+ parsed: list[tuple[str, str]] = []+ seen_types: set[str] = set()+ for raw in values:+ if "=" not in raw:+ raise UsageError("qualifiers must use TYPE=VALUE")+ qualifier_type, qualifier_value = raw.split("=", 1)+ validate_biolink_term(qualifier_type, "Biolink qualifier type")+ if (+ not qualifier_value+ or len(qualifier_value) > MAX_IDENTIFIER_LENGTH+ or _has_control(qualifier_value)+ ):+ raise UsageError("qualifier values must be nonempty, control-free, and at most 200 characters")+ if qualifier_type in seen_types:+ raise UsageError("a qualifier type may appear only once per edge")+ seen_types.add(qualifier_type)+ parsed.append((qualifier_type, qualifier_value))+ return parsed+++def validate_result_limit(value: int) -> int:+ if not 1 <= value <= MAX_RESULT_LIMIT:+ raise UsageError("result limit must be between 1 and 50")+ return value+++def validate_base_url(value: str, allow_nonproduction: bool) -> tuple[str, list[dict[str, Any]]]:+ raw = value.rstrip("/")+ parts = urllib.parse.urlsplit(raw)+ try:+ parts.port+ except ValueError as exc:+ raise UsageError("base URL contains an invalid port") from exc+ if parts.scheme.lower() != "https" or not parts.hostname:+ raise UsageError("base URL must be an absolute HTTPS URL")+ if parts.username or parts.password or parts.query or parts.fragment:+ raise UsageError("base URL may not contain credentials, a query string, or a fragment")+ hostname = parts.hostname.lower()+ if hostname == "localhost" or hostname.endswith(".localhost"):+ raise UsageError("localhost endpoints are not allowed")+ try:+ address = ipaddress.ip_address(hostname)+ except ValueError:+ address = None+ if address is not None and not address.is_global:+ raise UsageError("private, loopback, link-local, and reserved endpoint addresses are not allowed")+ normalized = urllib.parse.urlunsplit(("https", parts.netloc, parts.path.rstrip("/"), "", ""))+ warnings: list[dict[str, Any]] = []+ if normalized != PRODUCTION_BASE_URL:+ if not allow_nonproduction:+ raise PreflightError(+ "nonproduction endpoint requires --allow-nonproduction-endpoint"+ )+ _append_warning(+ warnings,+ "NONPRODUCTION_ENDPOINT",+ "An explicitly selected nonproduction ARAX endpoint is in use.",+ {"base_url": normalized},+ )+ return normalized, warnings+++def resolve_mode(+ mode: str,+ provider_values: Sequence[str],+ result_limit: int | None,+) -> tuple[list[str], int]:+ if mode == "lookup":+ if provider_values:+ raise UsageError("--kp is allowed only with --mode federated")+ providers = ["infores:rtx-kg2"]+ limit = LOOKUP_RESULT_LIMIT if result_limit is None else result_limit+ elif mode == "federated":+ providers = _unique([validate_provider_id(value) for value in provider_values], "provider")+ if not MIN_FEDERATED_PROVIDERS <= len(providers) <= MAX_PROVIDERS:+ raise UsageError("federated mode requires two to five explicit providers")+ limit = FEDERATED_RESULT_LIMIT if result_limit is None else result_limit+ else:+ raise UsageError(f"unsupported mode: {mode}")+ return providers, validate_result_limit(limit)+++def build_query_edge(+ subject: str,+ object_: str,+ predicates: Sequence[str],+ qualifiers: Sequence[tuple[str, str]],+) -> dict[str, Any]:+ edge: dict[str, Any] = {+ "subject": subject,+ "object": object_,+ "predicates": list(predicates),+ }+ if qualifiers:+ edge["qualifier_constraints"] = [+ {+ "qualifier_set": [+ {"qualifier_type_id": qualifier_type, "qualifier_value": qualifier_value}+ for qualifier_type, qualifier_value in qualifiers+ ]+ }+ ]+ return edge+++def _provider_parameter(mode: str, provider_ids: Sequence[str]) -> str:+ if mode == "lookup":+ return "infores:rtx-kg2"+ return "[" + ",".join(provider_ids) + "]"+++def build_operations(+ edge_keys: Sequence[str],+ mode: str,+ provider_ids: Sequence[str],+ result_limit: int,+) -> dict[str, list[str]]:+ kp_value = _provider_parameter(mode, provider_ids)+ actions = [+ f"expand(edge_key={edge_key},kp={kp_value},kp_timeout={KP_TIMEOUT_SECONDS},"+ "return_minimal_metadata=false)"+ for edge_key in edge_keys+ ]+ actions.extend(+ [+ "scoreless_resultify(ignore_edge_direction=true)",+ f"filter_results(action=limit_number_of_results,max_results={result_limit},prune_kg=true)",+ "return(response=true,store=false)",+ ]+ )+ return {"actions": actions}+++def build_one_hop_query(+ *,+ subject_id: str | None,+ subject_category: str,+ predicates: Sequence[str],+ object_id: str | None,+ object_category: str,+ qualifiers: Sequence[tuple[str, str]],+ mode: str,+ provider_ids: Sequence[str],+ result_limit: int,+) -> dict[str, Any]:+ if subject_id is None and object_id is None:+ raise UsageError("one-hop queries require at least one pinned endpoint")+ nodes: dict[str, dict[str, Any]] = {+ "n0": {"categories": [validate_biolink_term(subject_category, "Biolink category")]},+ "n1": {"categories": [validate_biolink_term(object_category, "Biolink category")]},+ }+ if subject_id is not None:+ nodes["n0"]["ids"] = [validate_curie(subject_id)]+ if object_id is not None:+ nodes["n1"]["ids"] = [validate_curie(object_id)]+ body = {+ "message": {+ "query_graph": {+ "nodes": nodes,+ "edges": {+ "e0": build_query_edge("n0", "n1", validate_predicates(predicates), qualifiers)+ },+ }+ },+ "operations": build_operations(["e0"], mode, provider_ids, result_limit),+ "stream_progress": False,+ "submitter": SUBMITTER,+ }+ return body+++def build_two_hop_query(+ *,+ subject_id: str,+ subject_category: str,+ predicates_1: Sequence[str],+ intermediate_category: str,+ predicates_2: Sequence[str],+ object_id: str,+ object_category: str,+ qualifiers_1: Sequence[tuple[str, str]],+ qualifiers_2: Sequence[tuple[str, str]],+ mode: str,+ provider_ids: Sequence[str],+ expand_order: str,+ result_limit: int,+) -> dict[str, Any]:+ if expand_order not in {"right-first", "left-first"}:+ raise UsageError("expand order must be right-first or left-first")+ nodes = {+ "n0": {+ "ids": [validate_curie(subject_id)],+ "categories": [validate_biolink_term(subject_category, "Biolink category")],+ },+ "n1": {+ "categories": [validate_biolink_term(intermediate_category, "Biolink category")]+ },+ "n2": {+ "ids": [validate_curie(object_id)],+ "categories": [validate_biolink_term(object_category, "Biolink category")],+ },+ }+ edge_order = ["e1", "e0"] if expand_order == "right-first" else ["e0", "e1"]+ return {+ "message": {+ "query_graph": {+ "nodes": nodes,+ "edges": {+ "e0": build_query_edge(+ "n0", "n1", validate_predicates(predicates_1), qualifiers_1+ ),+ "e1": build_query_edge(+ "n1", "n2", validate_predicates(predicates_2), qualifiers_2+ ),+ },+ }+ },+ "operations": build_operations(edge_order, mode, provider_ids, result_limit),+ "stream_progress": False,+ "submitter": SUBMITTER,+ }+++def serialize_request(body: Mapping[str, Any]) -> bytes:+ try:+ return json.dumps(+ body,+ sort_keys=True,+ separators=(",", ":"),+ ensure_ascii=False,+ allow_nan=False,+ ).encode("utf-8")+ except (TypeError, ValueError) as exc:+ raise UsageError("request contains a value that cannot be represented as strict JSON") from exc+++def _origin(url: str) -> tuple[str, str | None, int | None]:+ parts = urllib.parse.urlsplit(url)+ try:+ port = parts.port+ except ValueError as exc:+ raise ValueError("URL contains an invalid port") from exc+ if port is None and parts.scheme.lower() == "https":+ port = 443+ return parts.scheme.lower(), parts.hostname.lower() if parts.hostname else None, port+++class SameOriginHttpsRedirectHandler(urllib.request.HTTPRedirectHandler):+ def redirect_request(+ self,+ req: urllib.request.Request,+ fp: Any,+ code: int,+ msg: str,+ headers: Any,+ newurl: str,+ ) -> urllib.request.Request | None:+ try:+ original_origin = _origin(req.full_url)+ redirect_origin = _origin(newurl)+ except ValueError:+ original_origin = _origin(req.full_url)+ redirect_origin = ("", None, None)+ if original_origin != redirect_origin or redirect_origin[0] != "https":+ raise urllib.error.HTTPError(+ newurl,+ code,+ "cross-origin or protocol-downgrade redirect rejected",+ headers,+ fp,+ )+ return super().redirect_request(req, fp, code, msg, headers, newurl)+++def _open_url(request: urllib.request.Request, timeout: int) -> Any:+ opener = urllib.request.build_opener(SameOriginHttpsRedirectHandler())+ return opener.open(request, timeout=timeout)+++def read_bounded_response(response: Any, byte_limit: int = MAX_RESPONSE_BYTES) -> bytes:+ body = response.read(byte_limit + 1)+ if len(body) > byte_limit:+ raise ResponseError("response exceeded the 25 MiB byte limit")+ return body+++def _response_status(response: Any) -> int:+ status = getattr(response, "status", None)+ return int(status if status is not None else response.getcode())+++def _headers_dict(headers: Any) -> dict[str, str]:+ if headers is None:+ return {}+ try:+ return {str(key): str(value) for key, value in headers.items()}+ except AttributeError:+ return {}+++def _retry_delay(headers: Mapping[str, str], now: Callable[[], datetime] | None = None) -> float:+ raw = next((value for key, value in headers.items() if key.lower() == "retry-after"), None)+ if raw is None:+ return 1.0+ try:+ return min(10.0, max(0.0, float(raw)))+ except ValueError:+ try:+ parsed = email.utils.parsedate_to_datetime(raw)+ current = (now or (lambda: datetime.now(timezone.utc)))()+ if parsed.tzinfo is None:+ parsed = parsed.replace(tzinfo=timezone.utc)+ return min(10.0, max(0.0, (parsed - current).total_seconds()))+ except (TypeError, ValueError, OverflowError):+ return 1.0+++def _is_timeout_error(error: BaseException) -> bool:+ if isinstance(error, (TimeoutError, socket.timeout)):+ return True+ return isinstance(error, urllib.error.URLError) and isinstance(+ getattr(error, "reason", None), (TimeoutError, socket.timeout)+ )+++def request_get_with_retry(+ url: str,+ *,+ timeout: int = GET_TIMEOUT_SECONDS,+ sleep: Callable[[float], None] = time.sleep,+) -> HttpResult:+ request = urllib.request.Request(+ url,+ method="GET",+ headers={+ "Accept": "application/json",+ "Accept-Encoding": "identity",+ "User-Agent": USER_AGENT,+ },+ )+ started = time.monotonic()+ for attempt in (1, 2):+ try:+ with _open_url(request, timeout) as response:+ try:+ body = read_bounded_response(response)+ except ResponseError as exc:+ exc.attempts = attempt+ exc.http_status = _response_status(response)+ raise+ return HttpResult(+ status=_response_status(response),+ body=body,+ headers=_headers_dict(getattr(response, "headers", None)),+ elapsed_ms=round((time.monotonic() - started) * 1000),+ attempts=attempt,+ )+ except urllib.error.HTTPError as exc:+ headers = _headers_dict(exc.headers)+ if exc.code in RETRYABLE_GET_STATUS and attempt == 1:+ try:+ exc.close()+ finally:+ sleep(_retry_delay(headers))+ continue+ try:+ body = read_bounded_response(exc)+ except ResponseError as oversized:+ oversized.http_status = exc.code+ oversized.attempts = attempt+ raise oversized from exc+ raise TransportError(+ f"GET failed with HTTP {exc.code}",+ http_status=exc.code,+ response_body=body,+ attempts=attempt,+ ) from exc+ except (urllib.error.URLError, TimeoutError, socket.timeout) as exc:+ if _is_timeout_error(exc) and attempt == 1:+ sleep(1.0)+ continue+ raise TransportError(f"GET transport failure: {_sanitize_text(exc)}", attempts=attempt) from exc+ raise AssertionError("unreachable")+++def post_query(url: str, request_bytes: bytes, *, timeout: int) -> HttpResult:+ request = urllib.request.Request(+ url,+ data=request_bytes,+ method="POST",+ headers={+ "Accept": "application/json",+ "Accept-Encoding": "identity",+ "Content-Type": "application/json",+ "User-Agent": USER_AGENT,+ },+ )+ started = time.monotonic()+ try:+ with _open_url(request, timeout) as response:+ try:+ body = read_bounded_response(response)+ except ResponseError as exc:+ exc.attempts = 1+ exc.http_status = _response_status(response)+ raise+ return HttpResult(+ status=_response_status(response),+ body=body,+ headers=_headers_dict(getattr(response, "headers", None)),+ elapsed_ms=round((time.monotonic() - started) * 1000),+ attempts=1,+ )+ except urllib.error.HTTPError as exc:+ try:+ body = read_bounded_response(exc)+ except ResponseError as oversized:+ oversized.http_status = exc.code+ oversized.attempts = 1+ raise oversized from exc+ raise TransportError(+ f"POST failed with HTTP {exc.code}",+ http_status=exc.code,+ response_body=body,+ attempts=1,+ ) from exc+ except ResponseError:+ raise+ except (urllib.error.URLError, TimeoutError, socket.timeout) as exc:+ raise TransportError(f"POST transport failure: {_sanitize_text(exc)}", attempts=1) from exc+++def _decode_json(body: bytes, label: str) -> Any:+ def reject_constant(value: str) -> None:+ raise ValueError(f"non-finite JSON number: {value}")++ try:+ return json.loads(body.decode("utf-8"), parse_constant=reject_constant)+ except (UnicodeDecodeError, json.JSONDecodeError, ValueError) as exc:+ raise ResponseError(f"{label} was not valid strict UTF-8 JSON") from exc+++def _version_series(version: str | None) -> str | None:+ if not version:+ return None+ parts = version.split(".")+ if len(parts) < 2 or not all(part.isdigit() for part in parts[:2]):+ return None+ return ".".join(parts[:2])+++def _check_trapi_version(+ trapi_version: str | None,+ allow_untested: bool,+ warnings: list[dict[str, Any]],+) -> None:+ series = _version_series(trapi_version)+ if series not in SUPPORTED_TRAPI_SERIES and not allow_untested:+ raise PreflightError(+ "service reports an unknown or missing TRAPI series; use --allow-untested-version to continue"+ )+ if trapi_version != TESTED_TRAPI_VERSION:+ _append_warning(+ warnings,+ "UNTESTED_SERVICE_VERSION",+ "The service TRAPI version differs from the tested production version.",+ {"reported": trapi_version, "tested": TESTED_TRAPI_VERSION},+ )+++def parse_openapi_service_info(+ payload: Any,+ *,+ base_url: str,+ openapi_url: str,+ allow_untested_version: bool,+ initial_warnings: Sequence[dict[str, Any]] = (),+) -> ServiceInfo:+ if not isinstance(payload, dict):+ raise PreflightError("OpenAPI document is not an object")+ info = payload.get("info")+ paths = payload.get("paths")+ if not isinstance(info, dict) or not isinstance(paths, dict):+ raise PreflightError("OpenAPI document is missing info or paths")+ title = info.get("title")+ if not isinstance(title, str) or "arax" not in title.lower():+ raise PreflightError("OpenAPI title does not identify ARAX")+ if "/query" not in paths:+ raise PreflightError("OpenAPI document does not expose /query")+ version_match = TRAPI_VERSION_RE.search(title)+ trapi_version = version_match.group(1) if version_match else None+ arax_version = str(info["version"]) if info.get("version") is not None else None+ warnings = list(initial_warnings)+ _check_trapi_version(trapi_version, allow_untested_version, warnings)+ if arax_version != TESTED_ARAX_VERSION:+ _append_warning(+ warnings,+ "UNTESTED_SERVICE_VERSION",+ "The ARAX version differs from the tested production version.",+ {"reported": arax_version, "tested": TESTED_ARAX_VERSION},+ )+ return ServiceInfo(+ base_url=base_url,+ openapi_url=openapi_url,+ arax_version=arax_version,+ trapi_version=trapi_version,+ warnings=tuple(warnings),+ )+++def fetch_openapi(+ base_url: str,+ *,+ allow_untested_version: bool,+ initial_warnings: Sequence[dict[str, Any]] = (),+) -> tuple[ServiceInfo, HttpResult]:+ openapi_url = base_url + "/openapi.json"+ try:+ result = request_get_with_retry(openapi_url)+ except TransportError as exc:+ raise PreflightError(+ str(exc),+ http_status=exc.http_status,+ response_body=exc.response_body,+ attempts=exc.attempts,+ ) from exc+ try:+ payload = _decode_json(result.body, "OpenAPI response")+ service = parse_openapi_service_info(+ payload,+ base_url=base_url,+ openapi_url=openapi_url,+ allow_untested_version=allow_untested_version,+ initial_warnings=initial_warnings,+ )+ except (PreflightError, ResponseError) as exc:+ if isinstance(exc, ResponseError):+ wrapped = PreflightError(str(exc))+ else:+ wrapped = exc+ wrapped.http_status = result.status+ wrapped.response_body = result.body+ wrapped.attempts = result.attempts+ raise wrapped+ return service, result+++def normalize_entity_request(base_url: str, term: str) -> HttpResult:+ query = urllib.parse.urlencode({"q": term})+ return request_get_with_retry(base_url + "/entity?" + query)+++def parse_normalization_response(+ payload: Any,+ *,+ term: str,+ expected_category: str | None,+ max_synonyms: int,+ service: ServiceInfo,+) -> tuple[dict[str, Any], bool]:+ warnings = [make_warning("PUBLIC_QUERY", "The normalization request was sent to a public service.")]+ requires_confirmation = not _looks_like_curie(term)+ if requires_confirmation:+ _append_warning(+ warnings,+ "NORMALIZATION_REQUIRES_CONFIRMATION",+ "Review the normalized identifier and category before constructing a graph query.",+ )+ record: Any = payload.get(term) if isinstance(payload, dict) else None+ if record is None and isinstance(payload, dict) and len(payload) == 1:+ record = next(iter(payload.values()))+ usable = isinstance(record, dict) and isinstance(record.get("id"), dict)+ identifier_record = record.get("id", {}) if usable else {}+ identifier = identifier_record.get("identifier") if isinstance(identifier_record, dict) else None+ if not isinstance(identifier, str) or not _looks_like_curie(identifier):+ usable = False+ identifier = None+ category = identifier_record.get("category") if isinstance(identifier_record, dict) else None+ if expected_category is not None and category != expected_category and usable:+ _append_warning(+ warnings,+ "NORMALIZATION_CATEGORY_MISMATCH",+ "The canonical category differs from the expected category.",+ {"expected": expected_category, "returned": category},+ )+ nodes = record.get("nodes", []) if isinstance(record, dict) else []+ preview: list[dict[str, Any]] = []+ if isinstance(nodes, list):+ for node in nodes[:max_synonyms]:+ if not isinstance(node, dict):+ continue+ preview.append(+ {+ "identifier": node.get("identifier", node.get("id")),+ "name": node.get("name"),+ "category": node.get("category"),+ }+ )+ if not usable:+ _append_warning(+ warnings,+ "NO_RESULTS",+ "Normalization returned no usable canonical CURIE.",+ )+ summary = {+ "schema_version": "1.0",+ "kind": "normalization",+ "query": {+ "input": term,+ "expected_category": expected_category,+ "requires_user_confirmation": requires_confirmation,+ },+ "service": service.as_dict(),+ "canonical": {+ "identifier": identifier,+ "name": identifier_record.get("name") if isinstance(identifier_record, dict) else None,+ "category": category,+ },+ "category_counts": record.get("categories", {}) if isinstance(record, dict) else {},+ "total_synonyms": record.get("total_synonyms", 0) if isinstance(record, dict) else 0,+ "synonym_preview": preview,+ "warnings": warnings,+ }+ return summary, usable+++def _require_exact_keys(value: Mapping[str, Any], allowed: set[str], label: str) -> None:+ extras = set(value) - allowed+ missing = allowed - set(value)+ if extras or missing:+ details: list[str] = []+ if missing:+ details.append("missing " + ", ".join(sorted(missing)))+ if extras:+ details.append("unsupported " + ", ".join(sorted(extras)))+ raise UsageError(f"{label} has " + "; ".join(details))+++def _validate_edge_contract(edge: Any) -> tuple[str, str]:+ if not isinstance(edge, dict):+ raise UsageError("saved request contains an invalid query edge")+ allowed = {"subject", "object", "predicates"}+ if "qualifier_constraints" in edge:+ allowed.add("qualifier_constraints")+ _require_exact_keys(edge, allowed, "saved query edge")+ subject = edge.get("subject")+ object_ = edge.get("object")+ if not isinstance(subject, str) or not isinstance(object_, str):+ raise UsageError("saved query edge lacks subject or object")+ predicates = edge.get("predicates")+ if not isinstance(predicates, list):+ raise UsageError("saved query edge lacks predicates")+ validate_predicates(predicates)+ constraints = edge.get("qualifier_constraints")+ if constraints is not None:+ if not isinstance(constraints, list) or len(constraints) != 1:+ raise UsageError("saved query edge must have one AND qualifier set")+ if not isinstance(constraints[0], dict):+ raise UsageError("saved query edge has invalid qualifiers")+ _require_exact_keys(constraints[0], {"qualifier_set"}, "qualifier constraint")+ qualifier_set = constraints[0].get("qualifier_set")+ if not isinstance(qualifier_set, list):+ raise UsageError("saved query edge has invalid qualifiers")+ raw = []+ for qualifier in qualifier_set:+ if not isinstance(qualifier, dict):+ raise UsageError("saved query edge has invalid qualifiers")+ _require_exact_keys(+ qualifier,+ {"qualifier_type_id", "qualifier_value"},+ "saved qualifier",+ )+ raw.append(f"{qualifier.get('qualifier_type_id')}={qualifier.get('qualifier_value')}")+ parse_qualifiers(raw)+ return subject, object_+++def _parse_kp_parameter(value: str) -> tuple[str, tuple[str, ...]]:+ if value == "infores:rtx-kg2":+ return "lookup", (value,)+ if not value.startswith("[") or not value.endswith("]"):+ raise UsageError("saved request does not use lookup or selected-provider federation")+ providers = tuple(validate_provider_id(item) for item in value[1:-1].split(",") if item)+ if not MIN_FEDERATED_PROVIDERS <= len(providers) <= MAX_PROVIDERS:+ raise UsageError("saved federated request must name two to five providers")+ _unique(list(providers), "provider")+ return "federated", providers+++def validate_saved_request_contract(payload: Any) -> QueryContract:+ if not isinstance(payload, dict) or "workflow" in payload:+ raise UsageError("saved request is not a supported fixed-operation request")+ _require_exact_keys(+ payload,+ {"message", "operations", "stream_progress", "submitter"},+ "saved request",+ )+ if payload["stream_progress"] is not False or payload["submitter"] != SUBMITTER:+ raise UsageError("saved request changes fixed submission controls")+ message = payload.get("message")+ if not isinstance(message, dict):+ raise UsageError("saved request lacks a query graph")+ _require_exact_keys(message, {"query_graph"}, "saved message")+ graph = message.get("query_graph") if isinstance(message, dict) else None+ if not isinstance(graph, dict):+ raise UsageError("saved request lacks a query graph")+ _require_exact_keys(graph, {"nodes", "edges"}, "saved query graph")+ nodes = graph.get("nodes") if isinstance(graph, dict) else None+ edges = graph.get("edges") if isinstance(graph, dict) else None+ if not isinstance(nodes, dict) or not isinstance(edges, dict):+ raise UsageError("saved request lacks a query graph")+ if set(nodes) == {"n0", "n1"} and set(edges) == {"e0"}:+ kind = "one-hop"+ elif set(nodes) == {"n0", "n1", "n2"} and set(edges) == {"e0", "e1"}:+ kind = "two-hop"+ else:+ raise UsageError("saved request must be exactly one hop or endpoint-pinned two hop")+ qnode_ids: dict[str, list[str]] = {}+ for key, node in nodes.items():+ if not isinstance(node, dict):+ raise UsageError("saved request contains an invalid qnode")+ allowed_node_keys = {"categories"}+ if "ids" in node:+ allowed_node_keys.add("ids")+ _require_exact_keys(node, allowed_node_keys, "saved qnode")+ categories = node.get("categories")+ if not isinstance(categories, list) or len(categories) != 1:+ raise UsageError("every saved qnode must have exactly one category")+ validate_biolink_term(categories[0], "Biolink category")+ ids = node.get("ids", [])+ if not isinstance(ids, list) or len(ids) > 1:+ raise UsageError("saved qnodes may have at most one CURIE")+ qnode_ids[key] = [validate_curie(value) for value in ids]+ if kind == "one-hop" and not (qnode_ids["n0"] or qnode_ids["n1"]):+ raise UsageError("saved one-hop request has no pinned endpoint")+ if kind == "two-hop" and not (+ len(qnode_ids["n0"]) == 1 and not qnode_ids["n1"] and len(qnode_ids["n2"]) == 1+ ):+ raise UsageError("saved two-hop request is not endpoint pinned")+ query_edges = {key: _validate_edge_contract(edge) for key, edge in edges.items()}+ expected_edges = {"e0": ("n0", "n1")}+ if kind == "two-hop":+ expected_edges["e1"] = ("n1", "n2")+ if query_edges != expected_edges:+ raise UsageError("saved query edge topology is unsupported")+ operations = payload.get("operations")+ if not isinstance(operations, dict):+ raise UsageError("saved request lacks operations")+ _require_exact_keys(operations, {"actions"}, "saved operations")+ actions = operations.get("actions") if isinstance(operations, dict) else None+ expected_count = 4 if kind == "one-hop" else 5+ if not isinstance(actions, list) or len(actions) != expected_count:+ raise UsageError("saved request does not contain the fixed action sequence")+ if actions[-3] != "scoreless_resultify(ignore_edge_direction=true)":+ raise UsageError("saved request does not use scoreless resultification")+ filter_match = FILTER_RE.fullmatch(actions[-2]) if isinstance(actions[-2], str) else None+ if filter_match is None or actions[-1] != "return(response=true,store=false)":+ raise UsageError("saved request does not use the fixed filter and return actions")+ result_limit = validate_result_limit(int(filter_match.group(1)))+ expand_actions = actions[:-3]+ expand_keys: list[str] = []+ mode: str | None = None+ provider_ids: tuple[str, ...] | None = None+ for action in expand_actions:+ match = EXPAND_RE.fullmatch(action) if isinstance(action, str) else None+ if match is None:+ raise UsageError("saved request contains an unsupported expansion action")+ current_mode, current_providers = _parse_kp_parameter(match.group(2))+ if mode is not None and (current_mode, current_providers) != (mode, provider_ids):+ raise UsageError("saved request changes providers between edges")+ mode, provider_ids = current_mode, current_providers+ expand_keys.append(match.group(1))+ if kind == "one-hop":+ if expand_keys != ["e0"]:+ raise UsageError("saved one-hop request has invalid expansion order")+ expand_order = None+ elif expand_keys == ["e1", "e0"]:+ expand_order = "right-first"+ elif expand_keys == ["e0", "e1"]:+ expand_order = "left-first"+ else:+ raise UsageError("saved two-hop request has invalid expansion order")+ return QueryContract(+ kind=kind,+ mode=mode or "lookup",+ provider_ids=provider_ids or ("infores:rtx-kg2",),+ expand_order=expand_order,+ qnode_ids=qnode_ids,+ result_limit=result_limit,+ query_edges=query_edges,+ )+++def _normalize_node_bindings(value: Any) -> tuple[dict[str, list[dict[str, Any]]], dict[str, set[str]]]:+ if not isinstance(value, dict):+ raise ResponseError("result node_bindings is not an object")+ normalized: dict[str, list[dict[str, Any]]] = {}+ identifiers: dict[str, set[str]] = {}+ for qnode_key, bindings in value.items():+ if not isinstance(bindings, list):+ raise ResponseError("node binding list is malformed")+ normalized[qnode_key] = []+ identifiers[qnode_key] = set()+ for binding in bindings:+ if not isinstance(binding, dict) or not isinstance(binding.get("id"), str):+ raise ResponseError("node binding is missing an identifier")+ identifiers[qnode_key].add(binding["id"])+ normalized[qnode_key].append(+ {+ "id": binding["id"],+ "query_id": binding.get("query_id"),+ "attributes": binding.get("attributes", []),+ }+ )+ return normalized, identifiers+++def _resource_ids_for_role(sources: Sequence[dict[str, Any]], role: str) -> list[str]:+ found: list[str] = []+ for source in sources:+ resource_role = source.get("resource_role")+ if isinstance(resource_role, str) and resource_role.removeprefix("biolink:") == role:+ resource_id = source.get("resource_id")+ if isinstance(resource_id, str) and resource_id not in found:+ found.append(resource_id)+ return found+++def extract_publications(edge: Mapping[str, Any]) -> list[str]:+ publications: list[str] = []+ attributes = edge.get("attributes", [])+ if not isinstance(attributes, list):+ return publications+ for attribute in attributes:+ if not isinstance(attribute, dict) or attribute.get("attribute_type_id") != "biolink:publications":+ continue+ value = attribute.get("value")+ candidates: Iterable[Any] = value if isinstance(value, list) else [value]+ for candidate in candidates:+ if isinstance(candidate, str) and candidate not in publications:+ publications.append(candidate)+ return publications+++def _classify_logs(+ payload: Mapping[str, Any],+ contract: QueryContract,+ warnings: list[dict[str, Any]],+) -> bool:+ partial = False+ logs = payload.get("logs", [])+ if not isinstance(logs, list):+ return partial+ for log in logs:+ if not isinstance(log, dict):+ continue+ message = _sanitize_text(log.get("message", ""), MAX_WARNING_MESSAGE)+ code = _sanitize_text(log.get("code", ""), 100)+ level = _sanitize_text(log.get("level", ""), 30).lower()+ combined = f"{code} {message}".lower()+ provider = next((item for item in contract.provider_ids if item.lower() in combined), None)+ context = {"provider_id": provider} if provider else {}+ failure_level = level in {"warning", "error", "critical", "fatal"}+ timeout_failure = failure_level and (+ "timed out" in combined+ or "timeout error" in combined+ or "timeout failure" in combined+ or "timeout" in code.lower()+ )+ malformed_failure = failure_level and any(+ token in combined for token in ("malformed", "deserial", "invalid trapi")+ )+ if timeout_failure:+ _append_warning(warnings, "KP_TIMEOUT", message or "A provider timed out.", context)+ partial = partial or contract.mode == "federated"+ elif malformed_failure:+ _append_warning(+ warnings,+ "MALFORMED_KP_RESPONSE",+ message or "A provider returned a malformed response.",+ context,+ )+ partial = partial or contract.mode == "federated"+ elif contract.mode == "federated" and level in {"warning", "error", "critical"} and (+ "kp" in combined or provider is not None+ ):+ _append_warning(warnings, "KP_ERROR", message or "A provider reported an error.", context)+ partial = True+ result_pruning = (+ "result_limit" in code.lower()+ or "result_prun" in code.lower()+ or "pruned result" in combined+ or ("removed" in combined and "result" in combined)+ )+ if result_pruning:+ _append_warning(+ warnings,+ "INTERNAL_PRUNING_DETECTED",+ message or "ARAX reported internal pruning or result removal.",+ )+ return partial+++def parse_trapi_response(+ payload: Any,+ contract: QueryContract,+ *,+ service: ServiceInfo | None = None,+ initial_warnings: Sequence[dict[str, Any]] = (),+) -> dict[str, Any]:+ if not isinstance(payload, dict):+ raise ResponseError("TRAPI response is not an object")+ message = payload.get("message")+ if not isinstance(message, dict):+ raise ResponseError("TRAPI response is missing message")+ knowledge_graph = message.get("knowledge_graph")+ if not isinstance(knowledge_graph, dict):+ raise ResponseError("TRAPI response is missing knowledge_graph")+ kg_nodes = knowledge_graph.get("nodes")+ kg_edges = knowledge_graph.get("edges")+ results = message.get("results")+ if not isinstance(kg_nodes, dict) or not isinstance(kg_edges, dict) or not isinstance(results, list):+ raise ResponseError("TRAPI response has malformed nodes, edges, or results")+ auxiliary_graphs = message.get("auxiliary_graphs", {})+ if not isinstance(auxiliary_graphs, dict):+ auxiliary_graphs = {}+ warnings = [dict(item) for item in initial_warnings]+ _append_warning(+ warnings,+ "UNSCORED_RESPONSE_ORDER",+ "Result positions are preserved from the unscored ARAX response.",+ )+ partial = _classify_logs(payload, contract, warnings)+ summarized_results: list[dict[str, Any]] = []+ analyses_count = 0+ bound_edges_count = 0+ for position, result in enumerate(results[: contract.result_limit], start=1):+ if not isinstance(result, dict):+ raise ResponseError("TRAPI result is not an object")+ node_bindings, binding_ids = _normalize_node_bindings(result.get("node_bindings"))+ if set(node_bindings) != set(contract.qnode_ids):+ raise ResponseError("result node_bindings do not match the supported query graph")+ analyses = result.get("analyses")+ if not isinstance(analyses, list):+ raise ResponseError("TRAPI result analyses is not a list")+ normalized_analyses: list[dict[str, Any]] = []+ for analysis in analyses:+ if not isinstance(analysis, dict):+ raise ResponseError("TRAPI analysis is not an object")+ edge_bindings = analysis.get("edge_bindings")+ if not isinstance(edge_bindings, dict):+ raise ResponseError("TRAPI analysis edge_bindings is not an object")+ if set(edge_bindings) != set(contract.query_edges):+ raise ResponseError("TRAPI analysis edge_bindings do not match the supported query graph")+ support_graph_ids = analysis.get("support_graphs", [])+ if not isinstance(support_graph_ids, list):+ support_graph_ids = []+ missing_support = [item for item in support_graph_ids if item not in auxiliary_graphs]+ if support_graph_ids and missing_support:+ support_status = "missing"+ for graph_id in missing_support:+ _append_warning(+ warnings,+ "MISSING_AUXILIARY_GRAPH",+ "A referenced auxiliary graph was not returned.",+ {"support_graph_id": graph_id},+ )+ elif support_graph_ids:+ support_status = "available"+ else:+ support_status = "not_returned"+ normalized_edges: dict[str, list[dict[str, Any]]] = {}+ for qedge_key in contract.query_edges:+ bindings = edge_bindings.get(qedge_key, [])+ if not isinstance(bindings, list):+ raise ResponseError("query-edge binding list is malformed")+ normalized_edges[qedge_key] = []+ qsubject, qobject = contract.query_edges[qedge_key]+ expected_subjects = binding_ids.get(qsubject, set())+ expected_objects = binding_ids.get(qobject, set())+ for binding in bindings:+ if not isinstance(binding, dict) or not isinstance(binding.get("id"), str):+ raise ResponseError("query-edge binding is missing an edge identifier")+ edge_id = binding["id"]+ edge = kg_edges.get(edge_id)+ if not isinstance(edge, dict):+ raise ResponseError(f"bound knowledge-graph edge is missing: {edge_id}")+ subject = edge.get("subject")+ object_ = edge.get("object")+ predicate = edge.get("predicate")+ if not all(isinstance(item, str) for item in (subject, object_, predicate)):+ raise ResponseError(f"bound edge is malformed: {edge_id}")+ matches_direction = subject in expected_subjects and object_ in expected_objects+ matches_reverse = subject in expected_objects and object_ in expected_subjects+ if not matches_direction and not matches_reverse:+ raise ResponseError(+ f"bound edge endpoints do not match result node bindings: {edge_id}"+ )+ if matches_reverse:+ _append_warning(+ warnings,+ "REVERSED_EDGE_BINDING",+ "A bound edge does not match the query's physical direction; it was preserved.",+ {"edge_id": edge_id, "query_edge": qedge_key},+ )+ sources_value = edge.get("sources", [])+ sources = [dict(item) for item in sources_value if isinstance(item, dict)] if isinstance(sources_value, list) else []+ primary = _resource_ids_for_role(sources, "primary_knowledge_source")+ aggregators = _resource_ids_for_role(sources, "aggregator_knowledge_source")+ supporting = _resource_ids_for_role(sources, "supporting_data_source")+ if not primary:+ _append_warning(+ warnings,+ "NO_PRIMARY_SOURCE_RETURNED",+ "No primary knowledge source was returned for a bound edge.",+ {"edge_id": edge_id},+ )+ publications = extract_publications(edge)+ if not publications:+ _append_warning(+ warnings,+ "NO_PUBLICATIONS_RETURNED",+ "No recognized publication metadata was returned for a bound edge.",+ {"edge_id": edge_id},+ )+ qualifiers_value = edge.get("qualifiers", [])+ qualifiers = []+ if isinstance(qualifiers_value, list):+ qualifiers = [+ {+ "qualifier_type_id": item.get("qualifier_type_id"),+ "qualifier_value": item.get("qualifier_value"),+ }+ for item in qualifiers_value+ if isinstance(item, dict)+ ]+ subject_node = kg_nodes.get(subject, {})+ object_node = kg_nodes.get(object_, {})+ normalized_edges[qedge_key].append(+ {+ "edge_id": edge_id,+ "subject": subject,+ "subject_name": subject_node.get("name") if isinstance(subject_node, dict) else None,+ "predicate": predicate,+ "object": object_,+ "object_name": object_node.get("name") if isinstance(object_node, dict) else None,+ "matches_query_direction": matches_direction,+ "qualifiers": qualifiers,+ "sources": sources,+ "primary_knowledge_sources": primary,+ "aggregator_knowledge_sources": aggregators,+ "supporting_data_sources": supporting,+ "publication_ids": publications,+ "publication_availability": "available" if publications else "not_returned",+ "support_graph_ids": list(support_graph_ids),+ "support_graph_status": support_status,+ }+ )+ bound_edges_count += 1+ normalized_analyses.append(+ {+ "resource_id": analysis.get("resource_id"),+ "score": analysis.get("score"),+ "support_graphs": list(support_graph_ids),+ "edge_bindings": normalized_edges,+ }+ )+ analyses_count += 1+ summarized_results.append(+ {+ "position": position,+ "description": _sanitize_text(result.get("description"), MAX_DISPLAY_TEXT)+ if result.get("description") is not None+ else None,+ "node_bindings": node_bindings,+ "analyses": normalized_analyses,+ }+ )+ raw_count = len(results)+ total_results_count = payload.get("total_results_count")+ if not isinstance(total_results_count, int) or isinstance(total_results_count, bool):+ total_results_count = None+ pruning = any(item.get("code") == "INTERNAL_PRUNING_DETECTED" for item in warnings)+ if raw_count > contract.result_limit or pruning or (+ total_results_count is not None and total_results_count > raw_count+ ):+ truncation_status = "confirmed"+ elif raw_count == contract.result_limit:+ truncation_status = "possible"+ else:+ truncation_status = "no"+ if raw_count >= contract.result_limit:+ _append_warning(+ warnings,+ "RESULT_LIMIT_REACHED",+ "The response reached or exceeded the requested result limit.",+ {"result_limit": contract.result_limit},+ )+ if raw_count == 0:+ _append_warning(+ warnings,+ "NO_RESULTS",+ "ARAX returned no results under these constraints.",+ )+ if service is None:+ service_data = {+ "base_url": None,+ "openapi_url": None,+ "arax_version": payload.get("tool_version"),+ "trapi_version": payload.get("schema_version"),+ "biolink_version": payload.get("biolink_version"),+ }+ else:+ service_data = service.as_dict(biolink_version=payload.get("biolink_version"))+ return {+ "schema_version": "1.0",+ "query": {+ "kind": contract.kind,+ "mode": contract.mode,+ "provider_ids": list(contract.provider_ids),+ "expand_order": contract.expand_order,+ "qnode_ids": contract.qnode_ids,+ "result_limit": contract.result_limit,+ },+ "service": service_data,+ "counts": {+ "results_returned": raw_count,+ "results_summarized": len(summarized_results),+ "analyses_summarized": analyses_count,+ "bound_edges_summarized": bound_edges_count,+ "knowledge_graph_nodes": len(kg_nodes),+ "knowledge_graph_edges": len(kg_edges),+ "server_total_results_count": total_results_count,+ },+ "truncation_status": truncation_status,+ "completeness": "partial" if partial else "complete",+ "results": summarized_results,+ "warnings": warnings,+ }+++def render_text_summary(+ summary: Mapping[str, Any],+ *,+ summary_path: str = "summary.json",+ response_path: str = "response.json",+) -> str:+ def rendered(value: Any, limit: int = 200) -> str:+ return _sanitize_text(value, limit)++ def rendered_list(values: Any, *, limit: int = 200) -> str:+ if not isinstance(values, list) or not values:+ return "not returned"+ return ", ".join(rendered(value, limit) for value in values)++ lines: list[str] = []+ query = summary.get("query", {})+ counts = summary.get("counts", {})+ lines.append(+ f"ARAX returned {counts.get('results_returned', 0)} result(s); "+ f"showing {counts.get('results_summarized', 0)} in unscored response order."+ )+ lines.append(+ f"Query: {rendered(query.get('kind'))} / {rendered(query.get('mode'))}; "+ f"limit {rendered(query.get('result_limit'))}; "+ f"truncation {rendered(summary.get('truncation_status'))}; "+ f"completeness {rendered(summary.get('completeness'))}."+ )+ warnings = summary.get("warnings", [])+ if isinstance(warnings, list) and warnings:+ lines.append("Warnings:")+ for warning in warnings:+ if isinstance(warning, dict):+ lines.append(+ f" - {rendered(warning.get('code'), 100)}: "+ f"{rendered(warning.get('message', ''), MAX_WARNING_MESSAGE)}"+ )+ results = summary.get("results", [])+ if not results:+ lines.append("Not returned under these constraints.")+ for result in results if isinstance(results, list) else []:+ if not isinstance(result, dict):+ continue+ lines.append(+ f"Unscored position {rendered(result.get('position'))}: "+ f"{rendered(result.get('description') or 'candidate path', MAX_DISPLAY_TEXT)}"+ )+ node_bindings = result.get("node_bindings", {})+ if isinstance(node_bindings, dict):+ for qnode, bindings in node_bindings.items():+ ids = [item.get("id") for item in bindings if isinstance(item, dict)] if isinstance(bindings, list) else []+ lines.append(f" {rendered(qnode, 100)}: {rendered_list(ids)}")+ analyses = result.get("analyses", [])+ for analysis_index, analysis in enumerate(analyses if isinstance(analyses, list) else [], start=1):+ if not isinstance(analysis, dict):+ continue+ lines.append(+ f" Analysis {analysis_index}: resource {rendered(analysis.get('resource_id'))}; "+ f"score {rendered(analysis.get('score'))}"+ )+ edge_bindings = analysis.get("edge_bindings", {})+ if not isinstance(edge_bindings, dict):+ continue+ for qedge, edges in edge_bindings.items():+ for edge in edges if isinstance(edges, list) else []:+ if not isinstance(edge, dict):+ continue+ subject = edge.get("subject")+ subject_name = edge.get("subject_name")+ object_ = edge.get("object")+ object_name = edge.get("object_name")+ lines.append(+ f" {rendered(qedge, 100)}/{rendered(edge.get('edge_id'))}: "+ f"{rendered(subject)} ({rendered(subject_name)}) "+ f"--{rendered(edge.get('predicate'))}--> "+ f"{rendered(object_)} ({rendered(object_name)})"+ )+ if not edge.get("matches_query_direction"):+ lines.append(" Direction warning: physical edge orientation differs from the query.")+ qualifiers = edge.get("qualifiers", [])+ if qualifiers:+ rendered_qualifiers = ", ".join(+ f"{_sanitize_text(item.get('qualifier_type_id'), 200)}="+ f"{_sanitize_text(item.get('qualifier_value'), 200)}"+ for item in qualifiers+ if isinstance(item, dict)+ )+ lines.append(f" Qualifiers: {rendered_qualifiers}")+ for label, field in (+ ("Primary sources", "primary_knowledge_sources"),+ ("Aggregator sources", "aggregator_knowledge_sources"),+ ("Supporting sources", "supporting_data_sources"),+ ):+ values = edge.get(field, [])+ lines.append(f" {label}: {rendered_list(values)}")+ publications = edge.get("publication_ids", [])+ preview = publications[:PUBLICATION_PREVIEW] if isinstance(publications, list) else []+ lines.append(+ f" Publications: {len(publications) if isinstance(publications, list) else 0}; "+ f"preview {rendered_list(preview)}"+ )+ lines.append(f"Complete bounded publication and source lists: {rendered(summary_path, 500)}")+ lines.append(f"Exact TRAPI payload: {rendered(response_path, 500)}")+ lines.append("Candidate paths require subsequent scientific verification.")+ return "\n".join(lines)+++def sha256_bytes(value: bytes) -> str:+ return hashlib.sha256(value).hexdigest()+++def prepare_output_directory(value: str | Path) -> Path:+ path = Path(value)+ try:+ if path.exists():+ if not path.is_dir():+ raise UsageError("output path exists and is not a directory")+ if any(path.iterdir()):+ raise UsageError("output directory must be new or empty")+ else:+ path.mkdir(parents=True)+ except UsageError:+ raise+ except OSError as exc:+ raise ResponseError(f"could not prepare output directory: {_sanitize_text(exc)}") from exc+ return path+++def atomic_write_bytes(path: Path, value: bytes) -> None:+ try:+ if path.exists():+ raise ResponseError(f"refusing to overwrite existing artifact: {path.name}")+ except ResponseError:+ raise+ except OSError as exc:+ raise ResponseError(f"could not inspect artifact path {path.name}: {_sanitize_text(exc)}") from exc+ descriptor: int | None = None+ temporary: Path | None = None+ try:+ descriptor, temporary_name = tempfile.mkstemp(+ prefix=".ncats-arax-", dir=str(path.parent)+ )+ temporary = Path(temporary_name)+ try:+ os.chmod(temporary, 0o600)+ except OSError:+ pass+ handle = os.fdopen(descriptor, "wb")+ descriptor = None+ with handle:+ handle.write(value)+ handle.flush()+ os.fsync(handle.fileno())+ if path.exists():+ raise ResponseError(f"refusing to overwrite concurrently created artifact: {path.name}")+ os.replace(temporary, path)+ except ResponseError:+ raise+ except OSError as exc:+ raise ResponseError(f"could not write artifact {path.name}: {_sanitize_text(exc)}") from exc+ finally:+ if descriptor is not None:+ try:+ os.close(descriptor)+ except OSError:+ pass+ try:+ if temporary is not None:+ temporary.unlink(missing_ok=True)+ except OSError:+ pass+++def atomic_write_json(path: Path, value: Mapping[str, Any]) -> bytes:+ try:+ encoded = (+ json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False, allow_nan=False) + "\n"+ ).encode("utf-8")+ except (TypeError, ValueError) as exc:+ raise ResponseError("artifact data cannot be represented as strict JSON") from exc+ atomic_write_bytes(path, encoded)+ return encoded+++def _utc_now() -> str:+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")+++def new_manifest(+ command: str,+ *,+ base_url: str,+ privacy_acknowledged: bool,+ http_timeout: int,+ result_limit: int | None = None,+) -> dict[str, Any]:+ return {+ "manifest_version": "1.0",+ "run_id": str(uuid.uuid4()),+ "command": command,+ "started_at": _utc_now(),+ "finished_at": None,+ "execution_status": "client_error",+ "result_status": "not_available",+ "privacy_acknowledged": privacy_acknowledged,+ "client": {"name": CLIENT_NAME, "version": CLIENT_VERSION},+ "service": {+ "base_url": base_url,+ "openapi_url": base_url + "/openapi.json",+ "arax_version": None,+ "trapi_version": None,+ "biolink_version": None,+ },+ "request": {+ "method": "GET",+ "url": base_url + "/openapi.json",+ "file": None,+ "bytes": None,+ "sha256": None,+ },+ "response": {+ "http_status": None,+ "file": None,+ "bytes": None,+ "sha256": None,+ "elapsed_ms": None,+ },+ "limits": {+ "result_limit": result_limit,+ "response_byte_limit": MAX_RESPONSE_BYTES,+ "kp_timeout_seconds": KP_TIMEOUT_SECONDS if command in {"one-hop", "two-hop"} else None,+ "http_timeout_seconds": http_timeout,+ },+ "attempts": {"openapi_get": 0, "entity_get": 0, "query_post": 0},+ "artifacts": {"request": None, "response": None, "summary": None},+ "error": None,+ "warnings": [],+ }+++def _apply_service_to_manifest(manifest: dict[str, Any], service: ServiceInfo) -> None:+ manifest["service"].update(service.as_dict())+ manifest["warnings"] = [dict(item) for item in service.warnings]+++def _record_response(manifest: dict[str, Any], result: HttpResult, filename: str = "response.json") -> None:+ manifest["response"].update(+ {+ "http_status": result.status,+ "file": filename,+ "bytes": len(result.body),+ "sha256": sha256_bytes(result.body),+ "elapsed_ms": result.elapsed_ms,+ }+ )+ manifest["artifacts"]["response"] = filename+++def _write_manifest(output_dir: Path, manifest: dict[str, Any]) -> None:+ manifest["finished_at"] = _utc_now()+ atomic_write_json(output_dir / "manifest.json", manifest)+++def _retain_failure(+ output_dir: Path | None,+ manifest: dict[str, Any] | None,+ error: AraxClientError,+ stage: str,+) -> None:+ if output_dir is None or manifest is None:+ return+ try:+ manifest["execution_status"] = "http_error" if error.exit_code == 5 else "client_error"+ manifest["result_status"] = "not_available"+ manifest["error"] = {"kind": error.kind, "message": _sanitize_text(error)}+ if error.http_status is not None:+ manifest["response"]["http_status"] = error.http_status+ attempt_key = {+ "openapi": "openapi_get",+ "entity": "entity_get",+ "query": "query_post",+ }.get(stage)+ if error.attempts and attempt_key is not None:+ manifest["attempts"][attempt_key] = error.attempts+ if error.response_body is not None and not (output_dir / "response.json").exists():+ atomic_write_bytes(output_dir / "response.json", error.response_body)+ failed = HttpResult(+ status=error.http_status or 0,+ body=error.response_body,+ headers={},+ elapsed_ms=0,+ attempts=error.attempts,+ )+ _record_response(manifest, failed)+ if not (output_dir / "manifest.json").exists():+ _write_manifest(output_dir, manifest)+ except Exception as manifest_error:+ print(+ f"warning: could not retain failure artifacts: {_sanitize_text(manifest_error)}",+ file=sys.stderr,+ )+++def _json_from_http(result: HttpResult, label: str) -> Any:+ return _decode_json(result.body, label)+++def _preflight_summary(service: ServiceInfo) -> dict[str, Any]:+ return {+ "schema_version": "1.0",+ "kind": "preflight",+ "service": service.as_dict(),+ "checks": {+ "title_identifies_arax": True,+ "query_path_present": True,+ "version_supported": _version_series(service.trapi_version) in SUPPORTED_TRAPI_SERIES,+ },+ "warnings": [dict(item) for item in service.warnings],+ }+++def handle_preflight(args: argparse.Namespace) -> int:+ base_url, endpoint_warnings = validate_base_url(args.base_url, args.allow_nonproduction_endpoint)+ output_dir = prepare_output_directory(args.output_dir) if args.output_dir else None+ manifest = new_manifest(+ "preflight", base_url=base_url, privacy_acknowledged=False, http_timeout=GET_TIMEOUT_SECONDS+ ) if output_dir else None+ stage = "openapi"+ try:+ service, result = fetch_openapi(+ base_url,+ allow_untested_version=args.allow_untested_version,+ initial_warnings=endpoint_warnings,+ )+ summary = _preflight_summary(service)+ if output_dir is not None and manifest is not None:+ _apply_service_to_manifest(manifest, service)+ manifest["attempts"]["openapi_get"] = result.attempts+ atomic_write_bytes(output_dir / "response.json", result.body)+ _record_response(manifest, result)+ atomic_write_json(output_dir / "summary.json", summary)+ manifest["artifacts"]["summary"] = "summary.json"+ manifest["execution_status"] = "success"+ manifest["result_status"] = "not_available"+ _write_manifest(output_dir, manifest)+ print(+ f"ARAX {service.arax_version or 'unknown'}; TRAPI {service.trapi_version or 'unknown'}; "+ f"/query available at {service.base_url}"+ )+ for warning in service.warnings:+ print(f"warning {warning['code']}: {warning['message']}", file=sys.stderr)+ return 0+ except AraxClientError as exc:+ _retain_failure(output_dir, manifest, exc, stage)+ raise+++def handle_normalize(args: argparse.Namespace) -> int:+ if not 0 <= args.max_synonyms <= 50:+ raise UsageError("--max-synonyms must be between 0 and 50")+ expected_category = (+ validate_biolink_term(args.expected_category, "Biolink category")+ if args.expected_category+ else None+ )+ if not args.term or len(args.term) > MAX_IDENTIFIER_LENGTH or _has_control(args.term):+ raise UsageError("normalization term must be control-free and at most 200 characters")+ base_url, endpoint_warnings = validate_base_url(args.base_url, args.allow_nonproduction_endpoint)+ output_dir = prepare_output_directory(args.output_dir)+ manifest = new_manifest(+ "normalize", base_url=base_url, privacy_acknowledged=True, http_timeout=GET_TIMEOUT_SECONDS+ )+ stage = "openapi"+ try:+ service, preflight_result = fetch_openapi(+ base_url,+ allow_untested_version=args.allow_untested_version,+ initial_warnings=endpoint_warnings,+ )+ _apply_service_to_manifest(manifest, service)+ manifest["attempts"]["openapi_get"] = preflight_result.attempts+ stage = "entity"+ manifest["request"].update(+ {+ "method": "GET",+ "url": base_url + "/entity?" + urllib.parse.urlencode({"q": args.term}),+ }+ )+ entity_result = normalize_entity_request(base_url, args.term)+ manifest["attempts"]["entity_get"] = entity_result.attempts+ atomic_write_bytes(output_dir / "response.json", entity_result.body)+ _record_response(manifest, entity_result)+ payload = _json_from_http(entity_result, "entity response")+ summary, usable = parse_normalization_response(+ payload,+ term=args.term,+ expected_category=expected_category,+ max_synonyms=args.max_synonyms,+ service=service,+ )+ atomic_write_json(output_dir / "summary.json", summary)+ manifest["artifacts"]["summary"] = "summary.json"+ manifest["warnings"] = summary["warnings"]+ manifest["execution_status"] = "success"+ manifest["result_status"] = "results" if usable else "no_results"+ _write_manifest(output_dir, manifest)+ if not usable:+ raise NormalizationError("normalization returned no usable canonical CURIE")+ canonical = summary["canonical"]+ print(+ f"Canonical: {canonical['identifier']} ({canonical.get('name') or 'name not returned'}; "+ f"{canonical.get('category') or 'category not returned'})"+ )+ if summary["query"]["requires_user_confirmation"]:+ print("Review and confirm this normalization before constructing a graph query.")+ return 0+ except NormalizationError:+ raise+ except AraxClientError as exc:+ _retain_failure(output_dir, manifest, exc, stage)+ raise+++def _build_from_args(args: argparse.Namespace) -> tuple[dict[str, Any], QueryContract, int]:+ providers, limit = resolve_mode(args.mode, args.kp or [], args.result_limit)+ if args.command == "one-hop":+ body = build_one_hop_query(+ subject_id=args.subject_id,+ subject_category=args.subject_category,+ predicates=args.predicate,+ object_id=args.object_id,+ object_category=args.object_category,+ qualifiers=parse_qualifiers(args.qualifier or []),+ mode=args.mode,+ provider_ids=providers,+ result_limit=limit,+ )+ timeout = LOOKUP_TIMEOUT_SECONDS if args.mode == "lookup" else FEDERATED_TIMEOUT_SECONDS+ else:+ body = build_two_hop_query(+ subject_id=args.subject_id,+ subject_category=args.subject_category,+ predicates_1=args.predicate_1,+ intermediate_category=args.intermediate_category,+ predicates_2=args.predicate_2,+ object_id=args.object_id,+ object_category=args.object_category,+ qualifiers_1=parse_qualifiers(args.qualifier_1 or []),+ qualifiers_2=parse_qualifiers(args.qualifier_2 or []),+ mode=args.mode,+ provider_ids=providers,+ expand_order=args.expand_order,+ result_limit=limit,+ )+ timeout = LOOKUP_TIMEOUT_SECONDS if args.mode == "lookup" else FEDERATED_TIMEOUT_SECONDS+ return body, validate_saved_request_contract(body), timeout+++def _validate_query_response_version(+ payload: Mapping[str, Any],+ allow_untested_version: bool,+ warnings: list[dict[str, Any]],+) -> None:+ try:+ _check_trapi_version(+ payload.get("schema_version") if isinstance(payload.get("schema_version"), str) else None,+ allow_untested_version,+ warnings,+ )+ except PreflightError:+ raise+++def handle_graph_query(args: argparse.Namespace) -> int:+ body, contract, timeout = _build_from_args(args)+ request_bytes = serialize_request(body)+ base_url, endpoint_warnings = validate_base_url(args.base_url, args.allow_nonproduction_endpoint)+ output_dir = prepare_output_directory(args.output_dir)+ manifest = new_manifest(+ args.command,+ base_url=base_url,+ privacy_acknowledged=True,+ http_timeout=timeout,+ result_limit=contract.result_limit,+ )+ stage = "openapi"+ try:+ service, preflight_result = fetch_openapi(+ base_url,+ allow_untested_version=args.allow_untested_version,+ initial_warnings=endpoint_warnings,+ )+ _apply_service_to_manifest(manifest, service)+ manifest["attempts"]["openapi_get"] = preflight_result.attempts+ stage = "query"+ atomic_write_bytes(output_dir / "request.json", request_bytes)+ manifest["request"].update(+ {+ "method": "POST",+ "url": base_url + "/query",+ "file": "request.json",+ "bytes": len(request_bytes),+ "sha256": sha256_bytes(request_bytes),+ }+ )+ manifest["artifacts"]["request"] = "request.json"+ result = post_query(base_url + "/query", request_bytes, timeout=timeout)+ manifest["attempts"]["query_post"] = result.attempts+ atomic_write_bytes(output_dir / "response.json", result.body)+ _record_response(manifest, result)+ payload = _json_from_http(result, "TRAPI response")+ if not isinstance(payload, dict):+ raise ResponseError("TRAPI response is not an object")+ warnings = [dict(item) for item in service.warnings]+ _append_warning(warnings, "PUBLIC_QUERY", "The graph query was sent to a public service.")+ _validate_query_response_version(payload, args.allow_untested_version, warnings)+ summary = parse_trapi_response(payload, contract, service=service, initial_warnings=warnings)+ atomic_write_json(output_dir / "summary.json", summary)+ manifest["artifacts"]["summary"] = "summary.json"+ manifest["service"]["biolink_version"] = payload.get("biolink_version")+ manifest["warnings"] = summary["warnings"]+ manifest["execution_status"] = "success"+ if summary["completeness"] == "partial":+ manifest["result_status"] = "partial"+ exit_code = 7+ elif summary["counts"]["results_returned"] == 0:+ manifest["result_status"] = "no_results"+ exit_code = 0+ else:+ manifest["result_status"] = "results"+ exit_code = 0+ _write_manifest(output_dir, manifest)+ print(+ render_text_summary(+ summary,+ summary_path=str(output_dir / "summary.json"),+ response_path=str(output_dir / "response.json"),+ )+ )+ return exit_code+ except AraxClientError as exc:+ _retain_failure(output_dir, manifest, exc, stage)+ raise+++def handle_summarize(args: argparse.Namespace) -> int:+ request_path = Path(args.request)+ response_path = Path(args.response)+ try:+ request_bytes = request_path.read_bytes()+ response_bytes = response_path.read_bytes()+ except OSError as exc:+ raise UsageError(f"could not read saved artifact: {_sanitize_text(exc)}") from exc+ if len(response_bytes) > MAX_RESPONSE_BYTES:+ raise ResponseError("saved response exceeded the 25 MiB byte limit")+ request_payload = _decode_json(request_bytes, "saved request")+ response_payload = _decode_json(response_bytes, "saved response")+ contract = validate_saved_request_contract(request_payload)+ warnings: list[dict[str, Any]] = []+ if isinstance(response_payload, dict):+ _validate_query_response_version(response_payload, False, warnings)+ summary = parse_trapi_response(+ response_payload,+ contract,+ service=None,+ initial_warnings=warnings,+ )+ if args.format == "json":+ print(json.dumps(summary, indent=2, sort_keys=True, ensure_ascii=False))+ else:+ print(+ render_text_summary(+ summary,+ summary_path="standard output with --format json",+ response_path=str(response_path),+ )+ )+ return 7 if summary["completeness"] == "partial" else 0+++def _add_network_policy_options(parser: argparse.ArgumentParser) -> None:+ parser.add_argument("--base-url", default=PRODUCTION_BASE_URL)+ parser.add_argument("--allow-nonproduction-endpoint", action="store_true")+ parser.add_argument("--allow-untested-version", action="store_true")+++def _add_query_common(parser: argparse.ArgumentParser) -> None:+ parser.add_argument("--mode", choices=("lookup", "federated"), default="lookup")+ parser.add_argument("--kp", action="append", default=[])+ parser.add_argument("--result-limit", type=int)+ parser.add_argument("--acknowledge-public-query", action="store_true", required=True)+ parser.add_argument("--output-dir", required=True)+ _add_network_policy_options(parser)+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description="Bounded NCATS Translator ARAX lookup and provenance inspection"+ )+ subparsers = parser.add_subparsers(dest="command", required=True)++ preflight = subparsers.add_parser("preflight", help="verify the ARAX OpenAPI and versions")+ preflight.add_argument("--output-dir")+ _add_network_policy_options(preflight)++ normalize = subparsers.add_parser("normalize", help="normalize one term or CURIE for review")+ normalize.add_argument("term")+ normalize.add_argument("--expected-category")+ normalize.add_argument("--max-synonyms", type=int, default=10)+ normalize.add_argument("--acknowledge-public-query", action="store_true", required=True)+ normalize.add_argument("--output-dir", required=True)+ _add_network_policy_options(normalize)++ one_hop = subparsers.add_parser("one-hop", help="run a typed one-hop lookup")+ one_hop.add_argument("--subject-id", action=RejectRepeatedValueAction)+ one_hop.add_argument("--subject-category", required=True)+ one_hop.add_argument("--predicate", action="append", required=True)+ one_hop.add_argument("--object-id", action=RejectRepeatedValueAction)+ one_hop.add_argument("--object-category", required=True)+ one_hop.add_argument("--qualifier", action="append", default=[])+ _add_query_common(one_hop)++ two_hop = subparsers.add_parser("two-hop", help="run an endpoint-pinned two-hop lookup")+ two_hop.add_argument("--subject-id", required=True, action=RejectRepeatedValueAction)+ two_hop.add_argument("--subject-category", required=True)+ two_hop.add_argument("--predicate-1", action="append", required=True)+ two_hop.add_argument("--intermediate-category", required=True)+ two_hop.add_argument("--predicate-2", action="append", required=True)+ two_hop.add_argument("--object-id", required=True, action=RejectRepeatedValueAction)+ two_hop.add_argument("--object-category", required=True)+ two_hop.add_argument("--qualifier-1", action="append", default=[])+ two_hop.add_argument("--qualifier-2", action="append", default=[])+ two_hop.add_argument(+ "--expand-order", choices=("right-first", "left-first"), default="right-first"+ )+ _add_query_common(two_hop)++ summarize = subparsers.add_parser("summarize", help="inspect a saved supported ARAX response")+ summarize.add_argument("--request", required=True)+ summarize.add_argument("--response", required=True)+ summarize.add_argument("--format", choices=("text", "json"), default="text")+ return parser+++def main(argv: Sequence[str] | None = None) -> int:+ parser = build_parser()+ args = parser.parse_args(argv)+ try:+ if args.command == "preflight":+ return handle_preflight(args)+ if args.command == "normalize":+ return handle_normalize(args)+ if args.command in {"one-hop", "two-hop"}:+ return handle_graph_query(args)+ if args.command == "summarize":+ return handle_summarize(args)+ raise UsageError(f"unsupported command: {args.command}")+ except AraxClientError as exc:+ print(f"error: {exc}", file=sys.stderr)+ return exc.exit_code+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/ncats-arax/fixtures/federated_partial_response.json b/tests/ncats-arax/fixtures/federated_partial_response.jsonnew file mode 100644index 00000000..8e0a9632--- /dev/null+++ b/tests/ncats-arax/fixtures/federated_partial_response.json@@ -0,0 +1,34 @@+{+ "status": "Success",+ "schema_version": "1.5.0",+ "biolink_version": "4.2.1",+ "tool_version": "1.5.4",+ "logs": [+ {"level": "WARNING", "code": "KP_TIMEOUT", "message": "infores:molepro timed out"},+ {"level": "ERROR", "code": "KP_ERROR", "message": "KP infores:example returned HTTP 413"},+ {"level": "WARNING", "code": "DESERIALIZATION_ERROR", "message": "Malformed KP response could not be deserialized"}+ ],+ "message": {+ "knowledge_graph": {+ "nodes": {"CHEBI:31690": {"name": "imatinib"}, "NCBIGene:25": {"name": "ABL1"}},+ "edges": {+ "kg-partial": {+ "subject": "CHEBI:31690",+ "predicate": "biolink:affects",+ "object": "NCBIGene:25",+ "sources": [+ {"resource_id": "infores:drugbank", "resource_role": "primary_knowledge_source"},+ {"resource_id": "infores:rtx-kg2", "resource_role": "aggregator_knowledge_source"}+ ],+ "attributes": [{"attribute_type_id": "biolink:publications", "value": "PMID:300"}]+ }+ }+ },+ "results": [+ {+ "node_bindings": {"n0": [{"id": "CHEBI:31690"}], "n1": [{"id": "NCBIGene:25"}]},+ "analyses": [{"resource_id": "infores:arax", "edge_bindings": {"e0": [{"id": "kg-partial"}]}}]+ }+ ]+ }+}diff --git a/tests/ncats-arax/fixtures/missing_auxiliary_graph.json b/tests/ncats-arax/fixtures/missing_auxiliary_graph.jsonnew file mode 100644index 00000000..8b36c0a9--- /dev/null+++ b/tests/ncats-arax/fixtures/missing_auxiliary_graph.json@@ -0,0 +1,34 @@+{+ "status": "Success",+ "schema_version": "1.5.0",+ "biolink_version": "4.2.1",+ "tool_version": "1.5.4",+ "logs": [],+ "message": {+ "knowledge_graph": {+ "nodes": {"CHEBI:31690": {"name": "imatinib"}, "NCBIGene:25": {"name": "ABL1"}},+ "edges": {+ "kg-missing-aux": {+ "subject": "CHEBI:31690",+ "predicate": "biolink:affects",+ "object": "NCBIGene:25",+ "sources": [{"resource_id": "infores:drugbank", "resource_role": "primary_knowledge_source"}],+ "attributes": []+ }+ }+ },+ "auxiliary_graphs": {},+ "results": [+ {+ "node_bindings": {"n0": [{"id": "CHEBI:31690"}], "n1": [{"id": "NCBIGene:25"}]},+ "analyses": [+ {+ "resource_id": "infores:arax",+ "support_graphs": ["sg-absent"],+ "edge_bindings": {"e0": [{"id": "kg-missing-aux"}]}+ }+ ]+ }+ ]+ }+}diff --git a/tests/ncats-arax/fixtures/missing_publications.json b/tests/ncats-arax/fixtures/missing_publications.jsonnew file mode 100644index 00000000..e50e2ee5--- /dev/null+++ b/tests/ncats-arax/fixtures/missing_publications.json@@ -0,0 +1,30 @@+{+ "status": "Success",+ "schema_version": "1.5.0",+ "biolink_version": "4.2.1",+ "tool_version": "1.5.4",+ "logs": [],+ "message": {+ "knowledge_graph": {+ "nodes": {+ "CHEBI:31690": {"name": "imatinib"},+ "NCBIGene:25": {"name": "ABL1"}+ },+ "edges": {+ "kg-no-pubs": {+ "subject": "CHEBI:31690",+ "predicate": "biolink:affects",+ "object": "NCBIGene:25",+ "sources": [{"resource_id": "infores:drugbank", "resource_role": "primary_knowledge_source"}],+ "attributes": [{"attribute_type_id": "biolink:knowledge_level", "value": "knowledge_assertion"}]+ }+ }+ },+ "results": [+ {+ "node_bindings": {"n0": [{"id": "CHEBI:31690"}], "n1": [{"id": "NCBIGene:25"}]},+ "analyses": [{"resource_id": "infores:arax", "edge_bindings": {"e0": [{"id": "kg-no-pubs"}]}}]+ }+ ]+ }+}diff --git a/tests/ncats-arax/fixtures/no_results.json b/tests/ncats-arax/fixtures/no_results.jsonnew file mode 100644index 00000000..272f9262--- /dev/null+++ b/tests/ncats-arax/fixtures/no_results.json@@ -0,0 +1,12 @@+{+ "status": "Success",+ "schema_version": "1.5.0",+ "biolink_version": "4.2.1",+ "tool_version": "1.5.4",+ "total_results_count": 0,+ "logs": [],+ "message": {+ "knowledge_graph": {"nodes": {}, "edges": {}},+ "results": []+ }+}diff --git a/tests/ncats-arax/fixtures/normalization_response.json b/tests/ncats-arax/fixtures/normalization_response.jsonnew file mode 100644index 00000000..1074f7fe--- /dev/null+++ b/tests/ncats-arax/fixtures/normalization_response.json@@ -0,0 +1,28 @@+{+ "ivacaftor": {+ "categories": {+ "biolink:Drug": 3,+ "biolink:SmallMolecule": 2+ },+ "id": {+ "identifier": "CHEBI:66901",+ "name": "ivacaftor",+ "category": "biolink:SmallMolecule",+ "SRI_normalizer_name": "ivacaftor"+ },+ "knowledge_graph": {},+ "nodes": [+ {+ "identifier": "CHEBI:66901",+ "name": "ivacaftor",+ "category": "biolink:SmallMolecule"+ },+ {+ "identifier": "PUBCHEM.COMPOUND:16220172",+ "name": "Ivacaftor — synonym",+ "category": "biolink:SmallMolecule"+ }+ ],+ "total_synonyms": 2+ }+}diff --git a/tests/ncats-arax/fixtures/one_hop_provenance.json b/tests/ncats-arax/fixtures/one_hop_provenance.jsonnew file mode 100644index 00000000..642c3a67--- /dev/null+++ b/tests/ncats-arax/fixtures/one_hop_provenance.json@@ -0,0 +1,118 @@+{+ "status": "Success",+ "description": "Normal completion",+ "schema_version": "1.5.0",+ "biolink_version": "4.2.1",+ "tool_version": "1.5.4",+ "total_results_count": 1,+ "logs": [],+ "message": {+ "query_graph": {+ "nodes": {+ "n0": {"ids": ["CHEBI:31690"], "categories": ["biolink:SmallMolecule"]},+ "n1": {"ids": ["NCBIGene:25"], "categories": ["biolink:Gene"]}+ },+ "edges": {+ "e0": {"subject": "n0", "object": "n1", "predicates": ["biolink:affects"]}+ }+ },+ "knowledge_graph": {+ "nodes": {+ "CHEBI:31690": {"name": "imatinib methanesulfonate", "categories": ["biolink:SmallMolecule"]},+ "NCBIGene:25": {"name": "ABL1", "categories": ["biolink:Gene"]},+ "NCBIGene:999": {"name": "Unbound β node", "categories": ["biolink:Gene"]}+ },+ "edges": {+ "kg-e0-primary": {+ "subject": "CHEBI:31690",+ "predicate": "biolink:affects",+ "object": "NCBIGene:25",+ "qualifiers": [+ {"qualifier_type_id": "biolink:object_aspect_qualifier", "qualifier_value": "activity"},+ {"qualifier_type_id": "biolink:object_direction_qualifier", "qualifier_value": "decreased"}+ ],+ "sources": [+ {+ "resource_id": "infores:drugbank",+ "resource_role": "primary_knowledge_source",+ "source_record_urls": ["https://example.org/drugbank/one"]+ },+ {+ "resource_id": "infores:rtx-kg2",+ "resource_role": "aggregator_knowledge_source",+ "upstream_resource_ids": ["infores:drugbank"]+ },+ {+ "resource_id": "infores:arax",+ "resource_role": "aggregator_knowledge_source",+ "upstream_resource_ids": ["infores:rtx-kg2"]+ }+ ],+ "attributes": [+ {"attribute_type_id": "biolink:publications", "value": "PMID:100"}+ ]+ },+ "kg-e0-secondary": {+ "subject": "CHEBI:31690",+ "predicate": "biolink:affects",+ "object": "NCBIGene:25",+ "qualifiers": [+ {"qualifier_type_id": "biolink:object_direction_qualifier", "qualifier_value": "decreased"}+ ],+ "sources": [+ {"resource_id": "infores:semmeddb", "resource_role": "primary_knowledge_source"},+ {"resource_id": "infores:ctd", "resource_role": "supporting_data_source"}+ ],+ "attributes": [+ {"attribute_type_id": "biolink:publications", "value": ["PMID:101", "PMID:100"]}+ ]+ },+ "kg-e0-tertiary": {+ "subject": "CHEBI:31690",+ "predicate": "biolink:related_to",+ "object": "NCBIGene:25",+ "sources": [+ {"resource_id": "infores:dgidb", "resource_role": "primary_knowledge_source"}+ ],+ "attributes": []+ },+ "kg-unbound": {+ "subject": "CHEBI:31690",+ "predicate": "biolink:related_to",+ "object": "NCBIGene:999",+ "sources": [],+ "attributes": []+ }+ }+ },+ "auxiliary_graphs": {+ "sg-one": {"edges": ["kg-e0-primary"]}+ },+ "results": [+ {+ "description": "Imatinib–ABL1 candidate",+ "node_bindings": {+ "n0": [{"id": "CHEBI:31690", "query_id": "CHEBI:31690", "attributes": []}],+ "n1": [{"id": "NCBIGene:25", "query_id": "NCBIGene:25", "attributes": []}]+ },+ "analyses": [+ {+ "resource_id": "infores:arax",+ "score": null,+ "support_graphs": ["sg-one"],+ "edge_bindings": {+ "e0": [{"id": "kg-e0-primary"}, {"id": "kg-e0-secondary"}]+ }+ },+ {+ "resource_id": "infores:arax",+ "score": null,+ "edge_bindings": {+ "e0": [{"id": "kg-e0-tertiary"}]+ }+ }+ ]+ }+ ]+ }+}diff --git a/tests/ncats-arax/fixtures/openapi_1_5_minimal.json b/tests/ncats-arax/fixtures/openapi_1_5_minimal.jsonnew file mode 100644index 00000000..8e8c3dca--- /dev/null+++ b/tests/ncats-arax/fixtures/openapi_1_5_minimal.json@@ -0,0 +1,20 @@+{+ "openapi": "3.0.1",+ "info": {+ "title": "ARAX Translator Reasoner - TRAPI 1.5.0",+ "version": "1.5.4"+ },+ "servers": [+ {+ "url": "/api/arax/v1.4"+ }+ ],+ "paths": {+ "/entity": {+ "get": {}+ },+ "/query": {+ "post": {}+ }+ }+}diff --git a/tests/ncats-arax/fixtures/reversed_edge.json b/tests/ncats-arax/fixtures/reversed_edge.jsonnew file mode 100644index 00000000..15b0c6e9--- /dev/null+++ b/tests/ncats-arax/fixtures/reversed_edge.json@@ -0,0 +1,35 @@+{+ "status": "Success",+ "schema_version": "1.5.0",+ "biolink_version": "4.2.1",+ "tool_version": "1.5.4",+ "logs": [],+ "message": {+ "knowledge_graph": {+ "nodes": {+ "CHEBI:31690": {"name": "imatinib"},+ "NCBIGene:25": {"name": "ABL1"}+ },+ "edges": {+ "kg-reversed": {+ "subject": "NCBIGene:25",+ "predicate": "biolink:affected_by",+ "object": "CHEBI:31690",+ "sources": [{"resource_id": "infores:drugbank", "resource_role": "primary_knowledge_source"}],+ "attributes": []+ }+ }+ },+ "results": [+ {+ "node_bindings": {+ "n0": [{"id": "CHEBI:31690"}],+ "n1": [{"id": "NCBIGene:25"}]+ },+ "analyses": [+ {"resource_id": "infores:arax", "score": null, "edge_bindings": {"e0": [{"id": "kg-reversed"}]}}+ ]+ }+ ]+ }+}diff --git a/tests/ncats-arax/fixtures/two_hop_provenance.json b/tests/ncats-arax/fixtures/two_hop_provenance.jsonnew file mode 100644index 00000000..e81b60a0--- /dev/null+++ b/tests/ncats-arax/fixtures/two_hop_provenance.json@@ -0,0 +1,77 @@+{+ "status": "Success",+ "schema_version": "1.5.0",+ "biolink_version": "4.2.1",+ "tool_version": "1.5.4",+ "total_results_count": 1,+ "logs": [],+ "message": {+ "query_graph": {+ "nodes": {+ "n0": {"ids": ["CHEBI:66901"], "categories": ["biolink:SmallMolecule"]},+ "n1": {"categories": ["biolink:Gene"]},+ "n2": {"ids": ["MONDO:0009061"], "categories": ["biolink:Disease"]}+ },+ "edges": {+ "e0": {"subject": "n0", "object": "n1", "predicates": ["biolink:affects"]},+ "e1": {"subject": "n1", "object": "n2", "predicates": ["biolink:associated_with"]}+ }+ },+ "knowledge_graph": {+ "nodes": {+ "CHEBI:66901": {"name": "ivacaftor"},+ "NCBIGene:1080": {"name": "CFTR"},+ "MONDO:0009061": {"name": "cystic fibrosis"}+ },+ "edges": {+ "kg-drug-gene": {+ "subject": "CHEBI:66901",+ "predicate": "biolink:affects",+ "object": "NCBIGene:1080",+ "qualifiers": [+ {"qualifier_type_id": "biolink:object_aspect_qualifier", "qualifier_value": "activity"},+ {"qualifier_type_id": "biolink:object_direction_qualifier", "qualifier_value": "increased"}+ ],+ "sources": [+ {"resource_id": "infores:drugcentral", "resource_role": "primary_knowledge_source"},+ {"resource_id": "infores:rtx-kg2", "resource_role": "aggregator_knowledge_source", "upstream_resource_ids": ["infores:drugcentral"]}+ ],+ "attributes": [{"attribute_type_id": "biolink:publications", "value": ["PMID:200"]}]+ },+ "kg-gene-disease": {+ "subject": "NCBIGene:1080",+ "predicate": "biolink:gene_associated_with_condition",+ "object": "MONDO:0009061",+ "sources": [+ {"resource_id": "infores:disgenet", "resource_role": "primary_knowledge_source"},+ {"resource_id": "infores:arax", "resource_role": "aggregator_knowledge_source", "upstream_resource_ids": ["infores:rtx-kg2"]}+ ],+ "attributes": [{"attribute_type_id": "biolink:publications", "value": "PMID:201"}]+ }+ }+ },+ "auxiliary_graphs": {+ "sg-two": {"edges": ["kg-drug-gene", "kg-gene-disease"]}+ },+ "results": [+ {+ "node_bindings": {+ "n0": [{"id": "CHEBI:66901"}],+ "n1": [{"id": "NCBIGene:1080"}],+ "n2": [{"id": "MONDO:0009061"}]+ },+ "analyses": [+ {+ "resource_id": "infores:arax",+ "score": null,+ "support_graphs": ["sg-two"],+ "edge_bindings": {+ "e0": [{"id": "kg-drug-gene"}],+ "e1": [{"id": "kg-gene-disease"}]+ }+ }+ ]+ }+ ]+ }+}diff --git a/tests/ncats-arax/test_scripts.py b/tests/ncats-arax/test_scripts.pynew file mode 100644index 00000000..6625fc7e--- /dev/null+++ b/tests/ncats-arax/test_scripts.py@@ -0,0 +1,1531 @@+from __future__ import annotations++import argparse+import copy+import importlib.util+import io+import json+import os+import re+import stat+import sys+import tempfile+import unittest+import urllib.error+import urllib.request+from datetime import datetime, timedelta, timezone+from email.message import Message+from pathlib import Path+from unittest import mock++import skill_contract+++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "ncats-arax"+SCRIPT = SKILL_ROOT / "scripts" / "arax_client.py"+FIXTURES = Path(__file__).resolve().parent / "fixtures"+++def _load_client():+ spec = importlib.util.spec_from_file_location("ncats_arax_client", SCRIPT)+ module = importlib.util.module_from_spec(spec)+ sys.modules[spec.name] = module+ assert spec.loader is not None+ spec.loader.exec_module(module)+ return module+++client = _load_client()+CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+++def fixture_bytes(name: str) -> bytes:+ return (FIXTURES / name).read_bytes()+++def fixture_json(name: str):+ return json.loads(fixture_bytes(name).decode("utf-8"))+++def one_hop_body(**overrides):+ values = {+ "subject_id": "CHEBI:31690",+ "subject_category": "biolink:SmallMolecule",+ "predicates": ["biolink:affects"],+ "object_id": "NCBIGene:25",+ "object_category": "biolink:Gene",+ "qualifiers": [+ ("biolink:object_aspect_qualifier", "activity_or_abundance"),+ ("biolink:object_direction_qualifier", "decreased"),+ ],+ "mode": "lookup",+ "provider_ids": ["infores:rtx-kg2"],+ "result_limit": 20,+ }+ values.update(overrides)+ return client.build_one_hop_query(**values)+++def two_hop_body(**overrides):+ values = {+ "subject_id": "CHEBI:66901",+ "subject_category": "biolink:SmallMolecule",+ "predicates_1": ["biolink:affects"],+ "intermediate_category": "biolink:Gene",+ "predicates_2": ["biolink:associated_with"],+ "object_id": "MONDO:0009061",+ "object_category": "biolink:Disease",+ "qualifiers_1": [+ ("biolink:object_aspect_qualifier", "activity_or_abundance"),+ ("biolink:object_direction_qualifier", "increased"),+ ],+ "qualifiers_2": [],+ "mode": "lookup",+ "provider_ids": ["infores:rtx-kg2"],+ "expand_order": "right-first",+ "result_limit": 20,+ }+ values.update(overrides)+ return client.build_two_hop_query(**values)+++def service_info(warnings=()):+ return client.ServiceInfo(+ base_url=client.PRODUCTION_BASE_URL,+ openapi_url=client.PRODUCTION_BASE_URL + "/openapi.json",+ arax_version="1.5.4",+ trapi_version="1.5.0",+ warnings=tuple(warnings),+ )+++def one_hop_args(output_dir: Path, **overrides):+ values = {+ "command": "one-hop",+ "subject_id": "CHEBI:31690",+ "subject_category": "biolink:SmallMolecule",+ "predicate": ["biolink:affects"],+ "object_id": "NCBIGene:25",+ "object_category": "biolink:Gene",+ "qualifier": [],+ "mode": "lookup",+ "kp": [],+ "result_limit": 20,+ "acknowledge_public_query": True,+ "output_dir": str(output_dir),+ "base_url": client.PRODUCTION_BASE_URL,+ "allow_nonproduction_endpoint": False,+ "allow_untested_version": False,+ }+ values.update(overrides)+ return argparse.Namespace(**values)+++def normalize_args(output_dir: Path, **overrides):+ values = {+ "term": "ivacaftor",+ "expected_category": "biolink:SmallMolecule",+ "max_synonyms": 10,+ "acknowledge_public_query": True,+ "output_dir": str(output_dir),+ "base_url": client.PRODUCTION_BASE_URL,+ "allow_nonproduction_endpoint": False,+ "allow_untested_version": False,+ }+ values.update(overrides)+ return argparse.Namespace(**values)+++class FakeResponse:+ def __init__(self, body: bytes, *, status: int = 200, headers=None):+ self.body = io.BytesIO(body)+ self.status = status+ self.headers = headers or {}++ def read(self, amount=-1):+ return self.body.read(amount)++ def getcode(self):+ return self.status++ def close(self):+ self.body.close()++ def __enter__(self):+ return self++ def __exit__(self, exc_type, exc, traceback):+ return False+++class ValidationTests(unittest.TestCase):+ def test_curie_validation(self):+ self.assertEqual(client.validate_curie("CHEBI:31690"), "CHEBI:31690")+ for invalid in ("CHEBI", "9CHEBI:1", "CHEBI:one two", "CHEBI:one\ntwo", "CHEBI:\x00one", "X:" + "a" * 201):+ with self.subTest(invalid=repr(invalid)), self.assertRaises(client.UsageError):+ client.validate_curie(invalid)++ def test_biolink_and_provider_validation(self):+ self.assertEqual(client.validate_biolink_term("biolink:Gene"), "biolink:Gene")+ self.assertEqual(client.validate_provider_id("infores:rtx-kg2"), "infores:rtx-kg2")+ for invalid in ("Gene", "biolink:", "biolink:Gene name"):+ with self.subTest(invalid=invalid), self.assertRaises(client.UsageError):+ client.validate_biolink_term(invalid)+ for invalid in ("rtx-kg2", "infores:all", "infores:a,b", "infores:a]", "infores:a=b"):+ with self.subTest(invalid=invalid), self.assertRaises(client.UsageError):+ client.validate_provider_id(invalid)++ def test_qualifier_limits_and_duplicate_types(self):+ parsed = client.parse_qualifiers(+ [+ "biolink:object_aspect_qualifier=activity_or_abundance",+ "biolink:object_direction_qualifier=decreased",+ ]+ )+ self.assertEqual(len(parsed), 2)+ with self.assertRaises(client.UsageError):+ client.parse_qualifiers(["missing-equals"])+ with self.assertRaises(client.UsageError):+ client.parse_qualifiers(+ [+ "biolink:object_direction_qualifier=decreased",+ "biolink:object_direction_qualifier=increased",+ ]+ )+ with self.assertRaises(client.UsageError):+ client.parse_qualifiers([f"biolink:q{i}=v" for i in range(7)])++ def test_mode_provider_and_result_caps(self):+ self.assertEqual(client.resolve_mode("lookup", [], None), (["infores:rtx-kg2"], 20))+ self.assertEqual(+ client.resolve_mode("federated", ["infores:rtx-kg2", "infores:molepro"], None),+ (["infores:rtx-kg2", "infores:molepro"], 50),+ )+ invalid = [+ ("lookup", ["infores:rtx-kg2"], None),+ ("federated", [], None),+ ("federated", ["infores:rtx-kg2"], None),+ ("federated", ["infores:a", "infores:a"], None),+ ("federated", [f"infores:k{i}" for i in range(6)], None),+ ("lookup", [], 51),+ ("lookup", [], 0),+ ]+ for values in invalid:+ with self.subTest(values=values), self.assertRaises(client.UsageError):+ client.resolve_mode(*values)++ def test_one_hop_requires_a_pinned_endpoint(self):+ with self.assertRaises(client.UsageError):+ one_hop_body(subject_id=None, object_id=None)++ def test_base_url_policy(self):+ url, warnings = client.validate_base_url(client.PRODUCTION_BASE_URL, False)+ self.assertEqual(url, client.PRODUCTION_BASE_URL)+ self.assertEqual(warnings, [])+ with self.assertRaises(client.PreflightError):+ client.validate_base_url("https://arax.ncats.io/api/arax/v1.4", False)+ url, warnings = client.validate_base_url("https://arax.ncats.io/api/arax/v1.4/", True)+ self.assertEqual(url, "https://arax.ncats.io/api/arax/v1.4")+ self.assertEqual(warnings[0]["code"], "NONPRODUCTION_ENDPOINT")+ for invalid in (+ "http://arax.transltr.io/api/arax/v1.4",+ "https://user:[email protected]/arax",+ "https://localhost/arax",+ "https://127.0.0.1/arax",+ "https://example.org:abc/arax",+ "https://example.org/arax?q=one",+ "https://example.org/arax#fragment",+ ):+ with self.subTest(invalid=invalid), self.assertRaises(client.UsageError):+ client.validate_base_url(invalid, True)++ def test_repeated_endpoint_flag_is_rejected(self):+ parser = client.build_parser()+ with self.assertRaises(SystemExit) as raised, mock.patch("sys.stderr", new=io.StringIO()):+ parser.parse_args(+ [+ "one-hop",+ "--subject-id",+ "CHEBI:1",+ "--subject-id",+ "CHEBI:2",+ "--subject-category",+ "biolink:SmallMolecule",+ "--predicate",+ "biolink:related_to",+ "--object-category",+ "biolink:Gene",+ "--acknowledge-public-query",+ "--output-dir",+ "out",+ ]+ )+ self.assertEqual(raised.exception.code, 2)++ def test_parser_exposes_no_arbitrary_or_batch_query_surface(self):+ parser = client.build_parser()+ option_strings = {+ option+ for action in parser._actions+ for option in action.option_strings+ }+ subparsers = next(+ action for action in parser._actions if isinstance(action, argparse._SubParsersAction)+ )+ for subparser in subparsers.choices.values():+ option_strings.update(+ option for action in subparser._actions for option in action.option_strings+ )+ for excluded in (+ "--raw-query",+ "--query-file",+ "--workflow",+ "--action",+ "--overlay",+ "--rank",+ "--inference",+ "--ars",+ "--batch",+ "--all-kps",+ ):+ self.assertNotIn(excluded, option_strings)+++class RequestBuilderTests(unittest.TestCase):+ def test_one_hop_exact_shape_and_and_qualifiers(self):+ body = one_hop_body(object_id=None)+ graph = body["message"]["query_graph"]+ self.assertEqual(set(graph["nodes"]), {"n0", "n1"})+ self.assertNotIn("ids", graph["nodes"]["n1"])+ self.assertEqual(graph["edges"]["e0"]["subject"], "n0")+ self.assertEqual(graph["edges"]["e0"]["object"], "n1")+ constraints = graph["edges"]["e0"]["qualifier_constraints"]+ self.assertEqual(len(constraints), 1)+ self.assertEqual(len(constraints[0]["qualifier_set"]), 2)+ self.assertEqual(body["submitter"], client.SUBMITTER)+ self.assertNotIn("workflow", body)++ def test_empty_qualifiers_are_omitted(self):+ edge = one_hop_body(qualifiers=[])["message"]["query_graph"]["edges"]["e0"]+ self.assertNotIn("qualifier_constraints", edge)++ def test_two_hop_right_and_left_first(self):+ right = two_hop_body()+ left = two_hop_body(expand_order="left-first")+ graph = right["message"]["query_graph"]+ self.assertEqual(set(graph["nodes"]), {"n0", "n1", "n2"})+ self.assertNotIn("ids", graph["nodes"]["n1"])+ fixed_tail = [+ "scoreless_resultify(ignore_edge_direction=true)",+ "filter_results(action=limit_number_of_results,max_results=20,prune_kg=true)",+ "return(response=true,store=false)",+ ]+ self.assertEqual(+ right["operations"]["actions"],+ [+ "expand(edge_key=e1,kp=infores:rtx-kg2,kp_timeout=30,return_minimal_metadata=false)",+ "expand(edge_key=e0,kp=infores:rtx-kg2,kp_timeout=30,return_minimal_metadata=false)",+ *fixed_tail,+ ],+ )+ self.assertEqual(+ left["operations"]["actions"],+ [+ "expand(edge_key=e0,kp=infores:rtx-kg2,kp_timeout=30,return_minimal_metadata=false)",+ "expand(edge_key=e1,kp=infores:rtx-kg2,kp_timeout=30,return_minimal_metadata=false)",+ *fixed_tail,+ ],+ )+ self.assertIs(right["stream_progress"], False)++ def test_federation_uses_one_list_valued_kp(self):+ body = two_hop_body(+ mode="federated",+ provider_ids=["infores:rtx-kg2", "infores:molepro"],+ result_limit=50,+ )+ for action in body["operations"]["actions"][:2]:+ self.assertIn("kp=[infores:rtx-kg2,infores:molepro]", action)+ self.assertEqual(action.count("kp="), 1)++ def test_fixed_actions_exclude_banned_workflows(self):+ serialized = client.serialize_request(two_hop_body()).decode("utf-8")+ self.assertIn("scoreless_resultify(ignore_edge_direction=true)", serialized)+ self.assertIn("return(response=true,store=false)", serialized)+ for banned in ("overlay", "rank_results", "infer", "pathfinder", "workflow"):+ self.assertNotIn(banned, serialized.lower())++ def test_deterministic_non_ascii_serialization(self):+ body = one_hop_body()+ body["message"]["note"] = "β"+ encoded = client.serialize_request(body)+ self.assertIn("β".encode("utf-8"), encoded)+ self.assertNotIn(b" ", encoded)+ self.assertEqual(encoded, client.serialize_request(body))++ def test_strict_json_rejects_nonfinite_numbers(self):+ with self.assertRaises(client.UsageError):+ client.serialize_request({"score": float("nan")})+ for constant in (b'{"score":NaN}', b'{"score":Infinity}', b'{"score":-Infinity}'):+ with self.subTest(constant=constant), self.assertRaises(client.ResponseError):+ client._decode_json(constant, "fixture")++ def test_saved_request_validator_rejects_escape_hatches(self):+ body = two_hop_body()+ contract = client.validate_saved_request_contract(body)+ self.assertEqual(contract.kind, "two-hop")+ self.assertEqual(contract.expand_order, "right-first")+ mutations = []+ workflow = copy.deepcopy(body)+ workflow["workflow"] = []+ mutations.append(workflow)+ overlay = copy.deepcopy(body)+ overlay["operations"]["actions"][0] = "overlay(action=compute_ngd)"+ mutations.append(overlay)+ ranked = copy.deepcopy(body)+ ranked["operations"]["actions"][-3] = "rank_results()"+ mutations.append(ranked)+ third_hop = copy.deepcopy(body)+ third_hop["message"]["query_graph"]["nodes"]["n3"] = {"categories": ["biolink:Gene"]}+ mutations.append(third_hop)+ all_kp = copy.deepcopy(body)+ all_kp["operations"]["actions"][0] = all_kp["operations"]["actions"][0].replace(+ "kp=infores:rtx-kg2", "kp=[]"+ )+ mutations.append(all_kp)+ extra_cases = [+ ("inferred", ("message", "query_graph", "edges", "e0"), "knowledge_type", "inferred"),+ ("creative", (), "workflow", [{"id": "lookup_and_score"}]),+ ("pathfinder", (), "pathfinder", True),+ ("batch_ids", ("message", "query_graph", "nodes", "n0"), "ids", ["CHEBI:1", "CHEBI:2"]),+ ("qnode_escape", ("message", "query_graph", "nodes", "n1"), "is_set", True),+ ("result_limit", (), None, None),+ ("streaming", (), "stream_progress", True),+ ("altered_return", (), None, None),+ ("duplicate_expand", (), None, None),+ ("missing_action", (), None, None),+ ("wildcard_provider", (), None, None),+ ("mixed_providers", (), None, None),+ ]+ for name, path, key, value in extra_cases:+ mutation = copy.deepcopy(body)+ target = mutation+ for item in path:+ target = target[item]+ if key is not None:+ target[key] = value+ elif name == "result_limit":+ mutation["operations"]["actions"][-2] = mutation["operations"]["actions"][-2].replace(+ "max_results=20", "max_results=51"+ )+ elif name == "altered_return":+ mutation["operations"]["actions"][-1] = "return(response=true,store=true)"+ elif name == "duplicate_expand":+ mutation["operations"]["actions"][1] = mutation["operations"]["actions"][0]+ elif name == "missing_action":+ mutation["operations"]["actions"].pop()+ elif name == "wildcard_provider":+ mutation["operations"]["actions"][0] = mutation["operations"]["actions"][0].replace(+ "kp=infores:rtx-kg2", "kp=*"+ )+ elif name == "mixed_providers":+ mutation["operations"]["actions"][1] = mutation["operations"]["actions"][1].replace(+ "kp=infores:rtx-kg2", "kp=[infores:rtx-kg2,infores:molepro]"+ )+ mutations.append(mutation)+ for mutation in mutations:+ with self.subTest(mutation=mutation), self.assertRaises(client.UsageError):+ client.validate_saved_request_contract(mutation)+++class OpenApiAndTransportTests(unittest.TestCase):+ def test_minimal_openapi_parses(self):+ service = client.parse_openapi_service_info(+ fixture_json("openapi_1_5_minimal.json"),+ base_url=client.PRODUCTION_BASE_URL,+ openapi_url=client.PRODUCTION_BASE_URL + "/openapi.json",+ allow_untested_version=False,+ )+ self.assertEqual(service.arax_version, "1.5.4")+ self.assertEqual(service.trapi_version, "1.5.0")+ self.assertEqual(service.warnings, ())++ def test_openapi_title_path_and_version_failures(self):+ base = fixture_json("openapi_1_5_minimal.json")+ cases = []+ wrong_title = copy.deepcopy(base)+ wrong_title["info"]["title"] = "Other ARA - TRAPI 1.5.0"+ cases.append(wrong_title)+ no_query = copy.deepcopy(base)+ del no_query["paths"]["/query"]+ cases.append(no_query)+ unknown = copy.deepcopy(base)+ unknown["info"]["title"] = "ARAX Translator Reasoner - TRAPI 2.0.0"+ cases.append(unknown)+ for payload in cases:+ with self.subTest(payload=payload), self.assertRaises(client.PreflightError):+ client.parse_openapi_service_info(+ payload,+ base_url=client.PRODUCTION_BASE_URL,+ openapi_url=client.PRODUCTION_BASE_URL + "/openapi.json",+ allow_untested_version=False,+ )++ def test_known_version_skew_warns_and_unknown_override_warns(self):+ payload = fixture_json("openapi_1_5_minimal.json")+ payload["info"]["title"] = "ARAX Translator Reasoner - TRAPI 1.6.0"+ payload["info"]["version"] = "1.6.2"+ service = client.parse_openapi_service_info(+ payload,+ base_url=client.PRODUCTION_BASE_URL,+ openapi_url=client.PRODUCTION_BASE_URL + "/openapi.json",+ allow_untested_version=False,+ )+ self.assertTrue(all(item["code"] == "UNTESTED_SERVICE_VERSION" for item in service.warnings))+ payload["info"]["title"] = "ARAX Translator Reasoner - TRAPI 2.0.0"+ service = client.parse_openapi_service_info(+ payload,+ base_url=client.PRODUCTION_BASE_URL,+ openapi_url=client.PRODUCTION_BASE_URL + "/openapi.json",+ allow_untested_version=True,+ )+ self.assertIn("UNTESTED_SERVICE_VERSION", {item["code"] for item in service.warnings})++ def test_get_retries_one_retryable_status(self):+ headers = Message()+ headers["Retry-After"] = "0"+ failure = urllib.error.HTTPError("https://example.org", 503, "busy", headers, io.BytesIO(b"busy"))+ sleeps = []+ with mock.patch.object(+ client,+ "_open_url",+ side_effect=[failure, FakeResponse(b"{}")],+ ) as opener:+ result = client.request_get_with_retry("https://example.org", sleep=sleeps.append)+ self.assertEqual(result.attempts, 2)+ self.assertEqual(sleeps, [0.0])+ self.assertEqual(opener.call_count, 2)++ def test_get_headers_timeout_and_http_date_retry_after(self):+ captured = {}++ def opened(request, timeout):+ captured["request"] = request+ captured["timeout"] = timeout+ return FakeResponse(b"{}")++ with mock.patch.object(client, "_open_url", side_effect=opened):+ client.request_get_with_retry("https://example.org/data", timeout=17)+ headers = {key.lower(): value for key, value in captured["request"].header_items()}+ self.assertEqual(captured["request"].method, "GET")+ self.assertEqual(captured["timeout"], 17)+ self.assertEqual(headers["accept"], "application/json")+ self.assertEqual(headers["accept-encoding"], "identity")+ self.assertEqual(headers["user-agent"], client.USER_AGENT)++ now = datetime(2026, 8, 7, 12, 0, tzinfo=timezone.utc)+ retry_at = now + timedelta(seconds=7)+ self.assertEqual(+ client._retry_delay(+ {"Retry-After": retry_at.strftime("%a, %d %b %Y %H:%M:%S GMT")},+ now=lambda: now,+ ),+ 7.0,+ )++ def test_redirects_are_https_and_same_origin_only(self):+ handler = client.SameOriginHttpsRedirectHandler()+ request = urllib.request.Request("https://example.org/start")+ headers = Message()+ redirected = handler.redirect_request(+ request,+ FakeResponse(b""),+ 302,+ "found",+ headers,+ "https://example.org/next",+ )+ self.assertEqual(redirected.full_url, "https://example.org/next")+ for destination in (+ "https://other.example/next",+ "http://example.org/next",+ "https://example.org:abc/next",+ ):+ with self.subTest(destination=destination), self.assertRaises(urllib.error.HTTPError):+ handler.redirect_request(+ request,+ FakeResponse(b""),+ 302,+ "found",+ headers,+ destination,+ )++ def test_get_retries_timeout_but_not_other_transport(self):+ with mock.patch.object(+ client,+ "_open_url",+ side_effect=[TimeoutError("slow"), FakeResponse(b"{}")],+ ) as opener:+ result = client.request_get_with_retry("https://example.org", sleep=lambda _: None)+ self.assertEqual(result.attempts, 2)+ self.assertEqual(opener.call_count, 2)+ with mock.patch.object(+ client, "_open_url", side_effect=urllib.error.URLError("dns")+ ) as opener:+ with self.assertRaises(client.TransportError):+ client.request_get_with_retry("https://example.org", sleep=lambda _: None)+ self.assertEqual(opener.call_count, 1)++ def test_post_never_retries_and_uses_identity_encoding(self):+ captured = []++ def fail(request, timeout):+ captured.append((request, timeout))+ raise urllib.error.URLError("offline")++ with mock.patch.object(client, "_open_url", side_effect=fail):+ with self.assertRaises(client.TransportError):+ client.post_query("https://example.org/query", b"{}", timeout=120)+ self.assertEqual(len(captured), 1)+ headers = {key.lower(): value for key, value in captured[0][0].header_items()}+ self.assertEqual(headers["accept-encoding"], "identity")+ self.assertEqual(headers["user-agent"], client.USER_AGENT)++ def test_response_byte_limit(self):+ self.assertEqual(client.read_bounded_response(FakeResponse(b"12345"), 5), b"12345")+ with self.assertRaises(client.ResponseError):+ client.read_bounded_response(FakeResponse(b"123456"), 5)++ def test_oversized_success_and_http_error_preserve_exit_and_attempts(self):+ oversized = client.ResponseError("too large")+ with mock.patch.object(client, "_open_url", return_value=FakeResponse(b"{}")), mock.patch.object(+ client, "read_bounded_response", side_effect=oversized+ ):+ with self.assertRaises(client.ResponseError) as raised:+ client.request_get_with_retry("https://example.org")+ self.assertEqual(raised.exception.exit_code, 6)+ self.assertEqual(raised.exception.attempts, 1)+ self.assertEqual(raised.exception.http_status, 200)++ error = urllib.error.HTTPError(+ "https://example.org", 500, "failure", Message(), io.BytesIO(b"large")+ )+ with mock.patch.object(client, "_open_url", side_effect=error), mock.patch.object(+ client, "read_bounded_response", side_effect=client.ResponseError("too large")+ ):+ with self.assertRaises(client.ResponseError) as raised:+ client.post_query("https://example.org/query", b"{}", timeout=120)+ self.assertEqual(raised.exception.exit_code, 6)+ self.assertEqual(raised.exception.attempts, 1)+ self.assertEqual(raised.exception.http_status, 500)++ def test_retry_after_is_capped_and_invalid_defaults(self):+ self.assertEqual(client._retry_delay({"Retry-After": "99"}), 10.0)+ self.assertEqual(client._retry_delay({"Retry-After": "invalid"}), 1.0)++ def test_query_response_version_policy(self):+ for version, allowed, warning in (+ ("1.5.0", False, False),+ ("1.6.0", False, True),+ ("2.0.0", True, True),+ ):+ warnings = []+ client._validate_query_response_version(+ {"schema_version": version}, allowed, warnings+ )+ self.assertEqual(bool(warnings), warning)+ with self.assertRaises(client.PreflightError):+ client._validate_query_response_version(+ {"schema_version": "2.0.0"}, False, []+ )+++class NormalizationTests(unittest.TestCase):+ def test_nested_normalization_match_and_mismatch(self):+ payload = fixture_json("normalization_response.json")+ summary, usable = client.parse_normalization_response(+ payload,+ term="ivacaftor",+ expected_category="biolink:SmallMolecule",+ max_synonyms=1,+ service=service_info(),+ )+ self.assertTrue(usable)+ self.assertEqual(+ summary["canonical"],+ {+ "identifier": "CHEBI:66901",+ "name": "ivacaftor",+ "category": "biolink:SmallMolecule",+ },+ )+ self.assertEqual(+ summary["category_counts"],+ {"biolink:Drug": 3, "biolink:SmallMolecule": 2},+ )+ self.assertEqual(summary["total_synonyms"], 2)+ self.assertEqual(len(summary["synonym_preview"]), 1)+ self.assertTrue(summary["query"]["requires_user_confirmation"])+ codes = {item["code"] for item in summary["warnings"]}+ self.assertTrue({"PUBLIC_QUERY", "NORMALIZATION_REQUIRES_CONFIRMATION"}.issubset(codes))+ summary, usable = client.parse_normalization_response(+ payload,+ term="ivacaftor",+ expected_category="biolink:Disease",+ max_synonyms=10,+ service=service_info(),+ )+ self.assertTrue(usable)+ self.assertIn("NORMALIZATION_CATEGORY_MISMATCH", {item["code"] for item in summary["warnings"]})++ def test_curie_input_does_not_require_normalization_confirmation(self):+ payload = {"CHEBI:66901": fixture_json("normalization_response.json")["ivacaftor"]}+ summary, usable = client.parse_normalization_response(+ payload,+ term="CHEBI:66901",+ expected_category=None,+ max_synonyms=0,+ service=service_info(),+ )+ self.assertTrue(usable)+ self.assertFalse(summary["query"]["requires_user_confirmation"])+ self.assertEqual(summary["synonym_preview"], [])++ def test_no_usable_normalization(self):+ summary, usable = client.parse_normalization_response(+ {"unknown": {}},+ term="unknown",+ expected_category=None,+ max_synonyms=10,+ service=service_info(),+ )+ self.assertFalse(usable)+ self.assertIsNone(summary["canonical"]["identifier"])+ self.assertIn("NO_RESULTS", {item["code"] for item in summary["warnings"]})+++class ResponseParserTests(unittest.TestCase):+ def parse_fixture(self, name, *, contract=None):+ return client.parse_trapi_response(+ fixture_json(name),+ contract or client.validate_saved_request_contract(one_hop_body()),+ service=service_info(),+ )++ def test_one_hop_bindings_multiple_analyses_and_provenance(self):+ payload = fixture_json("one_hop_provenance.json")+ summary = client.parse_trapi_response(+ payload,+ client.validate_saved_request_contract(one_hop_body()),+ service=service_info(),+ )+ self.assertEqual(summary["counts"]["results_returned"], 1)+ self.assertEqual(summary["counts"]["analyses_summarized"], 2)+ self.assertEqual(summary["counts"]["bound_edges_summarized"], 3)+ analyses = summary["results"][0]["analyses"]+ edge_ids = [+ edge["edge_id"]+ for analysis in analyses+ for edge in analysis["edge_bindings"]["e0"]+ ]+ self.assertNotIn("kg-unbound", edge_ids)+ first = analyses[0]["edge_bindings"]["e0"][0]+ self.assertEqual(first["qualifiers"][0]["qualifier_value"], "activity")+ self.assertEqual(first["primary_knowledge_sources"], ["infores:drugbank"])+ self.assertEqual(first["aggregator_knowledge_sources"], ["infores:rtx-kg2", "infores:arax"])+ self.assertEqual(first["supporting_data_sources"], [])+ self.assertEqual(+ first["sources"],+ payload["message"]["knowledge_graph"]["edges"]["kg-e0-primary"]["sources"],+ )+ self.assertEqual(first["sources"][1]["upstream_resource_ids"], ["infores:drugbank"])+ self.assertEqual(first["sources"][0]["source_record_urls"], ["https://example.org/drugbank/one"])+ secondary = analyses[0]["edge_bindings"]["e0"][1]+ self.assertEqual(secondary["supporting_data_sources"], ["infores:ctd"])+ self.assertIsNone(analyses[0]["score"])+ self.assertEqual(analyses[0]["support_graphs"], ["sg-one"])+ self.assertEqual(first["support_graph_ids"], ["sg-one"])+ self.assertEqual(first["support_graph_status"], "available")+ self.assertEqual(+ analyses[1]["edge_bindings"]["e0"][0]["support_graph_status"],+ "not_returned",+ )+ self.assertEqual(+ summary["results"][0]["node_bindings"]["n0"][0],+ {"id": "CHEBI:31690", "query_id": "CHEBI:31690", "attributes": []},+ )+ publications = [+ publication+ for edge in analyses[0]["edge_bindings"]["e0"]+ for publication in edge["publication_ids"]+ ]+ self.assertEqual(publications, ["PMID:100", "PMID:101", "PMID:100"])+ self.assertIn("UNSCORED_RESPONSE_ORDER", {item["code"] for item in summary["warnings"]})++ def test_publications_are_deduplicated_within_each_edge(self):+ payload = fixture_json("one_hop_provenance.json")+ payload["message"]["knowledge_graph"]["edges"]["kg-e0-primary"]["attributes"][0][+ "value"+ ] = ["PMID:100", "PMID:100", "PMID:101"]+ summary = client.parse_trapi_response(+ payload,+ client.validate_saved_request_contract(one_hop_body()),+ service=service_info(),+ )+ publications = summary["results"][0]["analyses"][0]["edge_bindings"]["e0"][0][+ "publication_ids"+ ]+ self.assertEqual(publications, ["PMID:100", "PMID:101"])++ def test_two_hop_preserves_refined_predicate_and_support_graph(self):+ contract = client.validate_saved_request_contract(two_hop_body())+ summary = self.parse_fixture("two_hop_provenance.json", contract=contract)+ analysis = summary["results"][0]["analyses"][0]+ first = analysis["edge_bindings"]["e0"][0]+ second = analysis["edge_bindings"]["e1"][0]+ self.assertEqual(first["qualifiers"][0]["qualifier_value"], "activity")+ self.assertEqual(second["predicate"], "biolink:gene_associated_with_condition")+ self.assertEqual(first["support_graph_status"], "available")++ def test_reversed_edge_is_flagged_and_not_rewritten(self):+ summary = self.parse_fixture("reversed_edge.json")+ edge = summary["results"][0]["analyses"][0]["edge_bindings"]["e0"][0]+ self.assertFalse(edge["matches_query_direction"])+ self.assertEqual(edge["subject"], "NCBIGene:25")+ self.assertIn("REVERSED_EDGE_BINDING", {item["code"] for item in summary["warnings"]})++ def test_missing_publications_and_auxiliary_graph(self):+ publications = self.parse_fixture("missing_publications.json")+ edge = publications["results"][0]["analyses"][0]["edge_bindings"]["e0"][0]+ self.assertEqual(edge["publication_ids"], [])+ self.assertEqual(edge["publication_availability"], "not_returned")+ self.assertIn(+ "NO_PUBLICATIONS_RETURNED",+ {item["code"] for item in publications["warnings"]},+ )+ auxiliary = self.parse_fixture("missing_auxiliary_graph.json")+ edge = auxiliary["results"][0]["analyses"][0]["edge_bindings"]["e0"][0]+ self.assertEqual(edge["support_graph_status"], "missing")+ self.assertIn("MISSING_AUXILIARY_GRAPH", {item["code"] for item in auxiliary["warnings"]})++ no_primary = fixture_json("missing_publications.json")+ no_primary["message"]["knowledge_graph"]["edges"]["kg-no-pubs"]["sources"] = []+ summary = client.parse_trapi_response(+ no_primary,+ client.validate_saved_request_contract(one_hop_body()),+ service=service_info(),+ )+ codes = {item["code"] for item in summary["warnings"]}+ self.assertTrue({"NO_PRIMARY_SOURCE_RETURNED", "NO_PUBLICATIONS_RETURNED"}.issubset(codes))++ def test_zero_results_are_valid(self):+ summary = self.parse_fixture("no_results.json")+ self.assertEqual(summary["counts"]["results_returned"], 0)+ self.assertEqual(summary["results"], [])+ self.assertEqual(summary["truncation_status"], "no")+ self.assertIn("NO_RESULTS", {item["code"] for item in summary["warnings"]})++ def test_partial_federation_is_retained(self):+ body = one_hop_body(+ mode="federated",+ provider_ids=["infores:rtx-kg2", "infores:molepro"],+ result_limit=50,+ )+ summary = self.parse_fixture(+ "federated_partial_response.json",+ contract=client.validate_saved_request_contract(body),+ )+ self.assertEqual(summary["completeness"], "partial")+ codes = {item["code"] for item in summary["warnings"]}+ self.assertTrue({"KP_TIMEOUT", "KP_ERROR", "MALFORMED_KP_RESPONSE"}.issubset(codes))++ def test_truncation_states(self):+ payload = fixture_json("one_hop_provenance.json")+ contract = client.validate_saved_request_contract(one_hop_body(result_limit=1))+ summary = client.parse_trapi_response(payload, contract, service=service_info())+ self.assertEqual(summary["truncation_status"], "possible")+ payload["total_results_count"] = 2+ summary = client.parse_trapi_response(payload, contract, service=service_info())+ self.assertEqual(summary["truncation_status"], "confirmed")+ payload["total_results_count"] = 1+ payload["message"]["results"].append(copy.deepcopy(payload["message"]["results"][0]))+ summary = client.parse_trapi_response(payload, contract, service=service_info())+ self.assertEqual(summary["truncation_status"], "confirmed")+ self.assertEqual(len(summary["results"]), 1)++ def test_explicit_pruning_confirms_truncation(self):+ payload = fixture_json("one_hop_provenance.json")+ payload["logs"] = [{"level": "WARNING", "code": "PRUNED", "message": "Removed results during pruning"}]+ summary = client.parse_trapi_response(+ payload,+ client.validate_saved_request_contract(one_hop_body()),+ service=service_info(),+ )+ self.assertEqual(summary["truncation_status"], "confirmed")+ self.assertIn("INTERNAL_PRUNING_DETECTED", {item["code"] for item in summary["warnings"]})++ def test_informational_timeout_and_prune_configuration_do_not_mark_partial(self):+ payload = fixture_json("one_hop_provenance.json")+ payload["logs"] = [+ {"level": "INFO", "code": "CONFIG", "message": "kp_timeout=30"},+ {"level": "INFO", "code": "CONFIG", "message": "prune_kg=true"},+ ]+ contract = client.validate_saved_request_contract(+ one_hop_body(+ mode="federated",+ provider_ids=["infores:rtx-kg2", "infores:molepro"],+ result_limit=50,+ )+ )+ summary = client.parse_trapi_response(payload, contract, service=service_info())+ self.assertEqual(summary["completeness"], "complete")+ self.assertEqual(summary["truncation_status"], "no")+ codes = {item["code"] for item in summary["warnings"]}+ self.assertNotIn("KP_TIMEOUT", codes)+ self.assertNotIn("INTERNAL_PRUNING_DETECTED", codes)++ def test_malformed_message_graph_and_binding_fail(self):+ payload = fixture_json("one_hop_provenance.json")+ mutations = []+ no_message = copy.deepcopy(payload)+ del no_message["message"]+ mutations.append(no_message)+ no_graph = copy.deepcopy(payload)+ del no_graph["message"]["knowledge_graph"]+ mutations.append(no_graph)+ missing_edge = copy.deepcopy(payload)+ del missing_edge["message"]["knowledge_graph"]["edges"]["kg-e0-primary"]+ mutations.append(missing_edge)+ missing_qnode = copy.deepcopy(payload)+ del missing_qnode["message"]["results"][0]["node_bindings"]["n1"]+ mutations.append(missing_qnode)+ unrelated = copy.deepcopy(payload)+ unrelated["message"]["knowledge_graph"]["edges"]["kg-e0-primary"]["object"] = "NCBIGene:999"+ mutations.append(unrelated)+ extra_qedge = copy.deepcopy(payload)+ extra_qedge["message"]["results"][0]["analyses"][0]["edge_bindings"]["extra"] = []+ mutations.append(extra_qedge)+ contract = client.validate_saved_request_contract(one_hop_body())+ for mutation in mutations:+ with self.subTest(mutation=mutation), self.assertRaises(client.ResponseError):+ client.parse_trapi_response(mutation, contract, service=service_info())+++class RenderingTests(unittest.TestCase):+ def test_text_is_cautious_bounded_and_points_to_raw_artifacts(self):+ payload = fixture_json("one_hop_provenance.json")+ edge = payload["message"]["knowledge_graph"]["edges"]["kg-e0-primary"]+ edge["attributes"][0]["value"] = [f"PMID:{index}" for index in range(20)]+ summary = client.parse_trapi_response(+ payload,+ client.validate_saved_request_contract(one_hop_body()),+ service=service_info(),+ )+ rendered = client.render_text_summary(summary)+ self.assertIn("Unscored position 1", rendered)+ self.assertIn("Complete bounded publication and source lists: summary.json", rendered)+ self.assertIn("Exact TRAPI payload: response.json", rendered)+ self.assertIn("Candidate paths require subsequent scientific verification", rendered)+ self.assertIn("CHEBI:31690", rendered)+ self.assertIn("NCBIGene:25", rendered)+ self.assertIn("biolink:affects", rendered)+ self.assertIn("biolink:object_aspect_qualifier=activity", rendered)+ self.assertIn("infores:drugbank", rendered)+ self.assertIn("Publications: 20", rendered)+ self.assertNotIn("PMID:19", rendered)+ for prohibited in ("proved", "No relationship exists", "top-ranked"):+ self.assertNotIn(prohibited, rendered)++ def test_display_text_removes_controls_and_caps_length(self):+ value = client._sanitize_text("line\n" + "x" * 600)+ self.assertNotIn("\n", value)+ self.assertLessEqual(len(value), client.MAX_DISPLAY_TEXT)++ def test_all_remote_scalar_fields_are_terminal_safe(self):+ summary = client.parse_trapi_response(+ fixture_json("one_hop_provenance.json"),+ client.validate_saved_request_contract(one_hop_body()),+ service=service_info(),+ )+ result = summary["results"][0]+ result["node_bindings"]["n0\nINJECT"] = [{"id": "CURIE:1\nINJECT"}]+ analysis = result["analyses"][0]+ analysis["resource_id"] = "infores:arax\nINJECT"+ edge = analysis["edge_bindings"]["e0"][0]+ for field in ("edge_id", "subject", "subject_name", "predicate", "object", "object_name"):+ edge[field] = f"{field}\nINJECT"+ edge["qualifiers"] = [+ {"qualifier_type_id": "type\nINJECT", "qualifier_value": "value\nINJECT"}+ ]+ edge["primary_knowledge_sources"] = ["source\nINJECT"]+ edge["publication_ids"] = ["PMID:1\nINJECT"]+ rendered = client.render_text_summary(+ summary,+ summary_path="summary\nINJECT.json",+ response_path="response\nINJECT.json",+ )+ self.assertNotIn("\nINJECT", rendered)+++class ArtifactAndCommandTests(unittest.TestCase):+ def test_output_directory_policy_and_atomic_no_overwrite(self):+ with tempfile.TemporaryDirectory() as temporary:+ root = Path(temporary)+ existing_empty = root / "empty"+ existing_empty.mkdir()+ self.assertEqual(client.prepare_output_directory(existing_empty), existing_empty)+ new_dir = client.prepare_output_directory(root / "new")+ self.assertTrue(new_dir.is_dir())+ client.atomic_write_bytes(new_dir / "value.json", b"one")+ with self.assertRaises(client.ResponseError):+ client.atomic_write_bytes(new_dir / "value.json", b"two")+ with self.assertRaises(client.UsageError):+ client.prepare_output_directory(new_dir)+ self.assertEqual((new_dir / "value.json").read_bytes(), b"one")+ if os.name != "nt":+ self.assertEqual(stat.S_IMODE((new_dir / "value.json").stat().st_mode), 0o600)++ failed_dir = root / "failed"+ failed_dir.mkdir()+ with mock.patch.object(client.os, "replace", side_effect=OSError("disk full")):+ with self.assertRaises(client.ResponseError):+ client.atomic_write_bytes(failed_dir / "value.json", b"two")+ self.assertEqual(list(failed_dir.iterdir()), [])+ with mock.patch.object(client.tempfile, "mkstemp", side_effect=OSError("denied")):+ with self.assertRaises(client.ResponseError) as raised:+ client.atomic_write_bytes(failed_dir / "other.json", b"three")+ self.assertEqual(raised.exception.exit_code, 6)+ with mock.patch.object(client.Path, "mkdir", side_effect=OSError("denied")):+ with self.assertRaises(client.ResponseError) as raised:+ client.prepare_output_directory(root / "cannot-create")+ self.assertEqual(raised.exception.exit_code, 6)++ def test_failure_retention_is_best_effort_and_does_not_mask_original(self):+ with tempfile.TemporaryDirectory() as temporary:+ output = Path(temporary)+ manifest = client.new_manifest(+ "one-hop",+ base_url=client.PRODUCTION_BASE_URL,+ privacy_acknowledged=True,+ http_timeout=120,+ result_limit=20,+ )+ original = client.ResponseError("original artifact failure")+ with mock.patch.object(client, "_write_manifest", side_effect=OSError("disk full")), mock.patch(+ "sys.stderr", new=io.StringIO()+ ) as stderr:+ client._retain_failure(output, manifest, original, "query")+ self.assertIn("could not retain failure artifacts", stderr.getvalue())+ self.assertEqual(str(original), "original artifact failure")++ def test_graph_command_posts_saved_bytes_and_hashes_exact_response(self):+ captured = {}+ response_body = fixture_bytes("one_hop_provenance.json")+ preflight = client.HttpResult(200, fixture_bytes("openapi_1_5_minimal.json"), {}, 2, 1)++ def fake_post(url, request_bytes, *, timeout):+ captured["url"] = url+ captured["bytes"] = request_bytes+ captured["timeout"] = timeout+ return client.HttpResult(200, response_body, {}, 3, 1)++ with tempfile.TemporaryDirectory() as temporary, mock.patch.object(+ client, "fetch_openapi", return_value=(service_info(), preflight)+ ), mock.patch.object(client, "post_query", side_effect=fake_post):+ output = Path(temporary) / "run"+ args = argparse.Namespace(+ command="one-hop",+ subject_id="CHEBI:31690",+ subject_category="biolink:SmallMolecule",+ predicate=["biolink:affects"],+ object_id="NCBIGene:25",+ object_category="biolink:Gene",+ qualifier=[],+ mode="lookup",+ kp=[],+ result_limit=20,+ acknowledge_public_query=True,+ output_dir=str(output),+ base_url=client.PRODUCTION_BASE_URL,+ allow_nonproduction_endpoint=False,+ allow_untested_version=False,+ )+ with mock.patch("sys.stdout", new=io.StringIO()):+ self.assertEqual(client.handle_graph_query(args), 0)+ self.assertEqual((output / "request.json").read_bytes(), captured["bytes"])+ self.assertEqual((output / "response.json").read_bytes(), response_body)+ manifest = json.loads((output / "manifest.json").read_text(encoding="utf-8"))+ self.assertEqual(manifest["manifest_version"], "1.0")+ self.assertEqual(manifest["execution_status"], "success")+ self.assertEqual(manifest["result_status"], "results")+ self.assertTrue(manifest["privacy_acknowledged"])+ self.assertEqual(manifest["request"]["method"], "POST")+ self.assertEqual(manifest["request"]["url"], client.PRODUCTION_BASE_URL + "/query")+ self.assertEqual(manifest["request"]["file"], "request.json")+ self.assertEqual(manifest["request"]["bytes"], len(captured["bytes"]))+ self.assertEqual(manifest["request"]["sha256"], client.sha256_bytes(captured["bytes"]))+ self.assertEqual(manifest["response"]["http_status"], 200)+ self.assertEqual(manifest["response"]["file"], "response.json")+ self.assertEqual(manifest["response"]["bytes"], len(response_body))+ self.assertEqual(manifest["response"]["elapsed_ms"], 3)+ self.assertEqual(manifest["response"]["sha256"], client.sha256_bytes(response_body))+ self.assertEqual(+ manifest["limits"],+ {+ "http_timeout_seconds": 120,+ "kp_timeout_seconds": 30,+ "response_byte_limit": 25 * 1024 * 1024,+ "result_limit": 20,+ },+ )+ self.assertEqual(+ manifest["attempts"],+ {"openapi_get": 1, "entity_get": 0, "query_post": 1},+ )+ self.assertEqual(+ manifest["artifacts"],+ {"request": "request.json", "response": "response.json", "summary": "summary.json"},+ )+ self.assertIn("PUBLIC_QUERY", {item["code"] for item in manifest["warnings"]})+ self.assertRegex(manifest["run_id"], r"^[0-9a-f-]{36}$")+ self.assertTrue(manifest["started_at"].endswith("Z"))+ self.assertTrue(manifest["finished_at"].endswith("Z"))+ self.assertNotIn("CHEBI:31690", client.USER_AGENT)+ self.assertNotIn("CHEBI:31690", client.SUBMITTER)++ def test_preflight_with_output_has_get_manifest_and_no_request_artifact(self):+ response_body = fixture_bytes("openapi_1_5_minimal.json")+ result = client.HttpResult(200, response_body, {}, 4, 1)+ with tempfile.TemporaryDirectory() as temporary, mock.patch.object(+ client, "fetch_openapi", return_value=(service_info(), result)+ ):+ output = Path(temporary) / "preflight"+ args = argparse.Namespace(+ output_dir=str(output),+ base_url=client.PRODUCTION_BASE_URL,+ allow_nonproduction_endpoint=False,+ allow_untested_version=False,+ )+ with mock.patch("sys.stdout", new=io.StringIO()):+ self.assertEqual(client.handle_preflight(args), 0)+ self.assertEqual(+ {path.name for path in output.iterdir()},+ {"response.json", "summary.json", "manifest.json"},+ )+ manifest = json.loads((output / "manifest.json").read_text(encoding="utf-8"))+ self.assertFalse(manifest["privacy_acknowledged"])+ self.assertEqual(+ manifest["request"],+ {+ "method": "GET",+ "url": client.PRODUCTION_BASE_URL + "/openapi.json",+ "file": None,+ "bytes": None,+ "sha256": None,+ },+ )+ self.assertEqual(manifest["artifacts"]["request"], None)+ self.assertEqual(manifest["attempts"]["openapi_get"], 1)++ def test_failure_manifests_record_the_actual_network_stage(self):+ preflight = client.HttpResult(200, fixture_bytes("openapi_1_5_minimal.json"), {}, 2, 1)+ cases = [+ (+ "openapi",+ client.PreflightError(+ "preflight failed", http_status=503, response_body=b"openapi-error", attempts=2+ ),+ ),+ (+ "entity",+ client.TransportError(+ "entity failed", http_status=502, response_body=b"entity-error", attempts=1+ ),+ ),+ (+ "query",+ client.TransportError(+ "query failed", http_status=500, response_body=b"query-error", attempts=1+ ),+ ),+ ]+ for stage, failure in cases:+ with self.subTest(stage=stage), tempfile.TemporaryDirectory() as temporary:+ output = Path(temporary) / stage+ if stage == "openapi":+ with mock.patch.object(client, "fetch_openapi", side_effect=failure):+ with self.assertRaises(client.PreflightError):+ client.handle_graph_query(one_hop_args(output))+ expected_url = client.PRODUCTION_BASE_URL + "/openapi.json"+ expected_method = "GET"+ expected_attempts = {"openapi_get": 2, "entity_get": 0, "query_post": 0}+ self.assertFalse((output / "request.json").exists())+ elif stage == "entity":+ with mock.patch.object(+ client, "fetch_openapi", return_value=(service_info(), preflight)+ ), mock.patch.object(client, "normalize_entity_request", side_effect=failure):+ with self.assertRaises(client.TransportError):+ client.handle_normalize(normalize_args(output))+ expected_url = client.PRODUCTION_BASE_URL + "/entity?q=ivacaftor"+ expected_method = "GET"+ expected_attempts = {"openapi_get": 1, "entity_get": 1, "query_post": 0}+ else:+ with mock.patch.object(+ client, "fetch_openapi", return_value=(service_info(), preflight)+ ), mock.patch.object(client, "post_query", side_effect=failure):+ with self.assertRaises(client.TransportError):+ client.handle_graph_query(one_hop_args(output))+ expected_url = client.PRODUCTION_BASE_URL + "/query"+ expected_method = "POST"+ expected_attempts = {"openapi_get": 1, "entity_get": 0, "query_post": 1}+ self.assertTrue((output / "request.json").exists())+ self.assertEqual((output / "response.json").read_bytes(), failure.response_body)+ manifest = json.loads((output / "manifest.json").read_text(encoding="utf-8"))+ self.assertEqual(manifest["request"]["method"], expected_method)+ self.assertEqual(manifest["request"]["url"], expected_url)+ self.assertEqual(manifest["attempts"], expected_attempts)+ self.assertEqual(manifest["response"]["http_status"], failure.http_status)+ self.assertEqual(manifest["execution_status"], "http_error" if failure.exit_code == 5 else "client_error")++ def test_oversized_query_retains_request_and_manifest_but_no_partial_response(self):+ preflight = client.HttpResult(200, fixture_bytes("openapi_1_5_minimal.json"), {}, 2, 1)+ failure = client.ResponseError("response exceeded limit", http_status=200, attempts=1)+ with tempfile.TemporaryDirectory() as temporary, mock.patch.object(+ client, "fetch_openapi", return_value=(service_info(), preflight)+ ), mock.patch.object(client, "post_query", side_effect=failure):+ output = Path(temporary) / "oversized"+ with self.assertRaises(client.ResponseError):+ client.handle_graph_query(one_hop_args(output))+ self.assertTrue((output / "request.json").exists())+ self.assertFalse((output / "response.json").exists())+ self.assertFalse((output / "summary.json").exists())+ manifest = json.loads((output / "manifest.json").read_text(encoding="utf-8"))+ self.assertEqual(manifest["attempts"]["query_post"], 1)+ self.assertEqual(manifest["response"]["http_status"], 200)+ self.assertIsNone(manifest["response"]["file"])+ self.assertEqual(manifest["error"]["kind"], "invalid_response")++ def test_zero_result_and_normalization_no_result_statuses(self):+ preflight = client.HttpResult(200, fixture_bytes("openapi_1_5_minimal.json"), {}, 2, 1)+ with tempfile.TemporaryDirectory() as temporary, mock.patch.object(+ client, "fetch_openapi", return_value=(service_info(), preflight)+ ), mock.patch.object(+ client,+ "post_query",+ return_value=client.HttpResult(200, fixture_bytes("no_results.json"), {}, 3, 1),+ ):+ output = Path(temporary) / "zero"+ with mock.patch("sys.stdout", new=io.StringIO()):+ self.assertEqual(client.handle_graph_query(one_hop_args(output)), 0)+ manifest = json.loads((output / "manifest.json").read_text(encoding="utf-8"))+ self.assertEqual(manifest["execution_status"], "success")+ self.assertEqual(manifest["result_status"], "no_results")++ entity = client.HttpResult(200, b'{"ivacaftor":{}}', {}, 3, 1)+ with tempfile.TemporaryDirectory() as temporary, mock.patch.object(+ client, "fetch_openapi", return_value=(service_info(), preflight)+ ), mock.patch.object(client, "normalize_entity_request", return_value=entity):+ output = Path(temporary) / "normalize-none"+ with self.assertRaises(client.NormalizationError) as raised:+ client.handle_normalize(normalize_args(output))+ self.assertEqual(raised.exception.exit_code, 4)+ manifest = json.loads((output / "manifest.json").read_text(encoding="utf-8"))+ self.assertEqual(manifest["execution_status"], "success")+ self.assertEqual(manifest["result_status"], "no_results")++ def test_partial_graph_command_retains_all_artifacts_and_exits_seven(self):+ response_body = fixture_bytes("federated_partial_response.json")+ preflight = client.HttpResult(200, fixture_bytes("openapi_1_5_minimal.json"), {}, 2, 1)+ with tempfile.TemporaryDirectory() as temporary, mock.patch.object(+ client, "fetch_openapi", return_value=(service_info(), preflight)+ ), mock.patch.object(+ client,+ "post_query",+ return_value=client.HttpResult(200, response_body, {}, 3, 1),+ ):+ output = Path(temporary) / "run"+ args = argparse.Namespace(+ command="one-hop",+ subject_id="CHEBI:31690",+ subject_category="biolink:SmallMolecule",+ predicate=["biolink:affects"],+ object_id="NCBIGene:25",+ object_category="biolink:Gene",+ qualifier=[],+ mode="federated",+ kp=["infores:rtx-kg2", "infores:molepro"],+ result_limit=50,+ acknowledge_public_query=True,+ output_dir=str(output),+ base_url=client.PRODUCTION_BASE_URL,+ allow_nonproduction_endpoint=False,+ allow_untested_version=False,+ )+ with mock.patch("sys.stdout", new=io.StringIO()):+ self.assertEqual(client.handle_graph_query(args), 7)+ self.assertEqual(+ {path.name for path in output.iterdir()},+ {"request.json", "response.json", "summary.json", "manifest.json"},+ )+ manifest = json.loads((output / "manifest.json").read_text(encoding="utf-8"))+ self.assertEqual(manifest["result_status"], "partial")++ def test_malformed_response_is_retained_without_summary(self):+ preflight = client.HttpResult(200, fixture_bytes("openapi_1_5_minimal.json"), {}, 2, 1)+ with tempfile.TemporaryDirectory() as temporary, mock.patch.object(+ client, "fetch_openapi", return_value=(service_info(), preflight)+ ), mock.patch.object(+ client,+ "post_query",+ return_value=client.HttpResult(200, b"{not-json", {}, 3, 1),+ ):+ output = Path(temporary) / "run"+ args = argparse.Namespace(+ command="one-hop",+ subject_id="CHEBI:31690",+ subject_category="biolink:SmallMolecule",+ predicate=["biolink:affects"],+ object_id="NCBIGene:25",+ object_category="biolink:Gene",+ qualifier=[],+ mode="lookup",+ kp=[],+ result_limit=20,+ acknowledge_public_query=True,+ output_dir=str(output),+ base_url=client.PRODUCTION_BASE_URL,+ allow_nonproduction_endpoint=False,+ allow_untested_version=False,+ )+ with self.assertRaises(client.ResponseError):+ client.handle_graph_query(args)+ self.assertTrue((output / "request.json").exists())+ self.assertEqual((output / "response.json").read_bytes(), b"{not-json")+ self.assertFalse((output / "summary.json").exists())+ manifest = json.loads((output / "manifest.json").read_text(encoding="utf-8"))+ self.assertEqual(manifest["execution_status"], "client_error")++ def test_normalize_command_never_posts(self):+ preflight = client.HttpResult(200, fixture_bytes("openapi_1_5_minimal.json"), {}, 2, 1)+ entity = client.HttpResult(200, fixture_bytes("normalization_response.json"), {}, 3, 1)+ with tempfile.TemporaryDirectory() as temporary, mock.patch.object(+ client, "fetch_openapi", return_value=(service_info(), preflight)+ ), mock.patch.object(client, "normalize_entity_request", return_value=entity), mock.patch.object(+ client, "post_query", side_effect=AssertionError("normalization must not POST")+ ):+ output = Path(temporary) / "normalize"+ args = argparse.Namespace(+ term="ivacaftor",+ expected_category="biolink:SmallMolecule",+ max_synonyms=10,+ acknowledge_public_query=True,+ output_dir=str(output),+ base_url=client.PRODUCTION_BASE_URL,+ allow_nonproduction_endpoint=False,+ allow_untested_version=False,+ )+ with mock.patch("sys.stdout", new=io.StringIO()):+ self.assertEqual(client.handle_normalize(args), 0)+ self.assertFalse((output / "request.json").exists())+ self.assertTrue((output / "response.json").exists())+ manifest = json.loads((output / "manifest.json").read_text(encoding="utf-8"))+ self.assertEqual(+ manifest["request"],+ {+ "method": "GET",+ "url": client.PRODUCTION_BASE_URL + "/entity?q=ivacaftor",+ "file": None,+ "bytes": None,+ "sha256": None,+ },+ )+ self.assertEqual(+ manifest["attempts"],+ {"openapi_get": 1, "entity_get": 1, "query_post": 0},+ )+ self.assertEqual(manifest["artifacts"]["request"], None)++ def test_summarize_is_offline_and_preserves_inputs(self):+ request_bytes = client.serialize_request(one_hop_body())+ response_bytes = fixture_bytes("one_hop_provenance.json")+ with tempfile.TemporaryDirectory() as temporary:+ root = Path(temporary)+ request_path = root / "request.json"+ response_path = root / "response.json"+ request_path.write_bytes(request_bytes)+ response_path.write_bytes(response_bytes)+ args = argparse.Namespace(+ request=str(request_path), response=str(response_path), format="json"+ )+ with mock.patch.object(+ client, "_open_url", side_effect=AssertionError("offline summarize used network")+ ), mock.patch("sys.stdout", new=io.StringIO()) as stdout:+ self.assertEqual(client.handle_summarize(args), 0)+ parsed = json.loads(stdout.getvalue())+ self.assertEqual(parsed["results"][0]["position"], 1)+ self.assertEqual(request_path.read_bytes(), request_bytes)+ self.assertEqual(response_path.read_bytes(), response_bytes)++ def test_main_exit_code_mapping_for_local_and_response_errors(self):+ normalize_cli = [+ "normalize",+ "term",+ "--acknowledge-public-query",+ "--output-dir",+ "unused",+ ]+ graph_cli = [+ "one-hop",+ "--subject-id",+ "CHEBI:1",+ "--subject-category",+ "biolink:SmallMolecule",+ "--predicate",+ "biolink:related_to",+ "--object-category",+ "biolink:Gene",+ "--acknowledge-public-query",+ "--output-dir",+ "unused",+ ]+ cases = [+ ("handle_preflight", ["preflight"], client.PreflightError("bad service"), 3),+ ("handle_normalize", normalize_cli, client.NormalizationError("not found"), 4),+ ("handle_graph_query", graph_cli, client.TransportError("offline"), 5),+ ("handle_graph_query", graph_cli, client.ResponseError("bad response"), 6),+ ]+ for handler, argv, failure, expected in cases:+ with self.subTest(expected=expected), mock.patch.object(+ client, handler, side_effect=failure+ ), mock.patch("sys.stderr", new=io.StringIO()):+ self.assertEqual(client.main(argv), expected)+ with mock.patch.object(client, "handle_graph_query", return_value=0):+ self.assertEqual(client.main(graph_cli), 0)+ with mock.patch.object(client, "handle_graph_query", return_value=7):+ self.assertEqual(client.main(graph_cli), 7)++ with tempfile.TemporaryDirectory() as temporary:+ request = Path(temporary) / "request.json"+ response = Path(temporary) / "response.json"+ request.write_text("{}", encoding="utf-8")+ response.write_text("{}", encoding="utf-8")+ with mock.patch("sys.stderr", new=io.StringIO()):+ code = client.main(+ ["summarize", "--request", str(request), "--response", str(response)]+ )+ self.assertEqual(code, 2)+ request.write_bytes(client.serialize_request(one_hop_body()))+ response.write_bytes(b"not-json")+ with mock.patch("sys.stderr", new=io.StringIO()):+ code = client.main(+ ["summarize", "--request", str(request), "--response", str(response)]+ )+ self.assertEqual(code, 6)++[email protected](os.environ.get("ARAX_LIVE_TESTS") == "1", "set ARAX_LIVE_TESTS=1")+class LiveSmokeTests(unittest.TestCase):+ def live_service(self):+ service, _ = client.fetch_openapi(+ client.PRODUCTION_BASE_URL,+ allow_untested_version=False,+ )+ return service++ def live_query(self, body):+ service = self.live_service()+ contract = client.validate_saved_request_contract(body)+ timeout = (+ client.FEDERATED_TIMEOUT_SECONDS+ if contract.mode == "federated"+ else client.LOOKUP_TIMEOUT_SECONDS+ )+ result = client.post_query(+ client.PRODUCTION_BASE_URL + "/query",+ client.serialize_request(body),+ timeout=timeout,+ )+ payload = client._decode_json(result.body, "live TRAPI response")+ return client.parse_trapi_response(payload, contract, service=service)++ def bound_node_ids(self, summary):+ return {+ binding["id"]+ for result in summary["results"]+ for bindings in result["node_bindings"].values()+ for binding in bindings+ }++ def test_01_production_openapi(self):+ service = self.live_service()+ self.assertIn(service.trapi_version.split(".")[0:2], (["1", "5"], ["1", "6"]))++ def test_02_production_accepts_rtx_kg2_lookup(self):+ summary = self.live_query(one_hop_body(qualifiers=[], result_limit=5))+ self.assertLessEqual(summary["counts"]["results_summarized"], 5)++ def test_03_normalize_ivacaftor(self):+ service = self.live_service()+ result = client.normalize_entity_request(client.PRODUCTION_BASE_URL, "ivacaftor")+ summary, usable = client.parse_normalization_response(+ client._decode_json(result.body, "live entity response"),+ term="ivacaftor",+ expected_category="biolink:SmallMolecule",+ max_synonyms=10,+ service=service,+ )+ self.assertTrue(usable)+ self.assertRegex(summary["canonical"]["identifier"], r"^[^:]+:.+$")+ self.assertTrue(summary["canonical"]["category"])++ def test_04_pinned_imatinib_abl1_one_hop(self):+ summary = self.live_query(one_hop_body(result_limit=20))+ self.assertGreater(summary["counts"]["bound_edges_summarized"], 0)++ def test_05_ivacaftor_gene_cystic_fibrosis_contains_cftr(self):+ summary = self.live_query(two_hop_body(result_limit=20))+ self.assertIn("NCBIGene:1080", self.bound_node_ids(summary))++ def test_06_imatinib_gene_cml_contains_abl1(self):+ body = two_hop_body(+ subject_id="CHEBI:31690",+ object_id="MONDO:0011996",+ qualifiers_1=[+ ("biolink:object_aspect_qualifier", "activity_or_abundance"),+ ("biolink:object_direction_qualifier", "decreased"),+ ],+ result_limit=20,+ )+ summary = self.live_query(body)+ self.assertIn("NCBIGene:25", self.bound_node_ids(summary))++ def test_07_wrong_direction_does_not_return_abl1_path(self):+ body = one_hop_body(+ qualifiers=[+ ("biolink:object_aspect_qualifier", "activity_or_abundance"),+ ("biolink:object_direction_qualifier", "increased"),+ ],+ result_limit=20,+ )+ summary = self.live_query(body)+ self.assertEqual(summary["counts"]["results_returned"], 0)++ def test_08_selected_provider_federation_is_bounded_and_provenanced(self):+ body = one_hop_body(+ qualifiers=[],+ mode="federated",+ provider_ids=["infores:rtx-kg2", "infores:molepro"],+ result_limit=50,+ )+ summary = self.live_query(body)+ self.assertLessEqual(summary["counts"]["results_summarized"], 50)+ for result in summary["results"]:+ for analysis in result["analyses"]:+ for edges in analysis["edge_bindings"].values():+ for edge in edges:+ self.assertTrue(edge["sources"])+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/skill-requirements.toml b/tests/skill-requirements.tomlindex 9e442817..f4344e35 100644--- a/tests/skill-requirements.toml+++ b/tests/skill-requirements.toml@@ -130,6 +130,9 @@ packages = [][skills.ontology-term-resolution]packages = []+[skills.ncats-arax]+packages = []+[skills.peer-review]packages = []