-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1997 lines (1671 loc) · 75.4 KB
/
main.py
File metadata and controls
1997 lines (1671 loc) · 75.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Project Anchor – Main Orchestrator & CLI
Entry point for the forensic research aggregation system.
Coordinates all modules and provides a command-line interface.
Usage:
python main.py --all Run complete pipeline
python main.py --collect Data collection only
python main.py --analyze-pdf FILE Analyze a specific PDF
python main.py --physics Run physics computations
python main.py --waves Run wave science computations
python main.py --nlp Run NLP analysis on collected data
python main.py --graph Build propagation graph
python main.py --report Generate all reports
python main.py --dashboard Launch interactive dashboard
python main.py --static-report Generate static HTML report
python main.py --taxonomy Load taxonomy knowledge base into DB
python main.py --taxonomy-search Search taxonomy entries
python main.py --taxonomy-export Export taxonomy to JSON
python main.py --arxiv TERM Search arXiv for a term
python main.py --extended-search Run all extended terms through scrapers
Phase II:
python main.py --key-generate Generate Ed25519 signing keypair
python main.py --sign-cid CID Sign a CID with default key
python main.py --verify-cid CID Verify a CID signature
python main.py --snapshot Create Merkle snapshot of database
python main.py --verify-snapshot Verify latest Merkle snapshot
python main.py --ipns-publish CID Publish CID to IPNS
python main.py --ipns-resolve Resolve current IPNS pointer
python main.py --generate-audit Generate comprehensive audit report
python main.py --foia-search Q Search all FOIA sources for query
python main.py --tesla Run Tesla full investigation
python main.py --load-scientists Load scientist cases database
python main.py --search-scientists QUERY Search scientist cases
python main.py --gateway-health Check multi-gateway health
"""
import argparse
import sys
from pathlib import Path
from src.config import SEARCH_TERMS, ACADEMIC_TERMS, ALL_EXTENDED_TERMS
from src.database import init_db
from src.logger import get_logger
from src.reports import ReportGenerator
log = get_logger("main")
def run_collection():
"""Execute all data collection scrapers."""
log.info("=" * 60)
log.info("PHASE 1: DATA COLLECTION")
log.info("=" * 60)
from src.collectors.reddit_scraper import RedditScraper
from src.collectors.wayback_scraper import WaybackScraper
from src.collectors.web_search_scraper import WebSearchScraper
scrapers = [
RedditScraper(),
WaybackScraper(),
WebSearchScraper(),
]
for scraper in scrapers:
log.info("Running scraper: %s", scraper.platform)
try:
scraper.run_all_terms(SEARCH_TERMS)
except Exception as exc:
log.error("Scraper %s failed: %s", scraper.platform, exc)
def run_academic_search():
"""Search academic databases."""
log.info("=" * 60)
log.info("PHASE 2: ACADEMIC CROSS-REFERENCE")
log.info("=" * 60)
from src.crossref.academic_records import AcademicCrossRef
acad = AcademicCrossRef()
for term in ACADEMIC_TERMS:
try:
acad.search(term)
except Exception as exc:
log.error("Academic search failed for '%s': %s", term, exc)
# Specific author search
try:
results = acad.search_author("Thomas Webb")
log.info("Author 'Thomas Webb' search: %d profiles", len(results))
except Exception as exc:
log.error("Author search failed: %s", exc)
def run_government_crossref():
"""Search public government records."""
log.info("=" * 60)
log.info("PHASE 3: GOVERNMENT RECORD CROSS-REFERENCE")
log.info("=" * 60)
from src.crossref.government_records import GovernmentCrossRef
gov = GovernmentCrossRef()
search_terms = ["Project Anchor", "Thomas Webb NASA", "gravity anomaly research"]
for term in search_terms:
try:
gov.search(term)
except Exception as exc:
log.error("Government search failed for '%s': %s", term, exc)
def run_pdf_analysis(filepath: str):
"""Analyze a specific PDF document."""
log.info("=" * 60)
log.info("PHASE 4: PDF DOCUMENT ANALYSIS")
log.info("=" * 60)
from src.analyzers.pdf_analyzer import PDFAnalyzer
path = Path(filepath)
if not path.exists():
log.error("File not found: %s", filepath)
return
analyzer = PDFAnalyzer(path)
analyzer.save_to_db(source_url=str(path))
# Print summary
meta = analyzer.extract_metadata()
fonts = analyzer.extract_fonts()
markings = analyzer.detect_classification_markings()
report = analyzer.check_structural_consistency()
log.info("Metadata: %s", meta)
log.info("Fonts: %s", fonts)
log.info("Markings: %s", markings)
log.info("Inconsistencies: %d found", len(report.get("inconsistencies", [])))
def run_physics():
"""Execute gravitational physics computation suite."""
log.info("=" * 60)
log.info("PHASE 5: PHYSICS CONSISTENCY ANALYSIS")
log.info("=" * 60)
from src.physics.gravity_engine import GravityPhysicsEngine
engine = GravityPhysicsEngine()
results = engine.run_full_comparison()
for r in results:
log.info(
" %-60s %.4e %s",
r["description"],
r["value"],
r["units"],
)
def run_waves():
"""Execute wave science computation suite."""
log.info("=" * 60)
log.info("WAVE SCIENCE COMPUTATIONS")
log.info("=" * 60)
from src.physics.wave_engine import WaveScienceEngine
engine = WaveScienceEngine()
results = engine.run_full_suite()
for r in results:
log.info(
" %-60s %.4e %s",
r["description"],
r["value"],
r["units"],
)
def run_nlp():
"""Run NLP narrative analysis on collected posts."""
log.info("=" * 60)
log.info("PHASE 6: NARRATIVE STRUCTURE ANALYSIS")
log.info("=" * 60)
from src.nlp.narrative_analyzer import NarrativeAnalyzer
analyzer = NarrativeAnalyzer()
report = analyzer.analyze_all_posts()
log.info("NLP report: %s", report)
def run_graph():
"""Build and analyze propagation graph."""
log.info("=" * 60)
log.info("PHASE 7: PROPAGATION GRAPH ANALYSIS")
log.info("=" * 60)
from src.graph.propagation_graph import PropagationGraph
graph = PropagationGraph()
graph.build_from_db()
metrics = graph.compute_metrics()
timeline = graph.generate_timeline()
clusters = graph.detect_amplification_clusters()
log.info("Graph metrics: %s", metrics)
log.info("Timeline events: %d", len(timeline))
log.info("Clusters: %d", len(clusters))
graph.export_graphml()
graph.export_json()
graph.plot_timeline()
def run_reports():
"""Generate all structured reports."""
log.info("=" * 60)
log.info("GENERATING REPORTS")
log.info("=" * 60)
gen = ReportGenerator()
paths = gen.generate_all()
for name, path in paths.items():
log.info(" %s → %s", name, path)
def run_static_report():
"""Generate static HTML dashboard report."""
from src.dashboard.dashboard import Dashboard
dash = Dashboard()
path = dash.generate_static_report()
log.info("Static report: %s", path)
def run_dashboard():
"""Launch interactive dashboard."""
from src.dashboard.dashboard import Dashboard
dash = Dashboard()
dash.launch_interactive()
# ── IPFS Functions ───────────────────────────────────────────────────────────
def _get_ipfs_client():
"""Create and return an IPFS client, with connectivity check."""
from src.ipfs.ipfs_client import IPFSClient
client = IPFSClient()
if not client.is_online():
log.error("IPFS node is not reachable. Is Kubo running?")
return None
return client
def run_ipfs_status():
"""Show IPFS node status and archive statistics."""
log.info("=" * 60)
log.info("IPFS NODE STATUS")
log.info("=" * 60)
client = _get_ipfs_client()
if not client:
return
summary = client.status_summary()
for key, val in summary.items():
log.info(" %-20s %s", key, val)
from src.ipfs.evidence_archiver import EvidenceArchiver
archiver = EvidenceArchiver(client)
status = archiver.get_archive_status()
log.info("")
log.info(" Archive total pinned: %d", status["total_pinned"])
log.info(" Chain head CID: %s", status["chain_head"])
log.info(" Chain length: %d", status["chain_length"])
if status["by_type"]:
for t, c in status["by_type"].items():
log.info(" %-30s %d", t, c)
def run_ipfs_archive():
"""Archive all research evidence to IPFS."""
log.info("=" * 60)
log.info("IPFS EVIDENCE ARCHIVE")
log.info("=" * 60)
client = _get_ipfs_client()
if not client:
return
from src.ipfs.evidence_archiver import EvidenceArchiver
archiver = EvidenceArchiver(client)
report = archiver.archive_all()
log.info("Archive complete:")
log.info(" Total items pinned: %d", report["total_items_pinned"])
log.info(" Chain head: %s", report.get("proof_chain_head"))
log.info(" Manifest CID: %s", report.get("manifest_cid"))
log.info(" Errors: %d", len(report.get("errors", [])))
if report.get("ipns"):
log.info(" IPNS name: %s", report["ipns"].get("Name"))
def run_ipfs_pin_file(filepath: str):
"""Pin a specific file to IPFS and add to proof chain."""
log.info("=" * 60)
log.info("IPFS PIN FILE")
log.info("=" * 60)
client = _get_ipfs_client()
if not client:
return
from src.ipfs.proof_chain import ProofChain
chain = ProofChain(client)
result = chain.add_file_evidence(filepath)
log.info("File pinned to IPFS:")
log.info(" Evidence CID: %s", result["evidence_cid"])
log.info(" Proof CID: %s", result["proof_link_cid"])
log.info(" Gateway URL: %s", result["gateway_url"])
log.info(" Sequence: %d", result["sequence"])
def run_ipfs_verify():
"""Verify the integrity of the IPFS proof chain."""
log.info("=" * 60)
log.info("IPFS PROOF CHAIN VERIFICATION")
log.info("=" * 60)
client = _get_ipfs_client()
if not client:
return
from src.ipfs.proof_chain import ProofChain
chain = ProofChain(client)
report = chain.verify_chain()
log.info("Verification result:")
log.info(" Status: %s", report["status"])
log.info(" Links verified: %d", report["links_verified"])
log.info(" Head CID: %s", report.get("head_cid"))
if report.get("broken_links"):
for b in report["broken_links"]:
log.warning(" BROKEN: seq=%s cid=%s error=%s",
b.get("sequence"), b.get("cid"), b.get("error"))
# ── Taxonomy & Extended Search Functions ─────────────────────────────────────
def run_taxonomy_load():
"""Load all taxonomy entries into the database."""
log.info("=" * 60)
log.info("TAXONOMY KNOWLEDGE BASE – LOADING")
log.info("=" * 60)
from src.taxonomy.knowledge_base import save_all_to_db, get_all_entries
entries = get_all_entries()
log.info("Total taxonomy entries: %d", len(entries))
save_all_to_db()
log.info("All taxonomy entries saved to database.")
def run_taxonomy_search(query: str):
"""Search taxonomy entries for a term."""
log.info("=" * 60)
log.info("TAXONOMY SEARCH: '%s'", query)
log.info("=" * 60)
from src.taxonomy.knowledge_base import search_taxonomy
results = search_taxonomy(query)
log.info("Found %d matching entries:", len(results))
for entry in results:
log.info(" [%s/%s] %s – %s (status: %s)",
entry.category, entry.subcategory,
entry.term, entry.definition[:80],
entry.verification_status)
def run_taxonomy_export():
"""Export taxonomy knowledge base to JSON."""
log.info("=" * 60)
log.info("TAXONOMY EXPORT")
log.info("=" * 60)
from src.taxonomy.knowledge_base import export_taxonomy_json
from src.config import REPORTS_DIR
output_path = REPORTS_DIR / "taxonomy_knowledge_base.json"
data = export_taxonomy_json()
import json
output_path.parent.mkdir(parents=True, exist_ok=True)
output_path.write_text(json.dumps(data, indent=2), encoding="utf-8")
log.info("Taxonomy exported to: %s", output_path)
log.info("Total entries: %d", len(data))
def run_arxiv_search(term: str):
"""Search arXiv for a specific term."""
log.info("=" * 60)
log.info("arXiv SEARCH: '%s'", term)
log.info("=" * 60)
from src.crossref.research_sources import ArxivScraper
scraper = ArxivScraper()
results = scraper.search_gravity_propulsion(term, max_results=25)
log.info("arXiv returned %d papers for '%s'", len(results), term)
for r in results:
log.info(" [%s] %s – %s", r.get("year", "?"), r.get("title", "?")[:70], r.get("journal", ""))
def run_extended_search():
"""Run all extended search terms through arXiv and DTIC scrapers."""
log.info("=" * 60)
log.info("EXTENDED RESEARCH SOURCE SEARCH")
log.info("=" * 60)
from src.crossref.research_sources import ArxivScraper, DTICScraper
arxiv = ArxivScraper()
dtic = DTICScraper()
total_arxiv = 0
total_dtic = 0
for term in ALL_EXTENDED_TERMS:
log.info("Searching: '%s'", term)
try:
results = arxiv.search_gravity_propulsion(term, max_results=10)
total_arxiv += len(results)
except Exception as exc:
log.error("arXiv failed for '%s': %s", term, exc)
try:
results = dtic.search(term)
total_dtic += len(results)
except Exception as exc:
log.error("DTIC failed for '%s': %s", term, exc)
log.info("Extended search complete:")
log.info(" Total arXiv papers: %d", total_arxiv)
log.info(" Total DTIC records: %d", total_dtic)
log.info(" Search terms used: %d", len(ALL_EXTENDED_TERMS))
# ── Phase II: Crypto / Proof / FOIA / Investigation Functions ────────────────
def run_key_generate():
"""Generate a new Ed25519 signing keypair."""
log.info("=" * 60)
log.info("GENERATE ED25519 KEYPAIR")
log.info("=" * 60)
from src.crypto.signature_manager import SignatureManager
mgr = SignatureManager()
info = mgr.generate_keypair()
log.info(" Key name: %s", info.key_name)
log.info(" Fingerprint: %s", info.fingerprint)
log.info(" Created: %s", info.created_at)
log.info(" Keys dir: %s", mgr.keys_dir)
def run_sign_cid(cid: str):
"""Sign a CID with the default (latest) key."""
log.info("=" * 60)
log.info("SIGN CID: %s", cid)
log.info("=" * 60)
from src.crypto.signature_manager import SignatureManager
mgr = SignatureManager()
result = mgr.sign_cid(cid)
if result:
log.info(" Signature: %s…", result["signature_hex"][:64])
log.info(" Fingerprint: %s", result["fingerprint"])
else:
log.error("Signing failed. Do you have a keypair? Run --key-generate first.")
def run_verify_cid(cid: str):
"""Verify a CID signature."""
log.info("=" * 60)
log.info("VERIFY CID: %s", cid)
log.info("=" * 60)
from src.crypto.signature_manager import SignatureManager
from src.database import get_connection
conn = get_connection()
row = conn.execute(
"SELECT signature, pubkey_fingerprint FROM ipfs_evidence WHERE cid = ? AND signature IS NOT NULL",
(cid,)
).fetchone()
conn.close()
if not row:
log.error("No signed evidence found for CID: %s", cid)
return
mgr = SignatureManager()
result = mgr.verify_cid(cid, row[0])
if result.get("verified"):
log.info(" ✓ Signature VALID for CID %s", cid)
else:
log.error(" ✗ Signature INVALID for CID %s: %s", cid, result.get("error", ""))
def run_snapshot():
"""Create a Merkle snapshot of the current database state."""
log.info("=" * 60)
log.info("CREATE MERKLE SNAPSHOT")
log.info("=" * 60)
from src.proofs.merkle_snapshot import MerkleSnapshotEngine
engine = MerkleSnapshotEngine()
snap = engine.create_snapshot()
log.info(" Root hash: %s", snap["root_hash"])
log.info(" Leaf count: %d", snap["leaf_count"])
log.info(" IPFS CID: %s", snap.get("ipfs_cid", "N/A"))
log.info(" Snapshot ID: %s", snap.get("id", "?"))
def run_verify_snapshot():
"""Verify the latest Merkle snapshot against current DB state."""
log.info("=" * 60)
log.info("VERIFY MERKLE SNAPSHOT")
log.info("=" * 60)
from src.proofs.merkle_snapshot import MerkleSnapshotEngine
engine = MerkleSnapshotEngine()
latest = engine.get_latest_root()
if not latest:
log.error("No snapshots found. Create one with --snapshot first.")
return
ok = engine.verify_snapshot(latest)
if ok:
log.info(" ✓ Database integrity VERIFIED – root matches: %s", latest)
else:
log.error(" ✗ Database MODIFIED since last snapshot (root was: %s)", latest)
def run_ipns_publish(cid: str):
"""Publish a CID to IPNS."""
log.info("=" * 60)
log.info("IPNS PUBLISH: %s", cid)
log.info("=" * 60)
from src.ipfs.ipns_publisher import IPNSPublisher
publisher = IPNSPublisher()
result = publisher.publish(cid)
if result:
log.info(" IPNS Name: %s", result.get("Name"))
log.info(" Value: %s", result.get("Value"))
else:
log.error("IPNS publish failed. Is IPFS running?")
def run_ipns_resolve():
"""Resolve current IPNS pointer."""
log.info("=" * 60)
log.info("IPNS RESOLVE")
log.info("=" * 60)
from src.ipfs.ipns_publisher import IPNSPublisher
publisher = IPNSPublisher()
path = publisher.resolve()
if path:
log.info(" Resolved path: %s", path)
else:
log.error("IPNS resolve failed or no name published yet.")
def run_generate_audit():
"""Generate comprehensive audit report in all formats."""
log.info("=" * 60)
log.info("GENERATE AUDIT REPORT")
log.info("=" * 60)
from src.reports.audit_generator import AuditReportGenerator
gen = AuditReportGenerator()
report = gen.generate_full_report()
log.info("Audit report generated with %d sections.", len(report.get("sections", {})))
log.info(" Exported to: reports/audits/")
def run_foia_search(query: str):
"""Search all FOIA sources for a query."""
log.info("=" * 60)
log.info("FOIA SEARCH: '%s'", query)
log.info("=" * 60)
from src.foia.foia_ingester import FOIASearchEngine
engine = FOIASearchEngine()
results = engine.search_all(query)
log.info("Results by source:")
for source, docs in results.items():
log.info(" %-20s %d documents", source, len(docs))
total = sum(len(d) for d in results.values())
log.info(" Total: %d documents ingested", total)
def run_tesla_investigation():
"""Run the full Tesla investigation protocol."""
log.info("=" * 60)
log.info("TESLA INVESTIGATION – FULL PROTOCOL")
log.info("=" * 60)
from src.investigations.tesla_module import TeslaInvestigation
tesla = TeslaInvestigation()
report = tesla.run_full_investigation()
log.info("Tesla investigation complete:")
log.info(" Case ID: %s", report.get("case_id", "?"))
log.info(" Phases run: %d", len(report.get("phases", {})))
for phase_name, phase_data in report.get("phases", {}).items():
if isinstance(phase_data, dict):
log.info(" %-25s %d items", phase_name,
len(phase_data.get("results", phase_data.get("claims", phase_data.get("clusters", [])))))
elif isinstance(phase_data, list):
log.info(" %-25s %d items", phase_name, len(phase_data))
def run_load_scientist_cases():
"""Load all scientist cases into the database."""
log.info("=" * 60)
log.info("SCIENTIST CASES – LOADING")
log.info("=" * 60)
from src.investigations.scientist_cases import ScientistCasesDatabase
db = ScientistCasesDatabase()
loaded = db.load_all_cases()
log.info("Loaded %d new scientist cases into database.", loaded)
stats = db.get_statistics()
log.info(" Disputed: %d", stats.get("disputed_cases", 0))
log.info(" By field: %s", stats.get("by_field", {}))
def run_search_scientists(query: str):
"""Search scientist cases database."""
log.info("=" * 60)
log.info("SCIENTIST CASES – SEARCH: '%s'", query)
log.info("=" * 60)
from src.investigations.scientist_cases import ScientistCasesDatabase
db = ScientistCasesDatabase()
results = db.search_cases(query)
log.info("Found %d matching cases:", len(results))
for case in results:
log.info(" [%s] %s – %s (%s)", case.get("year", "?"),
case.get("name", "?"), case.get("field", "?"),
case.get("official_cause", "?"))
def run_gateway_health():
"""Check health of all configured IPFS gateways."""
log.info("=" * 60)
log.info("MULTI-GATEWAY HEALTH CHECK")
log.info("=" * 60)
from src.ipfs.multi_gateway import MultiGatewayPinner
pinner = MultiGatewayPinner()
report = pinner.gateway_health_check()
for gw in report:
status = "✓ OK" if gw.get("healthy") else "✗ DOWN"
log.info(" %-40s %s (%dms)", gw.get("gateway", "?"), status,
gw.get("response_time_ms", 0))
# ── Phase III: Math Forensics CLI handlers ──────────────────────────────
def run_parse_equation(text: str):
"""Parse a plaintext equation."""
log.info("=" * 60)
log.info("EQUATION PARSER – PLAINTEXT")
log.info("=" * 60)
from src.math.equation_parser import EquationParser
parser = EquationParser()
result = parser.parse_plaintext(text, name="cli_input")
if result.parse_error:
log.error("Parse error: %s", result.parse_error)
else:
log.info(" Name: %s", result.name)
log.info(" SymPy: %s", result.sympy_repr)
log.info(" LaTeX: %s", result.latex_form)
log.info(" Simplified: %s", result.simplified_form)
log.info(" Symbols: %s", ", ".join(result.symbols_found))
log.info(" SHA-256: %s", result.sha256)
if result.is_equation:
log.info(" LHS: %s", result.lhs)
log.info(" RHS: %s", result.rhs)
metrics = parser.get_complexity_metrics(result)
log.info(" Complexity: %s (ops=%d, depth=%d)",
metrics["complexity_class"], metrics["operation_count"],
metrics["tree_depth"])
def run_parse_latex(latex: str):
"""Parse a LaTeX equation string."""
log.info("=" * 60)
log.info("EQUATION PARSER – LaTeX")
log.info("=" * 60)
from src.math.equation_parser import EquationParser
parser = EquationParser()
result = parser.parse_latex(latex, name="cli_latex")
if result.parse_error:
log.error("Parse error: %s", result.parse_error)
else:
log.info(" SymPy: %s", result.sympy_repr)
log.info(" Simplified: %s", result.simplified_form)
log.info(" Symbols: %s", ", ".join(result.symbols_found))
log.info(" SHA-256: %s", result.sha256)
def run_dim_check(eq_name: str):
"""Dimensional analysis on a known equation."""
log.info("=" * 60)
log.info("DIMENSIONAL ANALYSIS – %s", eq_name)
log.info("=" * 60)
from src.math.dimensional_analyzer import DimensionalAnalyzer
analyzer = DimensionalAnalyzer()
report = analyzer.check_known_equation(eq_name)
if report is None:
log.error("Unknown equation name '%s'. Known: newton_gravity, einstein_energy, "
"coulomb, gravitational_pe, kinetic_energy, escape_velocity", eq_name)
return
log.info(" Status: %s", report.status)
log.info(" LHS dimension: %s", report.lhs_dimension or "(none)")
log.info(" RHS dimension: %s", report.rhs_dimension or "(none)")
log.info(" Match: %s", report.dimensions_match)
if report.errors:
for e in report.errors:
log.error(" ERROR: %s", e)
if report.warnings:
for w in report.warnings:
log.warning(" WARN: %s", w)
def run_simplify_equation(text: str):
"""Simplify an expression using symbolic refactoring."""
log.info("=" * 60)
log.info("SYMBOLIC SIMPLIFY")
log.info("=" * 60)
from src.math.equation_parser import EquationParser
from src.math.symbolic_refactor import SymbolicRefactor
parser = EquationParser()
parsed = parser.parse_plaintext(text, name="cli_simplify")
if parsed.parse_error:
log.error("Parse error: %s", parsed.parse_error)
return
refactor = SymbolicRefactor()
result = refactor.simplify(parsed)
log.info(" Input: %s", result.input_expr)
log.info(" Output: %s", result.output_expr)
log.info(" Equivalent: %s", result.is_equivalent)
log.info(" Complexity: %d → %d", result.complexity_before, result.complexity_after)
def run_math_audit():
"""Run full math forensics audit on built-in known equations."""
log.info("=" * 60)
log.info("MATHEMATICAL FORENSICS AUDIT")
log.info("=" * 60)
from src.math.equation_parser import EquationParser
from src.math.dimensional_analyzer import DimensionalAnalyzer
from src.math.symbolic_refactor import SymbolicRefactor
from src.math.equation_audit_report import EquationAuditReport
parser = EquationParser()
analyzer = DimensionalAnalyzer()
refactor = SymbolicRefactor()
# Parse known equations
known = {
"Einstein E=mc²": "E = m*c**2",
"Newton Gravity": "F = G*M*m/r**2",
"Kinetic Energy": "E = m*v**2/2",
"Gravitational PE": "E = -G*M*m/r",
"Escape Velocity": "v = (2*G*M/r)**(1/2)",
}
parsed_eqs = []
dim_reports = []
refactor_results = []
for name, text in known.items():
p = parser.parse_plaintext(text, name=name)
parsed_eqs.append(p)
dim_reports.append(analyzer.analyze(p))
refactor_results.append(refactor.simplify(p))
report_gen = EquationAuditReport()
report_text = report_gen.generate(
parsed_equations=parsed_eqs,
dimensional_reports=dim_reports,
refactor_results=refactor_results,
)
print(report_text)
# ── Phase III: Claim Graph CLI handlers ─────────────────────────────────
def run_add_claim(text: str):
"""Add a claim to the evidence graph."""
log.info("=" * 60)
log.info("CLAIM GRAPH – ADD CLAIM")
log.info("=" * 60)
from src.graph.claim_graph import ClaimGraph
graph = ClaimGraph()
claim_id = graph.add_claim(claim_text=text)
log.info(" Claim #%d added.", claim_id)
def run_add_source(title: str):
"""Add a source node."""
log.info("=" * 60)
log.info("CLAIM GRAPH – ADD SOURCE")
log.info("=" * 60)
from src.graph.claim_graph import ClaimGraph
graph = ClaimGraph()
source_id = graph.add_source(title=title)
log.info(" Source #%d added.", source_id)
def run_link_claim(spec: str):
"""Link two nodes: 'claim_id,source_id,relationship'."""
log.info("=" * 60)
log.info("CLAIM GRAPH – LINK")
log.info("=" * 60)
parts = spec.split(",")
if len(parts) < 3:
log.error("Format: claim_id,source_id,relationship")
return
from src.graph.claim_graph import ClaimGraph
graph = ClaimGraph()
link_id = graph.link(
from_type="claim", from_id=int(parts[0]),
to_type="source", to_id=int(parts[1]),
relationship=parts[2].strip(),
)
log.info(" Link #%d created.", link_id)
def run_claim_stats():
"""Show claim graph statistics."""
log.info("=" * 60)
log.info("CLAIM GRAPH – STATISTICS")
log.info("=" * 60)
from src.graph.claim_graph import ClaimGraph
graph = ClaimGraph()
stats = graph.get_statistics()
log.info(" Claims: %d", stats["total_claims"])
log.info(" Sources: %d", stats["total_sources"])
log.info(" Links: %d", stats["total_links"])
log.info(" Contradictions: %d", stats["total_contradictions"])
log.info(" Avg confidence: %.2f", stats["avg_confidence"])
log.info(" By type: %s", stats["claims_by_type"])
log.info(" By status: %s", stats["claims_by_status"])
def run_provenance(claim_id: int):
"""Show provenance chain for a claim."""
log.info("=" * 60)
log.info("CLAIM GRAPH – PROVENANCE (claim #%d)", claim_id)
log.info("=" * 60)
from src.graph.claim_graph import ClaimGraph
graph = ClaimGraph()
chain = graph.get_provenance(claim_id)
for node in chain:
indent = " " * (node["depth"] + 1)
label = node.get("text", node.get("title", "?"))[:60]
log.info("%s[%s#%d] %s", indent, node["type"], node["id"], label)
def run_contradictions():
"""List all contradictions in the claim graph."""
log.info("=" * 60)
log.info("CLAIM GRAPH – CONTRADICTIONS")
log.info("=" * 60)
from src.graph.claim_graph import ClaimGraph
graph = ClaimGraph()
contradictions = graph.find_contradictions()
if not contradictions:
log.info(" No contradictions found.")
return
for c in contradictions:
log.info(" Link #%d: %s#%d ↔ %s#%d",
c["link_id"], c["from_type"], c["from_id"],
c["to_type"], c["to_id"])
if "from_text" in c:
log.info(" FROM: %s", c["from_text"][:80])
if "to_text" in c:
log.info(" TO: %s", c["to_text"][:80])
# ── Phase IV: Claim Confidence & Mutation Entropy CLI handlers ────────
def run_score_claim(claim_id: int):
"""Score a single claim with the Bayesian confidence engine."""
log.info("=" * 60)
log.info("CONFIDENCE SCORER – CLAIM #%d", claim_id)
log.info("=" * 60)
from src.graph.confidence_scorer import ConfidenceScorer
scorer = ConfidenceScorer()
score = scorer.score_claim(claim_id)
log.info(" Composite: %.4f", score.composite)
log.info(" %-20s %.4f", "prior", score.prior)
log.info(" %-20s %.4f", "source_credibility", score.source_credibility)
log.info(" %-20s %.4f", "citation_support", score.citation_support)
log.info(" %-20s %.4f", "contradiction", score.contradiction_penalty)
log.info(" %-20s %.4f", "verification", score.verification_bonus)
log.info(" %-20s %.4f", "mutation_decay", score.mutation_decay)
scorer.save_score(score)
log.info(" Score saved to database.")
def run_score_all():
"""Score all claims and rank by confidence."""
log.info("=" * 60)
log.info("CONFIDENCE SCORER – ALL CLAIMS")
log.info("=" * 60)
from src.graph.confidence_scorer import ConfidenceScorer
scorer = ConfidenceScorer()
results = scorer.score_all_claims()
log.info(" Scored %d claims.", len(results))
ranked = scorer.rank_claims(top_n=20)
for cid, sc, text in ranked:
log.info(" #%-4d %.4f %s", cid, sc, text)
def run_mutation_entropy(claim_id: int):
"""Analyze mutation entropy for a claim chain."""
log.info("=" * 60)
log.info("MUTATION ENTROPY – CLAIM #%d", claim_id)
log.info("=" * 60)
from src.graph.mutation_entropy import MutationEntropy
engine = MutationEntropy()
metrics = engine.analyze_chain(claim_id)
if metrics:
log.info(" Chain length: %d", metrics.chain_length)
log.info(" Shannon entropy: %.4f", metrics.shannon_entropy)
log.info(" Drift velocity: %.4f", metrics.drift_velocity)
log.info(" Max diff ratio: %.4f", metrics.max_diff_ratio)
log.info(" Semantic stability: %.4f", metrics.semantic_stability)
engine.save_metrics(metrics)
log.info(" Metrics saved to database.")
else:
log.info(" No mutation chain found for claim #%d.", claim_id)
def run_citation_density(claim_id: int):
"""Analyze citation density for a claim."""
log.info("=" * 60)
log.info("CITATION DENSITY – CLAIM #%d", claim_id)
log.info("=" * 60)
from src.graph.citation_density import CitationDensity
engine = CitationDensity()
metrics = engine.analyze_claim(claim_id)
if metrics:
log.info(" Direct citations: %d", metrics.direct_citations)
log.info(" Unique sources: %d", metrics.unique_sources)
log.info(" Supporting claims: %d", metrics.supporting_claims)
log.info(" Contradicting: %d", metrics.contradicting_claims)
log.info(" Citation depth: %d", metrics.citation_depth)
log.info(" Density score: %.4f", metrics.density_score)
else:
log.info(" Claim #%d not found.", claim_id)
def run_tension_map():
"""Show contradiction tension map across all claims."""
log.info("=" * 60)
log.info("CONTRADICTION TENSION MAP")
log.info("=" * 60)
from src.graph.contradiction_analyzer import ContradictionAnalyzer
analyzer = ContradictionAnalyzer()
tmap = analyzer.tension_map()