This repository was archived by the owner on Jan 21, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
executable file
·1873 lines (1462 loc) · 65.2 KB
/
cli.py
File metadata and controls
executable file
·1873 lines (1462 loc) · 65.2 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
#!/usr/bin/env python3
"""
CIPHER CLI
Command-line interface for interacting with the Cipher system.
Usage:
python cli.py status # Show system status
python cli.py stats # Show knowledge base statistics
python cli.py insights # Show top cross-domain insights
python cli.py search <query> # Search claims
python cli.py learn <domain> # Trigger learning for domain
python cli.py think # Show recent thoughts
"""
import asyncio
import argparse
import os
import sys
from pathlib import Path
from datetime import datetime
sys.path.insert(0, str(Path(__file__).parent))
# Load environment variables from .env file if present
try:
from dotenv import load_dotenv
env_path = Path(__file__).parent / '.env'
if env_path.exists():
load_dotenv(env_path)
except ImportError:
pass # python-dotenv not installed
from config.settings import config
async def show_status():
"""Show system status."""
import asyncpg
print("CIPHER System Status")
print("=" * 50)
print(f"Iron Code: {config.iron_code}")
print(f"Base Path: {config.paths.base_path}")
print()
# Check database
print("Database Connection:")
try:
conn = await asyncpg.connect(config.db.connection_string)
version = await conn.fetchval("SELECT version()")
print(f" Status: Connected")
print(f" Version: {version[:50]}...")
await conn.close()
except Exception as e:
print(f" Status: Error - {e}")
# Check directories
print("\nDirectories:")
for name, path in [
("Mind", config.paths.mind_path),
("Tools", config.paths.tools_path),
("Logs", config.paths.logs_path),
]:
exists = path.exists()
print(f" {name}: {'OK' if exists else 'MISSING'} ({path})")
async def show_stats():
"""Show knowledge base statistics."""
import asyncpg
print("CIPHER Knowledge Base Statistics")
print("=" * 50)
try:
conn = await asyncpg.connect(config.db.connection_string)
# Get stats
stats = await conn.fetchrow("SELECT * FROM synthesis.get_stats()")
print(f"\nTotal Sources: {stats['total_sources']:,}")
print(f"Total Claims: {stats['total_claims']:,}")
print(f"Total Connections: {stats['total_connections']:,}")
print(f"Cross-Domain Connections:{stats['cross_domain_connections']:,}")
print(f"Total Patterns: {stats['total_patterns']:,}")
print(f"Open Contradictions: {stats['open_contradictions']:,}")
print(f"Open Gaps: {stats['open_gaps']:,}")
# Get per-domain stats
print("\nBy Domain:")
rows = await conn.fetch("""
SELECT d.name, COUNT(DISTINCT c.id) as claims
FROM synthesis.domains d
LEFT JOIN synthesis.claims c ON d.id = ANY(c.domains)
GROUP BY d.name
ORDER BY claims DESC
""")
for row in rows:
print(f" {row['name']:15} {row['claims']:,} claims")
await conn.close()
except Exception as e:
print(f"Error: {e}")
async def show_insights(limit: int = 10):
"""Show top cross-domain insights."""
import asyncpg
print("CIPHER Cross-Domain Insights")
print("=" * 50)
try:
conn = await asyncpg.connect(config.db.connection_string)
rows = await conn.fetch("""
SELECT pattern_name, pattern_type, description,
confidence, novelty_score, created_at
FROM synthesis.patterns
WHERE pattern_type = 'cross_domain' OR
(SELECT COUNT(DISTINCT unnest) FROM unnest(domains)) >= 2
ORDER BY novelty_score * confidence DESC
LIMIT $1
""", limit)
if not rows:
print("\nNo cross-domain insights found yet.")
print("Run a learning cycle to discover insights.")
return
for i, row in enumerate(rows, 1):
print(f"\n{i}. {row['pattern_name']}")
print(f" Type: {row['pattern_type']}")
print(f" Confidence: {row['confidence']:.2f}, Novelty: {row['novelty_score']:.2f}")
print(f" {row['description'][:200]}...")
await conn.close()
except Exception as e:
print(f"Error: {e}")
async def search_claims(query: str, limit: int = 20):
"""Search claims in the knowledge base."""
import asyncpg
print(f"Searching for: '{query}'")
print("=" * 50)
try:
conn = await asyncpg.connect(config.db.connection_string)
rows = await conn.fetch("""
SELECT c.claim_text, c.claim_type, c.confidence,
s.title as source_title
FROM synthesis.claims c
JOIN synthesis.sources s ON c.source_id = s.id
WHERE LOWER(c.claim_text) LIKE $1
ORDER BY c.confidence DESC
LIMIT $2
""", f"%{query.lower()}%", limit)
if not rows:
print(f"\nNo claims found matching '{query}'")
return
print(f"\nFound {len(rows)} claims:\n")
for row in rows:
print(f"[{row['claim_type']}] (conf: {row['confidence']:.2f})")
print(f" {row['claim_text'][:150]}...")
print(f" Source: {row['source_title'][:50]}...")
print()
await conn.close()
except Exception as e:
print(f"Error: {e}")
async def show_thoughts(limit: int = 20):
"""Show recent thoughts."""
import asyncpg
print("CIPHER Recent Thoughts")
print("=" * 50)
try:
conn = await asyncpg.connect(config.db.connection_string)
rows = await conn.fetch("""
SELECT thought_type, content, importance, created_at
FROM synthesis.thoughts
ORDER BY created_at DESC
LIMIT $1
""", limit)
if not rows:
print("\nNo thoughts recorded yet.")
return
for row in rows:
ts = row['created_at'].strftime('%Y-%m-%d %H:%M')
print(f"\n[{row['thought_type']}] ({ts}) imp={row['importance']:.1f}")
print(f" {row['content'][:200]}...")
await conn.close()
except Exception as e:
print(f"Error: {e}")
async def trigger_learn(domain: str):
"""Trigger learning for a specific domain."""
from tools.cipher_brain import CipherBrain, Domain
from tools.domain_learner import DomainLearner
domain_map = {
'math': Domain.MATHEMATICS,
'neuro': Domain.NEUROSCIENCES,
'bio': Domain.BIOLOGY,
'psych': Domain.PSYCHOLOGY,
'med': Domain.MEDICINE,
'art': Domain.ART,
}
if domain.lower() not in domain_map:
print(f"Unknown domain: {domain}")
print(f"Available: {list(domain_map.keys())}")
return
target = domain_map[domain.lower()]
print(f"Starting learning session for: {target.name}")
print("=" * 50)
brain = CipherBrain(config.db.connection_string)
await brain.connect()
learner = DomainLearner(brain, {
'email': config.api.openalex_email,
})
try:
session = await learner.learn_domain(target, max_papers=50)
print(f"\nResults:")
print(f" Papers fetched: {session.papers_fetched}")
print(f" Claims extracted: {session.claims_extracted}")
print(f" Connections found: {session.connections_found}")
print(f" Patterns detected: {session.patterns_detected}")
if session.errors:
print(f" Errors: {len(session.errors)}")
finally:
await learner.close()
await brain.close()
# =========================================================================
# SEMANTIC EMBEDDING COMMANDS
# =========================================================================
async def semantic_search(query: str, limit: int = 20, threshold: float = 0.5):
"""Semantic search using embeddings."""
from tools.cipher_brain import CipherBrain
print(f"Semantic search for: '{query}'")
print(f"Threshold: {threshold}, Limit: {limit}")
print("=" * 50)
brain = CipherBrain(config.db.connection_string)
await brain.connect()
try:
results = await brain.semantic_search_claims(
query=query,
limit=limit,
threshold=threshold
)
if not results:
print(f"\nNo semantically similar claims found.")
print("Try lowering the threshold with --threshold 0.3")
return
print(f"\nFound {len(results)} similar claims:\n")
for claim_id, claim_text, similarity in results:
print(f"[{similarity:.3f}] (ID: {claim_id})")
print(f" {claim_text[:150]}...")
print()
finally:
await brain.close()
async def embed_backfill(batch_size: int = 100, limit: int = None):
"""Backfill embeddings for existing claims."""
from tools.cipher_brain import CipherBrain
print("Backfilling embeddings for existing claims")
print("=" * 50)
brain = CipherBrain(config.db.connection_string)
await brain.connect()
try:
updated = await brain.embed_existing_claims(
batch_size=batch_size,
limit=limit
)
print(f"\nCompleted! Updated {updated} claims with embeddings.")
finally:
await brain.close()
async def find_bridges(threshold: float = 0.75, limit: int = 20):
"""Find cross-domain connections using embedding similarity."""
from tools.cipher_brain import CipherBrain
print("Finding cross-domain connections via embeddings")
print(f"Threshold: {threshold}")
print("=" * 50)
brain = CipherBrain(config.db.connection_string)
await brain.connect()
try:
connections = await brain.find_cross_domain_by_embedding(
threshold=threshold,
limit=limit
)
if not connections:
print("\nNo cross-domain connections found.")
print("Try lowering the threshold or run embed-backfill first.")
return
print(f"\nFound {len(connections)} potential cross-domain bridges:\n")
for i, conn in enumerate(connections, 1):
print(f"{i}. {conn['domain_a']} <-> {conn['domain_b']} (sim: {conn['similarity']:.3f})")
print(f" A: {conn['claim_a_text'][:80]}...")
print(f" B: {conn['claim_b_text'][:80]}...")
print()
finally:
await brain.close()
async def find_similar(claim_id: int, limit: int = 10, cross_domain: bool = False):
"""Find claims similar to a given claim."""
from tools.cipher_brain import CipherBrain
print(f"Finding claims similar to ID: {claim_id}")
if cross_domain:
print("(Cross-domain only)")
print("=" * 50)
brain = CipherBrain(config.db.connection_string)
await brain.connect()
try:
results = await brain.find_similar_claims(
claim_id=claim_id,
limit=limit,
cross_domain_only=cross_domain
)
if not results:
print("\nNo similar claims found.")
return
print(f"\nFound {len(results)} similar claims:\n")
for cid, text, similarity, domains in results:
domain_names = [d.name for d in domains]
print(f"[{similarity:.3f}] (ID: {cid}) Domains: {domain_names}")
print(f" {text[:150]}...")
print()
finally:
await brain.close()
async def embedding_stats():
"""Show embedding statistics."""
import asyncpg
print("CIPHER Embedding Statistics")
print("=" * 50)
try:
conn = await asyncpg.connect(config.db.connection_string)
# Count claims with/without embeddings
total = await conn.fetchval("SELECT COUNT(*) FROM synthesis.claims")
with_emb = await conn.fetchval(
"SELECT COUNT(*) FROM synthesis.claims WHERE embedding IS NOT NULL"
)
without_emb = total - with_emb
print(f"\nTotal claims: {total:,}")
print(f"With embeddings: {with_emb:,} ({100*with_emb/total:.1f}%)" if total > 0 else "With embeddings: 0")
print(f"Without embeddings: {without_emb:,}")
# Get embedding model info
from tools.embeddings import get_embedding_service
service = get_embedding_service()
print(f"\nEmbedding Model: {service.model_name}")
print(f"Dimensions: {service.dimensions}")
await conn.close()
except Exception as e:
print(f"Error: {e}")
# =========================================================================
# TEMPORAL TRACKING COMMANDS
# =========================================================================
async def temporal_stats():
"""Show temporal tracking statistics."""
import asyncpg
print("CIPHER Temporal Tracking Statistics")
print("=" * 50)
try:
conn = await asyncpg.connect(config.db.connection_string)
# Replication status distribution
print("\nReplication Status Distribution:")
rows = await conn.fetch("""
SELECT
COALESCE(replication_status, 'unreplicated') as status,
COUNT(*) as count
FROM synthesis.claims
GROUP BY replication_status
ORDER BY count DESC
""")
for row in rows:
print(f" {row['status']:20} {row['count']:,}")
# Claim status distribution
print("\nClaim Lifecycle Status:")
rows = await conn.fetch("""
SELECT
COALESCE(status, 'active') as status,
COUNT(*) as count
FROM synthesis.claims
GROUP BY status
ORDER BY count DESC
""")
for row in rows:
print(f" {row['status']:20} {row['count']:,}")
# Age distribution
print("\nClaim Age Distribution:")
rows = await conn.fetch("""
SELECT
CASE
WHEN EXTRACT(days FROM NOW() - created_at) < 30 THEN '< 1 month'
WHEN EXTRACT(days FROM NOW() - created_at) < 180 THEN '1-6 months'
WHEN EXTRACT(days FROM NOW() - created_at) < 365 THEN '6-12 months'
WHEN EXTRACT(days FROM NOW() - created_at) < 730 THEN '1-2 years'
ELSE '> 2 years'
END as age_group,
COUNT(*) as count,
AVG(COALESCE(current_confidence, confidence)) as avg_confidence
FROM synthesis.claims
GROUP BY age_group
ORDER BY count DESC
""")
for row in rows:
conf = row['avg_confidence'] or 0
print(f" {row['age_group']:15} {row['count']:,} claims (avg conf: {conf:.2f})")
await conn.close()
except Exception as e:
print(f"Error: {e}")
async def decay_claims():
"""Apply confidence decay to all claims."""
from tools.temporal_tracker import TemporalTracker
print("Applying confidence decay to claims...")
print("=" * 50)
tracker = TemporalTracker(config.db.connection_string)
await tracker.connect()
try:
updated = await tracker.decay_all_claims()
print(f"\nUpdated {updated} claims with decayed confidence.")
finally:
await tracker.close()
async def aging_claims(min_age: int = 180, max_conf: float = 0.5):
"""Show aging claims that need attention."""
from tools.temporal_tracker import TemporalTracker
print(f"Claims older than {min_age} days with confidence < {max_conf}")
print("=" * 60)
tracker = TemporalTracker(config.db.connection_string)
await tracker.connect()
try:
claims = await tracker.get_aging_claims(min_age, max_conf)
if not claims:
print("\nNo aging claims found matching criteria.")
return
print(f"\nFound {len(claims)} aging claims:\n")
for claim in claims[:20]:
age = int(claim.get('age_days', 0))
orig_conf = claim.get('original_confidence', 0) or 0
curr_conf = claim.get('current_confidence', 0) or 0
repl = claim.get('replication_status', 'unreplicated')
print(f"ID {claim['id']} | Age: {age}d | Conf: {orig_conf:.2f} -> {curr_conf:.2f} | Repl: {repl}")
print(f" {claim['claim_text'][:70]}...")
print()
finally:
await tracker.close()
async def claim_temporal(claim_id: int):
"""Show temporal state of a specific claim."""
from tools.temporal_tracker import TemporalTracker
print(f"Temporal State for Claim ID: {claim_id}")
print("=" * 50)
tracker = TemporalTracker(config.db.connection_string)
await tracker.connect()
try:
state = await tracker.get_temporal_state(claim_id)
if not state:
print(f"\nClaim {claim_id} not found.")
return
print(f"\nClaim ID: {state.claim_id}")
print(f"Status: {state.status.value}")
print(f"Age: {state.age_days} days")
print(f"Half-life: {state.half_life_days:.0f} days")
print(f"\nConfidence:")
print(f" Original: {state.original_confidence:.3f}")
print(f" Current: {state.current_confidence:.3f}")
print(f" Trend: {state.confidence_trend:+.3f}")
print(f"\nReplication:")
print(f" Status: {state.replication_status.value}")
print(f" Successful: {state.replication_count}")
print(f" Failed: {state.failed_replication_count}")
print(f"\nCitations:")
print(f" Total: {state.citation_count}")
print(f" Velocity: {state.citation_velocity:.1f}/month")
print(f"\nTimestamps:")
print(f" First seen: {state.first_seen}")
print(f" Last confirmed: {state.last_confirmed or 'Never'}")
print(f" Last cited: {state.last_cited or 'Never'}")
if state.superseded_by:
print(f"\nSuperseded by: Claim ID {state.superseded_by}")
finally:
await tracker.close()
async def detect_paradigm_shifts(days: int = 365):
"""Detect potential paradigm shifts."""
from tools.temporal_tracker import TemporalTracker
print(f"Detecting paradigm shifts (last {days} days)")
print("=" * 50)
tracker = TemporalTracker(config.db.connection_string)
await tracker.connect()
try:
patterns = await tracker.detect_paradigm_shifts(days)
if not patterns:
print("\nNo paradigm shifts detected.")
return
print(f"\nFound {len(patterns)} temporal patterns:\n")
for i, pattern in enumerate(patterns, 1):
print(f"{i}. [{pattern.pattern_type}] (conf: {pattern.confidence:.2f})")
print(f" {pattern.description}")
print(f" Claims involved: {len(pattern.claims_involved)}")
print(f" Started: {pattern.start_date}")
print()
finally:
await tracker.close()
async def record_replication(claim_id: int, success: bool, partial: bool = False):
"""Record a replication attempt for a claim."""
from tools.temporal_tracker import TemporalTracker
status = "successful" if success else "failed"
if partial:
status = "partial"
print(f"Recording {status} replication for Claim ID: {claim_id}")
print("=" * 50)
tracker = TemporalTracker(config.db.connection_string)
await tracker.connect()
try:
result = await tracker.record_replication(
claim_id=claim_id,
success=success,
partial=partial
)
if result:
print(f"\nReplication recorded successfully.")
# Show updated state
state = await tracker.get_temporal_state(claim_id)
if state:
print(f"New replication status: {state.replication_status.value}")
print(f"New confidence: {state.current_confidence:.3f}")
else:
print("\nFailed to record replication.")
finally:
await tracker.close()
# =========================================================================
# ACTIVE LEARNING COMMANDS
# =========================================================================
async def learning_plan(strategy: str = 'ucb', max_targets: int = 10):
"""Generate an active learning plan."""
from tools.active_learner import ActiveLearner, LearningStrategy
strategy_map = {
'ucb': LearningStrategy.UCB,
'uncertainty': LearningStrategy.UNCERTAINTY_SAMPLING,
'contradiction': LearningStrategy.CONTRADICTION_RESOLUTION,
'hypothesis': LearningStrategy.HYPOTHESIS_TESTING,
'gap': LearningStrategy.GAP_FILLING,
'exploration': LearningStrategy.EXPLORATION,
'exploitation': LearningStrategy.EXPLOITATION,
}
print(f"Generating Active Learning Plan")
print(f"Strategy: {strategy}")
print("=" * 60)
learner = ActiveLearner(config.db.connection_string)
await learner.connect()
try:
strat = strategy_map.get(strategy, LearningStrategy.UCB)
plan = await learner.create_learning_plan(strat, max_targets)
print(f"\n{plan.rationale}")
print(f"Total Priority: {plan.total_priority:.2f}")
print(f"Expected Value: {plan.expected_value:.2f}")
print(f"\nPrioritized Targets:\n")
for i, target in enumerate(plan.targets, 1):
print(f"{i}. [{target.target_type.upper()}] {target.target_name}")
print(f" Priority: {target.priority:.3f} | Uncertainty: {target.uncertainty:.3f}")
print(f" Strategy: {target.strategy.value}")
print(f" Rationale: {target.rationale}")
if target.search_queries:
print(f" Queries: {target.search_queries[:2]}")
print()
finally:
await learner.close()
async def domain_uncertainty():
"""Show uncertainty metrics for each domain."""
from tools.active_learner import ActiveLearner
print("Domain Uncertainty Analysis")
print("=" * 70)
learner = ActiveLearner(config.db.connection_string)
await learner.connect()
try:
uncertainties = await learner.compute_domain_uncertainty()
print(f"\n{'Domain':<15} {'Claims':<8} {'Conf':<8} {'Var':<8} {'Contr':<8} {'Stale':<8} {'Priority':<8}")
print("-" * 70)
for du in uncertainties:
print(f"{du.domain_name:<15} {du.claim_count:<8} {du.avg_confidence:<8.3f} "
f"{du.confidence_variance:<8.3f} {du.contradiction_count:<8} "
f"{du.staleness_days:<8.0f} {du.priority_score:<8.3f}")
print("\nLegend:")
print(" Conf = Average confidence")
print(" Var = Confidence variance")
print(" Contr = Unresolved contradictions")
print(" Stale = Days since last learning")
print(" Priority = Overall priority score (higher = needs more attention)")
finally:
await learner.close()
async def show_contradictions(limit: int = 20):
"""Show unresolved contradictions."""
from tools.active_learner import ActiveLearner
print("Unresolved Contradictions")
print("=" * 60)
learner = ActiveLearner(config.db.connection_string)
await learner.connect()
try:
targets = await learner.get_unresolved_contradictions(limit)
if not targets:
print("\nNo unresolved contradictions found.")
return
print(f"\nFound {len(targets)} unresolved contradictions:\n")
for i, target in enumerate(targets, 1):
print(f"{i}. Severity: {target.priority:.2f}")
print(f" Claim A: {target.metadata.get('claim_a', '')[:80]}...")
print(f" Claim B: {target.metadata.get('claim_b', '')[:80]}...")
print(f" Suggested queries: {target.search_queries[:2]}")
print()
finally:
await learner.close()
async def show_hypotheses(limit: int = 20):
"""Show open hypotheses needing testing."""
from tools.active_learner import ActiveLearner
print("Open Hypotheses")
print("=" * 60)
learner = ActiveLearner(config.db.connection_string)
await learner.connect()
try:
targets = await learner.get_open_hypotheses(limit)
if not targets:
print("\nNo open hypotheses found.")
return
print(f"\nFound {len(targets)} open hypotheses:\n")
for i, target in enumerate(targets, 1):
print(f"{i}. Priority: {target.priority:.2f} | Status: {target.metadata.get('status', 'unknown')}")
print(f" {target.metadata.get('hypothesis', '')[:100]}...")
if target.metadata.get('source_pattern'):
print(f" From pattern: {target.metadata['source_pattern']}")
print(f" Search queries: {target.search_queries[:2]}")
print()
finally:
await learner.close()
async def show_gaps(limit: int = 20):
"""Show open knowledge gaps."""
from tools.active_learner import ActiveLearner
print("Knowledge Gaps")
print("=" * 60)
learner = ActiveLearner(config.db.connection_string)
await learner.connect()
try:
targets = await learner.get_knowledge_gaps(limit)
if not targets:
print("\nNo open knowledge gaps found.")
return
print(f"\nFound {len(targets)} knowledge gaps:\n")
for i, target in enumerate(targets, 1):
importance = target.metadata.get('importance', 0)
tractability = target.metadata.get('tractability', 0)
print(f"{i}. Priority: {target.priority:.2f} (importance={importance:.2f}, tractability={tractability:.2f})")
print(f" {target.metadata.get('description', '')[:100]}...")
if target.metadata.get('directions'):
print(f" Research directions: {target.metadata['directions'][:2]}")
print(f" Search queries: {target.search_queries[:2]}")
print()
finally:
await learner.close()
async def low_confidence_concepts(threshold: float = 0.4, limit: int = 30):
"""Show concepts with low confidence claims."""
from tools.active_learner import ActiveLearner
print(f"Low Confidence Concepts (threshold: {threshold})")
print("=" * 60)
learner = ActiveLearner(config.db.connection_string)
await learner.connect()
try:
targets = await learner.get_low_confidence_concepts(threshold, limit)
if not targets:
print(f"\nNo concepts with confidence < {threshold} found.")
return
print(f"\nFound {len(targets)} low-confidence concepts:\n")
for i, target in enumerate(targets, 1):
claim_count = target.metadata.get('claim_count', 0)
avg_conf = target.metadata.get('avg_confidence', 0)
print(f"{i}. {target.target_name}")
print(f" Claims: {claim_count} | Avg confidence: {avg_conf:.3f}")
print(f" Search queries: {target.search_queries[:2]}")
print()
finally:
await learner.close()
async def active_learn(strategy: str = 'ucb', max_papers: int = 50):
"""Execute active learning using the specified strategy."""
from tools.active_learner import ActiveLearner, LearningStrategy
from tools.cipher_brain import CipherBrain, Domain
from tools.domain_learner import DomainLearner
strategy_map = {
'ucb': LearningStrategy.UCB,
'uncertainty': LearningStrategy.UNCERTAINTY_SAMPLING,
'contradiction': LearningStrategy.CONTRADICTION_RESOLUTION,
'hypothesis': LearningStrategy.HYPOTHESIS_TESTING,
'gap': LearningStrategy.GAP_FILLING,
'exploration': LearningStrategy.EXPLORATION,
'exploitation': LearningStrategy.EXPLOITATION,
}
print(f"Executing Active Learning")
print(f"Strategy: {strategy}")
print(f"Max papers per target: {max_papers}")
print("=" * 60)
# Get learning plan
learner = ActiveLearner(config.db.connection_string)
await learner.connect()
brain = CipherBrain(config.db.connection_string)
await brain.connect()
domain_learner = DomainLearner(brain, {
'email': config.api.openalex_email,
})
try:
strat = strategy_map.get(strategy, LearningStrategy.UCB)
plan = await learner.create_learning_plan(strat, max_targets=5)
print(f"\nLearning plan: {plan.rationale}")
print(f"Targets: {len(plan.targets)}\n")
total_papers = 0
total_claims = 0
total_connections = 0
for target in plan.targets:
print(f"\n>> Processing: {target.target_name}")
if target.target_type == 'domain':
# Use domain learner for domain targets
domain_map = {
'mathematics': Domain.MATHEMATICS,
'neurosciences': Domain.NEUROSCIENCES,
'biology': Domain.BIOLOGY,
'psychology': Domain.PSYCHOLOGY,
'medicine': Domain.MEDICINE,
'art': Domain.ART,
}
domain = domain_map.get(target.target_name.lower())
if domain:
session = await domain_learner.learn_domain(
domain,
max_papers=max_papers
)
total_papers += session.papers_fetched
total_claims += session.claims_extracted
total_connections += session.connections_found
print(f" Papers: {session.papers_fetched}, Claims: {session.claims_extracted}, "
f"Connections: {session.connections_found}")
elif target.search_queries:
# Use cross-domain search for other targets
session = await domain_learner.learn_cross_domain(
concepts=target.search_queries[:2],
max_papers=max_papers // 2
)
total_papers += session.papers_fetched
total_claims += session.claims_extracted
total_connections += session.connections_found
print(f" Papers: {session.papers_fetched}, Claims: {session.claims_extracted}, "
f"Connections: {session.connections_found}")
# Record learning round
domain_id = target.domains[0] if target.domains else None
await learner.record_learning_round(
domain_id=domain_id,
papers_processed=total_papers,
claims_extracted=total_claims,
connections_found=total_connections
)
print(f"\n" + "=" * 60)
print(f"Active Learning Complete!")
print(f"Total papers: {total_papers}")
print(f"Total claims: {total_claims}")
print(f"Total connections: {total_connections}")
finally:
await domain_learner.close()
await brain.close()
await learner.close()
# =========================================================================
# GRAPH ENGINE COMMANDS
# =========================================================================
async def graph_stats():
"""Show knowledge graph statistics."""
from tools.graph_engine import GraphEngine
print("Knowledge Graph Statistics")
print("=" * 60)
engine = GraphEngine(config.db.connection_string)
await engine.connect()
try:
await engine.load_graph()
stats = engine.compute_graph_stats()
print(f"\nNodes (claims): {stats.node_count:,}")
print(f"Edges (connections): {stats.edge_count:,}")
print(f"Graph density: {stats.density:.6f}")
print(f"Average degree: {stats.avg_degree:.2f}")
print(f"Average clustering: {stats.avg_clustering:.4f}")
print(f"Number of communities: {stats.num_communities}")
print(f"Largest community: {stats.largest_community_size} nodes")
print(f"Cross-domain edge ratio: {stats.cross_domain_edge_ratio:.2%}")
finally:
await engine.close()
async def find_path(source_id: int, target_id: int, path_type: str = 'shortest'):
"""Find path between two claims."""
from tools.graph_engine import GraphEngine
print(f"Finding {path_type} path from claim {source_id} to {target_id}")
print("=" * 60)
engine = GraphEngine(config.db.connection_string)
await engine.connect()
try:
if path_type == 'cte':
# Use database CTE
path = await engine.find_path_cte(source_id, target_id)
else:
# Use in-memory algorithms
await engine.load_graph()
if path_type == 'shortest':
path = engine.find_shortest_path(source_id, target_id)
elif path_type == 'strongest':
path = engine.find_strongest_path(source_id, target_id)
elif path_type == 'cross_domain':