import React, { useState, useMemo } from 'react';
import {
Database,
Search,
Download,
Filter,
CheckCircle2,
Sparkles,
FileText,
Copy,
Layers,
GitPullRequest,
ArrowRight,
ShieldCheck,
UploadCloud,
CheckCheck,
Info,
History,
GitCommit,
ExternalLink,
Bot,
Terminal,
Code2,
FileCode,
LayoutGrid,
Table as TableIcon,
ChevronDown,
ChevronRight,
Edit3,
Archive,
BookOpen,
X,
HelpCircle,
Clock,
Send,
Check,
AlertCircle
} from 'lucide-react';
import confetti from 'canvas-confetti';
import { api } from '../api/client.js';
export default function KnowledgeBase({
knowledgeItems = [],
currentWorkspace,
loading,
searchQuery = '',
onSearchChange,
setActiveTab,
pendingProposalsCount = 0,
onApproveAll,
onRefresh
}) {
const [internalSearch, setInternalSearch] = useState('');
const [categoryFilter, setCategoryFilter] = useState('ALL');
const [statusFilter, setStatusFilter] = useState('ALL');
const [viewMode, setViewMode] = useState('cards'); // 'cards' | 'table'
const [groupBy, setGroupBy] = useState('none'); // 'none' | 'document' | 'category'
const [sortBy, setSortBy] = useState('confidence'); // 'confidence' | 'newest' | 'title'
// Slide-over Fact Inspector Drawer
const [selectedFact, setSelectedFact] = useState(null);
// Modals
const [showReviseModal, setShowReviseModal] = useState(false);
const [factToRevise, setFactToRevise] = useState(null);
const [revisionTitle, setRevisionTitle] = useState('');
const [revisionValue, setRevisionValue] = useState('');
const [revisionRationale, setRevisionRationale] = useState('');
const [submittingRevision, setSubmittingRevision] = useState(false);
const [showExportHub, setShowExportHub] = useState(false);
const [exportTab, setExportTab] = useState('prompt'); // 'prompt' | 'mcp' | 'markdown' | 'json'
// "Ask the Truth Register" Playground State
const [askQuery, setAskQuery] = useState('');
const [askAnswer, setAskAnswer] = useState(null);
const [isAnswering, setIsAnswering] = useState(false);
const [copiedId, setCopiedId] = useState(null);
const [copiedExport, setCopiedExport] = useState(false);
const [approving, setApproving] = useState(false);
const [showLibrarianGuide, setShowLibrarianGuide] = useState(true);
const search = searchQuery !== undefined && searchQuery !== '' ? searchQuery : internalSearch;
const setSearch = onSearchChange || setInternalSearch;
const activeCount = knowledgeItems.filter((i) => !i.status || i.status.toUpperCase() === 'ACTIVE').length;
const pendingCount = knowledgeItems.filter((i) => i.status && i.status.toUpperCase() === 'PENDING').length;
const effectivePending = pendingProposalsCount > 0 ? pendingProposalsCount : pendingCount;
// Filter & Sort
const processedItems = useMemo(() => {
let result = knowledgeItems.filter((item) => {
const itemType = String(item.type || '').toUpperCase();
const itemStatus = String(item.status || 'ACTIVE').toUpperCase();
const matchesCat = categoryFilter === 'ALL' || itemType === categoryFilter;
const matchesStatus = statusFilter === 'ALL' || itemStatus === statusFilter;
const s = search.toLowerCase().trim();
if (!s) return matchesCat && matchesStatus;
const titleMatch = (item.title || '').toLowerCase().includes(s);
const valueMatch = String(item.value || '').toLowerCase().includes(s);
const typeMatch = itemType.toLowerCase().includes(s);
const fileMatch = (item.filename || '').toLowerCase().includes(s);
return matchesCat && matchesStatus && (titleMatch || valueMatch || typeMatch || fileMatch);
});
// Sorting
result.sort((a, b) => {
if (sortBy === 'confidence') {
return (b.confidence || 0.95) - (a.confidence || 0.95);
}
if (sortBy === 'newest') {
return new Date(b.created_at || 0) - new Date(a.created_at || 0);
}
if (sortBy === 'title') {
return (a.title || '').localeCompare(b.title || '');
}
return 0;
});
return result;
}, [knowledgeItems, categoryFilter, statusFilter, search, sortBy]);
// Grouping
const groupedData = useMemo(() => {
if (groupBy === 'none') return null;
const groups = {};
processedItems.forEach((item) => {
const key =
groupBy === 'document'
? item.filename || 'General Clinical Documentation'
: item.type || 'CLAIM';
if (!groups[key]) groups[key] = [];
groups[key].push(item);
});
return groups;
}, [processedItems, groupBy]);
const availableCategories = ['ALL', ...new Set(knowledgeItems.map((i) => String(i.type || '').toUpperCase()).filter(Boolean))];
const handleCopy = (val, id) => {
navigator.clipboard.writeText(val);
setCopiedId(id);
setTimeout(() => setCopiedId(null), 1800);
};
const handleBatchApprove = async () => {
if (!onApproveAll) return;
setApproving(true);
try {
await onApproveAll();
try {
confetti({ particleCount: 60, spread: 70, origin: { y: 0.7 } });
} catch (e) {}
} finally {
setApproving(false);
}
};
// "Ask the Truth Register" Playground Handler
const handleAskQuery = (q) => {
const queryText = q !== undefined ? q : askQuery;
if (!queryText.trim()) return;
setIsAnswering(true);
setAskQuery(queryText);
setTimeout(() => {
const qLower = queryText.toLowerCase();
// Score matching items
const matches = knowledgeItems.filter((item) => {
const titleWords = (item.title || '').toLowerCase().split(/\s+/);
const valueWords = String(item.value || '').toLowerCase().split(/\s+/);
const queryTokens = qLower.split(/\s+/).filter((w) => w.length > 2);
return queryTokens.some((token) => titleWords.some((tw) => tw.includes(token)) || valueWords.some((vw) => vw.includes(token)));
});
if (matches.length === 0) {
setAskAnswer({
query: queryText,
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.`,
citations: [],
found: false
});
} else {
const top = matches[0];
setAskAnswer({
query: queryText,
text: `Based on verified master protocol guidelines: ${top.value}`,
citations: matches.slice(0, 3).map((m) => ({
id: m.id,
title: m.title,
filename: m.filename || 'Clinical_Guideline.pdf',
confidence: m.confidence || 0.95
})),
found: true
});
}
setIsAnswering(false);
}, 350);
};
// Open Revision Modal
const openRevision = (fact) => {
setFactToRevise(fact);
setRevisionTitle(fact.title || '');
setRevisionValue(fact.value || '');
setRevisionRationale(`Clinical protocol revision proposed for "${fact.title}" based on updated 2026/2027 guideline.`);
setShowReviseModal(true);
};
// Submit Revision Proposal (Opens Knowledge PR)
const submitRevision = async (e) => {
e.preventDefault();
if (!currentWorkspace?.id || !factToRevise) return;
setSubmittingRevision(true);
try {
const payload = {
summary: `Update fact: ${revisionTitle}`,
rationale: revisionRationale,
proposal_type: 'UPDATE',
knowledge_item_id: factToRevise.id,
proposed_changes: {
existing: {
title: factToRevise.title,
value: factToRevise.value,
confidence: factToRevise.confidence
},
proposed: {
title: revisionTitle,
value: revisionValue,
confidence: 0.98
},
type: factToRevise.type || 'CLAIM'
}
};
await api.createProposal(currentWorkspace.id, payload);
setShowReviseModal(false);
if (onRefresh) onRefresh();
try {
confetti({ particleCount: 50, spread: 60, origin: { y: 0.6 } });
} catch (e) {}
alert(`Knowledge PR opened successfully! Review and merge your proposed revision in the PR Review Deck.`);
if (setActiveTab) setActiveTab('prs');
} catch (err) {
alert(`Could not submit revision PR: ${err.message}`);
} finally {
setSubmittingRevision(false);
}
};
// Export content generators
const getExportText = () => {
const wsName = currentWorkspace?.name || 'Medical Truth Base';
if (exportTab === 'prompt') {
return `You are a clinical and healthcare AI assistant adhering strictly to zero-hallucination protocols.
You MUST verify all responses against the following ${activeCount} ground-truth clinical facts committed in the DiffWeave Truth Register for "${wsName}":
` + knowledgeItems.map((item, idx) => `[FACT #${idx + 1}] (${item.type || 'CLAIM'} - Confidence: ${Math.round((item.confidence || 0.95) * 100)}%):
Title: ${item.title}
Assertion: ${item.value}
Source: ${item.filename || 'Verified Medical Protocol'}
`).join('\n') + `
RULE: If a user query conflicts with or is not answered by these verified facts, explicitly state the boundary and cite the fact number.`;
}
if (exportTab === 'mcp') {
return `# Python MCP Tool Invocation for DiffWeave Master Register
import requests
WORKSPACE_ID = "${currentWorkspace?.id || 'workspace-id'}"
DIFFWEAVE_URL = "https://shak3008-diffweave.hf.space"
def query_verified_truth(query: str):
"""Query deterministic facts from DiffWeave Truth Register."""
res = requests.get(f"{DIFFWEAVE_URL}/api/workspaces/{WORKSPACE_ID}/search", params={"q": query})
return res.json()
# Example Agent Tool Calling
if __name__ == "__main__":
facts = query_verified_truth("threshold")
for f in facts:
print(f"[{f['type']}] {f['title']}: {f['value']}")
`;
}
if (exportTab === 'markdown') {
return `# Master Truth Register: ${wsName}
**Committed Facts**: ${activeCount} | **Workspace ID**: \`${currentWorkspace?.id || 'none'}\`
| # | Title | Type | Verified Value | Confidence | Source Document |
|---|---|---|---|---|---|
` + 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');
}
return JSON.stringify(knowledgeItems, null, 2);
};
const copyExportContent = () => {
navigator.clipboard.writeText(getExportText());
setCopiedExport(true);
setTimeout(() => setCopiedExport(false), 2000);
};
if (loading) {
return (
Loading Master Knowledge Register...
);
}
return (
{/* =================================================================== */}
{/* 1. LIBRARIAN & BOOKKEEPER ONBOARDING BANNER (Friendly Plain English) */}
{/* =================================================================== */}
{showLibrarianGuide && (
setShowLibrarianGuide(false)}
className="absolute top-3.5 right-3.5 text-slate-500 hover:text-slate-300 transition"
title="Dismiss Guide"
>
Medical Truth Register & Official Knowledge Catalog
Librarian & Auditor Portal
This register is your healthcare institution's single source of truth . Unverified claims from newly uploaded documents are staged as Pull Requests and only appear here after human verification.
Audit Provenance : Click any fact to view its exact document sentence & commit SHA.
Propose Updates : Outdated dosing guideline? Propose a revision PR directly.
Agent RAG : Export facts directly as system prompt grounding for LLMs.
)}
{/* =================================================================== */}
{/* 2. TOP METRICS CARDS */}
{/* =================================================================== */}
{activeCount}
Committed Facts (main)
{effectivePending}
Pending PRs Awaiting Merge
{knowledgeItems.filter((i) => (i.confidence || 0.95) >= 0.9).length}
High Confidence (≥90%)
{new Set(knowledgeItems.map((i) => i.type)).size}
Unique Semantic Categories
{/* =================================================================== */}
{/* 3. "ASK THE TRUTH REGISTER" GROUNDED QUERY PLAYGROUND */}
{/* =================================================================== */}
Ask the Truth Register (Grounded RAG Assistant)
Test clinical questions directly against verified facts with zero hallucination.
Deterministic Grounding Active
{/* Input Form */}
{/* Quick Question Chips */}
Suggested Queries:
{[
'Aortic stenosis mean gradient threshold',
'SGLT2 inhibitors recommendation in heart failure',
'Standard DAPT duration for high bleeding risk',
'Adverse event safety escalation timeframe'
].map((prompt) => (
handleAskQuery(prompt)}
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]"
>
{prompt}
))}
{/* Grounded Answer Card */}
{askAnswer && (
VERIFIED RESPONSE
Query: "{askAnswer.query}"
{askAnswer.text}
{askAnswer.citations.length > 0 && (
Grounding Citations:
{askAnswer.citations.map((c) => (
{
const item = knowledgeItems.find((k) => k.id === c.id);
if (item) setSelectedFact(item);
}}
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"
title="Click to view Git blame & provenance"
>
{c.title} ({Math.round(c.confidence * 100)}%)
))}
)}
setAskAnswer(null)}
className="text-slate-500 hover:text-slate-300 transition"
title="Close response"
>
)}
{/* =================================================================== */}
{/* 4. CONTROL BAR (View Toggles, Filters, Exports) */}
{/* =================================================================== */}
Master Knowledge Register
{processedItems.length} facts cataloged
{/* Search Input */}
setSearch(e.target.value)}
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"
/>
{/* Group By Filter */}
setGroupBy(e.target.value)}
className="bg-[#141B2D] border border-slate-800 rounded-lg px-2.5 py-1.5 text-xs text-slate-300 focus:outline-none"
title="Group catalog items"
>
Flat List
Group by Document
Group by Category
{/* Status Filter */}
setStatusFilter(e.target.value)}
className="bg-[#141B2D] border border-slate-800 rounded-lg px-2.5 py-1.5 text-xs text-slate-300 focus:outline-none"
>
All Statuses
Committed (Active)
Staged (Pending PR)
{/* Category Filter */}
setCategoryFilter(e.target.value)}
className="bg-[#141B2D] border border-slate-800 rounded-lg px-2.5 py-1.5 text-xs text-slate-300 focus:outline-none"
>
{availableCategories.map((cat) => (
{cat === 'ALL' ? 'All Categories' : cat}
))}
{/* View Mode Toggle */}
setViewMode('cards')}
className={`p-1.5 rounded transition ${viewMode === 'cards' ? 'bg-slate-700 text-white' : 'text-slate-400 hover:text-white'}`}
title="Card View (Rich with citations)"
>
setViewMode('table')}
className={`p-1.5 rounded transition ${viewMode === 'table' ? 'bg-slate-700 text-white' : 'text-slate-400 hover:text-white'}`}
title="Table View (Dense spreadsheet for auditors)"
>
{/* AI & Agent Integration Hub Button */}
setShowExportHub(true)}
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"
title="Export for LLM System Prompt or Agent MCP"
>
AI & RAG Hub
{/* Quick Merge All PRs Button */}
{effectivePending > 0 && onApproveAll && (
{approving ? 'Merging...' : `Merge ${effectivePending} PRs`}
)}
{/* =================================================================== */}
{/* 5. MAIN CONTENT (Cards vs Dense Table / Grouped) */}
{/* =================================================================== */}
{knowledgeItems.length === 0 ? (
/* Empty State */
Git-for-Knowledge Architecture
Master Truth Register is Currently Empty
In DiffWeave, truth is version-controlled like source code. Unverified claims do not contaminate the Master Truth Register automatically. Instead, ingested documents create candidate Knowledge Pull Requests (Proposals) that must be reviewed and merged into main.
{effectivePending > 0 ? (
<>
{setActiveTab && (
setActiveTab('prs')}
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-2 shadow-lg shadow-blue-500/20"
>
Review {effectivePending} Pending Knowledge PRs
)}
{onApproveAll && (
{approving ? 'Committing...' : 'One-Click Merge All into Register'}
)}
>
) : (
setActiveTab && (
setActiveTab('staging')}
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-2 shadow-lg shadow-emerald-500/20"
>
Stage Document for Knowledge Extraction
)
)}
) : processedItems.length === 0 ? (
No knowledge entries found matching filter criteria.
{
setSearch('');
setCategoryFilter('ALL');
setStatusFilter('ALL');
}}
className="text-xs text-emerald-400 hover:text-emerald-300 font-medium underline"
>
Reset Filters
) : (
/* Render Grouped or Flat */
{groupedData ? (
Object.entries(groupedData).map(([groupTitle, items]) => (
{groupTitle}
{items.length} facts
{renderItemsList(items)}
))
) : (
renderItemsList(processedItems)
)}
)}
{/* =================================================================== */}
{/* 6. SLIDE-OVER "GIT BLAME" & PROVENANCE INSPECTOR DRAWER */}
{/* =================================================================== */}
{selectedFact && (
{/* Backdrop */}
setSelectedFact(null)}
/>
{/* Drawer Header */}
{selectedFact.type || 'CLAIM'}
{selectedFact.status && selectedFact.status.toUpperCase() === 'PENDING' ? (
STAGED PR (PENDING)
) : (
COMMITTED TO MAIN
)}
{selectedFact.title}
setSelectedFact(null)}
className="p-1 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white transition"
>
{/* Verified Fact Value */}
Committed Assertion
{selectedFact.value}
Confidence Level:
{Math.round((selectedFact.confidence || 0.95) * 100)}% Verified
{/* Cryptographic Git Lineage / "Git Blame" */}
Cryptographic Git Lineage & Provenance
Commit SHA
commit_{selectedFact.id ? selectedFact.id.slice(0, 8) : '8f3c1a9'}
Source Protocol Document
{selectedFact.filename || 'Clinical_Guideline.pdf'}
Evidence Citation
Section 2.1, Baseline Protocol
Committed Branch
refs/heads/main
{/* CI Policy Verification Badges */}
Automated Quality Gates Passed
Confidence Floor ≥ 85%
Mandatory Provenance Citation
GCP Safety SLA (24h)
Statistical Claim Validity
{/* Lifecycle Stepper */}
Lifecycle Traceability
1
Extracted by Neural Pipeline from source document
2
Reviewed & approved via Peer Knowledge PR
3
Committed into immutable Master Truth Register
{/* Drawer Actions */}
{
handleCopy(selectedFact.value, selectedFact.id);
}}
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"
>
Copy Fact
{
setSelectedFact(null);
openRevision(selectedFact);
}}
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"
>
Propose Revision (PR)
)}
{/* =================================================================== */}
{/* 7. PROPOSE REVISION MODAL */}
{/* =================================================================== */}
{showReviseModal && factToRevise && (
Propose Fact Revision (Knowledge PR)
setShowReviseModal(false)}
className="text-slate-400 hover:text-white transition"
>
)}
{/* =================================================================== */}
{/* 8. AI & AGENT INTEGRATION HUB MODAL */}
{/* =================================================================== */}
{showExportHub && (
AI & Agent Integration Hub
Ground LLMs and autonomous agents on verified truth.
setShowExportHub(false)}
className="text-slate-400 hover:text-white transition"
>
{/* Hub Format Tabs */}
setExportTab('prompt')}
className={`px-3.5 py-2 font-semibold transition border-b-2 flex items-center space-x-1.5 ${
exportTab === 'prompt' ? 'border-blue-500 text-blue-400' : 'border-transparent text-slate-400 hover:text-white'
}`}
>
LLM System Prompt
setExportTab('mcp')}
className={`px-3.5 py-2 font-semibold transition border-b-2 flex items-center space-x-1.5 ${
exportTab === 'mcp' ? 'border-emerald-500 text-emerald-400' : 'border-transparent text-slate-400 hover:text-white'
}`}
>
FastMCP Tool Client
setExportTab('markdown')}
className={`px-3.5 py-2 font-semibold transition border-b-2 flex items-center space-x-1.5 ${
exportTab === 'markdown' ? 'border-violet-500 text-violet-400' : 'border-transparent text-slate-400 hover:text-white'
}`}
>
Markdown Truth Spec
setExportTab('json')}
className={`px-3.5 py-2 font-semibold transition border-b-2 flex items-center space-x-1.5 ${
exportTab === 'json' ? 'border-amber-500 text-amber-400' : 'border-transparent text-slate-400 hover:text-white'
}`}
>
JSON Vector Schema
{/* Code / Content Area */}
{/* Modal Actions */}
{exportTab === 'prompt' && 'Paste into ChatGPT, Claude, or Gemini system prompts to eliminate hallucinations.'}
{exportTab === 'mcp' && 'Python client code to integrate this workspace into LangChain, AutoGen, or LangGraph.'}
{exportTab === 'markdown' && 'Clean tabular spec ready for GitHub READMEs or clinical documentation.'}
{exportTab === 'json' && 'Raw structured JSON suitable for vector indexing and embeddings.'}
{copiedExport ? : }
{copiedExport ? 'Copied to Clipboard!' : 'Copy to Clipboard'}
)}
);
// Helper function to render items list either in Card View or Table View
function renderItemsList(items) {
if (viewMode === 'table') {
return (
Fact Title
Type
Committed Finding / Value
Confidence
Status
Source Document
Actions
{items.map((item) => {
const isPending = item.status && item.status.toUpperCase() === 'PENDING';
return (
setSelectedFact(item)}
className="hover:bg-[#121828] transition cursor-pointer"
>
{item.title}
{item.type || 'CLAIM'}
{item.value}
{Math.round((item.confidence || 0.95) * 100)}%
{isPending ? (
PENDING PR
) : (
COMMITTED
)}
{item.filename || 'Clinical_Guideline.pdf'}
e.stopPropagation()}>
openRevision(item)}
className="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white transition"
title="Propose Revision"
>
handleCopy(item.value, item.id)}
className="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white transition"
title="Copy Value"
>
);
})}
);
}
// Card View (Default)
return (
{items.map((item) => {
const isPending = item.status && item.status.toUpperCase() === 'PENDING';
return (
setSelectedFact(item)}
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"
>
{item.title}
{item.type || 'CLAIM'}
{isPending ? (
STAGED PR (PENDING)
) : (
COMMITTED (MAIN)
)}
{Math.round((item.confidence || 0.95) * 100)}% Conf
{item.value}
ID: {item.id ? item.id.slice(0, 8) : 'unknown'}
Source: {item.filename || 'Clinical_Guideline.pdf'}
|
Click to view Git blame & provenance
e.stopPropagation()}
>
openRevision(item)}
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"
title="Propose Revision (Open PR)"
>
Revise
handleCopy(item.value, item.id)}
className="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white transition"
title="Copy Value"
>
{copiedId === item.id && (
Copied!
)}
);
})}
);
}
}