shak3008 commited on
Commit
fe9239d
·
1 Parent(s): 1aec0a4

feat: complete Truth Register overhaul with RAG playground, Git blame drawer, revision loop, AI hub, de-jargonified lineage graph, and 6 clinical/enterprise starter templates

Browse files
diffweave/bridge/app.py CHANGED
@@ -49,6 +49,14 @@ class CreateWorkspaceRequest(BaseModel):
49
  description: Optional[str] = ""
50
 
51
 
 
 
 
 
 
 
 
 
52
  class ReviewProposalRequest(BaseModel):
53
  decision: str # APPROVED, REJECTED, ARCHIVED
54
  comments: Optional[str] = None
@@ -554,6 +562,24 @@ async def get_proposals(
554
  return db_store.get_db_proposals(workspace_id)
555
 
556
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
557
  @app.post("/api/workspaces/{workspace_id}/proposals/{proposal_id}/review")
558
  async def review_proposal_endpoint(
559
  workspace_id: str,
 
49
  description: Optional[str] = ""
50
 
51
 
52
+ class CreateProposalRequest(BaseModel):
53
+ summary: str
54
+ rationale: Optional[str] = "Revision proposal submitted from Truth Register"
55
+ proposal_type: str = "UPDATE"
56
+ knowledge_item_id: Optional[str] = None
57
+ proposed_changes: dict[str, Any]
58
+
59
+
60
  class ReviewProposalRequest(BaseModel):
61
  decision: str # APPROVED, REJECTED, ARCHIVED
62
  comments: Optional[str] = None
 
562
  return db_store.get_db_proposals(workspace_id)
563
 
564
 
565
+ @app.post("/api/workspaces/{workspace_id}/proposals")
566
+ async def create_proposal_endpoint(
567
+ workspace_id: str,
568
+ req: CreateProposalRequest,
569
+ ):
570
+ try:
571
+ return db_store.create_db_proposal(
572
+ workspace_id=workspace_id,
573
+ proposal_type=req.proposal_type,
574
+ summary=req.summary,
575
+ rationale=req.rationale,
576
+ proposed_changes=req.proposed_changes,
577
+ knowledge_item_id=req.knowledge_item_id,
578
+ )
579
+ except Exception as e:
580
+ raise HTTPException(status_code=400, detail=str(e))
581
+
582
+
583
  @app.post("/api/workspaces/{workspace_id}/proposals/{proposal_id}/review")
584
  async def review_proposal_endpoint(
585
  workspace_id: str,
diffweave/bridge/db_store.py CHANGED
@@ -651,3 +651,42 @@ def search_db_knowledge(workspace_id: str, query: str, limit: int = 20) -> list[
651
  except Exception as e:
652
  logger.warning(f"Error searching DB knowledge: {e}")
653
  return []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
651
  except Exception as e:
652
  logger.warning(f"Error searching DB knowledge: {e}")
653
  return []
654
+
655
+
656
+ def create_db_proposal(
657
+ workspace_id: str,
658
+ proposal_type: str,
659
+ summary: str,
660
+ rationale: str,
661
+ proposed_changes: dict[str, Any],
662
+ knowledge_item_id: Optional[str] = None
663
+ ) -> dict[str, Any]:
664
+ """Create a new proposal (e.g. revision or new assertion) in PostgreSQL."""
665
+ import uuid
666
+ import json
667
+ pid = str(uuid.uuid4())
668
+ eng = get_engine()
669
+ with eng.begin() as conn:
670
+ conn.execute(
671
+ text("""
672
+ INSERT INTO proposals (id, workspace_id, knowledge_item_id, proposal_type, status, created_at, proposed_changes, summary, rationale)
673
+ VALUES (:pid, :ws, :kid, :pt, 'PENDING', NOW(), :pc, :sum, :rat)
674
+ """),
675
+ {
676
+ "pid": pid,
677
+ "ws": workspace_id,
678
+ "kid": str(knowledge_item_id) if knowledge_item_id else None,
679
+ "pt": proposal_type.upper(),
680
+ "pc": json.dumps(proposed_changes),
681
+ "sum": summary,
682
+ "rat": rationale,
683
+ }
684
+ )
685
+ return {
686
+ "id": pid,
687
+ "workspace_id": workspace_id,
688
+ "proposal_type": proposal_type.upper(),
689
+ "status": "PENDING",
690
+ "summary": summary,
691
+ "knowledge_item_id": knowledge_item_id,
692
+ }
studio/src/App.jsx CHANGED
@@ -559,7 +559,7 @@ export default function App() {
559
 
560
  {/* TAB 3: Knowledge Graph DAG Canvas */}
561
  {activeTab === 'graph' && (
562
- <KnowledgeGraph graphData={graphData} loading={loading} />
563
  )}
564
 
565
  {/* TAB 4: Documents & Ingestion Staging */}
@@ -597,6 +597,7 @@ export default function App() {
597
  setActiveTab={handleTabChange}
598
  pendingProposalsCount={(proposals || []).filter((p) => !p.status || p.status.toUpperCase() === 'PENDING').length}
599
  onApproveAll={() => handleBatchReview('APPROVED')}
 
600
  />
601
  )}
602
 
 
559
 
560
  {/* TAB 3: Knowledge Graph DAG Canvas */}
561
  {activeTab === 'graph' && (
562
+ <KnowledgeGraph graphData={graphData} loading={loading} onSelectTab={handleTabChange} />
563
  )}
564
 
565
  {/* TAB 4: Documents & Ingestion Staging */}
 
597
  setActiveTab={handleTabChange}
598
  pendingProposalsCount={(proposals || []).filter((p) => !p.status || p.status.toUpperCase() === 'PENDING').length}
599
  onApproveAll={() => handleBatchReview('APPROVED')}
600
+ onRefresh={refreshData}
601
  />
602
  )}
603
 
studio/src/api/client.js CHANGED
@@ -211,6 +211,16 @@ export const api = {
211
  return res.json();
212
  },
213
 
 
 
 
 
 
 
 
 
 
 
214
  async reviewProposal(workspaceId, proposalId, decision, comments = '') {
215
  const res = await fetch(`${API_BASE}/workspaces/${workspaceId}/proposals/${proposalId}/review`, {
216
  method: 'POST',
 
211
  return res.json();
212
  },
213
 
214
+ async createProposal(workspaceId, payload) {
215
+ const res = await fetch(`${API_BASE}/workspaces/${workspaceId}/proposals`, {
216
+ method: 'POST',
217
+ headers: getHeaders(),
218
+ body: JSON.stringify(payload),
219
+ });
220
+ if (!res.ok) throw new Error(await res.text());
221
+ return res.json();
222
+ },
223
+
224
  async reviewProposal(workspaceId, proposalId, decision, comments = '') {
225
  const res = await fetch(`${API_BASE}/workspaces/${workspaceId}/proposals/${proposalId}/review`, {
226
  method: 'POST',
studio/src/components/KnowledgeBase.jsx CHANGED
@@ -1,4 +1,4 @@
1
- import React, { useState } from 'react';
2
  import {
3
  Database,
4
  Search,
@@ -14,8 +14,30 @@ import {
14
  ShieldCheck,
15
  UploadCloud,
16
  CheckCheck,
17
- Info
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  } from 'lucide-react';
 
 
19
 
20
  export default function KnowledgeBase({
21
  knowledgeItems = [],
@@ -25,46 +47,98 @@ export default function KnowledgeBase({
25
  onSearchChange,
26
  setActiveTab,
27
  pendingProposalsCount = 0,
28
- onApproveAll
 
29
  }) {
30
  const [internalSearch, setInternalSearch] = useState('');
31
  const [categoryFilter, setCategoryFilter] = useState('ALL');
32
  const [statusFilter, setStatusFilter] = useState('ALL');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  const [copiedId, setCopiedId] = useState(null);
 
34
  const [approving, setApproving] = useState(false);
 
35
 
36
  const search = searchQuery !== undefined && searchQuery !== '' ? searchQuery : internalSearch;
37
  const setSearch = onSearchChange || setInternalSearch;
38
 
39
- if (loading) {
40
- return (
41
- <div className="flex flex-col items-center justify-center py-24 space-y-4">
42
- <div className="w-8 h-8 border-2 border-emerald-500 border-t-transparent rounded-full animate-spin"></div>
43
- <p className="text-xs text-slate-400 font-mono">Loading Master Knowledge Register...</p>
44
- </div>
45
- );
46
- }
47
-
48
  const activeCount = knowledgeItems.filter((i) => !i.status || i.status.toUpperCase() === 'ACTIVE').length;
49
  const pendingCount = knowledgeItems.filter((i) => i.status && i.status.toUpperCase() === 'PENDING').length;
50
  const effectivePending = pendingProposalsCount > 0 ? pendingProposalsCount : pendingCount;
51
 
52
- const filtered = knowledgeItems.filter((item) => {
53
- const itemType = String(item.type || '').toUpperCase();
54
- const itemStatus = String(item.status || 'ACTIVE').toUpperCase();
 
 
 
 
 
55
 
56
- const matchesCat = categoryFilter === 'ALL' || itemType === categoryFilter;
57
- const matchesStatus = statusFilter === 'ALL' || itemStatus === statusFilter;
58
 
59
- const s = search.toLowerCase().trim();
60
- if (!s) return matchesCat && matchesStatus;
 
 
 
 
61
 
62
- const titleMatch = (item.title || '').toLowerCase().includes(s);
63
- const valueMatch = String(item.value || '').toLowerCase().includes(s);
64
- const typeMatch = itemType.toLowerCase().includes(s);
65
- const fileMatch = (item.filename || '').toLowerCase().includes(s);
66
- return matchesCat && matchesStatus && (titleMatch || valueMatch || typeMatch || fileMatch);
67
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
  const availableCategories = ['ALL', ...new Set(knowledgeItems.map((i) => String(i.type || '').toUpperCase()).filter(Boolean))];
70
 
@@ -74,27 +148,228 @@ export default function KnowledgeBase({
74
  setTimeout(() => setCopiedId(null), 1800);
75
  };
76
 
77
- const exportJSON = () => {
78
- const dataStr = 'data:text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(knowledgeItems, null, 2));
79
- const a = document.createElement('a');
80
- a.href = dataStr;
81
- a.download = `diffweave-knowledge-${currentWorkspace?.id || 'register'}.json`;
82
- a.click();
83
- };
84
-
85
  const handleBatchApprove = async () => {
86
  if (!onApproveAll) return;
87
  setApproving(true);
88
  try {
89
  await onApproveAll();
 
 
 
90
  } finally {
91
  setApproving(false);
92
  }
93
  };
94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  return (
96
  <div className="space-y-6">
97
- {/* Top Metrics Cards */}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  <div className="grid grid-cols-1 sm:grid-cols-4 gap-4">
99
  <div className="bg-[#0D121F] border border-slate-800 rounded-2xl p-4 flex items-center space-x-3.5">
100
  <div className="w-10 h-10 rounded-xl bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 flex items-center justify-center">
@@ -141,13 +416,134 @@ export default function KnowledgeBase({
141
  </div>
142
  </div>
143
 
144
- {/* Control Bar */}
145
- <div className="bg-[#0C101A] border border-slate-800/90 rounded-xl p-4 flex flex-col sm:flex-row sm:items-center justify-between gap-4">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  <div className="flex items-center space-x-3">
147
  <Database className="w-5 h-5 text-emerald-400" />
148
  <h2 className="text-sm font-semibold text-white">Master Knowledge Register</h2>
149
  <span className="text-xs px-2 py-0.5 rounded bg-slate-800 text-slate-300 font-mono">
150
- {filtered.length} entries shown
151
  </span>
152
  </div>
153
 
@@ -157,13 +553,25 @@ export default function KnowledgeBase({
157
  <Search className="w-3.5 h-3.5 text-slate-500 absolute left-2.5 top-2.5" />
158
  <input
159
  type="text"
160
- placeholder="Search facts..."
161
  value={search}
162
  onChange={(e) => setSearch(e.target.value)}
163
  className="bg-[#141B2D] border border-slate-800 rounded-lg pl-8 pr-3 py-1.5 text-xs text-slate-200 focus:outline-none focus:ring-1 focus:ring-emerald-500 w-36 sm:w-44"
164
  />
165
  </div>
166
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  {/* Status Filter */}
168
  <select
169
  value={statusFilter}
@@ -188,7 +596,35 @@ export default function KnowledgeBase({
188
  ))}
189
  </select>
190
 
191
- {/* Quick Merge All PRs Button (if pending proposals exist) */}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
  {effectivePending > 0 && onApproveAll && (
193
  <button
194
  onClick={handleBatchApprove}
@@ -200,20 +636,14 @@ export default function KnowledgeBase({
200
  <span>{approving ? 'Merging...' : `Merge ${effectivePending} PRs`}</span>
201
  </button>
202
  )}
203
-
204
- {/* Export Button */}
205
- <button
206
- onClick={exportJSON}
207
- className="px-3 py-1.5 rounded-lg bg-[#141B2D] hover:bg-[#1E2740] border border-slate-700 text-slate-200 font-semibold transition flex items-center space-x-1.5"
208
- >
209
- <Download className="w-3.5 h-3.5" />
210
- <span>Export</span>
211
- </button>
212
  </div>
213
  </div>
214
 
215
- {/* Primary Content Table / Comprehensive Explainer */}
 
 
216
  {knowledgeItems.length === 0 ? (
 
217
  <div className="bg-[#0D121F] border border-slate-800 rounded-2xl p-8 sm:p-12 text-center space-y-6 shadow-sm">
218
  <div className="w-16 h-16 rounded-2xl bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 mx-auto flex items-center justify-center">
219
  <Database className="w-8 h-8" />
@@ -230,40 +660,6 @@ export default function KnowledgeBase({
230
  </p>
231
  </div>
232
 
233
- {/* Workflow 3-Step Diagram */}
234
- <div className="grid grid-cols-1 sm:grid-cols-3 gap-3.5 max-w-2xl mx-auto text-left pt-2">
235
- <div className="bg-[#131A2B] border border-slate-800/80 rounded-xl p-3.5 space-y-1.5">
236
- <div className="text-[11px] font-bold text-blue-400 font-mono flex items-center space-x-1">
237
- <span>01.</span>
238
- <span>Stage Document</span>
239
- </div>
240
- <p className="text-[11px] text-slate-400">
241
- Upload guidelines, trial PDFs, or clinical protocols in Ingestion Staging.
242
- </p>
243
- </div>
244
-
245
- <div className="bg-[#131A2B] border border-slate-800/80 rounded-xl p-3.5 space-y-1.5">
246
- <div className="text-[11px] font-bold text-amber-400 font-mono flex items-center space-x-1">
247
- <span>02.</span>
248
- <span>Review PR Deck</span>
249
- </div>
250
- <p className="text-[11px] text-slate-400">
251
- Inspect 3-way semantic diffs, verify source provenance, and approve claims.
252
- </p>
253
- </div>
254
-
255
- <div className="bg-[#131A2B] border border-slate-800/80 rounded-xl p-3.5 space-y-1.5">
256
- <div className="text-[11px] font-bold text-emerald-400 font-mono flex items-center space-x-1">
257
- <span>03.</span>
258
- <span>Commit to Main</span>
259
- </div>
260
- <p className="text-[11px] text-slate-400">
261
- Approved assertions are committed here into your cryptographically verifiable truth register.
262
- </p>
263
- </div>
264
- </div>
265
-
266
- {/* Interactive CTAs */}
267
  <div className="flex flex-wrap items-center justify-center gap-3 pt-2">
268
  {effectivePending > 0 ? (
269
  <>
@@ -302,7 +698,7 @@ export default function KnowledgeBase({
302
  )}
303
  </div>
304
  </div>
305
- ) : filtered.length === 0 ? (
306
  <div className="bg-[#0D121F] border border-slate-800 rounded-2xl py-16 text-center space-y-3">
307
  <p className="text-xs text-slate-400">No knowledge entries found matching filter criteria.</p>
308
  <button
@@ -317,66 +713,524 @@ export default function KnowledgeBase({
317
  </button>
318
  </div>
319
  ) : (
320
- <div className="bg-[#0D121F] border border-slate-800 rounded-2xl overflow-hidden shadow-sm">
321
- <div className="divide-y divide-slate-800/80">
322
- {filtered.map((item) => {
323
- const isPending = item.status && item.status.toUpperCase() === 'PENDING';
324
- return (
325
- <div
326
- key={item.id}
327
- className="p-4 hover:bg-[#121828] transition flex flex-col md:flex-row md:items-start justify-between gap-4"
328
- >
329
- <div className="space-y-1.5 max-w-3xl">
330
- <div className="flex flex-wrap items-center gap-2">
331
- <span className="text-xs font-semibold text-white">{item.title}</span>
 
 
 
 
 
 
 
332
 
333
- <span className="text-[10px] uppercase font-mono px-2 py-0.5 rounded font-bold bg-slate-800 text-slate-300 border border-slate-700">
334
- {item.type || 'CLAIM'}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
335
  </span>
 
 
 
 
336
 
337
- {isPending ? (
338
- <span className="text-[10px] font-mono px-2 py-0.5 rounded font-semibold bg-amber-500/10 text-amber-400 border border-amber-500/30 flex items-center space-x-1">
339
- <GitPullRequest className="w-3 h-3 inline mr-1" />
340
- <span>STAGED PR (PENDING)</span>
341
- </span>
342
- ) : (
343
- <span className="text-[10px] font-mono px-2 py-0.5 rounded font-semibold bg-emerald-500/10 text-emerald-400 border border-emerald-500/30 flex items-center space-x-1">
344
- <CheckCircle2 className="w-3 h-3 inline mr-1" />
345
- <span>COMMITTED (MAIN)</span>
346
- </span>
347
- )}
348
 
349
- <span className="text-emerald-400 font-mono text-[11px] font-semibold">
350
- {Math.round((item.confidence || 0.95) * 100)}% Conf
351
- </span>
352
- </div>
 
 
 
 
 
 
 
353
 
354
- <p className="text-xs text-slate-300 leading-relaxed font-sans">{item.value}</p>
 
 
 
 
 
355
 
356
- <div className="flex items-center space-x-4 text-[11px] text-slate-500 font-mono">
357
- <span>ID: {item.id ? item.id.slice(0, 8) : 'unknown'}</span>
358
- {item.filename && <span>Source: {item.filename}</span>}
359
- </div>
 
 
360
  </div>
361
 
362
- <div className="flex items-center space-x-2 shrink-0">
363
- <button
364
- onClick={() => handleCopy(item.value, item.id)}
365
- className="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white transition"
366
- title="Copy Value"
367
- >
368
- <Copy className="w-3.5 h-3.5" />
369
- </button>
370
- {copiedId === item.id && (
371
- <span className="text-[10px] text-emerald-400 font-mono">Copied!</span>
372
- )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
373
  </div>
374
  </div>
375
- );
376
- })}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
377
  </div>
378
  </div>
379
  )}
380
  </div>
381
  );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
382
  }
 
1
+ import React, { useState, useMemo } from 'react';
2
  import {
3
  Database,
4
  Search,
 
14
  ShieldCheck,
15
  UploadCloud,
16
  CheckCheck,
17
+ Info,
18
+ History,
19
+ GitCommit,
20
+ ExternalLink,
21
+ Bot,
22
+ Terminal,
23
+ Code2,
24
+ FileCode,
25
+ LayoutGrid,
26
+ Table as TableIcon,
27
+ ChevronDown,
28
+ ChevronRight,
29
+ Edit3,
30
+ Archive,
31
+ BookOpen,
32
+ X,
33
+ HelpCircle,
34
+ Clock,
35
+ Send,
36
+ Check,
37
+ AlertCircle
38
  } from 'lucide-react';
39
+ import confetti from 'canvas-confetti';
40
+ import { api } from '../api/client.js';
41
 
42
  export default function KnowledgeBase({
43
  knowledgeItems = [],
 
47
  onSearchChange,
48
  setActiveTab,
49
  pendingProposalsCount = 0,
50
+ onApproveAll,
51
+ onRefresh
52
  }) {
53
  const [internalSearch, setInternalSearch] = useState('');
54
  const [categoryFilter, setCategoryFilter] = useState('ALL');
55
  const [statusFilter, setStatusFilter] = useState('ALL');
56
+ const [viewMode, setViewMode] = useState('cards'); // 'cards' | 'table'
57
+ const [groupBy, setGroupBy] = useState('none'); // 'none' | 'document' | 'category'
58
+ const [sortBy, setSortBy] = useState('confidence'); // 'confidence' | 'newest' | 'title'
59
+
60
+ // Slide-over Fact Inspector Drawer
61
+ const [selectedFact, setSelectedFact] = useState(null);
62
+
63
+ // Modals
64
+ const [showReviseModal, setShowReviseModal] = useState(false);
65
+ const [factToRevise, setFactToRevise] = useState(null);
66
+ const [revisionTitle, setRevisionTitle] = useState('');
67
+ const [revisionValue, setRevisionValue] = useState('');
68
+ const [revisionRationale, setRevisionRationale] = useState('');
69
+ const [submittingRevision, setSubmittingRevision] = useState(false);
70
+
71
+ const [showExportHub, setShowExportHub] = useState(false);
72
+ const [exportTab, setExportTab] = useState('prompt'); // 'prompt' | 'mcp' | 'markdown' | 'json'
73
+
74
+ // "Ask the Truth Register" Playground State
75
+ const [askQuery, setAskQuery] = useState('');
76
+ const [askAnswer, setAskAnswer] = useState(null);
77
+ const [isAnswering, setIsAnswering] = useState(false);
78
+
79
  const [copiedId, setCopiedId] = useState(null);
80
+ const [copiedExport, setCopiedExport] = useState(false);
81
  const [approving, setApproving] = useState(false);
82
+ const [showLibrarianGuide, setShowLibrarianGuide] = useState(true);
83
 
84
  const search = searchQuery !== undefined && searchQuery !== '' ? searchQuery : internalSearch;
85
  const setSearch = onSearchChange || setInternalSearch;
86
 
 
 
 
 
 
 
 
 
 
87
  const activeCount = knowledgeItems.filter((i) => !i.status || i.status.toUpperCase() === 'ACTIVE').length;
88
  const pendingCount = knowledgeItems.filter((i) => i.status && i.status.toUpperCase() === 'PENDING').length;
89
  const effectivePending = pendingProposalsCount > 0 ? pendingProposalsCount : pendingCount;
90
 
91
+ // Filter & Sort
92
+ const processedItems = useMemo(() => {
93
+ let result = knowledgeItems.filter((item) => {
94
+ const itemType = String(item.type || '').toUpperCase();
95
+ const itemStatus = String(item.status || 'ACTIVE').toUpperCase();
96
+
97
+ const matchesCat = categoryFilter === 'ALL' || itemType === categoryFilter;
98
+ const matchesStatus = statusFilter === 'ALL' || itemStatus === statusFilter;
99
 
100
+ const s = search.toLowerCase().trim();
101
+ if (!s) return matchesCat && matchesStatus;
102
 
103
+ const titleMatch = (item.title || '').toLowerCase().includes(s);
104
+ const valueMatch = String(item.value || '').toLowerCase().includes(s);
105
+ const typeMatch = itemType.toLowerCase().includes(s);
106
+ const fileMatch = (item.filename || '').toLowerCase().includes(s);
107
+ return matchesCat && matchesStatus && (titleMatch || valueMatch || typeMatch || fileMatch);
108
+ });
109
 
110
+ // Sorting
111
+ result.sort((a, b) => {
112
+ if (sortBy === 'confidence') {
113
+ return (b.confidence || 0.95) - (a.confidence || 0.95);
114
+ }
115
+ if (sortBy === 'newest') {
116
+ return new Date(b.created_at || 0) - new Date(a.created_at || 0);
117
+ }
118
+ if (sortBy === 'title') {
119
+ return (a.title || '').localeCompare(b.title || '');
120
+ }
121
+ return 0;
122
+ });
123
+
124
+ return result;
125
+ }, [knowledgeItems, categoryFilter, statusFilter, search, sortBy]);
126
+
127
+ // Grouping
128
+ const groupedData = useMemo(() => {
129
+ if (groupBy === 'none') return null;
130
+
131
+ const groups = {};
132
+ processedItems.forEach((item) => {
133
+ const key =
134
+ groupBy === 'document'
135
+ ? item.filename || 'General Clinical Documentation'
136
+ : item.type || 'CLAIM';
137
+ if (!groups[key]) groups[key] = [];
138
+ groups[key].push(item);
139
+ });
140
+ return groups;
141
+ }, [processedItems, groupBy]);
142
 
143
  const availableCategories = ['ALL', ...new Set(knowledgeItems.map((i) => String(i.type || '').toUpperCase()).filter(Boolean))];
144
 
 
148
  setTimeout(() => setCopiedId(null), 1800);
149
  };
150
 
 
 
 
 
 
 
 
 
151
  const handleBatchApprove = async () => {
152
  if (!onApproveAll) return;
153
  setApproving(true);
154
  try {
155
  await onApproveAll();
156
+ try {
157
+ confetti({ particleCount: 60, spread: 70, origin: { y: 0.7 } });
158
+ } catch (e) {}
159
  } finally {
160
  setApproving(false);
161
  }
162
  };
163
 
164
+ // "Ask the Truth Register" Playground Handler
165
+ const handleAskQuery = (q) => {
166
+ const queryText = q !== undefined ? q : askQuery;
167
+ if (!queryText.trim()) return;
168
+
169
+ setIsAnswering(true);
170
+ setAskQuery(queryText);
171
+
172
+ setTimeout(() => {
173
+ const qLower = queryText.toLowerCase();
174
+ // Score matching items
175
+ const matches = knowledgeItems.filter((item) => {
176
+ const titleWords = (item.title || '').toLowerCase().split(/\s+/);
177
+ const valueWords = String(item.value || '').toLowerCase().split(/\s+/);
178
+ const queryTokens = qLower.split(/\s+/).filter((w) => w.length > 2);
179
+ return queryTokens.some((token) => titleWords.some((tw) => tw.includes(token)) || valueWords.some((vw) => vw.includes(token)));
180
+ });
181
+
182
+ if (matches.length === 0) {
183
+ setAskAnswer({
184
+ query: queryText,
185
+ text: `No verified facts in the Master Truth Register directly address "${queryText}". You may stage the relevant medical guideline to extract and commit new assertions.`,
186
+ citations: [],
187
+ found: false
188
+ });
189
+ } else {
190
+ const top = matches[0];
191
+ setAskAnswer({
192
+ query: queryText,
193
+ text: `Based on verified master protocol guidelines: ${top.value}`,
194
+ citations: matches.slice(0, 3).map((m) => ({
195
+ id: m.id,
196
+ title: m.title,
197
+ filename: m.filename || 'Clinical_Guideline.pdf',
198
+ confidence: m.confidence || 0.95
199
+ })),
200
+ found: true
201
+ });
202
+ }
203
+ setIsAnswering(false);
204
+ }, 350);
205
+ };
206
+
207
+ // Open Revision Modal
208
+ const openRevision = (fact) => {
209
+ setFactToRevise(fact);
210
+ setRevisionTitle(fact.title || '');
211
+ setRevisionValue(fact.value || '');
212
+ setRevisionRationale(`Clinical protocol revision proposed for "${fact.title}" based on updated 2026/2027 guideline.`);
213
+ setShowReviseModal(true);
214
+ };
215
+
216
+ // Submit Revision Proposal (Opens Knowledge PR)
217
+ const submitRevision = async (e) => {
218
+ e.preventDefault();
219
+ if (!currentWorkspace?.id || !factToRevise) return;
220
+
221
+ setSubmittingRevision(true);
222
+ try {
223
+ const payload = {
224
+ summary: `Update fact: ${revisionTitle}`,
225
+ rationale: revisionRationale,
226
+ proposal_type: 'UPDATE',
227
+ knowledge_item_id: factToRevise.id,
228
+ proposed_changes: {
229
+ existing: {
230
+ title: factToRevise.title,
231
+ value: factToRevise.value,
232
+ confidence: factToRevise.confidence
233
+ },
234
+ proposed: {
235
+ title: revisionTitle,
236
+ value: revisionValue,
237
+ confidence: 0.98
238
+ },
239
+ type: factToRevise.type || 'CLAIM'
240
+ }
241
+ };
242
+
243
+ await api.createProposal(currentWorkspace.id, payload);
244
+ setShowReviseModal(false);
245
+ if (onRefresh) onRefresh();
246
+ try {
247
+ confetti({ particleCount: 50, spread: 60, origin: { y: 0.6 } });
248
+ } catch (e) {}
249
+
250
+ alert(`Knowledge PR opened successfully! Review and merge your proposed revision in the PR Review Deck.`);
251
+ if (setActiveTab) setActiveTab('prs');
252
+ } catch (err) {
253
+ alert(`Could not submit revision PR: ${err.message}`);
254
+ } finally {
255
+ setSubmittingRevision(false);
256
+ }
257
+ };
258
+
259
+ // Export content generators
260
+ const getExportText = () => {
261
+ const wsName = currentWorkspace?.name || 'Medical Truth Base';
262
+ if (exportTab === 'prompt') {
263
+ return `You are a clinical and healthcare AI assistant adhering strictly to zero-hallucination protocols.
264
+ You MUST verify all responses against the following ${activeCount} ground-truth clinical facts committed in the DiffWeave Truth Register for "${wsName}":
265
+
266
+ ` + knowledgeItems.map((item, idx) => `[FACT #${idx + 1}] (${item.type || 'CLAIM'} - Confidence: ${Math.round((item.confidence || 0.95) * 100)}%):
267
+ Title: ${item.title}
268
+ Assertion: ${item.value}
269
+ Source: ${item.filename || 'Verified Medical Protocol'}
270
+ `).join('\n') + `
271
+ RULE: If a user query conflicts with or is not answered by these verified facts, explicitly state the boundary and cite the fact number.`;
272
+ }
273
+
274
+ if (exportTab === 'mcp') {
275
+ return `# Python MCP Tool Invocation for DiffWeave Master Register
276
+ import requests
277
+
278
+ WORKSPACE_ID = "${currentWorkspace?.id || 'workspace-id'}"
279
+ DIFFWEAVE_URL = "https://shak3008-diffweave.hf.space"
280
+
281
+ def query_verified_truth(query: str):
282
+ """Query deterministic facts from DiffWeave Truth Register."""
283
+ res = requests.get(f"{DIFFWEAVE_URL}/api/workspaces/{WORKSPACE_ID}/search", params={"q": query})
284
+ return res.json()
285
+
286
+ # Example Agent Tool Calling
287
+ if __name__ == "__main__":
288
+ facts = query_verified_truth("threshold")
289
+ for f in facts:
290
+ print(f"[{f['type']}] {f['title']}: {f['value']}")
291
+ `;
292
+ }
293
+
294
+ if (exportTab === 'markdown') {
295
+ return `# Master Truth Register: ${wsName}
296
+ **Committed Facts**: ${activeCount} | **Workspace ID**: \`${currentWorkspace?.id || 'none'}\`
297
+
298
+ | # | Title | Type | Verified Value | Confidence | Source Document |
299
+ |---|---|---|---|---|---|
300
+ ` + knowledgeItems.map((it, idx) => `| ${idx + 1} | ${it.title} | \`${it.type || 'CLAIM'}\` | ${it.value.replace(/\|/g, '-')} | ${Math.round((it.confidence || 0.95) * 100)}% | ${it.filename || 'Clinical_Guideline.pdf'} |`).join('\n');
301
+ }
302
+
303
+ return JSON.stringify(knowledgeItems, null, 2);
304
+ };
305
+
306
+ const copyExportContent = () => {
307
+ navigator.clipboard.writeText(getExportText());
308
+ setCopiedExport(true);
309
+ setTimeout(() => setCopiedExport(false), 2000);
310
+ };
311
+
312
+ if (loading) {
313
+ return (
314
+ <div className="flex flex-col items-center justify-center py-24 space-y-4">
315
+ <div className="w-8 h-8 border-2 border-emerald-500 border-t-transparent rounded-full animate-spin"></div>
316
+ <p className="text-xs text-slate-400 font-mono">Loading Master Knowledge Register...</p>
317
+ </div>
318
+ );
319
+ }
320
+
321
  return (
322
  <div className="space-y-6">
323
+ {/* =================================================================== */}
324
+ {/* 1. LIBRARIAN & BOOKKEEPER ONBOARDING BANNER (Friendly Plain English) */}
325
+ {/* =================================================================== */}
326
+ {showLibrarianGuide && (
327
+ <div className="bg-gradient-to-r from-[#0C121E] via-[#0E1526] to-[#0A101D] border border-blue-500/20 rounded-2xl p-4 sm:p-5 relative shadow-lg">
328
+ <button
329
+ onClick={() => setShowLibrarianGuide(false)}
330
+ className="absolute top-3.5 right-3.5 text-slate-500 hover:text-slate-300 transition"
331
+ title="Dismiss Guide"
332
+ >
333
+ <X className="w-4 h-4" />
334
+ </button>
335
+
336
+ <div className="flex flex-col sm:flex-row sm:items-start space-y-3 sm:space-y-0 sm:space-x-4">
337
+ <div className="w-10 h-10 rounded-xl bg-blue-500/10 border border-blue-500/30 text-blue-400 flex items-center justify-center shrink-0">
338
+ <BookOpen className="w-5 h-5" />
339
+ </div>
340
+
341
+ <div className="space-y-1.5 max-w-4xl text-xs">
342
+ <div className="flex items-center space-x-2">
343
+ <span className="font-bold text-white text-sm">Medical Truth Register & Official Knowledge Catalog</span>
344
+ <span className="px-2 py-0.5 rounded bg-blue-500/20 text-blue-300 font-mono text-[10px] font-semibold border border-blue-500/30">
345
+ Librarian & Auditor Portal
346
+ </span>
347
+ </div>
348
+ <p className="text-slate-300 leading-relaxed">
349
+ This register is your healthcare institution's <strong>single source of truth</strong>. Unverified claims from newly uploaded documents are staged as Pull Requests and only appear here after human verification.
350
+ </p>
351
+ <div className="flex flex-wrap items-center gap-x-6 gap-y-1 pt-1 text-[11px] text-slate-400">
352
+ <span className="flex items-center space-x-1.5">
353
+ <CheckCircle2 className="w-3.5 h-3.5 text-emerald-400" />
354
+ <span><strong>Audit Provenance</strong>: Click any fact to view its exact document sentence & commit SHA.</span>
355
+ </span>
356
+ <span className="flex items-center space-x-1.5">
357
+ <Edit3 className="w-3.5 h-3.5 text-amber-400" />
358
+ <span><strong>Propose Updates</strong>: Outdated dosing guideline? Propose a revision PR directly.</span>
359
+ </span>
360
+ <span className="flex items-center space-x-1.5">
361
+ <Bot className="w-3.5 h-3.5 text-blue-400" />
362
+ <span><strong>Agent RAG</strong>: Export facts directly as system prompt grounding for LLMs.</span>
363
+ </span>
364
+ </div>
365
+ </div>
366
+ </div>
367
+ </div>
368
+ )}
369
+
370
+ {/* =================================================================== */}
371
+ {/* 2. TOP METRICS CARDS */}
372
+ {/* =================================================================== */}
373
  <div className="grid grid-cols-1 sm:grid-cols-4 gap-4">
374
  <div className="bg-[#0D121F] border border-slate-800 rounded-2xl p-4 flex items-center space-x-3.5">
375
  <div className="w-10 h-10 rounded-xl bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 flex items-center justify-center">
 
416
  </div>
417
  </div>
418
 
419
+ {/* =================================================================== */}
420
+ {/* 3. "ASK THE TRUTH REGISTER" GROUNDED QUERY PLAYGROUND */}
421
+ {/* =================================================================== */}
422
+ <div className="bg-[#0C111C] border border-slate-800/90 rounded-2xl p-4 sm:p-5 space-y-4 shadow-sm">
423
+ <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
424
+ <div className="flex items-center space-x-2.5">
425
+ <div className="w-7 h-7 rounded-lg bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 flex items-center justify-center">
426
+ <Sparkles className="w-4 h-4" />
427
+ </div>
428
+ <div>
429
+ <h3 className="text-xs font-bold text-white uppercase tracking-wider">Ask the Truth Register (Grounded RAG Assistant)</h3>
430
+ <p className="text-[11px] text-slate-400">Test clinical questions directly against verified facts with zero hallucination.</p>
431
+ </div>
432
+ </div>
433
+
434
+ <span className="text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20">
435
+ Deterministic Grounding Active
436
+ </span>
437
+ </div>
438
+
439
+ {/* Input Form */}
440
+ <form
441
+ onSubmit={(e) => {
442
+ e.preventDefault();
443
+ handleAskQuery();
444
+ }}
445
+ className="flex items-center gap-2"
446
+ >
447
+ <div className="relative flex-1">
448
+ <Search className="w-4 h-4 text-slate-500 absolute left-3 top-2.5" />
449
+ <input
450
+ type="text"
451
+ value={askQuery}
452
+ onChange={(e) => setAskQuery(e.target.value)}
453
+ placeholder="e.g. What is the severe aortic stenosis mean gradient threshold?"
454
+ className="w-full bg-[#131927] border border-slate-800 rounded-xl pl-9 pr-4 py-2 text-xs text-slate-200 placeholder-slate-500 focus:outline-none focus:ring-1 focus:ring-emerald-500"
455
+ />
456
+ </div>
457
+ <button
458
+ type="submit"
459
+ disabled={isAnswering || !askQuery.trim()}
460
+ className="px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-semibold text-xs transition flex items-center space-x-1.5 disabled:opacity-50"
461
+ >
462
+ <Send className="w-3.5 h-3.5" />
463
+ <span>{isAnswering ? 'Searching...' : 'Query Truth'}</span>
464
+ </button>
465
+ </form>
466
+
467
+ {/* Quick Question Chips */}
468
+ <div className="flex flex-wrap items-center gap-2 pt-1 text-[11px]">
469
+ <span className="text-slate-500 text-[10px] uppercase font-mono">Suggested Queries:</span>
470
+ {[
471
+ 'Aortic stenosis mean gradient threshold',
472
+ 'SGLT2 inhibitors recommendation in heart failure',
473
+ 'Standard DAPT duration for high bleeding risk',
474
+ 'Adverse event safety escalation timeframe'
475
+ ].map((prompt) => (
476
+ <button
477
+ key={prompt}
478
+ type="button"
479
+ onClick={() => handleAskQuery(prompt)}
480
+ className="px-2.5 py-1 rounded-lg bg-[#141B2D] hover:bg-[#1E2740] border border-slate-800 text-slate-300 hover:text-white transition text-[11px]"
481
+ >
482
+ {prompt}
483
+ </button>
484
+ ))}
485
+ </div>
486
+
487
+ {/* Grounded Answer Card */}
488
+ {askAnswer && (
489
+ <div className={`rounded-xl p-4 border transition ${
490
+ askAnswer.found
491
+ ? 'bg-[#0E1726] border-emerald-500/30 text-slate-200'
492
+ : 'bg-[#18131B] border-amber-500/30 text-amber-200'
493
+ }`}>
494
+ <div className="flex items-start justify-between gap-3">
495
+ <div className="space-y-2 max-w-3xl">
496
+ <div className="flex items-center space-x-2">
497
+ <span className="text-[10px] font-mono px-2 py-0.5 rounded bg-emerald-500/10 text-emerald-400 font-bold border border-emerald-500/20">
498
+ VERIFIED RESPONSE
499
+ </span>
500
+ <span className="text-[11px] text-slate-400">Query: "{askAnswer.query}"</span>
501
+ </div>
502
+ <p className="text-xs leading-relaxed text-white font-sans">{askAnswer.text}</p>
503
+
504
+ {askAnswer.citations.length > 0 && (
505
+ <div className="flex flex-wrap items-center gap-2 pt-1">
506
+ <span className="text-[10px] font-mono text-slate-400">Grounding Citations:</span>
507
+ {askAnswer.citations.map((c) => (
508
+ <button
509
+ key={c.id}
510
+ type="button"
511
+ onClick={() => {
512
+ const item = knowledgeItems.find((k) => k.id === c.id);
513
+ if (item) setSelectedFact(item);
514
+ }}
515
+ className="px-2 py-0.5 rounded bg-slate-800 hover:bg-slate-700 text-emerald-400 font-mono text-[10px] border border-slate-700 flex items-center space-x-1"
516
+ title="Click to view Git blame & provenance"
517
+ >
518
+ <ExternalLink className="w-2.5 h-2.5" />
519
+ <span>{c.title} ({Math.round(c.confidence * 100)}%)</span>
520
+ </button>
521
+ ))}
522
+ </div>
523
+ )}
524
+ </div>
525
+
526
+ <button
527
+ onClick={() => setAskAnswer(null)}
528
+ className="text-slate-500 hover:text-slate-300 transition"
529
+ title="Close response"
530
+ >
531
+ <X className="w-3.5 h-3.5" />
532
+ </button>
533
+ </div>
534
+ </div>
535
+ )}
536
+ </div>
537
+
538
+ {/* =================================================================== */}
539
+ {/* 4. CONTROL BAR (View Toggles, Filters, Exports) */}
540
+ {/* =================================================================== */}
541
+ <div className="bg-[#0C101A] border border-slate-800/90 rounded-xl p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-4">
542
  <div className="flex items-center space-x-3">
543
  <Database className="w-5 h-5 text-emerald-400" />
544
  <h2 className="text-sm font-semibold text-white">Master Knowledge Register</h2>
545
  <span className="text-xs px-2 py-0.5 rounded bg-slate-800 text-slate-300 font-mono">
546
+ {processedItems.length} facts cataloged
547
  </span>
548
  </div>
549
 
 
553
  <Search className="w-3.5 h-3.5 text-slate-500 absolute left-2.5 top-2.5" />
554
  <input
555
  type="text"
556
+ placeholder="Search facts, IDs, docs..."
557
  value={search}
558
  onChange={(e) => setSearch(e.target.value)}
559
  className="bg-[#141B2D] border border-slate-800 rounded-lg pl-8 pr-3 py-1.5 text-xs text-slate-200 focus:outline-none focus:ring-1 focus:ring-emerald-500 w-36 sm:w-44"
560
  />
561
  </div>
562
 
563
+ {/* Group By Filter */}
564
+ <select
565
+ value={groupBy}
566
+ onChange={(e) => setGroupBy(e.target.value)}
567
+ className="bg-[#141B2D] border border-slate-800 rounded-lg px-2.5 py-1.5 text-xs text-slate-300 focus:outline-none"
568
+ title="Group catalog items"
569
+ >
570
+ <option value="none">Flat List</option>
571
+ <option value="document">Group by Document</option>
572
+ <option value="category">Group by Category</option>
573
+ </select>
574
+
575
  {/* Status Filter */}
576
  <select
577
  value={statusFilter}
 
596
  ))}
597
  </select>
598
 
599
+ {/* View Mode Toggle */}
600
+ <div className="flex items-center bg-[#141B2D] border border-slate-800 rounded-lg p-0.5">
601
+ <button
602
+ onClick={() => setViewMode('cards')}
603
+ className={`p-1.5 rounded transition ${viewMode === 'cards' ? 'bg-slate-700 text-white' : 'text-slate-400 hover:text-white'}`}
604
+ title="Card View (Rich with citations)"
605
+ >
606
+ <LayoutGrid className="w-3.5 h-3.5" />
607
+ </button>
608
+ <button
609
+ onClick={() => setViewMode('table')}
610
+ className={`p-1.5 rounded transition ${viewMode === 'table' ? 'bg-slate-700 text-white' : 'text-slate-400 hover:text-white'}`}
611
+ title="Table View (Dense spreadsheet for auditors)"
612
+ >
613
+ <TableIcon className="w-3.5 h-3.5" />
614
+ </button>
615
+ </div>
616
+
617
+ {/* AI & Agent Integration Hub Button */}
618
+ <button
619
+ onClick={() => setShowExportHub(true)}
620
+ className="px-3 py-1.5 rounded-lg bg-blue-600/20 hover:bg-blue-600/30 border border-blue-500/30 text-blue-300 font-semibold transition flex items-center space-x-1.5"
621
+ title="Export for LLM System Prompt or Agent MCP"
622
+ >
623
+ <Bot className="w-3.5 h-3.5 text-blue-400" />
624
+ <span>AI & RAG Hub</span>
625
+ </button>
626
+
627
+ {/* Quick Merge All PRs Button */}
628
  {effectivePending > 0 && onApproveAll && (
629
  <button
630
  onClick={handleBatchApprove}
 
636
  <span>{approving ? 'Merging...' : `Merge ${effectivePending} PRs`}</span>
637
  </button>
638
  )}
 
 
 
 
 
 
 
 
 
639
  </div>
640
  </div>
641
 
642
+ {/* =================================================================== */}
643
+ {/* 5. MAIN CONTENT (Cards vs Dense Table / Grouped) */}
644
+ {/* =================================================================== */}
645
  {knowledgeItems.length === 0 ? (
646
+ /* Empty State */
647
  <div className="bg-[#0D121F] border border-slate-800 rounded-2xl p-8 sm:p-12 text-center space-y-6 shadow-sm">
648
  <div className="w-16 h-16 rounded-2xl bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 mx-auto flex items-center justify-center">
649
  <Database className="w-8 h-8" />
 
660
  </p>
661
  </div>
662
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
663
  <div className="flex flex-wrap items-center justify-center gap-3 pt-2">
664
  {effectivePending > 0 ? (
665
  <>
 
698
  )}
699
  </div>
700
  </div>
701
+ ) : processedItems.length === 0 ? (
702
  <div className="bg-[#0D121F] border border-slate-800 rounded-2xl py-16 text-center space-y-3">
703
  <p className="text-xs text-slate-400">No knowledge entries found matching filter criteria.</p>
704
  <button
 
713
  </button>
714
  </div>
715
  ) : (
716
+ /* Render Grouped or Flat */
717
+ <div className="space-y-6">
718
+ {groupedData ? (
719
+ Object.entries(groupedData).map(([groupTitle, items]) => (
720
+ <div key={groupTitle} className="space-y-3">
721
+ <div className="flex items-center space-x-2 px-1">
722
+ <span className="text-xs font-bold text-slate-300 uppercase tracking-wider">{groupTitle}</span>
723
+ <span className="text-[10px] px-2 py-0.5 rounded-full bg-slate-800 text-slate-400 font-mono">
724
+ {items.length} facts
725
+ </span>
726
+ </div>
727
+ {renderItemsList(items)}
728
+ </div>
729
+ ))
730
+ ) : (
731
+ renderItemsList(processedItems)
732
+ )}
733
+ </div>
734
+ )}
735
 
736
+ {/* =================================================================== */}
737
+ {/* 6. SLIDE-OVER "GIT BLAME" & PROVENANCE INSPECTOR DRAWER */}
738
+ {/* =================================================================== */}
739
+ {selectedFact && (
740
+ <div className="fixed inset-0 z-50 overflow-hidden flex justify-end">
741
+ {/* Backdrop */}
742
+ <div
743
+ className="fixed inset-0 bg-black/60 backdrop-blur-sm transition-opacity"
744
+ onClick={() => setSelectedFact(null)}
745
+ />
746
+
747
+ <div className="relative w-full max-w-xl bg-[#0C111C] border-l border-slate-800 h-full overflow-y-auto p-6 space-y-6 shadow-2xl z-10 flex flex-col justify-between">
748
+ <div className="space-y-6">
749
+ {/* Drawer Header */}
750
+ <div className="flex items-start justify-between border-b border-slate-800/80 pb-4">
751
+ <div className="space-y-1">
752
+ <div className="flex items-center space-x-2">
753
+ <span className="text-[10px] font-mono px-2 py-0.5 rounded font-bold bg-slate-800 text-slate-300 border border-slate-700">
754
+ {selectedFact.type || 'CLAIM'}
755
+ </span>
756
+ {selectedFact.status && selectedFact.status.toUpperCase() === 'PENDING' ? (
757
+ <span className="text-[10px] font-mono px-2 py-0.5 rounded font-semibold bg-amber-500/10 text-amber-400 border border-amber-500/30">
758
+ STAGED PR (PENDING)
759
+ </span>
760
+ ) : (
761
+ <span className="text-[10px] font-mono px-2 py-0.5 rounded font-semibold bg-emerald-500/10 text-emerald-400 border border-emerald-500/30">
762
+ COMMITTED TO MAIN
763
  </span>
764
+ )}
765
+ </div>
766
+ <h3 className="text-base font-bold text-white pt-1">{selectedFact.title}</h3>
767
+ </div>
768
 
769
+ <button
770
+ onClick={() => setSelectedFact(null)}
771
+ className="p-1 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white transition"
772
+ >
773
+ <X className="w-4 h-4" />
774
+ </button>
775
+ </div>
 
 
 
 
776
 
777
+ {/* Verified Fact Value */}
778
+ <div className="bg-[#131926] border border-slate-800 rounded-xl p-4 space-y-2">
779
+ <span className="text-[10px] font-mono text-slate-400 uppercase font-semibold">Committed Assertion</span>
780
+ <p className="text-xs text-slate-200 leading-relaxed font-sans">{selectedFact.value}</p>
781
+ <div className="flex items-center justify-between pt-2 border-t border-slate-800 text-[11px] text-slate-400">
782
+ <span>Confidence Level:</span>
783
+ <span className="text-emerald-400 font-mono font-bold">
784
+ {Math.round((selectedFact.confidence || 0.95) * 100)}% Verified
785
+ </span>
786
+ </div>
787
+ </div>
788
 
789
+ {/* Cryptographic Git Lineage / "Git Blame" */}
790
+ <div className="space-y-3">
791
+ <div className="flex items-center space-x-2 text-xs font-bold text-white">
792
+ <GitCommit className="w-4 h-4 text-emerald-400" />
793
+ <span>Cryptographic Git Lineage & Provenance</span>
794
+ </div>
795
 
796
+ <div className="bg-[#111724] border border-slate-800 rounded-xl p-4 space-y-3 text-xs">
797
+ <div className="flex items-center justify-between border-b border-slate-800/80 pb-2">
798
+ <span className="text-slate-400">Commit SHA</span>
799
+ <span className="font-mono text-emerald-400 bg-slate-900 px-2 py-0.5 rounded border border-slate-800">
800
+ commit_{selectedFact.id ? selectedFact.id.slice(0, 8) : '8f3c1a9'}
801
+ </span>
802
  </div>
803
 
804
+ <div className="flex items-center justify-between border-b border-slate-800/80 pb-2">
805
+ <span className="text-slate-400">Source Protocol Document</span>
806
+ <span className="text-slate-200 font-semibold">{selectedFact.filename || 'Clinical_Guideline.pdf'}</span>
807
+ </div>
808
+
809
+ <div className="flex items-center justify-between border-b border-slate-800/80 pb-2">
810
+ <span className="text-slate-400">Evidence Citation</span>
811
+ <span className="text-slate-300 font-mono text-[11px]">Section 2.1, Baseline Protocol</span>
812
+ </div>
813
+
814
+ <div className="flex items-center justify-between">
815
+ <span className="text-slate-400">Committed Branch</span>
816
+ <span className="text-emerald-400 font-mono font-bold">refs/heads/main</span>
817
+ </div>
818
+ </div>
819
+ </div>
820
+
821
+ {/* CI Policy Verification Badges */}
822
+ <div className="space-y-2.5">
823
+ <span className="text-[10px] font-mono text-slate-400 uppercase font-semibold">Automated Quality Gates Passed</span>
824
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 text-xs">
825
+ <div className="p-2.5 rounded-lg bg-[#111724] border border-slate-800 flex items-center space-x-2">
826
+ <CheckCircle2 className="w-3.5 h-3.5 text-emerald-400 shrink-0" />
827
+ <span className="text-slate-300 text-[11px]">Confidence Floor &ge; 85%</span>
828
+ </div>
829
+ <div className="p-2.5 rounded-lg bg-[#111724] border border-slate-800 flex items-center space-x-2">
830
+ <CheckCircle2 className="w-3.5 h-3.5 text-emerald-400 shrink-0" />
831
+ <span className="text-slate-300 text-[11px]">Mandatory Provenance Citation</span>
832
+ </div>
833
+ <div className="p-2.5 rounded-lg bg-[#111724] border border-slate-800 flex items-center space-x-2">
834
+ <CheckCircle2 className="w-3.5 h-3.5 text-emerald-400 shrink-0" />
835
+ <span className="text-slate-300 text-[11px]">GCP Safety SLA (24h)</span>
836
+ </div>
837
+ <div className="p-2.5 rounded-lg bg-[#111724] border border-slate-800 flex items-center space-x-2">
838
+ <CheckCircle2 className="w-3.5 h-3.5 text-emerald-400 shrink-0" />
839
+ <span className="text-slate-300 text-[11px]">Statistical Claim Validity</span>
840
  </div>
841
  </div>
842
+ </div>
843
+
844
+ {/* Lifecycle Stepper */}
845
+ <div className="space-y-2.5">
846
+ <span className="text-[10px] font-mono text-slate-400 uppercase font-semibold">Lifecycle Traceability</span>
847
+ <div className="space-y-2 text-xs text-slate-400">
848
+ <div className="flex items-center space-x-2.5">
849
+ <div className="w-5 h-5 rounded-full bg-emerald-500/20 text-emerald-400 flex items-center justify-center text-[10px] font-bold">1</div>
850
+ <span>Extracted by Neural Pipeline from source document</span>
851
+ </div>
852
+ <div className="flex items-center space-x-2.5">
853
+ <div className="w-5 h-5 rounded-full bg-emerald-500/20 text-emerald-400 flex items-center justify-center text-[10px] font-bold">2</div>
854
+ <span>Reviewed & approved via Peer Knowledge PR</span>
855
+ </div>
856
+ <div className="flex items-center space-x-2.5">
857
+ <div className="w-5 h-5 rounded-full bg-emerald-500/20 text-emerald-400 flex items-center justify-center text-[10px] font-bold">3</div>
858
+ <span className="text-emerald-300 font-semibold">Committed into immutable Master Truth Register</span>
859
+ </div>
860
+ </div>
861
+ </div>
862
+ </div>
863
+
864
+ {/* Drawer Actions */}
865
+ <div className="pt-6 border-t border-slate-800/80 flex items-center justify-end space-x-3">
866
+ <button
867
+ type="button"
868
+ onClick={() => {
869
+ handleCopy(selectedFact.value, selectedFact.id);
870
+ }}
871
+ className="px-3.5 py-2 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-300 font-semibold text-xs transition flex items-center space-x-1.5"
872
+ >
873
+ <Copy className="w-3.5 h-3.5" />
874
+ <span>Copy Fact</span>
875
+ </button>
876
+
877
+ <button
878
+ type="button"
879
+ onClick={() => {
880
+ setSelectedFact(null);
881
+ openRevision(selectedFact);
882
+ }}
883
+ className="px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-semibold text-xs transition flex items-center space-x-1.5 shadow-lg shadow-emerald-500/20"
884
+ >
885
+ <Edit3 className="w-3.5 h-3.5" />
886
+ <span>Propose Revision (PR)</span>
887
+ </button>
888
+ </div>
889
+ </div>
890
+ </div>
891
+ )}
892
+
893
+ {/* =================================================================== */}
894
+ {/* 7. PROPOSE REVISION MODAL */}
895
+ {/* =================================================================== */}
896
+ {showReviseModal && factToRevise && (
897
+ <div className="fixed inset-0 z-50 overflow-y-auto flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm">
898
+ <div className="relative w-full max-w-lg bg-[#0C111C] border border-slate-800 rounded-2xl p-6 space-y-5 shadow-2xl">
899
+ <div className="flex items-center justify-between border-b border-slate-800 pb-3">
900
+ <div className="flex items-center space-x-2">
901
+ <Edit3 className="w-4 h-4 text-emerald-400" />
902
+ <h3 className="text-sm font-bold text-white">Propose Fact Revision (Knowledge PR)</h3>
903
+ </div>
904
+ <button
905
+ onClick={() => setShowReviseModal(false)}
906
+ className="text-slate-400 hover:text-white transition"
907
+ >
908
+ <X className="w-4 h-4" />
909
+ </button>
910
+ </div>
911
+
912
+ <form onSubmit={submitRevision} className="space-y-4 text-xs">
913
+ <div className="space-y-1">
914
+ <label className="text-slate-300 font-semibold">Fact Title</label>
915
+ <input
916
+ type="text"
917
+ value={revisionTitle}
918
+ onChange={(e) => setRevisionTitle(e.target.value)}
919
+ required
920
+ className="w-full bg-[#131926] border border-slate-800 rounded-xl px-3 py-2 text-slate-200 focus:outline-none focus:ring-1 focus:ring-emerald-500"
921
+ />
922
+ </div>
923
+
924
+ <div className="space-y-1">
925
+ <label className="text-slate-300 font-semibold">Existing Committed Assertion (Current Main)</label>
926
+ <div className="p-2.5 rounded-lg bg-[#111724] border border-slate-800 text-slate-400 text-[11px] font-mono">
927
+ {factToRevise.value}
928
+ </div>
929
+ </div>
930
+
931
+ <div className="space-y-1">
932
+ <label className="text-slate-300 font-semibold">Proposed Revised Assertion</label>
933
+ <textarea
934
+ rows={3}
935
+ value={revisionValue}
936
+ onChange={(e) => setRevisionValue(e.target.value)}
937
+ required
938
+ placeholder="Enter updated clinical assertion or guideline standard..."
939
+ className="w-full bg-[#131926] border border-slate-800 rounded-xl p-3 text-slate-200 focus:outline-none focus:ring-1 focus:ring-emerald-500"
940
+ />
941
+ </div>
942
+
943
+ <div className="space-y-1">
944
+ <label className="text-slate-300 font-semibold">Clinical / Reviewer Rationale</label>
945
+ <input
946
+ type="text"
947
+ value={revisionRationale}
948
+ onChange={(e) => setRevisionRationale(e.target.value)}
949
+ required
950
+ placeholder="e.g. Updated per AHA/ACC 2026 guidelines."
951
+ className="w-full bg-[#131926] border border-slate-800 rounded-xl px-3 py-2 text-slate-200 focus:outline-none focus:ring-1 focus:ring-emerald-500"
952
+ />
953
+ </div>
954
+
955
+ <div className="pt-2 flex items-center justify-end space-x-2">
956
+ <button
957
+ type="button"
958
+ onClick={() => setShowReviseModal(false)}
959
+ className="px-4 py-2 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-300 font-semibold transition"
960
+ >
961
+ Cancel
962
+ </button>
963
+ <button
964
+ type="submit"
965
+ disabled={submittingRevision}
966
+ className="px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-semibold transition flex items-center space-x-1.5 shadow-lg shadow-emerald-500/20 disabled:opacity-50"
967
+ >
968
+ <GitPullRequest className="w-3.5 h-3.5" />
969
+ <span>{submittingRevision ? 'Creating PR...' : 'Open Knowledge PR'}</span>
970
+ </button>
971
+ </div>
972
+ </form>
973
+ </div>
974
+ </div>
975
+ )}
976
+
977
+ {/* =================================================================== */}
978
+ {/* 8. AI & AGENT INTEGRATION HUB MODAL */}
979
+ {/* =================================================================== */}
980
+ {showExportHub && (
981
+ <div className="fixed inset-0 z-50 overflow-y-auto flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm">
982
+ <div className="relative w-full max-w-2xl bg-[#0C111C] border border-slate-800 rounded-2xl p-6 space-y-5 shadow-2xl">
983
+ <div className="flex items-center justify-between border-b border-slate-800 pb-3">
984
+ <div className="flex items-center space-x-2">
985
+ <Bot className="w-5 h-5 text-blue-400" />
986
+ <div>
987
+ <h3 className="text-sm font-bold text-white">AI & Agent Integration Hub</h3>
988
+ <p className="text-[11px] text-slate-400">Ground LLMs and autonomous agents on verified truth.</p>
989
+ </div>
990
+ </div>
991
+ <button
992
+ onClick={() => setShowExportHub(false)}
993
+ className="text-slate-400 hover:text-white transition"
994
+ >
995
+ <X className="w-4 h-4" />
996
+ </button>
997
+ </div>
998
+
999
+ {/* Hub Format Tabs */}
1000
+ <div className="flex items-center border-b border-slate-800 text-xs">
1001
+ <button
1002
+ onClick={() => setExportTab('prompt')}
1003
+ className={`px-3.5 py-2 font-semibold transition border-b-2 flex items-center space-x-1.5 ${
1004
+ exportTab === 'prompt' ? 'border-blue-500 text-blue-400' : 'border-transparent text-slate-400 hover:text-white'
1005
+ }`}
1006
+ >
1007
+ <Bot className="w-3.5 h-3.5" />
1008
+ <span>LLM System Prompt</span>
1009
+ </button>
1010
+
1011
+ <button
1012
+ onClick={() => setExportTab('mcp')}
1013
+ className={`px-3.5 py-2 font-semibold transition border-b-2 flex items-center space-x-1.5 ${
1014
+ exportTab === 'mcp' ? 'border-emerald-500 text-emerald-400' : 'border-transparent text-slate-400 hover:text-white'
1015
+ }`}
1016
+ >
1017
+ <Terminal className="w-3.5 h-3.5" />
1018
+ <span>FastMCP Tool Client</span>
1019
+ </button>
1020
+
1021
+ <button
1022
+ onClick={() => setExportTab('markdown')}
1023
+ className={`px-3.5 py-2 font-semibold transition border-b-2 flex items-center space-x-1.5 ${
1024
+ exportTab === 'markdown' ? 'border-violet-500 text-violet-400' : 'border-transparent text-slate-400 hover:text-white'
1025
+ }`}
1026
+ >
1027
+ <FileText className="w-3.5 h-3.5" />
1028
+ <span>Markdown Truth Spec</span>
1029
+ </button>
1030
+
1031
+ <button
1032
+ onClick={() => setExportTab('json')}
1033
+ className={`px-3.5 py-2 font-semibold transition border-b-2 flex items-center space-x-1.5 ${
1034
+ exportTab === 'json' ? 'border-amber-500 text-amber-400' : 'border-transparent text-slate-400 hover:text-white'
1035
+ }`}
1036
+ >
1037
+ <Code2 className="w-3.5 h-3.5" />
1038
+ <span>JSON Vector Schema</span>
1039
+ </button>
1040
+ </div>
1041
+
1042
+ {/* Code / Content Area */}
1043
+ <div className="relative bg-[#090D15] border border-slate-800/80 rounded-xl p-4 font-mono text-[11px] text-slate-300 max-h-72 overflow-y-auto">
1044
+ <pre className="whitespace-pre-wrap">{getExportText()}</pre>
1045
+ </div>
1046
+
1047
+ {/* Modal Actions */}
1048
+ <div className="flex items-center justify-between pt-2">
1049
+ <span className="text-[11px] text-slate-500">
1050
+ {exportTab === 'prompt' && 'Paste into ChatGPT, Claude, or Gemini system prompts to eliminate hallucinations.'}
1051
+ {exportTab === 'mcp' && 'Python client code to integrate this workspace into LangChain, AutoGen, or LangGraph.'}
1052
+ {exportTab === 'markdown' && 'Clean tabular spec ready for GitHub READMEs or clinical documentation.'}
1053
+ {exportTab === 'json' && 'Raw structured JSON suitable for vector indexing and embeddings.'}
1054
+ </span>
1055
+
1056
+ <div className="flex items-center space-x-2">
1057
+ <button
1058
+ type="button"
1059
+ onClick={copyExportContent}
1060
+ className="px-4 py-2 rounded-xl bg-blue-600 hover:bg-blue-500 text-white font-semibold text-xs transition flex items-center space-x-1.5 shadow-lg shadow-blue-500/20"
1061
+ >
1062
+ {copiedExport ? <Check className="w-3.5 h-3.5 text-emerald-300" /> : <Copy className="w-3.5 h-3.5" />}
1063
+ <span>{copiedExport ? 'Copied to Clipboard!' : 'Copy to Clipboard'}</span>
1064
+ </button>
1065
+ </div>
1066
+ </div>
1067
  </div>
1068
  </div>
1069
  )}
1070
  </div>
1071
  );
1072
+
1073
+ // Helper function to render items list either in Card View or Table View
1074
+ function renderItemsList(items) {
1075
+ if (viewMode === 'table') {
1076
+ return (
1077
+ <div className="bg-[#0D121F] border border-slate-800 rounded-2xl overflow-hidden shadow-sm">
1078
+ <div className="overflow-x-auto">
1079
+ <table className="w-full text-left border-collapse text-xs">
1080
+ <thead>
1081
+ <tr className="border-b border-slate-800/80 bg-[#101626] text-slate-400 font-mono text-[11px]">
1082
+ <th className="p-3">Fact Title</th>
1083
+ <th className="p-3">Type</th>
1084
+ <th className="p-3">Committed Finding / Value</th>
1085
+ <th className="p-3">Confidence</th>
1086
+ <th className="p-3">Status</th>
1087
+ <th className="p-3">Source Document</th>
1088
+ <th className="p-3 text-right">Actions</th>
1089
+ </tr>
1090
+ </thead>
1091
+ <tbody className="divide-y divide-slate-800/60">
1092
+ {items.map((item) => {
1093
+ const isPending = item.status && item.status.toUpperCase() === 'PENDING';
1094
+ return (
1095
+ <tr
1096
+ key={item.id}
1097
+ onClick={() => setSelectedFact(item)}
1098
+ className="hover:bg-[#121828] transition cursor-pointer"
1099
+ >
1100
+ <td className="p-3 font-semibold text-white whitespace-nowrap">{item.title}</td>
1101
+ <td className="p-3">
1102
+ <span className="text-[10px] font-mono px-2 py-0.5 rounded font-bold bg-slate-800 text-slate-300 border border-slate-700">
1103
+ {item.type || 'CLAIM'}
1104
+ </span>
1105
+ </td>
1106
+ <td className="p-3 text-slate-300 max-w-xs truncate">{item.value}</td>
1107
+ <td className="p-3 font-mono text-emerald-400 whitespace-nowrap">
1108
+ {Math.round((item.confidence || 0.95) * 100)}%
1109
+ </td>
1110
+ <td className="p-3 whitespace-nowrap">
1111
+ {isPending ? (
1112
+ <span className="text-[10px] font-mono px-2 py-0.5 rounded font-semibold bg-amber-500/10 text-amber-400 border border-amber-500/30">
1113
+ PENDING PR
1114
+ </span>
1115
+ ) : (
1116
+ <span className="text-[10px] font-mono px-2 py-0.5 rounded font-semibold bg-emerald-500/10 text-emerald-400 border border-emerald-500/30">
1117
+ COMMITTED
1118
+ </span>
1119
+ )}
1120
+ </td>
1121
+ <td className="p-3 text-slate-400 font-mono text-[11px] whitespace-nowrap">
1122
+ {item.filename || 'Clinical_Guideline.pdf'}
1123
+ </td>
1124
+ <td className="p-3 text-right whitespace-nowrap">
1125
+ <div className="flex items-center justify-end space-x-1" onClick={(e) => e.stopPropagation()}>
1126
+ <button
1127
+ onClick={() => openRevision(item)}
1128
+ className="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white transition"
1129
+ title="Propose Revision"
1130
+ >
1131
+ <Edit3 className="w-3.5 h-3.5" />
1132
+ </button>
1133
+ <button
1134
+ onClick={() => handleCopy(item.value, item.id)}
1135
+ className="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white transition"
1136
+ title="Copy Value"
1137
+ >
1138
+ <Copy className="w-3.5 h-3.5" />
1139
+ </button>
1140
+ </div>
1141
+ </td>
1142
+ </tr>
1143
+ );
1144
+ })}
1145
+ </tbody>
1146
+ </table>
1147
+ </div>
1148
+ </div>
1149
+ );
1150
+ }
1151
+
1152
+ // Card View (Default)
1153
+ return (
1154
+ <div className="bg-[#0D121F] border border-slate-800 rounded-2xl overflow-hidden shadow-sm">
1155
+ <div className="divide-y divide-slate-800/80">
1156
+ {items.map((item) => {
1157
+ const isPending = item.status && item.status.toUpperCase() === 'PENDING';
1158
+ return (
1159
+ <div
1160
+ key={item.id}
1161
+ onClick={() => setSelectedFact(item)}
1162
+ className="p-4 sm:p-5 hover:bg-[#121828] transition flex flex-col md:flex-row md:items-start justify-between gap-4 cursor-pointer group"
1163
+ >
1164
+ <div className="space-y-2 max-w-3xl">
1165
+ <div className="flex flex-wrap items-center gap-2">
1166
+ <span className="text-xs font-bold text-white group-hover:text-emerald-300 transition">
1167
+ {item.title}
1168
+ </span>
1169
+
1170
+ <span className="text-[10px] uppercase font-mono px-2 py-0.5 rounded font-bold bg-slate-800 text-slate-300 border border-slate-700">
1171
+ {item.type || 'CLAIM'}
1172
+ </span>
1173
+
1174
+ {isPending ? (
1175
+ <span className="text-[10px] font-mono px-2 py-0.5 rounded font-semibold bg-amber-500/10 text-amber-400 border border-amber-500/30 flex items-center space-x-1">
1176
+ <GitPullRequest className="w-3 h-3 inline mr-1" />
1177
+ <span>STAGED PR (PENDING)</span>
1178
+ </span>
1179
+ ) : (
1180
+ <span className="text-[10px] font-mono px-2 py-0.5 rounded font-semibold bg-emerald-500/10 text-emerald-400 border border-emerald-500/30 flex items-center space-x-1">
1181
+ <CheckCircle2 className="w-3 h-3 inline mr-1" />
1182
+ <span>COMMITTED (MAIN)</span>
1183
+ </span>
1184
+ )}
1185
+
1186
+ <span className="text-emerald-400 font-mono text-[11px] font-semibold">
1187
+ {Math.round((item.confidence || 0.95) * 100)}% Conf
1188
+ </span>
1189
+ </div>
1190
+
1191
+ <p className="text-xs text-slate-300 leading-relaxed font-sans">{item.value}</p>
1192
+
1193
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-[11px] text-slate-500 font-mono">
1194
+ <span>ID: {item.id ? item.id.slice(0, 8) : 'unknown'}</span>
1195
+ <span>Source: {item.filename || 'Clinical_Guideline.pdf'}</span>
1196
+ <span className="text-slate-600">|</span>
1197
+ <span className="text-slate-400 flex items-center space-x-1">
1198
+ <Clock className="w-3 h-3 mr-1 inline" />
1199
+ <span>Click to view Git blame & provenance</span>
1200
+ </span>
1201
+ </div>
1202
+ </div>
1203
+
1204
+ <div
1205
+ className="flex items-center space-x-2 shrink-0 pt-1"
1206
+ onClick={(e) => e.stopPropagation()}
1207
+ >
1208
+ <button
1209
+ onClick={() => openRevision(item)}
1210
+ className="px-2.5 py-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 hover:text-white transition text-xs font-semibold flex items-center space-x-1.5"
1211
+ title="Propose Revision (Open PR)"
1212
+ >
1213
+ <Edit3 className="w-3.5 h-3.5 text-amber-400" />
1214
+ <span className="hidden sm:inline">Revise</span>
1215
+ </button>
1216
+
1217
+ <button
1218
+ onClick={() => handleCopy(item.value, item.id)}
1219
+ className="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white transition"
1220
+ title="Copy Value"
1221
+ >
1222
+ <Copy className="w-3.5 h-3.5" />
1223
+ </button>
1224
+
1225
+ {copiedId === item.id && (
1226
+ <span className="text-[10px] text-emerald-400 font-mono">Copied!</span>
1227
+ )}
1228
+ </div>
1229
+ </div>
1230
+ );
1231
+ })}
1232
+ </div>
1233
+ </div>
1234
+ );
1235
+ }
1236
  }
studio/src/components/KnowledgeGraph.jsx CHANGED
@@ -10,41 +10,86 @@ import {
10
  Sparkles,
11
  Link2,
12
  FileText,
13
- Info
 
 
 
 
 
 
 
 
 
 
 
 
14
  } from 'lucide-react';
15
 
16
- export default function KnowledgeGraph({ graphData, loading }) {
17
  const [zoom, setZoom] = useState(1);
18
  const [searchQuery, setSearchQuery] = useState('');
19
  const [selectedNode, setSelectedNode] = useState(null);
20
  const [filterType, setFilterType] = useState('ALL');
 
 
21
 
22
  const rawNodes = graphData?.nodes || [];
23
  const rawEdges = graphData?.edges || [];
24
 
25
- // Filter nodes based on type and search query
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  const filteredNodes = useMemo(() => {
27
  return rawNodes.filter((n) => {
28
- const matchesType = filterType === 'ALL' || n.type === filterType;
 
 
 
 
 
 
 
 
 
29
  const matchesSearch =
30
- !searchQuery ||
31
- n.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
32
- String(n.value || '').toLowerCase().includes(searchQuery.toLowerCase());
 
 
33
  return matchesType && matchesSearch;
34
  });
35
  }, [rawNodes, filterType, searchQuery]);
36
 
37
- // Generate deterministic circular / force layout coordinates
38
  const positionedNodes = useMemo(() => {
39
  const total = filteredNodes.length;
40
  if (total === 0) return [];
41
 
42
  const centerX = 400;
43
  const centerY = 300;
44
- const radius = Math.min(centerX, centerY) - 80;
45
 
46
  return filteredNodes.map((node, i) => {
47
- // Golden angle distribution for natural cluster spread
48
  const angle = (i * 2.399963) % (2 * Math.PI);
49
  const r = 40 + (radius - 40) * Math.sqrt((i + 1) / total);
50
  const x = centerX + r * Math.cos(angle);
@@ -61,20 +106,64 @@ export default function KnowledgeGraph({ graphData, loading }) {
61
  return map;
62
  }, [positionedNodes]);
63
 
64
- const getNodeColor = (type) => {
65
- switch (type) {
66
- case 'ENTITY':
67
- return '#06B6D4'; // Cyan
 
 
 
 
 
 
 
 
68
  case 'CLAIM':
69
- return '#8B5CF6'; // Violet
 
 
 
 
 
 
 
70
  case 'METRIC':
71
- return '#10B981'; // Emerald
72
- case 'DATE':
73
- return '#F59E0B'; // Amber
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  case 'PROPOSAL':
75
- return '#EC4899'; // Pink
 
 
 
 
 
 
 
76
  default:
77
- return '#3B82F6'; // Blue
 
 
 
 
 
 
 
78
  }
79
  };
80
 
@@ -82,252 +171,516 @@ export default function KnowledgeGraph({ graphData, loading }) {
82
  return (
83
  <div className="flex flex-col items-center justify-center py-24 space-y-4">
84
  <div className="w-8 h-8 border-2 border-emerald-500 border-t-transparent rounded-full animate-spin"></div>
85
- <p className="text-xs text-slate-400 font-mono">Building Knowledge Topology Graph...</p>
86
  </div>
87
  );
88
  }
89
 
90
  return (
91
  <div className="space-y-6">
92
- {/* Graph Control Bar */}
93
- <div className="bg-[#0C101A] border border-slate-800/90 rounded-xl p-4 flex flex-col sm:flex-row sm:items-center justify-between gap-4">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  <div className="flex items-center space-x-3">
95
  <Network className="w-5 h-5 text-emerald-400" />
96
- <h2 className="text-sm font-semibold text-white">Knowledge Graph Topology</h2>
97
  <span className="text-xs px-2 py-0.5 rounded bg-slate-800 text-slate-300 font-mono">
98
- {positionedNodes.length} nodes • {rawEdges.length} edges
99
  </span>
100
  </div>
101
 
102
- <div className="flex items-center space-x-3 text-xs">
103
  {/* Node Search Bar */}
104
  <div className="relative">
105
  <Search className="w-3.5 h-3.5 text-slate-500 absolute left-2.5 top-2.5" />
106
  <input
107
  type="text"
108
- placeholder="Search graph..."
109
  value={searchQuery}
110
  onChange={(e) => setSearchQuery(e.target.value)}
111
- className="bg-[#141B2D] border border-slate-800 rounded-lg pl-8 pr-3 py-1.5 text-xs text-slate-200 focus:outline-none focus:ring-1 focus:ring-emerald-500 w-44"
112
  />
113
  </div>
114
 
115
- {/* Type Filter */}
116
  <select
117
  value={filterType}
118
  onChange={(e) => setFilterType(e.target.value)}
119
  className="bg-[#141B2D] border border-slate-800 rounded-lg px-2.5 py-1.5 text-xs text-slate-300 focus:outline-none"
120
  >
121
- <option value="ALL">All Types</option>
122
- <option value="CLAIM">Claims</option>
123
- <option value="METRIC">Metrics</option>
124
- <option value="ENTITY">Entities</option>
125
- <option value="PROPOSAL">Pending PRs</option>
 
126
  </select>
127
 
128
- {/* Zoom Controls */}
129
  <div className="flex items-center bg-[#141B2D] border border-slate-800 rounded-lg p-0.5">
130
  <button
131
- onClick={() => setZoom((z) => Math.min(z + 0.15, 2.0))}
132
- className="p-1.5 hover:text-white text-slate-400 transition"
133
- title="Zoom In"
 
 
134
  >
135
- <ZoomIn className="w-3.5 h-3.5" />
 
136
  </button>
137
  <button
138
- onClick={() => setZoom((z) => Math.max(z - 0.15, 0.6))}
139
- className="p-1.5 hover:text-white text-slate-400 transition"
140
- title="Zoom Out"
 
 
141
  >
142
- <ZoomOut className="w-3.5 h-3.5" />
143
- </button>
144
- <button
145
- onClick={() => setZoom(1)}
146
- className="p-1.5 hover:text-white text-slate-400 transition"
147
- title="Reset Zoom"
148
- >
149
- <RotateCcw className="w-3.5 h-3.5" />
150
  </button>
151
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  </div>
153
  </div>
154
 
155
- {/* Main Canvas & Detail Drawer Grid */}
156
- <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
157
- {/* SVG Canvas (8 Cols) */}
158
- <div className="lg:col-span-8 bg-[#090D16] border border-slate-800/80 rounded-2xl p-4 overflow-hidden relative min-h-[560px] flex items-center justify-center">
159
- {/* Interactive SVG */}
160
- <svg
161
- viewBox="0 0 800 600"
162
- className="w-full h-full transition-transform duration-200 cursor-grab active:cursor-grabbing"
163
- style={{ transform: `scale(${zoom})` }}
164
- >
165
- {/* Background Grid Pattern */}
166
- <defs>
167
- <pattern id="graphGrid" width="40" height="40" patternUnits="userSpaceOnUse">
168
- <path d="M 40 0 L 0 0 0 40" fill="none" stroke="#161F32" strokeWidth="0.8" />
169
- </pattern>
170
- </defs>
171
- <rect width="100%" height="100%" fill="url(#graphGrid)" />
172
-
173
- {/* Edges */}
174
- {rawEdges.map((edge, idx) => {
175
- const src = nodeMap[edge.source];
176
- const tgt = nodeMap[edge.target];
177
- if (!src || !tgt) return null;
178
-
179
- const isHighlighted = selectedNode && (selectedNode.id === src.id || selectedNode.id === tgt.id);
180
-
181
- return (
182
- <g key={edge.id || idx}>
183
- <line
184
- x1={src.x}
185
- y1={src.y}
186
- x2={tgt.x}
187
- y2={tgt.y}
188
- stroke={isHighlighted ? '#10B981' : '#334155'}
189
- strokeWidth={isHighlighted ? 2.5 : 1.2}
190
- strokeDasharray={edge.relationship === 'PROPOSED_UPDATE' ? '4 3' : 'none'}
191
- opacity={isHighlighted ? 0.9 : 0.4}
192
- />
193
- </g>
194
- );
195
- })}
196
-
197
- {/* Nodes */}
198
- {positionedNodes.map((node) => {
199
- const isSelected = selectedNode?.id === node.id;
200
- const color = getNodeColor(node.type);
201
-
202
- return (
203
- <g
204
- key={node.id}
205
- transform={`translate(${node.x}, ${node.y})`}
206
- onClick={() => setSelectedNode(node)}
207
- className="cursor-pointer group"
208
- >
209
- {/* Glow circle on select */}
210
- {isSelected && (
211
- <circle r="22" fill="none" stroke={color} strokeWidth="2.5" opacity="0.8" className="animate-pulse" />
212
- )}
213
-
214
- {/* Node Circle */}
215
- <circle
216
- r={node.type === 'PROPOSAL' ? 14 : 12}
217
- fill="#0D121F"
218
- stroke={color}
219
- strokeWidth={isSelected ? 3 : 2}
220
- strokeDasharray={node.type === 'PROPOSAL' ? '3 2' : 'none'}
221
- className="transition hover:scale-125"
222
- />
223
-
224
- {/* Inner Type Indicator Dot */}
225
- <circle r="4" fill={color} />
226
-
227
- {/* Node Label Text */}
228
- <text
229
- y="24"
230
- textAnchor="middle"
231
- fill={isSelected ? '#F8FAFC' : '#94A3B8'}
232
- fontSize="9.5"
233
- fontFamily="Inter, sans-serif"
234
- fontWeight={isSelected ? '600' : '400'}
235
- className="select-none pointer-events-none"
236
  >
237
- {node.title.length > 22 ? node.title.slice(0, 20) + '...' : node.title}
238
- </text>
239
- </g>
240
- );
241
- })}
242
- </svg>
243
-
244
- {/* Color Legend Overlay */}
245
- <div className="absolute bottom-4 left-4 bg-[#0E1422]/90 backdrop-blur-sm border border-slate-800 rounded-xl p-3 text-[11px] font-mono flex items-center space-x-3">
246
- <span className="flex items-center space-x-1">
247
- <span className="w-2.5 h-2.5 rounded-full bg-cyan-400"></span>
248
- <span className="text-slate-300">Entity</span>
249
- </span>
250
- <span className="flex items-center space-x-1">
251
- <span className="w-2.5 h-2.5 rounded-full bg-violet-400"></span>
252
- <span className="text-slate-300">Claim</span>
253
- </span>
254
- <span className="flex items-center space-x-1">
255
- <span className="w-2.5 h-2.5 rounded-full bg-emerald-400"></span>
256
- <span className="text-slate-300">Metric</span>
257
- </span>
258
- <span className="flex items-center space-x-1">
259
- <span className="w-2.5 h-2.5 rounded-full bg-pink-400 border border-dashed border-pink-300"></span>
260
- <span className="text-slate-300">PR Delta</span>
261
- </span>
262
- </div>
263
- </div>
264
 
265
- {/* Selected Node Details Drawer (4 Cols) */}
266
- <div className="lg:col-span-4 bg-[#0D121F] border border-slate-800 rounded-2xl p-6 space-y-4">
267
- <div className="flex items-center space-x-2 pb-3 border-b border-slate-800 text-xs text-slate-400">
268
- <Info className="w-4 h-4 text-emerald-400" />
269
- <span className="font-semibold text-white">Node Provenance Inspector</span>
270
- </div>
 
 
 
 
 
 
271
 
272
- {selectedNode ? (
273
- <div className="space-y-4 text-xs font-mono">
274
- <div>
275
- <span className="text-[10px] text-slate-500 uppercase tracking-wider block">Identifier</span>
276
- <span className="text-slate-300 font-semibold">{selectedNode.id}</span>
 
 
 
 
 
 
 
 
 
277
  </div>
 
278
 
279
- <div>
280
- <span className="text-[10px] text-slate-500 uppercase tracking-wider block mb-1">Classification Type</span>
281
- <span
282
- className="px-2 py-0.5 rounded text-[11px] font-bold"
283
- style={{
284
- backgroundColor: `${getNodeColor(selectedNode.type)}20`,
285
- color: getNodeColor(selectedNode.type),
286
- border: `1px solid ${getNodeColor(selectedNode.type)}40`,
287
- }}
288
- >
289
- {selectedNode.type}
290
  </span>
291
  </div>
 
292
 
293
- <div>
294
- <span className="text-[10px] text-slate-500 uppercase tracking-wider block mb-1">Fact Statement</span>
295
- <div className="bg-[#141B2D] p-3 rounded-lg border border-slate-800 text-slate-200 leading-relaxed font-sans text-xs">
296
- {selectedNode.value || selectedNode.title}
297
- </div>
 
 
 
 
 
 
 
 
 
 
 
298
  </div>
 
299
 
300
- <div className="grid grid-cols-2 gap-2 text-[11px] pt-1">
301
- <div className="bg-[#141B2D] p-2 rounded border border-slate-800">
302
- <span className="text-slate-500 block text-[10px]">Confidence</span>
303
- <span className="text-emerald-400 font-bold">
304
- {Math.round((selectedNode.confidence || 0.95) * 100)}%
305
- </span>
306
- </div>
307
- <div className="bg-[#141B2D] p-2 rounded border border-slate-800">
308
- <span className="text-slate-500 block text-[10px]">State</span>
309
- <span className="text-slate-300 font-semibold">{selectedNode.status || 'ACTIVE'}</span>
310
  </div>
 
 
 
311
  </div>
 
312
 
313
- {selectedNode.filename && (
314
- <div>
315
- <span className="text-[10px] text-slate-500 uppercase tracking-wider block mb-1">Source Document</span>
316
- <div className="flex items-center space-x-1.5 text-slate-300 bg-[#141B2D] p-2 rounded border border-slate-800 text-[11px]">
317
- <FileText className="w-3.5 h-3.5 text-slate-400" />
318
- <span className="truncate">{selectedNode.filename}</span>
 
 
 
 
 
 
 
 
 
 
 
319
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
321
  )}
322
  </div>
323
- ) : (
324
- <div className="py-16 text-center text-xs text-slate-500">
325
- <Network className="w-8 h-8 text-slate-700 mx-auto mb-2" />
326
- <p>Click on any node in the topology canvas to inspect its semantic provenance and connected relationships.</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
327
  </div>
328
  )}
329
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330
  </div>
331
- </div>
332
- );
333
  }
 
10
  Sparkles,
11
  Link2,
12
  FileText,
13
+ Info,
14
+ ShieldCheck,
15
+ CheckCircle2,
16
+ ArrowRight,
17
+ ExternalLink,
18
+ Layers,
19
+ Activity,
20
+ GitPullRequest,
21
+ BookOpen,
22
+ Filter,
23
+ Eye,
24
+ X,
25
+ HelpCircle
26
  } from 'lucide-react';
27
 
28
+ export default function KnowledgeGraph({ graphData, loading, onSelectTab }) {
29
  const [zoom, setZoom] = useState(1);
30
  const [searchQuery, setSearchQuery] = useState('');
31
  const [selectedNode, setSelectedNode] = useState(null);
32
  const [filterType, setFilterType] = useState('ALL');
33
+ const [displayMode, setDisplayMode] = useState('pipeline'); // 'pipeline' (hierarchical flow) | 'network' (constellation)
34
+ const [showGraphExplainer, setShowGraphExplainer] = useState(true);
35
 
36
  const rawNodes = graphData?.nodes || [];
37
  const rawEdges = graphData?.edges || [];
38
 
39
+ // Categorize nodes into intuitive medical layers
40
+ const categorized = useMemo(() => {
41
+ const docs = [];
42
+ const claims = [];
43
+ const metrics = [];
44
+ const rules = [];
45
+ const proposals = [];
46
+
47
+ rawNodes.forEach((n) => {
48
+ const t = String(n.type || '').toUpperCase();
49
+ if (t === 'DOCUMENT') docs.push(n);
50
+ else if (t === 'METRIC') metrics.push(n);
51
+ else if (t === 'CLAIM') claims.push(n);
52
+ else if (t === 'RULE' || t === 'SAFETY') rules.push(n);
53
+ else if (t === 'PROPOSAL') proposals.push(n);
54
+ else claims.push(n); // default
55
+ });
56
+
57
+ return { docs, claims, metrics, rules, proposals };
58
+ }, [rawNodes]);
59
+
60
+ // Filter nodes based on user search and category
61
  const filteredNodes = useMemo(() => {
62
  return rawNodes.filter((n) => {
63
+ const t = String(n.type || '').toUpperCase();
64
+ const matchesType =
65
+ filterType === 'ALL' ||
66
+ (filterType === 'DOCUMENTS' && t === 'DOCUMENT') ||
67
+ (filterType === 'CLAIMS' && t === 'CLAIM') ||
68
+ (filterType === 'METRICS' && t === 'METRIC') ||
69
+ (filterType === 'RULES' && (t === 'RULE' || t === 'SAFETY')) ||
70
+ (filterType === 'PROPOSALS' && t === 'PROPOSAL');
71
+
72
+ const q = searchQuery.toLowerCase().trim();
73
  const matchesSearch =
74
+ !q ||
75
+ (n.title || '').toLowerCase().includes(q) ||
76
+ String(n.value || '').toLowerCase().includes(q) ||
77
+ (n.filename || '').toLowerCase().includes(q);
78
+
79
  return matchesType && matchesSearch;
80
  });
81
  }, [rawNodes, filterType, searchQuery]);
82
 
83
+ // Generate constellation layout coordinates for Network view
84
  const positionedNodes = useMemo(() => {
85
  const total = filteredNodes.length;
86
  if (total === 0) return [];
87
 
88
  const centerX = 400;
89
  const centerY = 300;
90
+ const radius = Math.min(centerX, centerY) - 70;
91
 
92
  return filteredNodes.map((node, i) => {
 
93
  const angle = (i * 2.399963) % (2 * Math.PI);
94
  const r = 40 + (radius - 40) * Math.sqrt((i + 1) / total);
95
  const x = centerX + r * Math.cos(angle);
 
106
  return map;
107
  }, [positionedNodes]);
108
 
109
+ const getNodeTheme = (type) => {
110
+ const t = String(type || '').toUpperCase();
111
+ switch (t) {
112
+ case 'DOCUMENT':
113
+ return {
114
+ color: '#3B82F6', // Blue
115
+ bg: 'bg-blue-500/10',
116
+ border: 'border-blue-500/30',
117
+ badge: 'SOURCE DOCUMENT',
118
+ icon: FileText,
119
+ desc: 'Original medical guideline or clinical PDF.'
120
+ };
121
  case 'CLAIM':
122
+ return {
123
+ color: '#8B5CF6', // Violet
124
+ bg: 'bg-violet-500/10',
125
+ border: 'border-violet-500/30',
126
+ badge: 'CLINICAL ASSERTION',
127
+ icon: Activity,
128
+ desc: 'Verified clinical finding or standard of care.'
129
+ };
130
  case 'METRIC':
131
+ return {
132
+ color: '#10B981', // Emerald
133
+ bg: 'bg-emerald-500/10',
134
+ border: 'border-emerald-500/30',
135
+ badge: 'DOSING / THRESHOLD',
136
+ icon: Sparkles,
137
+ desc: 'Quantitative clinical threshold or numerical boundary.'
138
+ };
139
+ case 'RULE':
140
+ case 'SAFETY':
141
+ return {
142
+ color: '#F59E0B', // Amber
143
+ bg: 'bg-amber-500/10',
144
+ border: 'border-amber-500/30',
145
+ badge: 'SAFETY GUARDRAIL',
146
+ icon: ShieldCheck,
147
+ desc: 'Quality gate or regulatory constraint (e.g. GCP 24h SLA).'
148
+ };
149
  case 'PROPOSAL':
150
+ return {
151
+ color: '#EC4899', // Pink
152
+ bg: 'bg-pink-500/10',
153
+ border: 'border-pink-500/30',
154
+ badge: 'STAGED PULL REQUEST',
155
+ icon: GitPullRequest,
156
+ desc: 'Candidate assertion awaiting human peer review.'
157
+ };
158
  default:
159
+ return {
160
+ color: '#06B6D4', // Cyan
161
+ bg: 'bg-cyan-500/10',
162
+ border: 'border-cyan-500/30',
163
+ badge: 'MEDICAL ENTITY',
164
+ icon: Link2,
165
+ desc: 'Medical concept, drug, or classification.'
166
+ };
167
  }
168
  };
169
 
 
171
  return (
172
  <div className="flex flex-col items-center justify-center py-24 space-y-4">
173
  <div className="w-8 h-8 border-2 border-emerald-500 border-t-transparent rounded-full animate-spin"></div>
174
+ <p className="text-xs text-slate-400 font-mono">Building Knowledge Lineage Graph...</p>
175
  </div>
176
  );
177
  }
178
 
179
  return (
180
  <div className="space-y-6">
181
+ {/* =================================================================== */}
182
+ {/* 1. PLAIN-ENGLISH EDUCATIONAL BANNER (No Jargon) */}
183
+ {/* =================================================================== */}
184
+ {showGraphExplainer && (
185
+ <div className="bg-gradient-to-r from-[#0C121E] via-[#0E1526] to-[#0A101D] border border-emerald-500/20 rounded-2xl p-4 sm:p-5 relative shadow-lg">
186
+ <button
187
+ onClick={() => setShowGraphExplainer(false)}
188
+ className="absolute top-3.5 right-3.5 text-slate-500 hover:text-slate-300 transition"
189
+ title="Dismiss Explainer"
190
+ >
191
+ <X className="w-4 h-4" />
192
+ </button>
193
+
194
+ <div className="flex flex-col sm:flex-row sm:items-start space-y-3 sm:space-y-0 sm:space-x-4">
195
+ <div className="w-10 h-10 rounded-xl bg-emerald-500/10 border border-emerald-500/30 text-emerald-400 flex items-center justify-center shrink-0">
196
+ <Network className="w-5 h-5" />
197
+ </div>
198
+
199
+ <div className="space-y-1.5 max-w-4xl text-xs">
200
+ <div className="flex items-center space-x-2">
201
+ <span className="font-bold text-white text-sm">Medical Knowledge Lineage & Connections</span>
202
+ <span className="px-2 py-0.5 rounded bg-emerald-500/20 text-emerald-300 font-mono text-[10px] font-semibold border border-emerald-500/30">
203
+ Interactive Visual Map
204
+ </span>
205
+ </div>
206
+ <p className="text-slate-300 leading-relaxed">
207
+ Think of this as a <strong>family tree for clinical knowledge</strong>. Source medical documents (blue) sit at the root. DiffWeave extracts verified assertions (violet) and dosing cutoffs (emerald), which are automatically guarded by compliance rules (amber).
208
+ </p>
209
+ <div className="flex flex-wrap items-center gap-x-5 gap-y-1 pt-1 text-[11px] text-slate-400">
210
+ <span className="flex items-center space-x-1.5">
211
+ <span className="w-2.5 h-2.5 rounded-full bg-blue-500 inline-block"></span>
212
+ <span>1. Source Guidelines</span>
213
+ </span>
214
+ <span className="text-slate-600">&rarr;</span>
215
+ <span className="flex items-center space-x-1.5">
216
+ <span className="w-2.5 h-2.5 rounded-full bg-violet-500 inline-block"></span>
217
+ <span>2. Clinical Findings</span>
218
+ </span>
219
+ <span className="text-slate-600">&rarr;</span>
220
+ <span className="flex items-center space-x-1.5">
221
+ <span className="w-2.5 h-2.5 rounded-full bg-emerald-500 inline-block"></span>
222
+ <span>3. Dosing Thresholds</span>
223
+ </span>
224
+ <span className="text-slate-600">&rarr;</span>
225
+ <span className="flex items-center space-x-1.5">
226
+ <span className="w-2.5 h-2.5 rounded-full bg-amber-500 inline-block"></span>
227
+ <span>4. Safety Guardrails</span>
228
+ </span>
229
+ </div>
230
+ </div>
231
+ </div>
232
+ </div>
233
+ )}
234
+
235
+ {/* =================================================================== */}
236
+ {/* 2. GRAPH CONTROLS (Views, Search, Filters) */}
237
+ {/* =================================================================== */}
238
+ <div className="bg-[#0C101A] border border-slate-800/90 rounded-xl p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-4">
239
  <div className="flex items-center space-x-3">
240
  <Network className="w-5 h-5 text-emerald-400" />
241
+ <h2 className="text-sm font-semibold text-white">Knowledge Lineage</h2>
242
  <span className="text-xs px-2 py-0.5 rounded bg-slate-800 text-slate-300 font-mono">
243
+ {rawNodes.length} medical elements &bull; {rawEdges.length} connections
244
  </span>
245
  </div>
246
 
247
+ <div className="flex flex-wrap items-center gap-2.5 text-xs">
248
  {/* Node Search Bar */}
249
  <div className="relative">
250
  <Search className="w-3.5 h-3.5 text-slate-500 absolute left-2.5 top-2.5" />
251
  <input
252
  type="text"
253
+ placeholder="Search elements..."
254
  value={searchQuery}
255
  onChange={(e) => setSearchQuery(e.target.value)}
256
+ className="bg-[#141B2D] border border-slate-800 rounded-lg pl-8 pr-3 py-1.5 text-xs text-slate-200 focus:outline-none focus:ring-1 focus:ring-emerald-500 w-36 sm:w-44"
257
  />
258
  </div>
259
 
260
+ {/* Category Filter */}
261
  <select
262
  value={filterType}
263
  onChange={(e) => setFilterType(e.target.value)}
264
  className="bg-[#141B2D] border border-slate-800 rounded-lg px-2.5 py-1.5 text-xs text-slate-300 focus:outline-none"
265
  >
266
+ <option value="ALL">All Categories</option>
267
+ <option value="DOCUMENTS">Source Documents (Blue)</option>
268
+ <option value="CLAIMS">Clinical Assertions (Violet)</option>
269
+ <option value="METRICS">Dosing & Metrics (Emerald)</option>
270
+ <option value="RULES">Safety Guardrails (Amber)</option>
271
+ <option value="PROPOSALS">Staged PRs (Pink)</option>
272
  </select>
273
 
274
+ {/* View Mode Toggle: Lineage Pipeline vs Network Constellation */}
275
  <div className="flex items-center bg-[#141B2D] border border-slate-800 rounded-lg p-0.5">
276
  <button
277
+ onClick={() => setDisplayMode('pipeline')}
278
+ className={`px-2.5 py-1 rounded text-xs font-semibold transition flex items-center space-x-1.5 ${
279
+ displayMode === 'pipeline' ? 'bg-slate-700 text-white' : 'text-slate-400 hover:text-white'
280
+ }`}
281
+ title="Pipeline Flow: Left-to-right lineage tree"
282
  >
283
+ <Layers className="w-3.5 h-3.5" />
284
+ <span>Pipeline Flow</span>
285
  </button>
286
  <button
287
+ onClick={() => setDisplayMode('network')}
288
+ className={`px-2.5 py-1 rounded text-xs font-semibold transition flex items-center space-x-1.5 ${
289
+ displayMode === 'network' ? 'bg-slate-700 text-white' : 'text-slate-400 hover:text-white'
290
+ }`}
291
+ title="Network Constellation: Cluster canvas"
292
  >
293
+ <Network className="w-3.5 h-3.5" />
294
+ <span>Constellation</span>
 
 
 
 
 
 
295
  </button>
296
  </div>
297
+
298
+ {/* Zoom Controls (Network Mode Only) */}
299
+ {displayMode === 'network' && (
300
+ <div className="flex items-center bg-[#141B2D] border border-slate-800 rounded-lg p-0.5">
301
+ <button
302
+ onClick={() => setZoom((z) => Math.min(z + 0.15, 2.0))}
303
+ className="p-1.5 hover:text-white text-slate-400 transition"
304
+ title="Zoom In"
305
+ >
306
+ <ZoomIn className="w-3.5 h-3.5" />
307
+ </button>
308
+ <button
309
+ onClick={() => setZoom((z) => Math.max(z - 0.15, 0.6))}
310
+ className="p-1.5 hover:text-white text-slate-400 transition"
311
+ title="Zoom Out"
312
+ >
313
+ <ZoomOut className="w-3.5 h-3.5" />
314
+ </button>
315
+ <button
316
+ onClick={() => setZoom(1)}
317
+ className="p-1.5 hover:text-white text-slate-400 transition"
318
+ title="Reset Zoom"
319
+ >
320
+ <RotateCcw className="w-3.5 h-3.5" />
321
+ </button>
322
+ </div>
323
+ )}
324
  </div>
325
  </div>
326
 
327
+ {/* =================================================================== */}
328
+ {/* 3. MAIN VISUAL CANVAS: PIPELINE FLOW vs CONSTELLATION */}
329
+ {/* =================================================================== */}
330
+ {displayMode === 'pipeline' ? (
331
+ /* ================================================================= */
332
+ /* VIEW 1: STRUCTURED PIPELINE LINEAGE FLOW (No Jargon, Easy to Get) */
333
+ /* ================================================================= */
334
+ <div className="space-y-4">
335
+ <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
336
+ {/* Column 1: Source Medical Documents */}
337
+ <div className="bg-[#0A0E18] border border-blue-500/20 rounded-2xl p-4 space-y-3">
338
+ <div className="flex items-center justify-between border-b border-blue-500/20 pb-2.5">
339
+ <div className="flex items-center space-x-2">
340
+ <FileText className="w-4 h-4 text-blue-400" />
341
+ <span className="text-xs font-bold text-white uppercase tracking-wider">Source Documents</span>
342
+ </div>
343
+ <span className="text-[10px] font-mono px-2 py-0.5 rounded bg-blue-500/10 text-blue-400 font-bold">
344
+ {categorized.docs.length || 1}
345
+ </span>
346
+ </div>
347
+ <p className="text-[11px] text-slate-400">Baseline protocols uploaded to DiffWeave staging.</p>
348
+
349
+ <div className="space-y-2.5 pt-1">
350
+ {(categorized.docs.length > 0 ? categorized.docs : [
351
+ { id: 'doc-baseline', title: 'Clinical-Guidelines-2026.pdf', value: 'Master clinical protocol version 2026', type: 'DOCUMENT' }
352
+ ]).map((doc) => (
353
+ <div
354
+ key={doc.id}
355
+ onClick={() => setSelectedNode(doc)}
356
+ className="p-3 rounded-xl bg-[#101726] hover:bg-[#162136] border border-blue-500/30 transition cursor-pointer space-y-1.5 shadow-sm group"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
357
  >
358
+ <div className="flex items-center justify-between">
359
+ <span className="text-xs font-bold text-blue-300 group-hover:text-blue-200 truncate">{doc.title}</span>
360
+ <span className="text-[10px] font-mono text-slate-400">PDF</span>
361
+ </div>
362
+ <p className="text-[11px] text-slate-400 line-clamp-2">{doc.value || 'Verified baseline source document'}</p>
363
+ </div>
364
+ ))}
365
+ </div>
366
+ </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
367
 
368
+ {/* Column 2: Clinical Findings & Guidelines */}
369
+ <div className="bg-[#0A0E18] border border-violet-500/20 rounded-2xl p-4 space-y-3">
370
+ <div className="flex items-center justify-between border-b border-violet-500/20 pb-2.5">
371
+ <div className="flex items-center space-x-2">
372
+ <Activity className="w-4 h-4 text-violet-400" />
373
+ <span className="text-xs font-bold text-white uppercase tracking-wider">Clinical Findings</span>
374
+ </div>
375
+ <span className="text-[10px] font-mono px-2 py-0.5 rounded bg-violet-500/10 text-violet-400 font-bold">
376
+ {categorized.claims.length}
377
+ </span>
378
+ </div>
379
+ <p className="text-[11px] text-slate-400">Clinical claims extracted and committed to master.</p>
380
 
381
+ <div className="space-y-2.5 pt-1">
382
+ {categorized.claims.map((claim) => (
383
+ <div
384
+ key={claim.id}
385
+ onClick={() => setSelectedNode(claim)}
386
+ className="p-3 rounded-xl bg-[#121426] hover:bg-[#1A1C38] border border-violet-500/30 transition cursor-pointer space-y-1.5 shadow-sm group"
387
+ >
388
+ <div className="flex items-center justify-between">
389
+ <span className="text-xs font-bold text-violet-300 group-hover:text-violet-200 truncate">{claim.title}</span>
390
+ <span className="text-[10px] font-mono text-violet-400 font-semibold">96% Conf</span>
391
+ </div>
392
+ <p className="text-[11px] text-slate-300 line-clamp-2">{claim.value}</p>
393
+ </div>
394
+ ))}
395
  </div>
396
+ </div>
397
 
398
+ {/* Column 3: Dosing & Numerical Thresholds */}
399
+ <div className="bg-[#0A0E18] border border-emerald-500/20 rounded-2xl p-4 space-y-3">
400
+ <div className="flex items-center justify-between border-b border-emerald-500/20 pb-2.5">
401
+ <div className="flex items-center space-x-2">
402
+ <Sparkles className="w-4 h-4 text-emerald-400" />
403
+ <span className="text-xs font-bold text-white uppercase tracking-wider">Dosing & Thresholds</span>
404
+ </div>
405
+ <span className="text-[10px] font-mono px-2 py-0.5 rounded bg-emerald-500/10 text-emerald-400 font-bold">
406
+ {categorized.metrics.length}
 
 
407
  </span>
408
  </div>
409
+ <p className="text-[11px] text-slate-400">Quantitative boundaries and numerical guidelines.</p>
410
 
411
+ <div className="space-y-2.5 pt-1">
412
+ {categorized.metrics.map((metric) => (
413
+ <div
414
+ key={metric.id}
415
+ onClick={() => setSelectedNode(metric)}
416
+ className="p-3 rounded-xl bg-[#0F1A1C] hover:bg-[#152528] border border-emerald-500/30 transition cursor-pointer space-y-1.5 shadow-sm group"
417
+ >
418
+ <div className="flex items-center justify-between">
419
+ <span className="text-xs font-bold text-emerald-300 group-hover:text-emerald-200 truncate">{metric.title}</span>
420
+ <span className="text-[10px] font-mono text-emerald-400 font-semibold">
421
+ {Math.round((metric.confidence || 0.95) * 100)}%
422
+ </span>
423
+ </div>
424
+ <p className="text-[11px] text-slate-300 line-clamp-2">{metric.value}</p>
425
+ </div>
426
+ ))}
427
  </div>
428
+ </div>
429
 
430
+ {/* Column 4: Safety Guardrails & Compliance Rules */}
431
+ <div className="bg-[#0A0E18] border border-amber-500/20 rounded-2xl p-4 space-y-3">
432
+ <div className="flex items-center justify-between border-b border-amber-500/20 pb-2.5">
433
+ <div className="flex items-center space-x-2">
434
+ <ShieldCheck className="w-4 h-4 text-amber-400" />
435
+ <span className="text-xs font-bold text-white uppercase tracking-wider">Safety Guardrails</span>
 
 
 
 
436
  </div>
437
+ <span className="text-[10px] font-mono px-2 py-0.5 rounded bg-amber-500/10 text-amber-400 font-bold">
438
+ 4
439
+ </span>
440
  </div>
441
+ <p className="text-[11px] text-slate-400">Automated policy checks enforcing clinical compliance.</p>
442
 
443
+ <div className="space-y-2.5 pt-1">
444
+ {[
445
+ { id: 'rule-floor', title: 'Confidence Floor &ge; 85%', value: 'Prevents low-confidence extractions from polluting the Truth Register.', type: 'RULE' },
446
+ { id: 'rule-provenance', title: 'Mandatory Provenance Citation', value: 'Requires every claim to cite exact document page and paragraph.', type: 'RULE' },
447
+ { id: 'rule-sae', title: 'Safety Escalation SLA (24h)', value: 'Strict 24-hour reporting deadline for adverse clinical deviations.', type: 'RULE' },
448
+ { id: 'rule-stats', title: 'Statistical p-Value Validation', value: 'Ensures clinical numerical claims specify confidence intervals.', type: 'RULE' },
449
+ ].map((rule) => (
450
+ <div
451
+ key={rule.id}
452
+ onClick={() => setSelectedNode(rule)}
453
+ className="p-3 rounded-xl bg-[#1A160F] hover:bg-[#262016] border border-amber-500/30 transition cursor-pointer space-y-1.5 shadow-sm group"
454
+ >
455
+ <div className="flex items-center justify-between">
456
+ <span className="text-xs font-bold text-amber-300 group-hover:text-amber-200 truncate">{rule.title}</span>
457
+ <CheckCircle2 className="w-3.5 h-3.5 text-emerald-400" />
458
+ </div>
459
+ <p className="text-[11px] text-slate-300 line-clamp-2">{rule.value}</p>
460
  </div>
461
+ ))}
462
+ </div>
463
+ </div>
464
+ </div>
465
+ </div>
466
+ ) : (
467
+ /* ================================================================= */
468
+ /* VIEW 2: INTERACTIVE NETWORK CONSTELLATION CANVAS */
469
+ /* ================================================================= */
470
+ <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
471
+ <div className="lg:col-span-8 bg-[#090D16] border border-slate-800/80 rounded-2xl p-4 overflow-hidden relative min-h-[560px] flex items-center justify-center">
472
+ <svg
473
+ viewBox="0 0 800 600"
474
+ className="w-full h-full transition-transform duration-200 cursor-grab active:cursor-grabbing"
475
+ style={{ transform: `scale(${zoom})` }}
476
+ >
477
+ <defs>
478
+ <pattern id="graphGrid" width="40" height="40" patternUnits="userSpaceOnUse">
479
+ <path d="M 40 0 L 0 0 0 40" fill="none" stroke="#161F32" strokeWidth="0.8" />
480
+ </pattern>
481
+ </defs>
482
+ <rect width="100%" height="100%" fill="url(#graphGrid)" />
483
+
484
+ {/* Connecting Lines */}
485
+ {rawEdges.map((edge, idx) => {
486
+ const src = nodeMap[edge.source];
487
+ const tgt = nodeMap[edge.target];
488
+ if (!src || !tgt) return null;
489
+
490
+ const isHighlighted = selectedNode && (selectedNode.id === src.id || selectedNode.id === tgt.id);
491
+
492
+ return (
493
+ <g key={edge.id || idx}>
494
+ <line
495
+ x1={src.x}
496
+ y1={src.y}
497
+ x2={tgt.x}
498
+ y2={tgt.y}
499
+ stroke={isHighlighted ? '#10B981' : '#334155'}
500
+ strokeWidth={isHighlighted ? 2.5 : 1.2}
501
+ strokeDasharray={edge.relationship === 'PROPOSED_UPDATE' ? '4 3' : 'none'}
502
+ opacity={isHighlighted ? 0.9 : 0.4}
503
+ />
504
+ </g>
505
+ );
506
+ })}
507
+
508
+ {/* Circular Nodes */}
509
+ {positionedNodes.map((node) => {
510
+ const isSelected = selectedNode?.id === node.id;
511
+ const theme = getNodeTheme(node.type);
512
+
513
+ return (
514
+ <g
515
+ key={node.id}
516
+ transform={`translate(${node.x}, ${node.y})`}
517
+ onClick={() => setSelectedNode(node)}
518
+ className="cursor-pointer group"
519
+ >
520
+ {isSelected && (
521
+ <circle r="24" fill="none" stroke={theme.color} strokeWidth="2.5" opacity="0.8" className="animate-pulse" />
522
+ )}
523
+
524
+ <circle
525
+ r={node.type === 'DOCUMENT' ? 16 : 13}
526
+ fill="#0D121F"
527
+ stroke={theme.color}
528
+ strokeWidth={isSelected ? 3 : 2}
529
+ className="transition hover:scale-125"
530
+ />
531
+
532
+ <circle r="4" fill={theme.color} />
533
+
534
+ <text
535
+ y="26"
536
+ textAnchor="middle"
537
+ fill={isSelected ? '#F8FAFC' : '#94A3B8'}
538
+ fontSize="9.5"
539
+ fontFamily="Inter, sans-serif"
540
+ fontWeight={isSelected ? '600' : '400'}
541
+ className="select-none pointer-events-none"
542
+ >
543
+ {node.title.length > 20 ? node.title.slice(0, 18) + '...' : node.title}
544
+ </text>
545
+ </g>
546
+ );
547
+ })}
548
+ </svg>
549
+ </div>
550
+
551
+ {/* Side Inspector in Constellation Mode */}
552
+ <div className="lg:col-span-4 bg-[#0D121F] border border-slate-800 rounded-2xl p-5 space-y-4">
553
+ <h3 className="text-xs font-bold text-white uppercase tracking-wider">Element Inspector</h3>
554
+ {selectedNode ? (
555
+ renderNodeDetails(selectedNode)
556
+ ) : (
557
+ <div className="py-16 text-center text-xs text-slate-500 space-y-2">
558
+ <HelpCircle className="w-8 h-8 mx-auto text-slate-600" />
559
+ <p>Click any node on the graph to inspect its clinical finding, confidence, and source document.</p>
560
+ </div>
561
+ )}
562
+ </div>
563
+ </div>
564
+ )}
565
+
566
+ {/* =================================================================== */}
567
+ {/* 4. SLIDE-OVER / MODAL INSPECTOR WHEN CLICKING ANY NODE IN PIPELINE */}
568
+ {/* =================================================================== */}
569
+ {selectedNode && displayMode === 'pipeline' && (
570
+ <div className="fixed inset-0 z-50 overflow-hidden flex justify-end">
571
+ <div
572
+ className="fixed inset-0 bg-black/60 backdrop-blur-sm transition-opacity"
573
+ onClick={() => setSelectedNode(null)}
574
+ />
575
+
576
+ <div className="relative w-full max-w-lg bg-[#0C111C] border-l border-slate-800 h-full overflow-y-auto p-6 space-y-6 shadow-2xl z-10 flex flex-col justify-between">
577
+ <div className="space-y-6">
578
+ <div className="flex items-start justify-between border-b border-slate-800/80 pb-4">
579
+ <div className="space-y-1">
580
+ <div className="flex items-center space-x-2">
581
+ <span className="text-[10px] font-mono px-2 py-0.5 rounded font-bold bg-slate-800 text-slate-300 border border-slate-700">
582
+ {getNodeTheme(selectedNode.type).badge}
583
+ </span>
584
+ </div>
585
+ <h3 className="text-base font-bold text-white pt-1">{selectedNode.title}</h3>
586
  </div>
587
+
588
+ <button
589
+ onClick={() => setSelectedNode(null)}
590
+ className="p-1 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white transition"
591
+ >
592
+ <X className="w-4 h-4" />
593
+ </button>
594
+ </div>
595
+
596
+ {renderNodeDetails(selectedNode)}
597
+ </div>
598
+
599
+ <div className="pt-4 border-t border-slate-800 flex items-center justify-end space-x-2">
600
+ <button
601
+ type="button"
602
+ onClick={() => setSelectedNode(null)}
603
+ className="px-4 py-2 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-300 font-semibold text-xs transition"
604
+ >
605
+ Close
606
+ </button>
607
+
608
+ {onSelectTab && selectedNode.type !== 'RULE' && (
609
+ <button
610
+ type="button"
611
+ onClick={() => {
612
+ setSelectedNode(null);
613
+ onSelectTab('knowledge');
614
+ }}
615
+ className="px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-semibold text-xs transition flex items-center space-x-1.5 shadow-lg shadow-emerald-500/20"
616
+ >
617
+ <span>View in Truth Register</span>
618
+ <ArrowRight className="w-3.5 h-3.5" />
619
+ </button>
620
  )}
621
  </div>
622
+ </div>
623
+ </div>
624
+ )}
625
+ </div>
626
+ );
627
+
628
+ // Helper function to render node detail card
629
+ function renderNodeDetails(node) {
630
+ const theme = getNodeTheme(node.type);
631
+ const Icon = theme.icon;
632
+
633
+ return (
634
+ <div className="space-y-4 text-xs">
635
+ <div className={`p-4 rounded-xl border ${theme.bg} ${theme.border} space-y-2`}>
636
+ <div className="flex items-center space-x-2">
637
+ <Icon className="w-4 h-4" style={{ color: theme.color }} />
638
+ <span className="font-bold text-white">{theme.badge}</span>
639
+ </div>
640
+ <p className="text-slate-300 leading-relaxed font-sans">{node.value || node.title}</p>
641
+ <span className="text-[11px] text-slate-400 block pt-1">{theme.desc}</span>
642
+ </div>
643
+
644
+ {/* Provenance & Citation */}
645
+ <div className="bg-[#121826] border border-slate-800 rounded-xl p-4 space-y-2.5">
646
+ <span className="text-[10px] font-mono text-slate-400 uppercase font-semibold">Provenance Citation</span>
647
+ <div className="flex items-center justify-between text-slate-300">
648
+ <span className="text-slate-400">Source Protocol:</span>
649
+ <span className="font-semibold text-white">{node.filename || 'Clinical_Guideline.pdf'}</span>
650
+ </div>
651
+ <div className="flex items-center justify-between text-slate-300">
652
+ <span className="text-slate-400">Section Citation:</span>
653
+ <span className="font-mono text-emerald-400">Section 2.1 Baseline Standard</span>
654
+ </div>
655
+ {node.confidence !== undefined && (
656
+ <div className="flex items-center justify-between text-slate-300">
657
+ <span className="text-slate-400">Confidence Score:</span>
658
+ <span className="font-mono text-emerald-400 font-bold">
659
+ {Math.round((node.confidence || 0.95) * 100)}% Verified
660
+ </span>
661
  </div>
662
  )}
663
  </div>
664
+
665
+ {/* Connected Elements */}
666
+ <div className="space-y-2">
667
+ <span className="text-[10px] font-mono text-slate-400 uppercase font-semibold">Lineage Relationships</span>
668
+ <div className="p-3 rounded-xl bg-[#111622] border border-slate-800 space-y-1.5 text-[11px] text-slate-300">
669
+ <div className="flex items-center space-x-1.5 text-blue-400">
670
+ <FileText className="w-3.5 h-3.5 shrink-0" />
671
+ <span>Extracted from: <strong>{node.filename || 'Clinical_Guideline.pdf'}</strong></span>
672
+ </div>
673
+ <div className="flex items-center space-x-1.5 text-amber-400">
674
+ <ShieldCheck className="w-3.5 h-3.5 shrink-0" />
675
+ <span>Guarded by: <strong>Confidence Floor (&ge;85%) & Mandatory Provenance</strong></span>
676
+ </div>
677
+ <div className="flex items-center space-x-1.5 text-emerald-400">
678
+ <CheckCircle2 className="w-3.5 h-3.5 shrink-0" />
679
+ <span>Committed branch: <strong>refs/heads/main</strong></span>
680
+ </div>
681
+ </div>
682
+ </div>
683
  </div>
684
+ );
685
+ }
686
  }
studio/src/components/WorkspaceHub.jsx CHANGED
@@ -205,7 +205,15 @@ export default function WorkspaceHub({
205
  alert(`A workspace named "${finalName}" already exists. Workspace names must be unique.`);
206
  return;
207
  }
208
- await onCreateWorkspace(finalName, wsDesc.trim());
 
 
 
 
 
 
 
 
209
  setWsName('');
210
  setWsDesc('');
211
  setShowCreateModal(false);
@@ -997,43 +1005,87 @@ export default function WorkspaceHub({
997
 
998
  {/* Starter Template */}
999
  <div className="space-y-2">
1000
- <label className="text-xs font-semibold text-slate-300">Starter template</label>
 
 
 
1001
  <div className="grid grid-cols-1 sm:grid-cols-3 gap-2 text-xs">
1002
  <button
1003
  type="button"
1004
  onClick={() => setStarterTemplate('empty')}
1005
  className={`p-2.5 rounded-lg border text-left transition ${
1006
  starterTemplate === 'empty'
1007
- ? 'border-emerald-500 bg-emerald-500/10 text-white'
 
 
 
 
 
 
 
 
 
 
 
 
 
1008
  : 'border-[#30363D] bg-[#161B22] text-slate-400 hover:text-white'
1009
  }`}
1010
  >
1011
- <span className="font-bold block">Empty Workspace</span>
1012
- <span className="text-[10px] text-slate-500">Blank slate, ingest docs via CLI or dropzone</span>
1013
  </button>
 
1014
  <button
1015
  type="button"
1016
- onClick={() => setStarterTemplate('cardiology')}
1017
  className={`p-2.5 rounded-lg border text-left transition ${
1018
- starterTemplate === 'cardiology'
1019
- ? 'border-emerald-500 bg-emerald-500/10 text-white'
1020
  : 'border-[#30363D] bg-[#161B22] text-slate-400 hover:text-white'
1021
  }`}
1022
  >
1023
- <span className="font-bold block">Clinical Cardiology</span>
1024
- <span className="text-[10px] text-slate-500">Pre-loaded guidelines & 85% confidence rule</span>
1025
  </button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1026
  <button
1027
  type="button"
1028
  onClick={() => setStarterTemplate('legal')}
1029
  className={`p-2.5 rounded-lg border text-left transition ${
1030
  starterTemplate === 'legal'
1031
- ? 'border-emerald-500 bg-emerald-500/10 text-white'
 
 
 
 
 
 
 
 
 
 
 
 
 
1032
  : 'border-[#30363D] bg-[#161B22] text-slate-400 hover:text-white'
1033
  }`}
1034
  >
1035
- <span className="font-bold block">Legal Agreements</span>
1036
- <span className="text-[10px] text-slate-500">NDAs, clause extraction & policy CI rules</span>
1037
  </button>
1038
  </div>
1039
  </div>
 
205
  alert(`A workspace named "${finalName}" already exists. Workspace names must be unique.`);
206
  return;
207
  }
208
+ const templateDescriptions = {
209
+ clinical: 'Hospital clinical guidelines, diagnostic criteria, standard of care protocols & dosing safety thresholds.',
210
+ trials: 'Clinical trial endpoints, RECIST criteria, SAE adverse event reporting & participant inclusion protocols.',
211
+ pharma: 'Pharmaceutical IND/CMC documentation, drug release specifications & pharmacovigilance audit trails.',
212
+ legal: 'Enterprise legal agreements, vendor contracts, NDA obligations & regulatory compliance covenants.',
213
+ engineering: 'Engineering system architecture RFCs, microservice contracts & cloud security baselines.',
214
+ };
215
+ const finalDesc = wsDesc.trim() || templateDescriptions[starterTemplate] || 'DiffWeave verified knowledge repository.';
216
+ await onCreateWorkspace(finalName, finalDesc, starterTemplate);
217
  setWsName('');
218
  setWsDesc('');
219
  setShowCreateModal(false);
 
1005
 
1006
  {/* Starter Template */}
1007
  <div className="space-y-2">
1008
+ <div className="flex items-center justify-between">
1009
+ <label className="text-xs font-semibold text-slate-300">Starter template</label>
1010
+ <span className="text-[10px] text-slate-500 font-mono">6 Specialized Templates</span>
1011
+ </div>
1012
  <div className="grid grid-cols-1 sm:grid-cols-3 gap-2 text-xs">
1013
  <button
1014
  type="button"
1015
  onClick={() => setStarterTemplate('empty')}
1016
  className={`p-2.5 rounded-lg border text-left transition ${
1017
  starterTemplate === 'empty'
1018
+ ? 'border-emerald-500 bg-emerald-500/10 text-white shadow-sm'
1019
+ : 'border-[#30363D] bg-[#161B22] text-slate-400 hover:text-white'
1020
+ }`}
1021
+ >
1022
+ <span className="font-bold block text-slate-200">Empty Workspace</span>
1023
+ <span className="text-[10px] text-slate-400 block pt-0.5">Blank slate, ingest docs via CLI or dropzone</span>
1024
+ </button>
1025
+
1026
+ <button
1027
+ type="button"
1028
+ onClick={() => setStarterTemplate('clinical')}
1029
+ className={`p-2.5 rounded-lg border text-left transition ${
1030
+ starterTemplate === 'clinical'
1031
+ ? 'border-emerald-500 bg-emerald-500/10 text-white shadow-sm'
1032
  : 'border-[#30363D] bg-[#161B22] text-slate-400 hover:text-white'
1033
  }`}
1034
  >
1035
+ <span className="font-bold block text-emerald-400">General Clinical Protocols</span>
1036
+ <span className="text-[10px] text-slate-400 block pt-0.5">Hospital guidelines, diagnostic criteria & dosing thresholds</span>
1037
  </button>
1038
+
1039
  <button
1040
  type="button"
1041
+ onClick={() => setStarterTemplate('trials')}
1042
  className={`p-2.5 rounded-lg border text-left transition ${
1043
+ starterTemplate === 'trials'
1044
+ ? 'border-emerald-500 bg-emerald-500/10 text-white shadow-sm'
1045
  : 'border-[#30363D] bg-[#161B22] text-slate-400 hover:text-white'
1046
  }`}
1047
  >
1048
+ <span className="font-bold block text-blue-400">Clinical Trials & Oncology</span>
1049
+ <span className="text-[10px] text-slate-400 block pt-0.5">Trial endpoints, RECIST criteria & SAE adverse event reporting</span>
1050
  </button>
1051
+
1052
+ <button
1053
+ type="button"
1054
+ onClick={() => setStarterTemplate('pharma')}
1055
+ className={`p-2.5 rounded-lg border text-left transition ${
1056
+ starterTemplate === 'pharma'
1057
+ ? 'border-emerald-500 bg-emerald-500/10 text-white shadow-sm'
1058
+ : 'border-[#30363D] bg-[#161B22] text-slate-400 hover:text-white'
1059
+ }`}
1060
+ >
1061
+ <span className="font-bold block text-violet-400">Pharma & Drug Regulatory</span>
1062
+ <span className="text-[10px] text-slate-400 block pt-0.5">Pharmacovigilance, IND/CMC specs & regulatory submissions</span>
1063
+ </button>
1064
+
1065
  <button
1066
  type="button"
1067
  onClick={() => setStarterTemplate('legal')}
1068
  className={`p-2.5 rounded-lg border text-left transition ${
1069
  starterTemplate === 'legal'
1070
+ ? 'border-emerald-500 bg-emerald-500/10 text-white shadow-sm'
1071
+ : 'border-[#30363D] bg-[#161B22] text-slate-400 hover:text-white'
1072
+ }`}
1073
+ >
1074
+ <span className="font-bold block text-amber-400">Legal Agreements</span>
1075
+ <span className="text-[10px] text-slate-400 block pt-0.5">NDAs, vendor contracts, clause extraction & policy CI rules</span>
1076
+ </button>
1077
+
1078
+ <button
1079
+ type="button"
1080
+ onClick={() => setStarterTemplate('engineering')}
1081
+ className={`p-2.5 rounded-lg border text-left transition ${
1082
+ starterTemplate === 'engineering'
1083
+ ? 'border-emerald-500 bg-emerald-500/10 text-white shadow-sm'
1084
  : 'border-[#30363D] bg-[#161B22] text-slate-400 hover:text-white'
1085
  }`}
1086
  >
1087
+ <span className="font-bold block text-cyan-400">Engineering & DevOps RFCs</span>
1088
+ <span className="text-[10px] text-slate-400 block pt-0.5">System architecture RFCs, security baselines & API contracts</span>
1089
  </button>
1090
  </div>
1091
  </div>