Spaces:
4
Sleeping

Adi12345 commited on
Commit
d222726
·
verified ·
1 Parent(s): 11002af

Update dvnc_ai_v2_hf/app.py

Browse files
Files changed (1) hide show
  1. dvnc_ai_v2_hf/app.py +752 -4
dvnc_ai_v2_hf/app.py CHANGED
@@ -1276,6 +1276,572 @@ def load_example():
1276
  def load_paper_topic():
1277
  return "self-assembling conductive biomaterials for cardiac repair"
1278
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1279
 
1280
  CSS = r"""
1281
  :root {
@@ -1469,6 +2035,131 @@ footer { display: none !important; }
1469
  .model-switcher, .candidate-grid, .papers-grid, .journal-grid, .parse-grid { grid-template-columns: 1fr; }
1470
  .brain-svg { height: 460px; }
1471
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1472
  """
1473
 
1474
  HEAD = """
@@ -1508,7 +2199,19 @@ with gr.Blocks(css=CSS, head=HEAD, theme=gr.themes.Base(), fill_height=True) as
1508
 
1509
  with gr.Tabs():
1510
  with gr.Tab("Discovery Engine"):
 
 
 
 
 
 
 
1511
  model_html = gr.HTML(build_models_html("DVNC Sovereign"))
 
 
 
 
 
1512
  with gr.Row():
1513
  with gr.Column(scale=2):
1514
  model = gr.Dropdown(
@@ -1525,25 +2228,70 @@ with gr.Blocks(css=CSS, head=HEAD, theme=gr.themes.Base(), fill_height=True) as
1525
  with gr.Row():
1526
  run_btn = gr.Button("Run discovery", variant="primary")
1527
  example_btn = gr.Button("Load example", variant="secondary")
 
1528
  chat = gr.HTML(
1529
  """
1530
  <div class="panel chat-panel">
1531
  <div class="chat-thread">
1532
  <div class="bubble bubble-ai">
1533
  <span class="role">DVNC</span>
1534
- <p>Enter a query to activate the 7-agent discovery stack and illuminate the chosen path through the 3D connectome.</p>
1535
  </div>
1536
  </div>
1537
  </div>
1538
  """
1539
  )
1540
- timeline = gr.HTML('<div class="panel" style="padding:18px"><div class="timeline"></div></div>')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1541
 
1542
  with gr.Column(scale=3):
1543
  connectome = gr.HTML(build_connectome_html(DEFAULT_PATH))
1544
- cards = gr.HTML('<div class="panel" style="padding:20px"><div class="candidate-grid"></div></div>')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1545
 
1546
- output = gr.Markdown("# Discovery Output\n\nAwaiting query.")
 
 
 
 
 
1547
 
1548
  with gr.Tab("Self-Learning Graph"):
1549
  with gr.Row():
 
1276
  def load_paper_topic():
1277
  return "self-assembling conductive biomaterials for cardiac repair"
1278
 
1279
+ # =========================
1280
+ # Discovery Engine v2
1281
+ # =========================
1282
+
1283
+ AGENT_TAGS = ["input", "graph", "evidence", "analogy", "compose", "critique", "experiment"]
1284
+ DEFAULT_STAGE_SELECTIONS = [0, 1, 1, 0, 0, 0, 1]
1285
+
1286
+ STOPWORDS = {
1287
+ "the", "and", "for", "with", "that", "this", "into", "from", "about", "could",
1288
+ "would", "should", "using", "use", "how", "what", "why", "when", "where",
1289
+ "can", "may", "might", "through", "across", "under", "between", "within",
1290
+ "improve", "enhance", "study", "system", "effect", "effects"
1291
+ }
1292
+
1293
+ def query_terms(query: str, limit: int = 6) -> List[str]:
1294
+ tokens = re.findall(r"[A-Za-z][A-Za-z\-]{2,}", (query or "").lower())
1295
+ keep = []
1296
+ for t in tokens:
1297
+ if t not in STOPWORDS and t not in keep:
1298
+ keep.append(t)
1299
+ return keep[:limit] or ["target process"]
1300
+
1301
+ def infer_domain(query: str) -> str:
1302
+ q = (query or "").lower()
1303
+ if any(k in q for k in ["synapse", "synaptic", "neuron", "neuronal", "axon", "dendrite", "glia", "brain", "circuit", "hippocamp", "cortex"]):
1304
+ return "neuroscience"
1305
+ if any(k in q for k in ["biomaterial", "hydrogel", "scaffold", "regeneration", "cardiac", "myocard", "tissue", "conductive"]):
1306
+ return "biomaterials"
1307
+ if any(k in q for k in ["protein", "receptor", "enzyme", "ligand", "pathway", "transcript", "epigen"]):
1308
+ return "molecular biology"
1309
+ return "general bioscience"
1310
+
1311
+ def route_option(key, title, summary, mechanism, evidence, falsifier, downstream):
1312
+ return {
1313
+ "key": key,
1314
+ "title": title,
1315
+ "summary": summary,
1316
+ "mechanism": mechanism,
1317
+ "evidence": evidence,
1318
+ "falsifier": falsifier,
1319
+ "downstream": downstream,
1320
+ }
1321
+
1322
+ def default_stage_choice(stage_index: int, query: str, model_name: str, context: Dict) -> int:
1323
+ domain = context["domain"]
1324
+ model_l = (model_name or "").lower()
1325
+ if stage_index == 0:
1326
+ return 0 if domain in ("neuroscience", "molecular biology") else 2
1327
+ if stage_index == 1:
1328
+ return 1 if "atlas" in model_l or domain == "neuroscience" else 0
1329
+ if stage_index == 2:
1330
+ return 1
1331
+ if stage_index == 3:
1332
+ return 1 if "curie" in model_l else 0
1333
+ if stage_index == 4:
1334
+ return 2 if "vs" in (query or "").lower() or "compare" in (query or "").lower() else 0
1335
+ if stage_index == 5:
1336
+ return 0
1337
+ if stage_index == 6:
1338
+ return 1 if domain in ("neuroscience", "biomaterials") else 0
1339
+ return DEFAULT_STAGE_SELECTIONS[stage_index]
1340
+
1341
+ def make_stage_options(stage_index: int, query: str, model_name: str, context: Dict) -> List[Dict]:
1342
+ focus = ", ".join(context["terms"][:4])
1343
+ domain = context["domain"]
1344
+ upstream = " -> ".join(context["selected_titles"][-2:]) if context["selected_titles"] else "seed framing"
1345
+
1346
+ if stage_index == 0:
1347
+ return [
1348
+ route_option(
1349
+ "mechanistic",
1350
+ "Mechanistic decomposition",
1351
+ f"Resolve the question into substrate, perturbation, state variable, observable, and timescale for {focus}.",
1352
+ f"Treat '{query}' as a causal system. Force explicit definition of what is manipulated, what changes internally, and what is actually measured.",
1353
+ "Perturbation-response studies with temporal resolution, direct intermediate measurements, and intervention-linked readouts.",
1354
+ "If no stable intermediate variable links manipulation to the final phenotype, this framing is too strong.",
1355
+ "Biases the next agent toward causal neighborhoods rather than semantic similarity."
1356
+ ),
1357
+ route_option(
1358
+ "multiscale",
1359
+ "Multi-scale decomposition",
1360
+ f"Split the problem across molecular, cellular, circuit/tissue, and system levels for {focus}.",
1361
+ "Assume the phenomenon may only make sense when bridge variables are tracked across scales rather than at one level alone.",
1362
+ "Studies that align micro-scale state changes with meso-scale structure and macro-scale function.",
1363
+ "If cross-scale alignment disappears once measurement artifacts are removed, the bridge is likely spurious.",
1364
+ "Pushes the graph mapper toward scale-bridging routes and hierarchical evidence."
1365
+ ),
1366
+ route_option(
1367
+ "translational",
1368
+ "Constraint-led framing",
1369
+ f"Frame the problem around assay design, delivery constraints, model system choice, and endpoint validity for {focus}.",
1370
+ "Treat the bottleneck as experimental tractability: what could be built, delivered, perturbed, and measured credibly in a lab workflow.",
1371
+ "Comparable assays, realistic model systems, dosing or exposure constraints, and endpoint reproducibility.",
1372
+ "If the hypothesis only survives in unrealistic systems or with non-transferable protocols, it fails translationally.",
1373
+ "Steers later agents toward implementable rather than merely elegant hypotheses."
1374
+ ),
1375
+ ]
1376
+
1377
+ if stage_index == 1:
1378
+ return [
1379
+ route_option(
1380
+ "local_causal",
1381
+ "Local causal neighbourhood",
1382
+ f"Expand first into the nearest mechanistic neighborhood implied by {upstream}.",
1383
+ "Traverse directly adjacent concepts, pathways, materials, or circuit motifs before jumping domains.",
1384
+ "Primary literature with direct manipulations and nearest-neighbour mechanism comparisons.",
1385
+ "If nearby literature is internally inconsistent or purely correlative, local expansion is insufficient.",
1386
+ "Produces a conservative route with stronger interpretability."
1387
+ ),
1388
+ route_option(
1389
+ "cross_scale",
1390
+ "Cross-scale bridge mapping",
1391
+ f"Search for bridge variables linking one scale of {focus} to another.",
1392
+ "Map hidden intermediates that convert local events into tissue-, network-, or phenotype-level consequences.",
1393
+ "Studies that measure both local drivers and distal consequences in the same design.",
1394
+ "If distal outcomes can be explained without the proposed bridge variable, the route collapses.",
1395
+ "Creates more ambitious but scientifically legible divergence routes."
1396
+ ),
1397
+ route_option(
1398
+ "counterfactual",
1399
+ "Counterfactual branch generation",
1400
+ f"Create explicit rival routes that could explain the same observed effect in {focus}.",
1401
+ "Treat alternative mechanisms as first-class graph branches instead of afterthoughts.",
1402
+ "Negative controls, pathway-blocking experiments, and papers that report null or opposing effects.",
1403
+ "If the same phenotype survives orthogonal pathway blockade, the favored mechanism is underdetermined.",
1404
+ "Improves later critique quality and reduces one-path tunnel vision."
1405
+ ),
1406
+ ]
1407
+
1408
+ if stage_index == 2:
1409
+ return [
1410
+ route_option(
1411
+ "supportive",
1412
+ "Supportive evidence packet",
1413
+ f"Collect papers that directly support the active route emerging from {upstream}.",
1414
+ "Build the strongest mechanistic case first so the later critic attacks a real argument.",
1415
+ "Direct intervention papers, convergence across assays, and repeatable effect directions.",
1416
+ "If support depends mostly on proxy endpoints or one assay family, confidence is overstated.",
1417
+ "Feeds the hypothesis composer a cleaner positive evidence base."
1418
+ ),
1419
+ route_option(
1420
+ "contradiction",
1421
+ "Contradiction and boundary scan",
1422
+ f"Prioritise papers that limit, weaken, or reverse the active route for {focus}.",
1423
+ "Interrogate context dependence: cell type, preparation, species, timescale, and dose can invert conclusions.",
1424
+ "Conflicting papers, boundary-condition studies, and partial replication failures.",
1425
+ "If contradictions cluster around a coherent condition, the route must be narrowed rather than discarded wholesale.",
1426
+ "Produces scientist-grade nuance instead of marketing-grade certainty."
1427
+ ),
1428
+ route_option(
1429
+ "assay_gap",
1430
+ "Assay bias scan",
1431
+ f"Look for what is systematically missing from the measurement stack for {focus}.",
1432
+ "Assume the literature may be overconfident because the wrong readout is standing in for the real variable.",
1433
+ "Methods papers, assay comparison studies, and reviews on measurement blind spots.",
1434
+ "If the key claim depends on a weak proxy, downstream composition must be rewritten.",
1435
+ "Forces the experimental program to preserve stronger readouts."
1436
+ ),
1437
+ ]
1438
+
1439
+ if stage_index == 3:
1440
+ return [
1441
+ route_option(
1442
+ "near_analogy",
1443
+ "Near-domain transfer",
1444
+ f"Generate analogies from adjacent domains where mechanism transfer into {focus} is plausible.",
1445
+ "Use analogies only when the conserved variable is explicit: channel behavior, matrix mechanics, cell-state switching, or feedback topology.",
1446
+ "Cross-domain studies with shared physical or biological constraints.",
1447
+ "If the transfer is only verbal similarity with no conserved mechanism, reject it.",
1448
+ "Keeps novelty high without drifting into decorative analogy."
1449
+ ),
1450
+ route_option(
1451
+ "distant_analogy",
1452
+ "Distant mechanism transfer",
1453
+ f"Search for remote but defensible analogies that recast {focus} using a different scientific frame.",
1454
+ "This is the high-novelty branch: borrow control logic from a remote field only if its governing dynamics can be translated.",
1455
+ "Papers showing transferable control motifs, threshold effects, self-assembly, coupling, or synchronization.",
1456
+ "If translation requires too many hidden assumptions, novelty is not worth the loss of clarity.",
1457
+ "Can open frontier hypotheses, but only if later critics are harsh."
1458
+ ),
1459
+ route_option(
1460
+ "null_analogy",
1461
+ "Null analogy control",
1462
+ f"Actively test whether analogy adds anything beyond the evidence already assembled for {focus}.",
1463
+ "Assume the best move may be not to analogise at all if the local mechanism is already sufficient.",
1464
+ "Evidence showing that local route completeness beats imported conceptual structure.",
1465
+ "If analogy does not improve prediction, discrimination, or experimental design, remove it.",
1466
+ "Prevents the engine from performing novelty theatre."
1467
+ ),
1468
+ ]
1469
+
1470
+ if stage_index == 4:
1471
+ return [
1472
+ route_option(
1473
+ "focused_hypothesis",
1474
+ "Focused mechanistic hypothesis",
1475
+ f"Compose one tight causal hypothesis around the strongest route selected for {focus}.",
1476
+ "Prefer one dominant mechanism with explicit intermediate variables and one main prediction.",
1477
+ "A coherent chain from intervention to intermediate state to observable phenotype.",
1478
+ "Fails if the proposed intermediate cannot be isolated experimentally.",
1479
+ "Supports a crisp validation ladder and cleaner falsification."
1480
+ ),
1481
+ route_option(
1482
+ "hybrid_hypothesis",
1483
+ "Hybrid dual-mechanism hypothesis",
1484
+ f"Compose a two-path hypothesis in which parallel mechanisms jointly explain {focus}.",
1485
+ "Use this only when single-route explanations cannot account for the evidence landscape.",
1486
+ "Evidence for interacting mechanisms, sequential stages, or coupled state changes.",
1487
+ "Fails if one arm becomes redundant when the other is controlled.",
1488
+ "Improves realism but usually lowers tractability."
1489
+ ),
1490
+ route_option(
1491
+ "discriminative_hypothesis",
1492
+ "Competing hypothesis pair",
1493
+ f"Write two rival causal accounts for {focus} and define the experiment that separates them.",
1494
+ "Treat discovery as discrimination, not only generation.",
1495
+ "Evidence sufficient to state what each hypothesis predicts differently under the same perturbation.",
1496
+ "Fails if both hypotheses can fit every outcome post hoc.",
1497
+ "Ideal for a serious scientific audience because it exposes decision points."
1498
+ ),
1499
+ ]
1500
+
1501
+ if stage_index == 5:
1502
+ return [
1503
+ route_option(
1504
+ "confound_attack",
1505
+ "Confound attack",
1506
+ f"Stress-test the active hypothesis for hidden variables affecting {focus}.",
1507
+ "Interrogate preparation quality, baseline state, batch effects, adaptive responses, and off-target pathways.",
1508
+ "Controls that remove nuisance variables without erasing the signal of interest.",
1509
+ "If the result disappears under proper control structure, the route is not discovery-ready.",
1510
+ "Hardens the final program against obvious reviewer criticism."
1511
+ ),
1512
+ route_option(
1513
+ "measurement_attack",
1514
+ "Measurement attack",
1515
+ f"Attack whether the chosen readout is actually measuring the mechanism claimed for {focus}.",
1516
+ "Separate endpoint validity from convenience: many papers measure what is easy rather than what matters.",
1517
+ "Orthogonal assays, calibration studies, and causal versus proxy readout comparisons.",
1518
+ "If the signature does not survive a stronger measurement stack, the hypothesis needs rewriting.",
1519
+ "Improves scientific credibility for technically demanding readers."
1520
+ ),
1521
+ route_option(
1522
+ "boundary_attack",
1523
+ "Biological boundary attack",
1524
+ f"Test where the route breaks across species, preparations, states, and timescales in {focus}.",
1525
+ "Assume many attractive mechanisms are only locally true.",
1526
+ "Comparative experiments and context-stratified evidence.",
1527
+ "If the effect only exists in one narrow preparation, claims must be narrowed accordingly.",
1528
+ "Protects the program from overgeneralization."
1529
+ ),
1530
+ ]
1531
+
1532
+ if stage_index == 6:
1533
+ return [
1534
+ route_option(
1535
+ "assay_ladder",
1536
+ "In vitro assay ladder",
1537
+ f"Start with a staged assay sequence that resolves mechanism before scale for {focus}.",
1538
+ "Use tightly controlled perturbation-response experiments to confirm intermediate variables first.",
1539
+ "High-resolution assays, direct manipulation, matched controls, and replicated signal quantification.",
1540
+ "If the mechanism cannot be detected under controlled conditions, do not scale prematurely.",
1541
+ "Best when the scientific risk is mechanistic ambiguity."
1542
+ ),
1543
+ route_option(
1544
+ "tissue_program",
1545
+ "Tissue / ex vivo bridge",
1546
+ f"Bridge from mechanism into architecture-preserving systems before committing to full in vivo work for {focus}.",
1547
+ "Use preparations that preserve structure, coupling, and mesoscale organization while remaining experimentally tractable.",
1548
+ "Readouts that align cellular mechanism with tissue-level function.",
1549
+ "If the effect disappears once architecture is preserved, the earlier route was too reductionist.",
1550
+ "A strong middle ground for serious biology and neuroscience work."
1551
+ ),
1552
+ route_option(
1553
+ "in_vivo_program",
1554
+ "In vivo discriminative program",
1555
+ f"Design a decisive in vivo study that separates the competing causal accounts for {focus}.",
1556
+ "Only use this when the prior stages have already narrowed the uncertainty and defined discriminative endpoints.",
1557
+ "Pre-registered endpoints, direct perturbation arms, and a stopping rule tied to rival predictions.",
1558
+ "If the readouts cannot distinguish the alternatives, the study is expensive but non-informative.",
1559
+ "Highest translational relevance, highest execution burden."
1560
+ ),
1561
+ ]
1562
+
1563
+ return []
1564
+
1565
+ def build_stage_cards_html(stage: Dict) -> str:
1566
+ cards = []
1567
+ for idx, opt in enumerate(stage["options"]):
1568
+ selected = "selected" if idx == stage["selected"] else ""
1569
+ cards.append(
1570
+ f"""
1571
+ <article class="route-card {selected}">
1572
+ <div class="route-card-top">
1573
+ <span class="route-chip">Route {idx + 1}</span>
1574
+ <span class="route-state">{'Active' if idx == stage['selected'] else 'Available'}</span>
1575
+ </div>
1576
+ <h5>{safe_text(opt['title'])}</h5>
1577
+ <p>{safe_text(opt['summary'])}</p>
1578
+ <ul class="route-points">
1579
+ <li><strong>Mechanism:</strong> {safe_text(opt['mechanism'])}</li>
1580
+ <li><strong>Evidence:</strong> {safe_text(opt['evidence'])}</li>
1581
+ <li><strong>Falsifier:</strong> {safe_text(opt['falsifier'])}</li>
1582
+ <li><strong>Downstream:</strong> {safe_text(opt['downstream'])}</li>
1583
+ </ul>
1584
+ </article>
1585
+ """
1586
+ )
1587
+ return f'<div class="route-grid">{"".join(cards)}</div>'
1588
+
1589
+ def build_stage_detail_markdown(stage: Dict) -> str:
1590
+ opt = stage["options"][stage["selected"]]
1591
+ return (
1592
+ f"### Active route: {opt['title']}\n\n"
1593
+ f"- **Scientific line:** {opt['summary']}\n"
1594
+ f"- **Mechanistic interpretation:** {opt['mechanism']}\n"
1595
+ f"- **Evidence pressure:** {opt['evidence']}\n"
1596
+ f"- **Primary falsifier:** {opt['falsifier']}\n"
1597
+ f"- **Downstream routing effect:** {opt['downstream']}\n"
1598
+ )
1599
+
1600
+ def connectome_path_from_state(state: Dict) -> List[str]:
1601
+ s3 = state["stages"][3]["options"][state["stages"][3]["selected"]]["key"]
1602
+ s4 = state["stages"][4]["options"][state["stages"][4]["selected"]]["key"]
1603
+ s6 = state["stages"][6]["options"][state["stages"][6]["selected"]]["key"]
1604
+
1605
+ if s4 == "focused_hypothesis" and s3 == "near_analogy":
1606
+ return ["seed", "bio", "card", "alt1", "trial"]
1607
+ if s4 == "hybrid_hypothesis" or s3 == "distant_analogy":
1608
+ return ["seed", "nano", "selfasm", "alt2", "trial"]
1609
+ if s6 in ("tissue_program", "in_vivo_program"):
1610
+ return ["seed", "bio", "card", "immune", "trial"]
1611
+ return ["seed", "nano", "selfasm", "electro", "trial"]
1612
+
1613
+ def compose_primary_hypothesis(state: Dict) -> str:
1614
+ q = state["query"]
1615
+ a0 = state["stages"][0]["options"][state["stages"][0]["selected"]]["title"]
1616
+ a2 = state["stages"][2]["options"][state["stages"][2]["selected"]]["title"]
1617
+ a4 = state["stages"][4]["options"][state["stages"][4]["selected"]]["title"]
1618
+ a6 = state["stages"][6]["options"][state["stages"][6]["selected"]]["title"]
1619
+ return (
1620
+ f"Treat '{q}' through {a0.lower()}, prioritise the evidence posture defined by "
1621
+ f"{a2.lower()}, then test a {a4.lower()} using a {a6.lower()}."
1622
+ )
1623
+
1624
+ def compute_metrics(state: Dict) -> Dict[str, int]:
1625
+ novelty = 84
1626
+ clarity = 88
1627
+ tractability = 84
1628
+ cross_domain = 80
1629
+
1630
+ s1 = state["stages"][1]["options"][state["stages"][1]["selected"]]["key"]
1631
+ s3 = state["stages"][3]["options"][state["stages"][3]["selected"]]["key"]
1632
+ s4 = state["stages"][4]["options"][state["stages"][4]["selected"]]["key"]
1633
+ s6 = state["stages"][6]["options"][state["stages"][6]["selected"]]["key"]
1634
+
1635
+ if s1 == "cross_scale":
1636
+ cross_domain += 7
1637
+ novelty += 3
1638
+ if s3 == "distant_analogy":
1639
+ novelty += 6
1640
+ clarity -= 4
1641
+ tractability -= 3
1642
+ cross_domain += 8
1643
+ if s4 == "hybrid_hypothesis":
1644
+ novelty += 2
1645
+ clarity -= 5
1646
+ tractability -= 4
1647
+ if s4 == "discriminative_hypothesis":
1648
+ clarity += 3
1649
+ tractability -= 1
1650
+ if s6 == "in_vivo_program":
1651
+ tractability -= 6
1652
+ if s6 == "tissue_program":
1653
+ clarity += 2
1654
+
1655
+ return {
1656
+ "Novelty": max(60, min(99, novelty)),
1657
+ "Mechanistic clarity": max(60, min(99, clarity)),
1658
+ "Experimental tractability": max(55, min(99, tractability)),
1659
+ "Cross-domain distance": max(55, min(99, cross_domain)),
1660
+ }
1661
+
1662
+ def build_reasoning_state(query: str, model_name: str, selected: Optional[List[Optional[int]]] = None) -> Dict:
1663
+ query = (query or "").strip()
1664
+ if not query:
1665
+ return {
1666
+ "query": "",
1667
+ "model_name": model_name,
1668
+ "domain": "general bioscience",
1669
+ "terms": [],
1670
+ "stages": [],
1671
+ "summary": "Awaiting query.",
1672
+ "primary_hypothesis": "",
1673
+ "metrics": {},
1674
+ }
1675
+
1676
+ selected = selected or [None] * 7
1677
+ context = {
1678
+ "domain": infer_domain(query),
1679
+ "terms": query_terms(query),
1680
+ "selected_titles": [],
1681
+ "selected_keys": [],
1682
+ }
1683
+
1684
+ stages = []
1685
+ chosen = []
1686
+
1687
+ for idx, agent in enumerate(AGENTS):
1688
+ options = make_stage_options(idx, query, model_name, context)
1689
+ preferred = default_stage_choice(idx, query, model_name, context)
1690
+ sel = preferred if selected[idx] is None else max(0, min(2, int(selected[idx])))
1691
+ stage = {
1692
+ "step": idx + 1,
1693
+ "agent": agent,
1694
+ "tag": AGENT_TAGS[idx],
1695
+ "selected": sel,
1696
+ "options": options,
1697
+ }
1698
+ stages.append(stage)
1699
+
1700
+ picked = options[sel]
1701
+ context["selected_titles"].append(picked["title"])
1702
+ context["selected_keys"].append(picked["key"])
1703
+ chosen.append(sel)
1704
+
1705
+ state = {
1706
+ "query": query,
1707
+ "model_name": model_name,
1708
+ "domain": context["domain"],
1709
+ "terms": context["terms"],
1710
+ "selected": chosen,
1711
+ "stages": stages,
1712
+ }
1713
+ state["primary_hypothesis"] = compose_primary_hypothesis(state)
1714
+ state["metrics"] = compute_metrics(state)
1715
+ state["summary"] = (
1716
+ f"The 7-agent stack has routed '{query}' through a {state['domain']} reasoning program with "
1717
+ f"three explicit branches at every stage. Swapping any stage now invalidates downstream assumptions "
1718
+ f"and recomputes the remaining route."
1719
+ )
1720
+ return state
1721
+
1722
+ def build_route_synopsis_html(state: Dict) -> str:
1723
+ if not state.get("stages"):
1724
+ return '<div class="panel" style="padding:18px"><p>Run discovery to generate a routed 7-agent programme.</p></div>'
1725
+
1726
+ rows = []
1727
+ for stage in state["stages"]:
1728
+ opt = stage["options"][stage["selected"]]
1729
+ rows.append(
1730
+ f"""
1731
+ <div class="route-row">
1732
+ <div class="route-row-step">{stage['step']}</div>
1733
+ <div class="route-row-copy">
1734
+ <h4>{safe_text(stage['agent'])}</h4>
1735
+ <p>{safe_text(opt['title'])}</p>
1736
+ </div>
1737
+ </div>
1738
+ """
1739
+ )
1740
+
1741
+ return (
1742
+ f"""
1743
+ <div class="panel route-synopsis">
1744
+ <div class="brain-header">
1745
+ <div>
1746
+ <p class="eyebrow">Active Route</p>
1747
+ <h3>Selected scientific program</h3>
1748
+ </div>
1749
+ </div>
1750
+ <div class="route-rows">
1751
+ {''.join(rows)}
1752
+ </div>
1753
+ </div>
1754
+ """
1755
+ )
1756
+
1757
+ def build_discovery_markdown(state: Dict) -> str:
1758
+ if not state.get("stages"):
1759
+ return "# Discovery Output\n\nAwaiting query."
1760
+
1761
+ metrics = "\n".join([f"- {k}: {v}/100" for k, v in state["metrics"].items()])
1762
+ selected_titles = "\n".join(
1763
+ [f"{stage['step']}. {stage['agent']} -> {stage['options'][stage['selected']]['title']}" for stage in state["stages"]]
1764
+ )
1765
+
1766
+ return (
1767
+ "# Discovery Output\n\n"
1768
+ f"**Model:** {state['model_name']}\n\n"
1769
+ f"**Domain framing:** {state['domain']}\n\n"
1770
+ f"**Primary hypothesis:** {state['primary_hypothesis']}\n\n"
1771
+ "## Active route\n"
1772
+ f"{selected_titles}\n\n"
1773
+ "## Scoring\n"
1774
+ f"{metrics}\n\n"
1775
+ "## Experimental outline\n"
1776
+ "1. Confirm the active mechanistic framing with the strongest direct readout.\n"
1777
+ "2. Use the evidence posture selected by Agent 3 to define inclusion and exclusion criteria.\n"
1778
+ "3. Design one discriminative experiment that would separate the lead route from its nearest rival.\n"
1779
+ "4. Carry forward the critic-stage falsifier as a hard stopping condition.\n"
1780
+ )
1781
+
1782
+ def discovery_state_to_outputs(state: Dict):
1783
+ if not state.get("stages"):
1784
+ empty_cards = ['<div class="panel" style="padding:18px"><p>Awaiting route options.</p></div>'] * 7
1785
+ empty_choices = [gr.update(choices=[], value=None)] * 7
1786
+ empty_details = ["Awaiting route generation."] * 7
1787
+ return [
1788
+ build_chat_html("", {"summary": "Enter a query to activate the routed 7-agent stack.", "primary_hypothesis": "No active hypothesis."}),
1789
+ build_connectome_html(DEFAULT_PATH),
1790
+ build_route_synopsis_html(state),
1791
+ build_discovery_markdown(state),
1792
+ build_models_html(state.get("model_name", "DVNC Sovereign")),
1793
+ state,
1794
+ *empty_cards,
1795
+ *empty_choices,
1796
+ *empty_details,
1797
+ ]
1798
+
1799
+ card_html = [build_stage_cards_html(stage) for stage in state["stages"]]
1800
+ choice_updates = [
1801
+ gr.update(
1802
+ choices=[(f"Route {i + 1} · {opt['title']}", str(i)) for i, opt in enumerate(stage["options"])],
1803
+ value=str(stage["selected"])
1804
+ )
1805
+ for stage in state["stages"]
1806
+ ]
1807
+ details_md = [build_stage_detail_markdown(stage) for stage in state["stages"]]
1808
+
1809
+ return [
1810
+ build_chat_html(
1811
+ state["query"],
1812
+ {"summary": state["summary"], "primary_hypothesis": state["primary_hypothesis"]}
1813
+ ),
1814
+ build_connectome_html(connectome_path_from_state(state)),
1815
+ build_route_synopsis_html(state),
1816
+ build_discovery_markdown(state),
1817
+ build_models_html(state["model_name"]),
1818
+ state,
1819
+ *card_html,
1820
+ *choice_updates,
1821
+ *details_md,
1822
+ ]
1823
+
1824
+ def initialise_discovery(query: str, model_name: str):
1825
+ state = build_reasoning_state(query, model_name)
1826
+ return discovery_state_to_outputs(state)
1827
+
1828
+ def swap_stage_route(query: str, model_name: str, state: Dict, stage_index: int, selected_value: str):
1829
+ if not (query or "").strip():
1830
+ empty = build_reasoning_state("", model_name)
1831
+ return discovery_state_to_outputs(empty)
1832
+
1833
+ prior = list((state or {}).get("selected", [None] * 7))
1834
+ if len(prior) < 7:
1835
+ prior = [None] * 7
1836
+
1837
+ prior[stage_index] = int(selected_value) if selected_value is not None else 0
1838
+ for j in range(stage_index + 1, 7):
1839
+ prior[j] = None
1840
+
1841
+ new_state = build_reasoning_state(query, model_name, prior)
1842
+ return discovery_state_to_outputs(new_state)
1843
+
1844
+
1845
 
1846
  CSS = r"""
1847
  :root {
 
2035
  .model-switcher, .candidate-grid, .papers-grid, .journal-grid, .parse-grid { grid-template-columns: 1fr; }
2036
  .brain-svg { height: 460px; }
2037
  }
2038
+
2039
+ .route-grid {
2040
+ display: grid;
2041
+ grid-template-columns: repeat(3, minmax(0, 1fr));
2042
+ gap: 12px;
2043
+ margin-bottom: 12px;
2044
+ }
2045
+
2046
+ .route-card {
2047
+ border: 1px solid var(--line);
2048
+ border-radius: 18px;
2049
+ padding: 16px;
2050
+ background: #ffffff;
2051
+ min-height: 260px;
2052
+ display: flex;
2053
+ flex-direction: column;
2054
+ gap: 10px;
2055
+ box-shadow: 0 10px 20px rgba(0,0,0,0.04);
2056
+ }
2057
+
2058
+ .route-card.selected {
2059
+ border-color: rgba(255, 122, 26, 0.38);
2060
+ background: linear-gradient(135deg, rgba(255, 122, 26, 0.08), rgba(255,255,255,0.98));
2061
+ box-shadow: 0 14px 30px rgba(255, 122, 26, 0.10);
2062
+ }
2063
+
2064
+ .route-card-top {
2065
+ display: flex;
2066
+ justify-content: space-between;
2067
+ align-items: center;
2068
+ gap: 8px;
2069
+ }
2070
+
2071
+ .route-chip {
2072
+ font-size: .72rem;
2073
+ text-transform: uppercase;
2074
+ letter-spacing: .12em;
2075
+ color: #0b6f66;
2076
+ padding: 6px 10px;
2077
+ border-radius: 999px;
2078
+ background: rgba(23, 184, 166, 0.08);
2079
+ border: 1px solid rgba(23, 184, 166, 0.18);
2080
+ }
2081
+
2082
+ .route-state {
2083
+ font-size: .76rem;
2084
+ color: var(--gold);
2085
+ font-weight: 700;
2086
+ }
2087
+
2088
+ .route-card h5 {
2089
+ margin: 0;
2090
+ font-size: 1rem;
2091
+ line-height: 1.35;
2092
+ color: var(--text);
2093
+ }
2094
+
2095
+ .route-card p {
2096
+ margin: 0;
2097
+ color: #1e1e1e;
2098
+ line-height: 1.6;
2099
+ font-size: .93rem;
2100
+ }
2101
+
2102
+ .route-points {
2103
+ margin: 0;
2104
+ padding-left: 18px;
2105
+ display: flex;
2106
+ flex-direction: column;
2107
+ gap: 8px;
2108
+ color: #2a2a2a;
2109
+ line-height: 1.5;
2110
+ font-size: .9rem;
2111
+ }
2112
+
2113
+ .route-synopsis {
2114
+ padding: 18px;
2115
+ }
2116
+
2117
+ .route-rows {
2118
+ display: flex;
2119
+ flex-direction: column;
2120
+ gap: 10px;
2121
+ }
2122
+
2123
+ .route-row {
2124
+ display: grid;
2125
+ grid-template-columns: 42px 1fr;
2126
+ gap: 12px;
2127
+ align-items: center;
2128
+ padding: 12px;
2129
+ border: 1px solid var(--line);
2130
+ border-radius: 16px;
2131
+ background: #ffffff;
2132
+ }
2133
+
2134
+ .route-row-step {
2135
+ width: 42px;
2136
+ height: 42px;
2137
+ border-radius: 14px;
2138
+ display: grid;
2139
+ place-items: center;
2140
+ font-weight: 700;
2141
+ color: var(--gold);
2142
+ background: rgba(255, 122, 26, 0.08);
2143
+ border: 1px solid rgba(255, 122, 26, 0.18);
2144
+ }
2145
+
2146
+ .route-row-copy h4 {
2147
+ margin: 0 0 4px;
2148
+ font-size: .95rem;
2149
+ color: var(--text);
2150
+ }
2151
+
2152
+ .route-row-copy p {
2153
+ margin: 0;
2154
+ color: var(--muted);
2155
+ line-height: 1.45;
2156
+ }
2157
+
2158
+ @media (max-width: 1180px) {
2159
+ .route-grid {
2160
+ grid-template-columns: 1fr;
2161
+ }
2162
+ }
2163
  """
2164
 
2165
  HEAD = """
 
2199
 
2200
  with gr.Tabs():
2201
  with gr.Tab("Discovery Engine"):
2202
+ discovery_state = gr.State({
2203
+ "query": "",
2204
+ "model_name": "DVNC Sovereign",
2205
+ "stages": [],
2206
+ "selected": [None] * 7,
2207
+ })
2208
+
2209
  model_html = gr.HTML(build_models_html("DVNC Sovereign"))
2210
+
2211
+ stage_cards = []
2212
+ stage_choices = []
2213
+ stage_details = []
2214
+
2215
  with gr.Row():
2216
  with gr.Column(scale=2):
2217
  model = gr.Dropdown(
 
2228
  with gr.Row():
2229
  run_btn = gr.Button("Run discovery", variant="primary")
2230
  example_btn = gr.Button("Load example", variant="secondary")
2231
+
2232
  chat = gr.HTML(
2233
  """
2234
  <div class="panel chat-panel">
2235
  <div class="chat-thread">
2236
  <div class="bubble bubble-ai">
2237
  <span class="role">DVNC</span>
2238
+ <p>Enter a query to activate the routed 7-agent discovery stack. Each agent will expose three branchable routes, and changing one route will recompute everything downstream.</p>
2239
  </div>
2240
  </div>
2241
  </div>
2242
  """
2243
  )
2244
+
2245
+ for i, agent in enumerate(AGENTS):
2246
+ with gr.Accordion(f"{i+1}. {agent}", open=(i == 0)):
2247
+ stage_cards.append(
2248
+ gr.HTML('<div class="panel" style="padding:18px"><p>Awaiting route options.</p></div>')
2249
+ )
2250
+ stage_choices.append(
2251
+ gr.Radio(
2252
+ choices=[],
2253
+ value=None,
2254
+ label="Active route",
2255
+ interactive=True,
2256
+ )
2257
+ )
2258
+ stage_details.append(
2259
+ gr.Markdown("Awaiting route generation.")
2260
+ )
2261
 
2262
  with gr.Column(scale=3):
2263
  connectome = gr.HTML(build_connectome_html(DEFAULT_PATH))
2264
+ route_synopsis = gr.HTML(
2265
+ '<div class="panel" style="padding:18px"><p>Run discovery to generate the active scientific route.</p></div>'
2266
+ )
2267
+ output = gr.Markdown("# Discovery Output\n\nAwaiting query.")
2268
+
2269
+ example_btn.click(fn=load_example, outputs=query)
2270
+
2271
+ discovery_outputs = [
2272
+ chat,
2273
+ connectome,
2274
+ route_synopsis,
2275
+ output,
2276
+ model_html,
2277
+ discovery_state,
2278
+ *stage_cards,
2279
+ *stage_choices,
2280
+ *stage_details,
2281
+ ]
2282
+
2283
+ run_btn.click(
2284
+ fn=initialise_discovery,
2285
+ inputs=[query, model],
2286
+ outputs=discovery_outputs,
2287
+ )
2288
 
2289
+ for idx, choice in enumerate(stage_choices):
2290
+ choice.change(
2291
+ fn=lambda q, m, s, c, i=idx: swap_stage_route(q, m, s, i, c),
2292
+ inputs=[query, model, discovery_state, choice],
2293
+ outputs=discovery_outputs,
2294
+ )
2295
 
2296
  with gr.Tab("Self-Learning Graph"):
2297
  with gr.Row():