import { useState, useEffect, useCallback } from 'react' import { motion, AnimatePresence } from 'framer-motion' import { FileText, Dna, DollarSign, Scale, Brain, TrendingUp, AlertTriangle, Lightbulb, Loader2, FileCode, Hash, ChevronDown, ChevronRight, Copy, Check, Eye, Code, Sparkles, Shield, ShieldAlert, Lock, Package, TestTube, Bug, Gavel, Coins, BarChart3, Layers, ExternalLink, X, EyeOff, KeyRound, Server, FolderTree, Rocket, Microscope, Radar, } from 'lucide-react' const API_BASE = '' const GC = { 'A': 'text-success', 'A−': 'text-success', 'A+': 'text-success', 'B': 'text-success', 'B+': 'text-success', 'B−': 'text-warning', 'C': 'text-warning', 'C−': 'text-warning', 'C+': 'text-warning', 'D': 'text-critical', 'D+': 'text-critical', 'D−': 'text-critical', 'F': 'text-critical', 'Unknown': 'text-secondary' } const RC = { low: 'text-success', medium: 'text-warning', high: 'text-critical' } const PC = { critical: 'text-critical bg-critical/10', high: 'text-warning bg-warning/10', medium: 'text-primary bg-primary/10', low: 'text-secondary bg-white/5', info: 'text-secondary bg-white/3' } const PG = { critical: '⟁', high: '▲', medium: '◆', low: '◇', info: '◌' } const TIERS = { measured: { glyph: '◉', label: 'Measured', color: 'text-success', desc: 'Directly computed from artifact' }, inferred: { glyph: '◇', label: 'Inferred', color: 'text-warning', desc: 'Model-based estimate with assumptions' }, verified: { glyph: '✓', label: 'Verified', color: 'text-primary', desc: 'Externally confirmed' }, unverified: { glyph: '?', label: 'Unverified', color: 'text-critical', desc: 'No evidence found' }, } const SEC_BL = [ { sev: 'CRITICAL', icon: ShieldAlert, finding: 'No authentication or authorization layer', consequence: 'Any reachable user can upload, inspect, trigger analysis, invoke operational endpoints' }, { sev: 'CRITICAL', icon: FolderTree, finding: '/index/path accepts arbitrary server-side file path', consequence: 'Remote caller can index any file readable by service account' }, { sev: 'CRITICAL', icon: FolderTree, finding: '/index/dir recursively indexes arbitrary server directory', consequence: 'Mass disclosure of server files, configs, mounted data, credentials' }, { sev: 'CRITICAL', icon: Rocket, finding: '/pipeline/trigger creates GitHub repos, deploys HF Spaces + Vercel', consequence: 'Unauthenticated caller can abuse operator deployment credentials' }, { sev: 'CRITICAL', icon: Bug, finding: 'Upload paths use unsanitized file.filename', consequence: 'Path traversal or unintended file overwrite possible' }, { sev: 'HIGH', icon: Package, finding: 'Archive extraction has no validation (count, size, ratio, symlink)', consequence: 'Archive bombs, disk exhaustion, extraction traversal' }, { sev: 'HIGH', icon: EyeOff, finding: 'Indexes retain source previews exposed via search/chunk', consequence: 'Metadata-only separation is defeated' }, { sev: 'HIGH', icon: Eye, finding: 'All endpoints publicly readable (results, dossiers, ML, telemetry)', consequence: 'Proprietary metadata and source fragments enumerable' }, { sev: 'HIGH', icon: Server, finding: 'RentMasseur automation + underwriting share one process', consequence: 'Compromise of public service expands to operational account' }, { sev: 'MEDIUM', icon: KeyRound, finding: 'File passwords not used for endpoint authorization', consequence: 'Password feature is cosmetic, not access control' }, ] const DEFI_SCORES = [ { dim: 'Prototype Breadth', grade: 'B+', score: 85, tier: 'measured' }, { dim: 'Functional Architecture', grade: 'B−', score: 75, tier: 'measured' }, { dim: 'Privacy-Preserving Eval Path', grade: 'C', score: 55, tier: 'measured' }, { dim: 'Application-Wide Privacy', grade: 'F', score: 10, tier: 'measured' }, { dim: 'External Attack Resistance', grade: 'F', score: 5, tier: 'measured' }, { dim: 'Valuation Methodology', grade: 'F', score: 10, tier: 'measured' }, { dim: 'Cryptographic Evidence Strength', grade: 'C−', score: 40, tier: 'inferred' }, { dim: 'Production Readiness', grade: 'D', score: 30, tier: 'inferred' }, { dim: 'Underwriting Readiness', grade: 'F', score: 10, tier: 'inferred' }, { dim: 'Overall', grade: 'D', score: 32, tier: 'inferred' }, ] const IMPL_DEFS = [ { bug: '.git in EXCLUDE_DIRS removed before has_git_dir check', impact: 'Git provenance never detected — has_git always false', sev: 'high' }, { bug: 'Filename containing "test" treated as evidence of tests', impact: 'Tests never executed — false test-passing signal', sev: 'medium' }, { bug: 'try/except/"error" treated as functioning error handling', impact: 'Error handling presence ≠ correctness', sev: 'medium' }, { bug: '"auth"/"hash"/"token" treated as security readiness', impact: 'Keyword presence ≠ security implementation', sev: 'high' }, { bug: 'API_KEY reading env vars classified as hardcoded secret', impact: 'False positive secret detection', sev: 'medium' }, { bug: 'ML analysis on 3-line chunk previews, not complete semantic units', impact: 'Topic modeling and anomaly detection degraded', sev: 'medium' }, { bug: '/systemlake registered twice', impact: 'Route conflict, undefined behavior', sev: 'low' }, { bug: '/systemlake redirects to / which is RentMasseur dashboard', impact: 'Underwriting upload interface lost', sev: 'high' }, { bug: 'In-memory state + daemon threads under restarts/multi-worker', impact: 'Unpredictable state, data loss on Uvicorn restart', sev: 'high' }, ] const CRYPTO_LIM = [ { issue: 'No canonical file sorting', impact: 'Different traversal order → different Merkle root for same package' }, { issue: 'File paths not committed into leaf', impact: 'Directory rename not detected' }, { issue: 'No permissions or package metadata in leaf', impact: 'Permission changes invisible' }, { issue: 'Denied files excluded entirely', impact: 'Missing files not represented as null leaves' }, { issue: 'Depends on filesystem traversal order', impact: 'Non-deterministic across OS/FS' }, { issue: 'Hashes hex hash strings again', impact: 'No versioned canonical leaf format defined' }, { issue: 'Receipt hashed but not signed', impact: 'Anyone can modify receipt and recompute hash — no issuer authenticity' }, { issue: 'No asymmetric signature / key ID / timestamp', impact: 'Not lender-grade — needs PKI signature, trusted timestamp, canonical JSON' }, ] const EVIDENCE_LAYERS = [ { key: 'technical', icon: TestTube, glyph: '⌁', label: 'Technical Evidence', items: ['Reproducible installation', 'Passing tests (executed, not filename-matched)', 'Runtime smoke test', 'Dependency lockfile', 'Supported OS environments', 'Benchmark results', 'Deterministic build receipt'] }, { key: 'security', icon: ShieldAlert, glyph: '⟁', label: 'Security Evidence (NIST SSDF)', items: ['Verified secret-scan results (full Git history)', 'Revoked + rotated credentials', 'Vulnerability scan (CVE)', 'Dependency audit', 'Threat model', 'Remediation record', 'Push protection enabled'] }, { key: 'supplychain', icon: Package, glyph: '◇', label: 'Supply-Chain Evidence (SBOM — CISA)', items: ['Component identities + versions', 'Component hashes', 'Licenses', 'Dependency relationships', 'SBOM generation tool + context', 'Generation timestamp'] }, { key: 'legal', icon: Gavel, glyph: '§', label: 'Legal Evidence', items: ['Authorship declaration', 'Chain of title', 'License manifest', 'Contributor assignments (CLAs)', 'Third-party code review', 'Litigation search', 'Prior-lien search (UCC-1)', 'Exact collateral description'] }, { key: 'economic', icon: Coins, glyph: '$', label: 'Economic Evidence (3 Approaches)', items: ['Cost: documented recreation cost', 'Market: actual comparable transactions', 'Income: forecast cash flow + discount rate', 'Useful life estimate', 'Probability adjustment', 'Attributable revenue/cost savings'] }, ] export default function FileDossier({ fileId, onClose }) { const [dossier, setDossier] = useState(null) const [loading, setLoading] = useState(true) const [error, setError] = useState(null) const [viewMode, setViewMode] = useState('visual') const [asciiDossier, setAsciiDossier] = useState('') const [expanded, setExpanded] = useState({}) const [copied, setCopied] = useState(false) const fetchDossier = useCallback(async () => { setLoading(true); setError(null) try { const res = await fetch(`${API_BASE}/resume/${fileId}`) const data = await res.json() if (data.error) setError(data.error); else setDossier(data.resume) } catch (e) { setError(e.message) } finally { setLoading(false) } }, [fileId]) const fetchAscii = useCallback(async () => { try { const res = await fetch(`${API_BASE}/resume/${fileId}?format=text`); setAsciiDossier(await res.text()) } catch { } }, [fileId]) useEffect(() => { fetchDossier() }, [fetchDossier]) useEffect(() => { if (viewMode === 'ascii' && !asciiDossier) fetchAscii() }, [viewMode, asciiDossier, fetchAscii]) const toggle = (k) => setExpanded(p => ({ ...p, [k]: !p[k] })) const copyDossier = () => { if (asciiDossier) { navigator.clipboard?.writeText(asciiDossier); setCopied(true); setTimeout(() => setCopied(false), 2000) } } if (loading) return (
Compiling audited underwriting dossier · security · privacy · valuation deconstruction · crypto · defects · evidence layers…
) if (error) return (
{error}
) if (!dossier) return null const r = dossier, id = r.identity || {}, dna = r.structural_dna || {}, kpi = r.kpi_summary || {} const fin = r.financial_profile || {}, legal = r.legal_profile || {}, ml = r.ml_insights || {} const val = r.valuation_summary || {}, risk = r.risk_assessment || {}, recs = r.recommendations || [] const llmFacts = r.llm_facts || [], header = r.header || {} const hasSecret = (risk.signals || []).some(s => s.includes('secret') || s.includes('credential') || s.includes('hardcoded')) const hasLit = (risk.signals || []).some(s => s.includes('litigation') || s.includes('legal')) const buildCostLabor = val.time_to_rebuild_days ? Math.round(val.time_to_rebuild_days * 8 * 60) : 0 const totalKpi = (kpi.total || 0) + (ml.inferred_kpis?.length || 0) + (llmFacts.length || 0) return (
{/* Header */}
{header.title || id.name || 'Unknown'}
{header.file_id || fileId} · v3.0 · UNDERWRITING DOSSIER — AUDITED
{onClose && }
{header.merkle_root?.slice(0, 24) || id.merkle_prefix || '—'}… {id.primary_purpose || 'unknown'} ⟁ NOT UNDERWRITABLE IN CURRENT FORM ◇ POTENTIALLY UNDERWRITABLE AFTER REMEDIATION
{/* Corrected Verdict */}
Corrected Verdict — Not Underwritable in Present Deployed Form
Cryptographically identified software asset with measurable structure, preliminary commercial utility, and unresolved security, privacy, and valuation risks. Contains ~{id.lines || 6000} lines, ~159 functions, ~94 FastAPI routes. Exposes critical unauthenticated endpoints, sends source-derived content to external LLMs despite metadata-only claims, and uses keyword-heuristic valuation that does not constitute underwriting evidence.
Corrected Bottom Line
Potentially underwritable after: architectural separation of privacy gateway from content analysis · security remediation (auth, path sanitization, endpoint isolation) · independent execution verification · replacement of keyword valuation with evidence-linked appraisal · signed cryptographic receipts
QUERY FULL FILE → {API_BASE}/meta/{fileId}
{viewMode === 'ascii' ? (
Underwriting Intelligence Report — Audited
{asciiDossier || 'Loading…'}
) : ( {/* Evidence Tier Legend */} Evidence Tiers: {Object.entries(TIERS).map(([key, t]) => (
{t.glyph} {t.label} {t.desc}
))}
{/* Privacy Contradiction */}
toggle('privacy')}>
"source_code_sent_to_llm: False" is only accurate for POST /upload evaluation path
{['First 2,000 chars of reconstructed file text for "30 facts"', 'First 1,500 chars for LLM extrapolation', 'File names, extracted KPIs, topics, source-derived previews', 'Fallback calls to Groq, OpenAI, or anonymous LLM7 endpoint'].map((item, i) => (
{item}
))}
Data Exfiltration Path
unauthenticated /index/path → read local server file → store source previews in SQLite → retrieve via /search, /chunk, /ml, or dossier → transmit previews to external LLM
RELEASE-BLOCKING
{/* Security Blockers */}
toggle('security')}>
{SEC_BL.map((b, i) => { const Icon = b.icon const sc = b.sev === 'CRITICAL' ? 'text-critical border-critical/30' : b.sev === 'HIGH' ? 'text-warning border-warning/30' : 'text-primary border-primary/30' return (
{b.sev} {b.finding}
→ {b.consequence}
) })}
{/* Identity + DNA */}
toggle('identity')}>
{id.all_purposes?.length > 0 && (
Detected Purposes
{id.all_purposes.map((p, i) => {p})}
)}
toggle('dna')}>
Complexity
{(dna.complexity_score || 0).toFixed(1)}
{dna.genes && Object.keys(dna.genes).length > 0 && (
Genes ({Object.keys(dna.genes).length})
{Object.entries(dna.genes).slice(0, 16).map(([k, v]) => ( {k}: {String(v).slice(0, 20)} ))}
)}
{/* Crypto Limitations */}
toggle('crypto')}>
Receipt is hashed, not signed
receipt_hash = SHA256(receipt) — anyone can modify and recompute. Not lender-grade.
{CRYPTO_LIM.map((c, i) => (
{c.issue}
→ {c.impact}
))}
Required for Lender-Grade
Asymmetric signature (Ed25519/ECDSA) · Key identifier · Canonical JSON encoding · Trusted timestamp (RFC 3161) · Verification procedure
{/* Valuation Deconstruction */}
toggle('valuation')}>
Exposed: Keyword-Heuristic Valuation Formula
Collateral: min(signal_count × 3, 100)
→ Document discussing "revenue", "collateral", "litigation" scores A. Terms ≠ ownership, enforceability, revenue, or liquidation value.
Liquidity: score ≥ 60 → time_to_liquidate = "days"
→ Semantically circular. File mentioning liquidity ≠ liquid.
Borrowing base: low = score × $5 · mid = score × $15 · high = score × $25
→ Price mapping, not appraisal. No comparable sales, advance rates, enforcement cost.
Insurance: replacement + $5K security + $10K payment + $8K auth + $3K readiness≥60
→ Fixed keyword bonuses, not insurance loss model.
Defensible Economic Interpretation
As-is salvage/recreation
$4,000–$12,000
Cost to production-harden
$20,000–$60,000
Current liquidation/collateral
$0–$2,500
Potential post-remediation
Substantially higher — dependent on real customers
{/* Defensible Scoring */}
toggle('scoring')}>
{DEFI_SCORES.map((s, i) => (
{TIERS[s.tier]?.glyph || '?'} {s.dim}
= 70 ? 'bg-success' : s.score >= 40 ? 'bg-warning' : 'bg-critical'}`} style={{ width: `${s.score}%` }} />
{s.grade} {s.score}/100
))}
Eligibility ≠ Bankability: software may legally be pledged, borrower may own it, lender may perfect security interest — yet asset may have negligible liquidation value without buyers, revenue, documentation, or operating system.
{/* Five Evidence Layers */}
toggle('evidence')}>
{EVIDENCE_LAYERS.map(layer => { const Icon = layer.icon return (
{layer.glyph} {layer.label} ALL UNVERIFIED
{layer.items.map((item, i) => (
?{item}
))}
) })}
{/* Implementation Defects */}
toggle('defects')}>
{IMPL_DEFS.map((d, i) => (
{d.sev === 'high' ? '⟁' : d.sev === 'medium' ? '▲' : '◇'}
{d.bug}
→ {d.impact}
{d.sev}
))}
{/* Financial + Legal */}
toggle('financial')}>
Collateral Grade: F (GATED)
Secret exposure gate triggered. Unconditional A grade is invalid when risk=90/100, secret_exposure, and litigation_risk exist.
{fin.has_financial_statements && ◆ Financial statements detected} {fin.finance_metrics && Object.keys(fin.finance_metrics).length > 0 && (
Metrics Detected
{Object.entries(fin.finance_metrics).map(([k, v]) => {k} ×{v})}
)}
toggle('legal')}>
UCC Article 9 — General Intangible
Software may legally be pledged. Does NOT establish market value, lender acceptance, ownership, priority, or recoverability.
{legal.has_contract_language && ⚠ Contract language detected} {legal.regulatory?.length > 0 && (
Regulatory
{legal.regulatory.map(r => {r})}
)} {legal.ip_references?.length > 0 && (
IP References
{legal.ip_references.map(r => {r})}
)}
{/* ML Insights */}
toggle('ml')}> {ml.available ? (
{ml.topics?.length > 0 && (
NMF Topics
{ml.topics.map((t, i) => (
T{t.id}
{t.keywords?.map((kw, j) => {kw})}
{t.chunk_count} chunks
))}
)} {ml.tfidf_top?.length > 0 && (
TF-IDF Top Terms
{ml.tfidf_top.map((t, i) => {typeof t === 'object' ? t.term || t : t})}
)}
{ml.information_density &&
Info Density
{ml.information_density} bits/char
} {ml.zipf_slope &&
Zipf Slope
{ml.zipf_slope}
} {ml.vocabulary_concentration &&
Vocab Concentration
{ml.vocabulary_concentration}
} {ml.topic_coherence &&
Topic Coherence
{ml.topic_coherence}
}
{ml.anomaly_count > 0 && (
{ml.anomaly_count} anomalous chunks (Isolation Forest) — analysis on 3-line previews, degraded accuracy
)} {ml.llm_extrapolation && (
LLM Extrapolation (⚠ uses source-derived content)
{ml.llm_extrapolation.inferred_purpose &&
Purpose: {ml.llm_extrapolation.inferred_purpose}
} {ml.llm_extrapolation.hidden_value &&
Hidden Value: {ml.llm_extrapolation.hidden_value}
} {ml.llm_extrapolation.counterparty_risk &&
Risk: {ml.llm_extrapolation.counterparty_risk}
} {ml.llm_extrapolation.monetization_vector &&
Monetization: {ml.llm_extrapolation.monetization_vector}
}
)}
) :
ML features unavailable — {ml.error || 'scikit-learn not installed'}
}
{/* KPI Summary — Expanded */}
toggle('kpi')}>
{kpi.by_category && Object.keys(kpi.by_category).length > 0 && (
{Object.entries(kpi.by_category).map(([cat, count]) => ( {cat}: {count} ))} {ml.inferred_kpis?.length > 0 && ml_inferred: {ml.inferred_kpis.length}} {llmFacts.length > 0 && llm_generated: {llmFacts.length}}
)} {kpi.top_financial?.length > 0 && (
Top Financial KPIs
{kpi.top_financial.map((k, i) => (
{k.name} {k.value} L{k.line}
))}
)} {kpi.top_technical?.length > 0 && (
Top Technical KPIs
{kpi.top_technical.map((k, i) => (
{k.name} {k.value} L{k.line}
))}
)} {ml.inferred_kpis?.length > 0 && (
ML-Inferred KPIs (◇ inferred)
{ml.inferred_kpis.map((k, i) => (
{k.name} {k.value} {k.method}
))}
)}
{/* Risk Assessment */}
toggle('risk')}>
{risk.level?.toUpperCase()}
{risk.score}/100
Origin
{risk.origin}
{risk.signals?.length > 0 && (
{risk.signals.map((s, i) => ⟁ {s})}
)}
Risk-Collateral Contradiction
Risk 90/100 + secret_exposure + litigation_risk → Collateral A (100/100) is invalid. Corrected: F (0/100) — gated.
{/* LLM Facts */} {llmFacts.length > 0 && (
toggle('llmfacts')}>
{llmFacts.map((fact, i) => (
{String(fact.id || i + 1).padStart(2, '0')} {fact.label} {fact.value} {fact.category} {((fact.confidence || 0) * 100).toFixed(0)}%
))}
⟡ Groq LLM · llama-3.3-70b ⚠ First 2,000 chars of file content sent to LLM
)} {/* Recommendations */}
toggle('recs')}>
{recs.map((rec, i) => (
{PG[rec.priority] || '◌'}
{rec.action} {rec.priority}
{rec.reason}
))}
{/* Strongest Product */}
toggle('product')}>
Privacy-scoped software evidence gateway
Creates reproducible structural manifests and signed evaluation packets without transferring source code to an evaluator. To make this statement true, the underwriting gateway must be physically separated from Jorki content analysis, deployment automation, audio processing, and RentMasseur operations.
Separate from:
Content analysis · LLM calls · Deployment · Audio · RentMasseur
Keep in gateway:
Hashing · Merkle · Metadata · KPI extraction · Signed receipts
)}
) } // ─── Sub-components ─── function Section({ icon: Icon, glyph, title, tier, expanded, onToggle, children }) { const t = TIERS[tier] || TIERS.unverified return ( {expanded !== false && (
{children}
)}
) } function SR({ label, value, mono, tier }) { const t = TIERS[tier] || TIERS.unverified return (
{label}
{t.glyph} {value ?? '—'}
) } function CVC({ label, stated, corrected, note, status }) { return (
{label}
{stated}
{corrected}
{note}
{status === 'corrected' ? '⚠ CORRECTED' : '↻ RELABELED'}
) } function VAC({ label, glyph, icon: Icon, value, confidence, tier, detail, assumptions }) { const t = TIERS[tier] || TIERS.unverified const confColor = confidence === 'LOW' ? 'text-warning' : 'text-critical' return (
{t.glyph} {label}
{value}
Confidence: {confidence}
{detail}
{assumptions.map((a, i) =>
• {a}
)}
) } function GC2({ label, grade, score }) { return (
{label}
{grade} {score}/100
) }