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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0f7a6a
 
 
 
 
 
2666fa8
e0f7a6a
 
2666fa8
 
 
 
 
e0f7a6a
 
2666fa8
e0f7a6a
2666fa8
 
 
 
 
 
 
e0f7a6a
2666fa8
 
 
 
 
 
 
e0f7a6a
2666fa8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0f7a6a
2666fa8
 
 
 
 
 
 
e0f7a6a
2666fa8
 
 
 
e0f7a6a
 
2666fa8
 
 
 
e0f7a6a
 
 
2666fa8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0f7a6a
2666fa8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0f7a6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2666fa8
 
 
 
 
 
 
 
 
 
 
 
 
e0f7a6a
 
 
2666fa8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0f7a6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2666fa8
 
 
 
 
 
 
e0f7a6a
2666fa8
e0f7a6a
2666fa8
 
 
 
 
 
 
 
 
 
 
e0f7a6a
 
 
 
2666fa8
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
from __future__ import annotations

import os
from pathlib import Path
from typing import Any, Dict, List, Tuple

import gradio as gr

from orbit_core import (
    CLAIM_TYPES,
    DEFAULT_RELIABILITY,
    RELATIONS,
    SOURCE_TYPES,
    OrbitStore,
    decision_gate,
)

APP_DIR = Path(__file__).resolve().parent
DATA_DIR = Path(os.getenv("ORBIT_DATA_DIR", APP_DIR / "data"))
DATA_FILE = DATA_DIR / "beliefs.json"
DATA_DIR.mkdir(parents=True, exist_ok=True)

STORE = OrbitStore(DATA_FILE)
STORE.seed_if_empty()


def belief_row(belief) -> List[Any]:
    return [
        belief.id,
        belief.statement,
        belief.context,
        belief.claim_type,
        belief.status,
        round(float(belief.support_weight), 3),
        round(float(belief.contradiction_weight), 3),
        round(float(belief.confidence), 3),
        round(float(belief.pressure), 3),
        len(belief.evidence),
        round(float(getattr(belief, "source_diversity", 0.0)), 3),
        belief.updated_at,
    ]


def queue_row(belief) -> List[Any]:
    next_question = (
        belief.revision_triggers[0]
        if belief.revision_triggers
        else f"What evidence would materially change '{belief.statement}'?"
    )
    return [
        belief.id,
        belief.statement,
        belief.status,
        round(float(belief.confidence), 3),
        round(float(belief.pressure), 3),
        next_question,
    ]


def recent_row(belief) -> List[Any]:
    return [
        belief.id,
        belief.statement,
        belief.status,
        round(float(belief.confidence), 3),
        round(float(belief.pressure), 3),
        belief.updated_at,
    ]


def deck_rows(limit: int = 100) -> List[List[Any]]:
    return [belief_row(item) for item in STORE.all()[:limit]]


def queue_rows(limit: int = 50) -> List[List[Any]]:
    return [queue_row(item) for item in STORE.pressure_queue()[:limit]]


def recent_rows(limit: int = 25) -> List[List[Any]]:
    return [recent_row(item) for item in STORE.recent(limit)]


def beliefs_missing_revision(limit: int = 25) -> List[List[Any]]:
    rows = []
    for belief in STORE.all():
        if not belief.revision_triggers:
            rows.append(
                [
                    belief.id,
                    belief.statement,
                    belief.status,
                    round(float(belief.confidence), 3),
                    "No revision trigger recorded",
                ]
            )
    return rows[:limit]


def beliefs_missing_limits(limit: int = 25) -> List[List[Any]]:
    rows = []
    for belief in STORE.all():
        if not belief.instrument_limits:
            rows.append(
                [
                    belief.id,
                    belief.statement,
                    belief.status,
                    round(float(belief.confidence), 3),
                    "No instrument limit recorded",
                ]
            )
    return rows[:limit]


def low_evidence_high_confidence(limit: int = 25) -> List[List[Any]]:
    rows = []
    for belief in STORE.all():
        if len(belief.evidence) <= 1 and float(belief.confidence) >= 0.7:
            rows.append(
                [
                    belief.id,
                    belief.statement,
                    belief.status,
                    round(float(belief.confidence), 3),
                    len(belief.evidence),
                    "High confidence with sparse evidence",
                ]
            )
    return rows[:limit]


def compute_metrics() -> Dict[str, Any]:
    beliefs = STORE.all()
    total = len(beliefs)
    evidence_count = sum(len(item.evidence) for item in beliefs)

    status_counts: Dict[str, int] = {}
    for belief in beliefs:
        status_counts[belief.status] = status_counts.get(belief.status, 0) + 1

    avg_confidence = (
        sum(float(item.confidence) for item in beliefs) / total if total else 0.0
    )
    avg_pressure = (
        sum(float(item.pressure) for item in beliefs) / total if total else 0.0
    )
    avg_diversity = (
        sum(float(getattr(item, "source_diversity", 0.0)) for item in beliefs) / total
        if total
        else 0.0
    )

    high_pressure = sum(1 for item in beliefs if float(item.pressure) >= 0.6)
    missing_revision = sum(1 for item in beliefs if not item.revision_triggers)
    missing_limits = sum(1 for item in beliefs if not item.instrument_limits)

    return {
        "beliefs": total,
        "evidence": evidence_count,
        "supported": status_counts.get("supported", 0),
        "contested": status_counts.get("contested", 0),
        "provisional": status_counts.get("provisional", 0),
        "contradicted": status_counts.get("contradicted", 0),
        "avg_confidence": avg_confidence,
        "avg_pressure": avg_pressure,
        "avg_diversity": avg_diversity,
        "high_pressure": high_pressure,
        "missing_revision": missing_revision,
        "missing_limits": missing_limits,
    }


def serialize_belief(belief) -> Dict[str, Any]:
    if belief is None:
        return {"error": "belief not found"}
    return {
        "id": belief.id,
        "statement": belief.statement,
        "subject": belief.subject,
        "predicate": belief.predicate,
        "object": belief.obj,
        "context": belief.context,
        "claim_type": belief.claim_type,
        "status": belief.status,
        "support_weight": belief.support_weight,
        "contradiction_weight": belief.contradiction_weight,
        "confidence": belief.confidence,
        "pressure": belief.pressure,
        "source_diversity": getattr(belief, "source_diversity", 0.0),
        "risk_flags": getattr(belief, "risk_flags", []),
        "revision_triggers": belief.revision_triggers,
        "instrument_limits": belief.instrument_limits,
        "evidence": [
            {
                "id": item.id,
                "relation": item.relation,
                "source_type": item.source_type,
                "source_ref": item.source_ref,
                "speaker": item.speaker,
                "quote": item.quote,
                "note": item.note,
                "reliability": item.reliability,
                "observed_at": item.observed_at,
                "submitted_at": item.submitted_at,
            }
            for item in belief.evidence
        ],
        "created_at": belief.created_at,
        "updated_at": belief.updated_at,
    }


def metric_card(title: str, value: str, tone: str = "") -> str:
    return f"""
    <div class="metric-card {tone}">
        <div class="metric-title">{title}</div>
        <div class="metric-value">{value}</div>
    </div>
    """


def metrics_html() -> str:
    m = compute_metrics()
    return f"""
    <div class="metrics-grid">
        {metric_card("Beliefs", str(m["beliefs"]))}
        {metric_card("Evidence", str(m["evidence"]))}
        {metric_card("Supported", str(m["supported"]), "success")}
        {metric_card("Contested", str(m["contested"]), "warning")}
        {metric_card("Contradicted", str(m["contradicted"]), "danger")}
        {metric_card("High Pressure", str(m["high_pressure"]), "warning")}
        {metric_card("Avg Confidence", f'{m["avg_confidence"]:.2f}', "info")}
        {metric_card("Avg Pressure", f'{m["avg_pressure"]:.2f}', "info")}
        {metric_card("Avg Source Diversity", f'{m["avg_diversity"]:.2f}', "info")}
    </div>
    """


def fundamentals_html() -> str:
    return """
    <div class="fundamentals-grid">
        <div class="fundamental-card">
            <div class="fundamental-title">1. Contextual Sanity</div>
            <div class="fundamental-body">
                Keep contact with context. Ask when inquiry can change understanding.
            </div>
        </div>
        <div class="fundamental-card">
            <div class="fundamental-title">2. Provisional Judgment</div>
            <div class="fundamental-body">
                Form judgments, but bind them to conditions and keep them revisable.
            </div>
        </div>
        <div class="fundamental-card">
            <div class="fundamental-title">3. Childlike Capacity</div>
            <div class="fundamental-body">
                Preserve exploration, discovery, and play instead of collapsing too early.
            </div>
        </div>
        <div class="fundamental-card">
            <div class="fundamental-title">4. Instrument-Bounded Understanding</div>
            <div class="fundamental-body">
                Every conclusion is limited by the instruments used to produce it.
            </div>
        </div>
    </div>
    """


def health_warnings_markdown() -> str:
    m = compute_metrics()
    warnings: List[str] = []

    if m["missing_revision"] > 0:
        warnings.append(
            f"- **{m['missing_revision']} beliefs** have no revision trigger recorded."
        )
    if m["missing_limits"] > 0:
        warnings.append(
            f"- **{m['missing_limits']} beliefs** have no instrument limit recorded."
        )
    if m["high_pressure"] > 0:
        warnings.append(
            f"- **{m['high_pressure']} beliefs** are under elevated pressure."
        )

    sparse_rows = low_evidence_high_confidence()
    if sparse_rows:
        warnings.append(
            f"- **{len(sparse_rows)} beliefs** have high confidence with sparse evidence."
        )

    if not warnings:
        warnings.append("- No immediate governor warnings detected.")

    return "### Governor Health Warnings\n" + "\n".join(warnings)


def overview_markdown() -> str:
    m = compute_metrics()
    return f"""
### Orbit State

Orbit is a shared belief-revision system. It does not store final truth.  
It stores **claims**, **evidence**, **contradiction**, **pressure**, and **what would justify revision**.

**{m["beliefs"]} beliefs** · **{m["evidence"]} evidence records** ·
**{m["supported"]} supported** · **{m["contested"]} contested** ·
**{m["provisional"]} provisional** · **{m["contradicted"]} contradicted**
"""


def ask_orbit(query: str) -> Tuple[str, List[List[Any]], Dict[str, Any]]:
    query = (query or "").strip()
    if not query:
        return (
            """
### Ask Orbit

Enter a question, claim, or topic to inspect what Orbit currently believes.
""",
            [],
            {"error": "empty query"},
        )

    matches = STORE.search(query)
    if not matches:
        return (
            f"""
### No matching belief

Orbit has no stored belief for:

> {query}

That does **not** mean the claim is false.  
It means Orbit does not yet have enough structured memory around it.

You can contribute evidence below.
""",
            [],
            {"query": query, "matches": 0},
        )

    top = matches[0]
    evidence_count = len(top.evidence)
    summary = f"""
### Orbit's current lean

**{top.statement}**

- **Status:** {top.status}
- **Confidence:** {top.confidence:.3f}
- **Pressure:** {top.pressure:.3f}
- **Evidence records:** {evidence_count}
- **Source diversity:** {getattr(top, "source_diversity", 0.0):.3f}
- **Context:** {top.context or "not declared"}

**Interpretation:** Orbit is showing a bounded, revisable belief — not a declaration of final truth.
"""
    return summary, [belief_row(item) for item in matches[:20]], serialize_belief(top)


def orbit_inspect(belief_id: str) -> Dict[str, Any]:
    return serialize_belief(STORE.get((belief_id or "").strip()))


def orbit_record(
    subject: str,
    predicate: str,
    obj: str,
    context: str,
    claim_type: str,
    relation: str,
    source_type: str,
    source_ref: str,
    speaker: str,
    quote: str,
    reliability: float,
    note: str,
    observed_at: str,
    revision_trigger: str,
    instrument_limit: str,
) -> Tuple[str, str, str, str, List[List[Any]], List[List[Any]], List[List[Any]], List[List[Any]], List[List[Any]], List[List[Any]], Dict[str, Any]]:
    try:
        belief = STORE.record_evidence(
            subject=subject,
            predicate=predicate,
            obj=obj,
            context=context,
            claim_type=claim_type,
            relation=relation,
            source_type=source_type,
            source_ref=source_ref,
            speaker=speaker,
            quote=quote,
            reliability=reliability,
            note=note,
            observed_at=observed_at,
            revision_trigger=revision_trigger,
            instrument_limit=instrument_limit,
        )
    except (TypeError, ValueError) as exc:
        return (
            f"### Record rejected\n{exc}",
            overview_markdown(),
            metrics_html(),
            health_warnings_markdown(),
            deck_rows(),
            queue_rows(),
            recent_rows(),
            beliefs_missing_revision(),
            beliefs_missing_limits(),
            low_evidence_high_confidence(),
            {"error": str(exc)},
        )

    return (
        f"""
### Evidence recorded

Orbit updated belief **{belief.id}**

- **Statement:** {belief.statement}
- **Status:** {belief.status}
- **Confidence:** {belief.confidence:.3f}
- **Pressure:** {belief.pressure:.3f}
""",
        overview_markdown(),
        metrics_html(),
        health_warnings_markdown(),
        deck_rows(),
        queue_rows(),
        recent_rows(),
        beliefs_missing_revision(),
        beliefs_missing_limits(),
        low_evidence_high_confidence(),
        serialize_belief(belief),
    )


def orbit_pressure_queue() -> List[List[Any]]:
    return queue_rows()


def orbit_decision_gate(
    confidence: float,
    stakes: str,
    reversibility: str,
    time_pressure: str,
) -> Dict[str, Any]:
    return decision_gate(confidence, stakes, reversibility, time_pressure)


def orbit_snapshot() -> Dict[str, Any]:
    return STORE.export_snapshot()


def default_reliability(source_type: str) -> float:
    return DEFAULT_RELIABILITY.get(source_type, 0.35)


def refresh_all():
    return (
        metrics_html(),
        overview_markdown(),
        health_warnings_markdown(),
        deck_rows(),
        queue_rows(),
        recent_rows(),
        beliefs_missing_revision(),
        beliefs_missing_limits(),
        low_evidence_high_confidence(),
    )


TABLE_HEADERS = [
    "Belief ID",
    "Statement",
    "Context",
    "Claim type",
    "Status",
    "Support",
    "Contradiction",
    "Confidence",
    "Pressure",
    "Evidence",
    "Source diversity",
    "Updated",
]

QUEUE_HEADERS = [
    "Belief ID",
    "Statement",
    "Status",
    "Confidence",
    "Pressure",
    "Revision question",
]

RECENT_HEADERS = [
    "Belief ID",
    "Statement",
    "Status",
    "Confidence",
    "Pressure",
    "Updated",
]

WARNING_HEADERS = [
    "Belief ID",
    "Statement",
    "Status",
    "Confidence",
    "Issue",
]


CSS = """
:root {
    --bg: #060816;
    --panel: rgba(15, 23, 42, 0.88);
    --panel2: rgba(30, 41, 59, 0.78);
    --border: rgba(148, 163, 184, 0.20);
    --text: #e8eef9;
    --muted: #9fb0c8;
}

.gradio-container {
    background:
        radial-gradient(circle at top left, rgba(59,130,246,.11), transparent 28%),
        radial-gradient(circle at top right, rgba(139,92,246,.10), transparent 26%),
        radial-gradient(circle at bottom left, rgba(6,182,212,.08), transparent 30%),
        linear-gradient(180deg, #020617 0%, #0b1120 100%);
    color: var(--text);
}

.orbit-shell {
    max-width: 1400px;
    margin: 0 auto;
}

.orbit-hero {
    border: 1px solid var(--border);
    border-radius: 24px;
    padding: 30px;
    background:
        radial-gradient(circle at top right, rgba(59,130,246,.18), transparent 35%),
        radial-gradient(circle at bottom left, rgba(16,185,129,.10), transparent 35%),
        linear-gradient(180deg, rgba(15,23,42,.92), rgba(15,23,42,.74));
    box-shadow: 0 20px 60px rgba(0,0,0,.35);
    margin-bottom: 18px;
}

.orbit-kicker {
    display: inline-block;
    font-size: .8rem;
    letter-spacing: .08em;
    text-transform: uppercase;
    color: #c7d2fe;
    background: rgba(99,102,241,.15);
    border: 1px solid rgba(129,140,248,.22);
    border-radius: 999px;
    padding: 6px 10px;
    margin-bottom: 12px;
}

.orbit-subtitle {
    color: var(--muted);
    font-size: 1.05rem;
    line-height: 1.7;
    margin-top: 10px;
    max-width: 980px;
}

.metrics-grid {
    display: grid;
    grid-template-columns: repeat(9, minmax(120px, 1fr));
    gap: 12px;
    margin: 8px 0 18px 0;
}

.metric-card {
    background: linear-gradient(180deg, rgba(15,23,42,.90), rgba(30,41,59,.72));
    border: 1px solid var(--border);
    border-radius: 18px;
    padding: 16px;
    min-height: 92px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.metric-card.success { border-color: rgba(34,197,94,.35); }
.metric-card.warning { border-color: rgba(245,158,11,.35); }
.metric-card.danger { border-color: rgba(239,68,68,.35); }
.metric-card.info { border-color: rgba(6,182,212,.35); }

.metric-title {
    color: var(--muted);
    font-size: .8rem;
    text-transform: uppercase;
    letter-spacing: .04em;
}

.metric-value {
    font-size: 1.7rem;
    font-weight: 700;
    color: #fff;
    margin-top: 8px;
}

.fundamentals-grid {
    display: grid;
    grid-template-columns: repeat(4, minmax(180px, 1fr));
    gap: 12px;
    margin: 8px 0 20px 0;
}

.fundamental-card {
    background: linear-gradient(180deg, rgba(15,23,42,.90), rgba(30,41,59,.70));
    border: 1px solid var(--border);
    border-radius: 18px;
    padding: 16px;
    min-height: 150px;
}

.fundamental-title {
    font-weight: 700;
    color: #eef2ff;
    margin-bottom: 10px;
}

.fundamental-body {
    color: var(--muted);
    line-height: 1.6;
}

.gr-button-primary {
    background: linear-gradient(90deg, #2563eb, #7c3aed) !important;
    border: none !important;
}

thead tr th {
    background: rgba(30,41,59,.95) !important;
    color: #dbeafe !important;
}

tbody tr:nth-child(even) {
    background: rgba(255,255,255,.02) !important;
}

footer { display: none !important; }

@media (max-width: 1250px) {
    .metrics-grid {
        grid-template-columns: repeat(4, minmax(120px, 1fr));
    }
    .fundamentals-grid {
        grid-template-columns: repeat(2, minmax(180px, 1fr));
    }
}

@media (max-width: 700px) {
    .metrics-grid {
        grid-template-columns: repeat(2, minmax(120px, 1fr));
    }
    .fundamentals-grid {
        grid-template-columns: repeat(1, minmax(180px, 1fr));
    }
    .orbit-hero {
        padding: 22px;
    }
}
"""


with gr.Blocks(title="Orbit Command Deck", css=CSS, theme=gr.themes.Soft()) as demo:
    gr.Markdown(
        """
<div class="orbit-shell">
<div class="orbit-hero">
    <div class="orbit-kicker">Shared belief revision under uncertainty</div>
    <h1>🪐 Orbit Command Deck</h1>
    <div class="orbit-subtitle">
        Orbit is a governor for reasoning under uncertainty. It does not store final truth.
        It stores claims, evidence, contradiction, pressure, and what would justify revision.
        Anyone can query Orbit, inspect its current lean, and contribute new signal.
    </div>
</div>
</div>
"""
    )

    fundamentals = gr.HTML(value=fundamentals_html())
    metrics = gr.HTML(value=metrics_html())
    overview = gr.Markdown(value=overview_markdown())
    health_warnings = gr.Markdown(value=health_warnings_markdown())

    with gr.Tab("Ask Orbit"):
        gr.Markdown(
            """
Ask Orbit what it currently leans toward on a topic.  
Orbit returns a **bounded, revisable belief**, not a declaration of final truth.
"""
        )
        with gr.Row():
            ask_text = gr.Textbox(
                label="Question, claim, or topic",
                placeholder="What does Orbit currently believe about X?",
                scale=6,
            )
            ask_button = gr.Button("Ask Orbit", variant="primary", scale=1)

        ask_summary = gr.Markdown()
        ask_table = gr.Dataframe(
            headers=TABLE_HEADERS,
            interactive=False,
            wrap=True,
            label="Matching beliefs",
        )
        ask_detail = gr.JSON(label="Strongest matching belief")

    with gr.Tab("Contribute Evidence"):
        gr.Markdown(
            """
Contribute support or contradiction to a claim already forming inside Orbit's memory.
Use the simple fields first. Advanced provenance fields keep the belief revisable instead of brittle.
"""
        )

        with gr.Group():
            gr.Markdown("### 1) The claim")
            with gr.Row():
                subject = gr.Textbox(label="Subject", placeholder="The GSX-R750")
                predicate = gr.Textbox(label="Predicate", placeholder="weighs about")
                obj = gr.Textbox(label="Object", placeholder="330 lb")
            context = gr.Textbox(
                label="Context / scope",
                placeholder="Thomas's 2001 motorcycle in current configuration",
            )

        with gr.Group():
            gr.Markdown("### 2) The evidence")
            with gr.Row():
                relation = gr.Radio(
                    choices=list(RELATIONS),
                    value="support",
                    label="Relation",
                )
                source_type = gr.Dropdown(
                    choices=list(SOURCE_TYPES),
                    value="firsthand_report",
                    label="Source type",
                )
                claim_type = gr.Dropdown(
                    choices=list(CLAIM_TYPES),
                    value="world_claim",
                    label="Claim type",
                )

            with gr.Row():
                source_ref = gr.Textbox(
                    label="Source reference",
                    placeholder="URL, conversation, message, document...",
                )
                speaker = gr.Textbox(
                    label="Speaker / observer",
                    placeholder="Thomas",
                )
                observed_at = gr.Textbox(
                    label="Observed at",
                    placeholder="2026-06-23 or ISO timestamp",
                )

            quote = gr.Textbox(
                label="Exact quote / observation / measurement",
                lines=4,
                placeholder="Preserve the original wording or measurement here.",
            )
            note = gr.Textbox(
                label="Analyst note",
                lines=3,
                placeholder="Optional interpretation or caution.",
            )
            reliability = gr.Slider(
                minimum=0.0,
                maximum=1.0,
                value=DEFAULT_RELIABILITY["firsthand_report"],
                step=0.05,
                label="Reliability",
            )

        with gr.Group():
            gr.Markdown("### 3) Governor constraints")
            revision_trigger = gr.Textbox(
                label="Revision trigger",
                placeholder="What new signal would materially change this judgment?",
            )
            instrument_limit = gr.Textbox(
                label="Instrument limit",
                placeholder="What can this source, sensor, memory, or model not establish?",
            )

        record_button = gr.Button("Record evidence", variant="primary")
        record_status = gr.Markdown()
        record_detail = gr.JSON(label="Updated belief")

    with gr.Tab("Pressure & Risk"):
        gr.Markdown(
            """
These are the places where Orbit most needs attention:
- beliefs under pressure
- beliefs missing revision triggers
- beliefs missing instrument limits
- beliefs with high confidence but sparse evidence
"""
        )
        refresh_button = gr.Button("Refresh system state", variant="primary")

        pressure_table = gr.Dataframe(
            headers=QUEUE_HEADERS,
            value=queue_rows(),
            interactive=False,
            wrap=True,
            label="Pressure queue",
        )

        recent_table = gr.Dataframe(
            headers=RECENT_HEADERS,
            value=recent_rows(),
            interactive=False,
            wrap=True,
            label="Recently updated beliefs",
        )

        missing_revision_table = gr.Dataframe(
            headers=WARNING_HEADERS,
            value=beliefs_missing_revision(),
            interactive=False,
            wrap=True,
            label="Beliefs missing revision triggers",
        )

        missing_limits_table = gr.Dataframe(
            headers=WARNING_HEADERS,
            value=beliefs_missing_limits(),
            interactive=False,
            wrap=True,
            label="Beliefs missing instrument limits",
        )

        sparse_confidence_table = gr.Dataframe(
            headers=["Belief ID", "Statement", "Status", "Confidence", "Evidence", "Issue"],
            value=low_evidence_high_confidence(),
            interactive=False,
            wrap=True,
            label="High confidence / sparse evidence",
        )

    with gr.Tab("Inspect & Export"):
        gr.Markdown(
            """
Inspect a belief directly by ID, or export Orbit's current snapshot.
"""
        )
        inspect_id = gr.Textbox(label="Belief ID")
        with gr.Row():
            inspect_button = gr.Button("Inspect", variant="primary")
            snapshot_button = gr.Button("Export snapshot")
        inspect_result = gr.JSON(label="Belief")
        snapshot_result = gr.JSON(label="Orbit snapshot")

    with gr.Tab("Decision Gate"):
        gr.Markdown(
            """
A belief can be strong enough to use without being strong enough to act on.
Orbit separates judgment from action through stakes, reversibility, and time pressure.
"""
        )
        action_confidence = gr.Slider(
            0.0, 1.0, value=0.60, step=0.01, label="Current confidence"
        )
        with gr.Row():
            stakes = gr.Radio(["low", "medium", "high"], value="medium", label="Stakes")
            reversibility = gr.Radio(
                ["high", "medium", "low"], value="medium", label="Reversibility"
            )
            time_pressure = gr.Radio(
                ["low", "medium", "high"], value="medium", label="Time pressure"
            )
        gate_button = gr.Button("Apply action threshold", variant="primary")
        gate_result = gr.JSON(label="Decision gate result")

    with gr.Tab("Belief Deck"):
        gr.Markdown(
            "Browse Orbit's current belief memory. Strong beliefs are still revisable."
        )
        deck_table = gr.Dataframe(
            headers=TABLE_HEADERS,
            value=deck_rows(),
            interactive=False,
            wrap=True,
            label="Belief deck",
        )

    ask_button.click(
        ask_orbit,
        inputs=[ask_text],
        outputs=[ask_summary, ask_table, ask_detail],
        api_name="orbit_query",
    )

    source_type.change(
        default_reliability,
        inputs=[source_type],
        outputs=[reliability],
        api_name=False,
    )

    record_button.click(
        orbit_record,
        inputs=[
            subject,
            predicate,
            obj,
            context,
            claim_type,
            relation,
            source_type,
            source_ref,
            speaker,
            quote,
            reliability,
            note,
            observed_at,
            revision_trigger,
            instrument_limit,
        ],
        outputs=[
            record_status,
            overview,
            metrics,
            health_warnings,
            deck_table,
            pressure_table,
            recent_table,
            missing_revision_table,
            missing_limits_table,
            sparse_confidence_table,
            record_detail,
        ],
        api_name="orbit_record",
    )

    refresh_button.click(
        refresh_all,
        inputs=[],
        outputs=[
            metrics,
            overview,
            health_warnings,
            deck_table,
            pressure_table,
            recent_table,
            missing_revision_table,
            missing_limits_table,
            sparse_confidence_table,
        ],
        api_name=False,
    )

    inspect_button.click(
        orbit_inspect,
        inputs=[inspect_id],
        outputs=[inspect_result],
        api_name="orbit_inspect",
    )

    snapshot_button.click(
        orbit_snapshot,
        inputs=[],
        outputs=[snapshot_result],
        api_name="orbit_snapshot",
    )

    gate_button.click(
        orbit_decision_gate,
        inputs=[action_confidence, stakes, reversibility, time_pressure],
        outputs=[gate_result],
        api_name="orbit_decision_gate",
    )

    demo.load(
        refresh_all,
        inputs=[],
        outputs=[
            metrics,
            overview,
            health_warnings,
            deck_table,
            pressure_table,
            recent_table,
            missing_revision_table,
            missing_limits_table,
            sparse_confidence_table,
        ],
    )


if __name__ == "__main__":
    demo.launch(mcp_server=True)