about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorPjotr <wrk@bosa.lan>2026-11-10 12:34:53 +0000
committerPjotr <wrk@bosa.lan>2026-11-10 12:34:53 +0000
commit2b41fc94a5e2b33a411d22721a6ee2a97ac9ae60 (patch)
tree6292c0b625e616c08bbb767bc986c0b0646ab94f /src
parente0bbc56324cc7a6bd563f0dadd7163a93b8b4ad8 (diff)
downloadgenenetwork4-2b41fc94a5e2b33a411d22721a6ee2a97ac9ae60.tar.gz
api: every response suggests where to go next
A caller that knows only /version should be able to reach anything by
following links. Until now `next` was thin and uneven: the genotype
subtree offered none at all, the group record offered one, /version
offered nothing, and two links it did offer could not be followed.

  * suggest:: now builds the graph: root_links (groups, species,
    mapping-methods, openapi), genotype_version_links (frequencies,
    marker names, a marker's location and tally, the group, the scanning
    actions), unlisted_genotype_links, marker_links (location, tally,
    marker list, panel tally, PheWAS at that marker), group_links and
    trait_links. Envelope::with_links / with_links_except add them,
    deduplicating and never suggesting the response the caller is
    already reading.
  * Wired through the genotype surface (listing, version detail, markers,
    location), both frequencies routes, the compute endpoints, groups,
    traits, both value routes, species, datasets, publications,
    accessions, search, mapping methods, phewas, correlation and
    /version.
  * Fixed what was not followable, because `next` promises a GET that
    returns 200 and a client is the one that finds out otherwise:
    - /groups/{g}/phewas without a locus is a 422. Bare PheWAS links are
      gone; comput endpoints now link ?locus=<their strongest marker>
      (suggest::peak_marker_of, computed before the rows move).
    - /datasets and /publications are not routes; root_links offers the
      listings that exist (/groups, /species, /mapping-methods) and
      /openapi.json.
    - /search?q= with an empty query is a 400, so it is not a link.
    - the correlation endpoint's "/compute/correlation" was a POST in
      `next`; it is in `actions` now.
    - marker_links pointed at /markers/{marker}, which is not a route;
      it points at /markers/{marker}/location.

tests/links.rs walks the graph two hops from a dozen seeds and fails on
any link that does not answer 200, plus a check that a tally leads to the
marker list and to a marker's location, and a location to that marker's
tally and its PheWAS.
Diffstat (limited to 'src')
-rw-r--r--src/lib.rs2
-rw-r--r--src/response.rs30
-rw-r--r--src/routes/accessions.rs2
-rw-r--r--src/routes/correlation.rs12
-rw-r--r--src/routes/datasets.rs42
-rw-r--r--src/routes/fitqtl.rs19
-rw-r--r--src/routes/frequencies.rs53
-rw-r--r--src/routes/gemma.rs1
-rw-r--r--src/routes/genotypes.rs38
-rw-r--r--src/routes/groups.rs38
-rw-r--r--src/routes/mapping_methods.rs2
-rw-r--r--src/routes/phewas.rs2
-rw-r--r--src/routes/publications.rs2
-rw-r--r--src/routes/qtl2.rs18
-rw-r--r--src/routes/rqtl.rs1
-rw-r--r--src/routes/search.rs2
-rw-r--r--src/routes/species.rs29
-rw-r--r--src/routes/traits.rs33
-rw-r--r--src/suggest.rs201
19 files changed, 459 insertions, 68 deletions
diff --git a/src/lib.rs b/src/lib.rs
index 19bdf8b..9fd2ce5 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -264,5 +264,5 @@ async fn version(ctx: Ctx) -> Json<Envelope<VersionInfo>> {
             failure.detail.chars().take(200).collect::<String>()
         ));
     }
-    Json(envelope)
+    Json(envelope.with_links(crate::suggest::root_links()))
 }
diff --git a/src/response.rs b/src/response.rs
index fd37e21..556a0f8 100644
--- a/src/response.rs
+++ b/src/response.rs
@@ -125,6 +125,36 @@ impl<T: Serialize + utoipa::ToSchema> Envelope<T> {
         self
     }
 
+    /// Adds a batch of `next` links, skipping any that duplicate a link
+    /// already present -- a handler that adds a specific link and then a
+    /// domain-wide batch should not list the same call twice.
+    pub fn with_links(self, links: Vec<(String, &'static str)>) -> Self {
+        self.with_links_except(links, "")
+    }
+
+    /// [`with_links`](Self::with_links), minus the link to the response the
+    /// caller is already reading: a suggestion is where to go next, not here.
+    pub fn with_links_except(
+        mut self,
+        links: Vec<(String, &'static str)>,
+        current: &str,
+    ) -> Self {
+        let current = current.trim_end_matches('/');
+        for (href, description) in links {
+            if !current.is_empty() && href.trim_end_matches('/') == current {
+                continue;
+            }
+            if self.next.iter().any(|existing| existing.href == href) {
+                continue;
+            }
+            self.next.push(NextAction {
+                href,
+                description: description.to_string(),
+            });
+        }
+        self
+    }
+
     pub fn with_note(mut self, note: &str) -> Self {
         self.notes.push(note.to_string());
         self
diff --git a/src/routes/accessions.rs b/src/routes/accessions.rs
index 3ca7f7e..0c46c73 100644
--- a/src/routes/accessions.rs
+++ b/src/routes/accessions.rs
@@ -63,7 +63,7 @@ pub async fn accession(
             let group = found.group.as_deref().map(path_segment);
             let name = path_segment(&found.name);
             let category = found.category.clone();
-            let mut envelope = ctx.envelope(found);
+            let mut envelope = ctx.envelope(found).with_links(crate::suggest::root_links());
             if let Some(group) = &group {
                 envelope = envelope.with_next(
                     &format!("/groups/{group}"),
diff --git a/src/routes/correlation.rs b/src/routes/correlation.rs
index e703fd0..b0b6d16 100644
--- a/src/routes/correlation.rs
+++ b/src/routes/correlation.rs
@@ -65,7 +65,15 @@ pub async fn correlation(
             },
         ])
         .with_note("STUB: canned data; nothing was computed.")
-        .with_next("/compute/correlation", "Correlate another trait")
-        .with_next("/species", "Narrow by species"),
+        // `/compute/correlation` is a POST, so it belongs in `actions`, not in
+        // `next`: following a `next` link must be a GET that returns 200.
+        .with_action(crate::response::SuggestedCall {
+            method: "POST".to_string(),
+            href: "/compute/correlation".to_string(),
+            description: "Correlate another pair of traits".to_string(),
+            body: None,
+        })
+        .with_next("/species", "Narrow by species")
+        .with_links(crate::suggest::root_links()),
     ))
 }
diff --git a/src/routes/datasets.rs b/src/routes/datasets.rs
index 71aae52..07c40b1 100644
--- a/src/routes/datasets.rs
+++ b/src/routes/datasets.rs
@@ -44,10 +44,15 @@ pub async fn dataset_by_name(
         })?
         .map_err(|e| ApiError::from_db(e, "dataset_by_name").with_request_id(rid.clone()))?
         .map(|dataset| {
-            Json(ctx.envelope(dataset).with_next(
-                &format!("/datasets/{}/probesets", path_segment(&not_found_name)),
-                "The expression traits (probesets) of this dataset (can be very large)",
-            ))
+            Json(
+                ctx.envelope(dataset)
+                    .with_next(
+                        &format!("/datasets/{}/probesets", path_segment(&not_found_name)),
+                        "The expression traits (probesets) of this dataset (can be very large)",
+                    )
+                    .with_next("/datasets/{dataset}/probesets/{probeset}", "One probeset's metadata")
+                    .with_links(crate::suggest::root_links()),
+            )
         })
         .ok_or_else(|| {
             ApiError::new(
@@ -146,10 +151,17 @@ pub async fn dataset_probesets(
     })
     .and_then(|lookup| match lookup {
         DatasetProbesetsLookup::Found(_authorized, probesets) => Ok(Json(
-            ctx.envelope(probesets).with_note(db::LOD_NOTE).with_next(
-                &format!("/datasets/{}", path_segment(&not_found_name)),
-                "The dataset these probesets belong to",
-            ),
+            ctx.envelope(probesets)
+                .with_note(db::LOD_NOTE)
+                .with_next(
+                    &format!("/datasets/{}", path_segment(&not_found_name)),
+                    "The dataset these probesets belong to",
+                )
+                .with_next(
+                    &format!("/datasets/{}/probesets/{{probeset}}/values", path_segment(&not_found_name)),
+                    "One probeset's value per strain, with the mapping suggestions",
+                )
+                .with_links(crate::suggest::root_links()),
         )),
         DatasetProbesetsLookup::Forbidden => Err(ApiError::new(
             StatusCode::FORBIDDEN,
@@ -288,7 +300,12 @@ pub async fn dataset_probeset_info(
                     .with_next(
                         &format!("/datasets/{dataset}"),
                         "The dataset this probeset belongs to",
-                    ),
+                    )
+                    .with_next(
+                        &format!("/publications/{{pubmed_id}}/traits"),
+                        "Every trait this probeset's publication reports",
+                    )
+                    .with_links(crate::suggest::root_links()),
             ))
         }
         DatasetProbesetLookup::Forbidden => Err(ApiError::new(
@@ -416,7 +433,12 @@ pub async fn dataset_probeset_values(
                             path_segment(&not_found_probeset)
                         ),
                         "The probeset's metadata",
-                    ),
+                    )
+                    .with_next(
+                        &format!("/datasets/{}/probesets", path_segment(&not_found_dataset)),
+                        "The other probesets of this dataset",
+                    )
+                    .with_links(crate::suggest::root_links()),
             ))
         }
         DatasetProbesetLookup::Forbidden => Err(ApiError::new(
diff --git a/src/routes/fitqtl.rs b/src/routes/fitqtl.rs
index 50f8970..8c0c283 100644
--- a/src/routes/fitqtl.rs
+++ b/src/routes/fitqtl.rs
@@ -395,8 +395,10 @@ pub async fn compute_fitqtl(
         .await?;
 
     let num_rows = output.rows.len();
+    let rows = serde_json::Value::Array(output.rows);
+    let peak_marker = crate::suggest::peak_marker_of(&rows, 0, 3);
     let mut envelope = ctx
-        .envelope(serde_json::Value::Array(output.rows))
+        .envelope(rows)
         .with_columns(
             fitqtl::COLUMNS.iter().map(|name| name.to_string()).collect(),
             num_rows,
@@ -417,10 +419,17 @@ pub async fn compute_fitqtl(
         envelope = envelope.with_note(note);
     }
     if let Some(group) = request_group {
-        envelope = envelope.with_next(
-            &format!("/groups/{}/phewas", path_segment(&group)),
-            "PheWAS: every published trait peaking near a locus (add ?locus=)",
-        );
+        if let Some(peak) = &peak_marker {
+            envelope = envelope.with_next(
+                &format!(
+                    "/groups/{}/phewas?locus={}",
+                    path_segment(&group),
+                    path_segment(peak)
+                ),
+                "PheWAS: every published trait peaking at this fit's strongest marker",
+            );
+        }
+        envelope = envelope.with_links(crate::suggest::group_links(&group));
     }
     Ok(Json(envelope))
 }
diff --git a/src/routes/frequencies.rs b/src/routes/frequencies.rs
index 40c3877..2d45337 100644
--- a/src/routes/frequencies.rs
+++ b/src/routes/frequencies.rs
@@ -38,6 +38,7 @@ use crate::error::{ApiError, Unauthorized};
 use crate::frequencies::{self, Counted, FreqError};
 use crate::genotypes;
 use crate::response::{Ctx, Envelope, RequestInfo};
+use crate::suggest::{self, Link};
 
 #[derive(Deserialize, utoipa::IntoParams)]
 pub struct FrequencyParams {
@@ -91,8 +92,14 @@ pub async fn group_version_frequencies(
     let rid = ctx.request_info();
     let root = Config::load().genotype_files_dir.clone();
     let label = format!("{group} {version}");
-    let path = resolve_version(root, group, version, rid.clone()).await?;
-    let envelope = count(ctx, path, params.marker, params.bin, label, rid).await?;
+    let path = resolve_version(root.clone(), group.clone(), version.clone(), rid.clone()).await?;
+    let links = suggest::genotype_version_links(&group, &version);
+    let current = format!(
+        "/groups/{}/genotypes/{}/frequencies",
+        crate::response::path_segment(&group),
+        crate::response::path_segment(&version)
+    );
+    let envelope = count(ctx, path, params.marker, params.bin, label, links, current, rid).await?;
     Ok(Json(envelope))
 }
 
@@ -124,8 +131,15 @@ pub async fn group_marker_frequencies(
     let rid = ctx.request_info();
     let root = Config::load().genotype_files_dir.clone();
     let label = format!("{group} {version}");
-    let path = resolve_version(root, group, version, rid.clone()).await?;
-    let envelope = count(ctx, path, Some(marker), params.bin, label, rid).await?;
+    let path = resolve_version(root, group.clone(), version.clone(), rid.clone()).await?;
+    let links = suggest::marker_links(&group, &version, &marker);
+    let current = format!(
+        "/groups/{}/genotypes/{}/markers/{}/frequencies",
+        crate::response::path_segment(&group),
+        crate::response::path_segment(&version),
+        crate::response::path_segment(&marker)
+    );
+    let envelope = count(ctx, path, Some(marker), params.bin, label, links, current, rid).await?;
     Ok(Json(envelope))
 }
 
@@ -159,7 +173,12 @@ pub async fn unlisted_frequencies(
     .await
     .map_err(|error| internal(error.to_string(), rid.clone()))?
     .map_err(|error| map_genotype_error(error, rid.clone()))?;
-    let envelope = count(ctx, path, params.marker, params.bin, name, rid).await?;
+    let links = suggest::unlisted_genotype_links(&name);
+    let current = format!(
+        "/groups/unlisted/genotypes/{}/frequencies",
+        crate::response::path_segment(&name)
+    );
+    let envelope = count(ctx, path, params.marker, params.bin, name, links, current, rid).await?;
     Ok(Json(envelope))
 }
 
@@ -197,7 +216,13 @@ pub async fn unlisted_marker_frequencies(
     .await
     .map_err(|error| internal(error.to_string(), rid.clone()))?
     .map_err(|error| map_genotype_error(error, rid.clone()))?;
-    let envelope = count(ctx, path, Some(marker), params.bin, name, rid).await?;
+    let links = suggest::unlisted_marker_links(&name, &marker);
+    let current = format!(
+        "/groups/unlisted/genotypes/{}/markers/{}/frequencies",
+        crate::response::path_segment(&name),
+        crate::response::path_segment(&marker)
+    );
+    let envelope = count(ctx, path, Some(marker), params.bin, name, links, current, rid).await?;
     Ok(Json(envelope))
 }
 
@@ -225,6 +250,8 @@ async fn count(
     marker: Option<String>,
     bin: Option<f64>,
     label: String,
+    links: Vec<Link>,
+    current: String,
     rid: RequestInfo,
 ) -> Result<Envelope<serde_json::Value>, ApiError> {
     let counted = tokio::task::spawn_blocking({
@@ -234,7 +261,7 @@ async fn count(
     .await
     .map_err(|error| internal(error.to_string(), rid.clone()))?
     .map_err(|error| map_error(error, rid.clone()))?;
-    Ok(envelope(ctx, counted, &label, marker.as_deref()))
+    Ok(envelope(ctx, counted, &label, marker.as_deref(), links, &current))
 }
 
 /// The response: the frequency map as `data`, the counts that produced it in
@@ -244,6 +271,8 @@ fn envelope(
     counted: Counted,
     file: &str,
     marker: Option<&str>,
+    links: Vec<Link>,
+    current: &str,
 ) -> Envelope<serde_json::Value> {
     let tally = counted.tally;
     let cells = tally.called + tally.missing;
@@ -284,10 +313,12 @@ fn envelope(
              empty cell) are counted as missing, not as a call",
         );
     }
-    envelope.with_note(
-        "The genotypes themselves are counted and discarded: this endpoint reports a \
-         distribution, not the matrix.",
-    )
+    envelope
+        .with_note(
+            "The genotypes themselves are counted and discarded: this endpoint reports a \
+             distribution, not the matrix.",
+        )
+        .with_links_except(links, current)
 }
 
 fn internal(message: String, rid: RequestInfo) -> ApiError {
diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs
index 142a78b..2062425 100644
--- a/src/routes/gemma.rs
+++ b/src/routes/gemma.rs
@@ -580,6 +580,7 @@ pub async fn compute_gemma(
                     ),
                     "PheWAS: every published trait peaking within 10 kb of this GWAS's peak",
                 );
+                envelope = envelope.with_links(crate::suggest::group_links(group));
             }
         }
         envelope = envelope.with_note(
diff --git a/src/routes/genotypes.rs b/src/routes/genotypes.rs
index c81abc2..fa1f030 100644
--- a/src/routes/genotypes.rs
+++ b/src/routes/genotypes.rs
@@ -20,6 +20,7 @@ use crate::config::Config;
 use crate::error::{ApiError, Unauthorized};
 use crate::genotypes::{self, GenotypeError, OrderSource};
 use crate::response::{Ctx, Envelope, path_segment};
+use crate::suggest;
 
 /// One genotype file, as the listing reports it.
 #[derive(Serialize, ToSchema)]
@@ -187,6 +188,10 @@ pub async fn group_genotypes(
         None => "",
     };
 
+    let current_version = files
+        .iter()
+        .find(|file| file.current)
+        .map(|file| file.version.clone());
     Ok(Json(
         ctx.envelope(GroupGenotypes {
             group: group.clone(),
@@ -228,7 +233,11 @@ pub async fn group_genotypes(
         .with_next(
             &format!("/groups/{}", path_segment(&group)),
             "The group's record",
-        ),
+        )
+        .with_links(match current_version {
+            Some(version) => suggest::genotype_version_links(&group, &version),
+            None => suggest::root_links(),
+        }),
     ))
 }
 
@@ -276,7 +285,8 @@ pub async fn group_genotype_version(
             .with_next(
                 &format!("/groups/{}", path_segment(&link_group)),
                 "The group's record",
-            ),
+            )
+            .with_links(suggest::genotype_version_links(&link_group, &link_version)),
     ))
 }
 
@@ -327,8 +337,9 @@ pub async fn group_genotype_markers(
         path_segment(&group),
         path_segment(&version)
     );
+    let links = suggest::genotype_version_links(&group, &version);
     Ok(Json(
-        marker_names(ctx, geno, &params, &prefix, rid).await?,
+        marker_names(ctx, geno, &params, &prefix, &links, rid).await?,
     ))
 }
 
@@ -375,7 +386,10 @@ pub async fn group_marker_location(
         path_segment(&group),
         path_segment(&version)
     );
-    Ok(Json(marker_location(ctx, geno, &marker, &prefix, rid).await?))
+    let links = suggest::marker_links(&group, &version, &marker);
+    Ok(Json(
+        marker_location(ctx, geno, &marker, &prefix, &links, rid).await?,
+    ))
 }
 
 #[utoipa::path(get, path = "/groups/unlisted/genotypes/{name}/markers",
@@ -413,8 +427,9 @@ pub async fn unlisted_genotype_markers(
         genotype_error_to_api_error(error, "unlisted_genotype_markers", rid.clone())
     })?;
     let prefix = format!("/groups/unlisted/genotypes/{}/markers", path_segment(&name));
+    let links = suggest::unlisted_genotype_links(&name);
     Ok(Json(
-        marker_names(ctx, geno, &params, &prefix, rid).await?,
+        marker_names(ctx, geno, &params, &prefix, &links, rid).await?,
     ))
 }
 
@@ -449,7 +464,10 @@ pub async fn unlisted_marker_location(
     .map_err(|error| internal_error(error.to_string(), "unlisted_marker_location", rid.clone()))?
     .map_err(|error| genotype_error_to_api_error(error, "unlisted_marker_location", rid.clone()))?;
     let prefix = format!("/groups/unlisted/genotypes/{}/markers", path_segment(&name));
-    Ok(Json(marker_location(ctx, geno, &marker, &prefix, rid).await?))
+    let links = suggest::unlisted_marker_links(&name, &marker);
+    Ok(Json(
+        marker_location(ctx, geno, &marker, &prefix, &links, rid).await?,
+    ))
 }
 
 /// Read a `.geno`'s markers and answer with one page of names.
@@ -458,6 +476,7 @@ async fn marker_names(
     geno: std::path::PathBuf,
     params: &MarkerParams,
     prefix: &str,
+    links: &[suggest::Link],
     rid: crate::response::RequestInfo,
 ) -> Result<Envelope<serde_json::Value>, ApiError> {
     let limit = params.limit.unwrap_or(100).clamp(1, 10_000) as usize;
@@ -511,6 +530,7 @@ async fn marker_location(
     geno: std::path::PathBuf,
     marker: &str,
     prefix: &str,
+    links: &[suggest::Link],
     rid: crate::response::RequestInfo,
 ) -> Result<Envelope<serde_json::Value>, ApiError> {
     guard_size(&geno, "location", rid.clone())?;
@@ -538,7 +558,11 @@ async fn marker_location(
         .with_note(
             "Positions come from the genotype file itself: cM from its genetic map, Mb from its              physical one, either of which may be absent.",
         )
-        .with_next(prefix, "The marker names this file carries"))
+        .with_next(prefix, "The marker names this file carries")
+        .with_links_except(
+            links.to_vec(),
+            &format!("{prefix}/{}/location", path_segment(marker)),
+        ))
 }
 
 /// A whole-file read needs a size guard, or a 3.7 GB panel turns a listing into
diff --git a/src/routes/groups.rs b/src/routes/groups.rs
index c5af038..9d7a4bc 100644
--- a/src/routes/groups.rs
+++ b/src/routes/groups.rs
@@ -145,7 +145,8 @@ pub async fn group_by_name(
                     .with_next(
                         &format!("/groups/{name}/genotypes"),
                         "Genotype files this group can be mapped with, newest first",
-                    ),
+                    )
+                    .with_links(crate::suggest::root_links()),
             )
         })
         .ok_or_else(|| {
@@ -211,6 +212,7 @@ pub async fn group_strains(
                     &format!("/groups/{group}"),
                     "The group these strains belong to",
                 )
+                .with_links(crate::suggest::group_links(&not_found_name))
                 .with_next(
                     &format!("/groups/{group}/case-attributes"),
                     "Case-attribute names and per-strain values",
@@ -404,6 +406,7 @@ pub async fn group_trait_values(
                 &format!("/groups/{group}/traits/{trait_id}"),
                 "The trait's metadata",
             );
+            envelope = envelope.with_links(crate::suggest::trait_links(&not_found_group, i64::from(trait_id)));
             if let Some(note) = &applied_note {
                 envelope = envelope.with_note(note);
             }
@@ -521,7 +524,8 @@ pub async fn group_trait_info(
                 .with_next(
                     &format!("/groups/{group}"),
                     "The group this trait belongs to",
-                );
+                )
+                .with_links(crate::suggest::trait_links(&not_found_group, i64::from(trait_id)));
             if let Some(pubmed_id) = pubmed_id {
                 envelope = envelope.with_next(
                     &format!("/publications/{pubmed_id}/traits"),
@@ -654,7 +658,10 @@ pub async fn group_traits(
         GroupTraitsLookup::Found(traits) => {
             let group = path_segment(&not_found_name);
             Ok(Json(
-                ctx.envelope(traits).with_note(db::LOD_NOTE).with_next(
+                ctx.envelope(traits)
+                    .with_note(db::LOD_NOTE)
+                    .with_links(crate::suggest::root_links())
+                    .with_next(
                     &format!("/groups/{group}"),
                     "The group these traits belong to",
                 ),
@@ -718,10 +725,14 @@ pub async fn group_case_attributes(
     })?
     .map_err(|e| ApiError::from_db(e, "group_case_attributes").with_request_id(rid.clone()))?
     .map(|case_attributes| {
-        Json(ctx.envelope(case_attributes).with_next(
-            &format!("/groups/{}/strains", path_segment(&not_found_name)),
-            "The group's strains/samples",
-        ))
+        Json(
+            ctx.envelope(case_attributes)
+                .with_next(
+                    &format!("/groups/{}/strains", path_segment(&not_found_name)),
+                    "The group's strains/samples",
+                )
+                .with_links(crate::suggest::group_links(&not_found_name)),
+        )
     })
     .ok_or_else(|| {
         ApiError::new(
@@ -925,10 +936,15 @@ pub async fn group_datasets(
     })?
     .map_err(|e| ApiError::from_db(e, "group_datasets").with_request_id(rid.clone()))?
     .map(|datasets| {
-        Json(ctx.envelope(datasets).with_next(
-            &format!("/groups/{}", path_segment(&not_found_name)),
-            "The group these datasets belong to",
-        ))
+        Json(
+            ctx.envelope(datasets)
+                .with_next(
+                    &format!("/groups/{}", path_segment(&not_found_name)),
+                    "The group these datasets belong to",
+                )
+                .with_next("/datasets/{dataset}/probesets", "One dataset's probesets")
+                .with_links(crate::suggest::group_links(&not_found_name)),
+        )
     })
     .ok_or_else(|| {
         ApiError::new(
diff --git a/src/routes/mapping_methods.rs b/src/routes/mapping_methods.rs
index 96bd49d..3f48c63 100644
--- a/src/routes/mapping_methods.rs
+++ b/src/routes/mapping_methods.rs
@@ -34,7 +34,7 @@ pub async fn mapping_methods(
             .with_request_id(rid.clone())
         })?
         .map(|methods| {
-            Json(ctx.envelope(methods).with_next(
+            Json(ctx.envelope(methods).with_links(crate::suggest::root_links()).with_next(
                 "/groups",
                 "Groups, each with the mapping tool offered for it (`mapping_method`)",
             ))
diff --git a/src/routes/phewas.rs b/src/routes/phewas.rs
index b5eb45a..3ccccc3 100644
--- a/src/routes/phewas.rs
+++ b/src/routes/phewas.rs
@@ -364,7 +364,7 @@ pub async fn group_phewas(
             ),
             "The same PheWAS with a ten-times wider window",
         );
-    Ok(Json(envelope))
+    Ok(Json(envelope.with_links(crate::suggest::root_links())))
 }
 
 /// The group name a version stem belongs to, for error messages: `BXD.8`
diff --git a/src/routes/publications.rs b/src/routes/publications.rs
index fe2f553..b82e3af 100644
--- a/src/routes/publications.rs
+++ b/src/routes/publications.rs
@@ -132,7 +132,7 @@ pub async fn publication_traits(
                     "Metadata of the first trait",
                 );
             }
-            Ok(Json(envelope))
+            Ok(Json(envelope.with_links(crate::suggest::root_links())))
         }
         PublicationTraits::NotFound => Err(ApiError::new(
             StatusCode::NOT_FOUND,
diff --git a/src/routes/qtl2.rs b/src/routes/qtl2.rs
index 649600d..6cc736c 100644
--- a/src/routes/qtl2.rs
+++ b/src/routes/qtl2.rs
@@ -545,6 +545,9 @@ pub async fn compute_qtl2(
         .await?;
 
     let num_rows = output.markers;
+    // The strongest marker, for a PheWAS link that answers 200: a bare
+    // /phewas wants a locus.
+    let peak_marker = crate::suggest::peak_marker_of(&output.rows, 0, 3);
     let mut envelope = ctx
         .envelope(output.rows)
         .with_columns(
@@ -576,10 +579,17 @@ pub async fn compute_qtl2(
                 .to_string(),
             body: None,
         });
-        envelope = envelope.with_next(
-            &format!("/groups/{}/phewas", path_segment(&group)),
-            "PheWAS: every published trait peaking near a locus (add ?locus=)",
-        );
+        if let Some(peak) = &peak_marker {
+            envelope = envelope.with_next(
+                &format!(
+                    "/groups/{}/phewas?locus={}",
+                    path_segment(&group),
+                    path_segment(peak)
+                ),
+                "PheWAS: every published trait peaking at this scan's strongest marker",
+            );
+        }
+        envelope = envelope.with_links(crate::suggest::group_links(&group));
     }
     Ok(Json(envelope))
 }
diff --git a/src/routes/rqtl.rs b/src/routes/rqtl.rs
index 2a58efb..0e142fb 100644
--- a/src/routes/rqtl.rs
+++ b/src/routes/rqtl.rs
@@ -448,6 +448,7 @@ pub async fn compute_rqtl(
                     ),
                     "PheWAS: every published trait peaking within 10 kb of this QTL's peak",
                 );
+                envelope = envelope.with_links(crate::suggest::group_links(group));
             }
         }
         envelope = envelope.with_note(
diff --git a/src/routes/search.rs b/src/routes/search.rs
index f1ae7cf..20f9712 100644
--- a/src/routes/search.rs
+++ b/src/routes/search.rs
@@ -280,7 +280,7 @@ pub async fn search(
             "Metadata of the top hit",
         );
     }
-    Ok(Json(envelope))
+    Ok(Json(envelope.with_links(crate::suggest::root_links())))
 }
 
 #[cfg(test)]
diff --git a/src/routes/species.rs b/src/routes/species.rs
index 6c7474b..c87f2ca 100644
--- a/src/routes/species.rs
+++ b/src/routes/species.rs
@@ -37,10 +37,15 @@ pub async fn species(
             .with_request_id(rid.clone())
         })?
         .map(|species| {
-            Json(ctx.envelope(species).with_next(
-                "/groups",
-                "Groups (populations); add ?species=<name> to list one species' groups",
-            ))
+            Json(
+                ctx.envelope(species)
+                    .with_next(
+                        "/groups",
+                        "Groups (populations); add ?species=<name> to list one species' groups",
+                    )
+                    .with_next("/species/{species}", "One species by name")
+                    .with_links(crate::suggest::root_links()),
+            )
         })
         .map_err(|e| ApiError::from_db(e, "species").with_request_id(rid))
 }
@@ -82,7 +87,8 @@ pub async fn species_by_name(
                         &format!("/species/{name}/datasets"),
                         "Expression datasets of this species",
                     )
-                    .with_next(&format!("/groups?species={name}"), "Groups of this species"),
+                    .with_next(&format!("/groups?species={name}"), "Groups of this species")
+                    .with_links(crate::suggest::root_links()),
             )
         })
         .ok_or_else(|| {
@@ -133,10 +139,15 @@ pub async fn species_datasets(
     })?
     .map_err(|e| ApiError::from_db(e, "species_datasets").with_request_id(rid.clone()))?
     .map(|datasets| {
-        Json(ctx.envelope(datasets).with_next(
-            &format!("/species/{}", path_segment(&not_found_name)),
-            "The species these datasets belong to",
-        ))
+        Json(
+            ctx.envelope(datasets)
+                .with_next(
+                    &format!("/species/{}", path_segment(&not_found_name)),
+                    "The species these datasets belong to",
+                )
+                .with_next("/datasets/{dataset}", "One dataset's probesets")
+                .with_links(crate::suggest::root_links()),
+        )
     })
     .ok_or_else(|| {
         ApiError::new(
diff --git a/src/routes/traits.rs b/src/routes/traits.rs
index 28ff6ba..b6515e0 100644
--- a/src/routes/traits.rs
+++ b/src/routes/traits.rs
@@ -162,7 +162,11 @@ pub async fn traits(
         })
         .and_then(|lookup| match lookup {
             TraitsLookup::Found(_authorized, traits) => {
-                Ok(Json(ctx.envelope(traits).with_note(db::LOD_NOTE)))
+                Ok(Json(
+                    ctx.envelope(traits)
+                        .with_note(db::LOD_NOTE)
+                        .with_links(crate::suggest::root_links()),
+                ))
             }
             TraitsLookup::Forbidden => Err(ApiError::new(
                 StatusCode::FORBIDDEN,
@@ -321,7 +325,7 @@ pub async fn trait_info(
                     "Every trait reported by this trait's publication",
                 );
             }
-            Ok(Json(envelope))
+            Ok(Json(envelope.with_links(crate::suggest::root_links())))
         }
         TraitInfoLookup::Forbidden => Err(ApiError::new(
             StatusCode::FORBIDDEN,
@@ -489,7 +493,30 @@ pub async fn trait_values(
                             path_segment(&not_found_trait)
                         ),
                         "The trait's metadata",
-                    ),
+                    )
+                    .with_links(vec![
+                        (
+                            format!(
+                                "/traits/{}/{}/correlation",
+                                path_segment(&not_found_dataset),
+                                path_segment(&not_found_trait)
+                            ),
+                            "Correlate these values with another trait's (a POST: see actions)",
+                        ),
+                        (
+                            format!("/groups/{}/phewas", path_segment(&not_found_dataset)),
+                            "PheWAS: this group's traits peaking near one locus",
+                        ),
+                        (
+                            format!("/groups/{}/genotypes", path_segment(&not_found_dataset)),
+                            "The genotype versions these values can be mapped against",
+                        ),
+                        (
+                            format!("/groups/{}/traits", path_segment(&not_found_dataset)),
+                            "The group's other published traits",
+                        ),
+                    ])
+                    .with_links(crate::suggest::root_links()),
             ))
         }
         TraitValuesLookup::Forbidden => Err(ApiError::new(
diff --git a/src/suggest.rs b/src/suggest.rs
index debcdd0..51d729a 100644
--- a/src/suggest.rs
+++ b/src/suggest.rs
@@ -259,3 +259,204 @@ fn with_normalization(
     }
     serde_json::Value::Object(object)
 }
+
+// ---------------------------------------------------------------------------
+// `next` links: where a caller can go from what it just got.
+//
+// `next` is for `GET`s only (following one must return 200), which is why the
+// compute endpoints' `POST`s live in `actions`. The rule these builders
+// follow is that a link is offered whenever the id it needs is already known
+// to the server: a version's frequencies and markers, a marker's location and
+// tally, a group's traits and PheWAS, a trait's values, a species' datasets.
+// Offering the obvious next call is cheaper than making every client
+// re-derive the path vocabulary, and it is the only way an agent discovers
+// that `/groups/unlisted/...` exists at all.
+// ---------------------------------------------------------------------------
+
+use crate::response::path_segment;
+
+/// `(href, description)`, ready for [`NextAction`].
+pub type Link = (String, &'static str);
+
+/// Path-safe identifier.
+fn seg(value: &str) -> String {
+    path_segment(value)
+}
+
+/// The listings every endpoint can reach, so a dead end is never returned.
+pub fn root_links() -> Vec<Link> {
+    vec![
+        ("/groups".to_string(), "Every group, with its species and mapping method"),
+        ("/species".to_string(), "Every species"),
+        (
+            "/mapping-methods".to_string(),
+            "The mapping tools GeneNetwork has run (R/qtl, GEMMA, qtlreaper, ...)",
+        ),
+        ("/openapi.json".to_string(), "This API's OpenAPI document"),
+    ]
+}
+
+/// Everything one genotype version offers: the tally, the names, the
+/// positions, and the scans that run on it.
+pub fn genotype_version_links(group: &str, version: &str) -> Vec<Link> {
+    let base = format!(
+        "/groups/{}/genotypes/{}",
+        seg(group),
+        seg(version)
+    );
+    vec![
+        (
+            format!("{base}/frequencies"),
+            "What this panel is actually called as: call -> frequency",
+        ),
+        (
+            format!("{base}/markers"),
+            "The marker names this version carries, paged (positions are one call per marker)",
+        ),
+        (
+            format!("{base}/markers/{{marker}}/location"),
+            "One marker's position (name, chr, cM, Mb) -- fill in a marker name",
+        ),
+        (
+            format!("{base}/markers/{{marker}}/frequencies"),
+            "One marker's calls across the panel -- a flat LOD from a nearly-missing marker \
+             looks like real data otherwise",
+        ),
+        (
+            format!("/groups/{}", seg(group)),
+            "The group's record (species, mapping method, trait count)",
+        ),
+    ]
+}
+
+/// The same, for a file no group lists.
+pub fn unlisted_genotype_links(name: &str) -> Vec<Link> {
+    let base = format!("/groups/unlisted/genotypes/{}", seg(name));
+    vec![
+        (
+            format!("{base}/frequencies"),
+            "What this panel is actually called as: call -> frequency",
+        ),
+        (
+            format!("{base}/markers"),
+            "The marker names it carries, paged",
+        ),
+        (
+            format!("{base}/markers/{{marker}}/location"),
+            "One marker's position -- fill in a marker name",
+        ),
+        (
+            format!("{base}/markers/{{marker}}/frequencies"),
+            "One marker's calls across the panel -- fill in a marker name",
+        ),
+    ]
+}
+
+/// One marker of one version: its position, its tally, and its PheWAS.
+pub fn marker_links(group: &str, version: &str, marker: &str) -> Vec<Link> {
+    let base = format!(
+        "/groups/{}/genotypes/{}/markers",
+        seg(group),
+        seg(version)
+    );
+    vec![
+        (
+            format!("{base}/{}/location", seg(marker)),
+            "This marker's position (name, chr, cM, Mb)",
+        ),
+        (
+            format!("{base}/{}/frequencies", seg(marker)),
+            "This marker's calls across the panel, as frequencies",
+        ),
+        (base, "The names of every marker in this version"),
+        (
+            format!(
+                "/groups/{}/genotypes/{}/frequencies",
+                seg(group),
+                seg(version)
+            ),
+            "The whole panel's call frequencies",
+        ),
+        (
+            format!("/groups/{}/phewas?locus={}", seg(group), seg(marker)),
+            "PheWAS: every published trait of this group peaking at this marker",
+        ),
+    ]
+}
+
+/// One marker of a file no group lists.
+pub fn unlisted_marker_links(name: &str, marker: &str) -> Vec<Link> {
+    let base = format!("/groups/unlisted/genotypes/{}/markers", seg(name));
+    vec![
+        (
+            format!("{base}/{}/location", seg(marker)),
+            "This marker's position (name, chr, cM, Mb)",
+        ),
+        (
+            format!("{base}/{}/frequencies", seg(marker)),
+            "This marker's calls across the panel, as frequencies",
+        ),
+        (base, "Every marker name in this file"),
+        (
+            format!("/groups/unlisted/genotypes/{}/frequencies", seg(name)),
+            "The whole file's call frequencies",
+        ),
+    ]
+}
+
+/// What a group leads to.
+pub fn group_links(group: &str) -> Vec<Link> {
+    let base = format!("/groups/{}", seg(group));
+    vec![
+        (
+            format!("{base}/genotypes"),
+            "The genotype versions this group can be mapped with, newest first",
+        ),
+        (
+            format!("{base}/traits"),
+            "Every published trait of this group",
+        ),
+        (
+            "/species".to_string(),
+            "The species of this group, among every species the deployment holds",
+        ),
+        (
+            "/groups/unlisted/genotypes/{name}/frequencies".to_string(),
+            "Or tally a genotype file that no group lists",
+        ),
+    ]
+}
+
+/// What one trait leads to.
+pub fn trait_links(group: &str, trait_id: i64) -> Vec<Link> {
+    let base = format!("/groups/{}/traits/{}", seg(group), trait_id);
+    vec![
+        (
+            format!("{base}/values"),
+            "This trait's value per strain (and the mapping suggestions they come with)",
+        ),
+        (
+            format!("/groups/{}/genotypes", seg(group)),
+            "The genotype versions this group's traits can be mapped against",
+        ),
+        (
+            format!("/groups/{}/traits", seg(group)),
+            "Every published trait of this group",
+        ),
+    ]
+}
+
+/// The marker name of the row with the highest value in `score_column` --
+/// what a scan's strongest locus is, for a PheWAS link that can be followed.
+pub fn peak_marker_of(rows: &serde_json::Value, name_column: usize, score_column: usize) -> Option<String> {
+    rows.as_array()?
+        .iter()
+        .filter_map(|row| {
+            let row = row.as_array()?;
+            let score = row.get(score_column)?.as_f64()?;
+            let name = row.get(name_column)?.as_str()?.to_string();
+            Some((name, score))
+        })
+        .max_by(|left, right| left.1.partial_cmp(&right.1).unwrap_or(std::cmp::Ordering::Equal))
+        .map(|(name, _)| name)
+}