All files / src/app/api/graph route.ts

68.18% Statements 45/66
57.89% Branches 33/57
72.22% Functions 13/18
64.4% Lines 38/59

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553                        1x     1x                                       7x 7x 7x 7x 7x 7x                         7x 7x 11x   5x 5x 5x 1x 5x 5x                                                                                                                                                                                                                                                                                                                                                                                                     2x                                             2x                                                                                                                                                                                                                                                             6x                                                                                             5x                                                     8x 8x     56x 8x   8x   8x                     2x 2x               6x     7x               7x     15x 7x             1x   1x     1x         1x                    
import { NextResponse } from "next/server";
import { runQuery } from "@/lib/neo4j";
import {
  LABEL_LAYER,
  LAYER_COLORS,
  NODE_ROLE_COLORS,
  LABEL_SORT_ORDER,
  LABEL_GROUP,
  PERSONA_VIEWS,
  type PersonaId,
} from "@/lib/graph-constants";
 
export const dynamic = "force-dynamic";
 
// Governance + catalog labels — always included in researcher overview
const GOVERNANCE_LABELS = [
  "Participant",
  "DataProduct",
  "OdrlPolicy",
  "Contract",
  "HDABApproval",
  "ContractNegotiation",
  "HealthDataset",
  "Distribution",
  "EEHRxFProfile",
  "VerifiableCredential",
  "TransferEvent",
  "EhdsPurpose",
  "Catalogue",
  "Organization",
  "TrustCenter",
  "SPESession",
];
 
function toNode(r: { id: string; labels: string[]; name: string }) {
  const label = r.labels[0] ?? "Node";
  const layer = r.labels.map((l) => LABEL_LAYER[l]).find(Boolean) ?? 0;
  const color = NODE_ROLE_COLORS[label] ?? LAYER_COLORS[layer] ?? "#888";
  const group = LABEL_GROUP[label] ?? "other";
  const sortKey = LABEL_SORT_ORDER[label] ?? 99;
  return {
    id: r.id,
    name: r.name,
    label,
    layer,
    color,
    group,
    sortKey,
    expandable: true,
  };
}
 
function sortAndDedup(rows: { id: string; labels: string[]; name: string }[]) {
  const seen = new Set<string>();
  return rows
    .filter((r) => (seen.has(r.id) ? false : seen.add(r.id) && true))
    .sort((a, b) => {
      const la = a.labels.map((l) => LABEL_LAYER[l]).find(Boolean) ?? 0;
      const lb = b.labels.map((l) => LABEL_LAYER[l]).find(Boolean) ?? 0;
      if (la !== lb) return la - lb;
      const sa = LABEL_SORT_ORDER[a.labels[0] ?? ""] ?? 99;
      const sb = LABEL_SORT_ORDER[b.labels[0] ?? ""] ?? 99;
      if (sa !== sb) return sa - sb;
      return (a.name ?? "").localeCompare(b.name ?? "");
    })
    .map(toNode);
}
 
// ── Persona-specific subgraph builders ───────────────────────────────────────
 
/** Trust Center: pseudonym resolution chains + governed datasets + cross-border */
async function buildTrustCenterGraph() {
  const [tcNodes, speNodes, rpsnNodes, datasetNodes] = await Promise.all([
    runQuery<{ id: string; labels: string[]; name: string }>(
      `MATCH (tc:TrustCenter)
       OPTIONAL MATCH (tc)-[:GOVERNED_BY]->(ha:HDABApproval)
       WITH tc, ha
       RETURN elementId(tc) AS id, labels(tc) AS labels, tc.name AS name
       UNION
       MATCH (ha:HDABApproval)
       RETURN elementId(ha) AS id, labels(ha) AS labels,
              coalesce(ha.approvalId, elementId(ha)) AS name`,
    ),
    runQuery<{ id: string; labels: string[]; name: string }>(
      `MATCH (ss:SPESession)
       RETURN elementId(ss) AS id, labels(ss) AS labels,
              coalesce(ss.studyId, ss.sessionId, elementId(ss)) AS name
       ORDER BY ss.createdAt DESC LIMIT 20`,
    ),
    runQuery<{ id: string; labels: string[]; name: string }>(
      `MATCH (rp:ResearchPseudonym {revoked: false})
       RETURN elementId(rp) AS id, labels(rp) AS labels,
              coalesce(rp.studyId, rp.rpsnId, elementId(rp)) AS name
       LIMIT 20
       UNION
       MATCH (pp:ProviderPseudonym)
       RETURN elementId(pp) AS id, labels(pp) AS labels,
              coalesce(pp.providerId, pp.psnId, elementId(pp)) AS name
       LIMIT 20`,
    ),
    runQuery<{ id: string; labels: string[]; name: string }>(
      `MATCH (tc:TrustCenter)-[:RESOLVES_PSEUDONYMS_FOR]->(ds:HealthDataset)
       RETURN elementId(ds) AS id, labels(ds) AS labels,
              coalesce(ds.title, ds.datasetId, elementId(ds)) AS name`,
    ),
  ]);
  return sortAndDedup([...tcNodes, ...speNodes, ...rpsnNodes, ...datasetNodes]);
}
 
/** Hospital / Data Holder: their datasets, data products, active contracts, who has access */
async function buildHospitalGraph() {
  const [
    participantNodes,
    datasetNodes,
    productNodes,
    contractNodes,
    credNodes,
  ] = await Promise.all([
    runQuery<{ id: string; labels: string[]; name: string }>(
      `MATCH (p:Participant)
         RETURN elementId(p) AS id, labels(p) AS labels,
                coalesce(p.name, p.participantId, elementId(p)) AS name
         ORDER BY p.name`,
    ),
    runQuery<{ id: string; labels: string[]; name: string }>(
      `MATCH (ds:HealthDataset)
         RETURN elementId(ds) AS id, labels(ds) AS labels,
                coalesce(ds.title, ds.datasetId, elementId(ds)) AS name
         ORDER BY ds.title LIMIT 30
         UNION
         MATCH (d:Distribution)
         RETURN elementId(d) AS id, labels(d) AS labels,
                coalesce(d.name, d.title, d.format, d.distributionId, elementId(d)) AS name
         LIMIT 20
         UNION
         MATCH (ep:EEHRxFProfile)
         RETURN elementId(ep) AS id, labels(ep) AS labels,
                coalesce(ep.title, ep.profileId, elementId(ep)) AS name
         LIMIT 15`,
    ),
    // DataProduct — the offerings participants publish
    runQuery<{ id: string; labels: string[]; name: string }>(
      `MATCH (dp:DataProduct)
         RETURN elementId(dp) AS id, labels(dp) AS labels,
                coalesce(dp.name, dp.title, dp.productId, elementId(dp)) AS name
         LIMIT 20`,
    ),
    runQuery<{ id: string; labels: string[]; name: string }>(
      `MATCH (c:Contract)
         RETURN elementId(c) AS id, labels(c) AS labels,
                coalesce(c.name, c.contractId, elementId(c)) AS name
         UNION
         MATCH (ha:HDABApproval)
         RETURN elementId(ha) AS id, labels(ha) AS labels,
                coalesce(ha.name, ha.approvalId, elementId(ha)) AS name
         UNION
         MATCH (aa:AccessApplication)
         RETURN elementId(aa) AS id, labels(aa) AS labels,
                coalesce(aa.name, aa.applicationId, elementId(aa)) AS name`,
    ),
    runQuery<{ id: string; labels: string[]; name: string }>(
      `MATCH (vc:VerifiableCredential)
         RETURN elementId(vc) AS id, labels(vc) AS labels,
                coalesce(vc.credentialType, vc.credentialId, elementId(vc)) AS name
         ORDER BY vc.credentialType LIMIT 20`,
    ),
  ]);
  return sortAndDedup([
    ...participantNodes,
    ...datasetNodes,
    ...productNodes,
    ...contractNodes,
    ...credNodes,
  ]);
}
 
/** Researcher: datasets + OMOP analytics + pseudonym chain + clinical conditions */
async function buildResearcherGraph() {
  const [datasetNodes, omopNodes, conditionNodes, ontologyNodes, speNodes] =
    await Promise.all([
      runQuery<{ id: string; labels: string[]; name: string }>(
        `MATCH (ds:HealthDataset)
         RETURN elementId(ds) AS id, labels(ds) AS labels,
                coalesce(ds.title, ds.datasetId, elementId(ds)) AS name
         ORDER BY ds.title LIMIT 20
         UNION
         MATCH (dp:DataProduct)
         RETURN elementId(dp) AS id, labels(dp) AS labels,
                coalesce(dp.name, dp.productId, elementId(dp)) AS name
         LIMIT 15
         UNION
         MATCH (ep:EEHRxFProfile)
         RETURN elementId(ep) AS id, labels(ep) AS labels,
                coalesce(ep.title, ep.profileId, elementId(ep)) AS name
         LIMIT 10`,
      ),
      runQuery<{ id: string; labels: string[]; name: string }>(
        `MATCH (op:OMOPPerson)-[:HAS_CONDITION_OCCURRENCE]->(:OMOPConditionOccurrence)
         WITH op, count(*) AS cnt ORDER BY cnt DESC LIMIT 15
         RETURN elementId(op) AS id, labels(op) AS labels,
                coalesce(op.name, toString(op.personId), elementId(op)) AS name
         UNION
         MATCH (oc:OMOPConditionOccurrence)<-[:HAS_CONDITION_OCCURRENCE]-(:OMOPPerson)
         WITH oc, count(*) AS freq ORDER BY freq DESC LIMIT 30
         RETURN elementId(oc) AS id, labels(oc) AS labels,
                coalesce(oc.name, toString(oc.conditionConceptId), elementId(oc)) AS name
         UNION
         MATCH (om:OMOPMeasurement)
         RETURN elementId(om) AS id, labels(om) AS labels,
                coalesce(om.name, toString(om.measurementConceptId), elementId(om)) AS name
         LIMIT 10`,
      ),
      runQuery<{ id: string; labels: string[]; name: string }>(
        `MATCH (c:Condition)<-[:HAS_CONDITION]-(:Patient)
         WITH c, count(*) AS freq ORDER BY freq DESC LIMIT 30
         RETURN elementId(c) AS id, labels(c) AS labels,
                coalesce(c.display, c.name, c.code, elementId(c)) AS name`,
      ),
      runQuery<{ id: string; labels: string[]; name: string }>(
        `MATCH (s:SnomedConcept)
         WITH s, count{(s)-[]-()} AS deg ORDER BY deg DESC LIMIT 20
         RETURN elementId(s) AS id, labels(s) AS labels,
                coalesce(s.display, s.code, elementId(s)) AS name
         UNION
         MATCH (l:LoincCode)
         WITH l, count{(l)-[]-()} AS deg ORDER BY deg DESC LIMIT 10
         RETURN elementId(l) AS id, labels(l) AS labels,
                coalesce(l.display, l.code, elementId(l)) AS name
         UNION
         MATCH (rx:RxNormConcept)
         WITH rx, count{(rx)-[]-()} AS deg ORDER BY deg DESC LIMIT 10
         RETURN elementId(rx) AS id, labels(rx) AS labels,
                coalesce(rx.display, rx.name, rx.code, elementId(rx)) AS name`,
      ),
      runQuery<{ id: string; labels: string[]; name: string }>(
        `MATCH (rp:ResearchPseudonym {revoked: false})
         RETURN elementId(rp) AS id, labels(rp) AS labels,
                coalesce(rp.studyId, rp.rpsnId, elementId(rp)) AS name
         LIMIT 10
         UNION
         MATCH (ss:SPESession {status: "active"})
         RETURN elementId(ss) AS id, labels(ss) AS labels,
                coalesce(ss.studyId, ss.sessionId, elementId(ss)) AS name
         LIMIT 10`,
      ),
    ]);
  return sortAndDedup([
    ...datasetNodes,
    ...omopNodes,
    ...conditionNodes,
    ...ontologyNodes,
    ...speNodes,
  ]);
}
 
/** EDC Admin: all participants, products, contracts, negotiations, transfers */
async function buildEdcAdminGraph() {
  const rows = await runQuery<{ id: string; labels: string[]; name: string }>(
    `MATCH (n)
     WHERE any(l IN labels(n) WHERE l IN $labels)
     RETURN elementId(n) AS id, labels(n) AS labels,
            coalesce(n.name, n.title, n.display, n.participantId, n.productId,
                     n.contractId, n.credentialType, n.transferId,
                     n.endpoint + ' ' + n.method, n.endpoint,
                     n.eventId, n.id, elementId(n)) AS name
     ORDER BY labels(n)[0], coalesce(n.name, n.display, n.id)`,
    {
      labels: [
        "Participant",
        "Organization",
        "DataProduct",
        "OdrlPolicy",
        "Contract",
        "ContractNegotiation",
        "DataTransfer",
        "TransferEvent",
        "VerifiableCredential",
      ],
    },
  );
  return sortAndDedup(rows);
}
 
/** HDAB Authority: approval chains, credentials, trust center governance */
async function buildHdabGraph() {
  const [govNodes, tcNodes, vcNodes] = await Promise.all([
    runQuery<{ id: string; labels: string[]; name: string }>(
      `MATCH (n)
       WHERE any(l IN labels(n) WHERE l IN $labels)
       RETURN elementId(n) AS id, labels(n) AS labels,
              coalesce(n.name, n.display, n.title, n.approvalId, n.applicationId,
                       n.contractId, n.productId, n.participantId, elementId(n)) AS name
       ORDER BY labels(n)[0]`,
      {
        labels: [
          "HDABApproval",
          "AccessApplication",
          "OdrlPolicy",
          "Participant",
          "DataProduct",
          "Contract",
        ],
      },
    ),
    runQuery<{ id: string; labels: string[]; name: string }>(
      `MATCH (tc:TrustCenter)
       RETURN elementId(tc) AS id, labels(tc) AS labels, tc.name AS name
       UNION
       MATCH (ss:SPESession)
       RETURN elementId(ss) AS id, labels(ss) AS labels,
              coalesce(ss.studyId, ss.sessionId, elementId(ss)) AS name
       LIMIT 15`,
    ),
    runQuery<{ id: string; labels: string[]; name: string }>(
      `MATCH (vc:VerifiableCredential)
       RETURN elementId(vc) AS id, labels(vc) AS labels,
              coalesce(vc.credentialType, vc.credentialId, elementId(vc)) AS name
       ORDER BY vc.credentialType LIMIT 30`,
    ),
  ]);
  return sortAndDedup([...govNodes, ...tcNodes, ...vcNodes]);
}
 
/** Patient: own FHIR data + governance chain showing who uses it (EHDS Art. 3-12) */
async function buildPatientGraph() {
  const [patientNodes, conditionNodes, omopNodes, speNodes, govNodes] =
    await Promise.all([
      // Top 20 patients with richest records (GDPR Art. 15 — access own data)
      runQuery<{ id: string; labels: string[]; name: string }>(
        `MATCH (p:Patient)-[:HAS_CONDITION]->(:Condition)
         WITH p, count(*) AS cnt ORDER BY cnt DESC LIMIT 20
         RETURN elementId(p) AS id, labels(p) AS labels,
                coalesce(p.name, p.id, elementId(p)) AS name`,
        {},
      ),
      // Their top conditions — display name before code
      runQuery<{ id: string; labels: string[]; name: string }>(
        `MATCH (c:Condition)<-[:HAS_CONDITION]-(:Patient)
         WITH c, count(*) AS freq ORDER BY freq DESC LIMIT 30
         RETURN elementId(c) AS id, labels(c) AS labels,
                coalesce(c.display, c.code, elementId(c)) AS name`,
        {},
      ),
      // OMOP CDM: persons only (condition occurrences use numeric IDs unhelpful to patients)
      runQuery<{ id: string; labels: string[]; name: string }>(
        `MATCH (op:OMOPPerson)
         RETURN elementId(op) AS id, labels(op) AS labels,
                coalesce(op.name, toString(op.personId), elementId(op)) AS name
         LIMIT 15`,
        {},
      ),
      // Research pseudonyms, SPE sessions, consents (EHDS Art. 10 secondary use)
      runQuery<{ id: string; labels: string[]; name: string }>(
        `MATCH (rp:ResearchPseudonym {revoked: false})
         RETURN elementId(rp) AS id, labels(rp) AS labels,
                coalesce(rp.studyId, rp.rpsnId, elementId(rp)) AS name
         LIMIT 10
         UNION
         MATCH (ss:SPESession)
         RETURN elementId(ss) AS id, labels(ss) AS labels,
                coalesce(ss.studyId, ss.sessionId, elementId(ss)) AS name
         LIMIT 5
         UNION
         MATCH (pc:PatientConsent {revoked: false})
         RETURN elementId(pc) AS id, labels(pc) AS labels,
                coalesce(pc.studyId, pc.consentId, elementId(pc)) AS name
         LIMIT 10`,
        {},
      ),
      // Data consumers — who has access to the data (GDPR Art. 15 transparency)
      runQuery<{ id: string; labels: string[]; name: string }>(
        `MATCH (p:Participant)
         RETURN elementId(p) AS id, labels(p) AS labels,
                coalesce(p.name, p.participantId, elementId(p)) AS name
         ORDER BY p.name
         UNION
         MATCH (dp:DataProduct)
         RETURN elementId(dp) AS id, labels(dp) AS labels,
                coalesce(dp.name, dp.productId, elementId(dp)) AS name
         LIMIT 15
         UNION
         MATCH (ha:HDABApproval)
         RETURN elementId(ha) AS id, labels(ha) AS labels,
                coalesce(ha.approvalId, elementId(ha)) AS name
         LIMIT 10`,
        {},
      ),
    ]);
  return sortAndDedup([
    ...govNodes,
    ...patientNodes,
    ...conditionNodes,
    ...omopNodes,
    ...speNodes,
  ]);
}
 
// ── Default overview (unchanged from before) ─────────────────────────────────
 
async function buildDefaultGraph() {
  const [
    govNodes,
    patientNodes,
    conditionNodes,
    snomedNodes,
    loincNodes,
    rxnormNodes,
  ] = await Promise.all([
    runQuery<{ id: string; labels: string[]; name: string }>(
      `MATCH (n) WHERE any(l IN labels(n) WHERE l IN $labels)
         RETURN elementId(n) AS id, labels(n) AS labels,
                coalesce(n.name, n.title, n.display, n.participantId,
                         n.productId, n.credentialType, n.transferId,
                         n.endpoint + ' ' + n.method, n.endpoint,
                         n.eventId, n.code, n.id, elementId(n)) AS name
         ORDER BY labels(n)[0], coalesce(n.name, n.display, n.id)`,
      { labels: GOVERNANCE_LABELS },
    ),
    runQuery<{ id: string; labels: string[]; name: string }>(
      `MATCH (p:Patient)-[:HAS_CONDITION]->(:Condition)
         WITH p, count(*) AS cnt ORDER BY cnt DESC LIMIT 20
         RETURN elementId(p) AS id, labels(p) AS labels,
                coalesce(p.name, p.id, elementId(p)) AS name`,
      {},
    ),
    runQuery<{ id: string; labels: string[]; name: string }>(
      `MATCH (c:Condition)<-[:HAS_CONDITION]-(:Patient)
         WITH c, count(*) AS freq ORDER BY freq DESC LIMIT 50
         RETURN elementId(c) AS id, labels(c) AS labels,
                coalesce(c.display, c.name, c.code, elementId(c)) AS name`,
      {},
    ),
    runQuery<{ id: string; labels: string[]; name: string }>(
      `MATCH (s:SnomedConcept)
         WITH s, count{(s)-[]-()} AS deg ORDER BY deg DESC LIMIT 30
         RETURN elementId(s) AS id, labels(s) AS labels,
                coalesce(s.display, s.code, elementId(s)) AS name`,
      {},
    ),
    runQuery<{ id: string; labels: string[]; name: string }>(
      `MATCH (l:LoincCode)
         WITH l, count{(l)-[]-()} AS deg ORDER BY deg DESC LIMIT 20
         RETURN elementId(l) AS id, labels(l) AS labels,
                coalesce(l.display, l.code, elementId(l)) AS name`,
      {},
    ),
    runQuery<{ id: string; labels: string[]; name: string }>(
      `MATCH (r:RxNormConcept)
         WITH r, count{(r)-[]-()} AS deg ORDER BY deg DESC LIMIT 20
         RETURN elementId(r) AS id, labels(r) AS labels,
                coalesce(r.display, r.name, r.code, elementId(r)) AS name`,
      {},
    ),
  ]);
  return sortAndDedup([
    ...govNodes,
    ...patientNodes,
    ...conditionNodes,
    ...snomedNodes,
    ...loincNodes,
    ...rxnormNodes,
  ]);
}
 
// ── Route handler ─────────────────────────────────────────────────────────────
 
/**
 * GET /api/graph?persona=<id>
 *
 * Returns a persona-specific subgraph. Supported personas:
 *   default        — full researcher overview (~200 nodes)
 *   trust-center   — TC operator: pseudonym chains + governed datasets
 *   hospital       — data holder: datasets + contracts + credentials
 *   researcher     — data user: OMOP + datasets + clinical conditions
 *   edc-admin      — operator: participants + products + transfers
 *   hdab           — authority: approvals + credentials + TC governance
 */
// Public endpoint — the /graph page is the demo landing view and must
// work without authentication. Data is fully synthetic (127 fictional
// patients seeded from Synthea).
export async function GET(req: Request) {
  const { searchParams } = new URL(req.url);
  const persona = (searchParams.get("persona") ?? "default") as PersonaId;
 
  // Validate persona
  const validPersonas = PERSONA_VIEWS.map((p) => p.id);
  const safePersona = validPersonas.includes(persona) ? persona : "default";
 
  try {
    let nodes;
    switch (safePersona) {
      case "trust-center":
        nodes = await buildTrustCenterGraph();
        break;
      case "hospital":
        nodes = await buildHospitalGraph();
        break;
      case "researcher":
        nodes = await buildResearcherGraph();
        break;
      case "edc-admin":
        nodes = await buildEdcAdminGraph();
        break;
      case "hdab":
        nodes = await buildHdabGraph();
        break;
      case "patient":
        nodes = await buildPatientGraph();
        break;
      default:
        nodes = await buildDefaultGraph();
    }
 
    const links = await runQuery<{
      source: string;
      target: string;
      type: string;
    }>(
      `MATCH (a)-[r]->(b)
       WHERE elementId(a) IN $ids AND elementId(b) IN $ids
       RETURN DISTINCT elementId(a) AS source, elementId(b) AS target, type(r) AS type`,
      { ids: nodes.map((n) => n.id) },
    );
 
    const personaMeta = PERSONA_VIEWS.find((p) => p.id === safePersona);
    return NextResponse.json({
      nodes,
      links,
      persona: safePersona,
      question: personaMeta?.question,
    });
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    const code =
      err && typeof err === "object" && "code" in err
        ? String((err as { code?: unknown }).code ?? "")
        : "";
    console.error("GET /api/graph error:", {
      message: msg,
      code,
      uri: process.env.NEO4J_URI ?? "(unset)",
    });
    return NextResponse.json(
      {
        error: "Neo4j unavailable",
        detail: msg,
        code,
      },
      { status: 502 },
    );
  }
}